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