fullstackgtm 0.21.2 → 0.23.1
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/CHANGELOG.md +80 -0
- package/README.md +15 -0
- package/dist/bulkUpdate.d.ts +16 -1
- package/dist/bulkUpdate.js +88 -5
- package/dist/cli.js +670 -8
- package/dist/dedupe.d.ts +14 -0
- package/dist/dedupe.js +140 -0
- package/dist/enrich.d.ts +220 -0
- package/dist/enrich.js +724 -0
- package/dist/enrichApollo.d.ts +59 -0
- package/dist/enrichApollo.js +192 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +5 -1
- package/dist/marketReport.js +97 -44
- package/dist/reassign.d.ts +19 -0
- package/dist/reassign.js +87 -0
- package/dist/suggest.js +67 -5
- package/llms.txt +15 -0
- package/package.json +1 -1
- package/src/bulkUpdate.ts +109 -6
- package/src/cli.ts +756 -8
- package/src/dedupe.ts +182 -0
- package/src/enrich.ts +1016 -0
- package/src/enrichApollo.ts +250 -0
- package/src/index.ts +48 -1
- package/src/marketReport.ts +116 -62
- package/src/reassign.ts +117 -0
- package/src/suggest.ts +69 -5
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import type { CanonicalGtmSnapshot } from "./types.ts";
|
|
2
|
+
import type { EnrichObjectType, EnrichSourceRecord, EnrichWorkItem } from "./enrich.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Apollo source client for the enrich layer: raw fetch against Apollo's REST
|
|
6
|
+
* enrichment endpoints (people match, organization enrich), bring-your-own
|
|
7
|
+
* key (`login apollo`), no SDK.
|
|
8
|
+
*
|
|
9
|
+
* The one genuinely new HTTP behavior lives here and ONLY here: enrichment
|
|
10
|
+
* APIs rate-limit aggressively, so requests retry on 429 with capped
|
|
11
|
+
* exponential backoff (honoring Retry-After when present). The shared
|
|
12
|
+
* connector contract is deliberately untouched.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const DEFAULT_API_BASE_URL = "https://api.apollo.io";
|
|
16
|
+
const DEFAULT_MAX_RETRIES = 3;
|
|
17
|
+
const BASE_BACKOFF_MS = 500;
|
|
18
|
+
const MAX_BACKOFF_MS = 8_000;
|
|
19
|
+
|
|
20
|
+
export type ApolloClientOptions = {
|
|
21
|
+
getApiKey: () => string | Promise<string>;
|
|
22
|
+
apiBaseUrl?: string;
|
|
23
|
+
/** Injectable fetch for testing — tests must never hit the real Apollo API. */
|
|
24
|
+
fetchImpl?: typeof fetch;
|
|
25
|
+
/** Max retries after a 429 (default 3). */
|
|
26
|
+
maxRetries?: number;
|
|
27
|
+
/** Injectable sleep for testing backoff without waiting. */
|
|
28
|
+
sleep?: (ms: number) => Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type ApolloClient = {
|
|
32
|
+
/** GET /api/v1/organizations/enrich?domain=… → response body, or null on no data. */
|
|
33
|
+
enrichOrganization(domain: string): Promise<Record<string, unknown> | null>;
|
|
34
|
+
/** POST /api/v1/people/match { email } → response body, or null on no data. */
|
|
35
|
+
matchPerson(email: string): Promise<Record<string, unknown> | null>;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
39
|
+
|
|
40
|
+
function retryDelayMs(response: Response, attempt: number): number {
|
|
41
|
+
const retryAfter = response.headers.get("Retry-After");
|
|
42
|
+
if (retryAfter) {
|
|
43
|
+
const seconds = Number(retryAfter);
|
|
44
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, MAX_BACKOFF_MS);
|
|
45
|
+
const at = Date.parse(retryAfter);
|
|
46
|
+
if (Number.isFinite(at)) return Math.min(Math.max(at - Date.now(), 0), MAX_BACKOFF_MS);
|
|
47
|
+
}
|
|
48
|
+
return Math.min(BASE_BACKOFF_MS * 2 ** attempt, MAX_BACKOFF_MS);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function createApolloClient(options: ApolloClientOptions): ApolloClient {
|
|
52
|
+
const baseUrl = (options.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
|
|
53
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
54
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
55
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
56
|
+
|
|
57
|
+
async function request(path: string, init: RequestInit = {}): Promise<Record<string, unknown> | null> {
|
|
58
|
+
const apiKey = await options.getApiKey();
|
|
59
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
60
|
+
let response: Response;
|
|
61
|
+
try {
|
|
62
|
+
response = await fetchImpl(`${baseUrl}${path}`, {
|
|
63
|
+
...init,
|
|
64
|
+
headers: {
|
|
65
|
+
"X-Api-Key": apiKey,
|
|
66
|
+
"Content-Type": "application/json",
|
|
67
|
+
Accept: "application/json",
|
|
68
|
+
...(init.headers ?? {}),
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
const cause = error instanceof Error && error.cause instanceof Error ? `: ${error.cause.message}` : "";
|
|
73
|
+
throw new Error(`Cannot reach Apollo at ${baseUrl}${cause}. Check network access.`);
|
|
74
|
+
}
|
|
75
|
+
if (response.status === 429 && attempt < maxRetries) {
|
|
76
|
+
await sleep(retryDelayMs(response, attempt));
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (response.status === 404) return null;
|
|
80
|
+
if (!response.ok) {
|
|
81
|
+
const body = await response.text();
|
|
82
|
+
const exhausted = response.status === 429 ? ` (rate limited; ${maxRetries} retries exhausted)` : "";
|
|
83
|
+
throw new Error(`Apollo API error ${response.status}${exhausted}: ${body}`);
|
|
84
|
+
}
|
|
85
|
+
const text = await response.text();
|
|
86
|
+
return text ? (JSON.parse(text) as Record<string, unknown>) : null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
async enrichOrganization(domain) {
|
|
92
|
+
return request(`/api/v1/organizations/enrich?domain=${encodeURIComponent(domain)}`, {
|
|
93
|
+
method: "GET",
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
async matchPerson(email) {
|
|
97
|
+
return request("/api/v1/people/match", {
|
|
98
|
+
method: "POST",
|
|
99
|
+
body: JSON.stringify({ email }),
|
|
100
|
+
});
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
// Pull adapter: snapshot-driven keys in, normalized source records out.
|
|
107
|
+
|
|
108
|
+
export type ApolloPullKey = {
|
|
109
|
+
objectType: EnrichObjectType;
|
|
110
|
+
/** "domain" for companies, "email" for contacts. */
|
|
111
|
+
key: "domain" | "email";
|
|
112
|
+
value: string;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type ApolloPullResult = {
|
|
116
|
+
records: EnrichSourceRecord[];
|
|
117
|
+
/** Pull keys Apollo returned no data for. */
|
|
118
|
+
misses: ApolloPullKey[];
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export type ApolloPullProgress = {
|
|
122
|
+
/** The pull key just processed — the run-store cursor value. */
|
|
123
|
+
lastKeyValue: string;
|
|
124
|
+
record?: EnrichSourceRecord;
|
|
125
|
+
miss?: ApolloPullKey;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export type ApolloPullOptions = {
|
|
129
|
+
/** Resume checkpoint: pull keys at or before this value are skipped. */
|
|
130
|
+
resumeAfter?: string | null;
|
|
131
|
+
/** Checkpoint callback after each pull key is processed. */
|
|
132
|
+
onProgress?: (progress: ApolloPullProgress) => void | Promise<void>;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
function stringAt(payload: Record<string, unknown> | null | undefined, path: string[]): string | undefined {
|
|
136
|
+
let current: unknown = payload;
|
|
137
|
+
for (const segment of path) {
|
|
138
|
+
if (!current || typeof current !== "object") return undefined;
|
|
139
|
+
current = (current as Record<string, unknown>)[segment];
|
|
140
|
+
}
|
|
141
|
+
return typeof current === "string" && current ? current : undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Pull keys for an append run: records of the requested types where at least
|
|
146
|
+
* one configured field is blank and the pull key (companies: domain,
|
|
147
|
+
* contacts: email) is present. Deduplicated — two CRM companies sharing a
|
|
148
|
+
* domain produce ONE Apollo call, and the matcher then reports the collision.
|
|
149
|
+
*/
|
|
150
|
+
export function apolloPullKeysForAppend(
|
|
151
|
+
snapshot: CanonicalGtmSnapshot,
|
|
152
|
+
objectTypes: EnrichObjectType[],
|
|
153
|
+
needsEnrichment: (objectType: EnrichObjectType, record: Record<string, unknown>) => boolean,
|
|
154
|
+
): ApolloPullKey[] {
|
|
155
|
+
const keys: ApolloPullKey[] = [];
|
|
156
|
+
const seen = new Set<string>();
|
|
157
|
+
for (const objectType of objectTypes) {
|
|
158
|
+
const records = objectType === "company" ? snapshot.accounts : snapshot.contacts;
|
|
159
|
+
const keyName = objectType === "company" ? ("domain" as const) : ("email" as const);
|
|
160
|
+
for (const record of records) {
|
|
161
|
+
const value = ((record as unknown as Record<string, unknown>)[keyName] as string | undefined)?.trim();
|
|
162
|
+
if (!value) continue;
|
|
163
|
+
if (!needsEnrichment(objectType, record as unknown as Record<string, unknown>)) continue;
|
|
164
|
+
const dedupe = `${objectType}|${value.toLowerCase()}`;
|
|
165
|
+
if (seen.has(dedupe)) continue;
|
|
166
|
+
seen.add(dedupe);
|
|
167
|
+
keys.push({ objectType, key: keyName, value });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return keys;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Pull keys for a refresh run: the stale work set mapped back to pull keys. */
|
|
174
|
+
export function apolloPullKeysForRefresh(
|
|
175
|
+
snapshot: CanonicalGtmSnapshot,
|
|
176
|
+
workSet: EnrichWorkItem[],
|
|
177
|
+
): ApolloPullKey[] {
|
|
178
|
+
const keys: ApolloPullKey[] = [];
|
|
179
|
+
const seen = new Set<string>();
|
|
180
|
+
for (const item of workSet) {
|
|
181
|
+
const records = item.objectType === "company" ? snapshot.accounts : snapshot.contacts;
|
|
182
|
+
const record = records.find((entry) => entry.id === item.objectId);
|
|
183
|
+
if (!record) continue;
|
|
184
|
+
const keyName = item.objectType === "company" ? ("domain" as const) : ("email" as const);
|
|
185
|
+
const value = ((record as unknown as Record<string, unknown>)[keyName] as string | undefined)?.trim();
|
|
186
|
+
if (!value) continue;
|
|
187
|
+
const dedupe = `${item.objectType}|${value.toLowerCase()}`;
|
|
188
|
+
if (seen.has(dedupe)) continue;
|
|
189
|
+
seen.add(dedupe);
|
|
190
|
+
keys.push({ objectType: item.objectType, key: keyName, value });
|
|
191
|
+
}
|
|
192
|
+
return keys;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Execute the pull: one Apollo call per key, normalized into source records.
|
|
197
|
+
* Sequential on purpose (enrichment endpoints rate-limit aggressively); the
|
|
198
|
+
* 429 backoff lives in the client. `onProgress` checkpoints the run-store
|
|
199
|
+
* cursor after every key so an interrupted pull resumes instead of re-paying
|
|
200
|
+
* for completed lookups.
|
|
201
|
+
*/
|
|
202
|
+
export async function pullApolloRecords(
|
|
203
|
+
client: ApolloClient,
|
|
204
|
+
keys: ApolloPullKey[],
|
|
205
|
+
options: ApolloPullOptions = {},
|
|
206
|
+
): Promise<ApolloPullResult> {
|
|
207
|
+
const records: EnrichSourceRecord[] = [];
|
|
208
|
+
const misses: ApolloPullKey[] = [];
|
|
209
|
+
// Resume: skip keys up to and including the checkpoint. An unknown
|
|
210
|
+
// checkpoint (snapshot changed since the interrupted run) restarts cleanly.
|
|
211
|
+
const resumeIndex = options.resumeAfter
|
|
212
|
+
? keys.findIndex((key) => key.value === options.resumeAfter)
|
|
213
|
+
: -1;
|
|
214
|
+
for (const key of keys.slice(resumeIndex + 1)) {
|
|
215
|
+
let record: EnrichSourceRecord | undefined;
|
|
216
|
+
if (key.objectType === "company") {
|
|
217
|
+
const payload = await client.enrichOrganization(key.value);
|
|
218
|
+
const organization = payload?.organization as Record<string, unknown> | undefined;
|
|
219
|
+
if (organization) {
|
|
220
|
+
record = {
|
|
221
|
+
id: `apollo:org_${stringAt(payload, ["organization", "id"]) ?? key.value}`,
|
|
222
|
+
objectType: "company",
|
|
223
|
+
keys: {
|
|
224
|
+
domain: stringAt(payload, ["organization", "primary_domain"]) ?? key.value,
|
|
225
|
+
name: stringAt(payload, ["organization", "name"]),
|
|
226
|
+
},
|
|
227
|
+
payload: payload as Record<string, unknown>,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
} else {
|
|
231
|
+
const payload = await client.matchPerson(key.value);
|
|
232
|
+
const person = payload?.person as Record<string, unknown> | undefined;
|
|
233
|
+
if (person) {
|
|
234
|
+
record = {
|
|
235
|
+
id: `apollo:person_${stringAt(payload, ["person", "id"]) ?? key.value}`,
|
|
236
|
+
objectType: "contact",
|
|
237
|
+
keys: {
|
|
238
|
+
email: stringAt(payload, ["person", "email"]) ?? key.value,
|
|
239
|
+
name: stringAt(payload, ["person", "name"]),
|
|
240
|
+
},
|
|
241
|
+
payload: payload as Record<string, unknown>,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (record) records.push(record);
|
|
246
|
+
else misses.push(key);
|
|
247
|
+
await options.onProgress?.({ lastKeyValue: key.value, record, miss: record ? undefined : key });
|
|
248
|
+
}
|
|
249
|
+
return { records, misses };
|
|
250
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { auditSnapshot, defaultPolicy } from "./audit.ts";
|
|
2
|
-
export { buildBulkUpdatePlan, parseWhere, type BulkUpdateOptions } from "./bulkUpdate.ts";
|
|
2
|
+
export { buildBulkUpdatePlan, isFilterableField, parseWhere, type BulkUpdateOptions } from "./bulkUpdate.ts";
|
|
3
|
+
export { buildDedupePlan, dedupeKey, type DedupeOptions } from "./dedupe.ts";
|
|
4
|
+
export { buildReassignPlans, type ReassignObjectType, type ReassignOptions } from "./reassign.ts";
|
|
3
5
|
export {
|
|
4
6
|
CONFIG_FILE_NAME,
|
|
5
7
|
loadConfig,
|
|
@@ -50,6 +52,51 @@ export {
|
|
|
50
52
|
type StoredCredential,
|
|
51
53
|
} from "./credentials.ts";
|
|
52
54
|
export { generateDemoSnapshot, type DemoSnapshotOptions } from "./demo.ts";
|
|
55
|
+
export {
|
|
56
|
+
buildEnrichPlan,
|
|
57
|
+
createFileEnrichRunStore,
|
|
58
|
+
DEFAULT_STALE_DAYS,
|
|
59
|
+
ENRICH_CONFIG_FILE_NAME,
|
|
60
|
+
enrichRunId,
|
|
61
|
+
inferIngestObjectType,
|
|
62
|
+
ingestKeyValue,
|
|
63
|
+
latestStamps,
|
|
64
|
+
loadEnrichConfig,
|
|
65
|
+
matchSourceRecord,
|
|
66
|
+
parseCsv,
|
|
67
|
+
parseEnrichConfig,
|
|
68
|
+
resolveCrmField,
|
|
69
|
+
selectStaleWork,
|
|
70
|
+
sourceValueAt,
|
|
71
|
+
stagedSourceRecords,
|
|
72
|
+
staleDaysFor,
|
|
73
|
+
type BuildEnrichPlanOptions,
|
|
74
|
+
type EnrichAmbiguity,
|
|
75
|
+
type EnrichConfig,
|
|
76
|
+
type EnrichCounts,
|
|
77
|
+
type EnrichFieldConfig,
|
|
78
|
+
type EnrichMatchConfig,
|
|
79
|
+
type EnrichMode,
|
|
80
|
+
type EnrichObjectType,
|
|
81
|
+
type EnrichPlanResult,
|
|
82
|
+
type EnrichRun,
|
|
83
|
+
type EnrichRunStore,
|
|
84
|
+
type EnrichSourceConfig,
|
|
85
|
+
type EnrichSourceRecord,
|
|
86
|
+
type EnrichStamp,
|
|
87
|
+
type EnrichWorkItem,
|
|
88
|
+
type MatchOutcome,
|
|
89
|
+
} from "./enrich.ts";
|
|
90
|
+
export {
|
|
91
|
+
apolloPullKeysForAppend,
|
|
92
|
+
apolloPullKeysForRefresh,
|
|
93
|
+
createApolloClient,
|
|
94
|
+
pullApolloRecords,
|
|
95
|
+
type ApolloClient,
|
|
96
|
+
type ApolloClientOptions,
|
|
97
|
+
type ApolloPullKey,
|
|
98
|
+
type ApolloPullResult,
|
|
99
|
+
} from "./enrichApollo.ts";
|
|
53
100
|
export {
|
|
54
101
|
diffFindings,
|
|
55
102
|
diffSnapshots,
|
package/src/marketReport.ts
CHANGED
|
@@ -438,57 +438,119 @@ export function marketMapToHtml(config: MarketConfig, set: ObservationSet): stri
|
|
|
438
438
|
const e = escapeHtml;
|
|
439
439
|
const axisHtml = axisSectionsHtml(config, set);
|
|
440
440
|
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
)
|
|
458
|
-
|
|
441
|
+
const vendorNamesById = new Map(config.vendors.map((vendor) => [vendor.id, vendor.name]));
|
|
442
|
+
const frontByClaim = new Map(model.fronts.map((front) => [front.claimId, front]));
|
|
443
|
+
|
|
444
|
+
const matrixRow = (claimId: string): string => {
|
|
445
|
+
const claim = claimsById.get(claimId);
|
|
446
|
+
if (!claim) return "";
|
|
447
|
+
const state = stateByClaim.get(claimId) ?? "vacant";
|
|
448
|
+
const cells = config.vendors
|
|
449
|
+
.map((vendor) => {
|
|
450
|
+
const intensity = model.cell(vendor.id, claimId)?.intensity ?? "unobservable";
|
|
451
|
+
const anchorClass = vendor.id === anchor ? " anchor-col" : "";
|
|
452
|
+
return `<td class="cell${anchorClass}"><span class="g g-${intensity}" title="${e(vendor.name)}: ${intensity}"></span></td>`;
|
|
453
|
+
})
|
|
454
|
+
.join("");
|
|
455
|
+
return (
|
|
456
|
+
`<tr class="front-${state}"><th scope="row"><span class="claim-cap">${e(claim.capability.split(":")[0])}</span>` +
|
|
457
|
+
`<span class="claim-meta">${e(claim.icp)} · ${e(claim.pricingStructure)}</span></th>${cells}` +
|
|
458
|
+
`<td class="front"><span class="chip chip-${state}">${state.toUpperCase()}</span></td></tr>`
|
|
459
|
+
);
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
const vendorHeads = config.vendors
|
|
463
|
+
.map(
|
|
464
|
+
(vendor) =>
|
|
465
|
+
`<th class="vh${vendor.id === anchor ? " anchor-col" : ""}"><span>${e(vendor.name)}</span></th>`,
|
|
466
|
+
)
|
|
459
467
|
.join("");
|
|
460
468
|
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
}
|
|
469
|
+
// Claims grouped by front state, each group a collapsed <details> whose
|
|
470
|
+
// summary carries the stats a skimmer needs; the full matrix is one click
|
|
471
|
+
// away, not a wall the reader must climb to reach the takeaway.
|
|
472
|
+
const GROUPS: Array<{ states: FrontState[]; title: string; blurb: string }> = [
|
|
473
|
+
{ states: ["open", "vacant"], title: "Open ground", blurb: "no vendor is loud here" },
|
|
474
|
+
{ states: ["contested"], title: "Contested fronts", blurb: "2–3 vendors loud" },
|
|
475
|
+
{ states: ["owned"], title: "Owned fronts", blurb: "exactly one vendor loud" },
|
|
476
|
+
{ states: ["saturated"], title: "Saturated fronts", blurb: "4+ vendors loud" },
|
|
477
|
+
];
|
|
478
|
+
const groupedMatrix = GROUPS.map((group) => {
|
|
479
|
+
const claimIds = model.orderedClaimIds.filter((claimId) => group.states.includes(stateByClaim.get(claimId) ?? "vacant"));
|
|
480
|
+
if (claimIds.length === 0) return "";
|
|
481
|
+
const anchorLoud = anchor
|
|
482
|
+
? claimIds.filter((claimId) => model.cell(anchor, claimId)?.intensity === "loud").length
|
|
483
|
+
: 0;
|
|
484
|
+
const anchorNote = anchor ? ` · ${vendorNamesById.get(anchor) ?? anchor} loud on ${anchorLoud}` : "";
|
|
485
|
+
return `<details class="claim-group"><summary><b>${e(group.title)}</b> — ${claimIds.length} claim${claimIds.length === 1 ? "" : "s"} <span class="sum-soft">(${e(group.blurb)}${anchorNote})</span></summary>
|
|
486
|
+
<table><thead><tr><th></th>${vendorHeads}<th></th></tr></thead><tbody>${claimIds.map(matrixRow).join("")}</tbody></table>
|
|
487
|
+
</details>`;
|
|
488
|
+
}).join("");
|
|
489
|
+
|
|
490
|
+
// The closing argument: walk from open ground to a reasoned target list.
|
|
491
|
+
const openFronts = model.orderedClaimIds.filter((claimId) => {
|
|
492
|
+
const state = stateByClaim.get(claimId);
|
|
493
|
+
return state === "open" || state === "vacant";
|
|
494
|
+
});
|
|
495
|
+
const targetItems = openFronts
|
|
466
496
|
.map((claimId) => {
|
|
467
497
|
const claim = claimsById.get(claimId);
|
|
468
|
-
|
|
498
|
+
const front = frontByClaim.get(claimId);
|
|
499
|
+
if (!claim || !front) return "";
|
|
500
|
+
const quietNames = front.quietVendorIds.map((id) => vendorNamesById.get(id) ?? id);
|
|
501
|
+
const anchorIntensity = anchor ? model.cell(anchor, claimId)?.intensity ?? "unobservable" : null;
|
|
502
|
+
const nearest =
|
|
503
|
+
quietNames.length > 0
|
|
504
|
+
? `Closest contenders (quiet): ${quietNames.join(", ")}.`
|
|
505
|
+
: "Nobody even ships it quietly — vacant ground.";
|
|
506
|
+
const move =
|
|
507
|
+
anchorIntensity === "quiet"
|
|
508
|
+
? `${e(vendorNamesById.get(anchor as string) ?? "The anchor")} already ships this quietly — a promote-to-loud candidate.`
|
|
509
|
+
: anchorIntensity === "absent"
|
|
510
|
+
? "Unclaimed by the anchor: a first-mover messaging opportunity if the capability is real or buildable."
|
|
511
|
+
: "";
|
|
512
|
+
return `<li><b>${e(claim.capability.split(":")[0])}</b> <span class="sum-soft">(${e(claim.icp)} · ${e(claim.pricingStructure)})</span><br>
|
|
513
|
+
No vendor is loud on this claim. ${e(nearest)} ${move}</li>`;
|
|
469
514
|
})
|
|
470
515
|
.join("");
|
|
516
|
+
const heldFronts = anchor
|
|
517
|
+
? model.fronts.filter((front) => front.state === "owned" && front.loudVendorIds[0] === anchor)
|
|
518
|
+
: [];
|
|
519
|
+
const heldLine =
|
|
520
|
+
heldFronts.length > 0
|
|
521
|
+
? `<p><b>Held ground:</b> ${e(vendorNamesById.get(anchor as string) ?? "the anchor")} is the sole loud vendor on ${heldFronts
|
|
522
|
+
.map((front) => `<i>${e(claimsById.get(front.claimId)?.capability.split(":")[0] ?? front.claimId)}</i>`)
|
|
523
|
+
.join(", ")} — positions to defend, not abandon.</p>`
|
|
524
|
+
: "";
|
|
525
|
+
const crowdLine =
|
|
526
|
+
counts.saturated > 0
|
|
527
|
+
? `<p><b>Crowded ground:</b> ${counts.saturated} claim${counts.saturated === 1 ? " is" : "s are"} saturated (4+ vendors loud) — message budget spent there buys the least differentiation.</p>`
|
|
528
|
+
: "";
|
|
529
|
+
const takeaway = `<section>
|
|
530
|
+
<h2>Where to attack</h2>
|
|
531
|
+
<p class="lede">${openFronts.length === 0 ? "No open fronts this run — every claim has at least one loud vendor. Watch the drift between runs for windows opening." : `${openFronts.length} claim${openFronts.length === 1 ? "" : "s"} in this category ${openFronts.length === 1 ? "is" : "are"} open: buyers can be reached there without out-shouting anyone.`}</p>
|
|
532
|
+
<ul class="targets">${targetItems}</ul>
|
|
533
|
+
${heldLine}
|
|
534
|
+
${crowdLine}
|
|
535
|
+
<p class="sum-soft">These are messaging fronts, not verdicts — join the map to CRM ground truth (\`market overlay\`) for evidence-backed OCCUPY / PROMOTE / URGENT / RETREAT directives with win-rate stats.</p>
|
|
536
|
+
</section>`;
|
|
471
537
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
538
|
+
// Evidence grouped by vendor, collapsed: receipts on demand, not a scroll wall.
|
|
539
|
+
const appendixGroups = config.vendors
|
|
540
|
+
.map((vendor) => {
|
|
541
|
+
const items = model.orderedClaimIds.flatMap((claimId) => {
|
|
475
542
|
const obs = model.cell(vendor.id, claimId);
|
|
476
543
|
if (!obs || obs.evidence.length === 0) return [];
|
|
477
544
|
return obs.evidence.map(
|
|
478
545
|
(evidence) =>
|
|
479
|
-
`<div class="ev"><span class="ev-head">${e(
|
|
546
|
+
`<div class="ev"><span class="ev-head">${e(claimId)} · ${obs.intensity.toUpperCase()} (${obs.confidence})</span>` +
|
|
480
547
|
`<blockquote>“${e(evidence.text)}”</blockquote>` +
|
|
481
548
|
`<span class="ev-src">${e(String(evidence.metadata?.url ?? ""))} · capture ${e(String(evidence.metadata?.captureHash ?? "").slice(0, 12))}</span></div>`,
|
|
482
549
|
);
|
|
483
|
-
})
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
const vendorHeads = config.vendors
|
|
488
|
-
.map(
|
|
489
|
-
(vendor) =>
|
|
490
|
-
`<th class="vh${vendor.id === anchor ? " anchor-col" : ""}"><span>${e(vendor.name)}</span></th>`,
|
|
491
|
-
)
|
|
550
|
+
});
|
|
551
|
+
if (items.length === 0) return "";
|
|
552
|
+
return `<details class="ev-group"><summary><b>${e(vendor.name)}</b> <span class="sum-soft">— ${items.length} quoted span${items.length === 1 ? "" : "s"}</span></summary>${items.join("")}</details>`;
|
|
553
|
+
})
|
|
492
554
|
.join("");
|
|
493
555
|
|
|
494
556
|
return `<!doctype html>
|
|
@@ -506,14 +568,16 @@ h1 { font-size:27px; font-weight:600; line-height:1.2; }
|
|
|
506
568
|
.meta { font-size:11px; color:var(--soft); display:flex; gap:18px; flex-wrap:wrap; margin-top:8px; }
|
|
507
569
|
section { margin-top:44px; }
|
|
508
570
|
h2 { font-size:17px; font-weight:600; border-bottom:1px solid var(--line); padding-bottom:7px; margin-bottom:4px; }
|
|
509
|
-
.
|
|
510
|
-
.
|
|
511
|
-
.
|
|
512
|
-
.
|
|
513
|
-
.
|
|
514
|
-
.
|
|
515
|
-
.
|
|
516
|
-
.
|
|
571
|
+
details.claim-group, details.ev-group { border:1px solid var(--line); border-radius:3px; margin-top:10px; }
|
|
572
|
+
details.claim-group summary, details.ev-group summary { cursor:pointer; padding:10px 14px; font-size:14px; list-style-position:inside; }
|
|
573
|
+
details.claim-group summary:hover, details.ev-group summary:hover { background:var(--faint); }
|
|
574
|
+
details.claim-group[open] summary, details.ev-group[open] summary { border-bottom:1px solid var(--line); }
|
|
575
|
+
details.claim-group table { margin:4px 12px 12px; width:calc(100% - 24px); }
|
|
576
|
+
details.ev-group .ev { margin:0 14px; }
|
|
577
|
+
.sum-soft { color:var(--soft); font-size:12px; }
|
|
578
|
+
.lede { font-size:16px; margin-top:12px; }
|
|
579
|
+
.targets { margin-top:12px; font-size:14.5px; line-height:1.6; }
|
|
580
|
+
.targets li { margin:10px 0 10px 20px; }
|
|
517
581
|
.key { display:flex; gap:20px; flex-wrap:wrap; margin:14px 0 8px; font-size:10.5px; color:var(--soft); }
|
|
518
582
|
.lg { display:inline-flex; align-items:center; gap:6px; }
|
|
519
583
|
table { border-collapse:collapse; width:100%; margin-top:6px; }
|
|
@@ -574,34 +638,24 @@ footer { margin-top:60px; border-top:1px solid var(--ink); padding-top:12px; fon
|
|
|
574
638
|
<span>extractor: ${e(set.extractor)}</span>
|
|
575
639
|
</div>
|
|
576
640
|
</header>
|
|
641
|
+
${axisHtml.strategicMap}
|
|
577
642
|
<section>
|
|
578
|
-
<h2>
|
|
579
|
-
<div class="fronts">
|
|
580
|
-
<div class="fcard open"><b>${counts.open + counts.vacant}</b><span>Open / vacant</span></div>
|
|
581
|
-
<div class="fcard"><b>${counts.contested}</b><span>Contested</span></div>
|
|
582
|
-
<div class="fcard"><b>${counts.owned}</b><span>Owned</span></div>
|
|
583
|
-
<div class="fcard"><b>${counts.saturated}</b><span>Saturated</span></div>
|
|
584
|
-
</div>
|
|
585
|
-
<ul class="openlist">${openList}</ul>
|
|
586
|
-
</section>
|
|
587
|
-
<section>
|
|
588
|
-
<h2>Claim × vendor intensity matrix</h2>
|
|
643
|
+
<h2>Market Claims</h2>
|
|
589
644
|
<div class="key">
|
|
590
645
|
<span class="lg"><i class="g g-loud"></i>LOUD — hero-level claim</span>
|
|
591
646
|
<span class="lg"><i class="g g-quiet"></i>QUIET — shipped, buried</span>
|
|
592
647
|
<span class="lg"><i class="g g-absent"></i>ABSENT</span>
|
|
593
648
|
<span class="lg"><i class="g g-unobservable"></i>UNOBSERVABLE — capture failed</span>
|
|
594
649
|
</div>
|
|
595
|
-
|
|
596
|
-
<thead><tr><th></th>${vendorHeads}<th></th></tr></thead>
|
|
597
|
-
<tbody>${matrixRows}</tbody>
|
|
598
|
-
</table>
|
|
650
|
+
${groupedMatrix}
|
|
599
651
|
</section>
|
|
600
|
-
${
|
|
652
|
+
${takeaway}
|
|
601
653
|
<section>
|
|
602
654
|
<h2>Evidence appendix</h2>
|
|
603
|
-
|
|
655
|
+
<p class="sum-soft">Every loud/quiet reading is grounded in a verbatim span from a stored page capture; expand a vendor for its receipts.</p>
|
|
656
|
+
${appendixGroups}
|
|
604
657
|
</section>
|
|
658
|
+
<script>window.addEventListener("beforeprint",function(){document.querySelectorAll("details").forEach(function(d){d.open=true;});});</script>
|
|
605
659
|
<footer>
|
|
606
660
|
<span>Generated by fullstackgtm market · deterministic render of ${e(set.runLabel)}</span>
|
|
607
661
|
<span>Front rule v1: 0 loud=open · 1=owned · 2–3=contested · ≥4=saturated</span>
|
package/src/reassign.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ownership-handoff playbook: `reassign` compiles one bulk-update-style
|
|
3
|
+
* dry-run plan PER object type (accounts, contacts, deals by default) that
|
|
4
|
+
* moves every record owned by --from to --to. It NEVER writes — each plan
|
|
5
|
+
* flows through the same plans-approve → apply gate, and because every plan
|
|
6
|
+
* carries its full filter, eligibility (extra --where scoping AND the
|
|
7
|
+
* --except-deal-stage exclusion) is re-verified per record against a FRESH
|
|
8
|
+
* snapshot at apply time, with mid-apply rechecks. A record that drifts into
|
|
9
|
+
* the exception set mid-run surfaces as a conflict, not a bad write.
|
|
10
|
+
*
|
|
11
|
+
* --except-deal-stage <stage> excludes in-flight business end to end:
|
|
12
|
+
* - deal plans drop deals in that stage (stage!=<stage>), and
|
|
13
|
+
* - ALL plans drop records whose account has an OPEN deal in that stage
|
|
14
|
+
* (accounts: openDealStages!~<stage>; deals/contacts:
|
|
15
|
+
* account.openDealStages!~<stage>).
|
|
16
|
+
*
|
|
17
|
+
* Deal plans cover OPEN deals only unless includeClosedDeals is set: closed
|
|
18
|
+
* deals keep their historical owner in a handoff.
|
|
19
|
+
*
|
|
20
|
+
* Extra --where clauses are account-scoped where needed: a clause on a field
|
|
21
|
+
* that only exists on accounts (e.g. domain~.de) is lifted to the relational
|
|
22
|
+
* pseudo-field (account.domain~.de) for contact and deal plans, so one
|
|
23
|
+
* invocation scopes all three object types consistently.
|
|
24
|
+
*/
|
|
25
|
+
import { buildBulkUpdatePlan, isFilterableField, parseWhere } from "./bulkUpdate.ts";
|
|
26
|
+
import type { CanonicalGtmSnapshot, PatchPlan } from "./types.ts";
|
|
27
|
+
|
|
28
|
+
export type ReassignObjectType = "account" | "contact" | "deal";
|
|
29
|
+
|
|
30
|
+
export type ReassignOptions = {
|
|
31
|
+
/** the owner whose records are being handed off */
|
|
32
|
+
fromOwnerId: string;
|
|
33
|
+
/** the receiving owner — must be a known user in the snapshot */
|
|
34
|
+
toOwnerId: string;
|
|
35
|
+
/** which object types to compile plans for (default all three) */
|
|
36
|
+
objects?: ReassignObjectType[];
|
|
37
|
+
/** extra --where scoping, AND-ed into every plan (account fields lifted) */
|
|
38
|
+
where?: string[];
|
|
39
|
+
/** exclude records tied to an open deal in this stage (see module doc) */
|
|
40
|
+
exceptDealStage?: string;
|
|
41
|
+
/** also reassign closed deals (default false: history keeps its owner) */
|
|
42
|
+
includeClosedDeals?: boolean;
|
|
43
|
+
reason?: string;
|
|
44
|
+
maxOperations?: number;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const ALL_OBJECTS: ReassignObjectType[] = ["account", "contact", "deal"];
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Scope an extra --where clause to one object type: pass through when the
|
|
51
|
+
* field is valid there, lift account-only fields to account.<field> for
|
|
52
|
+
* contacts and deals. Unknown fields fall through to buildBulkUpdatePlan's
|
|
53
|
+
* strict validation, which throws with the valid-field list.
|
|
54
|
+
*/
|
|
55
|
+
function scopeWhere(objectType: ReassignObjectType, raw: string): string {
|
|
56
|
+
const clause = parseWhere(raw);
|
|
57
|
+
if (isFilterableField(objectType, clause.field)) return raw;
|
|
58
|
+
if (objectType !== "account" && isFilterableField(objectType, `account.${clause.field}`)) {
|
|
59
|
+
return `account.${raw}`;
|
|
60
|
+
}
|
|
61
|
+
return raw;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function buildReassignPlans(
|
|
65
|
+
snapshot: CanonicalGtmSnapshot,
|
|
66
|
+
options: ReassignOptions,
|
|
67
|
+
): PatchPlan[] {
|
|
68
|
+
if (!options.fromOwnerId || !options.toOwnerId) {
|
|
69
|
+
throw new Error("reassign requires both --from <ownerId> and --to <ownerId>.");
|
|
70
|
+
}
|
|
71
|
+
if (options.fromOwnerId === options.toOwnerId) {
|
|
72
|
+
throw new Error("reassign --from and --to are the same owner — nothing to hand off.");
|
|
73
|
+
}
|
|
74
|
+
// The receiving owner must exist: a typo'd --to would otherwise write an
|
|
75
|
+
// invalid owner onto every matched record.
|
|
76
|
+
if (!snapshot.users.some((user) => user.id === options.toOwnerId)) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`reassign --to ${options.toOwnerId} is not a known user in the snapshot. Known users: ${snapshot.users
|
|
79
|
+
.map((user) => `${user.id} (${user.name})`)
|
|
80
|
+
.join(", ") || "none"}.`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const objects = options.objects ?? ALL_OBJECTS;
|
|
84
|
+
for (const objectType of objects) {
|
|
85
|
+
if (!ALL_OBJECTS.includes(objectType)) {
|
|
86
|
+
throw new Error(`reassign --objects supports account, contact, deal — got "${objectType}".`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return objects.map((objectType) => {
|
|
91
|
+
const where = [`ownerId=${options.fromOwnerId}`];
|
|
92
|
+
if (objectType === "deal" && !options.includeClosedDeals) {
|
|
93
|
+
where.push("isClosed=false"); // closed deals keep their historical owner
|
|
94
|
+
}
|
|
95
|
+
for (const extra of options.where ?? []) {
|
|
96
|
+
where.push(scopeWhere(objectType, extra));
|
|
97
|
+
}
|
|
98
|
+
if (options.exceptDealStage) {
|
|
99
|
+
const stage = options.exceptDealStage;
|
|
100
|
+
if (objectType === "deal") where.push(`stage!=${stage}`);
|
|
101
|
+
where.push(
|
|
102
|
+
objectType === "account"
|
|
103
|
+
? `openDealStages!~${stage}`
|
|
104
|
+
: `account.openDealStages!~${stage}`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return buildBulkUpdatePlan(snapshot, {
|
|
108
|
+
objectType,
|
|
109
|
+
where,
|
|
110
|
+
set: { ownerId: options.toOwnerId },
|
|
111
|
+
reason:
|
|
112
|
+
options.reason ??
|
|
113
|
+
`reassign: hand off ${objectType}s from owner ${options.fromOwnerId} to ${options.toOwnerId}`,
|
|
114
|
+
maxOperations: options.maxOperations,
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|