domma-cms 1.35.0 → 1.37.0

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/admin/js/api.js +1 -1
  3. package/admin/js/app.js +2 -2
  4. package/admin/js/lib/image-editor.js +1 -1
  5. package/admin/js/lib/media-arrange.js +1 -1
  6. package/admin/js/lib/media-picker.js +2 -2
  7. package/admin/js/lib/media-upload.js +1 -1
  8. package/admin/js/lib/seo-redirects.js +1 -1
  9. package/admin/js/templates/docs/usage-media.html +6 -0
  10. package/admin/js/templates/media.html +1 -0
  11. package/admin/js/views/media.js +3 -3
  12. package/bin/lib/left-free-tier.js +4 -1
  13. package/bin/update.js +4 -0
  14. package/docs/DommaFeatures.md +10 -5
  15. package/docs/plugin-development.md +2 -2
  16. package/package.json +1 -1
  17. package/plugins/docs/tests/plugin.test.js +2 -0
  18. package/plugins/free-tier.lock.json +2 -50
  19. package/server/routes/api/media.js +3 -1
  20. package/server/routes/api/sidebar.js +2 -2
  21. package/server/services/content.js +26 -2
  22. package/server/services/hooks.js +27 -4
  23. package/server/services/plugins.js +9 -3
  24. package/server/services/renderer.js +3 -1
  25. package/server/services/siteGitignore.js +1 -1
  26. package/plugins/booking/CLAUDE.md +0 -204
  27. package/plugins/booking/admin/css/index.css +0 -192
  28. package/plugins/booking/admin/lib/details.js +0 -58
  29. package/plugins/booking/admin/lib/diary-layout.js +0 -158
  30. package/plugins/booking/admin/lib/drafts.js +0 -139
  31. package/plugins/booking/admin/lib/email.js +0 -191
  32. package/plugins/booking/admin/lib/extension-sections.js +0 -160
  33. package/plugins/booking/admin/lib/kit.js +0 -471
  34. package/plugins/booking/admin/templates/booking.html +0 -1
  35. package/plugins/booking/admin/views/booking.js +0 -216
  36. package/plugins/booking/admin/views/bookings.js +0 -132
  37. package/plugins/booking/admin/views/diary.js +0 -382
  38. package/plugins/booking/admin/views/panels.js +0 -603
  39. package/plugins/booking/admin/views/people.js +0 -318
  40. package/plugins/booking/admin/views/services.js +0 -264
  41. package/plugins/booking/admin/views/settings.js +0 -222
  42. package/plugins/booking/collections/booking-bookables.json +0 -17
  43. package/plugins/booking/collections/booking-bookings.json +0 -18
  44. package/plugins/booking/collections/booking-services.json +0 -17
  45. package/plugins/booking/config.js +0 -36
  46. package/plugins/booking/docs/guide.md +0 -73
  47. package/plugins/booking/inject/body.html +0 -1
  48. package/plugins/booking/lib/call.js +0 -88
  49. package/plugins/booking/lib/extensions.js +0 -169
  50. package/plugins/booking/lib/mail.js +0 -113
  51. package/plugins/booking/lib/store.js +0 -392
  52. package/plugins/booking/plugin.js +0 -905
  53. package/plugins/booking/plugin.json +0 -81
  54. package/plugins/booking/plugin.public.js +0 -175
  55. package/plugins/booking/public/booking.css +0 -159
  56. package/plugins/booking/public/booking.js +0 -808
  57. package/plugins/booking/public/lib/clean.js +0 -141
  58. package/plugins/booking/public/lib/page-format.js +0 -121
  59. package/plugins/booking/public/lib/slots.js +0 -247
  60. package/plugins/booking/public/lib/time.js +0 -131
  61. package/plugins/booking/templates/booking.html +0 -5
  62. package/plugins/booking/tests/admin-diary.test.js +0 -81
  63. package/plugins/booking/tests/admin-drafts.test.js +0 -67
  64. package/plugins/booking/tests/api.test.js +0 -651
  65. package/plugins/booking/tests/email.test.js +0 -69
  66. package/plugins/booking/tests/public.test.js +0 -72
  67. package/plugins/booking/tests/pure.test.js +0 -189
  68. package/plugins/booking/tests/seo.test.js +0 -71
