@aglyn/plugins-crm 1.0.0-beta.221 → 1.0.0-beta.223
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/README.md +2 -1
- package/package.json +13 -13
- package/src/lib/components/activity-list.js +12 -5
- package/src/lib/components/activity-list.js.map +1 -1
- package/src/lib/components/companies-bulk-bar.d.ts +1 -4
- package/src/lib/components/companies-bulk-bar.js +7 -20
- package/src/lib/components/companies-bulk-bar.js.map +1 -1
- package/src/lib/components/companies-section.d.ts +3 -3
- package/src/lib/components/companies-section.js +149 -46
- package/src/lib/components/companies-section.js.map +1 -1
- package/src/lib/components/company-edit-drawer.js +281 -20
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/company-properties-card.js +99 -8
- package/src/lib/components/company-properties-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.js +3 -1
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-merge-dialog.js +33 -10
- package/src/lib/components/contact-merge-dialog.js.map +1 -1
- package/src/lib/components/contact-properties-card.d.ts +0 -69
- package/src/lib/components/contact-properties-card.js +350 -60
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-reports-to-field.d.ts +46 -0
- package/src/lib/components/contact-reports-to-field.js +67 -0
- package/src/lib/components/contact-reports-to-field.js.map +1 -0
- package/src/lib/components/contacts-bulk-bar.d.ts +1 -8
- package/src/lib/components/contacts-bulk-bar.js +7 -19
- package/src/lib/components/contacts-bulk-bar.js.map +1 -1
- package/src/lib/components/contacts-section.js +46 -33
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-call-actions.d.ts +10 -0
- package/src/lib/components/crm-call-actions.js +26 -9
- package/src/lib/components/crm-call-actions.js.map +1 -1
- package/src/lib/components/crm-next-activity-column.js +1 -1
- package/src/lib/components/crm-next-activity-column.js.map +1 -1
- package/src/lib/components/crm-record-picker.d.ts +15 -0
- package/src/lib/components/crm-record-picker.js +16 -10
- package/src/lib/components/crm-record-picker.js.map +1 -1
- package/src/lib/components/crm-transfer-buttons.d.ts +54 -0
- package/src/lib/components/crm-transfer-buttons.js +167 -0
- package/src/lib/components/crm-transfer-buttons.js.map +1 -0
- package/src/lib/components/deal-contact-roles-card.d.ts +46 -0
- package/src/lib/components/deal-contact-roles-card.js +368 -0
- package/src/lib/components/deal-contact-roles-card.js.map +1 -0
- package/src/lib/components/deal-detail-page.d.ts +3 -2
- package/src/lib/components/deal-detail-page.js +25 -6
- package/src/lib/components/deal-detail-page.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.d.ts +10 -0
- package/src/lib/components/deal-edit-drawer.js +219 -10
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-properties-card.d.ts +7 -0
- package/src/lib/components/deal-properties-card.js +34 -3
- package/src/lib/components/deal-properties-card.js.map +1 -1
- package/src/lib/components/deal-stage-card.d.ts +4 -0
- package/src/lib/components/deal-stage-card.js +10 -2
- package/src/lib/components/deal-stage-card.js.map +1 -1
- package/src/lib/components/deals-bulk-bar.d.ts +0 -3
- package/src/lib/components/deals-bulk-bar.js +7 -20
- package/src/lib/components/deals-bulk-bar.js.map +1 -1
- package/src/lib/components/deals-section.d.ts +3 -3
- package/src/lib/components/deals-section.js +123 -63
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/fields-section.js +31 -17
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/lead-convert-dialog.d.ts +4 -0
- package/src/lib/components/lead-convert-dialog.js +23 -1
- package/src/lib/components/lead-convert-dialog.js.map +1 -1
- package/src/lib/components/lead-detail-page.js +8 -2
- package/src/lib/components/lead-detail-page.js.map +1 -1
- package/src/lib/components/lead-profile-fields.d.ts +71 -0
- package/src/lib/components/lead-profile-fields.js +386 -0
- package/src/lib/components/lead-profile-fields.js.map +1 -0
- package/src/lib/components/lead-properties-card.d.ts +2 -1
- package/src/lib/components/lead-properties-card.js +85 -176
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/lead-source-select.d.ts +4 -23
- package/src/lib/components/lead-source-select.js +9 -73
- package/src/lib/components/lead-source-select.js.map +1 -1
- package/src/lib/components/lead-status-chip.d.ts +9 -3
- package/src/lib/components/lead-status-chip.js +8 -4
- package/src/lib/components/lead-status-chip.js.map +1 -1
- package/src/lib/components/lead-status-options.d.ts +20 -0
- package/src/lib/components/lead-status-options.js +51 -0
- package/src/lib/components/lead-status-options.js.map +1 -0
- package/src/lib/components/lead-unqualify-dialog.d.ts +5 -0
- package/src/lib/components/lead-unqualify-dialog.js +50 -18
- package/src/lib/components/lead-unqualify-dialog.js.map +1 -1
- package/src/lib/components/leads-bulk-bar.d.ts +0 -3
- package/src/lib/components/leads-bulk-bar.js +29 -29
- package/src/lib/components/leads-bulk-bar.js.map +1 -1
- package/src/lib/components/leads-section.js +120 -68
- package/src/lib/components/leads-section.js.map +1 -1
- package/src/lib/components/linked-deals-card.d.ts +4 -0
- package/src/lib/components/linked-deals-card.js +47 -3
- package/src/lib/components/linked-deals-card.js.map +1 -1
- package/src/lib/components/log-activity-dialog.js +43 -3
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/new-contact-drawer.d.ts +8 -0
- package/src/lib/components/new-contact-drawer.js +108 -6
- package/src/lib/components/new-contact-drawer.js.map +1 -1
- package/src/lib/components/new-lead-drawer.d.ts +9 -2
- package/src/lib/components/new-lead-drawer.js +88 -121
- package/src/lib/components/new-lead-drawer.js.map +1 -1
- package/src/lib/components/picklist-select.d.ts +36 -0
- package/src/lib/components/picklist-select.js +114 -0
- package/src/lib/components/picklist-select.js.map +1 -0
- package/src/lib/components/picklist-values-card.d.ts +34 -0
- package/src/lib/components/{lead-source-values-card.js → picklist-values-card.js} +241 -58
- package/src/lib/components/picklist-values-card.js.map +1 -0
- package/src/lib/components/pipeline-stages-dialog.d.ts +7 -0
- package/src/lib/components/pipeline-stages-dialog.js +26 -4
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.js +15 -6
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/recent-activity-feed.js +20 -5
- package/src/lib/components/recent-activity-feed.js.map +1 -1
- package/src/lib/components/recipes-card.js +4 -2
- package/src/lib/components/recipes-card.js.map +1 -1
- package/src/lib/components/record-tasks-card.js +15 -8
- package/src/lib/components/record-tasks-card.js.map +1 -1
- package/src/lib/components/reports/forecast-card.d.ts +6 -0
- package/src/lib/components/reports/forecast-card.js +101 -3
- package/src/lib/components/reports/forecast-card.js.map +1 -1
- package/src/lib/components/reports/lead-funnel-card.d.ts +12 -0
- package/src/lib/components/reports/lead-funnel-card.js +9 -5
- package/src/lib/components/reports/lead-funnel-card.js.map +1 -1
- package/src/lib/components/reports/lead-source-card.d.ts +23 -0
- package/src/lib/components/reports/lead-source-card.js +318 -0
- package/src/lib/components/reports/lead-source-card.js.map +1 -0
- package/src/lib/components/reports/pipeline-card.js +2 -1
- package/src/lib/components/reports/pipeline-card.js.map +1 -1
- package/src/lib/components/reports/report-export.js +1 -1
- package/src/lib/components/reports/report-export.js.map +1 -1
- package/src/lib/components/reports-section.js +8 -0
- package/src/lib/components/reports-section.js.map +1 -1
- package/src/lib/components/sharing-rule-drawer.d.ts +5 -0
- package/src/lib/components/sharing-rule-drawer.js +108 -19
- package/src/lib/components/sharing-rule-drawer.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +11 -3
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/components/task-cells.d.ts +9 -1
- package/src/lib/components/task-cells.js +9 -4
- package/src/lib/components/task-cells.js.map +1 -1
- package/src/lib/components/task-edit-drawer.js +111 -43
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/components/tasks-bulk-bar.d.ts +0 -3
- package/src/lib/components/tasks-bulk-bar.js +7 -20
- package/src/lib/components/tasks-bulk-bar.js.map +1 -1
- package/src/lib/components/tasks-calendar.d.ts +3 -0
- package/src/lib/components/tasks-calendar.js +8 -1
- package/src/lib/components/tasks-calendar.js.map +1 -1
- package/src/lib/components/tasks-section.d.ts +3 -3
- package/src/lib/components/tasks-section.js +58 -43
- package/src/lib/components/tasks-section.js.map +1 -1
- package/src/lib/constants/api-routes.d.ts +2 -9
- package/src/lib/constants/api-routes.js +1 -7
- package/src/lib/constants/api-routes.js.map +1 -1
- package/src/lib/constants/bundle-common.d.ts +6 -0
- package/src/lib/constants/bundle-common.js +11 -0
- package/src/lib/constants/bundle-common.js.map +1 -1
- package/src/lib/constants/company-filters.d.ts +14 -0
- package/src/lib/constants/company-filters.js +51 -1
- package/src/lib/constants/company-filters.js.map +1 -1
- package/src/lib/constants/contact-filters.d.ts +2 -0
- package/src/lib/constants/contact-filters.js +18 -1
- package/src/lib/constants/contact-filters.js.map +1 -1
- package/src/lib/constants/deal-filters.d.ts +22 -1
- package/src/lib/constants/deal-filters.js +67 -4
- package/src/lib/constants/deal-filters.js.map +1 -1
- package/src/lib/declarations.console-server.d.ts +3 -0
- package/src/lib/declarations.console-server.js +35 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/declarations.d.ts +26 -0
- package/src/lib/declarations.js +35 -0
- package/src/lib/declarations.js.map +1 -0
- package/src/lib/declarations.server.d.ts +11 -0
- package/src/lib/declarations.server.js +97 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/hooks/use-company-picklists.d.ts +15 -0
- package/src/lib/hooks/use-company-picklists.js +55 -0
- package/src/lib/hooks/use-company-picklists.js.map +1 -0
- package/src/lib/hooks/use-crm-picklist.d.ts +25 -0
- package/src/lib/hooks/use-crm-picklist.js +53 -0
- package/src/lib/hooks/use-crm-picklist.js.map +1 -0
- package/src/lib/hooks/use-crm-record-names.d.ts +16 -0
- package/src/lib/hooks/use-crm-record-names.js +45 -19
- package/src/lib/hooks/use-crm-record-names.js.map +1 -1
- package/src/lib/hooks/use-crm-task-picklists.d.ts +11 -0
- package/src/lib/hooks/use-crm-task-picklists.js +45 -0
- package/src/lib/hooks/use-crm-task-picklists.js.map +1 -0
- package/src/lib/hooks/use-deals.d.ts +14 -0
- package/src/lib/hooks/use-deals.js +29 -0
- package/src/lib/hooks/use-deals.js.map +1 -1
- package/src/lib/hooks/use-lead-picklists.d.ts +14 -0
- package/src/lib/hooks/use-lead-picklists.js +46 -0
- package/src/lib/hooks/use-lead-picklists.js.map +1 -0
- package/src/lib/hooks/use-lead-source-picklist.d.ts +5 -19
- package/src/lib/hooks/use-lead-source-picklist.js +12 -22
- package/src/lib/hooks/use-lead-source-picklist.js.map +1 -1
- package/src/lib/hooks/use-lead-status-picklist.d.ts +9 -0
- package/src/lib/hooks/use-lead-status-picklist.js +40 -0
- package/src/lib/hooks/use-lead-status-picklist.js.map +1 -0
- package/src/lib/model/companies.d.ts +32 -3
- package/src/lib/model/companies.js +133 -16
- package/src/lib/model/companies.js.map +1 -1
- package/src/lib/model/contact-merge.d.ts +27 -3
- package/src/lib/model/contact-merge.js +81 -7
- package/src/lib/model/contact-merge.js.map +1 -1
- package/src/lib/model/contact-record.d.ts +17 -0
- package/src/lib/model/contact-record.js +17 -2
- package/src/lib/model/contact-record.js.map +1 -1
- package/src/lib/model/contact-update.d.ts +31 -2
- package/src/lib/model/contact-update.js +14 -0
- package/src/lib/model/contact-update.js.map +1 -1
- package/src/lib/model/crm-list-query.d.ts +5 -0
- package/src/lib/model/crm-list-query.js +8 -0
- package/src/lib/model/crm-list-query.js.map +1 -1
- package/src/lib/model/crm-next-activity.d.ts +107 -0
- package/src/lib/model/crm-next-activity.js +140 -0
- package/src/lib/model/crm-next-activity.js.map +1 -0
- package/src/lib/model/crm-recipes.d.ts +40 -0
- package/src/lib/model/crm-recipes.js +259 -0
- package/src/lib/model/crm-recipes.js.map +1 -0
- package/src/lib/model/crm-record-counts.d.ts +36 -0
- package/src/lib/model/crm-record-counts.js +54 -0
- package/src/lib/model/crm-record-counts.js.map +1 -0
- package/src/lib/model/crm-record-lists.d.ts +23 -0
- package/src/lib/model/crm-record-lists.js +161 -0
- package/src/lib/model/crm-record-lists.js.map +1 -0
- package/src/lib/model/crm-reports.d.ts +73 -3
- package/src/lib/model/crm-reports.js +120 -1
- package/src/lib/model/crm-reports.js.map +1 -1
- package/src/lib/model/crm-sharing.d.ts +21 -3
- package/src/lib/model/crm-sharing.js +27 -6
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/model/crm-task-reminders.d.ts +152 -0
- package/src/lib/model/crm-task-reminders.js +161 -0
- package/src/lib/model/crm-task-reminders.js.map +1 -0
- package/src/lib/model/deal-board-model.d.ts +8 -2
- package/src/lib/model/deal-board-model.js +15 -2
- package/src/lib/model/deal-board-model.js.map +1 -1
- package/src/lib/model/deal-contact-roles.d.ts +45 -0
- package/src/lib/model/deal-contact-roles.js +73 -0
- package/src/lib/model/deal-contact-roles.js.map +1 -0
- package/src/lib/model/deal-form-model.d.ts +56 -0
- package/src/lib/model/deal-form-model.js +79 -7
- package/src/lib/model/deal-form-model.js.map +1 -1
- package/src/lib/model/download-text-file.d.ts +23 -0
- package/src/lib/model/download-text-file.js +34 -0
- package/src/lib/model/download-text-file.js.map +1 -0
- package/src/lib/model/lead-filters.d.ts +36 -2
- package/src/lib/model/lead-filters.js +123 -2
- package/src/lib/model/lead-filters.js.map +1 -1
- package/src/lib/model/lead-source-direction.d.ts +38 -0
- package/src/lib/model/lead-source-direction.js +52 -0
- package/src/lib/model/lead-source-direction.js.map +1 -0
- package/src/lib/model/next-activity.d.ts +1 -1
- package/src/lib/model/next-activity.js.map +1 -1
- package/src/lib/model/picklist-values.d.ts +119 -0
- package/src/lib/model/picklist-values.js +256 -0
- package/src/lib/model/picklist-values.js.map +1 -0
- package/src/lib/model/record-facts-disclosed.d.ts +81 -0
- package/src/lib/model/record-facts-disclosed.js +281 -0
- package/src/lib/model/record-facts-disclosed.js.map +1 -0
- package/src/lib/model/record-facts.d.ts +215 -34
- package/src/lib/model/record-facts.js +307 -128
- package/src/lib/model/record-facts.js.map +1 -1
- package/src/lib/model/task-picklists.d.ts +52 -0
- package/src/lib/model/task-picklists.js +83 -0
- package/src/lib/model/task-picklists.js.map +1 -0
- package/src/lib/model/task-routes.d.ts +13 -0
- package/src/lib/model/task-routes.js +23 -4
- package/src/lib/model/task-routes.js.map +1 -1
- package/src/lib/plan-entitlements.js +6 -4
- package/src/lib/plan-entitlements.js.map +1 -1
- package/src/lib/plugin.js +17 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/api-v1/contacts.js +220 -14
- package/src/lib/server/api-v1/contacts.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +14 -1
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-companies.js +123 -14
- package/src/lib/server/api-v1/crm-companies.js.map +1 -1
- package/src/lib/server/api-v1/crm-deals.js +291 -26
- package/src/lib/server/api-v1/crm-deals.js.map +1 -1
- package/src/lib/server/api-v1/crm-leads.js +144 -38
- package/src/lib/server/api-v1/crm-leads.js.map +1 -1
- package/src/lib/server/api-v1/crm-pipelines.d.ts +6 -0
- package/src/lib/server/api-v1/crm-pipelines.js +8 -2
- package/src/lib/server/api-v1/crm-pipelines.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +78 -34
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/api-v1/openapi.d.ts +0 -11
- package/src/lib/server/api-v1/openapi.js +171 -16
- package/src/lib/server/api-v1/openapi.js.map +1 -1
- package/src/lib/server/assign-contact-owner.d.ts +188 -0
- package/src/lib/server/assign-contact-owner.js +446 -0
- package/src/lib/server/assign-contact-owner.js.map +1 -0
- package/src/lib/server/associate-company-by-domain.d.ts +70 -0
- package/src/lib/server/associate-company-by-domain.js +153 -0
- package/src/lib/server/associate-company-by-domain.js.map +1 -0
- package/src/lib/server/automation-steps.d.ts +140 -0
- package/src/lib/server/automation-steps.js +669 -0
- package/src/lib/server/automation-steps.js.map +1 -0
- package/src/lib/server/capture-contact.d.ts +17 -0
- package/src/lib/server/capture-contact.js +95 -26
- package/src/lib/server/capture-contact.js.map +1 -1
- package/src/lib/server/capture-host-contact.d.ts +104 -0
- package/src/lib/server/capture-host-contact.js +151 -0
- package/src/lib/server/capture-host-contact.js.map +1 -0
- package/src/lib/server/company-children.d.ts +25 -0
- package/src/lib/server/company-children.js +42 -0
- package/src/lib/server/company-children.js.map +1 -0
- package/src/lib/server/company-delete.d.ts +18 -0
- package/src/lib/server/company-delete.js +44 -21
- package/src/lib/server/company-delete.js.map +1 -1
- package/src/lib/server/contact-email-history.js +21 -19
- package/src/lib/server/contact-email-history.js.map +1 -1
- package/src/lib/server/contact-remove.js +27 -2
- package/src/lib/server/contact-remove.js.map +1 -1
- package/src/lib/server/contact-reports-to.d.ts +61 -0
- package/src/lib/server/contact-reports-to.js +114 -0
- package/src/lib/server/contact-reports-to.js.map +1 -0
- package/src/lib/server/contact-update.d.ts +42 -1
- package/src/lib/server/contact-update.js +204 -23
- package/src/lib/server/contact-update.js.map +1 -1
- package/src/lib/server/convert-host-lead.d.ts +46 -1
- package/src/lib/server/convert-host-lead.js +173 -15
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/convert-open-lead.js +12 -5
- package/src/lib/server/convert-open-lead.js.map +1 -1
- package/src/lib/server/crm-email-activity.d.ts +118 -0
- package/src/lib/server/crm-email-activity.js +148 -0
- package/src/lib/server/crm-email-activity.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +1 -1
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-next-activity.d.ts +74 -0
- package/src/lib/server/crm-next-activity.js +194 -0
- package/src/lib/server/crm-next-activity.js.map +1 -0
- package/src/lib/server/crm-record-indexes.d.ts +45 -0
- package/src/lib/server/crm-record-indexes.js +78 -0
- package/src/lib/server/crm-record-indexes.js.map +1 -0
- package/src/lib/server/crm-sharing.d.ts +9 -1
- package/src/lib/server/crm-sharing.js +23 -3
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/deal-contact-roles.d.ts +27 -0
- package/src/lib/server/deal-contact-roles.js +89 -0
- package/src/lib/server/deal-contact-roles.js.map +1 -0
- package/src/lib/server/email-send.js +2 -1
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/lead-convert.d.ts +5 -0
- package/src/lib/server/lead-convert.js +19 -3
- package/src/lib/server/lead-convert.js.map +1 -1
- package/src/lib/server/lead-create.d.ts +17 -2
- package/src/lib/server/lead-create.js +46 -14
- package/src/lib/server/lead-create.js.map +1 -1
- package/src/lib/server/lead-nurturing.d.ts +6 -0
- package/src/lib/server/lead-nurturing.js +57 -20
- package/src/lib/server/lead-nurturing.js.map +1 -1
- package/src/lib/server/lead-picklists.d.ts +35 -0
- package/src/lib/server/lead-picklists.js +52 -0
- package/src/lib/server/lead-picklists.js.map +1 -0
- package/src/lib/server/lead-source-picklist.d.ts +1 -13
- package/src/lib/server/lead-source-picklist.js +6 -33
- package/src/lib/server/lead-source-picklist.js.map +1 -1
- package/src/lib/server/merge-contacts.js +23 -5
- package/src/lib/server/merge-contacts.js.map +1 -1
- package/src/lib/server/next-activity-routes.js +2 -1
- package/src/lib/server/next-activity-routes.js.map +1 -1
- package/src/lib/server/person-eraser.d.ts +53 -0
- package/src/lib/server/person-eraser.js +149 -0
- package/src/lib/server/person-eraser.js.map +1 -0
- package/src/lib/server/person-records.d.ts +69 -0
- package/src/lib/server/person-records.js +317 -0
- package/src/lib/server/person-records.js.map +1 -0
- package/src/lib/server/person-refund.d.ts +97 -0
- package/src/lib/server/person-refund.js +221 -0
- package/src/lib/server/person-refund.js.map +1 -0
- package/src/lib/server/picklist-values.d.ts +21 -0
- package/src/lib/server/picklist-values.js +308 -0
- package/src/lib/server/picklist-values.js.map +1 -0
- package/src/lib/server/read-picklist.d.ts +44 -0
- package/src/lib/server/read-picklist.js +65 -0
- package/src/lib/server/read-picklist.js.map +1 -0
- package/src/lib/server/recipe-routes.js +22 -8
- package/src/lib/server/recipe-routes.js.map +1 -1
- package/src/lib/server/record-email-state.js +7 -1
- package/src/lib/server/record-email-state.js.map +1 -1
- package/src/lib/server/record-facts.d.ts +3 -0
- package/src/lib/server/record-facts.js +233 -31
- package/src/lib/server/record-facts.js.map +1 -1
- package/src/lib/server/record-origin.d.ts +27 -0
- package/src/lib/server/record-origin.js +104 -0
- package/src/lib/server/record-origin.js.map +1 -0
- package/src/lib/server/record-timeline.js +40 -3
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/suite-gate.js +4 -3
- package/src/lib/server/suite-gate.js.map +1 -1
- package/src/lib/server/task-reminders-route.js +2 -1
- package/src/lib/server/task-reminders-route.js.map +1 -1
- package/src/lib/server/task-routes.js +33 -17
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server-deal-stage.d.ts +5 -1
- package/src/lib/server-deal-stage.js +10 -5
- package/src/lib/server-deal-stage.js.map +1 -1
- package/src/lib/server.d.ts +8 -3
- package/src/lib/server.js +47 -43
- package/src/lib/server.js.map +1 -1
- package/src/lib/testing/memory-firestore.d.ts +55 -0
- package/src/lib/testing/memory-firestore.js +335 -0
- package/src/lib/testing/memory-firestore.js.map +1 -0
- package/src/lib/testing/stand-in-email-send-index.d.ts +25 -0
- package/src/lib/testing/stand-in-email-send-index.js +49 -0
- package/src/lib/testing/stand-in-email-send-index.js.map +1 -0
- package/src/lib/transfer/activities.d.ts +30 -0
- package/src/lib/transfer/activities.js +132 -0
- package/src/lib/transfer/activities.js.map +1 -0
- package/src/lib/transfer/aliases.d.ts +22 -0
- package/src/lib/transfer/aliases.js +1342 -0
- package/src/lib/transfer/aliases.js.map +1 -0
- package/src/lib/transfer/common.d.ts +222 -0
- package/src/lib/transfer/common.js +832 -0
- package/src/lib/transfer/common.js.map +1 -0
- package/src/lib/transfer/companies.d.ts +43 -0
- package/src/lib/transfer/companies.js +549 -0
- package/src/lib/transfer/companies.js.map +1 -0
- package/src/lib/transfer/contacts.d.ts +31 -0
- package/src/lib/transfer/contacts.js +727 -0
- package/src/lib/transfer/contacts.js.map +1 -0
- package/src/lib/transfer/deals.d.ts +66 -0
- package/src/lib/transfer/deals.js +698 -0
- package/src/lib/transfer/deals.js.map +1 -0
- package/src/lib/transfer/email-templates-package.d.ts +40 -0
- package/src/lib/transfer/email-templates-package.js +76 -0
- package/src/lib/transfer/email-templates-package.js.map +1 -0
- package/src/lib/transfer/email-templates-package.server.d.ts +32 -0
- package/src/lib/transfer/email-templates-package.server.js +176 -0
- package/src/lib/transfer/email-templates-package.server.js.map +1 -0
- package/src/lib/transfer/fields.d.ts +102 -0
- package/src/lib/transfer/fields.js +1755 -0
- package/src/lib/transfer/fields.js.map +1 -0
- package/src/lib/transfer/leads.d.ts +30 -0
- package/src/lib/transfer/leads.js +582 -0
- package/src/lib/transfer/leads.js.map +1 -0
- package/src/lib/transfer/pipelines.d.ts +21 -0
- package/src/lib/transfer/pipelines.js +172 -0
- package/src/lib/transfer/pipelines.js.map +1 -0
- package/src/lib/transfer/register.d.ts +47 -0
- package/src/lib/transfer/register.js +277 -0
- package/src/lib/transfer/register.js.map +1 -0
- package/src/lib/transfer/tasks.d.ts +30 -0
- package/src/lib/transfer/tasks.js +418 -0
- package/src/lib/transfer/tasks.js.map +1 -0
- package/src/lib/transfer/ui.d.ts +20 -0
- package/src/lib/transfer/ui.js +42 -0
- package/src/lib/transfer/ui.js.map +1 -0
- package/src/lib/components/company-import-drawer.d.ts +0 -42
- package/src/lib/components/company-import-drawer.js +0 -99
- package/src/lib/components/company-import-drawer.js.map +0 -1
- package/src/lib/components/contact-import-drawer.d.ts +0 -46
- package/src/lib/components/contact-import-drawer.js +0 -149
- package/src/lib/components/contact-import-drawer.js.map +0 -1
- package/src/lib/components/crm-export-all-button.d.ts +0 -39
- package/src/lib/components/crm-export-all-button.js +0 -98
- package/src/lib/components/crm-export-all-button.js.map +0 -1
- package/src/lib/components/csv-import-drawer.d.ts +0 -139
- package/src/lib/components/csv-import-drawer.js +0 -757
- package/src/lib/components/csv-import-drawer.js.map +0 -1
- package/src/lib/components/deal-import-drawer.d.ts +0 -24
- package/src/lib/components/deal-import-drawer.js +0 -83
- package/src/lib/components/deal-import-drawer.js.map +0 -1
- package/src/lib/components/lead-import-drawer.d.ts +0 -27
- package/src/lib/components/lead-import-drawer.js +0 -118
- package/src/lib/components/lead-import-drawer.js.map +0 -1
- package/src/lib/components/lead-source-values-card.d.ts +0 -27
- package/src/lib/components/lead-source-values-card.js.map +0 -1
- package/src/lib/components/task-import-drawer.d.ts +0 -24
- package/src/lib/components/task-import-drawer.js +0 -82
- package/src/lib/components/task-import-drawer.js.map +0 -1
- package/src/lib/model/companies-csv.d.ts +0 -36
- package/src/lib/model/companies-csv.js +0 -38
- package/src/lib/model/companies-csv.js.map +0 -1
- package/src/lib/model/contacts-csv.d.ts +0 -54
- package/src/lib/model/contacts-csv.js +0 -67
- package/src/lib/model/contacts-csv.js.map +0 -1
- package/src/lib/model/crm-company-import.d.ts +0 -154
- package/src/lib/model/crm-company-import.js +0 -331
- package/src/lib/model/crm-company-import.js.map +0 -1
- package/src/lib/model/crm-csv.d.ts +0 -239
- package/src/lib/model/crm-csv.js +0 -467
- package/src/lib/model/crm-csv.js.map +0 -1
- package/src/lib/model/crm-deal-import.d.ts +0 -112
- package/src/lib/model/crm-deal-import.js +0 -263
- package/src/lib/model/crm-deal-import.js.map +0 -1
- package/src/lib/model/crm-import.d.ts +0 -250
- package/src/lib/model/crm-import.js +0 -467
- package/src/lib/model/crm-import.js.map +0 -1
- package/src/lib/model/crm-lead-import.d.ts +0 -138
- package/src/lib/model/crm-lead-import.js +0 -446
- package/src/lib/model/crm-lead-import.js.map +0 -1
- package/src/lib/model/crm-task-import.d.ts +0 -94
- package/src/lib/model/crm-task-import.js +0 -275
- package/src/lib/model/crm-task-import.js.map +0 -1
- package/src/lib/model/deals-csv.d.ts +0 -32
- package/src/lib/model/deals-csv.js +0 -36
- package/src/lib/model/deals-csv.js.map +0 -1
- package/src/lib/model/import-column-shapes.d.ts +0 -36
- package/src/lib/model/import-column-shapes.js +0 -76
- package/src/lib/model/import-column-shapes.js.map +0 -1
- package/src/lib/model/lead-source-values.d.ts +0 -82
- package/src/lib/model/lead-source-values.js +0 -149
- package/src/lib/model/lead-source-values.js.map +0 -1
- package/src/lib/model/leads-csv.d.ts +0 -40
- package/src/lib/model/leads-csv.js +0 -40
- package/src/lib/model/leads-csv.js.map +0 -1
- package/src/lib/model/tasks-csv.d.ts +0 -28
- package/src/lib/model/tasks-csv.js +0 -28
- package/src/lib/model/tasks-csv.js.map +0 -1
- package/src/lib/server/companies-import.d.ts +0 -57
- package/src/lib/server/companies-import.js +0 -242
- package/src/lib/server/companies-import.js.map +0 -1
- package/src/lib/server/contacts-import.d.ts +0 -109
- package/src/lib/server/contacts-import.js +0 -393
- package/src/lib/server/contacts-import.js.map +0 -1
- package/src/lib/server/deals-import.d.ts +0 -76
- package/src/lib/server/deals-import.js +0 -248
- package/src/lib/server/deals-import.js.map +0 -1
- package/src/lib/server/export-route.d.ts +0 -60
- package/src/lib/server/export-route.js +0 -447
- package/src/lib/server/export-route.js.map +0 -1
- package/src/lib/server/import-context.d.ts +0 -87
- package/src/lib/server/import-context.js +0 -182
- package/src/lib/server/import-context.js.map +0 -1
- package/src/lib/server/lead-source-values.d.ts +0 -50
- package/src/lib/server/lead-source-values.js +0 -191
- package/src/lib/server/lead-source-values.js.map +0 -1
- package/src/lib/server/leads-import.d.ts +0 -84
- package/src/lib/server/leads-import.js +0 -367
- package/src/lib/server/leads-import.js.map +0 -1
- package/src/lib/server/tasks-import.d.ts +0 -54
- package/src/lib/server/tasks-import.js +0 -160
- package/src/lib/server/tasks-import.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/automation-steps.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\nimport {\n buildCrmEmailActivity,\n checkEntitlement,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_TAG_MAX_LENGTH,\n contactFacetPath,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActivity,\n type CrmActivityDirection,\n crmActivityDirection,\n type CrmActivityLink,\n type CrmTask,\n type CrmTaskPriority,\n crmEmailDeliveryTags,\n crmScopeTokens,\n crmTaskLabelsForNew,\n crmTaskListFields,\n normalizeContactEmail,\n parseCrmMemberRef,\n personKey,\n planLabelGrantingFeature,\n readContactFacet,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport type {\n PluginRecordEmailPrepareRequest,\n PluginRecordPreparedEmail,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport type {\n ServerStepAnswer,\n ServerStepRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport {\n consentGroupForSite,\n countCrmActivitiesForRecord,\n firebaseAdmin,\n orgDataQueryForHost,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\n// The leaf, not the barrel: the specs substitute the barrel wholesale, and\n// the lookup must reach the real index logic under them.\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { FieldValue } from 'firebase-admin/firestore'\n// The leaf, not the runtime barrel: the specs substitute it.\nimport {\n OWNER_ASSIGNMENT_REFUSALS,\n reassignContactOwner,\n reassignLeadOwner,\n} from './assign-contact-owner'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { InteractionStepGuard } from '@aglyn/aglyn/app-utils/site-interactions'\nimport type { ContactLifecycleStage, CrmActivityKind, CrmTaskKind } from '@aglyn/aglyn/app-utils/crm-kinds'\nimport type { CRM_STEP_TYPES } from '../constants/bundle-common'\nimport { readCrmTaskPicklists } from './read-picklist'\nimport { CRM_SUITE_FEATURE } from './suite-gate'\nimport { crmTaskReminderAfterEdit } from '../model/crm-task-reminders'\nimport { recomputeCrmNextTaskAt } from './crm-next-activity'\nimport { newCrmActivityRef, writeCrmEmailActivity } from './crm-email-activity'\n\n/**\n * THE AUTOMATION STEPS THAT WRITE THE CRM (AGL-2605), run for the automation\n * engine through the platform's server-step seam (`plugin-server-steps`,\n * AGL-3080): `setContactStage`, `addContactTag`, `assignContactOwner`,\n * `createCrmTask` and `logCrmActivity`.\n *\n * The engine keeps the step's guard, the run's order, its history and the\n * nesting cap; this answers what the step did. A refusal is ANSWERED as\n * `error`, never thrown, and its words are the line the run history carries —\n * the same words the engine wrote when these steps were its own.\n *\n * The five share one shape no other step has: each begins by finding THE\n * PERSON the event is about, and each writes either inside the site's facet on\n * that person or a record stamped with the site's scope. One resolver and one\n * scope expression, used five times, rather than five copies drifting apart.\n *\n * ## The person is the event's, never the step's\n *\n * A step carries no contact reference. The contact is whoever the event\n * names — by `contactId` when the emitting door knew the document, and by\n * `email` otherwise, which is what every pre-CRM event carries. Both lookups\n * are scoped to what THIS site may see: a document the id names but the site\n * cannot read is treated as absent, exactly as the scoped query would have\n * treated it, so an event replayed against the wrong site reaches nobody.\n *\n * ## A missing person is a reported no-op\n *\n * Nothing is written and the step's error names the reason, which lands in\n * the run summary beside the trigger — the same place \"why didn't it fire?\"\n * is answered for every other step. Silence here would make a mis-wired\n * trigger (a form with no email field) indistinguishable from a working one.\n *\n * ## The plan gate is the CRM's\n *\n * Every step is refused on a workspace whose plan does not carry the CRM,\n * into the run history with the tier that carries it, so a Free workspace\n * whose flow names a CRM step reads why the step did nothing rather than a\n * log that says it ran. The org document is the one the run's gate already\n * read, handed over with the step, so the check costs no read.\n *\n * The same module answers the record timeline's `prepareEmail` (AGL-2615): an\n * automation's email addressed to the contact the event is about is filed on\n * that contact's timeline — see {@link prepareCrmRecordEmail}.\n */\n\n/** One of the steps this module runs. */\nexport type CrmStepType = (typeof CRM_STEP_TYPES)[number]\n\n/**\n * A CRM step, as it is stored: the CRM's own shapes of the steps it runs. The\n * automation editor writes them and checks them; `apps/console/specs/\n * crm-automation-steps.spec.ts` runs what it writes through this module.\n */\nexport type CrmAutomationStep = (\n | { type: 'setContactStage'; lifecycleStage: ContactLifecycleStage }\n | { type: 'addContactTag'; tag: string }\n | { type: 'assignContactOwner'; ownerUid?: string; ownerEmail?: string; roundRobin?: boolean }\n | {\n type: 'createCrmTask'\n title: string\n kind: CrmTaskKind\n /** `normal` when absent — the steps written before priorities were (AGL-3517). */\n priority?: CrmTaskPriority\n dueInDays: number\n assigneeUid?: string\n assigneeEmail?: string\n }\n | {\n type: 'logCrmActivity'\n kind: CrmActivityKind\n body: string\n /** Which way a call or an email went (AGL-3517). */\n direction?: CrmActivityDirection\n }\n) & { when?: InteractionStepGuard | null } & { type: CrmStepType }\n\n/** The site, the plan and the org a step or an email is answered for. */\ninterface CrmStepEnv {\n hostId: string\n /** The owning org's billing doc, already read by the run's gate. */\n org: unknown\n orgId: string | null\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\ninterface ResolvedContact {\n id: string\n ref: FirebaseFirestore.DocumentReference\n data: Record<string, unknown>\n}\n\n/**\n * The person a CRM step acts on: a contact, or — when the workspace holds\n * none for them — the LEAD the site filed (AGL-3458).\n *\n * A lead-routed form files a lead and no contact (AGL-3232), and announces it\n * with the `lead` event. An automation welcoming that person — assign an\n * owner, book a call, tag them — has only the lead to act on, so each step\n * that has a lead's equivalent writes it there: the lead's own `ownerUid`,\n * its own `tags`, a task or an activity filed under `leadId`. A stage is a\n * contact's alone, and a step setting one on a lead says so.\n */\ntype ResolvedPerson =\n | ({ kind: 'contact' } & ResolvedContact)\n | ({ kind: 'lead' } & ResolvedContact)\n\n/**\n * The contact an event names, as this site may see it.\n *\n * Id first, because a CRM event carries the document the door just wrote and\n * a lookup by id is a read, not a query. The address second, through the\n * org's address index narrowed to this site (AGL-2633), for every event that\n * predates the CRM and knows only who filled in the form — so an address a\n * merge folded into another record still reaches the person who now holds it.\n */\nasync function resolveEventContact(\n hostId: string,\n named: { contactId?: unknown; email?: unknown },\n): Promise<ResolvedContact | null> {\n const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts')\n const contactId = String(named.contactId ?? '').trim()\n if (contactId) {\n const doc = await contactsRef.doc(contactId).get()\n if (doc.exists && visibleToHost(doc.get('visibleTo'), hostId)) {\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n }\n }\n const hit = await findContactByEmail(contactsRef, named.email, { hostId })\n return hit ? { id: hit.id, ref: hit.ref, data: hit.data() ?? {} } : null\n}\n\n/**\n * The lead an event names, as this site may see it: by `leadId` — the `lead`\n * event carries it, and it is the person's key — else by the key of the\n * `email`. A row this site cannot see is absent, exactly as a contact's is.\n */\nasync function resolveEventLead(\n hostId: string,\n named: { leadId?: unknown; email?: unknown },\n): Promise<ResolvedContact | null> {\n const key = String(named.leadId ?? '').trim() || personKey(named.email) || ''\n if (!key) return null\n const { ref: leadsRef } = await orgDataQueryForHost(hostId, 'leads')\n const doc = await leadsRef.doc(key).get()\n if (!doc.exists || !visibleToHost(doc.get('visibleTo'), hostId)) return null\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n}\n\n/** The contact the event names, else its lead — see {@link ResolvedPerson}. */\nasync function resolveEventPerson(\n hostId: string,\n named: { contactId?: unknown; leadId?: unknown; email?: unknown },\n): Promise<ResolvedPerson | null> {\n const contact = await resolveEventContact(hostId, named)\n if (contact) return { kind: 'contact', ...contact }\n const lead = await resolveEventLead(hostId, named)\n return lead ? { kind: 'lead', ...lead } : null\n}\n\n/**\n * The uid a step names for somebody on the team — an owner, an assignee —\n * resolved against the org's roster, whichever way the step named them.\n *\n * A step names a member by uid when a picker wrote it and by address when a\n * person typed it, and the editor's one text field accepts either — so both\n * fields are read through `parseCrmMemberRef`, and an address typed into the\n * uid slot or a uid typed into the address slot still names the person.\n *\n * Both are RESOLVED, not trusted. `orgs/{orgId}/members/{uid}` is keyed by the\n * uid, so a uid costs one document read and must exist: `ownerUid` and\n * `assigneeUid` are fields every reader resolves as a member, and a stranger's\n * uid in one is a task nobody on the team can find. An address is matched on\n * the roster's own `email` field, and two production paths create a member\n * document WITHOUT one (a host-access re-grant, and an add whose auth record\n * carried none) — such a member is named by uid, which is the reason the\n * editor takes one.\n *\n * The roster is the only directory consulted. A project-level Auth lookup by\n * address would resolve people who are not on this organization at all\n * (AGL-1122). A reference that resolves neither way is an error, not a stored\n * string.\n */\nasync function resolveMemberUid(\n orgId: string | null,\n named: { uid?: string; email?: string },\n role: 'owner' | 'assignee',\n): Promise<{ uid: string; detail: string } | { error: string }> {\n const ref = parseCrmMemberRef(named.uid) ?? parseCrmMemberRef(named.email)\n if (!ref) return { error: `no ${role} named on the step` }\n if (!orgId) return { error: 'this site has no organization' }\n const members = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n if (ref.kind === 'uid') {\n const member = await members.doc(ref.uid).get()\n if (member.exists) return { uid: ref.uid, detail: ref.uid }\n return { error: `no team member with the id ${ref.uid}` }\n }\n const byField = (await members.where('email', '==', ref.email).limit(1).get()).docs[0]\n if (byField) return { uid: byField.id, detail: ref.email }\n return { error: `no team member with the address ${ref.email}` }\n}\n\n/**\n * Runs one CRM step for the person the event names: the executor the CRM\n * registers on the server-step seam for every type in `CRM_STEP_TYPES`.\n *\n * Never throws for a plan without the CRM, a missing person, an unknown owner\n * or a site with no org — those are answered as `error` so the run records\n * them; a Firestore failure propagates, and the engine records it the same\n * way.\n */\nexport async function runCrmAutomationStep(\n request: ServerStepRequest,\n nowMs = Date.now(),\n): Promise<ServerStepAnswer> {\n if (!checkEntitlement(request.org as Parameters<typeof checkEntitlement>[0], CRM_SUITE_FEATURE)) {\n return { error: `CRM steps require the ${planLabelGrantingFeature(CRM_SUITE_FEATURE)} plan` }\n }\n const env: CrmStepEnv = { hostId: request.hostId, org: request.org, orgId: request.orgId }\n const step = request.step as unknown as CrmAutomationStep\n const actionId = request.run.id\n const { hostId } = env\n const person = await resolveEventPerson(hostId, request.payload)\n if (!person) {\n const named = String(request.payload['contactId'] ?? request.payload['email'] ?? '').trim()\n return {\n error: named\n ? `no contact or lead this site can see for ${named}`\n : 'the event names no contact — no contactId or email in its payload',\n }\n }\n if (person.kind === 'lead') return runLeadStep(env, actionId, step, person, nowMs)\n const contact = person\n /*\n * THE HOLDER whose facet the write addresses — the site's consent group,\n * which is the site alone unless the org declared the site one of a set\n * that presents as one sender. Same resolution the capture doors use, so a\n * stage set here lands in the facet the console reads.\n */\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const email = String(contact.data['email'] ?? '')\n\n if (step.type === 'setContactStage') {\n const previous = facet.lifecycleStage ?? ''\n const label = CONTACT_LIFECYCLE_STAGE_LABELS[step.lifecycleStage]\n /*\n * A stage set to what it already is changes nothing and ANNOUNCES\n * nothing. The write is skipped so the row's `updatedAt` does not move for\n * a non-event, and the absent emit is what stops an action that sets the\n * stage it listens for from re-running on its own write — the engine's\n * nesting cap bounds that chain, this ends it at once.\n */\n if (previous === step.lifecycleStage) {\n return { detail: `${label} (already)` }\n }\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: step.lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\n /*\n * A stage set by an automation IS a stage change, and the action\n * listening for it must run — but through the engine's nesting cap, so\n * the event is answered back for the engine to raise, never raised here.\n */\n return {\n detail: label,\n emit: {\n event: 'contactStageChanged',\n payload: {\n contactId: contact.id,\n email,\n lifecycleStage: step.lifecycleStage,\n previousStage: previous,\n },\n },\n }\n }\n\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n // `arrayUnion`, so the tag a merchant already applied by hand is not\n // duplicated and the tags beside it are kept.\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\n return { detail: tag }\n }\n\n if (step.type === 'assignContactOwner') {\n /*\n * Through the one server assignment (AGL-2618), in both of the step's\n * modes, rather than a facet write of its own: the helper is what moves\n * the round-robin pointer inside the transaction that writes the owner,\n * mirrors the owner onto the site's lead, and tells the new owner. A\n * member named on the step is still resolved here — by address against\n * the roster, as before — and handed over by uid; the helper checks the\n * roster document again, which is one read and the same answer.\n */\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignContactOwner({\n hostId,\n contactId: contact.id,\n email,\n assign,\n })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') {\n return { detail: `${named} (already)` }\n }\n return {\n detail: step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named,\n }\n }\n\n // The two record creators: a task and an activity are documents of their\n // own beside the contact, stamped with the scope a contact captured on this\n // site would carry — `crmScopeTokens` is the create path's own expression,\n // so a record an automation made is visible to exactly the sites a record a\n // person made would be.\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId)\n const visibleTo = crmScopeTokens((env.org ?? null) as Record<string, unknown> | null, group)\n const links = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\n }\n\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n /*\n * The assignee the step names, else the person who OWNS the contact, else\n * nobody. A follow-up task belongs to whoever holds the relationship, and\n * an automation that had to name one person for every contact it touches\n * would assign the whole list to one rep. A named assignee who cannot be\n * resolved is an error rather than a fallback to the owner: the author\n * named somebody on purpose.\n */\n let assignee = facet.ownerUid ?? ''\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const priority: CrmTaskPriority =\n step.priority === 'high' || step.priority === 'low' ? step.priority : 'normal'\n // The org's labels for the meanings the step names (AGL-3517).\n const labels = crmTaskLabelsForNew(\n await readCrmTaskPicklists(firebaseAdmin.app().firestore(), env.orgId),\n { kind: step.kind, priority },\n )\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority,\n status: 'open',\n ...labels,\n dueAtMs,\n // The reminder a person's task gets (AGL-2659): the due time.\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n // What the Tasks list searches by (AGL-3321), beside the task.\n await orgRef.collection(CRM_COLLECTIONS.tasks).add({ ...task, ...crmTaskListFields(task) })\n // The contact and company the task names carry `nextTaskAtMs` (AGL-2661);\n // a figure that could not move is the Fields section's recompute's.\n await recomputeCrmNextTaskAt(firebaseAdmin.app().firestore(), env.orgId, [links]).catch(\n (error: unknown) => {\n console.error('[crm] next activity could not be recomputed', env.orgId, error)\n },\n )\n return { detail: title.slice(0, 60) }\n }\n\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n /*\n * The per-record ceiling (AGL-2611), and this step is the writer it exists\n * for: a flow that logs on every page view fills one person's log in an\n * afternoon. Refused into the run history as an error, the way an\n * unresolvable assignee is, so the merchant reads why the flow stopped\n * writing rather than finding a log that silently stopped.\n */\n const logged = await countCrmActivitiesForRecord(orgRef, links)\n if (!crmActivityLogHasRoom(logged)) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const direction = crmActivityDirection(step.kind, step.direction)\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n ...(direction ? { direction } : {}),\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).add(activity)\n return { detail: step.kind }\n }\n\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * A CRM step on a LEAD (AGL-3458) — the person is not a contact yet, so each\n * step writes the lead's equivalent of what it writes on a contact. See\n * {@link ResolvedPerson}.\n */\nasync function runLeadStep(\n env: CrmStepEnv,\n actionId: string,\n step: CrmAutomationStep,\n lead: ResolvedContact,\n nowMs: number,\n): Promise<ServerStepAnswer> {\n const { hostId } = env\n if (step.type === 'setContactStage') {\n return {\n error:\n 'the event names a lead, and a lead has no lifecycle stage until it is ' +\n 'converted to a contact',\n }\n }\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n await lead.ref.update({\n tags: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // A lead's tags are what the Leads list searches (AGL-3321).\n await restampCrmListFieldsAt(lead.ref, 'leads')\n return { detail: `${tag} (lead)` }\n }\n if (step.type === 'assignContactOwner') {\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignLeadOwner({ hostId, leadId: lead.id, assign })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') return { detail: `${named} (already, lead)` }\n return {\n detail:\n step.roundRobin === true\n ? `round robin → ${verdict.ownerUid} (lead)`\n : `${named} (lead)`,\n }\n }\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId)\n const group = await consentGroupForSite(hostId)\n const visibleTo = crmScopeTokens((env.org ?? null) as Record<string, unknown> | null, group)\n // Filed under the lead, as a sequence's call step files one (AGL-3233); a\n // conversion stamps the contact beside it, and the task follows the person.\n const links = { leadId: lead.id }\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n // The named assignee, else whoever owns the lead NOW — an owner step\n // earlier in this same run wrote the lead after it was resolved, so it\n // is read again — else nobody.\n let assignee: string\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n } else {\n const fresh = await lead.ref.get()\n assignee = String((fresh.data() ?? lead.data)['ownerUid'] ?? '')\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority: 'normal',\n status: 'open',\n dueAtMs,\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef\n .collection(CRM_COLLECTIONS.tasks)\n .doc(createResourceUid())\n .set({ ...task, ...crmTaskListFields(task) })\n return { detail: `${title.slice(0, 60)} (lead)` }\n }\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, links))) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).doc(createResourceUid()).set(activity)\n return { detail: `${step.kind} (lead)` }\n }\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * Whether — and where — an email a plugin is about to send lands on a\n * timeline: the CRM's answer to the record timeline's `prepareEmail`.\n *\n * An automation's `sendEmail` step is not a CRM step: it mails whatever\n * address the event carries, to a person who may be nobody the CRM knows. It\n * earns a row on exactly one condition, that the message is ADDRESSED TO THE\n * PERSON the sender means — a contact, else the lead a lead-routed form filed\n * (AGL-3458), whose row lands on the lead's timeline — the person the request's link finds, at the\n * address the row holds. A welcome sequence to a new contact is that; an\n * internal alert routed to a merchant's own address through `toField` is not,\n * and a row for it would put the merchant's inbox on a customer's history.\n *\n * Prepared ahead of the send, for the reason the console route mints its id\n * first: the delivery webhook has nothing but the tags on the message to find\n * the row with. Nothing is written until `file` is called, once the provider\n * accepted the message. A workspace whose plan does not carry the CRM, a\n * record at the activity ceiling and a site with no org earn no row — the\n * message still goes, because the ceiling bounds the log and not the mail.\n *\n * **Never throws**, and neither does `file`. The row is bookkeeping beside a\n * send, and a lookup that fails must not become a message that never left —\n * the posture every meter beside a send takes. A failure is logged and the\n * message goes out untagged.\n */\nexport async function prepareCrmRecordEmail(\n request: PluginRecordEmailPrepareRequest,\n): Promise<PluginRecordPreparedEmail | null> {\n const orgId = String(request.orgId ?? '').trim()\n const hostId = String(request.hostId ?? '').trim()\n if (!orgId || !hostId) return null\n const address = normalizeContactEmail(request.to)\n if (!address) return null\n try {\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n // The org the caller already read, or the one read here once.\n const org =\n request.org !== undefined ? request.org : ((await orgRef.get()).data() ?? null)\n if (!checkEntitlement(org as Parameters<typeof checkEntitlement>[0], CRM_SUITE_FEATURE)) {\n return null\n }\n const person = await resolveEventPerson(hostId, request.link)\n if (!person || normalizeContactEmail(person.data['email']) !== address) {\n return null\n }\n const group = await consentGroupForSite(hostId)\n const facet = person.kind === 'contact' ? readContactFacet(person.data, group.groupId) : null\n const link: CrmActivityLink =\n person.kind === 'lead'\n ? { leadId: person.id }\n : {\n contactId: person.id,\n ...(facet?.companyId ? { companyId: facet.companyId } : {}),\n }\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {\n return null\n }\n const ref = newCrmActivityRef(firestore, orgId)\n const visibleTo = crmScopeTokens((org ?? null) as Record<string, unknown> | null, group)\n return {\n tags: crmEmailDeliveryTags({ orgId, hostId, activityId: ref.id }),\n /*\n * The same shape the console route logs — `buildCrmEmailActivity` is the\n * one builder — with the sender's id as its source and nobody as its\n * author. Never throws: the message has left, and a row that could not\n * be written is a gap on the timeline rather than a failed send.\n */\n async file(sent) {\n try {\n await writeCrmEmailActivity(\n ref,\n buildCrmEmailActivity({\n subject: sent.subject,\n body: sent.body,\n to: normalizeContactEmail(sent.to) ?? sent.to,\n atMs: sent.atMs ?? Date.now(),\n byUid: '',\n sourceActionId: sent.sourceRef,\n link,\n hostId,\n visibleTo,\n }),\n )\n } catch (error) {\n console.error('[crm] automation email activity write failed', ref.id, error)\n }\n },\n }\n } catch (error) {\n console.error('[crm] automation email activity could not be prepared', hostId, error)\n return null\n }\n}\n"],"names":["buildCrmEmailActivity","checkEntitlement","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_TAG_MAX_LENGTH","contactFacetPath","CRM_ACTIVITY_LOG_FULL_MESSAGE","CRM_COLLECTIONS","crmActivityLogHasRoom","crmActivityDirection","crmEmailDeliveryTags","crmScopeTokens","crmTaskLabelsForNew","crmTaskListFields","normalizeContactEmail","parseCrmMemberRef","personKey","planLabelGrantingFeature","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","orgDataQueryForHost","restampCrmListFieldsAt","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","reassignLeadOwner","createResourceUid","readCrmTaskPicklists","CRM_SUITE_FEATURE","crmTaskReminderAfterEdit","recomputeCrmNextTaskAt","newCrmActivityRef","writeCrmEmailActivity","DAY_MS","resolveEventContact","hostId","named","hit","ref","contactsRef","contactId","String","trim","doc","get","exists","id","data","email","resolveEventLead","key","leadId","leadsRef","resolveEventPerson","contact","kind","lead","resolveMemberUid","orgId","role","uid","error","members","app","firestore","collection","member","detail","byField","where","limit","docs","runCrmAutomationStep","request","nowMs","Date","now","env","org","step","actionId","run","person","payload","runLeadStep","group","facet","groupId","type","previous","lifecycleStage","label","update","updatedAt","serverTimestamp","emit","event","previousStage","tag","slice","arrayUnion","assign","roundRobin","owner","ownerUid","ownerEmail","memberUid","verdict","outcome","reason","orgRef","visibleTo","links","companyId","title","dueInDays","Math","max","round","Number","assignee","assigneeUid","assigneeEmail","dueAtMs","priority","labels","task","status","remindAtMs","createdByUid","sourceActionId","createdAt","tasks","add","catch","console","body","logged","direction","activity","atMs","byUid","activities","tags","fresh","set","prepareCrmRecordEmail","address","to","undefined","link","activityId","file","sent","subject","sourceRef"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,gBAAgB,EAChBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,eAAe,EACfC,qBAAqB,EAGrBC,oBAAoB,EAIpBC,oBAAoB,EACpBC,cAAc,EACdC,mBAAmB,EACnBC,iBAAiB,EACjBC,qBAAqB,EACrBC,iBAAiB,EACjBC,SAAS,EACTC,wBAAwB,EACxBC,gBAAgB,EAChBC,aAAa,QACR,sBAAqB;AAS5B,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,aAAa,EACbC,mBAAmB,EACnBC,sBAAsB,QACjB,2BAA0B;AACjC,2EAA2E;AAC3E,yDAAyD;AACzD,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,6DAA6D;AAC7D,SACEC,yBAAyB,EACzBC,oBAAoB,EACpBC,iBAAiB,QACZ,4BAAwB;AAC/B,SAASC,iBAAiB,QAAQ,6CAA4C;AAI9E,SAASC,oBAAoB,QAAQ,qBAAiB;AACtD,SAASC,iBAAiB,QAAQ,kBAAc;AAChD,SAASC,wBAAwB,QAAQ,iCAA6B;AACtE,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,qBAAqB,QAAQ,0BAAsB;AAsF/E,MAAMC,SAAS,KAAK,KAAK,KAAK;AAuB9B;;;;;;;;CAQC,GACD,eAAeC,oBACbC,MAAc,EACdC,KAA+C;QAGtBA,kBAQsBC;IAT/C,MAAM,EAAEC,KAAKC,WAAW,EAAE,GAAG,MAAMpB,oBAAoBgB,QAAQ;IAC/D,MAAMK,YAAYC,QAAOL,mBAAAA,MAAMI,SAAS,YAAfJ,mBAAmB,IAAIM,IAAI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BACfY,EAAE,GAAE1I,yBAAAA,sBAAsB+I,KAAKL,EAAE,aAA7B1I,yBAAkC+I,KAAKL,EAAE;wBAC7CR,IAAI,GAAEa,aAAAA,KAAKb,IAAI,YAATa,aAAa9E,KAAKC,GAAG;wBAC3BiE,OAAO;wBACPX,gBAAgBuB,KAAKE,SAAS;wBAC9BL;wBACAnH;wBACA4E;oBACF;gBAEJ,EAAE,OAAOlD,OAAO;oBACd0E,QAAQ1E,KAAK,CAAC,gDAAgDvB,IAAIQ,EAAE,EAAEe;gBACxE;YACF;QACF;IACF,EAAE,OAAOA,OAAO;QACd0E,QAAQ1E,KAAK,CAAC,yDAAyD1B,QAAQ0B;QAC/E,OAAO;IACT;AACF"}
|
|
@@ -67,6 +67,23 @@ import { type ContactSource } from '@aglyn/aglyn/app-utils/contacts';
|
|
|
67
67
|
* way a repeat visit by a contact is an interaction and not a creation.
|
|
68
68
|
*/
|
|
69
69
|
export declare function captureContactForCrm(request: PluginContactCaptureRequest): Promise<PluginContactCaptured>;
|
|
70
|
+
/**
|
|
71
|
+
* The `lead` payload (AGL-3458), as the scalars an event may carry — the
|
|
72
|
+
* shape `contactCreatedPayload` gives a new contact, so one condition reads
|
|
73
|
+
* the same on either event: `name` always present, empty when the door had
|
|
74
|
+
* none; `formId` only when a form filed the lead, so `notEmpty` on it reads
|
|
75
|
+
* as "came in through a form" and `equals` picks one form's people out; and
|
|
76
|
+
* `campaignIds` comma-joined, only when the surface is filed under any.
|
|
77
|
+
*/
|
|
78
|
+
export declare function leadCreatedPayload(lead: {
|
|
79
|
+
leadId: string;
|
|
80
|
+
email: string;
|
|
81
|
+
name?: string | null;
|
|
82
|
+
source: string;
|
|
83
|
+
hostId: string;
|
|
84
|
+
formId?: string | null;
|
|
85
|
+
campaignIds?: readonly string[];
|
|
86
|
+
}): Record<string, string>;
|
|
70
87
|
/**
|
|
71
88
|
* The silo's word for its door, as a source the CRM stores.
|
|
72
89
|
*
|
|
@@ -16,12 +16,15 @@
|
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
17
|
import { CONTACT_SOURCE_LABELS } from "@aglyn/aglyn/app-utils/contacts";
|
|
18
18
|
import { formLeadSource } from "@aglyn/aglyn/app-utils/forms";
|
|
19
|
+
import { normalizePhone } from "@aglyn/aglyn/foundation/definitions/contact.types";
|
|
19
20
|
import { isCrmLeadOpen, normalizeContactEmail, personKey } from "@aglyn/aglyn/server";
|
|
20
|
-
import { captureHostContact } from "
|
|
21
|
+
import { captureHostContact } from "./capture-host-contact.js";
|
|
21
22
|
import { contactCaptureActor } from "@aglyn/tenant-runtime/capture-actor";
|
|
22
23
|
import { emitHostEvent } from "@aglyn/tenant-runtime/emit-host-event";
|
|
23
24
|
import { addHostLeadOutcome, findContactByEmail, firebaseAdmin, orgDataCollectionForHost, readLeadForHost } from "@aglyn/tenant-data-admin";
|
|
25
|
+
import { CONVERSION_TOUCH_DETAIL } from "@aglyn/aglyn/plugin-manager/plugin-conversion-credit";
|
|
24
26
|
import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
27
|
+
import { crmRecordOriginWriter } from "./record-origin.js";
|
|
25
28
|
/**
|
|
26
29
|
* The CRM answering the platform's contact-capture contract (AGL-3080).
|
|
27
30
|
*
|
|
@@ -78,11 +81,12 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
78
81
|
if (!normalizeContactEmail(request.identity.email)) return refusedEmail();
|
|
79
82
|
try {
|
|
80
83
|
if (surface === 'lead') {
|
|
81
|
-
if (!await heldAsContact(request)) return await fileLead(request);
|
|
84
|
+
if (!await heldAsContact(request)) return await stampedAfter(request, fileLead(request));
|
|
82
85
|
} else if (surface === 'touch') {
|
|
83
|
-
if (await openLeadFor(request)) return await fileLead(request);
|
|
86
|
+
if (await openLeadFor(request)) return await stampedAfter(request, fileLead(request));
|
|
84
87
|
}
|
|
85
88
|
const verdict = await captureOnContact(request);
|
|
89
|
+
if (verdict.ok) await stampOrigin(request);
|
|
86
90
|
if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {
|
|
87
91
|
var _request_purchaseCents;
|
|
88
92
|
await convertOpenLeadOntoContact({
|
|
@@ -104,6 +108,26 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
104
108
|
};
|
|
105
109
|
}
|
|
106
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* WHERE THE PERSON CAME FROM (AGL-3519): the door's word — a form, a
|
|
113
|
+
* booking, a newsletter, a member, an order — as the built-in Lead source
|
|
114
|
+
* it names, on a record the capture just started and that names none. A
|
|
115
|
+
* person met before keeps whatever lead source they hold, or the lack of one.
|
|
116
|
+
* Never fails the capture: the writer swallows its own errors.
|
|
117
|
+
*/ async function stampOrigin(request) {
|
|
118
|
+
var _normalizeContactEmail;
|
|
119
|
+
await crmRecordOriginWriter.stamp({
|
|
120
|
+
hostId: request.hostId,
|
|
121
|
+
email: (_normalizeContactEmail = normalizeContactEmail(request.identity.email)) != null ? _normalizeContactEmail : '',
|
|
122
|
+
origin: request.interaction.source,
|
|
123
|
+
firstTouchOnly: true
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/** A filed lead's verdict, after its origin is stamped when the filing took. */ async function stampedAfter(request, filed) {
|
|
127
|
+
const verdict = await filed;
|
|
128
|
+
if (verdict.ok) await stampOrigin(request);
|
|
129
|
+
return verdict;
|
|
130
|
+
}
|
|
107
131
|
/** The refusal every door gets for an address nothing can key. */ function refusedEmail() {
|
|
108
132
|
return {
|
|
109
133
|
ok: false,
|
|
@@ -159,9 +183,9 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
159
183
|
source
|
|
160
184
|
}, request.marketingConsent ? {
|
|
161
185
|
marketingConsent: true
|
|
162
|
-
} : {}, disclosureOf(request))
|
|
163
|
-
},
|
|
164
|
-
touch:
|
|
186
|
+
} : {}, disclosureOf(request), campaignsFiledUnder(request), phoneFillOf(request))
|
|
187
|
+
}, conversionTouchOf(request.detail).conversionTouch ? {
|
|
188
|
+
touch: conversionTouchOf(request.detail).conversionTouch
|
|
165
189
|
} : {}));
|
|
166
190
|
if (!outcome.stored) {
|
|
167
191
|
return {
|
|
@@ -172,13 +196,15 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
172
196
|
}
|
|
173
197
|
if (created) {
|
|
174
198
|
const cause = contactCaptureActor(request.interaction.source, email, request.actor);
|
|
175
|
-
await emitHostEvent(request.hostId, 'lead',
|
|
199
|
+
await emitHostEvent(request.hostId, 'lead', leadCreatedPayload({
|
|
200
|
+
leadId: key,
|
|
176
201
|
email,
|
|
202
|
+
name: request.identity.name,
|
|
177
203
|
source,
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
}
|
|
204
|
+
hostId: request.hostId,
|
|
205
|
+
formId,
|
|
206
|
+
campaignIds: campaignsFiledUnder(request).campaignIds
|
|
207
|
+
}), cause ? {
|
|
182
208
|
actor: cause
|
|
183
209
|
} : {});
|
|
184
210
|
}
|
|
@@ -190,6 +216,29 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
190
216
|
sourceAdded: outcome.sourceAdded
|
|
191
217
|
};
|
|
192
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* The `lead` payload (AGL-3458), as the scalars an event may carry — the
|
|
221
|
+
* shape `contactCreatedPayload` gives a new contact, so one condition reads
|
|
222
|
+
* the same on either event: `name` always present, empty when the door had
|
|
223
|
+
* none; `formId` only when a form filed the lead, so `notEmpty` on it reads
|
|
224
|
+
* as "came in through a form" and `equals` picks one form's people out; and
|
|
225
|
+
* `campaignIds` comma-joined, only when the surface is filed under any.
|
|
226
|
+
*/ export function leadCreatedPayload(lead) {
|
|
227
|
+
var _lead_formId, _lead_name;
|
|
228
|
+
var _lead_campaignIds;
|
|
229
|
+
const formId = String((_lead_formId = lead.formId) != null ? _lead_formId : '').trim();
|
|
230
|
+
return _extends({
|
|
231
|
+
leadId: lead.leadId,
|
|
232
|
+
email: lead.email,
|
|
233
|
+
name: String((_lead_name = lead.name) != null ? _lead_name : '').trim(),
|
|
234
|
+
source: lead.source,
|
|
235
|
+
hostId: lead.hostId
|
|
236
|
+
}, formId ? {
|
|
237
|
+
formId
|
|
238
|
+
} : {}, ((_lead_campaignIds = lead.campaignIds) == null ? void 0 : _lead_campaignIds.length) ? {
|
|
239
|
+
campaignIds: lead.campaignIds.join(',')
|
|
240
|
+
} : {});
|
|
241
|
+
}
|
|
193
242
|
/** The capture as a CONTACT — what every capture was before the rule above. */ async function captureOnContact(request) {
|
|
194
243
|
try {
|
|
195
244
|
var _request_tags;
|
|
@@ -209,7 +258,7 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
209
258
|
} : {}, request.interaction.summary ? {
|
|
210
259
|
summary: request.interaction.summary
|
|
211
260
|
} : {}, entryPointOf(request.detail))
|
|
212
|
-
},
|
|
261
|
+
}, conversionTouchOf(request.detail), request.marketingConsent === undefined ? {} : {
|
|
213
262
|
marketingConsent: request.marketingConsent
|
|
214
263
|
}, disclosureOf(request), ((_request_tags = request.tags) == null ? void 0 : _request_tags.length) ? {
|
|
215
264
|
tags: request.tags
|
|
@@ -221,6 +270,10 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
221
270
|
initialLifecycleStage: request.lifecycleFloor
|
|
222
271
|
} : {}, request.profile ? {
|
|
223
272
|
facet: request.profile
|
|
273
|
+
} : {}, phoneFillOf(request).phoneFill ? {
|
|
274
|
+
facetFill: {
|
|
275
|
+
phone: phoneFillOf(request).phoneFill
|
|
276
|
+
}
|
|
224
277
|
} : {}));
|
|
225
278
|
if ('refused' in verdict) {
|
|
226
279
|
return {
|
|
@@ -263,6 +316,22 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
263
316
|
disclosedConsentGroup: key
|
|
264
317
|
} : {};
|
|
265
318
|
}
|
|
319
|
+
/**
|
|
320
|
+
* THE PHONE A CAPTURE LEARNED IN PASSING (AGL-3493), off `profileFill`.
|
|
321
|
+
*
|
|
322
|
+
* Normalized here so a lead and a contact written by one capture keep the
|
|
323
|
+
* same E.164 string, and dropped when it will not normalize: a fill is an
|
|
324
|
+
* enrichment, and a number in some other shape on the record is the
|
|
325
|
+
* "stored three ways" failure `normalizePhone` exists to end. Both writers
|
|
326
|
+
* put it only where the record holds no phone.
|
|
327
|
+
*/ function phoneFillOf(request) {
|
|
328
|
+
var _request_profileFill;
|
|
329
|
+
const raw = (_request_profileFill = request.profileFill) == null ? void 0 : _request_profileFill['phone'];
|
|
330
|
+
const phone = typeof raw === 'string' ? normalizePhone(raw) : null;
|
|
331
|
+
return phone ? {
|
|
332
|
+
phoneFill: phone
|
|
333
|
+
} : {};
|
|
334
|
+
}
|
|
266
335
|
/**
|
|
267
336
|
* THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).
|
|
268
337
|
*
|
|
@@ -305,21 +374,21 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
|
|
|
305
374
|
*
|
|
306
375
|
* ⚠️ A different fact from `campaignIds` and the two must never be folded
|
|
307
376
|
* together — `upsert-contact.ts` says so at the field itself. A touch is the
|
|
308
|
-
* ad or the link the visitor arrived by, already resolved
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
* address.
|
|
377
|
+
* ad or the link the visitor arrived by, already resolved by the plugin that
|
|
378
|
+
* credits outcomes (`plugin-conversion-credit`) at the silo's door;
|
|
379
|
+
* `campaignIds` is which campaigns the merchant filed the capture SURFACE
|
|
380
|
+
* under, which is true of everybody who fills that form in. Folding them
|
|
381
|
+
* would credit a campaign for a visitor who typed the address.
|
|
313
382
|
*
|
|
314
|
-
* Passed through as the silo
|
|
315
|
-
* to
|
|
316
|
-
*
|
|
317
|
-
* `null` and absent mean the same thing to the writer and a caller
|
|
318
|
-
* not have to know which one it sends.
|
|
319
|
-
*/ function
|
|
320
|
-
const touch = detail == null ? void 0 : detail[
|
|
321
|
-
return touch ? {
|
|
322
|
-
|
|
383
|
+
* Passed through as the silo handed it, unread: the touch's shape belongs
|
|
384
|
+
* to the creditor that resolved it, and the creditor checks it again when
|
|
385
|
+
* the contact or the lead is credited. Only its presence is decided here,
|
|
386
|
+
* because `null` and absent mean the same thing to the writer and a caller
|
|
387
|
+
* should not have to know which one it sends.
|
|
388
|
+
*/ function conversionTouchOf(detail) {
|
|
389
|
+
const touch = detail == null ? void 0 : detail[CONVERSION_TOUCH_DETAIL];
|
|
390
|
+
return touch && typeof touch === 'object' ? {
|
|
391
|
+
conversionTouch: touch
|
|
323
392
|
} : {};
|
|
324
393
|
}
|
|
325
394
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-contact.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\nimport type {\n PluginContactCaptureRequest,\n PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport { formLeadSource } from '@aglyn/aglyn/app-utils/forms'\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { captureHostContact } from '@aglyn/tenant-runtime/capture-host-contact'\nimport { contactCaptureActor } from '@aglyn/tenant-runtime/capture-actor'\nimport { emitHostEvent } from '@aglyn/tenant-runtime/emit-host-event'\nimport {\n addHostLeadOutcome,\n findContactByEmail,\n firebaseAdmin,\n orgDataCollectionForHost,\n readLeadForHost,\n type UpsertHostContactOptions,\n} from '@aglyn/tenant-data-admin'\nimport type { ResolvedCampaignTouch } from '@aglyn/tenant-data-admin/server/campaign-conversion-attribution'\nimport { convertOpenLeadOntoContact } from './convert-open-lead'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\n/**\n * WHICH RECORD A CAPTURE LANDS ON (AGL-3232) — the Salesforce rule, decided\n * here because the CRM is the plugin that models both records.\n *\n * One person is one record: a LEAD until somebody qualifies them, a CONTACT\n * after. Every door used to write both — a lead-routed form filed a lead\n * AND a contact at stage Lead — so one person sat in two lists and the Leads\n * queue was never the whole story. Now a door says what kind of surface it\n * is (`request.surface`) and this decides:\n *\n * - a LEAD surface files a lead, unless the workspace already holds the\n * address as a contact — a customer who books a demo is a customer's\n * interaction, not a new lead — in which case the capture lands on the\n * contact and no lead is filed;\n * - a RELATIONSHIP (a member account, a purchase) makes the contact, and\n * an open lead the site held for the address is stamped converted onto\n * it, so nobody keeps working a lead who already joined or bought;\n * - a TOUCH (an unrouted form, a newsletter opt-in) lands on the open lead\n * when the site holds one — its consent and its history stay on the one\n * record the rep is working — and on the contact otherwise.\n *\n * A lead is filed through `addHostLead`, the one writer of the leads silo,\n * so it is keyed on the person, counted against the ceiling and carries the\n * campaign touch the door resolved. A NEW lead announces itself with the\n * `lead` host event, which is what a \"new lead\" automation listens for; a\n * repeat capture on a lead the site already held announces nothing, the\n * way a repeat visit by a contact is an interaction and not a creation.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n const surface = request.surface ?? 'touch'\n // The one refusal every surface shares, answered before any read: an\n // address nothing can key is a person nothing can record.\n if (!normalizeContactEmail(request.identity.email)) return refusedEmail()\n try {\n if (surface === 'lead') {\n if (!(await heldAsContact(request))) return await fileLead(request)\n } else if (surface === 'touch') {\n if (await openLeadFor(request)) return await fileLead(request)\n }\n const verdict = await captureOnContact(request)\n if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {\n await convertOpenLeadOntoContact({\n hostId: request.hostId,\n email: request.identity.email,\n contactId: verdict.contactId,\n // Money changing hands is a purchase whichever door took it — a paid\n // booking or a stay is one as much as an order is.\n by:\n request.interaction.source === 'order' || (request.purchaseCents ?? 0) > 0\n ? 'purchase'\n : 'signup',\n })\n }\n return verdict\n } catch (error) {\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/** The refusal every door gets for an address nothing can key. */\nfunction refusedEmail(): PluginContactCaptured {\n return { ok: false, reason: 'invalid-email', error: refusalText('invalid-email') }\n}\n\n/**\n * Whether the workspace already holds the address as a contact — the\n * address index first, then the query, the same lookup every dedupe uses.\n * ORG-wide, not scoped to the capturing site: the contact door dedupes\n * across every site in the org, so a person any site holds as a contact\n * is a contact, whichever site met them this time.\n */\nasync function heldAsContact(request: PluginContactCaptureRequest): Promise<boolean> {\n const contacts = await orgDataCollectionForHost(request.hostId, 'contacts')\n return (await findContactByEmail(contacts, request.identity.email)) !== null\n}\n\n/** Whether the site holds an OPEN lead for the address — neither converted nor closed. */\nasync function openLeadFor(request: PluginContactCaptureRequest): Promise<boolean> {\n const key = personKey(request.identity.email) as string\n /*\n * Through the seam, which reads the org row and falls back to a lead the\n * backfill has not reached (AGL-3275). UNSCOPED on purpose: a sibling brand\n * in the same consent group has to find this person, or its door concludes\n * there is no lead and files the duplicate this migration exists to end.\n */\n const snapshot = await readLeadForHost(request.hostId, key)\n if (!snapshot) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n return !lead.convertedContactId && isCrmLeadOpen(lead)\n}\n\n/**\n * The capture as a LEAD. The source string is the lead silo's own\n * vocabulary — `form:{formId}` for a form, the door's word otherwise — so\n * a lead's provenance survives the form being renamed, as the submission's\n * does.\n */\nasync function fileLead(request: PluginContactCaptureRequest): Promise<PluginContactCaptured> {\n const email = normalizeContactEmail(request.identity.email) as string\n const key = personKey(email) as string\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId)\n // `addHostLead` resolves and writes the org collection itself (AGL-3275);\n // this only needs to know whether the person is new, which decides the event.\n const created = !(await readLeadForHost(request.hostId, key))\n const { formId } = entryPointOf(request.detail)\n const source =\n request.interaction.source === 'form' && formId\n ? formLeadSource(formId)\n : request.interaction.source\n const outcome = await addHostLeadOutcome({\n hostRef,\n hostId: request.hostId,\n lead: {\n email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source,\n ...(request.marketingConsent ? { marketingConsent: true } : {}),\n ...disclosureOf(request),\n },\n ...(campaignTouchOf(request.detail).campaignTouch\n ? { touch: campaignTouchOf(request.detail).campaignTouch }\n : {}),\n })\n if (!outcome.stored) {\n return {\n ok: false,\n reason: 'band',\n error: 'This site is at the number of leads it may hold, so the lead was not recorded.',\n }\n }\n if (created) {\n const cause = contactCaptureActor(\n request.interaction.source,\n email,\n request.actor,\n )\n await emitHostEvent(\n request.hostId,\n 'lead',\n {\n email,\n source,\n leadId: key,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n },\n cause ? { actor: cause } : {},\n )\n }\n return { ok: true, record: 'lead', leadId: key, created, sourceAdded: outcome.sourceAdded }\n}\n\n/** The capture as a CONTACT — what every capture was before the rule above. */\nasync function captureOnContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n ...(request.actor ? { actor: request.actor } : {}),\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...campaignTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...disclosureOf(request),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...campaignsFiledUnder(request),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return {\n ok: true,\n record: 'contact',\n contactId: verdict.contactId,\n created: verdict.created,\n }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE DISCLOSURE the capture surface rendered, handed to whichever record the\n * capture lands on (AGL-3320).\n *\n * Passed through unread: both writers resolve the site's group themselves and\n * pool the opt-in only when this is its current key, so a lead and a contact\n * written by one capture record the same sites. A string or nothing, since\n * the writers compare it exactly and anything else could only fail to match.\n */\nfunction disclosureOf(\n request: PluginContactCaptureRequest,\n): { disclosedConsentGroup?: string } {\n const key = request.disclosedConsentGroup\n return typeof key === 'string' && key ? { disclosedConsentGroup: key } : {}\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * The campaigns the capture surface is filed under, as the contact writer\n * records them. A capture names what its surface is filed under by container\n * kind; the CRM keeps the `campaign` kind on the person's site facet, and a\n * kind it does not keep is the capture's to name and the CRM's to ignore.\n */\nfunction campaignsFiledUnder(\n request: PluginContactCaptureRequest,\n): Pick<UpsertHostContactOptions, 'campaignIds'> {\n const ids = request.containers?.['campaign'] ?? []\n return ids.length ? { campaignIds: ids } : {}\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved through the\n * allowlist by the silo; `campaignIds` is which campaigns the merchant filed\n * the capture SURFACE under, which is true of everybody who fills that form\n * in. Folding them would credit a campaign for a visitor who typed the\n * address.\n *\n * Passed through as the silo resolved it, unread: the touch's shape belongs\n * to whatever resolves it, and re-validating it here would be a second copy\n * of a rule that has already run. Only its presence is decided here, because\n * `null` and absent mean the same thing to the writer and a caller should\n * not have to know which one it sends.\n */\nfunction campaignTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'campaignTouch'> {\n const touch = detail?.['campaignTouch']\n return touch ? { campaignTouch: touch as ResolvedCampaignTouch } : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * ⛔ What it costs, until the union is widened: the console's source filter\n * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw\n * and matches no filter. Every first-party silo uses a word in the union, so\n * nothing does that today.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["CONTACT_SOURCE_LABELS","formLeadSource","isCrmLeadOpen","normalizeContactEmail","personKey","captureHostContact","contactCaptureActor","emitHostEvent","addHostLeadOutcome","findContactByEmail","firebaseAdmin","orgDataCollectionForHost","readLeadForHost","convertOpenLeadOntoContact","captureContactForCrm","request","surface","identity","email","refusedEmail","heldAsContact","fileLead","openLeadFor","verdict","captureOnContact","ok","record","hostId","contactId","by","interaction","source","purchaseCents","error","console","reason","refusalText","contacts","snapshot","key","lead","data","convertedContactId","hostRef","app","firestore","collection","doc","created","formId","entryPointOf","detail","outcome","name","marketingConsent","disclosureOf","campaignTouchOf","campaignTouch","touch","stored","cause","actor","leadId","sourceAdded","contactSourceOf","atMs","undefined","refId","summary","tags","length","campaignsFiledUnder","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","refused","disclosedConsentGroup","text","value","trim","path","ids","containers","campaignIds","word","String","Object","hasOwn","warn"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SACEA,qBAAqB,QAEhB,kCAAiC;AACxC,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SAEEC,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,aAAa,QAAQ,wCAAuC;AACrE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,aAAa,EACbC,wBAAwB,EACxBC,eAAe,QAEV,2BAA0B;AAEjC,SAASC,0BAA0B,QAAQ,yBAAqB;AAEhE;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,eAAeC,qBACpBC,OAAoC;QAEpBA;IAAhB,MAAMC,WAAUD,mBAAAA,QAAQC,OAAO,YAAfD,mBAAmB;IACnC,qEAAqE;IACrE,0DAA0D;IAC1D,IAAI,CAACZ,sBAAsBY,QAAQE,QAAQ,CAACC,KAAK,GAAG,OAAOC;IAC3D,IAAI;QACF,IAAIH,YAAY,QAAQ;YACtB,IAAI,CAAE,MAAMI,cAAcL,UAAW,OAAO,MAAMM,SAASN;QAC7D,OAAO,IAAIC,YAAY,SAAS;YAC9B,IAAI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D,SAASX,oBACPxD,OAAoC;;QAExBA;IAAZ,MAAMoE,eAAMpE,sBAAAA,QAAQqE,UAAU,qBAAlBrE,mBAAoB,CAAC,WAAW,mBAAI,EAAE;IAClD,OAAOoE,IAAIb,MAAM,GAAG;QAAEe,aAAaF;IAAI,IAAI,CAAC;AAC9C;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,SAAS3B,gBACPL,MAAqD;IAErD,MAAMO,QAAQP,0BAAAA,MAAQ,CAAC,gBAAgB;IACvC,OAAOO,QAAQ;QAAED,eAAeC;IAA+B,IAAI,CAAC;AACtE;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASM,gBAAgBjC,MAAc;IAC5C,MAAMuD,OAAOC,OAAOxD,iBAAAA,SAAU,IAAIkD,IAAI;IACtC,IAAI,CAACO,OAAOC,MAAM,CAACzF,uBAAuBsF,OAAO;QAC/C,sEAAsE;QACtE,2DAA2D;QAC3DpD,QAAQwD,IAAI,CACV,CAAC,6BAA6B,EAAEJ,KAAK,kCAAkC,CAAC,GACtE;IAEN;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAASlD,YAAYD,MAAqD;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-contact.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\nimport type {\n PluginContactCaptureRequest,\n PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport { formLeadSource } from '@aglyn/aglyn/app-utils/forms'\nimport { normalizePhone } from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { captureHostContact } from './capture-host-contact'\nimport { contactCaptureActor } from '@aglyn/tenant-runtime/capture-actor'\nimport { emitHostEvent } from '@aglyn/tenant-runtime/emit-host-event'\nimport {\n addHostLeadOutcome,\n findContactByEmail,\n firebaseAdmin,\n orgDataCollectionForHost,\n readLeadForHost,\n type UpsertHostContactOptions,\n} from '@aglyn/tenant-data-admin'\nimport {\n CONVERSION_TOUCH_DETAIL,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { convertOpenLeadOntoContact } from './convert-open-lead'\nimport { crmRecordOriginWriter } from './record-origin'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\n/**\n * WHICH RECORD A CAPTURE LANDS ON (AGL-3232) — the Salesforce rule, decided\n * here because the CRM is the plugin that models both records.\n *\n * One person is one record: a LEAD until somebody qualifies them, a CONTACT\n * after. Every door used to write both — a lead-routed form filed a lead\n * AND a contact at stage Lead — so one person sat in two lists and the Leads\n * queue was never the whole story. Now a door says what kind of surface it\n * is (`request.surface`) and this decides:\n *\n * - a LEAD surface files a lead, unless the workspace already holds the\n * address as a contact — a customer who books a demo is a customer's\n * interaction, not a new lead — in which case the capture lands on the\n * contact and no lead is filed;\n * - a RELATIONSHIP (a member account, a purchase) makes the contact, and\n * an open lead the site held for the address is stamped converted onto\n * it, so nobody keeps working a lead who already joined or bought;\n * - a TOUCH (an unrouted form, a newsletter opt-in) lands on the open lead\n * when the site holds one — its consent and its history stay on the one\n * record the rep is working — and on the contact otherwise.\n *\n * A lead is filed through `addHostLead`, the one writer of the leads silo,\n * so it is keyed on the person, counted against the ceiling and carries the\n * campaign touch the door resolved. A NEW lead announces itself with the\n * `lead` host event, which is what a \"new lead\" automation listens for; a\n * repeat capture on a lead the site already held announces nothing, the\n * way a repeat visit by a contact is an interaction and not a creation.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n const surface = request.surface ?? 'touch'\n // The one refusal every surface shares, answered before any read: an\n // address nothing can key is a person nothing can record.\n if (!normalizeContactEmail(request.identity.email)) return refusedEmail()\n try {\n if (surface === 'lead') {\n if (!(await heldAsContact(request))) return await stampedAfter(request, fileLead(request))\n } else if (surface === 'touch') {\n if (await openLeadFor(request)) return await stampedAfter(request, fileLead(request))\n }\n const verdict = await captureOnContact(request)\n if (verdict.ok) await stampOrigin(request)\n if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {\n await convertOpenLeadOntoContact({\n hostId: request.hostId,\n email: request.identity.email,\n contactId: verdict.contactId,\n // Money changing hands is a purchase whichever door took it — a paid\n // booking or a stay is one as much as an order is.\n by:\n request.interaction.source === 'order' || (request.purchaseCents ?? 0) > 0\n ? 'purchase'\n : 'signup',\n })\n }\n return verdict\n } catch (error) {\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * WHERE THE PERSON CAME FROM (AGL-3519): the door's word — a form, a\n * booking, a newsletter, a member, an order — as the built-in Lead source\n * it names, on a record the capture just started and that names none. A\n * person met before keeps whatever lead source they hold, or the lack of one.\n * Never fails the capture: the writer swallows its own errors.\n */\nasync function stampOrigin(request: PluginContactCaptureRequest): Promise<void> {\n await crmRecordOriginWriter.stamp({\n hostId: request.hostId,\n email: normalizeContactEmail(request.identity.email) ?? '',\n origin: request.interaction.source,\n firstTouchOnly: true,\n })\n}\n\n/** A filed lead's verdict, after its origin is stamped when the filing took. */\nasync function stampedAfter(\n request: PluginContactCaptureRequest,\n filed: Promise<PluginContactCaptured>,\n): Promise<PluginContactCaptured> {\n const verdict = await filed\n if (verdict.ok) await stampOrigin(request)\n return verdict\n}\n\n/** The refusal every door gets for an address nothing can key. */\nfunction refusedEmail(): PluginContactCaptured {\n return { ok: false, reason: 'invalid-email', error: refusalText('invalid-email') }\n}\n\n/**\n * Whether the workspace already holds the address as a contact — the\n * address index first, then the query, the same lookup every dedupe uses.\n * ORG-wide, not scoped to the capturing site: the contact door dedupes\n * across every site in the org, so a person any site holds as a contact\n * is a contact, whichever site met them this time.\n */\nasync function heldAsContact(request: PluginContactCaptureRequest): Promise<boolean> {\n const contacts = await orgDataCollectionForHost(request.hostId, 'contacts')\n return (await findContactByEmail(contacts, request.identity.email)) !== null\n}\n\n/** Whether the site holds an OPEN lead for the address — neither converted nor closed. */\nasync function openLeadFor(request: PluginContactCaptureRequest): Promise<boolean> {\n const key = personKey(request.identity.email) as string\n /*\n * Through the seam, which reads the org row and falls back to a lead the\n * backfill has not reached (AGL-3275). UNSCOPED on purpose: a sibling brand\n * in the same consent group has to find this person, or its door concludes\n * there is no lead and files the duplicate this migration exists to end.\n */\n const snapshot = await readLeadForHost(request.hostId, key)\n if (!snapshot) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n return !lead.convertedContactId && isCrmLeadOpen(lead)\n}\n\n/**\n * The capture as a LEAD. The source string is the lead silo's own\n * vocabulary — `form:{formId}` for a form, the door's word otherwise — so\n * a lead's provenance survives the form being renamed, as the submission's\n * does.\n */\nasync function fileLead(request: PluginContactCaptureRequest): Promise<PluginContactCaptured> {\n const email = normalizeContactEmail(request.identity.email) as string\n const key = personKey(email) as string\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId)\n // `addHostLead` resolves and writes the org collection itself (AGL-3275);\n // this only needs to know whether the person is new, which decides the event.\n const created = !(await readLeadForHost(request.hostId, key))\n const { formId } = entryPointOf(request.detail)\n const source =\n request.interaction.source === 'form' && formId\n ? formLeadSource(formId)\n : request.interaction.source\n const outcome = await addHostLeadOutcome({\n hostRef,\n hostId: request.hostId,\n lead: {\n email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source,\n ...(request.marketingConsent ? { marketingConsent: true } : {}),\n ...disclosureOf(request),\n // Filed under the surface's campaigns, as the contact door files a\n // contact (AGL-3458): a lead-routed form in a campaign makes a lead\n // in that campaign.\n ...campaignsFiledUnder(request),\n ...phoneFillOf(request),\n },\n ...(conversionTouchOf(request.detail).conversionTouch\n ? { touch: conversionTouchOf(request.detail).conversionTouch }\n : {}),\n })\n if (!outcome.stored) {\n return {\n ok: false,\n reason: 'band',\n error: 'This site is at the number of leads it may hold, so the lead was not recorded.',\n }\n }\n if (created) {\n const cause = contactCaptureActor(\n request.interaction.source,\n email,\n request.actor,\n )\n await emitHostEvent(\n request.hostId,\n 'lead',\n leadCreatedPayload({\n leadId: key,\n email,\n name: request.identity.name,\n source,\n hostId: request.hostId,\n formId,\n campaignIds: campaignsFiledUnder(request).campaignIds,\n }),\n cause ? { actor: cause } : {},\n )\n }\n return { ok: true, record: 'lead', leadId: key, created, sourceAdded: outcome.sourceAdded }\n}\n\n/**\n * The `lead` payload (AGL-3458), as the scalars an event may carry — the\n * shape `contactCreatedPayload` gives a new contact, so one condition reads\n * the same on either event: `name` always present, empty when the door had\n * none; `formId` only when a form filed the lead, so `notEmpty` on it reads\n * as \"came in through a form\" and `equals` picks one form's people out; and\n * `campaignIds` comma-joined, only when the surface is filed under any.\n */\nexport function leadCreatedPayload(lead: {\n leadId: string\n email: string\n name?: string | null\n source: string\n hostId: string\n formId?: string | null\n campaignIds?: readonly string[]\n}): Record<string, string> {\n const formId = String(lead.formId ?? '').trim()\n return {\n leadId: lead.leadId,\n email: lead.email,\n name: String(lead.name ?? '').trim(),\n source: lead.source,\n hostId: lead.hostId,\n ...(formId ? { formId } : {}),\n ...(lead.campaignIds?.length ? { campaignIds: lead.campaignIds.join(',') } : {}),\n }\n}\n\n/** The capture as a CONTACT — what every capture was before the rule above. */\nasync function captureOnContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n ...(request.actor ? { actor: request.actor } : {}),\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...conversionTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...disclosureOf(request),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...campaignsFiledUnder(request),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n ...(phoneFillOf(request).phoneFill\n ? { facetFill: { phone: phoneFillOf(request).phoneFill } }\n : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return {\n ok: true,\n record: 'contact',\n contactId: verdict.contactId,\n created: verdict.created,\n }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE DISCLOSURE the capture surface rendered, handed to whichever record the\n * capture lands on (AGL-3320).\n *\n * Passed through unread: both writers resolve the site's group themselves and\n * pool the opt-in only when this is its current key, so a lead and a contact\n * written by one capture record the same sites. A string or nothing, since\n * the writers compare it exactly and anything else could only fail to match.\n */\nfunction disclosureOf(\n request: PluginContactCaptureRequest,\n): { disclosedConsentGroup?: string } {\n const key = request.disclosedConsentGroup\n return typeof key === 'string' && key ? { disclosedConsentGroup: key } : {}\n}\n\n/**\n * THE PHONE A CAPTURE LEARNED IN PASSING (AGL-3493), off `profileFill`.\n *\n * Normalized here so a lead and a contact written by one capture keep the\n * same E.164 string, and dropped when it will not normalize: a fill is an\n * enrichment, and a number in some other shape on the record is the\n * \"stored three ways\" failure `normalizePhone` exists to end. Both writers\n * put it only where the record holds no phone.\n */\nfunction phoneFillOf(request: PluginContactCaptureRequest): { phoneFill?: string } {\n const raw = request.profileFill?.['phone']\n const phone = typeof raw === 'string' ? normalizePhone(raw) : null\n return phone ? { phoneFill: phone } : {}\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * The campaigns the capture surface is filed under, as the contact writer\n * records them. A capture names what its surface is filed under by container\n * kind; the CRM keeps the `campaign` kind on the person's site facet, and a\n * kind it does not keep is the capture's to name and the CRM's to ignore.\n */\nfunction campaignsFiledUnder(\n request: PluginContactCaptureRequest,\n): Pick<UpsertHostContactOptions, 'campaignIds'> {\n const ids = request.containers?.['campaign'] ?? []\n return ids.length ? { campaignIds: ids } : {}\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved by the plugin that\n * credits outcomes (`plugin-conversion-credit`) at the silo's door;\n * `campaignIds` is which campaigns the merchant filed the capture SURFACE\n * under, which is true of everybody who fills that form in. Folding them\n * would credit a campaign for a visitor who typed the address.\n *\n * Passed through as the silo handed it, unread: the touch's shape belongs\n * to the creditor that resolved it, and the creditor checks it again when\n * the contact or the lead is credited. Only its presence is decided here,\n * because `null` and absent mean the same thing to the writer and a caller\n * should not have to know which one it sends.\n */\nfunction conversionTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'conversionTouch'> {\n const touch = detail?.[CONVERSION_TOUCH_DETAIL]\n return touch && typeof touch === 'object'\n ? { conversionTouch: touch as PluginConversionTouch }\n : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * ⛔ What it costs, until the union is widened: the console's source filter\n * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw\n * and matches no filter. Every first-party silo uses a word in the union, so\n * nothing does that today.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["CONTACT_SOURCE_LABELS","formLeadSource","normalizePhone","isCrmLeadOpen","normalizeContactEmail","personKey","captureHostContact","contactCaptureActor","emitHostEvent","addHostLeadOutcome","findContactByEmail","firebaseAdmin","orgDataCollectionForHost","readLeadForHost","CONVERSION_TOUCH_DETAIL","convertOpenLeadOntoContact","crmRecordOriginWriter","captureContactForCrm","request","surface","identity","email","refusedEmail","heldAsContact","stampedAfter","fileLead","openLeadFor","verdict","captureOnContact","ok","stampOrigin","record","hostId","contactId","by","interaction","source","purchaseCents","error","console","reason","stamp","origin","firstTouchOnly","filed","refusalText","contacts","snapshot","key","lead","data","convertedContactId","hostRef","app","firestore","collection","doc","created","formId","entryPointOf","detail","outcome","name","marketingConsent","disclosureOf","campaignsFiledUnder","phoneFillOf","conversionTouchOf","conversionTouch","touch","stored","cause","actor","leadCreatedPayload","leadId","campaignIds","sourceAdded","String","trim","length","join","contactSourceOf","atMs","undefined","refId","summary","tags","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","phoneFill","facetFill","phone","refused","disclosedConsentGroup","raw","profileFill","text","value","path","ids","containers","word","Object","hasOwn","warn"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SACEA,qBAAqB,QAEhB,kCAAiC;AACxC,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAEEC,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,aAAa,QAAQ,wCAAuC;AACrE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,aAAa,EACbC,wBAAwB,EACxBC,eAAe,QAEV,2BAA0B;AACjC,SACEC,uBAAuB,QAElB,uDAAsD;AAC7D,SAASC,0BAA0B,QAAQ,yBAAqB;AAChE,SAASC,qBAAqB,QAAQ,qBAAiB;AAEvD;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,eAAeC,qBACpBC,OAAoC;QAEpBA;IAAhB,MAAMC,WAAUD,mBAAAA,QAAQC,OAAO,YAAfD,mBAAmB;IACnC,qEAAqE;IACrE,0DAA0D;IAC1D,IAAI,CAACd,sBAAsBc,QAAQE,QAAQ,CAACC,KAAK,GAAG,OAAOC;IAC3D,IAAI;QACF,IAAIH,YAAY,QAAQ;YACtB,IAAI,CAAE,MAAMI,cAAcL,UAAW,OAAO,MAAMM,aAAaN,SAASO,SAASP;QACnF,OAAO,IAAIC,YAAY,SAAS;YAC9B,IAAI,MAAMO,YAAYR,UAAU,OAAO,MAAMM,aAAaN,SAASO,SAASP;QAC9E;QACA,MAAMS,UAA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AKvC,0BAAAA,MAAQ,CAAC,SAAS;IACtC,MAAMyC,OAAOF,KAAKvC,0BAAAA,MAAQ,CAAC,OAAO;IAClC,OAAO,aACDF,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvB2C,OAAO;QAAEA;IAAK,IAAI,CAAC;AAE3B;AAEA;;;;;CAKC,GACD,SAASpC,oBACP/C,OAAoC;;QAExBA;IAAZ,MAAMoF,eAAMpF,sBAAAA,QAAQqF,UAAU,qBAAlBrF,mBAAoB,CAAC,WAAW,mBAAI,EAAE;IAClD,OAAOoF,IAAIvB,MAAM,GAAG;QAAEJ,aAAa2B;IAAI,IAAI,CAAC;AAC9C;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,SAASnC,kBACPP,MAAqD;IAErD,MAAMS,QAAQT,0BAAAA,MAAQ,CAAC9C,wBAAwB;IAC/C,OAAOuD,SAAS,OAAOA,UAAU,WAC7B;QAAED,iBAAiBC;IAA+B,IAClD,CAAC;AACP;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASY,gBAAgB7C,MAAc;IAC5C,MAAMoE,OAAO3B,OAAOzC,iBAAAA,SAAU,IAAI0C,IAAI;IACtC,IAAI,CAAC2B,OAAOC,MAAM,CAAC1G,uBAAuBwG,OAAO;QAC/C,sEAAsE;QACtE,2DAA2D;QAC3DjE,QAAQoE,IAAI,CACV,CAAC,6BAA6B,EAAEH,KAAK,kCAAkC,CAAC,GACtE;IAEN;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAAS3D,YAAYL,MAAqD;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type HostContactCreated, type UpsertHostContactOptions, type UpsertHostContactVerdict } from '@aglyn/tenant-data-admin';
|
|
18
|
+
import type { HostEventActor, HostEventPayload } from '@aglyn/tenant-runtime/host-event-listeners';
|
|
19
|
+
/**
|
|
20
|
+
* THE contact capture door for a server path (AGL-2605).
|
|
21
|
+
*
|
|
22
|
+
* `upsertHostContact` writes the contact and reports, through its
|
|
23
|
+
* `onCreated` hook, when the write made a NEW person. This wrapper is the
|
|
24
|
+
* one place that hook is bound to `contactCreated`, and it is the function
|
|
25
|
+
* every server door calls — the forms route, the membership and newsletter
|
|
26
|
+
* handlers, the order and booking webhooks. A door that calls
|
|
27
|
+
* `upsertHostContact` directly still captures the contact and fires nothing,
|
|
28
|
+
* which is a contact no automation can welcome; `capture-host-contact.spec`
|
|
29
|
+
* scans for exactly that call.
|
|
30
|
+
*
|
|
31
|
+
* ## Why the binding lives here and not in the data library
|
|
32
|
+
*
|
|
33
|
+
* What listens for the event — the automation engine among them — imports
|
|
34
|
+
* the data library for its Firestore handle, its org helpers and its
|
|
35
|
+
* senders. The data library emitting an event would import the listeners
|
|
36
|
+
* back, which is a cycle, and the module boundaries (`scope:data` depends on
|
|
37
|
+
* data and util only) refuse it in any case. So the lower layer reports a
|
|
38
|
+
* fact and this layer, which already knows how to announce one, announces
|
|
39
|
+
* it. The alternative — a sink the runtime registers into when its module
|
|
40
|
+
* happens to be imported — would fire only in a process that had loaded the
|
|
41
|
+
* runtime, and a Stripe webhook that created a contact in a process that had
|
|
42
|
+
* not would announce nothing with no error anywhere. The listeners themselves
|
|
43
|
+
* are registered by a call made at boot (`host-event-listeners.ts`), so every
|
|
44
|
+
* process has them before its first request.
|
|
45
|
+
*
|
|
46
|
+
* Fire-and-forget in the same sense the capture itself is: the hook's
|
|
47
|
+
* failure is caught inside `upsertHostContact`, so a runner that throws
|
|
48
|
+
* costs the door nothing, and this function never rejects.
|
|
49
|
+
*
|
|
50
|
+
* ## The company, before the announcement (AGL-2613)
|
|
51
|
+
*
|
|
52
|
+
* A new person with a work email address is linked to the company at that
|
|
53
|
+
* domain here, in the same hook, BEFORE `contactCreated` goes out — so an
|
|
54
|
+
* automation that reads the new contact finds them already filed, rather
|
|
55
|
+
* than racing a link that lands a moment later. Only when the door did not
|
|
56
|
+
* name a company itself: the console's drawer and an import row that
|
|
57
|
+
* carried one have written it into the facet, and the capture must not
|
|
58
|
+
* second-guess a person's choice with a domain match. The association never
|
|
59
|
+
* rejects, and its own catch keeps a failed lookup from costing the event.
|
|
60
|
+
*
|
|
61
|
+
* ## The owner, on the same terms (AGL-2618)
|
|
62
|
+
*
|
|
63
|
+
* Then the org's assignment rules and the site's default owner decide who
|
|
64
|
+
* follows the new person up — again before `contactCreated`, so an
|
|
65
|
+
* automation's "create a task for the owner" finds one — and again only
|
|
66
|
+
* when the door named none: a drawer, an import column or a conversion
|
|
67
|
+
* that picked an owner has said whose the record is. The pass reads the
|
|
68
|
+
* form and the tags off the same options the data library was handed,
|
|
69
|
+
* because the created-report carries the identity and not the routing.
|
|
70
|
+
* It never rejects either; a record it could not assign is one somebody
|
|
71
|
+
* assigns by hand, which is what every record was before this existed.
|
|
72
|
+
*
|
|
73
|
+
* What this does NOT do is close a lead (AGL-3232): a lead is the CRM's
|
|
74
|
+
* record, and which relationship closes one is the CRM's rule, answered in
|
|
75
|
+
* its capture writer for the doors that report through the capture seam.
|
|
76
|
+
* The order doors call this directly and close nothing — a buyer with an
|
|
77
|
+
* open lead is a lead the rep converts, as in Salesforce.
|
|
78
|
+
*/
|
|
79
|
+
export declare function captureHostContact(captureOptions: Omit<UpsertHostContactOptions, 'onCreated'> & {
|
|
80
|
+
/** Who caused the capture, when the door knows (AGL-3376). */
|
|
81
|
+
actor?: HostEventActor;
|
|
82
|
+
}): Promise<UpsertHostContactVerdict>;
|
|
83
|
+
/**
|
|
84
|
+
* The `contactCreated` payload, as the scalars an event may carry.
|
|
85
|
+
*
|
|
86
|
+
* `HostEventPayload` holds strings, numbers and booleans and nothing
|
|
87
|
+
* nested, because the payload seeds an expression scope and a condition
|
|
88
|
+
* editor whose operators compare strings. So `campaignIds` rides as one
|
|
89
|
+
* comma-joined string — `contains` still finds a campaign in it — and is
|
|
90
|
+
* present only when the capture had campaigns, so `notEmpty` on it reads
|
|
91
|
+
* as "came in through a campaign form". `name` and `lifecycleStage` are
|
|
92
|
+
* always present, empty when the door had none, so a condition on either
|
|
93
|
+
* never sees a missing key: `lifecycleStage == "lead"` is the filter that
|
|
94
|
+
* picks the form captures out of the sign-ups (AGL-2612).
|
|
95
|
+
*
|
|
96
|
+
* `formId` rides the same way `campaignIds` does — present only when the
|
|
97
|
+
* capture came through a form — because the created-report carries the
|
|
98
|
+
* person's identity and not the routing, and the form is routing: it is
|
|
99
|
+
* read off the interaction the door was handed. Present, it is what lets a
|
|
100
|
+
* condition say `formId` equals this form and no other (AGL-2626); absent,
|
|
101
|
+
* `notEmpty` on it reads as "came in through a form".
|
|
102
|
+
*/
|
|
103
|
+
export declare function contactCreatedPayload(created: HostContactCreated, formId?: string | null): HostEventPayload;
|
|
104
|
+
export default captureHostContact;
|