@aglyn/tenant-runtime 1.0.0-beta.221 → 1.0.0-beta.223
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -3
- package/package.json +6 -3
- package/src/index.d.ts +0 -3
- package/src/index.js +1 -4
- package/src/index.js.map +1 -1
- package/src/lib/apply-publish-schedule.js +41 -17
- package/src/lib/apply-publish-schedule.js.map +1 -1
- package/src/lib/compose-screen-nodes.d.ts +9 -0
- package/src/lib/compose-screen-nodes.js +13 -4
- package/src/lib/compose-screen-nodes.js.map +1 -1
- package/src/lib/get-site-icon-facts.d.ts +43 -0
- package/src/lib/get-site-icon-facts.js +105 -0
- package/src/lib/get-site-icon-facts.js.map +1 -0
- package/src/lib/self-hosted-fonts.d.ts +44 -0
- package/src/lib/self-hosted-fonts.js +148 -0
- package/src/lib/self-hosted-fonts.js.map +1 -0
- package/src/lib/assign-contact-owner.d.ts +0 -162
- package/src/lib/assign-contact-owner.js +0 -340
- package/src/lib/assign-contact-owner.js.map +0 -1
- package/src/lib/associate-company-by-domain.d.ts +0 -70
- package/src/lib/associate-company-by-domain.js +0 -153
- package/src/lib/associate-company-by-domain.js.map +0 -1
- package/src/lib/capture-host-contact.d.ts +0 -104
- package/src/lib/capture-host-contact.js +0 -151
- package/src/lib/capture-host-contact.js.map +0 -1
- package/src/lib/repeat-record-pages.d.ts +0 -48
- package/src/lib/repeat-record-pages.js +0 -64
- package/src/lib/repeat-record-pages.js.map +0 -1
- package/src/lib/resolve-dataset.d.ts +0 -40
- package/src/lib/resolve-dataset.js +0 -64
- package/src/lib/resolve-dataset.js.map +0 -1
|
@@ -0,0 +1,148 @@
|
|
|
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 { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
import { boundedAwait, createSettledValueCache } from "@aglyn/shared-util-http/bounded-await";
|
|
18
|
+
// By path: the theme lib's barrel carries React providers a server module
|
|
19
|
+
// has no use for (AGL-405).
|
|
20
|
+
import { getGoogleFontsUrl } from "@aglyn/shared-ui-theme/util/host-theme";
|
|
21
|
+
import { googleFontFileUrl, isSelfHostedFontPath, parseGoogleFontFaces, selfHostedFontFaceCss, selfHostedFontPreloads } from "@aglyn/shared-ui-theme/util/self-hosted-fonts";
|
|
22
|
+
/**
|
|
23
|
+
* The tenant's half of self-hosted theme fonts (AGL-3485): fetching Google's
|
|
24
|
+
* stylesheet for a theme, and serving the files it names from the site's own
|
|
25
|
+
* origin. What is done with the stylesheet, and why, is the note on
|
|
26
|
+
* `@aglyn/shared-ui-theme/util/self-hosted-fonts`.
|
|
27
|
+
*/ /**
|
|
28
|
+
* A current desktop Chrome. Google's CSS2 API picks the font FORMAT from the
|
|
29
|
+
* user agent, and a server's default agent is answered with TrueType; this
|
|
30
|
+
* one is answered with WOFF2, the format every browser a site supports reads.
|
|
31
|
+
*/ const WOFF2_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36';
|
|
32
|
+
/** How long one process trusts a stylesheet it fetched. */ const STYLESHEET_TTL_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
/** How long a failed fetch is remembered before it is tried again. */ const FAILURE_TTL_MS = 5 * 60 * 1000;
|
|
34
|
+
/** How long a page render waits for Google before falling back. */ const STYLESHEET_TIMEOUT_MS = 2500;
|
|
35
|
+
/** The largest font file the route will pass on. */ const MAX_FONT_BYTES = 2 * 1024 * 1024;
|
|
36
|
+
/** A font file's URL never changes its bytes: the version is in the path. */ export const SELF_HOSTED_FONT_CACHE_CONTROL = 'public, max-age=31536000, s-maxage=31536000, immutable';
|
|
37
|
+
/**
|
|
38
|
+
* What this process learned about each stylesheet: the faces, or null for a
|
|
39
|
+
* failure. VALUES, never an in-flight promise — the settled-value cache
|
|
40
|
+
* refuses one. A promise held across requests is awaited by renders that did
|
|
41
|
+
* not create it, and one that never settles stalled every page of every site
|
|
42
|
+
* on the instance until the function timed out (AGL-3565).
|
|
43
|
+
*/ const stylesheets = createSettledValueCache();
|
|
44
|
+
/** Test seam: the process cache would otherwise leak between cases. */ export function resetSelfHostedFontsForTests() {
|
|
45
|
+
stylesheets.clear();
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Google's faces for a stylesheet URL, or null; never waits past `ms`. The
|
|
49
|
+
* deadline is a real timer (`boundedAwait`): an abort signal alone did not
|
|
50
|
+
* bound Next's patched fetch on Vercel, whose promise could never settle.
|
|
51
|
+
*/ function fetchFaces(url, ms) {
|
|
52
|
+
return boundedAwait((signal)=>fetch(url, {
|
|
53
|
+
headers: {
|
|
54
|
+
'User-Agent': WOFF2_USER_AGENT
|
|
55
|
+
},
|
|
56
|
+
signal,
|
|
57
|
+
next: {
|
|
58
|
+
revalidate: STYLESHEET_TTL_MS / 1000
|
|
59
|
+
}
|
|
60
|
+
}).then(async (response)=>{
|
|
61
|
+
if (!response.ok) return null;
|
|
62
|
+
const parsed = parseGoogleFontFaces(await response.text());
|
|
63
|
+
return parsed.length ? parsed : null;
|
|
64
|
+
}).catch(()=>null), ms, null, 'self-hosted-fonts.stylesheet');
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Google's faces for a stylesheet URL, from this process's cache when it has
|
|
68
|
+
* them. Null when the fetch failed, timed out or answered with nothing usable;
|
|
69
|
+
* the page then links the stylesheet as it always did, rather than losing its
|
|
70
|
+
* font. Asked through `fetch` with a day's revalidation, which on the server is
|
|
71
|
+
* Next's data cache: a cold process reads the stored stylesheet rather than
|
|
72
|
+
* asking Google again.
|
|
73
|
+
*/ function facesFor(url) {
|
|
74
|
+
return stylesheets.readThrough(url, ()=>fetchFaces(url, STYLESHEET_TIMEOUT_MS), (faces)=>faces ? STYLESHEET_TTL_MS : FAILURE_TTL_MS);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The theme's Google fonts as rules to inline and files to preload, or null
|
|
78
|
+
* when the theme loads none or Google could not be read — in which case the
|
|
79
|
+
* caller links the stylesheet as before.
|
|
80
|
+
*/ export async function selfHostedThemeFonts(theme) {
|
|
81
|
+
const url = getGoogleFontsUrl(theme == null ? void 0 : theme.fonts);
|
|
82
|
+
if (!url) return null;
|
|
83
|
+
const faces = await facesFor(url);
|
|
84
|
+
if (!faces) return null;
|
|
85
|
+
return {
|
|
86
|
+
css: selfHostedFontFaceCss(faces),
|
|
87
|
+
preloads: selfHostedFontPreloads(theme, faces)
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* One font file, fetched from Google and answered from the site's origin with
|
|
92
|
+
* a year-long `immutable` policy. `path` is the part below `/s/` on Google's
|
|
93
|
+
* origin (`inter/v18/….woff2`); anything else is a 404, so this route cannot
|
|
94
|
+
* be pointed at any other URL.
|
|
95
|
+
*
|
|
96
|
+
* The edge keeps the answer for the year too (`s-maxage`), so Google is asked
|
|
97
|
+
* once per file per edge region rather than once per visitor.
|
|
98
|
+
*/ export async function serveSelfHostedFont(path) {
|
|
99
|
+
var _upstream_headers_get;
|
|
100
|
+
const notFound = ()=>new Response('Not found', {
|
|
101
|
+
status: 404,
|
|
102
|
+
headers: {
|
|
103
|
+
'Cache-Control': 'public, max-age=300'
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
if (!isSelfHostedFontPath(path)) return notFound();
|
|
107
|
+
let upstream;
|
|
108
|
+
try {
|
|
109
|
+
upstream = await fetch(googleFontFileUrl(path), {
|
|
110
|
+
headers: {
|
|
111
|
+
'User-Agent': WOFF2_USER_AGENT
|
|
112
|
+
},
|
|
113
|
+
cache: 'force-cache'
|
|
114
|
+
});
|
|
115
|
+
} catch (unused) {
|
|
116
|
+
return new Response('Font unavailable', {
|
|
117
|
+
status: 502,
|
|
118
|
+
headers: {
|
|
119
|
+
'Cache-Control': 'no-store'
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (upstream.status === 404) return notFound();
|
|
124
|
+
const length = Number((_upstream_headers_get = upstream.headers.get('content-length')) != null ? _upstream_headers_get : 0);
|
|
125
|
+
if (!upstream.ok || !upstream.body || length > MAX_FONT_BYTES) {
|
|
126
|
+
return new Response('Font unavailable', {
|
|
127
|
+
status: 502,
|
|
128
|
+
headers: {
|
|
129
|
+
'Cache-Control': 'no-store'
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return new Response(upstream.body, {
|
|
134
|
+
status: 200,
|
|
135
|
+
headers: _extends({
|
|
136
|
+
'Content-Type': 'font/woff2',
|
|
137
|
+
'Cache-Control': SELF_HOSTED_FONT_CACHE_CONTROL,
|
|
138
|
+
'X-Content-Type-Options': 'nosniff',
|
|
139
|
+
// Fonts are fetched in CORS mode; a site reached on two hostnames (its
|
|
140
|
+
// own domain and its platform subdomain) shares one cached answer.
|
|
141
|
+
'Access-Control-Allow-Origin': '*'
|
|
142
|
+
}, length ? {
|
|
143
|
+
'Content-Length': String(length)
|
|
144
|
+
} : {})
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
//# sourceMappingURL=self-hosted-fonts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/self-hosted-fonts.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 { HostTheme } from '@aglyn/shared-data-types'\nimport {\n boundedAwait,\n createSettledValueCache,\n} from '@aglyn/shared-util-http/bounded-await'\n// By path: the theme lib's barrel carries React providers a server module\n// has no use for (AGL-405).\nimport { getGoogleFontsUrl } from '@aglyn/shared-ui-theme/util/host-theme'\nimport {\n type GoogleFontFace,\n googleFontFileUrl,\n isSelfHostedFontPath,\n parseGoogleFontFaces,\n selfHostedFontFaceCss,\n selfHostedFontPreloads,\n} from '@aglyn/shared-ui-theme/util/self-hosted-fonts'\n\n/**\n * The tenant's half of self-hosted theme fonts (AGL-3485): fetching Google's\n * stylesheet for a theme, and serving the files it names from the site's own\n * origin. What is done with the stylesheet, and why, is the note on\n * `@aglyn/shared-ui-theme/util/self-hosted-fonts`.\n */\n\n/**\n * A current desktop Chrome. Google's CSS2 API picks the font FORMAT from the\n * user agent, and a server's default agent is answered with TrueType; this\n * one is answered with WOFF2, the format every browser a site supports reads.\n */\nconst WOFF2_USER_AGENT =\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +\n '(KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'\n\n/** How long one process trusts a stylesheet it fetched. */\nconst STYLESHEET_TTL_MS = 24 * 60 * 60 * 1000\n\n/** How long a failed fetch is remembered before it is tried again. */\nconst FAILURE_TTL_MS = 5 * 60 * 1000\n\n/** How long a page render waits for Google before falling back. */\nconst STYLESHEET_TIMEOUT_MS = 2_500\n\n/** The largest font file the route will pass on. */\nconst MAX_FONT_BYTES = 2 * 1024 * 1024\n\n/** A font file's URL never changes its bytes: the version is in the path. */\nexport const SELF_HOSTED_FONT_CACHE_CONTROL =\n 'public, max-age=31536000, s-maxage=31536000, immutable'\n\n/**\n * What this process learned about each stylesheet: the faces, or null for a\n * failure. VALUES, never an in-flight promise — the settled-value cache\n * refuses one. A promise held across requests is awaited by renders that did\n * not create it, and one that never settles stalled every page of every site\n * on the instance until the function timed out (AGL-3565).\n */\nconst stylesheets = createSettledValueCache<string, GoogleFontFace[] | null>()\n\n/** Test seam: the process cache would otherwise leak between cases. */\nexport function resetSelfHostedFontsForTests(): void {\n stylesheets.clear()\n}\n\n/**\n * Google's faces for a stylesheet URL, or null; never waits past `ms`. The\n * deadline is a real timer (`boundedAwait`): an abort signal alone did not\n * bound Next's patched fetch on Vercel, whose promise could never settle.\n */\nfunction fetchFaces(url: string, ms: number): Promise<GoogleFontFace[] | null> {\n return boundedAwait(\n (signal) =>\n fetch(url, {\n headers: { 'User-Agent': WOFF2_USER_AGENT },\n signal,\n next: { revalidate: STYLESHEET_TTL_MS / 1000 },\n } as RequestInit)\n .then(async (response) => {\n if (!response.ok) return null\n const parsed = parseGoogleFontFaces(await response.text())\n return parsed.length ? parsed : null\n })\n .catch(() => null),\n ms,\n null,\n 'self-hosted-fonts.stylesheet',\n )\n}\n\n/**\n * Google's faces for a stylesheet URL, from this process's cache when it has\n * them. Null when the fetch failed, timed out or answered with nothing usable;\n * the page then links the stylesheet as it always did, rather than losing its\n * font. Asked through `fetch` with a day's revalidation, which on the server is\n * Next's data cache: a cold process reads the stored stylesheet rather than\n * asking Google again.\n */\nfunction facesFor(url: string): Promise<GoogleFontFace[] | null> {\n return stylesheets.readThrough(\n url,\n () => fetchFaces(url, STYLESHEET_TIMEOUT_MS),\n (faces) => (faces ? STYLESHEET_TTL_MS : FAILURE_TTL_MS),\n )\n}\n\n/** What a page inlines in its head for its theme's fonts. */\nexport interface SelfHostedThemeFonts {\n /** The `@font-face` rules, every `src` on the site's own origin. */\n css: string\n /** The one or two files the first screen paints with, to preload. */\n preloads: string[]\n}\n\n/**\n * The theme's Google fonts as rules to inline and files to preload, or null\n * when the theme loads none or Google could not be read — in which case the\n * caller links the stylesheet as before.\n */\nexport async function selfHostedThemeFonts(\n theme: Pick<HostTheme, 'fonts' | 'typography'> | undefined,\n): Promise<SelfHostedThemeFonts | null> {\n const url = getGoogleFontsUrl(theme?.fonts)\n if (!url) return null\n const faces = await facesFor(url)\n if (!faces) return null\n return {\n css: selfHostedFontFaceCss(faces),\n preloads: selfHostedFontPreloads(theme, faces),\n }\n}\n\n/**\n * One font file, fetched from Google and answered from the site's origin with\n * a year-long `immutable` policy. `path` is the part below `/s/` on Google's\n * origin (`inter/v18/….woff2`); anything else is a 404, so this route cannot\n * be pointed at any other URL.\n *\n * The edge keeps the answer for the year too (`s-maxage`), so Google is asked\n * once per file per edge region rather than once per visitor.\n */\nexport async function serveSelfHostedFont(path: string): Promise<Response> {\n const notFound = () =>\n new Response('Not found', {\n status: 404,\n headers: { 'Cache-Control': 'public, max-age=300' },\n })\n if (!isSelfHostedFontPath(path)) return notFound()\n let upstream: Response\n try {\n upstream = await fetch(googleFontFileUrl(path), {\n headers: { 'User-Agent': WOFF2_USER_AGENT },\n cache: 'force-cache',\n })\n } catch {\n return new Response('Font unavailable', {\n status: 502,\n headers: { 'Cache-Control': 'no-store' },\n })\n }\n if (upstream.status === 404) return notFound()\n const length = Number(upstream.headers.get('content-length') ?? 0)\n if (!upstream.ok || !upstream.body || length > MAX_FONT_BYTES) {\n return new Response('Font unavailable', {\n status: 502,\n headers: { 'Cache-Control': 'no-store' },\n })\n }\n return new Response(upstream.body, {\n status: 200,\n headers: {\n 'Content-Type': 'font/woff2',\n 'Cache-Control': SELF_HOSTED_FONT_CACHE_CONTROL,\n 'X-Content-Type-Options': 'nosniff',\n // Fonts are fetched in CORS mode; a site reached on two hostnames (its\n // own domain and its platform subdomain) shares one cached answer.\n 'Access-Control-Allow-Origin': '*',\n ...(length ? { 'Content-Length': String(length) } : {}),\n },\n })\n}\n"],"names":["boundedAwait","createSettledValueCache","getGoogleFontsUrl","googleFontFileUrl","isSelfHostedFontPath","parseGoogleFontFaces","selfHostedFontFaceCss","selfHostedFontPreloads","WOFF2_USER_AGENT","STYLESHEET_TTL_MS","FAILURE_TTL_MS","STYLESHEET_TIMEOUT_MS","MAX_FONT_BYTES","SELF_HOSTED_FONT_CACHE_CONTROL","stylesheets","resetSelfHostedFontsForTests","clear","fetchFaces","url","ms","signal","fetch","headers","next","revalidate","then","response","ok","parsed","text","length","catch","facesFor","readThrough","faces","selfHostedThemeFonts","theme","fonts","css","preloads","serveSelfHostedFont","path","upstream","notFound","Response","status","cache","Number","get","body","String"],"mappings":"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"}
|
|
@@ -1,162 +0,0 @@
|
|
|
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 ContactSource, type CrmAssignmentTarget } from '@aglyn/aglyn/server';
|
|
18
|
-
/**
|
|
19
|
-
* WHO A NEW RECORD BELONGS TO — the one place an owner is decided on the
|
|
20
|
-
* server (AGL-2618).
|
|
21
|
-
*
|
|
22
|
-
* Two entry points over one transaction. `assignOwnerForCapture` is the
|
|
23
|
-
* capture door's pass: it runs the org's assignment rules in order, falls
|
|
24
|
-
* back to the capturing site's default owner, and touches only a record
|
|
25
|
-
* that has NO owner — a door that named one (the console's drawer, an
|
|
26
|
-
* import column, a conversion with a picked owner) has expressed a person's
|
|
27
|
-
* choice. `reassignContactOwner` is the automation's: an author who put
|
|
28
|
-
* "assign an owner" on a stage change means to reassign, and the step hands
|
|
29
|
-
* this either a member or the rotation.
|
|
30
|
-
*
|
|
31
|
-
* ## One transaction, because the pointer is shared
|
|
32
|
-
*
|
|
33
|
-
* The round-robin pool's pointer lives on the org document, and two
|
|
34
|
-
* captures landing together must take two different members. Firestore
|
|
35
|
-
* transactions serialize on what they read, so the org document, the
|
|
36
|
-
* contact and the roster documents are all read inside the transaction and
|
|
37
|
-
* the pointer is advanced in the same commit that writes the owner: a
|
|
38
|
-
* concurrent capture that read the same pointer retries and reads the moved
|
|
39
|
-
* one. The alternative — read the pointer, decide, then write — is exactly
|
|
40
|
-
* the read-then-write shape that lets two captures pick the same person.
|
|
41
|
-
*
|
|
42
|
-
* ## The roster is checked, once per member per attempt
|
|
43
|
-
*
|
|
44
|
-
* A rule may name a member who has since left, and a pool may hold one. A
|
|
45
|
-
* rule naming nobody on the roster is passed over rather than stopping the
|
|
46
|
-
* pass — the next rule may well assign — and a pool member who is gone is
|
|
47
|
-
* skipped for the next in the order. `orgs/{orgId}/members/{uid}` is keyed
|
|
48
|
-
* by uid, so the check is one document read per candidate, and only the
|
|
49
|
-
* roster is consulted: a project-level Auth lookup would admit people who
|
|
50
|
-
* are not on this organization at all (AGL-1122).
|
|
51
|
-
*
|
|
52
|
-
* ## The lead follows the contact
|
|
53
|
-
*
|
|
54
|
-
* The capture doors that file a lead (`addHostLead`: a form routed to leads,
|
|
55
|
-
* a sign-up, a booking) key it by `personKey(email)`, so the lead's document
|
|
56
|
-
* is addressable from the capture alone. When it exists it is given the same
|
|
57
|
-
* owner in the same transaction; two doors write the lead AFTER the contact
|
|
58
|
-
* they `void`ed, so for those sources the mirror is retried a few times over
|
|
59
|
-
* the next seconds, detached, and the person's Leads list shows the owner
|
|
60
|
-
* as soon as the lead is there.
|
|
61
|
-
*
|
|
62
|
-
* ## The owner is told, unless they chose themselves
|
|
63
|
-
*
|
|
64
|
-
* One console notification per assignment, for the record the recipient
|
|
65
|
-
* will open: the lead when the site holds one for this person, the contact
|
|
66
|
-
* otherwise. Not when the actor IS the new owner — a rep who converts a
|
|
67
|
-
* lead into their own contact has not been handed anything.
|
|
68
|
-
*
|
|
69
|
-
* ## Never rejects
|
|
70
|
-
*
|
|
71
|
-
* The capture has already succeeded and a form submission must not fail
|
|
72
|
-
* because the CRM could not decide who follows up; a failure is logged and
|
|
73
|
-
* answered as `none`, and the record is exactly as assignable by hand as it
|
|
74
|
-
* was before this existed. The automation executor turns a `none` into the
|
|
75
|
-
* step's recorded error.
|
|
76
|
-
*/
|
|
77
|
-
export interface OwnerAssignmentInput {
|
|
78
|
-
hostId: string;
|
|
79
|
-
/** `orgs/{orgId}/contacts/{contactId}` — the record the owner is written on. */
|
|
80
|
-
contactId: string;
|
|
81
|
-
/** The contact's address, which keys the lead and names the person in the notification. */
|
|
82
|
-
email: string;
|
|
83
|
-
/**
|
|
84
|
-
* The signed-in person making the assignment, when there is one. Never
|
|
85
|
-
* notified about their own choice; absent for a capture and an automation.
|
|
86
|
-
*/
|
|
87
|
-
actorUid?: string | null;
|
|
88
|
-
}
|
|
89
|
-
export interface CaptureAssignmentInput extends OwnerAssignmentInput {
|
|
90
|
-
source: ContactSource;
|
|
91
|
-
/** The form the capture came through, for a rule conditioned on it. */
|
|
92
|
-
formId?: string | null;
|
|
93
|
-
/** The tags the capture carried; the contact's own are read from the facet. */
|
|
94
|
-
tags?: readonly string[];
|
|
95
|
-
}
|
|
96
|
-
export interface ReassignmentInput extends OwnerAssignmentInput {
|
|
97
|
-
assign: CrmAssignmentTarget;
|
|
98
|
-
}
|
|
99
|
-
/** Why an assignment assigned nobody — the automation reports these verbatim. */
|
|
100
|
-
export type OwnerAssignmentRefusal = 'no-org' | 'no-contact' | 'no-rule' | 'empty-pool' | 'not-a-member' | 'failed';
|
|
101
|
-
/** What decided an assignment: a rule, the site default, the step's member, or the rotation. */
|
|
102
|
-
export type OwnerAssignedBy = 'rule' | 'default' | 'member' | 'roundRobin';
|
|
103
|
-
export type OwnerAssignment = {
|
|
104
|
-
outcome: 'assigned';
|
|
105
|
-
ownerUid: string;
|
|
106
|
-
by: OwnerAssignedBy;
|
|
107
|
-
/** The rule that decided it, when one did. */
|
|
108
|
-
ruleId?: string;
|
|
109
|
-
/** The lead document existed and now carries the owner too. */
|
|
110
|
-
leadMirrored: boolean;
|
|
111
|
-
/** A notification was fanned out to the new owner. */
|
|
112
|
-
notified: boolean;
|
|
113
|
-
}
|
|
114
|
-
/** The record already had this owner (a capture), or the same one was named again (a reassignment). */
|
|
115
|
-
| {
|
|
116
|
-
outcome: 'unchanged';
|
|
117
|
-
ownerUid: string;
|
|
118
|
-
} | {
|
|
119
|
-
outcome: 'none';
|
|
120
|
-
reason: OwnerAssignmentRefusal;
|
|
121
|
-
};
|
|
122
|
-
/** The words the run history and the log give each refusal. */
|
|
123
|
-
export declare const OWNER_ASSIGNMENT_REFUSALS: Record<OwnerAssignmentRefusal, string>;
|
|
124
|
-
/** The record an assignment notification opens. */
|
|
125
|
-
export type AssignedRecord = {
|
|
126
|
-
kind: 'contact';
|
|
127
|
-
id: string;
|
|
128
|
-
} | {
|
|
129
|
-
kind: 'lead';
|
|
130
|
-
id: string;
|
|
131
|
-
};
|
|
132
|
-
/**
|
|
133
|
-
* Tells a member a record is now theirs — one console notification, typed
|
|
134
|
-
* by the record it opens — unless the member handed it to themselves.
|
|
135
|
-
* Shared by the pass above and by the routes where a person picks the
|
|
136
|
-
* owner outright (a lead conversion naming a colleague), so every server
|
|
137
|
-
* path that writes `ownerUid` says so in the same words. Never throws;
|
|
138
|
-
* the fan-out swallows its own failures.
|
|
139
|
-
*/
|
|
140
|
-
export declare function notifyRecordAssigned(input: {
|
|
141
|
-
hostId: string;
|
|
142
|
-
orgId: string;
|
|
143
|
-
ownerUid: string;
|
|
144
|
-
actorUid?: string | null;
|
|
145
|
-
record: AssignedRecord;
|
|
146
|
-
/** How the person reads in the message: their name, else their address. */
|
|
147
|
-
who: string;
|
|
148
|
-
}): Promise<boolean>;
|
|
149
|
-
/**
|
|
150
|
-
* The capture door's pass: the org's rules in order, then the capturing
|
|
151
|
-
* site's default owner, on a record that has no owner yet. See the module
|
|
152
|
-
* comment for the whole of it.
|
|
153
|
-
*/
|
|
154
|
-
export declare function assignOwnerForCapture(input: CaptureAssignmentInput): Promise<OwnerAssignment>;
|
|
155
|
-
/**
|
|
156
|
-
* The deliberate assignment — the `assignContactOwner` step, and a person
|
|
157
|
-
* handing a record to somebody: a member by uid (verified on the roster) or
|
|
158
|
-
* the next in the round-robin pool, overwriting whoever held it. Naming the
|
|
159
|
-
* owner the record already has changes nothing and tells nobody.
|
|
160
|
-
*/
|
|
161
|
-
export declare function reassignContactOwner(input: ReassignmentInput): Promise<OwnerAssignment>;
|
|
162
|
-
export default assignOwnerForCapture;
|
|
@@ -1,340 +0,0 @@
|
|
|
1
|
-
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
-
/**
|
|
3
|
-
* @license
|
|
4
|
-
* Copyright 2026 Aglyn LLC
|
|
5
|
-
*
|
|
6
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
-
* you may not use this file except in compliance with the License.
|
|
8
|
-
* You may obtain a copy of the License at
|
|
9
|
-
*
|
|
10
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
-
*
|
|
12
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
-
* See the License for the specific language governing permissions and
|
|
16
|
-
* limitations under the License.
|
|
17
|
-
*/ import { assignmentRuleMatches, consentGroupForHost, contactFacetPath, CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH, personKey, readContactFacet, readCrmAssignmentSettings, roundRobinOrder } from "@aglyn/aglyn/server";
|
|
18
|
-
import { firebaseAdmin, getHostDocAdmin, getOrgForHost, hostDisplayName, notifyUsers, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
|
|
19
|
-
import { FieldValue } from "firebase-admin/firestore";
|
|
20
|
-
/** The words the run history and the log give each refusal. */ export const OWNER_ASSIGNMENT_REFUSALS = {
|
|
21
|
-
'no-org': 'this site has no organization',
|
|
22
|
-
'no-contact': 'the contact no longer exists',
|
|
23
|
-
'no-rule': 'no assignment rule matched and the site has no default owner',
|
|
24
|
-
'empty-pool': 'the round-robin pool has nobody on the roster in it',
|
|
25
|
-
'not-a-member': 'the owner named is not on the team',
|
|
26
|
-
failed: 'the owner could not be assigned'
|
|
27
|
-
};
|
|
28
|
-
/**
|
|
29
|
-
* The doors whose lead lands after the contact they `void`ed — the ones the
|
|
30
|
-
* mirror is worth retrying for. An order, an import, a manual add and an
|
|
31
|
-
* API call file no lead, and a retry for them would be reads for nothing.
|
|
32
|
-
*/ const LEAD_FILING_SOURCES = new Set([
|
|
33
|
-
'form',
|
|
34
|
-
'member',
|
|
35
|
-
'booking'
|
|
36
|
-
]);
|
|
37
|
-
/** How long the detached lead mirror waits between its looks, in order. */ const LEAD_MIRROR_RETRY_MS = [
|
|
38
|
-
1000,
|
|
39
|
-
2000,
|
|
40
|
-
3000
|
|
41
|
-
];
|
|
42
|
-
/**
|
|
43
|
-
* The console path the owner's notification opens, in the `/{hostDocId}/rest`
|
|
44
|
-
* shape every host notification uses — the console rewrites it to
|
|
45
|
-
* `/{orgSlug}/hosts/{subdomain}/rest` when the link is followed, which is
|
|
46
|
-
* why `hostId` and `orgId` travel on the document. The same spelling the
|
|
47
|
-
* CRM's task notification uses; the hub's own route builder lives in the
|
|
48
|
-
* plugin, which this layer cannot import.
|
|
49
|
-
*/ function recordLink(hostId, record) {
|
|
50
|
-
const section = record.kind === 'contact' ? 'contacts' : 'leads';
|
|
51
|
-
return `/${hostId}/crm/${section}/${encodeURIComponent(record.id)}`;
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Tells a member a record is now theirs — one console notification, typed
|
|
55
|
-
* by the record it opens — unless the member handed it to themselves.
|
|
56
|
-
* Shared by the pass above and by the routes where a person picks the
|
|
57
|
-
* owner outright (a lead conversion naming a colleague), so every server
|
|
58
|
-
* path that writes `ownerUid` says so in the same words. Never throws;
|
|
59
|
-
* the fan-out swallows its own failures.
|
|
60
|
-
*/ export async function notifyRecordAssigned(input) {
|
|
61
|
-
var _input_actorUid;
|
|
62
|
-
if (!input.ownerUid || input.ownerUid === ((_input_actorUid = input.actorUid) != null ? _input_actorUid : '')) return false;
|
|
63
|
-
const lead = input.record.kind === 'lead';
|
|
64
|
-
/*
|
|
65
|
-
* THE BODY SAYS WHAT HAPPENED, AND ON WHICH SITE (AGL-3432).
|
|
66
|
-
*
|
|
67
|
-
* It was the bare name, so a member who owns records on several sites read
|
|
68
|
-
* "Ada" in an email body and could not tell what Ada was or where. The
|
|
69
|
-
* site's name is one request-cached read of a document most callers have
|
|
70
|
-
* already paid for, taken only when somebody is actually notified; a read
|
|
71
|
-
* that fails drops the "on {site}" clause rather than the notification.
|
|
72
|
-
*/ let site = '';
|
|
73
|
-
try {
|
|
74
|
-
const host = await getHostDocAdmin(input.hostId);
|
|
75
|
-
if (host) site = ` on ${hostDisplayName(host, input.hostId)}`;
|
|
76
|
-
} catch (unused) {
|
|
77
|
-
// The clause goes, never the notification.
|
|
78
|
-
}
|
|
79
|
-
await notifyUsers([
|
|
80
|
-
input.ownerUid
|
|
81
|
-
], {
|
|
82
|
-
type: lead ? 'content.leadAssigned' : 'content.contactAssigned',
|
|
83
|
-
title: lead ? 'Lead assigned to you' : 'Contact assigned to you',
|
|
84
|
-
body: `${input.who} was assigned to you as a ${lead ? 'lead' : 'contact'}${site}.`,
|
|
85
|
-
link: recordLink(input.hostId, input.record),
|
|
86
|
-
orgId: input.orgId,
|
|
87
|
-
hostId: input.hostId
|
|
88
|
-
});
|
|
89
|
-
return true;
|
|
90
|
-
}
|
|
91
|
-
async function assignOwner(policy) {
|
|
92
|
-
const { input } = policy;
|
|
93
|
-
try {
|
|
94
|
-
const resolved = await getOrgForHost(input.hostId);
|
|
95
|
-
if (!resolved) return {
|
|
96
|
-
outcome: 'none',
|
|
97
|
-
reason: 'no-org'
|
|
98
|
-
};
|
|
99
|
-
const { orgId } = resolved;
|
|
100
|
-
const firestore = firebaseAdmin.app().firestore();
|
|
101
|
-
const orgRef = firestore.collection('orgs').doc(orgId);
|
|
102
|
-
const contactRef = orgRef.collection('contacts').doc(input.contactId);
|
|
103
|
-
const membersRef = orgRef.collection('members');
|
|
104
|
-
const leadKey = personKey(input.email);
|
|
105
|
-
// Beside the contact on the org, keyed by the same address (AGL-3275).
|
|
106
|
-
const leadRef = leadKey ? orgRef.collection('leads').doc(leadKey) : null;
|
|
107
|
-
let contactName = '';
|
|
108
|
-
const verdict = await firestore.runTransaction(async (tx)=>{
|
|
109
|
-
var _orgSnapshot_data, _contactSnapshot_data, _contact_name, _ref;
|
|
110
|
-
/*
|
|
111
|
-
* ALL READS BEFORE THE WRITE, which Firestore requires. The org
|
|
112
|
-
* document is read here rather than trusted from `getOrgForHost`,
|
|
113
|
-
* because the pointer it carries is the one thing a concurrent
|
|
114
|
-
* capture may have moved, and the rules and the pool are read from
|
|
115
|
-
* the same snapshot so the decision and the pointer agree.
|
|
116
|
-
*/ const [orgSnapshot, contactSnapshot, leadSnapshot] = await Promise.all([
|
|
117
|
-
tx.get(orgRef),
|
|
118
|
-
tx.get(contactRef),
|
|
119
|
-
leadRef ? tx.get(leadRef) : Promise.resolve(null)
|
|
120
|
-
]);
|
|
121
|
-
if (!contactSnapshot.exists) {
|
|
122
|
-
return {
|
|
123
|
-
outcome: 'none',
|
|
124
|
-
reason: 'no-contact'
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
const org = (_orgSnapshot_data = orgSnapshot.data()) != null ? _orgSnapshot_data : {};
|
|
128
|
-
const contact = (_contactSnapshot_data = contactSnapshot.data()) != null ? _contactSnapshot_data : {};
|
|
129
|
-
contactName = String((_contact_name = contact['name']) != null ? _contact_name : '');
|
|
130
|
-
const group = consentGroupForHost(org, input.hostId);
|
|
131
|
-
const facet = readContactFacet(contact, group.groupId);
|
|
132
|
-
const current = typeof facet.ownerUid === 'string' ? facet.ownerUid : '';
|
|
133
|
-
if (policy.kind === 'capture' && current) {
|
|
134
|
-
return {
|
|
135
|
-
outcome: 'unchanged',
|
|
136
|
-
ownerUid: current
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
const settings = readCrmAssignmentSettings(org);
|
|
140
|
-
// One read per candidate per attempt; a retried transaction reads
|
|
141
|
-
// afresh, as it must.
|
|
142
|
-
const onRoster = new Map();
|
|
143
|
-
const isMember = (uid)=>{
|
|
144
|
-
let known = onRoster.get(uid);
|
|
145
|
-
if (!known) {
|
|
146
|
-
known = tx.get(membersRef.doc(uid)).then((snapshot)=>snapshot.exists);
|
|
147
|
-
onRoster.set(uid, known);
|
|
148
|
-
}
|
|
149
|
-
return known;
|
|
150
|
-
};
|
|
151
|
-
const fromPool = async ()=>{
|
|
152
|
-
for (const uid of roundRobinOrder(settings.pool.memberUids, settings.pool.lastAssignedUid)){
|
|
153
|
-
if (await isMember(uid)) return uid;
|
|
154
|
-
}
|
|
155
|
-
return null;
|
|
156
|
-
};
|
|
157
|
-
const resolveTarget = async (target)=>{
|
|
158
|
-
if ('roundRobin' in target) {
|
|
159
|
-
const uid = await fromPool();
|
|
160
|
-
return uid ? {
|
|
161
|
-
uid,
|
|
162
|
-
advancePointer: true
|
|
163
|
-
} : null;
|
|
164
|
-
}
|
|
165
|
-
return await isMember(target.memberUid) ? {
|
|
166
|
-
uid: target.memberUid,
|
|
167
|
-
advancePointer: false
|
|
168
|
-
} : null;
|
|
169
|
-
};
|
|
170
|
-
let decision = null;
|
|
171
|
-
let refusal = 'no-rule';
|
|
172
|
-
if (policy.kind === 'capture') {
|
|
173
|
-
var _policy_input_formId, _policy_input_tags, _facet_tags;
|
|
174
|
-
const capture = {
|
|
175
|
-
source: policy.input.source,
|
|
176
|
-
email: input.email,
|
|
177
|
-
formId: (_policy_input_formId = policy.input.formId) != null ? _policy_input_formId : null,
|
|
178
|
-
tags: [
|
|
179
|
-
...(_policy_input_tags = policy.input.tags) != null ? _policy_input_tags : [],
|
|
180
|
-
...(_facet_tags = facet.tags) != null ? _facet_tags : []
|
|
181
|
-
]
|
|
182
|
-
};
|
|
183
|
-
for (const rule of settings.rules){
|
|
184
|
-
if (!assignmentRuleMatches(rule.when, capture)) continue;
|
|
185
|
-
const hit = await resolveTarget(rule.assign);
|
|
186
|
-
if (hit) {
|
|
187
|
-
decision = _extends({}, hit, {
|
|
188
|
-
ownerUid: hit.uid,
|
|
189
|
-
by: 'rule',
|
|
190
|
-
ruleId: rule.id
|
|
191
|
-
});
|
|
192
|
-
break;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
const fallback = settings.hostDefaultOwners[input.hostId];
|
|
196
|
-
if (!decision && fallback && await isMember(fallback)) {
|
|
197
|
-
decision = {
|
|
198
|
-
ownerUid: fallback,
|
|
199
|
-
by: 'default',
|
|
200
|
-
advancePointer: false
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
} else {
|
|
204
|
-
const { assign } = policy.input;
|
|
205
|
-
const hit = await resolveTarget(assign);
|
|
206
|
-
if (hit) {
|
|
207
|
-
decision = _extends({}, hit, {
|
|
208
|
-
ownerUid: hit.uid,
|
|
209
|
-
by: 'roundRobin' in assign ? 'roundRobin' : 'member'
|
|
210
|
-
});
|
|
211
|
-
} else {
|
|
212
|
-
refusal = 'roundRobin' in assign ? 'empty-pool' : 'not-a-member';
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
if (!decision) return {
|
|
216
|
-
outcome: 'none',
|
|
217
|
-
reason: refusal
|
|
218
|
-
};
|
|
219
|
-
if (decision.ownerUid === current) {
|
|
220
|
-
return {
|
|
221
|
-
outcome: 'unchanged',
|
|
222
|
-
ownerUid: current
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
tx.update(contactRef, {
|
|
226
|
-
[contactFacetPath(group.groupId, 'ownerUid')]: decision.ownerUid,
|
|
227
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
228
|
-
});
|
|
229
|
-
if (decision.advancePointer) {
|
|
230
|
-
tx.update(orgRef, {
|
|
231
|
-
[CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH]: decision.ownerUid
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
/*
|
|
235
|
-
* A lead somebody already assigned by hand keeps its owner on a
|
|
236
|
-
* capture — the contact was new, the lead may not have been — and
|
|
237
|
-
* follows the contact on a deliberate reassignment.
|
|
238
|
-
*/ const leadOwner = String((_ref = leadSnapshot == null ? void 0 : leadSnapshot.get('ownerUid')) != null ? _ref : '');
|
|
239
|
-
const leadMirrored = Boolean((leadSnapshot == null ? void 0 : leadSnapshot.exists) && (policy.kind === 'reassign' || !leadOwner));
|
|
240
|
-
if (leadMirrored && leadRef) {
|
|
241
|
-
tx.update(leadRef, {
|
|
242
|
-
ownerUid: decision.ownerUid,
|
|
243
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
return _extends({
|
|
247
|
-
outcome: 'assigned',
|
|
248
|
-
ownerUid: decision.ownerUid,
|
|
249
|
-
by: decision.by
|
|
250
|
-
}, decision.ruleId ? {
|
|
251
|
-
ruleId: decision.ruleId
|
|
252
|
-
} : {}, {
|
|
253
|
-
leadMirrored,
|
|
254
|
-
notified: false
|
|
255
|
-
});
|
|
256
|
-
});
|
|
257
|
-
if (verdict.outcome !== 'assigned') return verdict;
|
|
258
|
-
// The owner is what the Contacts list filters by (AGL-3321).
|
|
259
|
-
await restampCrmListFieldsAt(contactRef, 'contacts');
|
|
260
|
-
if (!verdict.leadMirrored && leadRef && policy.kind === 'capture' && LEAD_FILING_SOURCES.has(policy.input.source)) {
|
|
261
|
-
void mirrorOwnerOntoLeadLater(leadRef, verdict.ownerUid);
|
|
262
|
-
}
|
|
263
|
-
const notified = await notifyRecordAssigned({
|
|
264
|
-
hostId: input.hostId,
|
|
265
|
-
orgId,
|
|
266
|
-
ownerUid: verdict.ownerUid,
|
|
267
|
-
actorUid: input.actorUid,
|
|
268
|
-
record: verdict.leadMirrored && leadKey ? {
|
|
269
|
-
kind: 'lead',
|
|
270
|
-
id: leadKey
|
|
271
|
-
} : {
|
|
272
|
-
kind: 'contact',
|
|
273
|
-
id: input.contactId
|
|
274
|
-
},
|
|
275
|
-
who: contactName || input.email
|
|
276
|
-
});
|
|
277
|
-
return _extends({}, verdict, {
|
|
278
|
-
notified
|
|
279
|
-
});
|
|
280
|
-
} catch (error) {
|
|
281
|
-
console.error('assignContactOwner failed', input.hostId, input.contactId, error);
|
|
282
|
-
return {
|
|
283
|
-
outcome: 'none',
|
|
284
|
-
reason: 'failed'
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
/**
|
|
289
|
-
* The detached second look for a lead that lands after the contact.
|
|
290
|
-
*
|
|
291
|
-
* Bounded, and only ever ADDS an owner: a lead that arrived with one (a
|
|
292
|
-
* person assigned it in the meantime) is left alone, and a lead that never
|
|
293
|
-
* arrives costs three reads over six seconds and nothing else. Detached
|
|
294
|
-
* because the capture must not hold `contactCreated` back for it — an
|
|
295
|
-
* automation welcoming the contact has nothing to do with the lead's owner
|
|
296
|
-
* column.
|
|
297
|
-
*/ async function mirrorOwnerOntoLeadLater(leadRef, ownerUid, delaysMs = LEAD_MIRROR_RETRY_MS) {
|
|
298
|
-
for (const delay of delaysMs){
|
|
299
|
-
await new Promise((resolve)=>setTimeout(resolve, delay));
|
|
300
|
-
try {
|
|
301
|
-
var _lead_get;
|
|
302
|
-
const lead = await leadRef.get();
|
|
303
|
-
if (!lead.exists) continue;
|
|
304
|
-
if (String((_lead_get = lead.get('ownerUid')) != null ? _lead_get : '')) return false;
|
|
305
|
-
await leadRef.update({
|
|
306
|
-
ownerUid,
|
|
307
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
308
|
-
});
|
|
309
|
-
return true;
|
|
310
|
-
} catch (error) {
|
|
311
|
-
console.error('assignContactOwner lead mirror failed', leadRef.path, error);
|
|
312
|
-
return false;
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
return false;
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* The capture door's pass: the org's rules in order, then the capturing
|
|
319
|
-
* site's default owner, on a record that has no owner yet. See the module
|
|
320
|
-
* comment for the whole of it.
|
|
321
|
-
*/ export function assignOwnerForCapture(input) {
|
|
322
|
-
return assignOwner({
|
|
323
|
-
kind: 'capture',
|
|
324
|
-
input
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* The deliberate assignment — the `assignContactOwner` step, and a person
|
|
329
|
-
* handing a record to somebody: a member by uid (verified on the roster) or
|
|
330
|
-
* the next in the round-robin pool, overwriting whoever held it. Naming the
|
|
331
|
-
* owner the record already has changes nothing and tells nobody.
|
|
332
|
-
*/ export function reassignContactOwner(input) {
|
|
333
|
-
return assignOwner({
|
|
334
|
-
kind: 'reassign',
|
|
335
|
-
input
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
export default assignOwnerForCapture;
|
|
339
|
-
|
|
340
|
-
//# sourceMappingURL=assign-contact-owner.js.map
|