Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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';
- import { Campaigns, Threads, Messages, Respondents, Surveys, EmailProfileMatchResults, Fields } from '/lib/collections/collections_nps';
- import { Subscriptions, Bounces, Unsubs, emailprofilematchingJobs } from '/lib/collections/collections_common';
- import { initialJobs, reminderJobs } from '/lib/collections/collections_common';
- import { replaceAffectedConditionIds } from '/server/studies/design_study/design_study_helpers';
- function randSurveySession(i) {
- if (i % 2 === 0) {
- return { startedDate: new Date(`4/${i}/2017`), completedDate: new Date(`4/${i}/2017`) };
- } else {
- return { startedDate: new Date(`4/${i}/2017`) };
- }
- }
- Meteor.methods({
- migrateVersioning() {
- console.log('Starting Migration...');
- const versions = Versions_Studies.find().fetch(),
- pageBlocks = PageBlocks_Studies.find().fetch(),
- pages = Pages_Studies.find().fetch(),
- questions = Questions_Studies.find().fetch(),
- stubs = QuestionStubs_Studies.find().fetch();
- const idMap = {},
- versionNumMap = {};
- let regExBuild = '';
- console.log('Creating ID Map...');
- for (const version of versions) {
- idMap[version._id] = {};
- versionNumMap[version._id] = version.number;
- }
- for (const pageBlock of pageBlocks) {
- const crossVersionId = Random.id();
- for (const versionId of pageBlock.versions) {
- idMap[versionId][pageBlock._id] = crossVersionId;
- }
- }
- for (const page of pages) {
- const crossVersionId = Random.id();
- regExBuild += `${page._id}|`;
- for (const versionId of page.versions) {
- idMap[versionId][page._id] = crossVersionId;
- }
- }
- for (const question of questions) {
- const crossVersionId = Random.id();
- regExBuild += `${question._id}|`;
- for (const versionId of question.versions) {
- idMap[versionId][question._id] = crossVersionId;
- }
- }
- for (const stub of stubs) {
- const crossVersionId = Random.id();
- regExBuild += `${stub._id}|`;
- for (const versionId of stub.versions) {
- idMap[versionId][stub._id] = crossVersionId;
- }
- }
- const builtRegex = new RegExp(regExBuild.slice(0, -1), 'g');
- console.log('Building Responses Bulk Ops...');
- const responsesBulkOps = [];
- Responses_Studies.find({ surveySession: { $exists: true } }).forEach((responseDoc) => {
- const versionIdMap = idMap[responseDoc.version],
- surveySession = responseDoc.surveySession;
- // Remap surveySession object
- if (surveySession.currentPage) {
- surveySession.currentPage = versionIdMap[surveySession.currentPage];
- }
- if (surveySession.branches) {
- surveySession.branches = Object.entries(surveySession.branches)
- .reduce((mapObj, [branchFromPageId, branchToPageId]) => {
- mapObj[versionIdMap[branchFromPageId]] = versionIdMap[branchToPageId];
- return mapObj;
- }, {});
- }
- if (surveySession.orders) {
- if (surveySession.orders.pages) {
- surveySession.orders.pages = surveySession.orders.pages.map(pageId => versionIdMap[pageId]);
- }
- if (surveySession.orders.randomQuestions) {
- surveySession.orders.randomQuestions = Object.entries(surveySession.orders.randomQuestions)
- .reduce((mapObj, [pageId, questionIds]) => {
- mapObj[versionIdMap[pageId]] = questionIds.map(questionId => versionIdMap[questionId]);
- return mapObj;
- }, {});
- }
- if (surveySession.orders.randomStubs) {
- surveySession.orders.randomStubs = Object.entries(surveySession.orders.randomStubs)
- .reduce((mapObj, [questionId, stubIds]) => {
- mapObj[versionIdMap[questionId]] = stubIds.map(stubId => versionIdMap[stubId]);
- return mapObj;
- }, {});
- }
- }
- // Remap responses array
- responses = responseDoc.responses.map((responseObj) => {
- responseObj.question = versionIdMap[responseObj.question];
- const questionType = responseObj.questionType;
- if (questionType === 0) {
- responseObj.response = versionIdMap[responseObj.response];
- } else if (questionType === 1) {
- responseObj.response = responseObj.response.map(stubId => versionIdMap[stubId]);
- } else if (questionType === 3 || questionType === 4) {
- responseObj.response = responseObj.response.map((concatStubId) => {
- const [rowStubId, colStubId] = concatStubId.split('.');
- return `${versionIdMap[rowStubId]}.${versionIdMap[colStubId]}`;
- });
- } else if (questionType === 5) {
- responseObj.response = Object.entries(responseObj.response)
- .reduce((mapObj, [subQStubId, textResponse]) => {
- mapObj[versionIdMap[subQStubId]] = textResponse;
- return mapObj;
- }, {});
- } else if (questionType === 7) {
- responseObj.response = responseObj.response.map((concatStubId) => {
- const [subQStubId, rowStubId, colStubId] = concatStubId.split('.');
- return `${versionIdMap[subQStubId]}.${versionIdMap[rowStubId]}.${versionIdMap[colStubId]}`;
- });
- }
- // Remap specifiers object if necessary
- if (responseObj.specifiers) {
- responseObj.specifiers = Object.entries(responseObj.specifiers)
- .reduce((mapObj, [stubId, specifyText]) => {
- mapObj[versionIdMap[stubId]] = specifyText;
- return mapObj;
- }, {});
- }
- return responseObj;
- });
- responsesBulkOps.push({
- updateOne: {
- filter: { _id: responseDoc._id },
- update: { $set: { surveySession, responses } }
- }
- });
- });
- console.log('Building Version Bulk Ops...');
- const versionBulkOps = [];
- for (const version of versions) {
- if (version.alerts && version.alerts.length) {
- versionBulkOps.push({
- updateOne: {
- filter: { _id: version._id },
- update: {
- $set: {
- alerts: version.alerts.map((alert) => {
- alert.condition = replaceAffectedConditionIds(alert.condition, idMap[version._id], builtRegex);
- return alert;
- })
- }
- }
- }
- });
- }
- }
- console.log('Building PageBlock Bulk Ops...');
- const removePageBlockIds = [],
- pageBlockBulkOps = [
- {
- deleteMany: {
- filter: { _id: { $in: removePageBlockIds } }
- }
- }
- ];
- for (const pageBlock of pageBlocks) {
- for (const versionId of pageBlock.versions) {
- pageBlockBulkOps.push({
- insertOne: {
- document: {
- _id: Random.id(),
- crossVersionId: idMap[versionId][pageBlock._id],
- study: pageBlock.study,
- version: versionId,
- title: pageBlock.title,
- number: pageBlock.number[versionId],
- options: pageBlock.options
- }
- }
- });
- }
- removePageBlockIds.push(pageBlock._id);
- }
- console.log('Building Page Bulk Ops...');
- const removePageIds = [],
- pageBulkOps = [
- {
- deleteMany: {
- filter: { _id: { $in: removePageIds } }
- }
- }
- ];
- for (const page of pages) {
- for (const versionId of page.versions) {
- const newPage = {
- _id: Random.id(),
- crossVersionId: idMap[versionId][page._id],
- study: page.study,
- version: versionId,
- pageBlock: idMap[versionId][page.pageBlocks[versionId]],
- title: page.title,
- number: page.number[versionId],
- options: page.options
- };
- if (page.visibilityCondition && page.visibilityCondition[versionId]) {
- newPage.visibilityCondition = replaceAffectedConditionIds(page.visibilityCondition[versionId], idMap[versionId], builtRegex);
- }
- if (page.branchConditions) {
- newPage.branchConditions = [];
- for (const cond of page.branchConditions) {
- if (cond.version === versionId) {
- newPage.branchConditions.push(replaceAffectedConditionIds(_.omit(cond, 'version'), idMap[versionId], builtRegex));
- }
- }
- }
- if (page.terminateConditions) {
- newPage.terminateConditions = [];
- for (const cond of page.terminateConditions) {
- if (cond.version === versionId) {
- newPage.terminateConditions.push(replaceAffectedConditionIds(_.omit(cond, 'version'), idMap[versionId], builtRegex));
- }
- }
- }
- pageBulkOps.push({ insertOne: { document: newPage } });
- }
- removePageIds.push(page._id);
- }
- console.log('Building Question Bulk Ops...');
- const removeQuestionIds = [],
- questionBulkOps = [
- {
- deleteMany: {
- filter: { _id: { $in: removeQuestionIds } }
- }
- }
- ];
- for (const question of questions) {
- const linkId = Random.id();
- let linkOrder = 0,
- sliceEndIndex = 1;
- for (const versionId of question.versions) {
- const newQuestion = {
- _id: Random.id(),
- crossVersionId: idMap[versionId][question._id],
- study: question.study,
- version: versionId,
- versionNum: versionNumMap[versionId],
- pageBlock: idMap[versionId][question.pageBlocks[versionId]],
- page: idMap[versionId][question.pages[versionId]],
- questionText: question.questionText,
- header: question.header || '',
- order: question.order[versionId],
- type: question.type,
- options: question.options,
- linkId: linkId,
- linkOrder: linkOrder++,
- linkedVersions: question.versions.slice(0, sliceEndIndex++)
- };
- if (question.number) {
- newQuestion.number = question.number[versionId];
- }
- if (question.visibilityCondition && question.visibilityCondition[versionId]) {
- newQuestion.visibilityCondition = replaceAffectedConditionIds(question.visibilityCondition[versionId], idMap[versionId], builtRegex);
- }
- if (question.pipes) {
- newQuestion.pipes = [];
- for (const pipe of question.pipes) {
- newQuestion.pipes.push(Object.assign(pipe, { fromQuestion: idMap[versionId][pipe.fromQuestion] }));
- }
- }
- questionBulkOps.push({ insertOne: { document: newQuestion } });
- }
- removeQuestionIds.push(question._id);
- }
- console.log('Building Stub Bulk Ops...');
- const removeStubIds = [],
- stubBulkOps = [
- {
- deleteMany: {
- filter: { _id: { $in: removeStubIds } }
- }
- }
- ];
- for (const stub of stubs) {
- const linkId = Random.id();
- let linkOrder = 0,
- sliceEndIndex = 1;
- for (const versionId of stub.versions) {
- const newStub = {
- _id: Random.id(),
- crossVersionId: idMap[versionId][stub._id],
- study: stub.study,
- version: versionId,
- pageBlock: idMap[versionId][stub.pageBlocks[versionId]],
- page: idMap[versionId][stub.pages[versionId]],
- question: idMap[versionId][stub.question],
- stubText: stub.stubText,
- number: stub.number[versionId],
- order: stub.order[versionId],
- type: stub.type,
- options: stub.options,
- linkId: linkId,
- linkOrder: linkOrder++,
- linkedVersions: stub.versions.slice(0, sliceEndIndex++)
- };
- if (stub.visibilityCondition && stub.visibilityCondition[versionId]) {
- newStub.visibilityCondition = replaceAffectedConditionIds(stub.visibilityCondition[versionId], idMap[versionId], builtRegex);
- }
- if (stub.relatedStub) {
- newStub.relatedStub = idMap[versionId][stub.relatedStub];
- }
- if (stub.pipe) {
- newStub.pipe = {
- question: idMap[versionId][stub.pipe.question],
- stub: idMap[versionId][stub.pipe.stub]
- };
- }
- stubBulkOps.push({ insertOne: { document: newStub } });
- }
- removeStubIds.push(stub._id);
- }
- const promises = [];
- if (responsesBulkOps.length) promises.push(Responses_Studies.rawCollection().bulkWrite(responsesBulkOps, { ordered: false }));
- if (versionBulkOps.length) promises.push(Versions_Studies.rawCollection().bulkWrite(versionBulkOps, { ordered: false }));
- if (removePageBlockIds.length) promises.push(PageBlocks_Studies.rawCollection().bulkWrite(pageBlockBulkOps, { ordered: false }));
- if (removePageIds.length) promises.push(Pages_Studies.rawCollection().bulkWrite(pageBulkOps, { ordered: false }));
- if (removeQuestionIds.length) promises.push(Questions_Studies.rawCollection().bulkWrite(questionBulkOps, { ordered: false }));
- if (removeStubIds.length) promises.push(QuestionStubs_Studies.rawCollection().bulkWrite(stubBulkOps, { ordered: false }));
- console.log('Running Ops...');
- return Promise.all(promises);
- },
- // Meteor.call('addResponseDataTypeOne', 'C5pG3Bq49DSiK6GXp')
- addResponseDataTypeOne(versionId) {
- const invite = InviteTemplates_Studies.findOne({ version: versionId });
- const responses = Responses_Studies.find({ version: versionId }).fetch();
- for (const response of responses) {
- if (!response.surveySession) {
- continue;
- }
- const responseData = {
- startedDate: new Date(response.surveySession.startedDate),
- inviteId: invite._id,
- versionId: versionId,
- responseId: response._id
- };
- if (response.surveySession.completedDate) {
- responseData.completedDate = new Date(response.surveySession.completedDate);
- }
- Respondents_Studies.update(
- { _id: response.respondent },
- {
- $addToSet:
- {
- responseData: responseData
- }
- }, { bypassCollection2: true });
- }
- },
- insertTest: function (data) {
- //console.log(data);
- Fields_Studies.insert(data, function (err, res) {
- if (err) {
- console.log('err ' + err);
- } else {
- console.log('res ' + res);
- }
- });
- },
- updateTest: function (dataOne, dataTwo) {
- Responses_Studies.update(dataOne, dataTwo, function (err, res) {
- if (err) {
- console.log('err ' + err);
- } else {
- console.log('res ' + res);
- }
- });
- },
- /* SIBYL STUDIES */
- // migrateNpsStudies: function() {
- // let user = Meteor.users.findOne(this.userId);
- //
- // if (!user || !user.admin) return;
- //
- // let subs = Subscriptions.aggregate([
- // {$match: { product: 0 }},
- // {$lookup: {
- // from: 'campaigns',
- // localField: '_id',
- // foreignField: 'Owner',
- // as: 'campaigns'
- // }},
- // {$lookup: {
- // from: 'campaigns',
- // localField: '_id',
- // foreignField: 'Owner',
- // as: 'campaigns'
- // }},
- // ], { allowDiskUse: true });
- //
- // for (let sub of subs) {
- //
- // }
- //
- // Subscriptions.update({ allowedQuestionTypes: {$exists: false} }, { $set: {allowedQuestionTypes: allowedTypes} }, { multi: true });
- // },
- /* SIBYL 2.0 */
- migrateAlertCounts: function () {
- let user = Meteor.users.findOne(this.userId);
- if (!user || user.emails[0].address !== "omer@signetresearch.com") {
- return;
- }
- console.log('running');
- let users = Meteor.users.find().fetch();
- for (let user of users) {
- if (typeof user.alertCounts === 'object' && Array.isArray(user.alertCounts)) {
- let alertCountsObj = {};
- if (Array.isArray(user.alertCounts)) {
- for (let alertCount of user.alertCounts) {
- let campaignId = alertCount.campaign;
- delete alertCount.campaign;
- alertCountsObj[campaignId] = alertCount;
- }
- }
- Meteor.users.update({ _id: user._id }, { $set: { alertCounts: alertCountsObj } });
- }
- }
- console.log('finished');
- },
- migrateSubscriptionsTracking: function () {
- let user = Meteor.users.findOne(this.userId);
- if (!user || user.emails[0].address !== "omer@signetresearch.com") {
- return;
- }
- console.log('running');
- Subscriptions.update({
- emailUsed: { $exists: false },
- emailContracted: { $exists: false },
- webSurveyUsed: { $exists: false },
- inboxUsed: { $exists: false },
- inboxContracted: { $exists: false },
- webSurveyContracted: { $exists: false },
- renewDate: { $exists: false },
- startDate: { $exists: false }
- }, {
- $set: {
- emailUsed: 0,
- emailContracted: 0,
- webSurveyUsed: 0,
- inboxUsed: 0,
- inboxContracted: 0,
- webSurveyContracted: 0,
- renewDate: new Date(),
- startDate: new Date()
- }
- }, { multi: true });
- console.log('finished');
- },
- migrateUnsubsBouncesThreads: function () {
- let user = Meteor.users.findOne(this.userId);
- if (!user || user.emails[0].address !== "omer@signetresearch.com") {
- return;
- }
- var subs = Subscriptions.find().fetch();
- for (let sub of subs) {
- var campaigns = Campaigns.find({ Owner: sub._id }).fetch();
- var bounces = Bounces.find({ Owner: sub._id }).fetch();
- var unsubs = Unsubs.find({ Owner: sub._id }).fetch();
- for (let campaign of campaigns) {
- for (let bounce of bounces) {
- Threads.update({ 'respondent.Email': bounce.email, campaign: campaign._id }, { $set: { bounce: true } }, { multi: true });
- }
- for (let unsub of unsubs) {
- if (unsub.email.indexOf('*@') === 0) {
- // global domain unsub
- var emailRegExp = new RegExp('.' + unsub.email, 'i');
- Threads.update({ 'respondent.Email': emailRegExp, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
- } else {
- // single email unsub
- Threads.update({ 'respondent.Email': unsub.email, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
- }
- }
- }
- }
- },
- addUsersUnreadThreads: function () {
- let user = Meteor.users.findOne(this.userId);
- if (!user || user.emails[0].address !== "omer@signetresearch.com") {
- return;
- }
- Meteor.users.update({}, { $set: { unreadThreads: [] } }, { multi: true });
- },
- /* /SIBYL 2.0 */
- addLastMessageDates: function () {
- let user = Meteor.users.findOne(this.userId);
- if (!user || user.emails[0].address !== "omer@signetresearch.com") {
- return;
- }
- let threads = Threads.find().fetch();
- for (let thread of threads) {
- let lastMessage = Messages.findOne({ thread: thread._id }, { sort: { createdAt: -1 } });
- Threads.update({ _id: thread._id }, { $set: { lastMessageDate: lastMessage.createdAt } });
- }
- },
- addCampaignDefaultquestion: function () {
- let user = Meteor.users.findOne(this.userId);
- if (!user || user.emails[0].address !== "omer@signetresearch.com") {
- return;
- }
- 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 });
- },
- cleaningjob: function () {
- var user = Meteor.users.findOne(this.userId);
- if (user && user.emails[0].address === "omer@signetresearch.com") {
- var now = new Date();
- var threehoursago = new Date(now.getTime() - 10800000);
- EmailProfileMatchResults.remove({ processedDate: { $lt: threehoursago } });
- initialJobs.remove({ status: "completed" });
- initialJobs.remove({ status: "completed" });
- reminderJobs.remove({ status: "completed" });
- emailprofilematchingJobs.remove({ status: "completed" });
- /*
- var ids = initialJobs.find({status:"completed"}).map(function(a){return a._id;});
- initialJobs.removeJobs(ids);
- */
- }
- },
- migrateRespondentSurveys: function () {
- var user = Meteor.users.findOne(this.userId);
- if (user && user.emails[0].address === "omer@signetresearch.com") {
- console.log('started');
- var subs = Subscriptions.find().fetch();
- for (let sub of subs) {
- var campaigns = Campaigns.find({ Owner: sub._id }).fetch();
- for (let campaign of campaigns) {
- var respondents = Respondents.find({ campaign: campaign._id }).fetch();
- for (let respondent of respondents) {
- var surveys = Surveys.find({ campaign: campaign._id, 'respondent._id': respondent._id }, { sort: { createdAt: -1 }, fields: { createdAt: 1 } }).fetch();
- if (surveys.length) {
- var dates = surveys.map(function (obj) {
- return obj.createdAt;
- });
- Respondents.update({ _id: respondent._id }, { $set: { surveyDates: dates } });
- }
- }
- }
- }
- }
- console.log('done');
- },
- migrateUnsubsBounces: function () {
- var user = Meteor.users.findOne(this.userId);
- if (user && user.emails[0].address === "omer@signetresearch.com") {
- var subs = Subscriptions.find().fetch();
- for (let sub of subs) {
- var campaigns = Campaigns.find({ Owner: sub._id }).fetch();
- var bounces = Bounces.find({ Owner: sub._id }).fetch();
- var unsubs = Unsubs.find({ Owner: sub._id }).fetch();
- for (let campaign of campaigns) {
- for (let bounce of bounces) {
- Respondents.update({ Email: bounce.email, campaign: campaign._id }, { $set: { bounce: true } }, { multi: true });
- }
- for (let unsub of unsubs) {
- if (unsub.email.indexOf('*@') === 0) {
- // global domain unsub
- var emailRegExp = new RegExp('.' + unsub.email, 'i');
- Respondents.update({ Email: emailRegExp, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
- } else {
- // single email unsub
- Respondents.update({ Email: unsub.email, campaign: campaign._id }, { $set: { unsub: true } }, { multi: true });
- }
- }
- }
- }
- }
- },
- deletejobs: function () {
- var user = Meteor.users.findOne(this.userId);
- if (user && user.emails[0].address === "omer@signetresearch.com") {
- initialJobs.remove({}, { multi: true });
- reminderJobs.remove({}, { multi: true });
- }
- },
- addUsers: function (accounts, password, subid) {
- var user = Meteor.users.findOne(this.userId);
- if (user && user.emails[0].address === "omer@signetresearch.com") {
- for (let account of accounts) {
- var name = account.name;
- var email = account.email;
- Accounts.createUser({ email: email, password: password });
- var newuser = Meteor.users.findOne({ emails: { $elemMatch: { address: email } } });
- var newuserid = newuser._id;
- Meteor.users.update({ _id: newuserid }, {
- $set: {
- Name: name,
- Sub: subid,
- alertCounts: {},
- integrations: {
- salesforce: {
- enabled: false,
- options: {}
- }
- },
- unreadThreads: []
- }
- });
- Subscriptions.update({ _id: subid }, { $push: { Members: newuserid } });
- // Push an alert count object for each campaign associated with the subscription
- var campaigns = Campaigns.find({ Owner: subid }).fetch();
- var newAlertCounts = {};
- for (let campaign of campaigns) {
- newAlertCounts[campaign._id] = {
- Detractors: 0,
- Neutral: 0,
- Promoters: 0
- };
- }
- Meteor.users.update({ _id: newuserid }, { $set: { alertCounts: newAlertCounts } });
- }
- //ADD A FUNCTION TO ADD IN DEFAULT ALERTCOUNTS OBJ TO 0s for each key.
- }
- else {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- addUser: function (email, password) {
- var user = Meteor.users.findOne(this.userId);
- if (user && user.emails[0].address === "omer@signetresearch.com") {
- Accounts.createUser({ email: email, password: password });
- //ADD A FUNCTION TO ADD IN DEFAULT ALERTCOUNTS OBJ TO 0s for each key.
- }
- else {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- setName: function (name) {
- Meteor.users.update({ _id: this.userId }, { $set: { Name: name } });
- },
- userChangeSubscription: function (userid, subid) {
- var user1 = Meteor.users.findOne(this.userId);
- if (user1 && user1.emails[0].address === "omer@signetresearch.com") {
- var user = Meteor.users.findOne(userid);
- var existing_sub = user.Sub;
- if (existing_sub) {
- Subscriptions.update({ _id: existing_sub }, { $pull: { Members: userid } });
- }
- Meteor.users.update({ _id: userid }, { $set: { Sub: subid } });
- Subscriptions.update({ _id: subid }, { $push: { Members: userid } });
- // Reset alertCounts and set an alert count object for each campaign associated with the new subscription
- var campaigns = Campaigns.find({ Owner: subid }).fetch();
- var newAlertCounts = {};
- for (let campaign of campaigns) {
- newAlertCounts[campaignId] = {
- Detractors: 0,
- Neutral: 0,
- Promoters: 0
- };
- }
- Meteor.users.update({_id: userid}, {$set: {alertCounts: newAlertCounts}});
- }
- else
- {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- userRemoveFromSub:function(userid,subid){
- var user = Meteor.users.findOne(this.userId);
- if(user && user.emails[0].address === "omer@signetresearch.com")
- {
- Subscriptions.update({_id: subid}, {$pull: {Members: userid}});
- }
- else
- {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- addSubscription: function(subname) {
- var user = Meteor.users.findOne(this.userId);
- if(user && user.emails[0].address === "omer@signetresearch.com")
- {
- var id = Subscriptions.insert({Name: subname, Members: [], product: 0, Domains: []});
- //Fields.insert({Owner: id, Fields: ["Email", "First Name", "Last Name", "Company"]});
- }
- else
- {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- addDomaintoSub: function(subid, domain) {
- var user = Meteor.users.findOne(this.userId);
- if(user && user.emails[0].address === "omer@signetresearch.com")
- {
- Subscriptions.update({_id: subid}, {$push: {Domains: domain}});
- }
- else
- {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- removeDomainfromSub: function(subid, domain) {
- var user = Meteor.users.findOne(this.userId);
- if(user && user.emails[0].address === "omer@signetresearch.com")
- {
- Subscriptions.update({_id: subid}, {$pull: {Domains: domain}});
- }
- else
- {
- throw new Meteor.Error('UnauthorizedAccess', 'You are not authorized.');
- }
- },
- genTestData: function(numOfEntries, campaignId){
- var currentUrl = Meteor.absoluteUrl();
- if (currentUrl.toLocaleLowerCase().includes("sibyl")){
- //if live server don't run
- throw new Meteor.Error("production-server","This isn't for production servers");
- }
- if (numOfEntries === null || numOfEntries < 0 || numOfEntries === undefined){
- throw new Meteor.Error("missing-var", "Please specify the amount of entries, ex - 'genData', 5");
- }
- if (campaignId === null || campaignId === undefined){
- throw new Meteor.Error("missing-var", "Please specify the campaign ID");
- }
- var todayDate = new Date();
- var pastDate = new Date();
- pastDate.setDate(todayDate.getDate()-1);
- var id = this.userId;
- var respondent = Respondents.findOne({campaign : campaignId});
- if (respondent === undefined){
- throw new Meteor.Error("bad-id", "campaign ID doesn't exist in respondents");
- }
- for (var i = 0; i < numOfEntries; i++){
- var npsNum = Math.round((Math.random() * 10));
- if (npsNum <= 5){
- npsNum = 9;
- }
- //var newName = String.fromCharCode(Math.random()*26+97);
- var newData = {
- createdAt: pastDate,
- completed: todayDate,
- respondent: respondent,
- campaign: campaignId,
- templatesent: "No Template",
- profilesent: "No Name",
- surveylogo : "any.jpg",
- status: "C",
- responses: {
- firstquestion: npsNum,
- secondquestion: "I love NPS"
- }
- };
- Surveys.insert(newData);
- }
- },
- addRespondentResponseData: function() {
- // you will need to update the Owner to your subscription
- Studies.insert({
- "_id" : "eCn9BSRY7PbQQoqjr",
- "name" : "Test Study For Collection type 2",
- "Owner" : "zWhgtEjAKGo4KHXPJ",
- "description" : "description text",
- "created" : new Date("2017-03-20T15:12:33.972Z"),
- "lastModified" : new Date("2017-04-07T13:50:26.645Z"),
- "options" : {
- "theme" : "default_theme",
- "showQuestionNumbers" : false,
- "backtracking" : false
- },
- "Alerts" : [ ],
- "Exclusions" : {
- "receivedInviteExclusion" : {
- "enabled" : true,
- "values" : {
- "numInvites" : {
- "value" : 1
- },
- "numDays" : {
- "value" : 1
- }
- }
- },
- "noResponseExclusion" : {
- "enabled" : true,
- "values" : {
- "numInvites" : {
- "value" : 0
- }
- }
- }
- },
- "Defaults" : {
- },
- "endPageHtml": "<p>End</p>",
- "closedPageHtml": "<p>End</p>",
- "status": 1,
- "collectionType": 2
- });
- Profiles_Studies.insert({
- "_id": "gBAiphxSbgujJcuPr",
- "study": "eCn9BSRY7PbQQoqjr",
- "name": "Profile Name Here",
- "sendername": "sendernametext",
- "fromfield": "fromfieldtext",
- "signaturehtml": "This is signature text",
- "key1": "key1",
- "key2": "k2",
- "key3": "k3"
- });
- InviteTemplates_Studies.insert({
- "_id": "ERQ52CEQQk7YknkDx",
- "study": "eCn9BSRY7PbQQoqjr",
- "title": "This Is An Email Template",
- "fromdomain": "mails.sibylsurveys.com",
- "subject": "New sub",
- "bodyhtml": "<p>%NPSQUESTION~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 oasdpportunity to do so? <br> %%UNSUB~Click here to unsubscribe.%%FIELD.Email%%FIELD.undefined%</p>"
- });
- // adds data for respondents and responses that are in pairs, calls functions for additional visual randomization
- for (let i = 1; i < 30; i++) {
- Responses_Studies.insert({
- "_id": `responserad${i}`,
- "study": "eCn9BSRY7PbQQoqjr",
- "respondent": `respondentrad${i}`,
- "profile": {
- "email": `any${i}@mailinator.com`,
- "first_name": `${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}`,
- "last_name": "Can"
- },
- "surveySession": randSurveySession(i),
- inviteDates: [
- {
- date: new Date(`4/${i}/2017`),
- profileSent: "gBAiphxSbgujJcuPr",
- inviteSent: "ERQ52CEQQk7YknkDx"
- }
- ],
- "createdAt": new Date(`4/${i}/2017`)
- });
- Respondents_Studies.insert({
- "_id": `respondentrad${i}`,
- "study": "eCn9BSRY7PbQQoqjr",
- "profile": {
- "email": `11${i}@mailinator.com`,
- "first_name": `${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}${String.fromCharCode((Math.random() * 26) + 96)}`,
- "last_name": "Can"
- }
- });
- }
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement