@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
@@ -41,6 +41,7 @@ var __importStar = (this && this.__importStar) || (function () {
41
41
  var __metadata = (this && this.__metadata) || function (k, v) {
42
42
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
43
  };
44
+ var QuotationService_1;
44
45
  Object.defineProperty(exports, "__esModule", { value: true });
45
46
  exports.QuotationService = exports.STAT_DEFS = exports.PREMIUM_FEATURES = void 0;
46
47
  const common_1 = require("@nestjs/common");
@@ -51,18 +52,31 @@ const vendure_licence_sdk_1 = require("@huloglobal/vendure-licence-sdk");
51
52
  const catalogue_search_1 = require("./catalogue-search");
52
53
  const pricing_1 = require("./pricing");
53
54
  const quote_version_1 = require("./quote-version");
55
+ const quote_total_1 = require("./quote-total");
54
56
  const templates_1 = require("./templates");
57
+ const events_1 = require("./events");
58
+ const pdf_1 = require("./pdf");
55
59
  const types_1 = require("./types");
56
60
  const loggerCtx = 'Quotations';
57
61
  const PLUGIN_ID = 'vendure-plugin-quotations';
58
62
  const PLUGIN_NAME = 'Quotations';
59
63
  const DAY_MS = 86400000;
60
- /** What the free tier loses — shown on the admin banners and in the weekly report. */
64
+ /**
65
+ * What the free tier does not have — shown on the admin banners and in the
66
+ * weekly report. Free: building, sending (and test-sending, marking as sent),
67
+ * the customer page with accept/decline, the PDF, storefront requests,
68
+ * "My quotes", the chaser and expiry reminder, auto-expiry, HULO Payments pay
69
+ * links on acceptance, EventBus events, KPIs and the 12-month report.
70
+ */
61
71
  exports.PREMIUM_FEATURES = [
62
- 'Send quotes and chasers by email',
63
- 'Convert accepted quotes to orders',
64
- 'Storefront quote requests with acknowledgement',
65
- 'Expiry and chaser automation',
72
+ 'Convert accepted quotes to draft orders from the admin',
73
+ 'Quote templates',
74
+ 'Follow-up sequences',
75
+ 'Discount approval',
76
+ 'Webhooks with Slack and Teams alerts',
77
+ 'Sales reports by staff and source, with CSV export',
78
+ 'Deposits and balance payments',
79
+ 'Weekly report and set-up checklist',
66
80
  ];
67
81
  /** The usage figures this plugin reports (evaluation + heartbeat stats,
68
82
  * weekly report, dashboard widget). Keys are stable; every value is a
@@ -75,6 +89,22 @@ exports.STAT_DEFS = [
75
89
  { key: 'requestsReceived', label: 'quote requests received from your storefront', format: 'count' },
76
90
  { key: 'winRatePct', label: 'win rate on quotes sent', format: 'percent' },
77
91
  ];
92
+ /**
93
+ * The weekly report scheduler, held back while premium is off (the report is
94
+ * a premium feature): ticks do nothing then, and the clock is not moved, so
95
+ * the report resumes on the next due Monday once a licence is active.
96
+ */
97
+ class PremiumDigest extends vendure_licence_sdk_1.WeeklyDigest {
98
+ constructor(opts, premium) {
99
+ super(opts);
100
+ this.premium = premium;
101
+ }
102
+ async tick(now = new Date()) {
103
+ if (!this.premium())
104
+ return false;
105
+ return super.tick(now);
106
+ }
107
+ }
78
108
  /** statuses a customer can still respond from */
79
109
  const OPEN_STATUSES = ['sent', 'viewed'];
80
110
  /** statuses an admin can still edit */
@@ -83,16 +113,18 @@ const EDITABLE_STATUSES = ['requested', 'draft', 'sent', 'viewed'];
83
113
  const REQUESTS_PER_HOUR = 10;
84
114
  /** request acknowledgements: at most one per recipient per day, and this many per hour per process */
85
115
  const ACKS_PER_HOUR = 30;
86
- let QuotationService = class QuotationService {
116
+ /** quote requests per e-mail address per hour, counted in the database (so across processes and restarts) */
117
+ const REQUESTS_PER_EMAIL_PER_HOUR = 10;
118
+ let QuotationService = QuotationService_1 = class QuotationService {
87
119
  initDigest(hooks) {
88
120
  this.digestHooks = hooks;
89
121
  if (!this.weeklyDigest) {
90
- this.weeklyDigest = new vendure_licence_sdk_1.WeeklyDigest({
122
+ this.weeklyDigest = new PremiumDigest({
91
123
  pluginId: PLUGIN_ID, pluginName: PLUGIN_NAME, prefs: this.prefs,
92
124
  collect: (from, to) => this.collectDigest(from, to),
93
125
  send: (to, mail) => this.sendDigest(to, mail),
94
126
  defaultRecipient: () => this.digestDefaultRecipient(),
95
- });
127
+ }, () => this.isPremium());
96
128
  }
97
129
  return this.weeklyDigest;
98
130
  }
@@ -103,10 +135,13 @@ let QuotationService = class QuotationService {
103
135
  }
104
136
  return this.purchaseClaim;
105
137
  }
106
- constructor(connection, channelService, orderService) {
138
+ constructor(connection, channelService, orderService, eventBus, requestContextService, customerService) {
107
139
  this.connection = connection;
108
140
  this.channelService = channelService;
109
141
  this.orderService = orderService;
142
+ this.eventBus = eventBus;
143
+ this.requestContextService = requestContextService;
144
+ this.customerService = customerService;
110
145
  this.options = {};
111
146
  this.licenceStore = new vendure_licence_sdk_1.LicenceStore((sql, params, opts) => (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection).query(sql, params, opts));
112
147
  /** Small per-plugin settings (weekly report recipient, dismissed set-up items, trial lead). */
@@ -117,6 +152,10 @@ let QuotationService = class QuotationService {
117
152
  // Buy-from-admin auto-install (hooks are supplied by the controller so
118
153
  // this file never imports the plugin class).
119
154
  this.purchaseClaim = null;
155
+ // ── Premium + extension hooks (supplied by the plugin class and the companion services) ──
156
+ this.premiumCheck = () => false;
157
+ this.preSendGates = [];
158
+ this.trailListeners = [];
120
159
  this.mailer = null;
121
160
  // ── Customer-initiated quote requests ───────────────────────────────
122
161
  this.requestHits = new Map();
@@ -125,10 +164,42 @@ let QuotationService = class QuotationService {
125
164
  // ── Product search for the editor ───────────────────────────────────
126
165
  /** Per channel+language: which catalogue the search reads (see catalogue-search.ts); re-checked every minute. */
127
166
  this.catalogueSources = new Map();
167
+ /** Payment / deposit text and buttons for the customer page (filled in by the payment service). */
168
+ this.pageExtrasProvider = null;
128
169
  }
129
170
  get db() { return (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection); }
171
+ /** The SQL adapter (MariaDB/MySQL/Postgres) the companion services share. */
172
+ get sql() { return this.db; }
130
173
  setOptions(o) { this.options = o || {}; }
131
174
  getOptions() { return this.options; }
175
+ setPremiumCheck(fn) { this.premiumCheck = fn; }
176
+ /** Licensed, or inside the evaluation. */
177
+ isPremium() { try {
178
+ return !!this.premiumCheck();
179
+ }
180
+ catch {
181
+ return false;
182
+ } }
183
+ addPreSendGate(gate) { this.preSendGates.push(gate); }
184
+ /** The first refusal from a gate, or null. Test sends go through the gates too (they decide whether to hold them). */
185
+ async preSend(q, mode, actor) {
186
+ for (const g of this.preSendGates) {
187
+ const r = await g(q, mode, actor).catch((e) => `Could not check the quote before sending: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
188
+ if (r)
189
+ return r;
190
+ }
191
+ return null;
192
+ }
193
+ onTrail(fn) { this.trailListeners.push(fn); }
194
+ /** A request context on the quote's channel for work no admin started (the customer page, the cron, payment events). */
195
+ async systemCtx(channelId) {
196
+ const channel = await this.channelService.findOne(core_1.RequestContext.empty(), channelId).catch(() => undefined)
197
+ || await this.channelService.getDefaultChannel().catch(() => undefined);
198
+ if (this.requestContextService && channel) {
199
+ return this.requestContextService.create({ apiType: 'admin', channelOrToken: channel });
200
+ }
201
+ return core_1.RequestContext.empty();
202
+ }
132
203
  async onModuleInit() {
133
204
  await this.ensureSchema();
134
205
  await this.licenceStore.ensureTable();
@@ -216,6 +287,17 @@ let QuotationService = class QuotationService {
216
287
  await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestMessage VARCHAR(2000) NOT NULL DEFAULT ''`);
217
288
  await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestSource VARCHAR(64) NOT NULL DEFAULT ''`);
218
289
  await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestedAt DATETIME NULL`);
290
+ // 0.9.0: validity counted from the send, payment (pay link + paid), My quotes and payment lookups.
291
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS validityDays INT NULL`);
292
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS paidAt DATETIME NULL`);
293
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS payUrl VARCHAR(1000) NOT NULL DEFAULT ''`);
294
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS payRef VARCHAR(190) NOT NULL DEFAULT ''`);
295
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS payProvider VARCHAR(120) NOT NULL DEFAULT ''`);
296
+ await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_order (convertedOrderId)`).catch(() => undefined);
297
+ await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_customer (customerId)`).catch(() => undefined);
298
+ await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_requested (customerEmail, requestedAt)`).catch(() => undefined);
299
+ await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS payLinkOnAccept TINYINT NOT NULL DEFAULT 0`);
300
+ await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS attachPdf TINYINT NOT NULL DEFAULT 0`);
219
301
  await this.db.query(`
220
302
  CREATE TABLE IF NOT EXISTS quotation_line (
221
303
  id INT AUTO_INCREMENT PRIMARY KEY,
@@ -243,7 +325,7 @@ let QuotationService = class QuotationService {
243
325
  }
244
326
  // ── Config ──────────────────────────────────────────────────────────
245
327
  rowToConfig(row, code) {
246
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v, _w;
328
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
247
329
  return {
248
330
  channelId: row.channelId,
249
331
  channelCode: code,
@@ -270,6 +352,8 @@ let QuotationService = class QuotationService {
270
352
  footerNote: (_v = row.footerNote) !== null && _v !== void 0 ? _v : '',
271
353
  acceptRequests: !!Number((_w = row.acceptRequests) !== null && _w !== void 0 ? _w : 1),
272
354
  requestAckBody: row.requestAckBody || types_1.DEFAULT_CONFIG.requestAckBody,
355
+ payLinkOnAccept: !!Number((_x = row.payLinkOnAccept) !== null && _x !== void 0 ? _x : 0),
356
+ attachPdf: !!Number((_y = row.attachPdf) !== null && _y !== void 0 ? _y : 0),
273
357
  };
274
358
  }
275
359
  async getConfig(channelId) {
@@ -289,8 +373,8 @@ let QuotationService = class QuotationService {
289
373
  await this.db.query(`INSERT INTO quotation_config (channelId, numberPrefix, nextNumber, defaultValidityDays, defaultVatRate, defaultTerms,
290
374
  businessName, replyTo, notifyEmail, currency, logoUrl, accentColor, chaserEnabled, chaserAfterDays,
291
375
  expiryReminderDays, emailSubject, emailBody, notifyOnView, websiteUrl, phone, addressText, footerNote,
292
- acceptRequests, requestAckBody)
293
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
376
+ acceptRequests, requestAckBody, payLinkOnAccept, attachPdf)
377
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
294
378
  ON DUPLICATE KEY UPDATE numberPrefix=VALUES(numberPrefix), defaultValidityDays=VALUES(defaultValidityDays),
295
379
  defaultVatRate=VALUES(defaultVatRate), defaultTerms=VALUES(defaultTerms), businessName=VALUES(businessName),
296
380
  replyTo=VALUES(replyTo), notifyEmail=VALUES(notifyEmail), currency=VALUES(currency), logoUrl=VALUES(logoUrl),
@@ -298,14 +382,16 @@ let QuotationService = class QuotationService {
298
382
  expiryReminderDays=VALUES(expiryReminderDays), emailSubject=VALUES(emailSubject), emailBody=VALUES(emailBody),
299
383
  notifyOnView=VALUES(notifyOnView), websiteUrl=VALUES(websiteUrl), phone=VALUES(phone),
300
384
  addressText=VALUES(addressText), footerNote=VALUES(footerNote),
301
- acceptRequests=VALUES(acceptRequests), requestAckBody=VALUES(requestAckBody)`, [c.channelId, c.numberPrefix || 'Q-', Math.max(1, Number(c.nextNumber) || 1),
385
+ acceptRequests=VALUES(acceptRequests), requestAckBody=VALUES(requestAckBody),
386
+ payLinkOnAccept=VALUES(payLinkOnAccept), attachPdf=VALUES(attachPdf)`, [c.channelId, c.numberPrefix || 'Q-', Math.max(1, Number(c.nextNumber) || 1),
302
387
  Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, String(c.defaultTerms || '').slice(0, 4000),
303
388
  c.businessName || '', c.replyTo || '', c.notifyEmail || '', (c.currency || 'GBP').toUpperCase().slice(0, 3),
304
389
  c.logoUrl || '', c.accentColor || '#1d4ed8', c.chaserEnabled ? 1 : 0, Math.max(1, Number(c.chaserAfterDays) || 3),
305
390
  Math.max(0, Number(c.expiryReminderDays) || 0), String(c.emailSubject || '').slice(0, 300), String(c.emailBody || '').slice(0, 4000), c.notifyOnView ? 1 : 0,
306
391
  String(c.websiteUrl || '').slice(0, 300), String(c.phone || '').slice(0, 64),
307
392
  String(c.addressText || '').slice(0, 500), String(c.footerNote || '').slice(0, 500),
308
- c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000)], { conflictColumns: ['channelId'] });
393
+ c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000),
394
+ c.payLinkOnAccept ? 1 : 0, c.attachPdf ? 1 : 0], { conflictColumns: ['channelId'] });
309
395
  }
310
396
  // ── Reference numbering ─────────────────────────────────────────────
311
397
  /** Atomically claims the next quote number for a channel. */
@@ -353,19 +439,21 @@ let QuotationService = class QuotationService {
353
439
  const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
354
440
  const reference = await this.nextReference(channelId);
355
441
  const token = crypto.randomBytes(24).toString('hex');
356
- const validityDays = Math.max(1, Number(input.validityDays) || cfg.defaultValidityDays);
442
+ // The validity period; it starts afresh when the quote is first sent (see sendQuote / markSent).
443
+ const validityDays = Math.min(365, Math.max(1, Math.floor(Number(input.validityDays) || cfg.defaultValidityDays || 30)));
357
444
  const res = await this.db.query(`INSERT INTO quotation (channelId, reference, status, token, customerId, customerName, customerEmail,
358
445
  customerCompany, customerPhone, notes, internalNotes, terms, vatRate, discountType, discountValue,
359
446
  currency, validUntil, subTotalPence, discountPence, vatPence, totalPence, createdBy,
360
- preparedByName, preparedByEmail, createdAt, updatedAt)
361
- VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
447
+ preparedByName, preparedByEmail, validityDays, createdAt, updatedAt)
448
+ VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
362
449
  String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
363
450
  String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
364
451
  String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000), String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : cfg.defaultTerms) !== null && _c !== void 0 ? _c : '').slice(0, 20000),
365
452
  vatRate, discountType, discountValue, (input.currency || cfg.currency || 'GBP').toUpperCase().slice(0, 3),
366
453
  validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
367
454
  actor.slice(0, 190),
368
- String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190)], { needInsertId: true });
455
+ String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
456
+ validityDays], { needInsertId: true });
369
457
  const quoteId = Number(res.insertId);
370
458
  await this.replaceLines(quoteId, lines);
371
459
  await this.logEvent(quoteId, 'created', `Quote ${reference} created`, actor);
@@ -403,6 +491,7 @@ let QuotationService = class QuotationService {
403
491
  await this.db.query(`UPDATE quotation SET customerId=?, customerName=?, customerEmail=?, customerCompany=?, customerPhone=?,
404
492
  notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
405
493
  validUntil=${touchValidity ? 'DATE_ADD(NOW(), INTERVAL ? DAY)' : 'validUntil'},
494
+ validityDays=${touchValidity ? '?' : 'validityDays'},
406
495
  subTotalPence=?, discountPence=?, vatPence=?, totalPence=?,
407
496
  preparedByName=?, preparedByEmail=?, updatedAt=NOW()
408
497
  WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
@@ -410,7 +499,7 @@ let QuotationService = class QuotationService {
410
499
  String(input.customerPhone || '').slice(0, 64), String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000),
411
500
  String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms) !== null && _c !== void 0 ? _c : '').slice(0, 20000), vatRate, discountType, discountValue,
412
501
  (input.currency || existing.currency).toUpperCase().slice(0, 3),
413
- ...(touchValidity ? [Math.max(1, Math.floor(newValidity))] : []),
502
+ ...(touchValidity ? [Math.min(365, Math.max(1, Math.floor(newValidity))), Math.min(365, Math.max(1, Math.floor(newValidity)))] : []),
414
503
  totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
415
504
  String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
416
505
  quoteId]);
@@ -424,8 +513,12 @@ let QuotationService = class QuotationService {
424
513
  return;
425
514
  if (q.status !== 'draft' && q.status !== 'requested')
426
515
  throw new Error('Only draft quotes and requests can be deleted — cancel instead');
516
+ await this.publishEvent({ ...q, status: 'deleted' }, 'deleted', `Quote ${q.reference} deleted`);
427
517
  await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
428
518
  await this.db.query(`DELETE FROM quotation_event WHERE quoteId = ?`, [quoteId]);
519
+ for (const t of ['quotation_followup', 'quotation_approval', 'quotation_deposit']) {
520
+ await this.db.query(`DELETE FROM ${t} WHERE quoteId = ?`, [quoteId]).catch(() => undefined);
521
+ }
429
522
  await this.db.query(`DELETE FROM quotation WHERE id = ?`, [quoteId]);
430
523
  }
