@wirecat/cli-core 0.675.0 → 0.677.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist/calendar/mcp/index.d.ts +12 -12
  3. package/dist/cli/command-runs.d.ts +2 -0
  4. package/dist/cli/command-runs.js +2 -0
  5. package/dist/cli/documents/words.d.ts +1 -1
  6. package/dist/cli/index.d.ts +2 -2
  7. package/dist/cli/index.js +1 -1
  8. package/dist/cli/list-query.d.ts +3 -2
  9. package/dist/cli/list-query.js +5 -2
  10. package/dist/cli/setup-command.js +9 -3
  11. package/dist/crm/cli/index.d.ts +7 -1
  12. package/dist/crm/cli/index.js +104 -20
  13. package/dist/crm/cli/pipeline-view.js +15 -1
  14. package/dist/crm/cli/records.js +11 -3
  15. package/dist/crm/cli/search-all.d.ts +5 -2
  16. package/dist/crm/cli/search-all.js +15 -3
  17. package/dist/crm/source.d.ts +3 -2
  18. package/dist/crm/stage-tasks.js +1 -1
  19. package/dist/crm/sync.js +13 -11
  20. package/dist/crm/testing/write-contract.js +5 -1
  21. package/dist/crm/viewer.d.ts +28 -0
  22. package/dist/crm/viewer.js +63 -0
  23. package/dist/crm/writer.d.ts +3 -0
  24. package/dist/crm/writes.d.ts +7 -2
  25. package/dist/crm/writes.js +24 -14
  26. package/dist/domain/crm.d.ts +9 -9
  27. package/dist/domain/moment.d.ts +2 -0
  28. package/dist/domain/moment.js +2 -0
  29. package/dist/entities/business-context.js +1 -1
  30. package/dist/entities/deal.d.ts +86 -39
  31. package/dist/entities/deal.js +45 -4
  32. package/dist/entities/index.d.ts +20 -32
  33. package/dist/errors/reasons.js +2 -0
  34. package/dist/meetings/mcp/index.d.ts +15 -15
  35. package/dist/services/metadata.d.ts +1 -1
  36. package/dist/services/search-all.d.ts +3 -1
  37. package/dist/services/search-all.js +1 -0
  38. package/dist/setup/define.d.ts +17 -2
  39. package/dist/store/exports.d.ts +1 -0
  40. package/dist/store/exports.js +1 -0
  41. package/dist/store/identity-links.d.ts +73 -0
  42. package/dist/store/identity-links.js +14 -0
  43. package/dist/store/index.d.ts +1 -1
  44. package/dist/store/index.js +1 -1
  45. package/dist/store/people.d.ts +23 -1
  46. package/dist/store/people.js +12 -1
  47. package/dist/store/sqlite/agent-links.d.ts +34 -0
  48. package/dist/store/sqlite/agent-links.js +184 -0
  49. package/dist/store/sqlite/copy-viewer.d.ts +16 -0
  50. package/dist/store/sqlite/copy-viewer.js +11 -0
  51. package/dist/store/sqlite/crm-activities.d.ts +7 -1
  52. package/dist/store/sqlite/crm-activities.js +32 -5
  53. package/dist/store/sqlite/crm-contacts.d.ts +5 -2
  54. package/dist/store/sqlite/crm-contacts.js +30 -14
  55. package/dist/store/sqlite/crm-rows.d.ts +7 -0
  56. package/dist/store/sqlite/crm-rows.js +37 -5
  57. package/dist/store/sqlite/crm-settings.d.ts +2 -1
  58. package/dist/store/sqlite/crm-settings.js +3 -2
  59. package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
  60. package/dist/store/sqlite/crm-stage-entries.js +77 -18
  61. package/dist/store/sqlite/crm.d.ts +14 -4
  62. package/dist/store/sqlite/crm.js +59 -7
  63. package/dist/store/sqlite/deals.d.ts +47 -29
  64. package/dist/store/sqlite/deals.js +64 -76
  65. package/dist/store/sqlite/identity-proposals.d.ts +2 -0
  66. package/dist/store/sqlite/identity-proposals.js +2 -0
  67. package/dist/store/sqlite/person-match-scan.d.ts +29 -0
  68. package/dist/store/sqlite/person-match-scan.js +4 -4
  69. package/dist/store/sqlite/person-merges.d.ts +3 -0
  70. package/dist/store/sqlite/pipeline-period.d.ts +85 -0
  71. package/dist/store/sqlite/pipeline-period.js +199 -0
  72. package/dist/store/sqlite/stage-amounts.d.ts +6 -2
  73. package/dist/store/sqlite/stage-amounts.js +8 -5
  74. 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 stagesOf = (pipelineIds) => database
