@mccaskie-labs/workbench-quotes 0.0.0-stage → 0.1.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 +5 -0
- package/README.md +92 -2
- package/dist/cli.d.ts +12 -0
- package/dist/cli.js +188 -0
- package/dist/document.d.ts +83 -0
- package/dist/document.js +67 -0
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +10 -0
- package/dist/handover.d.ts +25 -0
- package/dist/handover.js +24 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +20 -0
- package/dist/kinds.d.ts +114 -0
- package/dist/kinds.js +231 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +335 -0
- package/dist/money.d.ts +21 -0
- package/dist/money.js +68 -0
- package/dist/page.d.ts +31 -0
- package/dist/page.js +87 -0
- package/dist/quotes.d.ts +121 -0
- package/dist/quotes.js +313 -0
- package/dist/starters.d.ts +3 -0
- package/dist/starters.js +23 -0
- package/dist/styles.d.ts +34 -0
- package/dist/styles.js +83 -0
- package/dist/types.d.ts +53 -0
- package/dist/types.js +4 -0
- package/dist/words.d.ts +9 -0
- package/dist/words.js +189 -0
- package/package.json +52 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @mccaskie-labs/workbench-quotes
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First version. A price list per kind of quote (`workbench/quotes/<kind>.json`, `npx workbench-quotes init` with Australian defaults: AUD, GST included at 10%, 30 days) prices a workbench-forms form's answers in whole cents: a quantity from a whole or money field with a minimum, an item that applies when a choice is picked, discounts as negative prices, GST included (1/11 of the total) or added, and a deposit. `npx workbench-quotes generate [--check]` checks each kind against the form it reads and writes `src/quotes.generated.ts`; `migration` writes `quotesMigration` (service role only). `createQuotes` keeps quotes in the app's own database, numbered per business (Q-0001) under a lock: `create`, `update` (drafts only), `revise` (a new quote that withdraws the old when sent), `send` (an unguessable link on the project's own domain, only its SHA-256 stored), `withdraw`, `get`, `list`, `document` (for workbench-pdf) and a daily `cleanup` (quotes that weren't accepted, after the kind's `unaccepted_days`). `handle()` serves the accept page (`renderQuotePage`, plain HTML forms, no script; `wb-quote-*`, `QUOTE_STYLES`; words in English, Tagalog and Taglish): the customer accepts with their typed name and a tick, or declines with a reason from a list, never typed words and no IP address; an expired, withdrawn or answered quote says so. `onAccepted` runs once per quote with `toInvoice(quote)`, the payments and invoices tool's `InvoiceSource`. Money is shown to two decimal places.
|
package/README.md
CHANGED
|
@@ -1,3 +1,93 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mccaskie-labs/workbench-quotes
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Quotes and estimates for apps built on Workbench, a private platform. The business's price list turns a form's answers into a priced quote, the customer gets a link and a branded PDF, and accepts or declines online. An accepted quote is handed to the payments and invoices tool. Everything runs in the app's own Worker and database: no Gateway call, no AI and no cost. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @mccaskie-labs/workbench-quotes
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Set up
|
|
10
|
+
|
|
11
|
+
1. `npx workbench-quotes init job` writes `workbench/quotes/job.json` with Australian defaults (AUD, GST included at 10%, 30 days, no deposit). Fill it from the client's answers: the client questions in `capabilities/quotes.json` say how.
|
|
12
|
+
2. `npx workbench-quotes generate` checks every kind (and each field it reads against `workbench/forms/<form>.json`) and writes `src/quotes.generated.ts`. Checks runs `generate --check`.
|
|
13
|
+
3. `npx workbench-quotes migration` writes the tables and functions into `supabase/migrations/`, with the down file in `supabase/rollback/`. It creates functions, so Control asks for approval even on staging.
|
|
14
|
+
4. In the Worker: `quotes.handle(request, ctx)` before the app's own routes, and `quotes.cleanup()` in the daily cron. The PDF needs workbench-pdf and the `BROWSER` binding.
|
|
15
|
+
5. `npx workbench-ui styles` adds the page's look (`wb-quote-*`) to `public/styles/workbench.css`; restyle it in `project.css`. Copy `QUOTE_WORDS` into the strings catalogue as `ui.wbquote.*`.
|
|
16
|
+
|
|
17
|
+
## A price list
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"format": 1,
|
|
22
|
+
"kind": "job",
|
|
23
|
+
"document": "quote",
|
|
24
|
+
"form": "job_request",
|
|
25
|
+
"currency": "AUD",
|
|
26
|
+
"tax": { "name": "GST", "rate": 0.1, "included": true },
|
|
27
|
+
"valid_days": 30,
|
|
28
|
+
"deposit_percent": 0,
|
|
29
|
+
"number_prefix": "Q-",
|
|
30
|
+
"items": [
|
|
31
|
+
{ "id": "call-out", "label": "Call-out", "price": "90.00" },
|
|
32
|
+
{ "id": "labour", "label": "Labour, per hour", "price": "95.00", "quantity": { "field": "hours", "min": 1 } },
|
|
33
|
+
{ "id": "rubbish", "label": "Rubbish removal", "price": "60.00", "when": { "field": "extras", "is": ["rubbish"] } }
|
|
34
|
+
],
|
|
35
|
+
"terms": "This quote holds for 30 days. Prices include GST.",
|
|
36
|
+
"acceptance": { "name_required": true },
|
|
37
|
+
"retention": { "unaccepted_days": 365 }
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- Prices are decimal text; a discount is a negative price. Money is whole cents throughout, each line rounded half away from zero, and shown to two decimal places.
|
|
42
|
+
- A quantity comes from a whole or money field (`field`), or is fixed (`value`), with an optional `min`. An item with `when` applies only while a choice field holds one of the values.
|
|
43
|
+
- `tax.included: true` works the GST out of the total (1/11 at 10%); `false` adds it on top. `null` for a business not registered for GST.
|
|
44
|
+
- `document: "estimate"` prints "Estimate" and says the final price may change.
|
|
45
|
+
|
|
46
|
+
## Use
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { createQuotes } from '@mccaskie-labs/workbench-quotes'
|
|
50
|
+
import { createPdfMaker } from '@mccaskie-labs/workbench-pdf'
|
|
51
|
+
import { QUOTE_KINDS } from './quotes.generated'
|
|
52
|
+
|
|
53
|
+
const pdf = createPdfMaker({ browser: env.BROWSER, brand })
|
|
54
|
+
const quotes = createQuotes({
|
|
55
|
+
db: serviceClient,
|
|
56
|
+
kinds: QUOTE_KINDS,
|
|
57
|
+
baseUrl: env.PUBLIC_URL,
|
|
58
|
+
business: async (account) => ({ name: 'Harbour Plumbing', details: ['ABN 12 345 678 901'] }),
|
|
59
|
+
pdf: (quote, doc) => pdf.document(doc),
|
|
60
|
+
onAccepted: async ({ quote, invoice }) => {
|
|
61
|
+
// invoice is workbench-payments' InvoiceSource; the billed person goes separately.
|
|
62
|
+
await payments.invoiceFrom(invoice, { bill_to: { name: quote.accepted_name ?? quote.customer.name, email: quote.customer.email } })
|
|
63
|
+
},
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
// In the Worker's fetch handler:
|
|
67
|
+
const served = await quotes.handle(request, ctx)
|
|
68
|
+
if (served) return served
|
|
69
|
+
|
|
70
|
+
// The owner taps Send quote:
|
|
71
|
+
const draft = await quotes.create({ kind: 'job', account, customer: { subject: { type: 'contact', id: contact.id }, name, email }, answers })
|
|
72
|
+
const { quote, url } = await quotes.send(draft.id)
|
|
73
|
+
const bytes = await pdf.document(await quotes.document(quote, { url }))
|
|
74
|
+
await mailer.send({ to: email, subject: `Quote ${quote.number}`, text: `Your quote: ${url}`, template: 'quote', attachments: [{ filename: `${quote.number}.pdf`, mimeType: 'application/pdf', bytes }] })
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
| Export | What it does |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `createQuotes(opts)` | The store over the app's own database (service client). `create`, `update` (a draft only), `revise` (a new quote replacing a sent one; sending it withdraws the old), `send` (returns the link; sending again makes a new link and stops the old), `withdraw`, `get`, `list`, `document`, `handle`, `cleanup`, and `price` to show a price without saving |
|
|
80
|
+
| `priceQuote(kind, answers)`, `priceLines`, `totalsFor`, `checkLines` | The pure pricing, for a live price as the customer fills in the form |
|
|
81
|
+
| `quoteDocument(quote, { business, url? })` | The quote as workbench-pdf's standard layout |
|
|
82
|
+
| `renderQuotePage(quote, opts)` | The accept page's HTML, for an app that serves it itself |
|
|
83
|
+
| `toInvoice(quote)` | An accepted quote as the payments tool's `InvoiceSource`: ids and whole cents, no personal details |
|
|
84
|
+
| `money(cents, currency, pack)` | Cents for people, two decimal places with the pack's symbol (`A$435.00`) |
|
|
85
|
+
| `quotesMigration`, `QUOTE_WORDS`, `QUOTE_STYLES`, `QuotesError` | The tables and functions, the words, the look, and every failure's `code` |
|
|
86
|
+
|
|
87
|
+
**The accept page** (`/<path>/<token>`, default path `quote`) is plain HTML with no script. Accepting takes the customer's typed full name (unless the kind sets `name_required: false`) and a tick; declining takes a reason from a list (`price`, `timing`, `elsewhere`, `not_needed`, `other`), never typed words. A quote is accepted once and never after its valid-until time; an answered, withdrawn or expired quote shows where it stands. `onAccepted` and `onDeclined` run once per quote, and a hook that fails leaves the customer's answer standing. Views are counted only for people, not link-preview fetchers. No IP address or browser is stored, and the page sends no referrer, so the link's token never leaks.
|
|
88
|
+
|
|
89
|
+
**Keeping.** A quote that wasn't accepted (declined, withdrawn, expired, or a draft never sent) is deleted by `cleanup()` the kind's `unaccepted_days` after it ended. Accepted quotes stay until the app deletes them, because they back an invoice.
|
|
90
|
+
|
|
91
|
+
Error codes: `bad_config`, `bad_input`, `unknown_kind`, `unknown_quote`, `wrong_status`, `expired`, `store_failed`. Messages never hold a customer's name or a price.
|
|
92
|
+
|
|
93
|
+
**Tests.** `npm test` runs the pricing, page and CLI tests; `npm run test:store` runs the store against the local Supabase database (`npm run db:start` at the repo root).
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type QuoteKind } from "./kinds.ts";
|
|
3
|
+
export declare const QUOTES_DIR = "workbench/quotes";
|
|
4
|
+
export declare const QUOTES_MODULE = "src/quotes.generated.ts";
|
|
5
|
+
/** The generated module for checked kinds. */
|
|
6
|
+
export declare function moduleText(kinds: readonly QuoteKind[]): string;
|
|
7
|
+
/** Problems with the fields a kind reads from its form. */
|
|
8
|
+
export declare function formProblems(kind: QuoteKind, dir: string): string[];
|
|
9
|
+
/** Reads and checks the project's quote kinds. Throws naming every problem. */
|
|
10
|
+
export declare function readKinds(dir: string): QuoteKind[];
|
|
11
|
+
/** Runs one command; returns the exit code. */
|
|
12
|
+
export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx workbench-quotes init [kind] [dir]`, run in a project's folder: writes
|
|
3
|
+
// workbench/quotes/<kind>.json (default "job") with Australian defaults, to
|
|
4
|
+
// be filled from the client's answers. A file already there is left as it is.
|
|
5
|
+
//
|
|
6
|
+
// `npx workbench-quotes generate [--check] [dir]` reads every
|
|
7
|
+
// workbench/quotes/*.json, checks it, checks each field a price list reads
|
|
8
|
+
// against the form it names (workbench/forms/<form>.json: a quantity from a
|
|
9
|
+
// whole or money field, a condition on a choice field's members), and writes
|
|
10
|
+
// src/quotes.generated.ts: QUOTE_KINDS for createQuotes. --check writes
|
|
11
|
+
// nothing and fails when the file is out of date or wrong.
|
|
12
|
+
//
|
|
13
|
+
// `npx workbench-quotes migration [dir]` writes quotesMigration into
|
|
14
|
+
// supabase/migrations/<timestamp>_workbench_quotes.sql, and its down file into
|
|
15
|
+
// supabase/rollback/, unless a quotes migration is already there.
|
|
16
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { dirname, join, resolve } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import { readAnswers } from "@mccaskie-labs/workbench-forms/answers";
|
|
20
|
+
import { fieldsUsed, quoteKindProblems } from "./kinds.js";
|
|
21
|
+
import { quotesMigration } from "./migration.js";
|
|
22
|
+
import { starterKind } from "./starters.js";
|
|
23
|
+
const USAGE = "usage: workbench-quotes init [kind] [dir]\n workbench-quotes generate [--check] [dir]\n workbench-quotes migration [dir]";
|
|
24
|
+
export const QUOTES_DIR = "workbench/quotes";
|
|
25
|
+
export const QUOTES_MODULE = "src/quotes.generated.ts";
|
|
26
|
+
const json = (v) => `${JSON.stringify(v, null, 2)}\n`;
|
|
27
|
+
const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
|
|
28
|
+
/** The generated module for checked kinds. */
|
|
29
|
+
export function moduleText(kinds) {
|
|
30
|
+
const byName = Object.fromEntries([...kinds].sort((a, b) => (a.kind < b.kind ? -1 : 1)).map((k) => [k.kind, k]));
|
|
31
|
+
return [
|
|
32
|
+
`// Generated by \`npx workbench-quotes generate\` from ${QUOTES_DIR}/*.json. Don't edit: change the`,
|
|
33
|
+
"// JSON and generate again (Checks runs `npx workbench-quotes generate --check`).",
|
|
34
|
+
"",
|
|
35
|
+
'import type { QuoteKind } from "@mccaskie-labs/workbench-quotes";',
|
|
36
|
+
"",
|
|
37
|
+
`export const QUOTE_KINDS = ${JSON.stringify(byName, null, 2)} as const satisfies Record<string, QuoteKind>;`,
|
|
38
|
+
"",
|
|
39
|
+
"export type QuoteKindName = keyof typeof QUOTE_KINDS;",
|
|
40
|
+
"",
|
|
41
|
+
].join("\n");
|
|
42
|
+
}
|
|
43
|
+
/** Problems with the fields a kind reads from its form. */
|
|
44
|
+
export function formProblems(kind, dir) {
|
|
45
|
+
if (!kind.form) {
|
|
46
|
+
const used = fieldsUsed(kind);
|
|
47
|
+
return used.length ? [`${QUOTES_DIR}/${kind.kind}.json: items read form fields (${[...new Set(used.map((u) => u.field))].join(", ")}) but no form is named: set "form"`] : [];
|
|
48
|
+
}
|
|
49
|
+
const file = `workbench/forms/${kind.form}.json`;
|
|
50
|
+
if (!existsSync(join(dir, file)))
|
|
51
|
+
return [`${QUOTES_DIR}/${kind.kind}.json: the form ${kind.form} isn't in workbench/forms/`];
|
|
52
|
+
let fields;
|
|
53
|
+
try {
|
|
54
|
+
fields = readAnswers(JSON.parse(read(join(dir, file))), file).fields;
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
return [e.message];
|
|
58
|
+
}
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const use of fieldsUsed(kind)) {
|
|
61
|
+
const f = fields.find((x) => x.name === use.field);
|
|
62
|
+
const at = `${QUOTES_DIR}/${kind.kind}.json: item ${use.item}`;
|
|
63
|
+
if (!f)
|
|
64
|
+
out.push(`${at} reads ${use.field}, which isn't a field of ${file}`);
|
|
65
|
+
else if (use.as === "quantity" && f.kind !== "whole" && f.kind !== "money")
|
|
66
|
+
out.push(`${at}: ${use.field} is a ${f.kind} field; a quantity comes from a whole or money field`);
|
|
67
|
+
else if (use.as === "choice") {
|
|
68
|
+
if (f.kind !== "choice")
|
|
69
|
+
out.push(`${at}: ${use.field} is a ${f.kind} field; a condition reads a choice field`);
|
|
70
|
+
else
|
|
71
|
+
for (const v of use.values ?? [])
|
|
72
|
+
if (!f.members?.some((m) => m.value === v))
|
|
73
|
+
out.push(`${at}: ${v} isn't one of the ${use.field} field's members`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
/** Reads and checks the project's quote kinds. Throws naming every problem. */
|
|
79
|
+
export function readKinds(dir) {
|
|
80
|
+
const folder = join(dir, QUOTES_DIR);
|
|
81
|
+
const files = existsSync(folder) ? readdirSync(folder).filter((f) => f.endsWith(".json")).sort() : [];
|
|
82
|
+
if (!files.length)
|
|
83
|
+
throw new Error(`${QUOTES_DIR}/ has no quote kinds: run npx workbench-quotes init, then answer the quotes questions (capabilities/quotes.json, offer)`);
|
|
84
|
+
const problems = [];
|
|
85
|
+
const kinds = [];
|
|
86
|
+
for (const name of files) {
|
|
87
|
+
const file = `${QUOTES_DIR}/${name}`;
|
|
88
|
+
let parsed;
|
|
89
|
+
try {
|
|
90
|
+
parsed = JSON.parse(read(join(folder, name)));
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
problems.push(`${file}: not valid JSON (${e.message})`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const p = quoteKindProblems(parsed, file);
|
|
97
|
+
if (!p.length && parsed.kind !== name.replace(/\.json$/, ""))
|
|
98
|
+
p.push(`${file}: kind must be ${name.replace(/\.json$/, "")}, the file's name`);
|
|
99
|
+
if (p.length) {
|
|
100
|
+
problems.push(...p);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
problems.push(...formProblems(parsed, dir));
|
|
104
|
+
kinds.push(parsed);
|
|
105
|
+
}
|
|
106
|
+
if (problems.length)
|
|
107
|
+
throw new Error(problems.join("\n"));
|
|
108
|
+
return kinds;
|
|
109
|
+
}
|
|
110
|
+
function migrationStamp(at) {
|
|
111
|
+
return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
112
|
+
}
|
|
113
|
+
/** Runs one command; returns the exit code. */
|
|
114
|
+
export function run(argv, log = console.log, err = console.error) {
|
|
115
|
+
const [command, ...args] = argv;
|
|
116
|
+
const check = args.includes("--check");
|
|
117
|
+
const rest = args.filter((a) => a !== "--check");
|
|
118
|
+
const bad = rest.find((a) => a.startsWith("--"));
|
|
119
|
+
const maxArgs = command === "init" ? 2 : 1;
|
|
120
|
+
if (!["init", "generate", "migration"].includes(command ?? "") || bad || (check && command !== "generate") || rest.length > maxArgs) {
|
|
121
|
+
err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
|
|
122
|
+
return 2;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
if (command === "init") {
|
|
126
|
+
const kind = rest[0] ?? "job";
|
|
127
|
+
if (!/^[a-z][a-z0-9-]{0,39}$/.test(kind)) {
|
|
128
|
+
err("the kind is lower case letters, digits and hyphens, such as job or event");
|
|
129
|
+
return 2;
|
|
130
|
+
}
|
|
131
|
+
const dir = resolve(rest[1] ?? ".");
|
|
132
|
+
const path = `${QUOTES_DIR}/${kind}.json`;
|
|
133
|
+
const at = join(dir, path);
|
|
134
|
+
if (existsSync(at)) {
|
|
135
|
+
log(`${path} is already there; left as it is`);
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
mkdirSync(dirname(at), { recursive: true });
|
|
139
|
+
writeFileSync(at, json(starterKind(kind)));
|
|
140
|
+
log(`wrote ${path}. Now fill it from the client's answers and run \`npx workbench-quotes generate\`.`);
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
const dir = resolve(rest[0] ?? ".");
|
|
144
|
+
if (command === "migration") {
|
|
145
|
+
const folder = join(dir, "supabase/migrations");
|
|
146
|
+
if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_quotes.sql"))) {
|
|
147
|
+
log("supabase/migrations already has the quotes migration; nothing written");
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
const name = `${migrationStamp(new Date())}_workbench_quotes.sql`;
|
|
151
|
+
mkdirSync(folder, { recursive: true });
|
|
152
|
+
mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
|
|
153
|
+
writeFileSync(join(folder, name), `-- workbench-quotes: quotes and estimates\n${quotesMigration.up}`);
|
|
154
|
+
writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${quotesMigration.down}`);
|
|
155
|
+
log(`wrote supabase/migrations/${name} and its down file`);
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
|
158
|
+
const kinds = readKinds(dir);
|
|
159
|
+
const text = moduleText(kinds);
|
|
160
|
+
const out = join(dir, QUOTES_MODULE);
|
|
161
|
+
if (check) {
|
|
162
|
+
if (!existsSync(out) || read(out) !== text) {
|
|
163
|
+
err(`${QUOTES_MODULE} is out of date: run npx workbench-quotes generate`);
|
|
164
|
+
return 1;
|
|
165
|
+
}
|
|
166
|
+
log(`${QUOTES_MODULE} is up to date`);
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
170
|
+
writeFileSync(out, text);
|
|
171
|
+
log(`wrote ${QUOTES_MODULE}: ${kinds.length} kind${kinds.length === 1 ? "" : "s"} (${kinds.map((k) => k.kind).join(", ")})`);
|
|
172
|
+
return 0;
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
err(e.message);
|
|
176
|
+
return 1;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const isMain = (() => {
|
|
180
|
+
try {
|
|
181
|
+
return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
})();
|
|
187
|
+
if (isMain)
|
|
188
|
+
process.exitCode = run(process.argv.slice(2));
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type CountryPack } from "@mccaskie-labs/workbench-country";
|
|
2
|
+
import type { Quote } from "./types.ts";
|
|
3
|
+
import { type QuoteLang, type QuoteStrings } from "./words.ts";
|
|
4
|
+
/** What the page and the PDF show about the business sending the quote. */
|
|
5
|
+
export interface QuoteBusiness {
|
|
6
|
+
name: string;
|
|
7
|
+
/** Under the facts: "ABN 12 345 678 901", an address, a phone number. Up to 4 lines. */
|
|
8
|
+
details?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
export interface PresentOptions {
|
|
11
|
+
business: QuoteBusiness;
|
|
12
|
+
/** A country code or pack for money and dates. Default AU. */
|
|
13
|
+
country?: string | CountryPack;
|
|
14
|
+
language?: QuoteLang;
|
|
15
|
+
t?: QuoteStrings;
|
|
16
|
+
}
|
|
17
|
+
/** A quote's shown figures. */
|
|
18
|
+
export interface PresentedQuote {
|
|
19
|
+
lang: QuoteLang;
|
|
20
|
+
document: string;
|
|
21
|
+
title: string;
|
|
22
|
+
facts: {
|
|
23
|
+
label: string;
|
|
24
|
+
value: string;
|
|
25
|
+
}[];
|
|
26
|
+
estimateNote: string | null;
|
|
27
|
+
columns: [string, string, string, string];
|
|
28
|
+
lines: {
|
|
29
|
+
label: string;
|
|
30
|
+
quantity: string;
|
|
31
|
+
unit: string;
|
|
32
|
+
amount: string;
|
|
33
|
+
}[];
|
|
34
|
+
totals: {
|
|
35
|
+
label: string;
|
|
36
|
+
value: string;
|
|
37
|
+
grand?: boolean;
|
|
38
|
+
}[];
|
|
39
|
+
note: string | null;
|
|
40
|
+
terms: {
|
|
41
|
+
title: string;
|
|
42
|
+
text: string;
|
|
43
|
+
} | null;
|
|
44
|
+
}
|
|
45
|
+
/** The quote's words and figures in a language. */
|
|
46
|
+
export declare function presentQuote(quote: Quote, o: PresentOptions): PresentedQuote;
|
|
47
|
+
/** workbench-pdf's document shape (its PdfDocument), kept here so this package needn't depend on it. */
|
|
48
|
+
export interface QuotePdfDocument {
|
|
49
|
+
title: string;
|
|
50
|
+
subtitle?: string;
|
|
51
|
+
date?: string;
|
|
52
|
+
blocks: ({
|
|
53
|
+
type: "heading";
|
|
54
|
+
text: string;
|
|
55
|
+
level?: 2 | 3;
|
|
56
|
+
} | {
|
|
57
|
+
type: "paragraph";
|
|
58
|
+
text: string;
|
|
59
|
+
} | {
|
|
60
|
+
type: "table";
|
|
61
|
+
columns: string[];
|
|
62
|
+
rows: string[][];
|
|
63
|
+
align?: ("left" | "right")[];
|
|
64
|
+
} | {
|
|
65
|
+
type: "facts";
|
|
66
|
+
items: {
|
|
67
|
+
label: string;
|
|
68
|
+
value: string;
|
|
69
|
+
}[];
|
|
70
|
+
} | {
|
|
71
|
+
type: "note";
|
|
72
|
+
text: string;
|
|
73
|
+
})[];
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The quote as workbench-pdf's standard layout: pass it to
|
|
77
|
+
* `pdf.document(quoteDocument(quote, ...))` and the brand's logo, colours and
|
|
78
|
+
* footer go round it. `url` is the quote's accept page, printed so a customer
|
|
79
|
+
* with the PDF alone can still accept online.
|
|
80
|
+
*/
|
|
81
|
+
export declare function quoteDocument(quote: Quote, o: PresentOptions & {
|
|
82
|
+
url?: string;
|
|
83
|
+
}): QuotePdfDocument;
|
package/dist/document.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// A quote as words and figures, ready to show: shared by the PDF
|
|
2
|
+
// (quoteDocument, for workbench-pdf's standard layout) and the accept page.
|
|
3
|
+
// Money is always two decimal places with the country pack's symbol
|
|
4
|
+
// (Australian unless the app says otherwise); dates in the pack's style.
|
|
5
|
+
import { formatDate } from "@mccaskie-labs/workbench-country";
|
|
6
|
+
import { money, packFor } from "./money.js";
|
|
7
|
+
import { quoteWord } from "./words.js";
|
|
8
|
+
const quantityText = (q, pack) => q.toLocaleString(pack.locale, { maximumFractionDigits: 3 });
|
|
9
|
+
/** The quote's words and figures in a language. */
|
|
10
|
+
export function presentQuote(quote, o) {
|
|
11
|
+
const lang = o.language ?? "en";
|
|
12
|
+
const pack = packFor(o.country);
|
|
13
|
+
const w = (key, values = {}) => quoteWord(key, lang, values, o.t);
|
|
14
|
+
const m = (c) => money(c, quote.currency, pack);
|
|
15
|
+
const date = (iso) => formatDate(iso, { pack });
|
|
16
|
+
const document = w(quote.document === "estimate" ? "doc.estimate" : "doc.quote");
|
|
17
|
+
const facts = [{ label: w("number"), value: quote.number }, { label: w("date"), value: date(quote.sent_at ?? quote.created_at) }];
|
|
18
|
+
if (quote.valid_until)
|
|
19
|
+
facts.push({ label: w("valid_until"), value: date(quote.valid_until) });
|
|
20
|
+
if (quote.customer.name)
|
|
21
|
+
facts.push({ label: w("prepared_for"), value: quote.customer.name });
|
|
22
|
+
const totals = [];
|
|
23
|
+
if (quote.tax && !quote.tax.included) {
|
|
24
|
+
totals.push({ label: w("subtotal"), value: m(quote.subtotal_cents) });
|
|
25
|
+
totals.push({ label: w("tax_added", { tax: quote.tax.name }), value: m(quote.tax_cents) });
|
|
26
|
+
}
|
|
27
|
+
totals.push({ label: w("total"), value: m(quote.total_cents), grand: true });
|
|
28
|
+
if (quote.tax?.included)
|
|
29
|
+
totals.push({ label: w("tax_included", { tax: quote.tax.name }), value: m(quote.tax_cents) });
|
|
30
|
+
if (quote.deposit_cents > 0)
|
|
31
|
+
totals.push({ label: w("deposit"), value: m(quote.deposit_cents) });
|
|
32
|
+
return {
|
|
33
|
+
lang,
|
|
34
|
+
document,
|
|
35
|
+
title: `${document} ${quote.number}`,
|
|
36
|
+
facts,
|
|
37
|
+
estimateNote: quote.document === "estimate" ? w("doc.estimate_note") : null,
|
|
38
|
+
columns: [w("col.item"), w("col.quantity"), w("col.unit"), w("col.amount")],
|
|
39
|
+
lines: quote.lines.map((l) => ({ label: l.label, quantity: quantityText(l.quantity, pack), unit: m(l.unit_cents), amount: m(l.total_cents) })),
|
|
40
|
+
totals,
|
|
41
|
+
note: quote.note,
|
|
42
|
+
terms: quote.terms.trim() ? { title: w("terms"), text: quote.terms.trim() } : null,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The quote as workbench-pdf's standard layout: pass it to
|
|
47
|
+
* `pdf.document(quoteDocument(quote, ...))` and the brand's logo, colours and
|
|
48
|
+
* footer go round it. `url` is the quote's accept page, printed so a customer
|
|
49
|
+
* with the PDF alone can still accept online.
|
|
50
|
+
*/
|
|
51
|
+
export function quoteDocument(quote, o) {
|
|
52
|
+
const p = presentQuote(quote, o);
|
|
53
|
+
const blocks = [{ type: "facts", items: p.facts }];
|
|
54
|
+
if (p.estimateNote)
|
|
55
|
+
blocks.push({ type: "note", text: p.estimateNote });
|
|
56
|
+
if (p.note)
|
|
57
|
+
blocks.push({ type: "paragraph", text: p.note });
|
|
58
|
+
blocks.push({ type: "table", columns: [...p.columns], rows: p.lines.map((l) => [l.label, l.quantity, l.unit, l.amount]), align: ["left", "right", "right", "right"] });
|
|
59
|
+
blocks.push({ type: "table", columns: ["", ""], rows: p.totals.map((t) => [t.label, t.value]), align: ["right", "right"] });
|
|
60
|
+
if (p.terms)
|
|
61
|
+
blocks.push({ type: "heading", text: p.terms.title, level: 3 }, { type: "paragraph", text: p.terms.text });
|
|
62
|
+
for (const line of (o.business.details ?? []).slice(0, 4))
|
|
63
|
+
blocks.push({ type: "paragraph", text: line });
|
|
64
|
+
if (o.url)
|
|
65
|
+
blocks.push({ type: "note", text: quoteWord("accept_online", p.lang, { url: o.url }, o.t) });
|
|
66
|
+
return { title: p.title, subtitle: o.business.name, date: p.facts[1].value, blocks };
|
|
67
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type QuotesErrorCode =
|
|
2
|
+
/** A workbench/quotes/<kind>.json file is out of shape. */
|
|
3
|
+
"bad_config"
|
|
4
|
+
/** A call's arguments are out of shape (a line, an answer, a name). */
|
|
5
|
+
| "bad_input"
|
|
6
|
+
/** No such kind of quote in the project's quote files. */
|
|
7
|
+
| "unknown_kind"
|
|
8
|
+
/** No such quote. */
|
|
9
|
+
| "unknown_quote"
|
|
10
|
+
/** The quote can't do that now: sending an accepted quote, editing a sent one, accepting a withdrawn one. */
|
|
11
|
+
| "wrong_status"
|
|
12
|
+
/** The quote's valid-until date has passed. */
|
|
13
|
+
| "expired"
|
|
14
|
+
/** The database refused or failed. */
|
|
15
|
+
| "store_failed";
|
|
16
|
+
export declare class QuotesError extends Error {
|
|
17
|
+
readonly code: QuotesErrorCode;
|
|
18
|
+
constructor(code: QuotesErrorCode, message: string);
|
|
19
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Every failure carries a permanent code, so an app can act on it without
|
|
2
|
+
// reading the words. Messages never hold a customer's name or a price.
|
|
3
|
+
export class QuotesError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
constructor(code, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "QuotesError";
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { QuoteLine, QuoteTax } from "./kinds.ts";
|
|
2
|
+
import type { Quote, Subject } from "./types.ts";
|
|
3
|
+
export interface QuoteHandover {
|
|
4
|
+
format: 1;
|
|
5
|
+
source: {
|
|
6
|
+
type: "quote";
|
|
7
|
+
id: string;
|
|
8
|
+
number: string;
|
|
9
|
+
};
|
|
10
|
+
account: string;
|
|
11
|
+
customer: Subject | null;
|
|
12
|
+
currency: string;
|
|
13
|
+
/** total_cents is quantity × unit_cents, rounded to whole cents, on every line. */
|
|
14
|
+
lines: Pick<QuoteLine, "label" | "quantity" | "unit_cents" | "total_cents">[];
|
|
15
|
+
tax: QuoteTax | null;
|
|
16
|
+
subtotal_cents: number;
|
|
17
|
+
tax_cents: number;
|
|
18
|
+
/** subtotal_cents, plus tax_cents when the tax isn't included. */
|
|
19
|
+
total_cents: number;
|
|
20
|
+
/** 0: no deposit. */
|
|
21
|
+
deposit_cents: number;
|
|
22
|
+
accepted_at: string;
|
|
23
|
+
}
|
|
24
|
+
/** An accepted quote as the invoice's source. Throws wrong_status for any other quote. */
|
|
25
|
+
export declare function toInvoice(quote: Quote): QuoteHandover;
|
package/dist/handover.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The hand-over to the payments and invoices tool (workbench-payments'
|
|
2
|
+
// InvoiceSource): an accepted quote as plain data in whole cents, with no
|
|
3
|
+
// personal details. The app passes it to payments with its own bill_to
|
|
4
|
+
// (name, email) when it makes the invoice. Neither package imports the other.
|
|
5
|
+
import { QuotesError } from "./errors.js";
|
|
6
|
+
/** An accepted quote as the invoice's source. Throws wrong_status for any other quote. */
|
|
7
|
+
export function toInvoice(quote) {
|
|
8
|
+
if (quote.status !== "accepted" || !quote.accepted_at)
|
|
9
|
+
throw new QuotesError("wrong_status", `quote ${quote.number} isn't accepted`);
|
|
10
|
+
return {
|
|
11
|
+
format: 1,
|
|
12
|
+
source: { type: "quote", id: quote.id, number: quote.number },
|
|
13
|
+
account: quote.account,
|
|
14
|
+
customer: quote.customer.subject,
|
|
15
|
+
currency: quote.currency,
|
|
16
|
+
lines: quote.lines.map((l) => ({ label: l.label, quantity: l.quantity, unit_cents: l.unit_cents, total_cents: l.total_cents })),
|
|
17
|
+
tax: quote.tax,
|
|
18
|
+
subtotal_cents: quote.subtotal_cents,
|
|
19
|
+
tax_cents: quote.tax_cents,
|
|
20
|
+
total_cents: quote.total_cents,
|
|
21
|
+
deposit_cents: quote.deposit_cents,
|
|
22
|
+
accepted_at: quote.accepted_at,
|
|
23
|
+
};
|
|
24
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { createQuotes, type AcceptedEvent, type CreateQuoteRequest, type CustomerInput, type Quotes, type QuotesClient, type QuotesOptions, type UpdateQuoteRequest, type WaitContext } from "./quotes.ts";
|
|
2
|
+
export { checkLines, checkQuoteKind, fieldsUsed, MAX_LABEL, MAX_LINES, MAX_NOTE, MAX_TERMS, priceLines, priceQuote, quoteKindProblems, totalsFor, type Answers, type ItemCondition, type ItemQuantity, type PriceItem, type QuoteKind, type QuoteLine, type QuoteTax, type QuoteTotals } from "./kinds.ts";
|
|
3
|
+
export { centsText, DEFAULT_COUNTRY, lineCents, MAX_CENTS, MAX_QUANTITY, money, toCents } from "./money.ts";
|
|
4
|
+
export { presentQuote, quoteDocument, type PresentedQuote, type PresentOptions, type QuoteBusiness, type QuotePdfDocument } from "./document.ts";
|
|
5
|
+
export { DEFAULT_STYLESHEETS, quoteState, renderNotFoundPage, renderQuotePage, type QuotePageOptions } from "./page.ts";
|
|
6
|
+
export { toInvoice, type QuoteHandover, type QuoteHandover as InvoiceSource } from "./handover.ts";
|
|
7
|
+
export { quotesMigration } from "./migration.ts";
|
|
8
|
+
export { starterKind } from "./starters.ts";
|
|
9
|
+
export { QUOTE_WORDS, QUOTE_WORD_KEYS, quoteWord, type QuoteLang, type QuoteStrings, type QuoteWordKey } from "./words.ts";
|
|
10
|
+
export { QUOTE_STYLES } from "./styles.ts";
|
|
11
|
+
export { QuotesError, type QuotesErrorCode } from "./errors.ts";
|
|
12
|
+
export { DECLINE_REASONS, QUOTE_STATUSES, type DeclineReason, type Quote, type QuoteCustomer, type QuoteStatus, type Subject } from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// @mccaskie-labs/workbench-quotes: quotes and estimates. A price list per
|
|
2
|
+
// kind of quote (workbench/quotes/<kind>.json) prices a workbench-forms form's
|
|
3
|
+
// answers in whole cents with the tax (GST included, by default); the quote is
|
|
4
|
+
// kept in the app's own database (quotesMigration), sent as a link to an
|
|
5
|
+
// accept page and as a branded PDF (quoteDocument, for workbench-pdf), and the
|
|
6
|
+
// customer accepts or declines online. An accepted quote is handed to the
|
|
7
|
+
// payments and invoices tool as plain data (toInvoice). No AI and no Gateway
|
|
8
|
+
// call: it all runs in the app's own Worker and database.
|
|
9
|
+
export { createQuotes } from "./quotes.js";
|
|
10
|
+
export { checkLines, checkQuoteKind, fieldsUsed, MAX_LABEL, MAX_LINES, MAX_NOTE, MAX_TERMS, priceLines, priceQuote, quoteKindProblems, totalsFor } from "./kinds.js";
|
|
11
|
+
export { centsText, DEFAULT_COUNTRY, lineCents, MAX_CENTS, MAX_QUANTITY, money, toCents } from "./money.js";
|
|
12
|
+
export { presentQuote, quoteDocument } from "./document.js";
|
|
13
|
+
export { DEFAULT_STYLESHEETS, quoteState, renderNotFoundPage, renderQuotePage } from "./page.js";
|
|
14
|
+
export { toInvoice } from "./handover.js";
|
|
15
|
+
export { quotesMigration } from "./migration.js";
|
|
16
|
+
export { starterKind } from "./starters.js";
|
|
17
|
+
export { QUOTE_WORDS, QUOTE_WORD_KEYS, quoteWord } from "./words.js";
|
|
18
|
+
export { QUOTE_STYLES } from "./styles.js";
|
|
19
|
+
export { QuotesError } from "./errors.js";
|
|
20
|
+
export { DECLINE_REASONS, QUOTE_STATUSES } from "./types.js";
|