@aglyn/tenant-data-admin 1.0.0-beta.218 → 1.0.0-beta.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/package.json +8 -8
  2. package/src/lib/server/api-http.js +5 -1
  3. package/src/lib/server/api-http.js.map +1 -1
  4. package/src/lib/server/api-v1-description.d.ts +112 -0
  5. package/src/lib/server/api-v1-description.js +126 -0
  6. package/src/lib/server/api-v1-description.js.map +1 -0
  7. package/src/lib/server/api-v1-kit.d.ts +163 -0
  8. package/src/lib/server/api-v1-kit.js +191 -0
  9. package/src/lib/server/api-v1-kit.js.map +1 -0
  10. package/src/lib/server/api-v1-resources.d.ts +143 -0
  11. package/src/lib/server/api-v1-resources.js +125 -0
  12. package/src/lib/server/api-v1-resources.js.map +1 -0
  13. package/src/lib/server/campaign-conversion-attribution.d.ts +1 -1
  14. package/src/lib/server/campaign-conversion-attribution.js +3 -3
  15. package/src/lib/server/campaign-conversion-attribution.js.map +1 -1
  16. package/src/lib/server/card-payment-velocity.d.ts +9 -0
  17. package/src/lib/server/card-payment-velocity.js +28 -2
  18. package/src/lib/server/card-payment-velocity.js.map +1 -1
  19. package/src/lib/server/consent-group-carry.js +1 -1
  20. package/src/lib/server/consent-group-carry.js.map +1 -1
  21. package/src/lib/server/consent-group-change.d.ts +2 -1
  22. package/src/lib/server/consent-group-change.js +43 -18
  23. package/src/lib/server/consent-group-change.js.map +1 -1
  24. package/src/lib/server/contact-email-index.d.ts +22 -0
  25. package/src/lib/server/contact-email-index.js +108 -0
  26. package/src/lib/server/contact-email-index.js.map +1 -1
  27. package/src/lib/server/crm-email-activity.d.ts +1 -1
  28. package/src/lib/server/crm-email-activity.js +1 -1
  29. package/src/lib/server/crm-email-activity.js.map +1 -1
  30. package/src/lib/server/crm-records.d.ts +9 -1
  31. package/src/lib/server/crm-records.js +19 -2
  32. package/src/lib/server/crm-records.js.map +1 -1
  33. package/src/lib/server/cron-auth.d.ts +44 -0
  34. package/src/lib/server/cron-auth.js +76 -0
  35. package/src/lib/server/cron-auth.js.map +1 -0
  36. package/src/lib/server/dataset-live-pages.js +6 -6
  37. package/src/lib/server/dataset-live-pages.js.map +1 -1
  38. package/src/lib/server/duplicate-resource.d.ts +26 -0
  39. package/src/lib/server/duplicate-resource.js +47 -25
  40. package/src/lib/server/duplicate-resource.js.map +1 -1
  41. package/src/lib/server/dynamic-list-materialize.js +6 -3
  42. package/src/lib/server/dynamic-list-materialize.js.map +1 -1
  43. package/src/lib/server/email-flow-gate.js +2 -2
  44. package/src/lib/server/email-flow-gate.js.map +1 -1
  45. package/src/lib/server/email-suppression.d.ts +11 -0
  46. package/src/lib/server/email-suppression.js +37 -2
  47. package/src/lib/server/email-suppression.js.map +1 -1
  48. package/src/lib/server/email-unsubscribe-link.d.ts +8 -5
  49. package/src/lib/server/email-unsubscribe-link.js +7 -7
  50. package/src/lib/server/email-unsubscribe-link.js.map +1 -1
  51. package/src/lib/server/erase.d.ts +19 -33
  52. package/src/lib/server/erase.js +37 -162
  53. package/src/lib/server/erase.js.map +1 -1
  54. package/src/lib/server/host-email-tokens.js +1 -1
  55. package/src/lib/server/host-email-tokens.js.map +1 -1
  56. package/src/lib/server/host-memberships.js +3 -3
  57. package/src/lib/server/host-memberships.js.map +1 -1
  58. package/src/lib/server/host-visitor-records.d.ts +32 -4
  59. package/src/lib/server/host-visitor-records.js +73 -14
  60. package/src/lib/server/host-visitor-records.js.map +1 -1
  61. package/src/lib/server/hosted-page-review.d.ts +27 -0
  62. package/src/lib/server/hosted-page-review.js +149 -12
  63. package/src/lib/server/hosted-page-review.js.map +1 -1
  64. package/src/lib/server/media-cdn-rate-limit.d.ts +6 -3
  65. package/src/lib/server/media-cdn-rate-limit.js +6 -3
  66. package/src/lib/server/media-cdn-rate-limit.js.map +1 -1
  67. package/src/lib/server/member-email-aliases.d.ts +10 -2
  68. package/src/lib/server/member-email-aliases.js +26 -2
  69. package/src/lib/server/member-email-aliases.js.map +1 -1
  70. package/src/lib/server/new-account-announcement.d.ts +62 -0
  71. package/src/lib/server/new-account-announcement.js +77 -0
  72. package/src/lib/server/new-account-announcement.js.map +1 -0
  73. package/src/lib/server/notifications.d.ts +22 -2
  74. package/src/lib/server/notifications.js +40 -3
  75. package/src/lib/server/notifications.js.map +1 -1
  76. package/src/lib/server/operator-alerts.d.ts +7 -1
  77. package/src/lib/server/operator-alerts.js +5 -3
  78. package/src/lib/server/operator-alerts.js.map +1 -1
  79. package/src/lib/server/org-containers.d.ts +66 -0
  80. package/src/lib/server/org-containers.js +95 -0
  81. package/src/lib/server/org-containers.js.map +1 -0
  82. package/src/lib/server/org-member-notice.js +3 -2
  83. package/src/lib/server/org-member-notice.js.map +1 -1
  84. package/src/lib/server/payment-fraud-signal.js +5 -1
  85. package/src/lib/server/payment-fraud-signal.js.map +1 -1
  86. package/src/lib/server/{connect-payout-failure.d.ts → payment-provider-stripe-connect-payouts.d.ts} +3 -0
  87. package/src/lib/server/{connect-payout-failure.js → payment-provider-stripe-connect-payouts.js} +36 -2
  88. package/src/lib/server/payment-provider-stripe-connect-payouts.js.map +1 -0
  89. package/src/lib/server/{connect-account-status.d.ts → payment-provider-stripe-connect-status.d.ts} +3 -0
  90. package/src/lib/server/{connect-account-status.js → payment-provider-stripe-connect-status.js} +1 -1
  91. package/src/lib/server/payment-provider-stripe-connect-status.js.map +1 -0
  92. package/src/lib/server/{stripe-account-mode.d.ts → payment-provider-stripe-connect.d.ts} +45 -70
  93. package/src/lib/server/{stripe-account-mode.js → payment-provider-stripe-connect.js} +78 -52
  94. package/src/lib/server/payment-provider-stripe-connect.js.map +1 -0
  95. package/src/lib/server/payment-provider.d.ts +173 -0
  96. package/src/lib/server/payment-provider.js +70 -0
  97. package/src/lib/server/payment-provider.js.map +1 -0
  98. package/src/lib/server/payment-risk-record.d.ts +1 -1
  99. package/src/lib/server/payment-risk-record.js +3 -1
  100. package/src/lib/server/payment-risk-record.js.map +1 -1
  101. package/src/lib/server/personal-data-export.js +1 -1
  102. package/src/lib/server/personal-data-export.js.map +1 -1
  103. package/src/lib/server/platform-marketing-consent.d.ts +1 -1
  104. package/src/lib/server/platform-marketing-consent.js +1 -1
  105. package/src/lib/server/platform-marketing-consent.js.map +1 -1
  106. package/src/lib/server/rate-limit-store.js +13 -3
  107. package/src/lib/server/rate-limit-store.js.map +1 -1
  108. package/src/lib/server/realm-plugins.js +8 -3
  109. package/src/lib/server/realm-plugins.js.map +1 -1
  110. package/src/lib/server/retained-refusals.d.ts +142 -0
  111. package/src/lib/server/retained-refusals.js +325 -0
  112. package/src/lib/server/retained-refusals.js.map +1 -0
  113. package/src/lib/server/risk-notice.d.ts +32 -1
  114. package/src/lib/server/risk-notice.js +90 -28
  115. package/src/lib/server/risk-notice.js.map +1 -1
  116. package/src/lib/server/sending-domains.d.ts +17 -0
  117. package/src/lib/server/sending-domains.js +28 -4
  118. package/src/lib/server/sending-domains.js.map +1 -1
  119. package/src/lib/server/sso-enforcement.js +7 -2
  120. package/src/lib/server/sso-enforcement.js.map +1 -1
  121. package/src/lib/server/staff-alert-email.js +4 -2
  122. package/src/lib/server/staff-alert-email.js.map +1 -1
  123. package/src/lib/server/test-firestore-queries.d.ts +7 -0
  124. package/src/lib/server/test-firestore-queries.js +70 -27
  125. package/src/lib/server/test-firestore-queries.js.map +1 -1
  126. package/src/lib/server/{email-topic-confirmation.js → topic-subscriptions.js} +15 -11
  127. package/src/lib/server/topic-subscriptions.js.map +1 -0
  128. package/src/lib/server/upsert-contact.d.ts +46 -1
  129. package/src/lib/server/upsert-contact.js +87 -20
  130. package/src/lib/server/upsert-contact.js.map +1 -1
  131. package/src/tenancy.d.ts +5 -8
  132. package/src/tenancy.js +12 -13
  133. package/src/tenancy.js.map +1 -1
  134. package/src/lib/server/connect-account-status.js.map +0 -1
  135. package/src/lib/server/connect-payout-failure.js.map +0 -1
  136. package/src/lib/server/contact-email-engagement.d.ts +0 -32
  137. package/src/lib/server/contact-email-engagement.js +0 -145
  138. package/src/lib/server/contact-email-engagement.js.map +0 -1
  139. package/src/lib/server/contact-lifecycle-floor.d.ts +0 -89
  140. package/src/lib/server/contact-lifecycle-floor.js +0 -91
  141. package/src/lib/server/contact-lifecycle-floor.js.map +0 -1
  142. package/src/lib/server/contact-merge.d.ts +0 -55
  143. package/src/lib/server/contact-merge.js +0 -288
  144. package/src/lib/server/contact-merge.js.map +0 -1
  145. package/src/lib/server/crm-booking-activity.d.ts +0 -86
  146. package/src/lib/server/crm-booking-activity.js +0 -257
  147. package/src/lib/server/crm-booking-activity.js.map +0 -1
  148. package/src/lib/server/crm-inbound-email.d.ts +0 -145
  149. package/src/lib/server/crm-inbound-email.js +0 -297
  150. package/src/lib/server/crm-inbound-email.js.map +0 -1
  151. package/src/lib/server/email-topic-confirmation.js.map +0 -1
  152. package/src/lib/server/form-dataset-binding-token.d.ts +0 -35
  153. package/src/lib/server/form-dataset-binding-token.js +0 -107
  154. package/src/lib/server/form-dataset-binding-token.js.map +0 -1
  155. package/src/lib/server/stripe-account-mode.js.map +0 -1
  156. /package/src/lib/server/{email-topic-confirmation.d.ts → topic-subscriptions.d.ts} +0 -0
