@wirecat/cli-core 0.605.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 +284 -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 +4 -1
- package/dist/cli/index.js +4 -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/cli/store-settings.js +38 -4
- 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 +36 -22
- package/dist/crm/cli/pipeline-view.d.ts +3 -0
- package/dist/crm/cli/pipeline-view.js +36 -0
- package/dist/crm/index.d.ts +2 -2
- package/dist/crm/index.js +1 -1
- package/dist/crm/source.d.ts +35 -5
- package/dist/crm/sync.d.ts +15 -7
- package/dist/crm/sync.js +169 -11
- 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/crm.d.ts +41 -2
- package/dist/domain/deals.d.ts +5 -2
- package/dist/domain/deals.js +5 -2
- 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/relations.d.ts +125 -0
- package/dist/domain/relations.js +107 -0
- package/dist/domain/vcard.d.ts +25 -0
- package/dist/domain/vcard.js +267 -0
- package/dist/entities/deal.d.ts +16 -2
- package/dist/entities/deal.js +5 -1
- package/dist/entities/index.d.ts +29 -13
- package/dist/entities/relationship.d.ts +8 -2
- package/dist/entities/relationship.js +8 -2
- package/dist/entities/task-results.d.ts +10 -10
- package/dist/errors/reasons.js +73 -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 +7 -4
- package/dist/index.js +6 -3
- package/dist/mail/cli/review.js +20 -6
- package/dist/mail/index.d.ts +1 -1
- package/dist/mail/marks.d.ts +10 -5
- package/dist/mail/marks.js +16 -8
- package/dist/mail/review.d.ts +5 -0
- 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/link-scorers/scan.js +2 -1
- package/dist/services/link-scorers/shared.js +2 -1
- 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/project-status/index.js +2 -1
- 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/services/stored-project-gathering.js +4 -3
- package/dist/store/decisions.js +5 -1
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/index.d.ts +20 -4
- package/dist/store/index.js +4 -0
- package/dist/store/people.js +1 -1
- package/dist/store/project-transfer/request.d.ts +4 -1
- package/dist/store/project-transfer/schema.d.ts +9 -2
- package/dist/store/project-transfer/schema.js +4 -0
- package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
- 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-settings.d.ts +28 -0
- package/dist/store/sqlite/crm-settings.js +80 -0
- package/dist/store/sqlite/crm.d.ts +42 -11
- package/dist/store/sqlite/crm.js +402 -196
- package/dist/store/sqlite/deals.d.ts +4 -8
- package/dist/store/sqlite/deals.js +8 -5
- 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/involvement-queue.js +4 -3
- package/dist/store/sqlite/knowledge.d.ts +14 -4
- package/dist/store/sqlite/knowledge.js +108 -102
- 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 +4 -3
- package/dist/store/sqlite/link-kinds.js +6 -2
- package/dist/store/sqlite/manifest.js +7 -0
- package/dist/store/sqlite/memories.d.ts +24 -10
- package/dist/store/sqlite/memories.js +73 -19
- package/dist/store/sqlite/messages.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +134 -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 +14 -4
- package/dist/store/sqlite/notes.js +43 -31
- package/dist/store/sqlite/orders.d.ts +36 -6
- package/dist/store/sqlite/orders.js +126 -46
- package/dist/store/sqlite/organizations.d.ts +8 -0
- package/dist/store/sqlite/organizations.js +14 -0
- package/dist/store/sqlite/payment-facts.js +1 -1
- package/dist/store/sqlite/person-preparation.d.ts +1 -1
- package/dist/store/sqlite/person-preparation.js +3 -2
- 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 +39 -3
- package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +11 -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/relation-list.d.ts +43 -0
- package/dist/store/sqlite/relation-list.js +133 -0
- package/dist/store/sqlite/relation-proposals.d.ts +28 -6
- package/dist/store/sqlite/relation-proposals.js +134 -10
- package/dist/store/sqlite/relation-reads.d.ts +8 -0
- package/dist/store/sqlite/relation-reads.js +7 -0
- package/dist/store/sqlite/relation-roles.d.ts +26 -0
- package/dist/store/sqlite/relation-roles.js +91 -0
- package/dist/store/sqlite/reported-relations.d.ts +63 -0
- package/dist/store/sqlite/reported-relations.js +132 -0
- package/dist/store/sqlite/reviewed.d.ts +109 -0
- package/dist/store/sqlite/reviewed.js +173 -0
- package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
- package/dist/store/sqlite/schema/link-revisions.js +11 -0
- package/dist/store/sqlite/schema/links.d.ts +360 -0
- package/dist/store/sqlite/schema/links.js +32 -0
- package/dist/store/sqlite/schema.d.ts +2769 -306
- package/dist/store/sqlite/schema.js +258 -25
- 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 +19 -1
- package/dist/store/store.js +35 -6
- package/package.json +6 -3
- package/schemas/examples/records-business.jsonl +11 -0
- package/schemas/records-envelope.v1.schema.json +1160 -5
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
|
|
3
3
|
import { googleDocumentLinks } from "../../domain/google-documents.js";
|
|
4
|
-
import { DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, } from "../../domain/providers.js";
|
|
4
|
+
import { ADDED_PROVIDER, DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, notAdded, } from "../../domain/providers.js";
|
|
5
5
|
import { parseReference } from "../../domain/references.js";
|
|
6
|
+
import { isRelationKind } from "../../domain/relations.js";
|
|
6
7
|
import { normalizeTag } from "../../domain/tags.js";
|
|
7
8
|
import { assertMayWithdraw } from "../decisions.js";
|
|
8
9
|
import { fold } from "../normalize.js";
|
|
9
10
|
import { ulid } from "../ulid.js";
|
|
10
11
|
import { ownerPerson } from "./actors.js";
|
|
11
12
|
import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
|
|
13
|
+
import { deleteDocumentRow, forgetEvidenceToRow } from "./evidence-signature.js";
|
|
12
14
|
import { PREFERRED_FILE, syncFile } from "./files.js";
|
|
13
15
|
import { importedDocumentWhere } from "./imported-documents.js";
|
|
14
16
|
import { LINK_KINDS, LINK_ORIGINS, linkKind } from "./link-kinds.js";
|
|
@@ -16,23 +18,13 @@ import { reviewLink } from "./link-reviews.js";
|
|
|
16
18
|
import { dateFileNotes } from "./note-dates.js";
|
|
17
19
|
import { holdingText } from "./note-index.js";
|
|
18
20
|
import { addTags, ensureTag, labelsOf } from "./tags.js";
|
|
21
|
+
import { oneOf, textOf } from "./text-input.js";
|
|
19
22
|
import { referenceOfThing, storedThing, thingOf } from "./things.js";
|
|
20
23
|
import { write } from "./transaction.js";
|
|
21
24
|
export const NOTE_FORMATS = ["obsidian", "markdown"];
|
|
22
25
|
export { LINK_ORIGINS } from "./link-kinds.js";
|
|
23
26
|
const iso = (value) => new Date(Number(value)).toISOString();
|
|
24
27
|
const optionalIso = (value) => (value == null ? null : iso(value));
|
|
25
|
-
const textOf = (text, what, max = 100_000, allowEmpty = false) => {
|
|
26
|
-
const value = text.trim();
|
|
27
|
-
if ((!value && !allowEmpty) || value.length > max)
|
|
28
|
-
throw new CliError("validation_error", `${what} takes ${allowEmpty ? 0 : 1}–${max} characters`);
|
|
29
|
-
return value;
|
|
30
|
-
};
|
|
31
|
-
const oneOf = (value, allowed, what) => {
|
|
32
|
-
if (!allowed.includes(value))
|
|
33
|
-
throw new CliError("validation_error", `${what} is one of ${allowed.join(", ")}`);
|
|
34
|
-
return value;
|
|
35
|
-
};
|
|
36
28
|
/** What a link's written target is matched by: case, accents and a leading `@` do not count. */
|
|
37
29
|
export const targetKey = (text) => fold(text).trim().replace(/^@/, "");
|
|
38
30
|
export const documentOf = (row) => ({
|
|
@@ -78,9 +70,11 @@ export const noteRowOf = (database, reference) => {
|
|
|
78
70
|
return noteOf(database.prepare("SELECT * FROM notes WHERE id = ?").get(thing.id));
|
|
79
71
|
return undefined;
|
|
80
72
|
};
|
|
81
|
-
const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
|
|
73
|
+
export const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
|
|
82
74
|
export const linkOf = (database, row) => {
|
|
83
|
-
const metadata = row.metadata == null
|
|
75
|
+
const metadata = row.metadata == null
|
|
76
|
+
? {}
|
|
77
|
+
: JSON.parse(String(row.metadata));
|
|
84
78
|
return {
|
|
85
79
|
id: String(row.id),
|
|
86
80
|
from: thingRef(database, row.from_type, row.from_id),
|
|
@@ -95,6 +89,12 @@ export const linkOf = (database, row) => {
|
|
|
95
89
|
provenance: metadata.provenance ?? null,
|
|
96
90
|
confirmed: Number(row.confirmed) === 1,
|
|
97
91
|
createdAt: iso(row.created_at),
|
|
92
|
+
...(row.account_id == null ? {} : { accountId: Number(row.account_id) }),
|
|
93
|
+
...(row.starts_at == null ? {} : { startsAt: Number(row.starts_at) }),
|
|
94
|
+
...(row.ends_at == null ? {} : { endsAt: Number(row.ends_at) }),
|
|
95
|
+
...(row.deleted_at == null ? {} : { deletedAt: Number(row.deleted_at) }),
|
|
96
|
+
...(typeof metadata.position === "string" ? { position: metadata.position } : {}),
|
|
97
|
+
...(typeof metadata.overrides === "number" ? { overrides: metadata.overrides } : {}),
|
|
98
98
|
};
|
|
99
99
|
};
|
|
100
100
|
/** The row a reference names, refused when the store holds none. */
|
|
@@ -183,27 +183,35 @@ export const insertLink = (context, input) => {
|
|
|
183
183
|
if (to === null && targetText === null)
|
|
184
184
|
throw new CliError("validation_error", "a link needs a target");
|
|
185
185
|
if (to !== null) {
|
|
186
|
+
// A relationship's key holds its role and its source account: the owner's link with another role is another one.
|
|
187
|
+
const relationship = isRelationKind(kind);
|
|
188
|
+
const role = relationship && input.role !== undefined ? input.role.trim() : null;
|
|
186
189
|
const existing = database
|
|
187
|
-
.prepare("SELECT * FROM links WHERE from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ? AND anchor IS ?"
|
|
188
|
-
|
|
190
|
+
.prepare("SELECT * FROM links WHERE from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ? AND anchor IS ?" +
|
|
191
|
+
(relationship ? " AND account_id IS NULL AND (? IS NULL OR ifnull(role, '') = ?)" : ""))
|
|
192
|
+
.get(from.type, from.id, to.type, to.id, kind, input.anchor ?? null, ...(relationship ? [role, role] : []));
|
|
189
193
|
if (existing)
|
|
190
194
|
return linkOf(database, existing);
|
|
191
195
|
}
|
|
192
196
|
const at = now();
|
|
193
197
|
const provenance = input.provenance === undefined ? undefined : textOf(input.provenance, "provenance", 2000);
|
|
198
|
+
const position = input.position === undefined ? undefined : textOf(input.position, "a position", 200);
|
|
199
|
+
if (input.startsAt !== undefined && input.endsAt !== undefined && input.endsAt <= input.startsAt)
|
|
200
|
+
throw new CliError("validation_error", "a relationship ends after it starts");
|
|
201
|
+
const metadata = provenance === undefined && position === undefined ? null : JSON.stringify({ provenance, position });
|
|
194
202
|
const row = database
|
|
195
203
|
.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, anchor, source, target_text, target_folded, role, evidence, " +
|
|
196
|
-
"metadata, confirmed, created_at, author, updated_at, purpose
|
|
197
|
-
"RETURNING id")
|
|
198
|
-
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, kind, input.anchor ?? null, origin, targetText, targetText === null ? null : targetKey(targetText), input.role === undefined ? null : textOf(input.role, "a role", 200), input.evidence === undefined ? null : textOf(input.evidence, "evidence", 2000),
|
|
204
|
+
"metadata, confirmed, created_at, author, updated_at, purpose, starts_at, ends_at) " +
|
|
205
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
206
|
+
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, kind, input.anchor ?? null, origin, targetText, targetText === null ? null : targetKey(targetText), input.role === undefined ? null : textOf(input.role, "a role", 200), input.evidence === undefined ? null : textOf(input.evidence, "evidence", 2000), metadata, input.confirmed === false ? 0 : 1, at, origin === "owner" ? "owner" : null, at, input.purpose === undefined ? null : purposeOf(input.purpose), input.startsAt ?? null, input.endsAt ?? null);
|
|
199
207
|
if (to === null && targetText !== null)
|
|
200
208
|
resolveKey(database, targetKey(targetText));
|
|
201
209
|
return linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(Number(row?.id)));
|
|
202
210
|
};
|
|
203
211
|
/** A folder's `accounts` row; its format lives in `settings`. */
|
|
204
|
-
const folderOf = (row) => {
|
|
212
|
+
export const folderOf = (row) => {
|
|
205
213
|
const settings = row.settings == null ? {} : JSON.parse(String(row.settings));
|
|
206
|
-
const folder = !isDocumentAccountProvider(String(row.provider));
|
|
214
|
+
const folder = !isDocumentAccountProvider(String(row.provider)) && row.provider !== ADDED_PROVIDER;
|
|
207
215
|
return {
|
|
208
216
|
id: String(row.id),
|
|
209
217
|
name: folder ? String(row.name) : `${String(row.provider)}:${String(row.external_id)}`,
|
|
@@ -230,7 +238,7 @@ const frontMatterOf = (metadata) => {
|
|
|
230
238
|
return null;
|
|
231
239
|
}
|
|
232
240
|
};
|
|
233
|
-
const pathParts = (path) => {
|
|
241
|
+
export const pathParts = (path) => {
|
|
234
242
|
const slash = path.lastIndexOf("/");
|
|
235
243
|
const fileName = slash < 0 ? path : path.slice(slash + 1);
|
|
236
244
|
const dot = fileName.lastIndexOf(".");
|
|
@@ -242,12 +250,15 @@ const pathParts = (path) => {
|
|
|
242
250
|
};
|
|
243
251
|
export const notesStoreOver = (context) => {
|
|
244
252
|
const { database, now } = context;
|
|
245
|
-
|
|
253
|
+
/** `synced`: an account a sync writes, which the added sources never are. */
|
|
254
|
+
const folderRow = (id, synced = false) => {
|
|
246
255
|
const row = /^\d+$/.test(id)
|
|
247
256
|
? database.prepare(`SELECT * FROM accounts WHERE id = ? AND ${filesAccountSql()}`).get(Number(id))
|
|
248
257
|
: undefined;
|
|
249
258
|
if (!row)
|
|
250
259
|
throw new CliError("not_found", `no notes folder ${id} in the local store`);
|
|
260
|
+
if (synced && row.provider === ADDED_PROVIDER)
|
|
261
|
+
throw new CliError("validation_error", `account ${id} holds the sources added by hand; no folder syncs it`);
|
|
251
262
|
return row;
|
|
252
263
|
};
|
|
253
264
|
const documentRow = (id) => {
|
|
@@ -296,12 +307,12 @@ export const notesStoreOver = (context) => {
|
|
|
296
307
|
if (!hash || !text.trim())
|
|
297
308
|
return [];
|
|
298
309
|
const live = database
|
|
299
|
-
.prepare(
|
|
310
|
+
.prepare(`SELECT id FROM documents d WHERE content_hash = ? AND deleted_at IS NULL AND ${notAdded} ORDER BY id`)
|
|
300
311
|
.all(hash);
|
|
301
312
|
if (live.length)
|
|
302
313
|
return live.map(({ id }) => Number(id));
|
|
303
314
|
return database
|
|
304
|
-
.prepare(
|
|
315
|
+
.prepare(`SELECT d.id FROM documents d WHERE d.content_hash = ? AND d.deleted_at IS NOT NULL AND ${notAdded} AND NOT EXISTS ` +
|
|
305
316
|
"(SELECT 1 FROM files f WHERE f.document_id = d.id AND f.deleted_at IS NULL) ORDER BY d.id")
|
|
306
317
|
.all(hash)
|
|
307
318
|
.map(({ id }) => Number(id));
|
|
@@ -330,7 +341,7 @@ export const notesStoreOver = (context) => {
|
|
|
330
341
|
if (blocking?.deleted_at == null && blocking !== undefined)
|
|
331
342
|
return;
|
|
332
343
|
if (blocking)
|
|
333
|
-
database
|
|
344
|
+
deleteDocumentRow(database, Number(blocking.id), at);
|
|
334
345
|
const { location, fileName, extension } = pathParts(path);
|
|
335
346
|
database
|
|
336
347
|
.prepare("UPDATE documents SET account_id = ?, external_id = ?, location = ?, file_name = ?, extension = ?, updated_at = ? WHERE id = ?")
|
|
@@ -370,7 +381,7 @@ export const notesStoreOver = (context) => {
|
|
|
370
381
|
.all(...DOCUMENT_ACCOUNT_PROVIDERS)
|
|
371
382
|
.map(folderOf),
|
|
372
383
|
saveFileNote: async (input) => write(database, () => {
|
|
373
|
-
const folder = Number(folderRow(input.folderId).id);
|
|
384
|
+
const folder = Number(folderRow(input.folderId, true).id);
|
|
374
385
|
const path = textOf(input.path, "a note's path", 4096);
|
|
375
386
|
const text = textOf(input.text, "a note's text", MAX_TEXT_CHARS, true);
|
|
376
387
|
const frontMatter = input.frontMatter == null ? null : JSON.stringify(input.frontMatter);
|
|
@@ -442,7 +453,7 @@ export const notesStoreOver = (context) => {
|
|
|
442
453
|
return { note: noteAt(id, folder, path), changed: !same };
|
|
443
454
|
}),
|
|
444
455
|
renameFileNote: async (folderId, from, to) => write(database, () => {
|
|
445
|
-
const folder = Number(folderRow(folderId).id);
|
|
456
|
+
const folder = Number(folderRow(folderId, true).id);
|
|
446
457
|
const target = textOf(to, "a note's path", 4096);
|
|
447
458
|
const at = now();
|
|
448
459
|
const place = fileAt(folder, from, true);
|
|
@@ -462,7 +473,7 @@ export const notesStoreOver = (context) => {
|
|
|
462
473
|
throw new CliError("validation_error", `a live note is already at ${target} in folder ${folderId}`);
|
|
463
474
|
// The gone note at the target goes, as it always did; its file row goes with it or on its own.
|
|
464
475
|
if (taken)
|
|
465
|
-
database
|
|
476
|
+
deleteDocumentRow(database, Number(taken.id), now());
|
|
466
477
|
if (takenFile)
|
|
467
478
|
database.prepare("DELETE FROM files WHERE id = ?").run(Number(takenFile.id));
|
|
468
479
|
if (place)
|
|
@@ -487,9 +498,9 @@ export const notesStoreOver = (context) => {
|
|
|
487
498
|
});
|
|
488
499
|
return noteAt(id, folder, target);
|
|
489
500
|
}),
|
|
490
|
-
dateFileNotes: async (folderId, dates) => write(database, () => dateFileNotes(database, Number(folderRow(folderId).id), dates)),
|
|
501
|
+
dateFileNotes: async (folderId, dates) => write(database, () => dateFileNotes(database, Number(folderRow(folderId, true).id), dates)),
|
|
491
502
|
deleteFileNotes: async (folderId, paths) => write(database, () => {
|
|
492
|
-
const folder = Number(folderRow(folderId).id);
|
|
503
|
+
const folder = Number(folderRow(folderId, true).id);
|
|
493
504
|
let deleted = 0;
|
|
494
505
|
for (const path of paths) {
|
|
495
506
|
const at = now();
|
|
@@ -613,6 +624,7 @@ export const notesStoreOver = (context) => {
|
|
|
613
624
|
throw new CliError("validation_error", "a file note goes when its file does; the next import notices");
|
|
614
625
|
const bare = id.replace(/^note:/, "");
|
|
615
626
|
noteRow(bare);
|
|
627
|
+
forgetEvidenceToRow(database, { type: "note", id: Number(bare) }, now());
|
|
616
628
|
database.prepare("DELETE FROM notes WHERE id = ?").run(Number(bare));
|
|
617
629
|
return { id, removed: true };
|
|
618
630
|
}),
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { type OrderDirection } from "../../domain/business.js";
|
|
1
2
|
import { type FinanceReview } from "../../domain/finance.js";
|
|
2
3
|
import { type OrderPurpose, type OrderStatus } from "../../domain/orders.js";
|
|
3
|
-
import {
|
|
4
|
+
import type { Decider } from "../decisions.js";
|
|
4
5
|
import { type ProposedByFilter } from "./actors.js";
|
|
5
|
-
import { type Party, type Reviewed, type Written } from "./finance.js";
|
|
6
6
|
import { type Author } from "./memories.js";
|
|
7
|
+
import { type MoneyLine, type MoneyLineInput } from "./money-lines.js";
|
|
7
8
|
import type { StoreContext } from "./open.js";
|
|
9
|
+
import { type Party, type Reviewed, type Written } from "./reviewed.js";
|
|
8
10
|
export interface Order extends Reviewed {
|
|
9
11
|
id: string;
|
|
10
12
|
ref: string;
|
|
@@ -28,15 +30,23 @@ export interface Order extends Reviewed {
|
|
|
28
30
|
payment: string | null;
|
|
29
31
|
/** The order's page at the shop, http or https. */
|
|
30
32
|
sourceUrl: string | null;
|
|
33
|
+
/** `sale` when the owner sells: he is then its supplier. */
|
|
34
|
+
direction: OrderDirection;
|
|
35
|
+
contract: string | null;
|
|
36
|
+
deal: string | null;
|
|
37
|
+
}
|
|
38
|
+
export interface OrderDetail extends Order {
|
|
39
|
+
lines: MoneyLine[];
|
|
31
40
|
}
|
|
32
41
|
export interface OrderInput extends Written {
|
|
33
42
|
/** `person:` or `organization:`; the owner's own person when left out. */
|
|
34
43
|
customer?: string;
|
|
35
44
|
purpose: OrderPurpose;
|
|
36
45
|
supplier?: string;
|
|
37
|
-
|
|
46
|
+
/** Required for a purchase; a sale takes the supplier's name, the owner's by default. */
|
|
47
|
+
supplierName?: string;
|
|
38
48
|
number?: string;
|
|
39
|
-
/** A decimal string in `currency`; give both or neither. */
|
|
49
|
+
/** A decimal string in `currency`; give both or neither. With lines it is their sum, refused when it differs. */
|
|
40
50
|
total?: string;
|
|
41
51
|
currency?: string;
|
|
42
52
|
/** `placed` when left out. */
|
|
@@ -47,6 +57,13 @@ export interface OrderInput extends Written {
|
|
|
47
57
|
payment?: string;
|
|
48
58
|
/** The order's page at the shop: an http or https address. */
|
|
49
59
|
sourceUrl?: string;
|
|
60
|
+
/** `purchase` when left out. A sale names its customer, and its supplier is the owner's own person by default. */
|
|
61
|
+
direction?: OrderDirection;
|
|
62
|
+
contract?: string;
|
|
63
|
+
/** The deal it came from, when no contract sits between. */
|
|
64
|
+
deal?: string;
|
|
65
|
+
/** With lines the order has a currency and totals their sum. */
|
|
66
|
+
lines?: MoneyLineInput[];
|
|
50
67
|
}
|
|
51
68
|
export interface OrderFilter {
|
|
52
69
|
status?: OrderStatus;
|
|
@@ -66,8 +83,8 @@ export interface OrderFilter {
|
|
|
66
83
|
* confirmed at once; an agent's waits as proposed for him, and only he decides it.
|
|
67
84
|
*/
|
|
68
85
|
export interface OrdersStore {
|
|
69
|
-
add(input: OrderInput): Promise<
|
|
70
|
-
get(reference: string): Promise<
|
|
86
|
+
add(input: OrderInput): Promise<OrderDetail>;
|
|
87
|
+
get(reference: string): Promise<OrderDetail>;
|
|
71
88
|
list(filter?: OrderFilter): Promise<Order[]>;
|
|
72
89
|
/** The owner moves an order on, such as a later mail saying it shipped; `date` is the delivery day. */
|
|
73
90
|
setStatus(reference: string, input: {
|
|
@@ -77,6 +94,19 @@ export interface OrdersStore {
|
|
|
77
94
|
}): Promise<Order>;
|
|
78
95
|
confirm(reference: string, by: Decider, reason?: string): Promise<Order>;
|
|
79
96
|
reject(reference: string, by: Decider, reason?: string): Promise<Order>;
|
|
97
|
+
/**
|
|
98
|
+
* Everything an add sets, again: the owner on any order, a bot only on one it proposed that is still proposed, as
|
|
99
|
+
* an import does when its source changed the order. Its lines are replaced; who wrote it and its review stay.
|
|
100
|
+
*/
|
|
101
|
+
revise(reference: string, input: OrderInput): Promise<OrderDetail>;
|
|
102
|
+
/** A line at the end; the owner changes any order's lines, a bot only those of an order it proposed still proposed. */
|
|
103
|
+
addLine(reference: string, input: MoneyLineInput & {
|
|
104
|
+
by: Author;
|
|
105
|
+
}): Promise<OrderDetail>;
|
|
106
|
+
removeLine(reference: string, input: {
|
|
107
|
+
position: number;
|
|
108
|
+
by: Author;
|
|
109
|
+
}): Promise<OrderDetail>;
|
|
80
110
|
}
|
|
81
111
|
type OrderOperations = {
|
|
82
112
|
[K in keyof OrdersStore]: OrdersStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
|
|
@@ -1,20 +1,23 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { ORDER_DIRECTIONS } from "../../domain/business.js";
|
|
2
3
|
import { sourceUrlOf } from "../../domain/external-links.js";
|
|
3
4
|
import { FINANCE_REVIEWS } from "../../domain/finance.js";
|
|
4
|
-
import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
|
|
5
|
+
import { currencyOf, formatDecimal, minorUnits, moneyLabel, scaleOf } from "../../domain/money.js";
|
|
5
6
|
import { ORDER_PURPOSES, ORDER_STATUSES, orderTitle } from "../../domain/orders.js";
|
|
6
|
-
import { assertMayDecide, deciderAuthor } from "../decisions.js";
|
|
7
7
|
import { fold } from "../normalize.js";
|
|
8
|
-
import { ownerPerson, proposedBySql
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
8
|
+
import { ownerPerson, proposedBySql } from "./actors.js";
|
|
9
|
+
import { projectId } from "./memories.js";
|
|
10
|
+
import { moneyLinesOver } from "./money-lines.js";
|
|
11
11
|
import { requiredThing } from "./notes.js";
|
|
12
|
+
import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
|
|
12
13
|
import { write } from "./transaction.js";
|
|
14
|
+
const MAX_LINES = 500;
|
|
13
15
|
const ORDERS = "SELECT o.*, b.name AS author_name, b.kind AS author_kind FROM orders o " +
|
|
14
16
|
"LEFT JOIN bots b ON o.author_type = 'bot' AND b.id = o.author_id";
|
|
15
17
|
export const orderOperationsOver = (context) => {
|
|
16
18
|
const { database, now } = context;
|
|
17
|
-
const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly,
|
|
19
|
+
const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
|
|
20
|
+
const moneyLines = moneyLinesOver(context);
|
|
18
21
|
const orderOf = (row) => {
|
|
19
22
|
const currency = row.currency == null ? null : String(row.currency);
|
|
20
23
|
const total = row.total == null || currency === null ? null : Number(row.total);
|
|
@@ -44,82 +47,123 @@ export const orderOperationsOver = (context) => {
|
|
|
44
47
|
invoice: row.invoice_id == null ? null : `invoice:${row.invoice_id}`,
|
|
45
48
|
payment: row.payment_id == null ? null : `payment:${row.payment_id}`,
|
|
46
49
|
sourceUrl: row.source_url == null ? null : String(row.source_url),
|
|
50
|
+
direction: row.direction,
|
|
51
|
+
contract: row.contract_id == null ? null : `contract:${row.contract_id}`,
|
|
52
|
+
deal: row.deal_id == null ? null : `deal:${row.deal_id}`,
|
|
47
53
|
...reviewedOf(row, "order"),
|
|
48
54
|
};
|
|
49
55
|
};
|
|
56
|
+
const detailOf = (row) => ({
|
|
57
|
+
...orderOf(row),
|
|
58
|
+
lines: row.currency == null ? [] : moneyLines.shownLines("order", Number(row.id), String(row.currency)),
|
|
59
|
+
});
|
|
60
|
+
/** The order's total follows its lines in the same write: the trigger checks the sum when the order changes. */
|
|
61
|
+
const retotal = (orderId) => {
|
|
62
|
+
database
|
|
63
|
+
.prepare("UPDATE orders SET total = coalesce((SELECT sum(amount) FROM order_lines WHERE order_id = ?), total), " +
|
|
64
|
+
"updated_at = ? WHERE id = ?")
|
|
65
|
+
.run(orderId, now(), orderId);
|
|
66
|
+
};
|
|
67
|
+
const mayChangeLines = (row, by) => {
|
|
68
|
+
mayChangeParts(row, by, `only the owner changes the lines of order:${row.id}; a bot changes only an order it proposed that is still proposed`, "order.owner-only");
|
|
69
|
+
if (row.review === "rejected" || row.deleted_at != null)
|
|
70
|
+
refuse(`order:${row.id} is ${row.deleted_at != null ? "deleted" : "rejected"}`, "order.status");
|
|
71
|
+
};
|
|
50
72
|
const rowOf = (reference) => {
|
|
51
73
|
const thing = requiredThing(database, reference.includes(":") ? reference : `order:${reference}`, "the order");
|
|
52
74
|
if (thing.type !== "order")
|
|
53
75
|
return refuse(`${reference} is not an order`, "order.ref");
|
|
54
76
|
return database.prepare(`${ORDERS} WHERE o.id = ?`).get(thing.id);
|
|
55
77
|
};
|
|
56
|
-
const linked = (reference, type) =>
|
|
57
|
-
if (reference === undefined)
|
|
58
|
-
return null;
|
|
59
|
-
const thing = requiredThing(database, reference, `the ${type}`);
|
|
60
|
-
if (thing.type !== type)
|
|
61
|
-
return refuse(`${reference} is not an ${type}: reference`, "order.ref");
|
|
62
|
-
return thing.id;
|
|
63
|
-
};
|
|
78
|
+
const linked = (reference, type) => linkedId(reference, type, "order.ref");
|
|
64
79
|
const statusOf = (value) => oneOf(value, ORDER_STATUSES, "an order's status");
|
|
65
80
|
const decide = (reference, by, reason, confirm) => {
|
|
66
81
|
const row = rowOf(reference);
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (row.review !== "proposed")
|
|
70
|
-
refuse(`${ref} is already ${String(row.review)}`, "proposal.wrong-state");
|
|
71
|
-
write(database, () => {
|
|
72
|
-
if (confirm) {
|
|
73
|
-
const { actor } = authorActor(context, deciderAuthor(by));
|
|
74
|
-
database
|
|
75
|
-
.prepare("UPDATE orders SET review = 'confirmed', confirmed_by_type = ?, confirmed_by_id = ?, updated_at = ? WHERE id = ?")
|
|
76
|
-
.run(actor.type, actor.id, now(), Number(row.id));
|
|
77
|
-
}
|
|
78
|
-
else
|
|
79
|
-
database
|
|
80
|
-
.prepare("UPDATE orders SET review = 'rejected', updated_at = ? WHERE id = ?")
|
|
81
|
-
.run(now(), Number(row.id));
|
|
82
|
-
keepDecision("orders", Number(row.id), by, reason);
|
|
83
|
-
});
|
|
84
|
-
return orderOf(rowOf(ref));
|
|
82
|
+
decideRow("order", row, { by, reason, confirm });
|
|
83
|
+
return orderOf(rowOf(`order:${row.id}`));
|
|
85
84
|
};
|
|
86
|
-
|
|
87
|
-
|
|
85
|
+
/** Checks an add's input and writes it: a new order, or `held`'s columns and lines replaced. */
|
|
86
|
+
const save = (input, held) => {
|
|
87
|
+
{
|
|
88
88
|
const purpose = oneOf(input.purpose, ORDER_PURPOSES, "an order's purpose");
|
|
89
|
+
const direction = input.direction === undefined ? "purchase" : oneOf(input.direction, ORDER_DIRECTIONS, "a direction");
|
|
89
90
|
const status = input.status === undefined ? "placed" : statusOf(input.status);
|
|
90
|
-
const
|
|
91
|
+
const named = text(input.supplierName, "an order's supplier name", 200);
|
|
92
|
+
if (named === null && direction === "purchase")
|
|
91
93
|
refuse("an order names its shop or supplier", "order.field");
|
|
94
|
+
if (direction === "sale" && input.customer === undefined)
|
|
95
|
+
refuse("a sale names its customer, a person: or organization:", "order.field");
|
|
92
96
|
const number = text(input.number, "an order's number", 80);
|
|
93
|
-
|
|
97
|
+
const lines = input.lines ?? [];
|
|
98
|
+
if (!Array.isArray(lines) || lines.length > MAX_LINES)
|
|
99
|
+
refuse(`an order has at most ${MAX_LINES} lines`, "order.field");
|
|
100
|
+
if (lines.length && input.currency === undefined)
|
|
101
|
+
refuse("an order with lines names its currency", "order.total");
|
|
102
|
+
if (!lines.length && (input.total === undefined) !== (input.currency === undefined))
|
|
94
103
|
refuse("an order's amount and currency come together", "order.field");
|
|
95
104
|
const currency = input.currency === undefined ? null : currencyOf(input.currency);
|
|
96
|
-
const
|
|
105
|
+
const priced = currency === null ? [] : moneyLines.linesOf("order", lines, currency);
|
|
106
|
+
const sum = priced.reduce((all, line) => all + line.amount, 0);
|
|
107
|
+
const given = currency === null || input.total === undefined ? null : minorUnits(input.total, currency, "an order's amount");
|
|
108
|
+
if (priced.length && given !== null && given !== sum)
|
|
109
|
+
refuse(`the order's total ${moneyLabel(given, currency)} is not the sum of its lines, ` +
|
|
110
|
+
`${moneyLabel(sum, currency)}`, "order.total");
|
|
111
|
+
const total = priced.length ? sum : given;
|
|
97
112
|
if (total !== null && total < 0)
|
|
98
113
|
refuse("an order's amount is 0 or more", "money.amount");
|
|
99
114
|
const orderDate = isoDate(input.orderDate, "an order's date");
|
|
100
115
|
const fulfilledDate = isoDate(input.fulfilledDate, "an order's delivery date");
|
|
101
116
|
const sourceUrl = input.sourceUrl === undefined ? null : sourceUrlOf(input.sourceUrl, "order.source-url");
|
|
102
117
|
const id = write(database, () => {
|
|
103
|
-
if (number !== null && ordersOfShop(database, supplierName, number).length)
|
|
104
|
-
refuse(`order ${number} from ${supplierName} is already stored; change its status instead`, "order.duplicate");
|
|
105
118
|
const customer = partyThing(input.customer, "the customer") ?? ownerPerson(database);
|
|
106
|
-
const supplier = partyThing(input.supplier, "the supplier");
|
|
119
|
+
const supplier = partyThing(input.supplier, "the supplier") ?? (direction === "sale" ? ownerPerson(database) : undefined);
|
|
120
|
+
const party = partyOf(supplier?.type, supplier?.id);
|
|
121
|
+
const supplierName = named ?? party?.name ?? (party?.owner ? "owner" : null);
|
|
122
|
+
if (supplierName === null)
|
|
123
|
+
return refuse("an order names its shop or supplier", "order.field");
|
|
124
|
+
if (number !== null &&
|
|
125
|
+
ordersOfShop(database, supplierName, number).some((one) => held === undefined || one.id !== held.id))
|
|
126
|
+
refuse(`order ${number} from ${supplierName} is already stored; change its status instead`, "order.duplicate");
|
|
107
127
|
const invoice = linked(input.invoice, "invoice");
|
|
108
128
|
const payment = linked(input.payment, "payment");
|
|
109
|
-
const
|
|
129
|
+
const contract = linked(input.contract, "contract");
|
|
130
|
+
const deal = linked(input.deal, "deal");
|
|
110
131
|
const at = now();
|
|
132
|
+
if (held !== undefined) {
|
|
133
|
+
const id = Number(held.id);
|
|
134
|
+
database.prepare("DELETE FROM order_lines WHERE order_id = ?").run(id);
|
|
135
|
+
database
|
|
136
|
+
.prepare("UPDATE orders SET customer_type = ?, customer_id = ?, purpose = ?, supplier_type = ?, supplier_id = ?, " +
|
|
137
|
+
"supplier_name = ?, number = ?, currency = ?, total = ?, status = ?, order_date = ?, " +
|
|
138
|
+
"fulfilled_date = ?, invoice_id = ?, payment_id = ?, project_id = ?, source_url = ?, direction = ?, " +
|
|
139
|
+
"contract_id = ?, deal_id = ?, updated_at = ? WHERE id = ?")
|
|
140
|
+
.run(customer.type, customer.id, purpose, supplier?.type ?? null, supplier?.id ?? null, supplierName, number, currency, total, status, orderDate, fulfilledDate, invoice, payment, input.project === undefined ? null : projectId(database, input.project), sourceUrl, direction, contract, deal, at, id);
|
|
141
|
+
moneyLines.insertLines("order", id, priced, 1, at);
|
|
142
|
+
return id;
|
|
143
|
+
}
|
|
144
|
+
const by = written(input);
|
|
111
145
|
const made = Number(database
|
|
112
146
|
.prepare("INSERT INTO orders (customer_type, customer_id, purpose, supplier_type, supplier_id, supplier_name, number, " +
|
|
113
147
|
"currency, total, status, order_date, fulfilled_date, invoice_id, payment_id, project_id, review, " +
|
|
114
148
|
"author_type, author_id, model, confirmed_by_type, confirmed_by_id, source, metadata, created_at, updated_at, " +
|
|
115
|
-
"source_url
|
|
116
|
-
|
|
149
|
+
"source_url, direction, contract_id, deal_id) " +
|
|
150
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
151
|
+
.get(customer.type, customer.id, purpose, supplier?.type ?? null, supplier?.id ?? null, supplierName, number, currency, total, status, orderDate, fulfilledDate, invoice, payment, by.project, by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at, sourceUrl, direction, contract, deal)?.id);
|
|
152
|
+
moneyLines.insertLines("order", made, priced, 1, at);
|
|
117
153
|
keepEvidence("order", made, by);
|
|
118
154
|
return made;
|
|
119
155
|
});
|
|
120
|
-
return
|
|
156
|
+
return id;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
return {
|
|
160
|
+
add: (input) => detailOf(rowOf(`order:${save(input)}`)),
|
|
161
|
+
revise: (reference, input) => {
|
|
162
|
+
const row = rowOf(reference);
|
|
163
|
+
mayChangeLines(row, input.by);
|
|
164
|
+
return detailOf(rowOf(`order:${save(input, row)}`));
|
|
121
165
|
},
|
|
122
|
-
get: (reference) =>
|
|
166
|
+
get: (reference) => detailOf(rowOf(reference)),
|
|
123
167
|
list: (filter = {}) => {
|
|
124
168
|
const project = filter.project === undefined ? null : projectId(database, filter.project);
|
|
125
169
|
const customer = partyThing(filter.customer, "the customer");
|
|
@@ -129,7 +173,7 @@ export const orderOperationsOver = (context) => {
|
|
|
129
173
|
const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
|
|
130
174
|
const number = filter.number === undefined ? null : filter.number.trim();
|
|
131
175
|
const shop = filter.supplierName === undefined ? null : fold(filter.supplierName);
|
|
132
|
-
const limit =
|
|
176
|
+
const limit = limitOf(filter.limit);
|
|
133
177
|
const rows = database
|
|
134
178
|
.prepare(`${ORDERS} WHERE o.deleted_at IS NULL AND (? IS NULL OR o.status = ?) AND (? IS NULL OR o.purpose = ?) ` +
|
|
135
179
|
"AND (? IS NULL OR o.review = ?) AND (? IS NULL OR o.project_id = ?) AND (? IS NULL OR o.number = ?) " +
|
|
@@ -157,6 +201,39 @@ export const orderOperationsOver = (context) => {
|
|
|
157
201
|
},
|
|
158
202
|
confirm: (reference, by, reason) => decide(reference, by, reason, true),
|
|
159
203
|
reject: (reference, by, reason) => decide(reference, by, reason, false),
|
|
204
|
+
addLine: (reference, { by, ...line }) => {
|
|
205
|
+
const row = rowOf(reference);
|
|
206
|
+
mayChangeLines(row, by);
|
|
207
|
+
if (row.currency == null)
|
|
208
|
+
refuse(`order:${row.id} has no currency; a line needs one`, "order.total");
|
|
209
|
+
const [priced] = moneyLines.linesOf("order", [line], String(row.currency));
|
|
210
|
+
write(database, () => {
|
|
211
|
+
const last = Number(database
|
|
212
|
+
.prepare("SELECT coalesce(max(position), 0) AS n FROM order_lines WHERE order_id = ?")
|
|
213
|
+
.get(Number(row.id))?.n);
|
|
214
|
+
if (last >= MAX_LINES)
|
|
215
|
+
refuse(`an order has at most ${MAX_LINES} lines`, "order.field");
|
|
216
|
+
moneyLines.insertLines("order", Number(row.id), [priced], last + 1, now());
|
|
217
|
+
retotal(Number(row.id));
|
|
218
|
+
});
|
|
219
|
+
return detailOf(rowOf(`order:${row.id}`));
|
|
220
|
+
},
|
|
221
|
+
removeLine: (reference, { position, by }) => {
|
|
222
|
+
const row = rowOf(reference);
|
|
223
|
+
mayChangeLines(row, by);
|
|
224
|
+
write(database, () => {
|
|
225
|
+
const lines = Number(database.prepare("SELECT count(*) AS n FROM order_lines WHERE order_id = ?").get(Number(row.id))?.n);
|
|
226
|
+
const gone = database
|
|
227
|
+
.prepare("DELETE FROM order_lines WHERE order_id = ? AND position = ?")
|
|
228
|
+
.run(Number(row.id), position);
|
|
229
|
+
if (gone.changes === 0)
|
|
230
|
+
throw new CliError("not_found", `order:${row.id} has no line ${position}`, { reason: "order.no-line" });
|
|
231
|
+
if (lines === 1)
|
|
232
|
+
refuse(`line ${position} is the last of order:${row.id}; reject or cancel the order instead`, "order.line");
|
|
233
|
+
retotal(Number(row.id));
|
|
234
|
+
});
|
|
235
|
+
return detailOf(rowOf(`order:${row.id}`));
|
|
236
|
+
},
|
|
160
237
|
};
|
|
161
238
|
};
|
|
162
239
|
/** Orders of one shop with one number that still count: neither rejected nor deleted, the name in any letter case. */
|
|
@@ -185,5 +262,8 @@ export const ordersStoreOver = (context) => {
|
|
|
185
262
|
setStatus: async (reference, input) => operations.setStatus(reference, input),
|
|
186
263
|
confirm: async (reference, by, reason) => operations.confirm(reference, by, reason),
|
|
187
264
|
reject: async (reference, by, reason) => operations.reject(reference, by, reason),
|
|
265
|
+
addLine: async (reference, input) => operations.addLine(reference, input),
|
|
266
|
+
removeLine: async (reference, input) => operations.removeLine(reference, input),
|
|
267
|
+
revise: async (reference, input) => operations.revise(reference, input),
|
|
188
268
|
};
|
|
189
269
|
};
|
|
@@ -9,6 +9,14 @@ export interface OrganizationsStore {
|
|
|
9
9
|
updateOrganization(organization: string, input: {
|
|
10
10
|
name: string;
|
|
11
11
|
}): Promise<Organization>;
|
|
12
|
+
/**
|
|
13
|
+
* The owner says whether an organization is one of his own; a CRM sync never changes his word. `null` hands it back
|
|
14
|
+
* to the CRM's own-company flag.
|
|
15
|
+
*/
|
|
16
|
+
setOwnOrganization(organization: string, own: boolean | null): Promise<{
|
|
17
|
+
ref: string;
|
|
18
|
+
own: boolean;
|
|
19
|
+
}>;
|
|
12
20
|
}
|
|
13
21
|
export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
|
|
14
22
|
export {};
|
|
@@ -45,4 +45,18 @@ export const organizationsStoreOver = ({ database, now }) => ({
|
|
|
45
45
|
throw new CliError("not_found", `no organization ${organization}`);
|
|
46
46
|
return organizationOf(row);
|
|
47
47
|
}),
|
|
48
|
+
setOwnOrganization: async (organization, own) => write(database, () => {
|
|
49
|
+
const thing = thingOf(database, organization.includes(":") ? organization : `organization:${organization}`);
|
|
50
|
+
const set = own === null
|
|
51
|
+
? "json_remove(coalesce(metadata, '{}'), '$.own', '$.own_by')"
|
|
52
|
+
: `json_set(coalesce(metadata, '{}'), '$.own', json('${own}'), '$.own_by', 'owner')`;
|
|
53
|
+
const row = thing?.type === "organization" &&
|
|
54
|
+
database
|
|
55
|
+
.prepare(`UPDATE organizations SET metadata = ${set}, updated_at = ? WHERE id = ? AND deleted_at IS NULL RETURNING id, metadata`)
|
|
56
|
+
.get(now(), thing.id);
|
|
57
|
+
if (!row)
|
|
58
|
+
throw new CliError("not_found", `no organization ${organization}`);
|
|
59
|
+
const metadata = JSON.parse(String(row.metadata ?? "{}"));
|
|
60
|
+
return { ref: `organization:${row.id}`, own: metadata.own === true };
|
|
61
|
+
}),
|
|
48
62
|
});
|
|
@@ -77,7 +77,7 @@ export const movePaymentFacts = (context) => {
|
|
|
77
77
|
keepHighestId(database, "facts", now());
|
|
78
78
|
for (const id of moved.keys()) {
|
|
79
79
|
database.prepare("UPDATE facts SET supersedes_id = NULL WHERE supersedes_id = ?").run(id);
|
|
80
|
-
dropLinksOf(database, { type: "fact", id });
|
|
80
|
+
dropLinksOf(database, { type: "fact", id }, now());
|
|
81
81
|
database.prepare("DELETE FROM links WHERE from_type = 'fact' AND from_id = ?").run(id);
|
|
82
82
|
database.prepare("DELETE FROM taggings WHERE taggable_type = 'fact' AND taggable_id = ?").run(id);
|
|
83
83
|
database.prepare("DELETE FROM facts WHERE id = ?").run(id);
|
|
@@ -42,7 +42,7 @@ export interface PersonPreparationRead {
|
|
|
42
42
|
* The accepted facts, the owner's notes and the open tasks about one person. A project bound to an account is that
|
|
43
43
|
* account's: its facts never come along, and its tasks only when `accounts` holds it.
|
|
44
44
|
*/
|
|
45
|
-
export declare const personPreparation: ({ database }: Pick<StoreContext, "database">, uid: string, { accounts, limit }: {
|
|
45
|
+
export declare const personPreparation: ({ database, now }: Pick<StoreContext, "database" | "now">, uid: string, { accounts, limit }: {
|
|
46
46
|
accounts: readonly AccountKey[];
|
|
47
47
|
limit: number;
|
|
48
48
|
}) => PersonPreparationRead;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { notOverriddenSql, usableLinkSql } from "../../domain/relations.js";
|
|
2
3
|
import { linkKind } from "./link-kinds.js";
|
|
3
4
|
import { taskIdOf } from "./things.js";
|
|
4
5
|
import { read } from "./transaction.js";
|
|
@@ -8,14 +9,14 @@ const iso = (value) => (value == null ? null : new Date(Number(value)).toISOStri
|
|
|
8
9
|
* The accepted facts, the owner's notes and the open tasks about one person. A project bound to an account is that
|
|
9
10
|
* account's: its facts never come along, and its tasks only when `accounts` holds it.
|
|
10
11
|
*/
|
|
11
|
-
export const personPreparation = ({ database }, uid, { accounts, limit }) => {
|
|
12
|
+
export const personPreparation = ({ database, now }, uid, { accounts, limit }) => {
|
|
12
13
|
const person = Number(uid);
|
|
13
14
|
if (!/^[1-9]\d*$/.test(uid) || !Number.isSafeInteger(person) || !Number.isSafeInteger(limit) || limit < 1)
|
|
14
15
|
throw new CliError("validation_error", "person preparation takes a person id and a positive limit");
|
|
15
16
|
const page = (rows) => ({ items: rows.slice(0, limit), hasMore: rows.length > limit });
|
|
16
17
|
return read(database, () => {
|
|
17
18
|
const projects = `SELECT l.to_id FROM links l WHERE l.from_type='person' AND l.from_id=? AND l.to_type='project'
|
|
18
|
-
AND l.kind=${linkKind("member-of")} AND l
|
|
19
|
+
AND l.kind=${linkKind("member-of")} AND ${usableLinkSql("l", now())} AND ${notOverriddenSql("l")} AND l.to_id IN (${GLOBAL_PROJECT})`;
|
|
19
20
|
const facts = database
|
|
20
21
|
.prepare(`SELECT f.id,f.type,f.statement,f.subject_type,f.subject_id,f.project_id,f.updated_at FROM facts f
|
|
21
22
|
WHERE f.status='accepted' AND f.deleted_at IS NULL
|