@huloglobal/vendure-plugin-quotations 0.8.6 → 0.10.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +123 -9
  3. package/dist/approvals.d.ts +46 -0
  4. package/dist/approvals.d.ts.map +1 -0
  5. package/dist/approvals.js +136 -0
  6. package/dist/approvals.js.map +1 -0
  7. package/dist/crons.d.ts +5 -3
  8. package/dist/crons.d.ts.map +1 -1
  9. package/dist/crons.js +16 -10
  10. package/dist/crons.js.map +1 -1
  11. package/dist/csv.d.ts +7 -0
  12. package/dist/csv.d.ts.map +1 -0
  13. package/dist/csv.js +32 -0
  14. package/dist/csv.js.map +1 -0
  15. package/dist/deposits.d.ts +25 -0
  16. package/dist/deposits.d.ts.map +1 -0
  17. package/dist/deposits.js +59 -0
  18. package/dist/deposits.js.map +1 -0
  19. package/dist/email-layout.d.ts +104 -0
  20. package/dist/email-layout.d.ts.map +1 -0
  21. package/dist/email-layout.js +250 -0
  22. package/dist/email-layout.js.map +1 -0
  23. package/dist/emails.d.ts +57 -0
  24. package/dist/emails.d.ts.map +1 -0
  25. package/dist/emails.js +124 -0
  26. package/dist/emails.js.map +1 -0
  27. package/dist/events.d.ts +55 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +58 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/index.d.ts +4 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +7 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/pay-links.d.ts +37 -0
  36. package/dist/pay-links.d.ts.map +1 -0
  37. package/dist/pay-links.js +61 -0
  38. package/dist/pay-links.js.map +1 -0
  39. package/dist/payment.service.d.ts +117 -0
  40. package/dist/payment.service.d.ts.map +1 -0
  41. package/dist/payment.service.js +479 -0
  42. package/dist/payment.service.js.map +1 -0
  43. package/dist/pdf.d.ts +15 -0
  44. package/dist/pdf.d.ts.map +1 -0
  45. package/dist/pdf.js +356 -0
  46. package/dist/pdf.js.map +1 -0
  47. package/dist/plugin.d.ts +5 -2
  48. package/dist/plugin.d.ts.map +1 -1
  49. package/dist/plugin.js +9 -6
  50. package/dist/plugin.js.map +1 -1
  51. package/dist/pro-settings.d.ts +72 -0
  52. package/dist/pro-settings.d.ts.map +1 -0
  53. package/dist/pro-settings.js +202 -0
  54. package/dist/pro-settings.js.map +1 -0
  55. package/dist/pro.service.d.ts +130 -0
  56. package/dist/pro.service.d.ts.map +1 -0
  57. package/dist/pro.service.js +749 -0
  58. package/dist/pro.service.js.map +1 -0
  59. package/dist/quotation.controller.d.ts +54 -8
  60. package/dist/quotation.controller.d.ts.map +1 -1
  61. package/dist/quotation.controller.js +626 -32
  62. package/dist/quotation.controller.js.map +1 -1
  63. package/dist/quotation.service.d.ts +192 -12
  64. package/dist/quotation.service.d.ts.map +1 -1
  65. package/dist/quotation.service.js +648 -103
  66. package/dist/quotation.service.js.map +1 -1
  67. package/dist/rate-limit.d.ts +15 -0
  68. package/dist/rate-limit.d.ts.map +1 -0
  69. package/dist/rate-limit.js +35 -0
  70. package/dist/rate-limit.js.map +1 -0
  71. package/dist/templates.d.ts +12 -3
  72. package/dist/templates.d.ts.map +1 -1
  73. package/dist/templates.js +15 -38
  74. package/dist/templates.js.map +1 -1
  75. package/dist/types.d.ts +13 -1
  76. package/dist/types.d.ts.map +1 -1
  77. package/dist/types.js +6 -4
  78. package/dist/types.js.map +1 -1
  79. package/dist/webhooks.d.ts +61 -0
  80. package/dist/webhooks.d.ts.map +1 -0
  81. package/dist/webhooks.js +308 -0
  82. package/dist/webhooks.js.map +1 -0
  83. package/package.json +7 -6
  84. package/ui/components/quotations.component.ts +328 -19
package/CHANGELOG.md CHANGED
@@ -5,6 +5,121 @@ documented here. The format follows
5
5
  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project
6
6
  adheres to [semantic versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.10.0] — 2026-11-16
