@aglyn/plugins-crm 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/contact-list-columns.js +4 -3
- package/src/lib/components/contact-list-columns.js.map +1 -1
- package/src/lib/components/contact-properties-card.js +6 -2
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contacts-bulk-bar.js +16 -5
- package/src/lib/components/contacts-bulk-bar.js.map +1 -1
- package/src/lib/components/contacts-section.js +6 -13
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-record-insights-zone.js +7 -0
- package/src/lib/components/crm-record-insights-zone.js.map +1 -1
- package/src/lib/components/crm-record-picker.js +25 -9
- package/src/lib/components/crm-record-picker.js.map +1 -1
- package/src/lib/components/deal-board.d.ts +2 -0
- package/src/lib/components/deal-board.js +20 -11
- package/src/lib/components/deal-board.js.map +1 -1
- package/src/lib/components/deal-stage-card.js +41 -28
- package/src/lib/components/deal-stage-card.js.map +1 -1
- package/src/lib/components/deals-bulk-bar.js +20 -10
- package/src/lib/components/deals-bulk-bar.js.map +1 -1
- package/src/lib/components/deals-section.js +1 -0
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/email-capture-card.d.ts +1 -1
- package/src/lib/components/email-capture-card.js +2 -1
- package/src/lib/components/email-capture-card.js.map +1 -1
- package/src/lib/components/record-sharing-card.d.ts +6 -5
- package/src/lib/components/record-sharing-card.js +45 -30
- package/src/lib/components/record-sharing-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +18 -11
- package/src/lib/components/settings-section.js +36 -19
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +2 -1
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/components/use-org-members.d.ts +17 -10
- package/src/lib/components/use-org-members.js +31 -66
- package/src/lib/components/use-org-members.js.map +1 -1
- package/src/lib/declarations.d.ts +6 -2
- package/src/lib/declarations.js +14 -2
- package/src/lib/declarations.js.map +1 -1
- package/src/lib/hooks/use-crm-activity-logger.d.ts +2 -2
- package/src/lib/hooks/use-crm-activity-logger.js +2 -2
- package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
- package/src/lib/hooks/use-crm-record-names.js +59 -6
- package/src/lib/hooks/use-crm-record-names.js.map +1 -1
- package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
- package/src/lib/hooks/use-deal-stage-api.js +7 -2
- package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
- package/src/lib/hooks/use-org-member-directory.js +49 -12
- package/src/lib/hooks/use-org-member-directory.js.map +1 -1
- package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
- package/src/lib/hooks/use-stage-move-blocked.js +71 -0
- package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
- package/src/lib/model/crm-api.d.ts +1 -1
- package/src/lib/model/crm-api.js +1 -1
- package/src/lib/model/crm-api.js.map +1 -1
- package/src/lib/model/crm-permissions.d.ts +35 -0
- package/src/lib/model/crm-permissions.js +87 -0
- package/src/lib/model/crm-permissions.js.map +1 -0
- package/src/lib/model/crm-sharing.d.ts +1 -1
- package/src/lib/model/crm-sharing.js +1 -1
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/plugin.js +4 -5
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/capture-contact.d.ts +3 -3
- package/src/lib/server/capture-contact.js +3 -3
- package/src/lib/server/capture-contact.js.map +1 -1
- package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
- package/src/lib/server/crm-setup-writers.server.js +4 -16
- package/src/lib/server/crm-setup-writers.server.js.map +1 -1
- package/src/lib/server/crm-sharing.d.ts +5 -4
- package/src/lib/server/crm-sharing.js +8 -6
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-template-duplicate.js +7 -7
- package/src/lib/server/email-template-duplicate.js.map +1 -1
- package/src/lib/server/inbound-address.d.ts +9 -7
- package/src/lib/server/inbound-address.js +18 -15
- package/src/lib/server/inbound-address.js.map +1 -1
- package/src/lib/server/org-caller.d.ts +19 -5
- package/src/lib/server/org-caller.js +25 -5
- package/src/lib/server/org-caller.js.map +1 -1
- package/src/lib/server/recipe-routes.d.ts +0 -34
- package/src/lib/server/recipe-routes.js +11 -10
- package/src/lib/server/recipe-routes.js.map +1 -1
- package/src/lib/server/task-routes.d.ts +6 -5
- package/src/lib/server/task-routes.js +11 -13
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server-deal-stage.d.ts +11 -6
- package/src/lib/server-deal-stage.js +18 -16
- package/src/lib/server-deal-stage.js.map +1 -1
- package/src/lib/server.js +16 -18
- package/src/lib/server.js.map +1 -1
|
@@ -20,7 +20,11 @@
|
|
|
20
20
|
*
|
|
21
21
|
* Its recipes (AGL-2626), so the automation editor's Recipes menu offers
|
|
22
22
|
* "Welcome a new lead" on a site whose CRM pages were never opened, and the
|
|
23
|
-
* automation it builds names the recipe it began as.
|
|
24
|
-
*
|
|
23
|
+
* automation it builds names the recipe it began as. And its keys, "Change CRM
|
|
24
|
+
* settings" and "Move contacts and deals between stages" (AGL-4047), so the
|
|
25
|
+
* role editor offers them, a custom role or a per-member override keeps them,
|
|
26
|
+
* and the routes and the projection resolve them before any CRM surface loads.
|
|
27
|
+
* Light by construction: all of it is definitions, and nothing here reaches
|
|
28
|
+
* Firestore or React.
|
|
25
29
|
*/
|
|
26
30
|
export declare function registerCrmDeclarations(): void;
|
package/src/lib/declarations.js
CHANGED
|
@@ -16,7 +16,10 @@
|
|
|
16
16
|
*/ // The seam from its own module, not the plugin-manager barrel: both apps load
|
|
17
17
|
// this at boot, and the barrel reaches the client contexts.
|
|
18
18
|
import { registerInteractionRecipes } from "@aglyn/aglyn/plugin-manager/interaction-recipes";
|
|
19
|
+
import { registerPluginEntitlements } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
|
|
20
|
+
import { registerPluginPermissions } from "@aglyn/aglyn/plugin-manager/plugin-permissions";
|
|
19
21
|
import { BUNDLE_ID } from "./constants/bundle-common.js";
|
|
22
|
+
import { CRM_PERMISSIONS, CRM_SITE_PERMISSIONS } from "./model/crm-permissions.js";
|
|
20
23
|
import { CRM_ACTION_RECIPES } from "./model/crm-recipes.js";
|
|
21
24
|
/**
|
|
22
25
|
* The CRM's DECLARATIONS: what another surface reads of this plugin before any
|
|
@@ -24,12 +27,21 @@ import { CRM_ACTION_RECIPES } from "./model/crm-recipes.js";
|
|
|
24
27
|
*
|
|
25
28
|
* Its recipes (AGL-2626), so the automation editor's Recipes menu offers
|
|
26
29
|
* "Welcome a new lead" on a site whose CRM pages were never opened, and the
|
|
27
|
-
* automation it builds names the recipe it began as.
|
|
28
|
-
*
|
|
30
|
+
* automation it builds names the recipe it began as. And its keys, "Change CRM
|
|
31
|
+
* settings" and "Move contacts and deals between stages" (AGL-4047), so the
|
|
32
|
+
* role editor offers them, a custom role or a per-member override keeps them,
|
|
33
|
+
* and the routes and the projection resolve them before any CRM surface loads.
|
|
34
|
+
* Light by construction: all of it is definitions, and nothing here reaches
|
|
35
|
+
* Firestore or React.
|
|
29
36
|
*/ export function registerCrmDeclarations() {
|
|
30
37
|
registerInteractionRecipes(CRM_ACTION_RECIPES, {
|
|
31
38
|
pluginId: BUNDLE_ID
|
|
32
39
|
});
|
|
40
|
+
registerPluginPermissions(CRM_PERMISSIONS);
|
|
41
|
+
registerPluginEntitlements({
|
|
42
|
+
pluginId: BUNDLE_ID,
|
|
43
|
+
orgPermissions: CRM_SITE_PERMISSIONS
|
|
44
|
+
});
|
|
33
45
|
}
|
|
34
46
|
|
|
35
47
|
//# sourceMappingURL=declarations.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionRecipes } from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_ACTION_RECIPES } from './model/crm-recipes'\n\n/**\n * The CRM's DECLARATIONS: what another surface reads of this plugin before any\n * of its own surfaces load, in both apps and in the console's browser.\n *\n * Its recipes (AGL-2626), so the automation editor's Recipes menu offers\n * \"Welcome a new lead\" on a site whose CRM pages were never opened, and the\n * automation it builds names the recipe it began as.
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionRecipes } from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport { registerPluginEntitlements } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport { registerPluginPermissions } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_PERMISSIONS, CRM_SITE_PERMISSIONS } from './model/crm-permissions'\nimport { CRM_ACTION_RECIPES } from './model/crm-recipes'\n\n/**\n * The CRM's DECLARATIONS: what another surface reads of this plugin before any\n * of its own surfaces load, in both apps and in the console's browser.\n *\n * Its recipes (AGL-2626), so the automation editor's Recipes menu offers\n * \"Welcome a new lead\" on a site whose CRM pages were never opened, and the\n * automation it builds names the recipe it began as. And its keys, \"Change CRM\n * settings\" and \"Move contacts and deals between stages\" (AGL-4047), so the\n * role editor offers them, a custom role or a per-member override keeps them,\n * and the routes and the projection resolve them before any CRM surface loads.\n * Light by construction: all of it is definitions, and nothing here reaches\n * Firestore or React.\n */\nexport function registerCrmDeclarations(): void {\n registerInteractionRecipes(CRM_ACTION_RECIPES, { pluginId: BUNDLE_ID })\n registerPluginPermissions(CRM_PERMISSIONS)\n registerPluginEntitlements({ pluginId: BUNDLE_ID, orgPermissions: CRM_SITE_PERMISSIONS })\n}\n"],"names":["registerInteractionRecipes","registerPluginEntitlements","registerPluginPermissions","BUNDLE_ID","CRM_PERMISSIONS","CRM_SITE_PERMISSIONS","CRM_ACTION_RECIPES","registerCrmDeclarations","pluginId","orgPermissions"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,yBAAyB,QAAQ,iDAAgD;AAC1F,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,eAAe,EAAEC,oBAAoB,QAAQ,6BAAyB;AAC/E,SAASC,kBAAkB,QAAQ,yBAAqB;AAExD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC;IACdP,2BAA2BM,oBAAoB;QAAEE,UAAUL;IAAU;IACrED,0BAA0BE;IAC1BH,2BAA2B;QAAEO,UAAUL;QAAWM,gBAAgBJ;IAAqB;AACzF"}
|
|
@@ -27,8 +27,8 @@ export interface CrmActivityTarget {
|
|
|
27
27
|
*
|
|
28
28
|
* ## The two gates are on different axes, and that is the bug this closes
|
|
29
29
|
*
|
|
30
|
-
* The record write asks `canWriteOrgData()` —
|
|
31
|
-
*
|
|
30
|
+
* The record write asks `canWriteOrgData()` — "Manage data" in the org, plus
|
|
31
|
+
* the scope tokens. The line asks `canWriteHostContent()`,
|
|
32
32
|
* which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows
|
|
33
33
|
* nothing about the org roster. At the org hub the two come apart for
|
|
34
34
|
* members who are genuinely admitted to the hub:
|
|
@@ -30,8 +30,8 @@ import { useCrmOrgMount } from "./use-crm-org-mount.js";
|
|
|
30
30
|
*
|
|
31
31
|
* ## The two gates are on different axes, and that is the bug this closes
|
|
32
32
|
*
|
|
33
|
-
* The record write asks `canWriteOrgData()` —
|
|
34
|
-
*
|
|
33
|
+
* The record write asks `canWriteOrgData()` — "Manage data" in the org, plus
|
|
34
|
+
* the scope tokens. The line asks `canWriteHostContent()`,
|
|
35
35
|
* which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows
|
|
36
36
|
* nothing about the org roster. At the org hub the two come apart for
|
|
37
37
|
* members who are genuinely admitted to the hub:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-activity-logger.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'use client'\n\nimport {\n type HostActivityTarget,\n useHostActivityLogger,\n} from '@aglyn/tenant-feature-instance'\nimport { useCallback } from 'react'\nimport { useCrmApi } from '../components/use-crm-api'\nimport type { CrmOrgActivityKind } from '../constants/api-routes'\nimport {\n orgActivityRefusal,\n reportDroppedActivityLine,\n} from '../model/crm-activity-report'\nimport { useCrmOrgMount } from './use-crm-org-mount'\n\n/**\n * A record kind BOTH feeds accept.\n *\n * The org feed also files tasks and the host feed also files screens, and a\n * line that can land in either has to name something both presenters can\n * render as a link. Spelled as the intersection rather than a third hand-\n * written union so a kind added to one side alone cannot silently become a\n * line the other side draws as unknown.\n */\nexport type CrmActivityKind = Extract<\n CrmOrgActivityKind,\n HostActivityTarget['type']\n>\n\n/** What a CRM activity line points at. */\nexport interface CrmActivityTarget {\n type: CrmActivityKind\n id?: string\n name?: string\n}\n\n/**\n * ONE LINE FOR ONE RECORD, IN THE FEED THE ACT BELONGS TO (AGL-2738).\n *\n * A CRM record is org data whichever hub it is edited from, but the feed\n * that holds \"who deleted it\" is not: under a SITE the line goes into that\n * site's `hosts/{hostId}/activity` client-direct, and at the ORGANIZATION\n * level it goes into `orgs/{orgId}/activity` through `crm/org-activity`,\n * because the org feed is closed to every client by rule.\n *\n * ## The two gates are on different axes, and that is the bug this closes\n *\n * The record write asks `canWriteOrgData()` —
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-activity-logger.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'use client'\n\nimport {\n type HostActivityTarget,\n useHostActivityLogger,\n} from '@aglyn/tenant-feature-instance'\nimport { useCallback } from 'react'\nimport { useCrmApi } from '../components/use-crm-api'\nimport type { CrmOrgActivityKind } from '../constants/api-routes'\nimport {\n orgActivityRefusal,\n reportDroppedActivityLine,\n} from '../model/crm-activity-report'\nimport { useCrmOrgMount } from './use-crm-org-mount'\n\n/**\n * A record kind BOTH feeds accept.\n *\n * The org feed also files tasks and the host feed also files screens, and a\n * line that can land in either has to name something both presenters can\n * render as a link. Spelled as the intersection rather than a third hand-\n * written union so a kind added to one side alone cannot silently become a\n * line the other side draws as unknown.\n */\nexport type CrmActivityKind = Extract<\n CrmOrgActivityKind,\n HostActivityTarget['type']\n>\n\n/** What a CRM activity line points at. */\nexport interface CrmActivityTarget {\n type: CrmActivityKind\n id?: string\n name?: string\n}\n\n/**\n * ONE LINE FOR ONE RECORD, IN THE FEED THE ACT BELONGS TO (AGL-2738).\n *\n * A CRM record is org data whichever hub it is edited from, but the feed\n * that holds \"who deleted it\" is not: under a SITE the line goes into that\n * site's `hosts/{hostId}/activity` client-direct, and at the ORGANIZATION\n * level it goes into `orgs/{orgId}/activity` through `crm/org-activity`,\n * because the org feed is closed to every client by rule.\n *\n * ## The two gates are on different axes, and that is the bug this closes\n *\n * The record write asks `canWriteOrgData()` — \"Manage data\" in the org, plus\n * the scope tokens. The line asks `canWriteHostContent()`,\n * which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows\n * nothing about the org roster. At the org hub the two come apart for\n * members who are genuinely admitted to the hub:\n *\n * - a pre-`allHosts` member doc reads as org-wide (`isOrgWideMember`) and\n * projects to NO host role at all (`hostRoleFor` returns null without\n * `allHosts`), so an editor holding `data.manage` org-wide appears in no\n * site's `memberRoles`;\n * - an org editor carrying an explicit `hostAccess` entry of `viewer` on\n * one site writes the record and cannot write that site's feed;\n * - a site whose projection never ran, and a SUSPENDED site, refuse the\n * append while the org-level record write goes through untouched.\n *\n * Each of those used to spend its audit line on a rejected client write\n * that `useHostActivityLogger` swallowed. Widening the rule is not the\n * answer — `cloud/rules-tests/firestore-rules.test.mjs` pins that a viewer\n * cannot forge a line, and adding `activity` to the create exclusion list\n * ends host logging rather than moving it. Routing the org-level line\n * through the org's own door is: `crm/org-activity` authorizes the caller\n * on the ORG, which is the axis the record write was authorized on, and\n * appends with the Admin SDK.\n *\n * ## Which door, decided by the MOUNTED site and not by the record's\n *\n * `hostId` here is the site the surface is mounted under, never the site\n * the record was captured by. A record page at the org hub is handed\n * `null` and posts to the org feed; the lead page, which the hub mounts\n * UNDER a site by address (AGL-2630), is handed that site and keeps\n * writing client-direct exactly as it does on the site's own hub. Falling\n * back to the record's own site is what put an org-level act in front of a\n * site-level gate in the first place.\n *\n * This is the same split `useCrmBulkApply` makes for the bulk bars and the\n * email and stage routes make on the server: the level the act was\n * performed at decides the feed.\n *\n * @param hostId the site the surface is MOUNTED under — `props.hostId`,\n * which is `null` at the organization hub. Never the record's own\n * `hostId`.\n */\nexport function useCrmActivityLogger(hostId: string | null | undefined) {\n const mount = useCrmOrgMount()\n const logHostActivity = useHostActivityLogger(hostId ?? undefined)\n // `null`, because the line is about the org and not about a site: the\n // hook stamps the mount's `orgId` into the body, which is what makes the\n // call the route's org variant.\n const callCrm = useCrmApi(null)\n return useCallback(\n (action: string, target: CrmActivityTarget) => {\n if (hostId || !mount) {\n logHostActivity(action, target)\n return\n }\n void callCrm('org-activity', { action, target })\n .then(({ response, payload }) => {\n if (!response.ok) throw orgActivityRefusal(response.status, payload)\n })\n .catch(reportDroppedActivityLine)\n },\n [hostId, mount, logHostActivity, callCrm],\n )\n}\n\nexport default useCrmActivityLogger\n"],"names":["useHostActivityLogger","useCallback","useCrmApi","orgActivityRefusal","reportDroppedActivityLine","useCrmOrgMount","useCrmActivityLogger","hostId","mount","logHostActivity","undefined","callCrm","action","target","then","response","payload","ok","status","catch"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAEEA,qBAAqB,QAChB,iCAAgC;AACvC,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,SAAS,QAAQ,+BAA2B;AAErD,SACEC,kBAAkB,EAClBC,yBAAyB,QACpB,kCAA8B;AACrC,SAASC,cAAc,QAAQ,yBAAqB;AAuBpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDC,GACD,OAAO,SAASC,qBAAqBC,MAAiC;IACpE,MAAMC,QAAQH;IACd,MAAMI,kBAAkBT,sBAAsBO,iBAAAA,SAAUG;IACxD,sEAAsE;IACtE,yEAAyE;IACzE,gCAAgC;IAChC,MAAMC,UAAUT,UAAU;IAC1B,OAAOD,YACL,CAACW,QAAgBC;QACf,IAAIN,UAAU,CAACC,OAAO;YACpBC,gBAAgBG,QAAQC;YACxB;QACF;QACA,KAAKF,QAAQ,gBAAgB;YAAEC;YAAQC;QAAO,GAC3CC,IAAI,CAAC,CAAC,EAAEC,QAAQ,EAAEC,OAAO,EAAE;YAC1B,IAAI,CAACD,SAASE,EAAE,EAAE,MAAMd,mBAAmBY,SAASG,MAAM,EAAEF;QAC9D,GACCG,KAAK,CAACf;IACX,GACA;QAACG;QAAQC;QAAOC;QAAiBE;KAAQ;AAE7C;AAEA,eAAeL,qBAAoB"}
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { contactDisplayName, CRM_COLLECTIONS } from "@aglyn/aglyn";
|
|
17
|
-
import { useFirestore } from "@aglyn/tenant-feature-instance";
|
|
18
|
-
import { doc, getDoc } from "firebase/firestore";
|
|
17
|
+
import { subscribeFirestoreSessionHeal, useFirestore } from "@aglyn/tenant-feature-instance";
|
|
18
|
+
import { doc, getDoc, getDocFromCache } from "firebase/firestore";
|
|
19
19
|
import { useCallback, useEffect, useState } from "react";
|
|
20
20
|
import { contactPrimaryGroup } from "../model/contact-record.js";
|
|
21
21
|
/** The collection each kind of record lives in, under `orgs/{orgId}/`. */ export const CRM_RECORD_COLLECTIONS = {
|
|
@@ -61,6 +61,53 @@ const cacheKey = (orgId, kind, id)=>`${orgId}/${CRM_RECORD_COLLECTIONS[kind]}/${
|
|
|
61
61
|
/** Test seam: forget everything, so a spec's fixtures are what get read. */ export function resetCrmRecordNameCache() {
|
|
62
62
|
nameCache.clear();
|
|
63
63
|
pending.clear();
|
|
64
|
+
retriesSpentAt = 0;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The post-sign-in race's budget: the one the page's own listeners spend
|
|
68
|
+
* before they give up (`use-firestore-doc`, AGL-216). That race resolves in
|
|
69
|
+
* well under two seconds.
|
|
70
|
+
*/ const READ_RETRIES = 5;
|
|
71
|
+
const READ_RETRY_MS = 400;
|
|
72
|
+
/**
|
|
73
|
+
* When a name read last spent its whole budget and was still refused.
|
|
74
|
+
*
|
|
75
|
+
* Surviving the budget means it is not the post-sign-in race, and a session
|
|
76
|
+
* the server refuses refuses every read: a task list naming fifty records
|
|
77
|
+
* would otherwise spend six refused reads on each (AGL-1440, where retries
|
|
78
|
+
* that ignored what the last read had learned multiplied a dead session's
|
|
79
|
+
* cost sixfold). For a minute after, a read tries once. One read that gets
|
|
80
|
+
* through re-arms the budget.
|
|
81
|
+
*/ let retriesSpentAt = 0;
|
|
82
|
+
const RETRIES_SPENT_WINDOW_MS = 60000;
|
|
83
|
+
/**
|
|
84
|
+
* One record's document, read the way the page beside it is.
|
|
85
|
+
*
|
|
86
|
+
* A one-shot read gets no second try for free, and a record page's listeners
|
|
87
|
+
* do: they retry a refusal, they reopen when the session heals, and under
|
|
88
|
+
* `persistentLocalCache` they keep painting the cached document while the
|
|
89
|
+
* server refuses. So a single failed `getDoc` left a card naming a person by
|
|
90
|
+
* their id while the person's own page, open beside it, showed the name. The
|
|
91
|
+
* read retries on the listeners' budget, and when the server still cannot be
|
|
92
|
+
* read it names the record from the cached copy the page's listeners show.
|
|
93
|
+
* Throws only when neither has it.
|
|
94
|
+
*/ async function readRecordDocument(ref) {
|
|
95
|
+
for(let attempt = 0;; attempt += 1){
|
|
96
|
+
try {
|
|
97
|
+
const snapshot = await getDoc(ref);
|
|
98
|
+
retriesSpentAt = 0;
|
|
99
|
+
return snapshot;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
const spent = attempt >= READ_RETRIES || Date.now() - retriesSpentAt < RETRIES_SPENT_WINDOW_MS;
|
|
102
|
+
if (spent) {
|
|
103
|
+
retriesSpentAt = Date.now();
|
|
104
|
+
return getDocFromCache(ref).catch(()=>{
|
|
105
|
+
throw error;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
await new Promise((resolve)=>setTimeout(resolve, READ_RETRY_MS));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
64
111
|
}
|
|
65
112
|
/**
|
|
66
113
|
* The reads that fill the cache for `records` not already in it — each
|
|
@@ -73,12 +120,13 @@ const cacheKey = (orgId, kind, id)=>`${orgId}/${CRM_RECORD_COLLECTIONS[kind]}/${
|
|
|
73
120
|
if (nameCache.has(key)) continue;
|
|
74
121
|
let read = pending.get(key);
|
|
75
122
|
if (!read) {
|
|
76
|
-
read =
|
|
123
|
+
read = readRecordDocument(doc(firestore, 'orgs', orgId, CRM_RECORD_COLLECTIONS[kind], id)).then((snapshot)=>{
|
|
77
124
|
const data = snapshot.exists() ? snapshot.data() : undefined;
|
|
78
125
|
nameCache.set(key, data ? crmRecordName(kind, data, groupId != null ? groupId : contactPrimaryGroup(data, org).groupId) : null);
|
|
79
126
|
}).catch(()=>{
|
|
80
|
-
// A
|
|
81
|
-
// the id, and the next mount
|
|
127
|
+
// A read that failed even after its retries is not cached: the
|
|
128
|
+
// cell keeps showing the id, and the next mount, or the session
|
|
129
|
+
// healing, tries again.
|
|
82
130
|
}).finally(()=>{
|
|
83
131
|
pending.delete(key);
|
|
84
132
|
});
|
|
@@ -114,6 +162,10 @@ const cacheKey = (orgId, kind, id)=>`${orgId}/${CRM_RECORD_COLLECTIONS[kind]}/${
|
|
|
114
162
|
// A counter rather than a copy of the cache: the cache is the source of
|
|
115
163
|
// truth and this only exists to re-render when it grows.
|
|
116
164
|
const [, setResolved] = useState(0);
|
|
165
|
+
// Bumped when the session heals, so a name whose read was refused is read
|
|
166
|
+
// again on this mount, as the page's listeners reopen then too.
|
|
167
|
+
const [healed, setHealed] = useState(0);
|
|
168
|
+
useEffect(()=>subscribeFirestoreSessionHeal(()=>setHealed((count)=>count + 1)), []);
|
|
117
169
|
// The pairs as one string, so the effect runs when the SET changes and not
|
|
118
170
|
// when the caller builds a new array of the same pairs on every render.
|
|
119
171
|
const wanted = records.map((record)=>`${record.kind}:${record.id}`).filter((entry, index, all)=>all.indexOf(entry) === index).sort().join('\n');
|
|
@@ -138,7 +190,8 @@ const cacheKey = (orgId, kind, id)=>`${orgId}/${CRM_RECORD_COLLECTIONS[kind]}/${
|
|
|
138
190
|
firestore,
|
|
139
191
|
orgId,
|
|
140
192
|
groupId,
|
|
141
|
-
wanted
|
|
193
|
+
wanted,
|
|
194
|
+
healed
|
|
142
195
|
]);
|
|
143
196
|
return useCallback((kind, id)=>{
|
|
144
197
|
if (!orgId) return undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-record-names.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 { contactDisplayName, CRM_COLLECTIONS } from '@aglyn/aglyn'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport { doc, type Firestore, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { contactPrimaryGroup } from '../model/contact-record'\n\nexport type CrmRecordKind = 'contact' | 'company' | 'deal'\n\n/** The collection each kind of record lives in, under `orgs/{orgId}/`. */\nexport const CRM_RECORD_COLLECTIONS: Record<CrmRecordKind, string> = {\n contact: 'contacts',\n company: CRM_COLLECTIONS.companies,\n deal: CRM_COLLECTIONS.deals,\n}\n\n/**\n * What a record is CALLED, from its document.\n *\n * A contact's name is read through the viewing group's facet, the way the\n * people list reads it, so one business renaming a person does not change\n * what an unrelated business's task list shows; the email, then the phone\n * number, stands in for a contact nobody has named. A company has a name and\n * a deal a title.\n */\nexport function crmRecordName(\n kind: CrmRecordKind,\n data: Record<string, unknown> | undefined,\n groupId: string,\n): string {\n if (!data) return ''\n switch (kind) {\n case 'contact':\n return (\n contactDisplayName(data, groupId) || String(data['email'] || data['phone'] || '')\n )\n case 'company':\n return String(data['name'] ?? '')\n case 'deal':\n return String(data['title'] ?? '')\n }\n}\n\n/**\n * Names already read, keyed by `orgId/collection/id`, shared by every\n * mount for the life of the page.\n *\n * A task list names the same handful of records over and over — five tasks\n * about one deal are five rows and one name — and a person moves between the\n * tasks section, a contact's page and the dashboard without the records\n * changing underneath them. `null` records a document that does not exist,\n * so a task pointing at a deleted record costs one read rather than one per\n * render. A rename is picked up on the next page load, which is the right\n * staleness for a label beside a link to the record itself.\n */\nconst nameCache = new Map<string, string | null>()\nconst pending = new Map<string, Promise<void>>()\n\nconst cacheKey = (orgId: string, kind: CrmRecordKind, id: string) =>\n `${orgId}/${CRM_RECORD_COLLECTIONS[kind]}/${id}`\n\n/** Test seam: forget everything, so a spec's fixtures are what get read. */\nexport function resetCrmRecordNameCache(): void {\n nameCache.clear()\n pending.clear()\n}\n\n/**\n * The reads that fill the cache for `records` not already in it — each\n * record read once however many callers ask at the same time.\n */\nfunction startNameReads(\n firestore: Firestore,\n orgId: string,\n groupId: string | null,\n org: Record<string, unknown> | null | undefined,\n records: ReadonlyArray<{ kind: CrmRecordKind; id: string }>,\n): Promise<void>[] {\n const reads: Promise<void>[] = []\n for (const { kind, id } of records) {\n if (!id) continue\n const key = cacheKey(orgId, kind, id)\n if (nameCache.has(key)) continue\n let read = pending.get(key)\n if (!read) {\n read = getDoc(doc(firestore, 'orgs', orgId, CRM_RECORD_COLLECTIONS[kind], id))\n .then((snapshot) => {\n const data = snapshot.exists() ? (snapshot.data() as Record<string, unknown>) : undefined\n nameCache.set(\n key,\n data ? crmRecordName(kind, data, groupId ?? contactPrimaryGroup(data, org).groupId) : null,\n )\n })\n .catch(() => {\n // A refused or failed read is not cached: the cell keeps showing\n // the id, and the next mount tries again.\n })\n .finally(() => {\n pending.delete(key)\n })\n pending.set(key, read)\n }\n reads.push(read)\n }\n return reads\n}\n\n/**\n * The names of `records`, read now — for a one-off like a file export,\n * which needs every name at once rather than a listener's re-render\n * (AGL-3521). Shares {@link useCrmRecordNames}' cache, and answers the same\n * lookup: `undefined` for a record that could not be named.\n */\nexport async function readCrmRecordNames(\n firestore: Firestore,\n options: {\n orgId: string\n groupId: string | null\n org?: Record<string, unknown> | null\n records: ReadonlyArray<{ kind: CrmRecordKind; id: string }>\n },\n): Promise<(kind: CrmRecordKind, id: string) => string | undefined> {\n const { orgId, groupId, org, records } = options\n await Promise.all(startNameReads(firestore, orgId, groupId, org, records))\n return (kind, id) => nameCache.get(cacheKey(orgId, kind, id)) ?? undefined\n}\n\n/**\n * The names of the records a list of tasks points at, resolved once each.\n *\n * Returns a lookup rather than a map so the caller does not have to know the\n * cache's key shape. An unresolved record answers `undefined` — the cell\n * renders the link with the id until the name lands, which is one render\n * later on a warm cache and one round trip on a cold one.\n */\nexport function useCrmRecordNames(options: {\n orgId: string | null | undefined\n /**\n * The viewing group a contact is named through, or `null` at the\n * organization level (AGL-2630), where each contact is named through its\n * own primary holder, resolved from {@link org}.\n */\n groupId: string | null\n org?: Record<string, unknown> | null\n records: ReadonlyArray<{ kind: CrmRecordKind; id: string }>\n}): (kind: CrmRecordKind, id: string) => string | undefined {\n const { orgId, groupId, org, records } = options\n const firestore = useFirestore()\n // A counter rather than a copy of the cache: the cache is the source of\n // truth and this only exists to re-render when it grows.\n const [, setResolved] = useState(0)\n\n // The pairs as one string, so the effect runs when the SET changes and not\n // when the caller builds a new array of the same pairs on every render.\n const wanted = records\n .map((record) => `${record.kind}:${record.id}`)\n .filter((entry, index, all) => all.indexOf(entry) === index)\n .sort()\n .join('\\n')\n\n useEffect(() => {\n if (!orgId || !wanted) return\n let active = true\n const reads = startNameReads(\n firestore,\n orgId,\n groupId,\n org,\n wanted.split('\\n').map((entry) => {\n const [kind, id] = entry.split(':') as [CrmRecordKind, string]\n return { kind, id }\n }),\n )\n if (!reads.length) return\n void Promise.all(reads).then(() => {\n if (active) setResolved((count) => count + 1)\n })\n return () => {\n active = false\n }\n }, [firestore, orgId, groupId, wanted])\n\n return useCallback(\n (kind: CrmRecordKind, id: string) => {\n if (!orgId) return undefined\n const hit = nameCache.get(cacheKey(orgId, kind, id))\n return hit === null ? undefined : hit\n },\n [orgId],\n )\n}\n"],"names":["contactDisplayName","CRM_COLLECTIONS","useFirestore","doc","getDoc","useCallback","useEffect","useState","contactPrimaryGroup","CRM_RECORD_COLLECTIONS","contact","company","companies","deal","deals","crmRecordName","kind","data","groupId","String","nameCache","Map","pending","cacheKey","orgId","id","resetCrmRecordNameCache","clear","startNameReads","firestore","org","records","reads","key","has","read","get","then","snapshot","exists","undefined","set","catch","finally","delete","push","readCrmRecordNames","options","Promise","all","useCrmRecordNames","setResolved","wanted","map","record","filter","entry","index","indexOf","sort","join","active","split","length","count","hit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,eAAe,QAAQ,eAAc;AAClE,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SAASC,GAAG,EAAkBC,MAAM,QAAQ,qBAAoB;AAChE,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,mBAAmB,QAAQ,6BAAyB;AAI7D,wEAAwE,GACxE,OAAO,MAAMC,yBAAwD;IACnEC,SAAS;IACTC,SAASV,gBAAgBW,SAAS;IAClCC,MAAMZ,gBAAgBa,KAAK;AAC7B,EAAC;AAED;;;;;;;;CAQC,GACD,OAAO,SAASC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AACxC,MAAMS,GAAG,GAAG+B,MAAMM,KAAK,CAAC;YAC/B,OAAO;gBAAE9C;gBAAMS;YAAG;QACpB;QAEF,IAAI,CAACO,MAAM+B,MAAM,EAAE;QACnB,KAAKf,QAAQC,GAAG,CAACjB,OAAOK,IAAI,CAAC;YAC3B,IAAIwB,QAAQV,YAAY,CAACa,QAAUA,QAAQ;QAC7C;QACA,OAAO;YACLH,SAAS;QACX;IACF,GAAG;QAAChC;QAAWL;QAAON;QAASkC;KAAO;IAEtC,OAAO/C,YACL,CAACW,MAAqBS;QACpB,IAAI,CAACD,OAAO,OAAOgB;QACnB,MAAMyB,MAAM7C,UAAUgB,GAAG,CAACb,SAASC,OAAOR,MAAMS;QAChD,OAAOwC,QAAQ,OAAOzB,YAAYyB;IACpC,GACA;QAACzC;KAAM;AAEX"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-record-names.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 { contactDisplayName, CRM_COLLECTIONS } from '@aglyn/aglyn'\nimport { subscribeFirestoreSessionHeal, useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n doc,\n type DocumentReference,\n type DocumentSnapshot,\n type Firestore,\n getDoc,\n getDocFromCache,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { contactPrimaryGroup } from '../model/contact-record'\n\nexport type CrmRecordKind = 'contact' | 'company' | 'deal'\n\n/** The collection each kind of record lives in, under `orgs/{orgId}/`. */\nexport const CRM_RECORD_COLLECTIONS: Record<CrmRecordKind, string> = {\n contact: 'contacts',\n company: CRM_COLLECTIONS.companies,\n deal: CRM_COLLECTIONS.deals,\n}\n\n/**\n * What a record is CALLED, from its document.\n *\n * A contact's name is read through the viewing group's facet, the way the\n * people list reads it, so one business renaming a person does not change\n * what an unrelated business's task list shows; the email, then the phone\n * number, stands in for a contact nobody has named. A company has a name and\n * a deal a title.\n */\nexport function crmRecordName(\n kind: CrmRecordKind,\n data: Record<string, unknown> | undefined,\n groupId: string,\n): string {\n if (!data) return ''\n switch (kind) {\n case 'contact':\n return (\n contactDisplayName(data, groupId) || String(data['email'] || data['phone'] || '')\n )\n case 'company':\n return String(data['name'] ?? '')\n case 'deal':\n return String(data['title'] ?? '')\n }\n}\n\n/**\n * Names already read, keyed by `orgId/collection/id`, shared by every\n * mount for the life of the page.\n *\n * A task list names the same handful of records over and over — five tasks\n * about one deal are five rows and one name — and a person moves between the\n * tasks section, a contact's page and the dashboard without the records\n * changing underneath them. `null` records a document that does not exist,\n * so a task pointing at a deleted record costs one read rather than one per\n * render. A rename is picked up on the next page load, which is the right\n * staleness for a label beside a link to the record itself.\n */\nconst nameCache = new Map<string, string | null>()\nconst pending = new Map<string, Promise<void>>()\n\nconst cacheKey = (orgId: string, kind: CrmRecordKind, id: string) =>\n `${orgId}/${CRM_RECORD_COLLECTIONS[kind]}/${id}`\n\n/** Test seam: forget everything, so a spec's fixtures are what get read. */\nexport function resetCrmRecordNameCache(): void {\n nameCache.clear()\n pending.clear()\n retriesSpentAt = 0\n}\n\n/**\n * The post-sign-in race's budget: the one the page's own listeners spend\n * before they give up (`use-firestore-doc`, AGL-216). That race resolves in\n * well under two seconds.\n */\nconst READ_RETRIES = 5\nconst READ_RETRY_MS = 400\n\n/**\n * When a name read last spent its whole budget and was still refused.\n *\n * Surviving the budget means it is not the post-sign-in race, and a session\n * the server refuses refuses every read: a task list naming fifty records\n * would otherwise spend six refused reads on each (AGL-1440, where retries\n * that ignored what the last read had learned multiplied a dead session's\n * cost sixfold). For a minute after, a read tries once. One read that gets\n * through re-arms the budget.\n */\nlet retriesSpentAt = 0\nconst RETRIES_SPENT_WINDOW_MS = 60_000\n\n/**\n * One record's document, read the way the page beside it is.\n *\n * A one-shot read gets no second try for free, and a record page's listeners\n * do: they retry a refusal, they reopen when the session heals, and under\n * `persistentLocalCache` they keep painting the cached document while the\n * server refuses. So a single failed `getDoc` left a card naming a person by\n * their id while the person's own page, open beside it, showed the name. The\n * read retries on the listeners' budget, and when the server still cannot be\n * read it names the record from the cached copy the page's listeners show.\n * Throws only when neither has it.\n */\nasync function readRecordDocument(ref: DocumentReference): Promise<DocumentSnapshot> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n const snapshot = await getDoc(ref)\n retriesSpentAt = 0\n return snapshot\n } catch (error) {\n const spent =\n attempt >= READ_RETRIES || Date.now() - retriesSpentAt < RETRIES_SPENT_WINDOW_MS\n if (spent) {\n retriesSpentAt = Date.now()\n return getDocFromCache(ref).catch(() => {\n throw error\n })\n }\n await new Promise((resolve) => setTimeout(resolve, READ_RETRY_MS))\n }\n }\n}\n\n/**\n * The reads that fill the cache for `records` not already in it — each\n * record read once however many callers ask at the same time.\n */\nfunction startNameReads(\n firestore: Firestore,\n orgId: string,\n groupId: string | null,\n org: Record<string, unknown> | null | undefined,\n records: ReadonlyArray<{ kind: CrmRecordKind; id: string }>,\n): Promise<void>[] {\n const reads: Promise<void>[] = []\n for (const { kind, id } of records) {\n if (!id) continue\n const key = cacheKey(orgId, kind, id)\n if (nameCache.has(key)) continue\n let read = pending.get(key)\n if (!read) {\n read = readRecordDocument(doc(firestore, 'orgs', orgId, CRM_RECORD_COLLECTIONS[kind], id))\n .then((snapshot) => {\n const data = snapshot.exists() ? (snapshot.data() as Record<string, unknown>) : undefined\n nameCache.set(\n key,\n data ? crmRecordName(kind, data, groupId ?? contactPrimaryGroup(data, org).groupId) : null,\n )\n })\n .catch(() => {\n // A read that failed even after its retries is not cached: the\n // cell keeps showing the id, and the next mount, or the session\n // healing, tries again.\n })\n .finally(() => {\n pending.delete(key)\n })\n pending.set(key, read)\n }\n reads.push(read)\n }\n return reads\n}\n\n/**\n * The names of `records`, read now — for a one-off like a file export,\n * which needs every name at once rather than a listener's re-render\n * (AGL-3521). Shares {@link useCrmRecordNames}' cache, and answers the same\n * lookup: `undefined` for a record that could not be named.\n */\nexport async function readCrmRecordNames(\n firestore: Firestore,\n options: {\n orgId: string\n groupId: string | null\n org?: Record<string, unknown> | null\n records: ReadonlyArray<{ kind: CrmRecordKind; id: string }>\n },\n): Promise<(kind: CrmRecordKind, id: string) => string | undefined> {\n const { orgId, groupId, org, records } = options\n await Promise.all(startNameReads(firestore, orgId, groupId, org, records))\n return (kind, id) => nameCache.get(cacheKey(orgId, kind, id)) ?? undefined\n}\n\n/**\n * The names of the records a list of tasks points at, resolved once each.\n *\n * Returns a lookup rather than a map so the caller does not have to know the\n * cache's key shape. An unresolved record answers `undefined` — the cell\n * renders the link with the id until the name lands, which is one render\n * later on a warm cache and one round trip on a cold one.\n */\nexport function useCrmRecordNames(options: {\n orgId: string | null | undefined\n /**\n * The viewing group a contact is named through, or `null` at the\n * organization level (AGL-2630), where each contact is named through its\n * own primary holder, resolved from {@link org}.\n */\n groupId: string | null\n org?: Record<string, unknown> | null\n records: ReadonlyArray<{ kind: CrmRecordKind; id: string }>\n}): (kind: CrmRecordKind, id: string) => string | undefined {\n const { orgId, groupId, org, records } = options\n const firestore = useFirestore()\n // A counter rather than a copy of the cache: the cache is the source of\n // truth and this only exists to re-render when it grows.\n const [, setResolved] = useState(0)\n // Bumped when the session heals, so a name whose read was refused is read\n // again on this mount, as the page's listeners reopen then too.\n const [healed, setHealed] = useState(0)\n useEffect(() => subscribeFirestoreSessionHeal(() => setHealed((count) => count + 1)), [])\n\n // The pairs as one string, so the effect runs when the SET changes and not\n // when the caller builds a new array of the same pairs on every render.\n const wanted = records\n .map((record) => `${record.kind}:${record.id}`)\n .filter((entry, index, all) => all.indexOf(entry) === index)\n .sort()\n .join('\\n')\n\n useEffect(() => {\n if (!orgId || !wanted) return\n let active = true\n const reads = startNameReads(\n firestore,\n orgId,\n groupId,\n org,\n wanted.split('\\n').map((entry) => {\n const [kind, id] = entry.split(':') as [CrmRecordKind, string]\n return { kind, id }\n }),\n )\n if (!reads.length) return\n void Promise.all(reads).then(() => {\n if (active) setResolved((count) => count + 1)\n })\n return () => {\n active = false\n }\n }, [firestore, orgId, groupId, wanted, healed])\n\n return useCallback(\n (kind: CrmRecordKind, id: string) => {\n if (!orgId) return undefined\n const hit = nameCache.get(cacheKey(orgId, kind, id))\n return hit === null ? undefined : hit\n },\n [orgId],\n )\n}\n"],"names":["contactDisplayName","CRM_COLLECTIONS","subscribeFirestoreSessionHeal","useFirestore","doc","getDoc","getDocFromCache","useCallback","useEffect","useState","contactPrimaryGroup","CRM_RECORD_COLLECTIONS","contact","company","companies","deal","deals","crmRecordName","kind","data","groupId","String","nameCache","Map","pending","cacheKey","orgId","id","resetCrmRecordNameCache","clear","retriesSpentAt","READ_RETRIES","READ_RETRY_MS","RETRIES_SPENT_WINDOW_MS","readRecordDocument","ref","attempt","snapshot","error","spent","Date","now","catch","Promise","resolve","setTimeout","startNameReads","firestore","org","records","reads","key","has","read","get","then","exists","undefined","set","finally","delete","push","readCrmRecordNames","options","all","useCrmRecordNames","setResolved","healed","setHealed","count","wanted","map","record","filter","entry","index","indexOf","sort","join","active","split","length","hit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,eAAe,QAAQ,eAAc;AAClE,SAASC,6BAA6B,EAAEC,YAAY,QAAQ,iCAAgC;AAC5F,SACEC,GAAG,EAIHC,MAAM,EACNC,eAAe,QACV,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,mBAAmB,QAAQ,6BAAyB;AAI7D,wEAAwE,GACxE,OAAO,MAAMC,yBAAwD;IACnEC,SAAS;IACTC,SAASZ,g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MAAqBS;QACpB,IAAI,CAACD,OAAO,OAAO+B;QACnB,MAAMyB,MAAM5D,UAAUgC,GAAG,CAAC7B,SAASC,OAAOR,MAAMS;QAChD,OAAOuD,QAAQ,OAAOzB,YAAYyB;IACpC,GACA;QAACxD;KAAM;AAEX"}
|
|
@@ -65,5 +65,7 @@ export declare function useDealStageApi(hostId: string | null): {
|
|
|
65
65
|
moveToStage: (deal: DealStageRef, stageId: string) => Promise<DealStageResponse>;
|
|
66
66
|
markWon: (deal: DealStageRef) => Promise<DealStageResponse>;
|
|
67
67
|
markLost: (deal: DealStageRef, lostReason?: string) => Promise<DealStageResponse>;
|
|
68
|
+
/** "Move contacts and deals between stages" is known refused here (AGL-4047): controls switch off. */
|
|
69
|
+
moveBlocked: boolean;
|
|
68
70
|
};
|
|
69
71
|
export type DealStageApi = ReturnType<typeof useDealStageApi>;
|
|
@@ -19,6 +19,7 @@ import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
|
|
|
19
19
|
import { useUser } from "@aglyn/tenant-feature-instance";
|
|
20
20
|
import { useCallback, useMemo } from "react";
|
|
21
21
|
import { useCrmOrgMount } from "./use-crm-org-mount.js";
|
|
22
|
+
import { useStageMoveBlocked } from "./use-stage-move-blocked.js";
|
|
22
23
|
/**
|
|
23
24
|
* Beneath the org hub's mount the body names the ORG (AGL-2634), and the
|
|
24
25
|
* route runs its org variant: authorized by the org rather than by a role
|
|
@@ -29,6 +30,8 @@ import { useCrmOrgMount } from "./use-crm-org-mount.js";
|
|
|
29
30
|
var _useCrmOrgMount;
|
|
30
31
|
const { data: user } = useUser();
|
|
31
32
|
const orgId = (_ref = (_useCrmOrgMount = useCrmOrgMount()) == null ? void 0 : _useCrmOrgMount.orgId) != null ? _ref : null;
|
|
33
|
+
// Asked where the route will ask it: at the org hub the body names the org.
|
|
34
|
+
const moveBlocked = useStageMoveBlocked(orgId ? null : hostId);
|
|
32
35
|
const call = useCallback(async (deal, body)=>{
|
|
33
36
|
var _ref;
|
|
34
37
|
const site = (_ref = hostId != null ? hostId : deal.hostId) != null ? _ref : null;
|
|
@@ -69,9 +72,11 @@ import { useCrmOrgMount } from "./use-crm-org-mount.js";
|
|
|
69
72
|
dealId: deal.$id,
|
|
70
73
|
status: 'lost',
|
|
71
74
|
lostReason
|
|
72
|
-
})
|
|
75
|
+
}),
|
|
76
|
+
/** "Move contacts and deals between stages" is known refused here (AGL-4047): controls switch off. */ moveBlocked
|
|
73
77
|
}), [
|
|
74
|
-
call
|
|
78
|
+
call,
|
|
79
|
+
moveBlocked
|
|
75
80
|
]);
|
|
76
81
|
}
|
|
77
82
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-deal-stage-api.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'use client'\n\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useMemo } from 'react'\nimport { useCrmOrgMount } from './use-crm-org-mount'\n\n/** What `POST /api/crm/deal-stage` accepts, minus the `hostId` this hook adds. */\nexport type DealStageRequest =\n | { dealId: string; stageId: string }\n | { dealId: string; status: 'won' }\n | { dealId: string; status: 'lost'; lostReason?: string }\n\n/** What the route answers on success. */\nexport interface DealStageResponse {\n ok: true\n dealId: string\n stageId: string\n status: 'open' | 'won' | 'lost'\n previousStageId: string\n /** The host event that was emitted, or `null` for a move to the same stage. */\n event: 'dealStageChanged' | 'dealWon' | 'dealLost' | null\n /**\n * What a win did to the deal's contact (AGL-2641): the lifecycle stage\n * the person now holds and whether this call raised it to `customer`.\n * `null` on anything but a win, and on a deal that names no contact.\n */\n customer: { contactId: string; lifecycleStage: string; advanced: boolean } | null\n}\n\n/**\n * The ONE door a stage change goes through (AGL-2598).\n *\n * A deal's stage, its won and its lost are not written by the browser even\n * though the rules would let them be: the console can create and edit a deal\n * client-direct, but a move is the moment an automation wants to hear about\n * — \"notify the owner when a deal is won\", \"file a task when one goes to\n * negotiation\" — and a workflow can only hear an event the server emits.\n * Every surface that moves a deal (the board's drag, a card's menu, the\n * detail page's stepper and its Won and Lost buttons) calls this, so there\n * is no stage change that fires no event.\n *\n * Errors are thrown with the route's own message, which is written for the\n * person reading it, so a caller shows `error.message` and nothing else.\n */\n/**\n * What a call names: the deal, and — at the organization level (AGL-2630),\n * where the surface has no site of its own — the site the deal was made on,\n * which is the site the route emits the stage event for. Under a site the\n * mounted site wins, as it always has.\n */\nexport interface DealStageRef {\n $id: string\n hostId?: string\n}\n\n/**\n * Beneath the org hub's mount the body names the ORG (AGL-2634), and the\n * route runs its org variant: authorized by the org rather than by a role\n * on the deal's site, so a deal no site captured moves too — the site\n * beside it, when the deal has one, is where the event goes.\n */\nexport function useDealStageApi(hostId: string | null) {\n const { data: user } = useUser()\n const orgId = useCrmOrgMount()?.orgId ?? null\n\n const call = useCallback(\n async (\n deal: DealStageRef,\n body: DealStageRequest,\n ): Promise<DealStageResponse> => {\n const site = hostId ?? deal.hostId ?? null\n if (!site && !orgId) {\n throw new Error('This deal names no site, so its stage cannot be moved.')\n }\n const response = await authorizedFetch(user, '/api/crm/deal-stage', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId: site,\n ...(orgId ? { orgId } : {}),\n ...body,\n }),\n })\n const payload = (await response.json().catch(() => ({}))) as\n | DealStageResponse\n | { error?: string }\n if (!response.ok || !('ok' in payload)) {\n throw new Error(\n (payload as { error?: string }).error ||\n 'The deal could not be moved. Try again.',\n )\n }\n return payload\n },\n [user, hostId, orgId],\n )\n\n return useMemo(\n () => ({\n moveToStage: (deal: DealStageRef, stageId: string) =>\n call(deal, { dealId: deal.$id, stageId }),\n markWon: (deal: DealStageRef) => call(deal, { dealId: deal.$id, status: 'won' }),\n markLost: (deal: DealStageRef, lostReason?: string) =>\n call(deal, { dealId: deal.$id, status: 'lost', lostReason }),\n }),\n [call],\n )\n}\n\nexport type DealStageApi = ReturnType<typeof useDealStageApi>\n"],"names":["authorizedFetch","useUser","useCallback","useMemo","useCrmOrgMount","useDealStageApi","hostId","data","user","orgId","call","deal","body","site","Error","response","method","headers","JSON","stringify","payload","json","catch","ok","error","moveToStage","stageId","dealId","$id","markWon","status","markLost","lostReason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,WAAW,EAAEC,OAAO,QAAQ,QAAO;AAC5C,SAASC,cAAc,QAAQ,yBAAqB;
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-deal-stage-api.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'use client'\n\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useMemo } from 'react'\nimport { useCrmOrgMount } from './use-crm-org-mount'\nimport { useStageMoveBlocked } from './use-stage-move-blocked'\n\n/** What `POST /api/crm/deal-stage` accepts, minus the `hostId` this hook adds. */\nexport type DealStageRequest =\n | { dealId: string; stageId: string }\n | { dealId: string; status: 'won' }\n | { dealId: string; status: 'lost'; lostReason?: string }\n\n/** What the route answers on success. */\nexport interface DealStageResponse {\n ok: true\n dealId: string\n stageId: string\n status: 'open' | 'won' | 'lost'\n previousStageId: string\n /** The host event that was emitted, or `null` for a move to the same stage. */\n event: 'dealStageChanged' | 'dealWon' | 'dealLost' | null\n /**\n * What a win did to the deal's contact (AGL-2641): the lifecycle stage\n * the person now holds and whether this call raised it to `customer`.\n * `null` on anything but a win, and on a deal that names no contact.\n */\n customer: { contactId: string; lifecycleStage: string; advanced: boolean } | null\n}\n\n/**\n * The ONE door a stage change goes through (AGL-2598).\n *\n * A deal's stage, its won and its lost are not written by the browser even\n * though the rules would let them be: the console can create and edit a deal\n * client-direct, but a move is the moment an automation wants to hear about\n * — \"notify the owner when a deal is won\", \"file a task when one goes to\n * negotiation\" — and a workflow can only hear an event the server emits.\n * Every surface that moves a deal (the board's drag, a card's menu, the\n * detail page's stepper and its Won and Lost buttons) calls this, so there\n * is no stage change that fires no event.\n *\n * Errors are thrown with the route's own message, which is written for the\n * person reading it, so a caller shows `error.message` and nothing else.\n */\n/**\n * What a call names: the deal, and — at the organization level (AGL-2630),\n * where the surface has no site of its own — the site the deal was made on,\n * which is the site the route emits the stage event for. Under a site the\n * mounted site wins, as it always has.\n */\nexport interface DealStageRef {\n $id: string\n hostId?: string\n}\n\n/**\n * Beneath the org hub's mount the body names the ORG (AGL-2634), and the\n * route runs its org variant: authorized by the org rather than by a role\n * on the deal's site, so a deal no site captured moves too — the site\n * beside it, when the deal has one, is where the event goes.\n */\nexport function useDealStageApi(hostId: string | null) {\n const { data: user } = useUser()\n const orgId = useCrmOrgMount()?.orgId ?? null\n // Asked where the route will ask it: at the org hub the body names the org.\n const moveBlocked = useStageMoveBlocked(orgId ? null : hostId)\n\n const call = useCallback(\n async (\n deal: DealStageRef,\n body: DealStageRequest,\n ): Promise<DealStageResponse> => {\n const site = hostId ?? deal.hostId ?? null\n if (!site && !orgId) {\n throw new Error('This deal names no site, so its stage cannot be moved.')\n }\n const response = await authorizedFetch(user, '/api/crm/deal-stage', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId: site,\n ...(orgId ? { orgId } : {}),\n ...body,\n }),\n })\n const payload = (await response.json().catch(() => ({}))) as\n | DealStageResponse\n | { error?: string }\n if (!response.ok || !('ok' in payload)) {\n throw new Error(\n (payload as { error?: string }).error ||\n 'The deal could not be moved. Try again.',\n )\n }\n return payload\n },\n [user, hostId, orgId],\n )\n\n return useMemo(\n () => ({\n moveToStage: (deal: DealStageRef, stageId: string) =>\n call(deal, { dealId: deal.$id, stageId }),\n markWon: (deal: DealStageRef) => call(deal, { dealId: deal.$id, status: 'won' }),\n markLost: (deal: DealStageRef, lostReason?: string) =>\n call(deal, { dealId: deal.$id, status: 'lost', lostReason }),\n /** \"Move contacts and deals between stages\" is known refused here (AGL-4047): controls switch off. */\n moveBlocked,\n }),\n [call, moveBlocked],\n )\n}\n\nexport type DealStageApi = ReturnType<typeof useDealStageApi>\n"],"names":["authorizedFetch","useUser","useCallback","useMemo","useCrmOrgMount","useStageMoveBlocked","useDealStageApi","hostId","data","user","orgId","moveBlocked","call","deal","body","site","Error","response","method","headers","JSON","stringify","payload","json","catch","ok","error","moveToStage","stageId","dealId","$id","markWon","status","markLost","lostReason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,WAAW,EAAEC,OAAO,QAAQ,QAAO;AAC5C,SAASC,cAAc,QAAQ,yBAAqB;AACpD,SAASC,mBAAmB,QAAQ,8BAA0B;AAmD9D;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,MAAqB;;QAErCH;IADd,MAAM,EAAEI,MAAMC,IAAI,EAAE,GAAGR;IACvB,MAAMS,iBAAQN,kBAAAA,qCAAAA,gBAAkBM,KAAK,mBAAI;IACzC,4EAA4E;IAC5E,MAAMC,cAAcN,oBAAoBK,QAAQ,OAAOH;IAEvD,MAAMK,OAAOV,YACX,OACEW,MACAC;YAEaP;QAAb,MAAMQ,QAAOR,OAAAA,iBAAAA,SAAUM,KAAKN,MAAM,YAArBA,OAAyB;QACtC,IAAI,CAACQ,QAAQ,CAACL,OAAO;YACnB,MAAM,IAAIM,MAAM;QAClB;QACA,MAAMC,WAAW,MAAMjB,gBAAgBS,MAAM,uBAAuB;YAClES,QAAQ;YACRC,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CL,MAAMM,KAAKC,SAAS,CAAC;gBACnBd,QAAQQ;eACJL,QAAQ;gBAAEA;YAAM,IAAI,CAAC,GACtBI;QAEP;QACA,MAAMQ,UAAW,MAAML,SAASM,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;QAGrD,IAAI,CAACP,SAASQ,EAAE,IAAI,CAAE,CAAA,QAAQH,OAAM,GAAI;YACtC,MAAM,IAAIN,MACR,AAACM,QAA+BI,KAAK,IACnC;QAEN;QACA,OAAOJ;IACT,GACA;QAACb;QAAMF;QAAQG;KAAM;IAGvB,OAAOP,QACL,IAAO,CAAA;YACLwB,aAAa,CAACd,MAAoBe,UAChChB,KAAKC,MAAM;oBAAEgB,QAAQhB,KAAKiB,GAAG;oBAAEF;gBAAQ;YACzCG,SAAS,CAAClB,OAAuBD,KAAKC,MAAM;oBAAEgB,QAAQhB,KAAKiB,GAAG;oBAAEE,QAAQ;gBAAM;YAC9EC,UAAU,CAACpB,MAAoBqB,aAC7BtB,KAAKC,MAAM;oBAAEgB,QAAQhB,KAAKiB,GAAG;oBAAEE,QAAQ;oBAAQE;gBAAW;YAC5D,oGAAoG,GACpGvB;QACF,CAAA,GACA;QAACC;QAAMD;KAAY;AAEvB"}
|
|
@@ -33,6 +33,25 @@ import { useCallback, useEffect, useState } from "react";
|
|
|
33
33
|
/** Test seam. */ export function resetOrgMemberDirectoryCache() {
|
|
34
34
|
rosterCache.clear();
|
|
35
35
|
}
|
|
36
|
+
/** The one empty roster, so a caller's memo does not change on every render while it loads. */ const NO_MEMBERS = [];
|
|
37
|
+
/** Tries per roster read, and the wait before each retry. */ const ROSTER_ATTEMPTS = 3;
|
|
38
|
+
const ROSTER_RETRY_MS = 1000;
|
|
39
|
+
/**
|
|
40
|
+
* A failure that may answer differently a moment later: the request never
|
|
41
|
+
* went out because the sign-in token was not ready in time (`authorizedFetch`
|
|
42
|
+
* answers that `401` itself), the route timed out, was busy, or failed. A
|
|
43
|
+
* `403` (not a member), `400` or `423` (locked) will not change by asking
|
|
44
|
+
* again.
|
|
45
|
+
*/ const RETRYABLE_STATUSES = new Set([
|
|
46
|
+
401,
|
|
47
|
+
408,
|
|
48
|
+
429
|
|
49
|
+
]);
|
|
50
|
+
let RosterReadError = class RosterReadError extends Error {
|
|
51
|
+
constructor(message, retryable){
|
|
52
|
+
super(message), this.retryable = retryable;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
36
55
|
function memberOption(member) {
|
|
37
56
|
var _member_role;
|
|
38
57
|
const option = crmMemberOption(member);
|
|
@@ -40,11 +59,36 @@ function memberOption(member) {
|
|
|
40
59
|
role: String((_member_role = member['role']) != null ? _member_role : '')
|
|
41
60
|
}) : null;
|
|
42
61
|
}
|
|
62
|
+
async function readRosterOnce(user, orgId) {
|
|
63
|
+
var _payload_members;
|
|
64
|
+
const response = await authorizedFetch(user, `/api/orgs/members?orgId=${encodeURIComponent(orgId)}`);
|
|
65
|
+
const payload = await response.json().catch(()=>({}));
|
|
66
|
+
if (!response.ok) {
|
|
67
|
+
throw new RosterReadError(payload.error || 'The team could not be loaded.', RETRYABLE_STATUSES.has(response.status) || response.status >= 500);
|
|
68
|
+
}
|
|
69
|
+
return ((_payload_members = payload.members) != null ? _payload_members : []).map(memberOption).filter((member)=>member !== null).sort((a, b)=>a.label.localeCompare(b.label));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The roster, asked again when the first answer was a failure that can
|
|
73
|
+
* clear. A page that loses the read keeps naming owners by their uid until
|
|
74
|
+
* it is reloaded, so one late token or one busy moment on the route must not
|
|
75
|
+
* be the final answer.
|
|
76
|
+
*/ async function readRoster(user, orgId) {
|
|
77
|
+
for(let attempt = 1;; attempt += 1){
|
|
78
|
+
try {
|
|
79
|
+
return await readRosterOnce(user, orgId);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
const retryable = !(error instanceof RosterReadError) || error.retryable;
|
|
82
|
+
if (!retryable || attempt >= ROSTER_ATTEMPTS) throw error;
|
|
83
|
+
await new Promise((resolve)=>setTimeout(resolve, ROSTER_RETRY_MS * attempt));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
43
87
|
export function useOrgMemberDirectory(orgId) {
|
|
44
88
|
const { data: user } = useUser();
|
|
45
89
|
const [state, setState] = useState({
|
|
46
90
|
orgId: null,
|
|
47
|
-
members:
|
|
91
|
+
members: NO_MEMBERS,
|
|
48
92
|
loading: false,
|
|
49
93
|
error: null
|
|
50
94
|
});
|
|
@@ -53,14 +97,7 @@ export function useOrgMemberDirectory(orgId) {
|
|
|
53
97
|
let active = true;
|
|
54
98
|
let roster = rosterCache.get(orgId);
|
|
55
99
|
if (!roster) {
|
|
56
|
-
roster =
|
|
57
|
-
var _payload_members;
|
|
58
|
-
const payload = await response.json().catch(()=>({}));
|
|
59
|
-
if (!response.ok) {
|
|
60
|
-
throw new Error(payload.error || 'The team could not be loaded.');
|
|
61
|
-
}
|
|
62
|
-
return ((_payload_members = payload.members) != null ? _payload_members : []).map(memberOption).filter((member)=>member !== null).sort((a, b)=>a.label.localeCompare(b.label));
|
|
63
|
-
});
|
|
100
|
+
roster = readRoster(user, orgId);
|
|
64
101
|
rosterCache.set(orgId, roster);
|
|
65
102
|
// A failed read is not kept: the next mount asks again rather than
|
|
66
103
|
// remembering an outage for the life of the page.
|
|
@@ -68,7 +105,7 @@ export function useOrgMemberDirectory(orgId) {
|
|
|
68
105
|
}
|
|
69
106
|
setState({
|
|
70
107
|
orgId,
|
|
71
|
-
members:
|
|
108
|
+
members: NO_MEMBERS,
|
|
72
109
|
loading: true,
|
|
73
110
|
error: null
|
|
74
111
|
});
|
|
@@ -83,7 +120,7 @@ export function useOrgMemberDirectory(orgId) {
|
|
|
83
120
|
if (active) {
|
|
84
121
|
setState({
|
|
85
122
|
orgId,
|
|
86
|
-
members:
|
|
123
|
+
members: NO_MEMBERS,
|
|
87
124
|
loading: false,
|
|
88
125
|
error: error instanceof Error ? error.message : String(error)
|
|
89
126
|
});
|
|
@@ -96,7 +133,7 @@ export function useOrgMemberDirectory(orgId) {
|
|
|
96
133
|
orgId,
|
|
97
134
|
user
|
|
98
135
|
]);
|
|
99
|
-
const members = state.orgId === orgId ? state.members :
|
|
136
|
+
const members = state.orgId === orgId ? state.members : NO_MEMBERS;
|
|
100
137
|
const nameOf = useCallback((ref)=>{
|
|
101
138
|
var _ref;
|
|
102
139
|
var _findOrgMember;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-org-member-directory.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 CrmMemberOption, crmMemberOption, findOrgMember } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useEffect, useState } from 'react'\n\n/** One person a task can be assigned to. */\nexport interface OrgMemberOption extends CrmMemberOption {\n role: string\n}\n\n/**\n * The org's roster, read once per org per page and shared by every mount.\n *\n * The roster is what the assignee picker offers and what the assignee\n * column prints — a uid is not a name anybody recognizes. It comes from\n * `GET /api/orgs/members`, which re-derives membership with the Admin SDK\n * (the client-side rules cannot evaluate a list query against the member's\n * own-document clause, so a direct read is refused for the very people who\n * may assign tasks). A roster changes on the order of days; the promise is\n * kept so a second card on the same page shares the request rather than\n * repeating it.\n */\nconst rosterCache = new Map<string, Promise<OrgMemberOption[]>>()\n\n/** Test seam. */\nexport function resetOrgMemberDirectoryCache(): void {\n rosterCache.clear()\n}\n\nfunction memberOption(member: Record<string, unknown>): OrgMemberOption | null {\n const option = crmMemberOption(member)\n return option ? { ...option, role: String(member['role'] ?? '') } : null\n}\n\nexport interface OrgMemberDirectory {\n members: OrgMemberOption[]\n /** The read has not settled — the picker disables rather than offers nobody. */\n loading: boolean\n /** Why the roster could not be read, when it could not. */\n error: string | null\n /**\n * A stored reference — a uid, or an address the roster has — as a person,\n * or the reference itself for someone no longer on the roster.\n */\n nameOf: (ref: string | null | undefined) => string\n}\n\nexport function useOrgMemberDirectory(\n orgId: string | null | undefined,\n): OrgMemberDirectory {\n const { data: user } = useUser()\n const [state, setState] = useState<{\n orgId: string | null\n members: OrgMemberOption[]\n loading: boolean\n error: string | null\n }>({ orgId: null, members: [], loading: false, error: null })\n\n useEffect(() => {\n if (!orgId || !user) return\n let active = true\n let roster = rosterCache.get(orgId)\n if (!roster) {\n roster = authorizedFetch(\n user,\n `/api/orgs/members?orgId=${encodeURIComponent(orgId)}`,\n ).then(async (response) => {\n const payload = (await response.json().catch(() => ({}))) as {\n members?: Array<Record<string, unknown>>\n error?: string\n }\n if (!response.ok) {\n throw new Error(payload.error || 'The team could not be loaded.')\n }\n return (payload.members ?? [])\n .map(memberOption)\n .filter((member): member is OrgMemberOption => member !== null)\n .sort((a, b) => a.label.localeCompare(b.label))\n })\n rosterCache.set(orgId, roster)\n // A failed read is not kept: the next mount asks again rather than\n // remembering an outage for the life of the page.\n roster.catch(() => rosterCache.delete(orgId))\n }\n setState({ orgId, members: [], loading: true, error: null })\n roster.then(\n (members) => {\n if (active) setState({ orgId, members, loading: false, error: null })\n },\n (error: unknown) => {\n if (active) {\n setState({\n orgId,\n members: [],\n loading: false,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n },\n )\n return () => {\n active = false\n }\n }, [orgId, user])\n\n const members = state.orgId === orgId ? state.members : []\n const nameOf = useCallback(\n (ref: string | null | undefined) => {\n if (!ref) return ''\n return findOrgMember(members, ref)?.label ?? ref\n },\n [members],\n )\n return {\n members,\n loading: Boolean(orgId) && (state.orgId !== orgId || state.loading),\n error: state.orgId === orgId ? state.error : null,\n nameOf,\n }\n}\n"],"names":["crmMemberOption","findOrgMember","authorizedFetch","useUser","useCallback","useEffect","useState","rosterCache","Map","resetOrgMemberDirectoryCache","clear","memberOption","member","option","role","String","useOrgMemberDirectory","orgId","data","user","state","setState","members","loading","error","active","roster","get","encodeURIComponent","then","response","payload","json","catch","ok","Error","map","filter","sort","a","b","label","localeCompare","set","delete","message","nameOf","ref","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA+BA,eAAe,EAAEC,aAAa,QAAQ,eAAc;AACnF,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAOxD;;;;;;;;;;;CAWC,GACD,MAAMC,cAAc,IAAIC;AAExB,eAAe,GACf,OAAO,SAASC;IACdF,YAAYG,KAAK;AACnB;AAEA,SAASC,aAAaC,MAA+B;QAETA;IAD1C,MAAMC,SAASb,gBAAgBY;IAC/B,OAAOC,SAAS,aAAKA;QAAQC,MAAMC,QAAOH,eAAAA,MAAM,CAAC,OAAO,YAAdA,eAAkB;SAAQ;AACtE;AAeA,OAAO,SAASI,sBACdC,KAAgC;IAEhC,MAAM,EAAEC,MAAMC,IAAI,EAAE,GAAGhB;IAC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YACLC,SAAS;QACX;IACF,GAAG;QAACR;QAAOE;KAAK;IAEhB,MAAMG,UAAUF,MAAMH,KAAK,KAAKA,QAAQG,MAAME,OAAO,GAAG,EAAE;IAC1D,MAAMwB,SAAS1C,YACb,CAAC2C;;YAEQ9C;QADP,IAAI,CAAC8C,KAAK,OAAO;QACjB,gBAAO9C,iBAAAA,cAAcqB,SAASyB,yBAAvB9C,eAA6BwC,KAAK,mBAAIM;IAC/C,GACA;QAACzB;KAAQ;IAEX,OAAO;QACLA;QACAC,SAASyB,QAAQ/B,UAAWG,CAAAA,MAAMH,KAAK,KAAKA,SAASG,MAAMG,OAAO,AAAD;QACjEC,OAAOJ,MAAMH,KAAK,KAAKA,QAAQG,MAAMI,KAAK,GAAG;QAC7CsB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-org-member-directory.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 CrmMemberOption, crmMemberOption, findOrgMember } from '@aglyn/aglyn'\nimport { authorizedFetch, type TokenSource } from '@aglyn/shared-util-http/authorized-token'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useEffect, useState } from 'react'\n\n/** One person a task can be assigned to. */\nexport interface OrgMemberOption extends CrmMemberOption {\n role: string\n}\n\n/**\n * The org's roster, read once per org per page and shared by every mount.\n *\n * The roster is what the assignee picker offers and what the assignee\n * column prints — a uid is not a name anybody recognizes. It comes from\n * `GET /api/orgs/members`, which re-derives membership with the Admin SDK\n * (the client-side rules cannot evaluate a list query against the member's\n * own-document clause, so a direct read is refused for the very people who\n * may assign tasks). A roster changes on the order of days; the promise is\n * kept so a second card on the same page shares the request rather than\n * repeating it.\n */\nconst rosterCache = new Map<string, Promise<OrgMemberOption[]>>()\n\n/** Test seam. */\nexport function resetOrgMemberDirectoryCache(): void {\n rosterCache.clear()\n}\n\n/** The one empty roster, so a caller's memo does not change on every render while it loads. */\nconst NO_MEMBERS: OrgMemberOption[] = []\n\n/** Tries per roster read, and the wait before each retry. */\nconst ROSTER_ATTEMPTS = 3\nconst ROSTER_RETRY_MS = 1_000\n\n/**\n * A failure that may answer differently a moment later: the request never\n * went out because the sign-in token was not ready in time (`authorizedFetch`\n * answers that `401` itself), the route timed out, was busy, or failed. A\n * `403` (not a member), `400` or `423` (locked) will not change by asking\n * again.\n */\nconst RETRYABLE_STATUSES = new Set([401, 408, 429])\n\nclass RosterReadError extends Error {\n constructor(\n message: string,\n readonly retryable: boolean,\n ) {\n super(message)\n }\n}\n\nfunction memberOption(member: Record<string, unknown>): OrgMemberOption | null {\n const option = crmMemberOption(member)\n return option ? { ...option, role: String(member['role'] ?? '') } : null\n}\n\nasync function readRosterOnce(user: TokenSource, orgId: string): Promise<OrgMemberOption[]> {\n const response = await authorizedFetch(\n user,\n `/api/orgs/members?orgId=${encodeURIComponent(orgId)}`,\n )\n const payload = (await response.json().catch(() => ({}))) as {\n members?: Array<Record<string, unknown>>\n error?: string\n }\n if (!response.ok) {\n throw new RosterReadError(\n payload.error || 'The team could not be loaded.',\n RETRYABLE_STATUSES.has(response.status) || response.status >= 500,\n )\n }\n return (payload.members ?? [])\n .map(memberOption)\n .filter((member): member is OrgMemberOption => member !== null)\n .sort((a, b) => a.label.localeCompare(b.label))\n}\n\n/**\n * The roster, asked again when the first answer was a failure that can\n * clear. A page that loses the read keeps naming owners by their uid until\n * it is reloaded, so one late token or one busy moment on the route must not\n * be the final answer.\n */\nasync function readRoster(user: TokenSource, orgId: string): Promise<OrgMemberOption[]> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await readRosterOnce(user, orgId)\n } catch (error) {\n const retryable = !(error instanceof RosterReadError) || error.retryable\n if (!retryable || attempt >= ROSTER_ATTEMPTS) throw error\n await new Promise((resolve) => setTimeout(resolve, ROSTER_RETRY_MS * attempt))\n }\n }\n}\n\nexport interface OrgMemberDirectory {\n members: OrgMemberOption[]\n /** The read has not settled — the picker disables rather than offers nobody. */\n loading: boolean\n /** Why the roster could not be read, when it could not. */\n error: string | null\n /**\n * A stored reference — a uid, or an address the roster has — as a person,\n * or the reference itself for someone no longer on the roster.\n */\n nameOf: (ref: string | null | undefined) => string\n}\n\nexport function useOrgMemberDirectory(\n orgId: string | null | undefined,\n): OrgMemberDirectory {\n const { data: user } = useUser()\n const [state, setState] = useState<{\n orgId: string | null\n members: OrgMemberOption[]\n loading: boolean\n error: string | null\n }>({ orgId: null, members: NO_MEMBERS, loading: false, error: null })\n\n useEffect(() => {\n if (!orgId || !user) return\n let active = true\n let roster = rosterCache.get(orgId)\n if (!roster) {\n roster = readRoster(user, orgId)\n rosterCache.set(orgId, roster)\n // A failed read is not kept: the next mount asks again rather than\n // remembering an outage for the life of the page.\n roster.catch(() => rosterCache.delete(orgId))\n }\n setState({ orgId, members: NO_MEMBERS, loading: true, error: null })\n roster.then(\n (members) => {\n if (active) setState({ orgId, members, loading: false, error: null })\n },\n (error: unknown) => {\n if (active) {\n setState({\n orgId,\n members: NO_MEMBERS,\n loading: false,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n },\n )\n return () => {\n active = false\n }\n }, [orgId, user])\n\n const members = state.orgId === orgId ? state.members : NO_MEMBERS\n const nameOf = useCallback(\n (ref: string | null | undefined) => {\n if (!ref) return ''\n return findOrgMember(members, ref)?.label ?? ref\n },\n [members],\n )\n return {\n members,\n loading: Boolean(orgId) && (state.orgId !== orgId || state.loading),\n error: state.orgId === orgId ? state.error : null,\n nameOf,\n }\n}\n"],"names":["crmMemberOption","findOrgMember","authorizedFetch","useUser","useCallback","useEffect","useState","rosterCache","Map","resetOrgMemberDirectoryCache","clear","NO_MEMBERS","ROSTER_ATTEMPTS","ROSTER_RETRY_MS","RETRYABLE_STATUSES","Set","RosterReadError","Error","message","retryable","memberOption","member","option","role","String","readRosterOnce","user","orgId","payload","response","encodeURIComponent","json","catch","ok","error","has","status","members","map","filter","sort","a","b","label","localeCompare","readRoster","attempt","Promise","resolve","setTimeout","useOrgMemberDirectory","data","state","setState","loading","active","roster","get","set","delete","then","nameOf","ref","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA+BA,eAAe,EAAEC,aAAa,QAAQ,eAAc;AACnF,SAASC,eAAe,QAA0B,2CAA0C;AAC5F,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAOxD;;;;;;;;;;;CAWC,GACD,MAAMC,cAAc,IAAIC;AAExB,eAAe,GACf,OAAO,SAASC;IACdF,YAAYG,KAAK;AACnB;AAEA,6FAA6F,GAC7F,MAAMC,aAAgC,EAAE;AAExC,2DAA2D,GAC3D,MAAMC,kBAAkB;AACxB,MAAMC,kBAAkB;AAExB;;;;;;CAMC,GACD,MAAMC,qBAAqB,IAAIC,IAAI;IAAC;IAAK;IAAK;CAAI;AAElD,IAAA,AAAMC,kBAAN,MAAMA,wBAAwBC;IAC5B,YACEC,OAAe,EACf,AAASC,SAAkB,CAC3B;QACA,KAAK,CAACD,eAFGC,YAAAA;IAGX;AACF;AAEA,SAASC,aAAaC,MAA+B;QAETA;IAD1C,MAAMC,SAAStB,gBAAgBqB;IAC/B,OAAOC,SAAS,aAAKA;QAAQC,MAAMC,QAAOH,eAAAA,MAAM,CAAC,OAAO,YAAdA,eAAkB;SAAQ;AACtE;AAEA,eAAeI,eAAeC,IAAiB,EAAEC,KAAa;QAepDC;IAdR,MAAMC,WAAW,MAAM3B,gBACrBwB,MACA,CAAC,wBAAwB,EAAEI,mBAAmBH,QAAQ;IA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AAO6B;YACvB,mEAAmE;YACnE,kDAAkD;YAClDA,OAAOxB,KAAK,CAAC,IAAMzB,YAAYoD,MAAM,CAAChC;QACxC;QACA0B,SAAS;YAAE1B;YAAOU,SAAS1B;YAAY2C,SAAS;YAAMpB,OAAO;QAAK;QAClEsB,OAAOI,IAAI,CACT,CAACvB;YACC,IAAIkB,QAAQF,SAAS;gBAAE1B;gBAAOU;gBAASiB,SAAS;gBAAOpB,OAAO;YAAK;QACrE,GACA,CAACA;YACC,IAAIqB,QAAQ;gBACVF,SAAS;oBACP1B;oBACAU,SAAS1B;oBACT2C,SAAS;oBACTpB,OAAOA,iBAAiBjB,QAAQiB,MAAMhB,OAAO,GAAGM,OAAOU;gBACzD;YACF;QACF;QAEF,OAAO;YACLqB,SAAS;QACX;IACF,GAAG;QAAC5B;QAAOD;KAAK;IAEhB,MAAMW,UAAUe,MAAMzB,KAAK,KAAKA,QAAQyB,MAAMf,OAAO,GAAG1B;IACxD,MAAMkD,SAASzD,YACb,CAAC0D;;YAEQ7D;QADP,IAAI,CAAC6D,KAAK,OAAO;QACjB,gBAAO7D,iBAAAA,cAAcoC,SAASyB,yBAAvB7D,eAA6B0C,KAAK,mBAAImB;IAC/C,GACA;QAACzB;KAAQ;IAEX,OAAO;QACLA;QACAiB,SAASS,QAAQpC,UAAWyB,CAAAA,MAAMzB,KAAK,KAAKA,SAASyB,MAAME,OAAO,AAAD;QACjEpB,OAAOkB,MAAMzB,KAAK,KAAKA,QAAQyB,MAAMlB,KAAK,GAAG;QAC7C2B;IACF;AACF"}
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
/**
|
|
18
|
+
* Whether the signed-in member is known NOT to hold "Move contacts and deals
|
|
19
|
+
* between stages" where a stage route would ask it (AGL-4047), so a stage
|
|
20
|
+
* control switches off with the permission named beside it.
|
|
21
|
+
*
|
|
22
|
+
* Read as the routes read it. Given a site: the site's `memberPermissions`
|
|
23
|
+
* stamp, else the preset of the member's site role. Given none, beneath the org
|
|
24
|
+
* hub's mount: the catalog's verdict for an org-wide member, off their own
|
|
25
|
+
* membership document and custom role.
|
|
26
|
+
*
|
|
27
|
+
* `true` only once the answer is known, so nobody sees a control flash off
|
|
28
|
+
* while it loads. A reader with no membership in the org is staff, whom the org
|
|
29
|
+
* doors admit: there the server answers. A deal's route also asks "Manage
|
|
30
|
+
* data", which the CRM's pages have already asked by the time this is drawn.
|
|
31
|
+
*/
|
|
32
|
+
export declare function useStageMoveBlocked(hostId: string | null | undefined): boolean;
|