@aglyn/aglyn 1.0.0-beta.221 → 1.0.0-beta.222
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.
- package/package.json +15 -11
- package/src/lib/app-utils/agent-openapi.js +1 -1
- package/src/lib/app-utils/agent-openapi.js.map +1 -1
- package/src/lib/app-utils/analytics-events.d.ts +3 -2
- package/src/lib/app-utils/analytics-events.js +3 -2
- package/src/lib/app-utils/analytics-events.js.map +1 -1
- package/src/lib/app-utils/api-plugins.d.ts +30 -0
- package/src/lib/app-utils/api-plugins.js +24 -1
- package/src/lib/app-utils/api-plugins.js.map +1 -1
- package/src/lib/app-utils/author-html.d.ts +1 -1
- package/src/lib/app-utils/author-html.js.map +1 -1
- package/src/lib/app-utils/bandwidth-cap.d.ts +12 -1
- package/src/lib/app-utils/bandwidth-cap.js +17 -1
- package/src/lib/app-utils/bandwidth-cap.js.map +1 -1
- package/src/lib/app-utils/compose-reusable-components.d.ts +19 -0
- package/src/lib/app-utils/compose-reusable-components.js +116 -26
- package/src/lib/app-utils/compose-reusable-components.js.map +1 -1
- package/src/lib/app-utils/console-routes.d.ts +4 -0
- package/src/lib/app-utils/console-routes.js +3 -0
- package/src/lib/app-utils/console-routes.js.map +1 -1
- package/src/lib/app-utils/contacts.d.ts +71 -0
- package/src/lib/app-utils/contacts.js +55 -0
- package/src/lib/app-utils/contacts.js.map +1 -1
- package/src/lib/app-utils/contexts.d.ts +1 -0
- package/src/lib/app-utils/contexts.js +1 -0
- package/src/lib/app-utils/contexts.js.map +1 -1
- package/src/lib/app-utils/crm-email-templates.js +21 -4
- package/src/lib/app-utils/crm-email-templates.js.map +1 -1
- package/src/lib/app-utils/crm-kinds.d.ts +2 -0
- package/src/lib/app-utils/crm-kinds.js +1 -0
- package/src/lib/app-utils/crm-kinds.js.map +1 -1
- package/src/lib/app-utils/crm.d.ts +1199 -67
- package/src/lib/app-utils/crm.js +1951 -310
- package/src/lib/app-utils/crm.js.map +1 -1
- package/src/lib/app-utils/csv-import.d.ts +10 -38
- package/src/lib/app-utils/csv-import.js +17 -42
- package/src/lib/app-utils/csv-import.js.map +1 -1
- package/src/lib/app-utils/csv.d.ts +32 -11
- package/src/lib/app-utils/csv.js +43 -5
- package/src/lib/app-utils/csv.js.map +1 -1
- package/src/lib/app-utils/default-site.d.ts +116 -0
- package/src/lib/app-utils/default-site.js +1024 -0
- package/src/lib/app-utils/default-site.js.map +1 -0
- package/src/lib/app-utils/docs-help.generated.d.ts +22 -22
- package/src/lib/app-utils/docs-help.generated.js +44 -10
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +738 -150
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/draft-placeholders.d.ts +76 -0
- package/src/lib/app-utils/draft-placeholders.js +115 -0
- package/src/lib/app-utils/draft-placeholders.js.map +1 -0
- package/src/lib/app-utils/entity-picker-context.d.ts +19 -15
- package/src/lib/app-utils/entity-picker-context.js +4 -4
- package/src/lib/app-utils/entity-picker-context.js.map +1 -1
- package/src/lib/app-utils/expand-repeatables.d.ts +66 -10
- package/src/lib/app-utils/expand-repeatables.js +88 -14
- package/src/lib/app-utils/expand-repeatables.js.map +1 -1
- package/src/lib/app-utils/forms.d.ts +33 -22
- package/src/lib/app-utils/forms.js +47 -28
- package/src/lib/app-utils/forms.js.map +1 -1
- package/src/lib/app-utils/full-use-cost.d.ts +277 -0
- package/src/lib/app-utils/full-use-cost.js +421 -0
- package/src/lib/app-utils/full-use-cost.js.map +1 -0
- package/src/lib/app-utils/health-report.js +11 -0
- package/src/lib/app-utils/health-report.js.map +1 -1
- package/src/lib/app-utils/llms-txt.d.ts +20 -0
- package/src/lib/app-utils/llms-txt.js +7 -1
- package/src/lib/app-utils/llms-txt.js.map +1 -1
- package/src/lib/app-utils/media-asset-facts.d.ts +16 -1
- package/src/lib/app-utils/media-asset-facts.js +40 -13
- package/src/lib/app-utils/media-asset-facts.js.map +1 -1
- package/src/lib/app-utils/media-bandwidth.d.ts +52 -0
- package/src/lib/app-utils/media-bandwidth.js +94 -0
- package/src/lib/app-utils/media-bandwidth.js.map +1 -0
- package/src/lib/app-utils/media-ref.d.ts +241 -33
- package/src/lib/app-utils/media-ref.js +324 -43
- package/src/lib/app-utils/media-ref.js.map +1 -1
- package/src/lib/app-utils/media-src.d.ts +8 -8
- package/src/lib/app-utils/media-src.js +27 -11
- package/src/lib/app-utils/media-src.js.map +1 -1
- package/src/lib/app-utils/media-takedown-reach.d.ts +4 -1
- package/src/lib/app-utils/media-takedown-reach.js +6 -3
- package/src/lib/app-utils/media-takedown-reach.js.map +1 -1
- package/src/lib/app-utils/notifications.d.ts +1 -1
- package/src/lib/app-utils/notifications.js +2 -0
- package/src/lib/app-utils/notifications.js.map +1 -1
- package/src/lib/app-utils/organizations.d.ts +51 -2
- package/src/lib/app-utils/organizations.js +56 -3
- package/src/lib/app-utils/organizations.js.map +1 -1
- package/src/lib/app-utils/page-record-sources.d.ts +87 -0
- package/src/lib/app-utils/page-record-sources.js +53 -0
- package/src/lib/app-utils/page-record-sources.js.map +1 -0
- package/src/lib/app-utils/paid-media-source.d.ts +3 -7
- package/src/lib/app-utils/paid-media-source.js +5 -19
- package/src/lib/app-utils/paid-media-source.js.map +1 -1
- package/src/lib/app-utils/person-erasure.d.ts +5 -2
- package/src/lib/app-utils/person-erasure.js.map +1 -1
- package/src/lib/app-utils/picklists.d.ts +187 -0
- package/src/lib/app-utils/picklists.js +320 -0
- package/src/lib/app-utils/picklists.js.map +1 -0
- package/src/lib/app-utils/plan-entitlements.d.ts +220 -50
- package/src/lib/app-utils/plan-entitlements.js +309 -115
- package/src/lib/app-utils/plan-entitlements.js.map +1 -1
- package/src/lib/app-utils/realm-host-surface.generated.js +2 -0
- package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
- package/src/lib/app-utils/release-flags.d.ts +1 -1
- package/src/lib/app-utils/release-flags.js +11 -0
- package/src/lib/app-utils/release-flags.js.map +1 -1
- package/src/lib/app-utils/rendered-widths.d.ts +121 -0
- package/src/lib/app-utils/rendered-widths.js +211 -0
- package/src/lib/app-utils/rendered-widths.js.map +1 -0
- package/src/lib/app-utils/repeat-sources.d.ts +2 -1
- package/src/lib/app-utils/repeat-sources.js.map +1 -1
- package/src/lib/app-utils/screen-route.d.ts +154 -36
- package/src/lib/app-utils/screen-route.js +185 -40
- package/src/lib/app-utils/screen-route.js.map +1 -1
- package/src/lib/app-utils/seo-audit.d.ts +11 -1
- package/src/lib/app-utils/seo-audit.js +33 -13
- package/src/lib/app-utils/seo-audit.js.map +1 -1
- package/src/lib/app-utils/seo-keywords.d.ts +11 -0
- package/src/lib/app-utils/seo-keywords.js +19 -5
- package/src/lib/app-utils/seo-keywords.js.map +1 -1
- package/src/lib/app-utils/seo-page-facts.d.ts +47 -4
- package/src/lib/app-utils/seo-page-facts.js +136 -31
- package/src/lib/app-utils/seo-page-facts.js.map +1 -1
- package/src/lib/app-utils/seo-site-scan.d.ts +42 -4
- package/src/lib/app-utils/seo-site-scan.js +113 -12
- package/src/lib/app-utils/seo-site-scan.js.map +1 -1
- package/src/lib/app-utils/server.d.ts +5 -4
- package/src/lib/app-utils/server.js +14 -5
- package/src/lib/app-utils/server.js.map +1 -1
- package/src/lib/app-utils/site-icon-set.d.ts +195 -0
- package/src/lib/app-utils/site-icon-set.js +351 -0
- package/src/lib/app-utils/site-icon-set.js.map +1 -0
- package/src/lib/app-utils/site-interactions.d.ts +101 -4
- package/src/lib/app-utils/site-interactions.js +120 -4
- package/src/lib/app-utils/site-interactions.js.map +1 -1
- package/src/lib/app-utils/starter-template-nodes.d.ts +7 -0
- package/src/lib/app-utils/starter-template-nodes.js +3 -0
- package/src/lib/app-utils/starter-template-nodes.js.map +1 -1
- package/src/lib/app-utils/starter-templates.d.ts +5 -19
- package/src/lib/app-utils/starter-templates.js +5 -49
- package/src/lib/app-utils/starter-templates.js.map +1 -1
- package/src/lib/app-utils/transfer-launcher-context.d.ts +136 -0
- package/src/lib/app-utils/transfer-launcher-context.js +23 -0
- package/src/lib/app-utils/transfer-launcher-context.js.map +1 -0
- package/src/lib/app-utils/transfer-resume-import.d.ts +39 -0
- package/src/lib/app-utils/transfer-resume-import.js +128 -0
- package/src/lib/app-utils/transfer-resume-import.js.map +1 -0
- package/src/lib/app-utils/upgrade-proposal.d.ts +66 -0
- package/src/lib/app-utils/upgrade-proposal.js +95 -0
- package/src/lib/app-utils/upgrade-proposal.js.map +1 -0
- package/src/lib/app-utils/utc-month.d.ts +33 -0
- package/src/lib/app-utils/utc-month.js +35 -0
- package/src/lib/app-utils/utc-month.js.map +1 -0
- package/src/lib/app-utils/visitor-record-ceiling.d.ts +4 -4
- package/src/lib/app-utils/visitor-record-ceiling.js +4 -4
- package/src/lib/app-utils/visitor-record-ceiling.js.map +1 -1
- package/src/lib/app-utils/wire-nodes.d.ts +39 -19
- package/src/lib/app-utils/wire-nodes.js +120 -34
- package/src/lib/app-utils/wire-nodes.js.map +1 -1
- package/src/lib/data-transfer/access.d.ts +74 -0
- package/src/lib/data-transfer/access.js +93 -0
- package/src/lib/data-transfer/access.js.map +1 -0
- package/src/lib/data-transfer/derive.d.ts +246 -0
- package/src/lib/data-transfer/derive.js +1007 -0
- package/src/lib/data-transfer/derive.js.map +1 -0
- package/src/lib/data-transfer/export-file.d.ts +46 -0
- package/src/lib/data-transfer/export-file.js +146 -0
- package/src/lib/data-transfer/export-file.js.map +1 -0
- package/src/lib/data-transfer/field-catalog.d.ts +134 -0
- package/src/lib/data-transfer/field-catalog.js +278 -0
- package/src/lib/data-transfer/field-catalog.js.map +1 -0
- package/src/lib/data-transfer/header-match.d.ts +129 -0
- package/src/lib/data-transfer/header-match.js +367 -0
- package/src/lib/data-transfer/header-match.js.map +1 -0
- package/src/lib/data-transfer/index.d.ts +34 -0
- package/src/lib/data-transfer/index.js +40 -0
- package/src/lib/data-transfer/index.js.map +1 -0
- package/src/lib/data-transfer/job.d.ts +190 -0
- package/src/lib/data-transfer/job.js +229 -0
- package/src/lib/data-transfer/job.js.map +1 -0
- package/src/lib/data-transfer/lookup.d.ts +45 -0
- package/src/lib/data-transfer/lookup.js +71 -0
- package/src/lib/data-transfer/lookup.js.map +1 -0
- package/src/lib/data-transfer/match.d.ts +99 -0
- package/src/lib/data-transfer/match.js +244 -0
- package/src/lib/data-transfer/match.js.map +1 -0
- package/src/lib/data-transfer/package-plan.d.ts +205 -0
- package/src/lib/data-transfer/package-plan.js +475 -0
- package/src/lib/data-transfer/package-plan.js.map +1 -0
- package/src/lib/data-transfer/package.d.ts +181 -0
- package/src/lib/data-transfer/package.js +426 -0
- package/src/lib/data-transfer/package.js.map +1 -0
- package/src/lib/data-transfer/picklist-map.d.ts +139 -0
- package/src/lib/data-transfer/picklist-map.js +271 -0
- package/src/lib/data-transfer/picklist-map.js.map +1 -0
- package/src/lib/data-transfer/plan.d.ts +176 -0
- package/src/lib/data-transfer/plan.js +451 -0
- package/src/lib/data-transfer/plan.js.map +1 -0
- package/src/lib/data-transfer/policy.d.ts +170 -0
- package/src/lib/data-transfer/policy.js +378 -0
- package/src/lib/data-transfer/policy.js.map +1 -0
- package/src/lib/data-transfer/resource.d.ts +211 -0
- package/src/lib/data-transfer/resource.js +241 -0
- package/src/lib/data-transfer/resource.js.map +1 -0
- package/src/lib/data-transfer/review.d.ts +70 -0
- package/src/lib/data-transfer/review.js +233 -0
- package/src/lib/data-transfer/review.js.map +1 -0
- package/src/lib/data-transfer/similarity.d.ts +40 -0
- package/src/lib/data-transfer/similarity.js +106 -0
- package/src/lib/data-transfer/similarity.js.map +1 -0
- package/src/lib/data-transfer/site-package.d.ts +365 -0
- package/src/lib/data-transfer/site-package.js +1077 -0
- package/src/lib/data-transfer/site-package.js.map +1 -0
- package/src/lib/data-transfer/source.d.ts +74 -0
- package/src/lib/data-transfer/source.js +293 -0
- package/src/lib/data-transfer/source.js.map +1 -0
- package/src/lib/data-transfer/transfer-api.d.ts +898 -0
- package/src/lib/data-transfer/transfer-api.js +107 -0
- package/src/lib/data-transfer/transfer-api.js.map +1 -0
- package/src/lib/foundation/definitions/org-billing.types.d.ts +31 -0
- package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
- package/src/lib/foundation/definitions/organization.types.d.ts +42 -1
- package/src/lib/foundation/definitions/organization.types.js.map +1 -1
- package/src/lib/foundation/definitions/platform.types.d.ts +6 -4
- package/src/lib/foundation/definitions/platform.types.js.map +1 -1
- package/src/lib/foundation/index.d.ts +1 -1
- package/src/lib/foundation/index.js.map +1 -1
- package/src/lib/plugin-manager/feature-plugins.d.ts +91 -2
- package/src/lib/plugin-manager/feature-plugins.js +48 -3
- package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.d.ts +50 -0
- package/src/lib/plugin-manager/first-party-plugins.generated.js +1129 -28
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/index.d.ts +0 -1
- package/src/lib/plugin-manager/index.js +0 -1
- package/src/lib/plugin-manager/index.js.map +1 -1
- package/src/lib/plugin-manager/interaction-recipes.d.ts +142 -0
- package/src/lib/plugin-manager/interaction-recipes.js +104 -0
- package/src/lib/plugin-manager/interaction-recipes.js.map +1 -0
- package/src/lib/plugin-manager/interaction-step-checks.d.ts +66 -0
- package/src/lib/plugin-manager/interaction-step-checks.js +86 -0
- package/src/lib/plugin-manager/interaction-step-checks.js.map +1 -0
- package/src/lib/plugin-manager/plugin-artifact-types.d.ts +235 -0
- package/src/lib/plugin-manager/plugin-artifact-types.js +99 -0
- package/src/lib/plugin-manager/plugin-artifact-types.js.map +1 -0
- package/src/lib/plugin-manager/plugin-contact-capture.d.ts +8 -0
- package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
- package/src/lib/plugin-manager/plugin-conversion-credit.d.ts +216 -0
- package/src/lib/plugin-manager/plugin-conversion-credit.js +91 -0
- package/src/lib/plugin-manager/plugin-conversion-credit.js.map +1 -0
- package/src/lib/plugin-manager/plugin-entity-pickers.d.ts +83 -0
- package/src/lib/plugin-manager/plugin-entity-pickers.js +87 -0
- package/src/lib/plugin-manager/plugin-entity-pickers.js.map +1 -0
- package/src/lib/plugin-manager/plugin-host-resources.d.ts +6 -0
- package/src/lib/plugin-manager/plugin-host-resources.js +6 -1
- package/src/lib/plugin-manager/plugin-host-resources.js.map +1 -1
- package/src/lib/plugin-manager/plugin-intake-gates.d.ts +75 -0
- package/src/lib/plugin-manager/plugin-intake-gates.js +49 -0
- package/src/lib/plugin-manager/plugin-intake-gates.js.map +1 -0
- package/src/lib/plugin-manager/plugin-jobs.d.ts +5 -5
- package/src/lib/plugin-manager/plugin-jobs.js +7 -7
- package/src/lib/plugin-manager/plugin-jobs.js.map +1 -1
- package/src/lib/plugin-manager/plugin-live-paths.d.ts +70 -0
- package/src/lib/plugin-manager/plugin-live-paths.js +66 -0
- package/src/lib/plugin-manager/plugin-live-paths.js.map +1 -0
- package/src/lib/plugin-manager/plugin-org-erasure.d.ts +3 -2
- package/src/lib/plugin-manager/plugin-org-erasure.js +30 -5
- package/src/lib/plugin-manager/plugin-org-erasure.js.map +1 -1
- package/src/lib/plugin-manager/plugin-person-erasure.d.ts +68 -9
- package/src/lib/plugin-manager/plugin-person-erasure.js +196 -51
- package/src/lib/plugin-manager/plugin-person-erasure.js.map +1 -1
- package/src/lib/plugin-manager/plugin-person-records.d.ts +275 -0
- package/src/lib/plugin-manager/plugin-person-records.js +107 -0
- package/src/lib/plugin-manager/plugin-person-records.js.map +1 -0
- package/src/lib/plugin-manager/plugin-record-counts.d.ts +76 -0
- package/src/lib/plugin-manager/plugin-record-counts.js +49 -0
- package/src/lib/plugin-manager/plugin-record-counts.js.map +1 -0
- package/src/lib/plugin-manager/plugin-record-email-state.d.ts +26 -0
- package/src/lib/plugin-manager/plugin-record-email-state.js +16 -0
- package/src/lib/plugin-manager/plugin-record-email-state.js.map +1 -1
- package/src/lib/plugin-manager/plugin-record-index.d.ts +10 -0
- package/src/lib/plugin-manager/plugin-record-index.js.map +1 -1
- package/src/lib/plugin-manager/plugin-record-lists.d.ts +86 -6
- package/src/lib/plugin-manager/plugin-record-lists.js +42 -5
- package/src/lib/plugin-manager/plugin-record-lists.js.map +1 -1
- package/src/lib/plugin-manager/plugin-record-origin.d.ts +79 -0
- package/src/lib/plugin-manager/plugin-record-origin.js +46 -0
- package/src/lib/plugin-manager/plugin-record-origin.js.map +1 -0
- package/src/lib/plugin-manager/plugin-record-pages.d.ts +37 -0
- package/src/lib/plugin-manager/plugin-record-pages.js +52 -0
- package/src/lib/plugin-manager/plugin-record-pages.js.map +1 -0
- package/src/lib/plugin-manager/plugin-record-timeline.d.ts +60 -0
- package/src/lib/plugin-manager/plugin-record-timeline.js +16 -0
- package/src/lib/plugin-manager/plugin-record-timeline.js.map +1 -1
- package/src/lib/plugin-manager/plugin-resource-drafts.d.ts +5 -5
- package/src/lib/plugin-manager/plugin-resource-drafts.js.map +1 -1
- package/src/lib/plugin-manager/plugin-revocations.d.ts +64 -0
- package/src/lib/plugin-manager/plugin-revocations.js +47 -0
- package/src/lib/plugin-manager/plugin-revocations.js.map +1 -0
- package/src/lib/plugin-manager/plugin-send-tallies.d.ts +69 -0
- package/src/lib/plugin-manager/plugin-send-tallies.js +45 -0
- package/src/lib/plugin-manager/plugin-send-tallies.js.map +1 -0
- package/src/lib/plugin-manager/plugin-site-bundle.d.ts +40 -0
- package/src/lib/plugin-manager/plugin-site-bundle.js +4 -0
- package/src/lib/plugin-manager/plugin-site-bundle.js.map +1 -1
- package/src/lib/plugin-manager/plugin-site-export.d.ts +57 -1
- package/src/lib/plugin-manager/plugin-site-export.js +23 -10
- package/src/lib/plugin-manager/plugin-site-export.js.map +1 -1
- package/src/lib/plugin-manager/plugin-sitemap-readers.d.ts +146 -0
- package/src/lib/plugin-manager/plugin-sitemap-readers.js +110 -0
- package/src/lib/plugin-manager/plugin-sitemap-readers.js.map +1 -0
- package/src/lib/plugin-manager/plugin-transfer-resources.d.ts +714 -0
- package/src/lib/plugin-manager/plugin-transfer-resources.js +443 -0
- package/src/lib/plugin-manager/plugin-transfer-resources.js.map +1 -0
- package/src/lib/plugin-manager/plugin-usage-axes.d.ts +54 -5
- package/src/lib/plugin-manager/plugin-usage-axes.js +11 -3
- package/src/lib/plugin-manager/plugin-usage-axes.js.map +1 -1
- package/src/lib/plugin-manager/plugin-user-erasure.js +9 -1
- package/src/lib/plugin-manager/plugin-user-erasure.js.map +1 -1
- package/src/lib/plugin-manager/plugin-visitor-doors.d.ts +104 -0
- package/src/lib/plugin-manager/plugin-visitor-doors.js +108 -0
- package/src/lib/plugin-manager/plugin-visitor-doors.js.map +1 -0
- package/src/lib/plugin-manager/realm-host-aglyn.generated.js +2 -0
- package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
- package/src/lib/plugin-manager/repeat-rows.d.ts +5 -6
- package/src/lib/plugin-manager/repeat-rows.js.map +1 -1
- package/src/lib/app-utils/actions.d.ts +0 -310
- package/src/lib/app-utils/actions.js +0 -506
- package/src/lib/app-utils/actions.js.map +0 -1
- package/src/lib/app-utils/automation-placeholders.d.ts +0 -72
- package/src/lib/app-utils/automation-placeholders.js +0 -207
- package/src/lib/app-utils/automation-placeholders.js.map +0 -1
- package/src/lib/app-utils/dataset-models.d.ts +0 -339
- package/src/lib/app-utils/dataset-models.js +0 -722
- package/src/lib/app-utils/dataset-models.js.map +0 -1
- package/src/lib/app-utils/datasets.d.ts +0 -171
- package/src/lib/app-utils/datasets.js +0 -227
- package/src/lib/app-utils/datasets.js.map +0 -1
- package/src/lib/app-utils/form-abuse-ceiling.d.ts +0 -146
- package/src/lib/app-utils/form-abuse-ceiling.js +0 -158
- package/src/lib/app-utils/form-abuse-ceiling.js.map +0 -1
- package/src/lib/plugin-manager/order-fulfilment.d.ts +0 -142
- package/src/lib/plugin-manager/order-fulfilment.js +0 -104
- package/src/lib/plugin-manager/order-fulfilment.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contacts.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 * Contacts CRM v1 (AGL-197): one contact per normalized email per host,\n * fed by the four existing capture silos (forms, members, orders,\n * bookings). Pure data module — the admin-SDK upsert lives in\n * `@aglyn/tenant-data-admin` (`upsertHostContact`) and the console reads\n * client-side under the host-admin rules.\n */\n\nimport type { AglynPostalAddress } from '../foundation'\nimport { consentGroupForHost } from './consent-groups'\nimport type { ContactCustomValue, ContactLifecycleStage } from './crm'\nimport type { EmailState } from './email-state'\nimport { heldScopeTokens } from './scope-tokens'\nimport {\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n readMarketingBasis,\n type MarketingBasis,\n} from './marketing-consent'\nimport { refusalsOf, type RetainedRefusals } from './retained-refusals'\n\nexport type ContactSource =\n | 'form'\n | 'member'\n | 'order'\n | 'booking'\n | 'newsletter'\n // AGL-2276: `POST /v1/contacts`. A first-class source rather than a blank\n // one, because \"where did this person come from\" is the question the\n // console's source filter exists to answer, and an integration importing a\n // CRM is a different answer from a visitor filling in a form. Adding it to\n // the union is what makes `SOURCE_LABELS` and the filter cover it — a raw\n // string written past the type would render as `api` and match no filter.\n | 'api'\n // CRM v2 (AGL-2595): the two doors that are not a capture at all. A person\n // typed into the console by a member of the team, and a person who arrived\n // in a file. Both are first-class for the reason `api` is — a merchant\n // asking \"who did we add ourselves\" and \"who came from the spreadsheet\" is\n // asking the source filter, and a source the union does not name is one it\n // cannot answer for.\n | 'manual'\n | 'import'\n // AGL-3185: the platform's own console — an account created there, and\n // the product-updates decision that account makes at sign-up, in its\n // preferences or at the one-time prompt. First-class for the reason `api`\n // is: the operator's CRM asks \"who signed up for the product\", and\n // `member` is a SITE's member, which an account holder of the platform\n // is not.\n | 'account'\n\n/**\n * How a capture source reads on screen.\n *\n * Typed `Record<ContactSource, string>` so a source added to the union cannot\n * ship without a label, and kept beside the union rather than in the console\n * that first needed it: the contacts filter, the campaign audience and the\n * dynamic-list rule editor all name the same six sources, and three copies of\n * this map is three places for `order` to stop reading as \"Customer\".\n */\nexport const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {\n form: 'Form',\n member: 'Member',\n order: 'Customer',\n booking: 'Booking',\n newsletter: 'Newsletter',\n api: 'API',\n manual: 'Added by hand',\n import: 'Import',\n account: 'Account',\n}\n\nexport interface ContactInteraction {\n type: ContactSource\n /** Source doc id (formSubmissions/siteMembers/orders/bookings). */\n refId?: string\n /** Epoch millis — Timestamps don't serialize into arrays cleanly. */\n atMs: number\n summary?: string\n /**\n * WHICH SITE this interaction happened on.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one person, and splitting them into two rows would\n * bill the org twice for the same address and lose the dedupe that makes a\n * multi-brand account worth having. But the HISTORY on that shared row is\n * not shared: a booking made on one client's site is that client's, and a\n * timeline that cannot be split by site shows an agency's client the other\n * clients' activity.\n *\n * Optional because a row written before this field existed carries none,\n * and an interaction whose site is unknown must read as unattributed rather\n * than be assigned to whoever is looking. Nothing may infer it from the\n * contact's own capture attribution: `capturedByHostIds` says which sites\n * met this person, not which of them produced any particular visit.\n */\n hostId?: string\n /**\n * THE ENTRY POINT: the form this capture came in through.\n *\n * `sources` answers \"what KIND of surface met this person\" and is what the\n * console's capture filter reads; it cannot answer \"which form\", because\n * every form on the site sets the same `form` flag. The id rather than the\n * name, for the reason the submission carries the id: a form's caption is\n * editable and a stored name splits the moment somebody renames it.\n *\n * Beside {@link refId} rather than derived from it. The submission the\n * interaction names does carry the form, but reading it back would be a\n * document read per row of a timeline the console renders straight out of\n * the contact.\n */\n formId?: string\n /**\n * THE ENTRY POINT: the page the person was on when this happened.\n *\n * The same `path` the submission stores. It belongs on the interaction and\n * not on the contact, because a person who came in through the pricing page\n * and returned through a blog post has two entry points and one row —\n * a single field at the top would keep whichever capture wrote last.\n */\n path?: string\n}\n\n/** `orgs/{orgId}/contacts/{contactId}` doc shape. */\nexport interface HostContact {\n /** Normalized (trimmed, lowercased) email — the dedupe key. */\n email: string\n name?: string\n sources: Partial<Record<ContactSource, true>>\n /** Newest-first, capped — the profile timeline. */\n interactions: ContactInteraction[]\n tags?: string[]\n notes?: string\n /**\n * Every site that has captured this person, in no order.\n *\n * An ARRAY and a top-level field, because this is the one attribution that\n * has to survive being a QUERY: \"everyone captured on A, B or C\" is an\n * audience, and `array-contains-any` is what answers it. The per-interaction\n * host says which visit belonged to whom; this says which sites have a\n * relationship at all, and only the second shape can be filtered on in\n * Firestore.\n *\n * Grows by `arrayUnion` on every capture, including the ones that merge\n * onto an existing row — which is exactly what the create-only `hostId`\n * beside it could never do.\n */\n capturedByHostIds?: string[]\n /**\n * Every form this person has come in through, in no order (AGL-2612).\n *\n * The entry point proper is `interactions[].formId` inside the capturing\n * holder's facet, and that stays the record: which form produced which\n * visit is one holder's business. But Firestore cannot select documents\n * by a field of an array ELEMENT, and a facet path is per group, so\n * \"everyone who filled in this form\" — the question the form's own page\n * asks of the Contacts list — has to be a top-level array an\n * `array-contains` can hit, exactly as `capturedByHostIds` is for sites\n * and `companyIds` is for companies. A form id is minted under one site,\n * so a query on it is one site's captures by construction.\n *\n * Grows by `arrayUnion` on every form capture, create or merge, bounded at\n * {@link CONTACT_FORM_IDS_CAP}: a person who has filled in more forms than\n * that keeps the first twenty and the timeline keeps the rest. The facet is\n * the truth and this is its index — a reader answering \"which form\" reads\n * the interaction; only a QUERY reads this.\n */\n formIds?: string[]\n /*\n * SEARCH KEYS (AGL-2596), and nothing more.\n *\n * The console's global search reads a window of contact documents and\n * matches over their top-level fields; it never resolves a holder's facet,\n * because it is one search over a dozen collections and a facet read is a\n * contacts-only idea. So the two profile values a person is looked up BY —\n * their phone number and the company they work for — are mirrored here by\n * every writer that sets them on a facet, as plain values a query can hit.\n *\n * The FACET is the record. These are a last-writer-wins echo of it: two\n * holders who keep different numbers for one person each overwrite the\n * echo and each keep their own facet value, and nothing renders these to a\n * reader — the list, the record page and the export all read through the\n * viewing group's facet. `ORG_CONTACT_FIELDS` below is an allow-list, so\n * neither reaches the org view either.\n */\n /** E.164, mirrored from the last facet write that set one. */\n phone?: string\n /** The company name as typed, mirrored the same way. */\n companyName?: string\n /**\n * The OTHER addresses this person answers to (AGL-2625).\n *\n * A contact is keyed on one email, so one human with a work address and a\n * personal one is two documents until somebody merges them. The merge keeps\n * the survivor's `email` as the identity and records the merged record's\n * address here, so a later capture on it — a form filled in from the\n * personal account — resolves to this row rather than minting the second\n * document again. `emailIndex` (see {@link CONTACT_EMAIL_INDEX_COLLECTION})\n * is the lookup; this array is the record of why an entry there points\n * where it does, and what the record page shows as \"also\".\n *\n * Shared identity like `email`, not a facet field: which addresses are one\n * person is a fact about the person, and a holder that did not perform the\n * merge still needs its capture on the alternate address to land on the\n * shared row. Bounded at {@link CONTACT_ALTERNATE_EMAILS_CAP}.\n */\n alternateEmails?: string[]\n /**\n * When the earliest OPEN task filed against this person is due, epoch\n * ms, or `null` when none is (AGL-2661) — see `CrmDeal.nextTaskAtMs` in\n * `crm.ts` for the rule. On the SHARED row rather than a facet, because a\n * task lives at the organization level and names the contact, not a\n * holder's view of them.\n */\n nextTaskAtMs?: number | null\n /**\n * The last verdict on the address (AGL-3245) — bounced, blocked,\n * unsubscribed, do-not-contact — written by the platform's senders only,\n * on the SHARED row because the address is shared. Absent means nothing\n * is known. See `email-state.ts`.\n */\n emailState?: EmailState\n}\n\n/** Timeline cap: keeps the doc small; older interactions age out. */\nexport const CONTACT_INTERACTIONS_CAP = 50\n\n/** The field holding {@link HostContact.alternateEmails}. */\nexport const CONTACT_ALTERNATE_EMAILS_FIELD = 'alternateEmails'\n\n/**\n * The most alternate addresses one contact carries. Ten is past any real\n * person's mailbox count, and it bounds the index writes one merge fans out.\n */\nexport const CONTACT_ALTERNATE_EMAILS_CAP = 10\n\n/**\n * `orgs/{orgId}/emailIndex/{personKey}` → `{ email, contactId }` (AGL-2625).\n *\n * The address-to-contact lookup the capture door consults BEFORE the\n * per-document `email ==` query, so an address recorded as an alternate on a\n * merged row resolves to the survivor. Keyed by `personKey` — the sha256 of\n * the normalized address — so a document id never carries the address\n * itself, the same derivation a lead and a list membership use.\n *\n * WRITTEN LAZILY, never backfilled: the query on `email` stays as the\n * fallback, and a contact that has no entry gets one on the next write that\n * finds it. A row the index has never seen therefore costs one extra read\n * once, and nothing needs to run over the existing collection.\n *\n * Server-written only; the rules close it to every client.\n */\nexport const CONTACT_EMAIL_INDEX_COLLECTION = 'emailIndex'\n\n/**\n * Every address a contact answers to — the primary first, then the\n * alternates — normalized and deduplicated, so an index writer and a lead\n * lookup walk one list.\n */\nexport function contactEmails(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (value: unknown) => {\n const email = normalizeContactEmail(value)\n if (email && !seen.has(email)) {\n seen.add(email)\n out.push(email)\n }\n }\n push((contact ?? {})['email'])\n const alternates = (contact ?? {})[CONTACT_ALTERNATE_EMAILS_FIELD]\n if (Array.isArray(alternates)) alternates.forEach(push)\n return out\n}\n\n/** The top-level field naming every form a contact came in through — see `HostContact.formIds`. */\nexport const CONTACT_FORM_IDS_FIELD = 'formIds'\n\n/**\n * How many forms the {@link CONTACT_FORM_IDS_FIELD} mirror holds.\n *\n * The same figure as the tag cap: enough that no real person reaches it,\n * small enough that the array never becomes the document. Past it the\n * capture stops adding rather than dropping the oldest, because the mirror\n * is an index of the facet's timeline and an index that silently forgets an\n * entry the timeline still holds would answer a form's contact list wrongly\n * in the one direction nobody would notice.\n */\nexport const CONTACT_FORM_IDS_CAP = 20\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Normalized dedupe key, or null when the input isn't a usable email. */\nexport function normalizeContactEmail(input: unknown): string | null {\n const email = String(input ?? '')\n .trim()\n .toLowerCase()\n return EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null\n}\n\n/**\n * First usable email in a free-form form-submission fields map — forms\n * don't guarantee a canonical email field, so prefer keys that look like\n * email fields before falling back to any email-shaped value.\n */\nexport function extractEmailFromFields(\n fields: Record<string, unknown> | null | undefined,\n): string | null {\n const entries = Object.entries(fields ?? {})\n const preferred = entries.find(([key]) => /email/i.test(key))\n const fromPreferred = normalizeContactEmail(preferred?.[1])\n if (fromPreferred) return fromPreferred\n for (const [, value] of entries) {\n const email = normalizeContactEmail(value)\n if (email) return email\n }\n return null\n}\n\n/**\n * Merges a new interaction into a contact: source flag set, interaction\n * prepended, timeline capped. Pure — the caller persists the result.\n */\nexport function mergeContactInteraction(\n existing: Pick<HostContact, 'sources' | 'interactions'> & {\n name?: string\n },\n update: { source: ContactSource; interaction: ContactInteraction; name?: string },\n): Pick<HostContact, 'sources' | 'interactions'> & { name?: string } {\n return {\n // Existing names win — a later anonymous form shouldn't blank a name.\n name: existing.name || update.name,\n sources: { ...existing.sources, [update.source]: true as const },\n interactions: [update.interaction, ...(existing.interactions ?? [])].slice(\n 0,\n CONTACT_INTERACTIONS_CAP,\n ),\n }\n}\n\n/**\n * THE PER-HOLDER FACET on a shared contact document.\n *\n * ## What is shared and what is not\n *\n * One human who touched two sites is ONE document. That is not a compromise:\n * it is the dedupe the shared address book exists for, it is what keeps a\n * bounce and a suppression describing one person, and it is what makes a\n * multi-brand account bill once for one human instead of once per site. A\n * document per host would push an agency toward twelve separate accounts and\n * throw the whole advantage away.\n *\n * But almost nothing ON that document is legitimately shared.\n *\n * - **SHARED IDENTITY** — `email`, and the canonical `name`. One human, one\n * identity. This is the only part two unrelated businesses may both see,\n * and it is the minimum that makes them one row.\n * - **PER-HOLDER FACET** — everything in this interface. A note, a tag, a\n * call log and a lifetime value are the HOLDER's own business records.\n * Host A's note about a customer is Host A's; a competitor sharing the\n * platform must not read it, and while these lived at the top of the\n * document every site in the org could.\n * - **CONSENT AND VISIBILITY** — per declared group, decided by\n * `marketing-consent.ts` and by `visibleTo`.\n *\n * ## Keyed by GROUP, not by host\n *\n * A business that declared three sites to be one sender is one CRM: a note\n * written on the shop belongs beside the booking made on the booking page,\n * because one team keeps both. Across groups, never — and an undeclared site\n * is a group of one, so the agency case is isolated with nothing configured.\n *\n * ## Commercial figures are per-facet, and that is not a billing change\n *\n * `ltvCents` and `ordersCount` answer \"what is this person worth to ME\". Two\n * unrelated merchants who both sell to one person have two different answers\n * and neither is entitled to the other's. Billing counts DOCUMENTS, and there\n * is still one document, so a person held by two hosts stays one billable\n * contact.\n */\nexport interface ContactFacet {\n /**\n * This holder's display name for the person, overriding the canonical one.\n *\n * The canonical `name` is shared and mutable, so without this a rename on\n * one site changes what an unrelated business sees in its own CRM — two\n * companies that do not know each other exist editing each other's records.\n * The override is written by whoever edits the name from their own console;\n * the canonical field stays as the identity of last resort, for a holder\n * that has never set one.\n */\n name?: string\n /** Which capture surfaces THIS holder saw the person through. */\n sources: Partial<Record<ContactSource, true>>\n /** THIS holder's timeline, newest-first and capped. */\n interactions: ContactInteraction[]\n /** THIS holder's tags. */\n tags?: string[]\n /** THIS holder's notes. */\n notes?: string\n /**\n * The campaigns THIS holder has filed the person under.\n *\n * A label on the CRM record, not an audience: who a campaign's mail reaches\n * is decided by the campaign's lists and by each send's own picker, and\n * nothing in the send path reads this. It answers \"who did we put in the\n * spring push\", which is a question about the holder's own working set.\n *\n * Per-holder for the reason the notes are: two unrelated businesses sharing\n * one row must not read each other's segmentation of a person they both\n * know. See `container-membership.ts` for the field and the path.\n */\n campaignIds?: string[]\n /** Gross of fees and refunds — see `upsertHostContact`. */\n ltvCents?: number\n ordersCount?: number\n lastPurchaseAtMs?: number\n firstPurchaseAtMs?: number\n refundedCents?: number\n refundedOrdersCount?: number\n lastRefundAtMs?: number\n /*\n * CRM v2 (AGL-2595): the profile a sales team keeps on a person.\n *\n * Per-holder like everything above them, and for the same reason: a phone\n * number, a job title, an owner and a lifecycle stage are one business's\n * knowledge of a person, and two unrelated businesses sharing the row must\n * not read each other's. `companyId` points at a company document in the\n * same scope, never at the org's whole company list. `custom` is keyed by\n * `ContactFieldDefinition.key`, so a holder's field definitions and a\n * holder's values live under the same group and cannot be joined across\n * one.\n *\n * ⛔ None of these reach the org view. `ORG_CONTACT_FIELDS` is an\n * allow-list, and the org-view spec seeds every one of these with a\n * sentinel and proves it never surfaces.\n */\n /** E.164 — `normalizePhone` before writing. */\n phone?: string\n jobTitle?: string\n /**\n * Where this holder met the person — Salesforce's Lead Source, carried\n * from the lead on conversion and picked from the org's lead source\n * values after it (AGL-3298). The value's label, as the lead stores it.\n */\n leadSource?: string\n /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */\n companyId?: string\n /**\n * The company's name as this holder knows it.\n *\n * Free text, so a person can be filed under a company before one exists\n * as a record; the company picker that later sets `companyId` writes the\n * picked company's name here too, so the row reads the same whether the\n * link was made or the name typed. The top-level `companyName` on the\n * document is the search echo of this value — see `HostContact`.\n */\n companyName?: string\n address?: AglynPostalAddress | null\n /** The team member responsible for the relationship. */\n ownerUid?: string\n lifecycleStage?: ContactLifecycleStage\n /** Custom field values, keyed by `ContactFieldDefinition.key`. */\n custom?: Record<string, ContactCustomValue>\n /**\n * When this person last OPENED or CLICKED a campaign sent by one of this\n * holder's sites, epoch ms (AGL-2616).\n *\n * Stamped by the delivery webhook, forward-only, on the first open and the\n * first click of each message — the same bound the per-person rollup on\n * `emailDeliveries/{key}` keeps, so a reader opening one newsletter six\n * times is one write. Per-holder because it answers \"is this person still\n * reading OUR mail\": the address-level rollup counts every sender's mail\n * and a sibling business's, and a re-engagement audience built on that\n * would mail people who are reading somebody else.\n *\n * Absent until the first engagement after the stamp shipped; a message\n * opened before then advanced the address-level rollup and nothing here.\n */\n lastEmailEngagementAtMs?: number\n /**\n * The org-library files THIS holder has attached to the person\n * (AGL-2662), by media document id.\n *\n * Per-holder for the reason every other field here is: an agency running\n * two client brands has one contact document between them, and a signed\n * contract one client filed is not the other client's to see. Ids rather\n * than URLs so a file moved between folders keeps its attachment, and so\n * a private asset is still served through the signed CDN door.\n */\n mediaIds?: string[]\n}\n\n/** The map field holding the facets: `{ [groupId]: ContactFacet }`. */\nexport const CONTACT_FACETS_FIELD = 'facets'\n\n/**\n * The facet one group holds, or an empty one.\n *\n * `map[groupId]` — a lookup, not a search, for the reason the consent map is\n * shaped the same way: there is no expression of this form that returns\n * another holder's notes.\n *\n * An absent facet reads EMPTY rather than falling back to the top-level\n * fields. A fallback would hand every holder in the org the fields the\n * pre-facet document carried at its top, which is the disclosure this shape\n * exists to end; the migration moves them into the capturing group's facet\n * instead.\n */\nexport function readContactFacet(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): ContactFacet {\n const facets = (contact ?? {})[CONTACT_FACETS_FIELD]\n const facet =\n facets && typeof facets === 'object' && !Array.isArray(facets)\n ? (facets as Record<string, unknown>)[groupId]\n : undefined\n if (!facet || typeof facet !== 'object' || Array.isArray(facet)) {\n return { sources: {}, interactions: [] }\n }\n const value = facet as Record<string, unknown>\n return {\n ...(value as unknown as ContactFacet),\n sources: (value['sources'] ?? {}) as ContactFacet['sources'],\n interactions: Array.isArray(value['interactions'])\n ? (value['interactions'] as ContactInteraction[])\n : [],\n }\n}\n\n/** The dotted Firestore path to one field of one holder's facet. */\nexport function contactFacetPath(groupId: string, field: string): string {\n if (!groupId) throw new Error('a contact facet must name a holder')\n return `${CONTACT_FACETS_FIELD}.${groupId}.${field}`\n}\n\n/**\n * The name a given holder should SEE for this person.\n *\n * Their own override first, the canonical identity second. Nothing falls\n * through to another holder's override: that would be one business's edit\n * showing up in another's CRM, which is the thing the override exists to\n * prevent.\n */\nexport function contactDisplayName(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): string {\n const facet = readContactFacet(contact, groupId)\n if (facet.name) return facet.name\n const canonical = (contact ?? {})['name']\n return typeof canonical === 'string' ? canonical : ''\n}\n\n/**\n * Every group that holds this contact — the reference count behind a detach.\n *\n * Read from `visibleTo` rather than from the facet map, because `visibleTo`\n * is what both enforcement layers actually evaluate: a holder that can still\n * READ the row is still holding it whether or not they ever wrote a note. A\n * count taken from the facets would drop a holder who has one and no facet\n * and leave them able to see a document nothing believes they hold.\n *\n * Less the tokens a share ADDED (AGL-3336): a site the record was shared\n * with sees it and holds nothing, so it must not keep the record alive when\n * its last holder lets go — `heldScopeTokens` is `visibleTo` without them.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n return heldScopeTokens(contact)\n}\n\n/** What a holder letting go of a contact should do to the document. */\nexport type ContactDetach =\n | {\n /** Nobody else holds it. Delete the document. */\n action: 'delete'\n /**\n * Every refusal the document holds, every site's and the unscoped one,\n * which the delete keeps in `retainedRefusals` in the same transaction\n * — see `retained-refusals.ts`. `null` when it holds none.\n */\n retained: RetainedRefusals | null\n }\n | {\n /** Other holders remain. Drop this one's half. */\n action: 'detach'\n /**\n * Field-level removals, as a patch. Dotted paths so the OTHER holders'\n * facets and consent entries are untouched — a nested write would\n * replace the whole map and take every other holder's records with it.\n *\n * A consent entry that is a REFUSAL is not among them: it stays on the\n * document for the holders that remain, because a person's \"no\" is not\n * the leaving holder's to take with it.\n */\n remove: string[]\n /** Scope tokens to pull out of `visibleTo`. */\n removeTokens: string[]\n /** Host ids to pull out of the capture attribution. */\n removeHostIds: string[]\n }\n\n/**\n * DELETE IS A DETACH.\n *\n * One holder removing a contact from their own CRM must not destroy another\n * holder's relationship with that person: they have their own notes, their\n * own order history and their own consent, none of which the deleting holder\n * ever had a claim on. So a delete drops the deleting group's facet, its\n * consent grants, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * A REFUSAL IS NOT LET GO (AGL-3338). The list gate reads a stored refusal\n * as the one fact an operator's attestation cannot overrule, so a detach\n * leaves the leaving group's refusal entries on the document, and a delete\n * answers every refusal the document holds for the caller to retain beside\n * the delete. Read off the document's own data: a table row's projection\n * carries neither the consent map nor the unscoped field.\n *\n * ⛔ This is NOT the erasure path. A privacy erasure removes the person\n * everywhere regardless of how many holders remain, and routing it through\n * reference counting would turn a lawful erasure into a partial one — the same\n * absent-versus-invisible defect this area keeps hitting, in the one place\n * where getting it wrong is a legal failure rather than a bug. Erasure calls\n * the document delete directly and must never consult this function.\n *\n * @param group the holder letting go, with every site it covers.\n */\nexport function planContactDetach(\n contact: Record<string, unknown> | null | undefined,\n group: { groupId: string; hostIds: readonly string[] },\n): ContactDetach {\n const held = contactHolderTokens(contact)\n const leaving = new Set(group.hostIds.map((id) => `host:${id}`))\n /*\n * A remaining holder is a token naming somebody else. `'org'` counts as one\n * and blocks the delete on purpose: an org-wide row is held by every site\n * in the account, so one site letting go leaves it held. Narrowing it would\n * be a scope decision, and a delete button is not where that belongs.\n */\n const remaining = held.filter((token) => !leaving.has(token))\n if (!remaining.length) return { action: 'delete', retained: refusalsOf(contact) }\n const refused = refusalsOf(contact)?.byHost ?? {}\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds\n .filter((id) => !(id in refused))\n .map((id) => `${MARKETING_CONSENT_BY_HOST_FIELD}.${id}`),\n ],\n removeTokens: [...leaving],\n removeHostIds: [...group.hostIds],\n }\n}\n\n/**\n * The interactions one group of sites may see on a shared contact.\n *\n * An interaction with NO host is shown to everyone: it predates the\n * attribution, so hiding it would empty every existing timeline, and it is\n * already visible to anyone who can read the row. An interaction that names a\n * site is shown only to that site's own group — the agency case, where one\n * client must not read another client's bookings off a person they both know.\n */\nexport function interactionsForGroup(\n interactions: readonly ContactInteraction[] | undefined,\n hostIds: readonly string[],\n): ContactInteraction[] {\n const reach = new Set(hostIds)\n return (interactions ?? []).filter(\n (interaction) => !interaction.hostId || reach.has(interaction.hostId),\n )\n}\n\n/** `orgs/{orgId}/contactSegments/{id}` — a saved audience filter. */\nexport interface ContactSegment {\n name: string\n /** Match contacts sharing at least one tag (empty = any). */\n tags?: string[]\n /** Match contacts with at least one of these sources (empty = any). */\n sources?: ContactSource[]\n}\n\n/** Segment matching (AGL-199): AND across filter kinds, OR within one. */\nexport function contactMatchesSegment(\n contact: Pick<HostContact, 'tags' | 'sources'>,\n segment: Pick<ContactSegment, 'tags' | 'sources'>,\n): boolean {\n if (segment.tags?.length) {\n const contactTags = new Set(\n (contact.tags ?? []).map((tag) => tag.toLowerCase()),\n )\n if (!segment.tags.some((tag) => contactTags.has(tag.toLowerCase()))) {\n return false\n }\n }\n if (segment.sources?.length) {\n if (!segment.sources.some((source) => contact.sources?.[source])) {\n return false\n }\n }\n return true\n}\n\n/*==========================================\n * THE ORG-LEVEL VIEW: the complement of the facet reader above.\n *\n * {@link readContactFacet} answers \"what does THIS holder know about this\n * person\". Everything below answers the question no host page can:\n *\n * who does this ORGANIZATION know, and which of its sites know them.\n *\n * That question is the entire justification for one shared document. Dedupe,\n * suppression and honest billing all rest on one human being one row, and\n * with no surface that shows the deduped person the model's benefit is\n * invisible and the billing unit — unique people per org — looks arbitrary.\n *\n * ## The org view crosses the host boundary, so it carries LESS, not more\n *\n * It is the one place in the product designed to read across holders, which\n * makes it the one place where a careless field re-creates the disclosure the\n * facets exist to end. So the projection is an ALLOW-LIST\n * ({@link ORG_CONTACT_FIELDS}) rather than an omission: identity, capture\n * attribution and consent state. Notes, tags, timelines, call logs and\n * commercial figures are the holder's own business records and are not read\n * here at all — not summarized, not counted, not indicated by their absence.\n *\n * An allow-list rather than a `delete facets` is the load-bearing choice. A\n * subtraction is correct only for as long as somebody remembers to extend it,\n * and a field added to {@link ContactFacet} tomorrow would ride out through a\n * subtraction and be caught by an allow-list.\n *\n * ## The NAME is the canonical one, never a holder's override\n *\n * {@link contactDisplayName} prefers the viewing group's own override, which\n * is right on a host page and wrong here: an override is a name ONE business\n * chose, and rendering it at org level shows an agency the label its client\n * picked. The shared identity is what every holder already sees, so it is the\n * only name that belongs to the org.\n *=========================================*/\n\n/**\n * Every field of a contact document the org view may read.\n *\n * Stated as a value so it can be asserted against — see the org-view spec,\n * which seeds each facet field with a sentinel and proves none of them\n * reaches a row.\n */\nexport const ORG_CONTACT_FIELDS = [\n 'email',\n 'name',\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n] as const\n\n/**\n * What one site's relationship with one person amounts to, at org level.\n *\n * Consent is per (contact, host-or-group) and there is no expression that\n * returns another controller's grant, so a row cannot carry one consent\n * verdict. It carries one PER CAPTURING SITE, each naming the controller it\n * was read for — a bare \"consented\" with nobody attached would be exactly the\n * confusion the per-brand model was built to prevent.\n */\nexport interface OrgContactHostConsent {\n /** The site this verdict answers about, and no other. */\n hostId: string\n /** The controller the basis runs to — the declared group, or the site. */\n groupId: string\n /**\n * The group's disclosed name, or `null` for a site that pools with nobody.\n *\n * `null` is not \"unknown\": it is the group of one, where the site's own\n * name is the disclosure and inventing a second would put a label in front\n * of a reader that nothing else uses.\n */\n groupName: string | null\n /** Whether the controller is a DECLARED group rather than the site alone. */\n declared: boolean\n /** `granted` | `declined` | `unrecorded` — never collapsed to a boolean. */\n basis: MarketingBasis\n}\n\n/** One person, as the organization may see them across all of its sites. */\nexport interface OrgContactRow {\n $id: string\n /** The dedupe key, and the reason two captures are one row. */\n email: string\n /** The SHARED identity. Never a holder's own override. */\n name: string\n /** Every site that has captured this person, sorted for a stable render. */\n capturedByHostIds: string[]\n /** One verdict per capturing site, in the same order. */\n consent: OrgContactHostConsent[]\n}\n\n/**\n * Every site that has captured this person.\n *\n * Sorted, because the array is maintained by `arrayUnion` and therefore\n * carries capture order, which is not an order anything should render: two\n * readers of the same row would see the sites in different places on the\n * screen depending on which site met the person first.\n */\nexport function contactCaptureHostIds(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const raw = (contact ?? {})[CAPTURED_BY_HOST_FIELD]\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw\n .map((id) => String(id ?? '').trim())\n .filter((id): id is string => id !== ''),\n ),\n ].sort()\n}\n\n/**\n * One contact document, projected to what an ORG may see.\n *\n * @param org - the org document — the only input that can resolve a declared\n * consent group, and required for that reason. Without it every site reads\n * as a group of one, which understates the disclosure a person was given\n * and is the safe direction to be wrong in.\n */\nexport function orgContactRow(\n contact: Record<string, unknown> | null | undefined,\n contactId: string,\n org: Record<string, unknown> | null | undefined,\n): OrgContactRow {\n const record = contact ?? {}\n const capturedByHostIds = contactCaptureHostIds(record)\n return {\n $id: contactId,\n email: typeof record['email'] === 'string' ? record['email'] : '',\n name: typeof record['name'] === 'string' ? record['name'] : '',\n capturedByHostIds,\n consent: capturedByHostIds.map((hostId) => {\n /*\n * READ FOR THE SITE, one call per site. `readMarketingBasis` requires\n * the group it is being read for and has no default, so this cannot\n * accidentally report a grant that belongs to somebody else — the\n * argument is the guarantee, and passing the whole row through one\n * call would have had to invent a controller to ask about.\n */\n const group = consentGroupForHost(org, hostId)\n const { basis } = readMarketingBasis(record, group)\n return {\n hostId,\n groupId: group.groupId,\n groupName: group.name,\n declared: group.declared,\n basis,\n }\n }),\n }\n}\n\n/**\n * How a basis reads on screen.\n *\n * Three labels because there are three states. \"Opted in\" and \"No record\" are\n * not opposites and must never collapse into one negative: absence is the\n * commonest case by far — a record captured before the checkbox existed — and\n * showing it as a refusal would tell a merchant they may not mail somebody\n * who never said so.\n */\nexport const MARKETING_BASIS_LABELS: Record<MarketingBasis, string> = {\n granted: 'Opted in',\n declined: 'Opted out',\n unrecorded: 'No record',\n}\n\n/**\n * One consent verdict, WITH THE CONTROLLER IT RUNS TO, as one string.\n *\n * ⛔ There is no function here that returns a basis on its own, and that is\n * the point. A basis is per (person, controller): the same person can be\n * opted in to one brand in an org and opted out of another, so \"consented\"\n * with nobody attached is not a shortened truth, it is a different and false\n * claim — precisely the confusion the per-brand model was built to prevent.\n * Joining the two into a single value is what stops a caller rendering half\n * of it.\n *\n * The controller is the DECLARED GROUP when there is one, because that is who\n * the person was told they would hear from, and the site otherwise. A group\n * of one is named by the site, which is what the capture surface already\n * showed them.\n *\n * @param siteName - how this site reads — the caller resolves it, since the\n * contact document holds ids and not names. An empty one falls back to the\n * id: a site whose name cannot be resolved must still be NAMED, because\n * dropping it would understate which brands hold a relationship.\n */\nexport function orgContactConsentLabel(\n entry: OrgContactHostConsent,\n siteName?: string,\n): string {\n const controller = entry.declared\n ? (entry.groupName ?? entry.groupId)\n : siteName || entry.hostId\n return `${controller} · ${MARKETING_BASIS_LABELS[entry.basis]}`\n}\n"],"names":["consentGroupForHost","heldScopeTokens","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","refusalsOf","CONTACT_SOURCE_LABELS","form","member","order","booking","newsletter","api","manual","import","account","CONTACT_INTERACTIONS_CAP","CONTACT_ALTERNATE_EMAILS_FIELD","CONTACT_ALTERNATE_EMAILS_CAP","CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","contact","out","seen","Set","push","value","email","normalizeContactEmail","has","add","alternates","Array","isArray","forEach","CONTACT_FORM_IDS_FIELD","CONTACT_FORM_IDS_CAP","EMAIL_PATTERN","input","String","trim","toLowerCase","test","length","extractEmailFromFields","fields","entries","Object","preferred","find","key","fromPreferred","mergeContactInteraction","existing","update","name","sources","source","interactions","interaction","slice","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","contactFacetPath","field","Error","contactDisplayName","canonical","contactHolderTokens","planContactDetach","group","held","leaving","hostIds","map","id","remaining","filter","token","action","retained","refused","byHost","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","$id","consent","basis","groupName","declared","MARKETING_BASIS_LABELS","granted","declined","unrecorded","orgContactConsentLabel","entry","siteName","controller"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC;AAGD,SAASA,mBAAmB,QAAQ,sBAAkB;AAGtD,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AAC5B,SAASC,UAAU,QAA+B,yBAAqB;AA+BvE;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAuD;IAClEC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,SAAS;IACTC,YAAY;IACZC,KAAK;IACLC,QAAQ;IACRC,QAAQ;IACRC,SAAS;AACX,EAAC;AA0JD,mEAAmE,GACnE,OAAO,MAAMC,2BAA2B,GAAE;AAE1C,2DAA2D,GAC3D,OAAO,MAAMC,iCAAiC,kBAAiB;AAE/D;;;CAGC,GACD,OAAO,MAAMC,+BAA+B,GAAE;AAE9C;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,iCAAiC,aAAY;AAE1D;;;;CAIC,GACD,OAAO,SAASC,cACdC,OAAmD;IAEnD,MAAMC,MAAgB,EAAE;IACxB,MAAMC,OAAO,IAAIC;IACjB,MAAMC,OAAO,CAACC;QACZ,MAAMC,QAAQC,sBAAsBF;QACpC,IAAIC,SAAS,CAACJ,KAAKM,GAAG,CAACF,QAAQ;YAC7BJ,KAAKO,GAAG,CAACH;YACTL,IAAIG,IAAI,CAACE;QACX;IACF;IACAF,KAAK,CAACJ,kBAAAA,UAAW,CAAC,EAAE,CAAC,QAAQ;IAC7B,MAAMU,aAAa,CAACV,kBAAAA,UAAW,CAAC,EAAE,CAACJ,+BAA+B;IAClE,IAAIe,MAAMC,OAAO,CAACF,aAAaA,WAAWG,OAAO,CAACT;IAClD,OAAOH;AACT;AAEA,iGAAiG,GACjG,OAAO,MAAMa,yBAAyB,UAAS;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0G,KAAKb;YACvC,MAAM,EAAEkB,KAAK,EAAE,GAAG1G,mBAAmBsG,QAAQhC;YAC7C,OAAO;gBACLkB;gBACA7B,SAASW,MAAMX,OAAO;gBACtBgD,WAAWrC,MAAMnB,IAAI;gBACrByD,UAAUtC,MAAMsC,QAAQ;gBACxBF;YACF;QACF;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,MAAMG,yBAAyD;IACpEC,SAAS;IACTC,UAAU;IACVC,YAAY;AACd,EAAC;AAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASC,uBACdC,KAA4B,EAC5BC,QAAiB;QAGZD;IADL,MAAME,aAAaF,MAAMN,QAAQ,IAC5BM,mBAAAA,MAAMP,SAAS,YAAfO,mBAAmBA,MAAMvD,OAAO,GACjCwD,YAAYD,MAAM1B,MAAM;IAC5B,OAAO,GAAG4B,WAAW,GAAG,EAAEP,sBAAsB,CAACK,MAAMR,KAAK,CAAC,EAAE;AACjE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contacts.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 * Contacts CRM v1 (AGL-197): one contact per normalized email per host,\n * fed by the four existing capture silos (forms, members, orders,\n * bookings). Pure data module — the admin-SDK upsert lives in\n * `@aglyn/tenant-data-admin` (`upsertHostContact`) and the console reads\n * client-side under the host-admin rules.\n */\n\nimport type { AglynPostalAddress } from '../foundation'\nimport { consentGroupForHost } from './consent-groups'\nimport type { ContactCustomValue, ContactLifecycleStage } from './crm'\nimport type { EmailState } from './email-state'\nimport { heldScopeTokens } from './scope-tokens'\nimport {\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n readMarketingBasis,\n type MarketingBasis,\n} from './marketing-consent'\nimport { refusalsOf, type RetainedRefusals } from './retained-refusals'\n\nexport type ContactSource =\n | 'form'\n | 'member'\n | 'order'\n | 'booking'\n | 'newsletter'\n // AGL-2276: `POST /v1/contacts`. A first-class source rather than a blank\n // one, because \"where did this person come from\" is the question the\n // console's source filter exists to answer, and an integration importing a\n // CRM is a different answer from a visitor filling in a form. Adding it to\n // the union is what makes `SOURCE_LABELS` and the filter cover it — a raw\n // string written past the type would render as `api` and match no filter.\n | 'api'\n // CRM v2 (AGL-2595): the two doors that are not a capture at all. A person\n // typed into the console by a member of the team, and a person who arrived\n // in a file. Both are first-class for the reason `api` is — a merchant\n // asking \"who did we add ourselves\" and \"who came from the spreadsheet\" is\n // asking the source filter, and a source the union does not name is one it\n // cannot answer for.\n | 'manual'\n | 'import'\n // AGL-3185: the platform's own console — an account created there, and\n // the product-updates decision that account makes at sign-up, in its\n // preferences or at the one-time prompt. First-class for the reason `api`\n // is: the operator's CRM asks \"who signed up for the product\", and\n // `member` is a SITE's member, which an account holder of the platform\n // is not.\n | 'account'\n\n/**\n * How a capture source reads on screen.\n *\n * Typed `Record<ContactSource, string>` so a source added to the union cannot\n * ship without a label, and kept beside the union rather than in the console\n * that first needed it: the contacts filter, the campaign audience and the\n * dynamic-list rule editor all name the same six sources, and three copies of\n * this map is three places for `order` to stop reading as \"Customer\".\n */\nexport const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {\n form: 'Form',\n member: 'Member',\n order: 'Customer',\n booking: 'Booking',\n newsletter: 'Newsletter',\n api: 'API',\n manual: 'Added by hand',\n import: 'Import',\n account: 'Account',\n}\n\nexport interface ContactInteraction {\n type: ContactSource\n /** Source doc id (formSubmissions/siteMembers/orders/bookings). */\n refId?: string\n /** Epoch millis — Timestamps don't serialize into arrays cleanly. */\n atMs: number\n summary?: string\n /**\n * WHICH SITE this interaction happened on.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one person, and splitting them into two rows would\n * bill the org twice for the same address and lose the dedupe that makes a\n * multi-brand account worth having. But the HISTORY on that shared row is\n * not shared: a booking made on one client's site is that client's, and a\n * timeline that cannot be split by site shows an agency's client the other\n * clients' activity.\n *\n * Optional because a row written before this field existed carries none,\n * and an interaction whose site is unknown must read as unattributed rather\n * than be assigned to whoever is looking. Nothing may infer it from the\n * contact's own capture attribution: `capturedByHostIds` says which sites\n * met this person, not which of them produced any particular visit.\n */\n hostId?: string\n /**\n * THE ENTRY POINT: the form this capture came in through.\n *\n * `sources` answers \"what KIND of surface met this person\" and is what the\n * console's capture filter reads; it cannot answer \"which form\", because\n * every form on the site sets the same `form` flag. The id rather than the\n * name, for the reason the submission carries the id: a form's caption is\n * editable and a stored name splits the moment somebody renames it.\n *\n * Beside {@link refId} rather than derived from it. The submission the\n * interaction names does carry the form, but reading it back would be a\n * document read per row of a timeline the console renders straight out of\n * the contact.\n */\n formId?: string\n /**\n * THE ENTRY POINT: the page the person was on when this happened.\n *\n * The same `path` the submission stores. It belongs on the interaction and\n * not on the contact, because a person who came in through the pricing page\n * and returned through a blog post has two entry points and one row —\n * a single field at the top would keep whichever capture wrote last.\n */\n path?: string\n}\n\n/** `orgs/{orgId}/contacts/{contactId}` doc shape. */\nexport interface HostContact {\n /** Normalized (trimmed, lowercased) email — the dedupe key. */\n email: string\n name?: string\n sources: Partial<Record<ContactSource, true>>\n /** Newest-first, capped — the profile timeline. */\n interactions: ContactInteraction[]\n tags?: string[]\n notes?: string\n /**\n * Every site that has captured this person, in no order.\n *\n * An ARRAY and a top-level field, because this is the one attribution that\n * has to survive being a QUERY: \"everyone captured on A, B or C\" is an\n * audience, and `array-contains-any` is what answers it. The per-interaction\n * host says which visit belonged to whom; this says which sites have a\n * relationship at all, and only the second shape can be filtered on in\n * Firestore.\n *\n * Grows by `arrayUnion` on every capture, including the ones that merge\n * onto an existing row — which is exactly what the create-only `hostId`\n * beside it could never do.\n */\n capturedByHostIds?: string[]\n /**\n * Every form this person has come in through, in no order (AGL-2612).\n *\n * The entry point proper is `interactions[].formId` inside the capturing\n * holder's facet, and that stays the record: which form produced which\n * visit is one holder's business. But Firestore cannot select documents\n * by a field of an array ELEMENT, and a facet path is per group, so\n * \"everyone who filled in this form\" — the question the form's own page\n * asks of the Contacts list — has to be a top-level array an\n * `array-contains` can hit, exactly as `capturedByHostIds` is for sites\n * and `companyIds` is for companies. A form id is minted under one site,\n * so a query on it is one site's captures by construction.\n *\n * Grows by `arrayUnion` on every form capture, create or merge, bounded at\n * {@link CONTACT_FORM_IDS_CAP}: a person who has filled in more forms than\n * that keeps the first twenty and the timeline keeps the rest. The facet is\n * the truth and this is its index — a reader answering \"which form\" reads\n * the interaction; only a QUERY reads this.\n */\n formIds?: string[]\n /*\n * SEARCH KEYS (AGL-2596), and nothing more.\n *\n * The console's global search reads a window of contact documents and\n * matches over their top-level fields; it never resolves a holder's facet,\n * because it is one search over a dozen collections and a facet read is a\n * contacts-only idea. So the two profile values a person is looked up BY —\n * their phone number and the company they work for — are mirrored here by\n * every writer that sets them on a facet, as plain values a query can hit.\n *\n * The FACET is the record. These are a last-writer-wins echo of it: two\n * holders who keep different numbers for one person each overwrite the\n * echo and each keep their own facet value, and nothing renders these to a\n * reader — the list, the record page and the export all read through the\n * viewing group's facet. `ORG_CONTACT_FIELDS` below is an allow-list, so\n * neither reaches the org view either.\n */\n /** E.164, mirrored from the last facet write that set one. */\n phone?: string\n /** The company name as typed, mirrored the same way. */\n companyName?: string\n /**\n * The OTHER addresses this person answers to (AGL-2625).\n *\n * A contact is keyed on one email, so one human with a work address and a\n * personal one is two documents until somebody merges them. The merge keeps\n * the survivor's `email` as the identity and records the merged record's\n * address here, so a later capture on it — a form filled in from the\n * personal account — resolves to this row rather than minting the second\n * document again. `emailIndex` (see {@link CONTACT_EMAIL_INDEX_COLLECTION})\n * is the lookup; this array is the record of why an entry there points\n * where it does, and what the record page shows as \"also\".\n *\n * Shared identity like `email`, not a facet field: which addresses are one\n * person is a fact about the person, and a holder that did not perform the\n * merge still needs its capture on the alternate address to land on the\n * shared row. Bounded at {@link CONTACT_ALTERNATE_EMAILS_CAP}.\n */\n alternateEmails?: string[]\n /**\n * When the earliest OPEN task filed against this person is due, epoch\n * ms, or `null` when none is (AGL-2661) — see `CrmDeal.nextTaskAtMs` in\n * `crm.ts` for the rule. On the SHARED row rather than a facet, because a\n * task lives at the organization level and names the contact, not a\n * holder's view of them.\n */\n nextTaskAtMs?: number | null\n /**\n * The last verdict on the address (AGL-3245) — bounced, blocked,\n * unsubscribed, do-not-contact — written by the platform's senders only,\n * on the SHARED row because the address is shared. Absent means nothing\n * is known. See `email-state.ts`.\n */\n emailState?: EmailState\n}\n\n/** Timeline cap: keeps the doc small; older interactions age out. */\nexport const CONTACT_INTERACTIONS_CAP = 50\n\n/** The field holding {@link HostContact.alternateEmails}. */\nexport const CONTACT_ALTERNATE_EMAILS_FIELD = 'alternateEmails'\n\n/**\n * The most alternate addresses one contact carries. Ten is past any real\n * person's mailbox count, and it bounds the index writes one merge fans out.\n */\nexport const CONTACT_ALTERNATE_EMAILS_CAP = 10\n\n/**\n * `orgs/{orgId}/emailIndex/{personKey}` → `{ email, contactId }` (AGL-2625).\n *\n * The address-to-contact lookup the capture door consults BEFORE the\n * per-document `email ==` query, so an address recorded as an alternate on a\n * merged row resolves to the survivor. Keyed by `personKey` — the sha256 of\n * the normalized address — so a document id never carries the address\n * itself, the same derivation a lead and a list membership use.\n *\n * WRITTEN LAZILY, never backfilled: the query on `email` stays as the\n * fallback, and a contact that has no entry gets one on the next write that\n * finds it. A row the index has never seen therefore costs one extra read\n * once, and nothing needs to run over the existing collection.\n *\n * Server-written only; the rules close it to every client.\n */\nexport const CONTACT_EMAIL_INDEX_COLLECTION = 'emailIndex'\n\n/**\n * Every address a contact answers to — the primary first, then the\n * alternates — normalized and deduplicated, so an index writer and a lead\n * lookup walk one list.\n */\nexport function contactEmails(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (value: unknown) => {\n const email = normalizeContactEmail(value)\n if (email && !seen.has(email)) {\n seen.add(email)\n out.push(email)\n }\n }\n push((contact ?? {})['email'])\n const alternates = (contact ?? {})[CONTACT_ALTERNATE_EMAILS_FIELD]\n if (Array.isArray(alternates)) alternates.forEach(push)\n return out\n}\n\n/** The top-level field naming every form a contact came in through — see `HostContact.formIds`. */\nexport const CONTACT_FORM_IDS_FIELD = 'formIds'\n\n/**\n * How many forms the {@link CONTACT_FORM_IDS_FIELD} mirror holds.\n *\n * The same figure as the tag cap: enough that no real person reaches it,\n * small enough that the array never becomes the document. Past it the\n * capture stops adding rather than dropping the oldest, because the mirror\n * is an index of the facet's timeline and an index that silently forgets an\n * entry the timeline still holds would answer a form's contact list wrongly\n * in the one direction nobody would notice.\n */\nexport const CONTACT_FORM_IDS_CAP = 20\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Normalized dedupe key, or null when the input isn't a usable email. */\nexport function normalizeContactEmail(input: unknown): string | null {\n const email = String(input ?? '')\n .trim()\n .toLowerCase()\n return EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null\n}\n\n/**\n * First usable email in a free-form form-submission fields map — forms\n * don't guarantee a canonical email field, so prefer keys that look like\n * email fields before falling back to any email-shaped value.\n */\nexport function extractEmailFromFields(\n fields: Record<string, unknown> | null | undefined,\n): string | null {\n const entries = Object.entries(fields ?? {})\n const preferred = entries.find(([key]) => /email/i.test(key))\n const fromPreferred = normalizeContactEmail(preferred?.[1])\n if (fromPreferred) return fromPreferred\n for (const [, value] of entries) {\n const email = normalizeContactEmail(value)\n if (email) return email\n }\n return null\n}\n\n/**\n * Merges a new interaction into a contact: source flag set, interaction\n * prepended, timeline capped. Pure — the caller persists the result.\n */\nexport function mergeContactInteraction(\n existing: Pick<HostContact, 'sources' | 'interactions'> & {\n name?: string\n },\n update: { source: ContactSource; interaction: ContactInteraction; name?: string },\n): Pick<HostContact, 'sources' | 'interactions'> & { name?: string } {\n return {\n // Existing names win — a later anonymous form shouldn't blank a name.\n name: existing.name || update.name,\n sources: { ...existing.sources, [update.source]: true as const },\n interactions: [update.interaction, ...(existing.interactions ?? [])].slice(\n 0,\n CONTACT_INTERACTIONS_CAP,\n ),\n }\n}\n\n/**\n * THE PER-HOLDER FACET on a shared contact document.\n *\n * ## What is shared and what is not\n *\n * One human who touched two sites is ONE document. That is not a compromise:\n * it is the dedupe the shared address book exists for, it is what keeps a\n * bounce and a suppression describing one person, and it is what makes a\n * multi-brand account bill once for one human instead of once per site. A\n * document per host would push an agency toward twelve separate accounts and\n * throw the whole advantage away.\n *\n * But almost nothing ON that document is legitimately shared.\n *\n * - **SHARED IDENTITY** — `email`, and the canonical `name`. One human, one\n * identity. This is the only part two unrelated businesses may both see,\n * and it is the minimum that makes them one row.\n * - **PER-HOLDER FACET** — everything in this interface. A note, a tag, a\n * call log and a lifetime value are the HOLDER's own business records.\n * Host A's note about a customer is Host A's; a competitor sharing the\n * platform must not read it, and while these lived at the top of the\n * document every site in the org could.\n * - **CONSENT AND VISIBILITY** — per declared group, decided by\n * `marketing-consent.ts` and by `visibleTo`.\n *\n * ## Keyed by GROUP, not by host\n *\n * A business that declared three sites to be one sender is one CRM: a note\n * written on the shop belongs beside the booking made on the booking page,\n * because one team keeps both. Across groups, never — and an undeclared site\n * is a group of one, so the agency case is isolated with nothing configured.\n *\n * ## Commercial figures are per-facet, and that is not a billing change\n *\n * `ltvCents` and `ordersCount` answer \"what is this person worth to ME\". Two\n * unrelated merchants who both sell to one person have two different answers\n * and neither is entitled to the other's. Billing counts DOCUMENTS, and there\n * is still one document, so a person held by two hosts stays one billable\n * contact.\n */\nexport interface ContactFacet {\n /**\n * This holder's display name for the person, overriding the canonical one.\n *\n * The canonical `name` is shared and mutable, so without this a rename on\n * one site changes what an unrelated business sees in its own CRM — two\n * companies that do not know each other exist editing each other's records.\n * The override is written by whoever edits the name from their own console;\n * the canonical field stays as the identity of last resort, for a holder\n * that has never set one.\n */\n name?: string\n /** Which capture surfaces THIS holder saw the person through. */\n sources: Partial<Record<ContactSource, true>>\n /** THIS holder's timeline, newest-first and capped. */\n interactions: ContactInteraction[]\n /** THIS holder's tags. */\n tags?: string[]\n /** THIS holder's notes. */\n notes?: string\n /**\n * The campaigns THIS holder has filed the person under.\n *\n * A label on the CRM record, not an audience: who a campaign's mail reaches\n * is decided by the campaign's lists and by each send's own picker, and\n * nothing in the send path reads this. It answers \"who did we put in the\n * spring push\", which is a question about the holder's own working set.\n *\n * Per-holder for the reason the notes are: two unrelated businesses sharing\n * one row must not read each other's segmentation of a person they both\n * know. See `container-membership.ts` for the field and the path.\n */\n campaignIds?: string[]\n /** Gross of fees and refunds — see `upsertHostContact`. */\n ltvCents?: number\n ordersCount?: number\n lastPurchaseAtMs?: number\n firstPurchaseAtMs?: number\n refundedCents?: number\n refundedOrdersCount?: number\n lastRefundAtMs?: number\n /*\n * CRM v2 (AGL-2595): the profile a sales team keeps on a person.\n *\n * Per-holder like everything above them, and for the same reason: a phone\n * number, a job title, an owner and a lifecycle stage are one business's\n * knowledge of a person, and two unrelated businesses sharing the row must\n * not read each other's. `companyId` points at a company document in the\n * same scope, never at the org's whole company list. `custom` is keyed by\n * `ContactFieldDefinition.key`, so a holder's field definitions and a\n * holder's values live under the same group and cannot be joined across\n * one.\n *\n * ⛔ None of these reach the org view. `ORG_CONTACT_FIELDS` is an\n * allow-list, and the org-view spec seeds every one of these with a\n * sentinel and proves it never surfaces.\n */\n /** E.164 — `normalizePhone` before writing. */\n phone?: string\n jobTitle?: string\n /**\n * Where this holder met the person — Salesforce's Lead Source, carried\n * from the lead on conversion and picked from the org's lead source\n * values after it (AGL-3298). The value's label, as the lead stores it.\n */\n leadSource?: string\n /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */\n companyId?: string\n /**\n * The company's name as this holder knows it.\n *\n * Free text, so a person can be filed under a company before one exists\n * as a record; the company picker that later sets `companyId` writes the\n * picked company's name here too, so the row reads the same whether the\n * link was made or the name typed. The top-level `companyName` on the\n * document is the search echo of this value — see `HostContact`.\n */\n companyName?: string\n address?: AglynPostalAddress | null\n /** The team member responsible for the relationship. */\n ownerUid?: string\n lifecycleStage?: ContactLifecycleStage\n /** Custom field values, keyed by `ContactFieldDefinition.key`. */\n custom?: Record<string, ContactCustomValue>\n /**\n * When this person last OPENED or CLICKED a campaign sent by one of this\n * holder's sites, epoch ms (AGL-2616).\n *\n * Stamped by the delivery webhook, forward-only, on the first open and the\n * first click of each message — the same bound the per-person rollup on\n * `emailDeliveries/{key}` keeps, so a reader opening one newsletter six\n * times is one write. Per-holder because it answers \"is this person still\n * reading OUR mail\": the address-level rollup counts every sender's mail\n * and a sibling business's, and a re-engagement audience built on that\n * would mail people who are reading somebody else.\n *\n * Absent until the first engagement after the stamp shipped; a message\n * opened before then advanced the address-level rollup and nothing here.\n */\n lastEmailEngagementAtMs?: number\n /**\n * The org-library files THIS holder has attached to the person\n * (AGL-2662), by media document id.\n *\n * Per-holder for the reason every other field here is: an agency running\n * two client brands has one contact document between them, and a signed\n * contract one client filed is not the other client's to see. Ids rather\n * than URLs so a file moved between folders keeps its attachment, and so\n * a private asset is still served through the signed CDN door.\n */\n mediaIds?: string[]\n /*\n * SALESFORCE'S STANDARD CONTACT FIELDS (AGL-3515), per holder like the\n * profile above and for the same reason. Every one of them is personal\n * data about the person, so none reaches the org view (see\n * `ORG_CONTACT_FIELDS`) and an erasure takes them with the document.\n */\n /** One of the org's salutation values, by label (`Mr.`, `Dr.` …). */\n salutation?: string\n /**\n * The person's given and family names. While either is set, {@link name}\n * is their composition — see {@link composeContactName} — so every reader\n * of the display name reads the same person the structured fields name. A\n * facet holding only `name` keeps it as typed: nothing splits a stored\n * name into parts after the fact.\n */\n firstName?: string\n lastName?: string\n department?: string\n /** E.164, like {@link phone}. */\n mobilePhone?: string\n /** E.164. */\n homePhone?: string\n /** E.164. */\n otherPhone?: string\n /** E.164. */\n fax?: string\n /** A calendar date, `YYYY-MM-DD`, never in the future — {@link normalizeContactBirthdate}. */\n birthdate?: string\n assistantName?: string\n /** E.164. */\n assistantPhone?: string\n /**\n * Another contact of the org this holder can see — the person's manager.\n * Never the contact itself, and never a contact whose own chain leads\n * back here: `crm/contact-update` refuses both. `null` is \"nobody\" — what\n * a merge leaves where a pointer would have named the person themselves.\n */\n reportsToContactId?: string | null\n /**\n * A second postal address. {@link address} is the MAILING address — the\n * one a letter goes to — and keeps its field name; this is Salesforce's\n * Other Address beside it.\n */\n otherAddress?: AglynPostalAddress | null\n /**\n * The person asked not to be phoned. Stored only as `true`; absent is\n * \"may be called\". A hint beside every number and on the Call button,\n * never a block: the rep decides.\n */\n doNotCall?: boolean\n}\n\n/**\n * The profile's phone fields besides `phone` (AGL-3515), each stored E.164\n * through `normalizePhone`, in the order a record page lists them.\n */\nexport const CONTACT_EXTRA_PHONE_FIELDS = [\n 'mobilePhone',\n 'homePhone',\n 'otherPhone',\n 'fax',\n 'assistantPhone',\n] as const\n\nexport type ContactExtraPhoneField = (typeof CONTACT_EXTRA_PHONE_FIELDS)[number]\n\n/** How each phone field is labeled on screen, in a file and in the docs. */\nexport const CONTACT_PHONE_FIELD_LABELS: Record<'phone' | ContactExtraPhoneField, string> = {\n phone: 'Phone',\n mobilePhone: 'Mobile phone',\n homePhone: 'Home phone',\n otherPhone: 'Other phone',\n fax: 'Fax',\n assistantPhone: 'Assistant phone',\n}\n\n/** The longest first or last name a facet keeps — the composed name stays within 120. */\nexport const CONTACT_NAME_PART_MAX = 59\n\n/**\n * The display name a holder's first and last names make: `\"First Last\"`,\n * either alone, or `''` when neither is set — Salesforce's Name, less the\n * salutation, which is a form of address and not part of who the person is.\n */\nexport function composeContactName(firstName: unknown, lastName: unknown): string {\n const part = (value: unknown) =>\n String(value ?? '')\n .trim()\n .replace(/\\s+/g, ' ')\n .slice(0, CONTACT_NAME_PART_MAX)\n return [part(firstName), part(lastName)].filter(Boolean).join(' ')\n}\n\n/** The sentence a birthdate that cannot be stored is refused with. */\nexport const CONTACT_BIRTHDATE_REFUSAL =\n 'Birthdate must be a past date written YYYY-MM-DD, like 1984-07-21.'\n\n/**\n * A birthdate as stored: `YYYY-MM-DD` for a real calendar date that is not\n * in the future, `''` for a blank (a clear), and `null` for anything else.\n *\n * \"Not in the future\" is judged against the latest calendar day anywhere on\n * Earth (UTC+14), so a person entering today's date where the day has\n * already turned is never refused.\n */\nexport function normalizeContactBirthdate(value: unknown, nowMs = Date.now()): string | null {\n const text = String(value ?? '').trim()\n if (!text) return ''\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return null\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\n const date = new Date(Date.UTC(year, month - 1, day))\n if (\n year < 1000 ||\n date.getUTCFullYear() !== year ||\n date.getUTCMonth() !== month - 1 ||\n date.getUTCDate() !== day\n ) {\n return null\n }\n const latestToday = new Date(nowMs + 14 * 60 * 60 * 1000).toISOString().slice(0, 10)\n return text > latestToday ? null : text\n}\n\n/** The map field holding the facets: `{ [groupId]: ContactFacet }`. */\nexport const CONTACT_FACETS_FIELD = 'facets'\n\n/**\n * The facet one group holds, or an empty one.\n *\n * `map[groupId]` — a lookup, not a search, for the reason the consent map is\n * shaped the same way: there is no expression of this form that returns\n * another holder's notes.\n *\n * An absent facet reads EMPTY rather than falling back to the top-level\n * fields. A fallback would hand every holder in the org the fields the\n * pre-facet document carried at its top, which is the disclosure this shape\n * exists to end; the migration moves them into the capturing group's facet\n * instead.\n */\nexport function readContactFacet(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): ContactFacet {\n const facets = (contact ?? {})[CONTACT_FACETS_FIELD]\n const facet =\n facets && typeof facets === 'object' && !Array.isArray(facets)\n ? (facets as Record<string, unknown>)[groupId]\n : undefined\n if (!facet || typeof facet !== 'object' || Array.isArray(facet)) {\n return { sources: {}, interactions: [] }\n }\n const value = facet as Record<string, unknown>\n return {\n ...(value as unknown as ContactFacet),\n sources: (value['sources'] ?? {}) as ContactFacet['sources'],\n interactions: Array.isArray(value['interactions'])\n ? (value['interactions'] as ContactInteraction[])\n : [],\n }\n}\n\n/** The dotted Firestore path to one field of one holder's facet. */\nexport function contactFacetPath(groupId: string, field: string): string {\n if (!groupId) throw new Error('a contact facet must name a holder')\n return `${CONTACT_FACETS_FIELD}.${groupId}.${field}`\n}\n\n/**\n * The name a given holder should SEE for this person.\n *\n * Their own override first, the canonical identity second. Nothing falls\n * through to another holder's override: that would be one business's edit\n * showing up in another's CRM, which is the thing the override exists to\n * prevent.\n */\nexport function contactDisplayName(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): string {\n const facet = readContactFacet(contact, groupId)\n if (facet.name) return facet.name\n const canonical = (contact ?? {})['name']\n return typeof canonical === 'string' ? canonical : ''\n}\n\n/**\n * Every group that holds this contact — the reference count behind a detach.\n *\n * Read from `visibleTo` rather than from the facet map, because `visibleTo`\n * is what both enforcement layers actually evaluate: a holder that can still\n * READ the row is still holding it whether or not they ever wrote a note. A\n * count taken from the facets would drop a holder who has one and no facet\n * and leave them able to see a document nothing believes they hold.\n *\n * Less the tokens a share ADDED (AGL-3336): a site the record was shared\n * with sees it and holds nothing, so it must not keep the record alive when\n * its last holder lets go — `heldScopeTokens` is `visibleTo` without them.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n return heldScopeTokens(contact)\n}\n\n/** What a holder letting go of a contact should do to the document. */\nexport type ContactDetach =\n | {\n /** Nobody else holds it. Delete the document. */\n action: 'delete'\n /**\n * Every refusal the document holds, every site's and the unscoped one,\n * which the delete keeps in `retainedRefusals` in the same transaction\n * — see `retained-refusals.ts`. `null` when it holds none.\n */\n retained: RetainedRefusals | null\n }\n | {\n /** Other holders remain. Drop this one's half. */\n action: 'detach'\n /**\n * Field-level removals, as a patch. Dotted paths so the OTHER holders'\n * facets and consent entries are untouched — a nested write would\n * replace the whole map and take every other holder's records with it.\n *\n * A consent entry that is a REFUSAL is not among them: it stays on the\n * document for the holders that remain, because a person's \"no\" is not\n * the leaving holder's to take with it.\n */\n remove: string[]\n /** Scope tokens to pull out of `visibleTo`. */\n removeTokens: string[]\n /** Host ids to pull out of the capture attribution. */\n removeHostIds: string[]\n }\n\n/**\n * DELETE IS A DETACH.\n *\n * One holder removing a contact from their own CRM must not destroy another\n * holder's relationship with that person: they have their own notes, their\n * own order history and their own consent, none of which the deleting holder\n * ever had a claim on. So a delete drops the deleting group's facet, its\n * consent grants, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * A REFUSAL IS NOT LET GO (AGL-3338). The list gate reads a stored refusal\n * as the one fact an operator's attestation cannot overrule, so a detach\n * leaves the leaving group's refusal entries on the document, and a delete\n * answers every refusal the document holds for the caller to retain beside\n * the delete. Read off the document's own data: a table row's projection\n * carries neither the consent map nor the unscoped field.\n *\n * ⛔ This is NOT the erasure path. A privacy erasure removes the person\n * everywhere regardless of how many holders remain, and routing it through\n * reference counting would turn a lawful erasure into a partial one — the same\n * absent-versus-invisible defect this area keeps hitting, in the one place\n * where getting it wrong is a legal failure rather than a bug. Erasure calls\n * the document delete directly and must never consult this function.\n *\n * @param group the holder letting go, with every site it covers.\n */\nexport function planContactDetach(\n contact: Record<string, unknown> | null | undefined,\n group: { groupId: string; hostIds: readonly string[] },\n): ContactDetach {\n const held = contactHolderTokens(contact)\n const leaving = new Set(group.hostIds.map((id) => `host:${id}`))\n /*\n * A remaining holder is a token naming somebody else. `'org'` counts as one\n * and blocks the delete on purpose: an org-wide row is held by every site\n * in the account, so one site letting go leaves it held. Narrowing it would\n * be a scope decision, and a delete button is not where that belongs.\n */\n const remaining = held.filter((token) => !leaving.has(token))\n if (!remaining.length) return { action: 'delete', retained: refusalsOf(contact) }\n const refused = refusalsOf(contact)?.byHost ?? {}\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds\n .filter((id) => !(id in refused))\n .map((id) => `${MARKETING_CONSENT_BY_HOST_FIELD}.${id}`),\n ],\n removeTokens: [...leaving],\n removeHostIds: [...group.hostIds],\n }\n}\n\n/**\n * The interactions one group of sites may see on a shared contact.\n *\n * An interaction with NO host is shown to everyone: it predates the\n * attribution, so hiding it would empty every existing timeline, and it is\n * already visible to anyone who can read the row. An interaction that names a\n * site is shown only to that site's own group — the agency case, where one\n * client must not read another client's bookings off a person they both know.\n */\nexport function interactionsForGroup(\n interactions: readonly ContactInteraction[] | undefined,\n hostIds: readonly string[],\n): ContactInteraction[] {\n const reach = new Set(hostIds)\n return (interactions ?? []).filter(\n (interaction) => !interaction.hostId || reach.has(interaction.hostId),\n )\n}\n\n/** `orgs/{orgId}/contactSegments/{id}` — a saved audience filter. */\nexport interface ContactSegment {\n name: string\n /** Match contacts sharing at least one tag (empty = any). */\n tags?: string[]\n /** Match contacts with at least one of these sources (empty = any). */\n sources?: ContactSource[]\n}\n\n/** Segment matching (AGL-199): AND across filter kinds, OR within one. */\nexport function contactMatchesSegment(\n contact: Pick<HostContact, 'tags' | 'sources'>,\n segment: Pick<ContactSegment, 'tags' | 'sources'>,\n): boolean {\n if (segment.tags?.length) {\n const contactTags = new Set(\n (contact.tags ?? []).map((tag) => tag.toLowerCase()),\n )\n if (!segment.tags.some((tag) => contactTags.has(tag.toLowerCase()))) {\n return false\n }\n }\n if (segment.sources?.length) {\n if (!segment.sources.some((source) => contact.sources?.[source])) {\n return false\n }\n }\n return true\n}\n\n/*==========================================\n * THE ORG-LEVEL VIEW: the complement of the facet reader above.\n *\n * {@link readContactFacet} answers \"what does THIS holder know about this\n * person\". Everything below answers the question no host page can:\n *\n * who does this ORGANIZATION know, and which of its sites know them.\n *\n * That question is the entire justification for one shared document. Dedupe,\n * suppression and honest billing all rest on one human being one row, and\n * with no surface that shows the deduped person the model's benefit is\n * invisible and the billing unit — unique people per org — looks arbitrary.\n *\n * ## The org view crosses the host boundary, so it carries LESS, not more\n *\n * It is the one place in the product designed to read across holders, which\n * makes it the one place where a careless field re-creates the disclosure the\n * facets exist to end. So the projection is an ALLOW-LIST\n * ({@link ORG_CONTACT_FIELDS}) rather than an omission: identity, capture\n * attribution and consent state. Notes, tags, timelines, call logs and\n * commercial figures are the holder's own business records and are not read\n * here at all — not summarized, not counted, not indicated by their absence.\n *\n * An allow-list rather than a `delete facets` is the load-bearing choice. A\n * subtraction is correct only for as long as somebody remembers to extend it,\n * and a field added to {@link ContactFacet} tomorrow would ride out through a\n * subtraction and be caught by an allow-list.\n *\n * ## The NAME is the canonical one, never a holder's override\n *\n * {@link contactDisplayName} prefers the viewing group's own override, which\n * is right on a host page and wrong here: an override is a name ONE business\n * chose, and rendering it at org level shows an agency the label its client\n * picked. The shared identity is what every holder already sees, so it is the\n * only name that belongs to the org.\n *=========================================*/\n\n/**\n * Every field of a contact document the org view may read.\n *\n * Stated as a value so it can be asserted against — see the org-view spec,\n * which seeds each facet field with a sentinel and proves none of them\n * reaches a row.\n */\nexport const ORG_CONTACT_FIELDS = [\n 'email',\n 'name',\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n] as const\n\n/**\n * What one site's relationship with one person amounts to, at org level.\n *\n * Consent is per (contact, host-or-group) and there is no expression that\n * returns another controller's grant, so a row cannot carry one consent\n * verdict. It carries one PER CAPTURING SITE, each naming the controller it\n * was read for — a bare \"consented\" with nobody attached would be exactly the\n * confusion the per-brand model was built to prevent.\n */\nexport interface OrgContactHostConsent {\n /** The site this verdict answers about, and no other. */\n hostId: string\n /** The controller the basis runs to — the declared group, or the site. */\n groupId: string\n /**\n * The group's disclosed name, or `null` for a site that pools with nobody.\n *\n * `null` is not \"unknown\": it is the group of one, where the site's own\n * name is the disclosure and inventing a second would put a label in front\n * of a reader that nothing else uses.\n */\n groupName: string | null\n /** Whether the controller is a DECLARED group rather than the site alone. */\n declared: boolean\n /** `granted` | `declined` | `unrecorded` — never collapsed to a boolean. */\n basis: MarketingBasis\n}\n\n/** One person, as the organization may see them across all of its sites. */\nexport interface OrgContactRow {\n $id: string\n /** The dedupe key, and the reason two captures are one row. */\n email: string\n /** The SHARED identity. Never a holder's own override. */\n name: string\n /** Every site that has captured this person, sorted for a stable render. */\n capturedByHostIds: string[]\n /** One verdict per capturing site, in the same order. */\n consent: OrgContactHostConsent[]\n}\n\n/**\n * Every site that has captured this person.\n *\n * Sorted, because the array is maintained by `arrayUnion` and therefore\n * carries capture order, which is not an order anything should render: two\n * readers of the same row would see the sites in different places on the\n * screen depending on which site met the person first.\n */\nexport function contactCaptureHostIds(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const raw = (contact ?? {})[CAPTURED_BY_HOST_FIELD]\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw\n .map((id) => String(id ?? '').trim())\n .filter((id): id is string => id !== ''),\n ),\n ].sort()\n}\n\n/**\n * One contact document, projected to what an ORG may see.\n *\n * @param org - the org document — the only input that can resolve a declared\n * consent group, and required for that reason. Without it every site reads\n * as a group of one, which understates the disclosure a person was given\n * and is the safe direction to be wrong in.\n */\nexport function orgContactRow(\n contact: Record<string, unknown> | null | undefined,\n contactId: string,\n org: Record<string, unknown> | null | undefined,\n): OrgContactRow {\n const record = contact ?? {}\n const capturedByHostIds = contactCaptureHostIds(record)\n return {\n $id: contactId,\n email: typeof record['email'] === 'string' ? record['email'] : '',\n name: typeof record['name'] === 'string' ? record['name'] : '',\n capturedByHostIds,\n consent: capturedByHostIds.map((hostId) => {\n /*\n * READ FOR THE SITE, one call per site. `readMarketingBasis` requires\n * the group it is being read for and has no default, so this cannot\n * accidentally report a grant that belongs to somebody else — the\n * argument is the guarantee, and passing the whole row through one\n * call would have had to invent a controller to ask about.\n */\n const group = consentGroupForHost(org, hostId)\n const { basis } = readMarketingBasis(record, group)\n return {\n hostId,\n groupId: group.groupId,\n groupName: group.name,\n declared: group.declared,\n basis,\n }\n }),\n }\n}\n\n/**\n * How a basis reads on screen.\n *\n * Three labels because there are three states. \"Opted in\" and \"No record\" are\n * not opposites and must never collapse into one negative: absence is the\n * commonest case by far — a record captured before the checkbox existed — and\n * showing it as a refusal would tell a merchant they may not mail somebody\n * who never said so.\n */\nexport const MARKETING_BASIS_LABELS: Record<MarketingBasis, string> = {\n granted: 'Opted in',\n declined: 'Opted out',\n unrecorded: 'No record',\n}\n\n/**\n * One consent verdict, WITH THE CONTROLLER IT RUNS TO, as one string.\n *\n * ⛔ There is no function here that returns a basis on its own, and that is\n * the point. A basis is per (person, controller): the same person can be\n * opted in to one brand in an org and opted out of another, so \"consented\"\n * with nobody attached is not a shortened truth, it is a different and false\n * claim — precisely the confusion the per-brand model was built to prevent.\n * Joining the two into a single value is what stops a caller rendering half\n * of it.\n *\n * The controller is the DECLARED GROUP when there is one, because that is who\n * the person was told they would hear from, and the site otherwise. A group\n * of one is named by the site, which is what the capture surface already\n * showed them.\n *\n * @param siteName - how this site reads — the caller resolves it, since the\n * contact document holds ids and not names. An empty one falls back to the\n * id: a site whose name cannot be resolved must still be NAMED, because\n * dropping it would understate which brands hold a relationship.\n */\nexport function orgContactConsentLabel(\n entry: OrgContactHostConsent,\n siteName?: string,\n): string {\n const controller = entry.declared\n ? (entry.groupName ?? entry.groupId)\n : siteName || entry.hostId\n return `${controller} · ${MARKETING_BASIS_LABELS[entry.basis]}`\n}\n"],"names":["consentGroupForHost","heldScopeTokens","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","refusalsOf","CONTACT_SOURCE_LABELS","form","member","order","booking","newsletter","api","manual","import","account","CONTACT_INTERACTIONS_CAP","CONTACT_ALTERNATE_EMAILS_FIELD","CONTACT_ALTERNATE_EMAILS_CAP","CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","contact","out","seen","Set","push","value","email","normalizeContactEmail","has","add","alternates","Array","isArray","forEach","CONTACT_FORM_IDS_FIELD","CONTACT_FORM_IDS_CAP","EMAIL_PATTERN","input","String","trim","toLowerCase","test","length","extractEmailFromFields","fields","entries","Object","preferred","find","key","fromPreferred","mergeContactInteraction","existing","update","name","sources","source","interactions","interaction","slice","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_PHONE_FIELD_LABELS","phone","mobilePhone","homePhone","otherPhone","fax","assistantPhone","CONTACT_NAME_PART_MAX","composeContactName","firstName","lastName","part","replace","filter","Boolean","join","CONTACT_BIRTHDATE_REFUSAL","normalizeContactBirthdate","nowMs","Date","now","text","match","exec","year","month","day","Number","date","UTC","getUTCFullYear","getUTCMonth","getUTCDate","latestToday","toISOString","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","contactFacetPath","field","Error","contactDisplayName","canonical","contactHolderTokens","planContactDetach","group","held","leaving","hostIds","map","id","remaining","token","action","retained","refused","byHost","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","$id","consent","basis","groupName","declared","MARKETING_BASIS_LABELS","granted","declined","unrecorded","orgContactConsentLabel","entry","siteName","controller"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC;AAGD,SAASA,mBAAmB,QAAQ,sBAAkB;AAGtD,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AAC5B,SAASC,UAAU,QAA+B,yBAAqB;AA+BvE;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAuD;IAClEC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,SAAS;IACTC,YAAY;IACZC,KAAK;IACLC,QAAQ;IACRC,QAAQ;IACRC,SAAS;AACX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QAGZD;IADL,MAAME,aAAaF,MAAMN,QAAQ,IAC5BM,mBAAAA,MAAMP,SAAS,YAAfO,mBAAmBA,MAAMtD,OAAO,GACjCuD,YAAYD,MAAM1B,MAAM;IAC5B,OAAO,GAAG4B,WAAW,GAAG,EAAEP,sBAAsB,CAACK,MAAMR,KAAK,CAAC,EAAE;AACjE"}
|
|
@@ -33,5 +33,6 @@ export * from "./page-header-help-context.js";
|
|
|
33
33
|
export * from "./page-header-record-context.js";
|
|
34
34
|
export * from "./screen-link-context.js";
|
|
35
35
|
export * from "./site-context.js";
|
|
36
|
+
export * from "./transfer-launcher-context.js";
|
|
36
37
|
|
|
37
38
|
//# sourceMappingURL=contexts.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contexts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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 * Client-only React contexts that live in @aglyn/aglyn (not a UI lib) so\n * every canvas-rendering surface — console, plugins, tenant render — shares\n * ONE context module instance (a second instance renders the site blank).\n * They call `createContext` at module scope, which App Router forbids in a\n * Server Component's module graph, so they are split out of the server-safe\n * `./server` barrel and only reachable via the full `@aglyn/aglyn` barrel\n * (client) — never `@aglyn/aglyn/server` (AGL-405).\n */\nexport * from './console-widget-slot-context'\nexport * from './deployment-capabilities-context'\nexport * from './enabled-plugins-context'\nexport * from './entity-picker-context'\nexport * from './link-target-search-context'\nexport * from './media-picker-context'\nexport * from './node-identity'\nexport * from './page-header-actions-context'\nexport * from './page-header-help-context'\nexport * from './page-header-record-context'\nexport * from './screen-link-context'\nexport * from './site-context'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GACD,cAAc,mCAA+B;AAC7C,cAAc,uCAAmC;AACjD,cAAc,+BAA2B;AACzC,cAAc,6BAAyB;AACvC,cAAc,kCAA8B;AAC5C,cAAc,4BAAwB;AACtC,cAAc,qBAAiB;AAC/B,cAAc,mCAA+B;AAC7C,cAAc,gCAA4B;AAC1C,cAAc,kCAA8B;AAC5C,cAAc,2BAAuB;AACrC,cAAc,oBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contexts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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 * Client-only React contexts that live in @aglyn/aglyn (not a UI lib) so\n * every canvas-rendering surface — console, plugins, tenant render — shares\n * ONE context module instance (a second instance renders the site blank).\n * They call `createContext` at module scope, which App Router forbids in a\n * Server Component's module graph, so they are split out of the server-safe\n * `./server` barrel and only reachable via the full `@aglyn/aglyn` barrel\n * (client) — never `@aglyn/aglyn/server` (AGL-405).\n */\nexport * from './console-widget-slot-context'\nexport * from './deployment-capabilities-context'\nexport * from './enabled-plugins-context'\nexport * from './entity-picker-context'\nexport * from './link-target-search-context'\nexport * from './media-picker-context'\nexport * from './node-identity'\nexport * from './page-header-actions-context'\nexport * from './page-header-help-context'\nexport * from './page-header-record-context'\nexport * from './screen-link-context'\nexport * from './site-context'\nexport * from './transfer-launcher-context'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GACD,cAAc,mCAA+B;AAC7C,cAAc,uCAAmC;AACjD,cAAc,+BAA2B;AACzC,cAAc,6BAAyB;AACvC,cAAc,kCAA8B;AAC5C,cAAc,4BAAwB;AACtC,cAAc,qBAAiB;AAC/B,cAAc,mCAA+B;AAC7C,cAAc,gCAA4B;AAC1C,cAAc,kCAA8B;AAC5C,cAAc,2BAAuB;AACrC,cAAc,oBAAgB;AAC9B,cAAc,iCAA6B"}
|
|
@@ -283,11 +283,20 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
283
283
|
const groupId = text(context.contactGroupId);
|
|
284
284
|
const facet = readContactFacet(contact, groupId);
|
|
285
285
|
const name = groupId ? contactDisplayName(contact, groupId) : text(contact['name']);
|
|
286
|
+
/*
|
|
287
|
+
* The holder's own first and last names when it keeps them (AGL-3515)
|
|
288
|
+
* — a two-word first name or a particle in a surname is then what the
|
|
289
|
+
* person wrote — and the display name split at its first space when
|
|
290
|
+
* it keeps neither.
|
|
291
|
+
*/ const parts = text(facet.firstName) || text(facet.lastName) ? {
|
|
292
|
+
firstName: text(facet.firstName),
|
|
293
|
+
lastName: text(facet.lastName)
|
|
294
|
+
} : splitPersonName(name);
|
|
286
295
|
switch(field){
|
|
287
296
|
case 'firstName':
|
|
288
|
-
return
|
|
297
|
+
return parts.firstName;
|
|
289
298
|
case 'lastName':
|
|
290
|
-
return
|
|
299
|
+
return parts.lastName;
|
|
291
300
|
case 'name':
|
|
292
301
|
return name;
|
|
293
302
|
case 'email':
|
|
@@ -305,11 +314,19 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
305
314
|
{
|
|
306
315
|
const lead = context.lead;
|
|
307
316
|
if (!lead) return '';
|
|
317
|
+
/*
|
|
318
|
+
* The lead's own first and last names when it keeps them (AGL-3513),
|
|
319
|
+
* as the contact's are read; the name split at its first space when
|
|
320
|
+
* it keeps neither.
|
|
321
|
+
*/ const parts = text(lead['firstName']) || text(lead['lastName']) ? {
|
|
322
|
+
firstName: text(lead['firstName']),
|
|
323
|
+
lastName: text(lead['lastName'])
|
|
324
|
+
} : splitPersonName(lead['name']);
|
|
308
325
|
switch(field){
|
|
309
326
|
case 'firstName':
|
|
310
|
-
return
|
|
327
|
+
return parts.firstName;
|
|
311
328
|
case 'lastName':
|
|
312
|
-
return
|
|
329
|
+
return parts.lastName;
|
|
313
330
|
case 'name':
|
|
314
331
|
return text(lead['name']);
|
|
315
332
|
case 'email':
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/crm-email-templates.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 * EMAIL TEMPLATES, SNIPPETS AND MERGE FIELDS (AGL-2658).\n *\n * A one-to-one email is a letter, and a rep writes the same three letters\n * all week: the follow-up, the proposal cover note, the \"still keen?\". A\n * TEMPLATE is one of those letters kept under a name — a subject and a body\n * the dialog fills in whole. A SNIPPET is a paragraph kept under a name —\n * a signature block, a pricing line — inserted where the caret is. Both\n * carry MERGE FIELDS, `{{contact.firstName}}` and the like, which the send\n * route fills from the record the email is about, so a template written\n * once reads as a letter to each person it is sent to.\n *\n * ## One resolver, run twice\n *\n * The server resolves at send time, off the documents it has already read\n * to find the recipient, and what it writes to the timeline is the letter\n * as it left. The dialog runs the SAME resolver over the same documents to\n * show the rep what will go out, so the preview and the message cannot\n * disagree. The resolver is pure and lives here, beside the model, so\n * neither caller can drift into its own grammar.\n *\n * ## What a field with no value does\n *\n * It renders as nothing. A template that greets `{{contact.firstName}}` is\n * sent to a contact known only by email as \"Hi ,\" — which is why the dialog\n * counts the empty fields and says so before the rep clicks Send, and why\n * an unknown field name renders as nothing too rather than as its own\n * braces: a typo in a merge field must not reach a customer as `{{contct.\n * firstName}}`. Nothing is escaped, because the mail is plain text.\n *\n * ## Shared or personal\n *\n * A template is either the team's — every CRM editor may use and change it\n * — or one person's, listed for its owner alone. The rules gate the writes\n * (`cloud/firebase-firestore.rules`); the listing hides a colleague's\n * personal rows the way a private saved view is hidden (AGL-2617), because\n * a rule per reader would need a query per reader.\n *==========================================*/\n\nimport {\n contactDisplayName,\n normalizeContactEmail,\n readContactFacet,\n} from './contacts'\nimport { CRM_EMAIL_BODY_MAX, CRM_EMAIL_SUBJECT_MAX, type CrmScoped } from './crm'\n\n/** The most a template's name may hold. */\nexport const CRM_EMAIL_TEMPLATE_NAME_MAX = 80\n\n/**\n * The listing's window, and the ceiling the console's create respects.\n *\n * A LOOKUP rather than a list: the picker is a menu a rep opens, and two\n * hundred named letters for one workspace is past what anybody scrolls.\n * Bounded so the listen cannot grow with the org.\n */\nexport const CRM_EMAIL_TEMPLATES_LIMIT = 200\n\n/** A whole letter under a name, or a paragraph under one. */\nexport const CRM_EMAIL_TEMPLATE_KINDS = ['template', 'snippet'] as const\nexport type CrmEmailTemplateKind = (typeof CRM_EMAIL_TEMPLATE_KINDS)[number]\n\nexport const CRM_EMAIL_TEMPLATE_KIND_LABELS: Record<CrmEmailTemplateKind, string> = {\n template: 'Template',\n snippet: 'Snippet',\n}\n\nexport function isCrmEmailTemplateKind(value: unknown): value is CrmEmailTemplateKind {\n return (\n typeof value === 'string' &&\n (CRM_EMAIL_TEMPLATE_KINDS as readonly string[]).includes(value)\n )\n}\n\n/** The team's, or one person's. */\nexport const CRM_EMAIL_TEMPLATE_VISIBILITIES = ['shared', 'personal'] as const\nexport type CrmEmailTemplateVisibility = (typeof CRM_EMAIL_TEMPLATE_VISIBILITIES)[number]\n\nexport const CRM_EMAIL_TEMPLATE_VISIBILITY_LABELS: Record<CrmEmailTemplateVisibility, string> = {\n shared: 'Shared',\n personal: 'Personal',\n}\n\nexport function isCrmEmailTemplateVisibility(\n value: unknown,\n): value is CrmEmailTemplateVisibility {\n return (\n typeof value === 'string' &&\n (CRM_EMAIL_TEMPLATE_VISIBILITIES as readonly string[]).includes(value)\n )\n}\n\n/**\n * `orgs/{orgId}/crmEmailTemplates/{templateId}`.\n *\n * Scoped like a task (AGL-2637): under a site it carries that site's tokens\n * and `hostId`; written from the organization's own hub it carries the org\n * token and `hostId: null`, because a letter the whole workspace keeps is\n * not any one brand's. `ownerUid` is set on a personal template only, and\n * is the one member the listing shows it to.\n */\nexport interface CrmEmailTemplate extends Omit<CrmScoped, 'hostId'> {\n /** The site it was written under, or `null` for the organization's own. */\n hostId: string | null\n name: string\n /** The subject line a template fills in; `''` on a snippet. */\n subject: string\n /** Plain text, with merge fields — see {@link renderCrmMergeFields}. */\n body: string\n kind: CrmEmailTemplateKind\n visibility: CrmEmailTemplateVisibility\n /** The one member a personal template is listed for; absent on a shared one. */\n ownerUid?: string\n /** Who made it — `'api'` for a key, which has no uid. */\n createdByUid: string\n createdAtMs: number\n updatedAtMs: number\n}\n\n/** A template as a listener hands it back: the document plus its id. */\nexport type CrmEmailTemplateRow = CrmEmailTemplate & { $id: string }\n\n/**\n * Whether a template belongs in `uid`'s menu: every shared one, and the\n * personal ones they own. A colleague's personal template is readable under\n * the rules and hidden here — see the module header.\n */\nexport function crmEmailTemplateIsListed(\n template: Pick<CrmEmailTemplate, 'visibility' | 'ownerUid'>,\n uid: string | null | undefined,\n): boolean {\n if (template.visibility !== 'personal') return true\n return Boolean(uid) && template.ownerUid === uid\n}\n\nconst asText = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.slice(0, max) : ''\n\nconst asMs = (value: unknown): number =>\n typeof value === 'number' && Number.isFinite(value) ? value : 0\n\n/**\n * A stored document held to shape, for a listener that reads it raw.\n *\n * Lenient where the rules are not: a kind or a visibility the union does not\n * name reads as the default, because a row some other writer produced is\n * still a letter somebody kept, and dropping it from the menu would lose it.\n */\nexport function normalizeCrmEmailTemplate(\n row: Record<string, unknown> | null | undefined,\n): CrmEmailTemplate {\n const data = row ?? {}\n const visibility = isCrmEmailTemplateVisibility(data['visibility'])\n ? data['visibility']\n : 'shared'\n const ownerUid = asText(data['ownerUid'], 128)\n return {\n name: asText(data['name'], CRM_EMAIL_TEMPLATE_NAME_MAX).trim(),\n subject: asText(data['subject'], CRM_EMAIL_SUBJECT_MAX),\n body: asText(data['body'], CRM_EMAIL_BODY_MAX),\n kind: isCrmEmailTemplateKind(data['kind']) ? data['kind'] : 'template',\n visibility,\n ...(visibility === 'personal' && ownerUid ? { ownerUid } : {}),\n createdByUid: asText(data['createdByUid'], 128),\n createdAtMs: asMs(data['createdAtMs']),\n updatedAtMs: asMs(data['updatedAtMs']),\n hostId: typeof data['hostId'] === 'string' ? data['hostId'] : null,\n visibleTo: Array.isArray(data['visibleTo'])\n ? (data['visibleTo'] as unknown[]).map(String)\n : [],\n createdAt: data['createdAt'],\n updatedAt: data['updatedAt'],\n }\n}\n\n/*==========================================\n * MERGE FIELDS.\n *==========================================*/\n\n/** The group a field belongs to, as the picker headings it. */\nexport type CrmMergeFieldGroup = 'Contact' | 'Lead' | 'Deal' | 'You' | 'Site'\n\nexport interface CrmMergeFieldDefinition {\n key: string\n label: string\n group: CrmMergeFieldGroup\n}\n\n/**\n * Every field the resolver knows, in the order the picker offers them.\n *\n * A fixed list rather than a path into the document, because a merge field\n * is a promise about what a person will read: `contact.title` has to mean\n * the job title on every send, whatever the document happens to call it\n * this year, and a free path would let a template reach into a note or a\n * consent map.\n */\nexport const CRM_MERGE_FIELDS: readonly CrmMergeFieldDefinition[] = [\n { key: 'contact.firstName', label: 'First name', group: 'Contact' },\n { key: 'contact.lastName', label: 'Last name', group: 'Contact' },\n { key: 'contact.name', label: 'Full name', group: 'Contact' },\n { key: 'contact.email', label: 'Email address', group: 'Contact' },\n { key: 'contact.company', label: 'Company', group: 'Contact' },\n { key: 'contact.title', label: 'Job title', group: 'Contact' },\n { key: 'lead.firstName', label: 'First name', group: 'Lead' },\n { key: 'lead.lastName', label: 'Last name', group: 'Lead' },\n { key: 'lead.name', label: 'Full name', group: 'Lead' },\n { key: 'lead.email', label: 'Email address', group: 'Lead' },\n { key: 'lead.company', label: 'Company', group: 'Lead' },\n { key: 'lead.title', label: 'Job title', group: 'Lead' },\n { key: 'deal.name', label: 'Deal name', group: 'Deal' },\n { key: 'deal.amount', label: 'Deal amount', group: 'Deal' },\n { key: 'sender.firstName', label: 'Your first name', group: 'You' },\n { key: 'sender.name', label: 'Your name', group: 'You' },\n { key: 'sender.email', label: 'Your email address', group: 'You' },\n { key: 'site.name', label: 'Site name', group: 'Site' },\n]\n\n/** `{{key}}` — the one spelling the resolver reads and the picker inserts. */\nexport function crmMergeFieldToken(key: string): string {\n return `{{${key}}}`\n}\n\n/**\n * What the resolver reads from: the documents as they are stored, so the\n * send route hands over what it already read and the dialog what it\n * fetched for the preview, with no projection in between to drift.\n */\nexport interface CrmMergeContext {\n /** The contact document, `orgs/{orgId}/contacts/{id}`. */\n contact?: Record<string, unknown> | null\n /**\n * The holder group whose facet names the contact — the sending site's,\n * since a name, a job title and a company are one holder's knowledge of\n * a person (`readContactFacet`). The canonical name is the fallback.\n */\n contactGroupId?: string | null\n /** The lead document, `hosts/{hostId}/leads/{id}`. */\n lead?: Record<string, unknown> | null\n /** The deal document, `orgs/{orgId}/deals/{id}`. */\n deal?: Record<string, unknown> | null\n /** The person sending, as their token or session names them. */\n sender?: { name?: string | null; email?: string | null } | null\n /** The site the email leaves from. */\n site?: { name?: string | null } | null\n /**\n * Fields a caller brings from a record of its own, keyed by the whole\n * `group.field` name — a plugin's `enrollment.personalLine`, say.\n *\n * Read only for a group the resolver above does not know, so no caller can\n * change what `contact.email` means. The fixed list is a promise about what\n * a person will read, and this is where a caller that makes its own promise\n * keeps it: the value is passed as written, never looked up by path.\n */\n extra?: Readonly<Record<string, string | null | undefined>> | null\n}\n\nexport interface CrmMergeResult {\n /** The text with every field replaced — by its value, or by nothing. */\n text: string\n /** The fields that rendered as nothing, unique, in order of appearance. */\n unresolved: string[]\n}\n\n/*\n * `{{ group.field }}`, spaces allowed inside the braces because a rep will\n * type them. A single brace pair or a bare word is left alone: a letter may\n * legitimately contain braces.\n */\nconst MERGE_FIELD_PATTERN = /\\{\\{\\s*([A-Za-z][A-Za-z0-9]*\\.[A-Za-z][A-Za-z0-9]*)\\s*\\}\\}/g\n\n/** The merge fields a text names, unique, in order of first appearance. */\nexport function crmMergeFieldsIn(text: string): string[] {\n const seen = new Set<string>()\n const fields: string[] = []\n for (const match of String(text ?? '').matchAll(MERGE_FIELD_PATTERN)) {\n const key = match[1]\n if (seen.has(key)) continue\n seen.add(key)\n fields.push(key)\n }\n return fields\n}\n\nexport function hasCrmMergeFields(text: string): boolean {\n MERGE_FIELD_PATTERN.lastIndex = 0\n return MERGE_FIELD_PATTERN.test(String(text ?? ''))\n}\n\n/** A name as one string → its first word and the rest. */\nexport function splitPersonName(name: unknown): { firstName: string; lastName: string } {\n const words = String(name ?? '')\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n return {\n firstName: words[0] ?? '',\n lastName: words.slice(1).join(' '),\n }\n}\n\n/**\n * A deal's amount as a letter prints it.\n *\n * A fixed locale rather than the reader's, on purpose: the server has no\n * reader, and the preview has to print what the server will send. Cents\n * that are not a number render as nothing, so a deal with no value greets\n * nobody with \"$0.00\".\n */\nexport function formatCrmMergeAmount(cents: unknown, currency: unknown): string {\n if (typeof cents !== 'number' || !Number.isFinite(cents)) return ''\n const code = String(currency || 'usd').toUpperCase()\n const amount = cents / 100\n try {\n return new Intl.NumberFormat('en-US', { style: 'currency', currency: code }).format(amount)\n } catch {\n return `${amount.toFixed(2)} ${code}`\n }\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** One field's value from the context, or `''` for anything it cannot answer. */\nfunction resolveCrmMergeField(key: string, context: CrmMergeContext): string {\n const [group, field] = key.split('.')\n switch (group) {\n case 'contact': {\n const contact = context.contact\n if (!contact) return ''\n const groupId = text(context.contactGroupId)\n const facet = readContactFacet(contact, groupId)\n const name = groupId\n ? contactDisplayName(contact, groupId)\n : text(contact['name'])\n switch (field) {\n case 'firstName':\n return splitPersonName(name).firstName\n case 'lastName':\n return splitPersonName(name).lastName\n case 'name':\n return name\n case 'email':\n return normalizeContactEmail(contact['email']) ?? ''\n case 'company':\n return text(facet.companyName)\n case 'title':\n return text(facet.jobTitle)\n default:\n return ''\n }\n }\n case 'lead': {\n const lead = context.lead\n if (!lead) return ''\n switch (field) {\n case 'firstName':\n return splitPersonName(lead['name']).firstName\n case 'lastName':\n return splitPersonName(lead['name']).lastName\n case 'name':\n return text(lead['name'])\n case 'email':\n return normalizeContactEmail(lead['email']) ?? ''\n // The lead's own profile (AGL-3231): the company as text, the title.\n case 'company':\n return text(lead['company'])\n case 'title':\n return text(lead['jobTitle'])\n default:\n return ''\n }\n }\n case 'deal': {\n const deal = context.deal\n if (!deal) return ''\n switch (field) {\n case 'name':\n return text(deal['title'])\n case 'amount':\n return formatCrmMergeAmount(deal['amountCents'], deal['currency'])\n default:\n return ''\n }\n }\n case 'sender': {\n const sender = context.sender\n if (!sender) return ''\n switch (field) {\n case 'firstName':\n return splitPersonName(sender.name).firstName\n case 'name':\n return text(sender.name)\n case 'email':\n return normalizeContactEmail(sender.email) ?? ''\n default:\n return ''\n }\n }\n case 'site':\n return field === 'name' ? text(context.site?.name) : ''\n default: {\n const extra = context.extra\n return extra && Object.prototype.hasOwnProperty.call(extra, key)\n ? text(extra[key])\n : ''\n }\n }\n}\n\n/**\n * Every merge field in `text` replaced from `context`, and the ones that\n * had nothing to say. Pure, and never throws: a missing record, an unknown\n * field, a malformed context each render as nothing and are named in\n * `unresolved`.\n */\nexport function resolveCrmMergeFields(\n text: string,\n context: CrmMergeContext | null | undefined,\n): CrmMergeResult {\n const source = String(text ?? '')\n const ctx = context ?? {}\n const unresolved = new Set<string>()\n const rendered = source.replace(MERGE_FIELD_PATTERN, (_match, key: string) => {\n const value = resolveCrmMergeField(key, ctx)\n if (!value) unresolved.add(key)\n return value\n })\n return { text: rendered, unresolved: [...unresolved] }\n}\n\n/** {@link resolveCrmMergeFields}, text alone — what the send route sends. */\nexport function renderCrmMergeFields(\n text: string,\n context: CrmMergeContext | null | undefined,\n): string {\n return resolveCrmMergeFields(text, context).text\n}\n\n/** What the dialog says under a draft whose fields have nothing to fill. */\nexport function crmMergeUnresolvedMessage(unresolved: readonly string[]): string {\n if (unresolved.length === 0) return ''\n const count = unresolved.length\n const noun = count === 1 ? '1 field has no value' : `${count} fields have no value`\n return `${noun}: ${unresolved.map(crmMergeFieldToken).join(', ')}`\n}\n"],"names":["contactDisplayName","normalizeContactEmail","readContactFacet","CRM_EMAIL_BODY_MAX","CRM_EMAIL_SUBJECT_MAX","CRM_EMAIL_TEMPLATE_NAME_MAX","CRM_EMAIL_TEMPLATES_LIMIT","CRM_EMAIL_TEMPLATE_KINDS","CRM_EMAIL_TEMPLATE_KIND_LABELS","template","snippet","isCrmEmailTemplateKind","value","includes","CRM_EMAIL_TEMPLATE_VISIBILITIES","CRM_EMAIL_TEMPLATE_VISIBILITY_LABELS","shared","personal","isCrmEmailTemplateVisibility","crmEmailTemplateIsListed","uid","visibility","Boolean","ownerUid","asText","max","slice","asMs","Number","isFinite","normalizeCrmEmailTemplate","row","data","name","trim","subject","body","kind","createdByUid","createdAtMs","updatedAtMs","hostId","visibleTo","Array","isArray","map","String","createdAt","updatedAt","CRM_MERGE_FIELDS","key","label","group","crmMergeFieldToken","MERGE_FIELD_PATTERN","crmMergeFieldsIn","text","seen","Set","fields","match","matchAll","has","add","push","hasCrmMergeFields","lastIndex","test","splitPersonName","words","split","filter","firstName","lastName","join","formatCrmMergeAmount","cents","currency","code","toUpperCase","amount","Intl","NumberFormat","style","format","toFixed","resolveCrmMergeField","context","field","contact","groupId","contactGroupId","facet","companyName","jobTitle","lead","deal","sender","email","site","extra","Object","prototype","hasOwnProperty","call","resolveCrmMergeFields","source","ctx","unresolved","rendered","replace","_match","renderCrmMergeFields","crmMergeUnresolvedMessage","length","count","noun"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAqC4C,GAE5C,SACEA,kBAAkB,EAClBC,qBAAqB,EACrBC,gBAAgB,QACX,gBAAY;AACnB,SAASC,kBAAkB,EAAEC,qBAAqB,QAAwB,WAAO;AAEjF,yCAAyC,GACzC,OAAO,MAAMC,8BAA8B,GAAE;AAE7C;;;;;;CAMC,GACD,OAAO,MAAMC,4BAA4B,IAAG;AAE5C,2DAA2D,GAC3D,OAAO,MAAMC,2BAA2B;IAAC;IAAY;CAAU,CAAS;AAGxE,OAAO,MAAMC,iCAAuE;IAClFC,UAAU;IACVC,SAAS;AACX,EAAC;AAED,OAAO,SAASC,uBAAuBC,KAAc;IACnD,OACE,OAAOA,UAAU,YACjB,AAACL,yBAA+CM,QAAQ,CAACD;AAE7D;AAEA,iCAAiC,GACjC,OAAO,MAAME,kCAAkC;IAAC;IAAU;CAAW,CAAS;AAG9E,OAAO,MAAMC,uCAAmF;IAC9FC,QAAQ;IACRC,UAAU;AACZ,EAAC;AAED,OAAO,SAASC,6BACdN,KAAc;IAEd,OACE,OAAOA,UAAU,YACjB,AAACE,gCAAsDD,QAAQ,CAACD;AAEpE;AAgCA;;;;CAIC,GACD,OAAO,SAASO,yBACdV,QAA2D,EAC3DW,GAA8B;IAE9B,IAAIX,SAASY,UAAU,KAAK,YAAY,OAAO;IAC/C,OAAOC,QAAQF,QAAQX,SAASc,QAAQ,KAAKH;AAC/C;AAEA,MAAMI,SAAS,CAACZ,OAAgBa,MAC9B,OAAOb,UAAU,WAAWA,MAAMc,KAAK,CAAC,GAAGD,OAAO;AAEpD,MAAME,OAAO,CAACf,QACZ,OAAOA,UAAU,YA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,0BAA0BL,UAA6B;IACrE,IAAIA,WAAWM,MAAM,KAAK,GAAG,OAAO;IACpC,MAAMC,QAAQP,WAAWM,MAAM;IAC/B,MAAME,OAAOD,UAAU,IAAI,yBAAyB,GAAGA,MAAM,qBAAqB,CAAC;IACnF,OAAO,GAAGC,KAAK,EAAE,EAAER,WAAW/D,GAAG,CAACQ,oBAAoBqB,IAAI,CAAC,OAAO;AACpE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/crm-email-templates.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 * EMAIL TEMPLATES, SNIPPETS AND MERGE FIELDS (AGL-2658).\n *\n * A one-to-one email is a letter, and a rep writes the same three letters\n * all week: the follow-up, the proposal cover note, the \"still keen?\". A\n * TEMPLATE is one of those letters kept under a name — a subject and a body\n * the dialog fills in whole. A SNIPPET is a paragraph kept under a name —\n * a signature block, a pricing line — inserted where the caret is. Both\n * carry MERGE FIELDS, `{{contact.firstName}}` and the like, which the send\n * route fills from the record the email is about, so a template written\n * once reads as a letter to each person it is sent to.\n *\n * ## One resolver, run twice\n *\n * The server resolves at send time, off the documents it has already read\n * to find the recipient, and what it writes to the timeline is the letter\n * as it left. The dialog runs the SAME resolver over the same documents to\n * show the rep what will go out, so the preview and the message cannot\n * disagree. The resolver is pure and lives here, beside the model, so\n * neither caller can drift into its own grammar.\n *\n * ## What a field with no value does\n *\n * It renders as nothing. A template that greets `{{contact.firstName}}` is\n * sent to a contact known only by email as \"Hi ,\" — which is why the dialog\n * counts the empty fields and says so before the rep clicks Send, and why\n * an unknown field name renders as nothing too rather than as its own\n * braces: a typo in a merge field must not reach a customer as `{{contct.\n * firstName}}`. Nothing is escaped, because the mail is plain text.\n *\n * ## Shared or personal\n *\n * A template is either the team's — every CRM editor may use and change it\n * — or one person's, listed for its owner alone. The rules gate the writes\n * (`cloud/firebase-firestore.rules`); the listing hides a colleague's\n * personal rows the way a private saved view is hidden (AGL-2617), because\n * a rule per reader would need a query per reader.\n *==========================================*/\n\nimport {\n contactDisplayName,\n normalizeContactEmail,\n readContactFacet,\n} from './contacts'\nimport { CRM_EMAIL_BODY_MAX, CRM_EMAIL_SUBJECT_MAX, type CrmScoped } from './crm'\n\n/** The most a template's name may hold. */\nexport const CRM_EMAIL_TEMPLATE_NAME_MAX = 80\n\n/**\n * The listing's window, and the ceiling the console's create respects.\n *\n * A LOOKUP rather than a list: the picker is a menu a rep opens, and two\n * hundred named letters for one workspace is past what anybody scrolls.\n * Bounded so the listen cannot grow with the org.\n */\nexport const CRM_EMAIL_TEMPLATES_LIMIT = 200\n\n/** A whole letter under a name, or a paragraph under one. */\nexport const CRM_EMAIL_TEMPLATE_KINDS = ['template', 'snippet'] as const\nexport type CrmEmailTemplateKind = (typeof CRM_EMAIL_TEMPLATE_KINDS)[number]\n\nexport const CRM_EMAIL_TEMPLATE_KIND_LABELS: Record<CrmEmailTemplateKind, string> = {\n template: 'Template',\n snippet: 'Snippet',\n}\n\nexport function isCrmEmailTemplateKind(value: unknown): value is CrmEmailTemplateKind {\n return (\n typeof value === 'string' &&\n (CRM_EMAIL_TEMPLATE_KINDS as readonly string[]).includes(value)\n )\n}\n\n/** The team's, or one person's. */\nexport const CRM_EMAIL_TEMPLATE_VISIBILITIES = ['shared', 'personal'] as const\nexport type CrmEmailTemplateVisibility = (typeof CRM_EMAIL_TEMPLATE_VISIBILITIES)[number]\n\nexport const CRM_EMAIL_TEMPLATE_VISIBILITY_LABELS: Record<CrmEmailTemplateVisibility, string> = {\n shared: 'Shared',\n personal: 'Personal',\n}\n\nexport function isCrmEmailTemplateVisibility(\n value: unknown,\n): value is CrmEmailTemplateVisibility {\n return (\n typeof value === 'string' &&\n (CRM_EMAIL_TEMPLATE_VISIBILITIES as readonly string[]).includes(value)\n )\n}\n\n/**\n * `orgs/{orgId}/crmEmailTemplates/{templateId}`.\n *\n * Scoped like a task (AGL-2637): under a site it carries that site's tokens\n * and `hostId`; written from the organization's own hub it carries the org\n * token and `hostId: null`, because a letter the whole workspace keeps is\n * not any one brand's. `ownerUid` is set on a personal template only, and\n * is the one member the listing shows it to.\n */\nexport interface CrmEmailTemplate extends Omit<CrmScoped, 'hostId'> {\n /** The site it was written under, or `null` for the organization's own. */\n hostId: string | null\n name: string\n /** The subject line a template fills in; `''` on a snippet. */\n subject: string\n /** Plain text, with merge fields — see {@link renderCrmMergeFields}. */\n body: string\n kind: CrmEmailTemplateKind\n visibility: CrmEmailTemplateVisibility\n /** The one member a personal template is listed for; absent on a shared one. */\n ownerUid?: string\n /** Who made it — `'api'` for a key, which has no uid. */\n createdByUid: string\n createdAtMs: number\n updatedAtMs: number\n}\n\n/** A template as a listener hands it back: the document plus its id. */\nexport type CrmEmailTemplateRow = CrmEmailTemplate & { $id: string }\n\n/**\n * Whether a template belongs in `uid`'s menu: every shared one, and the\n * personal ones they own. A colleague's personal template is readable under\n * the rules and hidden here — see the module header.\n */\nexport function crmEmailTemplateIsListed(\n template: Pick<CrmEmailTemplate, 'visibility' | 'ownerUid'>,\n uid: string | null | undefined,\n): boolean {\n if (template.visibility !== 'personal') return true\n return Boolean(uid) && template.ownerUid === uid\n}\n\nconst asText = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.slice(0, max) : ''\n\nconst asMs = (value: unknown): number =>\n typeof value === 'number' && Number.isFinite(value) ? value : 0\n\n/**\n * A stored document held to shape, for a listener that reads it raw.\n *\n * Lenient where the rules are not: a kind or a visibility the union does not\n * name reads as the default, because a row some other writer produced is\n * still a letter somebody kept, and dropping it from the menu would lose it.\n */\nexport function normalizeCrmEmailTemplate(\n row: Record<string, unknown> | null | undefined,\n): CrmEmailTemplate {\n const data = row ?? {}\n const visibility = isCrmEmailTemplateVisibility(data['visibility'])\n ? data['visibility']\n : 'shared'\n const ownerUid = asText(data['ownerUid'], 128)\n return {\n name: asText(data['name'], CRM_EMAIL_TEMPLATE_NAME_MAX).trim(),\n subject: asText(data['subject'], CRM_EMAIL_SUBJECT_MAX),\n body: asText(data['body'], CRM_EMAIL_BODY_MAX),\n kind: isCrmEmailTemplateKind(data['kind']) ? data['kind'] : 'template',\n visibility,\n ...(visibility === 'personal' && ownerUid ? { ownerUid } : {}),\n createdByUid: asText(data['createdByUid'], 128),\n createdAtMs: asMs(data['createdAtMs']),\n updatedAtMs: asMs(data['updatedAtMs']),\n hostId: typeof data['hostId'] === 'string' ? data['hostId'] : null,\n visibleTo: Array.isArray(data['visibleTo'])\n ? (data['visibleTo'] as unknown[]).map(String)\n : [],\n createdAt: data['createdAt'],\n updatedAt: data['updatedAt'],\n }\n}\n\n/*==========================================\n * MERGE FIELDS.\n *==========================================*/\n\n/** The group a field belongs to, as the picker headings it. */\nexport type CrmMergeFieldGroup = 'Contact' | 'Lead' | 'Deal' | 'You' | 'Site'\n\nexport interface CrmMergeFieldDefinition {\n key: string\n label: string\n group: CrmMergeFieldGroup\n}\n\n/**\n * Every field the resolver knows, in the order the picker offers them.\n *\n * A fixed list rather than a path into the document, because a merge field\n * is a promise about what a person will read: `contact.title` has to mean\n * the job title on every send, whatever the document happens to call it\n * this year, and a free path would let a template reach into a note or a\n * consent map.\n */\nexport const CRM_MERGE_FIELDS: readonly CrmMergeFieldDefinition[] = [\n { key: 'contact.firstName', label: 'First name', group: 'Contact' },\n { key: 'contact.lastName', label: 'Last name', group: 'Contact' },\n { key: 'contact.name', label: 'Full name', group: 'Contact' },\n { key: 'contact.email', label: 'Email address', group: 'Contact' },\n { key: 'contact.company', label: 'Company', group: 'Contact' },\n { key: 'contact.title', label: 'Job title', group: 'Contact' },\n { key: 'lead.firstName', label: 'First name', group: 'Lead' },\n { key: 'lead.lastName', label: 'Last name', group: 'Lead' },\n { key: 'lead.name', label: 'Full name', group: 'Lead' },\n { key: 'lead.email', label: 'Email address', group: 'Lead' },\n { key: 'lead.company', label: 'Company', group: 'Lead' },\n { key: 'lead.title', label: 'Job title', group: 'Lead' },\n { key: 'deal.name', label: 'Deal name', group: 'Deal' },\n { key: 'deal.amount', label: 'Deal amount', group: 'Deal' },\n { key: 'sender.firstName', label: 'Your first name', group: 'You' },\n { key: 'sender.name', label: 'Your name', group: 'You' },\n { key: 'sender.email', label: 'Your email address', group: 'You' },\n { key: 'site.name', label: 'Site name', group: 'Site' },\n]\n\n/** `{{key}}` — the one spelling the resolver reads and the picker inserts. */\nexport function crmMergeFieldToken(key: string): string {\n return `{{${key}}}`\n}\n\n/**\n * What the resolver reads from: the documents as they are stored, so the\n * send route hands over what it already read and the dialog what it\n * fetched for the preview, with no projection in between to drift.\n */\nexport interface CrmMergeContext {\n /** The contact document, `orgs/{orgId}/contacts/{id}`. */\n contact?: Record<string, unknown> | null\n /**\n * The holder group whose facet names the contact — the sending site's,\n * since a name, a job title and a company are one holder's knowledge of\n * a person (`readContactFacet`). The canonical name is the fallback.\n */\n contactGroupId?: string | null\n /** The lead document, `hosts/{hostId}/leads/{id}`. */\n lead?: Record<string, unknown> | null\n /** The deal document, `orgs/{orgId}/deals/{id}`. */\n deal?: Record<string, unknown> | null\n /** The person sending, as their token or session names them. */\n sender?: { name?: string | null; email?: string | null } | null\n /** The site the email leaves from. */\n site?: { name?: string | null } | null\n /**\n * Fields a caller brings from a record of its own, keyed by the whole\n * `group.field` name — a plugin's `enrollment.personalLine`, say.\n *\n * Read only for a group the resolver above does not know, so no caller can\n * change what `contact.email` means. The fixed list is a promise about what\n * a person will read, and this is where a caller that makes its own promise\n * keeps it: the value is passed as written, never looked up by path.\n */\n extra?: Readonly<Record<string, string | null | undefined>> | null\n}\n\nexport interface CrmMergeResult {\n /** The text with every field replaced — by its value, or by nothing. */\n text: string\n /** The fields that rendered as nothing, unique, in order of appearance. */\n unresolved: string[]\n}\n\n/*\n * `{{ group.field }}`, spaces allowed inside the braces because a rep will\n * type them. A single brace pair or a bare word is left alone: a letter may\n * legitimately contain braces.\n */\nconst MERGE_FIELD_PATTERN = /\\{\\{\\s*([A-Za-z][A-Za-z0-9]*\\.[A-Za-z][A-Za-z0-9]*)\\s*\\}\\}/g\n\n/** The merge fields a text names, unique, in order of first appearance. */\nexport function crmMergeFieldsIn(text: string): string[] {\n const seen = new Set<string>()\n const fields: string[] = []\n for (const match of String(text ?? '').matchAll(MERGE_FIELD_PATTERN)) {\n const key = match[1]\n if (seen.has(key)) continue\n seen.add(key)\n fields.push(key)\n }\n return fields\n}\n\nexport function hasCrmMergeFields(text: string): boolean {\n MERGE_FIELD_PATTERN.lastIndex = 0\n return MERGE_FIELD_PATTERN.test(String(text ?? ''))\n}\n\n/** A name as one string → its first word and the rest. */\nexport function splitPersonName(name: unknown): { firstName: string; lastName: string } {\n const words = String(name ?? '')\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n return {\n firstName: words[0] ?? '',\n lastName: words.slice(1).join(' '),\n }\n}\n\n/**\n * A deal's amount as a letter prints it.\n *\n * A fixed locale rather than the reader's, on purpose: the server has no\n * reader, and the preview has to print what the server will send. Cents\n * that are not a number render as nothing, so a deal with no value greets\n * nobody with \"$0.00\".\n */\nexport function formatCrmMergeAmount(cents: unknown, currency: unknown): string {\n if (typeof cents !== 'number' || !Number.isFinite(cents)) return ''\n const code = String(currency || 'usd').toUpperCase()\n const amount = cents / 100\n try {\n return new Intl.NumberFormat('en-US', { style: 'currency', currency: code }).format(amount)\n } catch {\n return `${amount.toFixed(2)} ${code}`\n }\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** One field's value from the context, or `''` for anything it cannot answer. */\nfunction resolveCrmMergeField(key: string, context: CrmMergeContext): string {\n const [group, field] = key.split('.')\n switch (group) {\n case 'contact': {\n const contact = context.contact\n if (!contact) return ''\n const groupId = text(context.contactGroupId)\n const facet = readContactFacet(contact, groupId)\n const name = groupId\n ? contactDisplayName(contact, groupId)\n : text(contact['name'])\n /*\n * The holder's own first and last names when it keeps them (AGL-3515)\n * — a two-word first name or a particle in a surname is then what the\n * person wrote — and the display name split at its first space when\n * it keeps neither.\n */\n const parts =\n text(facet.firstName) || text(facet.lastName)\n ? { firstName: text(facet.firstName), lastName: text(facet.lastName) }\n : splitPersonName(name)\n switch (field) {\n case 'firstName':\n return parts.firstName\n case 'lastName':\n return parts.lastName\n case 'name':\n return name\n case 'email':\n return normalizeContactEmail(contact['email']) ?? ''\n case 'company':\n return text(facet.companyName)\n case 'title':\n return text(facet.jobTitle)\n default:\n return ''\n }\n }\n case 'lead': {\n const lead = context.lead\n if (!lead) return ''\n /*\n * The lead's own first and last names when it keeps them (AGL-3513),\n * as the contact's are read; the name split at its first space when\n * it keeps neither.\n */\n const parts =\n text(lead['firstName']) || text(lead['lastName'])\n ? { firstName: text(lead['firstName']), lastName: text(lead['lastName']) }\n : splitPersonName(lead['name'])\n switch (field) {\n case 'firstName':\n return parts.firstName\n case 'lastName':\n return parts.lastName\n case 'name':\n return text(lead['name'])\n case 'email':\n return normalizeContactEmail(lead['email']) ?? ''\n // The lead's own profile (AGL-3231): the company as text, the title.\n case 'company':\n return text(lead['company'])\n case 'title':\n return text(lead['jobTitle'])\n default:\n return ''\n }\n }\n case 'deal': {\n const deal = context.deal\n if (!deal) return ''\n switch (field) {\n case 'name':\n return text(deal['title'])\n case 'amount':\n return formatCrmMergeAmount(deal['amountCents'], deal['currency'])\n default:\n return ''\n }\n }\n case 'sender': {\n const sender = context.sender\n if (!sender) return ''\n switch (field) {\n case 'firstName':\n return splitPersonName(sender.name).firstName\n case 'name':\n return text(sender.name)\n case 'email':\n return normalizeContactEmail(sender.email) ?? ''\n default:\n return ''\n }\n }\n case 'site':\n return field === 'name' ? text(context.site?.name) : ''\n default: {\n const extra = context.extra\n return extra && Object.prototype.hasOwnProperty.call(extra, key)\n ? text(extra[key])\n : ''\n }\n }\n}\n\n/**\n * Every merge field in `text` replaced from `context`, and the ones that\n * had nothing to say. Pure, and never throws: a missing record, an unknown\n * field, a malformed context each render as nothing and are named in\n * `unresolved`.\n */\nexport function resolveCrmMergeFields(\n text: string,\n context: CrmMergeContext | null | undefined,\n): CrmMergeResult {\n const source = String(text ?? '')\n const ctx = context ?? {}\n const unresolved = new Set<string>()\n const rendered = source.replace(MERGE_FIELD_PATTERN, (_match, key: string) => {\n const value = resolveCrmMergeField(key, ctx)\n if (!value) unresolved.add(key)\n return value\n })\n return { text: rendered, unresolved: [...unresolved] }\n}\n\n/** {@link resolveCrmMergeFields}, text alone — what the send route sends. */\nexport function renderCrmMergeFields(\n text: string,\n context: CrmMergeContext | null | undefined,\n): string {\n return resolveCrmMergeFields(text, context).text\n}\n\n/** What the dialog says under a draft whose fields have nothing to fill. */\nexport function crmMergeUnresolvedMessage(unresolved: readonly string[]): string {\n if (unresolved.length === 0) return ''\n const count = unresolved.length\n const noun = count === 1 ? '1 field has no value' : `${count} fields have no value`\n return `${noun}: ${unresolved.map(crmMergeFieldToken).join(', ')}`\n}\n"],"names":["contactDisplayName","normalizeContactEmail","readContactFacet","CRM_EMAIL_BODY_MAX","CRM_EMAIL_SUBJECT_MAX","CRM_EMAIL_TEMPLATE_NAME_MAX","CRM_EMAIL_TEMPLATES_LIMIT","CRM_EMAIL_TEMPLATE_KINDS","CRM_EMAIL_TEMPLATE_KIND_LABELS","template","snippet","isCrmEmailTemplateKind","value","includes","CRM_EMAIL_TEMPLATE_VISIBILITIES","CRM_EMAIL_TEMPLATE_VISIBILITY_LABELS","shared","personal","isCrmEmailTemplateVisibility","crmEmailTemplateIsListed","uid","visibility","Boolean","ownerUid","asText","max","slice","asMs","Number","isFinite","normalizeCrmEmailTemplate","row","data","name","trim","subject","body","kind","createdByUid","createdAtMs","updatedAtMs","hostId","visibleTo","Array","isArray","map","String","createdAt","updatedAt","CRM_MERGE_FIELDS","key","label","group","crmMergeFieldToken","MERGE_FIELD_PATTERN","crmMergeFieldsIn","text","seen","Set","fields","match","matchAll","has","add","push","hasCrmMergeFields","lastIndex","test","splitPersonName","words","split","filter","firstName","lastName","join","formatCrmMergeAmount","cents","currency","code","toUpperCase","amount","Intl","NumberFormat","style","format","toFixed","resolveCrmMergeField","context","field","contact","groupId","contactGroupId","facet","parts","companyName","jobTitle","lead","deal","sender","email","site","extra","Object","prototype","hasOwnProperty","call","resolveCrmMergeFields","source","ctx","unresolved","rendered","replace","_match","renderCrmMergeFields","crmMergeUnresolvedMessage","length","count","noun"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAqC4C,GAE5C,SACEA,kBAAkB,EAClBC,qBAAqB,EACrBC,gBAAgB,QACX,gBAAY;AACnB,SAASC,kBAAkB,EAAEC,qBAAqB,QAAwB,WAAO;AAEjF,yCAAyC,GACzC,OAAO,MAAMC,8BAA8B,GAAE;AAE7C;;;;;;CAMC,GACD,OAAO,MAAMC,4BAA4B,IAAG;AAE5C,2DAA2D,GAC3D,OAAO,MAAMC,2BAA2B;IAAC;IAAY;CAAU,CAAS;AAGxE,OAAO,MAAMC,iCAAuE;IAClFC,UAAU;IACVC,SAAS;AACX,EAAC;AAED,OAAO,SAASC,uBAAuBC,KAAc;IACnD,OACE,OAAOA,UAAU,YACjB,AAACL,yBAA+CM,QAAQ,CAACD;AAE7D;AAEA,iCAAiC,GACjC,OAAO,MAAME,kCAAkC;IAAC;IAAU;CAAW,CAAS;AAG9E,OAAO,MAAMC,uCAAmF;IAC9FC,QAAQ;IACRC,UAAU;AACZ,EAAC;AAED,OAAO,SAASC,6BACdN,KAAc;IAEd,OACE,OAAOA,UAAU,YACjB,AAACE,gCAAsDD,QAAQ,CAACD;AAEpE;AAgCA;;;;CAIC,GACD,OAAO,SAASO,yBACdV,QAA2D,EAC3DW,GAA8B;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ACN;IACF;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASwD,sBACdlD,IAAY,EACZ+B,OAA2C;IAE3C,MAAMoB,SAAS7D,OAAOU,eAAAA,OAAQ;IAC9B,MAAMoD,MAAMrB,kBAAAA,UAAW,CAAC;IACxB,MAAMsB,aAAa,IAAInD;IACvB,MAAMoD,WAAWH,OAAOI,OAAO,CAACzD,qBAAqB,CAAC0D,QAAQ9D;QAC5D,MAAMtC,QAAQ0E,qBAAqBpC,KAAK0D;QACxC,IAAI,CAAChG,OAAOiG,WAAW9C,GAAG,CAACb;QAC3B,OAAOtC;IACT;IACA,OAAO;QAAE4C,MAAMsD;QAAUD,YAAY;eAAIA;SAAW;IAAC;AACvD;AAEA,2EAA2E,GAC3E,OAAO,SAASI,qBACdzD,IAAY,EACZ+B,OAA2C;IAE3C,OAAOmB,sBAAsBlD,MAAM+B,SAAS/B,IAAI;AAClD;AAEA,0EAA0E,GAC1E,OAAO,SAAS0D,0BAA0BL,UAA6B;IACrE,IAAIA,WAAWM,MAAM,KAAK,GAAG,OAAO;IACpC,MAAMC,QAAQP,WAAWM,MAAM;IAC/B,MAAME,OAAOD,UAAU,IAAI,yBAAyB,GAAGA,MAAM,qBAAqB,CAAC;IACnF,OAAO,GAAGC,KAAK,EAAE,EAAER,WAAWhE,GAAG,CAACQ,oBAAoBqB,IAAI,CAAC,OAAO;AACpE"}
|
|
@@ -59,6 +59,8 @@ export declare function isCrmTaskKind(value: unknown): value is CrmTaskKind;
|
|
|
59
59
|
* nobody will find on the list when it comes due.
|
|
60
60
|
*/
|
|
61
61
|
export declare const CRM_TASK_MAX_DUE_DAYS = 365;
|
|
62
|
+
/** Longest tag an automation may write — the console's own tag field cap. */
|
|
63
|
+
export declare const CONTACT_TAG_MAX_LENGTH = 60;
|
|
62
64
|
/**
|
|
63
65
|
* What a person can log, in the order the picker offers them (AGL-2600).
|
|
64
66
|
*
|
|
@@ -70,6 +70,7 @@ export function isCrmTaskKind(value) {
|
|
|
70
70
|
* an annual renewal check, and a task dated further out than that is one
|
|
71
71
|
* nobody will find on the list when it comes due.
|
|
72
72
|
*/ export const CRM_TASK_MAX_DUE_DAYS = 365;
|
|
73
|
+
/** Longest tag an automation may write — the console's own tag field cap. */ export const CONTACT_TAG_MAX_LENGTH = 60;
|
|
73
74
|
/**
|
|
74
75
|
* What a person can log, in the order the picker offers them (AGL-2600).
|
|
75
76
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/crm-kinds.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 * The CRM's fixed vocabularies — lifecycle stages, task kinds, activity\n * kinds — and the guards that check a value against them.\n *\n * A leaf module with no imports, re-exported by `crm.ts`, so every existing\n * `crm` import keeps working. It is separate because the actions builder\n * validates an automation step against these lists, and the actions builder\n * ships with the element renderer to every published page: importing them\n * from `crm.ts` put the whole CRM record model — companies, deals, tasks,\n * the contact facet helpers it reads — in front of every visitor to check a\n * string against a four-item list.\n *\n * Only the lists, their types, their guards and the task horizon live here.\n * The on-screen labels stay in `crm.ts`, beside the records they describe.\n */\n\n/**\n * Where a person sits in the relationship, as one of a fixed list.\n *\n * A fixed list rather than free text so that a report can count people per\n * stage and a filter can select one, and in the order a person usually moves\n * through them so a picker reads as a progression. `other` is the escape\n * hatch for a business whose funnel has a step none of these name; it is a\n * deliberate stage, not an absent one.\n */\nexport const CONTACT_LIFECYCLE_STAGES = [\n 'subscriber',\n 'lead',\n 'marketing-qualified',\n 'sales-qualified',\n 'opportunity',\n 'customer',\n 'evangelist',\n 'other',\n] as const\n\nexport type ContactLifecycleStage = (typeof CONTACT_LIFECYCLE_STAGES)[number]\n\nexport function isContactLifecycleStage(\n value: unknown,\n): value is ContactLifecycleStage {\n return (\n typeof value === 'string' &&\n (CONTACT_LIFECYCLE_STAGES as readonly string[]).includes(value)\n )\n}\n\n/**\n * What a task is, as a fixed list.\n *\n * A const array rather than a bare union because two surfaces have to\n * enumerate it — the task form's picker and the automation step that creates\n * a task without a form — and a union cannot be iterated at run time.\n */\nexport const CRM_TASK_KINDS = ['call', 'email', 'meeting', 'todo'] as const\nexport type CrmTaskKind = (typeof CRM_TASK_KINDS)[number]\n\nexport function isCrmTaskKind(value: unknown): value is CrmTaskKind {\n return (\n typeof value === 'string' &&\n (CRM_TASK_KINDS as readonly string[]).includes(value)\n )\n}\n\n/**\n * How far ahead an automation may date a task, in days.\n *\n * A year, because the longest follow-up anybody schedules from a trigger is\n * an annual renewal check, and a task dated further out than that is one\n * nobody will find on the list when it comes due.\n */\nexport const CRM_TASK_MAX_DUE_DAYS = 365\n\n/**\n * What a person can log, in the order the picker offers them (AGL-2600).\n *\n * A fixed list rather than free text for the reason the lifecycle stages are\n * one: a report counts calls per week and a filter selects meetings, and\n * neither can be done over a string somebody typed. `note` is the plain\n * entry — something worth writing down that was not a conversation — and\n * `other` the escape hatch for the kind none of these name.\n */\nexport const CRM_ACTIVITY_KINDS = ['call', 'email', 'meeting', 'note', 'other'] as const\n\nexport type CrmActivityKind = (typeof CRM_ACTIVITY_KINDS)[number]\n\nexport function isCrmActivityKind(value: unknown): value is CrmActivityKind {\n return (\n typeof value === 'string' &&\n (CRM_ACTIVITY_KINDS as readonly string[]).includes(value)\n )\n}\n"],"names":["CONTACT_LIFECYCLE_STAGES","isContactLifecycleStage","value","includes","CRM_TASK_KINDS","isCrmTaskKind","CRM_TASK_MAX_DUE_DAYS","CRM_ACTIVITY_KINDS","isCrmActivityKind"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED;;;;;;;;CAQC,GACD,OAAO,MAAMA,2BAA2B;IACtC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAIV,OAAO,SAASC,wBACdC,KAAc;IAEd,OACE,OAAOA,UAAU,YACjB,AAACF,yBAA+CG,QAAQ,CAACD;AAE7D;AAEA;;;;;;CAMC,GACD,OAAO,MAAME,iBAAiB;IAAC;IAAQ;IAAS;IAAW;CAAO,CAAS;AAG3E,OAAO,SAASC,cAAcH,KAAc;IAC1C,OACE,OAAOA,UAAU,YACjB,AAACE,eAAqCD,QAAQ,CAACD;AAEnD;AAEA;;;;;;CAMC,GACD,OAAO,MAAMI,wBAAwB,IAAG;AAExC;;;;;;;;CAQC,GACD,OAAO,MAAMC,qBAAqB;IAAC;IAAQ;IAAS;IAAW;IAAQ;CAAQ,CAAS;AAIxF,OAAO,SAASC,
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/crm-kinds.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 * The CRM's fixed vocabularies — lifecycle stages, task kinds, activity\n * kinds — and the guards that check a value against them.\n *\n * A leaf module with no imports, re-exported by `crm.ts`, so every existing\n * `crm` import keeps working. It is separate because the actions builder\n * validates an automation step against these lists, and the actions builder\n * ships with the element renderer to every published page: importing them\n * from `crm.ts` put the whole CRM record model — companies, deals, tasks,\n * the contact facet helpers it reads — in front of every visitor to check a\n * string against a four-item list.\n *\n * Only the lists, their types, their guards and the task horizon live here.\n * The on-screen labels stay in `crm.ts`, beside the records they describe.\n */\n\n/**\n * Where a person sits in the relationship, as one of a fixed list.\n *\n * A fixed list rather than free text so that a report can count people per\n * stage and a filter can select one, and in the order a person usually moves\n * through them so a picker reads as a progression. `other` is the escape\n * hatch for a business whose funnel has a step none of these name; it is a\n * deliberate stage, not an absent one.\n */\nexport const CONTACT_LIFECYCLE_STAGES = [\n 'subscriber',\n 'lead',\n 'marketing-qualified',\n 'sales-qualified',\n 'opportunity',\n 'customer',\n 'evangelist',\n 'other',\n] as const\n\nexport type ContactLifecycleStage = (typeof CONTACT_LIFECYCLE_STAGES)[number]\n\nexport function isContactLifecycleStage(\n value: unknown,\n): value is ContactLifecycleStage {\n return (\n typeof value === 'string' &&\n (CONTACT_LIFECYCLE_STAGES as readonly string[]).includes(value)\n )\n}\n\n/**\n * What a task is, as a fixed list.\n *\n * A const array rather than a bare union because two surfaces have to\n * enumerate it — the task form's picker and the automation step that creates\n * a task without a form — and a union cannot be iterated at run time.\n */\nexport const CRM_TASK_KINDS = ['call', 'email', 'meeting', 'todo'] as const\nexport type CrmTaskKind = (typeof CRM_TASK_KINDS)[number]\n\nexport function isCrmTaskKind(value: unknown): value is CrmTaskKind {\n return (\n typeof value === 'string' &&\n (CRM_TASK_KINDS as readonly string[]).includes(value)\n )\n}\n\n/**\n * How far ahead an automation may date a task, in days.\n *\n * A year, because the longest follow-up anybody schedules from a trigger is\n * an annual renewal check, and a task dated further out than that is one\n * nobody will find on the list when it comes due.\n */\nexport const CRM_TASK_MAX_DUE_DAYS = 365\n\n/** Longest tag an automation may write — the console's own tag field cap. */\nexport const CONTACT_TAG_MAX_LENGTH = 60\n\n/**\n * What a person can log, in the order the picker offers them (AGL-2600).\n *\n * A fixed list rather than free text for the reason the lifecycle stages are\n * one: a report counts calls per week and a filter selects meetings, and\n * neither can be done over a string somebody typed. `note` is the plain\n * entry — something worth writing down that was not a conversation — and\n * `other` the escape hatch for the kind none of these name.\n */\nexport const CRM_ACTIVITY_KINDS = ['call', 'email', 'meeting', 'note', 'other'] as const\n\nexport type CrmActivityKind = (typeof CRM_ACTIVITY_KINDS)[number]\n\nexport function isCrmActivityKind(value: unknown): value is CrmActivityKind {\n return (\n typeof value === 'string' &&\n (CRM_ACTIVITY_KINDS as readonly string[]).includes(value)\n )\n}\n"],"names":["CONTACT_LIFECYCLE_STAGES","isContactLifecycleStage","value","includes","CRM_TASK_KINDS","isCrmTaskKind","CRM_TASK_MAX_DUE_DAYS","CONTACT_TAG_MAX_LENGTH","CRM_ACTIVITY_KINDS","isCrmActivityKind"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED;;;;;;;;CAQC,GACD,OAAO,MAAMA,2BAA2B;IACtC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAIV,OAAO,SAASC,wBACdC,KAAc;IAEd,OACE,OAAOA,UAAU,YACjB,AAACF,yBAA+CG,QAAQ,CAACD;AAE7D;AAEA;;;;;;CAMC,GACD,OAAO,MAAME,iBAAiB;IAAC;IAAQ;IAAS;IAAW;CAAO,CAAS;AAG3E,OAAO,SAASC,cAAcH,KAAc;IAC1C,OACE,OAAOA,UAAU,YACjB,AAACE,eAAqCD,QAAQ,CAACD;AAEnD;AAEA;;;;;;CAMC,GACD,OAAO,MAAMI,wBAAwB,IAAG;AAExC,2EAA2E,GAC3E,OAAO,MAAMC,yBAAyB,GAAE;AAExC;;;;;;;;CAQC,GACD,OAAO,MAAMC,qBAAqB;IAAC;IAAQ;IAAS;IAAW;IAAQ;CAAQ,CAAS;AAIxF,OAAO,SAASC,kBAAkBP,KAAc;IAC9C,OACE,OAAOA,UAAU,YACjB,AAACM,mBAAyCL,QAAQ,CAACD;AAEvD"}
|