@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
@@ -32,14 +32,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
32
32
  * - a rule's recompute over existing records (`rule-save`, `rule-continue`),
33
33
  * and its removal (`rule-delete`), in budgeted passes with the progress on
34
34
  * the rule.
35
- */ import { CRM_COLLECTIONS, crmActivityLogHasRoom, crmListFieldsPatch } from "@aglyn/aglyn/app-utils/crm";
35
+ */ import { CRM_COLLECTIONS, crmActivityLogHasRoom, crmDefaultExceptOf, crmListFieldsPatch } from "@aglyn/aglyn/app-utils/crm";
36
36
  import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
37
- import { hostIdsFromScope } from "@aglyn/aglyn/app-utils/scope-tokens";
37
+ import { hostIdsFromScope, sharingFromChoice } from "@aglyn/aglyn/app-utils/scope-tokens";
38
38
  import { firebaseAdmin, getOrgForHost, logOrgActivity } from "@aglyn/tenant-data-admin";
39
39
  import { countCrmActivitiesForRecord } from "@aglyn/tenant-data-admin/server/crm-records";
40
40
  import { FieldPath, FieldValue } from "firebase-admin/firestore";
41
41
  import { BUNDLE_ID } from "../constants/bundle-common.js";
42
- import { activeSharingRules, CRM_SHARING_CRITERIA_FOR, CRM_SHARING_CRITERIA_KEYS, CRM_SHARING_FIELD, CRM_SHARING_IDS_MAX, CRM_SHARING_OBJECT_LABELS, CRM_SHARING_RULE_IDS_PATH, CRM_SHARING_RULES_MAX, CRM_WRITE_SCOPE_FIELD, describeShareTargets, evaluateRecordGrants, isCrmShareAccess, isCrmSharingObject, planRecordSharing, readCrmSharingRule, readCrmSharingRules, recordHeldScope, sharingPlanChanges, shareTargetsFrom, sharingRulesAskLeadSourceDirection, withManualShares, withoutManualShares } from "../model/crm-sharing.js";
42
+ import { activeSharingRules, CRM_SHARING_CRITERIA_FOR, CRM_SHARING_CRITERIA_KEYS, CRM_SHARING_FIELD, CRM_SHARING_IDS_MAX, crmOrgHostIds, CRM_SHARING_MAX_INCLUDED, CRM_SHARING_OBJECT_LABELS, CRM_SHARING_RULE_IDS_PATH, CRM_SHARING_RULES_MAX, CRM_WRITE_SCOPE_FIELD, describeShareTargets, evaluateRecordGrants, isCrmDefaultMarkOnlyCollection, isCrmShareAccess, isCrmSharingObject, planRecordSharing, readCrmSharingRule, readCrmSharingRules, recordHeldScope, sharingAsksOrgSites, sharingPlanChanges, shareExceptChoiceFrom, shareTargetsFrom, sharingRulesAskLeadSourceDirection, withManualExceptShare, withManualShares, withoutManualExceptShare, withoutManualShares } from "../model/crm-sharing.js";
43
43
  import { stampCrmActivityCompany } from "../model/crm-activity-link.js";
44
44
  import { crmSettingsPermissionRefusal } from "../model/crm-permissions.js";
45
45
  import { readLeadSourcePicklist } from "./lead-source-picklist.js";
@@ -58,25 +58,37 @@ const rulesCache = new Map();
58
58
  if (orgId) rulesCache.delete(orgId);
59
59
  else rulesCache.clear();
60
60
  }