9
+
10
+ ### Changed
11
+ - **Every e-mail restyled to one shared design:** a 600px white card on a light grey background, the store's
12
+ logo (or its name) over a 3px accent bar, a clear heading, the quote's reference, validity and total in a
13
+ summary box, a button, a "Kind regards" sign-off with the store's reply-to address, and a footer strip with
14
+ the store's address, phone, website and footer note. Inline styles and tables only, every value escaped,
15
+ and every message now has a plain-text part. It uses the existing **Accent colour**, **Logo URL** and
16
+ footer settings, so nothing needs setting up. Restyled: the quote e-mail, test sends (now with a "Test
17
+ send" warning box), the chaser, the expiry reminder (its heading names the date), follow-up steps, the
18
+ pay-link e-mails for the whole amount, a deposit or the balance (the pay button plus a secondary "View
19
+ your quotation" button, and the amount due now), and the request acknowledgement (which had no HTML
20
+ part). Store notifications (new request, first view, accepted, declined) and discount-approval requests
21
+ and outcomes use the same design, more compact; they were plain text. The weekly report uses the shared
22
+ design from the licence SDK 0.15.7 with the store's logo and accent colour.
23
+ - Your own e-mail templates are used as they are: the summary box and button go where the template has the
24
+ quote link on a line of its own (else before its sign-off), and no second sign-off is added when the
25
+ template has one.
26
+ - Default texts: British English, "Kind regards", "e-mail"; the request acknowledgement no longer promises
27
+ a reply "usually within one working day" (nothing in the plugin ensures that). Stored templates are not
28
+ changed.
29
+ - Licence SDK `^0.15.7`; dev dependencies refreshed to the latest minor versions (TypeScript 5.9, Vitest
30
+ 2.1, @types/nodemailer 6.4). Held back: TypeScript 7, Vitest 5 (the monorepo harness pins Vitest 2) and
31
+ @types/nodemailer 8 (the types for nodemailer 8+, while the peer range starts at 6).
32
+
33
+ ### Fixed
34
+ - The plain-text part of the pay-link e-mails had no link (it said "with the button below"); it now carries
35
+ the pay link and the quote link.
36
+ - The public quote page and the accept/decline form are rate limited per client address (120 page views
37
+ and 20 responses a minute; 429 after that), as the PDF download already was.
38
+ - Store notification subjects are kept to one line whatever the requester typed.
39
+
40
+ ## [0.9.0] — 2026-11-13
41
+
42
+ Parity with HULO Quotations for WordPress (free 0.1.4 and Pro).
43
+
44
+ ### Changed (tiers)
45
+ - **Free now:** sending a quote, test sends, the unopened-quote chaser and the expiry reminder (they ran
46
+ premium-only before). Auto-expiry was already free and is now listed as such.
47
+ - **Premium now:** the weekly e-mail report and the set-up checklist. Without a licence or the evaluation the
48
+ report is not sent (the weekly clock is left as it was, so it resumes on the next Monday once a licence is
49
+ active), *Send me a test* and *Preview* answer 402, and the checklist reports nothing to do. Settings and data
50
+ are kept.
51
+ - Still premium: converting an accepted quote to a draft order from the admin, plus the new templates,
52
+ follow-up sequences, discount approval, webhooks, sales reports and deposits below.
53
+ - `PREMIUM_FEATURES` lists what is actually gated (storefront requests were listed but never gated).
54
+
55
+ ### Fixed
56
+ - **B5: KPIs and the weekly report no longer add amounts in different currencies together.** `GET /quotations/stats`
57
+ reports `valueByCurrency` per status, `pipelineByCurrency` and `last30.valueWonByCurrency` (minor units per
58
+ currency; `value` and `last30.valueWonPence` are gone). The weekly report, the admin banner and the dashboard
59
+ widget show value won per currency ("£1,234.56 + €500.00"). The anonymous heartbeat figure `valueWonPence`
60
+ counts the store's main currency only.
61
+ - Expiry is recorded per quote (trail entry "Validity ended" and an event) instead of one silent bulk update.
62
+ - Chasers and expiry reminders are claimed before they are sent and released when the e-mail fails, so an
63
+ overlapping or late run never sends one twice; the chaser only goes to quotes never opened.
64
+
65
+ ### Added (free)
66
+ - **EventBus events:** `QuotationEvent` (exported) for created, requested, updated, sent, viewed, accepted,
67
+ declined, expired, cancelled, converted, paid, payment, approval, follow-up and deleted, with a quote summary
68
+ (no token, no internal notes).
69
+ - **Mark as sent** (`POST /quotations/quotes/:id/mark-sent`): the store shared the quote itself; a draft or
70
+ request opens for the customer without an e-mail.
71
+ - **Validity counted from the send:** a quote keeps its validity period (`validityDays`) and its date starts
72
+ when it is first sent (or marked as sent). A resend keeps the date; a quote whose date has passed must be
73
+ extended first.
74
+ - **Staff preview** of the customer page (`GET /quotations/quotes/:id/page`): not counted as an opening, the
75
+ accept form is switched off.
76
+ - **Server-side PDF** (built in, no dependency): `GET /quotations/quote/:token/pdf` from the customer link
77
+ (rate-limited, not an opening, never cached), `GET /quotations/quotes/:id/pdf` for staff, a *Download PDF*
78
+ button on the customer page and an optional attachment on the quote e-mail (Settings → *Attach the quote as
79
+ a PDF*).
80
+ - **"My quotes"** for signed-in customers: `GET /quotations/my` (shop session, channel from `vendure-token`)
81
+ lists the customer's own quotes (by account, never by e-mail; drafts hidden; requests as "awaiting price")
82
+ with quote, PDF and pay links. A request posted while signed in is linked to the account; guest requests are
83
+ no longer linked to an account by e-mail address.
84
+ - **12-month report** (`GET /quotations/reports/monthly`, Reports tab): created, sent, accepted, win rate and
85
+ value won per currency per month.
86
+ - **Per-e-mail request throttle** kept in the database (10 an hour per address, across processes and restarts),
87
+ on top of the per-client limit.
88
+ - **HULO Payments pay link on acceptance:** with *Pay link on acceptance* on (Settings, per channel) the accepted
89
+ quote becomes a draft order at the quoted total, moves to ArrangingPayment (a free shipping method is picked
90
+ when the channel has one) and the customer is e-mailed a pay link; staff can also create and e-mail it from
91
+ the quote. HULO Payments for Vendure is detected at runtime (no dependency); a host can pass its own
92
+ `payLinks` provider to `init()`. The quote is marked paid when the order's settled payments cover the total.
93
+ The converted draft order now carries the quote's customer.
94
+
95
+ ### Added (premium)
96
+ - **Quote templates:** save a quote's lines, discounts, VAT, notes, terms, validity and currency (never the
97
+ customer or internal notes) and start new drafts from them (Templates tab).
98
+ - **Follow-up sequences:** up to three extra e-mails N days after sending while the quote is open and unpaid;
99
+ each step claimed once, in order, at most one a day per quote, never within a day of the chaser or reminder.
100
+ - **Discount approval:** limits on discount % off list, discount amount and total (per currency). A quote over
101
+ a limit cannot be sent or marked as sent until an approver approves exactly that version (a hash of lines,
102
+ discounts, VAT, currency and totals); an edit invalidates the approval. Test sends are never held; without
103
+ premium the gate is off. Approvers: listed admin e-mails, else any SuperAdmin; the preparer cannot approve
104
+ their own quote unless they are the only approver and that is allowed.
105
+ - **Webhooks** (up to five): JSON signed with `X-Hulo-Signature: sha256=HMAC(secret, "<timestamp>.<body>")`,
106
+ Slack and Microsoft Teams presets; public http(s) addresses on standard ports only, checked on save and on
107
+ every delivery with the connection pinned to the checked address; no redirects; retries with back-off (six
108
+ attempts); 30-day delivery log with retry and test.
109
+ - **Sales reports** by member of staff and by source, per currency, with a formula-safe CSV export.
110
+ - **Deposits:** a percentage (optionally only above a per-currency threshold, or per quote) taken first, then
111
+ the balance, as two pay links on the same order. Deposit + balance = the quoted total exactly in minor units
112
+ (zero-decimal currencies in whole units); every link is claimed before it is created; the quote is paid only
113
+ when the balance settles. A deposit already taken is completed whatever the licence state.
114
+
115
+ ### Compatibility
116
+ - New tables `quotation_template`, `quotation_followup`, `quotation_approval`, `quotation_webhook_log`,
117
+ `quotation_deposit` and new nullable / defaulted columns, created on start-up on MySQL, MariaDB and
118
+ PostgreSQL. Tested with Vendure 3.8.2; `@vendure/core >=3.5.0 <4.0.0`.
119
+ - Pay links need HULO Payments for Vendure exposing `createPayLink(ctx, { orderCode, amount?, currency,
120
+ description, customerEmail?, returnUrl?, expiresInHours?, reference?, metadata? }) → { url, ref }` on an
121
+ exported service (`PayLinkService` or `PaymentsService`), or a `payLinks` provider in `init()`.
122
+
8
123
  ## [0.8.6] — 2026-11-13
