serverCsvUpload.js 7.99 KB
// import { } from '/imports/collections/staff/methods';
import _                                  from 'lodash';
import { Meteor }                         from 'meteor/meteor';
import Papa                               from 'meteor/harrison:papa-parse'
import csv                                from 'csv2json-convertor'
import { ValidatedMethod }                from 'meteor/mdg:validated-method';
import { SimpleSchema }                   from 'meteor/aldeed:simple-schema';
import { DDPRateLimiter }                 from 'meteor/ddp-rate-limiter';
import { Bert }                           from 'meteor/themeteorchef:bert';
import { Users }                          from '/imports/collections/users/index';
import { Orgs }                           from '/imports/collections/orgs/index';
import { Students }                       from '/imports/collections/students/index'
import { Parents }                        from '/imports/collections/parents/index';
import { Staffs }                         from '/imports/collections/staff/index';
import csv1                               from 'csv2json-convertor'
import json2csv                           from 'json2csv'
import fs                                 from 'fs'
import Validation                         from '/imports/validation/validationMethods';
import Constants                          from '/imports/constants/constants'

export const staffCsvtMethod = new ValidatedMethod({
  name: 'staff.csvMethod',

  validate: new SimpleSchema({
    itemId: { type: String },
  }).validator(),

  run({itemId}) {
    return {};
  },

});

export const staffSaveCsvData = new ValidatedMethod({
  name: 'staff.saveCsvData',

  validate: null,

  run({item,filename,csv_fiels}) {
    var csv = json2csv({
      data: item,
      fields: csv_fiels
    });
    fs.writeFile(filename, csv,function(err) {
      if (err) throw err;
    });
  },
});

export const addStaffCSV= new ValidatedMethod({
  name: 'staff.addCSV',

  validate: null,

  run(item){
    data = item ;
    console.log("data");
    console.log(data);
   // return true;
    const user = Users.findOne({_id: this.userId});
    orgId = user.orgId;
    newStaffId = Users.insert({
     // emails:     [{address:data.email, verified: false}],
      //username:   data["First Name*"],
      firstName:  data["First Name*"],
      lastName:   data['Last Name*'],
      emails: [{ address: data['Staff Email*'],verified: false }],
      phones: [{ number:  data['Staff Phone*'],verified: false }],
      orgId:      orgId,
      role:       'STAFF'
    });
    console.log("newStaffId");
    console.log(newStaffId);





    if(newStaffId){
      newStaff = Staffs.insert({
        userId: newStaffId,
        orgId: orgId,

        employeeId:          data['Employee ID*'],
        martialStatus:       data['Marital Status(married/unmarried)*'],
        dob:                 data['Staff Birthday(YYYY-MM-DD)*'],
        gender:              data['Gender(male/female)*'],
        teaching:            data['Teaching Staff(yes/no)*'],
        type:                data['Job Type(permanent/contract)*'],
        doj:                 data['Date of joining(YYYY-MM-DD)*'],

        bloodGroup:          data['Blood group*'],
        nationality:         data['Nationality*'],
        motherTongue:        data['Mother Tongue*'],
        religion:            data['Religion*'],

        PANNumber:           data['PAN Number'],
        ESINumber:           data['ESI Number'],
        aadharNumber:        data['Aadhar Number'],
        PFNumber:            data['PF Number'],

        permanentAddress: { street: data['Staff Line Address*'],
                            city:   data['City*'], 
                            state:  data['State*'],
                            zip:    data['Zip*'] 
                          },


        bankdetails: {     bankAccountNo:     data['Bank Account No'],
                            bankIFSC:          data['Bank IFSC'], 
                            bankBranchDetails: data['Bank Branch Details']
                     },

        workingExperience: [{   previousJobRole:      data['Previous job Role'],
                                previousJobType:      data['Previous Job Type'], 
                                previousOrganization: data['Previous Organization'],
                                from:                 data['From'],
                                to:                   data['To']
                           }],   

        educationDetails:  [{   qualifaication:      data['Qualification*'],
                                specialization:      data['Specialization*'], 
                                university:          data['University*'],
                                from:                data['From*'],
                                to:                  data['To*']
                           }]


      });
      console.log("newStaff");
      console.log(newStaff);
    }
    return {newStaffId};
  },

});

export const staffUploadCsv = new ValidatedMethod({
  name: 'staff.uploadCsv',

  validate: null,

  run({data}) {
     let validation = new Validation();
     let constants = new Constants();
     var CSV_valid_buffer   = [];
     var CSV_invalid_buffer = [];
     var filename           = "Staff-" + new Date().getTime().toString();
     var csv_filepath = '/Users/satheeshnagaraj/Documents/Workspace/Meteor/Youngdesk/ydapp/CSV_Files/';
     for (let i = 0; i < data.length; i++)
        {
            let item = data[i];
            delete item['Errors'];
            var formate_validation = 1;
            var is_not_null = 1;
            var errors = [];
            for (var key in item){
              var value = item[key];
              var n = key.indexOf("*");
              if(n!=-1) {
                  if(!(validation.notNull(value)))
                  {
                    errors.push(key+"is Empty");
                  }
                  is_not_null = is_not_null && validation.notNull(value);
                }
            }
            var formate_validation = validation.validateEmail(item["Staff Email*"]) && validation.mobileNumber(item["Staff Phone*"]) ; //&& validation.validateEmail(item["Parent Mobile"]) );

                  if (!(validation.validateEmail(item["Staff Email*"]))){
                      errors.push('Staff Email is invalid');
                  }
                  if (!(validation.mobileNumber(item["Staff Phone*"])))
                  {
                        errors.push('Staffs Mobile is invalid');
                  }

                  var is_valid = formate_validation && is_not_null ;



                    if (is_valid)
                       {
                         exists = Users.findOne({"firstName": item["First Name*"],"lastName": item["Last Name*"],'emails.$.address' : item['Staff Email*'],'phones.$.number' : item['Staff Phone*']}, {"_id": 1});
                          
                               if (!exists)
                                  { 
                                    CSV_valid_buffer.push(item);
                                    Meteor.call('staff.addCSV',item);
                                    console.warn('done');
                                  }
                               else
                                  {
                                    console.warn('This data already exists.');
                                    errors.push('This data already exists');
                                    var str = errors.toString();
                                    item.Errors = str;
                                    CSV_invalid_buffer.push(item);
                                  }
                 
                        }

                }


    console.log(csv_filepath+filename+"_CSV_invalid_data"+".csv");
    Meteor.call('staff.saveCsvData',{ item : CSV_invalid_buffer, filename: csv_filepath+filename+"_CSV_invalid_data"+".csv",csv_fiels :constants.csv_staff_data()});
    Meteor.call('staff.saveCsvData',{ item : CSV_valid_buffer,filename: csv_filepath+filename+"_CSV_valid_data"+".csv",csv_fiels :constants.csv_staff_data()});
    return {};
  },

});