431
524
  async cancelQuote(quoteId, actor) {
@@ -447,7 +540,7 @@ let QuotationService = class QuotationService {
447
540
  customerCompany: q.customerCompany, customerPhone: q.customerPhone,
448
541
  notes: q.notes, internalNotes: q.internalNotes, terms: q.terms,
449
542
  vatRate: q.vatRate, discountType: q.discountType, discountValue: q.discountValue,
450
- currency: q.currency, validityDays: 30,
543
+ currency: q.currency, validityDays: this.validityDaysOf(q),
451
544
  lines: q.lines.map((l) => ({
452
545
  productVariantId: l.productVariantId, sku: l.sku, description: l.description,
453
546
  quantity: l.quantity, unitPricePence: l.unitPricePence, lineDiscountPercent: l.lineDiscountPercent,
@@ -506,8 +599,40 @@ let QuotationService = class QuotationService {
506
599
  FROM quotation ${whereSql} ORDER BY id DESC LIMIT ${perPage} OFFSET ${(page - 1) * perPage}`, params);
507
600
  return { items, totalItems: Number((count === null || count === void 0 ? void 0 : count.n) || 0), page, perPage };
508
601
  }
602
+ /**
603
+ * Add an entry to the quote's activity trail, then tell the listeners
604
+ * (webhooks, pay links) and publish a {@link QuotationEvent} on the
605
+ * EventBus for the types subscribers care about.
606
+ */
509
607
  async logEvent(quoteId, type, detail, actor = '') {
510
- await this.db.query(`INSERT INTO quotation_event (quoteId, type, detail, actor, createdAt) VALUES (?, ?, ?, ?, NOW())`, [quoteId, type.slice(0, 24), detail.slice(0, 1000), actor.slice(0, 190)]).catch(() => undefined);
608
+ const res = await this.db.query(`INSERT INTO quotation_event (quoteId, type, detail, actor, createdAt) VALUES (?, ?, ?, ?, NOW())`, [quoteId, type.slice(0, 24), detail.slice(0, 1000), actor.slice(0, 190)], { needInsertId: true }).catch(() => null);
609
+ const id = Number((res === null || res === void 0 ? void 0 : res.insertId) || 0);
610
+ for (const fn of this.trailListeners) {
611
+ try {
612
+ fn({ id, quoteId, type, detail, actor });
613
+ }
614
+ catch (e) {
615
+ core_1.Logger.warn(`trail listener failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
616
+ }
617
+ }
618
+ if (events_1.PUBLISHED_EVENT_TYPES.has(type))
619
+ void this.publishEvent(quoteId, type, detail, actor);
620
+ }
621
+ /** Publish a QuotationEvent (never throws; subscribers run after this request's work). */
622
+ async publishEvent(quoteIdOrQuote, type, detail, actor = '') {
623
+ if (!this.eventBus)
624
+ return;
625
+ try {
626
+ const q = typeof quoteIdOrQuote === 'object' ? quoteIdOrQuote
627
+ : (await this.db.query(`SELECT * FROM quotation WHERE id = ?`, [quoteIdOrQuote]))[0];
628
+ if (!q)
629
+ return;
630
+ const ctx = await this.systemCtx(Number(q.channelId) || 1);
631
+ await this.eventBus.publish(new events_1.QuotationEvent(ctx, type, (0, events_1.eventQuote)(q), detail, actor));
632
+ }
633
+ catch (e) {
634
+ core_1.Logger.warn(`could not publish the ${type} quotation event: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
635
+ }
511
636
  }
512
637
  // ── Sending ─────────────────────────────────────────────────────────
513
638
  quoteUrl(token) {
@@ -555,37 +680,101 @@ let QuotationService = class QuotationService {
555
680
  new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`SMTP send timed out after ${ms / 1000}s`)), ms); }),
556
681
  ]).finally(() => clearTimeout(timer));
557
682
  }
683
+ /**
684
+ * The quote's validity period in days: as set in the editor, else derived
685
+ * from the stored dates (quotes made before 0.9.0), else the channel default.
686
+ */
687
+ validityDaysOf(q, cfg) {
688
+ let d = Number(q.validityDays || 0);
689
+ if (d < 1 && q.validUntil && q.createdAt)
690
+ d = Math.round((new Date(q.validUntil).getTime() - new Date(q.createdAt).getTime()) / DAY_MS);
691
+ if (d < 1)
692
+ d = Number((cfg === null || cfg === void 0 ? void 0 : cfg.defaultValidityDays) || types_1.DEFAULT_CONFIG.defaultValidityDays);
693
+ return Math.max(1, Math.min(365, Math.floor(d)));
694
+ }
695
+ /**
696
+ * E-mail the quote to the customer and open it for their response. A
697
+ * first send (draft or request) starts the validity period, so the e-mail
698
+ * (and its PDF) carry the new date; a resend keeps the date, and a quote
699
+ * whose date has passed must be extended first. Free.
700
+ */
558
701
  async sendQuote(quoteId, actor) {
559
702
  const q = await this.getQuote(quoteId);
560
703
  if (!q)
561
704
  return { ok: false, reason: 'Quote not found' };
562
- if (!q.customerEmail)
563
- return { ok: false, reason: 'The quote has no customer email' };
705
+ if (!q.customerEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q.customerEmail))
706
+ return { ok: false, reason: 'The quote has no valid customer email' };
564
707
  if (['accepted', 'declined', 'converted', 'cancelled', 'expired'].includes(q.status)) {
565
708
  return { ok: false, reason: `A ${q.status} quote cannot be sent` };
566
709
  }
710
+ const held = await this.preSend(q, 'send', actor);
711
+ if (held)
712
+ return { ok: false, reason: held };
567
713
  const cfg = await this.getConfig(q.channelId);
714
+ const first = q.status === 'draft' || q.status === 'requested';
715
+ const days = this.validityDaysOf(q, cfg);
716
+ if (first) {
717
+ q.validUntil = new Date(Date.now() + days * DAY_MS);
718
+ }
719
+ else if (q.validUntil && new Date(q.validUntil).getTime() <= Date.now()) {
720
+ return { ok: false, reason: `This quote's validity ended on ${new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })}. Extend it first, then send it again.` };
721
+ }
568
722
  const res = await this.deliverEmail(q, cfg, 'quote');
569
723
  if (!res.ok)
570
724
  return res;
571
- await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), updatedAt=NOW() WHERE id = ?`, [quoteId]);
572
- await this.logEvent(quoteId, 'sent', `Sent to ${q.customerEmail}`, actor);
725
+ if (first) {
726
+ await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), validUntil=DATE_ADD(NOW(), INTERVAL ? DAY), validityDays=?, expiryReminderSentAt=NULL, updatedAt=NOW()
727
+ WHERE id = ? AND status IN ('draft','requested')`, [days, days, quoteId]);
728
+ }
729
+ else {
730
+ await this.db.query(`UPDATE quotation SET sentAt=NOW(), updatedAt=NOW() WHERE id = ? AND status IN ('sent','viewed')`, [quoteId]);
731
+ }
732
+ const until = new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
733
+ await this.logEvent(quoteId, 'sent', first ? `Sent to ${q.customerEmail}; valid until ${until}` : `Sent again to ${q.customerEmail}`, actor);
573
734
  return { ok: true };
574
735
  }
575
- async deliverEmail(q, cfg, kind, overrideTo) {
576
- const smtp = this.smtpSettings();
577
- if (!smtp)
578
- return { ok: false, reason: 'SMTP is not configured (SMTP_SERVER / SMTP_USER env or plugin options)' };
579
- const url = this.quoteUrl(q.token);
580
- const vars = {
736
+ /**
737
+ * The store shared the quote itself (the PDF, or the customer link by its
738
+ * own e-mail): open it for the customer's response without e-mailing.
739
+ * Only a draft or a request moves, and its validity starts now. Free.
740
+ */
741
+ async markSent(quoteId, actor) {
742
+ const q = await this.getQuote(quoteId);
743
+ if (!q)
744
+ return { ok: false, reason: 'Quote not found' };
745
+ const held = await this.preSend(q, 'mark_sent', actor);
746
+ if (held)
747
+ return { ok: false, reason: held };
748
+ const cfg = await this.getConfig(q.channelId);
749
+ const days = this.validityDaysOf(q, cfg);
750
+ const res = await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), validUntil=DATE_ADD(NOW(), INTERVAL ? DAY), validityDays=?, expiryReminderSentAt=NULL, updatedAt=NOW()
751
+ WHERE id = ? AND status IN ('draft','requested')`, [days, days, quoteId], { needAffected: true });
752
+ if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) !== 1) {
753
+ const now = await this.getQuote(quoteId);
754
+ if (now && OPEN_STATUSES.includes(now.status))
755
+ return { ok: false, reason: 'This quote is already marked as sent: the customer can open the link.' };
756
+ if ((now === null || now === void 0 ? void 0 : now.status) === 'expired')
757
+ return { ok: false, reason: 'This quote has expired. Extend it to open it for the customer again.' };
758
+ return { ok: false, reason: `A ${(now === null || now === void 0 ? void 0 : now.status) || 'missing'} quote cannot be marked as sent.` };
759
+ }
760
+ const until = new Date(Date.now() + days * DAY_MS).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
761
+ await this.logEvent(quoteId, 'sent', `Marked as sent (shared by the store); valid until ${until}`, actor);
762
+ return { ok: true };
763
+ }
764
+ /** The {{placeholders}} every customer e-mail can use. */
765
+ emailVars(q, cfg, extra = {}) {
766
+ return {
581
767
  reference: q.reference,
582
768
  customerName: q.customerName || 'there',
583
769
  businessName: cfg.businessName || 'our team',
584
770
  staffName: q.preparedByName || cfg.businessName || 'our team',
585
771
  total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
586
772
  validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
587
- quoteUrl: url,
773
+ quoteUrl: this.quoteUrl(q.token),
774
+ ...extra,
588
775
  };
776
+ }
777
+ async deliverEmail(q, cfg, kind, overrideTo) {
589
778
  let subject = cfg.emailSubject || types_1.DEFAULT_CONFIG.emailSubject;
590
779
  let body = cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody;
591
780
  if (kind === 'chaser') {
@@ -596,21 +785,36 @@ let QuotationService = class QuotationService {
596
785
  subject = `Your quotation {{reference}} expires soon`;
597
786
  body = 'Hi {{customerName}},\n\nA quick heads-up: quotation {{reference}} for {{total}} expires on {{validUntil}}.\n\nAccept it online here:\n\n{{quoteUrl}}\n\nIf the timing does not work, reply and we will extend it.\n\nBest regards,\n{{businessName}}';
598
787
  }
599
- const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
788
+ return this.emailCustomer(q, cfg, subject, body, { to: overrideTo, test: !!overrideTo, attachPdf: cfg.attachPdf });
789
+ }
790
+ /**
791
+ * One e-mail to the customer (or `to`, for a test), as the member of staff
792
+ * who prepared the quote: their name fronts the From header and replies go
793
+ * straight to them. Templates use {{placeholders}} (see emailVars).
794
+ */
795
+ async emailCustomer(q, cfg, subjectTpl, bodyTpl, opts = {}) {
796
+ var _a, _b;
797
+ const smtp = this.smtpSettings();
798
+ if (!smtp)
799
+ return { ok: false, reason: 'SMTP is not configured (SMTP_SERVER / SMTP_USER env or plugin options)' };
800
+ const url = this.quoteUrl(q.token);
801
+ const vars = this.emailVars(q, cfg, opts.vars);
802
+ const render = (t) => String(t || '').replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
600
803
  try {
601
804
  const transporter = this.transporter(smtp);
602
- // Send as the member of staff who prepared the quote: their name
603
- // fronts the From header and replies go straight to them.
604
805
  const senderName = q.preparedByName
605
806
  ? (cfg.businessName ? `${q.preparedByName} — ${cfg.businessName}` : q.preparedByName)
606
807
  : (cfg.businessName || '');
607
808
  await this.sendWithDeadline(transporter, {
608
- from: senderName ? `"${senderName.replace(/"/g, "'")}" <${smtp.from}>` : smtp.from,
609
- to: overrideTo || q.customerEmail,
809
+ from: senderName ? `"${senderName.replace(/["\r\n]/g, "'")}" <${smtp.from}>` : smtp.from,
810
+ to: opts.to || q.customerEmail,
610
811
  replyTo: q.preparedByEmail || cfg.replyTo || undefined,
611
- subject: (overrideTo ? '[TEST] ' : '') + render(subject),
612
- text: (0, templates_1.renderQuoteEmailText)(render(body)),
613
- html: (0, templates_1.renderQuoteEmailHtml)(render(body), q, cfg, url),
812
+ subject: ((opts.test ? '[TEST] ' : '') + render(subjectTpl)).replace(/[\r\n]+/g, ' '),
813
+ text: (0, templates_1.renderQuoteEmailText)(render(bodyTpl)),
814
+ html: (0, templates_1.renderQuoteEmailHtml)(render(bodyTpl), q, cfg, ((_a = opts.button) === null || _a === void 0 ? void 0 : _a.url) || url, (_b = opts.button) === null || _b === void 0 ? void 0 : _b.label),
815
+ attachments: opts.attachPdf
816
+ ? [{ filename: `Quotation-${String(q.reference).replace(/[^A-Za-z0-9._-]/g, '_')}.pdf`, content: (0, pdf_1.renderQuotePdf)(q, cfg, url), contentType: 'application/pdf' }]
817
+ : undefined,
614
818
  });
615
819
  return { ok: true };
616
820
  }
@@ -618,6 +822,21 @@ let QuotationService = class QuotationService {
618
822
  return { ok: false, reason: e.message };
619
823
  }
620
824
  }
825
+ /** A plain-text note to members of staff (approvals). Never throws. */
826
+ async mailStaff(to, subject, text) {
827
+ const smtp = this.smtpSettings();
828
+ const list = [...new Set(to.map(t => String(t || '').trim().toLowerCase()).filter(t => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)))].slice(0, 50);
829
+ if (!smtp || !list.length)
830
+ return false;
831
+ try {
832
+ await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to: list.join(', '), subject: subject.replace(/[\r\n]+/g, ' '), text });
833
+ return true;
834
+ }
835
+ catch (e) {
836
+ core_1.Logger.warn(`staff e-mail failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
837
+ return false;
838
+ }
839
+ }
621
840
  /** Fire-and-forget notification to the merchant on accept/decline. */
622
841
  async notifyMerchant(q, cfg, subject, text) {
623
842
  const smtp = this.smtpSettings();
@@ -698,7 +917,7 @@ let QuotationService = class QuotationService {
698
917
  * "Quotation …" surcharge, so the draft order total equals the quote
699
918
  * total exactly. The admin completes the draft as usual.
700
919
  */
701
- async convertToDraftOrder(ctx, quoteId, actor) {
920
+ async convertToDraftOrder(ctx, quoteId, actor, opts = {}) {
702
921
  var _a;
703
922
  const q = await this.getQuote(quoteId);
704
923
  if (!q)
@@ -718,7 +937,8 @@ let QuotationService = class QuotationService {
718
937
  req: ctx.req, apiType: ctx.apiType, channel, session: ctx.session, languageCode: ctx.languageCode,
719
938
  currencyCode: currency, isAuthorized: ctx.isAuthorized, authorizedAsOwnerOnly: ctx.authorizedAsOwnerOnly,
720
939
  });
721
- if (!octx.userHasPermissions([core_1.Permission.CreateOrder])) {
940
+ // The pay link on acceptance converts on the customer's click: no administrator, no permission to check.
941
+ if (!opts.system && !octx.userHasPermissions([core_1.Permission.CreateOrder])) {
722
942
  return { ok: false, reason: `You need the CreateOrder permission on channel ${channel.code} to convert this quote` };
723
943
  }
724
944
  // Claim the quote before creating anything, so a double click or a retried request cannot make two draft orders.
@@ -738,23 +958,17 @@ let QuotationService = class QuotationService {
738
958
  }
739
959
  }
740
960
  const fresh = await this.orderService.findOne(octx, draft.id);
741
- // The surcharge carries the gross difference (so the total is exact) and the VAT difference as its
742
- // tax rate (so the order's net/VAT split matches the quote instead of booking the gap as tax-free).
743
- const deltaGross = Number(q.totalPence) - Number((fresh === null || fresh === void 0 ? void 0 : fresh.totalWithTax) || 0);
744
- const deltaNet = (Number(q.subTotalPence) - Number(q.discountPence)) - Number((fresh === null || fresh === void 0 ? void 0 : fresh.total) || 0);
745
- const deltaTax = deltaGross - deltaNet;
746
- const rate = deltaNet !== 0 ? (deltaTax / deltaNet) * 100 : NaN;
747
- const taxLines = deltaTax !== 0 && Number.isFinite(rate) && rate > 0 && rate <= 100
748
- ? [{ description: `VAT ${Number(q.vatRate)}%`, taxRate: rate }] : [];
749
- if (deltaGross !== 0 || q.lines.some((l) => !l.productVariantId)) {
961
+ const surcharge = (0, quote_total_1.quoteSurchargeFor)(q, { net: Number((fresh === null || fresh === void 0 ? void 0 : fresh.total) || 0), gross: Number((fresh === null || fresh === void 0 ? void 0 : fresh.totalWithTax) || 0) });
962
+ if (surcharge) {
750
963
  await this.orderService.addSurchargeToOrder(octx, draft.id, {
751
964
  description: `Quotation ${q.reference} pricing`,
752
- listPrice: deltaGross,
965
+ listPrice: surcharge.listPrice,
753
966
  listPriceIncludesTax: true,
754
967
  sku: q.reference,
755
- taxLines,
968
+ taxLines: surcharge.taxLines,
756
969
  });
757
970
  }
971
+ await this.attachCustomer(octx, Number(draft.id), q);
758
972
  await this.db.query(`UPDATE quotation SET convertedOrderId=?, updatedAt=NOW() WHERE id = ?`, [draft.id, quoteId]);
759
973
  await this.logEvent(quoteId, 'converted', `Draft order ${(fresh === null || fresh === void 0 ? void 0 : fresh.code) || draft.id} created`, actor);
760
974
  return { ok: true, orderId: Number(draft.id), orderCode: fresh === null || fresh === void 0 ? void 0 : fresh.code };
@@ -765,6 +979,91 @@ let QuotationService = class QuotationService {
765
979
  return { ok: false, reason: e.message };
766
980
  }
767
981
  }
982
+ /**
983
+ * Put the quote's customer on the draft order: the linked account, else an
984
+ * existing customer with the quote's e-mail address (never renamed), else
985
+ * a new guest customer. Best effort: a failure leaves the draft without a
986
+ * customer, as before, for the admin to set.
987
+ */
988
+ async attachCustomer(ctx, orderId, q) {
989
+ try {
990
+ const repo = this.connection.getRepository(ctx, core_1.Customer);
991
+ let customer = null;
992
+ if (q.customerId)
993
+ customer = await repo.findOne({ where: { id: q.customerId } });
994
+ const email = String(q.customerEmail || '').trim().toLowerCase();
995
+ if (!customer && email)
996
+ customer = await repo.findOne({ where: { emailAddress: email } });
997
+ if (!customer && email && this.customerService) {
998
+ const parts = String(q.customerName || '').trim().split(/\s+/);
999
+ const created = await this.customerService.createOrUpdate(ctx, {
1000
+ emailAddress: email, firstName: parts[0] || '', lastName: parts.slice(1).join(' ') || '',
1001
+ phoneNumber: q.customerPhone || undefined,
1002
+ }, false);
1003
+ if (created && !created.errorCode)
1004
+ customer = created;
1005
+ }
1006
+ if ((customer === null || customer === void 0 ? void 0 : customer.id) && !customer.deletedAt)
1007
+ await this.orderService.addCustomerToOrder(ctx, orderId, customer);
1008
+ }
1009
+ catch (e) {
1010
+ core_1.Logger.warn(`could not put the customer of quote ${q.reference} on its draft order: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
1011
+ }
1012
+ }
1013
+ /**
1014
+ * Keep a converted draft order at the quoted price when it leaves Draft. Vendure 3.8+
1015
+ * recalculates every order on the transition to ArrangingPayment, so catalogue price or
1016
+ * promotion changes made after the conversion would otherwise move the total away from the
1017
+ * price the customer accepted. Called by the plugin's order process inside the transition's
1018
+ * transaction; re-balances the quote surcharge on the in-memory order, which Vendure saves.
1019
+ * Leaves orders alone that are not from a quote, or whose lines an admin has since changed.
1020
+ * Shipping is not part of a quote and is left as it is.
1021
+ */
1022
+ async keepQuotedTotal(ctx, order) {
1023
+ if (!(order === null || order === void 0 ? void 0 : order.id))
1024
+ return 'not-a-quote';
1025
+ const [row] = await this.db.query(`SELECT id FROM quotation WHERE convertedOrderId = ? ORDER BY id DESC LIMIT 1`, [order.id]).catch(() => []);
1026
+ if (!(row === null || row === void 0 ? void 0 : row.id))
1027
+ return 'not-a-quote';
1028
+ const q = await this.getQuote(Number(row.id));
1029
+ if (!q)
1030
+ return 'not-a-quote';
1031
+ const wantGross = Number(q.totalPence);
1032
+ const wantNet = Number(q.subTotalPence) - Number(q.discountPence);
1033
+ if (Number(order.subTotalWithTax) === wantGross && Number(order.subTotal) === wantNet)
1034
+ return 'unchanged';
1035
+ if (!(0, quote_total_1.orderLinesMatchQuote)(order.lines || [], q.lines || [])) {
1036
+ core_1.Logger.info(`Order ${order.code} (quote ${q.reference}) no longer holds the quoted lines; its total follows the catalogue`, loggerCtx);
1037
+ return 'lines-changed';
1038
+ }
1039
+ const existing = (order.surcharges || []).find(s => s.sku === q.reference);
1040
+ const base = {
1041
+ net: Number(order.subTotal) - (existing ? existing.price : 0),
1042
+ gross: Number(order.subTotalWithTax) - (existing ? existing.priceWithTax : 0),
1043
+ };
1044
+ const next = (0, quote_total_1.quoteSurchargeFor)(q, base);
1045
+ const repo = this.connection.getRepository(ctx, core_1.Surcharge);
1046
+ if (existing) {
1047
+ await repo.remove(existing);
1048
+ order.surcharges = order.surcharges.filter(s => s !== existing);
1049
+ }
1050
+ if (next) {
1051
+ const created = await repo.save(new core_1.Surcharge({
1052
+ description: `Quotation ${q.reference} pricing`,
1053
+ listPrice: next.listPrice,
1054
+ listPriceIncludesTax: true,
1055
+ sku: q.reference,
1056
+ taxLines: next.taxLines,
1057
+ order,
1058
+ }));
1059
+ order.surcharges = [...(order.surcharges || []), created];
1060
+ }
1061
+ await this.orderService.applyPriceAdjustments(ctx, order);
1062
+ const before = base.gross + (existing ? existing.priceWithTax : 0);
1063
+ await this.logEvent(Number(q.id), 'repriced', `Order ${order.code}: catalogue total moved at checkout (${before} -> ${base.gross + (next ? next.listPrice : 0)} incl. surcharge); quote surcharge re-balanced to keep ${wantGross}`, 'system');
1064
+ core_1.Logger.info(`Order ${order.code} kept at the quoted total of quote ${q.reference}`, loggerCtx);
1065
+ return 'repriced';
1066
+ }
768
1067
  /** Sliding-window throttle for the public request endpoint. */
