Advertisement
Guest User

Untitled

a guest
Nov 2nd, 2017
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Studies, Profiles_Studies, InviteTemplates_Studies, Responses_Studies, Respondents_Studies, Fields_Studies, Versions_Studies, PageBlocks_Studies, Pages_Studies, Questions_Studies, QuestionStubs_Studies } from '/lib/collections/collections_studies';
  2. import { Campaigns, Threads, Messages, Respondents, Surveys, EmailProfileMatchResults, Fields } from '/lib/collections/collections_nps';
  3. import { Subscriptions, Bounces, Unsubs, emailprofilematchingJobs } from '/lib/collections/collections_common';
  4.  
  5. import { initialJobs, reminderJobs } from '/lib/collections/collections_common';
  6.  
  7. import { replaceAffectedConditionIds } from '/server/studies/design_study/design_study_helpers';
  8.  
  9. function randSurveySession(i) {
  10.     if (i % 2 === 0) {
  11.         return { startedDate: new Date(`4/${i}/2017`), completedDate: new Date(`4/${i}/2017`) };
  12.     } else {
  13.         return { startedDate: new Date(`4/${i}/2017`) };
  14.     }
  15. }
  16.  
  17. Meteor.methods({
  18.     migrateVersioning() {
  19.         console.log('Starting Migration...');
  20.  
  21.         const versions = Versions_Studies.find().fetch(),
  22.             pageBlocks = PageBlocks_Studies.find().fetch(),
  23.             pages = Pages_Studies.find().fetch(),
  24.             questions = Questions_Studies.find().fetch(),
  25.             stubs = QuestionStubs_Studies.find().fetch();
  26.  
  27.         const idMap = {},
  28.             versionNumMap = {};
  29.          
  30.         let regExBuild = '';
  31.  
  32.         console.log('Creating ID Map...');
  33.  
  34.         for (const version of versions) {
  35.             idMap[version._id] = {};
  36.             versionNumMap[version._id] = version.number;
  37.         }
  38.         for (const pageBlock of pageBlocks) {
  39.             const crossVersionId = Random.id();
  40.              
  41.             for (const versionId of pageBlock.versions) {
  42.                 idMap[versionId][pageBlock._id] = crossVersionId;
  43.             }
  44.         }
  45.         for (const page of pages) {
  46.             const crossVersionId = Random.id();
  47.  
  48.             regExBuild += `${page._id}|`;
  49.              
  50.             for (const versionId of page.versions) {
  51.                 idMap[versionId][page._id] = crossVersionId;
  52.             }
  53.         }
  54.         for (const question of questions) {
  55.             const crossVersionId = Random.id();
  56.  
  57.             regExBuild += `${question._id}|`;
  58.              
  59.             for (const versionId of question.versions) {
  60.                 idMap[versionId][question._id] = crossVersionId;
  61.             }
  62.         }
  63.         for (const stub of stubs) {
  64.             const crossVersionId = Random.id();
  65.  
  66.             regExBuild += `${stub._id}|`;
  67.              
  68.             for (const versionId of stub.versions) {
  69.                 idMap[versionId][stub._id] = crossVersionId;
  70.             }
  71.         }
  72.  
  73.         const builtRegex = new RegExp(regExBuild.slice(0, -1), 'g');
  74.  
  75.  
  76.         console.log('Building Responses Bulk Ops...');
  77.  
  78.         const responsesBulkOps = [];
  79.          
  80.         Responses_Studies.find({ surveySession: { $exists: true } }).forEach((responseDoc) => {
  81.             const versionIdMap = idMap[responseDoc.version],
  82.                 surveySession = responseDoc.surveySession;
  83.  
  84.             // Remap surveySession object
  85.             if (surveySession.currentPage) {
  86.                 surveySession.currentPage = versionIdMap[surveySession.currentPage];
  87.             }
  88.              
  89.             if (surveySession.branches) {
  90.                 surveySession.branches = Object.entries(surveySession.branches)
  91.                     .reduce((mapObj, [branchFromPageId, branchToPageId]) => {
  92.                         mapObj[versionIdMap[branchFromPageId]] = versionIdMap[branchToPageId];
  93.                         return mapObj;
  94.                     }, {});
  95.             }
  96.  
  97.             if (surveySession.orders) {
  98.                 if (surveySession.orders.pages) {
  99.                     surveySession.orders.pages = surveySession.orders.pages.map(pageId => versionIdMap[pageId]);
  100.                 }
  101.  
  102.                 if (surveySession.orders.randomQuestions) {
  103.                     surveySession.orders.randomQuestions = Object.entries(surveySession.orders.randomQuestions)
  104.                         .reduce((mapObj, [pageId, questionIds]) => {
  105.                             mapObj[versionIdMap[pageId]] = questionIds.map(questionId => versionIdMap[questionId]);
  106.                             return mapObj;
  107.                         }, {});
  108.                 }
  109.  
  110.                 if (surveySession.orders.randomStubs) {
  111.                     surveySession.orders.randomStubs = Object.entries(surveySession.orders.randomStubs)
  112.                         .reduce((mapObj, [questionId, stubIds]) => {
  113.                             mapObj[versionIdMap[questionId]] = stubIds.map(stubId => versionIdMap[stubId]);
  114.                             return mapObj;
  115.                         }, {});
  116.                 }
  117.             }
  118.  
  119.             // Remap responses array
  120.             responses = responseDoc.responses.map((responseObj) => {
  121.                 responseObj.question = versionIdMap[responseObj.question];
  122.  
  123.                 const questionType = responseObj.questionType;
  124.  
  125.                 if (questionType === 0) {
  126.                     responseObj.response = versionIdMap[responseObj.response];
  127.  
  128.                 } else if (questionType === 1) {
  129.                     responseObj.response = responseObj.response.map(stubId => versionIdMap[stubId]);
  130.  
  131.                 } else if (questionType === 3 || questionType === 4) {
  132.                     responseObj.response = responseObj.response.map((concatStubId) => {
  133.                         const [rowStubId, colStubId] = concatStubId.split('.');
  134.                         return `${versionIdMap[rowStubId]}.${versionIdMap[colStubId]}`;
  135.                     });
  136.  
  137.                 } else if (questionType === 5) {
  138.                     responseObj.response = Object.entries(responseObj.response)
  139.                         .reduce((mapObj, [subQStubId, textResponse]) => {
  140.                             mapObj[versionIdMap[subQStubId]] = textResponse;
  141.                             return mapObj;
  142.                         }, {});
  143.                      
  144.                 } else if (questionType === 7) {
  145.                     responseObj.response = responseObj.response.map((concatStubId) => {
  146.                         const [subQStubId, rowStubId, colStubId] = concatStubId.split('.');
  147.                         return `${versionIdMap[subQStubId]}.${versionIdMap[rowStubId]}.${versionIdMap[colStubId]}`;
  148.                     });
  149.                 }
  150.  
  151.                 // Remap specifiers object if necessary
  152.                 if (responseObj.specifiers) {
  153.                     responseObj.specifiers = Object.entries(responseObj.specifiers)
  154.                         .reduce((mapObj, [stubId, specifyText]) => {
  155.                             mapObj[versionIdMap[stubId]] = specifyText;
  156.                             return mapObj;
  157.                         }, {});
  158.                 }
  159.  
  160.                 return responseObj;
  161.             });
  162.  
  163.             responsesBulkOps.push({
  164.                 updateOne: {
  165.                     filter: { _id: responseDoc._id },
  166.                     update: { $set: { surveySession, responses } }
  167.                 }
  168.             });
  169.         });
  170.  
  171.  
  172.         console.log('Building Version Bulk Ops...');
  173.  
  174.         const versionBulkOps = [];
  175.  
  176.         for (const version of versions) {
  177.             if (version.alerts && version.alerts.length) {
  178.                 versionBulkOps.push({
  179.                     updateOne: {
  180.                         filter: { _id: version._id },
  181.                         update: {
  182.                             $set: {
  183.                                 alerts: version.alerts.map((alert) => {
  184.                                     alert.condition = replaceAffectedConditionIds(alert.condition, idMap[version._id], builtRegex);
  185.                                     return alert;
  186.                                 })
  187.                             }
  188.                         }
  189.                     }
  190.                 });
  191.             }
  192.         }
  193.  
  194.  
  195.         console.log('Building PageBlock Bulk Ops...');
  196.  
  197.         const removePageBlockIds = [],
  198.             pageBlockBulkOps = [
  199.                 {
  200.                     deleteMany: {
  201.                         filter: { _id: { $in: removePageBlockIds } }
  202.                     }
  203.                 }
  204.             ];
  205.  
  206.         for (const pageBlock of pageBlocks) {
  207.             for (const versionId of pageBlock.versions) {
  208.                 pageBlockBulkOps.push({
  209.                     insertOne: {
  210.                         document: {
  211.                             _id: Random.id(),
  212.                             crossVersionId: idMap[versionId][pageBlock._id],
  213.                             study: pageBlock.study,
  214.                             version: versionId,
  215.                             title: pageBlock.title,
  216.                             number: pageBlock.number[versionId],
  217.                             options: pageBlock.options
  218.                         }
  219.                     }
  220.                 });
  221.             }
  222.  
  223.             removePageBlockIds.push(pageBlock._id);
  224.         }
  225.  
  226.  
  227.         console.log('Building Page Bulk Ops...');
  228.  
  229.         const removePageIds = [],
  230.             pageBulkOps = [
  231.                 {
  232.                     deleteMany: {
  233.                         filter: { _id: { $in: removePageIds } }
  234.                     }
  235.                 }
  236.             ];
  237.  
  238.         for (const page of pages) {
  239.             for (const versionId of page.versions) {
  240.                 const newPage = {
  241.                     _id: Random.id(),
  242.                     crossVersionId: idMap[versionId][page._id],
  243.                     study: page.study,
  244.                     version: versionId,
  245.                     pageBlock: idMap[versionId][page.pageBlocks[versionId]],
  246.                     title: page.title,
  247.                     number: page.number[versionId],
  248.                     options: page.options
  249.                 };
  250.  
  251.                 if (page.visibilityCondition && page.visibilityCondition[versionId]) {
  252.                     newPage.visibilityCondition = replaceAffectedConditionIds(page.visibilityCondition[versionId], idMap[versionId], builtRegex);
  253.                 }
  254.  
  255.                 if (page.branchConditions) {
  256.                     newPage.branchConditions = [];
  257.  
  258.                     for (const cond of page.branchConditions) {
  259.                         if (cond.version === versionId) {
  260.                             newPage.branchConditions.push(replaceAffectedConditionIds(_.omit(cond, 'version'), idMap[versionId], builtRegex));
  261.                         }                        
  262.                     }
  263.                 }
  264.  
  265.                 if (page.terminateConditions) {
  266.                     newPage.terminateConditions = [];
  267.  
  268.                     for (const cond of page.terminateConditions) {
  269.                         if (cond.version === versionId) {
  270.                             newPage.terminateConditions.push(replaceAffectedConditionIds(_.omit(cond, 'version'), idMap[versionId], builtRegex));
  271.                         }                        
  272.                     }
  273.                 }
  274.  
  275.                 pageBulkOps.push({ insertOne: { document: newPage } });
  276.             }
  277.  
  278.             removePageIds.push(page._id);
  279.         }
  280.  
  281.  
  282.         console.log('Building Question Bulk Ops...');
  283.  
  284.         const removeQuestionIds = [],
  285.             questionBulkOps = [
  286.                 {
  287.                     deleteMany: {
  288.                         filter: { _id: { $in: removeQuestionIds } }
  289.                     }
  290.                 }
  291.             ];
  292.  
  293.         for (const question of questions) {
  294.             const linkId = Random.id();
  295.  
  296.             let linkOrder = 0,
  297.                 sliceEndIndex = 1;
  298.  
  299.             for (const versionId of question.versions) {
  300.                 const newQuestion = {
  301.                     _id: Random.id(),
  302.                     crossVersionId: idMap[versionId][question._id],
  303.                     study: question.study,
  304.                     version: versionId,
  305.                     versionNum: versionNumMap[versionId],
  306.                     pageBlock: idMap[versionId][question.pageBlocks[versionId]],
  307.                     page: idMap[versionId][question.pages[versionId]],
  308.                     questionText: question.questionText,
  309.                     header: question.header || '',
  310.                     order: question.order[versionId],
  311.                     type: question.type,
  312.                     options: question.options,
  313.                     linkId: linkId,
  314.                     linkOrder: linkOrder++,
  315.                     linkedVersions: question.versions.slice(0, sliceEndIndex++)
  316.                 };
  317.  
  318.                 if (question.number) {
  319.                     newQuestion.number = question.number[versionId];
  320.                 }
  321.  
  322.                 if (question.visibilityCondition && question.visibilityCondition[versionId]) {
  323.                     newQuestion.visibilityCondition = replaceAffectedConditionIds(question.visibilityCondition[versionId], idMap[versionId], builtRegex);
  324.                 }
  325.  
  326.                 if (question.pipes) {
  327.                     newQuestion.pipes = [];
  328.  
  329.                     for (const pipe of question.pipes) {
  330.                         newQuestion.pipes.push(Object.assign(pipe, { fromQuestion: idMap[versionId][pipe.fromQuestion] }));                      
  331.                     }
  332.                 }
  333.  
  334.                 questionBulkOps.push({ insertOne: { document: newQuestion } });
  335.             }
  336.  
  337.             removeQuestionIds.push(question._id);
  338.         }
  339.  
  340.  
  341.         console.log('Building Stub Bulk Ops...');
  342.  
  343.         const removeStubIds = [],
  344.             stubBulkOps = [
  345.                 {
  346.                     deleteMany: {
  347.                         filter: { _id: { $in: removeStubIds } }
  348.                     }
  349.                 }
  350.             ];
  351.  
  352.         for (const stub of stubs) {
  353.             const linkId = Random.id();
  354.  
  355.             let linkOrder = 0,
  356.                 sliceEndIndex = 1;
  357.  
  358.             for (const versionId of stub.versions) {
  359.                 const newStub = {
  360.                     _id: Random.id(),
  361.                     crossVersionId: idMap[versionId][stub._id],
  362.                     study: stub.study,
  363.                     version: versionId,
  364.                     pageBlock: idMap[versionId][stub.pageBlocks[versionId]],
  365.                     page: idMap[versionId][stub.pages[versionId]],
  366.                     question: idMap[versionId][stub.question],
  367.                     stubText: stub.stubText,
  368.                     number: stub.number[versionId],
  369.                     order: stub.order[versionId],
  370.                     type: stub.type,
  371.                     options: stub.options,
  372.                     linkId: linkId,
  373.                     linkOrder: linkOrder++,
  374.                     linkedVersions: stub.versions.slice(0, sliceEndIndex++)
  375.                 };
  376.  
  377.                 if (stub.visibilityCondition && stub.visibilityCondition[versionId]) {
  378.                     newStub.visibilityCondition = replaceAffectedConditionIds(stub.visibilityCondition[versionId], idMap[versionId], builtRegex);
  379.                 }
  380.  
  381.                 if (stub.relatedStub) {
  382.                     newStub.relatedStub = idMap[versionId][stub.relatedStub];
  383.                 }
  384.  
  385.                 if (stub.pipe) {
  386.                     newStub.pipe = {
  387.                         question: idMap[versionId][stub.pipe.question],
  388.                         stub: idMap[versionId][stub.pipe.stub]
  389.                     };
  390.                 }
  391.  
  392.                 stubBulkOps.push({ insertOne: { document: newStub } });
  393.             }
  394.  
  395.             removeStubIds.push(stub._id);
  396.         }
  397.  
  398.  
  399.         const promises = [];
  400.  
  401.         if (responsesBulkOps.length) promises.push(Responses_Studies.rawCollection().bulkWrite(responsesBulkOps, { ordered: false }));
  402.         if (versionBulkOps.length) promises.push(Versions_Studies.rawCollection().bulkWrite(versionBulkOps, { ordered: false }));
  403.         if (removePageBlockIds.length) promises.push(PageBlocks_Studies.rawCollection().bulkWrite(pageBlockBulkOps, { ordered: false }));
  404.         if (removePageIds.length) promises.push(Pages_Studies.rawCollection().bulkWrite(pageBulkOps, { ordered: false }));
  405.         if (removeQuestionIds.length) promises.push(Questions_Studies.rawCollection().bulkWrite(questionBulkOps, { ordered: false }));
  406.         if (removeStubIds.length) promises.push(QuestionStubs_Studies.rawCollection().bulkWrite(stubBulkOps, { ordered: false }));
  407.  
  408.         console.log('Running Ops...');
  409.  
  410.         return Promise.all(promises);
  411.     },
  412.     // Meteor.call('addResponseDataTypeOne', 'C5pG3Bq49DSiK6GXp')
  413.     addResponseDataTypeOne(versionId) {
  414.         const invite = InviteTemplates_Studies.findOne({ version: versionId });
  415.         const responses = Responses_Studies.find({ version: versionId }).fetch();
  416.  
  417.         for (const response of responses) {
  418.             if (!response.surveySession) {
  419.                 continue;
  420.             }
  421.              
  422.             const responseData = {
  423.                 startedDate: new Date(response.surveySession.startedDate),
  424.                 inviteId: invite._id,
  425.                 versionId: versionId,
  426.                 responseId: response._id
  427.             };
  428.              
  429.             if (response.surveySession.completedDate) {
  430.                 responseData.completedDate = new Date(response.surveySession.completedDate);
  431.             }
  432.              
  433.             Respondents_Studies.update(
  434.                 { _id: response.respondent },
  435.                 {
  436.                     $addToSet:
  437.                         {
  438.                             responseData: responseData
  439.                         }
  440.                 }, { bypassCollection2: true });
  441.         }  
  442.     },
  443.     insertTest: function (data) {
  444.         //console.log(data);
  445.         Fields_Studies.insert(data, function (err, res) {
  446.             if (err) {
  447.                 console.log('err ' + err);
  448.             } else {
  449.                 console.log('res ' + res);
  450.             }
  451.         });
  452.  
  453.     },
  454.     updateTest: function (dataOne, dataTwo) {
  455.         Responses_Studies.update(dataOne, dataTwo, function (err, res) {
  456.             if (err) {
  457.                 console.log('err ' + err);
  458.             } else {
  459.                 console.log('res ' + res);
  460.             }
  461.         });
  462.  
  463.     },
  464.     /* SIBYL STUDIES */
  465.     // migrateNpsStudies: function() {
  466.     //   let user = Meteor.users.findOne(this.userId);
  467.     //
  468.     //   if (!user || !user.admin) return;
  469.     //
  470.     //     let subs = Subscriptions.aggregate([
  471.     //         {$match: { product: 0 }},
  472.     //         {$lookup: {
  473.     //             from: 'campaigns',
  474.     //             localField: '_id',
  475.     //             foreignField: 'Owner',
  476.     //             as: 'campaigns'
  477.     //         }},
  478.     //         {$lookup: {
  479.     //             from: 'campaigns',
  480.     //             localField: '_id',
  481.     //             foreignField: 'Owner',
  482.     //             as: 'campaigns'
  483.     //         }},
  484.     //     ], { allowDiskUse: true });
  485.     //
  486.     //     for (let sub of subs) {
  487.     //
  488.     //     }
  489.     //
  490.     //   Subscriptions.update({ allowedQuestionTypes: {$exists: false} }, { $set: {allowedQuestionTypes: allowedTypes} }, { multi: true });
  491.     // },
  492.     /* SIBYL 2.0 */
  493.     migrateAlertCounts: function () {
  494.         let user = Meteor.users.findOne(this.userId);
  495.  
  496.         if (!user || user.emails[0].address !== "omer@signetresearch.com") {
  497.             return;
  498.         }
  499.  
  500.         console.log('running');
  501.  
  502.         let users = Meteor.users.find().fetch();
  503.  
  504.         for (let user of users) {
  505.  
  506.             if (typeof user.alertCounts === 'object' && Array.isArray(user.alertCounts)) {
  507.                 let alertCountsObj = {};
  508.  
  509.                 if (Array.isArray(user.alertCounts)) {
  510.                     for (let alertCount of user.alertCounts) {
  511.                         let campaignId = alertCount.campaign;
  512.                         delete alertCount.campaign;
  513.  
  514.                         alertCountsObj[campaignId] = alertCount;
  515.                     }
  516.                 }
  517.  
  518.                 Meteor.users.update({ _id: user._id }, { $set: { alertCounts: alertCountsObj } });
  519.             }
  520.         }
  521.  
  522.         console.log('finished');
  523.     },
  524.     migrateSubscriptionsTracking: function () {
  525.         let user = Meteor.users.findOne(this.userId);
  526.  
  527.         if (!user || user.emails[0].address !== "omer@signetresearch.com") {
  528.             return;
  529.         }
  530.  
  531.         console.log('running');
  532.  
  533.         Subscriptions.update({
  534.             emailUsed: { $exists: false },
  535.             emailContracted: { $exists: false },
  536.             webSurveyUsed: { $exists: false },
  537.             inboxUsed: { $exists: false },
  538.             inboxContracted: { $exists: false },
  539.             webSurveyContracted: { $exists: false },
  540.             renewDate: { $exists: false },
  541.             startDate: { $exists: false }
  542.         }, {
  543.                 $set: {
  544.                     emailUsed: 0,
  545.                     emailContracted: 0,
  546.                     webSurveyUsed: 0,
  547.                     inboxUsed: 0,
  548.                     inboxContracted: 0,
  549.                     webSurveyContracted: 0,
  550.                     renewDate: new Date(),
  551.                     startDate: new Date()
  552.                 }
  553.             }, { multi: true });
  554.  
  555.         console.log('finished');
  556.     },
  557.     migrateUnsubsBouncesThreads: function () {
  558.         let user = Meteor.users.findOne(this.userId);
  559.  
  560.         if (!user || user.emails[0].address !== "omer@signetresearch.com") {
  561.             return;
  562.         }
  563.  
  564.         var subs = Subscriptions.find().fetch();
  565.  
  566.         for (let sub of subs) {
  567.             var campaigns = Campaigns.find({ Owner: sub._id }).fetch();
  568.             var bounces = Bounces.find({ Owner: sub._id }).fetch();
  569.             var unsubs = Unsubs.find({ Owner: sub._id }).fetch();
  570.  
  571.             for (let campaign of campaigns) {
  572.                 for (let bounce of bounces) {
  573.                     Threads.update({ 'respondent.Email': bounce.email, campaign: campaign._id }, { $set: { bounce: true } }, { multi: true });
  574.                 }
  575.  
  576.                 for (let unsub of unsubs) {
  577.                     if (unsub.email.indexOf('*@') === 0) {
  578.                         // global domain unsub
  579.                         var emailRegExp = new RegExp('.' + unsub.email, 'i');
  580.  
  581.                         Threads.update({ 'respondent.Email': emailRegExp, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
  582.                     } else {
  583.                         // single email unsub
  584.                         Threads.update({ 'respondent.Email': unsub.email, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
  585.                     }
  586.                 }
  587.             }
  588.         }
  589.     },
  590.     addUsersUnreadThreads: function () {
  591.         let user = Meteor.users.findOne(this.userId);
  592.  
  593.         if (!user || user.emails[0].address !== "omer@signetresearch.com") {
  594.             return;
  595.         }
  596.  
  597.         Meteor.users.update({}, { $set: { unreadThreads: [] } }, { multi: true });
  598.     },
  599.     /* /SIBYL 2.0 */
  600.     addLastMessageDates: function () {
  601.         let user = Meteor.users.findOne(this.userId);
  602.  
  603.         if (!user || user.emails[0].address !== "omer@signetresearch.com") {
  604.             return;
  605.         }
  606.  
  607.         let threads = Threads.find().fetch();
  608.  
  609.         for (let thread of threads) {
  610.             let lastMessage = Messages.findOne({ thread: thread._id }, { sort: { createdAt: -1 } });
  611.  
  612.             Threads.update({ _id: thread._id }, { $set: { lastMessageDate: lastMessage.createdAt } });
  613.         }
  614.     },
  615.     addCampaignDefaultquestion: function () {
  616.         let user = Meteor.users.findOne(this.userId);
  617.  
  618.         if (!user || user.emails[0].address !== "omer@signetresearch.com") {
  619.             return;
  620.         }
  621.         Campaigns.update({}, { $set: { webLink: "On a scale of 0-10 (where \"0\" is Not Likely and \"10\" is Very Likely), how likely are you to recommend us to a colleague or peer if you had the opportunity to do so?" } }, { multi: true });
  622.  
  623.     },
  624.     cleaningjob: function () {
  625.         var user = Meteor.users.findOne(this.userId);
  626.         if (user && user.emails[0].address === "omer@signetresearch.com") {
  627.             var now = new Date();
  628.             var threehoursago = new Date(now.getTime() - 10800000);
  629.             EmailProfileMatchResults.remove({ processedDate: { $lt: threehoursago } });
  630.             initialJobs.remove({ status: "completed" });
  631.             initialJobs.remove({ status: "completed" });
  632.             reminderJobs.remove({ status: "completed" });
  633.             emailprofilematchingJobs.remove({ status: "completed" });
  634.             /*
  635.             var ids = initialJobs.find({status:"completed"}).map(function(a){return a._id;});
  636.             initialJobs.removeJobs(ids);
  637.             */
  638.         }
  639.     },
  640.     migrateRespondentSurveys: function () {
  641.         var user = Meteor.users.findOne(this.userId);
  642.         if (user && user.emails[0].address === "omer@signetresearch.com") {
  643.             console.log('started');
  644.  
  645.             var subs = Subscriptions.find().fetch();
  646.  
  647.             for (let sub of subs) {
  648.                 var campaigns = Campaigns.find({ Owner: sub._id }).fetch();
  649.  
  650.                 for (let campaign of campaigns) {
  651.                     var respondents = Respondents.find({ campaign: campaign._id }).fetch();
  652.  
  653.                     for (let respondent of respondents) {
  654.                         var surveys = Surveys.find({ campaign: campaign._id, 'respondent._id': respondent._id }, { sort: { createdAt: -1 }, fields: { createdAt: 1 } }).fetch();
  655.  
  656.                         if (surveys.length) {
  657.                             var dates = surveys.map(function (obj) {
  658.                                 return obj.createdAt;
  659.                             });
  660.  
  661.                             Respondents.update({ _id: respondent._id }, { $set: { surveyDates: dates } });
  662.                         }
  663.                     }
  664.                 }
  665.             }
  666.         }
  667.  
  668.         console.log('done');
  669.     },
  670.     migrateUnsubsBounces: function () {
  671.         var user = Meteor.users.findOne(this.userId);
  672.         if (user && user.emails[0].address === "omer@signetresearch.com") {
  673.             var subs = Subscriptions.find().fetch();
  674.  
  675.             for (let sub of subs) {
  676.                 var campaigns = Campaigns.find({ Owner: sub._id }).fetch();
  677.                 var bounces = Bounces.find({ Owner: sub._id }).fetch();
  678.                 var unsubs = Unsubs.find({ Owner: sub._id }).fetch();
  679.  
  680.                 for (let campaign of campaigns) {
  681.                     for (let bounce of bounces) {
  682.                         Respondents.update({ Email: bounce.email, campaign: campaign._id }, { $set: { bounce: true } }, { multi: true });
  683.                     }
  684.  
  685.                     for (let unsub of unsubs) {
  686.                         if (unsub.email.indexOf('*@') === 0) {
  687.                             // global domain unsub
  688.                             var emailRegExp = new RegExp('.' + unsub.email, 'i');
  689.  
  690.                             Respondents.update({ Email: emailRegExp, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
  691.                         } else {
  692.                             // single email unsub
  693.                             Respondents.update({ Email: unsub.email, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
  694.                         }
  695.                     }
  696.                 }
  697.             }
  698.         }
  699.     },
  700.     deletejobs: function () {
  701.         var user = Meteor.users.findOne(this.userId);
  702.         if (user && user.emails[0].address === "omer@signetresearch.com") {
  703.             initialJobs.remove({}, { multi: true });
  704.             reminderJobs.remove({}, { multi: true });
  705.         }
  706.     },
  707.     addUsers: function (accounts, password, subid) {
  708.         var user = Meteor.users.findOne(this.userId);
  709.         if (user && user.emails[0].address === "omer@signetresearch.com") {
  710.             for (let account of accounts) {
  711.                 var name = account.name;
  712.                 var email = account.email;
  713.                 Accounts.createUser({ email: email, password: password });
  714.  
  715.                 var newuser = Meteor.users.findOne({ emails: { $elemMatch: { address: email } } });
  716.                 var newuserid = newuser._id;
  717.  
  718.                 Meteor.users.update({ _id: newuserid }, {
  719.                     $set: {
  720.                         Name: name,
  721.                         Sub: subid,
  722.                         alertCounts: {},
  723.                         integrations: {
  724.                             salesforce: {
  725.                                 enabled: false,
  726.                                 options: {}
  727.                             }
  728.                         },
  729.                         unreadThreads: []
  730.                     }
  731.                 });
  732.  
  733.                 Subscriptions.update({ _id: subid }, { $push: { Members: newuserid } });
  734.  
  735.                 // Push an alert count object for each campaign associated with the subscription
  736.                 var campaigns = Campaigns.find({ Owner: subid }).fetch();
  737.                 var newAlertCounts = {};
  738.  
  739.                 for (let campaign of campaigns) {
  740.                     newAlertCounts[campaign._id] = {
  741.                         Detractors: 0,
  742.                         Neutral: 0,
  743.                         Promoters: 0
  744.                     };
  745.                 }
  746.  
  747.                 Meteor.users.update({ _id: newuserid }, { $set: { alertCounts: newAlertCounts } });
  748.             }
  749.             //ADD A FUNCTION TO ADD IN DEFAULT ALERTCOUNTS OBJ TO 0s for each key.
  750.         }
  751.         else {
  752.             throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  753.         }
  754.     },
  755.     addUser: function (email, password) {
  756.         var user = Meteor.users.findOne(this.userId);
  757.         if (user && user.emails[0].address === "omer@signetresearch.com") {
  758.             Accounts.createUser({ email: email, password: password });
  759.  
  760.             //ADD A FUNCTION TO ADD IN DEFAULT ALERTCOUNTS OBJ TO 0s for each key.
  761.         }
  762.         else {
  763.             throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  764.         }
  765.     },
  766.     setName: function (name) {
  767.         Meteor.users.update({ _id: this.userId }, { $set: { Name: name } });
  768.  
  769.     },
  770.     userChangeSubscription: function (userid, subid) {
  771.         var user1 = Meteor.users.findOne(this.userId);
  772.         if (user1 && user1.emails[0].address === "omer@signetresearch.com") {
  773.             var user = Meteor.users.findOne(userid);
  774.             var existing_sub = user.Sub;
  775.  
  776.             if (existing_sub) {
  777.                 Subscriptions.update({ _id: existing_sub }, { $pull: { Members: userid } });
  778.             }
  779.  
  780.             Meteor.users.update({ _id: userid }, { $set: { Sub: subid } });
  781.             Subscriptions.update({ _id: subid }, { $push: { Members: userid } });
  782.  
  783.             // Reset alertCounts and set an alert count object for each campaign associated with the new subscription
  784.             var campaigns = Campaigns.find({ Owner: subid }).fetch();
  785.             var newAlertCounts = {};
  786.  
  787.             for (let campaign of campaigns) {
  788.                 newAlertCounts[campaignId] = {
  789.                     Detractors: 0,
  790.                     Neutral: 0,
  791.                     Promoters: 0
  792.                 };
  793.             }
  794.  
  795.       Meteor.users.update({_id: userid}, {$set: {alertCounts: newAlertCounts}});
  796.     }
  797.     else
  798.     {
  799.       throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  800.     }
  801.   },
  802.   userRemoveFromSub:function(userid,subid){
  803.     var user = Meteor.users.findOne(this.userId);
  804.     if(user && user.emails[0].address === "omer@signetresearch.com")
  805.     {
  806.       Subscriptions.update({_id: subid}, {$pull: {Members: userid}});
  807.     }
  808.     else
  809.     {
  810.       throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  811.     }
  812.   },
  813.   addSubscription: function(subname) {
  814.     var user = Meteor.users.findOne(this.userId);
  815.     if(user && user.emails[0].address === "omer@signetresearch.com")
  816.     {
  817.       var id = Subscriptions.insert({Name: subname, Members: [], product: 0, Domains: []});
  818.       //Fields.insert({Owner: id, Fields: ["Email", "First Name", "Last Name", "Company"]});
  819.     }
  820.     else
  821.     {
  822.       throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  823.     }
  824.   },
  825.   addDomaintoSub: function(subid, domain) {
  826.     var user = Meteor.users.findOne(this.userId);
  827.     if(user && user.emails[0].address === "omer@signetresearch.com")
  828.     {
  829.       Subscriptions.update({_id: subid}, {$push: {Domains: domain}});
  830.     }
  831.     else
  832.     {
  833.       throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  834.     }
  835.   },
  836.   removeDomainfromSub: function(subid, domain) {
  837.     var user = Meteor.users.findOne(this.userId);
  838.     if(user && user.emails[0].address === "omer@signetresearch.com")
  839.     {
  840.       Subscriptions.update({_id: subid}, {$pull: {Domains: domain}});
  841.     }
  842.     else
  843.     {
  844.       throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
  845.     }
  846.   },
  847.   genTestData: function(numOfEntries, campaignId){
  848.     var currentUrl = Meteor.absoluteUrl();
  849.     if (currentUrl.toLocaleLowerCase().includes("sibyl")){
  850.       //if live server don't run
  851.       throw new Meteor.Error("production-server","This isn't for production servers");
  852.     }
  853.     if (numOfEntries === null || numOfEntries < 0 || numOfEntries === undefined){
  854.       throw new Meteor.Error("missing-var", "Please specify the amount of entries, ex - 'genData', 5");
  855.     }
  856.     if (campaignId === null || campaignId === undefined){
  857.       throw new Meteor.Error("missing-var", "Please specify the campaign ID");
  858.     }
  859.     var todayDate = new Date();
  860.     var pastDate = new Date();
  861.     pastDate.setDate(todayDate.getDate()-1);
  862.     var id = this.userId;
  863.     var respondent = Respondents.findOne({campaign : campaignId});
  864.     if (respondent === undefined){
  865.       throw new Meteor.Error("bad-id", "campaign ID doesn't exist in respondents");
  866.     }
  867.     for (var i = 0; i < numOfEntries; i++){
  868.     var npsNum = Math.round((Math.random() * 10));
  869.     if (npsNum <= 5){
  870.       npsNum = 9;
  871.     }
  872.     //var newName = String.fromCharCode(Math.random()*26+97);
  873.     var newData = {
  874.       createdAt: pastDate,
  875.       completed: todayDate,
  876.       respondent: respondent,
  877.       campaign: campaignId,
  878.       templatesent: "No Template",
  879.       profilesent: "No Name",
  880.       surveylogo : "any.jpg",
  881.       status: "C",
  882.       responses: {
  883.           firstquestion: npsNum,
  884.           secondquestion: "I love NPS"
  885.         }
  886.       };
  887.       Surveys.insert(newData);
  888.     }
  889.   },
  890.   addRespondentResponseData: function() {
  891.     // you will need to update the Owner to your subscription
  892.     Studies.insert({
  893.       "_id" : "eCn9BSRY7PbQQoqjr",
  894.       "name" : "Test Study For Collection type 2",
  895.       "Owner" : "zWhgtEjAKGo4KHXPJ",
  896.       "description" : "description text",
  897.       "created" : new Date("2017-03-20T15:12:33.972Z"),
  898.       "lastModified" : new Date("2017-04-07T13:50:26.645Z"),
  899.       "options" : {
  900.         "theme" : "default_theme",
  901.         "showQuestionNumbers" : false,
  902.         "backtracking" : false
  903.       },
  904.       "Alerts" : [ ],
  905.       "Exclusions" : {
  906.         "receivedInviteExclusion" : {
  907.           "enabled" : true,
  908.           "values" : {
  909.             "numInvites" : {
  910.               "value" : 1
  911.             },
  912.             "numDays" : {
  913.               "value" : 1
  914.             }
  915.           }
  916.         },
  917.         "noResponseExclusion" : {
  918.           "enabled" : true,
  919.           "values" : {
  920.             "numInvites" : {
  921.               "value" : 0
  922.             }
  923.           }
  924.         }
  925.       },
  926.       "Defaults" : {
  927.  
  928.             },
  929.             "endPageHtml": "<p>End</p>",
  930.             "closedPageHtml": "<p>End</p>",
  931.             "status": 1,
  932.             "collectionType": 2
  933.         });
  934.         Profiles_Studies.insert({
  935.             "_id": "gBAiphxSbgujJcuPr",
  936.             "study": "eCn9BSRY7PbQQoqjr",
  937.             "name": "Profile Name Here",
  938.             "sendername": "sendernametext",
  939.             "fromfield": "fromfieldtext",
  940.             "signaturehtml": "This is signature text",
  941.             "key1": "key1",
  942.             "key2": "k2",
  943.             "key3": "k3"
  944.         });
  945.         InviteTemplates_Studies.insert({
  946.             "_id": "ERQ52CEQQk7YknkDx",
  947.             "study": "eCn9BSRY7PbQQoqjr",
  948.             "title": "This Is An Email Template",
  949.             "fromdomain": "mails.sibylsurveys.com",
  950.             "subject": "New sub",
  951.             "bodyhtml": "<p>%NPSQUESTION~On a scale of 0-10 (where &quot;0&quot; is Not Likely and &quot;10&quot; is Very Likely), how likely are you to recommend us to a colleague or peer if you had the oasdpportunity to do so? <br> %%UNSUB~Click here to unsubscribe.%%FIELD.Email%%FIELD.undefined%</p>"
  952.         });
  953.         // adds data for respondents and responses that are in pairs, calls functions for additional visual randomization
  954.         for (let i = 1; i < 30; i++) {
  955.             Responses_Studies.insert({
  956.                 "_id": `responserad${i}`,
  957.                 "study": "eCn9BSRY7PbQQoqjr",
  958.                 "respondent": `respondentrad${i}`,
  959.                 "profile": {
  960.                     "email": `any${i}@mailinator.com`,
  961.                     "first_name": `${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}`,
  962.                     "last_name": "Can"
  963.                 },
  964.                 "surveySession": randSurveySession(i),
  965.                 inviteDates: [
  966.                     {
  967.                         date: new Date(`4/${i}/2017`),
  968.                         profileSent: "gBAiphxSbgujJcuPr",
  969.                         inviteSent: "ERQ52CEQQk7YknkDx"
  970.                     }
  971.                 ],
  972.                 "createdAt": new Date(`4/${i}/2017`)
  973.             });
  974.  
  975.             Respondents_Studies.insert({
  976.                 "_id": `respondentrad${i}`,
  977.                 "study": "eCn9BSRY7PbQQoqjr",
  978.                 "profile": {
  979.                     "email": `11${i}@mailinator.com`,
  980.                     "first_name": `${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}`,
  981.                     "last_name": "Can"
  982.                 }
  983.             });
  984.         }
  985.     }
  986. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement