@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.
@@ -22,30 +22,49 @@ var pointsOfContact_exports = {};
22
22
  __export(pointsOfContact_exports, {
23
23
  CONTACT_PURPOSES: () => CONTACT_PURPOSES,
24
24
  CONTACT_PURPOSE_CODES: () => CONTACT_PURPOSE_CODES,
25
+ PARTNER_CONTACT_FAILURE_REASONS: () => PARTNER_CONTACT_FAILURE_REASONS,
25
26
  POC_ADDED_IN_APPS: () => POC_ADDED_IN_APPS,
26
27
  POC_IDENTITY_INDEX_FILTER: () => POC_IDENTITY_INDEX_FILTER,
27
28
  POC_ID_PATTERN: () => POC_ID_PATTERN,
29
+ POC_IN_APP_PENDING_CAP_PER_ACTOR: () => POC_IN_APP_PENDING_CAP_PER_ACTOR,
30
+ POC_IN_APP_PENDING_CAP_PER_PARTNER: () => POC_IN_APP_PENDING_CAP_PER_PARTNER,
31
+ POC_IN_APP_PENDING_INDEX: () => POC_IN_APP_PENDING_INDEX,
32
+ POC_IN_APP_PENDING_INDEX_FILTER: () => POC_IN_APP_PENDING_INDEX_FILTER,
33
+ POC_IN_APP_PENDING_INDEX_KEY: () => POC_IN_APP_PENDING_INDEX_KEY,
34
+ POC_MAX_CONTACT_ENTRIES: () => POC_MAX_CONTACT_ENTRIES,
28
35
  POC_ORIGINS: () => POC_ORIGINS,
36
+ POC_PARTNER_ADD_APPS: () => POC_PARTNER_ADD_APPS,
37
+ POC_PENDING_QUEUE_INDEX: () => POC_PENDING_QUEUE_INDEX,
29
38
  POC_PRIMARY_INDEX_FILTER: () => POC_PRIMARY_INDEX_FILTER,
30
39
  POC_STATUSES: () => POC_STATUSES,
31
40
  POC_SUBJECT_TYPES: () => POC_SUBJECT_TYPES,
41
+ POC_SUBJECT_TYPE_LABELS: () => POC_SUBJECT_TYPE_LABELS,
32
42
  POC_URGENT_METHODS: () => POC_URGENT_METHODS,
33
43
  POC_URGENT_METHOD_KEYS: () => POC_URGENT_METHOD_KEYS,
34
44
  POINTS_OF_CONTACT_COLLECTION: () => POINTS_OF_CONTACT_COLLECTION,
35
45
  POINT_OF_CONTACT_INDEXES: () => POINT_OF_CONTACT_INDEXES,
46
+ PartnerContactSelectorSchema: () => PartnerContactSelectorSchema,
36
47
  PocDetailsSchema: () => PocDetailsSchema,
48
+ PocEmailListSchema: () => PocEmailListSchema,
37
49
  PocEmailSchema: () => PocEmailSchema,
38
50
  PocInAppSchema: () => PocInAppSchema,
39
51
  PocLinkIdSchema: () => PocLinkIdSchema,
40
52
  PocOwnerSchema: () => PocOwnerSchema,
41
53
  PocPatchSchema: () => PocPatchSchema,
54
+ PocPhoneListSchema: () => PocPhoneListSchema,
42
55
  PocSeedSchema: () => PocSeedSchema,
43
56
  PointOfContactDocSchema: () => PointOfContactDocSchema,
44
57
  PointOfContactShapeError: () => PointOfContactShapeError,
45
58
  REFERRALS_MAGIC_LINK_PURPOSE: () => REFERRALS_MAGIC_LINK_PURPOSE,
59
+ StoredContactEntrySchema: () => StoredContactEntrySchema,
60
+ StoredEmailListSchema: () => StoredEmailListSchema,
61
+ StoredPhoneListSchema: () => StoredPhoneListSchema,
46
62
  byContactReadingOrder: () => byContactReadingOrder,
63
+ checkPocIndexes: () => checkPocIndexes,
47
64
  contactPurposeLabel: () => contactPurposeLabel,
48
65
  definedPatch: () => definedPatch,
66
+ ensurePocIndexes: () => ensurePocIndexes,
67
+ formatPocPhone: () => formatPocPhone,
49
68
  getContact: () => getContact,
50
69
  isContactPurposeCode: () => isContactPurposeCode,
51
70
  isNetworkVisible: () => isNetworkVisible,
@@ -54,11 +73,19 @@ __export(pointsOfContact_exports, {
54
73
  listOwnerContactsForSubject: () => listOwnerContactsForSubject,
55
74
  listPendingContacts: () => listPendingContacts,
56
75
  listReferralContactsForPartner: () => listReferralContactsForPartner,
76
+ mintPartnerContact: () => mintPartnerContact,
57
77
  normalizePointOfContact: () => normalizePointOfContact,
78
+ pocDuplicateKeyFailure: () => pocDuplicateKeyFailure,
58
79
  pocIdentityKey: () => pocIdentityKey,
59
80
  pocInitialStatus: () => pocInitialStatus,
81
+ pocPhoneDigits: () => pocPhoneDigits,
82
+ pocRowsWithIdentity: () => pocRowsWithIdentity,
60
83
  pocRuleViolations: () => pocRuleViolations,
84
+ pocSubjectTypeLabel: () => pocSubjectTypeLabel,
61
85
  pocUrgentMethodCode: () => pocUrgentMethodCode,
86
+ preferredContactEntry: () => preferredContactEntry,
87
+ preferredEmail: () => preferredEmail,
88
+ preferredPhone: () => preferredPhone,
62
89
  toNetworkView: () => toNetworkView,
63
90
  toOwnerView: () => toOwnerView,
64
91
  toStewardView: () => toStewardView
@@ -114,7 +141,18 @@ var preferredContactMethod_v1_0_0_default = {
114
141
  };
115
142
 
116
143
  // src/pointsOfContact/vocabulary.ts
117
- var POC_SUBJECT_TYPES = ["agency", "org", "program", "team", "site", "service"];
144
+ var POC_SUBJECT_TYPES = ["agency", "org", "program", "team", "location", "service"];
145
+ var POC_SUBJECT_TYPE_LABELS = {
146
+ agency: "Agency",
147
+ org: "Org",
148
+ program: "Program",
149
+ team: "Team",
150
+ location: "Site",
151
+ service: "Service listing"
152
+ };
153
+ function pocSubjectTypeLabel(type) {
154
+ return Object.hasOwn(POC_SUBJECT_TYPE_LABELS, type) ? POC_SUBJECT_TYPE_LABELS[type] : type;
155
+ }
118
156
  var CONTACT_PURPOSE_CODES = [
119
157
  "COMPLIANCE",
120
158
  "TRAINING",
@@ -194,10 +232,27 @@ var POINT_OF_CONTACT_INDEXES = {
194
232
  * `confirmed`: at most one VISIBLE primary per subject, so a stranger's
195
233
  * pending add can never hold the slot.
196
234
  */
197
- primary: "pointsofcontact_primary_unique"
235
+ primary: "pointsofcontact_primary_unique",
236
+ /**
237
+ * `{agency_id, subject_type, subject_id, identity_key, createdBy}` unique
238
+ * where {@link POC_IN_APP_PENDING_INDEX_FILTER}: one outstanding in-app add
239
+ * per adder, subject and IDENTITY ({@link pocIdentityKey}: name + preferred
240
+ * email). See `POC_IN_APP_PENDING_INDEX`.
241
+ */
242
+ inAppPending: "pointsofcontact_inapp_pending_unique",
243
+ /** `{status, createdAt, id}`: the steward's review queue, paged oldest first. */
244
+ pendingQueue: "pointsofcontact_pending_queue"
198
245
  };
199
246
  var POC_IDENTITY_INDEX_FILTER = { active: true, status: "confirmed" };
200
247
  var POC_PRIMARY_INDEX_FILTER = { is_primary: true, active: true, status: "confirmed" };
248
+ var POC_IN_APP_PENDING_INDEX_FILTER = { status: "pending", origin: "in_app", active: true };
249
+ var POC_IN_APP_PENDING_INDEX_KEY = {
250
+ agency_id: 1,
251
+ subject_type: 1,
252
+ subject_id: 1,
253
+ identity_key: 1,
254
+ createdBy: 1
255
+ };
201
256
  var POC_ID_PATTERN = /^poc-[a-z0-9_-]+$/;
202
257
  var HEX_24 = /^[0-9a-fA-F]{24}$/;
203
258
  var idString = import_zod.z.string().trim().min(1).max(200);
@@ -210,6 +265,87 @@ var UrgentMethodsSchema = import_zod.z.array(
210
265
  message: "urgent_methods holds selectable CVC-185 preferred_contact_method codes from the Agency Hub subset (email \xB7 call \xB7 text)."
211
266
  })
212
267
  ).max(3).transform((list) => [...new Set(list)]);
268
+ var POC_MAX_CONTACT_ENTRIES = 10;
269
+ var StoredContactEntrySchema = import_zod.z.object({
270
+ /** An email (lowercased) or a phone as typed (trimmed). */
271
+ value: import_zod.z.string(),
272
+ /** Exactly one entry of a non-empty list is the preferred one. */
273
+ is_preferred: import_zod.z.boolean()
274
+ });
275
+ var ReadContactEntrySchema = StoredContactEntrySchema.extend({
276
+ is_preferred: import_zod.z.boolean().nullish().transform((v) => v === true)
277
+ });
278
+ function pocPhoneDigits(v) {
279
+ const d = v.replace(/\D/g, "");
280
+ return d.length === 11 && d.charAt(0) === "1" ? d.slice(1) : d;
281
+ }
282
+ function formatPocPhone(s) {
283
+ let d = s.replace(/\D/g, "");
284
+ if (!d) return "";
285
+ if (d.length === 11 && d.charAt(0) === "1") d = d.slice(1);
286
+ if (d.length <= 3) return `(${d}`;
287
+ if (d.length <= 6) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
288
+ if (d.length <= 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
289
+ const cc = d.slice(0, d.length - 10);
290
+ const r = d.slice(d.length - 10);
291
+ return `+${cc} (${r.slice(0, 3)}) ${r.slice(3, 6)}-${r.slice(6)}`;
292
+ }
293
+ var emailKey = (v) => v.trim().toLowerCase();
294
+ function settlePreferred(list) {
295
+ const at = list.findIndex((e) => e.is_preferred);
296
+ const keep = at < 0 ? 0 : at;
297
+ return list.map((e, i) => ({ value: e.value, is_preferred: i === keep }));
298
+ }
299
+ function readEntries(list, clean, keyOf) {
300
+ const seen = /* @__PURE__ */ new Set();
301
+ const out = [];
302
+ for (const e of list) {
303
+ const value = clean(e.value);
304
+ const k = value ? keyOf(value) : "";
305
+ if (!k || seen.has(k)) continue;
306
+ seen.add(k);
307
+ out.push({ value, is_preferred: e.is_preferred });
308
+ }
309
+ return settlePreferred(out);
310
+ }
311
+ var StoredEmailListSchema = import_zod.z.array(ReadContactEntrySchema).transform((l) => readEntries(l, emailKey, (v) => v));
312
+ var StoredPhoneListSchema = import_zod.z.array(ReadContactEntrySchema).transform((l) => readEntries(l, (v) => v.trim(), pocPhoneDigits));
313
+ function entryListSchema(value, keyOf, noun) {
314
+ return import_zod.z.array(import_zod.z.object({ value, is_preferred: import_zod.z.boolean().optional() }).strict()).max(POC_MAX_CONTACT_ENTRIES).superRefine((list, ctx) => {
315
+ if (list.filter((e) => e.is_preferred === true).length > 1) {
316
+ ctx.addIssue({ code: "custom", message: `A contact has at most one preferred ${noun}.` });
317
+ }
318
+ const seen = /* @__PURE__ */ new Set();
319
+ list.forEach((e, i) => {
320
+ const k = keyOf(e.value);
321
+ if (seen.has(k)) {
322
+ ctx.addIssue({
323
+ code: "custom",
324
+ path: [i, "value"],
325
+ message: `The same ${noun} appears twice on one contact.`
326
+ });
327
+ }
328
+ seen.add(k);
329
+ });
330
+ }).transform(
331
+ (list) => settlePreferred(list.map((e) => ({ value: e.value, is_preferred: e.is_preferred === true })))
332
+ );
333
+ }
334
+ var PocEmailListSchema = entryListSchema(PocEmailSchema, (v) => v, "email");
335
+ var PocPhoneValueSchema = text(40).refine((v) => /\d/.test(v), {
336
+ message: "A phone number has at least one digit."
337
+ });
338
+ var PocPhoneListSchema = entryListSchema(PocPhoneValueSchema, pocPhoneDigits, "phone");
339
+ function preferredContactEntry(list) {
340
+ if (!list || list.length === 0) return null;
341
+ return list.find((e) => e.is_preferred) ?? list[0] ?? null;
342
+ }
343
+ function preferredEmail(c) {
344
+ return preferredContactEntry(c.emails)?.value ?? null;
345
+ }
346
+ function preferredPhone(c) {
347
+ return preferredContactEntry(c.phones)?.value ?? null;
348
+ }
213
349
  var PocOwnerSchema = import_zod.z.object({
214
350
  subject_type: import_zod.z.enum(POC_SUBJECT_TYPES),
215
351
  subject_id: idString,
@@ -222,7 +358,7 @@ var PocOwnerSchema = import_zod.z.object({
222
358
  if (o.subject_type === "org" && o.subject_id !== o.org_id) {
223
359
  ctx.addIssue({ code: "custom", path: ["subject_id"], message: "An org's own contact names that org: subject_id must equal org_id." });
224
360
  }
225
- if ((o.subject_type === "program" || o.subject_type === "team" || o.subject_type === "site") && !o.agency_id) {
361
+ if ((o.subject_type === "program" || o.subject_type === "team" || o.subject_type === "location") && !o.agency_id) {
226
362
  ctx.addIssue({ code: "custom", path: ["agency_id"], message: `A ${o.subject_type} contact names the agency it belongs to.` });
227
363
  }
228
364
  if (o.subject_type === "service" && !o.org_id) {
@@ -233,8 +369,8 @@ var PocDetailsSchema = import_zod.z.object({
233
369
  user_id: PocLinkIdSchema.nullable().optional(),
234
370
  person_id: PocLinkIdSchema.nullable().optional(),
235
371
  display_name: text(200).nullable().optional(),
236
- email: PocEmailSchema.nullable().optional(),
237
- phone: text(40).nullable().optional(),
372
+ emails: PocEmailListSchema.optional(),
373
+ phones: PocPhoneListSchema.optional(),
238
374
  purposes: PurposesSchema.optional(),
239
375
  urgent_methods: UrgentMethodsSchema.optional(),
240
376
  is_primary: import_zod.z.boolean().optional(),
@@ -243,8 +379,8 @@ var PocDetailsSchema = import_zod.z.object({
243
379
  }).strict();
244
380
  var PocInAppSchema = import_zod.z.object({
245
381
  display_name: text(200),
246
- email: PocEmailSchema,
247
- phone: text(40).nullable().optional(),
382
+ emails: PocEmailListSchema.refine((l) => l.length > 0, { message: "An in-app add names at least one email." }),
383
+ phones: PocPhoneListSchema.optional(),
248
384
  purposes: PurposesSchema.default([REFERRALS_MAGIC_LINK_PURPOSE]),
249
385
  urgent_methods: UrgentMethodsSchema.optional()
250
386
  }).strict();
@@ -267,9 +403,10 @@ var PointOfContactDocSchema = import_zod.z.object({
267
403
  user_id: nullableString,
268
404
  person_id: nullableString,
269
405
  display_name: nullableString,
270
- /** Lowercased. Null on a seat-linked contact (it resolves from the seat). */
271
- email: nullableString,
272
- phone: nullableString,
406
+ /** Lowercased emails, read leniently. Empty on a seat-linked contact (it resolves from the seat). */
407
+ emails: StoredEmailListSchema,
408
+ /** Read leniently. Empty on a seat-linked contact. */
409
+ phones: StoredPhoneListSchema,
273
410
  purposes: import_zod.z.array(import_zod.z.enum(CONTACT_PURPOSE_CODES)),
274
411
  /** CVC-185 codes. */
275
412
  urgent_methods: import_zod.z.array(import_zod.z.string()),
@@ -281,7 +418,7 @@ var PointOfContactDocSchema = import_zod.z.object({
281
418
  status: import_zod.z.enum(POC_STATUSES),
282
419
  origin: import_zod.z.enum(POC_ORIGINS),
283
420
  added_in_app: import_zod.z.enum(POC_ADDED_IN_APPS).nullable(),
284
- /** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<email>`, lowercased. */
421
+ /** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<preferred email>`, lowercased. */
285
422
  identity_key: import_zod.z.string().min(1),
286
423
  confirmed_by: nullableString,
287
424
  confirmed_at: nullableString,
@@ -300,7 +437,7 @@ function pocRuleViolations(c) {
300
437
  if (c.user_id && c.person_id) {
301
438
  out.push({ reason: "user_id_xor_person_id", message: "A contact points at a seat (user_id) or a person (person_id), never both." });
302
439
  }
303
- if (seat && (c.email || c.phone)) {
440
+ if (seat && (c.emails.length > 0 || c.phones.length > 0)) {
304
441
  out.push({
305
442
  reason: "seat_contact_has_own_reach",
306
443
  message: "A seat-linked contact stores no email or phone of its own; they resolve from the seat."
@@ -309,7 +446,7 @@ function pocRuleViolations(c) {
309
446
  if (!seat && !c.display_name) {
310
447
  out.push({ reason: "display_name_required", message: "A contact that holds no seat needs a display_name." });
311
448
  }
312
- if (!seat && c.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE) && !c.email) {
449
+ if (!seat && c.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE) && c.emails.length === 0) {
313
450
  out.push({
314
451
  reason: "referral_contact_needs_email",
315
452
  message: "A contact tagged Referrals (magic link) must have an email."
@@ -321,7 +458,7 @@ function pocIdentityKey(c) {
321
458
  const norm = (v) => (v ?? "").trim().toLowerCase();
322
459
  if (c.user_id) return `seat:${norm(c.user_id)}`;
323
460
  if (c.person_id) return `person:${norm(c.person_id)}`;
324
- return `writein:${norm(c.display_name)}|${norm(c.email)}`;
461
+ return `writein:${norm(c.display_name)}|${norm(preferredEmail(c))}`;
325
462
  }
326
463
 
327
464
  // src/pointsOfContact/readRules.ts
@@ -346,12 +483,29 @@ function normalizePointOfContact(raw) {
346
483
  function isNetworkVisible(d) {
347
484
  return d.active && d.status === "confirmed" && !d.is_confidential;
348
485
  }
486
+ var copyEntries = (list) => list.map((e) => ({ ...e }));
487
+ function reachOf(d, seat) {
488
+ if (!d.user_id) return { emails: copyEntries(d.emails), phones: copyEntries(d.phones) };
489
+ const one = (v) => v ? [{ value: v, is_preferred: true }] : [];
490
+ return {
491
+ emails: one(seat?.email?.trim().toLowerCase()),
492
+ phones: one(seat?.phone?.trim())
493
+ };
494
+ }
495
+ var preferredValue = (list) => preferredContactEntry(list)?.value ?? null;
349
496
  function toStewardView(d, seat) {
350
497
  const { identity_key: _internal, ...rest } = d;
498
+ const reach = reachOf(d, seat);
351
499
  return {
352
500
  ...rest,
501
+ emails: copyEntries(d.emails),
502
+ phones: copyEntries(d.phones),
503
+ purposes: [...d.purposes],
504
+ urgent_methods: [...d.urgent_methods],
353
505
  purpose_labels: d.purposes.map(contactPurposeLabel),
354
- seat: d.user_id ? seat ?? null : null
506
+ seat: d.user_id ? seat ?? null : null,
507
+ email: preferredValue(reach.emails),
508
+ phone: preferredValue(reach.phones)
355
509
  };
356
510
  }
357
511
  function toOwnerView(d, seat) {
@@ -368,6 +522,7 @@ function toOwnerView(d, seat) {
368
522
  function toNetworkView(d, seat) {
369
523
  if (!isNetworkVisible(d)) return null;
370
524
  const seatLinked = !!d.user_id;
525
+ const { emails, phones } = reachOf(d, seat);
371
526
  return {
372
527
  id: d.id,
373
528
  subject_type: d.subject_type,
@@ -375,11 +530,13 @@ function toNetworkView(d, seat) {
375
530
  agency_id: d.agency_id,
376
531
  org_id: d.org_id,
377
532
  display_name: d.display_name ?? (seatLinked ? seat?.name ?? null : null),
378
- email: seatLinked ? seat?.email ? seat.email.toLowerCase() : null : d.email,
379
- phone: seatLinked ? seat?.phone ?? null : d.phone,
380
- purposes: d.purposes,
533
+ emails,
534
+ phones,
535
+ email: preferredValue(emails),
536
+ phone: preferredValue(phones),
537
+ purposes: [...d.purposes],
381
538
  purpose_labels: d.purposes.map(contactPurposeLabel),
382
- urgent_methods: d.urgent_methods,
539
+ urgent_methods: [...d.urgent_methods],
383
540
  is_primary: d.is_primary,
384
541
  updatedAt: d.updatedAt
385
542
  };
@@ -389,7 +546,7 @@ var SUBJECT_ORDER = {
389
546
  org: 1,
390
547
  program: 2,
391
548
  team: 3,
392
- site: 4,
549
+ location: 4,
393
550
  service: 5
394
551
  };
395
552
  function byContactReadingOrder(a, b) {
@@ -401,7 +558,7 @@ function subjectFilter(subject) {
401
558
  const type = requireId("subject_type", subject.subject_type);
402
559
  const base = { subject_type: type, subject_id: requireId("subject_id", subject.subject_id) };
403
560
  const agency = subject.agency_id;
404
- if (type === "program" || type === "team" || type === "site") {
561
+ if (type === "program" || type === "team" || type === "location") {
405
562
  return { ...base, agency_id: requireId("agency_id", agency) };
406
563
  }
407
564
  if (type === "service" && agency === void 0) {
@@ -446,6 +603,7 @@ async function listReferralContactsForPartner(db, partner, opts) {
446
603
  keys.push({ org_id: requireId("org_id", partner.org_id) });
447
604
  }
448
605
  if (keys.length === 0) throw new TypeError("points-of-contact: select a partner by agency_id, org_id or both");
606
+ const pendingFor = opts.includeOwnPendingFor === void 0 ? null : requireId("includeOwnPendingFor", opts.includeOwnPendingFor);
449
607
  const docs = await findDocs(db, {
450
608
  $or: keys,
451
609
  purposes: REFERRALS_MAGIC_LINK_PURPOSE,
@@ -466,8 +624,31 @@ async function listReferralContactsForPartner(db, partner, opts) {
466
624
  seen.add(email);
467
625
  recipients.push({ ...v, email });
468
626
  }
627
+ if (pendingFor !== null) {
628
+ const pending = await findDocs(db, {
629
+ $or: keys,
630
+ purposes: REFERRALS_MAGIC_LINK_PURPOSE,
631
+ ...OWN_PENDING_IN_APP,
632
+ createdBy: pendingFor
633
+ });
634
+ for (const d of pending) {
635
+ if (!isOwnPendingInApp(d, pendingFor)) continue;
636
+ const v = toNetworkView({ ...d, status: "confirmed" });
637
+ const email = v?.email;
638
+ if (!v || !email || seen.has(email)) continue;
639
+ seen.add(email);
640
+ recipients.push({ ...v, email, pending: true });
641
+ }
642
+ }
469
643
  return { recipients, unreachable };
470
644
  }
645
+ var OWN_PENDING_IN_APP = {
646
+ active: true,
647
+ status: "pending",
648
+ origin: "in_app",
649
+ is_confidential: { $ne: true }
650
+ };
651
+ 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);
471
652
  async function getContact(db, id, opts = {}) {
472
653
  const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).findOne({ id: requireId("id", id) });
473
654
  if (!raw) return null;
@@ -487,34 +668,650 @@ async function listPendingContacts(db, opts = {}) {
487
668
  const seats = await seatsFor(docs, opts.resolveSeats);
488
669
  return docs.map((d) => toStewardView(d, seatOf(d, seats)));
489
670
  }
671
+
672
+ // src/pointsOfContact/writer.ts
673
+ var import_zod3 = require("zod");
674
+
675
+ // src/orgDirectory/schemas.ts
676
+ var import_zod2 = require("zod");
677
+
678
+ // src/orgDirectory/vocabulary.ts
679
+ var PROGRAM_REVIEW_STATUS = {
680
+ PENDING: "pending",
681
+ CONFIRMED: "confirmed",
682
+ REJECTED: "rejected"
683
+ };
684
+ var PROGRAM_REVIEW_STATUS_VALUES = Object.freeze([
685
+ PROGRAM_REVIEW_STATUS.PENDING,
686
+ PROGRAM_REVIEW_STATUS.CONFIRMED,
687
+ PROGRAM_REVIEW_STATUS.REJECTED
688
+ ]);
689
+ var PROGRAM_STATUS = {
690
+ ACTIVE: "active",
691
+ RETIRED: "retired"
692
+ };
693
+ var PROGRAM_STATUS_VALUES = Object.freeze([
694
+ PROGRAM_STATUS.ACTIVE,
695
+ PROGRAM_STATUS.RETIRED
696
+ ]);
697
+ function isLiveOrganizationProgram(row) {
698
+ return row.status !== PROGRAM_STATUS.RETIRED && row.reviewStatus !== PROGRAM_REVIEW_STATUS.REJECTED;
699
+ }
700
+
701
+ // src/orgDirectory/schemas.ts
702
+ var ORGANIZATION_PROGRAM_ROW_KEYS = Object.freeze([
703
+ "programId",
704
+ "name",
705
+ "description",
706
+ "status",
707
+ "defaultSharingPolicy",
708
+ "reviewStatus",
709
+ "addedBy",
710
+ "addedInApp",
711
+ "addedInSession"
712
+ ]);
713
+ var optionalText = import_zod2.z.string().nullish();
714
+ var OrganizationProgramRowSchema = import_zod2.z.object({
715
+ programId: import_zod2.z.string().min(1),
716
+ name: import_zod2.z.string().min(1),
717
+ description: optionalText,
718
+ status: optionalText,
719
+ defaultSharingPolicy: optionalText,
720
+ reviewStatus: import_zod2.z.enum(PROGRAM_REVIEW_STATUS_VALUES).nullish(),
721
+ addedBy: optionalText,
722
+ addedInApp: optionalText,
723
+ addedInSession: optionalText
724
+ });
725
+
726
+ // src/orgDirectory/rules.ts
727
+ function directoryIdString(value) {
728
+ if (typeof value === "string") return value === "" ? null : value;
729
+ if (value && typeof value === "object" && typeof value.toHexString === "function") {
730
+ return value.toHexString();
731
+ }
732
+ return null;
733
+ }
734
+ function sameDirectoryId(a, b) {
735
+ const x = directoryIdString(a);
736
+ const y = directoryIdString(b);
737
+ return x !== null && y !== null && x.toLowerCase() === y.toLowerCase();
738
+ }
739
+ function organizationRowShape(raw) {
740
+ if (!raw || typeof raw !== "object") return "unknown";
741
+ const r = raw;
742
+ if (typeof r.canonicalKey === "string" && r.canonicalKey !== "") return "canonical";
743
+ if (typeof r.id === "string" || typeof r.type === "string" || "acronym" in r || "location" in r)
744
+ return "pave";
745
+ if (typeof r.type === "number") return "thread";
746
+ return "unknown";
747
+ }
748
+ function isAgencyOwnOrganization(org, agency) {
749
+ if (!org || !agency) return false;
750
+ return sameDirectoryId(org.agencyId, agency._id) && sameDirectoryId(agency.organizationId, org._id);
751
+ }
752
+ function toDirectoryProgramView(raw) {
753
+ const parsed = OrganizationProgramRowSchema.safeParse(raw);
754
+ if (!parsed.success) return null;
755
+ const p = parsed.data;
756
+ return {
757
+ programId: p.programId,
758
+ name: p.name,
759
+ description: p.description ?? null,
760
+ status: p.status ?? null,
761
+ reviewStatus: p.reviewStatus ?? null,
762
+ addedBy: p.addedBy ?? null,
763
+ addedInApp: p.addedInApp ?? null,
764
+ live: isLiveOrganizationProgram(p)
765
+ };
766
+ }
767
+ var text2 = (v) => typeof v === "string" && v !== "" ? v : null;
768
+ function toDirectoryOrganizationView(raw) {
769
+ if (!raw || typeof raw !== "object") return null;
770
+ const r = raw;
771
+ const id = directoryIdString(r._id);
772
+ if (!id) return null;
773
+ const rows = Array.isArray(r.programs) ? r.programs : [];
774
+ const programs = rows.map(toDirectoryProgramView).filter((p) => p !== null);
775
+ return {
776
+ id,
777
+ shape: organizationRowShape(r),
778
+ name: text2(r.name) ?? "",
779
+ type: typeof r.type === "number" ? r.type : null,
780
+ typeKey: typeof r.type === "string" ? r.type : null,
781
+ paveId: text2(r.id),
782
+ community: text2(r.community),
783
+ agencyId: directoryIdString(r.agencyId),
784
+ agencyScope: directoryIdString(r.agencyScope),
785
+ canonicalKey: text2(r.canonicalKey),
786
+ programs,
787
+ invalidPrograms: rows.length - programs.length
788
+ };
789
+ }
790
+
791
+ // src/orgDirectory/read.ts
792
+ var ORGANIZATIONS_COLLECTION = "organizations";
793
+ var AGENCIES_COLLECTION = "agencies";
794
+ var HEX = /^[0-9a-fA-F]{24}$/;
795
+ function organizationIdForms(id, opts = {}) {
796
+ if (typeof id !== "string") return [id.toHexString(), id];
797
+ return HEX.test(id) && opts.toObjectId ? [id, opts.toObjectId(id.toLowerCase())] : [id];
798
+ }
799
+ async function readDirectoryOrganization(db, id, opts = {}) {
800
+ const raw = await db.collection(ORGANIZATIONS_COLLECTION).findOne({ _id: { $in: organizationIdForms(id, opts) } });
801
+ return raw ? toDirectoryOrganizationView(raw) : null;
802
+ }
803
+ async function readAgencyOwnOrganization(db, agencyId, opts = {}) {
804
+ const agency = await db.collection(AGENCIES_COLLECTION).findOne(
805
+ { _id: { $in: organizationIdForms(agencyId, opts) } },
806
+ { projection: { _id: 1, organizationId: 1 } }
807
+ );
808
+ if (!agency || agency.organizationId == null) return null;
809
+ const pointer = agency.organizationId;
810
+ const org = await db.collection(ORGANIZATIONS_COLLECTION).findOne({ _id: { $in: organizationIdForms(pointer, opts) } });
811
+ return org && isAgencyOwnOrganization(org, agency) ? toDirectoryOrganizationView(org) : null;
812
+ }
813
+
814
+ // src/pointsOfContact/writer.ts
815
+ var POC_PARTNER_ADD_APPS = POC_ADDED_IN_APPS.filter(
816
+ (a) => a !== "platform"
817
+ );
818
+ var directoryId = import_zod3.z.string().trim().min(1).max(200);
819
+ var PartnerContactSelectorSchema = import_zod3.z.object({ agency_id: directoryId.optional(), org_id: directoryId.optional() }).strict().refine((p) => Boolean(p.agency_id || p.org_id), {
820
+ message: "Name the partner's agency_id or org_id."
821
+ });
822
+ var POC_IN_APP_PENDING_CAP_PER_ACTOR = 25;
823
+ var POC_IN_APP_PENDING_CAP_PER_PARTNER = 5;
824
+ var POC_IN_APP_PENDING_INDEX = POINT_OF_CONTACT_INDEXES.inAppPending;
825
+ var POC_PENDING_QUEUE_INDEX = POINT_OF_CONTACT_INDEXES.pendingQueue;
826
+ var indexRuns = /* @__PURE__ */ new WeakMap();
827
+ function ensurePocIndexes(db) {
828
+ const memo = indexRuns.get(db);
829
+ if (memo) return memo;
830
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
831
+ const ix = POINT_OF_CONTACT_INDEXES;
832
+ const run = (async () => {
833
+ await coll.createIndex({ id: 1 }, { name: ix.id, unique: true });
834
+ await coll.createIndex({ subject_type: 1, subject_id: 1, active: 1 }, { name: ix.subject });
835
+ await coll.createIndex({ agency_id: 1, purposes: 1, active: 1 }, { name: ix.agencyPurpose });
836
+ await coll.createIndex({ org_id: 1, purposes: 1, active: 1 }, { name: ix.orgPurpose });
837
+ await coll.createIndex({ status: 1 }, { name: ix.status });
838
+ await coll.createIndex(
839
+ { agency_id: 1, subject_type: 1, subject_id: 1, identity_key: 1 },
840
+ {
841
+ name: ix.identity,
842
+ unique: true,
843
+ partialFilterExpression: { ...POC_IDENTITY_INDEX_FILTER }
844
+ }
845
+ );
846
+ await coll.createIndex(
847
+ { agency_id: 1, subject_type: 1, subject_id: 1 },
848
+ { name: ix.primary, unique: true, partialFilterExpression: { ...POC_PRIMARY_INDEX_FILTER } }
849
+ );
850
+ await coll.createIndex(
851
+ { ...POC_IN_APP_PENDING_INDEX_KEY },
852
+ {
853
+ name: POC_IN_APP_PENDING_INDEX,
854
+ unique: true,
855
+ partialFilterExpression: { ...POC_IN_APP_PENDING_INDEX_FILTER }
856
+ }
857
+ );
858
+ await coll.createIndex({ status: 1, createdAt: 1, id: 1 }, { name: POC_PENDING_QUEUE_INDEX });
859
+ })().catch((err) => {
860
+ indexRuns.delete(db);
861
+ throw err;
862
+ });
863
+ indexRuns.set(db, run);
864
+ return run;
865
+ }
866
+ var indexesChecked = /* @__PURE__ */ new WeakMap();
867
+ var codeOf = (err) => err && typeof err === "object" ? err.code : void 0;
868
+ var NAMESPACE_NOT_FOUND = 26;
869
+ var sameKey = (got, want) => {
870
+ if (!got || typeof got !== "object") return false;
871
+ const g = Object.entries(got);
872
+ const w = Object.entries(want);
873
+ return g.length === w.length && w.every(([k, v], i) => g[i][0] === k && Number(g[i][1]) === v);
874
+ };
875
+ var sameFilter = (got, want) => {
876
+ if (!want) return got === void 0 || got === null;
877
+ if (!got || typeof got !== "object") return false;
878
+ const sorted = (o) => JSON.stringify(Object.entries(o).sort(([a], [b]) => a < b ? -1 : 1));
879
+ return sorted(got) === sorted(want);
880
+ };
881
+ var REQUIRED_INDEXES = [
882
+ { key: { id: 1 } },
883
+ { key: { ...POC_IN_APP_PENDING_INDEX_KEY }, filter: { ...POC_IN_APP_PENDING_INDEX_FILTER } }
884
+ ];
885
+ async function checkPocIndexes(db) {
886
+ if (indexesChecked.has(db)) return null;
887
+ let listed;
888
+ try {
889
+ listed = await db.collection(POINTS_OF_CONTACT_COLLECTION).indexes();
890
+ } catch (err) {
891
+ if (codeOf(err) === NAMESPACE_NOT_FOUND) return INDEXES_MISSING;
892
+ throw err;
893
+ }
894
+ const present = REQUIRED_INDEXES.every(
895
+ (want) => listed.some(
896
+ (ix) => ix.unique === true && sameKey(ix.key, want.key) && sameFilter(ix.partialFilterExpression, want.filter)
897
+ )
898
+ );
899
+ if (!present) return INDEXES_MISSING;
900
+ indexesChecked.set(db, true);
901
+ return null;
902
+ }
903
+ var PARTNER_CONTACT_FAILURE_REASONS = [
904
+ "actor_required",
905
+ "invalid_app",
906
+ "invalid_contact",
907
+ "invalid_partner",
908
+ "owner_not_found",
909
+ "owner_mismatch",
910
+ "canonical_org",
911
+ "foreign_row_shape",
912
+ "contact_deactivated",
913
+ "too_many_pending_adds",
914
+ "duplicate_pending_add",
915
+ "duplicate_contact",
916
+ "primary_exists",
917
+ "duplicate_contact_id",
918
+ "duplicate_key",
919
+ "user_id_xor_person_id",
920
+ "seat_contact_has_own_reach",
921
+ "display_name_required",
922
+ "referral_contact_needs_email",
923
+ "indexes_missing"
924
+ ];
925
+ function fail(status, reason, message) {
926
+ return { ok: false, status, reason, ...message ? { message } : {} };
927
+ }
928
+ var INDEXES_MISSING = fail(
929
+ 503,
930
+ "indexes_missing",
931
+ "The points-of-contact indexes are not in place; the platform must create them (ensurePocIndexes) before an app writes."
932
+ );
933
+ var isFailure = (v) => !!v && typeof v === "object" && v.ok === false;
934
+ function invalid(err, reason) {
935
+ const issues = err.issues.map((i) => `${i.path.map(String).join(".") || "(body)"}: ${i.message}`);
936
+ return fail(400, reason, issues.join("; "));
937
+ }
938
+ var HEX_242 = /^[0-9a-fA-F]{24}$/;
939
+ var canonicalId = (v) => HEX_242.test(v) ? v.toLowerCase() : v;
940
+ var idOf = (v) => v === null || v === void 0 || v === "" ? null : String(v);
941
+ function idsOf(driver) {
942
+ const { ObjectId } = driver;
943
+ return {
944
+ forms: (value) => HEX_242.test(value) ? [value, new ObjectId(value)] : [value],
945
+ read: { toObjectId: (hex) => new ObjectId(hex) },
946
+ newId: () => `poc-${new ObjectId().toHexString()}`
947
+ };
948
+ }
949
+ var REGISTRY_AGENCIES_COLLECTION = "registry_agencies";
950
+ var AGENCY_PROJECTION = { projection: { _id: 1, entity_id: 1, id: 1 } };
951
+ function formsOf(row) {
952
+ const out = [];
953
+ if (typeof row.entity_id === "string" && row.entity_id !== "") out.push(row.entity_id);
954
+ if (typeof row.id === "string" && row.id !== "") out.push(row.id);
955
+ if (row._id !== void 0 && row._id !== null) out.push(String(row._id));
956
+ return [...new Set(out)];
957
+ }
958
+ var agencyIdFilter = (ids, agencyId) => ({
959
+ $or: [{ entity_id: agencyId }, { id: agencyId }, { _id: { $in: ids.forms(agencyId) } }]
960
+ });
961
+ function resolveRecipient(form, agencies, registry) {
962
+ const direct = agencies.find((a) => formsOf(a).includes(form));
963
+ if (direct) return String(direct._id);
964
+ const reg = registry.find((r) => formsOf(r).includes(form));
965
+ if (!reg) return null;
966
+ const regForms = formsOf(reg);
967
+ const mapped = agencies.find((a) => formsOf(a).some((f) => regForms.includes(f)));
968
+ return mapped ? String(mapped._id) : null;
969
+ }
970
+ async function resolveAgencyId(db, ids, form) {
971
+ const agencies = db.collection(AGENCIES_COLLECTION);
972
+ const direct = await agencies.find(agencyIdFilter(ids, form), AGENCY_PROJECTION).toArray();
973
+ if (direct.length > 0) return resolveRecipient(form, direct, []);
974
+ const registry = await db.collection(REGISTRY_AGENCIES_COLLECTION).find(agencyIdFilter(ids, form), AGENCY_PROJECTION).toArray();
975
+ if (registry.length === 0) return null;
976
+ const regForms = formsOf(registry[0]);
977
+ const mapped = await agencies.find({ $or: regForms.map((f) => agencyIdFilter(ids, f)) }, AGENCY_PROJECTION).toArray();
978
+ return resolveRecipient(form, mapped, registry);
979
+ }
980
+ async function agencyKey(db, ids, form) {
981
+ const id = await resolveAgencyId(db, ids, canonicalId(form));
982
+ return id ? canonicalId(id) : null;
983
+ }
984
+ var OWNER_NOT_FOUND = fail(
985
+ 400,
986
+ "owner_not_found",
987
+ "The contact's owner does not resolve to a platform agency or organization."
988
+ );
989
+ var OWNER_MISMATCH = fail(
990
+ 400,
991
+ "owner_mismatch",
992
+ "The agency and organization named are not the same partner."
993
+ );
994
+ async function genuineMirrorAgency(db, ids, org) {
995
+ const declared = idOf(org.agencyId);
996
+ if (!declared) return null;
997
+ const agency = await db.collection(AGENCIES_COLLECTION).findOne(
998
+ { _id: { $in: ids.forms(canonicalId(declared)) } },
999
+ { projection: { _id: 1, organizationId: 1 } }
1000
+ );
1001
+ if (!agency || !isAgencyOwnOrganization(org, agency)) return null;
1002
+ return agencyKey(db, ids, String(agency._id));
1003
+ }
1004
+ async function resolvePartnerOwner(db, ids, p) {
1005
+ let agencyId = null;
1006
+ if (p.agency_id) {
1007
+ agencyId = await agencyKey(db, ids, p.agency_id);
1008
+ if (!agencyId) return OWNER_NOT_FOUND;
1009
+ }
1010
+ let org = null;
1011
+ if (p.org_id) {
1012
+ org = await db.collection(ORGANIZATIONS_COLLECTION).findOne(
1013
+ { _id: { $in: ids.forms(canonicalId(p.org_id)) } },
1014
+ { projection: { _id: 1, agencyId: 1 } }
1015
+ );
1016
+ if (!org) return OWNER_NOT_FOUND;
1017
+ }
1018
+ const orgId = org ? canonicalId(String(org._id)) : null;
1019
+ if (!agencyId) {
1020
+ if (!org || !orgId) return OWNER_NOT_FOUND;
1021
+ const mirrorAgency = await genuineMirrorAgency(db, ids, org);
1022
+ if (mirrorAgency) {
1023
+ return {
1024
+ subject_type: "agency",
1025
+ subject_id: mirrorAgency,
1026
+ agency_id: mirrorAgency,
1027
+ org_id: orgId
1028
+ };
1029
+ }
1030
+ return { subject_type: "org", subject_id: orgId, agency_id: null, org_id: orgId };
1031
+ }
1032
+ const own = await readAgencyOwnOrganization(db, agencyId, ids.read);
1033
+ const mirrorOrg = own ? canonicalId(own.id) : null;
1034
+ if (orgId && orgId !== mirrorOrg) return OWNER_MISMATCH;
1035
+ return { subject_type: "agency", subject_id: agencyId, agency_id: agencyId, org_id: mirrorOrg };
1036
+ }
1037
+ async function refuseForeignPartnerOrg(db, ids, orgId) {
1038
+ if (!orgId) return null;
1039
+ const org = await readDirectoryOrganization(db, orgId, ids.read);
1040
+ if (org?.shape === "canonical") {
1041
+ return fail(409, "canonical_org", "A canonical singleton organization is not a partner.");
1042
+ }
1043
+ if (org?.shape === "pave") {
1044
+ return fail(
1045
+ 409,
1046
+ "foreign_row_shape",
1047
+ "This organization is a PAVE 2.0-shape row; an in-app contact is not added to it."
1048
+ );
1049
+ }
1050
+ return null;
1051
+ }
1052
+ async function pocRowsWithIdentity(db, owner, identityKey) {
1053
+ const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).find({
1054
+ agency_id: owner.agency_id,
1055
+ subject_type: owner.subject_type,
1056
+ subject_id: owner.subject_id,
1057
+ identity_key: identityKey
1058
+ }).toArray();
1059
+ return raw.map((r) => normalizePointOfContact(r)).filter((d) => d.identity_key === identityKey);
1060
+ }
1061
+ var identityOf = (body) => pocIdentityKey({
1062
+ user_id: null,
1063
+ person_id: null,
1064
+ display_name: body.display_name,
1065
+ emails: body.emails
1066
+ });
1067
+ var ownInApp = (d, actorId) => d.origin === "in_app" && d.createdBy === actorId;
1068
+ function classifyExisting(rows, body, actorId) {
1069
+ const visible = rows.find(
1070
+ (d) => d.active && d.status === "confirmed" && !d.is_confidential && body.purposes.every((p) => d.purposes.includes(p))
1071
+ );
1072
+ if (visible) return { kind: "visible", doc: visible };
1073
+ const pending = rows.find((d) => d.active && d.status === "pending" && ownInApp(d, actorId));
1074
+ if (pending) return { kind: "own_pending", doc: pending };
1075
+ const removed = rows.find((d) => !d.active && ownInApp(d, actorId));
1076
+ if (removed) return { kind: "own_deactivated", doc: removed };
1077
+ return null;
1078
+ }
1079
+ function pendingCaps(owner, actorId) {
1080
+ const mine = { createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER };
1081
+ return [
1082
+ {
1083
+ filter: {
1084
+ ...mine,
1085
+ agency_id: owner.agency_id,
1086
+ subject_type: owner.subject_type,
1087
+ subject_id: owner.subject_id
1088
+ },
1089
+ cap: POC_IN_APP_PENDING_CAP_PER_PARTNER,
1090
+ refusal: fail(
1091
+ 429,
1092
+ "too_many_pending_adds",
1093
+ `At most ${POC_IN_APP_PENDING_CAP_PER_PARTNER} contacts you added to one partner can wait for HTI Labs at a time.`
1094
+ )
1095
+ },
1096
+ {
1097
+ filter: mine,
1098
+ cap: POC_IN_APP_PENDING_CAP_PER_ACTOR,
1099
+ refusal: fail(
1100
+ 429,
1101
+ "too_many_pending_adds",
1102
+ `At most ${POC_IN_APP_PENDING_CAP_PER_ACTOR} contacts you added can wait for HTI Labs at a time.`
1103
+ )
1104
+ }
1105
+ ];
1106
+ }
1107
+ async function checkPendingCaps(db, owner, actorId) {
1108
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
1109
+ for (const c of pendingCaps(owner, actorId)) {
1110
+ if (await coll.countDocuments(c.filter) >= c.cap) return c.refusal;
1111
+ }
1112
+ return null;
1113
+ }
1114
+ async function overCapAfterInsert(db, owner, actorId, id) {
1115
+ const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);
1116
+ for (const c of pendingCaps(owner, actorId)) {
1117
+ if (await coll.countDocuments(c.filter) > c.cap) {
1118
+ await coll.deleteOne({ id, createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER });
1119
+ return c.refusal;
1120
+ }
1121
+ }
1122
+ return null;
1123
+ }
1124
+ function pocDuplicateKeyFailure(err) {
1125
+ if (!err || typeof err !== "object") return null;
1126
+ const e = err;
1127
+ const msg = typeof e.message === "string" ? e.message : "";
1128
+ if (e.code !== 11e3 && !/E11000/.test(msg)) return null;
1129
+ const ix = POINT_OF_CONTACT_INDEXES;
1130
+ const keys = Object.keys(e.keyPattern ?? {}).join(",");
1131
+ if (msg.includes(POC_IN_APP_PENDING_INDEX) || keys.includes("createdBy")) {
1132
+ return fail(
1133
+ 409,
1134
+ "duplicate_pending_add",
1135
+ "This adder already has a pending add of this person on this subject."
1136
+ );
1137
+ }
1138
+ if (msg.includes(ix.primary) || keys === "agency_id,subject_type,subject_id") {
1139
+ return fail(
1140
+ 409,
1141
+ "primary_exists",
1142
+ "The subject already has a primary contact. Use setPrimary to move it."
1143
+ );
1144
+ }
1145
+ if (msg.includes(ix.identity) || keys.includes("identity_key")) {
1146
+ return fail(409, "duplicate_contact", "This person is already an active contact on this subject.");
1147
+ }
1148
+ if (msg.includes(ix.id) || keys === "id") {
1149
+ return fail(409, "duplicate_contact_id", "A contact with this id exists.");
1150
+ }
1151
+ return fail(409, "duplicate_key", "The contact collides with a unique index.");
1152
+ }
1153
+ async function insertInAppContact(db, f) {
1154
+ const at = f.now.toISOString();
1155
+ const base = {
1156
+ user_id: null,
1157
+ person_id: null,
1158
+ display_name: f.body.display_name,
1159
+ emails: f.body.emails,
1160
+ phones: f.body.phones ?? []
1161
+ };
1162
+ const doc = {
1163
+ id: f.id,
1164
+ subject_type: f.owner.subject_type,
1165
+ subject_id: f.owner.subject_id,
1166
+ agency_id: f.owner.agency_id,
1167
+ org_id: f.owner.org_id,
1168
+ ...base,
1169
+ purposes: f.body.purposes,
1170
+ urgent_methods: f.body.urgent_methods ?? [],
1171
+ is_primary: false,
1172
+ is_confidential: false,
1173
+ active: true,
1174
+ notes: null,
1175
+ status: pocInitialStatus("in_app"),
1176
+ origin: "in_app",
1177
+ added_in_app: f.app,
1178
+ identity_key: pocIdentityKey(base),
1179
+ confirmed_by: null,
1180
+ confirmed_at: null,
1181
+ deactivated_by: null,
1182
+ deactivated_at: null,
1183
+ version: 1,
1184
+ createdBy: f.actorId,
1185
+ createdAt: at,
1186
+ updatedBy: f.actorId,
1187
+ updatedAt: at
1188
+ };
1189
+ const [broken] = pocRuleViolations(doc);
1190
+ if (broken) return fail(400, broken.reason, broken.message);
1191
+ const noIndexes = await checkPocIndexes(db);
1192
+ if (noIndexes) return noIndexes;
1193
+ try {
1194
+ await db.collection(POINTS_OF_CONTACT_COLLECTION).insertOne({ ...doc });
1195
+ } catch (err) {
1196
+ const dup = pocDuplicateKeyFailure(err);
1197
+ if (dup) return dup;
1198
+ throw err;
1199
+ }
1200
+ return { ok: true, value: doc };
1201
+ }
1202
+ function withReferralTag(purposes) {
1203
+ return [
1204
+ REFERRALS_MAGIC_LINK_PURPOSE,
1205
+ ...purposes.filter((p) => p !== REFERRALS_MAGIC_LINK_PURPOSE)
1206
+ ];
1207
+ }
1208
+ async function mintPartnerContact(db, args, driver) {
1209
+ const actor = args.actor;
1210
+ const actorId = actor && typeof actor === "object" ? actor.id : void 0;
1211
+ if (typeof actorId !== "string" || actorId.trim().length === 0) {
1212
+ return fail(400, "actor_required", "An in-app add names the advocate (their Auth0 sub).");
1213
+ }
1214
+ if (!POC_PARTNER_ADD_APPS.includes(args.app)) {
1215
+ return fail(400, "invalid_app", `An in-app add names its app: ${POC_PARTNER_ADD_APPS.join(", ")}.`);
1216
+ }
1217
+ const parsed = PocInAppSchema.safeParse(args.contact);
1218
+ if (!parsed.success) return invalid(parsed.error, "invalid_contact");
1219
+ const body = { ...parsed.data, purposes: withReferralTag(parsed.data.purposes) };
1220
+ const partner = PartnerContactSelectorSchema.safeParse(args.partner);
1221
+ if (!partner.success) return invalid(partner.error, "invalid_partner");
1222
+ const ids = idsOf(driver);
1223
+ const owner = await resolvePartnerOwner(db, ids, partner.data);
1224
+ if (isFailure(owner)) return owner;
1225
+ const foreign = await refuseForeignPartnerOrg(db, ids, owner.org_id);
1226
+ if (foreign) return foreign;
1227
+ const receipt = (d, created) => ({
1228
+ ok: true,
1229
+ value: {
1230
+ id: d.id,
1231
+ status: d.status,
1232
+ created,
1233
+ subject_type: owner.subject_type,
1234
+ subject_id: owner.subject_id,
1235
+ agency_id: owner.agency_id,
1236
+ org_id: owner.org_id
1237
+ }
1238
+ });
1239
+ const existingNow = async () => classifyExisting(await pocRowsWithIdentity(db, owner, identityOf(body)), body, actorId);
1240
+ const existing = await existingNow();
1241
+ if (existing?.kind === "own_deactivated") {
1242
+ return fail(
1243
+ 409,
1244
+ "contact_deactivated",
1245
+ "You added this contact before and it has since been removed from the partner; it is not added again."
1246
+ );
1247
+ }
1248
+ if (existing) return receipt(existing.doc, false);
1249
+ const capped = await checkPendingCaps(db, owner, actorId);
1250
+ if (capped) return capped;
1251
+ const r = await insertInAppContact(db, {
1252
+ id: ids.newId(),
1253
+ owner,
1254
+ body,
1255
+ app: args.app,
1256
+ actorId,
1257
+ now: args.now ?? /* @__PURE__ */ new Date()
1258
+ });
1259
+ if (!r.ok) {
1260
+ if (r.reason !== "duplicate_pending_add") return r;
1261
+ const raced = await existingNow();
1262
+ return raced && raced.kind !== "own_deactivated" ? receipt(raced.doc, false) : r;
1263
+ }
1264
+ const overCap = await overCapAfterInsert(db, owner, actorId, r.value.id);
1265
+ if (overCap) return overCap;
1266
+ return receipt(r.value, true);
1267
+ }
490
1268
  // Annotate the CommonJS export names for ESM import in node:
491
1269
  0 && (module.exports = {
492
1270
  CONTACT_PURPOSES,
493
1271
  CONTACT_PURPOSE_CODES,
1272
+ PARTNER_CONTACT_FAILURE_REASONS,
494
1273
  POC_ADDED_IN_APPS,
495
1274
  POC_IDENTITY_INDEX_FILTER,
496
1275
  POC_ID_PATTERN,
1276
+ POC_IN_APP_PENDING_CAP_PER_ACTOR,
1277
+ POC_IN_APP_PENDING_CAP_PER_PARTNER,
1278
+ POC_IN_APP_PENDING_INDEX,
1279
+ POC_IN_APP_PENDING_INDEX_FILTER,
1280
+ POC_IN_APP_PENDING_INDEX_KEY,
1281
+ POC_MAX_CONTACT_ENTRIES,
497
1282
  POC_ORIGINS,
1283
+ POC_PARTNER_ADD_APPS,
1284
+ POC_PENDING_QUEUE_INDEX,
498
1285
  POC_PRIMARY_INDEX_FILTER,
499
1286
  POC_STATUSES,
500
1287
  POC_SUBJECT_TYPES,
1288
+ POC_SUBJECT_TYPE_LABELS,
501
1289
  POC_URGENT_METHODS,
502
1290
  POC_URGENT_METHOD_KEYS,
503
1291
  POINTS_OF_CONTACT_COLLECTION,
504
1292
  POINT_OF_CONTACT_INDEXES,
1293
+ PartnerContactSelectorSchema,
505
1294
  PocDetailsSchema,
1295
+ PocEmailListSchema,
506
1296
  PocEmailSchema,
507
1297
  PocInAppSchema,
508
1298
  PocLinkIdSchema,
509
1299
  PocOwnerSchema,
510
1300
  PocPatchSchema,
1301
+ PocPhoneListSchema,
511
1302
  PocSeedSchema,
512
1303
  PointOfContactDocSchema,
513
1304
  PointOfContactShapeError,
514
1305
  REFERRALS_MAGIC_LINK_PURPOSE,
1306
+ StoredContactEntrySchema,
1307
+ StoredEmailListSchema,
1308
+ StoredPhoneListSchema,
515
1309
  byContactReadingOrder,
1310
+ checkPocIndexes,
516
1311
  contactPurposeLabel,
517
1312
  definedPatch,
1313
+ ensurePocIndexes,
1314
+ formatPocPhone,
518
1315
  getContact,
519
1316
  isContactPurposeCode,
520
1317
  isNetworkVisible,
@@ -523,11 +1320,19 @@ async function listPendingContacts(db, opts = {}) {
523
1320
  listOwnerContactsForSubject,
524
1321
  listPendingContacts,
525
1322
  listReferralContactsForPartner,
1323
+ mintPartnerContact,
526
1324
  normalizePointOfContact,
1325
+ pocDuplicateKeyFailure,
527
1326
  pocIdentityKey,
528
1327
  pocInitialStatus,
1328
+ pocPhoneDigits,
1329
+ pocRowsWithIdentity,
529
1330
  pocRuleViolations,
1331
+ pocSubjectTypeLabel,
530
1332
  pocUrgentMethodCode,
1333
+ preferredContactEntry,
1334
+ preferredEmail,
1335
+ preferredPhone,
531
1336
  toNetworkView,
532
1337
  toOwnerView,
533
1338
  toStewardView