769
1068
  requestAllowed(clientKey) {
770
1069
  const now = Date.now();
@@ -848,7 +1147,17 @@ let QuotationService = class QuotationService {
848
1147
  * gets an acknowledgement carrying the reference. Never throws for
849
1148
  * bots: honeypot hits look successful and persist nothing.
850
1149
  */
851
- async createRequest(channelId, input, clientKey) {
1150
+ /** Requests from this address in the last hour, from the database (shared by every process, kept across restarts). */
1151
+ async recentRequestsFor(email) {
1152
+ const [row] = await this.db.query(`SELECT COUNT(*) AS n FROM quotation WHERE customerEmail = ? AND requestedAt IS NOT NULL AND requestedAt > DATE_SUB(NOW(), INTERVAL 1 HOUR)`, [email]).catch(() => [{ n: 0 }]);
1153
+ return Number((row === null || row === void 0 ? void 0 : row.n) || 0);
1154
+ }
1155
+ /**
1156
+ * `customerId` is the signed-in storefront customer, when the request
1157
+ * carried a shop session: the request is then linked to that account (and
1158
+ * shows under "My quotes"). Guest requests are never linked by e-mail.
1159
+ */
1160
+ async createRequest(channelId, input, clientKey, customerId = null) {
852
1161
  const cfg = await this.getConfig(channelId);
853
1162
  if (!cfg.acceptRequests)
854
1163
  return { ok: false, reason: 'Quote requests are not accepted on this channel' };
@@ -859,6 +1168,8 @@ let QuotationService = class QuotationService {
859
1168
  return { ok: false, reason: 'Please enter a valid email address' };
860
1169
  if (!this.requestAllowed(clientKey || email) || !this.requestAllowed(`email:${email}`))
861
1170
  return { ok: false, reason: 'Too many requests — please try again later' };
1171
+ if (await this.recentRequestsFor(email) >= REQUESTS_PER_EMAIL_PER_HOUR)
1172
+ return { ok: false, reason: 'Too many requests — please try again later' };
862
1173
  const message = String(input.message || '').trim().slice(0, 2000);
863
1174
  const source = String(input.source || 'storefront').trim().slice(0, 64);
864
1175
  const rawLines = Array.isArray(input.lines) ? input.lines.slice(0, 50) : [];
@@ -868,9 +1179,8 @@ let QuotationService = class QuotationService {
868
1179
  return { ok: false, reason: 'Tell us what you need a quote for' };
869
1180
  lines = [{ productVariantId: null, sku: '', description: `Customer enquiry — see request: ${message.slice(0, 120)}`, quantity: 1, unitPricePence: 0 }];
870
1181
  }
871
- const [existingCustomer] = await this.db.query(`SELECT id FROM customer WHERE \`emailAddress\` = ? AND \`deletedAt\` IS NULL LIMIT 1`, [email]).catch(() => []);
872
1182
  const q = await this.createQuote(channelId, {
873
- customerId: (existingCustomer === null || existingCustomer === void 0 ? void 0 : existingCustomer.id) ? Number(existingCustomer.id) : null,
1183
+ customerId: customerId || null,
874
1184
  customerName: String(input.name || '').trim().slice(0, 190) || email,
875
1185
  customerEmail: email,
876
1186
  customerCompany: String(input.company || '').trim().slice(0, 190),
@@ -1007,14 +1317,99 @@ let QuotationService = class QuotationService {
1007
1317
  WHERE \`deletedAt\` IS NULL AND (\`firstName\` LIKE ? OR \`lastName\` LIKE ? OR \`emailAddress\` LIKE ?)
1008
1318
  ORDER BY \`lastName\` ASC LIMIT 20`, [like, like, like]).catch(() => []);
1009
1319
  }
1010
- /** Send the real quote email to a staff address instead of the customer. */
1320
+ /** Send the real quote email to a staff address instead of the customer. The quote does not change. Free. */
1011
1321
  async testSend(quoteId, to) {
1012
1322
  const q = await this.getQuote(quoteId);
1013
1323
  if (!q)
1014
1324
  return { ok: false, reason: 'Quote not found' };
1325
+ const held = await this.preSend(q, 'test', to);
1326
+ if (held)
1327
+ return { ok: false, reason: held };
1015
1328
  const cfg = await this.getConfig(q.channelId);
1016
1329
  return this.deliverEmail(q, cfg, 'quote', to);
1017
1330
  }
1331
+ /**
1332
+ * The customer quote page exactly as the customer would see it, for staff:
1333
+ * it does not count as an opening and its accept form is switched off.
1334
+ */
1335
+ async staffPreviewHtml(quoteId) {
1336
+ const q = await this.getQuote(quoteId);
1337
+ if (!q)
1338
+ return null;
1339
+ const cfg = await this.getConfig(q.channelId);
1340
+ if (q.status === 'draft' || q.status === 'requested') {
1341
+ // Not sent yet: show the dates the customer will get when it goes out now.
1342
+ q.validUntil = new Date(Date.now() + this.validityDaysOf(q, cfg) * DAY_MS);
1343
+ q.status = 'sent';
1344
+ }
1345
+ return (0, templates_1.renderQuotePage)(q, cfg, { preview: true, extra: await this.pageExtras(q) });
1346
+ }
1347
+ async pageExtras(q) {
1348
+ const base = this.pageExtrasProvider ? await this.pageExtrasProvider(q).catch(() => ({})) : {};
1349
+ return { ...base, pdfUrl: q.token ? `${this.quoteUrl(q.token)}/pdf` : undefined };
1350
+ }
1351
+ /**
1352
+ * The quote as a PDF (free). The "accept online" line is printed while the
1353
+ * customer can still respond. Drafts render with the dates they would get
1354
+ * if sent now.
1355
+ */
1356
+ async quotePdf(quoteId, token) {
1357
+ const q = quoteId ? await this.getQuote(quoteId) : token ? await this.getQuoteByToken(token) : null;
1358
+ if (!q)
1359
+ return null;
1360
+ const cfg = await this.getConfig(q.channelId);
1361
+ if (q.status === 'draft' || q.status === 'requested')
1362
+ q.validUntil = new Date(Date.now() + this.validityDaysOf(q, cfg) * DAY_MS);
1363
+ const extras = this.pageExtrasProvider ? await this.pageExtrasProvider(q).catch(() => ({})) : {};
1364
+ const acceptUrl = OPEN_STATUSES.includes(q.status) ? this.quoteUrl(q.token) : null;
1365
+ return {
1366
+ filename: `Quotation-${String(q.reference).replace(/[^A-Za-z0-9._-]/g, '_')}.pdf`,
1367
+ pdf: (0, pdf_1.renderQuotePdf)(q, cfg, acceptUrl, { depositText: extras === null || extras === void 0 ? void 0 : extras.depositText }),
1368
+ };
1369
+ }
1370
+ // ── "My quotes" for signed-in customers ─────────────────────────────
1371
+ /** The customer id behind a storefront session's user, or null. */
1372
+ async customerIdForUser(userId) {
1373
+ if (!userId)
1374
+ return null;
1375
+ const [row] = await this.db.query(`SELECT id FROM customer WHERE \`userId\` = ? AND \`deletedAt\` IS NULL LIMIT 1`, [Number(userId)]).catch(() => []);
1376
+ return (row === null || row === void 0 ? void 0 : row.id) ? Number(row.id) : null;
1377
+ }
1378
+ /**
1379
+ * Quotes linked to one customer account (customerId), never matched by
1380
+ * e-mail: each row carries the quote's secret link. Drafts are the store's
1381
+ * work in progress and never shown; requests show as "awaiting price".
1382
+ */
1383
+ async quotesForCustomer(customerId, channelId) {
1384
+ if (!customerId)
1385
+ return [];
1386
+ const params = [customerId];
1387
+ let chan = '';
1388
+ if (channelId) {
1389
+ chan = ' AND channelId = ?';
1390
+ params.push(channelId);
1391
+ }
1392
+ const rows = await this.db.query(`SELECT id, channelId, reference, status, token, currency, totalPence, validUntil, sentAt, createdAt, respondedAt, paidAt, payUrl, convertedOrderId
1393
+ FROM quotation WHERE customerId = ?${chan} AND status <> 'draft' ORDER BY id DESC LIMIT 100`, params);
1394
+ const out = [];
1395
+ for (const r of rows) {
1396
+ const extras = this.pageExtrasProvider ? await this.pageExtrasProvider(r).catch(() => ({})) : {};
1397
+ const visible = r.status !== 'requested';
1398
+ out.push({
1399
+ id: Number(r.id), reference: r.reference, status: r.status,
1400
+ statusLabel: r.paidAt || (extras === null || extras === void 0 ? void 0 : extras.paid) ? 'Paid' : r.status === 'requested' ? 'Awaiting price' : r.status,
1401
+ date: r.sentAt || r.createdAt,
1402
+ validUntil: r.status === 'requested' ? null : r.validUntil,
1403
+ totalPence: r.status === 'requested' ? null : Number(r.totalPence), currency: r.currency,
1404
+ url: visible ? this.quoteUrl(r.token) : null,
1405
+ pdfUrl: visible ? `${this.quoteUrl(r.token)}/pdf` : null,
1406
+ payUrl: !r.paidAt && (extras === null || extras === void 0 ? void 0 : extras.payUrl) ? extras.payUrl : null,
1407
+ paid: !!(r.paidAt || (extras === null || extras === void 0 ? void 0 : extras.paid)),
1408
+ canRespond: OPEN_STATUSES.includes(r.status),
1409
+ });
1410
+ }
1411
+ return out;
1412
+ }
1018
1413
  /** The customer email, rendered for preview. */
1019
1414
  async previewEmail(quoteId) {
1020
1415
  const q = await this.getQuote(quoteId);
@@ -1060,41 +1455,57 @@ let QuotationService = class QuotationService {
1060
1455
  return this.getQuote(quoteId);
1061
1456
  }
1062
1457
  // ── Crons ───────────────────────────────────────────────────────────
1063
- async expireOverdue() {
1064
- const res = await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW()
1065
- WHERE status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW()`, undefined, { needAffected: true });
1066
- const n = Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0);
1458
+ /** Expire quotes whose validity has passed (free), one by one so each gets its trail entry and event. */
1459
+ async expireOverdue(batch = 500) {
1460
+ const rows = await this.db.query(`SELECT id FROM quotation WHERE status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW() ORDER BY id LIMIT ${Math.max(1, Math.min(5000, batch))}`);
1461
+ let n = 0;
1462
+ for (const r of rows) {
1463
+ const res = await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW() WHERE id = ? AND status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW()`, [r.id], { needAffected: true });
1464
+ if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
1465
+ n++;
1466
+ await this.logEvent(Number(r.id), 'expired', 'Validity ended');
1467
+ }
1468
+ }
1067
1469
  if (n)
1068
1470
  core_1.Logger.info(`marked ${n} quote(s) expired`, loggerCtx);
1069
1471
  return n;
1070
1472
  }
1473
+ /** Claim one reminder (its column still empty), send it, and release the claim when the e-mail fails. */
1474
+ async remind(r, cfg, column, kind) {
1475
+ const claim = await this.db.query(`UPDATE quotation SET ${column} = NOW() WHERE id = ? AND ${column} IS NULL`, [r.id], { needAffected: true });
1476
+ if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) !== 1)
1477
+ return false;
1478
+ const q = await this.getQuote(Number(r.id));
1479
+ const res = q ? await this.deliverEmail(q, cfg, kind) : { ok: false };
1480
+ if (res.ok)
1481
+ return true;
1482
+ await this.db.query(`UPDATE quotation SET ${column} = NULL WHERE id = ?`, [r.id]).catch(() => undefined);
1483
+ return false;
1484
+ }
1485
+ /** The hourly reminders (free): one chaser for an unopened quote, one expires-soon reminder. */
1071
1486
  async runChasers() {
1072
1487
  const out = { chasers: 0, expiryReminders: 0 };
1073
1488
  const configs = await this.getAllConfigs();
1074
1489
  for (const cfg of configs) {
1075
1490
  if (cfg.chaserEnabled) {
1076
- const rows = await this.db.query(`SELECT * FROM quotation
1077
- WHERE channelId = ? AND status = 'sent' AND chaserSentAt IS NULL
1491
+ const rows = await this.db.query(`SELECT id FROM quotation
1492
+ WHERE channelId = ? AND status = 'sent' AND viewedAt IS NULL AND chaserSentAt IS NULL
1078
1493
  AND sentAt IS NOT NULL AND sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
1079
- AND (validUntil IS NULL OR validUntil > NOW()) LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
1494
+ AND (validUntil IS NULL OR validUntil > NOW()) ORDER BY id LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
1080
1495
  for (const r of rows) {
1081
- const res = await this.deliverEmail(r, cfg, 'chaser');
1082
- if (res.ok) {
1083
- await this.db.query(`UPDATE quotation SET chaserSentAt=NOW() WHERE id = ?`, [r.id]);
1496
+ if (await this.remind(r, cfg, 'chaserSentAt', 'chaser')) {
1084
1497
  await this.logEvent(r.id, 'chaser_sent', 'Unopened-quote reminder emailed');
1085
1498
  out.chasers++;
1086
1499
  }
1087
1500
  }
1088
1501
  }
1089
1502
  if (cfg.expiryReminderDays > 0) {
1090
- const rows = await this.db.query(`SELECT * FROM quotation
1503
+ const rows = await this.db.query(`SELECT id FROM quotation
1091
1504
  WHERE channelId = ? AND status IN ('sent','viewed') AND expiryReminderSentAt IS NULL
1092
1505
  AND validUntil IS NOT NULL AND validUntil > NOW()
1093
- AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
1506
+ AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) ORDER BY validUntil LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
1094
1507
  for (const r of rows) {
1095
- const res = await this.deliverEmail(r, cfg, 'expiry');
1096
- if (res.ok) {
1097
- await this.db.query(`UPDATE quotation SET expiryReminderSentAt=NOW() WHERE id = ?`, [r.id]);
1508
+ if (await this.remind(r, cfg, 'expiryReminderSentAt', 'expiry')) {
1098
1509
  await this.logEvent(r.id, 'expiry_reminder_sent', 'Expiry reminder emailed');
1099
1510
  out.expiryReminders++;
1100
1511
  }
@@ -1104,49 +1515,150 @@ let QuotationService = class QuotationService {
1104
1515
  return out;
1105
1516
  }
1106
1517
  // ── Stats ───────────────────────────────────────────────────────────
1518
+ /** Per-currency sums: money is never added across currencies. */
1519
+ static byCurrency(rows, value = 'value') {
1520
+ const out = {};
1521
+ for (const r of rows) {
1522
+ const v = Number((r === null || r === void 0 ? void 0 : r[value]) || 0);
1523
+ if (!v)
1524
+ continue;
1525
+ const c = String(r.currency || 'GBP').toUpperCase();
1526
+ out[c] = (out[c] || 0) + v;
1527
+ }
1528
+ return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b)));
1529
+ }
1530
+ /**
1531
+ * KPIs for the Quotes tab. Money is reported per currency (B5): every
1532
+ * value is a `{ GBP: …, EUR: … }` map in minor units.
1533
+ */
1107
1534
  async stats(channelId) {
1108
1535
  const where = channelId ? 'WHERE channelId = ?' : '';
1109
1536
  const params = channelId ? [channelId] : [];
1110
- const byStatus = await this.db.query(`SELECT status, COUNT(*) AS n, SUM(totalPence) AS value FROM quotation ${where} GROUP BY status`, params);
1537
+ const rows = await this.db.query(`SELECT status, currency, COUNT(*) AS n, SUM(totalPence) AS value FROM quotation ${where} GROUP BY status, currency`, params);
1538
+ const statusMap = new Map();
1539
+ for (const r of rows) {
1540
+ const e = statusMap.get(r.status) || { status: r.status, n: 0, rows: [] };
1541
+ e.n += Number(r.n || 0);
1542
+ e.rows.push(r);
1543
+ statusMap.set(r.status, e);
1544
+ }
1545
+ const byStatus = [...statusMap.values()].map(e => ({ status: e.status, n: e.n, valueByCurrency: QuotationService_1.byCurrency(e.rows) }));
1546
+ const pipeline = QuotationService_1.byCurrency(rows.filter((r) => r.status === 'sent' || r.status === 'viewed'));
1111
1547
  const [resp] = await this.db.query(`SELECT COUNT(*) AS n, AVG(TIMESTAMPDIFF(SECOND, sentAt, respondedAt)) AS avgSeconds
1112
1548
  FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt IS NOT NULL AND sentAt IS NOT NULL`, params);
1113
1549
  const [last30] = await this.db.query(`SELECT COUNT(*) AS sent, SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won
1114
1550
  FROM quotation ${where ? where + ' AND' : 'WHERE'} sentAt > DATE_SUB(NOW(), INTERVAL 30 DAY)`, params);
1115
1551
  const sent30 = Number((last30 === null || last30 === void 0 ? void 0 : last30.sent) || 0);
1116
1552
  const [req] = await this.db.query(`SELECT COUNT(*) AS n, MIN(requestedAt) AS oldest FROM quotation ${where ? where + ' AND' : 'WHERE'} status = 'requested'`, params);
1117
- // Value won: quotes the customer accepted in the last 30 days (by response date, not send date).
1118
- const [won30] = await this.db.query(`SELECT SUM(CASE WHEN status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS wonPence,
1119
- SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS accepted
1120
- FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt > DATE_SUB(NOW(), INTERVAL 30 DAY)`, params).catch(() => [null]);
1553
+ // Value won: quotes the customer accepted in the last 30 days (by response date, not send date), per currency.
1554
+ const won30 = await this.db.query(`SELECT currency, COUNT(*) AS n, SUM(totalPence) AS value
1555
+ FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt > DATE_SUB(NOW(), INTERVAL 30 DAY) AND status IN ('accepted','converted')
1556
+ GROUP BY currency`, params).catch(() => []);
1121
1557
  return {
1122
1558
  byStatus,
1559
+ pipelineByCurrency: pipeline,
1123
1560
  requests: { open: Number((req === null || req === void 0 ? void 0 : req.n) || 0), oldestAt: (req === null || req === void 0 ? void 0 : req.oldest) || null },
1124
1561
  avgResponseHours: (resp === null || resp === void 0 ? void 0 : resp.avgSeconds) ? Math.round(Number(resp.avgSeconds) / 360) / 10 : null,
1125
1562
  last30: {
1126
1563
  sent: sent30, won: Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0),
1127
1564
  winRate: sent30 ? Math.round((Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0) / sent30) * 100) : null,
1128
- valueWonPence: Number((won30 === null || won30 === void 0 ? void 0 : won30.wonPence) || 0), accepted: Number((won30 === null || won30 === void 0 ? void 0 : won30.accepted) || 0),
1565
+ valueWonByCurrency: QuotationService_1.byCurrency(won30),
1566
+ accepted: won30.reduce((a, r) => a + Number(r.n || 0), 0),
1129
1567
  },
1130
1568
  };
1131
1569
  }
1570
+ /**
1571
+ * The last 12 calendar months (free): per month, quotes created, sent and
1572
+ * accepted, the win rate on quotes sent that month, and the value won per
1573
+ * currency (by the month the customer accepted).
1574
+ */
1575
+ async monthlyReport(channelId, now = new Date()) {
1576
+ const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 11, 1));
1577
+ const chan = channelId ? ' AND channelId = ?' : '';
1578
+ const p = (extra = []) => [start, ...(channelId ? [channelId] : []), ...extra];
1579
+ const created = await this.db.query(`SELECT EXTRACT(YEAR FROM createdAt) AS y, EXTRACT(MONTH FROM createdAt) AS m, COUNT(*) AS n
1580
+ FROM quotation WHERE createdAt >= ?${chan} GROUP BY EXTRACT(YEAR FROM createdAt), EXTRACT(MONTH FROM createdAt)`, p());
1581
+ const sent = await this.db.query(`SELECT EXTRACT(YEAR FROM sentAt) AS y, EXTRACT(MONTH FROM sentAt) AS m, COUNT(*) AS n,
1582
+ SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won
1583
+ FROM quotation WHERE sentAt >= ?${chan} GROUP BY EXTRACT(YEAR FROM sentAt), EXTRACT(MONTH FROM sentAt)`, p());
1584
+ const won = await this.db.query(`SELECT EXTRACT(YEAR FROM respondedAt) AS y, EXTRACT(MONTH FROM respondedAt) AS m, currency, COUNT(*) AS n, SUM(totalPence) AS value
1585
+ FROM quotation WHERE respondedAt >= ?${chan} AND status IN ('accepted','converted')
1586
+ GROUP BY EXTRACT(YEAR FROM respondedAt), EXTRACT(MONTH FROM respondedAt), currency`, p());
1587
+ const key = (y, m) => `${Number(y)}-${String(Number(m)).padStart(2, '0')}`;
1588
+ const months = [];
1589
+ for (let i = 0; i < 12; i++) {
1590
+ const d = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + i, 1));
1591
+ months.push({ month: key(d.getUTCFullYear(), d.getUTCMonth() + 1), created: 0, sent: 0, sentWon: 0, accepted: 0, winRatePct: null, wonByCurrency: {} });
1592
+ }
1593
+ const at = (y, m) => months.find(x => x.month === key(y, m));
1594
+ for (const r of created) {
1595
+ const e = at(r.y, r.m);
1596
+ if (e)
1597
+ e.created += Number(r.n || 0);
1598
+ }
1599
+ for (const r of sent) {
1600
+ const e = at(r.y, r.m);
1601
+ if (e) {
1602
+ e.sent += Number(r.n || 0);
1603
+ e.sentWon += Number(r.won || 0);
1604
+ }
1605
+ }
1606
+ const currencies = new Set();
1607
+ for (const r of won) {
1608
+ const e = at(r.y, r.m);
1609
+ if (!e)
1610
+ continue;
1611
+ e.accepted += Number(r.n || 0);
1612
+ const c = String(r.currency || 'GBP').toUpperCase();
1613
+ if (Number(r.value || 0)) {
1614
+ e.wonByCurrency[c] = (e.wonByCurrency[c] || 0) + Number(r.value);
1615
+ currencies.add(c);
1616
+ }
1617
+ }
1618
+ for (const e of months)
1619
+ e.winRatePct = e.sent ? Math.round((e.sentWon / e.sent) * 1000) / 10 : null;
1620
+ return { months, currencies: [...currencies].sort() };
1621
+ }
1132
1622
  // ── Usage figures (evaluation + heartbeat stats, weekly report, widget) ──
