@mccaskie-labs/workbench-quotes 0.0.0-stage → 0.2.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.
@@ -0,0 +1,114 @@
1
+ /** An item only priced when an answer holds one of some values (a choice field's members). */
2
+ export interface ItemCondition {
3
+ field: string;
4
+ is: readonly string[];
5
+ }
6
+ /** How many of an item: a fixed number, or a form answer (a whole or money field), with a floor. */
7
+ export interface ItemQuantity {
8
+ /** The form field whose answer is the quantity (guests, hours, square metres). */
9
+ field?: string;
10
+ /** A fixed quantity. Default 1 when there is no field. */
11
+ value?: number;
12
+ /** The least charged for, even when the answer is less ("minimum 20 guests"). */
13
+ min?: number;
14
+ }
15
+ export interface PriceItem {
16
+ /** Lower case letters, digits and hyphens. */
17
+ id: string;
18
+ /** The line's words on the quote ("Labour, per hour"). */
19
+ label: string;
20
+ /** The unit price as decimal text, "95.00"; negative for a discount. */
21
+ price: string;
22
+ quantity?: ItemQuantity;
23
+ when?: ItemCondition;
24
+ }
25
+ export interface QuoteTax {
26
+ /** "GST". */
27
+ name: string;
28
+ /** 0.1 for 10%: at most four decimal places. */
29
+ rate: number;
30
+ /** True when the prices already include it (Australian consumer pricing). */
31
+ included: boolean;
32
+ }
33
+ export interface QuoteKind {
34
+ format: 1;
35
+ /** The kind's name: lower case letters, digits and hyphens. The file is workbench/quotes/<kind>.json. */
36
+ kind: string;
37
+ /** "quote": a fixed price the customer accepts. "estimate": a best guess, and the document says the final price may change. */
38
+ document: "quote" | "estimate";
39
+ /** The workbench-forms form whose answers price it (workbench/forms/<form>.json), if any. */
40
+ form?: string;
41
+ /** ISO 4217, such as "AUD". */
42
+ currency: string;
43
+ tax: QuoteTax | null;
44
+ /** Days a sent quote holds, 1 to 365. */
45
+ valid_days: number;
46
+ /** The share of the total asked for up front when it's accepted, 0 to 100. 0: no deposit. */
47
+ deposit_percent: number;
48
+ /** Numbers read <prefix>0001: "Q-". Letters, digits and hyphens, up to 8. */
49
+ number_prefix: string;
50
+ items: readonly PriceItem[];
51
+ /** Printed on the quote and the accept page. Up to 4,000 characters. */
52
+ terms: string;
53
+ acceptance: {
54
+ /** The customer types their full name to accept. Default true. */
55
+ name_required: boolean;
56
+ };
57
+ retention: {
58
+ /** Days a quote that wasn't accepted (declined, withdrawn, expired, or a draft never sent) is kept, then deleted. 30 to 3,650. */
59
+ unaccepted_days: number;
60
+ };
61
+ }
62
+ /** One line of a quote, in whole cents. total_cents is always quantity × unit_cents, rounded. */
63
+ export interface QuoteLine {
64
+ /** The price list item it came from; absent on a line the business added. */
65
+ item?: string;
66
+ label: string;
67
+ quantity: number;
68
+ unit_cents: number;
69
+ total_cents: number;
70
+ }
71
+ export interface QuoteTotals {
72
+ subtotal_cents: number;
73
+ tax_cents: number;
74
+ total_cents: number;
75
+ deposit_cents: number;
76
+ }
77
+ /** A form's answers, as workbench-forms' readForm gives them (or the app's own record). */
78
+ export type Answers = Readonly<Record<string, unknown>>;
79
+ /** The most lines on one quote. */
80
+ export declare const MAX_LINES = 200;
81
+ /** The longest line label, and the longest note and terms. */
82
+ export declare const MAX_LABEL = 200;
83
+ export declare const MAX_NOTE = 2000;
84
+ export declare const MAX_TERMS = 4000;
85
+ /** Every problem with a kind's file, each naming the file and the setting. Empty when it's good. */
86
+ export declare function quoteKindProblems(json: unknown, file?: string): string[];
87
+ /** Checks a kind's file and returns it typed. Throws bad_config naming every problem. */
88
+ export declare function checkQuoteKind(json: unknown, file?: string): QuoteKind;
89
+ /** The form fields a kind reads, with what it needs of each: for `npx workbench-quotes generate` to check against the form. */
90
+ export declare function fieldsUsed(kind: QuoteKind): {
91
+ field: string;
92
+ as: "quantity" | "choice";
93
+ values?: readonly string[];
94
+ item: string;
95
+ }[];
96
+ /**
97
+ * The lines a kind's price list gives for a form's answers. An item whose
98
+ * `when` doesn't hold is left out, and so is one whose quantity field is
99
+ * empty or 0; a quantity under `min` is charged as `min`. Throws bad_input
100
+ * when a quantity answer isn't a number.
101
+ */
102
+ export declare function priceLines(kind: QuoteKind, answers?: Answers): QuoteLine[];
103
+ /** Checks lines the app passes (the business edited or added some) and works out each line's amount. */
104
+ export declare function checkLines(lines: unknown): QuoteLine[];
105
+ /**
106
+ * Adds up lines. With tax included, the tax is the part of the total that is
107
+ * tax (a tenth of an Australian GST price is not the GST: it's 1/11).
108
+ * Without, it's added on top. The deposit is a share of the total.
109
+ */
110
+ export declare function totalsFor(lines: readonly QuoteLine[], tax: QuoteTax | null, depositPercent?: number): QuoteTotals;
111
+ /** A quote's lines and totals from a kind and a form's answers. */
112
+ export declare function priceQuote(kind: QuoteKind, answers?: Answers): {
113
+ lines: QuoteLine[];
114
+ } & QuoteTotals;
package/dist/kinds.js ADDED
@@ -0,0 +1,231 @@
1
+ // A kind of quote: one file per kind in the project, workbench/quotes/<kind>.json,
2
+ // written from the client's answers (capabilities/quotes.json, offer). It holds
3
+ // the price list, the tax, how long a quote holds, the deposit and the terms.
4
+ // priceQuote() turns a form's answers into lines with it, the same way every
5
+ // time, and totalsFor() adds them up. Both are pure: no database, no clock.
6
+ import { QuotesError } from "./errors.js";
7
+ import { checkQuantity, lineCents, MAX_CENTS, mulDiv, toCents } from "./money.js";
8
+ /** The most lines on one quote. */
9
+ export const MAX_LINES = 200;
10
+ /** The longest line label, and the longest note and terms. */
11
+ export const MAX_LABEL = 200;
12
+ export const MAX_NOTE = 2000;
13
+ export const MAX_TERMS = 4000;
14
+ const NAME = /^[a-z][a-z0-9-]{0,39}$/;
15
+ const FIELD = /^[a-z][a-z0-9_]{0,62}$/;
16
+ const KIND_KEYS = new Set(["$schema", "format", "kind", "document", "form", "currency", "tax", "valid_days", "deposit_percent", "number_prefix", "items", "terms", "acceptance", "retention"]);
17
+ const ITEM_KEYS = new Set(["id", "label", "price", "quantity", "when"]);
18
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+ const whole = (v, min, max) => typeof v === "number" && Number.isInteger(v) && v >= min && v <= max;
20
+ /** Every problem with a kind's file, each naming the file and the setting. Empty when it's good. */
21
+ export function quoteKindProblems(json, file = "workbench/quotes/<kind>.json") {
22
+ const out = [];
23
+ const bad = (why) => out.push(`${file}: ${why}`);
24
+ if (!isObject(json))
25
+ return [`${file}: not a JSON object`];
26
+ const k = json;
27
+ for (const key of Object.keys(k))
28
+ if (!KIND_KEYS.has(key))
29
+ bad(`"${key}" is not a quote setting`);
30
+ if (k.format !== 1)
31
+ bad("format must be 1");
32
+ if (typeof k.kind !== "string" || !NAME.test(k.kind))
33
+ bad("kind is lower case letters, digits and hyphens, starting with a letter");
34
+ if (k.document !== "quote" && k.document !== "estimate")
35
+ bad('document is "quote" or "estimate"');
36
+ if (k.form !== undefined && (typeof k.form !== "string" || !FIELD.test(k.form)))
37
+ bad("form is a workbench-forms form's name");
38
+ if (typeof k.currency !== "string" || !/^[A-Z]{3}$/.test(k.currency))
39
+ bad('currency is a three-letter code such as "AUD"');
40
+ if (k.tax !== null) {
41
+ const t = k.tax;
42
+ if (!isObject(t))
43
+ bad('tax is { "name", "rate", "included" } or null');
44
+ else {
45
+ for (const key of Object.keys(t))
46
+ if (!["name", "rate", "included"].includes(key))
47
+ bad(`tax: "${key}" is not a tax setting`);
48
+ if (typeof t.name !== "string" || !t.name.trim() || t.name.length > 20)
49
+ bad("tax.name is the tax's short name, such as GST");
50
+ if (typeof t.rate !== "number" || !(t.rate > 0 && t.rate < 1) || Math.round(t.rate * 10000) !== t.rate * 10000)
51
+ bad("tax.rate is more than 0 and less than 1, at most four decimal places (0.1 for 10%)");
52
+ if (typeof t.included !== "boolean")
53
+ bad("tax.included is true when prices include the tax");
54
+ }
55
+ }
56
+ if (!whole(k.valid_days, 1, 365))
57
+ bad("valid_days is a whole number of days, 1 to 365");
58
+ if (!whole(k.deposit_percent, 0, 100))
59
+ bad("deposit_percent is a whole number, 0 to 100");
60
+ if (typeof k.number_prefix !== "string" || !/^[A-Za-z0-9-]{0,8}$/.test(k.number_prefix))
61
+ bad("number_prefix is up to 8 letters, digits or hyphens");
62
+ if (typeof k.terms !== "string" || k.terms.length > MAX_TERMS)
63
+ bad(`terms is text, up to ${MAX_TERMS} characters`);
64
+ if (!isObject(k.acceptance) || typeof k.acceptance.name_required !== "boolean" || Object.keys(k.acceptance).some((x) => x !== "name_required"))
65
+ bad('acceptance is { "name_required": true | false }');
66
+ if (!isObject(k.retention) || !whole(k.retention.unaccepted_days, 30, 3650) || Object.keys(k.retention).some((x) => x !== "unaccepted_days"))
67
+ bad('retention is { "unaccepted_days": 30 to 3650 }');
68
+ if (!Array.isArray(k.items) || k.items.length === 0 || k.items.length > MAX_LINES)
69
+ bad(`items is a list of 1 to ${MAX_LINES} priced items`);
70
+ else {
71
+ const ids = new Set();
72
+ k.items.forEach((item, i) => {
73
+ const at = `items[${i}]`;
74
+ if (!isObject(item))
75
+ return void bad(`${at} is not an object`);
76
+ for (const key of Object.keys(item))
77
+ if (!ITEM_KEYS.has(key))
78
+ bad(`${at}: "${key}" is not an item setting`);
79
+ if (typeof item.id !== "string" || !NAME.test(item.id))
80
+ bad(`${at}.id is lower case letters, digits and hyphens`);
81
+ else if (ids.has(item.id))
82
+ bad(`${at}.id ${item.id} is used twice`);
83
+ else
84
+ ids.add(item.id);
85
+ if (typeof item.label !== "string" || !item.label.trim() || item.label.length > MAX_LABEL)
86
+ bad(`${at}.label is the line's words, up to ${MAX_LABEL} characters`);
87
+ try {
88
+ const c = toCents(item.price, `${at}.price`);
89
+ if (typeof item.price !== "string")
90
+ bad(`${at}.price is decimal text such as "95.00"`);
91
+ if (Math.abs(c) > MAX_CENTS)
92
+ bad(`${at}.price is too large`);
93
+ }
94
+ catch (e) {
95
+ bad(e.message);
96
+ }
97
+ if (item.quantity !== undefined) {
98
+ const q = item.quantity;
99
+ if (!isObject(q))
100
+ bad(`${at}.quantity is { "field"?, "value"?, "min"? }`);
101
+ else {
102
+ for (const key of Object.keys(q))
103
+ if (!["field", "value", "min"].includes(key))
104
+ bad(`${at}.quantity: "${key}" is not a quantity setting`);
105
+ if (q.field !== undefined && (typeof q.field !== "string" || !FIELD.test(q.field)))
106
+ bad(`${at}.quantity.field is a form field's name`);
107
+ if (q.field !== undefined && q.value !== undefined)
108
+ bad(`${at}.quantity has a field or a value, not both`);
109
+ for (const n of ["value", "min"]) {
110
+ if (q[n] === undefined)
111
+ continue;
112
+ try {
113
+ checkQuantity(q[n], `${at}.quantity.${n}`);
114
+ }
115
+ catch (e) {
116
+ bad(e.message);
117
+ }
118
+ }
119
+ }
120
+ }
121
+ if (item.when !== undefined) {
122
+ const w = item.when;
123
+ if (!isObject(w) || typeof w.field !== "string" || !FIELD.test(w.field) || !Array.isArray(w.is) || w.is.length === 0 || w.is.some((v) => typeof v !== "string" || !v)) {
124
+ bad(`${at}.when is { "field": "<choice field>", "is": ["<value>", ...] }`);
125
+ }
126
+ }
127
+ });
128
+ }
129
+ return out;
130
+ }
131
+ /** Checks a kind's file and returns it typed. Throws bad_config naming every problem. */
132
+ export function checkQuoteKind(json, file) {
133
+ const problems = quoteKindProblems(json, file);
134
+ if (problems.length)
135
+ throw new QuotesError("bad_config", problems.join("\n"));
136
+ return json;
137
+ }
138
+ /** The form fields a kind reads, with what it needs of each: for `npx workbench-quotes generate` to check against the form. */
139
+ export function fieldsUsed(kind) {
140
+ const out = [];
141
+ for (const item of kind.items) {
142
+ if (item.quantity?.field)
143
+ out.push({ field: item.quantity.field, as: "quantity", item: item.id });
144
+ if (item.when)
145
+ out.push({ field: item.when.field, as: "choice", values: item.when.is, item: item.id });
146
+ }
147
+ return out;
148
+ }
149
+ function holds(answer, values) {
150
+ if (Array.isArray(answer))
151
+ return answer.some((a) => typeof a === "string" && values.includes(a));
152
+ return typeof answer === "string" && values.includes(answer);
153
+ }
154
+ /**
155
+ * The lines a kind's price list gives for a form's answers. An item whose
156
+ * `when` doesn't hold is left out, and so is one whose quantity field is
157
+ * empty or 0; a quantity under `min` is charged as `min`. Throws bad_input
158
+ * when a quantity answer isn't a number.
159
+ */
160
+ export function priceLines(kind, answers = {}) {
161
+ const lines = [];
162
+ for (const item of kind.items) {
163
+ if (item.when && !holds(answers[item.when.field], item.when.is))
164
+ continue;
165
+ let quantity;
166
+ if (item.quantity?.field) {
167
+ const raw = answers[item.quantity.field];
168
+ if (raw === undefined || raw === null || raw === "" || raw === 0 || raw === "0")
169
+ continue;
170
+ quantity = checkQuantity(raw, `the answer to ${item.quantity.field}`);
171
+ }
172
+ else
173
+ quantity = item.quantity?.value ?? 1;
174
+ if (item.quantity?.min !== undefined && quantity < item.quantity.min)
175
+ quantity = item.quantity.min;
176
+ const unit = toCents(item.price);
177
+ lines.push({ item: item.id, label: item.label, quantity, unit_cents: unit, total_cents: lineCents(quantity, unit) });
178
+ }
179
+ return lines;
180
+ }
181
+ /** Checks lines the app passes (the business edited or added some) and works out each line's amount. */
182
+ export function checkLines(lines) {
183
+ if (!Array.isArray(lines) || lines.length === 0 || lines.length > MAX_LINES)
184
+ throw new QuotesError("bad_input", `a quote has 1 to ${MAX_LINES} lines`);
185
+ return lines.map((l, i) => {
186
+ const at = `lines[${i}]`;
187
+ if (!isObject(l))
188
+ throw new QuotesError("bad_input", `${at} is not an object`);
189
+ if (typeof l.label !== "string" || !l.label.trim() || l.label.length > MAX_LABEL)
190
+ throw new QuotesError("bad_input", `${at}.label is 1 to ${MAX_LABEL} characters`);
191
+ if (l.item !== undefined && (typeof l.item !== "string" || !NAME.test(l.item)))
192
+ throw new QuotesError("bad_input", `${at}.item is a price list item's id`);
193
+ const quantity = checkQuantity(l.quantity ?? 1, `${at}.quantity`);
194
+ const unit = typeof l.unit_cents === "number" ? l.unit_cents : toCents(l.price, `${at}.price`);
195
+ if (!Number.isSafeInteger(unit) || Math.abs(unit) > MAX_CENTS)
196
+ throw new QuotesError("bad_input", `${at}.unit_cents is whole cents`);
197
+ const total = lineCents(quantity, unit);
198
+ if (Math.abs(total) > MAX_CENTS)
199
+ throw new QuotesError("bad_input", `${at} is too large`);
200
+ return { ...(typeof l.item === "string" ? { item: l.item } : {}), label: l.label.trim(), quantity, unit_cents: unit, total_cents: total };
201
+ });
202
+ }
203
+ /**
204
+ * Adds up lines. With tax included, the tax is the part of the total that is
205
+ * tax (a tenth of an Australian GST price is not the GST: it's 1/11).
206
+ * Without, it's added on top. The deposit is a share of the total.
207
+ */
208
+ export function totalsFor(lines, tax, depositPercent = 0) {
209
+ const subtotal = lines.reduce((s, l) => s + l.total_cents, 0);
210
+ if (Math.abs(subtotal) > MAX_CENTS)
211
+ throw new QuotesError("bad_input", "the quote's total is too large");
212
+ if (subtotal < 0)
213
+ throw new QuotesError("bad_input", "the quote's total can't be less than 0");
214
+ let taxCents = 0;
215
+ let total = subtotal;
216
+ if (tax) {
217
+ const bp = Math.round(tax.rate * 10000);
218
+ if (tax.included)
219
+ taxCents = subtotal - mulDiv(subtotal, 10000, 10000 + bp);
220
+ else {
221
+ taxCents = mulDiv(subtotal, bp, 10000);
222
+ total = subtotal + taxCents;
223
+ }
224
+ }
225
+ return { subtotal_cents: subtotal, tax_cents: taxCents, total_cents: total, deposit_cents: mulDiv(total, depositPercent, 100) };
226
+ }
227
+ /** A quote's lines and totals from a kind and a form's answers. */
228
+ export function priceQuote(kind, answers = {}) {
229
+ const lines = priceLines(kind, answers);
230
+ return { lines, ...totalsFor(lines, kind.tax, kind.deposit_percent) };
231
+ }
@@ -0,0 +1,4 @@
1
+ export declare const quotesMigration: {
2
+ up: string;
3
+ down: string;
4
+ };