61
- export async function crmSharingRulesOf(firestore, orgId, options = {}) {
61
+ /**
62
+ * The org's rules, and from the same read its sites (`orgs/{orgId}.hosts`),
63
+ * which a grant shared with all sites except some reaches, and the document
64
+ * itself, whose CRM default a new record is marked by (AGL-4047).
65
+ */ export async function crmSharingRulesOf(firestore, orgId, options = {}) {
62
66
  var _options_nowMs, _snapshot_data;
63
67
  const nowMs = (_options_nowMs = options.nowMs) != null ? _options_nowMs : Date.now();
64
68
  const cached = rulesCache.get(orgId);
65
69
  if (!options.fresh && cached && nowMs - cached.atMs < RULES_TTL_MS) {
66
70
  return {
67
71
  rules: cached.rules,
68
- fresh: false
72
+ fresh: false,
73
+ orgHostIds: cached.orgHostIds,
74
+ org: cached.org
69
75
  };
70
76
  }
71
77
  const snapshot = await firestore.collection('orgs').doc(orgId).get();
72
- const rules = readCrmSharingRules((_snapshot_data = snapshot.data()) != null ? _snapshot_data : null);
78
+ const org = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
79
+ const rules = readCrmSharingRules(org);
80
+ const orgHostIds = crmOrgHostIds(org);
73
81
  rulesCache.set(orgId, {
74
82
  atMs: nowMs,
75
- rules
83
+ rules,
84
+ orgHostIds,
85
+ org
76
86
  });
77
87
  return {
78
88
  rules,
79
- fresh: true
89
+ fresh: true,
90
+ orgHostIds,
91
+ org
80
92
  };
81
93
  }
82
94
  /**
@@ -91,13 +103,19 @@ export async function crmSharingRulesOf(firestore, orgId, options = {}) {
91
103
  }
92
104
  export async function recomputeRecordSharing(input) {
93
105
  const { firestore, orgId, object, id, atMs } = input;
94
- const ref = firestore.collection('orgs').doc(orgId).collection(object).doc(id);
106
+ const orgRef = firestore.collection('orgs').doc(orgId);
107
+ const ref = orgRef.collection(object).doc(id);
95
108
  return await firestore.runTransaction(async (tx)=>{
96
109
  var _snapshot_data, _plan_writeTo, _plan_sharing, _plan_writeTo1, _plan_sharing1;
97
110
  var _input_context;
98
111
  const snapshot = await tx.get(ref);
99
112
  if (!snapshot.exists) return 'missing';
100
113
  const record = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
114
+ let orgData;
115
+ const readOrg = async ()=>{
116
+ var _data;
117
+ return orgData != null ? orgData : orgData = (_data = (await tx.get(orgRef)).data()) != null ? _data : {};
118
+ };
101
119
  let rules = input.rules;
102
120
  /*
103
121
  * A GRANT IS NEVER TAKEN AWAY ON A STALE ANSWER. A rule grant whose rule
@@ -109,13 +127,21 @@ export async function recomputeRecordSharing(input) {
109
127
  const stored = record[CRM_SHARING_FIELD];
110
128
  const ruleIds = Array.isArray(stored == null ? void 0 : stored.ruleIds) ? stored.ruleIds : [];
111
129
  if (ruleIds.some((ruleId)=>!known.has(String(ruleId)))) {
112
- var _org_data;
113
- const org = await tx.get(firestore.collection('orgs').doc(orgId));
114
- rules = readCrmSharingRules((_org_data = org.data()) != null ? _org_data : null);
130
+ rules = readCrmSharingRules(await readOrg());
115
131
  }
116
132
  }
117
133
  // A rule read afresh above may ask a direction the caller's context was not read for.
118
- const context = ((_input_context = input.context) == null ? void 0 : _input_context.leadSources) || rules === input.rules ? input.context : await crmSharingContextFor(firestore, orgId, rules, object);
134
+ let context = ((_input_context = input.context) == null ? void 0 : _input_context.leadSources) || rules === input.rules ? input.context : await crmSharingContextFor(firestore, orgId, rules, object);
135
+ /*
136
+ * A grant shared with all sites except some reaches the workspace's sites
137
+ * as they are at commit (AGL-4047): read in this transaction, so a site
138
+ * claimed meanwhile is either on the list or finds this record in its own
139
+ * site change. Nothing else pays for the read.
140
+ */ if (sharingAsksOrgSites(object, record, rules)) {
141
+ context = _extends({}, context, {
142
+ orgHostIds: crmOrgHostIds(await readOrg())
143
+ });
144
+ }
119
145
  let grants = evaluateRecordGrants(object, record, rules, atMs, context);
120
146
  if (input.manual) grants = input.manual(grants);
121
147
  const plan = planRecordSharing(record, grants);
@@ -133,7 +159,7 @@ export async function recomputeRecordSharing(input) {
133
159
  return 'changed';
134
160
  });
135
161
  }