1623
+ /** The store's main currency: the default channel's, else the first channel config's, else GBP. */
1624
+ async primaryCurrency() {
1625
+ try {
1626
+ const ch = await this.channelService.getDefaultChannel();
1627
+ if (ch === null || ch === void 0 ? void 0 : ch.defaultCurrencyCode)
1628
+ return String(ch.defaultCurrencyCode).toUpperCase();
1629
+ const cfg = await this.getConfig(Number(ch === null || ch === void 0 ? void 0 : ch.id) || 1);
1630
+ return String(cfg.currency || 'GBP').toUpperCase();
1631
+ }
1632
+ catch {
1633
+ return 'GBP';
1634
+ }
1635
+ }
1636
+ /** Value won (accepted, by response date) in `[from, to)`, per currency. */
1637
+ async periodWonByCurrency(from, to) {
1638
+ const rows = await this.db.query(`SELECT currency, SUM(totalPence) AS value FROM quotation
1639
+ WHERE respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') GROUP BY currency`, [from, to]).catch(() => []);
1640
+ return QuotationService_1.byCurrency(rows);
1641
+ }
1133
1642
  /**
1134
1643
  * Counts for one period `[from, to)`:
1135
1644
  * - quotesCreated / quotesSent / requestsReceived — by their own timestamp
1136
- * - quotesAccepted + valueWonPence — accepted (or since converted) with the
1137
- * customer's response inside the period
1645
+ * - quotesAccepted — accepted (or since converted) with the customer's
1646
+ * response inside the period
1647
+ * - valueWonPence — the value of those, in the store's main currency only
1648
+ * (never summed across currencies; see periodWonByCurrency for the rest)
1138
1649
  * - winRatePct — of the quotes *sent* in the period, the share accepted so far
1139
1650
  * Every event also bumps `updatedAt`, so the scan is bounded by it.
1140
1651
  */
