forked from StateVoicesNational/Spoke
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathschema.js
1757 lines (1673 loc) · 52 KB
/
schema.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import GraphQLDate from "graphql-date";
import GraphQLJSON from "graphql-type-json";
import { GraphQLError } from "graphql";
import isUrl from "is-url";
import _ from "lodash";
import { gzip, makeTree, getHighestRole } from "../../lib";
import { capitalizeWord, groupCannedResponses } from "./lib/utils";
import httpRequest from "../lib/http-request";
import ownedPhoneNumber from "./lib/owned-phone-number";
import { getIngestMethod } from "../../extensions/contact-loaders";
import {
Campaign,
CannedResponse,
InteractionStep,
Invite,
Message,
Organization,
Tag,
UserOrganization,
isSqlite,
r,
cacheableData
} from "../models";
import { resolvers as assignmentResolvers } from "./assignment";
import { getCampaigns, resolvers as campaignResolvers } from "./campaign";
import { resolvers as campaignContactResolvers } from "./campaign-contact";
import { resolvers as cannedResponseResolvers } from "./canned-response";
import {
getConversations,
getCampaignIdContactIdsMaps,
reassignConversations,
resolvers as conversationsResolver
} from "./conversations";
import {
accessRequired,
assignmentRequiredOrAdminRole,
authRequired
} from "./errors";
import { resolvers as interactionStepResolvers } from "./interaction-step";
import { resolvers as inviteResolvers } from "./invite";
import { saveNewIncomingMessage } from "../../extensions/service-vendors/message-sending";
import {
processServiceManagers,
serviceManagersHaveImplementation
} from "../../extensions/service-managers";
import { getConfig, getFeatures, getTheme } from "./lib/config";
import { resolvers as messageResolvers } from "./message";
import { resolvers as optOutResolvers } from "./opt-out";
import { resolvers as organizationResolvers } from "./organization";
import { GraphQLPhone } from "./phone";
import { resolvers as questionResolvers } from "./question";
import { resolvers as questionResponseResolvers } from "./question-response";
import { resolvers as tagResolvers } from "./tag";
import { getUsers, resolvers as userResolvers } from "./user";
import { change } from "../local-auth-helpers";
import {
bulkSendMessages,
bulkUpdateScript,
buyPhoneNumbers,
deletePhoneNumbers,
findNewCampaignContact,
getOptOutMessage,
joinOrganization,
editOrganization,
releaseContacts,
sendMessage,
startCampaign,
updateContactTags,
updateContactCustomFields,
updateQuestionResponses,
releaseCampaignNumbers,
clearCachedOrgAndExtensionCaches,
updateFeedback,
updateServiceManager,
updateServiceVendorConfig
} from "./mutations";
import { jobRunner } from "../../extensions/job-runners";
import { Jobs } from "../../workers/job-processes";
import { Tasks } from "../../workers/tasks";
const uuidv4 = require("uuid").v4;
// This function determines whether a field was requested
// in a graphql query. Each graphql resolver receives a fourth parameter,
// which contains information about the current request and the execution
// context. It might be userful to determine this in order to avoid
// retrieving fields through database joins if they were not
// requested, for example.
//
// In the following query, let's say you want to test whether tags was
// included. The path to tags is conversations/conversations/contact/tags,
// because tags is in the contact object which is in the conversations
// object which is in the conversations query.
//
// Therefore, assuming the fourth parameter to your resolver is called
// 'graphqlInfo', the call to this function to determine if tags is in
// that specific position would be:
// isFieldInSelectionSetHierarchy(graphqlInfo, ["conversations", "conversations", "contact", "tags"]);
//
// query Q(
// $organizationId: String!
// $cursor: OffsetLimitCursor!
// $contactsFilter: ContactsFilter
// $campaignsFilter: CampaignsFilter
// $assignmentsFilter: AssignmentsFilter
// $utc: String
// ) {
// conversations(
// cursor: $cursor
// organizationId: $organizationId
// campaignsFilter: $campaignsFilter
// contactsFilter: $contactsFilter
// assignmentsFilter: $assignmentsFilter
// utc: $utc
// ) {
// pageInfo {
// limit
// offset
// total
// }
// conversations {
// texter {
// id
// displayName
// }
// contact {
// id
// assignmentId
// firstName
// lastName
// cell
// messageStatus
// messages {
// id
// text
// isFromContact
// }
// tags {
// id
// }
// optOut {
// id
// }
// }
// campaign {
// id
// title
// }
// }
// }
// }
const isFieldInSelectionSetHierarchy = (graphqlInfo, fieldPath) => {
const findField = (selectionSet, fieldName) => {
if (!selectionSet.selections) {
return undefined;
}
return selectionSet.selections.find(
ss =>
ss.kind === "Field" &&
ss.name.kind === "Name" &&
ss.name.value === fieldName
);
};
let currentLevel = graphqlInfo.operation;
return fieldPath.every(field => {
currentLevel = findField(currentLevel.selectionSet, field);
return !!currentLevel;
});
};
async function editCampaign(id, campaign, loaders, user, origCampaignRecord) {
const {
title,
description,
dueBy,
useDynamicAssignment,
batchSize,
batchPolicies,
responseWindow,
logoImageUrl,
introHtml,
primaryColor,
useOwnMessagingService,
messageserviceSid,
overrideOrganizationTextingHours,
textingHoursEnforced,
textingHoursStart,
textingHoursEnd,
timezone,
serviceManagers,
useDynamicReplies,
replyBatchSize
} = campaign;
// some changes require ADMIN and we recheck below
const organizationId =
campaign.organizationId || origCampaignRecord.organization_id;
await accessRequired(
user,
organizationId.toString(),
"SUPERVOLUNTEER",
/* superadmin*/ true
);
const organization = await loaders.organization.load(organizationId);
const campaignUpdates = {
title,
description,
due_by: dueBy,
use_dynamic_assignment: useDynamicAssignment,
logo_image_url: logoImageUrl,
primary_color: primaryColor,
intro_html: introHtml,
override_organization_texting_hours: overrideOrganizationTextingHours,
texting_hours_enforced: textingHoursEnforced,
texting_hours_start: textingHoursStart,
texting_hours_end: textingHoursEnd,
use_own_messaging_service: useOwnMessagingService,
messageservice_sid: messageserviceSid,
batch_size: batchSize,
response_window: responseWindow,
timezone
};
Object.keys(campaignUpdates).forEach(key => {
if (typeof campaignUpdates[key] === "undefined") {
delete campaignUpdates[key];
}
});
if (
user.is_superadmin &&
campaignUpdates.description &&
/org=\d+/.test(campaignUpdates.description)
) {
// hacky org change
campaignUpdates.organization_id = campaignUpdates.description.match(
/org=(\d+)/
)[1];
}
if (campaignUpdates.logo_image_url && !isUrl(logoImageUrl)) {
campaignUpdates.logo_image_url = "";
}
if (origCampaignRecord && !origCampaignRecord.join_token) {
campaignUpdates.join_token = uuidv4();
}
const features = getFeatures(origCampaignRecord);
if (campaign.texterUIConfig && campaign.texterUIConfig.options) {
Object.assign(features, {
TEXTER_UI_SETTINGS: campaign.texterUIConfig.options
});
campaignUpdates.features = JSON.stringify(features);
}
if (batchPolicies) {
Object.assign(features, {
DYNAMICASSIGNMENT_BATCHES: batchPolicies.join(",")
});
campaignUpdates.features = JSON.stringify(features);
}
if (useDynamicReplies) {
Object.assign(features, {
"USE_DYNAMIC_REPLIES": true,
"REPLY_BATCH_SIZE": replyBatchSize
})
} else {
Object.assign(features, {
"USE_DYNAMIC_REPLIES": false
})
}
campaignUpdates.features = JSON.stringify(features);
let changed = Boolean(Object.keys(campaignUpdates).length);
if (changed) {
await r
.knex("campaign")
.where("id", id)
.update(campaignUpdates);
}
if (campaign.ingestMethod && campaign.contactData) {
await accessRequired(user, organizationId, "ADMIN", /* superadmin*/ true);
changed = true;
const ingestMethod = await getIngestMethod(
campaign.ingestMethod,
organization,
user
);
if (ingestMethod) {
await jobRunner.dispatchJob({
queue_name: `${id}:edit_campaign`,
job_type: `ingest.${campaign.ingestMethod}`,
locks_queue: true,
campaign_id: id,
payload: campaign.contactData
});
await r
.knex("campaign_admin")
.where("campaign_id", id)
.update({
contacts_count: null,
ingest_method: campaign.ingestMethod,
ingest_success: null
});
} else {
console.error("ingestMethod unavailable", campaign.ingestMethod);
}
}
if (campaign.hasOwnProperty("texters")) {
changed = true;
await jobRunner.dispatchJob({
queue_name: `${id}:edit_campaign`,
locks_queue: true,
job_type: Jobs.ASSIGN_TEXTERS,
campaign_id: id,
payload: JSON.stringify({
id,
texters: campaign.texters
})
});
}
if (campaign.hasOwnProperty("interactionSteps")) {
changed = true;
await accessRequired(
user,
organizationId,
"SUPERVOLUNTEER",
/* superadmin*/ true
);
await updateInteractionSteps(
id,
[campaign.interactionSteps],
origCampaignRecord
);
await cacheableData.campaign.clear(id);
}
if (campaign.hasOwnProperty("cannedResponses")) {
changed = true;
const cannedResponses = campaign.cannedResponses;
const convertedResponses = [];
for (let index = 0; index < cannedResponses.length; index++) {
const response = cannedResponses[index];
convertedResponses.push({
campaign_id: id,
id: undefined,
title: response.title,
text: response.text,
tagIds: response.tagIds,
answer_actions: response.answerActions,
answer_actions_data: response.answerActionsData
});
}
// delete canned response / tag relations from tag_canned_response
await r.knex.transaction(async trx => {
await trx("tag_canned_response")
.whereIn(
"canned_response_id",
r
.knex("canned_response")
.select("id")
.where({ campaign_id: id })
)
.delete();
// delete canned responses
await trx("canned_response")
.where({ campaign_id: id })
.delete();
// save new canned responses and add their ids with related tag ids to tag_canned_response
const saveCannedResponse = async cannedResponse => {
const [res] = await trx("canned_response").insert(cannedResponse, [
"id"
]);
return res.id;
};
const tagCannedResponses = _.flatten(
await Promise.all(
convertedResponses.map(async response => {
const { tagIds, ...filteredResponse } = response;
const responseId = await saveCannedResponse(filteredResponse);
return (tagIds || []).map(t => ({
tag_id: t,
canned_response_id: responseId
}));
})
)
);
if (tagCannedResponses.length) {
await trx("tag_canned_response").insert(tagCannedResponses);
}
});
await cacheableData.cannedResponse.clearQuery({
userId: "",
campaignId: id
});
}
const campaignRefreshed = await cacheableData.campaign.load(id, {
forceLoad: changed
});
// hacky easter egg to force reload campaign contacts
if (r.redis && campaignUpdates.description?.endsWith("..")) {
// some asynchronous cache-priming
console.log(
"force-loading loadCampaignCache",
campaignRefreshed,
organization
);
await jobRunner.dispatchTask(Tasks.CAMPAIGN_START_CACHE, {
campaign: campaignRefreshed,
organization
});
}
const toReturn = await Campaign.get(id.toString());
toReturn.id = toReturn.id.toString();
toReturn.organization_id = toReturn.organization_id.toString();
return toReturn;
}
async function updateInteractionSteps(
campaignId,
interactionSteps,
origCampaignRecord,
idMap = {}
) {
// Allows cascade delete for SQLite
if (isSqlite) {
await r.knex.raw("PRAGMA foreign_keys = ON");
}
for (let i = 0; i < interactionSteps.length; i++) {
const is = interactionSteps[i];
// map the interaction step ids for new ones
if (idMap[is.parentInteractionId]) {
is.parentInteractionId = idMap[is.parentInteractionId];
}
if (typeof is.id === "undefined") continue;
if (is.id.indexOf("new") !== -1) {
const newIstep = await InteractionStep.save({
parent_interaction_id: is.parentInteractionId || null,
question: is.questionText,
script: is.script,
answer_option: is.answerOption,
answer_actions: is.answerActions,
answer_actions_data: is.answerActionsData,
campaign_id: campaignId,
is_deleted: false
});
idMap[is.id] = newIstep.id;
} else {
if (
origCampaignRecord &&
!origCampaignRecord.is_started &&
is.isDeleted
) {
await r
.knex("interaction_step")
.where({ id: is.id })
.delete();
} else {
await r
.knex("interaction_step")
.where({ id: is.id })
.update({
question: is.questionText,
script: is.script,
answer_option: is.answerOption,
answer_actions: is.answerActions,
answer_actions_data: is.answerActionsData,
is_deleted: is.isDeleted
});
}
}
if (Array.isArray(is.interactionSteps) && is.interactionSteps.length) {
await updateInteractionSteps(
campaignId,
is.interactionSteps,
origCampaignRecord,
idMap
);
}
}
}
const rootMutations = {
RootMutation: {
bulkSendMessages,
bulkUpdateScript,
buyPhoneNumbers,
deletePhoneNumbers,
editOrganization,
findNewCampaignContact,
joinOrganization,
releaseContacts,
sendMessage,
startCampaign,
releaseCampaignNumbers,
clearCachedOrgAndExtensionCaches,
updateServiceManager,
updateServiceVendorConfig,
userAgreeTerms: async (_, { userId }, { user }) => {
// We ignore userId: you can only agree to terms for yourself
await r
.knex("user")
.where("id", user.id)
.update({
terms: true
});
await cacheableData.user.clearUser(user.id, user.auth0_id);
return {
...user,
terms: true
};
},
updateFeedback,
sendReply: async (_, { id, message }, { user, loaders }) => {
const contact = await cacheableData.campaignContact.load(id);
const campaign = await loaders.campaign.load(contact.campaign_id);
await accessRequired(user, campaign.organization_id, "ADMIN");
const [lastMessage] = await r
.knex("message")
.where("campaign_contact_id", id)
.limit(1);
if (!lastMessage) {
const errorStatusAndMessage = {
status: 400,
message:
"Cannot fake a reply to a contact that has no existing thread yet"
};
throw new GraphQLError(errorStatusAndMessage);
}
const userNumber = lastMessage.user_number;
const contactNumber = contact.cell;
const mockId = `mocked_${Math.random()
.toString(36)
.replace(/[^a-zA-Z1-9]+/g, "")}`;
await saveNewIncomingMessage(
new Message({
contact_number: contactNumber,
user_number: userNumber,
is_from_contact: true,
text: message,
error_code: null,
service_id: mockId,
campaign_contact_id: contact.id,
messageservice_sid: lastMessage.messageservice_sid,
service: lastMessage.service,
send_status: "DELIVERED"
}),
contact
);
return await cacheableData.campaignContact.load(id);
},
exportCampaign: async (_, { id }, { user, loaders }) => {
const campaign = await loaders.campaign.load(id);
const organizationId = campaign.organization_id;
await accessRequired(user, organizationId, "ADMIN");
return await jobRunner.dispatchJob({
queue_name: `${id}:export`,
job_type: Jobs.EXPORT,
locks_queue: false,
campaign_id: id,
payload: JSON.stringify({
id,
requester: user.id
})
});
},
editOrganizationRoles: async (
_,
{ userId, organizationId, roles },
{ user }
) => {
const currentRoles = (
await r
.knex("user_organization")
.where({
organization_id: organizationId,
user_id: userId
})
.select("role")
).map(res => res.role);
const oldRoleIsOwner = currentRoles.indexOf("OWNER") !== -1;
const newRoleIsOwner = roles.indexOf("OWNER") !== -1;
const roleRequired = oldRoleIsOwner || newRoleIsOwner ? "OWNER" : "ADMIN";
let newOrgRoles = [];
await accessRequired(user, organizationId, roleRequired);
// Roles is sent as an array for historical purposes
// but roles are hierarchical, so we only want one user_organization
// record. For legacy compatibility we still need to delete all recs for that user_id.
await r
.knex("user_organization")
.where({ organization_id: organizationId, user_id: userId })
.delete();
if (roles.length) {
const newRole = getHighestRole(roles);
await r.knex("user_organization").insert({
organization_id: organizationId,
user_id: userId,
role: newRole
});
}
await cacheableData.user.clearUser(userId);
return { id: userId };
},
editUser: async (_, { organizationId, userId, userData }, { user }) => {
if (user.id !== userId) {
// User can edit themselves
await accessRequired(user, organizationId, "ADMIN", true);
}
const userRes = await r
.knex("user")
.join("user_organization", "user.id", "user_organization.user_id")
.where({
"user_organization.organization_id": organizationId,
"user.id": userId
})
.limit(1);
if (!userRes || !userRes.length) {
return null;
} else {
const member = userRes[0];
if (userData) {
const newUserData = {
first_name: capitalizeWord(userData.firstName).trim(),
last_name: capitalizeWord(userData.lastName).trim(),
alias: userData.alias
? capitalizeWord(userData.alias).trim()
: null,
email: userData.email,
cell: userData.cell
};
if (member.extra || userData.extra) {
newUserData.extra = {
...member.extra,
...JSON.parse(userData.extra || "{}")
};
}
const userRes = await r
.knex("user")
.where("id", userId)
.update(newUserData);
await cacheableData.user.clearUser(member.user_id, member.auth0_id);
userData = {
id: userId,
...newUserData
};
} else {
userData = member;
}
return userData;
}
},
resetUserPassword: async (
_,
{ organizationId, userId },
{ user, loaders }
) => {
if (user.id === userId) {
throw new Error("You can't reset your own password.");
}
// might need to impliment user password change available elsewhere.
await accessRequired(user, organizationId, "ADMIN", true);
const organization = await loaders.organization.load(organizationId);
const passportStrategy =
getConfig("PASSPORT_STRATEGY", organization) || "auth0";
if (passportStrategy === "auth0") {
const { email } = await r
.knex("user")
.select("email")
.where({
"user.id": userId
})
.first();
const auth0Domain = getConfig("AUTH0_DOMAIN", organization);
const auth0ClientID = getConfig("AUTH0_CLIENT_ID", organization);
const url = `https://${auth0Domain}/dbconnections/change_password`;
const body = JSON.stringify({
client_id: auth0ClientID,
email,
connection: "Username-Password-Authentication"
});
try {
let res = await httpRequest(url, {
method: "POST",
retries: 2,
timeout: 5000,
headers: { "Content-Type": "application/json" },
body,
validStatuses: [200],
compress: false
});
res = await res.text();
console.log(res, email);
return res;
} catch (err) {
//handles error and sends it to the client
throw new Error(err);
}
} else {
// Add date at the end in case user record is modified after password is reset
const passwordResetHash = uuidv4();
const auth0_id = `reset|${passwordResetHash}|${Date.now()}`;
const userRes = await r
.knex("user")
.where("id", userId)
.update({
auth0_id
});
return passwordResetHash;
}
},
changeUserPassword: async (_, { userId, formData }, { user }) => {
if (user.id !== userId) {
throw new Error("You can only change your own password.");
}
const { password, newPassword, passwordConfirm } = formData;
const updatedUser = await change({
user,
password,
newPassword,
passwordConfirm
});
return updatedUser;
},
updateTextingHours: async (
_,
{ organizationId, textingHoursStart, textingHoursEnd },
{ user }
) => {
await accessRequired(user, organizationId, "OWNER");
await Organization.get(organizationId).update({
texting_hours_start: textingHoursStart,
texting_hours_end: textingHoursEnd
});
await cacheableData.organization.clear(organizationId);
return await cacheableData.organization.load(organizationId);
},
updateTextingHoursEnforcement: async (
_,
{ organizationId, textingHoursEnforced },
{ user }
) => {
await accessRequired(user, organizationId, "SUPERVOLUNTEER");
await Organization.get(organizationId).update({
texting_hours_enforced: textingHoursEnforced
});
await cacheableData.organization.clear(organizationId);
return await cacheableData.organization.load(organizationId);
},
getOptOutMessage,
updateOptOutMessage: async (
_,
{ organizationId, optOutMessage },
{ user }
) => {
await accessRequired(user, organizationId, "OWNER");
const organization = await Organization.get(organizationId);
const featuresJSON = getFeatures(organization);
featuresJSON.opt_out_message = optOutMessage;
organization.features = JSON.stringify(featuresJSON);
await organization.save();
await cacheableData.organization.clear(organizationId);
return await Organization.get(organizationId);
},
updateTheme: async (
_,
{ organizationId, primary, secondary, info, success, warning, error },
{ user }
) => {
await accessRequired(user, organizationId, "OWNER");
const organization = await Organization.get(organizationId);
const featuresJSON = getFeatures(organization);
featuresJSON.theme = {
palette: {
primary: { main: primary },
secondary: { main: secondary },
info: { main: info },
success: { main: success },
warning: { main: warning },
error: { main: error }
}
};
organization.features = JSON.stringify(featuresJSON);
await organization.save();
await cacheableData.organization.clear(organizationId);
return await Organization.get(organizationId);
},
createInvite: async (_, { invite }, { user }) => {
if (
(user && user.is_superadmin) ||
!getConfig("SUPPRESS_SELF_INVITE", null, { truthy: true })
) {
const inviteInstance = new Invite({
is_valid: invite.is_valid,
hash: uuidv4()
});
const newInvite = await inviteInstance.save();
return newInvite;
}
},
createCampaign: async (_, { campaign }, { user, loaders }) => {
await accessRequired(
user,
campaign.organizationId,
"ADMIN",
/* allowSuperadmin=*/ true
);
const organization = await loaders.organization.load(
campaign.organizationId
);
const campaignInstance = new Campaign({
organization_id: campaign.organizationId,
creator_id: user.id,
title: campaign.title,
description: campaign.description,
due_by: campaign.dueBy,
is_started: false,
is_archived: false,
join_token: uuidv4(),
batch_size: Number(getConfig("DEFAULT_BATCHSIZE", organization) || 300),
response_window: getConfig("DEFAULT_RESPONSEWINDOW", organization, {
default: 48
}),
use_own_messaging_service: false,
timezone: getConfig("DST_REFERENCE_TIMEZONE", organization)
});
const newCampaign = await campaignInstance.save();
await r.knex("campaign_admin").insert({
campaign_id: newCampaign.id
});
return editCampaign(newCampaign.id, campaign, loaders, user);
},
copyCampaign: async (_, { id }, { user }) => {
const campaign = await cacheableData.campaign.load(id);
await accessRequired(user, campaign.organization_id, "ADMIN");
const organization = await cacheableData.organization.load(
campaign.organization_id
);
const campaignInstance = new Campaign({
organization_id: campaign.organization_id,
creator_id: user.id,
title: "COPY - " + campaign.title.replace(/\s*template\W*/i, ""),
description: campaign.description,
due_by: campaign.due_by,
features: campaign.features,
intro_html: campaign.intro_html,
primary_color: campaign.primary_color,
logo_image_url: campaign.logo_image_url,
override_organization_texting_hours:
campaign.override_organization_texting_hours,
texting_hours_enforced: campaign.texting_hours_enforced,
texting_hours_start: campaign.texting_hours_start,
texting_hours_end: campaign.texting_hours_end,
timezone: campaign.timezone,
use_dynamic_assignment: campaign.use_dynamic_assignment,
batch_size:
campaign.batch_size ||
Number(getConfig("DEFAULT_BATCHSIZE", organization) || 300),
response_window:
campaign.response_window ||
Number(getConfig("DEFAULT_RESPONSEWINDOW", organization) || 48),
is_started: false,
is_archived: false,
join_token: uuidv4()
});
const newCampaign = await campaignInstance.save();
await r.knex("campaign_admin").insert({
campaign_id: newCampaign.id
});
const newCampaignId = newCampaign.id;
const oldCampaignId = campaign.id;
let interactions = await r
.knex("interaction_step")
.where({ campaign_id: oldCampaignId, is_deleted: false })
.orderBy("id"); // Ensure that the copy is deterministic.
const interactionsArr = [];
interactions.forEach((interaction, index) => {
if (interaction.parent_interaction_id) {
let is = {
id: "new" + interaction.id,
questionText: interaction.question,
script: interaction.script,
answerOption: interaction.answer_option,
answerActions: interaction.answer_actions,
answerActionsData: interaction.answer_actions_data,
isDeleted: interaction.is_deleted,
campaign_id: newCampaignId,
parentInteractionId: "new" + interaction.parent_interaction_id
};
interactionsArr.push(is);
} else if (!interaction.parent_interaction_id) {
let is = {
id: "new" + interaction.id,
questionText: interaction.question,
script: interaction.script,
answerOption: interaction.answer_option,
answerActions: interaction.answer_actions,
answerActionsData: interaction.answer_actions_data,
isDeleted: interaction.is_deleted,
campaign_id: newCampaignId,
parentInteractionId: interaction.parent_interaction_id
};
interactionsArr.push(is);
}
});
await updateInteractionSteps(
newCampaignId,
[makeTree(interactionsArr, (id = null))],
campaign,
{}
);
const originalCannedResponses = await r
.knex("canned_response")
.leftJoin(
"tag_canned_response",
"canned_response.id",
"tag_canned_response.canned_response_id"
)
.where({ campaign_id: oldCampaignId })
.select("canned_response.*", "tag_canned_response.tag_id");
const groupedCannedResponses = groupCannedResponses(
originalCannedResponses
);
const tagCannedResponses = [];
const copiedCannedResponsePromises = groupedCannedResponses.map(
response => {
return r
.knex("canned_response")
.insert(
{
campaign_id: newCampaignId,
title: response.title,
text: response.text,
answer_actions: response.answer_actions,
answer_actions_data: response.answer_actions_data
},
["id"]
)
.then(res => {
response.tagIds.forEach(t => {
tagCannedResponses.push({
canned_response_id: res[0].id,
tag_id: t
});
});
});
}
);
await Promise.all(copiedCannedResponsePromises);
if (tagCannedResponses.length) {
await r.knex("tag_canned_response").insert(tagCannedResponses);
}
return newCampaign;
},
unarchiveCampaign: async (_, { id }, { user }) => {
const campaign = await cacheableData.campaign.load(id);