@@ -1,392 +0,0 @@
1
- /**
2
- * Booking's data: the three collections, the live settings, and the moves a
3
- * booking makes (made, moved, cancelled, marked done or no-show).
4
- *
5
- * Every write to a booking goes through `withLock`, one at a time, and
6
- * re-checks the slot inside it. Two people choosing the same time in the same
7
- * second: the second finds the first's booking and is told the time has gone.
8
- *
9
- * @module booking/lib/store
10
- */
11
-
12
- import {randomBytes} from 'crypto';
13
- import {createCollection, createEntry, deleteEntry, getCollection, getEntry, listEntries, updateEntry} from '../../../server/services/collections.js';
14
- import {getPluginSettings, getPluginStates, savePluginState} from '../../../server/services/plugins.js';
15
- import {cleanDaysOff, EMAIL_RE, STATUSES} from '../public/lib/clean.js';
16
- import {PLAIN, pickBookable, spanOf, whoCanTake} from '../public/lib/slots.js';
17
- import {atWallClock, cleanZone, isDate, wallClock} from '../public/lib/time.js';
18
- import defaults from '../config.js';
19
- import {joinPath} from './call.js';
20
-
21
- export const NAME = 'booking';
22
- export const BOOKABLES = 'booking-bookables';
23
- export const SERVICES = 'booking-services';
24
- export const BOOKINGS = 'booking-bookings';
25
-
26
- // ---- Setup ---------------------------------------------------------------------
27
-
28
- /** Make the collections that are missing. Every boot: a plugin switched on by copy never has onEnable run. */
29
- export async function ensureCollections(log = console) {
30
- const fs = await import('fs/promises');
31
- for (const slug of [BOOKABLES, SERVICES, BOOKINGS]) {
32
- if (await getCollection(slug)) continue;
33
- const schema = JSON.parse(await fs.readFile(new URL(`../collections/${slug}.json`, import.meta.url), 'utf8'));
34
- await createCollection(schema);
35
- log.info?.(`[booking] Created collection: ${slug}`);
36
- }
37
- }
38
-
39
- // ---- Settings ------------------------------------------------------------------
40
-
41
- const RESERVED = /^\/(admin|api|plugins|dist|media|assets|login|shop|blog|calendar)(\/|$)/;
42
-
43
- /** "/booking" from "booking/", "/Booking//" - one leading slash, no trailing one, never an engine address. */
44
- export function cleanPath(p) {
45
- const t = '/' + String(p || '/booking').toLowerCase().replace(/[^a-z0-9/_-]/g, '').replace(/\/+/g, '/').replace(/^\/|\/$/g, '');
46
- return t === '/' || RESERVED.test(t) ? '/booking' : t;
47
- }
48
-
49
- const withDefaults = (s) => ({...defaults, ...s, bookingPath: cleanPath(s.bookingPath), timeZone: cleanZone(s.timeZone)});
50
-
51
- /** The settings as they are NOW - read per request, so a change needs no restart. */
52
- export async function liveSettings() {
53
- return withDefaults(await getPluginSettings(NAME) || {});
54
- }
55
-
56
- /** The same, synchronously - for shortcodes, which cannot wait. */
57
- export function settingsNow() {
58
- return withDefaults(getPluginStates()[NAME]?.settings || {});
59
- }
60
-
61
- /** @returns {{settings: object, errors: Object<string, string>}} */
62
- export function cleanSettings(input, current) {
63
- const errors = {};
64
- const v = {...current, ...input};
65
- const str = (k, max = 300) => String(v[k] ?? '').trim().slice(0, max);
66
- const out = {
67
- pageTitle: str('pageTitle', 80) || 'Book',
68
- bookingPath: cleanPath(v.bookingPath),
69
- intro: str('intro', 2000),
70
- timeZone: cleanZone(v.timeZone),
71
- askPhone: v.askPhone !== false,
72
- phoneRequired: v.phoneRequired === true,
73
- termsUrl: str('termsUrl'),
74
- confirmationNote: str('confirmationNote', 2000),
75
- allowCancel: v.allowCancel !== false,
76
- allowMove: v.allowMove !== false,
77
- changeNoticeHours: Math.max(0, Math.min(24 * 30, Math.round(Number(v.changeNoticeHours) || 0))),
78
- sendConfirmation: v.sendConfirmation !== false,
79
- reminderHours: Math.max(0, Math.min(24 * 14, Math.round(Number(v.reminderHours) || 0))),
80
- notifyAddress: str('notifyAddress', 200),
81
- addToContacts: v.addToContacts !== false,
82
- contactsOwnerId: str('contactsOwnerId', 64),
83
- calendarBusy: v.calendarBusy !== false,
84
- closures: cleanDaysOff(v.closures)
85
- };
86
- if (input.timeZone !== undefined && cleanZone(input.timeZone) !== String(input.timeZone).trim()) errors.timeZone = 'A time zone such as Europe/London.';
87
- if (out.termsUrl && !/^(\/(?!\/)|https?:\/\/)/.test(out.termsUrl)) errors.termsUrl = 'A page on this site (/terms) or a full https:// address.';
88
- if (out.notifyAddress && !EMAIL_RE.test(out.notifyAddress)) errors.notifyAddress = 'An email address, or leave it empty.';
89
- if (input.bookingPath !== undefined && cleanPath(input.bookingPath) !== '/' + String(input.bookingPath).trim().replace(/^\/+|\/+$/g, '').toLowerCase()) {
90
- errors.bookingPath = 'Letters, numbers and hyphens, and not an address the CMS uses (admin, api, shop, blog...).';
91
- }
92
- return {settings: out, errors};
93
- }
94
-
95
- export function saveSettings(next) {
96
- const state = getPluginStates()[NAME] || {};
97
- savePluginState(NAME, {settings: {...(state.settings || {}), ...next}});
98
- }
99
-
100
- // ---- Reading -------------------------------------------------------------------
101
-
102
- const all = async (slug) => (await listEntries(slug, {limit: 100000}).catch(() => ({entries: []}))).entries || [];
103
- const flat = (e) => (e ? {id: e.id, ...e.data, createdAt: e.meta?.createdAt, updatedAt: e.meta?.updatedAt} : null);
104
- const byOrder = (a, b) => (a.order || 0) - (b.order || 0) || String(a.name).localeCompare(String(b.name));
105
-
106
- export const allBookables = async () => (await all(BOOKABLES)).map(flat).sort(byOrder);
107
- export const allServices = async () => (await all(SERVICES)).map(flat).sort(byOrder);
108
- export const allBookings = async () => (await all(BOOKINGS)).map(flat);
109
- export const getBooking = async (id) => flat(await getEntry(BOOKINGS, id).catch(() => null));
110
- export const getService = async (id) => flat(await getEntry(SERVICES, id).catch(() => null));
111
- export const getBookable = async (id) => flat(await getEntry(BOOKABLES, id).catch(() => null));
112
-
113
- /** The snapshot shortcodes render from (they are synchronous). */
114
- let shelf = {services: [], bookables: []};
115
- export async function refreshShelf() {
116
- shelf = {services: await allServices(), bookables: await allBookables()};
117
- return shelf;
118
- }
119
- export const shelfNow = () => shelf;
120
-
121
- // ---- Writing: services and bookables -------------------------------------------
122
-
123
- export async function saveThing(slug, id, data) {
124
- const saved = id ? await updateEntry(slug, id, data) : await createEntry(slug, data);
125
- await refreshShelf();
126
- return flat(saved);
127
- }
128
-
129
- export async function removeThing(slug, id) {
130
- await deleteEntry(slug, id);
131
- await refreshShelf();
132
- }
133
-
134
- /** A service's slug, unique among services. */
135
- export function uniqueSlug(slug, services, selfId = '') {
136
- // 'manage' is the customer's own page (<base>/manage/<id>), never a service.
137
- const taken = new Set(['manage', ...services.filter(s => s.id !== selfId).map(s => s.slug)]);
138
- if (!taken.has(slug)) return slug;
139
- for (let n = 2; ; n++) if (!taken.has(`${slug}-${n}`)) return `${slug}-${n}`;
140
- }
141
-
142
- // ---- The lock ------------------------------------------------------------------
143
-
144
- let queue = Promise.resolve();
145
- /** Run `fn` after every write before it has finished. */
146
- export function withLock(fn) {
147
- const run = queue.then(fn, fn);
148
- queue = run.catch(() => {});
149
- return run;
150
- }
151
-
152
- // ---- Busy time from the Calendar -----------------------------------------------
153
-
154
- /**
155
- * A person's commitments in the Calendar, when the Calendar is here: the
156
- * active occurrences of events they organise. Read through the collections
157
- * service (no import of the Calendar's code - it is a separate, paid Tool).
158
- *
159
- * An all-day event is stored as UTC midnights of its dates (end exclusive);
160
- * it blocks the business's own midnight to midnight, not UTC's.
161
- *
162
- * @param {object[]} bookables
163
- * @param {{from: string, to: string}} range - ISO instants
164
- * @param {string} [tz] - the business zone
165
- * @returns {Promise<Object<string, {startAt: string, endAt: string}[]>>}
166
- */
167
- export async function calendarBusy(bookables, {from, to}, tz = 'Europe/London') {
168
- const out = {};
169
- const people = bookables.filter(b => b.kind === 'person' && b.userId && b.calendarBusy !== false);
170
- if (!people.length || !getPluginStates().calendar?.enabled) return out;
171
- const [events, occurrences] = await Promise.all([all('calendar-events'), all('calendar-occurrences')]);
172
- const organiser = new Map(events.map(e => [e.id, e.data?.organiserId]));
173
- for (const bk of people) out[bk.id] = [];
174
- for (const o of occurrences) {
175
- const d = o.data || {};
176
- if (d.status && d.status !== 'active') continue;
177
- if (!d.startAt) continue;
178
- let startAt = new Date(d.startAt).toISOString();
179
- let endAt = new Date(d.endAt || d.startAt).toISOString();
180
- if (d.allDay) {
181
- const first = startAt.slice(0, 10);
182
- const end = endAt.slice(0, 10) > first ? endAt.slice(0, 10) : first;
183
- startAt = atWallClock(first, 0, tz).toISOString();
184
- endAt = atWallClock(end === first ? addDay(first) : end, 0, tz).toISOString();
185
- }
186
- if (startAt >= to || endAt <= from) continue;
187
- const who = organiser.get(d.eventId);
188
- for (const bk of people) if (bk.userId === who) out[bk.id].push({startAt, endAt});
189
- }
190
- return out;
191
- }
192
-
193
- /** Calendar busy time when the site's setting wants it, else none. */
194
- export async function settingsBusy(bookables, range, tz) {
195
- const s = await liveSettings();
196
- return s.calendarBusy ? calendarBusy(bookables, range, tz) : {};
197
- }
198
-
199
- const addDay = (date) => new Date(Date.parse(`${date}T00:00:00Z`) + 86400000).toISOString().slice(0, 10);
200
-
201
- // ---- Bookings ------------------------------------------------------------------
202
-
203
- export const newToken = () => randomBytes(18).toString('base64url');
204
-
205
- /** Is this the booking's own link? Constant-time is overkill for 24 random chars; equality of type and value is not. */
206
- export const tokenOk = (booking, t) => Boolean(booking?.token) && typeof t === 'string' && t === booking.token;
207
-
208
- /** Why a booking cannot be made at a time, or '' when it can. */
209
- export class SlotTaken extends Error {
210
- constructor(message = 'That time has just been taken. Please pick another.') { super(message); this.code = 'slot-taken'; }
211
- }
212
-
213
- /**
214
- * Make (or move) a booking, inside the lock, after checking the time again.
215
- *
216
- * @param {object} p
217
- * @param {object} p.service
218
- * @param {object[]} p.candidates - bookables that may take it (one when chosen)
219
- * @param {string} p.startAt - ISO
220
- * @param {object} p.fields - everything else stored on the booking
221
- * @param {string} [p.moveId] - move this booking instead of making one
222
- * @param {boolean} [p.force] - staff booking over a clash (admin only)
223
- * @param {string} p.tz
224
- * @param {Function} [p.busyFor] - (bookables, range) => busy map
225
- * @param {object} [p.rules] - capacity, companions, maxPerDay (extensions'; plain without)
226
- * @returns {Promise<object>} the booking
227
- */
228
- export function placeBooking({service, candidates, startAt, fields, moveId = '', force = false, tz, busyFor = settingsBusy, rules = PLAIN}) {
229
- return withLock(async () => {
230
- const span = spanOf(service, startAt);
231
- const bookings = await allBookings();
232
- const range = {from: new Date(span.blockStart).toISOString(), to: new Date(span.blockEnd).toISOString()};
233
- const companions = rules.companions || [];
234
- const everyone = [...candidates, ...companions.flat()];
235
- const busy = force ? {} : await busyFor(everyone, range, tz).catch(() => ({}));
236
- const dayOf = (ms) => wallClock(ms, tz).date;
237
- let able = whoCanTake({service, candidates, companions, span, bookings, busy, ignoreId: moveId, rules, dayOf});
238
- if (!able.length && force) {
239
- // Staff booking over a clash: the chosen (or first) provider, and the first of each companion group.
240
- able = candidates.slice(0, 1).map(bk => ({bookableId: bk.id, holds: [bk.id, ...companions.map(g => g.find(c => c.id !== bk.id)?.id).filter(Boolean)], left: 1}));
241
- }
242
- if (!able.length) throw new SlotTaken();
243
- const date = dayOf(span.start);
244
- const bookableId = pickBookable(able.map(a => a.bookableId), bookings.filter(b => b.id !== moveId), date, tz, {serviceId: service.id, start: span.start});
245
- const chosen = able.find(a => a.bookableId === bookableId);
246
- const byId = new Map(everyone.map(b => [b.id, b]));
247
- const times = {
248
- startAt: new Date(span.start).toISOString(),
249
- endAt: new Date(span.end).toISOString(),
250
- blockStart: new Date(span.blockStart).toISOString(),
251
- blockEnd: new Date(span.blockEnd).toISOString(),
252
- bookableId,
253
- bookableName: byId.get(bookableId)?.name || '',
254
- holds: chosen.holds,
255
- // What it took along (a court with the trainer), by name, for the diary and the emails.
256
- alsoNames: chosen.holds.slice(1).map(id => byId.get(id)?.name || '').filter(Boolean),
257
- reminderSentAt: ''
258
- };
259
- if (moveId) {
260
- const current = await getEntry(BOOKINGS, moveId);
261
- if (!current) throw new Error('That booking no longer exists.');
262
- const history = [...(current.data.history || []), {at: new Date().toISOString(), what: 'moved', from: current.data.startAt, by: fields.by || ''}].slice(-50);
263
- // A call opened early ("Call now") was for the old time; the new one opens as usual.
264
- return flat(await updateEntry(BOOKINGS, moveId, {...current.data, ...times, callOpenedAt: '', history}));
265
- }
266
- const {by, ...rest} = fields;
267
- return flat(await createEntry(BOOKINGS, {
268
- serviceId: service.id,
269
- serviceName: service.name,
270
- duration: service.duration,
271
- status: 'confirmed',
272
- token: newToken(),
273
- ...rest,
274
- ...times,
275
- history: [{at: new Date().toISOString(), what: 'made', by: by || ''}],
276
- ext: rest.ext && typeof rest.ext === 'object' ? rest.ext : {},
277
- // Held as a video call (Pro said so when it was made). Kept on the booking, so the call still
278
- // happens if Pro lapses; the host key is the person booked's link and never reaches the customer.
279
- ...(rules.online ? {online: true, hostKey: newToken(), recordingAllowed: rules.recordingAllowed === true} : {})
280
- }));
281
- });
282
- }
283
-
284
- /**
285
- * Change a booking's status or note (no time change), inside the lock.
286
- *
287
- * @returns {Promise<{booking: object, from: string}>}
288
- */
289
- export function changeBooking(id, patch, by = '') {
290
- return withLock(async () => {
291
- const current = await getEntry(BOOKINGS, id);
292
- if (!current) return null;
293
- const data = {...current.data};
294
- const from = data.status;
295
- if (patch.status !== undefined) {
296
- if (!STATUSES.includes(patch.status)) throw new Error('Not a status a booking can have.');
297
- // Its time may be someone else's by now: bringing it back would be a double booking nobody checked.
298
- if (from === 'cancelled' && patch.status !== 'cancelled') throw new Error('A cancelled booking cannot be brought back. Make a new booking for that time instead.');
299
- data.status = patch.status;
300
- if (patch.status !== from) {
301
- data.history = [...(data.history || []), {at: new Date().toISOString(), what: patch.status, by, reason: String(patch.reason || '').slice(0, 300)}].slice(-50);
302
- if (patch.status === 'cancelled') data.cancelledAt = new Date().toISOString();
303
- }
304
- }
305
- if (patch.staffNote !== undefined) data.staffNote = String(patch.staffNote).slice(0, 4000);
306
- if (patch.customer) {
307
- for (const k of ['name', 'email', 'phone', 'notes']) if (patch.customer[k] !== undefined) data[k] = patch.customer[k];
308
- }
309
- if (patch.reminderSentAt !== undefined) data.reminderSentAt = patch.reminderSentAt;
310
- if (patch.contactId !== undefined) data.contactId = patch.contactId;
311
- // "Call now" (1.4): an online booking's call opened before its time.
312
- if (patch.callOpenedAt !== undefined && data.online === true) {
313
- data.callOpenedAt = String(patch.callOpenedAt || '');
314
- if (data.callOpenedAt) data.history = [...(data.history || []), {at: data.callOpenedAt, what: 'call-opened', by}].slice(-50);
315
- }
316
- // "Add people" (1.6): the session's key for invite passes - set once, never replaced.
317
- if (patch.callExtraKey !== undefined && data.online === true && !data.callExtraKey) data.callExtraKey = String(patch.callExtraKey || '').slice(0, 64);
318
- if (patch.ext && typeof patch.ext === 'object') data.ext = {...(data.ext || {}), ...patch.ext};
319
- return {booking: flat(await updateEntry(BOOKINGS, id, data)), from};
320
- });
321
- }
322
-
323
- export async function removeBooking(id) {
324
- return withLock(() => deleteEntry(BOOKINGS, id));
325
- }
326
-
327
- /** May the customer still change it themselves? */
328
- export function customerMayChange(booking, settings, now = Date.now()) {
329
- if (booking.status !== 'confirmed') return false;
330
- return new Date(booking.startAt).getTime() - now >= (Number(settings.changeNoticeHours) || 0) * 3600000;
331
- }
332
-
333
- /** What the customer's own page may see of a booking. */
334
- export function publicBooking(b, settings, now = Date.now()) {
335
- const wall = wallClock(b.startAt, settings.timeZone);
336
- const may = customerMayChange(b, settings, now);
337
- return {
338
- id: b.id, serviceId: b.serviceId, serviceName: b.serviceName, bookableId: b.bookableId, bookableName: b.bookableName,
339
- startAt: b.startAt, endAt: b.endAt, date: wall.date, time: wall.time, status: b.status,
340
- name: b.name, email: b.email, phone: b.phone, notes: b.notes,
341
- canCancel: may && settings.allowCancel !== false,
342
- canMove: may && settings.allowMove !== false,
343
- online: b.online === true,
344
- callUrl: b.online === true && b.status !== 'cancelled' ? joinPath(settings, b) : ''
345
- };
346
- }
347
-
348
- // ---- Contacts ------------------------------------------------------------------
349
-
350
- /**
351
- * Find or make the customer's contact in the owner's address book. Contacts
352
- * are per user; the owner is the person being booked (when they are a user),
353
- * else the setting, else whoever made the booking. '' when Contacts is off or
354
- * nobody owns it.
355
- *
356
- * @returns {Promise<string>} contact id
357
- */
358
- export async function linkContact({name, email, phone}, ownerId, contactsOn) {
359
- if (!contactsOn || !ownerId || !email) return '';
360
- const want = String(email).trim().toLowerCase();
361
- const entries = await all('contacts-contacts');
362
- const same = entries.find(c => c.data?.userId === ownerId && [c.data?.email, ...(Array.isArray(c.data?.emails) ? c.data.emails.map(x => x?.address) : [])]
363
- .some(a => String(a || '').trim().toLowerCase() === want));
364
- if (same) return same.id;
365
- const made = await createEntry('contacts-contacts', {
366
- name: String(name || email).trim(), email: String(email).trim(), phone: String(phone || '').trim(),
367
- userId: ownerId, groups: [], favourite: false
368
- });
369
- return made.id;
370
- }
371
-
372
- /** A contact of this user's, or null. */
373
- export async function ownContact(id, userId) {
374
- const e = await getEntry('contacts-contacts', id).catch(() => null);
375
- if (!e || (userId && e.data?.userId !== userId)) return null;
376
- return {id: e.id, name: e.data?.name || '', email: e.data?.email || '', phone: e.data?.phone || ''};
377
- }
378
-
379
- /**
380
- * The caller's own contact with this email (main address or any of Contacts Pro's), or null - so an email's
381
- * "Book Sam…" and a typed address both find the contact they already have instead of making another.
382
- */
383
- export async function contactByEmail(email, userId) {
384
- const want = String(email || '').trim().toLowerCase();
385
- if (!want || !userId) return null;
386
- const e = (await all('contacts-contacts')).find(c => c.data?.userId === userId
387
- && [c.data?.email, ...(Array.isArray(c.data?.emails) ? c.data.emails.map(x => x?.address) : [])]
388
- .some(a => String(a || '').trim().toLowerCase() === want));
389
- return e ? {id: e.id, name: e.data?.name || '', email: e.data?.email || want, phone: e.data?.phone || ''} : null;
390
- }
391
-
392
- export {isDate};