1141
1652
  async periodStats(from, to) {
1142
1653
  try {
1654
+ const currency = await this.primaryCurrency();
1143
1655
  const [row] = await this.db.query(`SELECT SUM(CASE WHEN createdAt >= ? AND createdAt < ? THEN 1 ELSE 0 END) AS created,
1144
1656
  SUM(CASE WHEN sentAt >= ? AND sentAt < ? THEN 1 ELSE 0 END) AS sent,
1145
1657
  SUM(CASE WHEN sentAt >= ? AND sentAt < ? AND status IN ('accepted','converted') THEN 1 ELSE 0 END) AS sentWon,
1146
1658
  SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') THEN 1 ELSE 0 END) AS accepted,
1147
- SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS wonPence,
1659
+ SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') AND currency = ? THEN totalPence ELSE 0 END) AS wonPence,
1148
1660
  SUM(CASE WHEN requestedAt >= ? AND requestedAt < ? THEN 1 ELSE 0 END) AS requests
1149
- FROM quotation WHERE updatedAt >= ?`, [from, to, from, to, from, to, from, to, from, to, from, to, from]);
1661
+ FROM quotation WHERE updatedAt >= ?`, [from, to, from, to, from, to, from, to, from, to, currency, from, to, from]);
1150
1662
  const n = (v) => Number(v || 0);
1151
1663
  const sent = n(row === null || row === void 0 ? void 0 : row.sent);
1152
1664
  return {
@@ -1169,27 +1681,48 @@ let QuotationService = class QuotationService {
1169
1681
  const now = new Date();
1170
1682
  return this.periodStats(new Date(now.getTime() - 30 * DAY_MS), now);
1171
1683
  }
1172
- toDigestStats(current, previous) {
1173
- return exports.STAT_DEFS.map(d => ({
1174
- key: d.key, label: d.label, format: d.format,
1175
- value: Number(current[d.key] || 0),
1176
- previous: previous ? Number(previous[d.key] || 0) : null,
1177
- }));
1684
+ /**
1685
+ * The figures as report lines. Value won is one line per currency when
1686
+ * quotes were won in more than one currency, or in a currency other than
1687
+ * GBP (the report's money format): never one sum across currencies.
1688
+ */
1689
+ toDigestStats(current, previous, wonByCurrency) {
1690
+ const out = [];
1691
+ for (const d of exports.STAT_DEFS) {
1692
+ const won = wonByCurrency ? Object.entries(wonByCurrency).filter(([, v]) => v) : [];
1693
+ if (d.key === 'valueWonPence' && (won.length > 1 || (won.length === 1 && won[0][0] !== 'GBP'))) {
1694
+ out.push({
1695
+ key: d.key, label: d.label, format: 'text',
1696
+ value: won.length, previous: null,
1697
+ text: won.map(([c, v]) => (0, pricing_1.formatMoney)(v, c)).join(' + '),
1698
+ });
1699
+ continue;
1700
+ }
1701
+ out.push({
1702
+ key: d.key, label: d.label, format: d.format,
1703
+ value: d.key === 'valueWonPence' && wonByCurrency ? Number(wonByCurrency.GBP || 0) : Number(current[d.key] || 0),
1704
+ previous: previous ? Number(previous[d.key] || 0) : null,
1705
+ });
1706
+ }
1707
+ return out;
1178
1708
  }
1179
1709
  /** Top three non-zero 30-day figures, formatted for the admin banner. */
1180
1710
  async recentStats() {
1181
- const stats = this.toDigestStats(await this.evalStats());
1711
+ const now = new Date();
1712
+ const from = new Date(now.getTime() - 30 * DAY_MS);
1713
+ const stats = this.toDigestStats(await this.evalStats(), undefined, await this.periodWonByCurrency(from, now));
1182
1714
  return stats.filter(s => s.value > 0).slice(0, 3).map(s => ({ label: s.label, value: (0, vendure_licence_sdk_1.formatStat)(s) }));
1183
1715
  }
1184
- /** Three headline figures for the dashboard widget (last 7 days). */
1716
+ /** Three headline figures for the dashboard widget (last 7 days); value won per currency. */
1185
1717
  async widgetStats() {
1186
1718
  const now = new Date();
1187
- const s = await this.periodStats(new Date(now.getTime() - 7 * DAY_MS), now);
1188
- const stat = (key, label) => {
1189
- const def = exports.STAT_DEFS.find(d => d.key === key);
1190
- return { label, value: (0, vendure_licence_sdk_1.formatStat)({ key, label, format: def.format, value: Number(s[key] || 0) }) };
1719
+ const from = new Date(now.getTime() - 7 * DAY_MS);
1720
+ const stats = this.toDigestStats(await this.periodStats(from, now), undefined, await this.periodWonByCurrency(from, now));
1721
+ const pick = (key, label) => {
1722
+ const st = stats.find(x => x.key === key);
1723
+ return { label, value: (0, vendure_licence_sdk_1.formatStat)(st) };
1191
1724
  };
1192
- return [stat('quotesSent', 'Quotes sent'), stat('quotesAccepted', 'Accepted'), stat('valueWonPence', 'Value won')];
1725
+ return [pick('quotesSent', 'Quotes sent'), pick('quotesAccepted', 'Accepted'), pick('valueWonPence', 'Value won')];
1193
1726
  }
1194
1727
  // ── Set-up checklist ────────────────────────────────────────────────
1195
1728
  adminUrl() {
@@ -1253,10 +1786,11 @@ let QuotationService = class QuotationService {
1253
1786
  async collectDigest(from, to) {
1254
1787
  var _a, _b, _c;
1255
1788
  const hooks = this.digestHooks;
1256
- const [current, previous, setup] = await Promise.all([
1789
+ const [current, previous, setup, won] = await Promise.all([
1257
1790
  this.periodStats(from, to),
1258
1791
  this.periodStats(new Date(from.getTime() - (to.getTime() - from.getTime())), from),
1259
1792
  this.setupChecklist(),
1793
+ this.periodWonByCurrency(from, to),
1260
1794
  ]);
1261
1795
  const adminUrl = this.adminUrl();
1262
1796
  const tips = setup.items.filter(i => !i.done).slice(0, 3)
@@ -1272,7 +1806,7 @@ let QuotationService = class QuotationService {
1272
1806
  }
1273
1807
  const status = (_a = hooks === null || hooks === void 0 ? void 0 : hooks.licence()) !== null && _a !== void 0 ? _a : null;
1274
1808
  return {
1275
- stats: this.toDigestStats(current, previous),
1809
+ stats: this.toDigestStats(current, previous, won),
1276
1810
  tips,
1277
1811
  tier: (_b = hooks === null || hooks === void 0 ? void 0 : hooks.tier()) !== null && _b !== void 0 ? _b : 'free',
1278
1812
  licence: (0, vendure_licence_sdk_1.describeLicence)(status),
@@ -1320,10 +1854,13 @@ let QuotationService = class QuotationService {
1320
1854
  }
1321
1855
  };
1322
1856
  exports.QuotationService = QuotationService;
1323
- exports.QuotationService = QuotationService = __decorate([
1857
+ exports.QuotationService = QuotationService = QuotationService_1 = __decorate([
1324
1858
  (0, common_1.Injectable)(),
1325
1859
  __metadata("design:paramtypes", [core_1.TransactionalConnection,
1326
1860
  core_1.ChannelService,
1327
- core_1.OrderService])
1861
+ core_1.OrderService,
1862
+ core_1.EventBus,
1863
+ core_1.RequestContextService,
1864
+ core_1.CustomerService])
1328
1865
  ], QuotationService);
1329
1866
  //# sourceMappingURL=quotation.service.js.map