@bendyline/gilde 0.3.5 → 0.3.6
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/authoring/chat-models/gemma4-12b-q4.json +7 -3
- package/authoring/chat-models/qwen3.8-flash-next-q2.json +24 -7
- package/data/chat-models/ge/gemma4-12b-q4/manifest.json +46 -3
- package/data/chat-models/ge/gemma4-12b-q4/versions/1.2.1/manifest.json +141 -0
- package/data/chat-models/ge/gemma4-e4b-q4/manifest.json +5 -0
- package/data/chat-models/index.json +1 -1
- package/data/chat-models/or/ornith1.5-9b-q4/manifest.json +5 -0
- package/data/chat-models/or/ornith1.5-9b-q8/manifest.json +5 -0
- package/data/chat-models/qw/qwen3.5-9b-q4/manifest.json +5 -0
- package/data/chat-models/qw/qwen3.8-27b-q4/manifest.json +5 -0
- package/data/chat-models/qw/qwen3.8-flash-next-q2/manifest.json +24 -7
- package/data/chat-models/qw/qwen3.8-flash-next-q2/versions/1.0.3/manifest.json +47 -0
- package/data/chat-models/raw-index.json +1 -1
- package/data/craftbook-templates/al/alert-rules/versions/1.0.6/craftbook.json +383 -0
- package/data/craftbook-templates/al/alert-rules/versions/1.0.6/test.json +145 -0
- package/data/craftbook-templates/index.json +1 -1
- package/data/craftbook-templates/raw-index.json +1 -1
- package/data/craftbook-templates/re/refactor-module/versions/2.0.8/craftbook.json +754 -0
- package/data/craftbook-templates/re/refactor-module/versions/2.0.8/test.json +241 -0
- package/data/project-types/index.json +1 -1
- package/data/project-types/qu/quotes-and-bids/versions/1.0.0/manifest.json +1 -1
- package/data/project-types/qu/quotes-and-bids/versions/1.0.0/pages/quotes/index.html +1 -1
- package/data/project-types/raw-index.json +1 -1
- package/package.json +1 -1
- package/schemas/chat-model-identity.schema.json +31 -0
- package/schemas/chat-model-version.schema.json +66 -0
- package/schemas/craftbook-doc.schema.json +15 -0
- package/schemas/craftbook-template-version.schema.json +12 -0
- package/schemas/craftbook-test.schema.json +12 -0
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
}
|
|
38
38
|
],
|
|
39
39
|
"scripts": {
|
|
40
|
-
"quote-store": "import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'quote-store',\n description:\n \"Price jobs and track quotes (quotes.json) at the business's own rates, tax and terms (rates.json). action:'status' for every quote with its exact total, the follow-ups due and the win/loss record; 'add' to start a quote (an existing title is updated, never duplicated); 'add_line' and 'remove_line' to price it (the script works out every amount and the tax); 'send', 'follow_up' and 'outcome' as it moves; 'set_rate' and 'set_terms' for the business's rates, tax and quote terms; 'show' for one quote line by line.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add', 'add_line', 'remove_line', 'send', 'follow_up', 'outcome', 'set_rate', 'set_terms', 'show', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Quote id, e.g. 'q-3'.\" },\n title: {\n type: 'string',\n description: \"The job, e.g. 'Harbor Street Café kitchen rewire'. Also finds the quote (or its client) when no id is given.\",\n },\n client: { type: 'string', description: 'Who the quote is for.' },\n contact: { type: 'string', description: 'The person there.' },\n site: { type: 'string', description: 'Where the work is.' },\n kind: { type: 'string', description: 'labor, materials, or other.' },\n description: { type: 'string', description: \"What the line is, e.g. 'Electrician labor' or '200A panel'.\" },\n qty: { type: 'number', description: 'Quantity, e.g. 16 hours or 2 panels (default 1).' },\n addQty: { type: 'number', description: \"Add to the quantity of the line with this description, e.g. 6 more hours.\" },\n unit: { type: 'string', description: 'hour, each, foot, or lot.' },\n rate: { type: 'number', description: 'Price per unit in dollars, e.g. 95.' },\n rateName: { type: 'string', description: \"A saved rate by name, e.g. 'Electrician'; it fills the rate, unit and kind.\" },\n line: { type: 'number', description: 'Line number, for remove_line.' },\n name: { type: 'string', description: \"For set_rate: the rate's name, e.g. 'Electrician'.\" },\n taxRate: { type: 'number', description: 'For set_terms: the sales tax percent the business charges, e.g. 8.25 (0 for none).' },\n taxOn: { type: 'string', description: 'For set_terms: materials (tax on materials only) or all (the whole quote).' },\n validDays: { type: 'number', description: 'How many days a quote stays valid after sending.' },\n followUpDays: { type: 'number', description: 'For set_terms: days after sending to follow up.' },\n followUpAt: { type: 'string', description: 'Next follow-up date, YYYY-MM-DD.' },\n inDays: { type: 'number', description: 'Next follow-up this many days from today, instead of followUpAt.' },\n outcome: { type: 'string', description: 'won or lost.' },\n note: { type: 'string', description: 'What happened or why, in the words given.' },\n withinDays: { type: 'number', description: 'How many days ahead counts for follow-ups (default 7).' },\n },\n outputs: {\n drafts: { type: 'number', description: 'Quotes still being priced.' },\n waiting: { type: 'number', description: 'Quotes sent and waiting for an answer.' },\n followUpsDue: { type: 'number', description: 'Follow-ups overdue or due today.' },\n total: { type: 'number', description: 'The total of the quote this call acted on, in dollars (0 when none).' },\n summary: { type: 'string', description: 'What changed, then the quotes picture; or one quote line by line; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── quote-rules-start ──\n// Pure derivations: money in integer cents, line amounts and quote totals that\n// are exact to the cent (quantities to a thousandth, tax rates in basis\n// points, both rounded half up), local calendar days for follow-ups, finding a\n// quote or a line by name, and the quotes picture the crew reads. Kept\n// self-contained between these sentinels so unit tests execute the shipped\n// bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['draft', 'sent', 'won', 'lost'];\nvar KINDS = ['labor', 'materials', 'other'];\nvar NAME_STOP = ['the', 'and', 'for', 'with', 'our', 'quote', 'bid', 'job', 'estimate'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(raw)) return raw.slice(0, 10);\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'today';\n if (days === 1) return 'tomorrow';\n return 'in ' + days + ' days';\n}\nfunction cap(text) {\n return String(text).charAt(0).toUpperCase() + String(text).slice(1);\n}\nfunction ago(days) {\n return days <= 0 ? 'today' : days === 1 ? 'yesterday' : days + ' days ago';\n}\n// Dollars as a number or text ('$1,850', '95.50') to integer cents; null when it is not money.\nfunction toCents(value) {\n if (typeof value === 'string') value = Number(value.replace(/[$,\\s]/g, ''));\n if (typeof value !== 'number' || !isFinite(value)) return null;\n return (value < 0 ? -1 : 1) * Math.round(Math.abs(value) * 100);\n}\n// A quantity in thousandths, so 6.5 hours or 12.25 feet multiply exactly.\nfunction toMilli(qty) {\n if (typeof qty === 'string') qty = Number(qty.replace(/[,\\s]/g, ''));\n return typeof qty === 'number' && isFinite(qty) && qty > 0 ? Math.round(qty * 1000) : null;\n}\nfunction money(cents) {\n var n = Math.round(Number(cents) || 0);\n var abs = Math.abs(n);\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (n < 0 ? '-$' : '$') + whole + '.' + pad(abs % 100);\n}\nfunction percent(bp) {\n return (bp / 100).toFixed(2).replace(/\\.?0+$/, '') + '%';\n}\nfunction fold(text) {\n return String(text || '')\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[‘’]/g, \"'\")\n .toLowerCase()\n .trim();\n}\n// Quantity times rate, rounded half away from zero to the cent.\nfunction lineAmount(qtyMilli, rateCents) {\n var x = qtyMilli * rateCents;\n return (x < 0 ? -1 : 1) * Math.floor((Math.abs(x) + 500) / 1000);\n}\nfunction qtyText(qty, unit) {\n var n = Math.round(Number(qty) * 1000) / 1000;\n var u = String(unit || 'each');\n if (n === 1 || u === 'each' || u === 'lot' || /s$/.test(u)) return n + ' ' + u;\n return n + ' ' + (u === 'foot' ? 'feet' : /(x|ch|sh)$/.test(u) ? u + 'es' : u + 's');\n}\nfunction totals(lines, taxBp, taxOn) {\n var t = { labor: 0, materials: 0, other: 0, subtotal: 0, taxable: 0, tax: 0, total: 0 };\n (lines || []).forEach(function (l) {\n var a = Number(l.amountCents) || 0;\n t[KINDS.indexOf(l.kind) >= 0 ? l.kind : 'other'] += a;\n t.subtotal += a;\n });\n t.taxable = Math.max(0, taxOn === 'all' ? t.subtotal : t.materials);\n t.tax = Math.floor((t.taxable * (taxBp || 0) + 5000) / 10000);\n t.total = t.subtotal + t.tax;\n return t;\n}\nfunction quoteTotals(record) {\n var f = record.fields || {};\n return totals(f.lines, f.taxBp, f.taxOn);\n}\n// The fields a quote stores beside its lines, so a reader never re-adds them.\nfunction totalFields(lines, taxBp, taxOn) {\n var t = totals(lines, taxBp, taxOn);\n return { laborCents: t.labor, materialsCents: t.materials, otherCents: t.other, subtotalCents: t.subtotal, taxCents: t.tax, totalCents: t.total };\n}\nfunction normalizeTerms(doc) {\n var d = doc && typeof doc === 'object' ? doc : {};\n var whole = function (v, fallback) {\n return typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : fallback;\n };\n return {\n version: 1,\n taxBp: typeof d.taxBp === 'number' && Number.isInteger(d.taxBp) && d.taxBp >= 0 ? d.taxBp : 0,\n taxOn: d.taxOn === 'all' ? 'all' : 'materials',\n validDays: whole(d.validDays, 30),\n followUpDays: whole(d.followUpDays, 5),\n rates: (Array.isArray(d.rates) ? d.rates : []).filter(function (r) {\n return r && typeof r.name === 'string' && typeof r.rateCents === 'number' && Number.isInteger(r.rateCents);\n }),\n };\n}\nfunction rateText(r) {\n return r.name + ' ' + money(r.rateCents) + '/' + r.unit + ' (' + r.kind + ')';\n}\nfunction findRate(rates, name) {\n var wanted = fold(name);\n if (!wanted) return null;\n var exact = rates.filter(function (r) { return fold(r.name) === wanted; });\n if (exact.length) return exact[0];\n var partial = rates.filter(function (r) { return fold(r.name).indexOf(wanted) >= 0 || wanted.indexOf(fold(r.name)) >= 0; });\n return partial.length === 1 ? partial[0] : null;\n}\nfunction lineText(l) {\n return '#' + l.n + ' ' + l.description + ', ' + qtyText(l.qty, l.unit) + ' x ' + money(l.rateCents) + ' = ' + money(l.amountCents) + ' (' + l.kind + ')';\n}\n// Add a line, or change the one with the same description. Returns the new\n// list and what changed; the caller re-totals.\nfunction upsertLine(lines, input, terms) {\n var list = (lines || []).map(function (l) { return Object.assign({}, l); });\n var saved = input.rateName ? findRate(terms.rates, input.rateName) : null;\n if (input.rateName && !saved) {\n throw new Error(\n \"No saved rate named '\" + input.rateName + \"'. Saved rates: \" +\n (terms.rates.map(rateText).join(', ') || 'none yet; pass rate in dollars') + '.',\n );\n }\n var description = String(input.description || (saved && saved.name) || '').trim();\n if (!description) throw new Error(\"add_line needs 'description', e.g. 'Electrician labor' or '200A panel'.\");\n var existing = list.filter(function (l) { return fold(l.description) === fold(description); })[0] || null;\n if (!existing && !saved && (input.rate === undefined || input.rate === null || input.rate === '')) saved = findRate(terms.rates, description);\n var rateCents =\n input.rate !== undefined && input.rate !== null && input.rate !== ''\n ? toCents(input.rate)\n : saved ? saved.rateCents : existing ? existing.rateCents : null;\n if (rateCents === null) {\n throw new Error(\n \"'\" + description + \"' needs 'rate' (dollars per unit) or 'rateName'\" +\n (terms.rates.length ? ' from the saved rates: ' + terms.rates.map(rateText).join(', ') : '') + '.',\n );\n }\n var kind = KINDS.indexOf(input.kind) >= 0 ? input.kind : saved ? saved.kind : existing ? existing.kind : 'other';\n if (rateCents < 0 && kind !== 'other') throw new Error('Only an \"other\" line can be a credit with a negative rate.');\n var unit = input.unit ? String(input.unit).trim() : saved ? saved.unit : existing ? existing.unit : 'each';\n var add = input.addQty !== undefined && input.addQty !== null && input.addQty !== '' ? toMilli(input.addQty) : null;\n var set = input.qty !== undefined && input.qty !== null && input.qty !== '' ? toMilli(input.qty) : null;\n if (add === null && input.addQty !== undefined && input.addQty !== null && input.addQty !== '') throw new Error('addQty must be a positive number.');\n if (set === null && input.qty !== undefined && input.qty !== null && input.qty !== '') throw new Error('qty must be a positive number.');\n var before = existing ? Math.round(existing.qty * 1000) : 0;\n var qtyMilli = add !== null ? before + add : set !== null ? set : existing ? before : 1000;\n var line = { description: existing ? existing.description : description, kind: kind, qty: qtyMilli / 1000, unit: unit, rateCents: rateCents, amountCents: lineAmount(qtyMilli, rateCents) };\n if (existing) Object.assign(existing, line);\n else list.push(line);\n list.forEach(function (l, i) { l.n = i + 1; });\n var placed = existing || list[list.length - 1];\n return {\n lines: list,\n note:\n (existing ? 'Updated line ' : 'Added line ') + lineText(placed) +\n (existing && add !== null ? ' (' + before / 1000 + ' + ' + add / 1000 + ')' : '') + '.',\n };\n}\nfunction removeLine(lines, input) {\n var list = (lines || []).map(function (l) { return Object.assign({}, l); });\n var hit = null;\n if (input.line !== undefined && input.line !== null && input.line !== '') {\n hit = list.filter(function (l) { return l.n === Number(input.line); })[0] || null;\n } else if (input.description) {\n var wanted = fold(input.description);\n var exact = list.filter(function (l) { return fold(l.description) === wanted; });\n var partial = list.filter(function (l) { return fold(l.description).indexOf(wanted) >= 0; });\n hit = exact[0] || (partial.length === 1 ? partial[0] : null);\n }\n if (!hit) {\n throw new Error(\n \"Name the line by 'line' number or 'description'. Lines: \" + (list.map(lineText).join('; ') || 'none') + '.',\n );\n }\n var rest = list.filter(function (l) { return l !== hit; });\n rest.forEach(function (l, i) { l.n = i + 1; });\n return { lines: rest, note: 'Removed ' + hit.description + ' (' + money(hit.amountCents) + ').' };\n}\nfunction isOpen(record) {\n return record.status === 'draft' || record.status === 'sent';\n}\n// The quote a person means: its id, its exact title, a title or client that\n// contains what they wrote, or one whose name holds every word they used.\n// Several matches prefer the open quotes; a tie is an error that names them.\nfunction findQuote(records, input) {\n if (input.id) {\n var byId = records.filter(function (r) { return r.id === String(input.id).trim(); });\n if (byId.length) return byId[0];\n if (!input.title && !input.client) throw new Error(\"No quote '\" + input.id + \"'. \" + roll(records));\n }\n var wanted = fold(input.title || input.client);\n if (!wanted) throw new Error(\"Pass 'id' (e.g. 'q-3') or the quote's 'title'. \" + roll(records));\n var name = function (r) { return fold(r.fields.title); };\n var both = function (r) { return name(r) + ' ' + fold(r.fields.client); };\n var words = wanted.split(/[^a-z0-9']+/).filter(function (w) { return w.length > 2 && NAME_STOP.indexOf(w) < 0; });\n var tiers = [\n function (r) { return name(r) === wanted; },\n function (r) { return name(r).indexOf(wanted) >= 0 || fold(r.fields.client) === wanted; },\n function (r) {\n return words.length > 0 && words.every(function (w) { return both(r).indexOf(w) >= 0 || both(r).indexOf(w.replace(/s$/, '')) >= 0; });\n },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hits = records.filter(tiers[i]);\n if (hits.length > 1) {\n var open = hits.filter(isOpen);\n if (open.length) hits = open;\n }\n if (hits.length === 1) return hits[0];\n if (hits.length > 1) {\n throw new Error(\n \"More than one quote matches '\" + (input.title || input.client) + \"': \" +\n hits.map(function (r) { return r.id + ' ' + r.fields.title; }).join(', ') + '. Pass id.',\n );\n }\n }\n throw new Error(\"No quote matches '\" + (input.title || input.client) + \"'. \" + roll(records));\n}\nfunction roll(records) {\n return records.length\n ? 'Quotes: ' + records.map(function (r) { return r.id + ' ' + r.fields.title + ' (' + r.status + ')'; }).join(', ') + '.'\n : 'There are no quotes yet.';\n}\nfunction lastNote(record) {\n var notes = (record.history || []).filter(function (h) { return h.note; });\n return notes.length ? notes[notes.length - 1].note : '';\n}\nfunction quoteLine(record, nowMs) {\n var f = record.fields || {};\n var t = quoteTotals(record);\n var lines = (f.lines || []).length;\n var head =\n record.id + (f.client && fold(f.title).indexOf(fold(f.client)) < 0 ? ', ' + f.client : '') + ', ' + record.status + ', ' +\n lines + (lines === 1 ? ' line' : ' lines') + ', total ' + money(t.total) + (t.tax ? ' with ' + money(t.tax) + ' tax' : '');\n var parts = [head];\n if (record.status === 'sent') {\n if (f.sentAt) parts.push('sent ' + ago(-daysLeft(f.sentAt, nowMs)));\n if (f.followUpAt) parts.push('follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')');\n if (f.validUntil) parts.push((daysLeft(f.validUntil, nowMs) < 0 ? 'expired ' : 'valid until ') + f.validUntil);\n }\n if (!isOpen(record) && f.closedAt) parts.push(record.status + ' ' + f.closedAt + (f.reason ? ': ' + f.reason : ''));\n return f.title + ' (' + parts.join('; ') + ')';\n}\nfunction followLine(record, nowMs) {\n var f = record.fields;\n var note = lastNote(record).replace(/[.\\s]+$/, '');\n return (\n f.title + ' (' + record.id + (f.contact ? ', ' + f.contact : '') + ', ' + money(quoteTotals(record).total) +\n (f.sentAt ? ', sent ' + ago(-daysLeft(f.sentAt, nowMs)) : '') + ') ' + when(daysLeft(f.followUpAt, nowMs)) +\n (note && note !== 'Sent to the client' ? '; last note: ' + note : '')\n );\n}\nfunction picture(records, terms, nowMs, withinDays) {\n var byStatus = function (s) { return records.filter(function (r) { return r.status === s; }); };\n var drafts = byStatus('draft');\n var sent = byStatus('sent');\n var won = byStatus('won');\n var lost = byStatus('lost');\n var total = function (list) { return list.reduce(function (t, r) { return t + quoteTotals(r).total; }, 0); };\n var due = sent\n .filter(function (r) { return r.fields.followUpAt && daysLeft(r.fields.followUpAt, nowMs) <= withinDays; })\n .sort(function (a, b) { return String(a.fields.followUpAt).localeCompare(String(b.fields.followUpAt)); });\n var dueNow = due.filter(function (r) { return daysLeft(r.fields.followUpAt, nowMs) <= 0; });\n var recentFirst = function (list) {\n return list.slice().sort(function (a, b) { return String(b.fields.closedAt || '').localeCompare(String(a.fields.closedAt || '')); });\n };\n var parts = [\n records.length + (records.length === 1 ? ' quote: ' : ' quotes: ') + drafts.length + ' draft, ' + sent.length +\n ' sent and waiting (' + money(total(sent)) + '), ' + won.length + ' won, ' + lost.length + ' lost.',\n ];\n // One list, overdue first: a model asked what needs chasing reads a separate late list as out of scope.\n parts.push(\n due.length\n ? 'Follow-ups within ' + withinDays + ' days, overdue first: ' + due.map(function (r) { return followLine(r, nowMs); }).join(' | ') + '.'\n : 'No follow-ups due in the next ' + withinDays + ' days.',\n );\n if (drafts.length) parts.push('Drafts: ' + drafts.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (sent.length) parts.push('Sent and waiting: ' + sent.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (won.length) parts.push('Won (latest first): ' + recentFirst(won).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (lost.length) parts.push('Lost (latest first): ' + recentFirst(lost).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (won.length + lost.length) {\n var decided = total(won) + total(lost);\n parts.push(\n 'Win rate: ' + won.length + ' of ' + (won.length + lost.length) + ' decided quotes (' + Math.round((won.length / (won.length + lost.length)) * 100) + '%), ' +\n money(total(won)) + ' of ' + money(decided) + ' by value.',\n );\n }\n parts.push(\n 'Tax: ' + (terms.taxBp ? percent(terms.taxBp) + ' on ' + (terms.taxOn === 'all' ? 'the whole quote' : 'materials') : 'none set') +\n '. Quotes stay valid ' + terms.validDays + ' days; follow up ' + terms.followUpDays + ' days after sending. Saved rates: ' +\n (terms.rates.map(rateText).join(', ') || 'none yet') + '.',\n );\n return {\n drafts: drafts.length,\n waiting: sent.length,\n followUpsDue: dueNow.length,\n summary: parts.join(' '),\n };\n}\n// One quote line by line, for the person to read or the crew to quote exactly.\nfunction detail(record, nowMs) {\n var f = record.fields || {};\n var t = quoteTotals(record);\n var rows = (f.lines || []).map(lineText);\n return [\n f.title + ' (' + record.id + ', ' + record.status + (f.client ? ', for ' + f.client : '') + (f.site ? ' at ' + f.site : '') + ').',\n rows.length ? 'Lines: ' + rows.join('; ') + '.' : 'No lines yet.',\n 'Labor ' + money(t.labor) + ', materials ' + money(t.materials) + (t.other ? ', other ' + money(t.other) : '') +\n '. Subtotal ' + money(t.subtotal) + '. Tax ' + money(t.tax) +\n (f.taxBp ? ' (' + percent(f.taxBp) + ' on ' + (f.taxOn === 'all' ? 'the whole quote' : 'materials ' + money(t.materials)) + ')' : ' (no tax set)') +\n '. Total ' + money(t.total) + '.',\n record.status === 'sent'\n ? 'Sent ' + f.sentAt + (f.followUpAt ? '; follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')' : '') +\n (f.validUntil ? '; valid until ' + f.validUntil : '') + '.'\n : !isOpen(record) && f.closedAt\n ? cap(record.status) + ' ' + f.closedAt + (f.reason ? ': ' + f.reason : '') + '.'\n : '',\n ]\n .filter(Boolean)\n .join(' ');\n}\n// ── quote-rules-end ──\n\ntype Quote = { id: string; status: string; fields: Record<string, unknown>; history?: Array<{ note?: string }> };\ntype Line = Record<string, unknown>;\n\nconst quotes = rosterStore(gezel.fs, 'quotes.json', { stages: ['draft', 'sent', 'won', 'lost'], idPrefix: 'q' });\nconst now = Date.now();\nconst today = localDay(now);\n\nfunction given(value: unknown): boolean {\n return value !== undefined && value !== null && value !== '';\n}\n\nasync function readTerms(): Promise<ReturnType<typeof normalizeTerms>> {\n let raw: string | null = null;\n try {\n raw = await gezel.fs.read('rates.json');\n } catch {\n raw = null;\n }\n if (raw === null) return normalizeTerms(null);\n try {\n return normalizeTerms(JSON.parse(raw));\n } catch {\n throw new Error('rates.json is not valid JSON. Fix or remove it; it will not be overwritten automatically.');\n }\n}\n\nasync function writeTerms(terms: ReturnType<typeof normalizeTerms>): Promise<void> {\n await gezel.fs.write('rates.json', JSON.stringify(terms, null, 2) + '\\n');\n}\n\nfunction followUpInput(): string | undefined {\n if (typeof input.inDays === 'number' && isFinite(input.inDays)) return addDays(today, Math.max(0, Math.round(input.inDays)));\n if (given(input.followUpAt)) {\n const day = normalizeDate(input.followUpAt);\n if (!day) throw new Error(\"followUpAt must be a date, e.g. '2026-11-20', or pass inDays.\");\n return day;\n }\n return undefined;\n}\n\nfunction wholeDays(value: unknown, label: string): number | undefined {\n if (!given(value)) return undefined;\n const n = Number(value);\n if (!isFinite(n) || n < 1 || n > 365) throw new Error(label + ' is a number of days from 1 to 365.');\n return Math.round(n);\n}\n\n// Lines change only on an open quote; a sent one goes back to draft so the\n// client is never holding a price the register no longer shows.\nasync function reprice(record: Quote, lines: Line[], what: string): Promise<string> {\n const f = record.fields;\n const title = String(f.title);\n if (!isOpen(record)) throw new Error(title + ' is ' + record.status + '; its price is settled. Start a new quote for more work.');\n await quotes.update(record.id, { fields: { lines, ...totalFields(lines, f.taxBp, f.taxOn) } });\n let tail = '';\n if (record.status === 'sent') {\n await quotes.update(record.id, { fields: { followUpAt: null } });\n await quotes.transition(record.id, 'draft', { note: 'Revised after sending: ' + what });\n tail = ' It had been sent, so it is back in draft: send it again when the client should see the new price.';\n }\n return what + ' ' + title + ' total now ' + money(totals(lines, f.taxBp, f.taxOn).total) + '.' + tail;\n}\n\n// The quotes' one reminder sits on the soonest follow-up, the morning it is due.\nasync function remindNextFollowUp(): Promise<void> {\n const next = (await quotes.list())\n .filter((r) => r.status === 'sent' && typeof r.fields.followUpAt === 'string')\n .map((r) => ({ record: r, at: Date.parse(String(r.fields.followUpAt) + 'T09:00:00') }))\n .filter((r) => r.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) await gezel.reminder.clear();\n else {\n const f = next.record.fields;\n await gezel.reminder.set({\n at: new Date(next.at).toISOString(),\n title: ('Follow up on the quote for ' + String(f.client || f.title)).slice(0, 80),\n body: (String(f.title) + ', ' + money(quoteTotals(next.record).total) + ', sent ' + String(f.sentAt) + '.').slice(0, 160),\n });\n }\n } catch {\n // Reminders are a convenience; the quotes are the record.\n }\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 7;\nlet note = '';\nlet acted: string | null = null;\nlet shown = '';\n\nif (input.action === 'add') {\n const all = (await quotes.list()) as Quote[];\n const title = String(input.title || input.client || '').trim();\n let existing: Quote | null = null;\n if (given(input.id)) existing = findQuote(all, { id: input.id, title: input.title });\n else if (title) existing = all.find((r) => fold(r.fields.title) === fold(title)) ?? null;\n if (!existing && !title) throw new Error(\"add needs 'title': the job, e.g. 'Maple Row panel upgrade'.\");\n const fields: Record<string, unknown> = {};\n if (input.client) fields.client = input.client.trim();\n if (input.contact) fields.contact = input.contact.trim();\n if (input.site) fields.site = input.site.trim();\n if (input.note) fields.note = input.note.trim();\n if (existing) {\n if (given(input.id) && input.title && fold(input.title) !== fold(existing.fields.title)) fields.title = input.title.trim();\n await quotes.update(existing.id, { fields });\n acted = existing.id;\n note = 'Updated ' + String(existing.fields.title) + '.';\n } else {\n const terms = await readTerms();\n const record = await quotes.add({\n status: 'draft',\n fields: { title, ...fields, lines: [], taxBp: terms.taxBp, taxOn: terms.taxOn, ...totalFields([], terms.taxBp, terms.taxOn) },\n });\n acted = record.id;\n note = 'Started ' + record.id + ': ' + title + ' (draft). Add its lines next.';\n }\n} else if (input.action === 'add_line' || input.action === 'remove_line') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const lines = (record.fields.lines ?? []) as Line[];\n const change = input.action === 'add_line' ? upsertLine(lines, input, await readTerms()) : removeLine(lines, input);\n note = await reprice(record, change.lines, change.note);\n acted = record.id;\n} else if (input.action === 'send') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n acted = record.id;\n if (record.status === 'sent') note = title + ' was already sent on ' + String(record.fields.sentAt) + '.';\n else if (!isOpen(record)) throw new Error(title + ' is ' + record.status + '; it cannot be sent again.');\n else {\n if (!((record.fields.lines ?? []) as Line[]).length) throw new Error(title + ' has no lines yet; add them before sending.');\n const terms = await readTerms();\n const validUntil = addDays(today, wholeDays(input.validDays, 'validDays') ?? terms.validDays);\n const follow = followUpInput() ?? addDays(today, terms.followUpDays);\n await quotes.update(record.id, { fields: { sentAt: today, validUntil, followUpAt: follow } });\n await quotes.transition(record.id, 'sent', { note: input.note || 'Sent to the client.' });\n note = 'Sent ' + title + ', total ' + money(quoteTotals(record).total) + '. Valid until ' + validUntil + '; first follow-up ' + follow + '.';\n }\n} else if (input.action === 'follow_up') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n if (record.status !== 'sent') {\n throw new Error(title + ' is ' + record.status + (record.status === 'draft' ? '; send it before following up.' : '; it is closed.'));\n }\n const next = followUpInput() ?? addDays(today, (await readTerms()).followUpDays);\n await quotes.update(record.id, { fields: { followUpAt: next, lastFollowUpAt: today }, note: input.note || 'Followed up.' });\n acted = record.id;\n note = 'Logged the follow-up on ' + title + (input.note ? ': ' + input.note.trim() : '') + '. Next follow-up ' + next + '.';\n} else if (input.action === 'outcome') {\n const outcome = String(input.outcome || '').trim().toLowerCase();\n if (outcome !== 'won' && outcome !== 'lost') throw new Error(\"outcome needs 'outcome': won or lost.\");\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n acted = record.id;\n if (record.status === outcome) note = title + ' is already ' + outcome + '.';\n else if (!isOpen(record)) throw new Error(title + ' is already ' + record.status + '.');\n else {\n await quotes.update(record.id, { fields: { closedAt: today, followUpAt: null, ...(input.note ? { reason: input.note.trim() } : {}) } });\n await quotes.transition(record.id, outcome, { note: input.note || (outcome === 'won' ? 'Won.' : 'Lost.') });\n note = (outcome === 'won' ? 'Won ' : 'Lost ') + title + ', ' + money(quoteTotals(record).total) + (input.note ? ' (' + input.note.trim() + ')' : '') + '.';\n }\n} else if (input.action === 'set_rate') {\n const name = String(input.name || input.description || '').trim();\n if (!name) throw new Error(\"set_rate needs 'name', e.g. 'Electrician'.\");\n const rateCents = toCents(input.rate);\n if (rateCents === null || rateCents < 0) throw new Error(\"set_rate needs 'rate' in dollars per unit, e.g. 95.\");\n const kind = KINDS.indexOf(String(input.kind)) >= 0 ? String(input.kind) : 'labor';\n const unit = input.unit ? input.unit.trim() : kind === 'labor' ? 'hour' : 'each';\n const terms = await readTerms();\n const at = terms.rates.findIndex((r) => fold(r.name) === fold(name));\n const rate = { name, kind, unit, rateCents };\n if (at >= 0) terms.rates[at] = rate;\n else terms.rates.push(rate);\n await writeTerms(terms);\n note = (at >= 0 ? 'Updated the rate ' : 'Saved the rate ') + rateText(rate) + '. Lines already on quotes keep their price; new lines use this one.';\n} else if (input.action === 'set_terms') {\n const terms = await readTerms();\n let changed = false;\n if (given(input.taxRate)) {\n const p = Number(String(input.taxRate).replace('%', ''));\n if (!isFinite(p) || p < 0 || p > 50) throw new Error('taxRate is a percent, e.g. 8.25 (0 for none).');\n terms.taxBp = Math.round(p * 100);\n changed = true;\n }\n if (given(input.taxOn)) {\n const on = String(input.taxOn).trim().toLowerCase();\n if (on !== 'materials' && on !== 'all') throw new Error('taxOn is materials or all.');\n terms.taxOn = on;\n changed = true;\n }\n const valid = wholeDays(input.validDays, 'validDays');\n if (valid !== undefined) terms.validDays = valid;\n const follow = wholeDays(input.followUpDays, 'followUpDays');\n if (follow !== undefined) terms.followUpDays = follow;\n if (!changed && valid === undefined && follow === undefined) throw new Error('set_terms needs taxRate, taxOn, validDays or followUpDays.');\n await writeTerms(terms);\n // Drafts follow the business's tax; sent and closed quotes keep the tax they went out with.\n const drafts = (await quotes.list()).filter((r) => r.status === 'draft');\n for (const d of drafts) {\n await quotes.update(d.id, {\n fields: { taxBp: terms.taxBp, taxOn: terms.taxOn, ...totalFields((d.fields.lines ?? []) as Line[], terms.taxBp, terms.taxOn) },\n });\n }\n note =\n 'Tax is ' + (terms.taxBp ? percent(terms.taxBp) + ' on ' + (terms.taxOn === 'all' ? 'the whole quote' : 'materials') : 'not charged') +\n '; quotes stay valid ' + terms.validDays + ' days; follow up ' + terms.followUpDays + ' days after sending.' +\n (drafts.length ? ' Re-totaled ' + drafts.length + (drafts.length === 1 ? ' draft' : ' drafts') + '; sent quotes keep the tax they went out with.' : '');\n} else if (input.action === 'show') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n acted = record.id;\n shown = detail(record, now);\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\n \"Unknown action '\" + input.action + \"'. Use status, add, add_line, remove_line, send, follow_up, outcome, set_rate, set_terms, show, or list.\",\n );\n}\n\nconst records = (await quotes.list()) as Quote[];\nconst view = picture(records, await readTerms(), now, withinDays);\nconst touched = acted ? records.find((r) => r.id === acted) : undefined;\nawait remindNextFollowUp();\n\ngezel.output({\n drafts: view.drafts,\n waiting: view.waiting,\n followUpsDue: view.followUpsDue,\n total: touched ? quoteTotals(touched).total / 100 : 0,\n summary: shown\n ? shown\n : input.action === 'list'\n ? records.map((r) => '[' + r.status + '] ' + quoteLine(r, now)).join('\\n') || 'There are no quotes yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"
|
|
40
|
+
"quote-store": "import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';\nimport { rosterStore } from '@bendyline/gezel-sdk/stores';\n\nexport const meta = defineScript({\n name: 'quote-store',\n description:\n \"Price jobs and track quotes (quotes.json) at the business's own rates, tax and terms (rates.json). action:'status' for every quote with its exact total, the follow-ups due and the win/loss record; 'add' to start a quote (an existing title is updated, never duplicated); 'add_line' and 'remove_line' to price it (the script works out every amount and the tax); 'send', 'follow_up' and 'outcome' as it moves; 'set_rate' and 'set_terms' for the business's rates, tax and quote terms; 'show' for one quote line by line.\",\n inputs: {\n action: {\n type: 'string',\n description:\n \"One of 'status', 'add', 'add_line', 'remove_line', 'send', 'follow_up', 'outcome', 'set_rate', 'set_terms', 'show', or 'list'.\",\n required: true,\n },\n id: { type: 'string', description: \"Quote id, e.g. 'q-3'.\" },\n title: {\n type: 'string',\n description: \"The job, e.g. 'Harbor Street Café kitchen rewire'. Also finds the quote (or its client) when no id is given.\",\n },\n client: { type: 'string', description: 'Who the quote is for.' },\n contact: { type: 'string', description: 'The person there.' },\n site: { type: 'string', description: 'Where the work is.' },\n kind: { type: 'string', description: 'labor, materials, or other.' },\n description: { type: 'string', description: \"What the line is, e.g. 'Electrician labor' or '200A panel'.\" },\n qty: { type: 'number', description: 'Quantity, e.g. 16 hours or 2 panels (default 1).' },\n addQty: { type: 'number', description: \"Add to the quantity of the line with this description, e.g. 6 more hours.\" },\n unit: { type: 'string', description: 'hour, each, foot, or lot.' },\n rate: { type: 'number', description: 'Price per unit in dollars, e.g. 95.' },\n rateName: { type: 'string', description: \"A saved rate by name, e.g. 'Electrician'; it fills the rate, unit and kind.\" },\n line: { type: 'number', description: 'Line number, for remove_line.' },\n name: { type: 'string', description: \"For set_rate: the rate's name, e.g. 'Electrician'.\" },\n taxRate: { type: 'number', description: 'For set_terms: the sales tax percent the business charges, e.g. 8.25 (0 for none).' },\n taxOn: { type: 'string', description: 'For set_terms: materials (tax on materials only) or all (the whole quote).' },\n validDays: { type: 'number', description: 'How many days a quote stays valid after sending.' },\n followUpDays: { type: 'number', description: 'For set_terms: days after sending to follow up.' },\n followUpAt: { type: 'string', description: 'Next follow-up date, YYYY-MM-DD.' },\n inDays: { type: 'number', description: 'Next follow-up this many days from today, instead of followUpAt.' },\n outcome: { type: 'string', description: 'won or lost.' },\n note: { type: 'string', description: 'What happened or why, in the words given.' },\n withinDays: { type: 'number', description: 'How many days ahead counts for follow-ups (default 7).' },\n },\n outputs: {\n drafts: { type: 'number', description: 'Quotes still being priced.' },\n waiting: { type: 'number', description: 'Quotes sent and waiting for an answer.' },\n followUpsDue: { type: 'number', description: 'Follow-ups overdue or due today.' },\n total: { type: 'number', description: 'The total of the quote this call acted on, in dollars (0 when none).' },\n summary: { type: 'string', description: 'What changed, then the quotes picture; or one quote line by line; or the listing.' },\n },\n requires: ['workspace.read', 'workspace.write', 'reminders'],\n} as const);\n\nconst input = gezel.input as InferredInput<typeof meta>;\n\n// ── quote-rules-start ──\n// Pure derivations: money in integer cents, line amounts and quote totals that\n// are exact to the cent (quantities to a thousandth, tax rates in basis\n// points, both rounded half up), local calendar days for follow-ups, finding a\n// quote or a line by name, and the quotes picture the crew reads. Kept\n// self-contained between these sentinels so unit tests execute the shipped\n// bytes.\nvar DAY_MS = 86400000;\nvar STAGES = ['draft', 'sent', 'won', 'lost'];\nvar KINDS = ['labor', 'materials', 'other'];\nvar NAME_STOP = ['the', 'and', 'for', 'with', 'our', 'quote', 'bid', 'job', 'estimate'];\n\nfunction pad(n) {\n return n < 10 ? '0' + n : String(n);\n}\nfunction localDay(ms) {\n var d = new Date(ms);\n return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());\n}\nfunction normalizeDate(text) {\n var raw = String(text || '').trim();\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(raw)) return raw.slice(0, 10);\n var parsed = Date.parse(raw);\n return isFinite(parsed) ? localDay(parsed) : null;\n}\nfunction daysLeft(day, nowMs) {\n var due = Date.parse(String(day).slice(0, 10) + 'T00:00:00');\n var today = Date.parse(localDay(nowMs) + 'T00:00:00');\n return Math.round((due - today) / DAY_MS);\n}\nfunction addDays(day, n) {\n var d = new Date(String(day).slice(0, 10) + 'T12:00:00');\n d.setDate(d.getDate() + n);\n return localDay(d.getTime());\n}\nfunction when(days) {\n if (days < 0) return -days + (days === -1 ? ' day late' : ' days late');\n if (days === 0) return 'today';\n if (days === 1) return 'tomorrow';\n return 'in ' + days + ' days';\n}\nfunction cap(text) {\n return String(text).charAt(0).toUpperCase() + String(text).slice(1);\n}\nfunction ago(days) {\n return days <= 0 ? 'today' : days === 1 ? 'yesterday' : days + ' days ago';\n}\n// Dollars as a number or text ('$1,850', '95.50') to integer cents; null when it is not money.\nfunction toCents(value) {\n if (typeof value === 'string') value = Number(value.replace(/[$,\\s]/g, ''));\n if (typeof value !== 'number' || !isFinite(value)) return null;\n return (value < 0 ? -1 : 1) * Math.round(Math.abs(value) * 100);\n}\n// A quantity in thousandths, so 6.5 hours or 12.25 feet multiply exactly.\nfunction toMilli(qty) {\n if (typeof qty === 'string') qty = Number(qty.replace(/[,\\s]/g, ''));\n return typeof qty === 'number' && isFinite(qty) && qty > 0 ? Math.round(qty * 1000) : null;\n}\nfunction money(cents) {\n var n = Math.round(Number(cents) || 0);\n var abs = Math.abs(n);\n var whole = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n return (n < 0 ? '-$' : '$') + whole + '.' + pad(abs % 100);\n}\nfunction percent(bp) {\n return (bp / 100).toFixed(2).replace(/\\.?0+$/, '') + '%';\n}\nfunction fold(text) {\n return String(text || '')\n .normalize('NFD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/[‘’]/g, \"'\")\n .toLowerCase()\n .trim();\n}\n// Quantity times rate, rounded half away from zero to the cent.\nfunction lineAmount(qtyMilli, rateCents) {\n var x = qtyMilli * rateCents;\n return (x < 0 ? -1 : 1) * Math.floor((Math.abs(x) + 500) / 1000);\n}\nfunction qtyText(qty, unit) {\n var n = Math.round(Number(qty) * 1000) / 1000;\n var u = String(unit || 'each');\n if (n === 1 || u === 'each' || u === 'lot' || /s$/.test(u)) return n + ' ' + u;\n return n + ' ' + (u === 'foot' ? 'feet' : /(x|ch|sh)$/.test(u) ? u + 'es' : u + 's');\n}\nfunction totals(lines, taxBp, taxOn) {\n var t = { labor: 0, materials: 0, other: 0, subtotal: 0, taxable: 0, tax: 0, total: 0 };\n (lines || []).forEach(function (l) {\n var a = Number(l.amountCents) || 0;\n t[KINDS.indexOf(l.kind) >= 0 ? l.kind : 'other'] += a;\n t.subtotal += a;\n });\n t.taxable = Math.max(0, taxOn === 'all' ? t.subtotal : t.materials);\n t.tax = Math.floor((t.taxable * (taxBp || 0) + 5000) / 10000);\n t.total = t.subtotal + t.tax;\n return t;\n}\nfunction quoteTotals(record) {\n var f = record.fields || {};\n return totals(f.lines, f.taxBp, f.taxOn);\n}\n// The fields a quote stores beside its lines, so a reader never re-adds them.\nfunction totalFields(lines, taxBp, taxOn) {\n var t = totals(lines, taxBp, taxOn);\n return { laborCents: t.labor, materialsCents: t.materials, otherCents: t.other, subtotalCents: t.subtotal, taxCents: t.tax, totalCents: t.total };\n}\nfunction normalizeTerms(doc) {\n var d = doc && typeof doc === 'object' ? doc : {};\n var whole = function (v, fallback) {\n return typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : fallback;\n };\n return {\n version: 1,\n taxBp: typeof d.taxBp === 'number' && Number.isInteger(d.taxBp) && d.taxBp >= 0 ? d.taxBp : 0,\n taxOn: d.taxOn === 'all' ? 'all' : 'materials',\n validDays: whole(d.validDays, 30),\n followUpDays: whole(d.followUpDays, 5),\n rates: (Array.isArray(d.rates) ? d.rates : []).filter(function (r) {\n return r && typeof r.name === 'string' && typeof r.rateCents === 'number' && Number.isInteger(r.rateCents);\n }),\n };\n}\nfunction rateText(r) {\n return r.name + ' ' + money(r.rateCents) + '/' + r.unit + ' (' + r.kind + ')';\n}\nfunction findRate(rates, name) {\n var wanted = fold(name);\n if (!wanted) return null;\n var exact = rates.filter(function (r) { return fold(r.name) === wanted; });\n if (exact.length) return exact[0];\n var partial = rates.filter(function (r) { return fold(r.name).indexOf(wanted) >= 0 || wanted.indexOf(fold(r.name)) >= 0; });\n return partial.length === 1 ? partial[0] : null;\n}\nfunction lineText(l) {\n return '#' + l.n + ' ' + l.description + ', ' + qtyText(l.qty, l.unit) + ' x ' + money(l.rateCents) + ' = ' + money(l.amountCents) + ' (' + l.kind + ')';\n}\n// Add a line, or change the one with the same description. Returns the new\n// list and what changed; the caller re-totals.\nfunction upsertLine(lines, input, terms) {\n var list = (lines || []).map(function (l) { return Object.assign({}, l); });\n var saved = input.rateName ? findRate(terms.rates, input.rateName) : null;\n if (input.rateName && !saved) {\n throw new Error(\n \"No saved rate named '\" + input.rateName + \"'. Saved rates: \" +\n (terms.rates.map(rateText).join(', ') || 'none yet; pass rate in dollars') + '.',\n );\n }\n var description = String(input.description || (saved && saved.name) || '').trim();\n if (!description) throw new Error(\"add_line needs 'description', e.g. 'Electrician labor' or '200A panel'.\");\n var existing = list.filter(function (l) { return fold(l.description) === fold(description); })[0] || null;\n if (!existing && !saved && (input.rate === undefined || input.rate === null || input.rate === '')) saved = findRate(terms.rates, description);\n var rateCents =\n input.rate !== undefined && input.rate !== null && input.rate !== ''\n ? toCents(input.rate)\n : saved ? saved.rateCents : existing ? existing.rateCents : null;\n if (rateCents === null) {\n throw new Error(\n \"'\" + description + \"' needs 'rate' (dollars per unit) or 'rateName'\" +\n (terms.rates.length ? ' from the saved rates: ' + terms.rates.map(rateText).join(', ') : '') + '.',\n );\n }\n var kind = KINDS.indexOf(input.kind) >= 0 ? input.kind : saved ? saved.kind : existing ? existing.kind : 'other';\n if (rateCents < 0 && kind !== 'other') throw new Error('Only an \"other\" line can be a credit with a negative rate.');\n var unit = input.unit ? String(input.unit).trim() : saved ? saved.unit : existing ? existing.unit : 'each';\n var add = input.addQty !== undefined && input.addQty !== null && input.addQty !== '' ? toMilli(input.addQty) : null;\n var set = input.qty !== undefined && input.qty !== null && input.qty !== '' ? toMilli(input.qty) : null;\n if (add === null && input.addQty !== undefined && input.addQty !== null && input.addQty !== '') throw new Error('addQty must be a positive number.');\n if (set === null && input.qty !== undefined && input.qty !== null && input.qty !== '') throw new Error('qty must be a positive number.');\n var before = existing ? Math.round(existing.qty * 1000) : 0;\n var qtyMilli = add !== null ? before + add : set !== null ? set : existing ? before : 1000;\n var line = { description: existing ? existing.description : description, kind: kind, qty: qtyMilli / 1000, unit: unit, rateCents: rateCents, amountCents: lineAmount(qtyMilli, rateCents) };\n if (existing) Object.assign(existing, line);\n else list.push(line);\n list.forEach(function (l, i) { l.n = i + 1; });\n var placed = existing || list[list.length - 1];\n return {\n lines: list,\n note:\n (existing ? 'Updated line ' : 'Added line ') + lineText(placed) +\n (existing && add !== null ? ' (' + before / 1000 + ' + ' + add / 1000 + ')' : '') + '.',\n };\n}\nfunction removeLine(lines, input) {\n var list = (lines || []).map(function (l) { return Object.assign({}, l); });\n var hit = null;\n if (input.line !== undefined && input.line !== null && input.line !== '') {\n hit = list.filter(function (l) { return l.n === Number(input.line); })[0] || null;\n } else if (input.description) {\n var wanted = fold(input.description);\n var exact = list.filter(function (l) { return fold(l.description) === wanted; });\n var partial = list.filter(function (l) { return fold(l.description).indexOf(wanted) >= 0; });\n hit = exact[0] || (partial.length === 1 ? partial[0] : null);\n }\n if (!hit) {\n throw new Error(\n \"Name the line by 'line' number or 'description'. Lines: \" + (list.map(lineText).join('; ') || 'none') + '.',\n );\n }\n var rest = list.filter(function (l) { return l !== hit; });\n rest.forEach(function (l, i) { l.n = i + 1; });\n return { lines: rest, note: 'Removed ' + hit.description + ' (' + money(hit.amountCents) + ').' };\n}\nfunction isOpen(record) {\n return record.status === 'draft' || record.status === 'sent';\n}\n// The quote a person means: its id, its exact title, a title or client that\n// contains what they wrote, or one whose name holds every word they used.\n// Several matches prefer the open quotes; a tie is an error that names them.\nfunction findQuote(records, input) {\n if (input.id) {\n var byId = records.filter(function (r) { return r.id === String(input.id).trim(); });\n if (byId.length) return byId[0];\n if (!input.title && !input.client) throw new Error(\"No quote '\" + input.id + \"'. \" + roll(records));\n }\n var wanted = fold(input.title || input.client);\n if (!wanted) throw new Error(\"Pass 'id' (e.g. 'q-3') or the quote's 'title'. \" + roll(records));\n var name = function (r) { return fold(r.fields.title); };\n var both = function (r) { return name(r) + ' ' + fold(r.fields.client); };\n var words = wanted.split(/[^a-z0-9']+/).filter(function (w) { return w.length > 2 && NAME_STOP.indexOf(w) < 0; });\n var tiers = [\n function (r) { return name(r) === wanted; },\n function (r) { return name(r).indexOf(wanted) >= 0 || fold(r.fields.client) === wanted; },\n function (r) {\n return words.length > 0 && words.every(function (w) { return both(r).indexOf(w) >= 0 || both(r).indexOf(w.replace(/s$/, '')) >= 0; });\n },\n ];\n for (var i = 0; i < tiers.length; i++) {\n var hits = records.filter(tiers[i]);\n if (hits.length > 1) {\n var open = hits.filter(isOpen);\n if (open.length) hits = open;\n }\n if (hits.length === 1) return hits[0];\n if (hits.length > 1) {\n throw new Error(\n \"More than one quote matches '\" + (input.title || input.client) + \"': \" +\n hits.map(function (r) { return r.id + ' ' + r.fields.title; }).join(', ') + '. Pass id.',\n );\n }\n }\n throw new Error(\"No quote matches '\" + (input.title || input.client) + \"'. \" + roll(records));\n}\nfunction roll(records) {\n return records.length\n ? 'Quotes: ' + records.map(function (r) { return r.id + ' ' + r.fields.title + ' (' + r.status + ')'; }).join(', ') + '.'\n : 'There are no quotes yet.';\n}\nfunction lastNote(record) {\n var notes = (record.history || []).filter(function (h) { return h.note; });\n return notes.length ? notes[notes.length - 1].note : '';\n}\nfunction quoteLine(record, nowMs) {\n var f = record.fields || {};\n var t = quoteTotals(record);\n var lines = (f.lines || []).length;\n var head =\n record.id + (f.client && fold(f.title).indexOf(fold(f.client)) < 0 ? ', ' + f.client : '') + ', ' + record.status + ', ' +\n lines + (lines === 1 ? ' line' : ' lines') + ', total ' + money(t.total) + (t.tax ? ' with ' + money(t.tax) + ' tax' : '');\n var parts = [head];\n if (record.status === 'sent') {\n if (f.sentAt) parts.push('sent ' + ago(-daysLeft(f.sentAt, nowMs)));\n if (f.followUpAt) parts.push('follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')');\n if (f.validUntil) parts.push((daysLeft(f.validUntil, nowMs) < 0 ? 'expired ' : 'valid until ') + f.validUntil);\n }\n if (!isOpen(record) && f.closedAt) parts.push(record.status + ' ' + f.closedAt + (f.reason ? ': ' + f.reason : ''));\n return f.title + ' (' + parts.join('; ') + ')';\n}\nfunction followLine(record, nowMs) {\n var f = record.fields;\n var note = lastNote(record).replace(/[.\\s]+$/, '');\n return (\n f.title + ' (' + record.id + (f.contact ? ', ' + f.contact : '') + ', ' + money(quoteTotals(record).total) +\n (f.sentAt ? ', sent ' + ago(-daysLeft(f.sentAt, nowMs)) : '') + ') ' + when(daysLeft(f.followUpAt, nowMs)) +\n (note && note !== 'Sent to the client' ? '; last note: ' + note : '')\n );\n}\nfunction picture(records, terms, nowMs, withinDays) {\n var byStatus = function (s) { return records.filter(function (r) { return r.status === s; }); };\n var drafts = byStatus('draft');\n var sent = byStatus('sent');\n var won = byStatus('won');\n var lost = byStatus('lost');\n var total = function (list) { return list.reduce(function (t, r) { return t + quoteTotals(r).total; }, 0); };\n var due = sent\n .filter(function (r) { return r.fields.followUpAt && daysLeft(r.fields.followUpAt, nowMs) <= withinDays; })\n .sort(function (a, b) { return String(a.fields.followUpAt).localeCompare(String(b.fields.followUpAt)); });\n var dueNow = due.filter(function (r) { return daysLeft(r.fields.followUpAt, nowMs) <= 0; });\n var recentFirst = function (list) {\n return list.slice().sort(function (a, b) { return String(b.fields.closedAt || '').localeCompare(String(a.fields.closedAt || '')); });\n };\n var parts = [\n records.length + (records.length === 1 ? ' quote: ' : ' quotes: ') + drafts.length + ' draft, ' + sent.length +\n ' sent and waiting (' + money(total(sent)) + '), ' + won.length + ' won, ' + lost.length + ' lost.',\n ];\n // One list, overdue first: a model asked what needs chasing reads a separate late list as out of scope.\n parts.push(\n due.length\n ? 'Follow-ups within ' + withinDays + ' days, overdue first: ' + due.map(function (r) { return followLine(r, nowMs); }).join(' | ') + '.'\n : 'No follow-ups due in the next ' + withinDays + ' days.',\n );\n if (drafts.length) parts.push('Drafts: ' + drafts.map(function (r) { var ls = r.fields.lines || []; return quoteLine(r, nowMs) + (ls.length ? ': ' + ls.map(lineText).join('; ') : ''); }).join(' | ') + '.');\n if (sent.length) parts.push('Sent and waiting: ' + sent.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (won.length) parts.push('Won (latest first): ' + recentFirst(won).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (lost.length) parts.push('Lost (latest first): ' + recentFirst(lost).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');\n if (won.length + lost.length) {\n var decided = total(won) + total(lost);\n parts.push(\n 'Win rate: ' + won.length + ' of ' + (won.length + lost.length) + ' decided quotes (' + Math.round((won.length / (won.length + lost.length)) * 100) + '%), ' +\n money(total(won)) + ' of ' + money(decided) + ' by value.',\n );\n }\n parts.push(\n 'Tax: ' + (terms.taxBp ? percent(terms.taxBp) + ' on ' + (terms.taxOn === 'all' ? 'the whole quote' : 'materials') : 'none set') +\n '. Quotes stay valid ' + terms.validDays + ' days; follow up ' + terms.followUpDays + ' days after sending. Saved rates: ' +\n (terms.rates.map(rateText).join(', ') || 'none yet') + '.',\n );\n return {\n drafts: drafts.length,\n waiting: sent.length,\n followUpsDue: dueNow.length,\n summary: parts.join(' '),\n };\n}\n// One quote line by line, for the person to read or the crew to quote exactly.\nfunction detail(record, nowMs) {\n var f = record.fields || {};\n var t = quoteTotals(record);\n var rows = (f.lines || []).map(lineText);\n return [\n f.title + ' (' + record.id + ', ' + record.status + (f.client ? ', for ' + f.client : '') + (f.site ? ' at ' + f.site : '') + ').',\n rows.length ? 'Lines: ' + rows.join('; ') + '.' : 'No lines yet.',\n 'Labor ' + money(t.labor) + ', materials ' + money(t.materials) + (t.other ? ', other ' + money(t.other) : '') +\n '. Subtotal ' + money(t.subtotal) + '. Tax ' + money(t.tax) +\n (f.taxBp ? ' (' + percent(f.taxBp) + ' on ' + (f.taxOn === 'all' ? 'the whole quote' : 'materials ' + money(t.materials)) + ')' : ' (no tax set)') +\n '. Total ' + money(t.total) + '.',\n record.status === 'sent'\n ? 'Sent ' + f.sentAt + (f.followUpAt ? '; follow up ' + when(daysLeft(f.followUpAt, nowMs)) + ' (' + f.followUpAt + ')' : '') +\n (f.validUntil ? '; valid until ' + f.validUntil : '') + '.'\n : !isOpen(record) && f.closedAt\n ? cap(record.status) + ' ' + f.closedAt + (f.reason ? ': ' + f.reason : '') + '.'\n : '',\n ]\n .filter(Boolean)\n .join(' ');\n}\n// ── quote-rules-end ──\n\ntype Quote = { id: string; status: string; fields: Record<string, unknown>; history?: Array<{ note?: string }> };\ntype Line = Record<string, unknown>;\n\nconst quotes = rosterStore(gezel.fs, 'quotes.json', { stages: ['draft', 'sent', 'won', 'lost'], idPrefix: 'q' });\nconst now = Date.now();\nconst today = localDay(now);\n\nfunction given(value: unknown): boolean {\n return value !== undefined && value !== null && value !== '';\n}\n\nasync function readTerms(): Promise<ReturnType<typeof normalizeTerms>> {\n let raw: string | null = null;\n try {\n raw = await gezel.fs.read('rates.json');\n } catch {\n raw = null;\n }\n if (raw === null) return normalizeTerms(null);\n try {\n return normalizeTerms(JSON.parse(raw));\n } catch {\n throw new Error('rates.json is not valid JSON. Fix or remove it; it will not be overwritten automatically.');\n }\n}\n\nasync function writeTerms(terms: ReturnType<typeof normalizeTerms>): Promise<void> {\n await gezel.fs.write('rates.json', JSON.stringify(terms, null, 2) + '\\n');\n}\n\nfunction followUpInput(): string | undefined {\n if (typeof input.inDays === 'number' && isFinite(input.inDays)) return addDays(today, Math.max(0, Math.round(input.inDays)));\n if (given(input.followUpAt)) {\n const day = normalizeDate(input.followUpAt);\n if (!day) throw new Error(\"followUpAt must be a date, e.g. '2026-11-20', or pass inDays.\");\n return day;\n }\n return undefined;\n}\n\nfunction wholeDays(value: unknown, label: string): number | undefined {\n if (!given(value)) return undefined;\n const n = Number(value);\n if (!isFinite(n) || n < 1 || n > 365) throw new Error(label + ' is a number of days from 1 to 365.');\n return Math.round(n);\n}\n\n// Lines change only on an open quote; a sent one goes back to draft so the\n// client is never holding a price the register no longer shows.\nasync function reprice(record: Quote, lines: Line[], what: string): Promise<string> {\n const f = record.fields;\n const title = String(f.title);\n if (!isOpen(record)) throw new Error(title + ' is ' + record.status + '; its price is settled. Start a new quote for more work.');\n await quotes.update(record.id, { fields: { lines, ...totalFields(lines, f.taxBp, f.taxOn) } });\n let tail = '';\n if (record.status === 'sent') {\n await quotes.update(record.id, { fields: { followUpAt: null } });\n await quotes.transition(record.id, 'draft', { note: 'Revised after sending: ' + what });\n tail = ' It had been sent, so it is back in draft: send it again when the client should see the new price.';\n }\n return what + ' ' + title + ' total now ' + money(totals(lines, f.taxBp, f.taxOn).total) + '.' + tail;\n}\n\n// The quotes' one reminder sits on the soonest follow-up, the morning it is due.\nasync function remindNextFollowUp(): Promise<void> {\n const next = (await quotes.list())\n .filter((r) => r.status === 'sent' && typeof r.fields.followUpAt === 'string')\n .map((r) => ({ record: r, at: Date.parse(String(r.fields.followUpAt) + 'T09:00:00') }))\n .filter((r) => r.at > now)\n .sort((a, b) => a.at - b.at)[0];\n try {\n if (!next || next.at - now > 30 * DAY_MS) await gezel.reminder.clear();\n else {\n const f = next.record.fields;\n await gezel.reminder.set({\n at: new Date(next.at).toISOString(),\n title: ('Follow up on the quote for ' + String(f.client || f.title)).slice(0, 80),\n body: (String(f.title) + ', ' + money(quoteTotals(next.record).total) + ', sent ' + String(f.sentAt) + '.').slice(0, 160),\n });\n }\n } catch {\n // Reminders are a convenience; the quotes are the record.\n }\n}\n\nconst withinDays = typeof input.withinDays === 'number' && input.withinDays > 0 ? Math.round(input.withinDays) : 7;\nlet note = '';\nlet acted: string | null = null;\nlet shown = '';\n\nif (input.action === 'add') {\n const all = (await quotes.list()) as Quote[];\n const title = String(input.title || input.client || '').trim();\n let existing: Quote | null = null;\n if (given(input.id)) existing = findQuote(all, { id: input.id, title: input.title });\n else if (title) existing = all.find((r) => fold(r.fields.title) === fold(title)) ?? null;\n if (!existing && !title) throw new Error(\"add needs 'title': the job, e.g. 'Maple Row panel upgrade'.\");\n const fields: Record<string, unknown> = {};\n if (input.client) fields.client = input.client.trim();\n if (input.contact) fields.contact = input.contact.trim();\n if (input.site) fields.site = input.site.trim();\n if (input.note) fields.note = input.note.trim();\n if (existing) {\n if (given(input.id) && input.title && fold(input.title) !== fold(existing.fields.title)) fields.title = input.title.trim();\n await quotes.update(existing.id, { fields });\n acted = existing.id;\n note = 'Updated ' + String(existing.fields.title) + '.';\n } else {\n const terms = await readTerms();\n const record = await quotes.add({\n status: 'draft',\n fields: { title, ...fields, lines: [], taxBp: terms.taxBp, taxOn: terms.taxOn, ...totalFields([], terms.taxBp, terms.taxOn) },\n });\n acted = record.id;\n note = 'Started ' + record.id + ': ' + title + ' (draft). Add its lines next.';\n }\n} else if (input.action === 'add_line' || input.action === 'remove_line') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const lines = (record.fields.lines ?? []) as Line[];\n const change = input.action === 'add_line' ? upsertLine(lines, input, await readTerms()) : removeLine(lines, input);\n note = await reprice(record, change.lines, change.note);\n acted = record.id;\n} else if (input.action === 'send') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n acted = record.id;\n if (record.status === 'sent') note = title + ' was already sent on ' + String(record.fields.sentAt) + '.';\n else if (!isOpen(record)) throw new Error(title + ' is ' + record.status + '; it cannot be sent again.');\n else {\n if (!((record.fields.lines ?? []) as Line[]).length) throw new Error(title + ' has no lines yet; add them before sending.');\n const terms = await readTerms();\n const validUntil = addDays(today, wholeDays(input.validDays, 'validDays') ?? terms.validDays);\n const follow = followUpInput() ?? addDays(today, terms.followUpDays);\n await quotes.update(record.id, { fields: { sentAt: today, validUntil, followUpAt: follow } });\n await quotes.transition(record.id, 'sent', { note: input.note || 'Sent to the client.' });\n note = 'Sent ' + title + ', total ' + money(quoteTotals(record).total) + '. Valid until ' + validUntil + '; first follow-up ' + follow + '.';\n }\n} else if (input.action === 'follow_up') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n if (record.status !== 'sent') {\n throw new Error(title + ' is ' + record.status + (record.status === 'draft' ? '; send it before following up.' : '; it is closed.'));\n }\n const next = followUpInput() ?? addDays(today, (await readTerms()).followUpDays);\n await quotes.update(record.id, { fields: { followUpAt: next, lastFollowUpAt: today }, note: input.note || 'Followed up.' });\n acted = record.id;\n note = 'Logged the follow-up on ' + title + (input.note ? ': ' + input.note.trim() : '') + '. Next follow-up ' + next + '.';\n} else if (input.action === 'outcome') {\n const outcome = String(input.outcome || '').trim().toLowerCase();\n if (outcome !== 'won' && outcome !== 'lost') throw new Error(\"outcome needs 'outcome': won or lost.\");\n const record = findQuote((await quotes.list()) as Quote[], input);\n const title = String(record.fields.title);\n acted = record.id;\n if (record.status === outcome) note = title + ' is already ' + outcome + '.';\n else if (!isOpen(record)) throw new Error(title + ' is already ' + record.status + '.');\n else {\n await quotes.update(record.id, { fields: { closedAt: today, followUpAt: null, ...(input.note ? { reason: input.note.trim() } : {}) } });\n await quotes.transition(record.id, outcome, { note: input.note || (outcome === 'won' ? 'Won.' : 'Lost.') });\n note = (outcome === 'won' ? 'Won ' : 'Lost ') + title + ', ' + money(quoteTotals(record).total) + (input.note ? ' (' + input.note.trim() + ')' : '') + '.';\n }\n} else if (input.action === 'set_rate') {\n const name = String(input.name || input.description || '').trim();\n if (!name) throw new Error(\"set_rate needs 'name', e.g. 'Electrician'.\");\n const rateCents = toCents(input.rate);\n if (rateCents === null || rateCents < 0) throw new Error(\"set_rate needs 'rate' in dollars per unit, e.g. 95.\");\n const kind = KINDS.indexOf(String(input.kind)) >= 0 ? String(input.kind) : 'labor';\n const unit = input.unit ? input.unit.trim() : kind === 'labor' ? 'hour' : 'each';\n const terms = await readTerms();\n const at = terms.rates.findIndex((r) => fold(r.name) === fold(name));\n const rate = { name, kind, unit, rateCents };\n if (at >= 0) terms.rates[at] = rate;\n else terms.rates.push(rate);\n await writeTerms(terms);\n note = (at >= 0 ? 'Updated the rate ' : 'Saved the rate ') + rateText(rate) + '. Lines already on quotes keep their price; new lines use this one.';\n} else if (input.action === 'set_terms') {\n const terms = await readTerms();\n let changed = false;\n if (given(input.taxRate)) {\n const p = Number(String(input.taxRate).replace('%', ''));\n if (!isFinite(p) || p < 0 || p > 50) throw new Error('taxRate is a percent, e.g. 8.25 (0 for none).');\n terms.taxBp = Math.round(p * 100);\n changed = true;\n }\n if (given(input.taxOn)) {\n const on = String(input.taxOn).trim().toLowerCase();\n if (on !== 'materials' && on !== 'all') throw new Error('taxOn is materials or all.');\n terms.taxOn = on;\n changed = true;\n }\n const valid = wholeDays(input.validDays, 'validDays');\n if (valid !== undefined) terms.validDays = valid;\n const follow = wholeDays(input.followUpDays, 'followUpDays');\n if (follow !== undefined) terms.followUpDays = follow;\n if (!changed && valid === undefined && follow === undefined) throw new Error('set_terms needs taxRate, taxOn, validDays or followUpDays.');\n await writeTerms(terms);\n // Drafts follow the business's tax; sent and closed quotes keep the tax they went out with.\n const drafts = (await quotes.list()).filter((r) => r.status === 'draft');\n for (const d of drafts) {\n await quotes.update(d.id, {\n fields: { taxBp: terms.taxBp, taxOn: terms.taxOn, ...totalFields((d.fields.lines ?? []) as Line[], terms.taxBp, terms.taxOn) },\n });\n }\n note =\n 'Tax is ' + (terms.taxBp ? percent(terms.taxBp) + ' on ' + (terms.taxOn === 'all' ? 'the whole quote' : 'materials') : 'not charged') +\n '; quotes stay valid ' + terms.validDays + ' days; follow up ' + terms.followUpDays + ' days after sending.' +\n (drafts.length ? ' Re-totaled ' + drafts.length + (drafts.length === 1 ? ' draft' : ' drafts') + '; sent quotes keep the tax they went out with.' : '');\n} else if (input.action === 'show') {\n const record = findQuote((await quotes.list()) as Quote[], input);\n acted = record.id;\n shown = detail(record, now);\n} else if (input.action !== 'status' && input.action !== 'list') {\n throw new Error(\n \"Unknown action '\" + input.action + \"'. Use status, add, add_line, remove_line, send, follow_up, outcome, set_rate, set_terms, show, or list.\",\n );\n}\n\nconst records = (await quotes.list()) as Quote[];\nconst view = picture(records, await readTerms(), now, withinDays);\nconst touched = acted ? records.find((r) => r.id === acted) : undefined;\nawait remindNextFollowUp();\n\ngezel.output({\n drafts: view.drafts,\n waiting: view.waiting,\n followUpsDue: view.followUpsDue,\n total: touched ? quoteTotals(touched).total / 100 : 0,\n summary: shown\n ? shown\n : input.action === 'list'\n ? records.map((r) => '[' + r.status + '] ' + quoteLine(r, now)).join('\\n') || 'There are no quotes yet.'\n : (note ? note + ' ' : '') + view.summary,\n});\n"
|
|
41
41
|
},
|
|
42
42
|
"tools": [
|
|
43
43
|
{
|
|
@@ -471,7 +471,7 @@ window.addEventListener('pagehide',function(){appDisposed=true;appLoadRevision++
|
|
|
471
471
|
? 'Follow-ups within ' + withinDays + ' days, overdue first: ' + due.map(function (r) { return followLine(r, nowMs); }).join(' | ') + '.'
|
|
472
472
|
: 'No follow-ups due in the next ' + withinDays + ' days.',
|
|
473
473
|
);
|
|
474
|
-
if (drafts.length) parts.push('Drafts: ' + drafts.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');
|
|
474
|
+
if (drafts.length) parts.push('Drafts: ' + drafts.map(function (r) { var ls = r.fields.lines || []; return quoteLine(r, nowMs) + (ls.length ? ': ' + ls.map(lineText).join('; ') : ''); }).join(' | ') + '.');
|
|
475
475
|
if (sent.length) parts.push('Sent and waiting: ' + sent.map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');
|
|
476
476
|
if (won.length) parts.push('Won (latest first): ' + recentFirst(won).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');
|
|
477
477
|
if (lost.length) parts.push('Lost (latest first): ' + recentFirst(lost).slice(0, 5).map(function (r) { return quoteLine(r, nowMs); }).join(' | ') + '.');
|