@aglyn/plugins-crm 1.19.0 → 1.20.1

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 (76) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/log-activity-dialog.d.ts +2 -0
  3. package/src/lib/components/log-activity-dialog.js +11 -2
  4. package/src/lib/components/log-activity-dialog.js.map +1 -1
  5. package/src/lib/components/record-sharing-card.js +8 -7
  6. package/src/lib/components/record-sharing-card.js.map +1 -1
  7. package/src/lib/components/settings-section.d.ts +10 -3
  8. package/src/lib/components/settings-section.js +286 -35
  9. package/src/lib/components/settings-section.js.map +1 -1
  10. package/src/lib/components/share-records-dialog.d.ts +17 -3
  11. package/src/lib/components/share-records-dialog.js +59 -45
  12. package/src/lib/components/share-records-dialog.js.map +1 -1
  13. package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
  14. package/src/lib/components/sharing-rule-drawer.js +51 -40
  15. package/src/lib/components/sharing-rule-drawer.js.map +1 -1
  16. package/src/lib/components/sharing-rules-card.js +2 -1
  17. package/src/lib/components/sharing-rules-card.js.map +1 -1
  18. package/src/lib/declarations.server.js +10 -1
  19. package/src/lib/declarations.server.js.map +1 -1
  20. package/src/lib/hooks/use-campaign-filing-log.js +10 -2
  21. package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
  22. package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
  23. package/src/lib/hooks/use-crm-sharing.js +20 -0
  24. package/src/lib/hooks/use-crm-sharing.js.map +1 -1
  25. package/src/lib/model/crm-sharing-api.d.ts +5 -2
  26. package/src/lib/model/crm-sharing-api.js +3 -0
  27. package/src/lib/model/crm-sharing-api.js.map +1 -1
  28. package/src/lib/model/crm-sharing.d.ts +153 -5
  29. package/src/lib/model/crm-sharing.js +243 -20
  30. package/src/lib/model/crm-sharing.js.map +1 -1
  31. package/src/lib/model/lead-filters.d.ts +1 -1
  32. package/src/lib/server/add-contact-by-hand.js +11 -4
  33. package/src/lib/server/add-contact-by-hand.js.map +1 -1
  34. package/src/lib/server/api-v1/crm-activities.js +2 -2
  35. package/src/lib/server/api-v1/crm-activities.js.map +1 -1
  36. package/src/lib/server/api-v1/crm-companies.js +2 -2
  37. package/src/lib/server/api-v1/crm-companies.js.map +1 -1
  38. package/src/lib/server/api-v1/crm-deals.js +2 -2
  39. package/src/lib/server/api-v1/crm-deals.js.map +1 -1
  40. package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
  41. package/src/lib/server/api-v1/crm-shared.js +12 -1
  42. package/src/lib/server/api-v1/crm-shared.js.map +1 -1
  43. package/src/lib/server/api-v1/crm-tasks.js +2 -2
  44. package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
  45. package/src/lib/server/associate-company-by-domain.d.ts +1 -1
  46. package/src/lib/server/associate-company-by-domain.js +4 -4
  47. package/src/lib/server/associate-company-by-domain.js.map +1 -1
  48. package/src/lib/server/automation-steps.js +24 -12
  49. package/src/lib/server/automation-steps.js.map +1 -1
  50. package/src/lib/server/campaign-filing-activity.js +7 -3
  51. package/src/lib/server/campaign-filing-activity.js.map +1 -1
  52. package/src/lib/server/convert-host-lead.js +13 -4
  53. package/src/lib/server/convert-host-lead.js.map +1 -1
  54. package/src/lib/server/crm-default-sharing.d.ts +86 -0
  55. package/src/lib/server/crm-default-sharing.js +409 -0
  56. package/src/lib/server/crm-default-sharing.js.map +1 -0
  57. package/src/lib/server/crm-inbound-email.js +2 -2
  58. package/src/lib/server/crm-inbound-email.js.map +1 -1
  59. package/src/lib/server/crm-sharing-runs.d.ts +71 -0
  60. package/src/lib/server/crm-sharing-runs.js +221 -0
  61. package/src/lib/server/crm-sharing-runs.js.map +1 -0
  62. package/src/lib/server/crm-sharing.d.ts +24 -1
  63. package/src/lib/server/crm-sharing.js +183 -31
  64. package/src/lib/server/crm-sharing.js.map +1 -1
  65. package/src/lib/server/email-send.js +5 -2
  66. package/src/lib/server/email-send.js.map +1 -1
  67. package/src/lib/server/record-timeline.d.ts +2 -1
  68. package/src/lib/server/record-timeline.js +11 -6
  69. package/src/lib/server/record-timeline.js.map +1 -1
  70. package/src/lib/server/task-routes.js +10 -6
  71. package/src/lib/server/task-routes.js.map +1 -1
  72. package/src/lib/server.js +23 -1
  73. package/src/lib/server.js.map +1 -1
  74. package/src/lib/transfer/common.d.ts +5 -1
  75. package/src/lib/transfer/common.js +8 -5
  76. package/src/lib/transfer/common.js.map +1 -1
