@huloglobal/vendure-plugin-quotations 0.8.5 → 0.9.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 (76) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +107 -10
  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/events.d.ts +55 -0
  20. package/dist/events.d.ts.map +1 -0
  21. package/dist/events.js +58 -0
  22. package/dist/events.js.map +1 -0
  23. package/dist/index.d.ts +4 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +7 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/pay-links.d.ts +37 -0
  28. package/dist/pay-links.d.ts.map +1 -0
  29. package/dist/pay-links.js +61 -0
  30. package/dist/pay-links.js.map +1 -0
  31. package/dist/payment.service.d.ts +117 -0
  32. package/dist/payment.service.d.ts.map +1 -0
  33. package/dist/payment.service.js +476 -0
  34. package/dist/payment.service.js.map +1 -0
  35. package/dist/pdf.d.ts +15 -0
  36. package/dist/pdf.d.ts.map +1 -0
  37. package/dist/pdf.js +356 -0
  38. package/dist/pdf.js.map +1 -0
  39. package/dist/plugin.d.ts +5 -2
  40. package/dist/plugin.d.ts.map +1 -1
  41. package/dist/plugin.js +18 -6
  42. package/dist/plugin.js.map +1 -1
  43. package/dist/pro-settings.d.ts +72 -0
  44. package/dist/pro-settings.d.ts.map +1 -0
  45. package/dist/pro-settings.js +202 -0
  46. package/dist/pro-settings.js.map +1 -0
  47. package/dist/pro.service.d.ts +130 -0
  48. package/dist/pro.service.d.ts.map +1 -0
  49. package/dist/pro.service.js +732 -0
  50. package/dist/pro.service.js.map +1 -0
  51. package/dist/quotation.controller.d.ts +50 -6
  52. package/dist/quotation.controller.d.ts.map +1 -1
  53. package/dist/quotation.controller.js +618 -24
  54. package/dist/quotation.controller.js.map +1 -1
  55. package/dist/quotation.service.d.ts +188 -11
  56. package/dist/quotation.service.d.ts.map +1 -1
  57. package/dist/quotation.service.js +636 -99
  58. package/dist/quotation.service.js.map +1 -1
  59. package/dist/quote-total.d.ts +49 -0
  60. package/dist/quote-total.d.ts.map +1 -0
  61. package/dist/quote-total.js +81 -0
  62. package/dist/quote-total.js.map +1 -0
  63. package/dist/templates.d.ts +13 -1
  64. package/dist/templates.d.ts.map +1 -1
  65. package/dist/templates.js +17 -6
  66. package/dist/templates.js.map +1 -1
  67. package/dist/types.d.ts +12 -0
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js +2 -0
  70. package/dist/types.js.map +1 -1
  71. package/dist/webhooks.d.ts +61 -0
  72. package/dist/webhooks.d.ts.map +1 -0
  73. package/dist/webhooks.js +308 -0
  74. package/dist/webhooks.js.map +1 -0
  75. package/package.json +4 -3
  76. package/ui/components/quotations.component.ts +328 -19