136
- /** Several records at once, a few in flight. */ async function recomputeMany(input, ids) {
162
+ /** Several records at once, a few in flight. */ export async function recomputeMany(input, ids) {
137
163
  const queue = [
138
164
  ...new Set(ids)
139
165
  ];
@@ -156,18 +182,50 @@ export async function recomputeRecordSharing(input) {
156
182
  missing
157
183
  };
158
184
  }
185
+ /**
186
+ * A record the CRM default "All sites except…" stamped carries the sites it
187
+ * reaches today; the marker that lets a site added later join it is the
188
+ * server's to write (AGL-4047). Only an org with that default pays for it.
189
+ * Answers how many records it marked.
190
+ */ async function markUnderDefault(firestore, orgId, collection, ids, org) {
191
+ if (!crmDefaultExceptOf(org)) return 0;
192
+ const { markRecordUnderDefault } = await import("./crm-default-sharing.js");
193
+ let marked = 0;
194
+ for (const id of ids){
195
+ const wrote = await markRecordUnderDefault(firestore, orgId, collection, id, org).catch((error)=>{
196
+ console.error(`[crm] ${collection}/${id} was not marked for the default sharing`, error);
197
+ return false;
198
+ });
199
+ if (wrote) marked += 1;
200
+ }
201
+ return marked;
202
+ }
203
+ /**
204
+ * What a browser's own write of a record no sharing rule applies to — a
205
+ * logged activity — owes the CRM default: the marker, when its sites are
206
+ * exactly the default's (AGL-4047). Nothing else moves.
207
+ */ export async function markCrmRecordsUnderDefault(firestore, orgId, collection, ids) {
208
+ const { org } = await crmSharingRulesOf(firestore, orgId);
209
+ return {
210
+ changed: await markUnderDefault(firestore, orgId, collection, ids, org),
211
+ missing: 0
212
+ };
213
+ }
159
214
  /**
160
215
  * Re-evaluates the org's rules for these records — the one thing a write
161
216
  * anywhere owes the sharing. An org with no active rule for the object
162
217
  * costs one cached read and nothing else; grants of a rule switched off
163
218
  * are taken away by that rule's own removal pass, not here.
164
219
  */ export async function evaluateCrmSharing(firestore, orgId, object, ids) {
165
- const { rules, fresh } = await crmSharingRulesOf(firestore, orgId);
220
+ const { rules, fresh, orgHostIds, org } = await crmSharingRulesOf(firestore, orgId);
221
+ await markUnderDefault(firestore, orgId, object, ids, org);
166
222
  if (!activeSharingRules(rules, object).length) return {
167
223
  changed: 0,
168
224
  missing: 0
169
225
  };
170
- const context = await crmSharingContextFor(firestore, orgId, rules, object);
226
+ const context = _extends({}, await crmSharingContextFor(firestore, orgId, rules, object), {
227
+ orgHostIds
228
+ });
171
229
  const outcome = await recomputeMany({
172
230
  firestore,
173
231
  orgId,
@@ -313,7 +371,25 @@ const ORG_TARGET = {
313
371
  error: 'A site the rule names is not one of this organization’s.'
314
372
  };
315
373
  }
316
- const targets = shareTargetsFrom(value['targets']);
374
+ /*
375
+ * All sites except some (AGL-4047): the sites it leaves out decide, and its
376
+ * targets are the sites that leaves today, so a reader that predates the
377
+ * choice shares with no site it leaves out.
378
+ */ const exceptChoice = shareExceptChoiceFrom(value['targets']);
379
+ let except = [];
380
+ let targets = exceptChoice ? null : shareTargetsFrom(value['targets']);
381
+ if (exceptChoice) {
382
+ var _context_orgSiteIds, _shared_fields_scopeExcept;
383
+ const shared = sharingFromChoice(exceptChoice, (_context_orgSiteIds = context.orgSiteIds) != null ? _context_orgSiteIds : context.hostIds, {
384
+ maxIncluded: CRM_SHARING_MAX_INCLUDED
385
+ });
386
+ if (!shared.fields) return {
387
+ rule: null,
388
+ error: shared.problem
389
+ };
390
+ targets = shared.fields.visibleTo;
391
+ except = (_shared_fields_scopeExcept = shared.fields.scopeExcept) != null ? _shared_fields_scopeExcept : [];
392
+ }
317
393
  if (!targets) return {
318
394
  rule: null,
319
395
  error: 'Choose the sites to share with, or All sites.'
@@ -339,19 +415,22 @@ const ORG_TARGET = {
339
415
  if (list.length) criteria[key] = list;
340
416
  }
341
417
  const existing = context.existing;
342
- const rule = readCrmSharingRule({
418
+ const rule = readCrmSharingRule(_extends({
343
419
  id: (_ref = existing == null ? void 0 : existing.id) != null ? _ref : createResourceUid(),
344
420
  name,
345
421
  object,
346
422
  enabled: value['enabled'] !== false,
347
423
  sourceHostIds,
348
424
  criteria,
349
- targets,
425
+ targets
426
+ }, except.length ? {
427
+ except
428
+ } : {}, {
350
429
  access: access != null ? access : 'read',
351
430
  createdByUid: (_ref1 = existing == null ? void 0 : existing.createdByUid) != null ? _ref1 : context.uid,
352
431
  createdAtMs: (_ref2 = existing == null ? void 0 : existing.createdAtMs) != null ? _ref2 : context.nowMs,
353
432
  updatedAtMs: context.nowMs
354
- });
433
+ }));
355
434
  if (!rule) return {
356
435
  rule: null,
357
436
  error: 'The rule could not be read.'
@@ -425,10 +504,12 @@ const ORG_TARGET = {
425
504
  while(Date.now() < deadlineMs){
426
505
  var _ref, _ref1;
427
506
  var _page_docs_;
428
- const { rules } = await crmSharingRulesOf(firestore, orgId, {
507
+ const { rules, orgHostIds } = await crmSharingRulesOf(firestore, orgId, {
429
508
  fresh: true
430
509
  });
431
- const context = await crmSharingContextFor(firestore, orgId, rules, rule.object);
510
+ const context = _extends({}, await crmSharingContextFor(firestore, orgId, rules, rule.object), {
511
+ orgHostIds
512
+ });
432
513
  let page;
433
514
  if (run.mode === 'apply') {
434
515
  let query = records.orderBy(FieldPath.documentId()).limit(RUN_PAGE);
@@ -538,7 +619,7 @@ function readIds(raw) {
538
619
  if (action === 'evaluate') {
539
620
  const object = body['object'];
540
621
  const ids = readIds(body['ids']);
541
- if (!isCrmSharingObject(object) || !ids) {
622
+ if (!isCrmSharingObject(object) && !isCrmDefaultMarkOnlyCollection(object) || !ids) {
542
623
  res.status(400).json({
543
624
  error: 'Name the records.'
544
625
  });
@@ -551,7 +632,8 @@ function readIds(raw) {
551
632
  res.status(writer.status).json(writer.body);
552
633
  return;
553
634
  }
554
- const outcome = await evaluateCrmSharing(firestore, writer.orgId, object, ids);
635
+ // A logged activity no rule applies to: only the CRM default's marker (AGL-4047).
636
+ const outcome = isCrmDefaultMarkOnlyCollection(object) ? await markCrmRecordsUnderDefault(firestore, writer.orgId, object, ids) : await evaluateCrmSharing(firestore, writer.orgId, object, ids);
555
637
  const answer = _extends({
556
638
  ok: true
557
639
  }, outcome);
@@ -603,7 +685,32 @@ function readIds(raw) {
603
685
  });
604
686
  return;
605
687
  }
606
- const targets = shareTargetsFrom(body['targets']);
688
+ const access = body['access'] === 'edit' ? 'edit' : 'read';
689
+ const { rules, fresh, orgHostIds } = await crmSharingRulesOf(firestore, orgId);
690
+ /*
691
+ * All sites except some (AGL-4047): one grant, worked out against the
692
+ * workspace's sites as `orgs/{orgId}.hosts` names them, at most
693
+ * CRM_SHARING_MAX_INCLUDED of them. Its unshare names it as 'allExcept'.
694
+ */ const exceptChoice = action === 'share' ? shareExceptChoiceFrom(body['targets']) : null;
695
+ const unshareExcept = action === 'unshare' && body['targets'] === 'allExcept';
696
+ let except = [];
697
+ let targets = exceptChoice || unshareExcept ? null : shareTargetsFrom(body['targets']);
698
+ if (exceptChoice) {
699
+ var _shared_fields_scopeExcept;
700
+ const fromOrg = await firestore.collection('orgs').doc(orgId).get();
701
+ const shared = sharingFromChoice(exceptChoice, crmOrgHostIds(fromOrg.data()), {
702
+ maxIncluded: CRM_SHARING_MAX_INCLUDED
703
+ });
704
+ if (!shared.fields) {
705
+ res.status(400).json({
706
+ error: shared.problem
707
+ });
708
+ return;
709
+ }
710
+ targets = shared.fields.visibleTo;
711
+ except = (_shared_fields_scopeExcept = shared.fields.scopeExcept) != null ? _shared_fields_scopeExcept : [];
712
+ }
713
+ if (unshareExcept) targets = [];
607
714
  if (!targets) {
608
715
  res.status(400).json({
609
716
  error: 'Choose the sites, or All sites.'
@@ -618,9 +725,10 @@ function readIds(raw) {
618
725
  });
619
726
  return;
620
727
  }
621
- const access = body['access'] === 'edit' ? 'edit' : 'read';
622
- const { rules, fresh } = await crmSharingRulesOf(firestore, orgId);
623
- const context = await crmSharingContextFor(firestore, orgId, rules, object);
728
+ const shareTokens = targets;
729
+ const context = _extends({}, await crmSharingContextFor(firestore, orgId, rules, object), {
730
+ orgHostIds
731
+ });
624
732
  const outcome = await recomputeMany({
625
733
  firestore,
626
734
  orgId,
@@ -629,17 +737,23 @@ function readIds(raw) {
629
737
  fresh,
630
738
  context,
631
739
  atMs: nowMs,
632
- manual: (grants)=>action === 'share' ? withManualShares(grants, targets, access, {
740
+ manual: (grants)=>exceptChoice ? withManualExceptShare(grants, {
741
+ tokens: shareTokens,
742
+ except
743
+ }, access, {
633
744
  uid: caller.uid,
634
745
  name: byName
635
- }, nowMs) : withoutManualShares(grants, targets)
746
+ }, nowMs) : unshareExcept ? withoutManualExceptShare(grants) : action === 'share' ? withManualShares(grants, shareTokens, access, {
747
+ uid: caller.uid,
748
+ name: byName
749
+ }, nowMs) : withoutManualShares(grants, shareTokens)
636
750
  }, ids);
637
751
  const siteName = (id)=>{
638
752
  var _ref;
639
753
  var _sites_find;
640
754
  return (_ref = (_sites_find = sites.find((site)=>site.id === id)) == null ? void 0 : _sites_find.name) != null ? _ref : 'a site';
641
755
  };
642
- const named = describeShareTargets(targets, siteName);
756
+ const named = unshareExcept ? 'all sites except some' : describeShareTargets(targets, siteName, except);
643
757
  const sentence = action === 'share' ? `Shared with ${named}${access === 'edit' ? ' (read and edit)' : ' (read-only)'}` : `Stopped sharing with ${named}`;
644
758
  await Promise.all(outcome.changed.map((id)=>fileSharingActivity(firestore, {
645
759
  orgId,
@@ -672,6 +786,7 @@ function readIds(raw) {
672
786
  if (action === 'rule-save') {
673
787
  var _raw_id;
674
788
  const hostIds = await orgHostIds(firestore, orgId);
789
+ const orgSiteIds = crmOrgHostIds((await firestore.collection('orgs').doc(orgId).get()).data());
675
790
  const raw = body['rule'];
676
791
  const ruleId = raw && typeof raw === 'object' ? String((_raw_id = raw['id']) != null ? _raw_id : '') : '';
677
792
  let saved = null;
@@ -692,6 +807,7 @@ function readIds(raw) {
692
807
  }
693
808
  const judged = ruleFromRequest(raw, {
694
809
  hostIds,
810
+ orgSiteIds,
695
811
  existing,
696
812
  uid: caller.uid,
697
813
  nowMs
@@ -743,6 +859,42 @@ function readIds(raw) {
743
859
  res.status(200).json(answer);
744
860
  return;
745
861
  }
862
+ /*
863
+ * "Apply to existing records" (AGL-4047): the CRM default all sites except
864
+ * some, brought to every record the workspace already has. Started here,
865
+ * and carried on here while the card is open and by the CRM job when not.
866
+ */ if (action === 'default-apply' || action === 'default-apply-continue') {
867
+ const { advanceDefaultApply, findDefaultApply, startDefaultApply } = await import("./crm-default-sharing.js");
868
+ let runId;
869
+ if (action === 'default-apply') {
870
+ const started = await startDefaultApply(firestore, orgId, {
871
+ uid: caller.uid
872
+ });
873
+ if (started.ok === false) {
874
+ res.status(400).json({
875
+ error: started.error
876
+ });
877
+ return;
878
+ }
879
+ runId = started.runId;
880
+ await logOrgActivity(orgId, actor, 'Started applying the CRM default sharing to existing records', {
881
+ type: `${BUNDLE_ID}:defaultSharing`
882
+ }).catch(()=>undefined);
883
+ } else {
884
+ runId = await findDefaultApply(firestore, orgId);
885
+ }
886
+ const pass = runId ? await advanceDefaultApply(firestore, orgId, runId, Date.now() + RUN_BUDGET_MS) : {
887
+ run: null,
888
+ more: false
889
+ };
890
+ const answer = {
891
+ ok: true,
892
+ applyRun: pass.run,
893
+ more: pass.more
894
+ };
895
+ res.status(200).json(answer);
896
+ return;
897
+ }
746
898
  if (action === 'rule-delete' || action === 'rule-continue') {
747
899
  var _body_ruleId;
748
900
  const ruleId = String((_body_ruleId = body['ruleId']) != null ? _body_ruleId : '').trim();