@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,12 +1,14 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { MEMORY_KINDS, MEMORY_SCOPES } from "../../domain/knowledge.js";
|
|
3
|
-
import { assertMayDecide, assertMayWithdraw } from "../decisions.js";
|
|
3
|
+
import { assertMayDecide, assertMayWithdraw, deciderAuthor } from "../decisions.js";
|
|
4
4
|
import { normalize } from "../normalize.js";
|
|
5
5
|
import { botNamed, ownerPerson, proposedBySql, proposerOf } from "./actors.js";
|
|
6
|
+
import { assertQuoted, evidenceInputOf, evidenceMetadata, evidenceSignature, forgetEvidenceToRow, } from "./evidence-signature.js";
|
|
6
7
|
import { evidenceSourcesOf } from "./evidence-sources.js";
|
|
7
8
|
import { linkKind } from "./link-kinds.js";
|
|
8
9
|
import { CORPORA, corpusIndexState, drainCorpus } from "./note-index.js";
|
|
9
10
|
import { requiredThing } from "./notes.js";
|
|
11
|
+
import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
|
|
10
12
|
import { stemmerCache } from "./stems.js";
|
|
11
13
|
import { referenceOfThing, storedThing } from "./things.js";
|
|
12
14
|
import { write } from "./transaction.js";
|
|
@@ -31,14 +33,19 @@ export const authorOf = (row) => ({
|
|
|
31
33
|
name: row.author_name == null ? null : String(row.author_name),
|
|
32
34
|
kind: row.author_type !== "bot" ? null : row.author_kind === "rule" || row.author_name === "rule" ? "rule" : "agent",
|
|
33
35
|
});
|
|
34
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Writes `evidence` links from a row to each reference, refusing one the store does not hold. Each link keeps the
|
|
38
|
+
* source's signature and the quote it was given, so a later check sees whether the source still says it.
|
|
39
|
+
*/
|
|
35
40
|
export const linkEvidence = (context, from, references, author) => {
|
|
36
41
|
const at = context.now();
|
|
37
|
-
const insert = context.database.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, confirmed, created_at, author, updated_at) " +
|
|
38
|
-
`VALUES (?, ?, ?, ?, ${linkKind("evidence")}, ?, 1, ?, ?, ?)`);
|
|
39
|
-
for (const
|
|
40
|
-
const thing = requiredThing(context.database,
|
|
41
|
-
|
|
42
|
+
const insert = context.database.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, source, metadata, confirmed, created_at, author, updated_at) " +
|
|
43
|
+
`VALUES (?, ?, ?, ?, ${linkKind("evidence")}, ?, ?, 1, ?, ?, ?)`);
|
|
44
|
+
for (const { ref, quote } of references.map(evidenceInputOf)) {
|
|
45
|
+
const thing = requiredThing(context.database, ref, "the evidence");
|
|
46
|
+
assertQuoted(context.database, thing, ref, quote);
|
|
47
|
+
const metadata = evidenceMetadata(evidenceSignature(context.database, thing), at, quote);
|
|
48
|
+
insert.run(from.type, from.id, thing.type, thing.id, author === "owner" ? "owner" : "suggested", JSON.stringify(metadata), at, author, at);
|
|
42
49
|
}
|
|
43
50
|
};
|
|
44
51
|
export const evidenceOf = (context, from) => context.database
|
|
@@ -97,13 +104,17 @@ export const keepHighestId = (database, table, at) => {
|
|
|
97
104
|
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
98
105
|
.run(highestKey(table), String(highest), at);
|
|
99
106
|
};
|
|
100
|
-
/**
|
|
101
|
-
|
|
107
|
+
/**
|
|
108
|
+
* Counts every link from or to a row and drops the ones its delete trigger does not: those pointing at it. Evidence
|
|
109
|
+
* that cites it stays, with no pointer, so a memory or fact that rested on it still shows a source that went.
|
|
110
|
+
*/
|
|
111
|
+
export const dropLinksOf = (database, thing, at) => {
|
|
102
112
|
const count = Number(database
|
|
103
113
|
.prepare("SELECT count(*) AS n FROM links WHERE (from_type = ? AND from_id = ?) OR (to_type = ? AND to_id = ?)")
|
|
104
114
|
.get(thing.type, thing.id, thing.type, thing.id)?.n);
|
|
115
|
+
const kept = forgetEvidenceToRow(database, storedThing(thing.type, thing.id), at).length;
|
|
105
116
|
database.prepare("DELETE FROM links WHERE to_type = ? AND to_id = ?").run(thing.type, thing.id);
|
|
106
|
-
return count;
|
|
117
|
+
return count - kept;
|
|
107
118
|
};
|
|
108
119
|
/**
|
|
109
120
|
* Runs a delete so the text does not linger in the file: freed pages are zeroed, the words indexes merged so no
|
|
@@ -142,6 +153,7 @@ export const memoriesStoreOver = (context) => {
|
|
|
142
153
|
scope: row.scope,
|
|
143
154
|
supersedes: row.supersedes_id == null ? null : `memory:${row.supersedes_id}`,
|
|
144
155
|
evidence: evidenceOf(context, { type: "memory", id: Number(row.id) }),
|
|
156
|
+
sourceReview: sourceReviewOf(database, { type: "memory", id: Number(row.id) }),
|
|
145
157
|
lastVerifiedAt: row.last_verified_at == null ? null : iso(row.last_verified_at),
|
|
146
158
|
createdAt: iso(row.created_at),
|
|
147
159
|
updatedAt: iso(row.updated_at),
|
|
@@ -155,10 +167,26 @@ export const memoriesStoreOver = (context) => {
|
|
|
155
167
|
throw new CliError("not_found", `${reference} is a fact now: store.facts holds it`);
|
|
156
168
|
return row;
|
|
157
169
|
};
|
|
158
|
-
const decided = (reference, by) => {
|
|
170
|
+
const decided = (reference, by, ownerOnly = false) => {
|
|
171
|
+
const row = rowOf(reference);
|
|
172
|
+
assertMayDecide({ id: `memory:${row.id}`, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly }, by, context.decisions);
|
|
173
|
+
};
|
|
174
|
+
const alreadySuperseded = (id) => new CliError("validation_error", `memory:${id} is already superseded; correct the one that replaced it`, {
|
|
175
|
+
reason: "memory.already-superseded",
|
|
176
|
+
});
|
|
177
|
+
const replaceable = (reference) => {
|
|
159
178
|
const row = rowOf(reference);
|
|
160
|
-
|
|
179
|
+
if (row.status === "superseded")
|
|
180
|
+
throw alreadySuperseded(row.id);
|
|
181
|
+
return row;
|
|
161
182
|
};
|
|
183
|
+
/**
|
|
184
|
+
* A correction retired the memory if it was ever confirmed. An older store let an agent's proposal retire it at
|
|
185
|
+
* once, so a memory superseded only by the one being confirmed is not refused.
|
|
186
|
+
*/
|
|
187
|
+
const retiredByAnother = (replaced, by) => database
|
|
188
|
+
.prepare("SELECT 1 FROM memories WHERE supersedes_id = ? AND id <> ? AND last_verified_at IS NOT NULL LIMIT 1")
|
|
189
|
+
.get(replaced, by) !== undefined;
|
|
162
190
|
const setStatus = (reference, status, verified) => {
|
|
163
191
|
const row = rowOf(reference);
|
|
164
192
|
const at = now();
|
|
@@ -167,6 +195,11 @@ export const memoriesStoreOver = (context) => {
|
|
|
167
195
|
.run(...(verified ? [status, at, at, Number(row.id)] : [status, at, Number(row.id)]));
|
|
168
196
|
return memoryOf(rowOf(reference));
|
|
169
197
|
};
|
|
198
|
+
const closing = (by, why) => ({
|
|
199
|
+
actor: authorActor(context, deciderAuthor(by)).actor,
|
|
200
|
+
at: now(),
|
|
201
|
+
why,
|
|
202
|
+
});
|
|
170
203
|
/** `add` inside the caller's write, so a decision that adds a memory rolls back with it. */
|
|
171
204
|
const addNow = (input) => {
|
|
172
205
|
const kind = oneOf(input.kind, MEMORY_KINDS, "a memory's kind");
|
|
@@ -193,7 +226,7 @@ export const memoriesStoreOver = (context) => {
|
|
|
193
226
|
const { actor, model } = authorActor(context, input.author);
|
|
194
227
|
const subject = input.subject === undefined ? undefined : requiredThing(database, input.subject, "the subject");
|
|
195
228
|
const project = input.project === undefined ? null : projectId(database, input.project);
|
|
196
|
-
const replaced = input.supersedes === undefined ? undefined : Number(
|
|
229
|
+
const replaced = input.supersedes === undefined ? undefined : Number(replaceable(input.supersedes).id);
|
|
197
230
|
const at = now();
|
|
198
231
|
const made = Number(database
|
|
199
232
|
.prepare("INSERT INTO memories (id, kind, body, subject_type, subject_id, author_type, author_id, model, confidence, status, " +
|
|
@@ -201,16 +234,29 @@ export const memoriesStoreOver = (context) => {
|
|
|
201
234
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
202
235
|
.get(nextId(database, "memories"), kind, body, subject?.type ?? null, subject?.id ?? null, actor.type, actor.id, model, input.confidence ?? null, status, status === "confirmed" ? at : null, replaced ?? null, scope, project, at, at)?.id);
|
|
203
236
|
linkEvidence(context, { type: "memory", id: made }, input.evidence, input.author === "owner" ? "owner" : "agent");
|
|
204
|
-
if (replaced !== undefined)
|
|
237
|
+
if (replaced !== undefined && status === "confirmed") {
|
|
205
238
|
database.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?").run(at, replaced);
|
|
239
|
+
closeSourceReviews(database, { type: "memory", id: replaced }, { actor, at, why: "superseded" });
|
|
240
|
+
}
|
|
206
241
|
return made;
|
|
207
242
|
});
|
|
208
243
|
return memoryOf(rowOf(`memory:${id}`));
|
|
209
244
|
};
|
|
210
|
-
|
|
211
|
-
|
|
245
|
+
/** Applies a pending correction; only the owner retires a confirmed memory, whatever `agent_decisions` says. */
|
|
246
|
+
const confirmNow = (reference, by) => write(database, () => {
|
|
247
|
+
const row = rowOf(reference);
|
|
248
|
+
const replaced = row.status === "confirmed" || row.supersedes_id == null ? undefined : rowOf(`memory:${row.supersedes_id}`);
|
|
249
|
+
decided(reference, by, replaced?.status === "confirmed");
|
|
250
|
+
if (replaced !== undefined) {
|
|
251
|
+
if (retiredByAnother(Number(replaced.id), Number(row.id)))
|
|
252
|
+
throw alreadySuperseded(replaced.id);
|
|
253
|
+
database
|
|
254
|
+
.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?")
|
|
255
|
+
.run(now(), Number(replaced.id));
|
|
256
|
+
closeSourceReviews(database, { type: "memory", id: Number(replaced.id) }, closing(by, "superseded"));
|
|
257
|
+
}
|
|
212
258
|
return setStatus(reference, "confirmed", true);
|
|
213
|
-
};
|
|
259
|
+
});
|
|
214
260
|
return {
|
|
215
261
|
addNow,
|
|
216
262
|
confirmNow,
|
|
@@ -235,8 +281,15 @@ export const memoriesStoreOver = (context) => {
|
|
|
235
281
|
}),
|
|
236
282
|
confirm: async (reference, by) => confirmNow(reference, by),
|
|
237
283
|
markStale: async (reference, by) => {
|
|
284
|
+
const row = rowOf(reference);
|
|
285
|
+
if (by !== "owner" && row.status === "confirmed")
|
|
286
|
+
throw new CliError("permission_error", `memory:${row.id} is confirmed; only the owner retires it. Challenge it with what contradicts it instead`, { reason: "proposal.owner-only" });
|
|
238
287
|
decided(reference, by);
|
|
239
|
-
return
|
|
288
|
+
return write(database, () => {
|
|
289
|
+
const memory = setStatus(reference, "stale", false);
|
|
290
|
+
closeSourceReviews(database, { type: "memory", id: Number(row.id) }, closing(by, "invalidated"));
|
|
291
|
+
return memoryOf(rowOf(memory.ref));
|
|
292
|
+
});
|
|
240
293
|
},
|
|
241
294
|
remove: async (reference, by) => {
|
|
242
295
|
const row = rowOf(reference);
|
|
@@ -249,7 +302,8 @@ export const memoriesStoreOver = (context) => {
|
|
|
249
302
|
const links = erase(database, () => {
|
|
250
303
|
keepHighestId(database, "memories", now());
|
|
251
304
|
database.prepare("UPDATE memories SET supersedes_id = NULL WHERE supersedes_id = ?").run(id);
|
|
252
|
-
|
|
305
|
+
eraseSourceReviews(database, { type: "memory", id });
|
|
306
|
+
const count = dropLinksOf(database, { type: "memory", id }, now());
|
|
253
307
|
database.prepare("DELETE FROM memories WHERE id = ?").run(id);
|
|
254
308
|
return count;
|
|
255
309
|
});
|
|
@@ -3,6 +3,7 @@ import { NORMALIZER_VERSION, normalize } from "../normalize.js";
|
|
|
3
3
|
import { findChatPk } from "./chats.js";
|
|
4
4
|
import { applyCounterObservations } from "./counters.js";
|
|
5
5
|
import { and, eq, isNull, sql } from "./drizzle/core.js";
|
|
6
|
+
import { forgetEvidenceToRow } from "./evidence-signature.js";
|
|
6
7
|
import { folded } from "./folded.js";
|
|
7
8
|
import { identityPk } from "./identities.js";
|
|
8
9
|
import { attachments, chats, messageRevisions, messages, messageTranscripts } from "./schema.js";
|
|
@@ -264,6 +265,7 @@ export const tombstone = (context, pk) => {
|
|
|
264
265
|
.prepare("UPDATE attachments SET extraction=NULL, extractor=NULL, extraction_error=NULL, content_sha256=NULL, extracted_at=NULL, updated_at=? WHERE attachable_type='message' AND attachable_id=?")
|
|
265
266
|
.run(now(), pk);
|
|
266
267
|
orm.delete(messageRevisions).where(eq(messageRevisions.messageId, pk)).run();
|
|
268
|
+
forgetEvidenceToRow(context.database, { type: "message", id: pk }, now(), { keepPointer: true });
|
|
267
269
|
context.database
|
|
268
270
|
.prepare("DELETE FROM poll_votes WHERE chat_id=? AND message_external_id=?")
|
|
269
271
|
.run(row.chatId, row.externalId);
|
|
@@ -1060,5 +1060,139 @@ export const GENERATED = [
|
|
|
1060
1060
|
"statements": [
|
|
1061
1061
|
"CREATE INDEX `decision_requests_by_channel_bot_profile_chat_id_message_id` ON `decision_requests` (`channel`,`bot_profile`,`chat_id`,`message_id`);"
|
|
1062
1062
|
]
|
|
1063
|
+
},
|
|
1064
|
+
{
|
|
1065
|
+
"name": "20261107162427_version-56-relationship-links",
|
|
1066
|
+
"statements": [
|
|
1067
|
+
"CREATE TABLE `link_revisions` (\n\t`id` integer PRIMARY KEY,\n\t`link_id` integer NOT NULL,\n\t`change` text NOT NULL,\n\t`before` text,\n\t`after` text,\n\t`author` text,\n\t`account_id` integer,\n\t`created_at` integer NOT NULL\n);",
|
|
1068
|
+
"ALTER TABLE `links` ADD `account_id` integer;",
|
|
1069
|
+
"ALTER TABLE `links` ADD `starts_at` integer;",
|
|
1070
|
+
"ALTER TABLE `links` ADD `ends_at` integer;",
|
|
1071
|
+
"ALTER TABLE `links` ADD `deleted_at` integer;",
|
|
1072
|
+
"CREATE INDEX `link_revisions_by_link_id_created_at` ON `link_revisions` (`link_id`,`created_at`);"
|
|
1073
|
+
]
|
|
1074
|
+
},
|
|
1075
|
+
{
|
|
1076
|
+
"name": "20261107162448_version-56-relationship-links-history",
|
|
1077
|
+
"statements": [
|
|
1078
|
+
"-- A CRM's deal and lead people were stored as the owner's (confirmed = 1): they are the CRM account's report.\nUPDATE links SET confirmed = 0, account_id = (SELECT d.account_id FROM deals d WHERE d.id = links.from_id)\n WHERE source = 'crm' AND kind = 'related-to' AND from_type = 'deal';",
|
|
1079
|
+
"UPDATE links SET confirmed = 0, account_id = (SELECT l.account_id FROM leads l WHERE l.id = links.from_id)\n WHERE source = 'crm' AND kind = 'related-to' AND from_type = 'lead';",
|
|
1080
|
+
"-- The unique key below needs one row per relationship. Of duplicates the owner's row stays, then a confirmed one,\n-- then the oldest; it takes the others' metadata where its own has none, and proposals naming a dropped row name it.\nWITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE links SET metadata = json_patch(\n (SELECT json_group_object(j.key, CASE WHEN j.type IN ('object', 'array') THEN json(j.value) ELSE j.value END)\n FROM link_fold f JOIN links d ON d.id = f.drop_id, json_each(d.metadata) j\n WHERE f.keep_id = links.id AND json_valid(d.metadata)),\n coalesce(links.metadata, '{}'))\n WHERE id IN (SELECT f.keep_id FROM link_fold f JOIN links d ON d.id = f.drop_id\n WHERE d.metadata IS NOT NULL AND json_valid(d.metadata));",
|
|
1081
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE proposed_actions SET payload = json_set(payload, '$.relationship',\n (SELECT CAST(f.keep_id AS TEXT) FROM link_fold f WHERE CAST(f.drop_id AS TEXT) = json_extract(payload, '$.relationship')))\n WHERE kind = 'relationship_update'\n AND json_extract(payload, '$.relationship') IN (SELECT CAST(drop_id AS TEXT) FROM link_fold);",
|
|
1082
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE proposed_actions SET result = json_set(result, '$.link',\n (SELECT CAST(f.keep_id AS TEXT) FROM link_fold f WHERE CAST(f.drop_id AS TEXT) = json_extract(result, '$.link')))\n WHERE json_valid(result) AND json_extract(result, '$.link') IN (SELECT CAST(drop_id AS TEXT) FROM link_fold);",
|
|
1083
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nDELETE FROM links WHERE id IN (SELECT drop_id FROM link_fold);",
|
|
1084
|
+
"CREATE TRIGGER link_revisions_ai AFTER INSERT ON links\n WHEN new.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND new.to_id IS NOT NULL BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (new.id, 'added', NULL,\n json_object('role', new.role, 'confirmed', new.confirmed, 'account_id', new.account_id, 'starts_at', new.starts_at,\n 'ends_at', new.ends_at, 'deleted_at', new.deleted_at),\n new.author, new.account_id, new.updated_at);\nEND;",
|
|
1085
|
+
"-- Only a change a reader sees: a sync that touches `updated_at` alone writes no revision.\nCREATE TRIGGER link_revisions_au AFTER UPDATE OF role, confirmed, account_id, starts_at, ends_at, deleted_at ON links\n WHEN new.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND new.to_id IS NOT NULL\n AND (old.role IS NOT new.role OR old.confirmed IS NOT new.confirmed OR old.account_id IS NOT new.account_id\n OR old.starts_at IS NOT new.starts_at OR old.ends_at IS NOT new.ends_at OR old.deleted_at IS NOT new.deleted_at) BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (new.id,\n CASE\n WHEN old.deleted_at IS NULL AND new.deleted_at IS NOT NULL THEN 'withdrawn'\n WHEN old.deleted_at IS NOT NULL AND new.deleted_at IS NULL THEN 'restored'\n WHEN old.confirmed = 0 AND new.confirmed = 1 THEN 'confirmed'\n WHEN old.ends_at IS NULL AND new.ends_at IS NOT NULL THEN 'ended'\n ELSE 'changed'\n END,\n json_object('role', old.role, 'confirmed', old.confirmed, 'account_id', old.account_id, 'starts_at', old.starts_at,\n 'ends_at', old.ends_at, 'deleted_at', old.deleted_at),\n json_object('role', new.role, 'confirmed', new.confirmed, 'account_id', new.account_id, 'starts_at', new.starts_at,\n 'ends_at', new.ends_at, 'deleted_at', new.deleted_at),\n new.author, new.account_id, new.updated_at);\nEND;",
|
|
1086
|
+
"CREATE TRIGGER link_revisions_ad AFTER DELETE ON links\n WHEN old.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND old.to_id IS NOT NULL BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (old.id,\n -- The store records the rejection, then sets updated_at, then deletes: an older rejection the fold re-pointed is not this one.\n CASE WHEN old.confirmed = 0 AND EXISTS (SELECT 1 FROM proposed_actions p WHERE p.kind = 'relationship'\n AND p.status = 'rejected' AND p.decided_at >= old.updated_at AND json_valid(p.result)\n AND json_extract(p.result, '$.link') = CAST(old.id AS TEXT))\n THEN 'rejected' ELSE 'removed' END,\n json_object('role', old.role, 'confirmed', old.confirmed, 'account_id', old.account_id, 'starts_at', old.starts_at,\n 'ends_at', old.ends_at, 'deleted_at', old.deleted_at),\n NULL, old.author, old.account_id, old.updated_at);\nEND;"
|
|
1087
|
+
]
|
|
1088
|
+
},
|
|
1089
|
+
{
|
|
1090
|
+
"name": "20261107163245_version-56-relationship-links-key",
|
|
1091
|
+
"statements": [
|
|
1092
|
+
"CREATE UNIQUE INDEX `links_relationship_key` ON `links` (`kind`,`from_type`,`from_id`,`to_type`,`to_id`,ifnull(\"anchor\", ''),ifnull(\"role\", ''),ifnull(\"account_id\", 0)) WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL;"
|
|
1093
|
+
]
|
|
1094
|
+
},
|
|
1095
|
+
{
|
|
1096
|
+
"name": "20261108010753_version-57-business",
|
|
1097
|
+
"statements": [
|
|
1098
|
+
"CREATE TABLE `catalog_items` (\n\t`id` integer PRIMARY KEY,\n\t`kind` text NOT NULL,\n\t`name` text NOT NULL,\n\t`name_folded` text NOT NULL,\n\t`sku` text,\n\t`supplier_type` text,\n\t`supplier_id` integer,\n\t`unit` text,\n\t`unit_price` integer,\n\t`currency` text,\n\t`description` text,\n\t`archived_date` text,\n\t`author_type` text NOT NULL,\n\t`author_id` integer NOT NULL,\n\t`model` text,\n\t`source` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`deleted_at` integer\n);",
|
|
1099
|
+
"CREATE TABLE `contracts` (\n\t`id` integer PRIMARY KEY,\n\t`name` text NOT NULL,\n\t`number` text,\n\t`kind` text NOT NULL,\n\t`status` text NOT NULL,\n\t`signed_date` text,\n\t`effective_date` text,\n\t`expiration_date` text,\n\t`auto_renew` integer DEFAULT 0 NOT NULL,\n\t`renewal_count` integer,\n\t`renewal_unit` text,\n\t`notice_days` integer,\n\t`terms` text,\n\t`value` integer,\n\t`currency` text,\n\t`project_id` integer,\n\t`deal_id` integer,\n\t`review` text NOT NULL,\n\t`author_type` text NOT NULL,\n\t`author_id` integer NOT NULL,\n\t`model` text,\n\t`confirmed_by_type` text,\n\t`confirmed_by_id` integer,\n\t`source` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`deleted_at` integer,\n\tCONSTRAINT `fk_contracts_project_id_projects_id_fk` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`),\n\tCONSTRAINT `fk_contracts_deal_id_deals_id_fk` FOREIGN KEY (`deal_id`) REFERENCES `deals`(`id`)\n);",
|
|
1100
|
+
"CREATE TABLE `financial_accounts` (\n\t`id` integer PRIMARY KEY,\n\t`name` text NOT NULL,\n\t`name_folded` text NOT NULL,\n\t`kind` text NOT NULL,\n\t`currency` text NOT NULL,\n\t`institution` text,\n\t`number_hint` text,\n\t`holder_type` text,\n\t`holder_id` integer,\n\t`opening_balance` integer,\n\t`opening_date` text,\n\t`closed_date` text,\n\t`author_type` text NOT NULL,\n\t`author_id` integer NOT NULL,\n\t`model` text,\n\t`source` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`deleted_at` integer\n);",
|
|
1101
|
+
"CREATE TABLE `financial_transactions` (\n\t`id` integer PRIMARY KEY,\n\t`financial_account_id` integer NOT NULL,\n\t`direction` text NOT NULL,\n\t`amount` integer NOT NULL,\n\t`currency` text NOT NULL,\n\t`status` text NOT NULL,\n\t`statement_date` text NOT NULL,\n\t`booked_date` text,\n\t`description` text,\n\t`counterparty_name` text,\n\t`counterparty_type` text,\n\t`counterparty_id` integer,\n\t`reference` text,\n\t`payment_id` integer,\n\t`project_id` integer,\n\t`review` text NOT NULL,\n\t`author_type` text NOT NULL,\n\t`author_id` integer NOT NULL,\n\t`model` text,\n\t`confirmed_by_type` text,\n\t`confirmed_by_id` integer,\n\t`source` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`deleted_at` integer,\n\tCONSTRAINT `fk_financial_transactions_financial_account_id_financial_accounts_id_fk` FOREIGN KEY (`financial_account_id`) REFERENCES `financial_accounts`(`id`),\n\tCONSTRAINT `fk_financial_transactions_payment_id_payments_id_fk` FOREIGN KEY (`payment_id`) REFERENCES `payments`(`id`),\n\tCONSTRAINT `fk_financial_transactions_project_id_projects_id_fk` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`)\n);",
|
|
1102
|
+
"CREATE TABLE `order_lines` (\n\t`id` integer PRIMARY KEY,\n\t`order_id` integer NOT NULL,\n\t`position` integer NOT NULL,\n\t`description` text NOT NULL,\n\t`quantity` text NOT NULL,\n\t`unit_price` integer,\n\t`amount` integer NOT NULL,\n\t`catalog_item_id` integer,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tCONSTRAINT `fk_order_lines_order_id_orders_id_fk` FOREIGN KEY (`order_id`) REFERENCES `orders`(`id`),\n\tCONSTRAINT `fk_order_lines_catalog_item_id_catalog_items_id_fk` FOREIGN KEY (`catalog_item_id`) REFERENCES `catalog_items`(`id`),\n\tCONSTRAINT `order_lines_order_id_position_unique` UNIQUE(`order_id`,`position`)\n);",
|
|
1103
|
+
"CREATE TABLE `subscription_prices` (\n\t`id` integer PRIMARY KEY,\n\t`subscription_id` integer NOT NULL,\n\t`amount` integer NOT NULL,\n\t`currency` text NOT NULL,\n\t`effective_from` text NOT NULL,\n\t`review` text NOT NULL,\n\t`author_type` text NOT NULL,\n\t`author_id` integer NOT NULL,\n\t`model` text,\n\t`confirmed_by_type` text,\n\t`confirmed_by_id` integer,\n\t`source` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tCONSTRAINT `fk_subscription_prices_subscription_id_subscriptions_id_fk` FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`)\n);",
|
|
1104
|
+
"CREATE TABLE `subscriptions` (\n\t`id` integer PRIMARY KEY,\n\t`name` text NOT NULL,\n\t`direction` text NOT NULL,\n\t`supplier_type` text NOT NULL,\n\t`supplier_id` integer NOT NULL,\n\t`customer_type` text NOT NULL,\n\t`customer_id` integer NOT NULL,\n\t`catalog_item_id` integer,\n\t`contract_id` integer,\n\t`project_id` integer,\n\t`status` text NOT NULL,\n\t`interval_count` integer NOT NULL,\n\t`interval_unit` text NOT NULL,\n\t`start_date` text NOT NULL,\n\t`trial_end_date` text,\n\t`next_renewal_date` text,\n\t`cancelled_date` text,\n\t`end_date` text,\n\t`review` text NOT NULL,\n\t`author_type` text NOT NULL,\n\t`author_id` integer NOT NULL,\n\t`model` text,\n\t`confirmed_by_type` text,\n\t`confirmed_by_id` integer,\n\t`source` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`deleted_at` integer,\n\tCONSTRAINT `fk_subscriptions_catalog_item_id_catalog_items_id_fk` FOREIGN KEY (`catalog_item_id`) REFERENCES `catalog_items`(`id`),\n\tCONSTRAINT `fk_subscriptions_contract_id_contracts_id_fk` FOREIGN KEY (`contract_id`) REFERENCES `contracts`(`id`),\n\tCONSTRAINT `fk_subscriptions_project_id_projects_id_fk` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`)\n);",
|
|
1105
|
+
"CREATE TABLE `transaction_splits` (\n\t`id` integer PRIMARY KEY,\n\t`transaction_id` integer NOT NULL,\n\t`position` integer NOT NULL,\n\t`category` text NOT NULL,\n\t`category_folded` text NOT NULL,\n\t`amount` integer NOT NULL,\n\t`project_id` integer,\n\t`note` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tCONSTRAINT `fk_transaction_splits_transaction_id_financial_transactions_id_fk` FOREIGN KEY (`transaction_id`) REFERENCES `financial_transactions`(`id`),\n\tCONSTRAINT `fk_transaction_splits_project_id_projects_id_fk` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`),\n\tCONSTRAINT `transaction_splits_transaction_id_position_unique` UNIQUE(`transaction_id`,`position`)\n);",
|
|
1106
|
+
"ALTER TABLE `invoice_lines` ADD `catalog_item_id` integer REFERENCES catalog_items(id);",
|
|
1107
|
+
"ALTER TABLE `invoices` ADD `contract_id` integer REFERENCES contracts(id);",
|
|
1108
|
+
"ALTER TABLE `invoices` ADD `subscription_id` integer REFERENCES subscriptions(id);",
|
|
1109
|
+
"ALTER TABLE `orders` ADD `contract_id` integer REFERENCES contracts(id);",
|
|
1110
|
+
"ALTER TABLE `orders` ADD `deal_id` integer REFERENCES deals(id);",
|
|
1111
|
+
"ALTER TABLE `orders` ADD `direction` text DEFAULT 'purchase' NOT NULL;",
|
|
1112
|
+
"ALTER TABLE `payments` ADD `refund_of` integer REFERENCES payments(id);",
|
|
1113
|
+
"ALTER TABLE `payments` ADD `subscription_id` integer REFERENCES subscriptions(id);",
|
|
1114
|
+
"ALTER TABLE `record_relations` ADD `as_role` text;",
|
|
1115
|
+
"ALTER TABLE `records` ADD `created_entity` integer DEFAULT 0 NOT NULL;",
|
|
1116
|
+
"CREATE UNIQUE INDEX `catalog_items_by_supplier_type_supplier_id_sku` ON `catalog_items` (`supplier_type`,`supplier_id`,`sku`) WHERE supplier_id IS NOT NULL AND sku IS NOT NULL AND deleted_at IS NULL;",
|
|
1117
|
+
"CREATE UNIQUE INDEX `catalog_items_by_sku` ON `catalog_items` (`sku`) WHERE supplier_id IS NULL AND sku IS NOT NULL AND deleted_at IS NULL;",
|
|
1118
|
+
"CREATE INDEX `catalog_items_by_name_folded` ON `catalog_items` (`name_folded`);",
|
|
1119
|
+
"CREATE INDEX `catalog_items_by_author_type_author_id` ON `catalog_items` (`author_type`,`author_id`);",
|
|
1120
|
+
"CREATE INDEX `contracts_by_project_id` ON `contracts` (`project_id`);",
|
|
1121
|
+
"CREATE INDEX `contracts_by_deal_id` ON `contracts` (`deal_id`);",
|
|
1122
|
+
"CREATE INDEX `contracts_by_author_type_author_id` ON `contracts` (`author_type`,`author_id`);",
|
|
1123
|
+
"CREATE INDEX `contracts_by_confirmed_by_type_confirmed_by_id` ON `contracts` (`confirmed_by_type`,`confirmed_by_id`);",
|
|
1124
|
+
"CREATE INDEX `financial_accounts_by_name_folded` ON `financial_accounts` (`name_folded`);",
|
|
1125
|
+
"CREATE INDEX `financial_accounts_by_holder_type_holder_id` ON `financial_accounts` (`holder_type`,`holder_id`);",
|
|
1126
|
+
"CREATE INDEX `financial_accounts_by_author_type_author_id` ON `financial_accounts` (`author_type`,`author_id`);",
|
|
1127
|
+
"CREATE INDEX `financial_transactions_by_financial_account_id_booked_date` ON `financial_transactions` (`financial_account_id`,`booked_date`);",
|
|
1128
|
+
"CREATE UNIQUE INDEX `financial_transactions_by_payment_id` ON `financial_transactions` (`payment_id`) WHERE payment_id IS NOT NULL AND deleted_at IS NULL;",
|
|
1129
|
+
"CREATE INDEX `financial_transactions_by_counterparty_type_counterparty_id` ON `financial_transactions` (`counterparty_type`,`counterparty_id`);",
|
|
1130
|
+
"CREATE INDEX `financial_transactions_by_project_id` ON `financial_transactions` (`project_id`);",
|
|
1131
|
+
"CREATE INDEX `financial_transactions_by_author_type_author_id` ON `financial_transactions` (`author_type`,`author_id`);",
|
|
1132
|
+
"CREATE INDEX `financial_transactions_by_confirmed_by_type_confirmed_by_id` ON `financial_transactions` (`confirmed_by_type`,`confirmed_by_id`);",
|
|
1133
|
+
"CREATE INDEX `identities_by_phone` ON `identities` (`phone`) WHERE phone IS NOT NULL;",
|
|
1134
|
+
"CREATE INDEX `invoice_lines_by_catalog_item_id` ON `invoice_lines` (`catalog_item_id`);",
|
|
1135
|
+
"CREATE INDEX `invoices_by_contract_id` ON `invoices` (`contract_id`);",
|
|
1136
|
+
"CREATE INDEX `invoices_by_subscription_id` ON `invoices` (`subscription_id`);",
|
|
1137
|
+
"CREATE INDEX `order_lines_by_catalog_item_id` ON `order_lines` (`catalog_item_id`);",
|
|
1138
|
+
"CREATE INDEX `orders_by_contract_id` ON `orders` (`contract_id`);",
|
|
1139
|
+
"CREATE INDEX `orders_by_deal_id` ON `orders` (`deal_id`);",
|
|
1140
|
+
"CREATE INDEX `payments_by_refund_of` ON `payments` (`refund_of`);",
|
|
1141
|
+
"CREATE INDEX `payments_by_subscription_id` ON `payments` (`subscription_id`);",
|
|
1142
|
+
"CREATE INDEX `records_by_account_id_batch_id` ON `records` (`account_id`,`batch_id`);",
|
|
1143
|
+
"CREATE UNIQUE INDEX `subscription_prices_by_subscription_id_effective_from` ON `subscription_prices` (`subscription_id`,`effective_from`) WHERE review <> 'rejected';",
|
|
1144
|
+
"CREATE INDEX `subscription_prices_by_author_type_author_id` ON `subscription_prices` (`author_type`,`author_id`);",
|
|
1145
|
+
"CREATE INDEX `subscription_prices_by_confirmed_by_type_confirmed_by_id` ON `subscription_prices` (`confirmed_by_type`,`confirmed_by_id`);",
|
|
1146
|
+
"CREATE INDEX `subscriptions_by_supplier_type_supplier_id` ON `subscriptions` (`supplier_type`,`supplier_id`);",
|
|
1147
|
+
"CREATE INDEX `subscriptions_by_customer_type_customer_id` ON `subscriptions` (`customer_type`,`customer_id`);",
|
|
1148
|
+
"CREATE INDEX `subscriptions_by_catalog_item_id` ON `subscriptions` (`catalog_item_id`);",
|
|
1149
|
+
"CREATE INDEX `subscriptions_by_contract_id` ON `subscriptions` (`contract_id`);",
|
|
1150
|
+
"CREATE INDEX `subscriptions_by_project_id` ON `subscriptions` (`project_id`);",
|
|
1151
|
+
"CREATE INDEX `subscriptions_by_author_type_author_id` ON `subscriptions` (`author_type`,`author_id`);",
|
|
1152
|
+
"CREATE INDEX `subscriptions_by_confirmed_by_type_confirmed_by_id` ON `subscriptions` (`confirmed_by_type`,`confirmed_by_id`);",
|
|
1153
|
+
"CREATE INDEX `transaction_splits_by_category_folded` ON `transaction_splits` (`category_folded`);",
|
|
1154
|
+
"CREATE INDEX `transaction_splits_by_project_id` ON `transaction_splits` (`project_id`);"
|
|
1155
|
+
]
|
|
1156
|
+
},
|
|
1157
|
+
{
|
|
1158
|
+
"name": "20261108010754_version-57-business-rules",
|
|
1159
|
+
"statements": [
|
|
1160
|
+
"-- The store's code checks these first and says why; the triggers keep a stray write from another build or a hand\n-- edit from storing business data that does not add up. Paid is net: a confirmed refund's allocation counts against\n-- the payment it refunds, so an invoice refunded in full is owed again.\nCREATE TRIGGER catalog_items_valid_bi BEFORE INSERT ON catalog_items\n WHEN new.kind NOT IN ('product', 'service') OR new.unit_price < 0\n OR (new.unit_price IS NULL) <> (new.currency IS NULL) BEGIN\n SELECT RAISE(ABORT, 'catalog_items: kind product or service, a price of 0 or more with its currency');\nEND;",
|
|
1161
|
+
"CREATE TRIGGER catalog_items_valid_bu BEFORE UPDATE ON catalog_items\n WHEN new.kind NOT IN ('product', 'service') OR new.unit_price < 0\n OR (new.unit_price IS NULL) <> (new.currency IS NULL) BEGIN\n SELECT RAISE(ABORT, 'catalog_items: kind product or service, a price of 0 or more with its currency');\nEND;",
|
|
1162
|
+
"CREATE TRIGGER order_lines_valid_bi BEFORE INSERT ON order_lines\n WHEN new.amount < 0 OR new.unit_price < 0 BEGIN\n SELECT RAISE(ABORT, 'order_lines: an amount and a unit price of 0 or more');\nEND;",
|
|
1163
|
+
"CREATE TRIGGER order_lines_valid_bu BEFORE UPDATE ON order_lines\n WHEN new.amount < 0 OR new.unit_price < 0 OR new.order_id IS NOT old.order_id BEGIN\n SELECT RAISE(ABORT, 'order_lines: an amount and a unit price of 0 or more, on the same order');\nEND;",
|
|
1164
|
+
"DROP TRIGGER orders_valid_bi;",
|
|
1165
|
+
"CREATE TRIGGER orders_valid_bi BEFORE INSERT ON orders\n WHEN new.customer_type NOT IN ('person', 'organization')\n OR new.purpose NOT IN ('personal', 'business', 'client', 'other')\n OR new.status NOT IN ('placed', 'shipped', 'delivered', 'cancelled', 'returned')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR new.direction NOT IN ('purchase', 'sale')\n OR (new.total IS NULL) <> (new.currency IS NULL) OR new.total < 0 BEGIN\n SELECT RAISE(ABORT, 'orders: a person or organization customer, a known purpose, status, review and direction, an amount with its currency');\nEND;",
|
|
1166
|
+
"DROP TRIGGER orders_valid_bu;",
|
|
1167
|
+
"-- A line is written before the order's total moves to the new sum, so the sum is checked when the order changes.\nCREATE TRIGGER orders_valid_bu BEFORE UPDATE ON orders\n WHEN new.customer_type NOT IN ('person', 'organization')\n OR new.purpose NOT IN ('personal', 'business', 'client', 'other')\n OR new.status NOT IN ('placed', 'shipped', 'delivered', 'cancelled', 'returned')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR new.direction NOT IN ('purchase', 'sale')\n OR (new.total IS NULL) <> (new.currency IS NULL) OR new.total < 0\n OR (EXISTS (SELECT 1 FROM order_lines WHERE order_id = new.id)\n AND (new.currency IS NULL OR new.total IS NOT (SELECT sum(amount) FROM order_lines WHERE order_id = new.id))) BEGIN\n SELECT RAISE(ABORT, 'orders: a known customer, purpose, status, review and direction; with lines, a currency and their sum as the total');\nEND;",
|
|
1168
|
+
"CREATE TRIGGER contracts_valid_bi BEFORE INSERT ON contracts\n WHEN new.kind NOT IN ('sale', 'purchase', 'service', 'lease', 'employment', 'nda', 'license', 'other')\n OR new.status NOT IN ('draft', 'active', 'ended', 'terminated')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected') OR new.auto_renew NOT IN (0, 1)\n OR (new.renewal_count IS NULL) <> (new.renewal_unit IS NULL) OR new.renewal_count < 1\n OR new.renewal_unit NOT IN ('day', 'week', 'month', 'year') OR new.notice_days < 0\n OR new.effective_date > new.expiration_date\n OR (new.value IS NULL) <> (new.currency IS NULL) OR new.value < 0 BEGIN\n SELECT RAISE(ABORT, 'contracts: a known kind, status and review, dates in order, a renewal and a value each complete');\nEND;",
|
|
1169
|
+
"CREATE TRIGGER contracts_valid_bu BEFORE UPDATE ON contracts\n WHEN new.kind NOT IN ('sale', 'purchase', 'service', 'lease', 'employment', 'nda', 'license', 'other')\n OR new.status NOT IN ('draft', 'active', 'ended', 'terminated')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected') OR new.auto_renew NOT IN (0, 1)\n OR (new.renewal_count IS NULL) <> (new.renewal_unit IS NULL) OR new.renewal_count < 1\n OR new.renewal_unit NOT IN ('day', 'week', 'month', 'year') OR new.notice_days < 0\n OR new.effective_date > new.expiration_date\n OR (new.value IS NULL) <> (new.currency IS NULL) OR new.value < 0 BEGIN\n SELECT RAISE(ABORT, 'contracts: a known kind, status and review, dates in order, a renewal and a value each complete');\nEND;",
|
|
1170
|
+
"CREATE TRIGGER subscriptions_valid_bi BEFORE INSERT ON subscriptions\n WHEN new.direction NOT IN ('receivable', 'payable')\n OR new.supplier_type NOT IN ('person', 'organization') OR new.customer_type NOT IN ('person', 'organization')\n OR new.status NOT IN ('trial', 'active', 'paused', 'cancelled', 'ended')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR new.interval_count < 1 OR new.interval_unit NOT IN ('day', 'week', 'month', 'year')\n OR new.trial_end_date < new.start_date OR new.end_date < new.start_date\n OR (new.status = 'trial' AND new.trial_end_date IS NULL)\n OR (new.status = 'cancelled' AND new.cancelled_date IS NULL) BEGIN\n SELECT RAISE(ABORT, 'subscriptions: a known direction, parties, status and review, an interval, dates in order');\nEND;",
|
|
1171
|
+
"CREATE TRIGGER subscriptions_valid_bu BEFORE UPDATE ON subscriptions\n WHEN new.direction NOT IN ('receivable', 'payable')\n OR new.supplier_type NOT IN ('person', 'organization') OR new.customer_type NOT IN ('person', 'organization')\n OR new.status NOT IN ('trial', 'active', 'paused', 'cancelled', 'ended')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR new.interval_count < 1 OR new.interval_unit NOT IN ('day', 'week', 'month', 'year')\n OR new.trial_end_date < new.start_date OR new.end_date < new.start_date\n OR (new.status = 'trial' AND new.trial_end_date IS NULL)\n OR (new.status = 'cancelled' AND new.cancelled_date IS NULL) BEGIN\n SELECT RAISE(ABORT, 'subscriptions: a known direction, parties, status and review, an interval, dates in order');\nEND;",
|
|
1172
|
+
"CREATE TRIGGER subscription_prices_valid_bi BEFORE INSERT ON subscription_prices\n WHEN new.amount < 0 OR new.review NOT IN ('proposed', 'confirmed', 'rejected') BEGIN\n SELECT RAISE(ABORT, 'subscription_prices: an amount of 0 or more and a known review');\nEND;",
|
|
1173
|
+
"-- A price is history: a correction is a rejection and a new row, so only its decision changes.\nCREATE TRIGGER subscription_prices_fixed_bu BEFORE UPDATE ON subscription_prices\n WHEN new.amount IS NOT old.amount OR new.currency IS NOT old.currency\n OR new.effective_from IS NOT old.effective_from OR new.subscription_id IS NOT old.subscription_id\n OR new.author_type IS NOT old.author_type OR new.author_id IS NOT old.author_id\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR (old.review = 'confirmed' AND new.review <> 'confirmed') BEGIN\n SELECT RAISE(ABORT, 'subscription_prices: a price is never changed; reject it and add a new one');\nEND;",
|
|
1174
|
+
"CREATE TRIGGER subscription_prices_kept_bd BEFORE DELETE ON subscription_prices BEGIN\n SELECT RAISE(ABORT, 'subscription_prices: a price is history and is never deleted');\nEND;",
|
|
1175
|
+
"CREATE TRIGGER financial_accounts_valid_bi BEFORE INSERT ON financial_accounts\n WHEN new.kind NOT IN ('bank', 'card', 'cash', 'wallet', 'other')\n OR (new.opening_balance IS NULL) <> (new.opening_date IS NULL) OR length(new.number_hint) > 4\n OR new.holder_type NOT IN ('person', 'organization') BEGIN\n SELECT RAISE(ABORT, 'financial_accounts: a known kind, an opening balance with its date, at most 4 characters of the number');\nEND;",
|
|
1176
|
+
"CREATE TRIGGER financial_accounts_valid_bu BEFORE UPDATE ON financial_accounts\n WHEN new.kind NOT IN ('bank', 'card', 'cash', 'wallet', 'other')\n OR (new.opening_balance IS NULL) <> (new.opening_date IS NULL) OR length(new.number_hint) > 4\n OR new.holder_type NOT IN ('person', 'organization')\n OR (new.currency IS NOT old.currency\n AND EXISTS (SELECT 1 FROM financial_transactions WHERE financial_account_id = new.id)) BEGIN\n SELECT RAISE(ABORT, 'financial_accounts: a known kind, an opening balance with its date, the currency kept once it has transactions');\nEND;",
|
|
1177
|
+
"CREATE TRIGGER financial_transactions_valid_bi BEFORE INSERT ON financial_transactions\n WHEN new.direction NOT IN ('in', 'out') OR new.amount <= 0 OR new.status NOT IN ('pending', 'booked')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR new.currency IS NOT (SELECT currency FROM financial_accounts WHERE id = new.financial_account_id)\n OR (new.status = 'booked') <> (new.booked_date IS NOT NULL)\n OR (new.payment_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM payments p WHERE p.id = new.payment_id\n AND p.currency = new.currency AND p.direction = new.direction AND p.amount = new.amount)) BEGIN\n SELECT RAISE(ABORT, 'financial_transactions: a known direction, status and review, above 0 in its account''s currency, booked with a date, its payment of the same amount');\nEND;",
|
|
1178
|
+
"CREATE TRIGGER financial_transactions_valid_bu BEFORE UPDATE ON financial_transactions\n WHEN new.direction NOT IN ('in', 'out') OR new.amount <= 0 OR new.status NOT IN ('pending', 'booked')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR new.currency IS NOT (SELECT currency FROM financial_accounts WHERE id = new.financial_account_id)\n OR (new.status = 'booked') <> (new.booked_date IS NOT NULL)\n OR (new.payment_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM payments p WHERE p.id = new.payment_id\n AND p.currency = new.currency AND p.direction = new.direction AND p.amount = new.amount))\n OR new.amount < (SELECT coalesce(sum(amount), 0) FROM transaction_splits WHERE transaction_id = new.id) BEGIN\n SELECT RAISE(ABORT, 'financial_transactions: a known direction, status and review, booked with a date, its payment of the same amount, at or above its splits');\nEND;",
|
|
1179
|
+
"CREATE TRIGGER transaction_splits_valid_bi BEFORE INSERT ON transaction_splits\n WHEN new.amount <= 0\n OR (SELECT coalesce(sum(amount), 0) FROM transaction_splits WHERE transaction_id = new.transaction_id) + new.amount\n > (SELECT amount FROM financial_transactions WHERE id = new.transaction_id) BEGIN\n SELECT RAISE(ABORT, 'transaction_splits: above 0, and the splits within the transaction''s amount');\nEND;",
|
|
1180
|
+
"CREATE TRIGGER transaction_splits_valid_bu BEFORE UPDATE ON transaction_splits\n WHEN new.amount <= 0 OR new.transaction_id IS NOT old.transaction_id\n OR (SELECT coalesce(sum(amount), 0) FROM transaction_splits WHERE transaction_id = new.transaction_id AND id <> old.id)\n + new.amount > (SELECT amount FROM financial_transactions WHERE id = new.transaction_id) BEGIN\n SELECT RAISE(ABORT, 'transaction_splits: above 0, on the same transaction, and the splits within its amount');\nEND;",
|
|
1181
|
+
"CREATE TRIGGER payments_refund_bi BEFORE INSERT ON payments\n WHEN new.refund_of IS NOT NULL AND (\n NOT EXISTS (SELECT 1 FROM payments o WHERE o.id = new.refund_of AND o.refund_of IS NULL\n AND o.direction <> new.direction AND o.currency = new.currency AND o.review <> 'rejected' AND o.deleted_at IS NULL)\n OR (SELECT coalesce(sum(r.amount), 0) FROM payments r WHERE r.refund_of = new.refund_of\n AND r.review = 'confirmed' AND r.deleted_at IS NULL) + new.amount\n > (SELECT amount FROM payments WHERE id = new.refund_of)) BEGIN\n SELECT RAISE(ABORT, 'payments: a refund goes the other way in the same currency, of a live payment that is not a refund, within its amount');\nEND;",
|
|
1182
|
+
"CREATE TRIGGER payments_refund_bu BEFORE UPDATE ON payments\n WHEN new.refund_of IS NOT old.refund_of\n OR (new.refund_of IS NOT NULL AND new.review <> 'rejected' AND new.deleted_at IS NULL AND (\n NOT EXISTS (SELECT 1 FROM payments o WHERE o.id = new.refund_of AND o.refund_of IS NULL\n AND o.direction <> new.direction AND o.currency = new.currency AND o.review <> 'rejected' AND o.deleted_at IS NULL)\n OR (SELECT coalesce(sum(r.amount), 0) FROM payments r WHERE r.refund_of = new.refund_of AND r.id <> new.id\n AND r.review = 'confirmed' AND r.deleted_at IS NULL) + new.amount\n > (SELECT amount FROM payments WHERE id = new.refund_of)))\n OR ((new.review = 'rejected' OR new.deleted_at IS NOT NULL) AND old.review <> 'rejected' AND old.deleted_at IS NULL\n AND EXISTS (SELECT 1 FROM payments r WHERE r.refund_of = new.id AND r.review <> 'rejected' AND r.deleted_at IS NULL))\n OR (new.refund_of IS NULL AND new.amount < (SELECT coalesce(sum(r.amount), 0) FROM payments r\n WHERE r.refund_of = new.id AND r.review = 'confirmed' AND r.deleted_at IS NULL)) BEGIN\n SELECT RAISE(ABORT, 'payments: a refund keeps its payment, goes the other way and stays within it; a refunded payment is not rejected or deleted');\nEND;",
|
|
1183
|
+
"-- A confirmed refund that stops counting gives its shares back to their invoices: never beyond a total.\nCREATE TRIGGER payments_refund_leaves_bu BEFORE UPDATE ON payments\n WHEN new.refund_of IS NOT NULL AND old.review = 'confirmed' AND old.deleted_at IS NULL\n AND (new.review <> 'confirmed' OR new.deleted_at IS NOT NULL)\n AND EXISTS (SELECT 1 FROM payment_allocations a JOIN invoices i ON i.id = a.invoice_id WHERE a.payment_id = new.id\n AND (SELECT coalesce(sum(CASE WHEN np.refund_of IS NULL THEN na.amount ELSE -na.amount END), 0) FROM payment_allocations na JOIN payments np ON np.id = na.payment_id WHERE na.invoice_id = i.id AND np.review = 'confirmed' AND np.deleted_at IS NULL) + a.amount > i.total) BEGIN\n SELECT RAISE(ABORT, 'payments: a refund leaving the confirmed ones would pay an invoice beyond its total');\nEND;",
|
|
1184
|
+
"CREATE TRIGGER payments_linked_bu BEFORE UPDATE ON payments\n WHEN (new.amount IS NOT old.amount OR new.currency IS NOT old.currency OR new.direction IS NOT old.direction\n OR (new.review = 'rejected' AND old.review <> 'rejected') OR (new.deleted_at IS NOT NULL AND old.deleted_at IS NULL))\n AND EXISTS (SELECT 1 FROM financial_transactions WHERE payment_id = new.id AND deleted_at IS NULL) BEGIN\n SELECT RAISE(ABORT, 'payments: a transaction records this payment; take the link back first');\nEND;",
|
|
1185
|
+
"DROP TRIGGER invoices_valid_bu;",
|
|
1186
|
+
"CREATE TRIGGER invoices_valid_bu BEFORE UPDATE ON invoices\n WHEN new.direction NOT IN ('receivable', 'payable') OR new.total < 0\n OR new.status NOT IN ('draft', 'issued', 'partly_paid', 'paid', 'void')\n OR new.review NOT IN ('proposed', 'confirmed', 'rejected')\n OR (new.currency IS NOT old.currency AND EXISTS (SELECT 1 FROM payment_allocations WHERE invoice_id = new.id))\n OR new.total < (SELECT coalesce(sum(CASE WHEN p.refund_of IS NULL THEN a.amount ELSE -a.amount END), 0)\n FROM payment_allocations a JOIN payments p ON p.id = a.payment_id\n WHERE a.invoice_id = new.id AND p.review = 'confirmed' AND p.deleted_at IS NULL) BEGIN\n SELECT RAISE(ABORT, 'invoices: the total stays at or above what is paid on it, in the same currency');\nEND;",
|
|
1187
|
+
"DROP TRIGGER payments_confirm_bu;",
|
|
1188
|
+
"CREATE TRIGGER payments_confirm_bu BEFORE UPDATE OF review ON payments\n WHEN new.review = 'confirmed' AND old.review IS NOT 'confirmed' AND (\n (new.refund_of IS NULL AND EXISTS (\n SELECT 1 FROM payment_allocations a JOIN invoices i ON i.id = a.invoice_id WHERE a.payment_id = new.id\n AND a.amount + (SELECT coalesce(sum(CASE WHEN p.refund_of IS NULL THEN o.amount ELSE -o.amount END), 0)\n FROM payment_allocations o JOIN payments p ON p.id = o.payment_id\n WHERE o.invoice_id = a.invoice_id AND o.payment_id <> new.id AND p.review = 'confirmed' AND p.deleted_at IS NULL)\n > i.total))\n OR (new.refund_of IS NOT NULL AND NOT EXISTS (\n SELECT 1 FROM payments o WHERE o.id = new.refund_of AND o.review = 'confirmed' AND o.deleted_at IS NULL))\n OR (new.refund_of IS NOT NULL AND EXISTS (\n SELECT 1 FROM payment_allocations a WHERE a.payment_id = new.id\n AND a.amount + (SELECT coalesce(sum(o.amount), 0) FROM payment_allocations o JOIN payments r ON r.id = o.payment_id\n WHERE o.invoice_id = a.invoice_id AND r.refund_of = new.refund_of AND r.id <> new.id\n AND r.review = 'confirmed' AND r.deleted_at IS NULL)\n > coalesce((SELECT amount FROM payment_allocations WHERE payment_id = new.refund_of AND invoice_id = a.invoice_id), 0)))) BEGIN\n SELECT RAISE(ABORT, 'payments: confirming it would settle more than an invoice''s total, or take back more than its payment gave, or come before its payment');\nEND;",
|
|
1189
|
+
"DROP TRIGGER payment_allocations_valid_bi;",
|
|
1190
|
+
"-- An ordinary payment counts against what the invoice still owes; a refund's share counts against what the payment\n-- it refunds gave that invoice, so net paid never goes below 0.\nCREATE TRIGGER payment_allocations_valid_bi BEFORE INSERT ON payment_allocations\n WHEN new.amount <= 0\n OR (SELECT currency FROM payments WHERE id = new.payment_id)\n IS NOT (SELECT currency FROM invoices WHERE id = new.invoice_id)\n OR (SELECT coalesce(sum(amount), 0) FROM payment_allocations WHERE payment_id = new.payment_id) + new.amount\n > (SELECT amount FROM payments WHERE id = new.payment_id)\n OR ((SELECT refund_of FROM payments WHERE id = new.payment_id) IS NULL\n AND (SELECT coalesce(sum(CASE WHEN p.refund_of IS NULL THEN a.amount ELSE -a.amount END), 0)\n FROM payment_allocations a JOIN payments p ON p.id = a.payment_id WHERE a.invoice_id = new.invoice_id\n AND ((p.review = 'confirmed' AND p.deleted_at IS NULL) OR a.payment_id = new.payment_id)) + new.amount\n > (SELECT total FROM invoices WHERE id = new.invoice_id))\n OR ((SELECT refund_of FROM payments WHERE id = new.payment_id) IS NOT NULL\n AND (SELECT coalesce(sum(a.amount), 0) FROM payment_allocations a JOIN payments r ON r.id = a.payment_id\n WHERE a.invoice_id = new.invoice_id AND r.refund_of = (SELECT refund_of FROM payments WHERE id = new.payment_id)\n AND ((r.review = 'confirmed' AND r.deleted_at IS NULL) OR a.payment_id = new.payment_id)) + new.amount\n > coalesce((SELECT amount FROM payment_allocations WHERE invoice_id = new.invoice_id\n AND payment_id = (SELECT refund_of FROM payments WHERE id = new.payment_id)), 0)) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: above 0, one currency, within the payment and within the invoice or the refunded share');\nEND;",
|
|
1191
|
+
"DROP TRIGGER payment_allocations_valid_bu;",
|
|
1192
|
+
"CREATE TRIGGER payment_allocations_valid_bu BEFORE UPDATE ON payment_allocations\n WHEN new.amount <= 0 OR new.payment_id IS NOT old.payment_id OR new.invoice_id IS NOT old.invoice_id\n OR (SELECT coalesce(sum(amount), 0) FROM payment_allocations WHERE payment_id = new.payment_id AND id <> old.id)\n + new.amount > (SELECT amount FROM payments WHERE id = new.payment_id)\n OR ((SELECT refund_of FROM payments WHERE id = new.payment_id) IS NULL\n AND (SELECT coalesce(sum(CASE WHEN p.refund_of IS NULL THEN a.amount ELSE -a.amount END), 0)\n FROM payment_allocations a JOIN payments p ON p.id = a.payment_id WHERE a.invoice_id = new.invoice_id\n AND a.id <> old.id AND ((p.review = 'confirmed' AND p.deleted_at IS NULL) OR a.payment_id = new.payment_id))\n + new.amount > (SELECT total FROM invoices WHERE id = new.invoice_id))\n OR ((SELECT refund_of FROM payments WHERE id = new.payment_id) IS NOT NULL\n AND (SELECT coalesce(sum(a.amount), 0) FROM payment_allocations a JOIN payments r ON r.id = a.payment_id\n WHERE a.invoice_id = new.invoice_id AND a.id <> old.id\n AND r.refund_of = (SELECT refund_of FROM payments WHERE id = new.payment_id)\n AND ((r.review = 'confirmed' AND r.deleted_at IS NULL) OR a.payment_id = new.payment_id)) + new.amount\n > coalesce((SELECT amount FROM payment_allocations WHERE invoice_id = new.invoice_id\n AND payment_id = (SELECT refund_of FROM payments WHERE id = new.payment_id)), 0))\n OR ((SELECT refund_of FROM payments WHERE id = new.payment_id) IS NULL\n AND new.amount < (SELECT coalesce(sum(a.amount), 0) FROM payment_allocations a JOIN payments r ON r.id = a.payment_id\n WHERE r.refund_of = new.payment_id AND a.invoice_id = new.invoice_id))\n OR (new.amount < old.amount\n AND (SELECT refund_of IS NOT NULL AND review = 'confirmed' AND deleted_at IS NULL FROM payments WHERE id = new.payment_id)\n AND (SELECT coalesce(sum(CASE WHEN np.refund_of IS NULL THEN na.amount ELSE -na.amount END), 0)\n FROM payment_allocations na JOIN payments np ON np.id = na.payment_id\n WHERE na.invoice_id = new.invoice_id AND np.review = 'confirmed' AND np.deleted_at IS NULL)\n + old.amount - new.amount > (SELECT total FROM invoices WHERE id = new.invoice_id)) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: above 0, within the payment, the invoice or the refunded share, at or above its refunds, sides unchanged');\nEND;",
|
|
1193
|
+
"CREATE TRIGGER payment_allocations_refunded_bd BEFORE DELETE ON payment_allocations\n WHEN (SELECT review FROM invoices WHERE id = old.invoice_id) <> 'rejected' AND EXISTS (SELECT 1 FROM payment_allocations a JOIN payments r ON r.id = a.payment_id\n WHERE r.refund_of = old.payment_id AND a.invoice_id = old.invoice_id) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: a refund of this payment is allocated to the invoice; take it back first');\nEND;",
|
|
1194
|
+
"CREATE TRIGGER payment_allocations_refund_bd BEFORE DELETE ON payment_allocations\n WHEN (SELECT refund_of IS NOT NULL AND review = 'confirmed' AND deleted_at IS NULL FROM payments WHERE id = old.payment_id)\n AND (SELECT review FROM invoices WHERE id = old.invoice_id) <> 'rejected'\n AND (SELECT coalesce(sum(CASE WHEN np.refund_of IS NULL THEN na.amount ELSE -na.amount END), 0) FROM payment_allocations na JOIN payments np ON np.id = na.payment_id WHERE na.invoice_id = old.invoice_id AND np.review = 'confirmed' AND np.deleted_at IS NULL) + old.amount\n > (SELECT total FROM invoices WHERE id = old.invoice_id) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: taking a refund''s share back would pay the invoice beyond its total');\nEND;",
|
|
1195
|
+
"-- A void invoice keeps what was settled on it; a rejected one lets its allocations go, as reject sets review first.\nCREATE TRIGGER payment_allocations_void_bd BEFORE DELETE ON payment_allocations\n WHEN (SELECT status = 'void' AND review <> 'rejected' FROM invoices WHERE id = old.invoice_id) BEGIN\n SELECT RAISE(ABORT, 'payment_allocations: a void invoice keeps its allocations');\nEND;"
|
|
1196
|
+
]
|
|
1063
1197
|
}
|
|
1064
1198
|
];
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { StoreContext } from "./open.js";
|
|
2
|
+
export interface MoneyLineInput {
|
|
3
|
+
/** Taken from the product when left out. */
|
|
4
|
+
description?: string;
|
|
5
|
+
/** A decimal string; `1` when not given. */
|
|
6
|
+
quantity?: string;
|
|
7
|
+
/** Decimal strings in the parent's currency. Give either or both: both must agree, quantity × unit price. */
|
|
8
|
+
unitPrice?: string;
|
|
9
|
+
amount?: string;
|
|
10
|
+
/** `product:<id>`: its name and price are copied onto the line, and a later price change leaves the line as it is. */
|
|
11
|
+
product?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface MoneyLine {
|
|
14
|
+
position: number;
|
|
15
|
+
description: string;
|
|
16
|
+
quantity: string;
|
|
17
|
+
unitPrice: string | null;
|
|
18
|
+
amount: string;
|
|
19
|
+
product: string | null;
|
|
20
|
+
}
|
|
21
|
+
export interface PricedLine {
|
|
22
|
+
description: string;
|
|
23
|
+
quantity: string;
|
|
24
|
+
unitPrice: number | null;
|
|
25
|
+
amount: number;
|
|
26
|
+
productId: number | null;
|
|
27
|
+
}
|
|
28
|
+
/** Where each parent keeps its lines, and the prefix of the reasons its line errors carry. */
|
|
29
|
+
declare const PARENTS: {
|
|
30
|
+
readonly invoice: {
|
|
31
|
+
readonly table: "invoice_lines";
|
|
32
|
+
readonly column: "invoice_id";
|
|
33
|
+
readonly reasons: "finance";
|
|
34
|
+
};
|
|
35
|
+
readonly order: {
|
|
36
|
+
readonly table: "order_lines";
|
|
37
|
+
readonly column: "order_id";
|
|
38
|
+
readonly reasons: "order";
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
export type LineParent = keyof typeof PARENTS;
|
|
42
|
+
/** Invoice and order lines: quantity × unit price, in the parent's currency, a product's name and price copied. */
|
|
43
|
+
export declare const moneyLinesOver: ({ database }: StoreContext) => {
|
|
44
|
+
linesOf: (parent: LineParent, lines: MoneyLineInput[], currency: string) => PricedLine[];
|
|
45
|
+
insertLines: (parent: LineParent, id: number, lines: PricedLine[], from: number, at: number) => void;
|
|
46
|
+
shownLines: (parent: LineParent, id: number, currency: string) => MoneyLine[];
|
|
47
|
+
};
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { formatDecimal, lineUnits, minorUnits, moneyLabel, quantityOf, scaleOf } from "../../domain/money.js";
|
|
2
|
+
import { requiredThing } from "./notes.js";
|
|
3
|
+
import { refuse, text } from "./reviewed.js";
|
|
4
|
+
/** Where each parent keeps its lines, and the prefix of the reasons its line errors carry. */
|
|
5
|
+
const PARENTS = {
|
|
6
|
+
invoice: { table: "invoice_lines", column: "invoice_id", reasons: "finance" },
|
|
7
|
+
order: { table: "order_lines", column: "order_id", reasons: "order" },
|
|
8
|
+
};
|
|
9
|
+
/** Invoice and order lines: quantity × unit price, in the parent's currency, a product's name and price copied. */
|
|
10
|
+
export const moneyLinesOver = ({ database }) => {
|
|
11
|
+
const productOf = (reference, what, code) => {
|
|
12
|
+
const thing = requiredThing(database, reference, `${what}'s product`);
|
|
13
|
+
if (thing.type !== "product")
|
|
14
|
+
return refuse(`${what}'s product is a product: reference, not ${reference}`, code("lines"));
|
|
15
|
+
const row = database.prepare("SELECT * FROM catalog_items WHERE id = ?").get(thing.id);
|
|
16
|
+
if (row.deleted_at != null)
|
|
17
|
+
refuse(`product:${row.id} is deleted`, code("lines"));
|
|
18
|
+
return row;
|
|
19
|
+
};
|
|
20
|
+
const priced = (parent, line, at, currency) => {
|
|
21
|
+
const code = (name) => `${PARENTS[parent].reasons}.${name}`;
|
|
22
|
+
const what = `line ${at + 1}`;
|
|
23
|
+
const product = line.product === undefined ? null : productOf(line.product, what, code);
|
|
24
|
+
const quantity = quantityOf(line.quantity ?? "1");
|
|
25
|
+
const copied = product !== null && line.unitPrice === undefined && line.amount === undefined;
|
|
26
|
+
if (copied && product.unit_price != null && product.currency !== currency)
|
|
27
|
+
refuse(`product:${product.id} is priced in ${String(product.currency)}; give ${what}'s price in ${currency}`, code("currency"));
|
|
28
|
+
const unitPrice = copied
|
|
29
|
+
? product.unit_price == null
|
|
30
|
+
? null
|
|
31
|
+
: Number(product.unit_price)
|
|
32
|
+
: line.unitPrice === undefined
|
|
33
|
+
? null
|
|
34
|
+
: minorUnits(line.unitPrice, currency, `${what}'s unit price`);
|
|
35
|
+
const computed = unitPrice === null ? null : lineUnits(quantity.thousandths, unitPrice);
|
|
36
|
+
const amount = line.amount === undefined ? computed : minorUnits(line.amount, currency, `${what}'s amount`);
|
|
37
|
+
if (amount === null)
|
|
38
|
+
return refuse(`${what} takes a unit price, an amount or both`, code("lines"));
|
|
39
|
+
if (computed !== null && computed !== amount)
|
|
40
|
+
refuse(`${what}: ${quantity.text} × ${moneyLabel(unitPrice, currency)} is ` +
|
|
41
|
+
`${moneyLabel(computed, currency)}, not ${moneyLabel(amount, currency)}`, code("line-amount"));
|
|
42
|
+
const description = text(line.description ?? (product === null ? undefined : String(product.name)), `${what}'s description`, 500, code("field")) ?? refuse(`${what} needs a description`, code("lines"));
|
|
43
|
+
return {
|
|
44
|
+
description,
|
|
45
|
+
quantity: quantity.text,
|
|
46
|
+
unitPrice: unitPrice ?? (quantity.thousandths === 1000n ? amount : null),
|
|
47
|
+
amount,
|
|
48
|
+
productId: product === null ? null : Number(product.id),
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
const linesOf = (parent, lines, currency) => lines.map((line, at) => priced(parent, line, at, currency));
|
|
52
|
+
/** Writes lines from position `from` on. */
|
|
53
|
+
const insertLines = (parent, id, lines, from, at) => {
|
|
54
|
+
const { table, column } = PARENTS[parent];
|
|
55
|
+
const insert = database.prepare(`INSERT INTO ${table} (${column}, position, description, quantity, unit_price, amount, catalog_item_id, ` +
|
|
56
|
+
"created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
|
|
57
|
+
for (const [index, line] of lines.entries())
|
|
58
|
+
insert.run(id, from + index, line.description, line.quantity, line.unitPrice, line.amount, line.productId, at, at);
|
|
59
|
+
};
|
|
60
|
+
const shownLines = (parent, id, currency) => {
|
|
61
|
+
const { table, column } = PARENTS[parent];
|
|
62
|
+
const scale = scaleOf(currency);
|
|
63
|
+
return database
|
|
64
|
+
.prepare(`SELECT * FROM ${table} WHERE ${column} = ? ORDER BY position`)
|
|
65
|
+
.all(id)
|
|
66
|
+
.map((line) => ({
|
|
67
|
+
position: Number(line.position),
|
|
68
|
+
description: String(line.description),
|
|
69
|
+
quantity: String(line.quantity),
|
|
70
|
+
unitPrice: line.unit_price == null ? null : formatDecimal(Number(line.unit_price), scale),
|
|
71
|
+
amount: formatDecimal(Number(line.amount), scale),
|
|
72
|
+
product: line.catalog_item_id == null ? null : `product:${line.catalog_item_id}`,
|
|
73
|
+
}));
|
|
74
|
+
};
|
|
75
|
+
return { linesOf, insertLines, shownLines };
|
|
76
|
+
};
|