package/CHANGELOG.md CHANGED
@@ -5,6 +5,116 @@ 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.9.0] — 2026-11-13
9
+
10
+ Parity with HULO Quotations for WordPress (free 0.1.4 and Pro).
11
+
12
+ ### Changed (tiers)
13
+ - **Free now:** sending a quote, test sends, the unopened-quote chaser and the expiry reminder (they ran
14
+ premium-only before). Auto-expiry was already free and is now listed as such.
15
+ - **Premium now:** the weekly e-mail report and the set-up checklist. Without a licence or the evaluation the
16
+ report is not sent (the weekly clock is left as it was, so it resumes on the next Monday once a licence is
17
+ active), *Send me a test* and *Preview* answer 402, and the checklist reports nothing to do. Settings and data
18
+ are kept.
19
+ - Still premium: converting an accepted quote to a draft order from the admin, plus the new templates,
20
+ follow-up sequences, discount approval, webhooks, sales reports and deposits below.
21
+ - `PREMIUM_FEATURES` lists what is actually gated (storefront requests were listed but never gated).
22
+
23
+ ### Fixed
24
+ - **B5: KPIs and the weekly report no longer add amounts in different currencies together.** `GET /quotations/stats`
25
+ reports `valueByCurrency` per status, `pipelineByCurrency` and `last30.valueWonByCurrency` (minor units per
26
+ currency; `value` and `last30.valueWonPence` are gone). The weekly report, the admin banner and the dashboard
27
+ widget show value won per currency ("£1,234.56 + €500.00"). The anonymous heartbeat figure `valueWonPence`
28
+ counts the store's main currency only.
29
+ - Expiry is recorded per quote (trail entry "Validity ended" and an event) instead of one silent bulk update.
30
+ - Chasers and expiry reminders are claimed before they are sent and released when the e-mail fails, so an
31
+ overlapping or late run never sends one twice; the chaser only goes to quotes never opened.
32
+
33
+ ### Added (free)
34
+ - **EventBus events:** `QuotationEvent` (exported) for created, requested, updated, sent, viewed, accepted,
35
+ declined, expired, cancelled, converted, paid, payment, approval, follow-up and deleted, with a quote summary
36
+ (no token, no internal notes).
37
+ - **Mark as sent** (`POST /quotations/quotes/:id/mark-sent`): the store shared the quote itself; a draft or
38
+ request opens for the customer without an e-mail.
39
+ - **Validity counted from the send:** a quote keeps its validity period (`validityDays`) and its date starts
40
+ when it is first sent (or marked as sent). A resend keeps the date; a quote whose date has passed must be
41
+ extended first.
42
+ - **Staff preview** of the customer page (`GET /quotations/quotes/:id/page`): not counted as an opening, the
43
+ accept form is switched off.
44
+ - **Server-side PDF** (built in, no dependency): `GET /quotations/quote/:token/pdf` from the customer link
45
+ (rate-limited, not an opening, never cached), `GET /quotations/quotes/:id/pdf` for staff, a *Download PDF*
46
+ button on the customer page and an optional attachment on the quote e-mail (Settings → *Attach the quote as
47
+ a PDF*).
48
+ - **"My quotes"** for signed-in customers: `GET /quotations/my` (shop session, channel from `vendure-token`)
49
+ lists the customer's own quotes (by account, never by e-mail; drafts hidden; requests as "awaiting price")
50
+ with quote, PDF and pay links. A request posted while signed in is linked to the account; guest requests are
51
+ no longer linked to an account by e-mail address.
52
+ - **12-month report** (`GET /quotations/reports/monthly`, Reports tab): created, sent, accepted, win rate and
53
+ value won per currency per month.
54
+ - **Per-e-mail request throttle** kept in the database (10 an hour per address, across processes and restarts),
55
+ on top of the per-client limit.
56
+ - **HULO Payments pay link on acceptance:** with *Pay link on acceptance* on (Settings, per channel) the accepted
57
+ quote becomes a draft order at the quoted total, moves to ArrangingPayment (a free shipping method is picked
58
+ when the channel has one) and the customer is e-mailed a pay link; staff can also create and e-mail it from
59
+ the quote. HULO Payments for Vendure is detected at runtime (no dependency); a host can pass its own
60
+ `payLinks` provider to `init()`. The quote is marked paid when the order's settled payments cover the total.
61
+ The converted draft order now carries the quote's customer.
62
+
63
+ ### Added (premium)
64
+ - **Quote templates:** save a quote's lines, discounts, VAT, notes, terms, validity and currency (never the
65
+ customer or internal notes) and start new drafts from them (Templates tab).
66
+ - **Follow-up sequences:** up to three extra e-mails N days after sending while the quote is open and unpaid;
67
+ each step claimed once, in order, at most one a day per quote, never within a day of the chaser or reminder.
68
+ - **Discount approval:** limits on discount % off list, discount amount and total (per currency). A quote over
69
+ a limit cannot be sent or marked as sent until an approver approves exactly that version (a hash of lines,
70
+ discounts, VAT, currency and totals); an edit invalidates the approval. Test sends are never held; without
71
+ premium the gate is off. Approvers: listed admin e-mails, else any SuperAdmin; the preparer cannot approve
72
+ their own quote unless they are the only approver and that is allowed.
73
+ - **Webhooks** (up to five): JSON signed with `X-Hulo-Signature: sha256=HMAC(secret, "<timestamp>.<body>")`,
74
+ Slack and Microsoft Teams presets; public http(s) addresses on standard ports only, checked on save and on
75
+ every delivery with the connection pinned to the checked address; no redirects; retries with back-off (six
76
+ attempts); 30-day delivery log with retry and test.
77
+ - **Sales reports** by member of staff and by source, per currency, with a formula-safe CSV export.
78
+ - **Deposits:** a percentage (optionally only above a per-currency threshold, or per quote) taken first, then
79
+ the balance, as two pay links on the same order. Deposit + balance = the quoted total exactly in minor units
80
+ (zero-decimal currencies in whole units); every link is claimed before it is created; the quote is paid only
81
+ when the balance settles. A deposit already taken is completed whatever the licence state.
82
+
83
+ ### Compatibility
84
+ - New tables `quotation_template`, `quotation_followup`, `quotation_approval`, `quotation_webhook_log`,
85
+ `quotation_deposit` and new nullable / defaulted columns, created on start-up on MySQL, MariaDB and
86
+ PostgreSQL. Tested with Vendure 3.8.2; `@vendure/core >=3.5.0 <4.0.0`.
87
+ - Pay links need HULO Payments for Vendure exposing `createPayLink(ctx, { orderCode, amount?, currency,
88
+ description, customerEmail?, returnUrl?, expiresInHours?, reference?, metadata? }) → { url, ref }` on an
89
+ exported service (`PayLinkService` or `PaymentsService`), or a `payLinks` provider in `init()`.
90
+
91
+ ## [0.8.6] — 2026-11-13
92
+
93
+ ### Fixed
94
+ - **A converted quote keeps its quoted price through checkout on Vendure 3.8+.** Vendure 3.8 recalculates
95
+ every order, draft orders included, when it moves to `ArrangingPayment`. A draft order converted from a quote
96
+ then picked up catalogue price or promotion changes made after the conversion: in the e2e test a price rise
97
+ from 100.00 to 125.00 moved the accepted 168.00 quote to 198.00 at checkout. The plugin now adds an order
98
+ process that re-balances the quote surcharge right after that recalculation, in the same transaction, so the
99
+ order total (before shipping) and its VAT split match the quote again; the quote's history records a
100
+ `repriced` event. Orders whose lines an admin has changed since the conversion follow the catalogue as
101
+ before. Shipping is not part of a quote and is not touched. No change on Vendure 3.5 to 3.7, where the
102
+ transition does not recalculate.
103
+
104
+ ### Security
105
+ - **Admin REST routes refuse a Shop-API session on Vendure 3.8+.** Vendure 3.8 binds every session to the
106
+ API it was created on and refuses Shop-API sessions on the Admin API (GHSA-5fpx-9m35-w745), but it does not
107
+ check REST routes added by plugins: an administrator's storefront session still carried their admin
108
+ permissions into the Quotations admin REST routes. Those routes now also require a session created on the Admin API
109
+ (`isAdminApiSession` from the licence SDK 0.15.6, the same rule as Vendure's own AuthGuard). The admin UI
110
+ is unaffected; administrators logged in before the 3.8 upgrade log in again once, as Vendure already
111
+ requires. No change on Vendure 3.5 to 3.7.
112
+
113
+ ### Compatibility
114
+ - **Tested with Vendure 3.8.2** (NestJS 12, `@nestjs/graphql` 14, Apollo Server 5), as well as 3.5 to 3.7.
115
+ The peer range stays `@vendure/core >=3.5.0 <4.0.0`; nothing here needs 3.8.
116
+ - Requires `@huloglobal/vendure-licence-sdk` ^0.15.6.
117
+
8
118
  ## [0.8.5] — 2026-11-05
9
119
 
10
120
  ### Package metadata
package/README.md CHANGED
@@ -13,9 +13,19 @@ End-to-end quotation engine for [Vendure](https://www.vendure.io/):
13
13
  expires-soon nudge, plus auto-expiry.
14
14
  - **Convert** accepted quotes to Vendure draft orders at the exact quoted
15
15
  total and VAT (a pricing surcharge reconciles quoted vs catalogue pricing),
16
- in the quote's own channel and currency.
16
+ in the quote's own channel and currency. The price holds through checkout:
17
+ Vendure 3.8+ recalculates draft orders when they leave Draft, and the plugin
18
+ re-balances the surcharge so a later catalogue price or promotion change
19
+ does not move the quoted total (unless an admin has changed the lines).
17
20
  - **Receive requests** from your storefront: customers ask for a quote from
18
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.
19
29
 
20
30
  Works on MySQL, MariaDB and PostgreSQL. Admin UI included (Quotes,
21
31
  editor with catalogue search, Settings, a Help drawer and a set-up
@@ -80,14 +90,92 @@ await fetch('https://shop.example.com/quotations/request', {
80
90
 
81
91
  The quote appears under **Sales → Quotations** as *requested*; price any
82
92
  free-text lines, then **Send to customer**. Turn requests off per channel in
83
- Settings. Requests are throttled (10 an hour per client) and a hidden
84
- `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
+ ## PDF
113
+
114
+ `GET /quotations/quote/:token/pdf` (the customer link, rate-limited, never
115
+ cached, does not count as opening the quote) and `GET /quotations/quotes/:id/pdf`
116
+ (admin). Built in, no dependency: A4, Helvetica, Western European text
117
+ (other scripts print as "?"; the customer page shows every language). Turn on
118
+ **Settings → Attach the quote as a PDF** to attach it to the quote e-mail.
119
+
120
+ ## Pay links and deposits
121
+
122
+ With HULO Payments for Vendure installed (or your own provider passed as
123
+ `payLinks` in `init()`), an accepted quote can be paid online: the quote
124
+ becomes a draft order at the quoted total, the order moves to
125
+ ArrangingPayment (a free shipping method is chosen when the channel has one;
126
+ otherwise the admin is told what is missing), and the customer gets a pay
127
+ link. Turn on **Settings → Pay link on acceptance** to do this the moment the
128
+ customer accepts, or use **Create pay link** on the quote. The quote is marked
129
+ paid when the order's settled payments cover the quoted total. Quotations
130
+ works the same with or without HULO Payments.
131
+
132
+ ```ts
133
+ QuotationsPlugin.init({
134
+ payLinks: { create: async (ctx, { orderCode, amount, currency, description, reference }) => ({ url, ref }) },
135
+ });
136
+ ```
137
+
138
+ **Deposits (premium):** set a percentage (and optionally a per-currency
139
+ threshold, e.g. `GBP 1000, EUR 1200`) or a per-quote override. The customer
140
+ pays the deposit link first, then the balance link, both on the same order;
141
+ deposit + balance equal the quoted total exactly.
142
+
143
+ ## EventBus events
144
+
145
+ ```ts
146
+ import { QuotationEvent } from '@huloglobal/vendure-plugin-quotations';
147
+ eventBus.ofType(QuotationEvent).pipe(filter(e => e.type === 'accepted')).subscribe(e => { /* e.quote, e.detail, e.actor */ });
148
+ ```
149
+
150
+ Types: `created`, `requested`, `updated`, `sent`, `viewed`, `accepted`,
151
+ `declined`, `expired`, `cancelled`, `converted`, `paid`, `payment`,
152
+ `approval`, `followup`, `deleted`.
153
+
154
+ ## Premium features
155
+
156
+ - **Templates** (Templates tab): save a quote's lines, discounts, VAT, notes,
157
+ terms, validity and currency; start new drafts from them.
158
+ - **Follow-up sequences** (Settings): up to three e-mails N days after
159
+ sending, while the quote is open and unpaid.
160
+ - **Discount approval** (Settings): a quote whose discount off list (percent
161
+ or amount) or total is over a limit cannot be sent or marked as sent until
162
+ an approver approves that exact version; any edit needs a new approval.
163
+ - **Webhooks** (Settings, up to five): JSON (signed
164
+ `X-Hulo-Signature: sha256=HMAC-SHA256(secret, "<X-Hulo-Timestamp>.<body>")`),
165
+ Slack or Microsoft Teams. Events: request created, quote sent, opened,
166
+ accepted, declined, paid, expired, converted, approval requested. Public
167
+ addresses only, retries with back-off, a 30-day delivery log.
168
+ - **Sales reports** (Reports tab) by member of staff and by source, per
169
+ currency, with a CSV export.
170
+ - **Deposits**, the **weekly report** and the **set-up checklist**.
85
171
 
86
172
  ## Admin UI
87
173
 
88
174
  **Sales → Quotations** (requires the `ReadSettings` permission; writes need
89
- `UpdateSettings`). The page has three tabs — Quotes (inbox, KPIs, detail
90
- and activity trail), the step-by-step editor, and Settings — plus a
175
+ `UpdateSettings`). The page has five tabs — Quotes (inbox, KPIs per
176
+ currency, detail with payment, deposit and approval, activity trail), the
177
+ step-by-step editor, Reports (12 months; sales by staff and source),
178
+ Templates, and Settings — plus a
91
179
  **Help** button in the header that opens a three-step drawer (New quote →
92
180
  Send → Convert).
93
181
 
@@ -97,6 +185,10 @@ and a link into the page.
97
185
 
98
186
  ## Weekly report, setup checklist and dashboard widget
99
187
 
188
+ The weekly report and the set-up checklist are **premium** (licence or the
189
+ 14-day evaluation). Without premium the report is not sent and the checklist
190
+ is not shown; their settings are kept and they resume when a licence is active.
191
+
100
192
  **Set-up checklist.** The top of the Quotes tab shows what is left to do,
101
193
  each item checked against the real state: an email server reachable
102
194
  (`SMTP_*` env or the `smtp` option), a reply-to or notify address saved
@@ -131,11 +223,16 @@ Endpoints (admin session): `GET /quotations/setup`,
131
223
 
132
224
  ## Licensing
133
225
 
134
- Unlicensed installs run in the free tier; the 14-day free trial (card required) is started from the admin banner. Afterwards the
135
- plugin drops to the free tier: drafting, pricing and previews stay free —
136
- **sending, chasers and order conversion require a licence** from
137
- https://huloglobal.com/vendure-plugins/quotations/.
226
+ Unlicensed installs run in the free tier, with a 14-day evaluation of the
227
+ premium features (no card). **Free:** building, sending, test sends, mark as
228
+ sent, the customer page with signature, PDF, storefront requests, "My quotes",
229
+ the chaser and expiry reminder, auto-expiry, pay links on acceptance, KPIs,
230
+ the 12-month report and EventBus events. **Premium** (licence from
231
+ https://huloglobal.com/vendure-plugins/quotations/): converting to a draft
232
+ order from the admin, templates, follow-up sequences, discount approval,
233
+ webhooks, sales reports with CSV, deposits, the weekly report and the set-up
234
+ checklist.
138
235
 
139
236
  ## Buying a licence
140
237
 
141
- 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.
238
+ 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,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AC;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,CAAC,CAAC;IACb,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE;QAAE,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,cAAc,IAAI,CAAC,CAAC,CAAC;IAC/F,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,aAAa,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,aAAa,IAAI,CAAC,CAAC,CAAC;IACxE,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC;IACvC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC3F,CAAC;AAED,SAAS,OAAO,CAAC,CA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AK,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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AC;YAClB,MAAM,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;QACpC,CAAC,CAAC,EAAE,CAAC;QACL,IAAI,KAAiC,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,uBAAuB,kBAAkB,GAAG,KAAM,WAAW,IAAI,EAAE,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9L,IAAI,CAAC;YACD,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC;QACxC,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YACd,aAAM,CAAC,KAAK,CAAC,iCAAiC,CAAA,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,KAAK,EAAE,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;QAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;IACpD,OAAO,CAAC,CAAC;AACb,CAAC;AAED,iHAAiH;AACjH,SAAgB,OAAO,CAAC,KAAgB,EAAE,UAAoB,EAAE;IAC5D,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACtB,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACnF,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QAClG,OAAO,UAAU,C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