@wirecat/cli-core 0.606.0 → 0.607.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 +186 -1
- package/dist/calendar/index.d.ts +1 -0
- package/dist/calendar/index.js +1 -0
- package/dist/calendar/reads.js +5 -0
- package/dist/cli/app-mcp-command.d.ts +6 -2
- package/dist/cli/app-mcp-command.js +11 -2
- package/dist/cli/csv.d.ts +10 -0
- package/dist/cli/csv.js +22 -0
- package/dist/cli/early-refusal.d.ts +10 -0
- package/dist/cli/early-refusal.js +19 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.js +3 -0
- package/dist/cli/profile-token.d.ts +29 -0
- package/dist/cli/profile-token.js +65 -0
- package/dist/cli/program.js +4 -2
- package/dist/crm/cli/csv.d.ts +23 -0
- package/dist/crm/cli/csv.js +135 -0
- package/dist/crm/cli/index.d.ts +1 -1
- package/dist/crm/cli/index.js +33 -21
- package/dist/crm/cli/pipeline-view.d.ts +3 -0
- package/dist/crm/cli/pipeline-view.js +36 -0
- package/dist/crm/writes.d.ts +6 -4
- package/dist/crm/writes.js +17 -13
- package/dist/documents.d.ts +2 -0
- package/dist/documents.js +2 -0
- package/dist/domain/business.d.ts +79 -0
- package/dist/domain/business.js +42 -0
- package/dist/domain/finance.d.ts +2 -0
- package/dist/domain/finance.js +2 -2
- package/dist/domain/google-documents.d.ts +2 -0
- package/dist/domain/google-documents.js +3 -1
- package/dist/domain/money.d.ts +2 -0
- package/dist/domain/money.js +11 -3
- package/dist/domain/providers.d.ts +36 -1
- package/dist/domain/providers.js +69 -7
- package/dist/domain/record-fields.d.ts +42 -0
- package/dist/domain/record-fields.js +122 -0
- package/dist/domain/record-types.d.ts +489 -16
- package/dist/domain/record-types.js +374 -7
- package/dist/domain/records.d.ts +96 -5
- package/dist/domain/records.js +178 -32
- package/dist/domain/ref-summaries.js +5 -0
- package/dist/domain/references.d.ts +1 -1
- package/dist/domain/references.js +5 -0
- package/dist/domain/vcard.d.ts +25 -0
- package/dist/domain/vcard.js +267 -0
- package/dist/entities/deal.d.ts +14 -0
- package/dist/entities/deal.js +3 -0
- package/dist/entities/index.d.ts +12 -0
- package/dist/errors/reasons.js +61 -2
- package/dist/fetch/addresses.d.ts +5 -0
- package/dist/fetch/addresses.js +76 -0
- package/dist/fetch/page.d.ts +64 -0
- package/dist/fetch/page.js +256 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +5 -3
- package/dist/meetings/calendar-text.d.ts +1 -1
- package/dist/meetings/calendar-text.js +4 -0
- package/dist/meetings/event-store.d.ts +2 -2
- package/dist/search/account-list.d.ts +4 -0
- package/dist/search/account-list.js +19 -8
- package/dist/search/query.js +2 -2
- package/dist/services/events-search.js +2 -2
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/ingest.d.ts +56 -8
- package/dist/services/ingest.js +95 -61
- package/dist/services/messages-search.js +3 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/notes-search.js +1 -0
- package/dist/services/proposals/kinds/contracts.d.ts +4 -0
- package/dist/services/proposals/kinds/contracts.js +9 -0
- package/dist/services/proposals/kinds/finance.d.ts +4 -0
- package/dist/services/proposals/kinds/finance.js +14 -35
- package/dist/services/proposals/kinds/orders.js +7 -30
- package/dist/services/proposals/kinds/shared.d.ts +27 -1
- package/dist/services/proposals/kinds/shared.js +34 -0
- package/dist/services/proposals/kinds/source-review.d.ts +4 -0
- package/dist/services/proposals/kinds/source-review.js +45 -0
- package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
- package/dist/services/proposals/kinds/subscriptions.js +24 -0
- package/dist/services/proposals/kinds/transactions.d.ts +4 -0
- package/dist/services/proposals/kinds/transactions.js +10 -0
- package/dist/services/proposals/registry.js +9 -0
- package/dist/services/search-all-meetings.js +2 -2
- package/dist/services/search-all.js +4 -3
- package/dist/services/search-kind.js +3 -3
- package/dist/store/decisions.js +5 -1
- package/dist/store/index.d.ts +14 -3
- package/dist/store/index.js +3 -0
- package/dist/store/people.js +1 -1
- package/dist/store/source-review.d.ts +64 -0
- package/dist/store/source-review.js +7 -0
- package/dist/store/sqlite/accounts.d.ts +1 -1
- package/dist/store/sqlite/accounts.js +24 -1
- package/dist/store/sqlite/added-sources.d.ts +82 -0
- package/dist/store/sqlite/added-sources.js +237 -0
- package/dist/store/sqlite/business-contracts.d.ts +90 -0
- package/dist/store/sqlite/business-contracts.js +182 -0
- package/dist/store/sqlite/calendar-events.js +7 -3
- package/dist/store/sqlite/calendar-forget.js +3 -0
- package/dist/store/sqlite/calendar.d.ts +21 -1
- package/dist/store/sqlite/calendar.js +27 -7
- package/dist/store/sqlite/chat-rekey.js +7 -0
- package/dist/store/sqlite/chats.d.ts +3 -1
- package/dist/store/sqlite/chats.js +15 -1
- package/dist/store/sqlite/crm-rows.d.ts +44 -0
- package/dist/store/sqlite/crm-rows.js +195 -0
- package/dist/store/sqlite/crm.d.ts +2 -11
- package/dist/store/sqlite/crm.js +11 -166
- package/dist/store/sqlite/deals.d.ts +4 -8
- package/dist/store/sqlite/deals.js +5 -3
- package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
- package/dist/store/sqlite/emails.js +2 -0
- package/dist/store/sqlite/entity-types.d.ts +14 -9
- package/dist/store/sqlite/entity-types.js +4 -10
- package/dist/store/sqlite/evidence-signature.d.ts +114 -0
- package/dist/store/sqlite/evidence-signature.js +349 -0
- package/dist/store/sqlite/evidence-sources.d.ts +2 -1
- package/dist/store/sqlite/evidence-sources.js +7 -3
- package/dist/store/sqlite/facts.d.ts +7 -2
- package/dist/store/sqlite/facts.js +21 -5
- package/dist/store/sqlite/finance.d.ts +18 -105
- package/dist/store/sqlite/finance.js +100 -219
- package/dist/store/sqlite/knowledge.d.ts +8 -2
- package/dist/store/sqlite/knowledge.js +65 -71
- package/dist/store/sqlite/labelled.d.ts +3 -0
- package/dist/store/sqlite/labelled.js +11 -0
- package/dist/store/sqlite/link-kinds.d.ts +2 -0
- package/dist/store/sqlite/link-kinds.js +2 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/memories.d.ts +23 -9
- package/dist/store/sqlite/memories.js +41 -13
- package/dist/store/sqlite/messages.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +103 -0
- package/dist/store/sqlite/money-lines.d.ts +48 -0
- package/dist/store/sqlite/money-lines.js +76 -0
- package/dist/store/sqlite/money-transactions.d.ts +132 -0
- package/dist/store/sqlite/money-transactions.js +295 -0
- package/dist/store/sqlite/notes.d.ts +11 -2
- package/dist/store/sqlite/notes.js +20 -25
- package/dist/store/sqlite/orders.d.ts +36 -6
- package/dist/store/sqlite/orders.js +126 -46
- package/dist/store/sqlite/payment-facts.js +1 -1
- package/dist/store/sqlite/private-people.js +2 -0
- package/dist/store/sqlite/products.d.ts +78 -0
- package/dist/store/sqlite/products.js +131 -0
- package/dist/store/sqlite/project-transfer/records.js +26 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
- package/dist/store/sqlite/proposed-actions.d.ts +1 -1
- package/dist/store/sqlite/proposed-actions.js +24 -7
- package/dist/store/sqlite/providers.d.ts +0 -4
- package/dist/store/sqlite/providers.js +20 -2
- package/dist/store/sqlite/record-matching.d.ts +80 -0
- package/dist/store/sqlite/record-matching.js +264 -0
- package/dist/store/sqlite/record-projection.d.ts +89 -0
- package/dist/store/sqlite/record-projection.js +50 -0
- package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
- package/dist/store/sqlite/record-projectors-direct.js +125 -0
- package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
- package/dist/store/sqlite/record-projectors-money.js +214 -0
- package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
- package/dist/store/sqlite/record-projectors-phone.js +212 -0
- package/dist/store/sqlite/record-projectors.d.ts +3 -44
- package/dist/store/sqlite/record-projectors.js +7 -67
- package/dist/store/sqlite/record-relations.d.ts +24 -0
- package/dist/store/sqlite/record-relations.js +92 -0
- package/dist/store/sqlite/record-remap.d.ts +12 -0
- package/dist/store/sqlite/record-remap.js +92 -0
- package/dist/store/sqlite/record-run.d.ts +71 -0
- package/dist/store/sqlite/record-run.js +179 -0
- package/dist/store/sqlite/record-settling.d.ts +9 -0
- package/dist/store/sqlite/record-settling.js +74 -0
- package/dist/store/sqlite/record-stamps.d.ts +13 -0
- package/dist/store/sqlite/record-stamps.js +30 -0
- package/dist/store/sqlite/record-writes.d.ts +43 -0
- package/dist/store/sqlite/record-writes.js +307 -0
- package/dist/store/sqlite/records.d.ts +52 -42
- package/dist/store/sqlite/records.js +123 -353
- package/dist/store/sqlite/ref-summaries.d.ts +6 -5
- package/dist/store/sqlite/ref-summaries.js +60 -8
- package/dist/store/sqlite/refunds.d.ts +31 -0
- package/dist/store/sqlite/refunds.js +112 -0
- package/dist/store/sqlite/reviewed.d.ts +109 -0
- package/dist/store/sqlite/reviewed.js +173 -0
- package/dist/store/sqlite/schema.d.ts +2840 -83
- package/dist/store/sqlite/schema.js +256 -1
- package/dist/store/sqlite/source-review-marks.d.ts +54 -0
- package/dist/store/sqlite/source-review-marks.js +143 -0
- package/dist/store/sqlite/source-review.d.ts +54 -0
- package/dist/store/sqlite/source-review.js +221 -0
- package/dist/store/sqlite/stage-amounts.d.ts +14 -0
- package/dist/store/sqlite/stage-amounts.js +23 -0
- package/dist/store/sqlite/subscriptions.d.ts +135 -0
- package/dist/store/sqlite/subscriptions.js +294 -0
- package/dist/store/sqlite/text-input.d.ts +3 -0
- package/dist/store/sqlite/text-input.js +13 -0
- package/dist/store/sqlite/things.js +2 -9
- package/dist/store/sqlite/transaction.d.ts +15 -0
- package/dist/store/sqlite/transaction.js +57 -0
- package/dist/store/sqlite/wallets.d.ts +88 -0
- package/dist/store/sqlite/wallets.js +143 -0
- package/dist/store/store-errors.d.ts +1 -0
- package/dist/store/store-errors.js +45 -0
- package/dist/store/store.d.ts +16 -1
- package/dist/store/store.js +30 -6
- package/package.json +5 -2
- package/schemas/examples/records-business.jsonl +11 -0
- package/schemas/records-envelope.v1.schema.json +1160 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { addProvider, providerEntryOf, useStoredProviders } from "../../domain/providers.js";
|
|
1
|
+
import { addProvider, importedOf, kindsOfEntry, providerEntryOf, unitedKinds, useStoredProviders, } from "../../domain/providers.js";
|
|
2
2
|
import { write } from "./transaction.js";
|
|
3
3
|
export const PROVIDERS_SETTING = "providers";
|
|
4
4
|
/** The entries as stored, unchecked: a newer CLI may have written a kind this build does not know. */
|
|
@@ -23,10 +23,28 @@ const nameOf = (stored) => typeof stored === "object" && stored !== null ? store
|
|
|
23
23
|
* Writes `entry` over the stored one of its name and loads the result. Every run of every CLI calls it, so it
|
|
24
24
|
* writes only when the entry changed. Entries this build cannot read stay stored for the CLIs that can.
|
|
25
25
|
*/
|
|
26
|
+
/**
|
|
27
|
+
* The entry with what the stored one of its name held beyond it: another build's kinds are never dropped, and
|
|
28
|
+
* `imported` is kept as `importedOf` rules, so it can be neither stripped nor added later.
|
|
29
|
+
*/
|
|
30
|
+
const keptBeside = (entry, stored) => {
|
|
31
|
+
const found = stored.find((one) => nameOf(one) === entry.name);
|
|
32
|
+
let held;
|
|
33
|
+
try {
|
|
34
|
+
held = found === undefined ? undefined : providerEntryOf(found);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
held = undefined;
|
|
38
|
+
}
|
|
39
|
+
const imported = importedOf(entry, held);
|
|
40
|
+
const { imported: _given, ...rest } = entry;
|
|
41
|
+
const kinds = held && held.kind === entry.kind ? unitedKinds(kindsOfEntry(held), kindsOfEntry(entry)) : kindsOfEntry(entry);
|
|
42
|
+
return { ...rest, ...(kinds.length > 1 ? { kinds } : {}), ...(imported ? { imported: true } : {}) };
|
|
43
|
+
};
|
|
26
44
|
export const registerProvider = (database, value, now) => {
|
|
27
|
-
const entry = providerEntryOf(value);
|
|
28
45
|
write(database, () => {
|
|
29
46
|
const stored = storedProvidersOf(database);
|
|
47
|
+
const entry = keptBeside(providerEntryOf(value), stored);
|
|
30
48
|
const others = stored.filter((one) => nameOf(one) !== entry.name);
|
|
31
49
|
try {
|
|
32
50
|
useStoredProviders(others);
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type IdentityType } from "../../domain/record-types.js";
|
|
2
|
+
import type { EnvelopeOptions, EnvelopeSource } from "../../domain/records.js";
|
|
3
|
+
import type { CacheDatabase } from "../driver.js";
|
|
4
|
+
import type { StoreContext } from "./open.js";
|
|
5
|
+
import { type Row } from "./record-projection.js";
|
|
6
|
+
/** The strong identifiers a person, organization or project record gives; a name is never one. */
|
|
7
|
+
export interface Identifiers {
|
|
8
|
+
/** Lower-cased, as every writer of an e-mail identity keeps them. */
|
|
9
|
+
emails: string[];
|
|
10
|
+
/** E.164. */
|
|
11
|
+
phones: string[];
|
|
12
|
+
/** The source's own contact identity, `<account>/contact/<external id>` under its provider, as CRM sync writes it. */
|
|
13
|
+
contact?: {
|
|
14
|
+
provider: string;
|
|
15
|
+
externalId: string;
|
|
16
|
+
};
|
|
17
|
+
/** An organization's, by the identity provider its scheme is kept under. */
|
|
18
|
+
organization: {
|
|
19
|
+
provider: string;
|
|
20
|
+
value: string;
|
|
21
|
+
}[];
|
|
22
|
+
/** A project's key, upper-cased. */
|
|
23
|
+
key?: string;
|
|
24
|
+
/** Values that look like an identifier but were not read as one, with why: a phone without `+` and no region. */
|
|
25
|
+
ignored: {
|
|
26
|
+
at: (string | number)[];
|
|
27
|
+
reason: "record.phone-region";
|
|
28
|
+
}[];
|
|
29
|
+
}
|
|
30
|
+
export type Match = {
|
|
31
|
+
outcome: "none";
|
|
32
|
+
} | {
|
|
33
|
+
outcome: "one";
|
|
34
|
+
id: number;
|
|
35
|
+
} | {
|
|
36
|
+
outcome: "ambiguous";
|
|
37
|
+
ids: number[];
|
|
38
|
+
reason: "record.ambiguous" | "record.separated";
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* A phone as E.164, `null` for a number written without `+` or `00` when the envelope names no `phone_region`, or
|
|
42
|
+
* nothing when it is no phone. Only the envelope says which country a national number is from: the store's
|
|
43
|
+
* `phone_countries` setting reads `4155550100` as Russian, so it never decides an identifier.
|
|
44
|
+
*/
|
|
45
|
+
export declare const e164Of: (phone: string, region: string | undefined) => string | null | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* A record's identifiers. What does not read as an e-mail, a phone or a `{scheme, value}` of a known scheme is no
|
|
48
|
+
* identifier and stays in the fields, as v1 kept it; a free-mail domain claimed as an organization's is refused.
|
|
49
|
+
*/
|
|
50
|
+
export declare const identifiersOf: (type: IdentityType, fields: Row, source: EnvelopeSource, externalId: string, options?: EnvelopeOptions) => Identifiers;
|
|
51
|
+
/**
|
|
52
|
+
* The entities the identifiers point at, each once. The one lookup an import matches by: the Memory workstream's
|
|
53
|
+
* shared matcher (D5) takes it over as it is, so it reads the store and nothing else.
|
|
54
|
+
*/
|
|
55
|
+
export declare const entitiesByIdentifiers: (database: CacheDatabase, type: IdentityType, ids: Identifiers) => number[];
|
|
56
|
+
/** Whether the owner separated `person` from an identity the record brings: linking would join what he told apart. */
|
|
57
|
+
export declare const separatedByOwner: (context: StoreContext, person: number, identities: number[]) => boolean;
|
|
58
|
+
/** What the identifiers say: no entity, exactly one, or several the owner has to choose between. */
|
|
59
|
+
export declare const matchOf: (context: StoreContext, type: IdentityType, ids: Identifiers) => Match;
|
|
60
|
+
/** The identity of `(provider, externalId)`, made when the store has none; never another person's. */
|
|
61
|
+
export declare const importedIdentity: ({ database, now }: StoreContext, identity: {
|
|
62
|
+
provider: string;
|
|
63
|
+
externalId: string;
|
|
64
|
+
name: string | null;
|
|
65
|
+
email?: string;
|
|
66
|
+
phone?: string;
|
|
67
|
+
}) => number;
|
|
68
|
+
/** Gives a person the record brought these identifiers; an identity another person already has stays theirs. */
|
|
69
|
+
export declare const linkToPerson: (context: StoreContext, person: number, identity: number, source: EnvelopeSource) => void;
|
|
70
|
+
/** Adds the record's identifiers to an entity the import made; never to one it linked by an identifier. */
|
|
71
|
+
export declare const addIdentifiers: (context: StoreContext, type: IdentityType, id: number, ids: Identifiers, name: string | null, source: EnvelopeSource) => void;
|
|
72
|
+
/** Makes the entity a record with no match stands for, marked by the caller as made by the import. */
|
|
73
|
+
export declare const createEntity: (context: StoreContext, type: IdentityType, fields: Row, ids: Identifiers, related: {
|
|
74
|
+
organization?: number | null;
|
|
75
|
+
}, source: EnvelopeSource, externalId: string) => number;
|
|
76
|
+
/**
|
|
77
|
+
* The name of an entity the import made follows the source, unless someone renamed it here: `before` is the name
|
|
78
|
+
* the source gave last time.
|
|
79
|
+
*/
|
|
80
|
+
export declare const renameMade: ({ database, now }: StoreContext, type: IdentityType, id: number, name: unknown, before: unknown) => void;
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { typedPhone } from "../../domain/mentions.js";
|
|
2
|
+
import { nationalPhone } from "../../domain/phones.js";
|
|
3
|
+
import { isObject } from "../../domain/record-fields.js";
|
|
4
|
+
import { RECORD_TABLES } from "../../domain/record-types.js";
|
|
5
|
+
import { FREE_MAIL } from "../../mail/score.js";
|
|
6
|
+
import { fold } from "../normalize.js";
|
|
7
|
+
import { crmIdentityId } from "./crm.js";
|
|
8
|
+
import { insertProject } from "./knowledge.js";
|
|
9
|
+
import { identitySeparated } from "./person-separation.js";
|
|
10
|
+
import { refusal } from "./record-projection.js";
|
|
11
|
+
const valuesOf = (value) => (Array.isArray(value) ? value : [value]).filter((one) => typeof one === "string");
|
|
12
|
+
const SCHEME = /^(email|domain|tax-id:[a-z]{2}|registration:[a-z]{2})$/;
|
|
13
|
+
/**
|
|
14
|
+
* Each scheme under a provider of its own: an organization's address is never a person's `email` identity, so a
|
|
15
|
+
* company identifier can never take, or be taken for, a person's mail.
|
|
16
|
+
*/
|
|
17
|
+
const ORG_EMAIL = "org-email";
|
|
18
|
+
const providerOf = (scheme) => (scheme === "email" ? ORG_EMAIL : scheme);
|
|
19
|
+
const domainOf = (value) => value
|
|
20
|
+
.trim()
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.replace(/^www\./, "");
|
|
23
|
+
/**
|
|
24
|
+
* A phone as E.164, `null` for a number written without `+` or `00` when the envelope names no `phone_region`, or
|
|
25
|
+
* nothing when it is no phone. Only the envelope says which country a national number is from: the store's
|
|
26
|
+
* `phone_countries` setting reads `4155550100` as Russian, so it never decides an identifier.
|
|
27
|
+
*/
|
|
28
|
+
export const e164Of = (phone, region) => {
|
|
29
|
+
if (/^\s*(\+|00)/.test(phone))
|
|
30
|
+
return typedPhone(phone)?.value;
|
|
31
|
+
if (typedPhone(phone) === undefined)
|
|
32
|
+
return undefined;
|
|
33
|
+
if (region === undefined)
|
|
34
|
+
return null;
|
|
35
|
+
const digits = phone.replace(/\(0\)/, "").replace(/\D/g, "");
|
|
36
|
+
return nationalPhone(digits, [region], { anyType: true })?.value;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* A record's identifiers. What does not read as an e-mail, a phone or a `{scheme, value}` of a known scheme is no
|
|
40
|
+
* identifier and stays in the fields, as v1 kept it; a free-mail domain claimed as an organization's is refused.
|
|
41
|
+
*/
|
|
42
|
+
export const identifiersOf = (type, fields, source, externalId, options = {}) => {
|
|
43
|
+
const found = { emails: [], phones: [], organization: [], ignored: [] };
|
|
44
|
+
if (type === "person") {
|
|
45
|
+
found.contact = { provider: source.provider, externalId: crmIdentityId(source, externalId) };
|
|
46
|
+
for (const email of valuesOf(fields.email)) {
|
|
47
|
+
const address = email.trim().toLowerCase();
|
|
48
|
+
if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(address) && !found.emails.includes(address))
|
|
49
|
+
found.emails.push(address);
|
|
50
|
+
}
|
|
51
|
+
const region = options.phone_region?.toLowerCase();
|
|
52
|
+
const phones = Array.isArray(fields.phone) ? fields.phone : [fields.phone];
|
|
53
|
+
for (const [index, phone] of phones.entries()) {
|
|
54
|
+
if (typeof phone !== "string")
|
|
55
|
+
continue;
|
|
56
|
+
const value = e164Of(phone, region);
|
|
57
|
+
if (value === null)
|
|
58
|
+
found.ignored.push({
|
|
59
|
+
at: ["fields", "phone", ...(Array.isArray(fields.phone) ? [index] : [])],
|
|
60
|
+
reason: "record.phone-region",
|
|
61
|
+
});
|
|
62
|
+
else if (value !== undefined && !found.phones.includes(value))
|
|
63
|
+
found.phones.push(value);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (type === "organization")
|
|
67
|
+
for (const [index, item] of (Array.isArray(fields.identifiers) ? fields.identifiers : []).entries()) {
|
|
68
|
+
if (!isObject(item) || typeof item.scheme !== "string" || typeof item.value !== "string")
|
|
69
|
+
continue;
|
|
70
|
+
if (!SCHEME.test(item.scheme) || !item.value.trim())
|
|
71
|
+
continue;
|
|
72
|
+
const value = item.scheme === "domain"
|
|
73
|
+
? domainOf(item.value)
|
|
74
|
+
: item.scheme === "email"
|
|
75
|
+
? item.value.trim().toLowerCase()
|
|
76
|
+
: item.value.trim();
|
|
77
|
+
if (item.scheme === "domain" && FREE_MAIL.has(value))
|
|
78
|
+
refusal(`${value} is a free mail domain: anyone has an address there, so it names no organization`, "record.identifier", ["fields", "identifiers", index, "value"]);
|
|
79
|
+
found.organization.push({ provider: providerOf(item.scheme), value });
|
|
80
|
+
}
|
|
81
|
+
if (type === "project" && typeof fields.key === "string" && fields.key.trim())
|
|
82
|
+
found.key = fields.key.trim().toUpperCase();
|
|
83
|
+
return found;
|
|
84
|
+
};
|
|
85
|
+
const PERSON_BY = {
|
|
86
|
+
// UNION, not OR: each branch reads its own index.
|
|
87
|
+
email: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
|
|
88
|
+
"WHERE i.provider = 'email' AND i.external_id = ? UNION " +
|
|
89
|
+
"SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE i.email = ?",
|
|
90
|
+
// A messenger or CRM contact keeps its number raw in identities.phone, with or without the +.
|
|
91
|
+
phone: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
|
|
92
|
+
"WHERE i.provider = 'phone' AND i.external_id = ? UNION " +
|
|
93
|
+
"SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id WHERE i.phone IN (?, ?)",
|
|
94
|
+
contact: "SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
|
|
95
|
+
"WHERE i.provider = ? AND i.external_id = ?",
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* The entities the identifiers point at, each once. The one lookup an import matches by: the Memory workstream's
|
|
99
|
+
* shared matcher (D5) takes it over as it is, so it reads the store and nothing else.
|
|
100
|
+
*/
|
|
101
|
+
export const entitiesByIdentifiers = (database, type, ids) => {
|
|
102
|
+
const found = new Set();
|
|
103
|
+
const add = (rows, column) => {
|
|
104
|
+
for (const row of rows)
|
|
105
|
+
found.add(Number(row[column]));
|
|
106
|
+
};
|
|
107
|
+
if (type === "person") {
|
|
108
|
+
for (const email of ids.emails)
|
|
109
|
+
add(database.prepare(PERSON_BY.email).all(email, email), "person_id");
|
|
110
|
+
for (const value of ids.phones)
|
|
111
|
+
add(database.prepare(PERSON_BY.phone).all(value, value, value.slice(1)), "person_id");
|
|
112
|
+
if (ids.contact)
|
|
113
|
+
add(database.prepare(PERSON_BY.contact).all(ids.contact.provider, ids.contact.externalId), "person_id");
|
|
114
|
+
}
|
|
115
|
+
if (type === "organization") {
|
|
116
|
+
const organization = database.prepare("SELECT o.id FROM identities i JOIN organization_identities oi ON oi.identity_id = i.id " +
|
|
117
|
+
"JOIN organizations o ON o.id = oi.organization_id WHERE o.deleted_at IS NULL AND i.provider = ? " +
|
|
118
|
+
"AND i.external_id = ?");
|
|
119
|
+
for (const { provider, value } of ids.organization) {
|
|
120
|
+
add(organization.all(provider, value), "id");
|
|
121
|
+
// Mail findings and mentions give a company its address as an `email` identity; it is the same company.
|
|
122
|
+
if (provider === ORG_EMAIL)
|
|
123
|
+
add(organization.all("email", value), "id");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (type === "project" && ids.key !== undefined)
|
|
127
|
+
add(database.prepare("SELECT id FROM projects WHERE key = ? AND deleted_at IS NULL").all(ids.key), "id");
|
|
128
|
+
return [...found].sort((a, b) => a - b);
|
|
129
|
+
};
|
|
130
|
+
/** The identities the store already has for a person record's identifiers. */
|
|
131
|
+
const identitiesOf = (database, ids) => {
|
|
132
|
+
const pairs = [
|
|
133
|
+
...ids.emails.map((value) => ["email", value]),
|
|
134
|
+
...ids.phones.map((value) => ["phone", value]),
|
|
135
|
+
...(ids.contact ? [[ids.contact.provider, ids.contact.externalId]] : []),
|
|
136
|
+
];
|
|
137
|
+
return pairs.flatMap(([provider, value]) => {
|
|
138
|
+
const row = database
|
|
139
|
+
.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?")
|
|
140
|
+
.get(provider, value);
|
|
141
|
+
return row ? [Number(row.id)] : [];
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
/** Whether the owner separated `person` from an identity the record brings: linking would join what he told apart. */
|
|
145
|
+
export const separatedByOwner = (context, person, identities) => identities.some((identity) => identitySeparated(context, identity, person));
|
|
146
|
+
/** What the identifiers say: no entity, exactly one, or several the owner has to choose between. */
|
|
147
|
+
export const matchOf = (context, type, ids) => {
|
|
148
|
+
const { database } = context;
|
|
149
|
+
const found = entitiesByIdentifiers(database, type, ids);
|
|
150
|
+
if (found.length === 0)
|
|
151
|
+
return { outcome: "none" };
|
|
152
|
+
if (found.length > 1)
|
|
153
|
+
return { outcome: "ambiguous", ids: found, reason: "record.ambiguous" };
|
|
154
|
+
const id = found[0];
|
|
155
|
+
if (type === "person" && separatedByOwner(context, id, identitiesOf(database, ids)))
|
|
156
|
+
return { outcome: "ambiguous", ids: found, reason: "record.separated" };
|
|
157
|
+
return { outcome: "one", id };
|
|
158
|
+
};
|
|
159
|
+
const IMPORT = "import";
|
|
160
|
+
/** The identity of `(provider, externalId)`, made when the store has none; never another person's. */
|
|
161
|
+
export const importedIdentity = ({ database, now }, identity) => {
|
|
162
|
+
const held = database
|
|
163
|
+
.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?")
|
|
164
|
+
.get(identity.provider, identity.externalId);
|
|
165
|
+
if (held)
|
|
166
|
+
return Number(held.id);
|
|
167
|
+
const at = now();
|
|
168
|
+
return Number(database
|
|
169
|
+
.prepare("INSERT INTO identities (provider, external_id, name, name_folded, email, phone, created_at, updated_at) " +
|
|
170
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
171
|
+
.get(identity.provider, identity.externalId, identity.name, identity.name === null ? null : fold(identity.name), identity.email ?? null, identity.phone ?? null, at, at)?.id);
|
|
172
|
+
};
|
|
173
|
+
/** Gives a person the record brought these identifiers; an identity another person already has stays theirs. */
|
|
174
|
+
export const linkToPerson = (context, person, identity, source) => {
|
|
175
|
+
const { database, now } = context;
|
|
176
|
+
if (database.prepare("SELECT 1 FROM identity_links WHERE identity_id = ?").get(identity))
|
|
177
|
+
return;
|
|
178
|
+
if (identitySeparated(context, identity, person))
|
|
179
|
+
return;
|
|
180
|
+
const at = now();
|
|
181
|
+
database
|
|
182
|
+
.prepare("INSERT INTO identity_links (identity_id, person_id, method, confidence, created_at, author, source, " +
|
|
183
|
+
"updated_at) VALUES (?, ?, ?, 1, ?, ?, ?, ?)")
|
|
184
|
+
.run(identity, person, IMPORT, at, IMPORT, `import:${source.provider}`, at);
|
|
185
|
+
database
|
|
186
|
+
.prepare("INSERT INTO identity_link_events (identity_id, from_person_id, to_person_id, method, created_at, author) " +
|
|
187
|
+
"VALUES (?, NULL, ?, ?, ?, ?)")
|
|
188
|
+
.run(identity, person, IMPORT, at, IMPORT);
|
|
189
|
+
};
|
|
190
|
+
/** Adds the record's identifiers to an entity the import made; never to one it linked by an identifier. */
|
|
191
|
+
export const addIdentifiers = (context, type, id, ids, name, source) => {
|
|
192
|
+
const { database, now } = context;
|
|
193
|
+
if (type === "person") {
|
|
194
|
+
const [email] = ids.emails;
|
|
195
|
+
const [phone] = ids.phones;
|
|
196
|
+
if (ids.contact)
|
|
197
|
+
linkToPerson(context, id, importedIdentity(context, { ...ids.contact, name, email, phone }), source);
|
|
198
|
+
for (const address of ids.emails)
|
|
199
|
+
linkToPerson(context, id, importedIdentity(context, { provider: "email", externalId: address, name, email: address }), source);
|
|
200
|
+
for (const value of ids.phones)
|
|
201
|
+
linkToPerson(context, id, importedIdentity(context, { provider: "phone", externalId: value, name, phone: value }), source);
|
|
202
|
+
}
|
|
203
|
+
if (type === "organization")
|
|
204
|
+
for (const { provider, value } of ids.organization) {
|
|
205
|
+
const identity = importedIdentity(context, { provider, externalId: value, name });
|
|
206
|
+
const at = now();
|
|
207
|
+
database
|
|
208
|
+
.prepare("INSERT OR IGNORE INTO organization_identities (identity_id, organization_id, method, author, created_at, " +
|
|
209
|
+
"updated_at) VALUES (?, ?, ?, ?, ?, ?)")
|
|
210
|
+
.run(identity, id, IMPORT, IMPORT, at, at);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
/** Makes the entity a record with no match stands for, marked by the caller as made by the import. */
|
|
214
|
+
export const createEntity = (context, type, fields, ids, related, source, externalId) => {
|
|
215
|
+
const { database, now } = context;
|
|
216
|
+
const name = typeof fields.name === "string" && fields.name.trim() ? fields.name.trim() : null;
|
|
217
|
+
const at = now();
|
|
218
|
+
let id;
|
|
219
|
+
if (type === "person")
|
|
220
|
+
id = Number(database
|
|
221
|
+
.prepare("INSERT INTO persons (name, created_at, updated_at) VALUES (?, ?, ?) RETURNING id")
|
|
222
|
+
.get(name, at, at)?.id);
|
|
223
|
+
else if (type === "organization")
|
|
224
|
+
id = Number(database
|
|
225
|
+
.prepare("INSERT INTO organizations (kind, name, scope, created_at, updated_at) VALUES ('company', ?, 'work', ?, ?) " +
|
|
226
|
+
"RETURNING id")
|
|
227
|
+
.get(name ?? `${source.provider} organization ${externalId}`, at, at)?.id);
|
|
228
|
+
else {
|
|
229
|
+
const title = name ?? `${source.provider} project ${externalId}`;
|
|
230
|
+
const free = ids.key !== undefined &&
|
|
231
|
+
/^[A-Z][A-Z0-9]{2,3}$/.test(ids.key) &&
|
|
232
|
+
!database.prepare("SELECT 1 FROM projects WHERE key = ?").get(ids.key);
|
|
233
|
+
const organization = related.organization == null ? undefined : `organization:${related.organization}`;
|
|
234
|
+
const row = insertProject(context, {
|
|
235
|
+
name: title,
|
|
236
|
+
...(free ? { key: ids.key } : {}),
|
|
237
|
+
...(organization ? { organization } : {}),
|
|
238
|
+
...(typeof fields.description === "string" ? { description: fields.description } : {}),
|
|
239
|
+
scope: "work",
|
|
240
|
+
});
|
|
241
|
+
id = Number(row.id);
|
|
242
|
+
}
|
|
243
|
+
addIdentifiers(context, type, id, ids, name, source);
|
|
244
|
+
return id;
|
|
245
|
+
};
|
|
246
|
+
/**
|
|
247
|
+
* The name of an entity the import made follows the source, unless someone renamed it here: `before` is the name
|
|
248
|
+
* the source gave last time.
|
|
249
|
+
*/
|
|
250
|
+
export const renameMade = ({ database, now }, type, id, name, before) => {
|
|
251
|
+
if (typeof name !== "string" || !name.trim() || name === before)
|
|
252
|
+
return;
|
|
253
|
+
const table = RECORD_TABLES[type];
|
|
254
|
+
const folded = type === "project" ? ", name_folded = ?" : "";
|
|
255
|
+
database
|
|
256
|
+
.prepare(`UPDATE ${table} SET name = ?${folded}, updated_at = ? WHERE id = ? AND name IS ?`)
|
|
257
|
+
.run(...[
|
|
258
|
+
name.trim(),
|
|
259
|
+
...(type === "project" ? [fold(name.trim())] : []),
|
|
260
|
+
now(),
|
|
261
|
+
id,
|
|
262
|
+
typeof before === "string" ? before : null,
|
|
263
|
+
]);
|
|
264
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import type { RecordEntityType } from "../../domain/record-types.js";
|
|
3
|
+
import type { EnvelopeOptions, EnvelopeSource } from "../../domain/records.js";
|
|
4
|
+
import type { contractOperationsOver } from "./business-contracts.js";
|
|
5
|
+
import type { crmRowsOver } from "./crm.js";
|
|
6
|
+
import type { financeOperationsOver, PaymentDetail } from "./finance.js";
|
|
7
|
+
import type { transactionOperationsOver } from "./money-transactions.js";
|
|
8
|
+
import type { StoreContext } from "./open.js";
|
|
9
|
+
import type { orderOperationsOver } from "./orders.js";
|
|
10
|
+
import type { productOperationsOver } from "./products.js";
|
|
11
|
+
import type { Reviewed } from "./reviewed.js";
|
|
12
|
+
import type { subscriptionOperationsOver } from "./subscriptions.js";
|
|
13
|
+
import type { walletOperationsOver } from "./wallets.js";
|
|
14
|
+
export type Row = Record<string, unknown>;
|
|
15
|
+
export interface Share {
|
|
16
|
+
invoice: string;
|
|
17
|
+
/** As the source gave it; `null` settles as far as both allow. */
|
|
18
|
+
amount: string | null;
|
|
19
|
+
}
|
|
20
|
+
/** What a record stands for, with every reference it makes resolved to an entity. */
|
|
21
|
+
export interface Projection {
|
|
22
|
+
externalId: string;
|
|
23
|
+
accountId: number;
|
|
24
|
+
source: EnvelopeSource;
|
|
25
|
+
options: EnvelopeOptions;
|
|
26
|
+
fields: Row;
|
|
27
|
+
/** The entities its relations resolved to, by role, in the order sent. */
|
|
28
|
+
related: Map<string, string[]>;
|
|
29
|
+
/** The `as` of each relation in `related`, by role and in the same order. */
|
|
30
|
+
as: Map<string, (string | null)[]>;
|
|
31
|
+
/** What each invoice a payment settles gets. */
|
|
32
|
+
shares: Share[];
|
|
33
|
+
/** `product:` refs of the product records its lines name by external id; empty when it names none. */
|
|
34
|
+
products: Map<string, string>;
|
|
35
|
+
}
|
|
36
|
+
export interface ProjectionTools {
|
|
37
|
+
context: StoreContext;
|
|
38
|
+
finance: ReturnType<typeof financeOperationsOver>;
|
|
39
|
+
orders: ReturnType<typeof orderOperationsOver>;
|
|
40
|
+
contracts: ReturnType<typeof contractOperationsOver>;
|
|
41
|
+
subscriptions: ReturnType<typeof subscriptionOperationsOver>;
|
|
42
|
+
transactions: ReturnType<typeof transactionOperationsOver>;
|
|
43
|
+
products: ReturnType<typeof productOperationsOver>;
|
|
44
|
+
wallets: ReturnType<typeof walletOperationsOver>;
|
|
45
|
+
crm: ReturnType<typeof crmRowsOver>;
|
|
46
|
+
settle: (made: PaymentDetail, shares: Share[]) => string;
|
|
47
|
+
}
|
|
48
|
+
export interface RecordProjector {
|
|
49
|
+
/** Makes the entity or the proposal the record stands for and returns its ref. */
|
|
50
|
+
create(projection: Projection, tools: ProjectionTools): string;
|
|
51
|
+
/**
|
|
52
|
+
* Takes a changed record into the entity it made, while that is the import's to change: `false` when the owner
|
|
53
|
+
* decided it, and the change is only flagged. Left out, every change is flagged.
|
|
54
|
+
*/
|
|
55
|
+
update?(ref: string, projection: Projection, tools: ProjectionTools): boolean;
|
|
56
|
+
/** A deleted record's entity, for a source copy (an SMS, a call) the delete takes away too. Left out, it stays. */
|
|
57
|
+
remove?(ref: string, tools: ProjectionTools): void;
|
|
58
|
+
/** Brings back what `remove` took when the record is sent again after its delete. */
|
|
59
|
+
restore?(ref: string, projection: Projection, tools: ProjectionTools): void;
|
|
60
|
+
}
|
|
61
|
+
export declare const IMPORTER: {
|
|
62
|
+
readonly bot: "import";
|
|
63
|
+
};
|
|
64
|
+
/** A proposal the import made that the owner has not decided yet: the import may still change it. */
|
|
65
|
+
export declare const importersProposal: (entity: Pick<Reviewed, "review" | "author">) => boolean;
|
|
66
|
+
/** The stable word a store refusal carries, for the receipt. */
|
|
67
|
+
export declare const codeOf: (error: CliError) => string;
|
|
68
|
+
/** `at` names the record's member at fault; a refused entity is the fields' fault. */
|
|
69
|
+
export declare const refusal: (message: string, code: string, at?: string | (string | number)[]) => never;
|
|
70
|
+
export declare const stringField: (fields: Row, name: string) => string | undefined;
|
|
71
|
+
/** A field the registry's schema already typed, read without a second check. */
|
|
72
|
+
export declare const given: <T>(fields: Row, name: string) => T | undefined;
|
|
73
|
+
export declare const importedBy: (source: EnvelopeSource) => {
|
|
74
|
+
by: {
|
|
75
|
+
readonly bot: "import";
|
|
76
|
+
};
|
|
77
|
+
source: string;
|
|
78
|
+
reason: string;
|
|
79
|
+
};
|
|
80
|
+
/** The one entity a single role resolved to. */
|
|
81
|
+
export declare const entityOf: (projection: Projection, role: string) => string | undefined;
|
|
82
|
+
export declare const moneyLinesOf: (projection: Projection, list: unknown) => {
|
|
83
|
+
description: string;
|
|
84
|
+
quantity: string | undefined;
|
|
85
|
+
unitPrice: string | undefined;
|
|
86
|
+
amount: string | undefined;
|
|
87
|
+
product?: string | undefined;
|
|
88
|
+
}[];
|
|
89
|
+
export type RecordProjectors = Record<RecordEntityType, RecordProjector | null>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
export const IMPORTER = { bot: "import" };
|
|
3
|
+
/** A proposal the import made that the owner has not decided yet: the import may still change it. */
|
|
4
|
+
export const importersProposal = (entity) => entity.review === "proposed" && entity.author.type === "bot" && entity.author.name === IMPORTER.bot;
|
|
5
|
+
/** The stable word a store refusal carries, for the receipt. */
|
|
6
|
+
export const codeOf = (error) => {
|
|
7
|
+
const reason = error.details?.reason;
|
|
8
|
+
if (typeof reason === "string")
|
|
9
|
+
return reason;
|
|
10
|
+
return error.code === "not_found" ? "record.reference-not-found" : "record.entity";
|
|
11
|
+
};
|
|
12
|
+
/** `at` names the record's member at fault; a refused entity is the fields' fault. */
|
|
13
|
+
export const refusal = (message, code, at) => {
|
|
14
|
+
throw new CliError("validation_error", message, { reason: code, ...(at === undefined ? {} : { at }) });
|
|
15
|
+
};
|
|
16
|
+
export const stringField = (fields, name) => {
|
|
17
|
+
const value = fields[name];
|
|
18
|
+
if (value === undefined || value === null)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (typeof value !== "string")
|
|
21
|
+
return refusal(`fields.${name} is text`, "record.invalid");
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
/** A field the registry's schema already typed, read without a second check. */
|
|
25
|
+
export const given = (fields, name) => fields[name] === undefined || fields[name] === null ? undefined : fields[name];
|
|
26
|
+
export const importedBy = (source) => ({
|
|
27
|
+
by: IMPORTER,
|
|
28
|
+
source: `import:${source.provider}`,
|
|
29
|
+
reason: `imported from ${source.provider} account ${source.account}, batch ${source.batch_id}`,
|
|
30
|
+
});
|
|
31
|
+
/** The one entity a single role resolved to. */
|
|
32
|
+
export const entityOf = (projection, role) => projection.related.get(role)?.[0];
|
|
33
|
+
/** A line's product: the product record it names in this account, or a `product:` ref. */
|
|
34
|
+
const productOf = (projection, line) => {
|
|
35
|
+
if (typeof line.product_ref === "string")
|
|
36
|
+
return line.product_ref;
|
|
37
|
+
if (typeof line.product === "string")
|
|
38
|
+
return projection.products.get(line.product);
|
|
39
|
+
return undefined;
|
|
40
|
+
};
|
|
41
|
+
export const moneyLinesOf = (projection, list) => (Array.isArray(list) ? list : []).map((line) => {
|
|
42
|
+
const product = productOf(projection, line);
|
|
43
|
+
return {
|
|
44
|
+
description: given(line, "description"),
|
|
45
|
+
quantity: given(line, "quantity"),
|
|
46
|
+
unitPrice: given(line, "unit_price"),
|
|
47
|
+
amount: given(line, "amount"),
|
|
48
|
+
...(product === undefined ? {} : { product }),
|
|
49
|
+
};
|
|
50
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Projection, type ProjectionTools, type RecordProjector } from "./record-projection.js";
|
|
2
|
+
export declare const DIRECT_PROJECTORS: {
|
|
3
|
+
readonly product: {
|
|
4
|
+
readonly create: ({ fields, source, related }: Projection, { products }: ProjectionTools) => string;
|
|
5
|
+
readonly update: (ref: string, { fields }: Projection, { products }: ProjectionTools) => true;
|
|
6
|
+
};
|
|
7
|
+
readonly wallet: {
|
|
8
|
+
readonly create: ({ fields, source, related }: Projection, { wallets }: ProjectionTools) => string;
|
|
9
|
+
readonly update: (ref: string, { fields }: Projection, { wallets }: ProjectionTools) => true;
|
|
10
|
+
};
|
|
11
|
+
readonly pipeline: {
|
|
12
|
+
readonly create: (projection: Projection, { crm, context }: ProjectionTools) => string;
|
|
13
|
+
readonly update: (_ref: string, projection: Projection, { crm, context }: ProjectionTools) => true;
|
|
14
|
+
};
|
|
15
|
+
readonly deal: RecordProjector;
|
|
16
|
+
readonly lead: RecordProjector;
|
|
17
|
+
};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { authorActor } from "./memories.js";
|
|
2
|
+
import { requiredThing } from "./notes.js";
|
|
3
|
+
import { entityOf, given, IMPORTER, importedBy, refusal, } from "./record-projection.js";
|
|
4
|
+
const productFields = (fields) => ({
|
|
5
|
+
name: given(fields, "name"),
|
|
6
|
+
unit: given(fields, "unit"),
|
|
7
|
+
unitPrice: given(fields, "unit_price"),
|
|
8
|
+
currency: given(fields, "currency"),
|
|
9
|
+
description: given(fields, "description"),
|
|
10
|
+
});
|
|
11
|
+
const pipelineOf = (projection) => {
|
|
12
|
+
const { fields, externalId } = projection;
|
|
13
|
+
const stages = fields.stages.map((stage, index) => ({
|
|
14
|
+
externalId: String(stage.external_id),
|
|
15
|
+
name: String(stage.name),
|
|
16
|
+
position: typeof stage.position === "number" ? stage.position : index + 1,
|
|
17
|
+
outcome: (given(stage, "outcome") ?? "open"),
|
|
18
|
+
}));
|
|
19
|
+
return { externalId, name: String(fields.name), stages };
|
|
20
|
+
};
|
|
21
|
+
const idOf = (ref, { context }) => ref === undefined ? undefined : requiredThing(context.database, ref).id;
|
|
22
|
+
/** A deal or a lead on the row of `(account, external id)`: the one CRM sync writes for the same account. */
|
|
23
|
+
const saveDeal = (kind) => (projection, tools) => {
|
|
24
|
+
const { fields, externalId, source, accountId } = projection;
|
|
25
|
+
const item = {
|
|
26
|
+
externalId,
|
|
27
|
+
title: String(fields.title),
|
|
28
|
+
pipeline: String(fields.pipeline),
|
|
29
|
+
stage: String(fields.stage),
|
|
30
|
+
status: given(fields, "status"),
|
|
31
|
+
amount: given(fields, "amount"),
|
|
32
|
+
currency: given(fields, "currency"),
|
|
33
|
+
closeDate: given(fields, "close_date"),
|
|
34
|
+
closedDate: given(fields, "closed_date"),
|
|
35
|
+
closedReason: given(fields, "closed_reason"),
|
|
36
|
+
url: given(fields, "url"),
|
|
37
|
+
};
|
|
38
|
+
const saved = tools.crm.saveItemRow(source, accountId, kind, item, tools.context.now(), {
|
|
39
|
+
organization: idOf(entityOf(projection, "organization"), tools) ?? null,
|
|
40
|
+
// Left out, the project stays: the owner may have set one on the deal here.
|
|
41
|
+
project: idOf(entityOf(projection, "project"), tools),
|
|
42
|
+
...(kind === "lead" ? { deal: idOf(entityOf(projection, "deal"), tools) ?? null } : {}),
|
|
43
|
+
author: authorActor(tools.context, IMPORTER).actor,
|
|
44
|
+
source: importedBy(source).source,
|
|
45
|
+
});
|
|
46
|
+
if ("reason" in saved)
|
|
47
|
+
return refusal(saved.message, "record.reference-not-found", ["fields", "stage"]);
|
|
48
|
+
return `${kind}:${saved.id}`;
|
|
49
|
+
};
|
|
50
|
+
const dealProjector = (kind) => {
|
|
51
|
+
const save = saveDeal(kind);
|
|
52
|
+
return {
|
|
53
|
+
create: save,
|
|
54
|
+
update: (_ref, projection, tools) => {
|
|
55
|
+
save(projection, tools);
|
|
56
|
+
return true;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export const DIRECT_PROJECTORS = {
|
|
61
|
+
product: {
|
|
62
|
+
create: ({ fields, source, related }, { products }) => {
|
|
63
|
+
const made = products.add({
|
|
64
|
+
...productFields(fields),
|
|
65
|
+
by: IMPORTER,
|
|
66
|
+
kind: given(fields, "kind"),
|
|
67
|
+
sku: given(fields, "sku"),
|
|
68
|
+
supplier: related.get("supplier")?.[0],
|
|
69
|
+
source: importedBy(source).source,
|
|
70
|
+
});
|
|
71
|
+
const archived = given(fields, "archived_date");
|
|
72
|
+
if (archived !== undefined)
|
|
73
|
+
products.update(made.ref, { by: IMPORTER, archivedDate: archived });
|
|
74
|
+
return made.ref;
|
|
75
|
+
},
|
|
76
|
+
update: (ref, { fields }, { products }) => {
|
|
77
|
+
const { name, unit, unitPrice, currency, description } = productFields(fields);
|
|
78
|
+
products.update(ref, {
|
|
79
|
+
by: IMPORTER,
|
|
80
|
+
name,
|
|
81
|
+
unit: unit ?? null,
|
|
82
|
+
unitPrice: unitPrice ?? null,
|
|
83
|
+
currency: currency ?? null,
|
|
84
|
+
description: description ?? null,
|
|
85
|
+
archivedDate: given(fields, "archived_date") ?? null,
|
|
86
|
+
});
|
|
87
|
+
return true;
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
wallet: {
|
|
91
|
+
// The opening balance stays in the record: only the owner sets the wallet's.
|
|
92
|
+
create: ({ fields, source, related }, { wallets }) => wallets.add({
|
|
93
|
+
by: IMPORTER,
|
|
94
|
+
name: String(fields.name),
|
|
95
|
+
currency: String(fields.currency),
|
|
96
|
+
kind: given(fields, "kind"),
|
|
97
|
+
institution: given(fields, "institution"),
|
|
98
|
+
numberHint: given(fields, "number_hint"),
|
|
99
|
+
holder: related.get("holder")?.[0],
|
|
100
|
+
source: importedBy(source).source,
|
|
101
|
+
}).ref,
|
|
102
|
+
update: (ref, { fields }, { wallets }) => {
|
|
103
|
+
wallets.update(ref, {
|
|
104
|
+
by: IMPORTER,
|
|
105
|
+
name: String(fields.name),
|
|
106
|
+
institution: given(fields, "institution") ?? null,
|
|
107
|
+
numberHint: given(fields, "number_hint") ?? null,
|
|
108
|
+
});
|
|
109
|
+
return true;
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
pipeline: {
|
|
113
|
+
create: (projection, { crm, context }) => {
|
|
114
|
+
const kind = given(projection.fields, "kind") ?? "deal";
|
|
115
|
+
return `pipeline:${crm.savePipeline(projection.accountId, kind, pipelineOf(projection), context.now())}`;
|
|
116
|
+
},
|
|
117
|
+
update: (_ref, projection, { crm, context }) => {
|
|
118
|
+
const kind = given(projection.fields, "kind") ?? "deal";
|
|
119
|
+
crm.savePipeline(projection.accountId, kind, pipelineOf(projection), context.now());
|
|
120
|
+
return true;
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
deal: dealProjector("deal"),
|
|
124
|
+
lead: dealProjector("lead"),
|
|
125
|
+
};
|