187
- .prepare("SELECT s.*, (SELECT count(*) FROM deals d WHERE d.stage_id = s.id AND d.status = 'open' AND d.deleted_at IS NULL) + " +
188
- "(SELECT count(*) FROM leads l WHERE l.stage_id = s.id AND l.status = 'open' AND l.deleted_at IS NULL) AS open " +
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, since) => {
239
- const kind = pipeline.kind;
240
- const cutoff = since === null ? null : Date.parse(`${since}T00:00:00Z`);
241
- const items = database
242
- .prepare(`SELECT d.id, d.status, d.stage_id FROM ${TABLES[kind]} d JOIN pipeline_stages s ON s.id = d.stage_id ` +
243
- "WHERE s.pipeline_id = ? AND d.deleted_at IS NULL AND (? IS NULL OR d.created_at >= ?)")
244
- .all(Number(pipeline.id), cutoff, cutoff);
245
- const stages = database
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
- stages: funnel,
281
- totals: {
282
- items: items.length,
283
- open: items.length - won - lost,
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: (filter = {}) => pipelinesOf(pipelineRows(filter.kind === undefined ? undefined : kindOf(filter.kind), filter.account)),
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 since = isoDate(options.since, "the first day counted");
343
- return funnelOf(pipelinesOf([pipelineRow(reference, kind, options.account)])[0], since);
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
- return database
403
- .prepare("SELECT c.pipeline_id, c.changed_at, f.name AS from_name, t.name AS to_name FROM pipeline_stage_changes c " +
404
- "LEFT JOIN pipeline_stages f ON f.id = c.from_stage_id JOIN pipeline_stages t ON t.id = c.to_stage_id " +
405
- "WHERE c.item_type = ? AND c.item_id = ? ORDER BY c.id")
406
- .all(kind, Number(row.id))
407
- .map((change) => ({
408
- from: change.from_name == null ? null : String(change.from_name),
409
- to: String(change.to_name),
410
- pipeline: `pipeline:${change.pipeline_id}`,
411
- at: iso(change.changed_at),
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 AND (? IS NULL OR d.status = ?) ` +
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,
@@ -19,6 +19,8 @@ export interface Opening {
19
19
  candidates?: number[] | undefined;
20
20
  shared?: SharedMailbox | undefined;
21
21
  mailbox?: string | undefined;
22
+ strength?: IdentityLinkPayload["strength"];
23
+ run?: string | undefined;
22
24
  }
23
25
  export type Opened = {
24
26
  outcome: "proposed" | "open";
@@ -70,6 +70,8 @@ export const openIdentityLink = (context, opening, index) => write(context.datab
70
70
  evidence: opening.evidence ?? [],
71
71
  ...(opening.shared === undefined ? {} : { shared: opening.shared }),
72
72
  ...(opening.mailbox === undefined ? {} : { mailbox: opening.mailbox }),
73
+ ...(opening.strength === undefined ? {} : { strength: opening.strength }),
74
+ ...(opening.run === undefined ? {} : { run: opening.run }),
73
75
  };
74
76
  const action = operations.propose({
75
77
  kind: IDENTITY_LINK_KIND,
@@ -1,3 +1,4 @@
1
+ import type { CacheDatabase } from "../driver.js";
1
2
  import type { MatchScan } from "../identity-links.js";
2
3
  import type { Author } from "./memories.js";
3
4
  import type { StoreContext } from "./open.js";
@@ -18,6 +19,34 @@ export declare const PROPOSAL_SCORE: {
18
19
  group: number;
19
20
  nameInChats: number;
20
21
  };
22
+ /**
23
+ * NEED-2445, safe option until the owner rules: a number two people share joins them only when a messenger, which
24
+ * keeps its user's own number, holds it; a CRM's or a card's number is someone's word and waits as a proposal.
25
+ * NEED-2600: a call's other side, kept as `phone:<number>`, is that number as the phone network gave it, as strong
26
+ * as a messenger's; it joins only on a mobile number, since an office's landline is everyone's who works there.
27
+ */
28
+ export declare const phonePairJoins: (phone: string, holders: Holder[]) => boolean;
29
+ export interface Holder {
30
+ identity: number;
31
+ provider: string;
32
+ externalId: string;
33
+ /** The list it comes from: its source, and for a CRM the kind of record, `<portal>/contact/` or `<portal>/user/`. */
34
+ list: string;
35
+ /** An organization holds this identity: its number or address is the company's. */
36
+ company: boolean;
37
+ }
38
+ /**
39
+ * SEC-177: a company's line or mailbox is everyone's who works there, so it never says two people are one. It is one
40
+ * when an organization holds it, or when two people of one list have it, such as two CRM contacts with one number. A
41
+ * CRM's contact and its user may be one person, so they are two lists. A messenger keeps one account per number, so
42
+ * two of its accounts on one number are a number that changed hands, not a company's line.
43
+ */
44
+ export declare const sharedLine: (context: StoreContext, holders: Holder[]) => boolean;
45
+ /** Identities by the value they share. */
46
+ export type Holders = Map<string, Holder[]>;
47
+ export declare const phoneHolders: (database: CacheDatabase) => Holders;
48
+ /** A company's address is an `org-email` identity, never a person's, so it never joins people. */
49
+ export declare const emailHolders: (database: CacheDatabase) => Holders;
21
50
  /**
22
51
  * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
23
52
  * each group it changes, so other writers are never kept waiting for the whole pass. After the first pass, only the
@@ -47,7 +47,7 @@ export const PROPOSAL_SCORE = {
47
47
  * NEED-2600: a call's other side, kept as `phone:<number>`, is that number as the phone network gave it, as strong
48
48
  * as a messenger's; it joins only on a mobile number, since an office's landline is everyone's who works there.
49
49
  */
50
- const phonePairJoins = (phone, holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider)) ||
50
+ export const phonePairJoins = (phone, holders) => holders.some(({ provider }) => BARE_INTERNATIONAL_PROVIDERS.includes(provider)) ||
51
51
  (holders.some(({ externalId }) => externalId === `phone:${phone}`) && isMobilePhone(phone));
52
52
  /** NEED-2446, safe option until the owner rules: an address more than two people have is shared, so it proposes. */
53
53
  const addressGroupJoins = (people) => people <= 2;
@@ -60,7 +60,7 @@ const COMPANY = "EXISTS (SELECT 1 FROM organization_identities o WHERE o.identit
60
60
  * CRM's contact and its user may be one person, so they are two lists. A messenger keeps one account per number, so
61
61
  * two of its accounts on one number are a number that changed hands, not a company's line.
62
62
  */
63
- const sharedLine = (context, holders) => {
63
+ export const sharedLine = (context, holders) => {
64
64
  if (holders.some(({ company }) => company))
65
65
  return true;
66
66
  const seen = new Map();
@@ -136,7 +136,7 @@ const phonesOf = (row) => {
136
136
  catch { }
137
137
  return raws.filter((raw) => typeof raw === "string" && raw.trim() !== "");
138
138
  };
139
- const phoneHolders = (database) => {
139
+ export const phoneHolders = (database) => {
140
140
  const found = new Map();
141
141
  const countries = storePhoneCountries(database);
142
142
  for (const row of database
@@ -153,7 +153,7 @@ const addressOf = (value) => {
153
153
  return isEmailAddress(address) ? address : undefined;
154
154
  };
155
155
  /** A company's address is an `org-email` identity, never a person's, so it never joins people. */
156
- const emailHolders = (database) => {
156
+ export const emailHolders = (database) => {
157
157
  const found = new Map();
158
158
  for (const row of database
159
159
  .prepare(`SELECT i.id, i.provider, i.external_id, i.email, ${COMPANY} FROM identities i ` +
@@ -1,3 +1,4 @@
1
+ import type { AgentMerge } from "../identity-links.js";
1
2
  import type { IdentityRef, PersonRecord } from "../types.js";
2
3
  import type { StoreContext } from "./open.js";
3
4
  export interface PersonMerge {
@@ -11,6 +12,8 @@ export interface PersonMerge {
11
12
  method: string;
12
13
  by: string;
13
14
  at: string;
15
+ /** An agent's merge: which agent, in which run, why, and the evidence the store found. */
16
+ agent?: AgentMerge;
14
17
  }
15
18
  export declare const mergeId: (to: number | string, from: number | string) => string;
16
19
  /** The two uids a `merge:<to>-<from>` id names. */
@@ -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: `cutoff` (ms) keeps only rows made since then. */
14
- export declare const stageAmountsOf: ({ database }: StoreContext, kind: DealKind, stageIds: number[], cutoff: number | null) => StageAmounts[];
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[];