blob: e534ef9adc944327087f70f50a396cdef25c8f2d [file] [log] [blame]
Adrià Vilanova Martínez54964a52022-10-26 23:53:29 +02001import {CCApi} from '../../../../common/api.js';
2import {getAuthUser} from '../../../../common/communityConsoleUtils.js';
3
4const kPiiScanType_ScanNone = 0;
5const kType_Reply = 1;
6const kType_RecommendedAnswer = 3;
7const kPostMethodCommunityConsole = 4;
8
Adrià Vilanova Martínez41493f22022-11-06 22:38:21 +01009const kVariablesRegex = /\$([A-Za-z_]+)/g;
10
Adrià Vilanova Martínez54964a52022-10-26 23:53:29 +020011export default class CRRunner {
12 constructor() {
13 this._CRs = [];
14 this._haveCRsBeenLoaded = false;
15 }
16
17 loadCRs() {
18 return CCApi(
19 'ListCannedResponses', {}, /* authenticated = */ true,
20 getAuthUser())
21 .then(res => {
22 this._CRs = res?.[1] ?? [];
23 this._haveCRsBeenLoaded = true;
24 });
25 }
26
27 _getCRPayload(id) {
28 let maybeLoadCRsPromise;
29 if (!this._haveCRsBeenLoaded)
30 maybeLoadCRsPromise = this.loadCRs();
31 else
32 maybeLoadCRsPromise = Promise.resolve();
33
34 return maybeLoadCRsPromise.then(() => {
35 let cr = this._CRs.find(cr => cr?.[1]?.[1] == id);
36 if (!cr) throw new Error(`Couldn't find CR with id ${id}.`);
37 return cr?.[3];
38 });
39 }
40
Adrià Vilanova Martínez41493f22022-11-06 22:38:21 +010041 _templateSubstitute(payload, thread) {
42 if (!payload.match(kVariablesRegex)) return Promise.resolve(payload);
43
44 return thread.loadThreadDetails().then(() => {
45 return payload.replaceAll(kVariablesRegex, (_, p1) => {
46 return thread?.[p1] ?? '';
47 });
48 });
49 }
50
Adrià Vilanova Martínez54964a52022-10-26 23:53:29 +020051 execute(action, thread) {
52 let crId = action?.getCannedResponseId?.();
53 if (!crId)
54 return Promise.reject(
55 new Error('The action doesn\'t contain a valid CR id.'));
56
Adrià Vilanova Martínez41493f22022-11-06 22:38:21 +010057 return this._getCRPayload(crId)
58 .then(payload => this._templateSubstitute(payload, thread))
59 .then(payload => {
60 let subscribe = action?.getSubscribe?.() ?? false;
61 let markAsAnswer = action?.getMarkAsAnswer?.() ?? false;
62 return CCApi(
63 'CreateMessage', {
64 1: thread.forumId,
65 2: thread.threadId,
66 // message
67 3: {
68 4: payload,
69 6: {
70 1: markAsAnswer ? kType_RecommendedAnswer : kType_Reply,
71 },
72 11: kPostMethodCommunityConsole,
73 },
74 4: subscribe,
75 6: kPiiScanType_ScanNone,
Adrià Vilanova Martínez54964a52022-10-26 23:53:29 +020076 },
Adrià Vilanova Martínez41493f22022-11-06 22:38:21 +010077 /* authenticated = */ true, getAuthUser());
78 });
Adrià Vilanova Martínez54964a52022-10-26 23:53:29 +020079 }
80}