domma-cms 1.27.3 → 1.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/CLAUDE.md +2 -2
- package/admin/js/app.js +4 -4
- package/admin/js/lib/chats-arrange.js +2 -0
- package/admin/js/lib/launchers-arrange.js +2 -0
- package/admin/js/lib/menu-item-help.js +1 -1
- package/admin/js/lib/page-image-hosts.js +2 -2
- package/admin/js/lib/shortcode-form.js +6 -6
- package/admin/js/lib/shortcode-registry.js +1 -1
- package/admin/js/templates/chat-knowledge.html +96 -0
- package/admin/js/templates/chats.html +146 -0
- package/admin/js/templates/docs/usage-chat.html +96 -0
- package/admin/js/templates/docs/usage-launchers.html +83 -0
- package/admin/js/templates/docs/usage-media.html +14 -0
- package/admin/js/templates/docs/usage-navigation.html +3 -0
- package/admin/js/templates/docs/usage-shortcodes.html +8 -0
- package/admin/js/templates/documentation.html +8 -0
- package/admin/js/templates/launchers.html +105 -0
- package/admin/js/views/chat-knowledge.js +60 -0
- package/admin/js/views/chats.js +53 -0
- package/admin/js/views/doc-pages.js +1 -1
- package/admin/js/views/index.js +1 -1
- package/admin/js/views/launchers.js +230 -0
- package/admin/js/views/menu-editor.js +22 -22
- package/admin/js/views/page-editor.js +10 -10
- package/docs/DommaFeatures.md +30 -0
- package/docs/markdown-shortcodes.md +69 -16
- package/package.json +1 -1
- package/public/css/image-zoom.css +1 -0
- package/public/css/launcher-chat.css +1 -0
- package/public/css/launchers.css +1 -0
- package/public/css/site.css +1 -1
- package/public/js/image-zoom.mjs +30 -0
- package/public/js/launcher-chat.mjs +47 -0
- package/public/js/launcher-settings.mjs +2 -0
- package/public/js/launchers.mjs +12 -0
- package/public/js/motion-control.mjs +1 -1
- package/public/js/site.js +1 -1
- package/server/routes/api/chat.js +203 -0
- package/server/routes/api/chats.js +235 -0
- package/server/routes/api/launchers.js +50 -0
- package/server/routes/launcher-public.js +96 -0
- package/server/server.js +33 -0
- package/server/services/adapterRegistry.js +4 -4
- package/server/services/adapters/FileAdapter.js +18 -0
- package/server/services/adapters/MongoAdapter.js +14 -0
- package/server/services/chat/conversation.js +458 -0
- package/server/services/chat/launcher-bridge.js +73 -0
- package/server/services/chat/matcher.js +324 -0
- package/server/services/chat/settings.js +118 -0
- package/server/services/chat/store.js +532 -0
- package/server/services/collectionAccess.js +16 -0
- package/server/services/docs.js +2 -0
- package/server/services/launchers.js +172 -0
- package/server/services/markdown.js +175 -4
- package/server/services/number-fields-migration.js +4 -0
- package/server/services/permissionRegistry.js +12 -0
- package/server/services/presetCollections.js +75 -2
- package/server/services/renderer.js +86 -18
- package/server/services/roles.js +1 -1
- package/server/services/tools.js +1 -0
- package/server/templates/page.html +4 -2
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a chat goes - the rules between the visitor, the bot and the staff.
|
|
3
|
+
*
|
|
4
|
+
* A chat's `status`:
|
|
5
|
+
* bot the bot is answering (every chat starts here)
|
|
6
|
+
* waiting the visitor asked for a person and someone is available; it waits
|
|
7
|
+
* for the first staff reply (the sidebar badge counts it)
|
|
8
|
+
* open a member of staff has replied; the bot stays quiet from now on
|
|
9
|
+
* message nobody was available, so the visitor left their name and email
|
|
10
|
+
* for the team to get back to them (counted until someone deals with it)
|
|
11
|
+
* closed ended by the visitor, the staff or the daily tidy-up
|
|
12
|
+
*
|
|
13
|
+
* The bot answers from the Knowledge (matcher.js): a confident match gets the
|
|
14
|
+
* answer, near misses get "Did you mean ...?" choices, nothing close is logged
|
|
15
|
+
* as unanswered and the visitor is offered a person. "Talk to a person" (said
|
|
16
|
+
* or tapped) hands over: to the available staff, or - when nobody is - to the
|
|
17
|
+
* name-and-email form, as the launcher's `askDetails` says.
|
|
18
|
+
*
|
|
19
|
+
* Every change to a chat runs inside store.withChat, one at a time.
|
|
20
|
+
*
|
|
21
|
+
* @module services/chat/conversation
|
|
22
|
+
*/
|
|
23
|
+
import {match} from './matcher.js';
|
|
24
|
+
import {notify, registerNotificationSource, resolveNotification} from '../notify.js';
|
|
25
|
+
import {
|
|
26
|
+
addMessage, cleanText, countHit, forgetSession, getSession, knowledgeIndex, listSessions, logUnanswered, messagesAfter,
|
|
27
|
+
patchSession, removeSession, removeSessionsAndOrphans, renderAnswer, staffAvailable, withChat
|
|
28
|
+
} from './store.js';
|
|
29
|
+
import {readChatSettings, staffDisplayName} from './settings.js';
|
|
30
|
+
|
|
31
|
+
export const SOURCE = 'core:chat';
|
|
32
|
+
const int = (v) => (Number.isFinite(Number(v)) ? Math.trunc(Number(v)) : 0);
|
|
33
|
+
const ACTIVE = ['waiting', 'open', 'message'];
|
|
34
|
+
|
|
35
|
+
export const SAY = Object.freeze({
|
|
36
|
+
greeting: 'Hello! What would you like to know?',
|
|
37
|
+
thanks: 'You are welcome. Is there anything else?',
|
|
38
|
+
suggest: 'I am not sure I understood. Did you mean one of these?',
|
|
39
|
+
noneStaff: 'Sorry, I do not know the answer to that yet. Try asking another way, or ask to talk to a person.',
|
|
40
|
+
noneAlone: 'Sorry, I do not know the answer to that yet. Try asking another way.',
|
|
41
|
+
offerPerson: 'Shall I find a person for you? Tap "Talk to a person".',
|
|
42
|
+
connecting: 'Finding someone for you - they will reply here. You can keep typing in the meantime.',
|
|
43
|
+
detailsFirst: 'Before I put you through, please leave your name and email so we can reach you if we get cut off.',
|
|
44
|
+
nobodyDetails: 'Nobody is free to chat just now. Leave your name and email and we will get back to you.',
|
|
45
|
+
nobodyHaveDetails: 'Nobody is free to chat just now. We will get back to you at the email you left.',
|
|
46
|
+
nobodyLater: 'Nobody is free to chat just now. Please try again later.',
|
|
47
|
+
noStaffDetails: 'There is no one to chat with here, but leave your name and email and we will get back to you.',
|
|
48
|
+
noStaff: 'There is no one to chat with here, sorry.',
|
|
49
|
+
already: 'You are already in the queue for a person - they will reply here.',
|
|
50
|
+
ended: 'This chat has ended.',
|
|
51
|
+
endedByVisitor: 'You ended the chat.',
|
|
52
|
+
full: 'This chat is full. Start a new one to carry on.'
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
/** Register the notification source (server.js, at start-up). */
|
|
56
|
+
export function registerChatSource() {
|
|
57
|
+
registerNotificationSource({
|
|
58
|
+
id: SOURCE, owner: 'core', label: 'Visitor chat',
|
|
59
|
+
description: 'A visitor asked to talk to a person, or left a message for the team because nobody was available.',
|
|
60
|
+
severity: 'info', audience: 'admins'
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const noticeKey = (id) => `chat:${id}`;
|
|
65
|
+
|
|
66
|
+
function raise(session, kind) {
|
|
67
|
+
const d = session.data;
|
|
68
|
+
const who = d.visitorName || 'A visitor';
|
|
69
|
+
const about = d.summary ? `\n\nFirst question: "${d.summary}"` : '';
|
|
70
|
+
const where = d.page ? `\nPage: ${d.page}` : '';
|
|
71
|
+
const notice = kind === 'message'
|
|
72
|
+
? {severity: 'info', title: `${who} left a message in chat`, body: `Nobody was available, so they left their details${d.visitorEmail ? ` (${d.visitorEmail})` : ''}.${about}${where}`}
|
|
73
|
+
: {severity: 'warning', title: `${who} wants to talk to a person`, body: `They are waiting in chat now.${about}${where}`};
|
|
74
|
+
return notify({...notice, source: SOURCE, dedupeKey: noticeKey(session.id), link: '#/launchers/chats'}).catch(() => null);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const settle = (id) => resolveNotification(noticeKey(id), SOURCE).catch(() => 0);
|
|
78
|
+
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
// What visitors and staff see
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* One message as the visitor's browser gets it: no internal ids. Suggestions
|
|
85
|
+
* are offered by their place in the list (`i`), not by Knowledge id.
|
|
86
|
+
*
|
|
87
|
+
* @param {object} m - a chat-messages entry
|
|
88
|
+
* @param {{botName: string}} chat
|
|
89
|
+
* @param {Map<string, object>} [knowledge] - id -> Knowledge, for an answer's links
|
|
90
|
+
*/
|
|
91
|
+
export function publicMessage(m, chat, knowledge = new Map()) {
|
|
92
|
+
const d = m.data || {};
|
|
93
|
+
const out = {n: int(d.n), from: d.from, at: m.meta?.createdAt || null};
|
|
94
|
+
if (d.from === 'bot' && d.answerId) {
|
|
95
|
+
// The entry is the answer; the stored text is a short snapshot, used if the entry has gone.
|
|
96
|
+
out.html = renderAnswer(knowledge.get(d.answerId)?.answer ?? d.text);
|
|
97
|
+
const links = knowledge.get(d.answerId)?.links;
|
|
98
|
+
if (links?.length) out.links = links;
|
|
99
|
+
} else {
|
|
100
|
+
out.text = String(d.text || '');
|
|
101
|
+
}
|
|
102
|
+
if (d.from === 'bot') out.name = chat.botName;
|
|
103
|
+
if (d.from === 'staff') out.name = d.staffName || 'The team';
|
|
104
|
+
if (d.from === 'bot' && Array.isArray(d.suggestions) && d.suggestions.length) {
|
|
105
|
+
out.suggestions = d.suggestions.map((s, i) => ({label: String(s?.label || ''), i}));
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A chat's state as the visitor's browser gets it. */
|
|
111
|
+
export function publicState(session, chat) {
|
|
112
|
+
const d = session.data;
|
|
113
|
+
return {
|
|
114
|
+
status: d.status,
|
|
115
|
+
askDetails: d.askDetails === true || d.askDetails === 'true',
|
|
116
|
+
detailsGiven: Boolean(d.visitorEmail),
|
|
117
|
+
staff: chat.staff,
|
|
118
|
+
staffOnline: chat.staff && staffAvailable().length > 0,
|
|
119
|
+
last: int(d.count)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** One chat in the staff inbox. */
|
|
124
|
+
export function staffSummary(entry, at = Date.now()) {
|
|
125
|
+
const d = entry.data || {};
|
|
126
|
+
const waitingSince = d.waitingSince || null;
|
|
127
|
+
return {
|
|
128
|
+
id: entry.id, status: d.status, name: d.visitorName || '', email: d.visitorEmail || '', page: d.page || '',
|
|
129
|
+
summary: d.summary || '', count: int(d.count), unread: int(d.unread), assignedName: d.assignedName || '',
|
|
130
|
+
lastAt: d.lastAt || entry.meta?.updatedAt || null, startedAt: entry.meta?.createdAt || null,
|
|
131
|
+
waitingSince, waitingMs: waitingSince ? Math.max(0, at - Date.parse(waitingSince)) : 0,
|
|
132
|
+
launcherId: d.launcherId || ''
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** One message in the staff thread: everything, including which entry answered. */
|
|
137
|
+
export function staffMessage(m, knowledge = new Map()) {
|
|
138
|
+
const d = m.data || {};
|
|
139
|
+
return {
|
|
140
|
+
n: int(d.n), from: d.from, text: String(d.text || ''), at: m.meta?.createdAt || null,
|
|
141
|
+
name: d.staffName || '', answer: d.answerId ? (knowledge.get(d.answerId)?.question || '(an entry since removed)') : '',
|
|
142
|
+
suggestions: Array.isArray(d.suggestions) ? d.suggestions.map(s => String(s?.label || '')) : []
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Whether a chat needs staff now - the badge's rule: waiting for a person, a
|
|
148
|
+
* message left for the team, or an open chat with something unread.
|
|
149
|
+
*/
|
|
150
|
+
export function needsStaff(data) {
|
|
151
|
+
if (!data) return false;
|
|
152
|
+
if (data.status === 'waiting' || data.status === 'message') return true;
|
|
153
|
+
return data.status === 'open' && int(data.unread) > 0;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------------------------------------------------------------------------
|
|
157
|
+
// The bot
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
/** The bot's reply to a visitor's words, written to the chat. Inside withChat. */
|
|
161
|
+
async function botReply(id, text, chat, settings) {
|
|
162
|
+
const {index, byId} = await knowledgeIndex();
|
|
163
|
+
const r = match(index, text, {confidence: settings.confidence});
|
|
164
|
+
const session = await getSession(id, {fresh: true});
|
|
165
|
+
if (r.kind === 'handover') return handoverNow(id, chat);
|
|
166
|
+
if (r.kind === 'greeting') return addMessage(id, {from: 'bot', text: SAY.greeting});
|
|
167
|
+
if (r.kind === 'thanks') return addMessage(id, {from: 'bot', text: SAY.thanks});
|
|
168
|
+
if (r.kind === 'answer') {
|
|
169
|
+
countHit(r.best.id);
|
|
170
|
+
return addMessage(id, {from: 'bot', text: byId.get(r.best.id)?.answer || '', answerId: r.best.id}, {misses: 0});
|
|
171
|
+
}
|
|
172
|
+
if (r.kind === 'suggest') {
|
|
173
|
+
return addMessage(id, {from: 'bot', text: SAY.suggest,
|
|
174
|
+
suggestions: r.suggestions.map(s => ({id: s.id, label: s.question}))});
|
|
175
|
+
}
|
|
176
|
+
await logUnanswered(text, r.best?.question || '');
|
|
177
|
+
const misses = int(session?.data.misses) + 1;
|
|
178
|
+
const out = await addMessage(id, {from: 'bot', text: chat.staff ? SAY.noneStaff : SAY.noneAlone}, {misses});
|
|
179
|
+
if (chat.staff && misses >= 2) return addMessage(id, {from: 'bot', text: SAY.offerPerson});
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Hand the chat over to a person, or to the details form. Inside withChat. */
|
|
184
|
+
async function handoverNow(id, chat) {
|
|
185
|
+
const session = await getSession(id, {fresh: true});
|
|
186
|
+
const d = session.data;
|
|
187
|
+
if (d.status === 'waiting' || d.status === 'open') return addMessage(id, {from: 'system', text: SAY.already});
|
|
188
|
+
if (d.status === 'message') return addMessage(id, {from: 'system', text: SAY.already});
|
|
189
|
+
const hasDetails = Boolean(d.visitorEmail);
|
|
190
|
+
if (!chat.staff) {
|
|
191
|
+
if (chat.askDetails === 'never' || hasDetails) return addMessage(id, {from: 'system', text: SAY.noStaff});
|
|
192
|
+
return addMessage(id, {from: 'system', text: SAY.noStaffDetails}, {askDetails: true});
|
|
193
|
+
}
|
|
194
|
+
if (staffAvailable().length) {
|
|
195
|
+
const askFirst = chat.askDetails === 'always' && !hasDetails;
|
|
196
|
+
const out = await addMessage(id, {from: 'system', text: askFirst ? SAY.detailsFirst : SAY.connecting},
|
|
197
|
+
{status: 'waiting', waitingSince: new Date().toISOString(), askDetails: askFirst, misses: 0});
|
|
198
|
+
if (out) raise(out.session, 'waiting');
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
if (chat.askDetails === 'never') return addMessage(id, {from: 'system', text: SAY.nobodyLater});
|
|
202
|
+
if (hasDetails) {
|
|
203
|
+
const out = await addMessage(id, {from: 'system', text: SAY.nobodyHaveDetails},
|
|
204
|
+
{status: 'message', waitingSince: new Date().toISOString()});
|
|
205
|
+
if (out) raise(out.session, 'message');
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
return addMessage(id, {from: 'system', text: SAY.nobodyDetails}, {askDetails: true});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
// Visitor actions (each returns the chat after the change, or an error)
|
|
213
|
+
// ---------------------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
const full = (session) => int(session?.data.count) >= 300 - 3;
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The visitor wrote something.
|
|
219
|
+
*
|
|
220
|
+
* @returns {Promise<{session?: object, error?: string, code?: number}>}
|
|
221
|
+
*/
|
|
222
|
+
export function visitorSays(id, text, chat) {
|
|
223
|
+
return withChat(id, async () => {
|
|
224
|
+
const clean = cleanText(text);
|
|
225
|
+
if (!clean) return {error: 'Type a message first.', code: 400};
|
|
226
|
+
const session = await getSession(id, {fresh: true});
|
|
227
|
+
if (!session || session.data.status === 'closed') return {error: SAY.ended, code: 409};
|
|
228
|
+
if (full(session)) return {error: SAY.full, code: 409};
|
|
229
|
+
const staffSide = ACTIVE.includes(session.data.status);
|
|
230
|
+
const wrote = await addMessage(id, {from: 'visitor', text: clean}, staffSide ? {unread: int(session.data.unread) + 1} : {});
|
|
231
|
+
if (!staffSide) {
|
|
232
|
+
if (chat.bot) await botReply(id, clean, chat, readChatSettings());
|
|
233
|
+
else await handoverNow(id, chat);
|
|
234
|
+
}
|
|
235
|
+
return {session: await getSession(id, {fresh: true}) || wrote.session};
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The visitor tapped one of the bot's "Did you mean" choices (i), or "None of
|
|
241
|
+
* these" (i = -1).
|
|
242
|
+
*/
|
|
243
|
+
export function visitorPicks(id, n, i, chat) {
|
|
244
|
+
return withChat(id, async () => {
|
|
245
|
+
const session = await getSession(id, {fresh: true});
|
|
246
|
+
if (!session || session.data.status === 'closed') return {error: SAY.ended, code: 409};
|
|
247
|
+
if (full(session)) return {error: SAY.full, code: 409};
|
|
248
|
+
const msgs = await messagesAfter(id, Math.max(0, int(n) - 2));
|
|
249
|
+
const offer = msgs.find(m => int(m.data.n) === int(n));
|
|
250
|
+
const choices = offer?.data.from === 'bot' && Array.isArray(offer.data.suggestions) ? offer.data.suggestions : null;
|
|
251
|
+
if (!choices) return {error: 'That choice is no longer on offer.', code: 409};
|
|
252
|
+
if (i === -1) {
|
|
253
|
+
const asked = msgs.filter(m => m.data.from === 'visitor' && int(m.data.n) < int(n)).pop();
|
|
254
|
+
await addMessage(id, {from: 'visitor', text: 'None of these'});
|
|
255
|
+
if (asked) await logUnanswered(asked.data.text, choices[0]?.label || '');
|
|
256
|
+
await addMessage(id, {from: 'bot', text: chat.staff ? SAY.noneStaff : SAY.noneAlone});
|
|
257
|
+
return {session: await getSession(id, {fresh: true})};
|
|
258
|
+
}
|
|
259
|
+
const choice = choices[int(i)];
|
|
260
|
+
if (!choice || !Number.isInteger(i) || i < 0) return {error: 'That choice is no longer on offer.', code: 409};
|
|
261
|
+
const {byId} = await knowledgeIndex();
|
|
262
|
+
const entry = byId.get(choice.id);
|
|
263
|
+
await addMessage(id, {from: 'visitor', text: choice.label});
|
|
264
|
+
if (entry && entry.enabled) {
|
|
265
|
+
countHit(entry.id);
|
|
266
|
+
await addMessage(id, {from: 'bot', text: entry.answer, answerId: entry.id}, {misses: 0});
|
|
267
|
+
} else {
|
|
268
|
+
await addMessage(id, {from: 'bot', text: chat.staff ? SAY.noneStaff : SAY.noneAlone});
|
|
269
|
+
}
|
|
270
|
+
return {session: await getSession(id, {fresh: true})};
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** "Talk to a person". */
|
|
275
|
+
export function visitorAsksForPerson(id, chat) {
|
|
276
|
+
return withChat(id, async () => {
|
|
277
|
+
const session = await getSession(id, {fresh: true});
|
|
278
|
+
if (!session || session.data.status === 'closed') return {error: SAY.ended, code: 409};
|
|
279
|
+
if (full(session)) return {error: SAY.full, code: 409};
|
|
280
|
+
await addMessage(id, {from: 'visitor', text: 'Talk to a person'});
|
|
281
|
+
await handoverNow(id, chat);
|
|
282
|
+
return {session: await getSession(id, {fresh: true})};
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** A plain address: nothing a mailto: link would read as more than an address (?, &, spaces, brackets). */
|
|
287
|
+
const EMAIL_RE = /^[A-Za-z0-9._%+'-]{1,64}@(?=.{4,190}$)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\.[A-Za-z]{2,24}$/;
|
|
288
|
+
|
|
289
|
+
/** Validate the visitor's name-and-email form. */
|
|
290
|
+
export function detailsInput(body = {}) {
|
|
291
|
+
const name = cleanText(body.name, 80).replace(/\n/g, ' ');
|
|
292
|
+
const email = cleanText(body.email, 254).replace(/\s/g, '');
|
|
293
|
+
const message = cleanText(body.message, 1000);
|
|
294
|
+
if (!name) return {error: 'Please give your name.'};
|
|
295
|
+
if (!EMAIL_RE.test(email)) return {error: 'Please give an email address we can reply to.'};
|
|
296
|
+
return {name, email, message};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The visitor left their name and email (and perhaps a message). */
|
|
300
|
+
export function visitorDetails(id, body, chat) {
|
|
301
|
+
return withChat(id, async () => {
|
|
302
|
+
const session = await getSession(id, {fresh: true});
|
|
303
|
+
if (!session || session.data.status === 'closed') return {error: SAY.ended, code: 409};
|
|
304
|
+
// Only when this launcher asks for details and this chat was offered the form.
|
|
305
|
+
const offered = session.data.askDetails === true || session.data.askDetails === 'true';
|
|
306
|
+
if (chat.askDetails === 'never' || !offered) return {error: 'Details are not being asked for in this chat.', code: 403};
|
|
307
|
+
const input = detailsInput(body);
|
|
308
|
+
if (input.error) return {error: input.error, code: 400};
|
|
309
|
+
if (full(session)) return {error: SAY.full, code: 409};
|
|
310
|
+
const d = session.data;
|
|
311
|
+
await patchSession(id, {visitorName: input.name, visitorEmail: input.email, askDetails: false});
|
|
312
|
+
if (input.message) await addMessage(id, {from: 'visitor', text: input.message}, ACTIVE.includes(d.status) ? {unread: int(d.unread) + 1} : {});
|
|
313
|
+
const first = input.name.split(' ')[0];
|
|
314
|
+
if (d.status === 'bot') {
|
|
315
|
+
// The details form was the way to the team: nobody was free, or there is no staff chat.
|
|
316
|
+
const out = await addMessage(id, {from: 'system', text: `Thanks, ${first}. We will get back to you at ${input.email}.`},
|
|
317
|
+
{status: 'message', waitingSince: new Date().toISOString()});
|
|
318
|
+
if (out) raise(out.session, 'message');
|
|
319
|
+
} else {
|
|
320
|
+
const out = await addMessage(id, {from: 'system', text: `Thanks, ${first} - we have your details.`});
|
|
321
|
+
if (out && d.status === 'waiting') raise(out.session, 'waiting');
|
|
322
|
+
}
|
|
323
|
+
return {session: await getSession(id, {fresh: true})};
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The visitor ended the chat. */
|
|
328
|
+
export function visitorEnds(id) {
|
|
329
|
+
return withChat(id, async () => {
|
|
330
|
+
const session = await getSession(id, {fresh: true});
|
|
331
|
+
if (!session || session.data.status === 'closed') return {session};
|
|
332
|
+
await addMessage(id, {from: 'system', text: SAY.endedByVisitor}, {status: 'closed', closedAt: new Date().toISOString()});
|
|
333
|
+
// A message left for the team still wants an answer; anything else is settled.
|
|
334
|
+
if (session.data.status !== 'message') settle(id);
|
|
335
|
+
return {session: await getSession(id, {fresh: true})};
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
// Staff actions
|
|
341
|
+
// ---------------------------------------------------------------------------
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* A member of staff replied.
|
|
345
|
+
*
|
|
346
|
+
* @param {string} id
|
|
347
|
+
* @param {{id: string, name?: string}} user
|
|
348
|
+
* @param {string} text
|
|
349
|
+
*/
|
|
350
|
+
export function staffReplies(id, user, text) {
|
|
351
|
+
return withChat(id, async () => {
|
|
352
|
+
const clean = cleanText(text);
|
|
353
|
+
if (!clean) return {error: 'Type a reply first.', code: 400};
|
|
354
|
+
const session = await getSession(id, {fresh: true});
|
|
355
|
+
if (!session) return {error: 'Chat not found', code: 404};
|
|
356
|
+
if (session.data.status === 'closed') return {error: 'This chat has ended. The visitor will not see a reply.', code: 409};
|
|
357
|
+
if (int(session.data.count) >= 300) return {error: 'This chat is full.', code: 409};
|
|
358
|
+
const name = staffDisplayName(user, readChatSettings().staffName);
|
|
359
|
+
await addMessage(id, {from: 'staff', text: clean, staffName: name}, {
|
|
360
|
+
status: session.data.status === 'message' ? 'message' : 'open',
|
|
361
|
+
assignedTo: String(user?.id || ''), assignedName: String(user?.name || name).slice(0, 80),
|
|
362
|
+
unread: 0, waitingSince: null, askDetails: false
|
|
363
|
+
});
|
|
364
|
+
settle(id);
|
|
365
|
+
return {session: await getSession(id, {fresh: true})};
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Staff read the chat: nothing unread. */
|
|
370
|
+
export function staffSeen(id) {
|
|
371
|
+
return withChat(id, async () => {
|
|
372
|
+
const session = await getSession(id, {fresh: true});
|
|
373
|
+
if (!session || !int(session.data.unread)) return {session};
|
|
374
|
+
return {session: await patchSession(id, {unread: 0})};
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Staff ended the chat (the visitor sees that it ended). */
|
|
379
|
+
export function staffCloses(id) {
|
|
380
|
+
return withChat(id, async () => {
|
|
381
|
+
const session = await getSession(id, {fresh: true});
|
|
382
|
+
if (!session) return {error: 'Chat not found', code: 404};
|
|
383
|
+
if (session.data.status !== 'closed') {
|
|
384
|
+
await addMessage(id, {from: 'system', text: SAY.ended}, {status: 'closed', closedAt: new Date().toISOString(), unread: 0, waitingSince: null, askDetails: false});
|
|
385
|
+
}
|
|
386
|
+
settle(id);
|
|
387
|
+
return {session: await getSession(id, {fresh: true})};
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Staff deleted the chat and its messages. */
|
|
392
|
+
export function staffDeletes(id) {
|
|
393
|
+
return withChat(id, async () => {
|
|
394
|
+
const ok = await removeSession(id);
|
|
395
|
+
if (ok) settle(id);
|
|
396
|
+
return {ok};
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---------------------------------------------------------------------------
|
|
401
|
+
// The tidy-up (hourly)
|
|
402
|
+
// ---------------------------------------------------------------------------
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Close chats nobody is in any more and delete old ones.
|
|
406
|
+
* bot quiet for 2 hours -> closed
|
|
407
|
+
* waiting quiet for a day -> closed (nobody answered)
|
|
408
|
+
* open quiet for a day -> closed
|
|
409
|
+
* message -> kept until staff deal with it
|
|
410
|
+
* closed never reached a person and gave no details: deleted after BOT_ONLY_DAYS
|
|
411
|
+
* (or retentionDays, if shorter); otherwise after retentionDays
|
|
412
|
+
* Deleted chats go with their messages, and so does any message whose chat has
|
|
413
|
+
* gone - in one write per collection. Ended chats are dropped from memory.
|
|
414
|
+
*
|
|
415
|
+
* @returns {Promise<{closed: number, deleted: number, messages: number}>}
|
|
416
|
+
*/
|
|
417
|
+
export const BOT_ONLY_DAYS = 7;
|
|
418
|
+
|
|
419
|
+
export async function sweepChats({at = Date.now(), retentionDays = readChatSettings().retentionDays} = {}) {
|
|
420
|
+
const HOUR = 3_600_000;
|
|
421
|
+
let closed = 0;
|
|
422
|
+
const doomed = [];
|
|
423
|
+
for (const entry of await listSessions()) {
|
|
424
|
+
const d = entry.data;
|
|
425
|
+
const quiet = at - (Date.parse(d.lastAt || entry.meta?.updatedAt || '') || at);
|
|
426
|
+
const limit = d.status === 'bot' ? 2 * HOUR : (d.status === 'waiting' || d.status === 'open') ? 24 * HOUR : null;
|
|
427
|
+
if (limit !== null && quiet >= limit) {
|
|
428
|
+
await withChat(entry.id, async () => {
|
|
429
|
+
const fresh = await getSession(entry.id, {fresh: true});
|
|
430
|
+
if (!fresh || fresh.data.status !== d.status) return;
|
|
431
|
+
await addMessage(entry.id, {from: 'system', text: SAY.ended}, {status: 'closed', closedAt: new Date(at).toISOString(), unread: 0, waitingSince: null});
|
|
432
|
+
settle(entry.id);
|
|
433
|
+
closed++;
|
|
434
|
+
});
|
|
435
|
+
forgetSession(entry.id);
|
|
436
|
+
} else if (d.status === 'closed') {
|
|
437
|
+
const botOnly = !d.assignedTo && !d.visitorEmail;
|
|
438
|
+
const keepDays = botOnly ? Math.min(BOT_ONLY_DAYS, retentionDays) : retentionDays;
|
|
439
|
+
if (quiet >= keepDays * 24 * HOUR) doomed.push(entry.id);
|
|
440
|
+
else forgetSession(entry.id);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
const removed = await removeSessionsAndOrphans(doomed);
|
|
444
|
+
return {closed, deleted: removed.chats, messages: removed.messages};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let sweepTimer = null;
|
|
448
|
+
|
|
449
|
+
/** Run the tidy-up an hour after start, then hourly. */
|
|
450
|
+
export function startChatSweep({log = console} = {}) {
|
|
451
|
+
if (sweepTimer) return;
|
|
452
|
+
const run = () => sweepChats().then(r => {
|
|
453
|
+
if (r.closed || r.deleted) log.info?.(`[chat] Tidy-up: ${r.closed} closed, ${r.deleted} deleted.`);
|
|
454
|
+
}).catch(err => log.warn?.(`[chat] Tidy-up failed: ${err.message}`));
|
|
455
|
+
sweepTimer = setInterval(run, 3_600_000);
|
|
456
|
+
sweepTimer.unref?.();
|
|
457
|
+
setTimeout(run, 60_000).unref?.();
|
|
458
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which launchers may chat, and with what settings - the one place the chat
|
|
3
|
+
* asks Launchers (services/launchers.js `chatLaunchers()`).
|
|
4
|
+
*
|
|
5
|
+
* Every visitor request goes through chatLauncher(id): no enabled chat launcher
|
|
6
|
+
* with that id means the public chat API answers 404, so a site with no chat
|
|
7
|
+
* launcher (or Launchers switched off) has no chat surface at all.
|
|
8
|
+
*
|
|
9
|
+
* A missing Launchers module, or any failure asking it, refuses: the chat never
|
|
10
|
+
* opens for a launcher nobody switched on.
|
|
11
|
+
*
|
|
12
|
+
* @module services/chat/launcher-bridge
|
|
13
|
+
*/
|
|
14
|
+
import {normaliseLauncherChat} from './settings.js';
|
|
15
|
+
|
|
16
|
+
let loader = () => import('../launchers.js');
|
|
17
|
+
|
|
18
|
+
/** Tests: replace where the launchers come from. */
|
|
19
|
+
export function _setLauncherSource(fn) {
|
|
20
|
+
loader = typeof fn === 'function' ? async () => ({chatLaunchers: fn}) : () => import('../launchers.js');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The enabled chat launchers, or null when Launchers is not installed. */
|
|
24
|
+
async function listChatLaunchers() {
|
|
25
|
+
let mod;
|
|
26
|
+
try {
|
|
27
|
+
mod = await loader();
|
|
28
|
+
} catch (err) {
|
|
29
|
+
if (err?.code === 'ERR_MODULE_NOT_FOUND' && /launchers\.js/.test(String(err.message))) return null;
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
if (typeof mod?.chatLaunchers !== 'function') return null;
|
|
33
|
+
const list = await mod.chatLaunchers();
|
|
34
|
+
return Array.isArray(list) ? list : [];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A launcher id as the browser may send it. */
|
|
38
|
+
export const LAUNCHER_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The chat settings for one launcher, or null when it may not chat.
|
|
42
|
+
*
|
|
43
|
+
* @param {string} id
|
|
44
|
+
* @returns {Promise<{id: string, chat: ReturnType<typeof normaliseLauncherChat>}|null>}
|
|
45
|
+
*/
|
|
46
|
+
export async function chatLauncher(id) {
|
|
47
|
+
if (typeof id !== 'string' || !LAUNCHER_ID.test(id)) return null;
|
|
48
|
+
let list;
|
|
49
|
+
try {
|
|
50
|
+
list = await listChatLaunchers();
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
// Launchers ships with the engine now: no module means no chat, never "allow any id".
|
|
55
|
+
if (list === null) return null;
|
|
56
|
+
const found = list.find(l => l && String(l.id) === id);
|
|
57
|
+
return found ? {id, chat: normaliseLauncherChat(found.chat)} : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether any launcher may chat - the admin shows "no chat launcher yet"
|
|
62
|
+
* otherwise.
|
|
63
|
+
*
|
|
64
|
+
* @returns {Promise<{installed: boolean, count: number}>}
|
|
65
|
+
*/
|
|
66
|
+
export async function chatLauncherSummary() {
|
|
67
|
+
try {
|
|
68
|
+
const list = await listChatLaunchers();
|
|
69
|
+
return list === null ? {installed: false, count: 0} : {installed: true, count: list.length};
|
|
70
|
+
} catch {
|
|
71
|
+
return {installed: true, count: 0};
|
|
72
|
+
}
|
|
73
|
+
}
|