@@ -1,55 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2026 Aglyn LLC
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- import type { HostActivityActor } from '@aglyn/aglyn/app-utils/activity-presenter';
18
- export interface MergeContactsOptions {
19
- firestore: FirebaseFirestore.Firestore;
20
- /** `orgs/{orgId}` — the org whose contacts both records are. */
21
- orgRef: FirebaseFirestore.DocumentReference;
22
- /** The record that stays, and keeps its address as the identity. */
23
- survivorId: string;
24
- /** The record folded in and deleted. */
25
- mergedId: string;
26
- actor: HostActivityActor;
27
- /**
28
- * The site whose console did the work: where the activity feed entry
29
- * lands, and the site a timeline note is filed under. `null` for a door
30
- * with no site — the REST API — which logs no host entry.
31
- */
32
- hostId: string | null;
33
- /** The actor's display name for the timeline note, when the door knows it. */
34
- actorName?: string | null;
35
- }
36
- export interface MergeContactsRepointed {
37
- deals: number;
38
- tasks: number;
39
- activities: number;
40
- leads: number;
41
- }
42
- export type MergeContactsResult = {
43
- ok: true;
44
- survivorId: string;
45
- survivorEmail: string;
46
- mergedId: string;
47
- mergedEmail: string;
48
- /** Every address the survivor answers to now, primary first. */
49
- emails: string[];
50
- repointed: MergeContactsRepointed;
51
- } | {
52
- ok: false;
53
- reason: 'same-record' | 'survivor-missing' | 'merged-missing';
54
- };
55
- export declare function mergeContacts(options: MergeContactsOptions): Promise<MergeContactsResult>;
@@ -1,288 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- /**
3
- * @license
4
- * Copyright 2026 Aglyn LLC
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */ /**
18
- * MERGING TWO CONTACTS — the write (AGL-2625).
19
- *
20
- * `planContactMerge` says what the survivor becomes; this performs it, and
21
- * moves everything that pointed at the merged record. One function behind
22
- * two doors — the console's `crm/contacts-merge` route and
23
- * `POST /v1/contacts/{id}/merge` — so the REST caller and the record page
24
- * cannot merge two different ways.
25
- *
26
- * ## The order is the crash-safety argument
27
- *
28
- * 1. Every deal, task and activity naming the merged contact is repointed
29
- * at the survivor, and every lead converted into it. Batched, bounded,
30
- * idempotent: a re-run finds nothing left to move.
31
- * 2. Then, in ONE transaction: the survivor takes the plan, every address
32
- * it now answers to is indexed at it, and the merged document is
33
- * deleted — with both records re-read inside the transaction, so two
34
- * merges racing on one pair cannot both succeed and a plan is never
35
- * computed on a document that changed under it.
36
- *
37
- * Children first because a process that dies between the two steps leaves
38
- * children pointing at a record that EXISTS — the survivor — while the merged
39
- * document is still there for a retry to fold in. The other order would
40
- * leave deals pointing at a deleted contact, which is a record nobody can
41
- * open from anywhere.
42
- *
43
- * ## What it does not move
44
- *
45
- * List memberships, suppression entries and the delivery log are keyed by
46
- * ADDRESS, not by contact id, and stay under the merged address; a capture
47
- * on that address resolves to the survivor through the index, which is the
48
- * fact those keys need. A company's contacts count drops only for a company
49
- * both records named — the survivor still names the rest.
50
- */ import { CONTACT_EMAIL_INDEX_COLLECTION, contactEmails } from "@aglyn/aglyn/app-utils/contacts";
51
- import { planContactMerge } from "@aglyn/aglyn/app-utils/contact-merge";
52
- import { CRM_COLLECTIONS } from "@aglyn/aglyn/app-utils/crm";
53
- import { personKey } from "@aglyn/aglyn/app-utils/person-key";
54
- import { FieldValue } from "firebase-admin/firestore";
55
- import { settleCompanyContactsCounts } from "./contact-company-link.js";
56
- import { recomputeCrmNextTaskAt } from "./crm-next-activity.js";
57
- import { restampCrmListFieldsAt } from "./crm-records.js";
58
- import { logHostActivity } from "./organizations.js";
59
- /** How many pointing rows one repoint pass reads — and one batch writes. */ const REPOINT_PAGE = 400;
60
- /** A ceiling on passes, so a query that keeps answering cannot loop forever. */ const REPOINT_PASSES = 25;
61
- /**
62
- * Point every row of `collection` whose `contactId` is `from` at `to`.
63
- *
64
- * Page, batch, repeat: each pass reads the rows still pointing at the
65
- * merged record — the ones a previous pass moved no longer match — so the
66
- * loop ends when a pass finds nothing. `updatedAt` moves with the pointer
67
- * because an integration syncing by `updatedAfter` has to see the change.
68
- */ async function repointContactId(firestore, collection, from, to) {
69
- let moved = 0;
70
- for(let pass = 0; pass < REPOINT_PASSES; pass += 1){
71
- const page = await collection.where('contactId', '==', from).limit(REPOINT_PAGE).get();
72
- if (page.empty) break;
73
- const batch = firestore.batch();
74
- for (const row of page.docs){
75
- batch.update(row.ref, {
76
- contactId: to,
77
- updatedAt: FieldValue.serverTimestamp()
78
- });
79
- }
80
- await batch.commit();
81
- moved += page.size;
82
- if (page.size < REPOINT_PAGE) break;
83
- }
84
- return moved;
85
- }
86
- /**
87
- * The leads converted into the merged contact, restamped at the survivor.
88
- *
89
- * A lead lives at `orgs/{orgId}/leads/{personKey(email)}` (AGL-3275), so there
90
- * is still no query — one document per address, asked for directly. This used
91
- * to be bounded by sites TIMES addresses because a lead lived under each site;
92
- * it is bounded by addresses now, and the sites drop out of the signature
93
- * because the collection no longer has one per site to walk.
94
- */ async function repointLeads(orgRef, emails, from, to) {
95
- let moved = 0;
96
- /*
97
- * ONE ROW PER ADDRESS, on the org (AGL-3275). This walked the sites because
98
- * there was a lead under each of them; re-pointing the same document once
99
- * per site would now be the same write repeated, and the second would find
100
- * `convertedContactId` already moved and skip — a silent undercount rather
101
- * than a wrong answer, but an undercount the caller reports to the operator.
102
- */ for (const email of emails){
103
- const key = personKey(email);
104
- if (!key) continue;
105
- const leadRef = orgRef.collection('leads').doc(key);
106
- const lead = await leadRef.get();
107
- if (!lead.exists || lead.get('convertedContactId') !== from) continue;
108
- await leadRef.update({
109
- convertedContactId: to,
110
- updatedAt: FieldValue.serverTimestamp()
111
- });
112
- moved += 1;
113
- }
114
- return moved;
115
- }
116
- function strings(value) {
117
- return Array.isArray(value) ? value.filter((item)=>typeof item === 'string' && item !== '') : [];
118
- }
119
- export async function mergeContacts(options) {
120
- var _mergedBefore_data, _survivorBefore_data, _contactEmails_, _plan_emails_;
121
- const { firestore, orgRef, survivorId, mergedId, actor, hostId } = options;
122
- if (!survivorId || !mergedId || survivorId === mergedId) {
123
- return {
124
- ok: false,
125
- reason: 'same-record'
126
- };
127
- }
128
- const contactsRef = orgRef.collection('contacts');
129
- const survivorRef = contactsRef.doc(survivorId);
130
- const mergedRef = contactsRef.doc(mergedId);
131
- const [survivorBefore, mergedBefore] = await Promise.all([
132
- survivorRef.get(),
133
- mergedRef.get()
134
- ]);
135
- if (!survivorBefore.exists) return {
136
- ok: false,
137
- reason: 'survivor-missing'
138
- };
139
- if (!mergedBefore.exists) return {
140
- ok: false,
141
- reason: 'merged-missing'
142
- };
143
- const mergedData = (_mergedBefore_data = mergedBefore.data()) != null ? _mergedBefore_data : {};
144
- const survivorData = (_survivorBefore_data = survivorBefore.data()) != null ? _survivorBefore_data : {};
145
- /*==========================================
146
- * 1. THE CHILDREN — before the parent, for the reason the header gives.
147
- *=========================================*/ const [deals, tasks, activities] = await Promise.all([
148
- repointContactId(firestore, orgRef.collection(CRM_COLLECTIONS.deals), mergedId, survivorId),
149
- repointContactId(firestore, orgRef.collection(CRM_COLLECTIONS.tasks), mergedId, survivorId),
150
- repointContactId(firestore, orgRef.collection(CRM_COLLECTIONS.activities), mergedId, survivorId)
151
- ]);
152
- const leadHosts = [
153
- ...new Set([
154
- ...strings(mergedData['capturedByHostIds']),
155
- ...strings(survivorData['capturedByHostIds']),
156
- ...strings([
157
- mergedData['hostId'],
158
- survivorData['hostId'],
159
- hostId
160
- ])
161
- ])
162
- ];
163
- const leads = await repointLeads(orgRef, contactEmails(mergedData), mergedId, survivorId);
164
- /*==========================================
165
- * 2. THE SWAP — one transaction over both documents and the index.
166
- *=========================================*/ const index = orgRef.collection(CONTACT_EMAIL_INDEX_COLLECTION);
167
- const swapped = await firestore.runTransaction(async (transaction)=>{
168
- var _survivor_data, _merged_data, _survivor_data1;
169
- const [survivor, merged] = await Promise.all([
170
- transaction.get(survivorRef),
171
- transaction.get(mergedRef)
172
- ]);
173
- if (!survivor.exists) return {
174
- reason: 'survivor-missing'
175
- };
176
- if (!merged.exists) return {
177
- reason: 'merged-missing'
178
- };
179
- const plan = planContactMerge((_survivor_data = survivor.data()) != null ? _survivor_data : {}, (_merged_data = merged.data()) != null ? _merged_data : {});
180
- transaction.set(survivorRef, _extends({}, plan.survivor, {
181
- updatedAt: FieldValue.serverTimestamp()
182
- }), {
183
- merge: true
184
- });
185
- for (const email of plan.emails){
186
- const key = personKey(email);
187
- if (!key) continue;
188
- transaction.set(index.doc(key), {
189
- email,
190
- contactId: survivorId,
191
- updatedAt: FieldValue.serverTimestamp()
192
- }, {
193
- merge: true
194
- });
195
- }
196
- transaction.delete(mergedRef);
197
- return {
198
- plan,
199
- survivor: (_survivor_data1 = survivor.data()) != null ? _survivor_data1 : {}
200
- };
201
- });
202
- if ('reason' in swapped) return {
203
- ok: false,
204
- reason: swapped.reason
205
- };
206
- const { plan } = swapped;
207
- // The survivor now carries both records' addresses, holders and facets —
208
- // what the Contacts list searches and filters by (AGL-3321).
209
- await restampCrmListFieldsAt(survivorRef, 'contacts');
210
- /*
211
- * The companies both records named counted two people and now count one
212
- * (AGL-2613). Settled after the swap the way the capture settles its
213
- * counts: a figure that could not move is logged, and the company page's
214
- * live aggregate corrects it.
215
- */ await settleCompanyContactsCounts(orgRef.collection(CRM_COLLECTIONS.companies), {
216
- companyId: null,
217
- mirror: null,
218
- counts: plan.companyCounts
219
- });
220
- /*
221
- * The survivor now owns the merged record's open tasks too, so its next
222
- * activity is the earliest of both (AGL-2661). Settled the same way: a
223
- * figure that could not move is logged, and the Fields section's
224
- * recompute corrects it.
225
- */ await recomputeCrmNextTaskAt(firestore, orgRef.id, [
226
- {
227
- contactId: survivorId
228
- }
229
- ]).catch((error)=>{
230
- console.error('contact merge next activity could not be recomputed', survivorId, error);
231
- });
232
- const mergedEmail = (_contactEmails_ = contactEmails(mergedData)[0]) != null ? _contactEmails_ : '';
233
- const survivorEmail = (_plan_emails_ = plan.emails[0]) != null ? _plan_emails_ : '';
234
- // The canonical name — the one identity every holder shares — for the
235
- // feed; the address stands in for a person nobody has named.
236
- const survivorName = typeof swapped.survivor['name'] === 'string' ? swapped.survivor['name'] : '';
237
- /*
238
- * THE TIMELINE NOTE, on the survivor: the merge is an event in this
239
- * person's history, and the record page is where a reader looks for one.
240
- * Filed under the calling site, or the survivor's first site for a door
241
- * with none; its own catch, because a note that could not be written must
242
- * not read as a merge that did not happen.
243
- */ try {
244
- var _survivorData_hostId;
245
- await orgRef.collection(CRM_COLLECTIONS.activities).add(_extends({
246
- kind: 'note',
247
- body: `Merged with ${mergedEmail}`,
248
- atMs: Date.now(),
249
- byUid: actor.uid
250
- }, options.actorName || actor.email ? {
251
- byName: options.actorName || actor.email
252
- } : {}, {
253
- contactId: survivorId,
254
- visibleTo: plan.visibleTo,
255
- hostId: hostId != null ? hostId : String((_survivorData_hostId = survivorData['hostId']) != null ? _survivorData_hostId : ''),
256
- createdByUid: actor.uid,
257
- createdAt: FieldValue.serverTimestamp(),
258
- updatedAt: FieldValue.serverTimestamp()
259
- }));
260
- } catch (error) {
261
- console.error('[contact-merge] timeline note failed', survivorId, error);
262
- }
263
- // The audit line (AGL-2622), in the feed of the site whose console did
264
- // the work. A door with no site — the API — has no host feed to write.
265
- if (hostId) {
266
- await logHostActivity(hostId, actor, `Merged with ${mergedEmail}`, {
267
- type: 'contact',
268
- id: survivorId,
269
- name: survivorName || survivorEmail
270
- });
271
- }
272
- return {
273
- ok: true,
274
- survivorId,
275
- survivorEmail,
276
- mergedId,
277
- mergedEmail,
278
- emails: plan.emails,
279
- repointed: {
280
- deals,
281
- tasks,
282
- activities,
283
- leads
284
- }
285
- };
286
- }
287
-
288
- //# sourceMappingURL=contact-merge.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/contact-merge.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * MERGING TWO CONTACTS — the write (AGL-2625).\n *\n * `planContactMerge` says what the survivor becomes; this performs it, and\n * moves everything that pointed at the merged record. One function behind\n * two doors — the console's `crm/contacts-merge` route and\n * `POST /v1/contacts/{id}/merge` — so the REST caller and the record page\n * cannot merge two different ways.\n *\n * ## The order is the crash-safety argument\n *\n * 1. Every deal, task and activity naming the merged contact is repointed\n * at the survivor, and every lead converted into it. Batched, bounded,\n * idempotent: a re-run finds nothing left to move.\n * 2. Then, in ONE transaction: the survivor takes the plan, every address\n * it now answers to is indexed at it, and the merged document is\n * deleted — with both records re-read inside the transaction, so two\n * merges racing on one pair cannot both succeed and a plan is never\n * computed on a document that changed under it.\n *\n * Children first because a process that dies between the two steps leaves\n * children pointing at a record that EXISTS — the survivor — while the merged\n * document is still there for a retry to fold in. The other order would\n * leave deals pointing at a deleted contact, which is a record nobody can\n * open from anywhere.\n *\n * ## What it does not move\n *\n * List memberships, suppression entries and the delivery log are keyed by\n * ADDRESS, not by contact id, and stay under the merged address; a capture\n * on that address resolves to the survivor through the index, which is the\n * fact those keys need. A company's contacts count drops only for a company\n * both records named — the survivor still names the rest.\n */\n\nimport {\n CONTACT_EMAIL_INDEX_COLLECTION,\n contactEmails,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport type { HostActivityActor } from '@aglyn/aglyn/app-utils/activity-presenter'\nimport { planContactMerge } from '@aglyn/aglyn/app-utils/contact-merge'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { settleCompanyContactsCounts } from './contact-company-link'\nimport { recomputeCrmNextTaskAt } from './crm-next-activity'\nimport { restampCrmListFieldsAt } from './crm-records'\nimport { logHostActivity } from './organizations'\n\n/** How many pointing rows one repoint pass reads — and one batch writes. */\nconst REPOINT_PAGE = 400\n/** A ceiling on passes, so a query that keeps answering cannot loop forever. */\nconst REPOINT_PASSES = 25\n\nexport interface MergeContactsOptions {\n firestore: FirebaseFirestore.Firestore\n /** `orgs/{orgId}` — the org whose contacts both records are. */\n orgRef: FirebaseFirestore.DocumentReference\n /** The record that stays, and keeps its address as the identity. */\n survivorId: string\n /** The record folded in and deleted. */\n mergedId: string\n actor: HostActivityActor\n /**\n * The site whose console did the work: where the activity feed entry\n * lands, and the site a timeline note is filed under. `null` for a door\n * with no site — the REST API — which logs no host entry.\n */\n hostId: string | null\n /** The actor's display name for the timeline note, when the door knows it. */\n actorName?: string | null\n}\n\nexport interface MergeContactsRepointed {\n deals: number\n tasks: number\n activities: number\n leads: number\n}\n\nexport type MergeContactsResult =\n | {\n ok: true\n survivorId: string\n survivorEmail: string\n mergedId: string\n mergedEmail: string\n /** Every address the survivor answers to now, primary first. */\n emails: string[]\n repointed: MergeContactsRepointed\n }\n | { ok: false; reason: 'same-record' | 'survivor-missing' | 'merged-missing' }\n\n/**\n * Point every row of `collection` whose `contactId` is `from` at `to`.\n *\n * Page, batch, repeat: each pass reads the rows still pointing at the\n * merged record — the ones a previous pass moved no longer match — so the\n * loop ends when a pass finds nothing. `updatedAt` moves with the pointer\n * because an integration syncing by `updatedAfter` has to see the change.\n */\nasync function repointContactId(\n firestore: FirebaseFirestore.Firestore,\n collection: FirebaseFirestore.CollectionReference,\n from: string,\n to: string,\n): Promise<number> {\n let moved = 0\n for (let pass = 0; pass < REPOINT_PASSES; pass += 1) {\n const page = await collection\n .where('contactId', '==', from)\n .limit(REPOINT_PAGE)\n .get()\n if (page.empty) break\n const batch = firestore.batch()\n for (const row of page.docs) {\n batch.update(row.ref, {\n contactId: to,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n await batch.commit()\n moved += page.size\n if (page.size < REPOINT_PAGE) break\n }\n return moved\n}\n\n/**\n * The leads converted into the merged contact, restamped at the survivor.\n *\n * A lead lives at `orgs/{orgId}/leads/{personKey(email)}` (AGL-3275), so there\n * is still no query — one document per address, asked for directly. This used\n * to be bounded by sites TIMES addresses because a lead lived under each site;\n * it is bounded by addresses now, and the sites drop out of the signature\n * because the collection no longer has one per site to walk.\n */\nasync function repointLeads(\n orgRef: FirebaseFirestore.DocumentReference,\n emails: readonly string[],\n from: string,\n to: string,\n): Promise<number> {\n let moved = 0\n /*\n * ONE ROW PER ADDRESS, on the org (AGL-3275). This walked the sites because\n * there was a lead under each of them; re-pointing the same document once\n * per site would now be the same write repeated, and the second would find\n * `convertedContactId` already moved and skip — a silent undercount rather\n * than a wrong answer, but an undercount the caller reports to the operator.\n */\n for (const email of emails) {\n const key = personKey(email)\n if (!key) continue\n const leadRef = orgRef.collection('leads').doc(key)\n const lead = await leadRef.get()\n if (!lead.exists || lead.get('convertedContactId') !== from) continue\n await leadRef.update({\n convertedContactId: to,\n updatedAt: FieldValue.serverTimestamp(),\n })\n moved += 1\n }\n return moved\n}\n\nfunction strings(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string' && item !== '')\n : []\n}\n\nexport async function mergeContacts(\n options: MergeContactsOptions,\n): Promise<MergeContactsResult> {\n const { firestore, orgRef, survivorId, mergedId, actor, hostId } = options\n if (!survivorId || !mergedId || survivorId === mergedId) {\n return { ok: false, reason: 'same-record' }\n }\n const contactsRef = orgRef.collection('contacts')\n const survivorRef = contactsRef.doc(survivorId)\n const mergedRef = contactsRef.doc(mergedId)\n const [survivorBefore, mergedBefore] = await Promise.all([\n survivorRef.get(),\n mergedRef.get(),\n ])\n if (!survivorBefore.exists) return { ok: false, reason: 'survivor-missing' }\n if (!mergedBefore.exists) return { ok: false, reason: 'merged-missing' }\n const mergedData = (mergedBefore.data() ?? {}) as Record<string, unknown>\n const survivorData = (survivorBefore.data() ?? {}) as Record<string, unknown>\n\n /*==========================================\n * 1. THE CHILDREN — before the parent, for the reason the header gives.\n *=========================================*/\n const [deals, tasks, activities] = await Promise.all([\n repointContactId(firestore, orgRef.collection(CRM_COLLECTIONS.deals), mergedId, survivorId),\n repointContactId(firestore, orgRef.collection(CRM_COLLECTIONS.tasks), mergedId, survivorId),\n repointContactId(\n firestore,\n orgRef.collection(CRM_COLLECTIONS.activities),\n mergedId,\n survivorId,\n ),\n ])\n const leadHosts = [\n ...new Set([\n ...strings(mergedData['capturedByHostIds']),\n ...strings(survivorData['capturedByHostIds']),\n ...strings([mergedData['hostId'], survivorData['hostId'], hostId]),\n ]),\n ]\n const leads = await repointLeads(\n orgRef,\n contactEmails(mergedData),\n mergedId,\n survivorId,\n )\n\n /*==========================================\n * 2. THE SWAP — one transaction over both documents and the index.\n *=========================================*/\n const index = orgRef.collection(CONTACT_EMAIL_INDEX_COLLECTION)\n const swapped = await firestore.runTransaction(async (transaction) => {\n const [survivor, merged] = await Promise.all([\n transaction.get(survivorRef),\n transaction.get(mergedRef),\n ])\n if (!survivor.exists) return { reason: 'survivor-missing' as const }\n if (!merged.exists) return { reason: 'merged-missing' as const }\n const plan = planContactMerge(\n (survivor.data() ?? {}) as Record<string, unknown>,\n (merged.data() ?? {}) as Record<string, unknown>,\n )\n transaction.set(\n survivorRef,\n { ...plan.survivor, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n for (const email of plan.emails) {\n const key = personKey(email)\n if (!key) continue\n transaction.set(\n index.doc(key),\n { email, contactId: survivorId, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n transaction.delete(mergedRef)\n return { plan, survivor: (survivor.data() ?? {}) as Record<string, unknown> }\n })\n if ('reason' in swapped) return { ok: false, reason: swapped.reason }\n const { plan } = swapped\n // The survivor now carries both records' addresses, holders and facets —\n // what the Contacts list searches and filters by (AGL-3321).\n await restampCrmListFieldsAt(survivorRef, 'contacts')\n\n /*\n * The companies both records named counted two people and now count one\n * (AGL-2613). Settled after the swap the way the capture settles its\n * counts: a figure that could not move is logged, and the company page's\n * live aggregate corrects it.\n */\n await settleCompanyContactsCounts(orgRef.collection(CRM_COLLECTIONS.companies), {\n companyId: null,\n mirror: null,\n counts: plan.companyCounts,\n })\n /*\n * The survivor now owns the merged record's open tasks too, so its next\n * activity is the earliest of both (AGL-2661). Settled the same way: a\n * figure that could not move is logged, and the Fields section's\n * recompute corrects it.\n */\n await recomputeCrmNextTaskAt(firestore, orgRef.id, [{ contactId: survivorId }]).catch(\n (error: unknown) => {\n console.error('contact merge next activity could not be recomputed', survivorId, error)\n },\n )\n\n const mergedEmail = contactEmails(mergedData)[0] ?? ''\n const survivorEmail = plan.emails[0] ?? ''\n // The canonical name — the one identity every holder shares — for the\n // feed; the address stands in for a person nobody has named.\n const survivorName =\n typeof swapped.survivor['name'] === 'string' ? swapped.survivor['name'] : ''\n\n /*\n * THE TIMELINE NOTE, on the survivor: the merge is an event in this\n * person's history, and the record page is where a reader looks for one.\n * Filed under the calling site, or the survivor's first site for a door\n * with none; its own catch, because a note that could not be written must\n * not read as a merge that did not happen.\n */\n try {\n await orgRef.collection(CRM_COLLECTIONS.activities).add({\n kind: 'note',\n body: `Merged with ${mergedEmail}`,\n atMs: Date.now(),\n byUid: actor.uid,\n ...(options.actorName || actor.email\n ? { byName: options.actorName || actor.email }\n : {}),\n contactId: survivorId,\n visibleTo: plan.visibleTo,\n hostId: hostId ?? String(survivorData['hostId'] ?? ''),\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n } catch (error) {\n console.error('[contact-merge] timeline note failed', survivorId, error)\n }\n\n // The audit line (AGL-2622), in the feed of the site whose console did\n // the work. A door with no site — the API — has no host feed to write.\n if (hostId) {\n await logHostActivity(hostId, actor, `Merged with ${mergedEmail}`, {\n type: 'contact',\n id: survivorId,\n name: survivorName || survivorEmail,\n })\n }\n\n return {\n ok: true,\n survivorId,\n survivorEmail,\n mergedId,\n mergedEmail,\n emails: plan.emails,\n repointed: { deals, tasks, activities, leads },\n }\n}\n"],"names":["CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","planContactMerge","CRM_COLLECTIONS","personKey","FieldValue","settleCompanyContactsCounts","recomputeCrmNextTaskAt","restampCrmListFieldsAt","logHostActivity","REPOINT_PAGE","REPOINT_PASSES","repointContactId","firestore","collection","from","to","moved","pass","page","where","limit","get","empty","batch","row","docs","update","ref","contactId","updatedAt","serverTimestamp","commit","size","repointLeads","orgRef","emails","email","key","leadRef","doc","lead","exists","convertedContactId","strings","value","Array","isArray","filter","item","mergeContacts","options","mergedBefore","survivorBefore","plan","survivorId","mergedId","actor","hostId","ok","reason","contactsRef","survivorRef","mergedRef","Promise","all","mergedData","data","survivorData","deals","tasks","activities","leadHosts","Set","leads","index","swapped","runTransaction","transaction","survivor","merged","set","merge","delete","companies","companyId","mirror","counts","companyCounts","id","catch","error","console","mergedEmail","survivorEmail","survivorName","add","kind","body","atMs","Date","now","byUid","uid","actorName","byName","visibleTo","String","createdByUid","createdAt","type","name","repointed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GAED,SACEA,8BAA8B,EAC9BC,aAAa,QACR,kCAAiC;AAExC,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,2BAA2B,QAAQ,4BAAwB;AACpE,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,sBAAsB,QAAQ,mBAAe;AACtD,SAASC,eAAe,QAAQ,qBAAiB;AAEjD,0EAA0E,GAC1E,MAAMC,eAAe;AACrB,8EAA8E,GAC9E,MAAMC,iBAAiB;AAyCvB;;;;;;;CAOC,GACD,eAAeC,iBACbC,SAAsC,EACtCC,UAAiD,EACjDC,IAAY,EACZC,EAAU;IAEV,IAAIC,QAAQ;IACZ,IAAK,IAAIC,OAAO,GAAGA,OAAOP,gBAAgBO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QAAQD,KAAK,CAAC,wCAAwCpC,YAAYoC;IACpE;IAEA,uEAAuE;IACvE,uEAAuE;IACvE,IAAIjC,QAAQ;QACV,MAAMjD,gBAAgBiD,QAAQD,OAAO,CAAC,YAAY,EAAEoC,aAAa,EAAE;YACjEiB,MAAM;YACNrB,IAAIlC;YACJwD,MAAMhB,gBAAgBD;QACxB;IACF;IAEA,OAAO;QACLnC,IAAI;QACJJ;QACAuC;QACAtC;QACAqC;QACAzD,QAAQkB,KAAKlB,MAAM;QACnB4E,WAAW;YAAE3C;YAAOC;YAAOC;YAAYG;QAAM;IAC/C;AACF"}
@@ -1,86 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2026 Aglyn LLC
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- import { type CrmActivityLink } from '@aglyn/aglyn/server';
18
- export interface CrmBookingRecordInput {
19
- hostId: string;
20
- /**
21
- * The owning org, as `getOrgForHost` returns it — the plugin set, the
22
- * consent groups and the scope default are all read off it.
23
- */
24
- org: Record<string, unknown> | null | undefined;
25
- orgId: string;
26
- /** The booking as its row was written. */
27
- booking: {
28
- id: string;
29
- serviceId?: string;
30
- serviceName?: string;
31
- email?: string;
32
- startsAtMs: number;
33
- endsAtMs: number;
34
- /** The `crm` query value the link carried, kept on the row. */
35
- crmRef?: string | null;
36
- };
37
- /** The service as stored: its two CRM switches and its timezone. */
38
- service: {
39
- name?: string;
40
- timezone?: string;
41
- crmFollowUpTask?: boolean;
42
- crmMeetingActivity?: boolean;
43
- } | null | undefined;
44
- /**
45
- * The host document's plugin fields, when the caller already holds them;
46
- * read here otherwise. The deny-list is per site, and a site that has
47
- * switched the CRM off must file nothing.
48
- */
49
- host?: {
50
- disabledPlugins?: string[];
51
- enabledPlugins?: string[];
52
- } | null;
53
- }
54
- export type CrmBookingRecordOutcome = {
55
- filed: false;
56
- reason:
57
- /** The CRM plugin does not run on this site. */
58
- 'crm-off'
59
- /**
60
- * The org's plan does not carry the CRM suite, whose activities and
61
- * tasks these are (AGL-2787).
62
- */
63
- | 'not-entitled'
64
- /** Neither the reference nor the address named a record. */
65
- | 'no-record'
66
- /** A meeting for this booking is already on the timeline. */
67
- | 'already-filed'
68
- /** The service asks for neither a meeting nor a follow-up. */
69
- | 'nothing-to-file'
70
- /** A read or a write threw; logged, and nothing is promised. */
71
- | 'failed';
72
- } | {
73
- filed: true;
74
- /** How the record was found. */
75
- matchedBy: 'crmRef' | 'email';
76
- link: CrmActivityLink;
77
- /** The meeting's id, or `null` when the service files no meeting. */
78
- activityId: string | null;
79
- /** The follow-up's id, or `null` when the service asks for none. */
80
- taskId: string | null;
81
- };
82
- /**
83
- * Files what a confirmed booking owes the CRM: the meeting, and the
84
- * follow-up when the service asks for one. See the module comment.
85
- */
86
- export declare function recordCrmBooking(firestore: FirebaseFirestore.Firestore, input: CrmBookingRecordInput): Promise<CrmBookingRecordOutcome>;