@wirecat/cli-core 0.674.0 → 0.676.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/CHANGELOG.md +101 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/list-query.d.ts +3 -2
- package/dist/cli/list-query.js +5 -2
- package/dist/cli/messenger/search-command.js +3 -1
- package/dist/cli/option-hints.d.ts +2 -0
- package/dist/cli/option-hints.js +4 -2
- package/dist/cli/setup-command.js +9 -3
- package/dist/crm/cli/index.d.ts +7 -1
- package/dist/crm/cli/index.js +104 -20
- package/dist/crm/cli/pipeline-view.js +15 -1
- package/dist/crm/cli/records.js +11 -3
- package/dist/crm/cli/search-all.d.ts +5 -2
- package/dist/crm/cli/search-all.js +15 -3
- package/dist/crm/source.d.ts +3 -2
- package/dist/crm/stage-tasks.js +1 -1
- package/dist/crm/sync.js +13 -11
- package/dist/crm/testing/write-contract.js +5 -1
- package/dist/crm/viewer.d.ts +28 -0
- package/dist/crm/viewer.js +63 -0
- package/dist/crm/writer.d.ts +3 -0
- package/dist/crm/writes.d.ts +7 -2
- package/dist/crm/writes.js +24 -14
- package/dist/domain/crm.d.ts +9 -9
- package/dist/domain/moment.d.ts +2 -0
- package/dist/domain/moment.js +2 -0
- package/dist/entities/business-context.js +1 -1
- package/dist/entities/deal.d.ts +86 -39
- package/dist/entities/deal.js +45 -4
- package/dist/entities/index.d.ts +20 -32
- package/dist/errors/reasons.js +1 -0
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/services/search-all.d.ts +3 -1
- package/dist/services/search-all.js +1 -0
- package/dist/setup/define.d.ts +17 -2
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/sqlite/copy-viewer.d.ts +16 -0
- package/dist/store/sqlite/copy-viewer.js +11 -0
- package/dist/store/sqlite/crm-activities.d.ts +7 -1
- package/dist/store/sqlite/crm-activities.js +32 -5
- package/dist/store/sqlite/crm-contacts.d.ts +5 -2
- package/dist/store/sqlite/crm-contacts.js +30 -14
- package/dist/store/sqlite/crm-rows.d.ts +7 -0
- package/dist/store/sqlite/crm-rows.js +37 -5
- package/dist/store/sqlite/crm-settings.d.ts +2 -1
- package/dist/store/sqlite/crm-settings.js +3 -2
- package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
- package/dist/store/sqlite/crm-stage-entries.js +77 -18
- package/dist/store/sqlite/crm.d.ts +14 -4
- package/dist/store/sqlite/crm.js +59 -7
- package/dist/store/sqlite/deals.d.ts +47 -29
- package/dist/store/sqlite/deals.js +64 -76
- package/dist/store/sqlite/pipeline-period.d.ts +85 -0
- package/dist/store/sqlite/pipeline-period.js +199 -0
- package/dist/store/sqlite/stage-amounts.d.ts +6 -2
- package/dist/store/sqlite/stage-amounts.js +8 -5
- package/dist/store/sqlite/vectors.js +5 -3
- package/package.json +3 -3
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { timezoneOf } from "@wirecat/cli-base/query";
|
|
2
3
|
import { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, dealLine, STAGE_OUTCOMES, } from "../../domain/deals.js";
|
|
4
|
+
import { dayIn } from "../../domain/moment.js";
|
|
3
5
|
import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
|
|
4
6
|
import { notOverriddenSql } from "../../domain/relations.js";
|
|
5
7
|
import { correctWords } from "../../search/correct.js";
|
|
@@ -7,14 +9,16 @@ import { createStemmer, DEFAULT_STEMMERS } from "../../search/stem.js";
|
|
|
7
9
|
import { fold } from "../normalize.js";
|
|
8
10
|
import { proposedBySql } from "./actors.js";
|
|
9
11
|
import { suggestBaseStages } from "./base-suggest.js";
|
|
12
|
+
import { seenBy, viewerSql } from "./copy-viewer.js";
|
|
10
13
|
import { activityTexts } from "./crm-activities.js";
|
|
11
14
|
import { crmAccountPrefix } from "./crm-rows.js";
|
|
15
|
+
import { stageEntriesOf } from "./crm-stage-entries.js";
|
|
12
16
|
import { linkKind } from "./link-kinds.js";
|
|
13
17
|
import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf } from "./memories.js";
|
|
14
18
|
import { requiredThing } from "./notes.js";
|
|
19
|
+
import { bounded, boundOf, openPerStage, pipelinePeriod, } from "./pipeline-period.js";
|
|
15
20
|
import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
|
|
16
21
|
import { pageOfRows } from "./rows-page.js";
|
|
17
|
-
import { stageAmountsOf } from "./stage-amounts.js";
|
|
18
22
|
import { write } from "./transaction.js";
|
|
19
23
|
const TABLES = { deal: "deals", lead: "leads" };
|
|
20
24
|
const itemsSql = (kind) => "SELECT d.*, s.name AS stage_name, s.pipeline_id, p.name AS pipeline_name, b.name AS author_name, " +
|
|
@@ -183,14 +187,9 @@ export const dealOperationsOver = (context) => {
|
|
|
183
187
|
return refuse(`more than one pipeline is named ${named}: ${rows.map(label).join(", ")}; name one by its reference`, "pipeline.ambiguous");
|
|
184
188
|
return rows[0];
|
|
185
189
|
};
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
`FROM pipeline_stages s WHERE s.pipeline_id IN (${pipelineIds.map(() => "?").join(", ") || "NULL"}) ` +
|
|
190
|
-
"ORDER BY s.pipeline_id, s.position, s.id")
|
|
191
|
-
.all(...pipelineIds);
|
|
192
|
-
const pipelinesOf = (rows) => {
|
|
193
|
-
const stages = stagesOf(rows.map((row) => Number(row.id)));
|
|
190
|
+
const pipelinesOf = (rows, viewer) => {
|
|
191
|
+
const ids = rows.map((row) => Number(row.id));
|
|
192
|
+
const stages = openPerStage(database, ids, viewer);
|
|
194
193
|
return rows.map((row) => ({
|
|
195
194
|
id: String(row.id),
|
|
196
195
|
ref: `pipeline:${row.id}`,
|
|
@@ -235,57 +234,20 @@ export const dealOperationsOver = (context) => {
|
|
|
235
234
|
.get(Number(pipelines[0]?.id));
|
|
236
235
|
return row ?? refuse("the pipeline has no stages", "deal.stage");
|
|
237
236
|
};
|
|
238
|
-
const funnelOf = (pipeline,
|
|
239
|
-
const
|
|
240
|
-
const
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
const
|
|
246
|
-
.prepare("SELECT id, position, outcome FROM pipeline_stages WHERE pipeline_id = ? ORDER BY position, id")
|
|
247
|
-
.all(Number(pipeline.id));
|
|
248
|
-
const order = new Map(stages.map((stage, at) => [Number(stage.id), at]));
|
|
249
|
-
const standing = stageAmountsOf(context, kind, stages.map((stage) => Number(stage.id)), cutoff);
|
|
250
|
-
const lostStage = new Set(stages.filter((stage) => stage.outcome === "lost").map((stage) => Number(stage.id)));
|
|
251
|
-
const entered = new Map();
|
|
252
|
-
for (const change of database
|
|
253
|
-
.prepare("SELECT item_id, to_stage_id FROM pipeline_stage_changes WHERE item_type = ? AND pipeline_id = ?")
|
|
254
|
-
.all(kind, Number(pipeline.id))) {
|
|
255
|
-
const list = entered.get(Number(change.item_id)) ?? [];
|
|
256
|
-
list.push(Number(change.to_stage_id));
|
|
257
|
-
entered.set(Number(change.item_id), list);
|
|
258
|
-
}
|
|
259
|
-
const furthest = items.map((item) => {
|
|
260
|
-
if (item.status === "won")
|
|
261
|
-
return Number.POSITIVE_INFINITY;
|
|
262
|
-
const reached = [...(entered.get(Number(item.id)) ?? []), Number(item.stage_id)]
|
|
263
|
-
.filter((stage) => !lostStage.has(stage))
|
|
264
|
-
.map((stage) => order.get(stage) ?? -1);
|
|
265
|
-
return Math.max(-1, ...reached);
|
|
266
|
-
});
|
|
267
|
-
const lost = items.filter((item) => item.status === "lost").length;
|
|
268
|
-
const reachedAt = (at) => lostStage.has(Number(stages[at]?.id)) ? lost : furthest.filter((far) => far >= at).length;
|
|
269
|
-
const funnel = pipeline.stages.map((stage, at) => {
|
|
270
|
-
const reached = reachedAt(at);
|
|
271
|
-
const next = stages.findIndex((one, after) => after > at && !lostStage.has(Number(one.id)));
|
|
272
|
-
const conversion = lostStage.has(Number(stages[at]?.id)) || next === -1 || reached === 0
|
|
273
|
-
? null
|
|
274
|
-
: Math.round((reachedAt(next) / reached) * 1000) / 1000;
|
|
275
|
-
return { ...stage, reached, conversion, ...standing[at] };
|
|
276
|
-
});
|
|
277
|
-
const won = items.filter((item) => item.status === "won").length;
|
|
237
|
+
const funnelOf = (pipeline, options) => {
|
|
238
|
+
const { since, until, zone = timezoneOf(), viewer } = options;
|
|
239
|
+
const window = {
|
|
240
|
+
since: boundOf(since, "the first day counted", zone),
|
|
241
|
+
until: boundOf(until, "the last day counted", zone, true),
|
|
242
|
+
};
|
|
243
|
+
const { stages, ...period } = pipelinePeriod(context, pipeline, window, zone, viewer);
|
|
244
|
+
const at = (bound) => (bound === null ? null : new Date(bound).toISOString());
|
|
278
245
|
return {
|
|
279
246
|
...pipeline,
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
won,
|
|
285
|
-
lost,
|
|
286
|
-
winRate: won + lost === 0 ? null : Math.round((won / (won + lost)) * 1000) / 1000,
|
|
287
|
-
},
|
|
288
|
-
since,
|
|
247
|
+
...period,
|
|
248
|
+
stages: pipeline.stages.map((stage, index) => ({ ...stage, ...stages[index] })),
|
|
249
|
+
window: { since: at(window.since), until: at(window.until) },
|
|
250
|
+
since: at(window.since)?.slice(0, 10) ?? null,
|
|
289
251
|
};
|
|
290
252
|
};
|
|
291
253
|
/** Sets the stage and, from its outcome, the status; a stage that ends the row closes it today. */
|
|
@@ -336,11 +298,11 @@ export const dealOperationsOver = (context) => {
|
|
|
336
298
|
});
|
|
337
299
|
return pipelinesOf(pipelineRows(pipelineKind, undefined, { deleted: true }).filter((row) => Number(row.id) === id))[0];
|
|
338
300
|
},
|
|
339
|
-
pipelines: (
|
|
301
|
+
pipelines: ({ kind, account, viewer } = {}) => pipelinesOf(pipelineRows(kind === undefined ? undefined : kindOf(kind), account), viewer),
|
|
340
302
|
pipeline: (reference, options = {}) => {
|
|
341
303
|
const kind = options.kind === undefined ? undefined : kindOf(options.kind);
|
|
342
|
-
const
|
|
343
|
-
return funnelOf(
|
|
304
|
+
const [found] = pipelinesOf([pipelineRow(reference, kind, options.account)], options.viewer);
|
|
305
|
+
return funnelOf(found, options);
|
|
344
306
|
},
|
|
345
307
|
add: (input) => {
|
|
346
308
|
const kind = kindOf(input.kind);
|
|
@@ -399,17 +361,22 @@ export const dealOperationsOver = (context) => {
|
|
|
399
361
|
get: (reference) => read(reference),
|
|
400
362
|
stages: (reference) => {
|
|
401
363
|
const { kind, row } = rowOf(reference);
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
.
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
364
|
+
const own = stageEntriesOf(database, kind, { item: Number(row.id) });
|
|
365
|
+
const stages = new Map(database
|
|
366
|
+
.prepare(`SELECT id, name, pipeline_id FROM pipeline_stages WHERE id IN (${own.map(() => "?").join(", ") || "NULL"})`)
|
|
367
|
+
.all(...own.map(({ toStageId }) => toStageId))
|
|
368
|
+
.map((stage) => [Number(stage.id), stage]));
|
|
369
|
+
return own.map((entry, at) => {
|
|
370
|
+
const stage = stages.get(entry.toStageId);
|
|
371
|
+
const before = at === 0 ? undefined : stages.get(own[at - 1].toStageId);
|
|
372
|
+
return {
|
|
373
|
+
from: before === undefined ? null : String(before.name),
|
|
374
|
+
to: String(stage.name),
|
|
375
|
+
pipeline: `pipeline:${stage.pipeline_id}`,
|
|
376
|
+
at: iso(entry.at),
|
|
377
|
+
exact: entry.exact,
|
|
378
|
+
};
|
|
379
|
+
});
|
|
413
380
|
},
|
|
414
381
|
list: (filter = {}) => {
|
|
415
382
|
const kind = kindOf(filter.kind);
|
|
@@ -429,18 +396,37 @@ export const dealOperationsOver = (context) => {
|
|
|
429
396
|
? ""
|
|
430
397
|
: `AND (d.account_id IS NULL OR a.provider || ':' || a.external_id IN (${keys.map(() => "?").join(", ") || "NULL"})) `;
|
|
431
398
|
const offset = Math.max(0, Math.trunc(filter.offset ?? 0));
|
|
399
|
+
const zone = filter.zone ?? timezoneOf();
|
|
400
|
+
const days = {
|
|
401
|
+
since: filter.closed?.since === undefined ? undefined : dayIn(filter.closed.since, zone),
|
|
402
|
+
until: filter.closed?.until === undefined ? undefined : dayIn(filter.closed.until, zone),
|
|
403
|
+
};
|
|
404
|
+
const within = [
|
|
405
|
+
...(filter.viewer ? [viewerSql("d", filter.viewer)] : []),
|
|
406
|
+
...bounded("d.updated_at", filter.updated),
|
|
407
|
+
...bounded("d.closed_date", filter.closed && days),
|
|
408
|
+
...bounded("d.created_at", filter.created),
|
|
409
|
+
...(filter.owner === undefined
|
|
410
|
+
? []
|
|
411
|
+
: [
|
|
412
|
+
filter.owner === null
|
|
413
|
+
? { sql: "json_extract(d.metadata, '$.assignee') IS NULL", params: [] }
|
|
414
|
+
: { sql: "json_extract(d.metadata, '$.assignee') = ?", params: [filter.owner] },
|
|
415
|
+
]),
|
|
416
|
+
];
|
|
432
417
|
const rows = database
|
|
433
|
-
.prepare(`${itemsSql(kind)} WHERE d.deleted_at IS NULL
|
|
418
|
+
.prepare(`${itemsSql(kind)} WHERE d.deleted_at IS NULL ${within.map(({ sql }) => `AND ${sql} `).join("")}` +
|
|
419
|
+
"AND (? IS NULL OR d.status = ?) " +
|
|
434
420
|
"AND (? IS NULL OR d.project_id = ?) AND (? IS NULL OR s.name_folded = ?) AND (? IS NULL OR p.id = ?) " +
|
|
435
421
|
"AND (? IS NULL OR d.organization_id = ?) AND (? = 0 OR d.account_id IS NULL) " +
|
|
436
422
|
`AND (? IS NULL OR (a.provider = ? AND a.external_id = ?)) ${inAccounts}AND ${by.sql} ` +
|
|
437
423
|
"ORDER BY d.created_at DESC, d.id DESC LIMIT ? OFFSET ?")
|
|
438
|
-
.all(status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit + 1, offset)
|
|
424
|
+
.all(...within.flatMap(({ params }) => params), status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit + 1, offset)
|
|
439
425
|
.map(itemOf(kind));
|
|
440
426
|
return pageOfRows(rows, limit, offset);
|
|
441
427
|
},
|
|
442
428
|
find: async (wanted) => {
|
|
443
|
-
const { words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit, offset = 0 } = wanted;
|
|
429
|
+
const { words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit, offset = 0, viewers = [] } = wanted;
|
|
444
430
|
const seen = new Set();
|
|
445
431
|
const clauses = words
|
|
446
432
|
.map((word) => tokensOf(word).filter((token) => fold(token)))
|
|
@@ -502,11 +488,13 @@ export const dealOperationsOver = (context) => {
|
|
|
502
488
|
return database
|
|
503
489
|
.prepare(`SELECT d.id, d.account_id, d.external_id, d.title, d.updated_at, a.provider, a.external_id AS account, o.name AS company, ` +
|
|
504
490
|
"CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.company_name') END AS own_company, " +
|
|
505
|
-
"CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.contact_name') END AS own_contact " +
|
|
491
|
+
"CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.contact_name') END AS own_contact, " +
|
|
492
|
+
"CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.assignee') END AS assignee " +
|
|
506
493
|
`FROM ${TABLES[kind]} d LEFT JOIN accounts a ON a.id = d.account_id ` +
|
|
507
494
|
"LEFT JOIN organizations o ON o.id = d.organization_id WHERE d.deleted_at IS NULL")
|
|
508
495
|
.all()
|
|
509
496
|
.filter((row) => within === undefined || within.includes(`${row.provider}\u0000${row.account}`))
|
|
497
|
+
.filter((row) => viewers.every((viewer) => seenBy(viewer, row)))
|
|
510
498
|
.map((row) => ({
|
|
511
499
|
kind,
|
|
512
500
|
row,
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { DealKind } from "../../domain/deals.js";
|
|
2
|
+
import type { CacheDatabase } from "../driver.js";
|
|
3
|
+
import { type CopyViewer } from "./copy-viewer.js";
|
|
4
|
+
import type { StoreContext } from "./open.js";
|
|
5
|
+
import { type StageAmount, type StageAmounts } from "./stage-amounts.js";
|
|
6
|
+
/** A column between the bounds, each inclusive; no bound, no condition. */
|
|
7
|
+
export declare const bounded: (column: string, bounds: {
|
|
8
|
+
since?: number | string;
|
|
9
|
+
until?: number | string;
|
|
10
|
+
} | undefined) => {
|
|
11
|
+
sql: string;
|
|
12
|
+
params: (number | string)[];
|
|
13
|
+
}[];
|
|
14
|
+
/** A window's bound, a `YYYY-MM-DD` day in `zone` (its start, or its end for `end`) or an ISO time, as epoch ms. */
|
|
15
|
+
export declare const boundOf: (value: string | undefined, what: string, zone: string, end?: boolean) => number | null;
|
|
16
|
+
/** A stage the CRM removed stays in a pipeline only while a row stands in it (BUG-7). */
|
|
17
|
+
export declare const SHOWN_STAGE: string;
|
|
18
|
+
/** Each stage of these pipelines that is shown, with how many open deals and leads the viewer may read stand in it. */
|
|
19
|
+
export declare const openPerStage: (database: CacheDatabase, pipelineIds: number[], viewer?: CopyViewer) => Record<string, unknown>[];
|
|
20
|
+
/** Epoch ms bounds, both inclusive; `null` is open. */
|
|
21
|
+
export interface PeriodWindow {
|
|
22
|
+
since: number | null;
|
|
23
|
+
until: number | null;
|
|
24
|
+
}
|
|
25
|
+
export interface FunnelCounts extends StageAmounts {
|
|
26
|
+
/** Rows of the cohort that got this far: entered this stage or a later one that is not lost, or were won. */
|
|
27
|
+
reached: number;
|
|
28
|
+
/** `reached` of the next stage that is not lost over this stage's, 0–1; `null` for the last or an empty one. */
|
|
29
|
+
conversion: number | null;
|
|
30
|
+
/** The median days a cohort row stayed in the stage before it entered another; `null` when none left it. */
|
|
31
|
+
medianDays: number | null;
|
|
32
|
+
}
|
|
33
|
+
export interface PipelinePeriod {
|
|
34
|
+
stages: FunnelCounts[];
|
|
35
|
+
/** The cohort: rows made in the window. */
|
|
36
|
+
totals: {
|
|
37
|
+
items: number;
|
|
38
|
+
open: number;
|
|
39
|
+
won: number;
|
|
40
|
+
lost: number;
|
|
41
|
+
winRate: number | null;
|
|
42
|
+
};
|
|
43
|
+
/** Rows closed on a day in the window, in the owner's zone. */
|
|
44
|
+
closed: {
|
|
45
|
+
won: number;
|
|
46
|
+
lost: number;
|
|
47
|
+
winRate: number | null;
|
|
48
|
+
wonAmounts: StageAmount[];
|
|
49
|
+
};
|
|
50
|
+
/** Days from made to won, for rows won in the window: the CRM's entry into the won stage, else the closed day. */
|
|
51
|
+
cycle: {
|
|
52
|
+
medianDays: number | null;
|
|
53
|
+
items: number;
|
|
54
|
+
};
|
|
55
|
+
/** The cohort by its CRM assignee. */
|
|
56
|
+
owners: {
|
|
57
|
+
assignee: string | null;
|
|
58
|
+
name: string | null;
|
|
59
|
+
open: number;
|
|
60
|
+
won: number;
|
|
61
|
+
lost: number;
|
|
62
|
+
winRate: number | null;
|
|
63
|
+
}[];
|
|
64
|
+
/** Why rows closed lost in the window were lost, the most common first. */
|
|
65
|
+
lostReasons: {
|
|
66
|
+
reason: string;
|
|
67
|
+
items: number;
|
|
68
|
+
}[];
|
|
69
|
+
/** Rows whose stages came from the CRM's own history, and from the copy's diffs between syncs. */
|
|
70
|
+
history: {
|
|
71
|
+
exact: number;
|
|
72
|
+
copy: number;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* One pipeline's funnel and outcomes over a window: the funnel counts the cohort made in it, `closed`, `cycle` and
|
|
77
|
+
* `lostReasons` the rows closed in it. Each row's stages come from the CRM's history where it has one, else the copy's.
|
|
78
|
+
*/
|
|
79
|
+
export declare const pipelinePeriod: (context: StoreContext, pipeline: {
|
|
80
|
+
id: string;
|
|
81
|
+
kind: DealKind;
|
|
82
|
+
account: {
|
|
83
|
+
provider: string;
|
|
84
|
+
} | null;
|
|
85
|
+
}, window: PeriodWindow, zone: string, viewer?: CopyViewer) => PipelinePeriod;
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { zonedMoment } from "@wirecat/cli-base/query";
|
|
2
|
+
import { dayIn } from "../../domain/moment.js";
|
|
3
|
+
import { formatDecimal, scaleOf } from "../../domain/money.js";
|
|
4
|
+
import { viewerSql } from "./copy-viewer.js";
|
|
5
|
+
import { stageEntriesOf } from "./crm-stage-entries.js";
|
|
6
|
+
import { refuse } from "./reviewed.js";
|
|
7
|
+
import { stageAmountsOf } from "./stage-amounts.js";
|
|
8
|
+
const TABLES = { deal: "deals", lead: "leads" };
|
|
9
|
+
const DAY = 86_400_000;
|
|
10
|
+
const LOST_REASONS = 10;
|
|
11
|
+
/** A column between the bounds, each inclusive; no bound, no condition. */
|
|
12
|
+
export const bounded = (column, bounds) => [
|
|
13
|
+
...(bounds?.since === undefined ? [] : [{ sql: `${column} >= ?`, params: [bounds.since] }]),
|
|
14
|
+
...(bounds?.until === undefined ? [] : [{ sql: `${column} <= ?`, params: [bounds.until] }]),
|
|
15
|
+
];
|
|
16
|
+
/** A window's bound, a `YYYY-MM-DD` day in `zone` (its start, or its end for `end`) or an ISO time, as epoch ms. */
|
|
17
|
+
export const boundOf = (value, what, zone, end = false) => {
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return null;
|
|
20
|
+
const typed = value.trim();
|
|
21
|
+
try {
|
|
22
|
+
return zonedMoment(typed, zone, { start: 0, end: typed.length }, { end });
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return refuse(`${what} is a YYYY-MM-DD day or an ISO time, not ${value}`, "deal.field");
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/** A stage the CRM removed stays in a pipeline only while a row stands in it (BUG-7). */
|
|
29
|
+
export const SHOWN_STAGE = "(s.deleted_at IS NULL OR EXISTS (SELECT 1 FROM deals d WHERE d.stage_id = s.id AND d.deleted_at IS NULL) " +
|
|
30
|
+
"OR EXISTS (SELECT 1 FROM leads l WHERE l.stage_id = s.id AND l.deleted_at IS NULL))";
|
|
31
|
+
/** Each stage of these pipelines that is shown, with how many open deals and leads the viewer may read stand in it. */
|
|
32
|
+
export const openPerStage = (database, pipelineIds, viewer) => {
|
|
33
|
+
const deals = viewerSql("d", viewer);
|
|
34
|
+
const leads = viewerSql("l", viewer);
|
|
35
|
+
return database
|
|
36
|
+
.prepare(`SELECT s.*, (SELECT count(*) FROM deals d WHERE d.stage_id = s.id AND d.status = 'open' AND d.deleted_at IS NULL AND ${deals.sql}) + ` +
|
|
37
|
+
`(SELECT count(*) FROM leads l WHERE l.stage_id = s.id AND l.status = 'open' AND l.deleted_at IS NULL AND ${leads.sql}) AS open ` +
|
|
38
|
+
`FROM pipeline_stages s WHERE s.pipeline_id IN (${pipelineIds.map(() => "?").join(", ") || "NULL"}) ` +
|
|
39
|
+
`AND ${SHOWN_STAGE} ORDER BY s.pipeline_id, s.position, s.id`)
|
|
40
|
+
.all(...deals.params, ...leads.params, ...pipelineIds);
|
|
41
|
+
};
|
|
42
|
+
const share = (part, whole) => (whole === 0 ? null : Math.round((part / whole) * 1000) / 1000);
|
|
43
|
+
const median = (values) => {
|
|
44
|
+
if (values.length === 0)
|
|
45
|
+
return null;
|
|
46
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
47
|
+
const middle = Math.floor(sorted.length / 2);
|
|
48
|
+
const value = sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
49
|
+
return Math.round((value / DAY) * 10) / 10;
|
|
50
|
+
};
|
|
51
|
+
const rate = (won, lost) => share(won, won + lost);
|
|
52
|
+
const itemsOf = (database, kind, pipelineId, viewer) => {
|
|
53
|
+
const seen = viewerSql("d", viewer);
|
|
54
|
+
return database
|
|
55
|
+
.prepare("SELECT d.id, d.status, d.stage_id, d.created_at, d.closed_date, d.currency, d.amount, " +
|
|
56
|
+
"json_extract(d.metadata, '$.assignee') AS assignee, json_extract(d.metadata, '$.closed_reason') AS reason " +
|
|
57
|
+
`FROM ${TABLES[kind]} d JOIN pipeline_stages s ON s.id = d.stage_id WHERE s.pipeline_id = ? AND d.deleted_at IS NULL AND ${seen.sql}`)
|
|
58
|
+
.all(pipelineId, ...seen.params)
|
|
59
|
+
.map((row) => ({
|
|
60
|
+
id: Number(row.id),
|
|
61
|
+
status: String(row.status),
|
|
62
|
+
stageId: Number(row.stage_id),
|
|
63
|
+
createdAt: Number(row.created_at),
|
|
64
|
+
closedDate: row.closed_date == null ? null : String(row.closed_date),
|
|
65
|
+
assignee: row.assignee == null ? null : String(row.assignee),
|
|
66
|
+
reason: row.reason == null ? null : String(row.reason),
|
|
67
|
+
currency: row.currency == null ? null : String(row.currency),
|
|
68
|
+
amount: row.amount ?? null,
|
|
69
|
+
}));
|
|
70
|
+
};
|
|
71
|
+
/** The CRM user's name as its identity holds it; its ids are `<account>/user/<id>`. */
|
|
72
|
+
const userName = (database, provider, assignee) => {
|
|
73
|
+
if (provider === null || assignee === null)
|
|
74
|
+
return null;
|
|
75
|
+
const row = database
|
|
76
|
+
.prepare("SELECT coalesce(p.name, i.name) AS name FROM identities i LEFT JOIN identity_links l ON l.identity_id = i.id " +
|
|
77
|
+
"LEFT JOIN persons p ON p.id = l.person_id WHERE i.provider = ? AND i.external_id = ?")
|
|
78
|
+
.get(provider, assignee);
|
|
79
|
+
return row?.name == null ? null : String(row.name);
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* One pipeline's funnel and outcomes over a window: the funnel counts the cohort made in it, `closed`, `cycle` and
|
|
83
|
+
* `lostReasons` the rows closed in it. Each row's stages come from the CRM's history where it has one, else the copy's.
|
|
84
|
+
*/
|
|
85
|
+
export const pipelinePeriod = (context, pipeline, window, zone, viewer) => {
|
|
86
|
+
const { database } = context;
|
|
87
|
+
const { kind } = pipeline;
|
|
88
|
+
const pipelineId = Number(pipeline.id);
|
|
89
|
+
const made = (at) => (window.since === null || at >= window.since) && (window.until === null || at <= window.until);
|
|
90
|
+
const days = {
|
|
91
|
+
since: window.since === null ? null : dayIn(window.since, zone),
|
|
92
|
+
until: window.until === null ? null : dayIn(window.until, zone),
|
|
93
|
+
};
|
|
94
|
+
const closedIn = (day) => day !== null && (days.since === null || day >= days.since) && (days.until === null || day <= days.until);
|
|
95
|
+
const all = itemsOf(database, kind, pipelineId, viewer);
|
|
96
|
+
const cohort = all.filter((item) => made(item.createdAt));
|
|
97
|
+
const stages = database
|
|
98
|
+
.prepare(`SELECT s.id, s.position, s.outcome FROM pipeline_stages s WHERE s.pipeline_id = ? AND ${SHOWN_STAGE} ` +
|
|
99
|
+
"ORDER BY s.position, s.id")
|
|
100
|
+
.all(pipelineId)
|
|
101
|
+
.map((row) => ({ id: Number(row.id), outcome: row.outcome }));
|
|
102
|
+
const order = new Map(stages.map((stage, at) => [stage.id, at]));
|
|
103
|
+
const lostStage = new Set(stages.filter((stage) => stage.outcome === "lost").map(({ id }) => id));
|
|
104
|
+
const wonStage = new Set(stages.filter((stage) => stage.outcome === "won").map(({ id }) => id));
|
|
105
|
+
const entries = new Map();
|
|
106
|
+
for (const entry of stageEntriesOf(database, kind, { pipeline: pipelineId })) {
|
|
107
|
+
const own = entries.get(entry.itemId) ?? [];
|
|
108
|
+
own.push(entry);
|
|
109
|
+
entries.set(entry.itemId, own);
|
|
110
|
+
}
|
|
111
|
+
const furthest = cohort.map((item) => {
|
|
112
|
+
if (item.status === "won")
|
|
113
|
+
return Number.POSITIVE_INFINITY;
|
|
114
|
+
const reached = [...(entries.get(item.id) ?? []).map(({ toStageId }) => toStageId), item.stageId]
|
|
115
|
+
.filter((stage) => !lostStage.has(stage))
|
|
116
|
+
.map((stage) => order.get(stage) ?? -1);
|
|
117
|
+
// A row first seen closed has no entries: it got at least as far as the first stage.
|
|
118
|
+
return reached.reduce((far, at) => Math.max(far, at), 0);
|
|
119
|
+
});
|
|
120
|
+
const lost = cohort.filter((item) => item.status === "lost").length;
|
|
121
|
+
const won = cohort.filter((item) => item.status === "won").length;
|
|
122
|
+
const reachedAt = (at) => lostStage.has(stages[at]?.id) ? lost : furthest.filter((far) => far >= at).length;
|
|
123
|
+
const stays = new Map();
|
|
124
|
+
for (const item of cohort) {
|
|
125
|
+
const own = entries.get(item.id) ?? [];
|
|
126
|
+
own.slice(0, -1).forEach((entry, at) => {
|
|
127
|
+
const next = own[at + 1];
|
|
128
|
+
const days = stays.get(entry.toStageId) ?? [];
|
|
129
|
+
days.push(next.at - entry.at);
|
|
130
|
+
stays.set(entry.toStageId, days);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
const standing = stageAmountsOf(context, kind, stages.map(({ id }) => id), window, viewer);
|
|
134
|
+
const funnel = stages.map((stage, at) => {
|
|
135
|
+
const reached = reachedAt(at);
|
|
136
|
+
const next = stages.findIndex((one, after) => after > at && !lostStage.has(one.id));
|
|
137
|
+
const conversion = lostStage.has(stage.id) || next === -1 ? null : share(reachedAt(next), reached);
|
|
138
|
+
return { reached, conversion, medianDays: median(stays.get(stage.id) ?? []), ...standing[at] };
|
|
139
|
+
});
|
|
140
|
+
const closedWon = all.filter((item) => item.status === "won" && closedIn(item.closedDate));
|
|
141
|
+
const closedLost = all.filter((item) => item.status === "lost" && closedIn(item.closedDate));
|
|
142
|
+
const sums = new Map();
|
|
143
|
+
for (const item of closedWon)
|
|
144
|
+
if (item.currency !== null) {
|
|
145
|
+
const held = sums.get(item.currency) ?? { units: 0n, items: 0 };
|
|
146
|
+
sums.set(item.currency, { units: held.units + BigInt(item.amount ?? 0), items: held.items + 1 });
|
|
147
|
+
}
|
|
148
|
+
const wonAt = (item) => (entries.get(item.id) ?? []).filter((entry) => entry.exact && wonStage.has(entry.toStageId)).at(-1)?.at ??
|
|
149
|
+
(item.closedDate === null ? null : Date.parse(`${item.closedDate}T00:00:00Z`));
|
|
150
|
+
const cycles = closedWon.flatMap((item) => {
|
|
151
|
+
const at = wonAt(item);
|
|
152
|
+
return at === null ? [] : [Math.max(0, at - item.createdAt)];
|
|
153
|
+
});
|
|
154
|
+
const owners = new Map();
|
|
155
|
+
for (const item of cohort) {
|
|
156
|
+
const own = owners.get(item.assignee) ?? [];
|
|
157
|
+
own.push(item);
|
|
158
|
+
owners.set(item.assignee, own);
|
|
159
|
+
}
|
|
160
|
+
const reasons = new Map();
|
|
161
|
+
for (const item of closedLost)
|
|
162
|
+
if (item.reason)
|
|
163
|
+
reasons.set(item.reason, (reasons.get(item.reason) ?? 0) + 1);
|
|
164
|
+
const exact = cohort.filter((item) => entries.get(item.id)?.[0]?.exact === true).length;
|
|
165
|
+
return {
|
|
166
|
+
stages: funnel,
|
|
167
|
+
totals: { items: cohort.length, open: cohort.length - won - lost, won, lost, winRate: rate(won, lost) },
|
|
168
|
+
closed: {
|
|
169
|
+
won: closedWon.length,
|
|
170
|
+
lost: closedLost.length,
|
|
171
|
+
winRate: rate(closedWon.length, closedLost.length),
|
|
172
|
+
wonAmounts: [...sums]
|
|
173
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
174
|
+
.map(([currency, { units, items }]) => ({
|
|
175
|
+
amount: formatDecimal(units, scaleOf(currency)),
|
|
176
|
+
currency,
|
|
177
|
+
items,
|
|
178
|
+
})),
|
|
179
|
+
},
|
|
180
|
+
cycle: { medianDays: median(cycles), items: cycles.length },
|
|
181
|
+
owners: [...owners].map(([assignee, items]) => {
|
|
182
|
+
const ownWon = items.filter((item) => item.status === "won").length;
|
|
183
|
+
const ownLost = items.filter((item) => item.status === "lost").length;
|
|
184
|
+
return {
|
|
185
|
+
assignee,
|
|
186
|
+
name: userName(database, pipeline.account?.provider ?? null, assignee),
|
|
187
|
+
open: items.length - ownWon - ownLost,
|
|
188
|
+
won: ownWon,
|
|
189
|
+
lost: ownLost,
|
|
190
|
+
winRate: rate(ownWon, ownLost),
|
|
191
|
+
};
|
|
192
|
+
}),
|
|
193
|
+
lostReasons: [...reasons]
|
|
194
|
+
.sort(([a, x], [b, y]) => y - x || a.localeCompare(b))
|
|
195
|
+
.slice(0, LOST_REASONS)
|
|
196
|
+
.map(([reason, items]) => ({ reason, items })),
|
|
197
|
+
history: { exact, copy: cohort.length - exact },
|
|
198
|
+
};
|
|
199
|
+
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { DealKind } from "../../domain/deals.js";
|
|
2
2
|
import { type Money } from "../../domain/money.js";
|
|
3
|
+
import { type CopyViewer } from "./copy-viewer.js";
|
|
3
4
|
import type { StoreContext } from "./open.js";
|
|
4
5
|
export interface StageAmount extends Money {
|
|
5
6
|
items: number;
|
|
@@ -10,5 +11,8 @@ export interface StageAmounts {
|
|
|
10
11
|
/** One per currency, never converted; an item with no amount adds none. */
|
|
11
12
|
amounts: StageAmount[];
|
|
12
13
|
}
|
|
13
|
-
/** What stands in each stage of `stageIds`, in that order
|
|
14
|
-
export declare const stageAmountsOf: ({ database }: StoreContext, kind: DealKind, stageIds: number[],
|
|
14
|
+
/** What stands in each stage of `stageIds`, in that order, of the rows made in the window (epoch ms, inclusive). */
|
|
15
|
+
export declare const stageAmountsOf: ({ database }: StoreContext, kind: DealKind, stageIds: number[], { since, until }: {
|
|
16
|
+
since: number | null;
|
|
17
|
+
until: number | null;
|
|
18
|
+
}, viewer?: CopyViewer) => StageAmounts[];
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { formatDecimal, scaleOf } from "../../domain/money.js";
|
|
2
|
+
import { viewerSql } from "./copy-viewer.js";
|
|
2
3
|
const TABLES = { deal: "deals", lead: "leads" };
|
|
3
|
-
/** What stands in each stage of `stageIds`, in that order
|
|
4
|
-
export const stageAmountsOf = ({ database }, kind, stageIds,
|
|
4
|
+
/** What stands in each stage of `stageIds`, in that order, of the rows made in the window (epoch ms, inclusive). */
|
|
5
|
+
export const stageAmountsOf = ({ database }, kind, stageIds, { since, until }, viewer) => {
|
|
6
|
+
const seen = viewerSql("d", viewer);
|
|
5
7
|
const rows = database
|
|
6
8
|
.prepare("SELECT stage_id, currency, count(*) AS items, coalesce(sum(amount), 0) AS units " +
|
|
7
|
-
`FROM ${TABLES[kind]} WHERE stage_id IN (${stageIds.map(() => "?").join(", ") || "NULL"}) ` +
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
`FROM ${TABLES[kind]} d WHERE stage_id IN (${stageIds.map(() => "?").join(", ") || "NULL"}) ` +
|
|
10
|
+
`AND deleted_at IS NULL AND (? IS NULL OR created_at >= ?) AND (? IS NULL OR created_at <= ?) AND ${seen.sql} ` +
|
|
11
|
+
"GROUP BY stage_id, currency ORDER BY currency")
|
|
12
|
+
.all(...stageIds, since, since, until, until, ...seen.params);
|
|
10
13
|
return stageIds.map((stage) => {
|
|
11
14
|
const within = rows.filter((row) => Number(row.stage_id) === stage);
|
|
12
15
|
return {
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { chunkHash, chunkTextOf } from "../../conversations/chunks.js";
|
|
2
2
|
import { sql } from "./drizzle/core.js";
|
|
3
3
|
import { ensureVectorIndex, searchIndex, unitVector } from "./vector-index.js";
|
|
4
|
+
/** No planner statistics in the store: without CROSS JOIN SQLite reads every chunk of the store, of every chat. */
|
|
4
5
|
const currentChunks = (chatKey) => sql `SELECT k.content_hash, k.chunkable_id AS conversation_id, r.first_message_id,
|
|
5
|
-
r.last_message_id, r.text_start, r.text_end FROM
|
|
6
|
-
JOIN
|
|
6
|
+
r.last_message_id, r.text_start, r.text_end FROM conversations c
|
|
7
|
+
CROSS JOIN chunks k ON k.chunkable_type = 'conversation' AND k.chunkable_id = c.id
|
|
8
|
+
JOIN chunk_messages r ON r.chunk_id = k.id
|
|
7
9
|
WHERE c.chat_id = ${chatKey}
|
|
8
10
|
AND c.build = (SELECT s.current_build FROM conversation_state s WHERE s.chat_id = ${chatKey})`;
|
|
9
11
|
/**
|
|
@@ -308,7 +310,7 @@ export const readiness = ({ orm }, chatKey, model) => {
|
|
|
308
310
|
JOIN conversations c ON c.id = cm.conversation_id AND c.build = ${build}
|
|
309
311
|
WHERE m.chat_id = ${chatKey} AND (m.deleted_at IS NOT NULL OR ${editedSince(sql `m.id`)})),
|
|
310
312
|
stale AS (SELECT DISTINCT k.content_hash AS hash FROM changed g
|
|
311
|
-
JOIN chunks k ON k.chunkable_type = 'conversation' AND k.chunkable_id = g.conversation_id
|
|
313
|
+
CROSS JOIN chunks k ON k.chunkable_type = 'conversation' AND k.chunkable_id = g.conversation_id
|
|
312
314
|
JOIN chunk_messages r ON r.chunk_id = k.id
|
|
313
315
|
JOIN messages f ON f.id = r.first_message_id JOIN messages l ON l.id = r.last_message_id
|
|
314
316
|
WHERE (g.sent_at, g.id) >= (f.sent_at, f.id) AND (g.sent_at, g.id) <= (l.sent_at, l.id)),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.676.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|
|
@@ -300,7 +300,7 @@
|
|
|
300
300
|
"@types/pngjs": "6.0.5",
|
|
301
301
|
"@types/ssh2": "1.15.5",
|
|
302
302
|
"@vitest/coverage-v8": "^5.0.5",
|
|
303
|
-
"@wirecat/cli-base": "0.
|
|
303
|
+
"@wirecat/cli-base": "0.103.0",
|
|
304
304
|
"@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
|
|
305
305
|
"ajv": "8.17.1",
|
|
306
306
|
"commander": "15.0.0",
|
|
@@ -324,7 +324,7 @@
|
|
|
324
324
|
},
|
|
325
325
|
"peerDependencies": {
|
|
326
326
|
"@napi-rs/canvas": ">=0.1.69 <2",
|
|
327
|
-
"@wirecat/cli-base": ">=0.
|
|
327
|
+
"@wirecat/cli-base": ">=0.103.0 <1.0.0",
|
|
328
328
|
"commander": ">=15",
|
|
329
329
|
"mysql2": "^3.24.6",
|
|
330
330
|
"pg": "^8.23.1",
|