@aglyn/plugins-crm 1.11.0 → 1.13.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-send-email-dialog.js +1 -1
- package/src/lib/components/crm-send-email-dialog.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/declarations.server.js +16 -0
- package/src/lib/declarations.server.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/scope-sharing-patch.d.ts +22 -0
- package/src/lib/server/scope-sharing-patch.js +25 -0
- package/src/lib/server/scope-sharing-patch.js.map +1 -0
- 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
|
@@ -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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ACG;YACtB,MAAM,CAACxC,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,SAA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AO5D,YACL,CAACW,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,kB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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,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QACF;QAEF,OAAO;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,mB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,GAAG,CAAC/B,OAAO6B;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;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
17
|
+
import { resolveOrgPermissions } from "@aglyn/aglyn/app-utils/org-permissions";
|
|
18
|
+
import { isOrgWideMember } from "@aglyn/aglyn/app-utils/organizations";
|
|
19
|
+
import { useFirestore, useFirestoreDoc, useUser } from "@aglyn/tenant-feature-instance";
|
|
20
|
+
import { doc } from "firebase/firestore";
|
|
21
|
+
import { CRM_MOVE_STAGES_PERMISSION, CRM_MOVE_STAGES_SITE_ROLE_PRESET } from "../model/crm-permissions.js";
|
|
22
|
+
import { useCrmOrgMount } from "./use-crm-org-mount.js";
|
|
23
|
+
/**
|
|
24
|
+
* Whether the signed-in member is known NOT to hold "Move contacts and deals
|
|
25
|
+
* between stages" where a stage route would ask it (AGL-4047), so a stage
|
|
26
|
+
* control switches off with the permission named beside it.
|
|
27
|
+
*
|
|
28
|
+
* Read as the routes read it. Given a site: the site's `memberPermissions`
|
|
29
|
+
* stamp, else the preset of the member's site role. Given none, beneath the org
|
|
30
|
+
* hub's mount: the catalog's verdict for an org-wide member, off their own
|
|
31
|
+
* membership document and custom role.
|
|
32
|
+
*
|
|
33
|
+
* `true` only once the answer is known, so nobody sees a control flash off
|
|
34
|
+
* while it loads. A reader with no membership in the org is staff, whom the org
|
|
35
|
+
* doors admit: there the server answers. A deal's route also asks "Manage
|
|
36
|
+
* data", which the CRM's pages have already asked by the time this is drawn.
|
|
37
|
+
*/ export function useStageMoveBlocked(hostId) {
|
|
38
|
+
var _ref, _ref1, _roleRead_data;
|
|
39
|
+
var _useCrmOrgMount;
|
|
40
|
+
const firestore = useFirestore();
|
|
41
|
+
const { data: user } = useUser();
|
|
42
|
+
const uid = (_ref = user == null ? void 0 : user.uid) != null ? _ref : '';
|
|
43
|
+
const site = hostId || '';
|
|
44
|
+
const orgId = (_ref1 = (_useCrmOrgMount = useCrmOrgMount()) == null ? void 0 : _useCrmOrgMount.orgId) != null ? _ref1 : '';
|
|
45
|
+
const hostRead = useFirestoreDoc(()=>site ? doc(firestore, 'hosts', site) : null, [
|
|
46
|
+
firestore,
|
|
47
|
+
site
|
|
48
|
+
]);
|
|
49
|
+
const memberRead = useFirestoreDoc(()=>!site && orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null, [
|
|
50
|
+
firestore,
|
|
51
|
+
site,
|
|
52
|
+
orgId,
|
|
53
|
+
uid
|
|
54
|
+
]);
|
|
55
|
+
const member = memberRead.status === 'success' ? memberRead.data : undefined;
|
|
56
|
+
const roleId = !site && typeof (member == null ? void 0 : member.roleId) === 'string' ? member.roleId : '';
|
|
57
|
+
const roleRead = useFirestoreDoc(()=>orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null, [
|
|
58
|
+
firestore,
|
|
59
|
+
orgId,
|
|
60
|
+
roleId
|
|
61
|
+
]);
|
|
62
|
+
if (!uid) return false;
|
|
63
|
+
if (site) {
|
|
64
|
+
return hostRead.status === 'success' && !holdsStampedSiteKey(hostRead.data, uid, CRM_MOVE_STAGES_PERMISSION, CRM_MOVE_STAGES_SITE_ROLE_PRESET);
|
|
65
|
+
}
|
|
66
|
+
if (!member || roleId && roleRead.status === 'loading') return false;
|
|
67
|
+
const granted = resolveOrgPermissions(member, roleId && roleRead.status === 'success' ? (_roleRead_data = roleRead.data) != null ? _roleRead_data : null : null);
|
|
68
|
+
return !(isOrgWideMember(member) && granted[CRM_MOVE_STAGES_PERMISSION] === true);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=use-stage-move-blocked.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-stage-move-blocked.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { type AglynOrgCustomRole, resolveOrgPermissions } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport { doc } from 'firebase/firestore'\nimport { CRM_MOVE_STAGES_PERMISSION, CRM_MOVE_STAGES_SITE_ROLE_PRESET } from '../model/crm-permissions'\nimport { useCrmOrgMount } from './use-crm-org-mount'\n\n/** A membership document, as the permission resolver reads one. */\ntype MemberRecord = NonNullable<Parameters<typeof resolveOrgPermissions>[0]>\n\n/**\n * Whether the signed-in member is known NOT to hold \"Move contacts and deals\n * between stages\" where a stage route would ask it (AGL-4047), so a stage\n * control switches off with the permission named beside it.\n *\n * Read as the routes read it. Given a site: the site's `memberPermissions`\n * stamp, else the preset of the member's site role. Given none, beneath the org\n * hub's mount: the catalog's verdict for an org-wide member, off their own\n * membership document and custom role.\n *\n * `true` only once the answer is known, so nobody sees a control flash off\n * while it loads. A reader with no membership in the org is staff, whom the org\n * doors admit: there the server answers. A deal's route also asks \"Manage\n * data\", which the CRM's pages have already asked by the time this is drawn.\n */\nexport function useStageMoveBlocked(hostId: string | null | undefined): boolean {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = user?.uid ?? ''\n const site = hostId || ''\n const orgId = useCrmOrgMount()?.orgId ?? ''\n const hostRead = useFirestoreDoc<{ memberRoles?: unknown; memberPermissions?: unknown }>(\n () => (site ? doc(firestore, 'hosts', site) : null),\n [firestore, site],\n )\n const memberRead = useFirestoreDoc<MemberRecord>(\n () => (!site && orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, site, orgId, uid],\n )\n const member = memberRead.status === 'success' ? memberRead.data : undefined\n const roleId = !site && typeof member?.roleId === 'string' ? member.roleId : ''\n const roleRead = useFirestoreDoc<AglynOrgCustomRole>(\n () => (orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null),\n [firestore, orgId, roleId],\n )\n if (!uid) return false\n if (site) {\n return (\n hostRead.status === 'success' &&\n !holdsStampedSiteKey(hostRead.data, uid, CRM_MOVE_STAGES_PERMISSION, CRM_MOVE_STAGES_SITE_ROLE_PRESET)\n )\n }\n if (!member || (roleId && roleRead.status === 'loading')) return false\n const granted = resolveOrgPermissions(member, roleId && roleRead.status === 'success' ? (roleRead.data ?? null) : null)\n return !(isOrgWideMember(member) && granted[CRM_MOVE_STAGES_PERMISSION] === true)\n}\n"],"names":["holdsStampedSiteKey","resolveOrgPermissions","isOrgWideMember","useFirestore","useFirestoreDoc","useUser","doc","CRM_MOVE_STAGES_PERMISSION","CRM_MOVE_STAGES_SITE_ROLE_PRESET","useCrmOrgMount","useStageMoveBlocked","hostId","roleRead","firestore","data","user","uid","site","orgId","hostRead","memberRead","member","status","undefined","roleId","granted"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAAkCC,qBAAqB,QAAQ,yCAAwC;AACvG,SAASC,eAAe,QAAQ,uCAAsC;AACtE,SAASC,YAAY,EAAEC,eAAe,EAAEC,OAAO,QAAQ,iCAAgC;AACvF,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,0BAA0B,EAAEC,gCAAgC,QAAQ,8BAA0B;AACvG,SAASC,cAAc,QAAQ,yBAAqB;AAKpD;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,oBAAoBC,MAAiC;qBA4BsBC;QAvB3EH;IAJd,MAAMI,YAAYV;IAClB,MAAM,EAAEW,MAAMC,IAAI,EAAE,GAAGV;IACvB,MAAMW,cAAMD,wBAAAA,KAAMC,GAAG,mBAAI;IACzB,MAAMC,OAAON,UAAU;IACvB,MAAMO,kBAAQT,kBAAAA,qCAAAA,gBAAkBS,KAAK,oBAAI;IACzC,MAAMC,WAAWf,gBACf,IAAOa,OAAOX,IAAIO,WAAW,SAASI,QAAQ,MAC9C;QAACJ;QAAWI;KAAK;IAEnB,MAAMG,aAAahB,gBACjB,IAAO,CAACa,QAAQC,SAASF,MAAMV,IAAIO,WAAW,QAAQK,OAAO,WAAWF,OAAO,MAC/E;QAACH;QAAWI;QAAMC;QAAOF;KAAI;IAE/B,MAAMK,SAASD,WAAWE,MAAM,KAAK,YAAYF,WAAWN,IAAI,GAAGS;IACnE,MAAMC,SAAS,CAACP,QAAQ,QAAOI,0BAAAA,OAAQG,MAAM,MAAK,WAAWH,OAAOG,MAAM,GAAG;IAC7E,MAAMZ,WAAWR,gBACf,IAAOc,SAASM,SAASlB,IAAIO,WAAW,QAAQK,OAAO,SAASM,UAAU,MAC1E;QAACX;QAAWK;QAAOM;KAAO;IAE5B,IAAI,CAACR,KAAK,OAAO;IACjB,IAAIC,MAAM;QACR,OACEE,SAASG,MAAM,KAAK,aACpB,CAACtB,oBAAoBmB,SAASL,IAAI,EAAEE,KAAKT,4BAA4BC;IAEzE;IACA,IAAI,CAACa,UAAWG,UAAUZ,SAASU,MAAM,KAAK,WAAY,OAAO;IACjE,MAAMG,UAAUxB,sBAAsBoB,QAAQG,UAAUZ,SAASU,MAAM,KAAK,aAAaV,iBAAAA,SAASE,IAAI,YAAbF,iBAAiB,OAAQ;IAClH,OAAO,CAAEV,CAAAA,gBAAgBmB,WAAWI,OAAO,CAAClB,2BAA2B,KAAK,IAAG;AACjF"}
|
|
@@ -41,7 +41,7 @@ export interface ContactStageResult {
|
|
|
41
41
|
* the signed-in user.
|
|
42
42
|
*
|
|
43
43
|
* Throws with the route's own message on a refusal, so a control can show
|
|
44
|
-
*
|
|
44
|
+
* why the permission refused it rather than a generic failure; a network
|
|
45
45
|
* failure throws as `fetch` would.
|
|
46
46
|
*/
|
|
47
47
|
export declare function setContactStage(user: MaybeTokenSource,
|
package/src/lib/model/crm-api.js
CHANGED
|
@@ -21,7 +21,7 @@ import { crmApiUrl } from "../constants/api-routes.js";
|
|
|
21
21
|
* the signed-in user.
|
|
22
22
|
*
|
|
23
23
|
* Throws with the route's own message on a refusal, so a control can show
|
|
24
|
-
*
|
|
24
|
+
* why the permission refused it rather than a generic failure; a network
|
|
25
25
|
* failure throws as `fetch` would.
|
|
26
26
|
*/ export async function setContactStage(user, /** The site, or `null` for a person no site holds (AGL-4122), named by `orgId`. */ hostId, contactId, stage, options = {}) {
|
|
27
27
|
const response = await authorizedFetch(user, crmApiUrl('contactStage'), {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-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\nimport type { ContactLifecycleStage } from '@aglyn/aglyn'\nimport {\n authorizedFetch,\n type MaybeTokenSource,\n} from '@aglyn/shared-util-http/authorized-token'\nimport { crmApiUrl } from '../constants/api-routes'\n\n/**\n * The console's client half of the CRM server routes (AGL-2605).\n *\n * A stage change goes through the server rather than a client-direct\n * Firestore write, and the reason is the event: `contactStageChanged` can\n * only be emitted by a server path that performed the write, so a record\n * page that wrote the facet itself would move the person and tell no\n * automation. A CLEAR comes the same way (AGL-2804), because a facet is the\n * server's to write. This is the one function a stage control calls.\n */\n\n/** What `crm/contact-stage` answers. */\nexport interface ContactStageResult {\n ok: true\n /** False when the contact was already in that stage — nothing moved. */\n changed: boolean\n /** The stage the contact now holds, `''` after a clear. */\n lifecycleStage: ContactLifecycleStage | ''\n /** The stage before the move, `''` when the contact had none. */\n previousStage: string\n}\n\n/**\n * Moves one contact to a lifecycle stage — or, with `null`, clears it — as\n * the signed-in user.\n *\n * Throws with the route's own message on a refusal, so a control can show\n *
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-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\nimport type { ContactLifecycleStage } from '@aglyn/aglyn'\nimport {\n authorizedFetch,\n type MaybeTokenSource,\n} from '@aglyn/shared-util-http/authorized-token'\nimport { crmApiUrl } from '../constants/api-routes'\n\n/**\n * The console's client half of the CRM server routes (AGL-2605).\n *\n * A stage change goes through the server rather than a client-direct\n * Firestore write, and the reason is the event: `contactStageChanged` can\n * only be emitted by a server path that performed the write, so a record\n * page that wrote the facet itself would move the person and tell no\n * automation. A CLEAR comes the same way (AGL-2804), because a facet is the\n * server's to write. This is the one function a stage control calls.\n */\n\n/** What `crm/contact-stage` answers. */\nexport interface ContactStageResult {\n ok: true\n /** False when the contact was already in that stage — nothing moved. */\n changed: boolean\n /** The stage the contact now holds, `''` after a clear. */\n lifecycleStage: ContactLifecycleStage | ''\n /** The stage before the move, `''` when the contact had none. */\n previousStage: string\n}\n\n/**\n * Moves one contact to a lifecycle stage — or, with `null`, clears it — as\n * the signed-in user.\n *\n * Throws with the route's own message on a refusal, so a control can show\n * why the permission refused it rather than a generic failure; a network\n * failure throws as `fetch` would.\n */\nexport async function setContactStage(\n user: MaybeTokenSource,\n /** The site, or `null` for a person no site holds (AGL-4122), named by `orgId`. */\n hostId: string | null,\n contactId: string,\n stage: ContactLifecycleStage | null,\n options: { fetchImpl?: typeof fetch; orgId?: string | null } = {},\n): Promise<ContactStageResult> {\n const response = await authorizedFetch(\n user,\n crmApiUrl('contactStage'),\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n ...(hostId ? {} : { orgId: options.orgId }),\n contactId,\n lifecycleStage: stage,\n }),\n },\n options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},\n )\n const payload = (await response.json().catch(() => ({}))) as\n | ContactStageResult\n | { error?: string }\n if (!response.ok) {\n throw new Error(\n (payload as { error?: string }).error ?? 'The stage could not be changed',\n )\n }\n return payload as ContactStageResult\n}\n"],"names":["authorizedFetch","crmApiUrl","setContactStage","user","hostId","contactId","stage","options","response","method","headers","body","JSON","stringify","orgId","lifecycleStage","fetchImpl","payload","json","catch","ok","Error","error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,eAAe,QAEV,2CAA0C;AACjD,SAASC,SAAS,QAAQ,6BAAyB;AAwBnD;;;;;;;CAOC,GACD,OAAO,eAAeC,gBACpBC,IAAsB,EACtB,iFAAiF,GACjFC,MAAqB,EACrBC,SAAiB,EACjBC,KAAmC,EACnCC,UAA+D,CAAC,CAAC;IAEjE,MAAMC,WAAW,MAAMR,gBACrBG,MACAF,UAAU,iBACV;QACEQ,QAAQ;QACRC,SAAS;YAAE,gBAAgB;QAAmB;QAC9CC,MAAMC,KAAKC,SAAS,CAAC;YACnBT;WACIA,SAAS,CAAC,IAAI;YAAEU,OAAOP,QAAQO,KAAK;QAAC;YACzCT;YACAU,gBAAgBT;;IAEpB,GACAC,QAAQS,SAAS,GAAG;QAAEA,WAAWT,QAAQS,SAAS;IAAC,IAAI,CAAC;IAE1D,MAAMC,UAAW,MAAMT,SAASU,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;IAGrD,IAAI,CAACX,SAASY,EAAE,EAAE;YAEd;QADF,MAAM,IAAIC,OACR,iBAAA,AAACJ,QAA+BK,KAAK,YAArC,iBAAyC;IAE7C;IACA,OAAOL;AACT"}
|
|
@@ -0,0 +1,35 @@
|
|
|
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 { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types';
|
|
18
|
+
import type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements';
|
|
19
|
+
import type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions';
|
|
20
|
+
/** The CRM's workspace keys, declared by tier. */
|
|
21
|
+
export type CrmPermission = 'crm.settings';
|
|
22
|
+
/** "Change CRM settings". */
|
|
23
|
+
export declare const CRM_SETTINGS_PERMISSION: CrmPermission;
|
|
24
|
+
/** The keys as the plugin declares them; owners and admins hold it by default. */
|
|
25
|
+
export declare const CRM_PERMISSIONS: readonly PluginPermission[];
|
|
26
|
+
/** The refusal a door or a control answers without it: names the permission, never a role. */
|
|
27
|
+
export declare function crmSettingsPermissionRefusal(): string;
|
|
28
|
+
/** The key both stage routes ask. */
|
|
29
|
+
export declare const CRM_MOVE_STAGES_PERMISSION = "crm.moveStages";
|
|
30
|
+
/** Who moved a site's contacts and deals before it was a key: the site's Admin and Editor. */
|
|
31
|
+
export declare const CRM_MOVE_STAGES_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>>;
|
|
32
|
+
/** The CRM's site key, as the plugin declares it into the org permission catalog. */
|
|
33
|
+
export declare const CRM_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[];
|
|
34
|
+
/** The refusal a stage door or control answers without it: names the permission, never a role. */
|
|
35
|
+
export declare const CRM_MOVE_STAGES_REFUSAL = "Your role does not include \"Move contacts and deals between stages\" \u2014 ask an organization admin";
|