@@ -0,0 +1,71 @@
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 CrmSharingObject } from '../model/crm-sharing';
18
+ import { CRM_SHARING_RUNS_COLLECTION } from './crm-default-sharing';
19
+ export { CRM_SHARING_RUNS_COLLECTION };
20
+ type Firestore = FirebaseFirestore.Firestore;
21
+ /** Beats a failing run gets before it is dropped and reported. */
22
+ export declare const MAX_RUN_ATTEMPTS = 5;
23
+ /** A position in {@link CRM_SHARING_OBJECTS}. */
24
+ export interface CrmSharingRunCursor {
25
+ object: CrmSharingObject;
26
+ afterId: string | null;
27
+ }
28
+ export interface CrmExceptRefreshResult {
29
+ /** Records read. */
30
+ read: number;
31
+ /** Records whose sharing moved. */
32
+ changed: number;
33
+ /** Every kind of record was walked to its end. */
34
+ complete: boolean;
35
+ cursor: CrmSharingRunCursor | null;
36
+ }
37
+ /**
38
+ * Walks the records carrying an all-except grant and recomputes each, from
39
+ * `from` until the budget runs out. Throws only on a failed query.
40
+ */
41
+ export declare function refreshCrmExceptGrants(input: {
42
+ orgId: string;
43
+ budgetMs?: number;
44
+ from?: CrmSharingRunCursor | null;
45
+ firestore?: Firestore;
46
+ }): Promise<CrmExceptRefreshResult>;
47
+ /**
48
+ * The CRM's share of a change to a workspace's sites, called by the core
49
+ * sweep. NEVER THROWS: the site change is done. Work it could not finish is
50
+ * left for the job.
51
+ */
52
+ export declare function crmSharingAfterSiteChange(input: {
53
+ orgId: string;
54
+ reason: string;
55
+ hostId?: string;
56
+ budgetMs: number;
57
+ firestore?: Firestore;
58
+ }): Promise<void>;
59
+ /**
60
+ * Carries on every unfinished run: the job's handler. A run document exists
61
+ * only while work is left, so the unfiltered query needs no index and answers
62
+ * nothing on a quiet beat, for one read.
63
+ */
64
+ export declare function resumeCrmSharingRuns(options?: {
65
+ budgetMs?: number;
66
+ firestore?: Firestore;
67
+ }): Promise<{
68
+ resumed: number;
69
+ finished: number;
70
+ droppedAfterFailing: number;
71
+ }>;
@@ -0,0 +1,221 @@
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
+ * KEEPING THE CRM'S "ALL SITES EXCEPT…" GRANTS LEVEL (AGL-4047).
19
+ *
20
+ * A grant shared with all sites except some keeps the sites it reaches in its
21
+ * `tokens`, and so in the record's `visibleTo`, the one list readers enforce.
22
+ * A record's sharing is recomputed on every server write, which brings such a
23
+ * grant level as a side effect. A record nobody touches still has to gain a
24
+ * site the workspace adds, and lose one it erases, so a change to the
25
+ * workspace's sites walks the records that carry one: `sharing.hasExcept`,
26
+ * one equality query per kind of record, answering nothing in a workspace
27
+ * that never shared this way.
28
+ *
29
+ * The walk is started by the core sweep's site-change hook
30
+ * (`registerPluginScopeSharingSiteChange`), works for the few seconds the
31
+ * person creating or deleting the site waits, and leaves the rest in
32
+ * `orgs/{orgId}/crmSharingRuns/{runId}` for the CRM's job, which carries on
33
+ * from the cursor. That document exists only while work is left, so the
34
+ * job's query answers nothing on a quiet beat. No Firestore rule opens the
35
+ * path: only this server code reads or writes it.
36
+ *
37
+ * Every step is idempotent: a record already level reads `unchanged` and is
38
+ * not written.
39
+ *
40
+ * The same job carries on "Apply to existing records" (`crm-default-sharing.ts`),
41
+ * a run a person started, from the same collection.
42
+ */ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
43
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
44
+ import { FieldPath } from "firebase-admin/firestore";
45
+ import { CRM_SHARING_EXCEPT_PATH, CRM_SHARING_OBJECTS, isCrmSharingObject } from "../model/crm-sharing.js";
46
+ import { crmSharingContextFor, crmSharingRulesOf, recomputeMany } from "./crm-sharing.js";
47
+ import { advanceDefaultApply, CRM_DEFAULT_APPLY_KIND, CRM_SHARING_RUNS_COLLECTION } from "./crm-default-sharing.js";
48
+ export { CRM_SHARING_RUNS_COLLECTION };
49
+ /** Records read at a time. */ const PAGE_SIZE = 100;
50
+ /** How long one job beat spends, across every run it takes. */ const JOB_BUDGET_MS = 20000;
51
+ /** Runs one beat reads. */ const RUNS_PER_BEAT = 10;
52
+ /** Beats a failing run gets before it is dropped and reported. */ export const MAX_RUN_ATTEMPTS = 5;
53
+ const platformFirestore = ()=>firebaseAdmin.app().firestore();
54
+ /**
55
+ * Walks the records carrying an all-except grant and recomputes each, from
56
+ * `from` until the budget runs out. Throws only on a failed query.
57
+ */ export async function refreshCrmExceptGrants(input) {
58
+ var _input_firestore;
59
+ const firestore = (_input_firestore = input.firestore) != null ? _input_firestore : platformFirestore();
60
+ const orgRef = firestore.collection('orgs').doc(input.orgId);
61
+ const deadline = input.budgetMs == null ? null : Date.now() + input.budgetMs;
62
+ const startAt = input.from ? Math.max(0, CRM_SHARING_OBJECTS.indexOf(input.from.object)) : 0;
63
+ const result = {
64
+ read: 0,
65
+ changed: 0,
66
+ complete: true,
67
+ cursor: null
68
+ };
69
+ let read = null;
70
+ for (const object of CRM_SHARING_OBJECTS.slice(startAt)){
71
+ var _input_from;
72
+ let afterId = ((_input_from = input.from) == null ? void 0 : _input_from.object) === object ? input.from.afterId : null;
73
+ for(;;){
74
+ if (deadline != null && Date.now() >= deadline) {
75
+ return _extends({}, result, {
76
+ complete: false,
77
+ cursor: {
78
+ object,
79
+ afterId
80
+ }
81
+ });
82
+ }
83
+ let query = orgRef.collection(object).where(CRM_SHARING_EXCEPT_PATH, '==', true).orderBy(FieldPath.documentId()).limit(PAGE_SIZE);
84
+ if (afterId) query = query.startAfter(afterId);
85
+ const page = await query.get();
86
+ if (page.empty) break;
87
+ // The rules and the sites, read once, and only once a record turns up.
88
+ read != null ? read : read = await crmSharingRulesOf(firestore, input.orgId, {
89
+ fresh: true
90
+ });
91
+ const context = _extends({}, await crmSharingContextFor(firestore, input.orgId, read.rules, object), {
92
+ orgHostIds: read.orgHostIds
93
+ });
94
+ const outcome = await recomputeMany({
95
+ firestore,
96
+ orgId: input.orgId,
97
+ object,
98
+ rules: read.rules,
99
+ fresh: true,
100
+ context,
101
+ atMs: Date.now()
102
+ }, page.docs.map((doc)=>doc.id));
103
+ result.read += page.size;
104
+ result.changed += outcome.changed.length;
105
+ afterId = page.docs[page.docs.length - 1].id;
106
+ if (page.size < PAGE_SIZE) break;
107
+ }
108
+ }
109
+ return result;
110
+ }
111
+ /**
112
+ * The CRM's share of a change to a workspace's sites, called by the core
113
+ * sweep. NEVER THROWS: the site change is done. Work it could not finish is
114
+ * left for the job.
115
+ */ export async function crmSharingAfterSiteChange(input) {
116
+ var _input_firestore;
117
+ const firestore = (_input_firestore = input.firestore) != null ? _input_firestore : platformFirestore();
118
+ const leave = (cursor, attempts)=>firestore.collection('orgs').doc(input.orgId).collection(CRM_SHARING_RUNS_COLLECTION).doc(createResourceUid()).set(_extends({
119
+ kind: 'except-grants',
120
+ reason: input.reason
121
+ }, input.hostId ? {
122
+ hostId: input.hostId
123
+ } : {}, {
124
+ cursor,
125
+ attempts,
126
+ createdAtMs: Date.now()
127
+ }));
128
+ try {
129
+ const result = await refreshCrmExceptGrants({
130
+ orgId: input.orgId,
131
+ budgetMs: input.budgetMs,
132
+ firestore
133
+ });
134
+ if (!result.complete) await leave(result.cursor, 0);
135
+ } catch (error) {
136
+ console.error(`[crm] sharing grants were not brought level after ${input.reason} in ${input.orgId}`, error);
137
+ await leave(null, 1).catch((writeError)=>{
138
+ console.error(`[crm] could not leave ${input.orgId}'s sharing run for the job`, writeError);
139
+ });
140
+ }
141
+ }
142
+ function readCursor(raw) {
143
+ if (!raw || typeof raw !== 'object') return null;
144
+ const value = raw;
145
+ if (!isCrmSharingObject(value['object'])) return null;
146
+ return {
147
+ object: value['object'],
148
+ afterId: typeof value['afterId'] === 'string' ? value['afterId'] : null
149
+ };
150
+ }
151
+ /**
152
+ * Carries on every unfinished run: the job's handler. A run document exists
153
+ * only while work is left, so the unfiltered query needs no index and answers
154
+ * nothing on a quiet beat, for one read.
155
+ */ export async function resumeCrmSharingRuns(options = {}) {
156
+ var _options_firestore, _options_budgetMs;
157
+ const firestore = (_options_firestore = options.firestore) != null ? _options_firestore : platformFirestore();
158
+ const pending = await firestore.collectionGroup(CRM_SHARING_RUNS_COLLECTION).limit(RUNS_PER_BEAT).get();
159
+ const tally = {
160
+ resumed: 0,
161
+ finished: 0,
162
+ droppedAfterFailing: 0
163
+ };
164
+ const deadline = Date.now() + ((_options_budgetMs = options.budgetMs) != null ? _options_budgetMs : JOB_BUDGET_MS);
165
+ for (const run of pending.docs){
166
+ var _run_get;
167
+ const budgetMs = deadline - Date.now();
168
+ if (budgetMs <= 0) break;
169
+ tally.resumed += 1;
170
+ const orgRef = run.ref.parent.parent;
171
+ const attempts = Number((_run_get = run.get('attempts')) != null ? _run_get : 0);
172
+ try {
173
+ const org = orgRef ? await orgRef.get() : null;
174
+ // The workspace was erased after this was left: nothing to bring level.
175
+ if (!(org == null ? void 0 : org.exists)) {
176
+ await run.ref.delete();
177
+ tally.finished += 1;
178
+ continue;
179
+ }
180
+ if (run.get('kind') === CRM_DEFAULT_APPLY_KIND) {
181
+ var _pass_run, _pass_run1;
182
+ // A run a person started. One that keeps failing waits for them to
183
+ // resume it from the card, which says it stopped.
184
+ if (attempts >= MAX_RUN_ATTEMPTS) continue;
185
+ const pass = await advanceDefaultApply(firestore, org.id, run.id, Date.now() + budgetMs);
186
+ if (((_pass_run = pass.run) == null ? void 0 : _pass_run.status) === 'failed') await run.ref.update({
187
+ attempts: attempts + 1
188
+ }).catch(()=>undefined);
189
+ if (((_pass_run1 = pass.run) == null ? void 0 : _pass_run1.status) === 'done') tally.finished += 1;
190
+ continue;
191
+ }
192
+ const result = await refreshCrmExceptGrants({
193
+ orgId: org.id,
194
+ budgetMs,
195
+ from: readCursor(run.get('cursor')),
196
+ firestore
197
+ });
198
+ if (!result.complete) {
199
+ await run.ref.update({
200
+ cursor: result.cursor
201
+ });
202
+ continue;
203
+ }
204
+ await run.ref.delete();
205
+ tally.finished += 1;
206
+ } catch (error) {
207
+ console.error(`[crm] ${run.ref.path} failed on attempt ${attempts + 1}`, error);
208
+ if (attempts + 1 >= MAX_RUN_ATTEMPTS) {
209
+ await run.ref.delete().catch(()=>undefined);
210
+ tally.droppedAfterFailing += 1;
211
+ } else {
212
+ await run.ref.update({
213
+ attempts: attempts + 1
214
+ }).catch(()=>undefined);
215
+ }
216
+ }
217
+ }
218
+ return tally;
219
+ }
220
+
221
+ //# sourceMappingURL=crm-sharing-runs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-sharing-runs.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 * KEEPING THE CRM'S \"ALL SITES EXCEPT…\" GRANTS LEVEL (AGL-4047).\n *\n * A grant shared with all sites except some keeps the sites it reaches in its\n * `tokens`, and so in the record's `visibleTo`, the one list readers enforce.\n * A record's sharing is recomputed on every server write, which brings such a\n * grant level as a side effect. A record nobody touches still has to gain a\n * site the workspace adds, and lose one it erases, so a change to the\n * workspace's sites walks the records that carry one: `sharing.hasExcept`,\n * one equality query per kind of record, answering nothing in a workspace\n * that never shared this way.\n *\n * The walk is started by the core sweep's site-change hook\n * (`registerPluginScopeSharingSiteChange`), works for the few seconds the\n * person creating or deleting the site waits, and leaves the rest in\n * `orgs/{orgId}/crmSharingRuns/{runId}` for the CRM's job, which carries on\n * from the cursor. That document exists only while work is left, so the\n * job's query answers nothing on a quiet beat. No Firestore rule opens the\n * path: only this server code reads or writes it.\n *\n * Every step is idempotent: a record already level reads `unchanged` and is\n * not written.\n *\n * The same job carries on \"Apply to existing records\" (`crm-default-sharing.ts`),\n * a run a person started, from the same collection.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldPath } from 'firebase-admin/firestore'\nimport {\n CRM_SHARING_EXCEPT_PATH,\n CRM_SHARING_OBJECTS,\n type CrmSharingObject,\n isCrmSharingObject,\n} from '../model/crm-sharing'\nimport { crmSharingContextFor, crmSharingRulesOf, recomputeMany } from './crm-sharing'\nimport {\n advanceDefaultApply,\n CRM_DEFAULT_APPLY_KIND,\n CRM_SHARING_RUNS_COLLECTION,\n} from './crm-default-sharing'\n\nexport { CRM_SHARING_RUNS_COLLECTION }\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Records read at a time. */\nconst PAGE_SIZE = 100\n/** How long one job beat spends, across every run it takes. */\nconst JOB_BUDGET_MS = 20_000\n/** Runs one beat reads. */\nconst RUNS_PER_BEAT = 10\n/** Beats a failing run gets before it is dropped and reported. */\nexport const MAX_RUN_ATTEMPTS = 5\n\n/** A position in {@link CRM_SHARING_OBJECTS}. */\nexport interface CrmSharingRunCursor {\n object: CrmSharingObject\n afterId: string | null\n}\n\nexport interface CrmExceptRefreshResult {\n /** Records read. */\n read: number\n /** Records whose sharing moved. */\n changed: number\n /** Every kind of record was walked to its end. */\n complete: boolean\n cursor: CrmSharingRunCursor | null\n}\n\nconst platformFirestore = () => firebaseAdmin.app().firestore() as unknown as Firestore\n\n/**\n * Walks the records carrying an all-except grant and recomputes each, from\n * `from` until the budget runs out. Throws only on a failed query.\n */\nexport async function refreshCrmExceptGrants(input: {\n orgId: string\n budgetMs?: number\n from?: CrmSharingRunCursor | null\n firestore?: Firestore\n}): Promise<CrmExceptRefreshResult> {\n const firestore = input.firestore ?? platformFirestore()\n const orgRef = firestore.collection('orgs').doc(input.orgId)\n const deadline = input.budgetMs == null ? null : Date.now() + input.budgetMs\n const startAt = input.from ? Math.max(0, CRM_SHARING_OBJECTS.indexOf(input.from.object)) : 0\n const result: CrmExceptRefreshResult = { read: 0, changed: 0, complete: true, cursor: null }\n let read: Awaited<ReturnType<typeof crmSharingRulesOf>> | null = null\n for (const object of CRM_SHARING_OBJECTS.slice(startAt)) {\n let afterId = input.from?.object === object ? input.from.afterId : null\n for (;;) {\n if (deadline != null && Date.now() >= deadline) {\n return { ...result, complete: false, cursor: { object, afterId } }\n }\n let query = orgRef\n .collection(object)\n .where(CRM_SHARING_EXCEPT_PATH, '==', true)\n .orderBy(FieldPath.documentId())\n .limit(PAGE_SIZE)\n if (afterId) query = query.startAfter(afterId)\n const page = await query.get()\n if (page.empty) break\n // The rules and the sites, read once, and only once a record turns up.\n read ??= await crmSharingRulesOf(firestore, input.orgId, { fresh: true })\n const context = {\n ...(await crmSharingContextFor(firestore, input.orgId, read.rules, object)),\n orgHostIds: read.orgHostIds,\n }\n const outcome = await recomputeMany(\n {\n firestore,\n orgId: input.orgId,\n object,\n rules: read.rules,\n fresh: true,\n context,\n atMs: Date.now(),\n },\n page.docs.map((doc) => doc.id),\n )\n result.read += page.size\n result.changed += outcome.changed.length\n afterId = page.docs[page.docs.length - 1].id\n if (page.size < PAGE_SIZE) break\n }\n }\n return result\n}\n\n/**\n * The CRM's share of a change to a workspace's sites, called by the core\n * sweep. NEVER THROWS: the site change is done. Work it could not finish is\n * left for the job.\n */\nexport async function crmSharingAfterSiteChange(input: {\n orgId: string\n reason: string\n hostId?: string\n budgetMs: number\n firestore?: Firestore\n}): Promise<void> {\n const firestore = input.firestore ?? platformFirestore()\n const leave = (cursor: CrmSharingRunCursor | null, attempts: number) =>\n firestore\n .collection('orgs')\n .doc(input.orgId)\n .collection(CRM_SHARING_RUNS_COLLECTION)\n .doc(createResourceUid())\n .set({\n kind: 'except-grants',\n reason: input.reason,\n ...(input.hostId ? { hostId: input.hostId } : {}),\n cursor,\n attempts,\n createdAtMs: Date.now(),\n })\n try {\n const result = await refreshCrmExceptGrants({\n orgId: input.orgId,\n budgetMs: input.budgetMs,\n firestore,\n })\n if (!result.complete) await leave(result.cursor, 0)\n } catch (error) {\n console.error(`[crm] sharing grants were not brought level after ${input.reason} in ${input.orgId}`, error)\n await leave(null, 1).catch((writeError: unknown) => {\n console.error(`[crm] could not leave ${input.orgId}'s sharing run for the job`, writeError)\n })\n }\n}\n\nfunction readCursor(raw: unknown): CrmSharingRunCursor | null {\n if (!raw || typeof raw !== 'object') return null\n const value = raw as Record<string, unknown>\n if (!isCrmSharingObject(value['object'])) return null\n return {\n object: value['object'],\n afterId: typeof value['afterId'] === 'string' ? value['afterId'] : null,\n }\n}\n\n/**\n * Carries on every unfinished run: the job's handler. A run document exists\n * only while work is left, so the unfiltered query needs no index and answers\n * nothing on a quiet beat, for one read.\n */\nexport async function resumeCrmSharingRuns(\n options: { budgetMs?: number; firestore?: Firestore } = {},\n): Promise<{ resumed: number; finished: number; droppedAfterFailing: number }> {\n const firestore = options.firestore ?? platformFirestore()\n const pending = await firestore.collectionGroup(CRM_SHARING_RUNS_COLLECTION).limit(RUNS_PER_BEAT).get()\n const tally = { resumed: 0, finished: 0, droppedAfterFailing: 0 }\n const deadline = Date.now() + (options.budgetMs ?? JOB_BUDGET_MS)\n for (const run of pending.docs) {\n const budgetMs = deadline - Date.now()\n if (budgetMs <= 0) break\n tally.resumed += 1\n const orgRef = run.ref.parent.parent\n const attempts = Number(run.get('attempts') ?? 0)\n try {\n const org = orgRef ? await orgRef.get() : null\n // The workspace was erased after this was left: nothing to bring level.\n if (!org?.exists) {\n await run.ref.delete()\n tally.finished += 1\n continue\n }\n if (run.get('kind') === CRM_DEFAULT_APPLY_KIND) {\n // A run a person started. One that keeps failing waits for them to\n // resume it from the card, which says it stopped.\n if (attempts >= MAX_RUN_ATTEMPTS) continue\n const pass = await advanceDefaultApply(firestore, org.id, run.id, Date.now() + budgetMs)\n if (pass.run?.status === 'failed') await run.ref.update({ attempts: attempts + 1 }).catch(() => undefined)\n if (pass.run?.status === 'done') tally.finished += 1\n continue\n }\n const result = await refreshCrmExceptGrants({\n orgId: org.id,\n budgetMs,\n from: readCursor(run.get('cursor')),\n firestore,\n })\n if (!result.complete) {\n await run.ref.update({ cursor: result.cursor })\n continue\n }\n await run.ref.delete()\n tally.finished += 1\n } catch (error) {\n console.error(`[crm] ${run.ref.path} failed on attempt ${attempts + 1}`, error)\n if (attempts + 1 >= MAX_RUN_ATTEMPTS) {\n await run.ref.delete().catch(() => undefined)\n tally.droppedAfterFailing += 1\n } else {\n await run.ref.update({ attempts: attempts + 1 }).catch(() => undefined)\n }\n }\n }\n return tally\n}\n"],"names":["createResourceUid","firebaseAdmin","FieldPath","CRM_SHARING_EXCEPT_PATH","CRM_SHARING_OBJECTS","isCrmSharingObject","crmSharingContextFor","crmSharingRulesOf","recomputeMany","advanceDefaultApply","CRM_DEFAULT_APPLY_KIND","CRM_SHARING_RUNS_COLLECTION","PAGE_SIZE","JOB_BUDGET_MS","RUNS_PER_BEAT","MAX_RUN_ATTEMPTS","platformFirestore","app","firestore","refreshCrmExceptGrants","input","orgRef","collection","doc","orgId","deadline","budgetMs","Date","now","startAt","from","Math","max","indexOf","object","result","read","changed","complete","cursor","slice","afterId","query","where","orderBy","documentId","limit","startAfter","page","get","empty","fresh","context","rules","orgHostIds","outcome","atMs","docs","map","id","size","length","crmSharingAfterSiteChange","leave","attempts","set","kind","reason","hostId","createdAtMs","error","console","catch","writeError","readCursor","raw","value","resumeCrmSharingRuns","options","pending","collectionGroup","tally","resumed","finished","droppedAfterFailing","run","ref","parent","Number","org","exists","delete","pass","status","update","undefined","path"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SACEC,uBAAuB,EACvBC,mBAAmB,EAEnBC,kBAAkB,QACb,0BAAsB;AAC7B,SAASC,oBAAoB,EAAEC,iBAAiB,EAAEC,aAAa,QAAQ,mBAAe;AACtF,SACEC,mBAAmB,EACnBC,sBAAsB,EACtBC,2BAA2B,QACtB,2BAAuB;AAE9B,SAASA,2BAA2B,GAAE;AAItC,4BAA4B,GAC5B,MAAMC,YAAY;AAClB,6DAA6D,GAC7D,MAAMC,gBAAgB;AACtB,yBAAyB,GACzB,MAAMC,gBAAgB;AACtB,gEAAgE,GAChE,OAAO,MAAMC,mBAAmB,EAAC;AAkBjC,MAAMC,oBAAoB,IAAMf,cAAcgB,GAAG,GAAGC,SAAS;AAE7D;;;CAGC,GACD,OAAO,eAAe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BACpC,MAAMsE,IAAIC,GAAG,CAACK,MAAM,GAAGnB,KAAK,CAAC,IAAMuB;gBACnCd,MAAMG,mBAAmB,IAAI;YAC/B,OAAO;gBACL,MAAMC,IAAIC,GAAG,CAACQ,MAAM,CAAC;oBAAE9B,UAAUA,WAAW;gBAAE,GAAGQ,KAAK,CAAC,IAAMuB;YAC/D;QACF;IACF;IACA,OAAOd;AACT"}
@@ -15,16 +15,23 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import type { PluginApiHandler } from '@aglyn/aglyn/server';
18
- import { type CrmShareGrant, type CrmSharingContext, type CrmSharingObject, type CrmSharingRule, type CrmSharingSite } from '../model/crm-sharing';
18
+ import { type CrmShareGrant, type CrmDefaultMarkOnlyCollection, type CrmSharingContext, type CrmSharingObject, type CrmSharingRule, type CrmSharingSite } from '../model/crm-sharing';
19
19
  type Firestore = FirebaseFirestore.Firestore;