9
124
 
10
125
  ### Fixed
package/README.md CHANGED
@@ -19,6 +19,13 @@ End-to-end quotation engine for [Vendure](https://www.vendure.io/):
19
19
  does not move the quoted total (unless an admin has changed the lines).
20
20
  - **Receive requests** from your storefront: customers ask for a quote from
21
21
  a basket, product page or form, and it lands in your inbox pre-priced.
22
+ - **Get paid:** a HULO Payments pay link on acceptance (optional deposit,
23
+ then the balance); the quote is marked paid when the order is.
24
+ - **PDF** of every quote, a staff preview of the customer page, "My quotes"
25
+ for signed-in customers, a 12-month report and EventBus events.
26
+ - **Premium:** templates, follow-up sequences, discount approval, webhooks
27
+ (JSON, Slack, Teams), sales reports with CSV, deposits, the weekly report
28
+ and the set-up checklist.
22
29
 
23
30
  Works on MySQL, MariaDB and PostgreSQL. Admin UI included (Quotes,
24
31
  editor with catalogue search, Settings, a Help drawer and a set-up
@@ -83,14 +90,112 @@ await fetch('https://shop.example.com/quotations/request', {
83
90
 
84
91
  The quote appears under **Sales → Quotations** as *requested*; price any
85
92
  free-text lines, then **Send to customer**. Turn requests off per channel in
86
- Settings. Requests are throttled (10 an hour per client) and a hidden
87
- `website` field discards bots.
93
+ Settings. Requests are throttled (10 an hour per client and 10 an hour per e-mail
94
+ address, the latter counted in the database) and a hidden `website` field
95
+ discards bots. A request posted with the customer's shop session (cookie or
96
+ bearer token) is linked to their account and shows under "My quotes"; guest
97
+ requests are never linked by e-mail address.
98
+
99
+ ## "My quotes" for signed-in customers
100
+
101
+ ```ts
102
+ const res = await fetch('https://shop.example.com/quotations/my', {
103
+ headers: { authorization: `Bearer ${shopToken}`, 'vendure-token': CHANNEL_TOKEN },
104
+ });
105
+ // → { items: [{ reference, status, statusLabel, date, validUntil, totalPence, currency,
106
+ // url, pdfUrl, payUrl, paid, canRespond }] } (401 when not signed in)
107
+ ```
108
+
109
+ Only quotes linked to the customer's account are listed (staff link them with
110
+ the customer picker); drafts are never shown.
111
+
112
+ ## E-mails
113
+
114
+ Every message the plugin sends shares one design: a 600px white card, your
115
+ logo (or business name) over a 3px bar in your accent colour, a heading, the
116
+ quote's reference, validity and total in a summary box, a button, a "Kind
117
+ regards" sign-off with your reply-to address, and a footer strip with your
118
+ address, phone, website and footer note. Inline styles only, with a
119
+ plain-text part. It is set from **Settings** (business name, logo URL, accent
120
+ colour, reply-to, address, phone, website, footer note); nothing extra.
121
+
122
+ - **To customers:** the quote, test sends (marked "Test send"), the chaser,
123
+ the expiry reminder, follow-up steps, pay-link e-mails (whole amount,
124
+ deposit or balance) and the request acknowledgement. Your subject and body
125
+ templates are used as written; the summary box and button go where the
126
+ body has `{{quoteUrl}}` on a line of its own, else before your sign-off.
127
+ - **To your team (compact):** new request, first view, accepted, declined,
128
+ approval requested, approved or not.
129
+ - **Weekly report:** the licence SDK's report layout with your logo and
130
+ accent colour.
131
+
132
+ ## PDF
133
+
134
+ `GET /quotations/quote/:token/pdf` (the customer link, rate-limited, never
135
+ cached, does not count as opening the quote) and `GET /quotations/quotes/:id/pdf`
136
+ (admin). Built in, no dependency: A4, Helvetica, Western European text
137
+ (other scripts print as "?"; the customer page shows every language). Turn on
138
+ **Settings → Attach the quote as a PDF** to attach it to the quote e-mail.
139
+
140
+ ## Pay links and deposits
141
+
142
+ With HULO Payments for Vendure installed (or your own provider passed as
143
+ `payLinks` in `init()`), an accepted quote can be paid online: the quote
144
+ becomes a draft order at the quoted total, the order moves to
145
+ ArrangingPayment (a free shipping method is chosen when the channel has one;
146
+ otherwise the admin is told what is missing), and the customer gets a pay
147
+ link. Turn on **Settings → Pay link on acceptance** to do this the moment the
148
+ customer accepts, or use **Create pay link** on the quote. The quote is marked
149
+ paid when the order's settled payments cover the quoted total. Quotations
150
+ works the same with or without HULO Payments.
151
+
152
+ ```ts
153
+ QuotationsPlugin.init({
154
+ payLinks: { create: async (ctx, { orderCode, amount, currency, description, reference }) => ({ url, ref }) },
155
+ });
156
+ ```
157
+
158
+ **Deposits (premium):** set a percentage (and optionally a per-currency
159
+ threshold, e.g. `GBP 1000, EUR 1200`) or a per-quote override. The customer
160
+ pays the deposit link first, then the balance link, both on the same order;
161
+ deposit + balance equal the quoted total exactly.
162
+
163
+ ## EventBus events
164
+
165
+ ```ts
166
+ import { QuotationEvent } from '@huloglobal/vendure-plugin-quotations';
167
+ eventBus.ofType(QuotationEvent).pipe(filter(e => e.type === 'accepted')).subscribe(e => { /* e.quote, e.detail, e.actor */ });
168
+ ```
169
+
170
+ Types: `created`, `requested`, `updated`, `sent`, `viewed`, `accepted`,
171
+ `declined`, `expired`, `cancelled`, `converted`, `paid`, `payment`,
172
+ `approval`, `followup`, `deleted`.
173
+
174
+ ## Premium features
175
+
176
+ - **Templates** (Templates tab): save a quote's lines, discounts, VAT, notes,
177
+ terms, validity and currency; start new drafts from them.
178
+ - **Follow-up sequences** (Settings): up to three e-mails N days after
179
+ sending, while the quote is open and unpaid.
180
+ - **Discount approval** (Settings): a quote whose discount off list (percent
181
+ or amount) or total is over a limit cannot be sent or marked as sent until
182
+ an approver approves that exact version; any edit needs a new approval.
183
+ - **Webhooks** (Settings, up to five): JSON (signed
184
+ `X-Hulo-Signature: sha256=HMAC-SHA256(secret, "<X-Hulo-Timestamp>.<body>")`),
185
+ Slack or Microsoft Teams. Events: request created, quote sent, opened,
186
+ accepted, declined, paid, expired, converted, approval requested. Public
187
+ addresses only, retries with back-off, a 30-day delivery log.
188
+ - **Sales reports** (Reports tab) by member of staff and by source, per
189
+ currency, with a CSV export.
190
+ - **Deposits**, the **weekly report** and the **set-up checklist**.
88
191
 
89
192
  ## Admin UI
90
193
 
91
194
  **Sales → Quotations** (requires the `ReadSettings` permission; writes need
92
- `UpdateSettings`). The page has three tabs — Quotes (inbox, KPIs, detail
93
- and activity trail), the step-by-step editor, and Settings — plus a
195
+ `UpdateSettings`). The page has five tabs — Quotes (inbox, KPIs per
196
+ currency, detail with payment, deposit and approval, activity trail), the
197
+ step-by-step editor, Reports (12 months; sales by staff and source),
198
+ Templates, and Settings — plus a
94
199
  **Help** button in the header that opens a three-step drawer (New quote →
95
200
  Send → Convert).
96
201
 
@@ -100,6 +205,10 @@ and a link into the page.
100
205
 
101
206
  ## Weekly report, setup checklist and dashboard widget
102
207
 
208
+ The weekly report and the set-up checklist are **premium** (licence or the
209
+ 14-day evaluation). Without premium the report is not sent and the checklist
210
+ is not shown; their settings are kept and they resume when a licence is active.
211
+
103
212
  **Set-up checklist.** The top of the Quotes tab shows what is left to do,
104
213
  each item checked against the real state: an email server reachable
105
214
  (`SMTP_*` env or the `smtp` option), a reply-to or notify address saved
@@ -134,11 +243,16 @@ Endpoints (admin session): `GET /quotations/setup`,
134
243
 
135
244
  ## Licensing
136
245
 
137
- Unlicensed installs run in the free tier; the 14-day free trial (card required) is started from the admin banner. Afterwards the
138
- plugin drops to the free tier: drafting, pricing and previews stay free —
139
- **sending, chasers and order conversion require a licence** from
140
- https://huloglobal.com/vendure-plugins/quotations/.
246
+ Unlicensed installs run in the free tier, with a 14-day evaluation of the
247
+ premium features (no card). **Free:** building, sending, test sends, mark as
248
+ sent, the customer page with signature, PDF, storefront requests, "My quotes",
249
+ the chaser and expiry reminder, auto-expiry, pay links on acceptance, KPIs,
250
+ the 12-month report and EventBus events. **Premium** (licence from
251
+ https://huloglobal.com/vendure-plugins/quotations/): converting to a draft
252
+ order from the admin, templates, follow-up sequences, discount approval,
253
+ webhooks, sales reports with CSV, deposits, the weekly report and the set-up
254
+ checklist.
141
255
 
142
256
  ## Buying a licence
143
257
 
144
- Pick monthly or annual on the plugin's admin banner and click **Start 14-day free trial** (card required, nothing charged until day 15, cancel any time), or choose lifetime — checkout opens in a new tab and the key installs itself within a minute. You can also buy at https://elite.charity/licence/buy/vendure-plugin-quotations and paste the emailed key into the admin.
258
+ Pick monthly or annual on the plugin's admin banner and click **Subscribe** (cancel any time), or choose lifetime — checkout opens in a new tab and the key installs itself within a minute. You can also buy at https://elite.charity/licence/buy/vendure-plugin-quotations and paste the emailed key into the admin.
@@ -0,0 +1,46 @@
1
+ import { ProSettings } from './pro-settings';
2
+ /**
3
+ * Discount approval (premium). A quote over a limit (discount percent off
4
+ * list, discount amount, or total; each optional) cannot be sent or marked
5
+ * as sent until an approver has approved exactly this version of it: the
6
+ * approval stores a hash of the lines, discounts, VAT rate, currency and
7
+ * totals, and any later edit makes the hash differ, so the approval no longer
8
+ * counts (the snapshot is invalidated). Test sends are never held, and
9
+ * without premium the gate is off so no quote is ever stuck.
10
+ */
11
+ export type ApprovalStatus = 'not_needed' | 'needed' | 'pending' | 'approved' | 'rejected' | 'stale';
12
+ /** List value (quantity × unit price, before any discount) and the discount off it, in the quote's minor units. */
13
+ export declare function discountOffList(q: any): {
14
+ list: number;
15
+ amount: number;
16
+ pct: number;
17
+ };
18
+ /** Why the quote needs approval (empty: it does not). */
19
+ export declare function approvalReasons(q: any, s: ProSettings): string[];
20
+ export declare function approvalConfigured(s: ProSettings): boolean;
21
+ /** The version of the quote an approval is for: lines, discounts, VAT rate, currency and totals. */
22
+ export declare function approvalHash(q: any): string;
23
+ /** Where a quote stands, given its approval row (or none). */
24
+ export declare function approvalStatus(q: any, s: ProSettings, row: {
25
+ state: string;
26
+ hash: string;
27
+ } | null): ApprovalStatus;
28
+ /** The message shown when a send or mark-as-sent is held, or null when it may go ahead. */
29
+ export declare function approvalGateMessage(status: ApprovalStatus, reasons: string[]): string | null;
30
+ /**
31
+ * Whether `approverEmail` may decide on a quote: an approver (listed, or any
32
+ * SuperAdmin when the list is empty) who did not prepare it, unless they are
33
+ * the only approver and "let the preparer approve" is on.
34
+ */
35
+ export declare function canDecide(opts: {
36
+ approverEmail: string;
37
+ isSuperAdmin: boolean;
38
+ settings: ProSettings;
39
+ preparerEmail: string;
40
+ }): {
41
+ ok: true;
42
+ } | {
43
+ ok: false;
44
+ reason: string;
45
+ };
46
+ //# sourceMappingURL=approvals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approvals.d.ts","sourceRoot":"","sources":["../src/approvals.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAEvD;;;;;;;;GAQG;AAEH,MAAM,MAAM,cAAc,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,OAAO,CAAC;AAErG,mHAAmH;AACnH,wBAAgB,eAAe,CAAC,CAAC,EAAE,GAAG,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAMrF;AAMD,yDAAyD;AACzD,wBAAgB,eAAe,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,CAgBhE;AAED,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,WAAW,GAAG,OAAO,CAE1D;AAED,oGAAoG;AACpG,wBAAgB,YAAY,CAAC,CAAC,EAAE,GAAG,GAAG,MAAM,CAS3C;AAED,8DAA8D;AAC9D,wBAAgB,cAAc,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,GAAG,cAAc,CAKlH;AAOD,2FAA2F;AAC3F,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,IAAI,CAS5F;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE;IAC5B,aAAa,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;CAC9F,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAW/C"}
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.discountOffList = discountOffList;
37
+ exports.approvalReasons = approvalReasons;
38
+ exports.approvalConfigured = approvalConfigured;
39
+ exports.approvalHash = approvalHash;
40
+ exports.approvalStatus = approvalStatus;
41
+ exports.approvalGateMessage = approvalGateMessage;
42
+ exports.canDecide = canDecide;
43
+ const crypto = __importStar(require("crypto"));
44
+ const pricing_1 = require("./pricing");
45
+ const pro_settings_1 = require("./pro-settings");
46
+ /** List value (quantity × unit price, before any discount) and the discount off it, in the quote's minor units. */
47
+ function discountOffList(q) {
48
+ let list = 0;
49
+ for (const l of q.lines || [])
50
+ list += Number(l.quantity || 0) * Number(l.unitPricePence || 0);
51
+ const net = Number(q.subTotalPence || 0) - Number(q.discountPence || 0);
52
+ const amount = Math.max(0, list - net);
53
+ return { list, amount, pct: list > 0 ? Math.round((amount / list) * 10000) / 100 : 0 };
54
+ }
55
+ function pctText(n) {
56
+ return `${Number(n.toFixed(2))}%`;
57
+ }
58
+ /** Why the quote needs approval (empty: it does not). */
59
+ function approvalReasons(q, s) {
60
+ const cur = String(q.currency || 'GBP');
61
+ const d = discountOffList(q);
62
+ const out = [];
63
+ if (s.approvalMaxPct > 0 && d.pct > s.approvalMaxPct) {
64
+ out.push(`the discount of ${pctText(d.pct)} is over the ${pctText(s.approvalMaxPct)} limit`);
65
+ }
66
+ const maxAmt = (0, pro_settings_1.limitFor)(s.approvalMaxAmount, cur);
67
+ if (maxAmt !== null && d.amount > maxAmt) {
68
+ out.push(`the discount of ${(0, pricing_1.formatMoney)(d.amount, cur)} is over the ${(0, pricing_1.formatMoney)(maxAmt, cur)} limit`);
69
+ }
70
+ const above = (0, pro_settings_1.limitFor)(s.approvalAbove, cur);
71
+ if (above !== null && Number(q.totalPence || 0) > above) {
72
+ out.push(`the total of ${(0, pricing_1.formatMoney)(Number(q.totalPence), cur)} is over ${(0, pricing_1.formatMoney)(above, cur)}`);
73
+ }
74
+ return out;
75
+ }
76
+ function approvalConfigured(s) {
77
+ return s.approvalMaxPct > 0 || !!s.approvalMaxAmount.trim() || !!s.approvalAbove.trim();
78
+ }
79
+ /** The version of the quote an approval is for: lines, discounts, VAT rate, currency and totals. */
80
+ function approvalHash(q) {
81
+ const n = (v) => Number(v || 0);
82
+ const r2 = (v) => Math.round(n(v) * 100) / 100;
83
+ const lines = (q.lines || []).map((l) => [l.productVariantId ? Number(l.productVariantId) : 0, String(l.sku || ''),
84
+ String(l.description || ''), n(l.quantity), n(l.unitPricePence), r2(l.lineDiscountPercent), n(l.totalPence)]);
85
+ return crypto.createHash('sha256').update(JSON.stringify({
86
+ lines, discountType: String(q.discountType || 'none'), discountValue: r2(q.discountValue), vatRate: r2(q.vatRate),
87
+ currency: String(q.currency || ''), subTotal: n(q.subTotalPence), discount: n(q.discountPence), vat: n(q.vatPence), total: n(q.totalPence),
88
+ })).digest('hex');
89
+ }
90
+ /** Where a quote stands, given its approval row (or none). */
91
+ function approvalStatus(q, s, row) {
92
+ if (!approvalReasons(q, s).length)
93
+ return 'not_needed';
94
+ if (!row)
95
+ return 'needed';
96
+ if (!timingSafeEqualHex(String(row.hash || ''), approvalHash(q)))
97
+ return 'stale';
98
+ return ['pending', 'approved', 'rejected'].includes(row.state) ? row.state : 'needed';
99
+ }
100
+ function timingSafeEqualHex(a, b) {
101
+ const ab = Buffer.from(a);
102
+ const bb = Buffer.from(b);
103
+ return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);
104
+ }
105
+ /** The message shown when a send or mark-as-sent is held, or null when it may go ahead. */
106
+ function approvalGateMessage(status, reasons) {
107
+ if (status === 'not_needed' || status === 'approved')
108
+ return null;
109
+ const why = reasons.join('; ');
110
+ switch (status) {
111
+ case 'pending': return `This quote is waiting for discount approval (${why}). It can be sent once an approver approves it.`;
112
+ case 'rejected': return `Discount approval was rejected for this quote (${why}). Change it and request approval again.`;
113
+ case 'stale': return `This quote changed after approval was given or requested (${why}). Request approval again before sending it.`;
114
+ default: return `This quote needs discount approval before it is sent (${why}). Use "Request approval" on the quote.`;
115
+ }
116
+ }
117
+ /**
118
+ * Whether `approverEmail` may decide on a quote: an approver (listed, or any
119
+ * SuperAdmin when the list is empty) who did not prepare it, unless they are
120
+ * the only approver and "let the preparer approve" is on.
121
+ */
122
+ function canDecide(opts) {
123
+ const me = String(opts.approverEmail || '').toLowerCase();
124
+ const list = opts.settings.approvers;
125
+ const isApprover = list.length ? list.includes(me) : opts.isSuperAdmin;
126
+ if (!me || !isApprover)
127
+ return { ok: false, reason: 'You are not an approver for discount approval.' };
128
+ const prep = String(opts.preparerEmail || '').toLowerCase();
129
+ if (prep && prep === me) {
130
+ const sole = list.length === 1 && list[0] === me;
131
+ if (!(sole && opts.settings.approvalSelfSole))
132
+ return { ok: false, reason: 'You prepared this quote, so another approver has to approve it.' };
133
+ }
134
+ return { ok: true };
135
+ }
136
+ //# sourceMappingURL=approvals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approvals.js","sourceRoot":"","sources":["../src/approvals.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,0CAMC;AAOD,0CAgBC;AAED,gDAEC;AAGD,oCASC;AAGD,wCAKC;AAQD,kDASC;AAOD,8BAaC;AA3GD,+CAAiC;AACjC,uCAAwC;AACxC,iDAAuD;AAcvD,mHAAmH;AACnH,SAAgB,eAAe,CAAC,CAAM;IAClC,IAAI,IAAI,GAAG,C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pI,OAAO,CAAC,CAAC,OAAO,yDAAyD,GAAG,yCAAyC,CAAC;IAC1H,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,SAAgB,SAAS,CAAC,IAEzB;IACG,MAAM,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC;IACrC,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC;IACvE,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,gDAAgD,EAAE,CAAC;IACvG,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IAC5D,IAAI,IAAI,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;QACtB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;QACjD,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC;YAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,iEAAiE,EAAE,CAAC;IACnJ,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AACxB,CAAC"}
package/dist/crons.d.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  import { ProcessContext } from '@vendure/core';
2
2
  import { QuotationService } from './quotation.service';
3
+ import { QuotationProService } from './pro.service';
3
4
  export declare class QuotationCrons {
4
5
  private service;
6
+ private pro;
5
7
  private processContext;
6
- constructor(service: QuotationService, processContext: ProcessContext);
8
+ constructor(service: QuotationService, pro: QuotationProService, processContext: ProcessContext);
7
9
  /** Concurrency guard — duplicate same-tick invocations exit immediately
8
10
  * (schedule explorers have been observed double-firing handlers, and
9
11
  * overlapping runs could double-send chaser emails). */
10
12
  private runInFlight;
11
- /** Hourly: expire overdue quotes (free tier — data correctness), then
12
- * send chasers/expiry reminders (premium only — they email customers). */
13
+ /** Hourly: expire overdue quotes, send the chaser and expiry reminders
14
+ * (all free), then the premium follow-up sequences and webhook retries. */
13
15
  hourly(): Promise<void>;
14
16
  }
15
17
  //# sourceMappingURL=crons.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"crons.d.ts","sourceRoot":"","sources":["../src/crons.ts"],"names":[],"mappings":"AAEA,OAAO,EAAU,cAAc,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAQvD,qBACa,cAAc;IACX,OAAO,CAAC,OAAO;IAAoB,OAAO,CAAC,cAAc;gBAAjD,OAAO,EAAE,gBAAgB,EAAU,cAAc,EAAE,cAAc;IAErF;;6DAEyD;IACzD,OAAO,CAAC,WAAW,CAAS;IAE5B;+EAC2E;IAErE,MAAM;CA+Bf"}
1
+ {"version":3,"file":"crons.d.ts","sourceRoot":"","sources":["../src/crons.ts"],"names":[],"mappings":"AAEA,OAAO,EAAU,cAAc,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAQpD,qBACa,cAAc;IACX,OAAO,CAAC,OAAO;IAAoB,OAAO,CAAC,GAAG;IAAuB,OAAO,CAAC,cAAc;gBAAnF,OAAO,EAAE,gBAAgB,EAAU,GAAG,EAAE,mBAAmB,EAAU,cAAc,EAAE,cAAc;IAEvH;;6DAEyD;IACzD,OAAO,CAAC,WAAW,CAAS;IAE5B;gFAC4E;IAEtE,MAAM;CAkCf"}
package/dist/crons.js CHANGED
@@ -14,21 +14,23 @@ const common_1 = require("@nestjs/common");
14
14
  const schedule_1 = require("@nestjs/schedule");
15
15
  const core_1 = require("@vendure/core");
16
16
  const quotation_service_1 = require("./quotation.service");
17
+ const pro_service_1 = require("./pro.service");
17
18
  const plugin_1 = require("./plugin");
18
19
  const loggerCtx = 'Quotations';
19
20
  /** Upper bound for one hourly pass; a stuck pass is logged and the guard released. */
20
21
  const HOURLY_DEADLINE_MS = 15 * 60000;
21
22
  let QuotationCrons = class QuotationCrons {
22
- constructor(service, processContext) {
23
+ constructor(service, pro, processContext) {
23
24
  this.service = service;
25
+ this.pro = pro;
24
26
  this.processContext = processContext;
25
27
  /** Concurrency guard — duplicate same-tick invocations exit immediately
26
28
  * (schedule explorers have been observed double-firing handlers, and
27
29
  * overlapping runs could double-send chaser emails). */
28
30
  this.runInFlight = false;
29
31
  }
30
- /** Hourly: expire overdue quotes (free tier — data correctness), then
31
- * send chasers/expiry reminders (premium only — they email customers). */
32
+ /** Hourly: expire overdue quotes, send the chaser and expiry reminders
33
+ * (all free), then the premium follow-up sequences and webhook retries. */
32
34
  async hourly() {
33
35
  if (this.processContext.isServer)
34
36
  return;
@@ -46,13 +48,17 @@ let QuotationCrons = class QuotationCrons {
46
48
  let step = 'expireOverdue';
47
49
  const run = (async () => {
48
50
  await this.service.expireOverdue();
49
- if (plugin_1.QuotationsPlugin.hasPremiumAccess()) {
50
- step = 'runChasers';
51
- const r = await this.service.runChasers();
52
- if (r.chasers || r.expiryReminders) {
53
- core_1.Logger.info(`sent ${r.chasers} chaser(s) + ${r.expiryReminders} expiry reminder(s)`, loggerCtx);
54
- }
51
+ step = 'runChasers';
52
+ const r = await this.service.runChasers();
53
+ if (r.chasers || r.expiryReminders) {
54
+ core_1.Logger.info(`sent ${r.chasers} chaser(s) + ${r.expiryReminders} expiry reminder(s)`, loggerCtx);
55
55
  }
56
+ step = 'runFollowUps';
57
+ const f = await this.pro.runFollowUps();
58
+ if (f)
59
+ core_1.Logger.info(`sent ${f} follow-up e-mail(s)`, loggerCtx);
60
+ step = 'webhooks';
61
+ await this.pro.hourlyWebhooks();
56
62
  })();
57
63
  let timer;
58
64
  const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`hourly run exceeded ${HOURLY_DEADLINE_MS / 60000} min in ${step}`)), HOURLY_DEADLINE_MS); });
@@ -78,6 +84,6 @@ __decorate([
78
84
  ], QuotationCrons.prototype, "hourly", null);
79
85
  exports.QuotationCrons = QuotationCrons = __decorate([
80
86
  (0, common_1.Injectable)(),
81
- __metadata("design:paramtypes", [quotation_service_1.QuotationService, core_1.ProcessContext])
87
+ __metadata("design:paramtypes", [quotation_service_1.QuotationService, pro_service_1.QuotationProService, core_1.ProcessContext])
82
88
  ], QuotationCrons);
83
89
  //# sourceMappingURL=crons.js.map
package/dist/crons.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"crons.js","sourceRoot":"","sources":["../src/crons.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAA4C;AAC5C,+CAAwD;AACxD,wCAAuD;AACvD,2DAAuD;AACvD,qCAAwD;AAExD,MAAM,SAAS,GAAG,YAAY,CAAC;AAE/B,sFAAsF;AACtF,MAAM,kBAAkB,GAAG,EAAE,GAAG,KAAM,CAAC;AAGhC,IAAM,cAAc,GAApB,MAAM,cAAc;IACvB,YAAoB,OAAyB,EAAU,cAA8B;QAAjE,YAAO,GAAP,OAAO,CAAkB;QAAU,mBAAc,GAAd,cAAc,CAAgB;QAErF;;iEAEyD;QACjD,gBAAW,GAAG,KAAK,CAAC;IAL4D,CAAC;IAOzF;+EAC2E;IAErE,AAAN,KAAK,CAAC,MAAM;QACR,IAAI,IAAI,CAAC,cAAc,CAAC,QAAQ;YAAE,OAAO;QACzC,IAAI,IAAA,mBAAU,GAAE,CAAC,WAAW;YAAE,OAAO;QACrC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YAAC,aAAM,CAAC,IAAI,CAAC,sDAAsD,EAA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,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,OAAO,KAAI,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;QAChF,CAAC;gBAAS,CAAC;YACP,IAAI,KAAK;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QAC7B,CAAC;IACL,CAAC;CACJ,CAAA;AA7CY,wCAAc;AAWjB;IADL,IAAA,eAAI,EAAC,yBAAc,CAAC,UAAU,CAAC;;;;4CAkC/B;yBA5CQ,cAAc;IAD1B,IAAA,mBAAU,GAAE;qCAEoB,oCAAgB,EAAe,iCAAmB,EAA0B,qBAAc;GAD9G,cAAc,CA6C1B"}
package/dist/csv.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** A cell a spreadsheet will not run as a formula: text starting with = + - @ or a tab/CR gets a leading apostrophe. */
2
+ export declare function csvCell(v: unknown): string;
3
+ /** One CSV line (RFC 4180 quoting) of formula-safe cells; the `numeric` columns are written as plain numbers. */
4
+ export declare function csvLine(cells: unknown[], numeric?: number[]): string;
5
+ /** Minor units → "1234.56" (or '' for null). */
6
+ export declare function csvAmount(minor: unknown): string;
7
+ //# sourceMappingURL=csv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"csv.d.ts","sourceRoot":"","sources":["../src/csv.ts"],"names":[],"mappings":"AAAA,wHAAwH;AACxH,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,CAI1C;AAED,iHAAiH;AACjH,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,OAAO,GAAE,MAAM,EAAO,GAAG,MAAM,CAMxE;AAED,gDAAgD;AAChD,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOhD"}
package/dist/csv.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.csvCell = csvCell;
4
+ exports.csvLine = csvLine;
5
+ exports.csvAmount = csvAmount;
6
+ /** A cell a spreadsheet will not run as a formula: text starting with = + - @ or a tab/CR gets a leading apostrophe. */
7
+ function csvCell(v) {
8
+ let s = v === null || v === undefined ? '' : v instanceof Date ? v.toISOString() : String(v);
9
+ if (s !== '' && /^[=+\-@\t\r]/.test(s))
10
+ s = `'${s}`;
11
+ return s;
12
+ }
13
+ /** One CSV line (RFC 4180 quoting) of formula-safe cells; the `numeric` columns are written as plain numbers. */
14
+ function csvLine(cells, numeric = []) {
15
+ return cells.map((c, i) => {
16
+ const s = numeric.includes(i) && typeof c === 'string' && /^-?\d+(\.\d+)?$/.test(c) ? c
17
+ : numeric.includes(i) && typeof c === 'number' && Number.isFinite(c) ? String(c) : csvCell(c);
18
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
19
+ }).join(',') + '\r\n';
20
+ }
21
+ /** Minor units → "1234.56" (or '' for null). */
22
+ function csvAmount(minor) {
23
+ if (minor === null || minor === undefined || minor === '')
24
+ return '';
25
+ const n = Math.round(Number(minor));
26
+ if (!Number.isFinite(n))
27
+ return '';
28
+ const sign = n < 0 ? '-' : '';
29
+ const a = Math.abs(n);
30
+ return `${sign}${Math.floor(a / 100)}.${String(a % 100).padStart(2, '0')}`;
31
+ }
32
+ //# sourceMappingURL=csv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"csv.js","sourceRoot":"","sources":["../src/csv.ts"],"names":[],"mappings":";;AACA,0BAIC;AAGD,0BAMC;AAGD,8BAOC;AAxBD,wHAAwH;AACxH,SAAgB,OAAO,CAAC,CAAU;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC7F,IAAI,CAAC,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