@htilabs/platform-common-models 0.67.0 → 0.69.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.
@@ -0,0 +1,908 @@
1
+ // src/orgMerge/support.ts
2
+ var text = (v) => typeof v === "string" ? v.trim() : "";
3
+ function comparableName(value) {
4
+ return text(value).normalize("NFKD").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim().replace(/^the /, "");
5
+ }
6
+ var sheetText = (v) => {
7
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
8
+ return /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
9
+ };
10
+
11
+ // src/orgDirectory/orgRecord.ts
12
+ import { z } from "zod";
13
+
14
+ // src/orgDirectory/vocabulary.ts
15
+ var PROGRAM_REVIEW_STATUS = {
16
+ PENDING: "pending",
17
+ CONFIRMED: "confirmed",
18
+ REJECTED: "rejected"
19
+ };
20
+ var PROGRAM_REVIEW_STATUS_VALUES = Object.freeze([
21
+ PROGRAM_REVIEW_STATUS.PENDING,
22
+ PROGRAM_REVIEW_STATUS.CONFIRMED,
23
+ PROGRAM_REVIEW_STATUS.REJECTED
24
+ ]);
25
+ var PROGRAM_STATUS = {
26
+ ACTIVE: "active",
27
+ RETIRED: "retired"
28
+ };
29
+ var PROGRAM_STATUS_VALUES = Object.freeze([
30
+ PROGRAM_STATUS.ACTIVE,
31
+ PROGRAM_STATUS.RETIRED
32
+ ]);
33
+
34
+ // src/orgDirectory/orgRecord.ts
35
+ var ORG_REVIEW_STATUS = PROGRAM_REVIEW_STATUS;
36
+ var ORGANIZATION_STATUS = { ACTIVE: 1, INACTIVE: 2 };
37
+ function isListedOrganization(row) {
38
+ const active = row.status == null || row.status === ORGANIZATION_STATUS.ACTIVE;
39
+ return active && row.reviewStatus !== ORG_REVIEW_STATUS.REJECTED;
40
+ }
41
+ var ORG_RECORD_FIELD_NAMES = Object.freeze([
42
+ "key",
43
+ "legalName",
44
+ "commonName",
45
+ "shortName",
46
+ "website",
47
+ "parentOrgId",
48
+ "vsp",
49
+ "vspPrivateNonprofit",
50
+ "reviewStatus",
51
+ "addedInApp",
52
+ "addedBy"
53
+ ]);
54
+ var ORG_AS_BUILT_FIELD_NAMES = Object.freeze([
55
+ "requiresROI",
56
+ "isCustom",
57
+ "addedByUserId",
58
+ "addedInSession",
59
+ "division",
60
+ "typeOverride",
61
+ "typeKey"
62
+ ]);
63
+ var ORGANIZATION_BASE_ROW_KEYS = Object.freeze([
64
+ "name",
65
+ "type",
66
+ "phones",
67
+ "emails",
68
+ "address",
69
+ "notes",
70
+ "status",
71
+ "agencyScope",
72
+ "agencyId",
73
+ "community",
74
+ "canonicalKey",
75
+ "isAnonymous",
76
+ "programs"
77
+ ]);
78
+ var ORGANIZATION_ROW_KEYS = Object.freeze([
79
+ ...ORGANIZATION_BASE_ROW_KEYS,
80
+ ...ORG_RECORD_FIELD_NAMES,
81
+ ...ORG_AS_BUILT_FIELD_NAMES
82
+ ]);
83
+ var ORGANIZATION_ENVELOPE_KEYS = Object.freeze([
84
+ "_id",
85
+ "__v",
86
+ "_schemaVersion",
87
+ "createdUser",
88
+ "createdTime",
89
+ "updatedUser",
90
+ "updatedTime"
91
+ ]);
92
+ var line = (max) => z.string().trim().min(1).max(max).nullable();
93
+ var ORG_VSP_TWO_STEP_MESSAGE = "vspPrivateNonprofit is step 2 of the HMIS VSP two-step and requires vsp: true";
94
+ var OrgIdentityWriteSchema = z.object({
95
+ legalName: line(300),
96
+ commonName: line(300),
97
+ shortName: line(60),
98
+ website: line(500),
99
+ /** Another organization's id (24-hex or a seed slug). Self-reference is the writer's check. */
100
+ parentOrgId: line(120)
101
+ }).partial().strict();
102
+ var OrgVspWriteSchema = z.object({
103
+ vsp: z.boolean().nullable(),
104
+ vspPrivateNonprofit: z.boolean().nullable()
105
+ }).partial().strict().refine((v) => v.vspPrivateNonprofit == null || v.vsp === true, {
106
+ message: ORG_VSP_TWO_STEP_MESSAGE,
107
+ path: ["vspPrivateNonprofit"]
108
+ }).transform((v) => "vsp" in v && v.vsp !== true ? { ...v, vspPrivateNonprofit: null } : v);
109
+
110
+ // src/orgDirectory/schemas.ts
111
+ import { z as z2 } from "zod";
112
+ var ORGANIZATION_PROGRAM_ROW_KEYS = Object.freeze([
113
+ "programId",
114
+ "name",
115
+ "description",
116
+ "status",
117
+ "defaultSharingPolicy",
118
+ "reviewStatus",
119
+ "addedBy",
120
+ "addedInApp",
121
+ "addedInSession"
122
+ ]);
123
+ var optionalText = z2.string().nullish();
124
+ var OrganizationProgramRowSchema = z2.object({
125
+ programId: z2.string().min(1),
126
+ name: z2.string().min(1),
127
+ description: optionalText,
128
+ status: optionalText,
129
+ defaultSharingPolicy: optionalText,
130
+ reviewStatus: z2.enum(PROGRAM_REVIEW_STATUS_VALUES).nullish(),
131
+ addedBy: optionalText,
132
+ addedInApp: optionalText,
133
+ addedInSession: optionalText
134
+ });
135
+
136
+ // src/orgDirectory/rules.ts
137
+ function directoryIdString(value) {
138
+ if (typeof value === "string") return value === "" ? null : value;
139
+ if (value && typeof value === "object" && typeof value.toHexString === "function") {
140
+ return value.toHexString();
141
+ }
142
+ return null;
143
+ }
144
+
145
+ // src/orgDirectory/read.ts
146
+ var ORGANIZATIONS_COLLECTION = "organizations";
147
+ var AGENCIES_COLLECTION = "agencies";
148
+
149
+ // src/pointsOfContact/schemas.ts
150
+ import { z as z3 } from "zod";
151
+
152
+ // src/cvcs/preferredContactMethod.v1.0.0.json
153
+ var preferredContactMethod_v1_0_0_default = {
154
+ domain: "preferred_contact_method",
155
+ name: "Core Preferred Contact Method",
156
+ version: "1.0.0",
157
+ levels: {
158
+ "1": "Contact method"
159
+ },
160
+ entries: [
161
+ {
162
+ code: "185-001-000-000-000-000-000",
163
+ key: "call",
164
+ title: "Call",
165
+ selectable: true,
166
+ parentCode: null,
167
+ childCodes: [],
168
+ definition: "Voice telephone call to a reachable phone number."
169
+ },
170
+ {
171
+ code: "185-002-000-000-000-000-000",
172
+ key: "text",
173
+ title: "Text / SMS",
174
+ selectable: true,
175
+ parentCode: null,
176
+ childCodes: [],
177
+ definition: "SMS or text message to a reachable mobile number."
178
+ },
179
+ {
180
+ code: "185-003-000-000-000-000-000",
181
+ key: "email",
182
+ title: "Email",
183
+ selectable: true,
184
+ parentCode: null,
185
+ childCodes: [],
186
+ definition: "Electronic mail to a reachable email address."
187
+ },
188
+ {
189
+ code: "185-004-000-000-000-000-000",
190
+ key: "messaging_app_dm",
191
+ title: "Messaging app DM",
192
+ selectable: true,
193
+ parentCode: null,
194
+ childCodes: [],
195
+ definition: "Direct message on a messaging application (generic). The specific application is captured at the contact entry (see CVC-149 contact_info_types); this CVC records only the channel-class preference."
196
+ }
197
+ ]
198
+ };
199
+
200
+ // src/pointsOfContact/vocabulary.ts
201
+ var POC_SUBJECT_TYPES = ["agency", "org", "program", "team", "location", "service"];
202
+ var CONTACT_PURPOSE_CODES = [
203
+ "COMPLIANCE",
204
+ "TRAINING",
205
+ "REFERRALS_MAGIC_LINK",
206
+ "BILLING",
207
+ "DATA_REPORTING",
208
+ "PROGRAM_CONTACT",
209
+ "REFERRAL_CONTACT",
210
+ "DIRECTOR"
211
+ ];
212
+ var CONTACT_PURPOSES = [
213
+ { code: "COMPLIANCE", label: "Compliance", level: "agency" },
214
+ { code: "TRAINING", label: "Training", level: "agency" },
215
+ { code: "REFERRALS_MAGIC_LINK", label: "Referrals (magic link)", level: "agency" },
216
+ { code: "BILLING", label: "Billing", level: "agency" },
217
+ { code: "DATA_REPORTING", label: "Data & reporting", level: "agency" },
218
+ { code: "PROGRAM_CONTACT", label: "Program contact", level: "program" },
219
+ { code: "REFERRAL_CONTACT", label: "Referral contact", level: "program" },
220
+ { code: "DIRECTOR", label: "Program Director", level: "program" }
221
+ ];
222
+ var REFERRALS_MAGIC_LINK_PURPOSE = "REFERRALS_MAGIC_LINK";
223
+ var PURPOSE_BY_CODE = new Map(CONTACT_PURPOSES.map((p) => [p.code, p]));
224
+ var POC_URGENT_METHOD_KEYS = ["email", "call", "text"];
225
+ var CVC185_ENTRIES = preferredContactMethod_v1_0_0_default.entries;
226
+ function cvc185Entry(key) {
227
+ const e = CVC185_ENTRIES.find((x) => x.key === key);
228
+ if (!e) throw new Error(`points-of-contact: CVC-185 preferred_contact_method has no key "${key}"`);
229
+ return e;
230
+ }
231
+ var POC_URGENT_METHODS = POC_URGENT_METHOD_KEYS.map((k) => {
232
+ const e = cvc185Entry(k);
233
+ return { key: e.key, code: e.code, title: e.title, selectable: e.selectable !== false };
234
+ });
235
+ var URGENT_BY_CODE = new Map(POC_URGENT_METHODS.map((m) => [m.code, m]));
236
+ function isPocUrgentMethodCode(code) {
237
+ return typeof code === "string" && URGENT_BY_CODE.get(code)?.selectable === true;
238
+ }
239
+ var POC_STATUSES = ["pending", "confirmed"];
240
+ var POC_ORIGINS = ["survey", "admin_hub", "in_app", "steward_seed"];
241
+ var POC_ADDED_IN_APPS = ["pave", "thread", "leads", "platform"];
242
+
243
+ // src/pointsOfContact/schemas.ts
244
+ var POINTS_OF_CONTACT_COLLECTION = "pointsofcontact";
245
+ var POC_ID_PATTERN = /^poc-[a-z0-9_-]+$/;
246
+ var HEX_24 = /^[0-9a-fA-F]{24}$/;
247
+ var idString = z3.string().trim().min(1).max(200);
248
+ var text2 = (max) => z3.string().trim().min(1).max(max);
249
+ var PocLinkIdSchema = idString.transform((v) => HEX_24.test(v) ? v.toLowerCase() : v);
250
+ var PocEmailSchema = z3.string().trim().toLowerCase().email("Not an email address.").max(254);
251
+ var PurposesSchema = z3.array(z3.enum(CONTACT_PURPOSE_CODES)).max(CONTACT_PURPOSE_CODES.length).transform((list) => [...new Set(list)]);
252
+ var UrgentMethodsSchema = z3.array(
253
+ z3.string().refine(isPocUrgentMethodCode, {
254
+ message: "urgent_methods holds selectable CVC-185 preferred_contact_method codes from the Agency Hub subset (email \xB7 call \xB7 text)."
255
+ })
256
+ ).max(3).transform((list) => [...new Set(list)]);
257
+ var POC_MAX_CONTACT_ENTRIES = 10;
258
+ var StoredContactEntrySchema = z3.object({
259
+ /** An email (lowercased) or a phone as typed (trimmed). */
260
+ value: z3.string(),
261
+ /** Exactly one entry of a non-empty list is the preferred one. */
262
+ is_preferred: z3.boolean()
263
+ });
264
+ var ReadContactEntrySchema = StoredContactEntrySchema.extend({
265
+ is_preferred: z3.boolean().nullish().transform((v) => v === true)
266
+ });
267
+ function pocPhoneDigits(v) {
268
+ const d = v.replace(/\D/g, "");
269
+ return d.length === 11 && d.charAt(0) === "1" ? d.slice(1) : d;
270
+ }
271
+ var emailKey = (v) => v.trim().toLowerCase();
272
+ function settlePreferred(list) {
273
+ const at = list.findIndex((e) => e.is_preferred);
274
+ const keep = at < 0 ? 0 : at;
275
+ return list.map((e, i) => ({ value: e.value, is_preferred: i === keep }));
276
+ }
277
+ function readEntries(list, clean, keyOf) {
278
+ const seen = /* @__PURE__ */ new Set();
279
+ const out = [];
280
+ for (const e of list) {
281
+ const value = clean(e.value);
282
+ const k = value ? keyOf(value) : "";
283
+ if (!k || seen.has(k)) continue;
284
+ seen.add(k);
285
+ out.push({ value, is_preferred: e.is_preferred });
286
+ }
287
+ return settlePreferred(out);
288
+ }
289
+ var StoredEmailListSchema = z3.array(ReadContactEntrySchema).transform((l) => readEntries(l, emailKey, (v) => v));
290
+ var StoredPhoneListSchema = z3.array(ReadContactEntrySchema).transform((l) => readEntries(l, (v) => v.trim(), pocPhoneDigits));
291
+ function entryListSchema(value, keyOf, noun) {
292
+ return z3.array(z3.object({ value, is_preferred: z3.boolean().optional() }).strict()).max(POC_MAX_CONTACT_ENTRIES).superRefine((list, ctx) => {
293
+ if (list.filter((e) => e.is_preferred === true).length > 1) {
294
+ ctx.addIssue({ code: "custom", message: `A contact has at most one preferred ${noun}.` });
295
+ }
296
+ const seen = /* @__PURE__ */ new Set();
297
+ list.forEach((e, i) => {
298
+ const k = keyOf(e.value);
299
+ if (seen.has(k)) {
300
+ ctx.addIssue({
301
+ code: "custom",
302
+ path: [i, "value"],
303
+ message: `The same ${noun} appears twice on one contact.`
304
+ });
305
+ }
306
+ seen.add(k);
307
+ });
308
+ }).transform(
309
+ (list) => settlePreferred(list.map((e) => ({ value: e.value, is_preferred: e.is_preferred === true })))
310
+ );
311
+ }
312
+ var PocEmailListSchema = entryListSchema(PocEmailSchema, (v) => v, "email");
313
+ var PocPhoneValueSchema = text2(40).refine((v) => /\d/.test(v), {
314
+ message: "A phone number has at least one digit."
315
+ });
316
+ var PocPhoneListSchema = entryListSchema(PocPhoneValueSchema, pocPhoneDigits, "phone");
317
+ var PocOwnerSchema = z3.object({
318
+ subject_type: z3.enum(POC_SUBJECT_TYPES),
319
+ subject_id: idString,
320
+ agency_id: idString.nullable(),
321
+ org_id: idString.nullable()
322
+ }).strict().superRefine((o, ctx) => {
323
+ if (o.subject_type === "agency" && o.subject_id !== o.agency_id) {
324
+ ctx.addIssue({ code: "custom", path: ["subject_id"], message: "An agency's own contact names that agency: subject_id must equal agency_id." });
325
+ }
326
+ if (o.subject_type === "org" && o.subject_id !== o.org_id) {
327
+ ctx.addIssue({ code: "custom", path: ["subject_id"], message: "An org's own contact names that org: subject_id must equal org_id." });
328
+ }
329
+ if ((o.subject_type === "program" || o.subject_type === "team" || o.subject_type === "location") && !o.agency_id) {
330
+ ctx.addIssue({ code: "custom", path: ["agency_id"], message: `A ${o.subject_type} contact names the agency it belongs to.` });
331
+ }
332
+ if (o.subject_type === "service" && !o.org_id) {
333
+ ctx.addIssue({ code: "custom", path: ["org_id"], message: "A service listing's contact names the listing's organization." });
334
+ }
335
+ });
336
+ var PocDetailsSchema = z3.object({
337
+ user_id: PocLinkIdSchema.nullable().optional(),
338
+ person_id: PocLinkIdSchema.nullable().optional(),
339
+ display_name: text2(200).nullable().optional(),
340
+ emails: PocEmailListSchema.optional(),
341
+ phones: PocPhoneListSchema.optional(),
342
+ purposes: PurposesSchema.optional(),
343
+ urgent_methods: UrgentMethodsSchema.optional(),
344
+ is_primary: z3.boolean().optional(),
345
+ is_confidential: z3.boolean().optional(),
346
+ notes: text2(2e3).nullable().optional()
347
+ }).strict();
348
+ var PocInAppSchema = z3.object({
349
+ display_name: text2(200),
350
+ emails: PocEmailListSchema.refine((l) => l.length > 0, { message: "An in-app add names at least one email." }),
351
+ phones: PocPhoneListSchema.optional(),
352
+ purposes: PurposesSchema.default([REFERRALS_MAGIC_LINK_PURPOSE]),
353
+ urgent_methods: UrgentMethodsSchema.optional()
354
+ }).strict();
355
+ var PocSeedSchema = PocDetailsSchema.extend({
356
+ id: z3.string().trim().regex(POC_ID_PATTERN, "A seeded contact id is poc-<lowercase letters, digits, '_' or '-'>.")
357
+ }).strict();
358
+ var PocPatchSchema = PocDetailsSchema.omit({ user_id: true, person_id: true }).strict().refine((b) => Object.values(b).some((v) => v !== void 0), {
359
+ message: "A contact edit must name at least one field."
360
+ });
361
+ var nullableString = z3.string().nullable();
362
+ var PointOfContactDocSchema = z3.object({
363
+ id: z3.string().min(1),
364
+ subject_type: z3.enum(POC_SUBJECT_TYPES),
365
+ subject_id: z3.string().min(1),
366
+ agency_id: nullableString,
367
+ org_id: nullableString,
368
+ user_id: nullableString,
369
+ person_id: nullableString,
370
+ display_name: nullableString,
371
+ /** Lowercased emails, read leniently. Empty on a seat-linked contact (it resolves from the seat). */
372
+ emails: StoredEmailListSchema,
373
+ /** Read leniently. Empty on a seat-linked contact. */
374
+ phones: StoredPhoneListSchema,
375
+ purposes: z3.array(z3.enum(CONTACT_PURPOSE_CODES)),
376
+ /** CVC-185 codes. */
377
+ urgent_methods: z3.array(z3.string()),
378
+ is_primary: z3.boolean(),
379
+ is_confidential: z3.boolean(),
380
+ /** A removed contact is deactivated, never deleted. */
381
+ active: z3.boolean(),
382
+ notes: nullableString,
383
+ status: z3.enum(POC_STATUSES),
384
+ origin: z3.enum(POC_ORIGINS),
385
+ added_in_app: z3.enum(POC_ADDED_IN_APPS).nullable(),
386
+ /** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<preferred email>`, lowercased. */
387
+ identity_key: z3.string().min(1),
388
+ confirmed_by: nullableString,
389
+ confirmed_at: nullableString,
390
+ deactivated_by: nullableString,
391
+ deactivated_at: nullableString,
392
+ /** Bumped by every write; edits and the steward's confirm name the version they saw. */
393
+ version: z3.number().int().nonnegative(),
394
+ createdBy: nullableString,
395
+ createdAt: z3.string().min(1),
396
+ updatedBy: nullableString,
397
+ updatedAt: z3.string().min(1)
398
+ });
399
+
400
+ // src/serviceListings/vocabulary.ts
401
+ var LISTING_TIERS = ["primary", "additional"];
402
+ var ACCESS_PATHS = [
403
+ "Referral required",
404
+ "Hotline",
405
+ "Walk-in",
406
+ "Law enforcement initiated",
407
+ "Court/probation initiated"
408
+ ];
409
+ var STORED_VERIFICATION_STATUSES = ["pending", "verified"];
410
+ var ADDED_IN_APPS = ["pave", "thread", "leads", "platform"];
411
+ var LISTING_REVIEW_STATUSES = ["pending", "confirmed", "rejected"];
412
+ var LISTING_ORIGINS = ["survey", "admin_hub", "steward_seed"];
413
+
414
+ // src/serviceListings/schemas.ts
415
+ import { z as z4 } from "zod";
416
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
417
+ var LISTING_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
418
+ var IsoDateSchema = z4.string().regex(ISO_DATE, "Expected an ISO date (YYYY-MM-DD).").refine((s) => {
419
+ const d = /* @__PURE__ */ new Date(`${s}T00:00:00Z`);
420
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
421
+ }, "Not a real calendar date.");
422
+ var DirectoryIdSchema = z4.string().trim().min(1);
423
+ var ListingIdSchema = z4.string().regex(LISTING_ID, "A listing id is letters, digits, '.', '_' or '-'.");
424
+ var ServiceCategoryKeySchema = z4.string().trim().regex(/^[a-z][a-z0-9_]*$/, "Not a CVC key.");
425
+ var text3 = z4.string().trim();
426
+ var optionalText2 = text3.nullable().optional();
427
+ var ServiceListingDetailsSchema = z4.object({
428
+ program_id: DirectoryIdSchema.nullable().optional(),
429
+ agency_id: DirectoryIdSchema.nullable().optional(),
430
+ tier: z4.enum(LISTING_TIERS).nullable().optional(),
431
+ ht_specific: z4.boolean().nullable().optional(),
432
+ sector: optionalText2,
433
+ populations: z4.array(text3.min(1)).optional(),
434
+ access_path: z4.enum(ACCESS_PATHS).nullable().optional(),
435
+ jurisdiction: optionalText2,
436
+ hours: optionalText2,
437
+ eligibility: optionalText2,
438
+ cost: optionalText2,
439
+ contact_name: optionalText2,
440
+ contact_email: optionalText2,
441
+ contact_phone: optionalText2,
442
+ contact_city: optionalText2,
443
+ contact_state: optionalText2,
444
+ confidential: z4.boolean().optional()
445
+ }).strict();
446
+ var ServiceListingPatchSchema = ServiceListingDetailsSchema.refine(
447
+ (b) => Object.keys(b).length > 0,
448
+ { message: "A listing edit must name at least one field." }
449
+ );
450
+ var MintListingBodySchema = ServiceListingDetailsSchema.extend({
451
+ vscat_key: ServiceCategoryKeySchema
452
+ }).strict();
453
+ var SeedListingBodySchema = MintListingBodySchema.extend({
454
+ id: ListingIdSchema.optional(),
455
+ verification_status: z4.enum(STORED_VERIFICATION_STATUSES).optional(),
456
+ last_verified: IsoDateSchema.nullable().optional()
457
+ }).strict().refine((b) => b.verification_status !== "verified" || !!b.last_verified, {
458
+ message: "A verified listing carries the date it was verified (last_verified).",
459
+ path: ["last_verified"]
460
+ });
461
+ var nullableText = z4.string().nullable();
462
+ var StoredServiceListingSchema = z4.object({
463
+ id: ListingIdSchema,
464
+ org_id: DirectoryIdSchema,
465
+ program_id: DirectoryIdSchema.nullable(),
466
+ agency_id: DirectoryIdSchema.nullable(),
467
+ vscat_key: ServiceCategoryKeySchema,
468
+ vscat_code: z4.string(),
469
+ vscat_label: z4.string(),
470
+ tier: z4.enum(LISTING_TIERS).nullable(),
471
+ ht_specific: z4.boolean().nullable(),
472
+ sector: nullableText,
473
+ populations: z4.array(z4.string()),
474
+ access_path: z4.enum(ACCESS_PATHS).nullable(),
475
+ jurisdiction: nullableText,
476
+ hours: nullableText,
477
+ eligibility: nullableText,
478
+ cost: nullableText,
479
+ contact_name: nullableText,
480
+ contact_email: nullableText,
481
+ contact_phone: nullableText,
482
+ contact_city: nullableText,
483
+ contact_state: nullableText,
484
+ confidential: z4.boolean(),
485
+ verification_status: z4.enum(STORED_VERIFICATION_STATUSES),
486
+ last_verified: IsoDateSchema.nullable(),
487
+ origin: z4.enum(LISTING_ORIGINS),
488
+ added_by: nullableText,
489
+ added_in_app: z4.enum(ADDED_IN_APPS).nullable(),
490
+ review_status: z4.enum(LISTING_REVIEW_STATUSES).nullable(),
491
+ removal_requested_at: nullableText,
492
+ removal_requested_by: nullableText,
493
+ version: z4.number().int().min(1),
494
+ createdBy: nullableText,
495
+ createdAt: z4.string(),
496
+ updatedBy: nullableText,
497
+ updatedAt: z4.string()
498
+ });
499
+
500
+ // src/serviceListings/read.ts
501
+ var SERVICE_LISTINGS_COLLECTION = "servicelistings";
502
+
503
+ // src/orgMerge/orgMerge.ts
504
+ var text4 = (v) => typeof v === "string" ? v.trim() : "";
505
+ var blank = (v) => v == null || typeof v === "string" && v.trim() === "";
506
+ var idText = (v) => directoryIdString(v) ?? String(v);
507
+ var HEX_242 = /^[0-9a-fA-F]{24}$/;
508
+ var message = (err) => err instanceof Error ? err.message : String(err);
509
+ var idOf = (driver, v) => typeof v === "string" ? v.trim().toLowerCase() : v instanceof driver.ObjectId ? v.toHexString() : null;
510
+ function idForms(driver, id) {
511
+ const s = idText(id);
512
+ return HEX_242.test(s) ? [new driver.ObjectId(s.toLowerCase()), s.toLowerCase()] : [s];
513
+ }
514
+ function inFormOf(driver, from, keptId) {
515
+ const s = idText(keptId);
516
+ return from instanceof driver.ObjectId && HEX_242.test(s) ? new driver.ObjectId(s.toLowerCase()) : s.toLowerCase();
517
+ }
518
+ var THREAD_SAMPLE_ID_PREFIX = "64e4ff1c2a7dcd9cb5f4a";
519
+ var APP_LABEL = { platform: "the platform", thread: "Thread", pave: "PAVE" };
520
+ var ORG_REFERENCES = Object.freeze([
521
+ { app: "platform", collection: "personnelpeople", kind: "value", path: "organizationId", writtenBy: "auth at a first sign-in; Thread's staff records" },
522
+ { app: "platform", collection: ORGANIZATIONS_COLLECTION, kind: "value", path: "parentOrgId", writtenBy: "an Org that is a unit of this one" },
523
+ { app: "platform", collection: SERVICE_LISTINGS_COLLECTION, kind: "value", path: "org_id", writtenBy: "service listings" },
524
+ { app: "platform", collection: POINTS_OF_CONTACT_COLLECTION, kind: "value", path: "org_id", writtenBy: "points of contact" },
525
+ { app: "platform", collection: POINTS_OF_CONTACT_COLLECTION, kind: "value", path: "subject_id", writtenBy: "an Org's own point of contact" },
526
+ { app: "platform", collection: "personnelmergefolds", kind: "value", path: "survivorBefore.organizationId", writtenBy: "Thread's staff-record merge log" },
527
+ { app: "platform", collection: "personnelmergefolds", kind: "value", path: "survivorChange.liftedOrganizationId", writtenBy: "Thread's staff-record merge log" },
528
+ { app: "platform", collection: "surveyedOrganizations", kind: "value", path: "directoryOrganizationId", writtenBy: "the Platform app's agency survey link" },
529
+ { app: "platform", collection: "accountPolicies", kind: "value", path: "orgRef", writtenBy: "the Platform app's account-policy seed" },
530
+ { app: "platform", collection: AGENCIES_COLLECTION, kind: "list", path: "reportingDestinations.designated.mandatory_reporting", writtenBy: "the Platform app's reporting destinations" },
531
+ { app: "platform", collection: AGENCIES_COLLECTION, kind: "list", path: "reportingDestinations.designated.authority_reporting", writtenBy: "the Platform app's reporting destinations" },
532
+ { app: "thread", collection: "caserecords", kind: "value", path: "referralOrganizationId", writtenBy: "a case's referring organization" },
533
+ { app: "thread", collection: "caserecords", kind: "rows", path: "identifierEntries", field: "usedByOrgId", writtenBy: "a case number's organization" },
534
+ { app: "thread", collection: "submissions", kind: "answers", path: "answers", field: "val", writtenBy: "a form answer naming an organization (the referring-organization question)" },
535
+ { app: "thread", collection: "casesessions", kind: "list", path: "relevantOrganizationIds", writtenBy: "organizations added in a session" },
536
+ { app: "thread", collection: "serviceinstances", kind: "value", path: "referralToOrganizationId", writtenBy: "a service's referral" },
537
+ { app: "thread", collection: "serviceinstances", kind: "value", path: "serviceProviderOrganizationId", writtenBy: "a service's provider" },
538
+ { app: "thread", collection: "personnelpeople", kind: "value", path: "organizationId", writtenBy: "staff records" },
539
+ { app: "thread", collection: "personinteracteds", kind: "value", path: "organizationId", writtenBy: "people a case interacted with" },
540
+ { app: "pave", collection: "protectedpeople", kind: "value", path: "organizationId", writtenBy: "a person's organization" },
541
+ { app: "pave", collection: "relevantpersons", kind: "value", path: "organizationId", writtenBy: "a relevant person's organization" },
542
+ { app: "pave", collection: "serviceinstances", kind: "value", path: "serviceProviderOrgId", writtenBy: "a service's provider" },
543
+ { app: "pave", collection: "serviceinstances", kind: "value", path: "referralToOrganizationId", writtenBy: "a service's referral" },
544
+ { app: "pave", collection: "programhousingenrollments", kind: "value", path: "providerOrgId", writtenBy: "a housing program's provider" },
545
+ { app: "pave", collection: "householdpets", kind: "value", path: "providerOrgId", writtenBy: "a pet program's provider" },
546
+ { app: "pave", collection: "disclosure_records", kind: "value", path: "recipientOrg", writtenBy: "a disclosure's recipient" },
547
+ { app: "pave", collection: "reportingdestinationconfigs", kind: "list", path: "organizationIds", writtenBy: "reporting destinations" },
548
+ { app: "pave", collection: "casesessions", kind: "list", path: "relevantOrganizationIds", writtenBy: "organizations added in a session" },
549
+ { app: "pave", collection: "sharingsettings", kind: "count", path: "organizationId", writtenBy: "a sharing grant to a partner organization (never moved: sharing rules are not merged)" }
550
+ ]);
551
+ var APP_DATABASE_KINDS = ["thread", "pave"];
552
+ var APP_MARKER = { thread: "caserecords", pave: "protectedpeople" };
553
+ async function appDatabaseProblem(app, name, db) {
554
+ const found = await db.listCollections({ name: APP_MARKER[app] }, { nameOnly: true }).toArray();
555
+ return found.length ? null : `'${name}' has no ${APP_MARKER[app]} collection, so it is not a ${APP_LABEL[app]} database (check the name)`;
556
+ }
557
+ var refPath = (r) => r.kind === "rows" || r.kind === "answers" ? `${r.path}.${String(r.field)}` : r.path;
558
+ function getPath(doc, path) {
559
+ return path.split(".").reduce((v, k) => v && typeof v === "object" ? v[k] : void 0, doc);
560
+ }
561
+ function rewriteIds(driver, list, copy, kept) {
562
+ const keptHex = idText(kept).toLowerCase();
563
+ let hasKept = list.some((v) => idOf(driver, v) === keptHex);
564
+ const out = [];
565
+ for (const v of list) {
566
+ if (idOf(driver, v) !== copy) out.push(v);
567
+ else if (!hasKept) {
568
+ out.push(inFormOf(driver, v, kept));
569
+ hasKept = true;
570
+ }
571
+ }
572
+ return out;
573
+ }
574
+ function rewriteRows(driver, rows, field, copy, kept) {
575
+ const key = (r) => r && typeof r === "object" ? JSON.stringify({ ...r, [field]: idOf(driver, r[field]) }) : JSON.stringify(r);
576
+ const isCopyRow = (r) => !!r && typeof r === "object" && idOf(driver, r[field]) === copy;
577
+ const seen = new Set(rows.filter((r) => !isCopyRow(r)).map(key));
578
+ const out = [];
579
+ for (const r of rows) {
580
+ if (!isCopyRow(r)) {
581
+ out.push(r);
582
+ continue;
583
+ }
584
+ const moved = { ...r, [field]: inFormOf(driver, r[field], kept) };
585
+ if (seen.has(key(moved))) continue;
586
+ seen.add(key(moved));
587
+ out.push(moved);
588
+ }
589
+ return out;
590
+ }
591
+ function rewriteAnswers(driver, answers, field, copy, kept) {
592
+ return answers.map((a) => {
593
+ const vals = a && typeof a === "object" ? a[field] : void 0;
594
+ return Array.isArray(vals) && vals.some((v) => idOf(driver, v) === copy) ? { ...a, [field]: rewriteIds(driver, vals, copy, kept) } : a;
595
+ });
596
+ }
597
+ async function findReferences(driver, dbs, orgId, keptId) {
598
+ const out = [];
599
+ const copy = idText(orgId).toLowerCase();
600
+ for (const d of dbs) {
601
+ for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app)) {
602
+ if (ref.kind === "count") continue;
603
+ const base = { db: d.name, collection: ref.collection, kind: ref.kind, path: ref.path, ...ref.field ? { field: ref.field } : {} };
604
+ if (ref.kind === "value") {
605
+ for (const from of idForms(driver, orgId)) {
606
+ const docs2 = await d.db.collection(ref.collection).find({ [ref.path]: from }, { projection: { _id: 1 } }).toArray();
607
+ for (const doc of docs2) out.push({ ...base, docId: doc._id, from, to: inFormOf(driver, from, keptId) });
608
+ }
609
+ continue;
610
+ }
611
+ const docs = await d.db.collection(ref.collection).find({ [refPath(ref)]: { $in: idForms(driver, orgId) } }, { projection: { _id: 1, [ref.path]: 1 }, promoteValues: false }).toArray();
612
+ for (const doc of docs) {
613
+ const before = getPath(doc, ref.path);
614
+ if (!Array.isArray(before)) continue;
615
+ const after = ref.kind === "list" ? rewriteIds(driver, before, copy, keptId) : ref.kind === "rows" ? rewriteRows(driver, before, String(ref.field), copy, keptId) : rewriteAnswers(driver, before, String(ref.field), copy, keptId);
616
+ out.push({ ...base, docId: doc._id, from: copy, to: idText(keptId).toLowerCase(), before, after });
617
+ }
618
+ }
619
+ }
620
+ return out;
621
+ }
622
+ async function countReferences(driver, dbs, orgId, only) {
623
+ let n = 0;
624
+ for (const d of dbs) {
625
+ for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app && (!only || r.kind === only))) {
626
+ n += await d.db.collection(ref.collection).countDocuments({ [refPath(ref)]: { $in: idForms(driver, orgId) } });
627
+ }
628
+ if (d.app === "platform" && !only) {
629
+ n += await d.db.collection(AGENCIES_COLLECTION).countDocuments({ organizationId: { $in: idForms(driver, orgId) } });
630
+ }
631
+ }
632
+ return n;
633
+ }
634
+ async function repoint(db, ref, back) {
635
+ const coll = db.collection(ref.collection);
636
+ if (ref.kind === "value") {
637
+ const [from2, to2] = back ? [ref.to, ref.from] : [ref.from, ref.to];
638
+ return (await coll.updateOne({ _id: ref.docId, [ref.path]: from2 }, { $set: { [ref.path]: to2 } })).matchedCount === 1;
639
+ }
640
+ const [from, to] = back ? [ref.after, ref.before] : [ref.before, ref.after];
641
+ return (await coll.updateOne({ _id: ref.docId, [ref.path]: from }, { $set: { [ref.path]: to } })).matchedCount === 1;
642
+ }
643
+ async function holdsMerged(db, ref) {
644
+ const filter = ref.kind === "value" ? { _id: ref.docId, [ref.path]: ref.to } : { _id: ref.docId, [ref.path]: ref.after };
645
+ return await db.collection(ref.collection).countDocuments(filter) === 1;
646
+ }
647
+ var MERGE = "merge";
648
+ var YES = "yes";
649
+ async function planMerges(dbs, lines, driver) {
650
+ const platform = dbs[0];
651
+ const orgs = platform.db.collection(ORGANIZATIONS_COLLECTION);
652
+ const agencies = platform.db.collection(AGENCIES_COLLECTION);
653
+ const unchecked = APP_DATABASE_KINDS.filter((k) => !dbs.some((d) => d.app === k));
654
+ const listAgency = async (org) => blank(org.agencyScope) ? null : await agencies.findOne({ _id: { $in: idForms(driver, org.agencyScope) } }, { projection: { name: 1, state: 1 } });
655
+ const listOf = async (org) => {
656
+ if (blank(org.agencyScope)) return "in no agency's list";
657
+ const a = await listAgency(org);
658
+ return `in the list of ${a ? text4(a.name) || idText(org.agencyScope) : `agency ${idText(org.agencyScope)}, which is not in this database`}`;
659
+ };
660
+ const isUnitOf = async (kept, copyId) => {
661
+ const seen = /* @__PURE__ */ new Set();
662
+ let parent = kept.parentOrgId;
663
+ for (let depth = 0; depth < 25 && !blank(parent); depth += 1) {
664
+ const id = idOf(driver, parent);
665
+ if (id === null || seen.has(id)) return false;
666
+ if (id === copyId) return true;
667
+ seen.add(id);
668
+ const next = await orgs.findOne({ _id: { $in: idForms(driver, parent) } }, { projection: { parentOrgId: 1 } });
669
+ parent = next?.parentOrgId;
670
+ }
671
+ return false;
672
+ };
673
+ const out = [];
674
+ for (const line2 of lines) {
675
+ const one = async (id) => {
676
+ const found = await orgs.find({ _id: { $in: idForms(driver, id) } }).limit(2).toArray();
677
+ return found.length === 1 ? found[0] : null;
678
+ };
679
+ const dup = await one(line2.duplicateId);
680
+ const kept = await one(line2.keptId);
681
+ const base = {
682
+ line: line2,
683
+ duplicateName: dup ? text4(dup.name) : "",
684
+ keptName: kept ? text4(kept.name) : "",
685
+ duplicateList: dup ? await listOf(dup) : "",
686
+ keptList: kept ? await listOf(kept) : ""
687
+ };
688
+ const flags = [];
689
+ const skip = (detail) => {
690
+ out.push({ ...base, status: "skip", detail, flags });
691
+ };
692
+ if (line2.duplicateId.trim().toLowerCase() === line2.keptId.trim().toLowerCase()) {
693
+ skip("the copy and the kept organization are the same row");
694
+ continue;
695
+ }
696
+ const mergedFrom = kept?.legacy_ids?.merged_from;
697
+ const listed = Array.isArray(mergedFrom) && mergedFrom.includes(line2.duplicateId);
698
+ if (!dup && kept && listed) {
699
+ out.push({ ...base, status: "already", detail: "already merged: the copy is gone and the kept organization records its id", flags });
700
+ continue;
701
+ }
702
+ if (!dup || !kept) {
703
+ skip(`no organization has the id ${!dup ? line2.duplicateId : line2.keptId}`);
704
+ continue;
705
+ }
706
+ const misnamed = [
707
+ ["copy", line2.duplicateName, base.duplicateName],
708
+ ["kept organization", line2.keptName, base.keptName]
709
+ ].find(([, onSheet, stored]) => onSheet.trim() !== stored && onSheet.trim() !== sheetText(stored).trim());
710
+ if (misnamed) {
711
+ skip(`the sheet names the ${misnamed[0]} ${JSON.stringify(misnamed[1].trim())}, the database names it ${JSON.stringify(misnamed[2])}`);
712
+ continue;
713
+ }
714
+ if (!blank(dup.canonicalKey)) {
715
+ skip("the copy is a canonical singleton (Unknown / Anonymous); never merged");
716
+ continue;
717
+ }
718
+ const pointing = await agencies.countDocuments({ organizationId: { $in: idForms(driver, dup._id) } });
719
+ if (!blank(dup.agencyId) || pointing) {
720
+ skip("the copy is an Agency's own organization (it names an Agency, or an Agency points at it): that is not a copy");
721
+ continue;
722
+ }
723
+ if (Array.isArray(dup.programs) && dup.programs.length) {
724
+ skip("the copy has programs; merging programs is not supported");
725
+ continue;
726
+ }
727
+ if (!isListedOrganization(kept)) {
728
+ skip("the kept organization is inactive or declined: nothing is merged into a row that is not offered");
729
+ continue;
730
+ }
731
+ if (await isUnitOf(kept, idText(dup._id).toLowerCase())) {
732
+ skip("the kept organization is a unit of the copy (the copy is on its chain of parent organizations)");
733
+ continue;
734
+ }
735
+ if (comparableName(dup.name) !== comparableName(kept.name)) {
736
+ if (!line2.differentNameOk) {
737
+ skip(`the two names differ: write ${YES} in different_name_ok on this line if they are one organization`);
738
+ continue;
739
+ }
740
+ flags.push("the names differ; the sheet says they are one organization");
741
+ }
742
+ const sameList = !blank(kept.agencyScope) && idText(kept.agencyScope) === idText(dup.agencyScope);
743
+ const viewer = await listAgency(dup);
744
+ const state = typeof viewer?.state === "string" ? viewer.state : "";
745
+ const community = typeof kept.community === "string" ? kept.community : "";
746
+ if (!sameList && !(state !== "" && state === community)) {
747
+ skip(
748
+ `the kept organization could not be seen by the agency whose list the copy is in: the copy is ${base.duplicateList} (that agency's state ${JSON.stringify(state)}), the kept row is ${base.keptList} (community ${JSON.stringify(community)}). An agency sees another list's organization only when its state is exactly that organization's community. The kept row's list or community is corrected first, by a deliberate edit`
749
+ );
750
+ continue;
751
+ }
752
+ const keyed = !blank(dup.key);
753
+ if (keyed) {
754
+ flags.push(
755
+ `the copy carries the identifier ${String(dup.key)}: identifiers never move${blank(kept.key) ? " (the kept organization has none; the key sheet gives it one)" : ""}, so the copy is kept as inactive`
756
+ );
757
+ }
758
+ const refs = await findReferences(driver, dbs, dup._id, kept._id);
759
+ const grants = await countReferences(driver, dbs, dup._id, "count");
760
+ const outcome = keyed || grants || unchecked.length ? "retire" : "delete";
761
+ const moves = /* @__PURE__ */ new Map();
762
+ for (const r of refs) {
763
+ const k = `${r.db} ${r.collection}.${refPath(r)}`;
764
+ moves.set(k, (moves.get(k) ?? 0) + 1);
765
+ }
766
+ const why = [
767
+ ...unchecked.length ? [`references in ${unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(" and ")} could not be checked`] : [],
768
+ ...grants ? [`${grants} sharing grant(s) name the copy, and sharing rules are never moved`] : []
769
+ ];
770
+ const then = outcome === "delete" ? "then the copy is deleted" : `then the copy is kept as inactive${why.length ? `: ${why.join("; ")}` : ""}`;
771
+ out.push({
772
+ ...base,
773
+ status: "merge",
774
+ detail: `${moves.size ? `moves ${[...moves].map(([k, n]) => `${n} in ${k}`).join(", ")}` : "nothing points at the copy"}; ${then}`,
775
+ flags,
776
+ write: {
777
+ duplicateId: dup._id,
778
+ duplicateName: base.duplicateName,
779
+ keptId: kept._id,
780
+ keptName: base.keptName,
781
+ duplicate: dup,
782
+ refs,
783
+ outcome,
784
+ addsLegacyEntry: !listed
785
+ }
786
+ });
787
+ }
788
+ return out;
789
+ }
790
+ function formatPlannedMerge(p) {
791
+ return ` ${p.status.padEnd(6)} ${p.line.duplicateId} ${p.duplicateName || "(no organization)"}${p.duplicateList ? ` (${p.duplicateList})` : ""} -> ${p.line.keptId} ${p.keptName || "(no organization)"}${p.keptList ? ` (${p.keptList})` : ""}
792
+ ${p.detail}${p.flags.map((f) => ` [${f}]`).join("")}`;
793
+ }
794
+ async function executeMerges(dbs, merges, now, driver) {
795
+ const orgs = dbs[0].db.collection(ORGANIZATIONS_COLLECTION);
796
+ const dbNamed = new Map(dbs.map((d) => [d.name, d.db]));
797
+ const out = [];
798
+ for (const merge of merges) {
799
+ let moved = 0;
800
+ try {
801
+ const kept = await orgs.updateOne(
802
+ { _id: merge.keptId, status: { $in: [null, ORGANIZATION_STATUS.ACTIVE] }, reviewStatus: { $ne: "rejected" } },
803
+ { $addToSet: { "legacy_ids.merged_from": idText(merge.duplicateId) } }
804
+ );
805
+ if (kept.matchedCount !== 1) {
806
+ out.push({ merge, status: "changed", moved, detail: "the kept organization is gone or no longer offered since the plan; nothing was written" });
807
+ continue;
808
+ }
809
+ let stale = 0;
810
+ for (const ref of merge.refs) {
811
+ if (await repoint(dbNamed.get(ref.db), ref, false)) moved += 1;
812
+ else stale += 1;
813
+ }
814
+ const left = await countReferences(driver, dbs, merge.duplicateId);
815
+ const asPlanned = { _id: merge.duplicateId, updatedTime: merge.duplicate.updatedTime ?? null, status: merge.duplicate.status ?? null };
816
+ if (merge.outcome === "delete" && left === 0) {
817
+ const res2 = await orgs.deleteOne(asPlanned);
818
+ out.push(
819
+ res2.deletedCount === 1 ? { merge, status: "deleted", moved } : { merge, status: "changed", moved, detail: "the copy changed since the plan and was left as it is; its references were moved" }
820
+ );
821
+ continue;
822
+ }
823
+ const res = await orgs.updateOne(asPlanned, { $set: { status: ORGANIZATION_STATUS.INACTIVE, updatedTime: now } });
824
+ const why = merge.outcome === "delete" ? `${left} reference(s) still point at the copy${stale ? ` (${stale} changed since the plan)` : ""}, so it was not deleted` : left ? `${left} reference(s) still point at the copy` : void 0;
825
+ out.push(
826
+ res.matchedCount === 1 ? { merge, status: "retired", moved, ...why ? { detail: why } : {} } : { merge, status: "changed", moved, detail: "the copy changed since the plan and was left as it is; its references were moved" }
827
+ );
828
+ } catch (err) {
829
+ out.push({ merge, status: "failed", moved, detail: message(err) });
830
+ }
831
+ }
832
+ return out;
833
+ }
834
+ function sameDocument(driver, x, y) {
835
+ const sorted = (d) => Object.fromEntries(Object.keys(d).sort().map((k) => [k, d[k]]));
836
+ const strict = (d) => driver.EJSON.stringify({ v: d }, { relaxed: false });
837
+ return strict(sorted(x)) === strict(sorted(y));
838
+ }
839
+ async function rollbackMerges(dbFor, images, opts, driver) {
840
+ const orgs = dbFor(images.db).collection(ORGANIZATIONS_COLLECTION);
841
+ const out = [];
842
+ for (const image of [...images.merges ?? []].reverse()) {
843
+ const said = [];
844
+ let partial = false;
845
+ const before = image.duplicate;
846
+ const now = await orgs.findOne({ _id: image.duplicateId });
847
+ const retiredHere = !!now && sameDocument(driver, now, { ...before, status: ORGANIZATION_STATUS.INACTIVE, updatedTime: images.appliedTime });
848
+ if (!now) {
849
+ said.push("put the deleted copy back exactly as it was");
850
+ if (!opts.dryRun) await orgs.insertOne(before);
851
+ } else if (retiredHere) {
852
+ said.push(before.status === ORGANIZATION_STATUS.INACTIVE ? "put the copy back as it was before this run" : "make the copy active again, as it was");
853
+ if (!opts.dryRun) await orgs.replaceOne({ _id: image.duplicateId, updatedTime: images.appliedTime }, before);
854
+ } else if (sameDocument(driver, now, before)) {
855
+ said.push("the copy is as it was");
856
+ } else {
857
+ partial = true;
858
+ said.push("the copy has changed since the merge: left as it is");
859
+ }
860
+ let back = 0;
861
+ let moved = 0;
862
+ for (const ref of image.refs) {
863
+ const db = dbFor(ref.db);
864
+ if (!await holdsMerged(db, ref)) moved += 1;
865
+ else if (opts.dryRun || await repoint(db, ref, true)) back += 1;
866
+ else moved += 1;
867
+ }
868
+ if (image.refs.length) {
869
+ said.push(`${back} of ${image.refs.length} reference(s) back to the copy${moved ? ` (${moved} changed since the merge: left alone)` : ""}`);
870
+ }
871
+ if (moved) partial = true;
872
+ const entry = idText(image.duplicateId);
873
+ const listed = image.addsLegacyEntry ? await orgs.countDocuments({ _id: image.keptId, "legacy_ids.merged_from": entry }) : 0;
874
+ if (listed) {
875
+ said.push("take the copy's id off the kept organization's legacy_ids");
876
+ if (!opts.dryRun) {
877
+ await orgs.updateOne({ _id: image.keptId }, { $pull: { "legacy_ids.merged_from": entry } });
878
+ await orgs.updateOne({ _id: image.keptId, "legacy_ids.merged_from": { $size: 0 } }, { $unset: { "legacy_ids.merged_from": "" } });
879
+ await orgs.updateOne({ _id: image.keptId, legacy_ids: {} }, { $unset: { legacy_ids: "" } });
880
+ }
881
+ } else if (!image.addsLegacyEntry) {
882
+ said.push("the copy's id stays on the kept organization's legacy_ids (an earlier run put it there)");
883
+ }
884
+ const anything = !now || retiredHere || back > 0 || listed > 0;
885
+ out.push({
886
+ image,
887
+ status: !anything ? "skip" : partial ? "partial" : "restore",
888
+ detail: anything ? said.join("; ") : `nothing left to undo (${said.join("; ")})`
889
+ });
890
+ }
891
+ return out;
892
+ }
893
+ export {
894
+ APP_DATABASE_KINDS,
895
+ APP_LABEL,
896
+ MERGE,
897
+ ORG_REFERENCES,
898
+ THREAD_SAMPLE_ID_PREFIX,
899
+ YES,
900
+ appDatabaseProblem,
901
+ comparableName,
902
+ executeMerges,
903
+ formatPlannedMerge,
904
+ planMerges,
905
+ rollbackMerges,
906
+ sheetText
907
+ };
908
+ //# sourceMappingURL=index.js.map