@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.
@@ -0,0 +1,121 @@
1
+ import type { CountryPack } from "@mccaskie-labs/workbench-country";
2
+ import { type QuoteBusiness, type QuotePdfDocument } from "./document.ts";
3
+ import { type QuoteHandover } from "./handover.ts";
4
+ import { type Answers, type QuoteKind, type QuoteLine, type QuoteTotals } from "./kinds.ts";
5
+ import { type Quote, type QuoteStatus, type Subject } from "./types.ts";
6
+ import type { QuoteLang, QuoteStrings } from "./words.ts";
7
+ type DbError = {
8
+ message?: string;
9
+ code?: string;
10
+ details?: string;
11
+ } | null;
12
+ /** The part of a Supabase client quotes need. Any supabase-js client fits; use the service client. */
13
+ export interface QuotesClient {
14
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{
15
+ data: unknown;
16
+ error: DbError;
17
+ }>;
18
+ }
19
+ /** Who the quote is for: the app's customer record, and the name and email shown on the quote. */
20
+ export interface CustomerInput {
21
+ /** `{ type: "contact", id }` from workbench-contacts' contacts.record, or the app's own record. */
22
+ subject?: Subject | null;
23
+ name?: string | null;
24
+ email?: string | null;
25
+ }
26
+ export interface CreateQuoteRequest {
27
+ kind: string;
28
+ account: string;
29
+ customer?: CustomerInput;
30
+ /** The form's answers: the kind's price list makes the lines. */
31
+ answers?: Answers;
32
+ /** The lines as the business set them (edited, or added by hand): used instead of the price list. */
33
+ lines?: readonly (Partial<QuoteLine> & {
34
+ label: string;
35
+ price?: string;
36
+ })[];
37
+ /** A note to the customer, up to 2,000 characters. */
38
+ note?: string | null;
39
+ }
40
+ export interface UpdateQuoteRequest {
41
+ customer?: CustomerInput;
42
+ answers?: Answers;
43
+ lines?: CreateQuoteRequest["lines"];
44
+ note?: string | null;
45
+ }
46
+ /** What the accept page and the hooks see when a customer answers. */
47
+ export interface AcceptedEvent {
48
+ quote: Quote;
49
+ /** The hand-over to the payments and invoices tool. */
50
+ invoice: QuoteHandover;
51
+ }
52
+ export interface QuotesOptions {
53
+ /** The service client. */
54
+ db: QuotesClient;
55
+ /** QUOTE_KINDS from src/quotes.generated.ts (`npx workbench-quotes generate`). Checked here. */
56
+ kinds: Readonly<Record<string, unknown>>;
57
+ /** The environment's own address, such as https://staging.example.com.au: links are made on it. */
58
+ baseUrl: string;
59
+ /** The first part of a quote link's path. Default "quote": https://<domain>/quote/<token>. */
60
+ path?: string;
61
+ /** The business's name (and ABN, address) for an account, shown on the page and the PDF. */
62
+ business: (account: string) => Promise<QuoteBusiness | null>;
63
+ /** A country code or pack for money and dates. Default AU. */
64
+ country?: string | CountryPack;
65
+ /** The page's language for a quote. Default English. */
66
+ language?: (quote: Quote) => QuoteLang;
67
+ /** The app's strings catalogue. */
68
+ t?: QuoteStrings;
69
+ /** The page's stylesheets. Default /styles/workbench.css then /styles/project.css. */
70
+ styles?: readonly string[];
71
+ /** Makes the PDF (with workbench-pdf: `(q, doc) => pdf.document(doc)`). With it, the page has Download PDF. */
72
+ pdf?: (quote: Quote, doc: QuotePdfDocument) => Promise<Uint8Array>;
73
+ /** The customer accepted: make the invoice (workbench-payments), touch nudges, tell the owner. Runs once per quote. */
74
+ onAccepted?: (event: AcceptedEvent) => Promise<void> | void;
75
+ /** The customer declined. */
76
+ onDeclined?: (quote: Quote) => Promise<void> | void;
77
+ /** The clock, for tests. */
78
+ now?: () => Date;
79
+ }
80
+ /** The part of a Worker's ExecutionContext handle() uses. */
81
+ export interface WaitContext {
82
+ waitUntil(p: Promise<unknown>): void;
83
+ }
84
+ export interface Quotes {
85
+ /** The lines and totals a kind's price list gives for a form's answers, without saving anything. */
86
+ price(kind: string, answers: Answers): {
87
+ lines: QuoteLine[];
88
+ } & QuoteTotals;
89
+ /** A new draft, numbered for the account. */
90
+ create(req: CreateQuoteRequest): Promise<Quote>;
91
+ /** Changes a draft. Refused with wrong_status once sent: use revise. */
92
+ update(id: string, req: UpdateQuoteRequest): Promise<Quote>;
93
+ /** A new draft that replaces a sent quote: sending it withdraws the old one, whose link then says so. */
94
+ revise(id: string, req?: UpdateQuoteRequest): Promise<Quote>;
95
+ /** Sends a draft (or sends a sent quote again with a new link; the old link stops). Returns the link to give the customer. */
96
+ send(id: string): Promise<{
97
+ quote: Quote;
98
+ url: string;
99
+ }>;
100
+ /** Takes back a draft or a sent quote; its link shows it's no longer current. */
101
+ withdraw(id: string): Promise<Quote>;
102
+ get(id: string): Promise<Quote | null>;
103
+ /** An account's quotes, newest first. */
104
+ list(account: string, opts?: {
105
+ status?: QuoteStatus;
106
+ limit?: number;
107
+ }): Promise<Quote[]>;
108
+ /** The quote as workbench-pdf's standard layout, for pdf.document(). */
109
+ document(quote: Quote, opts?: {
110
+ url?: string;
111
+ }): Promise<QuotePdfDocument>;
112
+ /** Serves /<path>/<token> (the page), /accept and /decline (the forms) and /pdf. Null for any other address. */
113
+ handle(request: Request, ctx?: WaitContext): Promise<Response | null>;
114
+ /** The daily clean-up: quotes that weren't accepted, each kind's unaccepted_days after they ended. */
115
+ cleanup(): Promise<{
116
+ deleted: number;
117
+ }>;
118
+ readonly kinds: Readonly<Record<string, QuoteKind>>;
119
+ }
120
+ export declare function createQuotes(opts: QuotesOptions): Quotes;
121
+ export {};
package/dist/quotes.js ADDED
@@ -0,0 +1,313 @@
1
+ // createQuotes: quotes and estimates in the app's own database. The business
2
+ // makes a quote from a form's answers (priced by the kind's price list) or
3
+ // from its own lines, sends it (a link to the accept page, and a branded PDF
4
+ // through workbench-pdf), and the customer accepts or declines online. An
5
+ // accepted quote is handed to the payments and invoices tool as plain data
6
+ // (toInvoice), through the app's onAccepted.
7
+ //
8
+ // Use it with the service client, server side: the functions are the service
9
+ // role's only (see migration.ts). The app's own pages check that the signed-in
10
+ // owner may act for the account before calling create, send or withdraw.
11
+ import { length, tidyLine } from "@mccaskie-labs/workbench-forms";
12
+ import { quoteDocument } from "./document.js";
13
+ import { QuotesError } from "./errors.js";
14
+ import { toInvoice } from "./handover.js";
15
+ import { checkLines, checkQuoteKind, MAX_NOTE, priceLines, totalsFor } from "./kinds.js";
16
+ import { renderNotFoundPage, renderQuotePage } from "./page.js";
17
+ import { DECLINE_REASONS } from "./types.js";
18
+ const TOKEN = /^[A-Za-z0-9_-]{43}$/;
19
+ const PREVIEW = /bot|crawl|spider|preview|facebookexternalhit|whatsapp|slack|telegram|discord|skype|linkedin/i;
20
+ const MAX_BODY = 4096;
21
+ function newToken() {
22
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
23
+ let s = "";
24
+ for (const b of bytes)
25
+ s += String.fromCharCode(b);
26
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
27
+ }
28
+ async function sha256(text) {
29
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
30
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
31
+ }
32
+ function customerOf(c) {
33
+ const subject = c?.subject ?? null;
34
+ if (subject && (typeof subject.type !== "string" || !subject.type || subject.type.length > 60 || typeof subject.id !== "string" || !subject.id || subject.id.length > 200)) {
35
+ throw new QuotesError("bad_input", "customer.subject is { type, id } from the app's own tables");
36
+ }
37
+ const name = c?.name ? tidyLine(c.name) : null;
38
+ if (name !== null && (length(name) < 1 || length(name) > 120))
39
+ throw new QuotesError("bad_input", "customer.name is 1 to 120 characters");
40
+ const email = c?.email ? c.email.trim() : null;
41
+ if (email !== null && (email.length < 3 || email.length > 254 || !email.includes("@")))
42
+ throw new QuotesError("bad_input", "customer.email is an email address");
43
+ return { subject: subject ? { type: subject.type, id: subject.id } : null, name: name || null, email };
44
+ }
45
+ function noteOf(note) {
46
+ if (note === undefined || note === null || !note.trim())
47
+ return null;
48
+ if (note.length > MAX_NOTE)
49
+ throw new QuotesError("bad_input", `note is up to ${MAX_NOTE} characters`);
50
+ return note.trim();
51
+ }
52
+ export function createQuotes(opts) {
53
+ const kinds = {};
54
+ for (const [name, json] of Object.entries(opts.kinds)) {
55
+ const kind = checkQuoteKind(json, `workbench/quotes/${name}.json`);
56
+ if (kind.kind !== name)
57
+ throw new QuotesError("bad_config", `workbench/quotes/${name}.json: kind is ${kind.kind}, not ${name}`);
58
+ kinds[name] = kind;
59
+ }
60
+ let base;
61
+ try {
62
+ base = new URL(opts.baseUrl);
63
+ }
64
+ catch {
65
+ throw new QuotesError("bad_config", "baseUrl is the environment's https address");
66
+ }
67
+ if (base.protocol !== "https:" && base.hostname !== "localhost" && base.hostname !== "127.0.0.1")
68
+ throw new QuotesError("bad_config", "baseUrl must be https");
69
+ const path = opts.path ?? "quote";
70
+ if (!/^[a-z][a-z0-9-]{0,30}$/.test(path))
71
+ throw new QuotesError("bad_config", "path is lower case letters, digits and hyphens");
72
+ const prefix = `${base.pathname.replace(/\/$/, "")}/${path}/`;
73
+ const now = opts.now ?? (() => new Date());
74
+ const kindOf = (name) => {
75
+ const k = Object.hasOwn(kinds, name) ? kinds[name] : undefined;
76
+ if (!k)
77
+ throw new QuotesError("unknown_kind", `no quote kind ${name} (workbench/quotes/${name}.json)`);
78
+ return k;
79
+ };
80
+ async function call(fn, args) {
81
+ const { data, error } = await opts.db.rpc(fn, args);
82
+ if (error)
83
+ throw new QuotesError("store_failed", `${fn} failed${error.code ? ` (${error.code})` : ""}`);
84
+ if (data && typeof data === "object" && "error" in data && typeof data.error === "string") {
85
+ const code = data.error;
86
+ throw new QuotesError(code, `${fn}: ${code.replace(/_/g, " ")}`);
87
+ }
88
+ return data;
89
+ }
90
+ function linesFor(kind, req) {
91
+ if (req.lines)
92
+ return checkLines(req.lines);
93
+ const lines = priceLines(kind, req.answers ?? {});
94
+ if (lines.length === 0)
95
+ throw new QuotesError("bad_input", "the answers priced no lines: give lines, or answers that match the price list");
96
+ return lines;
97
+ }
98
+ async function business(account) {
99
+ const b = await opts.business(account);
100
+ if (!b || typeof b.name !== "string" || !b.name.trim())
101
+ throw new QuotesError("bad_input", "business() gave no name for the account");
102
+ return b;
103
+ }
104
+ const languageOf = (q) => opts.language?.(q) ?? "en";
105
+ const api = {
106
+ kinds,
107
+ price(name, answers) {
108
+ const kind = kindOf(name);
109
+ const lines = priceLines(kind, answers);
110
+ return { lines, ...totalsFor(lines, kind.tax, kind.deposit_percent) };
111
+ },
112
+ async create(req) {
113
+ const kind = kindOf(req.kind);
114
+ if (typeof req.account !== "string" || !req.account || req.account.length > 200)
115
+ throw new QuotesError("bad_input", "account is the business's id");
116
+ const lines = linesFor(kind, req);
117
+ const quote = {
118
+ account: req.account,
119
+ kind: kind.kind,
120
+ document: kind.document,
121
+ customer: customerOf(req.customer),
122
+ currency: kind.currency,
123
+ lines,
124
+ tax: kind.tax,
125
+ ...totalsFor(lines, kind.tax, kind.deposit_percent),
126
+ note: noteOf(req.note),
127
+ terms: kind.terms,
128
+ valid_days: kind.valid_days,
129
+ name_required: kind.acceptance.name_required,
130
+ retention_days: kind.retention.unaccepted_days,
131
+ replaces: req.replaces ?? null,
132
+ };
133
+ return call("quotes_create", { p_quote: quote, p_prefix: kind.number_prefix, p_now: now().toISOString() });
134
+ },
135
+ async update(id, req) {
136
+ const current = await api.get(id);
137
+ if (!current)
138
+ throw new QuotesError("unknown_quote", "no such quote");
139
+ if (current.status !== "draft")
140
+ throw new QuotesError("wrong_status", `quote ${current.number} has been sent: revise it instead`);
141
+ const kind = kindOf(current.kind);
142
+ const lines = req.lines || req.answers ? linesFor(kind, req) : current.lines;
143
+ const patch = {
144
+ customer: req.customer ? customerOf(req.customer) : current.customer,
145
+ lines,
146
+ ...totalsFor(lines, current.tax, kind.deposit_percent),
147
+ note: req.note === undefined ? current.note : noteOf(req.note),
148
+ };
149
+ return call("quotes_update", { p_id: id, p_quote: patch, p_now: now().toISOString() });
150
+ },
151
+ async revise(id, req = {}) {
152
+ const current = await api.get(id);
153
+ if (!current)
154
+ throw new QuotesError("unknown_quote", "no such quote");
155
+ if (current.status !== "sent" && current.status !== "expired")
156
+ throw new QuotesError("wrong_status", `quote ${current.number} is ${current.status}: only a sent quote is revised`);
157
+ const create = {
158
+ kind: current.kind,
159
+ account: current.account,
160
+ customer: req.customer ?? current.customer,
161
+ note: req.note === undefined ? current.note : req.note,
162
+ replaces: current.id,
163
+ ...(req.lines || req.answers ? { lines: req.lines, answers: req.answers } : { lines: current.lines }),
164
+ };
165
+ return api.create(create);
166
+ },
167
+ async send(id) {
168
+ const token = newToken();
169
+ const quote = await call("quotes_send", { p_id: id, p_token_hash: await sha256(token), p_now: now().toISOString() });
170
+ return { quote, url: new URL(`${prefix}${token}`, base).href };
171
+ },
172
+ async withdraw(id) {
173
+ return call("quotes_withdraw", { p_id: id, p_now: now().toISOString() });
174
+ },
175
+ async get(id) {
176
+ if (!/^[0-9a-f-]{36}$/i.test(id))
177
+ return null;
178
+ return (await call("quotes_get", { p_id: id, p_now: now().toISOString() })) ?? null;
179
+ },
180
+ async list(account, o = {}) {
181
+ return call("quotes_list", { p_account: account, p_status: o.status ?? null, p_limit: o.limit ?? 100, p_now: now().toISOString() });
182
+ },
183
+ async document(quote, o = {}) {
184
+ return quoteDocument(quote, { business: await business(quote.account), language: languageOf(quote), ...(opts.country ? { country: opts.country } : {}), ...(opts.t ? { t: opts.t } : {}), ...o });
185
+ },
186
+ async handle(request, ctx) {
187
+ const url = new URL(request.url);
188
+ if (!url.pathname.startsWith(prefix))
189
+ return null;
190
+ const [token, action, ...more] = url.pathname.slice(prefix.length).split("/");
191
+ if (more.length || (action !== undefined && !["accept", "decline", "pdf"].includes(action)))
192
+ return null;
193
+ const method = request.method;
194
+ const head = method === "HEAD";
195
+ const pagePath = `${prefix}${token}`;
196
+ const styles = opts.styles ? { styles: opts.styles } : {};
197
+ const headers = (type = "text/html; charset=utf-8") => new Headers({
198
+ "content-type": type,
199
+ "cache-control": "no-store",
200
+ "x-robots-tag": "noindex, nofollow",
201
+ "referrer-policy": "no-referrer",
202
+ "x-content-type-options": "nosniff",
203
+ "content-security-policy": "default-src 'none'; img-src https: data:; style-src 'self' https:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
204
+ });
205
+ const bare = (status, extra = {}) => new Response(null, { status, headers: { "cache-control": "no-store", ...extra } });
206
+ const notFound = () => new Response(head ? null : renderNotFoundPage({ ...(opts.t ? { t: opts.t } : {}), ...styles }), { status: 404, headers: headers() });
207
+ const posting = action === "accept" || action === "decline";
208
+ if (posting) {
209
+ if (method !== "POST")
210
+ return bare(405, { allow: "POST" });
211
+ const origin = request.headers.get("origin");
212
+ if (origin && origin !== url.origin && origin !== base.origin)
213
+ return bare(403);
214
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_BODY)
215
+ return bare(413);
216
+ }
217
+ else if (method !== "GET" && !head)
218
+ return bare(405, { allow: "GET, HEAD" });
219
+ if (!token || !TOKEN.test(token))
220
+ return notFound();
221
+ const hash = await sha256(token);
222
+ const at = now();
223
+ const page = async (quote, status, extra = {}) => {
224
+ const body = renderQuotePage(quote, {
225
+ business: await business(quote.account),
226
+ path: pagePath,
227
+ pdf: Boolean(opts.pdf),
228
+ language: languageOf(quote),
229
+ now: at,
230
+ ...(opts.country ? { country: opts.country } : {}),
231
+ ...(opts.t ? { t: opts.t } : {}),
232
+ ...styles,
233
+ ...extra,
234
+ });
235
+ return new Response(head ? null : body, { status, headers: headers() });
236
+ };
237
+ if (!posting) {
238
+ const counts = action === undefined && !head && !PREVIEW.test(request.headers.get("user-agent") ?? "");
239
+ const quote = await call("quotes_open", { p_token_hash: hash, p_count: counts, p_now: at.toISOString() });
240
+ if (!quote || quote.status === "draft")
241
+ return notFound();
242
+ if (action === "pdf") {
243
+ if (!opts.pdf)
244
+ return null;
245
+ const bytes = await opts.pdf(quote, await api.document(quote, { url: new URL(pagePath, base).href }));
246
+ const h = headers("application/pdf");
247
+ h.set("content-disposition", `inline; filename="${quote.number.replace(/[^A-Za-z0-9-]/g, "")}.pdf"`);
248
+ return new Response(head ? null : bytes, { status: 200, headers: h });
249
+ }
250
+ return page(quote, 200, { justAccepted: url.searchParams.get("done") === "accepted" && quote.status === "accepted" });
251
+ }
252
+ let form;
253
+ try {
254
+ const text = await request.text();
255
+ if (text.length > MAX_BODY)
256
+ return bare(413);
257
+ form = await new Response(text, { headers: { "content-type": request.headers.get("content-type") ?? "application/x-www-form-urlencoded" } }).formData();
258
+ }
259
+ catch {
260
+ return bare(400);
261
+ }
262
+ const current = await call("quotes_open", { p_token_hash: hash, p_count: false, p_now: at.toISOString() });
263
+ if (!current || current.status === "draft")
264
+ return notFound();
265
+ let name = null;
266
+ let reason = null;
267
+ if (action === "accept") {
268
+ const typed = typeof form.get("name") === "string" ? tidyLine(form.get("name")) : "";
269
+ const errors = [];
270
+ if (current.name_required && (length(typed) < 1 || length(typed) > 120))
271
+ errors.push("name");
272
+ if (form.get("agree") !== "yes")
273
+ errors.push("agree");
274
+ if (errors.length)
275
+ return page(current, 422, { errors, typedName: typed.slice(0, 120) });
276
+ name = current.name_required ? typed : null;
277
+ }
278
+ else {
279
+ const r = form.get("reason");
280
+ if (typeof r !== "string" || !DECLINE_REASONS.includes(r))
281
+ return page(current, 422);
282
+ reason = r;
283
+ }
284
+ const { data, error } = await opts.db.rpc("quotes_answer", { p_token_hash: hash, p_answer: action, p_name: name, p_reason: reason, p_now: at.toISOString() });
285
+ if (error)
286
+ throw new QuotesError("store_failed", `quotes_answer failed${error.code ? ` (${error.code})` : ""}`);
287
+ const result = data;
288
+ if (result.error === "unknown_quote" || !result.quote)
289
+ return notFound();
290
+ if (result.error)
291
+ return page(result.quote, 409);
292
+ if (result.changed) {
293
+ const hook = action === "accept" ? opts.onAccepted && (() => opts.onAccepted({ quote: result.quote, invoice: toInvoice(result.quote) })) : opts.onDeclined && (() => opts.onDeclined(result.quote));
294
+ if (hook) {
295
+ // The customer's answer stands whatever the hook does; a failing hook is the app's to retry from its own list.
296
+ const run = Promise.resolve()
297
+ .then(hook)
298
+ .catch(() => console.error(`workbench-quotes: the ${action === "accept" ? "onAccepted" : "onDeclined"} hook failed for quote ${result.quote.id}`));
299
+ if (ctx)
300
+ ctx.waitUntil(run);
301
+ else
302
+ await run;
303
+ }
304
+ }
305
+ return bare(303, { location: `${pagePath}${action === "accept" ? "?done=accepted" : ""}` });
306
+ },
307
+ async cleanup() {
308
+ const deleted = await call("quotes_cleanup", { p_now: now().toISOString() });
309
+ return { deleted: deleted ?? 0 };
310
+ },
311
+ };
312
+ return api;
313
+ }
@@ -0,0 +1,3 @@
1
+ import type { QuoteKind } from "./kinds.ts";
2
+ /** A starting workbench/quotes/<kind>.json. */
3
+ export declare function starterKind(kind?: string): QuoteKind;
@@ -0,0 +1,23 @@
1
+ // The starting price list `npx workbench-quotes init` writes: Australian
2
+ // defaults (AUD, GST included at 10%, 30 days, no deposit), with two example
3
+ // items to replace from the client's answers.
4
+ /** A starting workbench/quotes/<kind>.json. */
5
+ export function starterKind(kind = "job") {
6
+ return {
7
+ format: 1,
8
+ kind,
9
+ document: "quote",
10
+ currency: "AUD",
11
+ tax: { name: "GST", rate: 0.1, included: true },
12
+ valid_days: 30,
13
+ deposit_percent: 0,
14
+ number_prefix: "Q-",
15
+ items: [
16
+ { id: "call-out", label: "Call-out", price: "90.00" },
17
+ { id: "labour", label: "Labour, per hour", price: "95.00", quantity: { value: 2 } },
18
+ ],
19
+ terms: "This quote holds for 30 days from the date on it. Prices include GST.",
20
+ acceptance: { name_required: true },
21
+ retention: { unaccepted_days: 365 },
22
+ };
23
+ }
@@ -0,0 +1,34 @@
1
+ /** One CSS custom property the rules read, with its default. */
2
+ interface StyleVariable {
3
+ /** `--wb-<tool>-<what>`. */
4
+ name: string;
5
+ value: string;
6
+ about: string;
7
+ }
8
+ /** A rule for a class in another state, or for an element inside it. */
9
+ interface StyleState {
10
+ selector: string;
11
+ about: string;
12
+ css: string;
13
+ }
14
+ /** One class the tool puts on an element, with its default rule. */
15
+ interface StyleClass {
16
+ name: string;
17
+ element: string;
18
+ about: string;
19
+ css: string;
20
+ states?: readonly StyleState[];
21
+ }
22
+ /** Every class and variable the tool draws with. */
23
+ export interface ToolStyles {
24
+ format: 1;
25
+ tool: string;
26
+ package: string;
27
+ title: string;
28
+ prefix: string;
29
+ variables: readonly StyleVariable[];
30
+ classes: readonly StyleClass[];
31
+ }
32
+ /** The style hooks of the quote page (renderQuotePage). */
33
+ export declare const QUOTE_STYLES: ToolStyles;
34
+ export {};
package/dist/styles.js ADDED
@@ -0,0 +1,83 @@
1
+ // The look the accept page starts with (docs/capabilities-manifest.md §10).
2
+ // Every element renderQuotePage draws carries one of these classes, and every
3
+ // class has a default rule here, so the page looks finished out of the box and
4
+ // a project restyles it from its own CSS by the same names. `npx workbench-ui
5
+ // styles` writes these into the project's public/styles/workbench.css inside
6
+ // `@layer workbench`. The names are public: renaming one is a breaking change.
7
+ // The PDF is drawn by workbench-pdf, so it takes wb-pdf-* and the brand.
8
+ const v = (name) => `var(--wb-quote-${name})`;
9
+ const focus = { selector: ":focus-visible", about: "Has focus", css: `outline:none;box-shadow:0 0 0 3px ${v("focus")}` };
10
+ const button = `display:inline-flex;align-items:center;justify-content:center;min-height:2.75rem;padding:0 1.25rem;font:inherit;font-weight:600;border-radius:${v("radius")};cursor:pointer`;
11
+ const cell = `padding:.5rem .25rem;border-bottom:1px solid ${v("line")};vertical-align:top`;
12
+ /** The style hooks of the quote page (renderQuotePage). */
13
+ export const QUOTE_STYLES = {
14
+ format: 1,
15
+ tool: "quote",
16
+ package: "@mccaskie-labs/workbench-quotes",
17
+ title: "Quotes and estimates",
18
+ prefix: "wb-quote-",
19
+ variables: [
20
+ { name: "--wb-quote-text", value: "#1d1d22", about: "Text" },
21
+ { name: "--wb-quote-muted", value: "#5d5d68", about: "Quieter text: labels, the quantity, the terms" },
22
+ { name: "--wb-quote-page", value: "#f4f4f6", about: "Background behind the quote" },
23
+ { name: "--wb-quote-surface", value: "#ffffff", about: "Background of the quote and the forms" },
24
+ { name: "--wb-quote-line", value: "#dcdce2", about: "Borders and rules between lines" },
25
+ { name: "--wb-quote-accent", value: "#1b66d6", about: "The Accept button" },
26
+ { name: "--wb-quote-on-accent", value: "#ffffff", about: "Text on the Accept button" },
27
+ { name: "--wb-quote-good", value: "#1f7a3d", about: "The accepted notice" },
28
+ { name: "--wb-quote-ended", value: "#8a5a00", about: "The withdrawn, expired and declined notices" },
29
+ { name: "--wb-quote-error", value: "#b3261e", about: "A problem with what was typed" },
30
+ { name: "--wb-quote-focus", value: "rgba(27,102,214,.35)", about: "The ring round a control with focus" },
31
+ { name: "--wb-quote-radius", value: "8px", about: "Corner rounding" },
32
+ { name: "--wb-quote-width", value: "44rem", about: "The page's widest" },
33
+ ],
34
+ classes: [
35
+ { name: "wb-quote-page", element: "main", about: "The whole page", css: `box-sizing:border-box;max-width:${v("width")};margin:0 auto;padding:1rem;color:${v("text")};background:${v("page")}` },
36
+ { name: "wb-quote", element: "article", about: "The quote itself", css: `display:grid;gap:1rem;padding:1.25rem;background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}` },
37
+ { name: "wb-quote-header", element: "header", about: "The business and the title", css: "display:grid;gap:.25rem" },
38
+ { name: "wb-quote-business", element: "p", about: "The business's name", css: `margin:0;color:${v("muted")};font-weight:600` },
39
+ { name: "wb-quote-title", element: "h1", about: "\"Quote Q-0007\"", css: "margin:0;font-size:1.5rem;line-height:1.2" },
40
+ { name: "wb-quote-facts", element: "dl", about: "Number, date, valid until, prepared for", css: "display:grid;grid-template-columns:max-content 1fr;gap:.25rem 1rem;margin:0" },
41
+ { name: "wb-quote-label", element: "dt", about: "A fact's label", css: `color:${v("muted")}` },
42
+ { name: "wb-quote-value", element: "dd", about: "A fact's value", css: "margin:0" },
43
+ { name: "wb-quote-estimate", element: "p", about: "\"This is an estimate: the final price may change\"", css: `margin:0;padding:.5rem .75rem;border-left:4px solid ${v("ended")};background:${v("page")}` },
44
+ { name: "wb-quote-note", element: "p", about: "The business's note to the customer", css: "margin:0;white-space:pre-line" },
45
+ { name: "wb-quote-lines", element: "table", about: "The priced lines", css: "width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums" },
46
+ { name: "wb-quote-head", element: "th", about: "A column heading", css: `${cell};color:${v("muted")};font-weight:600;text-align:left`, states: [{ selector: ".wb-quote-num", about: "A number column's heading", css: "text-align:right" }] },
47
+ { name: "wb-quote-line", element: "tr", about: "One line", css: "break-inside:avoid" },
48
+ { name: "wb-quote-item", element: "td", about: "A line's words", css: cell },
49
+ { name: "wb-quote-num", element: "td", about: "A quantity, unit price or amount", css: `${cell};text-align:right;white-space:nowrap` },
50
+ { name: "wb-quote-totals", element: "dl", about: "Subtotal, tax, total and deposit", css: "display:grid;grid-template-columns:1fr max-content;gap:.25rem 1rem;margin:0;font-variant-numeric:tabular-nums" },
51
+ { name: "wb-quote-sum-label", element: "dt", about: "A total's label", css: "text-align:right" },
52
+ { name: "wb-quote-sum", element: "dd", about: "A total's amount", css: "margin:0;text-align:right" },
53
+ { name: "wb-quote-grand", element: "dt", about: "The total's label and amount (added to wb-quote-sum-label and wb-quote-sum)", css: "font-size:1.15rem;font-weight:700" },
54
+ { name: "wb-quote-terms", element: "section", about: "The terms", css: `color:${v("muted")};font-size:.9rem` },
55
+ { name: "wb-quote-terms-title", element: "h2", about: "\"Terms\"", css: "margin:0 0 .25rem;font-size:1rem" },
56
+ { name: "wb-quote-terms-text", element: "p", about: "The terms' words", css: "margin:0;white-space:pre-line" },
57
+ { name: "wb-quote-pdf", element: "a", about: "Download PDF", css: `color:${v("accent")};font-weight:600`, states: [focus] },
58
+ { name: "wb-quote-state", element: "p", about: "Where the quote stands: accepted, declined, withdrawn, expired", css: `margin:0;padding:.75rem;border-radius:${v("radius")};border:1px solid ${v("line")};font-weight:600` },
59
+ { name: "wb-quote-state-good", element: "p", about: "Accepted (added to wb-quote-state)", css: `color:${v("good")};border-color:${v("good")}` },
60
+ { name: "wb-quote-state-ended", element: "p", about: "Declined, withdrawn or expired (added to wb-quote-state)", css: `color:${v("ended")};border-color:${v("ended")}` },
61
+ { name: "wb-quote-accept", element: "form", about: "The accept form", css: `display:grid;gap:.75rem;padding:1rem;background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}` },
62
+ { name: "wb-quote-form-title", element: "h2", about: "\"Happy to go ahead?\" and \"Not going ahead?\"", css: "margin:0;font-size:1.15rem" },
63
+ { name: "wb-quote-field", element: "label", about: "The name's label and input", css: "display:grid;gap:.25rem;font-weight:600" },
64
+ {
65
+ name: "wb-quote-input",
66
+ element: "input",
67
+ about: "The name",
68
+ css: `box-sizing:border-box;width:100%;min-height:2.75rem;padding:0 .75rem;font:inherit;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}`,
69
+ states: [focus, { selector: "[aria-invalid=true]", about: "What was typed has a problem", css: `border-color:${v("error")}` }],
70
+ },
71
+ { name: "wb-quote-check", element: "label", about: "\"I accept this quote and its terms\" with its box", css: "display:flex;gap:.5rem;align-items:flex-start" },
72
+ { name: "wb-quote-box", element: "input", about: "A tick box or a reason's round button", css: "width:1.25rem;height:1.25rem;margin:.15rem 0 0;flex:none", states: [focus] },
73
+ { name: "wb-quote-error", element: "p", about: "What to fix", css: `margin:0;color:${v("error")};font-weight:600` },
74
+ { name: "wb-quote-accept-button", element: "button", about: "Accept", css: `${button};color:${v("on-accent")};background:${v("accent")};border:1px solid ${v("accent")}`, states: [focus] },
75
+ { name: "wb-quote-decline", element: "details", about: "The decline form, folded", css: `padding:1rem;background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}` },
76
+ { name: "wb-quote-decline-title", element: "summary", about: "\"Not going ahead?\"", css: "cursor:pointer;font-weight:600" },
77
+ { name: "wb-quote-decline-form", element: "form", about: "The reasons and Decline", css: "display:grid;gap:.75rem;margin-top:.75rem" },
78
+ { name: "wb-quote-reasons", element: "fieldset", about: "The reasons", css: "display:grid;gap:.5rem;margin:0;padding:0;border:0" },
79
+ { name: "wb-quote-reasons-title", element: "legend", about: "\"What's the main reason?\"", css: "padding:0;margin-bottom:.25rem;font-weight:600" },
80
+ { name: "wb-quote-reason", element: "label", about: "One reason with its round button", css: "display:flex;gap:.5rem;align-items:flex-start" },
81
+ { name: "wb-quote-decline-button", element: "button", about: "Decline", css: `${button};color:${v("text")};background:transparent;border:1px solid ${v("line")}`, states: [focus] },
82
+ ],
83
+ };
@@ -0,0 +1,53 @@
1
+ import type { QuoteLine, QuoteTax } from "./kinds.ts";
2
+ export declare const QUOTE_STATUSES: readonly ["draft", "sent", "accepted", "declined", "withdrawn", "expired"];
3
+ /** expired is worked out when read: a sent quote past its valid-until date. */
4
+ export type QuoteStatus = (typeof QUOTE_STATUSES)[number];
5
+ /** Why a customer declined: picked from a list, never typed, so no customer's words are kept. */
6
+ export declare const DECLINE_REASONS: readonly ["price", "timing", "elsewhere", "not_needed", "other"];
7
+ export type DeclineReason = (typeof DECLINE_REASONS)[number];
8
+ /** A row in the app's own tables (its customer record): `{ type: "contact", id }` with workbench-contacts. */
9
+ export interface Subject {
10
+ type: string;
11
+ id: string;
12
+ }
13
+ export interface QuoteCustomer {
14
+ subject: Subject | null;
15
+ /** Shown on the quote ("Prepared for"). Blanked with the quote's other personal details when an unaccepted quote is deleted. */
16
+ name: string | null;
17
+ email: string | null;
18
+ }
19
+ export interface Quote {
20
+ id: string;
21
+ account: string;
22
+ kind: string;
23
+ /** Q-0001: one sequence per account. */
24
+ number: string;
25
+ document: "quote" | "estimate";
26
+ status: QuoteStatus;
27
+ customer: QuoteCustomer;
28
+ currency: string;
29
+ lines: QuoteLine[];
30
+ tax: QuoteTax | null;
31
+ subtotal_cents: number;
32
+ tax_cents: number;
33
+ total_cents: number;
34
+ deposit_cents: number;
35
+ /** The business's note to the customer, if any. */
36
+ note: string | null;
37
+ terms: string;
38
+ valid_days: number;
39
+ name_required: boolean;
40
+ /** The quote this one replaces: sending it withdraws that one. */
41
+ replaces: string | null;
42
+ created_at: string;
43
+ sent_at: string | null;
44
+ valid_until: string | null;
45
+ viewed_at: string | null;
46
+ views: number;
47
+ accepted_at: string | null;
48
+ /** The full name the customer typed to accept. */
49
+ accepted_name: string | null;
50
+ declined_at: string | null;
51
+ decline_reason: DeclineReason | null;
52
+ withdrawn_at: string | null;
53
+ }
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ // A quote as the package returns it, read from the app's own database.
2
+ export const QUOTE_STATUSES = ["draft", "sent", "accepted", "declined", "withdrawn", "expired"];
3
+ /** Why a customer declined: picked from a list, never typed, so no customer's words are kept. */
4
+ export const DECLINE_REASONS = ["price", "timing", "elsewhere", "not_needed", "other"];