@htilabs/platform-common-models 0.29.0 → 0.30.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.
- package/README.md +268 -1
- package/dist/{index-Dr6GBCoY.d.ts → index-ClTjjJ_S.d.ts} +1 -1
- package/dist/{index-BTqHP4DM.d.cts → index-Pt82NxQg.d.cts} +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/models/index.d.cts +2 -2
- package/dist/models/index.d.ts +2 -2
- package/dist/points-of-contact/index.cjs +826 -21
- package/dist/points-of-contact/index.cjs.map +1 -1
- package/dist/points-of-contact/index.d.cts +936 -87
- package/dist/points-of-contact/index.d.ts +936 -87
- package/dist/points-of-contact/index.js +799 -21
- package/dist/points-of-contact/index.js.map +1 -1
- package/dist/schemas/index.d.cts +25 -25
- package/dist/schemas/index.d.ts +25 -25
- package/package.json +1 -1
- package/src/pointsOfContact/__tests__/mongoDouble.ts +194 -0
- package/src/pointsOfContact/__tests__/pointsOfContact.test.ts +379 -26
- package/src/pointsOfContact/__tests__/writer.mongo.test.ts +190 -0
- package/src/pointsOfContact/__tests__/writer.test.ts +782 -0
- package/src/pointsOfContact/index.ts +12 -7
- package/src/pointsOfContact/readRules.ts +73 -12
- package/src/pointsOfContact/reader.ts +75 -9
- package/src/pointsOfContact/schemas.ts +304 -34
- package/src/pointsOfContact/vocabulary.ts +40 -5
- package/src/pointsOfContact/writer.ts +967 -0
- package/dist/{cvcEntry-BqAGctqK.d.cts → cvcEntry-Asg7mxjB.d.cts} +8 -8
- package/dist/{cvcEntry-BqAGctqK.d.ts → cvcEntry-Asg7mxjB.d.ts} +8 -8
|
@@ -47,7 +47,18 @@ var preferredContactMethod_v1_0_0_default = {
|
|
|
47
47
|
};
|
|
48
48
|
|
|
49
49
|
// src/pointsOfContact/vocabulary.ts
|
|
50
|
-
var POC_SUBJECT_TYPES = ["agency", "org", "program", "team", "
|
|
50
|
+
var POC_SUBJECT_TYPES = ["agency", "org", "program", "team", "location", "service"];
|
|
51
|
+
var POC_SUBJECT_TYPE_LABELS = {
|
|
52
|
+
agency: "Agency",
|
|
53
|
+
org: "Org",
|
|
54
|
+
program: "Program",
|
|
55
|
+
team: "Team",
|
|
56
|
+
location: "Site",
|
|
57
|
+
service: "Service listing"
|
|
58
|
+
};
|
|
59
|
+
function pocSubjectTypeLabel(type) {
|
|
60
|
+
return Object.hasOwn(POC_SUBJECT_TYPE_LABELS, type) ? POC_SUBJECT_TYPE_LABELS[type] : type;
|
|
61
|
+
}
|
|
51
62
|
var CONTACT_PURPOSE_CODES = [
|
|
52
63
|
"COMPLIANCE",
|
|
53
64
|
"TRAINING",
|
|
@@ -127,10 +138,27 @@ var POINT_OF_CONTACT_INDEXES = {
|
|
|
127
138
|
* `confirmed`: at most one VISIBLE primary per subject, so a stranger's
|
|
128
139
|
* pending add can never hold the slot.
|
|
129
140
|
*/
|
|
130
|
-
primary: "pointsofcontact_primary_unique"
|
|
141
|
+
primary: "pointsofcontact_primary_unique",
|
|
142
|
+
/**
|
|
143
|
+
* `{agency_id, subject_type, subject_id, identity_key, createdBy}` unique
|
|
144
|
+
* where {@link POC_IN_APP_PENDING_INDEX_FILTER}: one outstanding in-app add
|
|
145
|
+
* per adder, subject and IDENTITY ({@link pocIdentityKey}: name + preferred
|
|
146
|
+
* email). See `POC_IN_APP_PENDING_INDEX`.
|
|
147
|
+
*/
|
|
148
|
+
inAppPending: "pointsofcontact_inapp_pending_unique",
|
|
149
|
+
/** `{status, createdAt, id}`: the steward's review queue, paged oldest first. */
|
|
150
|
+
pendingQueue: "pointsofcontact_pending_queue"
|
|
131
151
|
};
|
|
132
152
|
var POC_IDENTITY_INDEX_FILTER = { active: true, status: "confirmed" };
|
|
133
153
|
var POC_PRIMARY_INDEX_FILTER = { is_primary: true, active: true, status: "confirmed" };
|
|
154
|
+
var POC_IN_APP_PENDING_INDEX_FILTER = { status: "pending", origin: "in_app", active: true };
|
|
155
|
+
var POC_IN_APP_PENDING_INDEX_KEY = {
|
|
156
|
+
agency_id: 1,
|
|
157
|
+
subject_type: 1,
|
|
158
|
+
subject_id: 1,
|
|
159
|
+
identity_key: 1,
|
|
160
|
+
createdBy: 1
|
|
161
|
+
};
|
|
134
162
|
var POC_ID_PATTERN = /^poc-[a-z0-9_-]+$/;
|
|
135
163
|
var HEX_24 = /^[0-9a-fA-F]{24}$/;
|
|
136
164
|
var idString = z.string().trim().min(1).max(200);
|
|
@@ -143,6 +171,87 @@ var UrgentMethodsSchema = z.array(
|
|
|
143
171
|
message: "urgent_methods holds selectable CVC-185 preferred_contact_method codes from the Agency Hub subset (email \xB7 call \xB7 text)."
|
|
144
172
|
})
|
|
145
173
|
).max(3).transform((list) => [...new Set(list)]);
|
|
174
|
+
var POC_MAX_CONTACT_ENTRIES = 10;
|
|
175
|
+
var StoredContactEntrySchema = z.object({
|
|
176
|
+
/** An email (lowercased) or a phone as typed (trimmed). */
|
|
177
|
+
value: z.string(),
|
|
178
|
+
/** Exactly one entry of a non-empty list is the preferred one. */
|
|
179
|
+
is_preferred: z.boolean()
|
|
180
|
+
});
|
|
181
|
+
var ReadContactEntrySchema = StoredContactEntrySchema.extend({
|
|
182
|
+
is_preferred: z.boolean().nullish().transform((v) => v === true)
|
|
183
|
+
});
|
|
184
|
+
function pocPhoneDigits(v) {
|
|
185
|
+
const d = v.replace(/\D/g, "");
|
|
186
|
+
return d.length === 11 && d.charAt(0) === "1" ? d.slice(1) : d;
|
|
187
|
+
}
|
|
188
|
+
function formatPocPhone(s) {
|
|
189
|
+
let d = s.replace(/\D/g, "");
|
|
190
|
+
if (!d) return "";
|
|
191
|
+
if (d.length === 11 && d.charAt(0) === "1") d = d.slice(1);
|
|
192
|
+
if (d.length <= 3) return `(${d}`;
|
|
193
|
+
if (d.length <= 6) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
|
|
194
|
+
if (d.length <= 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
|
|
195
|
+
const cc = d.slice(0, d.length - 10);
|
|
196
|
+
const r = d.slice(d.length - 10);
|
|
197
|
+
return `+${cc} (${r.slice(0, 3)}) ${r.slice(3, 6)}-${r.slice(6)}`;
|
|
198
|
+
}
|
|
199
|
+
var emailKey = (v) => v.trim().toLowerCase();
|
|
200
|
+
function settlePreferred(list) {
|
|
201
|
+
const at = list.findIndex((e) => e.is_preferred);
|
|
202
|
+
const keep = at < 0 ? 0 : at;
|
|
203
|
+
return list.map((e, i) => ({ value: e.value, is_preferred: i === keep }));
|
|
204
|
+
}
|
|
205
|
+
function readEntries(list, clean, keyOf) {
|
|
206
|
+
const seen = /* @__PURE__ */ new Set();
|
|
207
|
+
const out = [];
|
|
208
|
+
for (const e of list) {
|
|
209
|
+
const value = clean(e.value);
|
|
210
|
+
const k = value ? keyOf(value) : "";
|
|
211
|
+
if (!k || seen.has(k)) continue;
|
|
212
|
+
seen.add(k);
|
|
213
|
+
out.push({ value, is_preferred: e.is_preferred });
|
|
214
|
+
}
|
|
215
|
+
return settlePreferred(out);
|
|
216
|
+
}
|
|
217
|
+
var StoredEmailListSchema = z.array(ReadContactEntrySchema).transform((l) => readEntries(l, emailKey, (v) => v));
|
|
218
|
+
var StoredPhoneListSchema = z.array(ReadContactEntrySchema).transform((l) => readEntries(l, (v) => v.trim(), pocPhoneDigits));
|
|
219
|
+
function entryListSchema(value, keyOf, noun) {
|
|
220
|
+
return z.array(z.object({ value, is_preferred: z.boolean().optional() }).strict()).max(POC_MAX_CONTACT_ENTRIES).superRefine((list, ctx) => {
|
|
221
|
+
if (list.filter((e) => e.is_preferred === true).length > 1) {
|
|
222
|
+
ctx.addIssue({ code: "custom", message: `A contact has at most one preferred ${noun}.` });
|
|
223
|
+
}
|
|
224
|
+
const seen = /* @__PURE__ */ new Set();
|
|
225
|
+
list.forEach((e, i) => {
|
|
226
|
+
const k = keyOf(e.value);
|
|
227
|
+
if (seen.has(k)) {
|
|
228
|
+
ctx.addIssue({
|
|
229
|
+
code: "custom",
|
|
230
|
+
path: [i, "value"],
|
|
231
|
+
message: `The same ${noun} appears twice on one contact.`
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
seen.add(k);
|
|
235
|
+
});
|
|
236
|
+
}).transform(
|
|
237
|
+
(list) => settlePreferred(list.map((e) => ({ value: e.value, is_preferred: e.is_preferred === true })))
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
var PocEmailListSchema = entryListSchema(PocEmailSchema, (v) => v, "email");
|
|
241
|
+
var PocPhoneValueSchema = text(40).refine((v) => /\d/.test(v), {
|
|
242
|
+
message: "A phone number has at least one digit."
|
|
243
|
+
});
|
|
244
|
+
var PocPhoneListSchema = entryListSchema(PocPhoneValueSchema, pocPhoneDigits, "phone");
|
|
245
|
+
function preferredContactEntry(list) {
|
|
246
|
+
if (!list || list.length === 0) return null;
|
|
247
|
+
return list.find((e) => e.is_preferred) ?? list[0] ?? null;
|
|
248
|
+
}
|
|
249
|
+
function preferredEmail(c) {
|
|
250
|
+
return preferredContactEntry(c.emails)?.value ?? null;
|
|
251
|
+
}
|
|
252
|
+
function preferredPhone(c) {
|
|
253
|
+
return preferredContactEntry(c.phones)?.value ?? null;
|
|
254
|
+
}
|
|
146
255
|
var PocOwnerSchema = z.object({
|
|
147
256
|
subject_type: z.enum(POC_SUBJECT_TYPES),
|
|
148
257
|
subject_id: idString,
|
|
@@ -155,7 +264,7 @@ var PocOwnerSchema = z.object({
|
|
|
155
264
|
if (o.subject_type === "org" && o.subject_id !== o.org_id) {
|
|
156
265
|
ctx.addIssue({ code: "custom", path: ["subject_id"], message: "An org's own contact names that org: subject_id must equal org_id." });
|
|
157
266
|
}
|
|
158
|
-
if ((o.subject_type === "program" || o.subject_type === "team" || o.subject_type === "
|
|
267
|
+
if ((o.subject_type === "program" || o.subject_type === "team" || o.subject_type === "location") && !o.agency_id) {
|
|
159
268
|
ctx.addIssue({ code: "custom", path: ["agency_id"], message: `A ${o.subject_type} contact names the agency it belongs to.` });
|
|
160
269
|
}
|
|
161
270
|
if (o.subject_type === "service" && !o.org_id) {
|
|
@@ -166,8 +275,8 @@ var PocDetailsSchema = z.object({
|
|
|
166
275
|
user_id: PocLinkIdSchema.nullable().optional(),
|
|
167
276
|
person_id: PocLinkIdSchema.nullable().optional(),
|
|
168
277
|
display_name: text(200).nullable().optional(),
|
|
169
|
-
|
|
170
|
-
|
|
278
|
+
emails: PocEmailListSchema.optional(),
|
|
279
|
+
phones: PocPhoneListSchema.optional(),
|
|
171
280
|
purposes: PurposesSchema.optional(),
|
|
172
281
|
urgent_methods: UrgentMethodsSchema.optional(),
|
|
173
282
|
is_primary: z.boolean().optional(),
|
|
@@ -176,8 +285,8 @@ var PocDetailsSchema = z.object({
|
|
|
176
285
|
}).strict();
|
|
177
286
|
var PocInAppSchema = z.object({
|
|
178
287
|
display_name: text(200),
|
|
179
|
-
|
|
180
|
-
|
|
288
|
+
emails: PocEmailListSchema.refine((l) => l.length > 0, { message: "An in-app add names at least one email." }),
|
|
289
|
+
phones: PocPhoneListSchema.optional(),
|
|
181
290
|
purposes: PurposesSchema.default([REFERRALS_MAGIC_LINK_PURPOSE]),
|
|
182
291
|
urgent_methods: UrgentMethodsSchema.optional()
|
|
183
292
|
}).strict();
|
|
@@ -200,9 +309,10 @@ var PointOfContactDocSchema = z.object({
|
|
|
200
309
|
user_id: nullableString,
|
|
201
310
|
person_id: nullableString,
|
|
202
311
|
display_name: nullableString,
|
|
203
|
-
/** Lowercased.
|
|
204
|
-
|
|
205
|
-
|
|
312
|
+
/** Lowercased emails, read leniently. Empty on a seat-linked contact (it resolves from the seat). */
|
|
313
|
+
emails: StoredEmailListSchema,
|
|
314
|
+
/** Read leniently. Empty on a seat-linked contact. */
|
|
315
|
+
phones: StoredPhoneListSchema,
|
|
206
316
|
purposes: z.array(z.enum(CONTACT_PURPOSE_CODES)),
|
|
207
317
|
/** CVC-185 codes. */
|
|
208
318
|
urgent_methods: z.array(z.string()),
|
|
@@ -214,7 +324,7 @@ var PointOfContactDocSchema = z.object({
|
|
|
214
324
|
status: z.enum(POC_STATUSES),
|
|
215
325
|
origin: z.enum(POC_ORIGINS),
|
|
216
326
|
added_in_app: z.enum(POC_ADDED_IN_APPS).nullable(),
|
|
217
|
-
/** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<email>`, lowercased. */
|
|
327
|
+
/** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<preferred email>`, lowercased. */
|
|
218
328
|
identity_key: z.string().min(1),
|
|
219
329
|
confirmed_by: nullableString,
|
|
220
330
|
confirmed_at: nullableString,
|
|
@@ -233,7 +343,7 @@ function pocRuleViolations(c) {
|
|
|
233
343
|
if (c.user_id && c.person_id) {
|
|
234
344
|
out.push({ reason: "user_id_xor_person_id", message: "A contact points at a seat (user_id) or a person (person_id), never both." });
|
|
235
345
|
}
|
|
236
|
-
if (seat && (c.
|
|
346
|
+
if (seat && (c.emails.length > 0 || c.phones.length > 0)) {
|
|
237
347
|
out.push({
|
|
238
348
|
reason: "seat_contact_has_own_reach",
|
|
239
349
|
message: "A seat-linked contact stores no email or phone of its own; they resolve from the seat."
|
|
@@ -242,7 +352,7 @@ function pocRuleViolations(c) {
|
|
|
242
352
|
if (!seat && !c.display_name) {
|
|
243
353
|
out.push({ reason: "display_name_required", message: "A contact that holds no seat needs a display_name." });
|
|
244
354
|
}
|
|
245
|
-
if (!seat && c.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE) &&
|
|
355
|
+
if (!seat && c.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE) && c.emails.length === 0) {
|
|
246
356
|
out.push({
|
|
247
357
|
reason: "referral_contact_needs_email",
|
|
248
358
|
message: "A contact tagged Referrals (magic link) must have an email."
|
|
@@ -254,7 +364,7 @@ function pocIdentityKey(c) {
|
|
|
254
364
|
const norm = (v) => (v ?? "").trim().toLowerCase();
|
|
255
365
|
if (c.user_id) return `seat:${norm(c.user_id)}`;
|
|
256
366
|
if (c.person_id) return `person:${norm(c.person_id)}`;
|
|
257
|
-
return `writein:${norm(c.display_name)}|${norm(c
|
|
367
|
+
return `writein:${norm(c.display_name)}|${norm(preferredEmail(c))}`;
|
|
258
368
|
}
|
|
259
369
|
|
|
260
370
|
// src/pointsOfContact/readRules.ts
|
|
@@ -279,12 +389,29 @@ function normalizePointOfContact(raw) {
|
|
|
279
389
|
function isNetworkVisible(d) {
|
|
280
390
|
return d.active && d.status === "confirmed" && !d.is_confidential;
|
|
281
391
|
}
|
|
392
|
+
var copyEntries = (list) => list.map((e) => ({ ...e }));
|
|
393
|
+
function reachOf(d, seat) {
|
|
394
|
+
if (!d.user_id) return { emails: copyEntries(d.emails), phones: copyEntries(d.phones) };
|
|
395
|
+
const one = (v) => v ? [{ value: v, is_preferred: true }] : [];
|
|
396
|
+
return {
|
|
397
|
+
emails: one(seat?.email?.trim().toLowerCase()),
|
|
398
|
+
phones: one(seat?.phone?.trim())
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
var preferredValue = (list) => preferredContactEntry(list)?.value ?? null;
|
|
282
402
|
function toStewardView(d, seat) {
|
|
283
403
|
const { identity_key: _internal, ...rest } = d;
|
|
404
|
+
const reach = reachOf(d, seat);
|
|
284
405
|
return {
|
|
285
406
|
...rest,
|
|
407
|
+
emails: copyEntries(d.emails),
|
|
408
|
+
phones: copyEntries(d.phones),
|
|
409
|
+
purposes: [...d.purposes],
|
|
410
|
+
urgent_methods: [...d.urgent_methods],
|
|
286
411
|
purpose_labels: d.purposes.map(contactPurposeLabel),
|
|
287
|
-
seat: d.user_id ? seat ?? null : null
|
|
412
|
+
seat: d.user_id ? seat ?? null : null,
|
|
413
|
+
email: preferredValue(reach.emails),
|
|
414
|
+
phone: preferredValue(reach.phones)
|
|
288
415
|
};
|
|
289
416
|
}
|
|
290
417
|
function toOwnerView(d, seat) {
|
|
@@ -301,6 +428,7 @@ function toOwnerView(d, seat) {
|
|
|
301
428
|
function toNetworkView(d, seat) {
|
|
302
429
|
if (!isNetworkVisible(d)) return null;
|
|
303
430
|
const seatLinked = !!d.user_id;
|
|
431
|
+
const { emails, phones } = reachOf(d, seat);
|
|
304
432
|
return {
|
|
305
433
|
id: d.id,
|
|
306
434
|
subject_type: d.subject_type,
|
|
@@ -308,11 +436,13 @@ function toNetworkView(d, seat) {
|
|
|
308
436
|
agency_id: d.agency_id,
|
|
309
437
|
org_id: d.org_id,
|
|
310
438
|
display_name: d.display_name ?? (seatLinked ? seat?.name ?? null : null),
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
439
|
+
emails,
|
|
440
|
+
phones,
|
|
441
|
+
email: preferredValue(emails),
|
|
442
|
+
phone: preferredValue(phones),
|
|
443
|
+
purposes: [...d.purposes],
|
|
314
444
|
purpose_labels: d.purposes.map(contactPurposeLabel),
|
|
315
|
-
urgent_methods: d.urgent_methods,
|
|
445
|
+
urgent_methods: [...d.urgent_methods],
|
|
316
446
|
is_primary: d.is_primary,
|
|
317
447
|
updatedAt: d.updatedAt
|
|
318
448
|
};
|
|
@@ -322,7 +452,7 @@ var SUBJECT_ORDER = {
|
|
|
322
452
|
org: 1,
|
|
323
453
|
program: 2,
|
|
324
454
|
team: 3,
|
|
325
|
-
|
|
455
|
+
location: 4,
|
|
326
456
|
service: 5
|
|
327
457
|
};
|
|
328
458
|
function byContactReadingOrder(a, b) {
|
|
@@ -334,7 +464,7 @@ function subjectFilter(subject) {
|
|
|
334
464
|
const type = requireId("subject_type", subject.subject_type);
|
|
335
465
|
const base = { subject_type: type, subject_id: requireId("subject_id", subject.subject_id) };
|
|
336
466
|
const agency = subject.agency_id;
|
|
337
|
-
if (type === "program" || type === "team" || type === "
|
|
467
|
+
if (type === "program" || type === "team" || type === "location") {
|
|
338
468
|
return { ...base, agency_id: requireId("agency_id", agency) };
|
|
339
469
|
}
|
|
340
470
|
if (type === "service" && agency === void 0) {
|
|
@@ -379,6 +509,7 @@ async function listReferralContactsForPartner(db, partner, opts) {
|
|
|
379
509
|
keys.push({ org_id: requireId("org_id", partner.org_id) });
|
|
380
510
|
}
|
|
381
511
|
if (keys.length === 0) throw new TypeError("points-of-contact: select a partner by agency_id, org_id or both");
|
|
512
|
+
const pendingFor = opts.includeOwnPendingFor === void 0 ? null : requireId("includeOwnPendingFor", opts.includeOwnPendingFor);
|
|
382
513
|
const docs = await findDocs(db, {
|
|
383
514
|
$or: keys,
|
|
384
515
|
purposes: REFERRALS_MAGIC_LINK_PURPOSE,
|
|
@@ -399,8 +530,31 @@ async function listReferralContactsForPartner(db, partner, opts) {
|
|
|
399
530
|
seen.add(email);
|
|
400
531
|
recipients.push({ ...v, email });
|
|
401
532
|
}
|
|
533
|
+
if (pendingFor !== null) {
|
|
534
|
+
const pending = await findDocs(db, {
|
|
535
|
+
$or: keys,
|
|
536
|
+
purposes: REFERRALS_MAGIC_LINK_PURPOSE,
|
|
537
|
+
...OWN_PENDING_IN_APP,
|
|
538
|
+
createdBy: pendingFor
|
|
539
|
+
});
|
|
540
|
+
for (const d of pending) {
|
|
541
|
+
if (!isOwnPendingInApp(d, pendingFor)) continue;
|
|
542
|
+
const v = toNetworkView({ ...d, status: "confirmed" });
|
|
543
|
+
const email = v?.email;
|
|
544
|
+
if (!v || !email || seen.has(email)) continue;
|
|
545
|
+
seen.add(email);
|
|
546
|
+
recipients.push({ ...v, email, pending: true });
|
|
547
|
+
}
|
|
548
|
+
}
|
|
402
549
|
return { recipients, unreachable };
|
|
403
550
|
}
|
|
551
|
+
var OWN_PENDING_IN_APP = {
|
|
552
|
+
active: true,
|
|
553
|
+
status: "pending",
|
|
554
|
+
origin: "in_app",
|
|
555
|
+
is_confidential: { $ne: true }
|
|
556
|
+
};
|
|
557
|
+
var isOwnPendingInApp = (d, sub) => d.active && d.status === "pending" && d.origin === "in_app" && !d.is_confidential && !d.user_id && d.createdBy === sub && d.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE);
|
|
404
558
|
async function getContact(db, id, opts = {}) {
|
|
405
559
|
const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).findOne({ id: requireId("id", id) });
|
|
406
560
|
if (!raw) return null;
|
|
@@ -420,33 +574,649 @@ async function listPendingContacts(db, opts = {}) {
|
|
|
420
574
|
const seats = await seatsFor(docs, opts.resolveSeats);
|
|
421
575
|
return docs.map((d) => toStewardView(d, seatOf(d, seats)));
|
|
422
576
|
}
|
|
577
|
+
|
|
578
|
+
// src/pointsOfContact/writer.ts
|
|
579
|
+
import { z as z3 } from "zod";
|
|
580
|
+
|
|
581
|
+
// src/orgDirectory/schemas.ts
|
|
582
|
+
import { z as z2 } from "zod";
|
|
583
|
+
|
|
584
|
+
// src/orgDirectory/vocabulary.ts
|
|
585
|
+
var PROGRAM_REVIEW_STATUS = {
|
|
586
|
+
PENDING: "pending",
|
|
587
|
+
CONFIRMED: "confirmed",
|
|
588
|
+
REJECTED: "rejected"
|
|
589
|
+
};
|
|
590
|
+
var PROGRAM_REVIEW_STATUS_VALUES = Object.freeze([
|
|
591
|
+
PROGRAM_REVIEW_STATUS.PENDING,
|
|
592
|
+
PROGRAM_REVIEW_STATUS.CONFIRMED,
|
|
593
|
+
PROGRAM_REVIEW_STATUS.REJECTED
|
|
594
|
+
]);
|
|
595
|
+
var PROGRAM_STATUS = {
|
|
596
|
+
ACTIVE: "active",
|
|
597
|
+
RETIRED: "retired"
|
|
598
|
+
};
|
|
599
|
+
var PROGRAM_STATUS_VALUES = Object.freeze([
|
|
600
|
+
PROGRAM_STATUS.ACTIVE,
|
|
601
|
+
PROGRAM_STATUS.RETIRED
|
|
602
|
+
]);
|
|
603
|
+
function isLiveOrganizationProgram(row) {
|
|
604
|
+
return row.status !== PROGRAM_STATUS.RETIRED && row.reviewStatus !== PROGRAM_REVIEW_STATUS.REJECTED;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// src/orgDirectory/schemas.ts
|
|
608
|
+
var ORGANIZATION_PROGRAM_ROW_KEYS = Object.freeze([
|
|
609
|
+
"programId",
|
|
610
|
+
"name",
|
|
611
|
+
"description",
|
|
612
|
+
"status",
|
|
613
|
+
"defaultSharingPolicy",
|
|
614
|
+
"reviewStatus",
|
|
615
|
+
"addedBy",
|
|
616
|
+
"addedInApp",
|
|
617
|
+
"addedInSession"
|
|
618
|
+
]);
|
|
619
|
+
var optionalText = z2.string().nullish();
|
|
620
|
+
var OrganizationProgramRowSchema = z2.object({
|
|
621
|
+
programId: z2.string().min(1),
|
|
622
|
+
name: z2.string().min(1),
|
|
623
|
+
description: optionalText,
|
|
624
|
+
status: optionalText,
|
|
625
|
+
defaultSharingPolicy: optionalText,
|
|
626
|
+
reviewStatus: z2.enum(PROGRAM_REVIEW_STATUS_VALUES).nullish(),
|
|
627
|
+
addedBy: optionalText,
|
|
628
|
+
addedInApp: optionalText,
|
|
629
|
+
addedInSession: optionalText
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
// src/orgDirectory/rules.ts
|
|
633
|
+
function directoryIdString(value) {
|
|
634
|
+
if (typeof value === "string") return value === "" ? null : value;
|
|
635
|
+
if (value && typeof value === "object" && typeof value.toHexString === "function") {
|
|
636
|
+
return value.toHexString();
|
|
637
|
+
}
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
function sameDirectoryId(a, b) {
|
|
641
|
+
const x = directoryIdString(a);
|
|
642
|
+
const y = directoryIdString(b);
|
|
643
|
+
return x !== null && y !== null && x.toLowerCase() === y.toLowerCase();
|
|
644
|
+
}
|
|
645
|
+
function organizationRowShape(raw) {
|
|
646
|
+
if (!raw || typeof raw !== "object") return "unknown";
|
|
647
|
+
const r = raw;
|
|
648
|
+
if (typeof r.canonicalKey === "string" && r.canonicalKey !== "") return "canonical";
|
|
649
|
+
if (typeof r.id === "string" || typeof r.type === "string" || "acronym" in r || "location" in r)
|
|
650
|
+
return "pave";
|
|
651
|
+
if (typeof r.type === "number") return "thread";
|
|
652
|
+
return "unknown";
|
|
653
|
+
}
|
|
654
|
+
function isAgencyOwnOrganization(org, agency) {
|
|
655
|
+
if (!org || !agency) return false;
|
|
656
|
+
return sameDirectoryId(org.agencyId, agency._id) && sameDirectoryId(agency.organizationId, org._id);
|
|
657
|
+
}
|
|
658
|
+
function toDirectoryProgramView(raw) {
|
|
659
|
+
const parsed = OrganizationProgramRowSchema.safeParse(raw);
|
|
660
|
+
if (!parsed.success) return null;
|
|
661
|
+
const p = parsed.data;
|
|
662
|
+
return {
|
|
663
|
+
programId: p.programId,
|
|
664
|
+
name: p.name,
|
|
665
|
+
description: p.description ?? null,
|
|
666
|
+
status: p.status ?? null,
|
|
667
|
+
reviewStatus: p.reviewStatus ?? null,
|
|
668
|
+
addedBy: p.addedBy ?? null,
|
|
669
|
+
addedInApp: p.addedInApp ?? null,
|
|
670
|
+
live: isLiveOrganizationProgram(p)
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
var text2 = (v) => typeof v === "string" && v !== "" ? v : null;
|
|
674
|
+
function toDirectoryOrganizationView(raw) {
|
|
675
|
+
if (!raw || typeof raw !== "object") return null;
|
|
676
|
+
const r = raw;
|
|
677
|
+
const id = directoryIdString(r._id);
|
|
678
|
+
if (!id) return null;
|
|
679
|
+
const rows = Array.isArray(r.programs) ? r.programs : [];
|
|
680
|
+
const programs = rows.map(toDirectoryProgramView).filter((p) => p !== null);
|
|
681
|
+
return {
|
|
682
|
+
id,
|
|
683
|
+
shape: organizationRowShape(r),
|
|
684
|
+
name: text2(r.name) ?? "",
|
|
685
|
+
type: typeof r.type === "number" ? r.type : null,
|
|
686
|
+
typeKey: typeof r.type === "string" ? r.type : null,
|
|
687
|
+
paveId: text2(r.id),
|
|
688
|
+
community: text2(r.community),
|
|
689
|
+
agencyId: directoryIdString(r.agencyId),
|
|
690
|
+
agencyScope: directoryIdString(r.agencyScope),
|
|
691
|
+
canonicalKey: text2(r.canonicalKey),
|
|
692
|
+
programs,
|
|
693
|
+
invalidPrograms: rows.length - programs.length
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// src/orgDirectory/read.ts
|
|
698
|
+
var ORGANIZATIONS_COLLECTION = "organizations";
|
|
699
|
+
var AGENCIES_COLLECTION = "agencies";
|
|
700
|
+
var HEX = /^[0-9a-fA-F]{24}$/;
|
|
701
|
+
function organizationIdForms(id, opts = {}) {
|
|
702
|
+
if (typeof id !== "string") return [id.toHexString(), id];
|
|
703
|
+
return HEX.test(id) && opts.toObjectId ? [id, opts.toObjectId(id.toLowerCase())] : [id];
|
|
704
|
+
}
|
|
705
|
+
async function readDirectoryOrganization(db, id, opts = {}) {
|
|
706
|
+
const raw = await db.collection(ORGANIZATIONS_COLLECTION).findOne({ _id: { $in: organizationIdForms(id, opts) } });
|
|
707
|
+
return raw ? toDirectoryOrganizationView(raw) : null;
|
|
708
|
+
}
|
|
709
|
+
async function readAgencyOwnOrganization(db, agencyId, opts = {}) {
|
|
710
|
+
const agency = await db.collection(AGENCIES_COLLECTION).findOne(
|
|
711
|
+
{ _id: { $in: organizationIdForms(agencyId, opts) } },
|
|
712
|
+
{ projection: { _id: 1, organizationId: 1 } }
|
|
713
|
+
);
|
|
714
|
+
if (!agency || agency.organizationId == null) return null;
|
|
715
|
+
const pointer = agency.organizationId;
|
|
716
|
+
const org = await db.collection(ORGANIZATIONS_COLLECTION).findOne({ _id: { $in: organizationIdForms(pointer, opts) } });
|
|
717
|
+
return org && isAgencyOwnOrganization(org, agency) ? toDirectoryOrganizationView(org) : null;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// src/pointsOfContact/writer.ts
|
|
721
|
+
var POC_PARTNER_ADD_APPS = POC_ADDED_IN_APPS.filter(
|
|
722
|
+
(a) => a !== "platform"
|
|
723
|
+
);
|
|
724
|
+
var directoryId = z3.string().trim().min(1).max(200);
|
|
725
|
+
var PartnerContactSelectorSchema = z3.object({ agency_id: directoryId.optional(), org_id: directoryId.optional() }).strict().refine((p) => Boolean(p.agency_id || p.org_id), {
|
|
726
|
+
message: "Name the partner's agency_id or org_id."
|
|
727
|
+
});
|
|
728
|
+
var POC_IN_APP_PENDING_CAP_PER_ACTOR = 25;
|
|
729
|
+
var POC_IN_APP_PENDING_CAP_PER_PARTNER = 5;
|
|
730
|
+
var POC_IN_APP_PENDING_INDEX = POINT_OF_CONTACT_INDEXES.inAppPending;
|
|
731
|
+
var POC_PENDING_QUEUE_INDEX = POINT_OF_CONTACT_INDEXES.pendingQueue;
|
|
732
|
+
var indexRuns = /* @__PURE__ */ new WeakMap();
|
|
733
|
+
function ensurePocIndexes(db) {
|
|
734
|
+
const memo = indexRuns.get(db);
|
|
735
|
+
if (memo) return memo;
|
|
736
|
+
const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
|
|
737
|
+
const ix = POINT_OF_CONTACT_INDEXES;
|
|
738
|
+
const run = (async () => {
|
|
739
|
+
await coll.createIndex({ id: 1 }, { name: ix.id, unique: true });
|
|
740
|
+
await coll.createIndex({ subject_type: 1, subject_id: 1, active: 1 }, { name: ix.subject });
|
|
741
|
+
await coll.createIndex({ agency_id: 1, purposes: 1, active: 1 }, { name: ix.agencyPurpose });
|
|
742
|
+
await coll.createIndex({ org_id: 1, purposes: 1, active: 1 }, { name: ix.orgPurpose });
|
|
743
|
+
await coll.createIndex({ status: 1 }, { name: ix.status });
|
|
744
|
+
await coll.createIndex(
|
|
745
|
+
{ agency_id: 1, subject_type: 1, subject_id: 1, identity_key: 1 },
|
|
746
|
+
{
|
|
747
|
+
name: ix.identity,
|
|
748
|
+
unique: true,
|
|
749
|
+
partialFilterExpression: { ...POC_IDENTITY_INDEX_FILTER }
|
|
750
|
+
}
|
|
751
|
+
);
|
|
752
|
+
await coll.createIndex(
|
|
753
|
+
{ agency_id: 1, subject_type: 1, subject_id: 1 },
|
|
754
|
+
{ name: ix.primary, unique: true, partialFilterExpression: { ...POC_PRIMARY_INDEX_FILTER } }
|
|
755
|
+
);
|
|
756
|
+
await coll.createIndex(
|
|
757
|
+
{ ...POC_IN_APP_PENDING_INDEX_KEY },
|
|
758
|
+
{
|
|
759
|
+
name: POC_IN_APP_PENDING_INDEX,
|
|
760
|
+
unique: true,
|
|
761
|
+
partialFilterExpression: { ...POC_IN_APP_PENDING_INDEX_FILTER }
|
|
762
|
+
}
|
|
763
|
+
);
|
|
764
|
+
await coll.createIndex({ status: 1, createdAt: 1, id: 1 }, { name: POC_PENDING_QUEUE_INDEX });
|
|
765
|
+
})().catch((err) => {
|
|
766
|
+
indexRuns.delete(db);
|
|
767
|
+
throw err;
|
|
768
|
+
});
|
|
769
|
+
indexRuns.set(db, run);
|
|
770
|
+
return run;
|
|
771
|
+
}
|
|
772
|
+
var indexesChecked = /* @__PURE__ */ new WeakMap();
|
|
773
|
+
var codeOf = (err) => err && typeof err === "object" ? err.code : void 0;
|
|
774
|
+
var NAMESPACE_NOT_FOUND = 26;
|
|
775
|
+
var sameKey = (got, want) => {
|
|
776
|
+
if (!got || typeof got !== "object") return false;
|
|
777
|
+
const g = Object.entries(got);
|
|
778
|
+
const w = Object.entries(want);
|
|
779
|
+
return g.length === w.length && w.every(([k, v], i) => g[i][0] === k && Number(g[i][1]) === v);
|
|
780
|
+
};
|
|
781
|
+
var sameFilter = (got, want) => {
|
|
782
|
+
if (!want) return got === void 0 || got === null;
|
|
783
|
+
if (!got || typeof got !== "object") return false;
|
|
784
|
+
const sorted = (o) => JSON.stringify(Object.entries(o).sort(([a], [b]) => a < b ? -1 : 1));
|
|
785
|
+
return sorted(got) === sorted(want);
|
|
786
|
+
};
|
|
787
|
+
var REQUIRED_INDEXES = [
|
|
788
|
+
{ key: { id: 1 } },
|
|
789
|
+
{ key: { ...POC_IN_APP_PENDING_INDEX_KEY }, filter: { ...POC_IN_APP_PENDING_INDEX_FILTER } }
|
|
790
|
+
];
|
|
791
|
+
async function checkPocIndexes(db) {
|
|
792
|
+
if (indexesChecked.has(db)) return null;
|
|
793
|
+
let listed;
|
|
794
|
+
try {
|
|
795
|
+
listed = await db.collection(POINTS_OF_CONTACT_COLLECTION).indexes();
|
|
796
|
+
} catch (err) {
|
|
797
|
+
if (codeOf(err) === NAMESPACE_NOT_FOUND) return INDEXES_MISSING;
|
|
798
|
+
throw err;
|
|
799
|
+
}
|
|
800
|
+
const present = REQUIRED_INDEXES.every(
|
|
801
|
+
(want) => listed.some(
|
|
802
|
+
(ix) => ix.unique === true && sameKey(ix.key, want.key) && sameFilter(ix.partialFilterExpression, want.filter)
|
|
803
|
+
)
|
|
804
|
+
);
|
|
805
|
+
if (!present) return INDEXES_MISSING;
|
|
806
|
+
indexesChecked.set(db, true);
|
|
807
|
+
return null;
|
|
808
|
+
}
|
|
809
|
+
var PARTNER_CONTACT_FAILURE_REASONS = [
|
|
810
|
+
"actor_required",
|
|
811
|
+
"invalid_app",
|
|
812
|
+
"invalid_contact",
|
|
813
|
+
"invalid_partner",
|
|
814
|
+
"owner_not_found",
|
|
815
|
+
"owner_mismatch",
|
|
816
|
+
"canonical_org",
|
|
817
|
+
"foreign_row_shape",
|
|
818
|
+
"contact_deactivated",
|
|
819
|
+
"too_many_pending_adds",
|
|
820
|
+
"duplicate_pending_add",
|
|
821
|
+
"duplicate_contact",
|
|
822
|
+
"primary_exists",
|
|
823
|
+
"duplicate_contact_id",
|
|
824
|
+
"duplicate_key",
|
|
825
|
+
"user_id_xor_person_id",
|
|
826
|
+
"seat_contact_has_own_reach",
|
|
827
|
+
"display_name_required",
|
|
828
|
+
"referral_contact_needs_email",
|
|
829
|
+
"indexes_missing"
|
|
830
|
+
];
|
|
831
|
+
function fail(status, reason, message) {
|
|
832
|
+
return { ok: false, status, reason, ...message ? { message } : {} };
|
|
833
|
+
}
|
|
834
|
+
var INDEXES_MISSING = fail(
|
|
835
|
+
503,
|
|
836
|
+
"indexes_missing",
|
|
837
|
+
"The points-of-contact indexes are not in place; the platform must create them (ensurePocIndexes) before an app writes."
|
|
838
|
+
);
|
|
839
|
+
var isFailure = (v) => !!v && typeof v === "object" && v.ok === false;
|
|
840
|
+
function invalid(err, reason) {
|
|
841
|
+
const issues = err.issues.map((i) => `${i.path.map(String).join(".") || "(body)"}: ${i.message}`);
|
|
842
|
+
return fail(400, reason, issues.join("; "));
|
|
843
|
+
}
|
|
844
|
+
var HEX_242 = /^[0-9a-fA-F]{24}$/;
|
|
845
|
+
var canonicalId = (v) => HEX_242.test(v) ? v.toLowerCase() : v;
|
|
846
|
+
var idOf = (v) => v === null || v === void 0 || v === "" ? null : String(v);
|
|
847
|
+
function idsOf(driver) {
|
|
848
|
+
const { ObjectId } = driver;
|
|
849
|
+
return {
|
|
850
|
+
forms: (value) => HEX_242.test(value) ? [value, new ObjectId(value)] : [value],
|
|
851
|
+
read: { toObjectId: (hex) => new ObjectId(hex) },
|
|
852
|
+
newId: () => `poc-${new ObjectId().toHexString()}`
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
var REGISTRY_AGENCIES_COLLECTION = "registry_agencies";
|
|
856
|
+
var AGENCY_PROJECTION = { projection: { _id: 1, entity_id: 1, id: 1 } };
|
|
857
|
+
function formsOf(row) {
|
|
858
|
+
const out = [];
|
|
859
|
+
if (typeof row.entity_id === "string" && row.entity_id !== "") out.push(row.entity_id);
|
|
860
|
+
if (typeof row.id === "string" && row.id !== "") out.push(row.id);
|
|
861
|
+
if (row._id !== void 0 && row._id !== null) out.push(String(row._id));
|
|
862
|
+
return [...new Set(out)];
|
|
863
|
+
}
|
|
864
|
+
var agencyIdFilter = (ids, agencyId) => ({
|
|
865
|
+
$or: [{ entity_id: agencyId }, { id: agencyId }, { _id: { $in: ids.forms(agencyId) } }]
|
|
866
|
+
});
|
|
867
|
+
function resolveRecipient(form, agencies, registry) {
|
|
868
|
+
const direct = agencies.find((a) => formsOf(a).includes(form));
|
|
869
|
+
if (direct) return String(direct._id);
|
|
870
|
+
const reg = registry.find((r) => formsOf(r).includes(form));
|
|
871
|
+
if (!reg) return null;
|
|
872
|
+
const regForms = formsOf(reg);
|
|
873
|
+
const mapped = agencies.find((a) => formsOf(a).some((f) => regForms.includes(f)));
|
|
874
|
+
return mapped ? String(mapped._id) : null;
|
|
875
|
+
}
|
|
876
|
+
async function resolveAgencyId(db, ids, form) {
|
|
877
|
+
const agencies = db.collection(AGENCIES_COLLECTION);
|
|
878
|
+
const direct = await agencies.find(agencyIdFilter(ids, form), AGENCY_PROJECTION).toArray();
|
|
879
|
+
if (direct.length > 0) return resolveRecipient(form, direct, []);
|
|
880
|
+
const registry = await db.collection(REGISTRY_AGENCIES_COLLECTION).find(agencyIdFilter(ids, form), AGENCY_PROJECTION).toArray();
|
|
881
|
+
if (registry.length === 0) return null;
|
|
882
|
+
const regForms = formsOf(registry[0]);
|
|
883
|
+
const mapped = await agencies.find({ $or: regForms.map((f) => agencyIdFilter(ids, f)) }, AGENCY_PROJECTION).toArray();
|
|
884
|
+
return resolveRecipient(form, mapped, registry);
|
|
885
|
+
}
|
|
886
|
+
async function agencyKey(db, ids, form) {
|
|
887
|
+
const id = await resolveAgencyId(db, ids, canonicalId(form));
|
|
888
|
+
return id ? canonicalId(id) : null;
|
|
889
|
+
}
|
|
890
|
+
var OWNER_NOT_FOUND = fail(
|
|
891
|
+
400,
|
|
892
|
+
"owner_not_found",
|
|
893
|
+
"The contact's owner does not resolve to a platform agency or organization."
|
|
894
|
+
);
|
|
895
|
+
var OWNER_MISMATCH = fail(
|
|
896
|
+
400,
|
|
897
|
+
"owner_mismatch",
|
|
898
|
+
"The agency and organization named are not the same partner."
|
|
899
|
+
);
|
|
900
|
+
async function genuineMirrorAgency(db, ids, org) {
|
|
901
|
+
const declared = idOf(org.agencyId);
|
|
902
|
+
if (!declared) return null;
|
|
903
|
+
const agency = await db.collection(AGENCIES_COLLECTION).findOne(
|
|
904
|
+
{ _id: { $in: ids.forms(canonicalId(declared)) } },
|
|
905
|
+
{ projection: { _id: 1, organizationId: 1 } }
|
|
906
|
+
);
|
|
907
|
+
if (!agency || !isAgencyOwnOrganization(org, agency)) return null;
|
|
908
|
+
return agencyKey(db, ids, String(agency._id));
|
|
909
|
+
}
|
|
910
|
+
async function resolvePartnerOwner(db, ids, p) {
|
|
911
|
+
let agencyId = null;
|
|
912
|
+
if (p.agency_id) {
|
|
913
|
+
agencyId = await agencyKey(db, ids, p.agency_id);
|
|
914
|
+
if (!agencyId) return OWNER_NOT_FOUND;
|
|
915
|
+
}
|
|
916
|
+
let org = null;
|
|
917
|
+
if (p.org_id) {
|
|
918
|
+
org = await db.collection(ORGANIZATIONS_COLLECTION).findOne(
|
|
919
|
+
{ _id: { $in: ids.forms(canonicalId(p.org_id)) } },
|
|
920
|
+
{ projection: { _id: 1, agencyId: 1 } }
|
|
921
|
+
);
|
|
922
|
+
if (!org) return OWNER_NOT_FOUND;
|
|
923
|
+
}
|
|
924
|
+
const orgId = org ? canonicalId(String(org._id)) : null;
|
|
925
|
+
if (!agencyId) {
|
|
926
|
+
if (!org || !orgId) return OWNER_NOT_FOUND;
|
|
927
|
+
const mirrorAgency = await genuineMirrorAgency(db, ids, org);
|
|
928
|
+
if (mirrorAgency) {
|
|
929
|
+
return {
|
|
930
|
+
subject_type: "agency",
|
|
931
|
+
subject_id: mirrorAgency,
|
|
932
|
+
agency_id: mirrorAgency,
|
|
933
|
+
org_id: orgId
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
return { subject_type: "org", subject_id: orgId, agency_id: null, org_id: orgId };
|
|
937
|
+
}
|
|
938
|
+
const own = await readAgencyOwnOrganization(db, agencyId, ids.read);
|
|
939
|
+
const mirrorOrg = own ? canonicalId(own.id) : null;
|
|
940
|
+
if (orgId && orgId !== mirrorOrg) return OWNER_MISMATCH;
|
|
941
|
+
return { subject_type: "agency", subject_id: agencyId, agency_id: agencyId, org_id: mirrorOrg };
|
|
942
|
+
}
|
|
943
|
+
async function refuseForeignPartnerOrg(db, ids, orgId) {
|
|
944
|
+
if (!orgId) return null;
|
|
945
|
+
const org = await readDirectoryOrganization(db, orgId, ids.read);
|
|
946
|
+
if (org?.shape === "canonical") {
|
|
947
|
+
return fail(409, "canonical_org", "A canonical singleton organization is not a partner.");
|
|
948
|
+
}
|
|
949
|
+
if (org?.shape === "pave") {
|
|
950
|
+
return fail(
|
|
951
|
+
409,
|
|
952
|
+
"foreign_row_shape",
|
|
953
|
+
"This organization is a PAVE 2.0-shape row; an in-app contact is not added to it."
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
return null;
|
|
957
|
+
}
|
|
958
|
+
async function pocRowsWithIdentity(db, owner, identityKey) {
|
|
959
|
+
const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).find({
|
|
960
|
+
agency_id: owner.agency_id,
|
|
961
|
+
subject_type: owner.subject_type,
|
|
962
|
+
subject_id: owner.subject_id,
|
|
963
|
+
identity_key: identityKey
|
|
964
|
+
}).toArray();
|
|
965
|
+
return raw.map((r) => normalizePointOfContact(r)).filter((d) => d.identity_key === identityKey);
|
|
966
|
+
}
|
|
967
|
+
var identityOf = (body) => pocIdentityKey({
|
|
968
|
+
user_id: null,
|
|
969
|
+
person_id: null,
|
|
970
|
+
display_name: body.display_name,
|
|
971
|
+
emails: body.emails
|
|
972
|
+
});
|
|
973
|
+
var ownInApp = (d, actorId) => d.origin === "in_app" && d.createdBy === actorId;
|
|
974
|
+
function classifyExisting(rows, body, actorId) {
|
|
975
|
+
const visible = rows.find(
|
|
976
|
+
(d) => d.active && d.status === "confirmed" && !d.is_confidential && body.purposes.every((p) => d.purposes.includes(p))
|
|
977
|
+
);
|
|
978
|
+
if (visible) return { kind: "visible", doc: visible };
|
|
979
|
+
const pending = rows.find((d) => d.active && d.status === "pending" && ownInApp(d, actorId));
|
|
980
|
+
if (pending) return { kind: "own_pending", doc: pending };
|
|
981
|
+
const removed = rows.find((d) => !d.active && ownInApp(d, actorId));
|
|
982
|
+
if (removed) return { kind: "own_deactivated", doc: removed };
|
|
983
|
+
return null;
|
|
984
|
+
}
|
|
985
|
+
function pendingCaps(owner, actorId) {
|
|
986
|
+
const mine = { createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER };
|
|
987
|
+
return [
|
|
988
|
+
{
|
|
989
|
+
filter: {
|
|
990
|
+
...mine,
|
|
991
|
+
agency_id: owner.agency_id,
|
|
992
|
+
subject_type: owner.subject_type,
|
|
993
|
+
subject_id: owner.subject_id
|
|
994
|
+
},
|
|
995
|
+
cap: POC_IN_APP_PENDING_CAP_PER_PARTNER,
|
|
996
|
+
refusal: fail(
|
|
997
|
+
429,
|
|
998
|
+
"too_many_pending_adds",
|
|
999
|
+
`At most ${POC_IN_APP_PENDING_CAP_PER_PARTNER} contacts you added to one partner can wait for HTI Labs at a time.`
|
|
1000
|
+
)
|
|
1001
|
+
},
|
|
1002
|
+
{
|
|
1003
|
+
filter: mine,
|
|
1004
|
+
cap: POC_IN_APP_PENDING_CAP_PER_ACTOR,
|
|
1005
|
+
refusal: fail(
|
|
1006
|
+
429,
|
|
1007
|
+
"too_many_pending_adds",
|
|
1008
|
+
`At most ${POC_IN_APP_PENDING_CAP_PER_ACTOR} contacts you added can wait for HTI Labs at a time.`
|
|
1009
|
+
)
|
|
1010
|
+
}
|
|
1011
|
+
];
|
|
1012
|
+
}
|
|
1013
|
+
async function checkPendingCaps(db, owner, actorId) {
|
|
1014
|
+
const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
|
|
1015
|
+
for (const c of pendingCaps(owner, actorId)) {
|
|
1016
|
+
if (await coll.countDocuments(c.filter) >= c.cap) return c.refusal;
|
|
1017
|
+
}
|
|
1018
|
+
return null;
|
|
1019
|
+
}
|
|
1020
|
+
async function overCapAfterInsert(db, owner, actorId, id) {
|
|
1021
|
+
const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
|
|
1022
|
+
for (const c of pendingCaps(owner, actorId)) {
|
|
1023
|
+
if (await coll.countDocuments(c.filter) > c.cap) {
|
|
1024
|
+
await coll.deleteOne({ id, createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER });
|
|
1025
|
+
return c.refusal;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
return null;
|
|
1029
|
+
}
|
|
1030
|
+
function pocDuplicateKeyFailure(err) {
|
|
1031
|
+
if (!err || typeof err !== "object") return null;
|
|
1032
|
+
const e = err;
|
|
1033
|
+
const msg = typeof e.message === "string" ? e.message : "";
|
|
1034
|
+
if (e.code !== 11e3 && !/E11000/.test(msg)) return null;
|
|
1035
|
+
const ix = POINT_OF_CONTACT_INDEXES;
|
|
1036
|
+
const keys = Object.keys(e.keyPattern ?? {}).join(",");
|
|
1037
|
+
if (msg.includes(POC_IN_APP_PENDING_INDEX) || keys.includes("createdBy")) {
|
|
1038
|
+
return fail(
|
|
1039
|
+
409,
|
|
1040
|
+
"duplicate_pending_add",
|
|
1041
|
+
"This adder already has a pending add of this person on this subject."
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
if (msg.includes(ix.primary) || keys === "agency_id,subject_type,subject_id") {
|
|
1045
|
+
return fail(
|
|
1046
|
+
409,
|
|
1047
|
+
"primary_exists",
|
|
1048
|
+
"The subject already has a primary contact. Use setPrimary to move it."
|
|
1049
|
+
);
|
|
1050
|
+
}
|
|
1051
|
+
if (msg.includes(ix.identity) || keys.includes("identity_key")) {
|
|
1052
|
+
return fail(409, "duplicate_contact", "This person is already an active contact on this subject.");
|
|
1053
|
+
}
|
|
1054
|
+
if (msg.includes(ix.id) || keys === "id") {
|
|
1055
|
+
return fail(409, "duplicate_contact_id", "A contact with this id exists.");
|
|
1056
|
+
}
|
|
1057
|
+
return fail(409, "duplicate_key", "The contact collides with a unique index.");
|
|
1058
|
+
}
|
|
1059
|
+
async function insertInAppContact(db, f) {
|
|
1060
|
+
const at = f.now.toISOString();
|
|
1061
|
+
const base = {
|
|
1062
|
+
user_id: null,
|
|
1063
|
+
person_id: null,
|
|
1064
|
+
display_name: f.body.display_name,
|
|
1065
|
+
emails: f.body.emails,
|
|
1066
|
+
phones: f.body.phones ?? []
|
|
1067
|
+
};
|
|
1068
|
+
const doc = {
|
|
1069
|
+
id: f.id,
|
|
1070
|
+
subject_type: f.owner.subject_type,
|
|
1071
|
+
subject_id: f.owner.subject_id,
|
|
1072
|
+
agency_id: f.owner.agency_id,
|
|
1073
|
+
org_id: f.owner.org_id,
|
|
1074
|
+
...base,
|
|
1075
|
+
purposes: f.body.purposes,
|
|
1076
|
+
urgent_methods: f.body.urgent_methods ?? [],
|
|
1077
|
+
is_primary: false,
|
|
1078
|
+
is_confidential: false,
|
|
1079
|
+
active: true,
|
|
1080
|
+
notes: null,
|
|
1081
|
+
status: pocInitialStatus("in_app"),
|
|
1082
|
+
origin: "in_app",
|
|
1083
|
+
added_in_app: f.app,
|
|
1084
|
+
identity_key: pocIdentityKey(base),
|
|
1085
|
+
confirmed_by: null,
|
|
1086
|
+
confirmed_at: null,
|
|
1087
|
+
deactivated_by: null,
|
|
1088
|
+
deactivated_at: null,
|
|
1089
|
+
version: 1,
|
|
1090
|
+
createdBy: f.actorId,
|
|
1091
|
+
createdAt: at,
|
|
1092
|
+
updatedBy: f.actorId,
|
|
1093
|
+
updatedAt: at
|
|
1094
|
+
};
|
|
1095
|
+
const [broken] = pocRuleViolations(doc);
|
|
1096
|
+
if (broken) return fail(400, broken.reason, broken.message);
|
|
1097
|
+
const noIndexes = await checkPocIndexes(db);
|
|
1098
|
+
if (noIndexes) return noIndexes;
|
|
1099
|
+
try {
|
|
1100
|
+
await db.collection(POINTS_OF_CONTACT_COLLECTION).insertOne({ ...doc });
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
const dup = pocDuplicateKeyFailure(err);
|
|
1103
|
+
if (dup) return dup;
|
|
1104
|
+
throw err;
|
|
1105
|
+
}
|
|
1106
|
+
return { ok: true, value: doc };
|
|
1107
|
+
}
|
|
1108
|
+
function withReferralTag(purposes) {
|
|
1109
|
+
return [
|
|
1110
|
+
REFERRALS_MAGIC_LINK_PURPOSE,
|
|
1111
|
+
...purposes.filter((p) => p !== REFERRALS_MAGIC_LINK_PURPOSE)
|
|
1112
|
+
];
|
|
1113
|
+
}
|
|
1114
|
+
async function mintPartnerContact(db, args, driver) {
|
|
1115
|
+
const actor = args.actor;
|
|
1116
|
+
const actorId = actor && typeof actor === "object" ? actor.id : void 0;
|
|
1117
|
+
if (typeof actorId !== "string" || actorId.trim().length === 0) {
|
|
1118
|
+
return fail(400, "actor_required", "An in-app add names the advocate (their Auth0 sub).");
|
|
1119
|
+
}
|
|
1120
|
+
if (!POC_PARTNER_ADD_APPS.includes(args.app)) {
|
|
1121
|
+
return fail(400, "invalid_app", `An in-app add names its app: ${POC_PARTNER_ADD_APPS.join(", ")}.`);
|
|
1122
|
+
}
|
|
1123
|
+
const parsed = PocInAppSchema.safeParse(args.contact);
|
|
1124
|
+
if (!parsed.success) return invalid(parsed.error, "invalid_contact");
|
|
1125
|
+
const body = { ...parsed.data, purposes: withReferralTag(parsed.data.purposes) };
|
|
1126
|
+
const partner = PartnerContactSelectorSchema.safeParse(args.partner);
|
|
1127
|
+
if (!partner.success) return invalid(partner.error, "invalid_partner");
|
|
1128
|
+
const ids = idsOf(driver);
|
|
1129
|
+
const owner = await resolvePartnerOwner(db, ids, partner.data);
|
|
1130
|
+
if (isFailure(owner)) return owner;
|
|
1131
|
+
const foreign = await refuseForeignPartnerOrg(db, ids, owner.org_id);
|
|
1132
|
+
if (foreign) return foreign;
|
|
1133
|
+
const receipt = (d, created) => ({
|
|
1134
|
+
ok: true,
|
|
1135
|
+
value: {
|
|
1136
|
+
id: d.id,
|
|
1137
|
+
status: d.status,
|
|
1138
|
+
created,
|
|
1139
|
+
subject_type: owner.subject_type,
|
|
1140
|
+
subject_id: owner.subject_id,
|
|
1141
|
+
agency_id: owner.agency_id,
|
|
1142
|
+
org_id: owner.org_id
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
const existingNow = async () => classifyExisting(await pocRowsWithIdentity(db, owner, identityOf(body)), body, actorId);
|
|
1146
|
+
const existing = await existingNow();
|
|
1147
|
+
if (existing?.kind === "own_deactivated") {
|
|
1148
|
+
return fail(
|
|
1149
|
+
409,
|
|
1150
|
+
"contact_deactivated",
|
|
1151
|
+
"You added this contact before and it has since been removed from the partner; it is not added again."
|
|
1152
|
+
);
|
|
1153
|
+
}
|
|
1154
|
+
if (existing) return receipt(existing.doc, false);
|
|
1155
|
+
const capped = await checkPendingCaps(db, owner, actorId);
|
|
1156
|
+
if (capped) return capped;
|
|
1157
|
+
const r = await insertInAppContact(db, {
|
|
1158
|
+
id: ids.newId(),
|
|
1159
|
+
owner,
|
|
1160
|
+
body,
|
|
1161
|
+
app: args.app,
|
|
1162
|
+
actorId,
|
|
1163
|
+
now: args.now ?? /* @__PURE__ */ new Date()
|
|
1164
|
+
});
|
|
1165
|
+
if (!r.ok) {
|
|
1166
|
+
if (r.reason !== "duplicate_pending_add") return r;
|
|
1167
|
+
const raced = await existingNow();
|
|
1168
|
+
return raced && raced.kind !== "own_deactivated" ? receipt(raced.doc, false) : r;
|
|
1169
|
+
}
|
|
1170
|
+
const overCap = await overCapAfterInsert(db, owner, actorId, r.value.id);
|
|
1171
|
+
if (overCap) return overCap;
|
|
1172
|
+
return receipt(r.value, true);
|
|
1173
|
+
}
|
|
423
1174
|
export {
|
|
424
1175
|
CONTACT_PURPOSES,
|
|
425
1176
|
CONTACT_PURPOSE_CODES,
|
|
1177
|
+
PARTNER_CONTACT_FAILURE_REASONS,
|
|
426
1178
|
POC_ADDED_IN_APPS,
|
|
427
1179
|
POC_IDENTITY_INDEX_FILTER,
|
|
428
1180
|
POC_ID_PATTERN,
|
|
1181
|
+
POC_IN_APP_PENDING_CAP_PER_ACTOR,
|
|
1182
|
+
POC_IN_APP_PENDING_CAP_PER_PARTNER,
|
|
1183
|
+
POC_IN_APP_PENDING_INDEX,
|
|
1184
|
+
POC_IN_APP_PENDING_INDEX_FILTER,
|
|
1185
|
+
POC_IN_APP_PENDING_INDEX_KEY,
|
|
1186
|
+
POC_MAX_CONTACT_ENTRIES,
|
|
429
1187
|
POC_ORIGINS,
|
|
1188
|
+
POC_PARTNER_ADD_APPS,
|
|
1189
|
+
POC_PENDING_QUEUE_INDEX,
|
|
430
1190
|
POC_PRIMARY_INDEX_FILTER,
|
|
431
1191
|
POC_STATUSES,
|
|
432
1192
|
POC_SUBJECT_TYPES,
|
|
1193
|
+
POC_SUBJECT_TYPE_LABELS,
|
|
433
1194
|
POC_URGENT_METHODS,
|
|
434
1195
|
POC_URGENT_METHOD_KEYS,
|
|
435
1196
|
POINTS_OF_CONTACT_COLLECTION,
|
|
436
1197
|
POINT_OF_CONTACT_INDEXES,
|
|
1198
|
+
PartnerContactSelectorSchema,
|
|
437
1199
|
PocDetailsSchema,
|
|
1200
|
+
PocEmailListSchema,
|
|
438
1201
|
PocEmailSchema,
|
|
439
1202
|
PocInAppSchema,
|
|
440
1203
|
PocLinkIdSchema,
|
|
441
1204
|
PocOwnerSchema,
|
|
442
1205
|
PocPatchSchema,
|
|
1206
|
+
PocPhoneListSchema,
|
|
443
1207
|
PocSeedSchema,
|
|
444
1208
|
PointOfContactDocSchema,
|
|
445
1209
|
PointOfContactShapeError,
|
|
446
1210
|
REFERRALS_MAGIC_LINK_PURPOSE,
|
|
1211
|
+
StoredContactEntrySchema,
|
|
1212
|
+
StoredEmailListSchema,
|
|
1213
|
+
StoredPhoneListSchema,
|
|
447
1214
|
byContactReadingOrder,
|
|
1215
|
+
checkPocIndexes,
|
|
448
1216
|
contactPurposeLabel,
|
|
449
1217
|
definedPatch,
|
|
1218
|
+
ensurePocIndexes,
|
|
1219
|
+
formatPocPhone,
|
|
450
1220
|
getContact,
|
|
451
1221
|
isContactPurposeCode,
|
|
452
1222
|
isNetworkVisible,
|
|
@@ -455,11 +1225,19 @@ export {
|
|
|
455
1225
|
listOwnerContactsForSubject,
|
|
456
1226
|
listPendingContacts,
|
|
457
1227
|
listReferralContactsForPartner,
|
|
1228
|
+
mintPartnerContact,
|
|
458
1229
|
normalizePointOfContact,
|
|
1230
|
+
pocDuplicateKeyFailure,
|
|
459
1231
|
pocIdentityKey,
|
|
460
1232
|
pocInitialStatus,
|
|
1233
|
+
pocPhoneDigits,
|
|
1234
|
+
pocRowsWithIdentity,
|
|
461
1235
|
pocRuleViolations,
|
|
1236
|
+
pocSubjectTypeLabel,
|
|
462
1237
|
pocUrgentMethodCode,
|
|
1238
|
+
preferredContactEntry,
|
|
1239
|
+
preferredEmail,
|
|
1240
|
+
preferredPhone,
|
|
463
1241
|
toNetworkView,
|
|
464
1242
|
toOwnerView,
|
|
465
1243
|
toStewardView
|