20
20
  /** Test seam, and what a rule write calls so its own process reads it fresh. */
21
21
  export declare function forgetCrmSharingRules(orgId?: string): void;
22
+ /**
23
+ * The org's rules, and from the same read its sites (`orgs/{orgId}.hosts`),
24
+ * which a grant shared with all sites except some reaches, and the document
25
+ * itself, whose CRM default a new record is marked by (AGL-4047).
26
+ */
22
27
  export declare function crmSharingRulesOf(firestore: Firestore, orgId: string, options?: {
23
28
  fresh?: boolean;
24
29
  nowMs?: number;
25
30
  }): Promise<{
26
31
  rules: CrmSharingRule[];
27
32
  fresh: boolean;
33
+ orgHostIds: string[];
34
+ org: Record<string, unknown>;
28
35
  }>;
29
36
  /**
30
37
  * What the rules for `object` are evaluated against beyond the record: the
@@ -49,6 +56,20 @@ export interface RecomputeRecordSharingInput {
49
56
  }
50
57
  export type RecomputeOutcome = 'changed' | 'unchanged' | 'missing';
51
58
  export declare function recomputeRecordSharing(input: RecomputeRecordSharingInput): Promise<RecomputeOutcome>;
59
+ /** Several records at once, a few in flight. */
60
+ export declare function recomputeMany(input: Omit<RecomputeRecordSharingInput, 'id'>, ids: readonly string[]): Promise<{
61
+ changed: string[];
62
+ missing: number;
63
+ }>;
64
+ /**
65
+ * What a browser's own write of a record no sharing rule applies to — a
66
+ * logged activity — owes the CRM default: the marker, when its sites are
67
+ * exactly the default's (AGL-4047). Nothing else moves.
68
+ */
69
+ export declare function markCrmRecordsUnderDefault(firestore: Firestore, orgId: string, collection: CrmDefaultMarkOnlyCollection, ids: readonly string[]): Promise<{
70
+ changed: number;
71
+ missing: number;
72
+ }>;
52
73
  /**
53
74
  * Re-evaluates the org's rules for these records — the one thing a write
54
75
  * anywhere owes the sharing. An org with no active rule for the object
@@ -76,6 +97,8 @@ export declare function crmSharingSites(firestore: Firestore, orgId: string): Pr
76
97
  */
77
98
  export declare function ruleFromRequest(raw: unknown, context: {
78
99
  hostIds: readonly string[];
100
+ /** The workspace's sites as `orgs/{orgId}.hosts` names them, which all sites except some is worked out from. */
101
+ orgSiteIds?: readonly string[];
79
102
  existing: CrmSharingRule | null;
80
103
  uid: string;
81
104
  nowMs: number;