@huloglobal/vendure-plugin-quotations 0.8.6 → 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 (72) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +103 -9
  3. package/dist/approvals.d.ts +46 -0
  4. package/dist/approvals.d.ts.map +1 -0
  5. package/dist/approvals.js +136 -0
  6. package/dist/approvals.js.map +1 -0
  7. package/dist/crons.d.ts +5 -3
  8. package/dist/crons.d.ts.map +1 -1
  9. package/dist/crons.js +16 -10
  10. package/dist/crons.js.map +1 -1
  11. package/dist/csv.d.ts +7 -0
  12. package/dist/csv.d.ts.map +1 -0
  13. package/dist/csv.js +32 -0
  14. package/dist/csv.js.map +1 -0
  15. package/dist/deposits.d.ts +25 -0
  16. package/dist/deposits.d.ts.map +1 -0
  17. package/dist/deposits.js +59 -0
  18. package/dist/deposits.js.map +1 -0
  19. package/dist/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 +9 -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 +617 -23
  54. package/dist/quotation.controller.js.map +1 -1
  55. package/dist/quotation.service.d.ts +178 -11
  56. package/dist/quotation.service.d.ts.map +1 -1
  57. package/dist/quotation.service.js +577 -88
  58. package/dist/quotation.service.js.map +1 -1
  59. package/dist/templates.d.ts +13 -1
  60. package/dist/templates.d.ts.map +1 -1
  61. package/dist/templates.js +17 -6
  62. package/dist/templates.js.map +1 -1
  63. package/dist/types.d.ts +12 -0
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +2 -0
  66. package/dist/types.js.map +1 -1
  67. package/dist/webhooks.d.ts +61 -0
  68. package/dist/webhooks.d.ts.map +1 -0
  69. package/dist/webhooks.js +308 -0
  70. package/dist/webhooks.js.map +1 -0
  71. package/package.json +3 -2
  72. 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");
@@ -53,17 +54,29 @@ const pricing_1 = require("./pricing");
53
54
  const quote_version_1 = require("./quote-version");
54
55
  const quote_total_1 = require("./quote-total");
55
56
  const templates_1 = require("./templates");
57
+ const events_1 = require("./events");
58
+ const pdf_1 = require("./pdf");
56
59
  const types_1 = require("./types");
57
60
  const loggerCtx = 'Quotations';
58
61
  const PLUGIN_ID = 'vendure-plugin-quotations';
59
62
  const PLUGIN_NAME = 'Quotations';
60
63
  const DAY_MS = 86400000;
61
- /** 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
+ */
62
71
  exports.PREMIUM_FEATURES = [
63
- 'Send quotes and chasers by email',
64
- 'Convert accepted quotes to orders',
65
- 'Storefront quote requests with acknowledgement',
66
- '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',
67
80
  ];
68
81
  /** The usage figures this plugin reports (evaluation + heartbeat stats,
69
82
  * weekly report, dashboard widget). Keys are stable; every value is a
@@ -76,6 +89,22 @@ exports.STAT_DEFS = [
76
89
  { key: 'requestsReceived', label: 'quote requests received from your storefront', format: 'count' },
77
90
  { key: 'winRatePct', label: 'win rate on quotes sent', format: 'percent' },
78
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
+ }
79
108
  /** statuses a customer can still respond from */
80
109
  const OPEN_STATUSES = ['sent', 'viewed'];
81
110
  /** statuses an admin can still edit */
@@ -84,16 +113,18 @@ const EDITABLE_STATUSES = ['requested', 'draft', 'sent', 'viewed'];
84
113
  const REQUESTS_PER_HOUR = 10;
85
114
  /** request acknowledgements: at most one per recipient per day, and this many per hour per process */
86
115
  const ACKS_PER_HOUR = 30;
87
- 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 {
88
119
  initDigest(hooks) {
89
120
  this.digestHooks = hooks;
90
121
  if (!this.weeklyDigest) {
91
- this.weeklyDigest = new vendure_licence_sdk_1.WeeklyDigest({
122
+ this.weeklyDigest = new PremiumDigest({
92
123
  pluginId: PLUGIN_ID, pluginName: PLUGIN_NAME, prefs: this.prefs,
93
124
  collect: (from, to) => this.collectDigest(from, to),
94
125
  send: (to, mail) => this.sendDigest(to, mail),
95
126
  defaultRecipient: () => this.digestDefaultRecipient(),
96
- });
127
+ }, () => this.isPremium());
97
128
  }
98
129
  return this.weeklyDigest;
99
130
  }
@@ -104,10 +135,13 @@ let QuotationService = class QuotationService {
104
135
  }
105
136
  return this.purchaseClaim;
106
137
  }
107
- constructor(connection, channelService, orderService) {
138
+ constructor(connection, channelService, orderService, eventBus, requestContextService, customerService) {
108
139
  this.connection = connection;
109
140
  this.channelService = channelService;
110
141
  this.orderService = orderService;
142
+ this.eventBus = eventBus;
143
+ this.requestContextService = requestContextService;
144
+ this.customerService = customerService;
111
145
  this.options = {};
112
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));
113
147
  /** Small per-plugin settings (weekly report recipient, dismissed set-up items, trial lead). */
@@ -118,6 +152,10 @@ let QuotationService = class QuotationService {
118
152
  // Buy-from-admin auto-install (hooks are supplied by the controller so
119
153
  // this file never imports the plugin class).
120
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 = [];
121
159
  this.mailer = null;
122
160
  // ── Customer-initiated quote requests ───────────────────────────────
123
161
  this.requestHits = new Map();
@@ -126,10 +164,42 @@ let QuotationService = class QuotationService {
126
164
  // ── Product search for the editor ───────────────────────────────────
127
165
  /** Per channel+language: which catalogue the search reads (see catalogue-search.ts); re-checked every minute. */
128
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;
129
169
  }
130
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; }
131
173
  setOptions(o) { this.options = o || {}; }
132
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
+ }
133
203
  async onModuleInit() {
134
204
  await this.ensureSchema();
135
205
  await this.licenceStore.ensureTable();
@@ -217,6 +287,17 @@ let QuotationService = class QuotationService {
217
287
  await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestMessage VARCHAR(2000) NOT NULL DEFAULT ''`);
218
288
  await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestSource VARCHAR(64) NOT NULL DEFAULT ''`);
219
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`);
220
301
  await this.db.query(`
221
302
  CREATE TABLE IF NOT EXISTS quotation_line (
222
303
  id INT AUTO_INCREMENT PRIMARY KEY,
@@ -244,7 +325,7 @@ let QuotationService = class QuotationService {
244
325
  }
245
326
  // ── Config ──────────────────────────────────────────────────────────
246
327
  rowToConfig(row, code) {
247
- 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;
248
329
  return {
249
330
  channelId: row.channelId,
250
331
  channelCode: code,
@@ -271,6 +352,8 @@ let QuotationService = class QuotationService {
271
352
  footerNote: (_v = row.footerNote) !== null && _v !== void 0 ? _v : '',
272
353
  acceptRequests: !!Number((_w = row.acceptRequests) !== null && _w !== void 0 ? _w : 1),
273
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),
274
357
  };
275
358
  }
276
359
  async getConfig(channelId) {
@@ -290,8 +373,8 @@ let QuotationService = class QuotationService {
290
373
  await this.db.query(`INSERT INTO quotation_config (channelId, numberPrefix, nextNumber, defaultValidityDays, defaultVatRate, defaultTerms,
291
374
  businessName, replyTo, notifyEmail, currency, logoUrl, accentColor, chaserEnabled, chaserAfterDays,
292
375
  expiryReminderDays, emailSubject, emailBody, notifyOnView, websiteUrl, phone, addressText, footerNote,
293
- acceptRequests, requestAckBody)
294
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
376
+ acceptRequests, requestAckBody, payLinkOnAccept, attachPdf)
377
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
295
378
  ON DUPLICATE KEY UPDATE numberPrefix=VALUES(numberPrefix), defaultValidityDays=VALUES(defaultValidityDays),
296
379
  defaultVatRate=VALUES(defaultVatRate), defaultTerms=VALUES(defaultTerms), businessName=VALUES(businessName),
297
380
  replyTo=VALUES(replyTo), notifyEmail=VALUES(notifyEmail), currency=VALUES(currency), logoUrl=VALUES(logoUrl),
@@ -299,14 +382,16 @@ let QuotationService = class QuotationService {
299
382
  expiryReminderDays=VALUES(expiryReminderDays), emailSubject=VALUES(emailSubject), emailBody=VALUES(emailBody),
300
383
  notifyOnView=VALUES(notifyOnView), websiteUrl=VALUES(websiteUrl), phone=VALUES(phone),
301
384
  addressText=VALUES(addressText), footerNote=VALUES(footerNote),
302
- 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),
303
387
  Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, String(c.defaultTerms || '').slice(0, 4000),
304
388
  c.businessName || '', c.replyTo || '', c.notifyEmail || '', (c.currency || 'GBP').toUpperCase().slice(0, 3),
305
389
  c.logoUrl || '', c.accentColor || '#1d4ed8', c.chaserEnabled ? 1 : 0, Math.max(1, Number(c.chaserAfterDays) || 3),
306
390
  Math.max(0, Number(c.expiryReminderDays) || 0), String(c.emailSubject || '').slice(0, 300), String(c.emailBody || '').slice(0, 4000), c.notifyOnView ? 1 : 0,
307
391
  String(c.websiteUrl || '').slice(0, 300), String(c.phone || '').slice(0, 64),
308
392
  String(c.addressText || '').slice(0, 500), String(c.footerNote || '').slice(0, 500),
309
- 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'] });
310
395
  }
311
396
  // ── Reference numbering ─────────────────────────────────────────────
312
397
  /** Atomically claims the next quote number for a channel. */
@@ -354,19 +439,21 @@ let QuotationService = class QuotationService {
354
439
  const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
355
440
  const reference = await this.nextReference(channelId);
356
441
  const token = crypto.randomBytes(24).toString('hex');
357
- 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)));
358
444
  const res = await this.db.query(`INSERT INTO quotation (channelId, reference, status, token, customerId, customerName, customerEmail,
359
445
  customerCompany, customerPhone, notes, internalNotes, terms, vatRate, discountType, discountValue,
360
446
  currency, validUntil, subTotalPence, discountPence, vatPence, totalPence, createdBy,
361
- preparedByName, preparedByEmail, createdAt, updatedAt)
362
- 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,
363
449
  String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
364
450
  String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
365
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),
366
452
  vatRate, discountType, discountValue, (input.currency || cfg.currency || 'GBP').toUpperCase().slice(0, 3),
367
453
  validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
368
454
  actor.slice(0, 190),
369
- 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 });
370
457
  const quoteId = Number(res.insertId);
371
458
  await this.replaceLines(quoteId, lines);
372
459
  await this.logEvent(quoteId, 'created', `Quote ${reference} created`, actor);
@@ -404,6 +491,7 @@ let QuotationService = class QuotationService {
404
491
  await this.db.query(`UPDATE quotation SET customerId=?, customerName=?, customerEmail=?, customerCompany=?, customerPhone=?,
405
492
  notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
406
493
  validUntil=${touchValidity ? 'DATE_ADD(NOW(), INTERVAL ? DAY)' : 'validUntil'},
494
+ validityDays=${touchValidity ? '?' : 'validityDays'},
407
495
  subTotalPence=?, discountPence=?, vatPence=?, totalPence=?,
408
496
  preparedByName=?, preparedByEmail=?, updatedAt=NOW()
409
497
  WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
@@ -411,7 +499,7 @@ let QuotationService = class QuotationService {
411
499
  String(input.customerPhone || '').slice(0, 64), String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000),
412
500
  String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms) !== null && _c !== void 0 ? _c : '').slice(0, 20000), vatRate, discountType, discountValue,
413
501
  (input.currency || existing.currency).toUpperCase().slice(0, 3),
414
- ...(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)))] : []),
415
503
  totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
416
504
  String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
417
505
  quoteId]);
@@ -425,8 +513,12 @@ let QuotationService = class QuotationService {
425
513
  return;
426
514
  if (q.status !== 'draft' && q.status !== 'requested')
427
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`);
428
517
  await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
429
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
+ }
430
522
  await this.db.query(`DELETE FROM quotation WHERE id = ?`, [quoteId]);
431
523
  }
432
524
  async cancelQuote(quoteId, actor) {
@@ -448,7 +540,7 @@ let QuotationService = class QuotationService {
448
540
  customerCompany: q.customerCompany, customerPhone: q.customerPhone,
449
541
  notes: q.notes, internalNotes: q.internalNotes, terms: q.terms,
450
542
  vatRate: q.vatRate, discountType: q.discountType, discountValue: q.discountValue,
451
- currency: q.currency, validityDays: 30,
543
+ currency: q.currency, validityDays: this.validityDaysOf(q),
452
544
  lines: q.lines.map((l) => ({
453
545
  productVariantId: l.productVariantId, sku: l.sku, description: l.description,
454
546
  quantity: l.quantity, unitPricePence: l.unitPricePence, lineDiscountPercent: l.lineDiscountPercent,
@@ -507,8 +599,40 @@ let QuotationService = class QuotationService {
507
599
  FROM quotation ${whereSql} ORDER BY id DESC LIMIT ${perPage} OFFSET ${(page - 1) * perPage}`, params);
508
600
  return { items, totalItems: Number((count === null || count === void 0 ? void 0 : count.n) || 0), page, perPage };
509
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
+ */
510
607
  async logEvent(quoteId, type, detail, actor = '') {
511
- 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
+ }
512
636
  }
513
637
  // ── Sending ─────────────────────────────────────────────────────────
514
638
  quoteUrl(token) {
@@ -556,37 +680,101 @@ let QuotationService = class QuotationService {
556
680
  new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`SMTP send timed out after ${ms / 1000}s`)), ms); }),
557
681
  ]).finally(() => clearTimeout(timer));
558
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
+ */
559
701
  async sendQuote(quoteId, actor) {
560
702
  const q = await this.getQuote(quoteId);
561
703
  if (!q)
562
704
  return { ok: false, reason: 'Quote not found' };
563
- if (!q.customerEmail)
564
- 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' };
565
707
  if (['accepted', 'declined', 'converted', 'cancelled', 'expired'].includes(q.status)) {
566
708
  return { ok: false, reason: `A ${q.status} quote cannot be sent` };
567
709
  }
710
+ const held = await this.preSend(q, 'send', actor);
711
+ if (held)
712
+ return { ok: false, reason: held };
568
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
+ }
569
722
  const res = await this.deliverEmail(q, cfg, 'quote');
570
723
  if (!res.ok)
571
724
  return res;
572
- await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), updatedAt=NOW() WHERE id = ?`, [quoteId]);
573
- 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);
574
734
  return { ok: true };
575
735
  }
576
- async deliverEmail(q, cfg, kind, overrideTo) {
577
- const smtp = this.smtpSettings();
578
- if (!smtp)
579
- return { ok: false, reason: 'SMTP is not configured (SMTP_SERVER / SMTP_USER env or plugin options)' };
580
- const url = this.quoteUrl(q.token);
581
- 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 {
582
767
  reference: q.reference,
583
768
  customerName: q.customerName || 'there',
584
769
  businessName: cfg.businessName || 'our team',
585
770
  staffName: q.preparedByName || cfg.businessName || 'our team',
586
771
  total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
587
772
  validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
588
- quoteUrl: url,
773
+ quoteUrl: this.quoteUrl(q.token),
774
+ ...extra,
589
775
  };
776
+ }
777
+ async deliverEmail(q, cfg, kind, overrideTo) {
590
778
  let subject = cfg.emailSubject || types_1.DEFAULT_CONFIG.emailSubject;
591
779
  let body = cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody;
592
780
  if (kind === 'chaser') {
@@ -597,21 +785,36 @@ let QuotationService = class QuotationService {
597
785
  subject = `Your quotation {{reference}} expires soon`;
598
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}}';
599
787
  }
600
- 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 : ''; });
601
803
  try {
602
804
  const transporter = this.transporter(smtp);
603
- // Send as the member of staff who prepared the quote: their name
604
- // fronts the From header and replies go straight to them.
605
805
  const senderName = q.preparedByName
606
806
  ? (cfg.businessName ? `${q.preparedByName} — ${cfg.businessName}` : q.preparedByName)
607
807
  : (cfg.businessName || '');
608
808
  await this.sendWithDeadline(transporter, {
609
- from: senderName ? `"${senderName.replace(/"/g, "'")}" <${smtp.from}>` : smtp.from,
610
- to: overrideTo || q.customerEmail,
809
+ from: senderName ? `"${senderName.replace(/["\r\n]/g, "'")}" <${smtp.from}>` : smtp.from,
810
+ to: opts.to || q.customerEmail,
611
811
  replyTo: q.preparedByEmail || cfg.replyTo || undefined,
612
- subject: (overrideTo ? '[TEST] ' : '') + render(subject),
613
- text: (0, templates_1.renderQuoteEmailText)(render(body)),
614
- 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,
615
818
  });
616
819
  return { ok: true };
617
820
  }
@@ -619,6 +822,21 @@ let QuotationService = class QuotationService {
619
822
  return { ok: false, reason: e.message };
620
823
  }
621
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
+ }
622
840
  /** Fire-and-forget notification to the merchant on accept/decline. */
623
841
  async notifyMerchant(q, cfg, subject, text) {
624
842
  const smtp = this.smtpSettings();
@@ -699,7 +917,7 @@ let QuotationService = class QuotationService {
699
917
  * "Quotation …" surcharge, so the draft order total equals the quote
700
918
  * total exactly. The admin completes the draft as usual.
701
919
  */
702
- async convertToDraftOrder(ctx, quoteId, actor) {
920
+ async convertToDraftOrder(ctx, quoteId, actor, opts = {}) {
703
921
  var _a;
704
922
  const q = await this.getQuote(quoteId);
705
923
  if (!q)
@@ -719,7 +937,8 @@ let QuotationService = class QuotationService {
719
937
  req: ctx.req, apiType: ctx.apiType, channel, session: ctx.session, languageCode: ctx.languageCode,
720
938
  currencyCode: currency, isAuthorized: ctx.isAuthorized, authorizedAsOwnerOnly: ctx.authorizedAsOwnerOnly,
721
939
  });
722
- 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])) {
723
942
  return { ok: false, reason: `You need the CreateOrder permission on channel ${channel.code} to convert this quote` };
724
943
  }
725
944
  // Claim the quote before creating anything, so a double click or a retried request cannot make two draft orders.
@@ -749,6 +968,7 @@ let QuotationService = class QuotationService {
749
968
  taxLines: surcharge.taxLines,
750
969
  });
751
970
  }
971
+ await this.attachCustomer(octx, Number(draft.id), q);
752
972
  await this.db.query(`UPDATE quotation SET convertedOrderId=?, updatedAt=NOW() WHERE id = ?`, [draft.id, quoteId]);
753
973
  await this.logEvent(quoteId, 'converted', `Draft order ${(fresh === null || fresh === void 0 ? void 0 : fresh.code) || draft.id} created`, actor);
754
974
  return { ok: true, orderId: Number(draft.id), orderCode: fresh === null || fresh === void 0 ? void 0 : fresh.code };
@@ -759,6 +979,37 @@ let QuotationService = class QuotationService {
759
979
  return { ok: false, reason: e.message };
760
980
  }
761
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
+ }
762
1013
  /**
763
1014
  * Keep a converted draft order at the quoted price when it leaves Draft. Vendure 3.8+
764
1015
  * recalculates every order on the transition to ArrangingPayment, so catalogue price or
@@ -896,7 +1147,17 @@ let QuotationService = class QuotationService {
896
1147
  * gets an acknowledgement carrying the reference. Never throws for
897
1148
  * bots: honeypot hits look successful and persist nothing.
898
1149
  */
899
- 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) {
900
1161
  const cfg = await this.getConfig(channelId);
901
1162
  if (!cfg.acceptRequests)
902
1163
  return { ok: false, reason: 'Quote requests are not accepted on this channel' };
@@ -907,6 +1168,8 @@ let QuotationService = class QuotationService {
907
1168
  return { ok: false, reason: 'Please enter a valid email address' };
908
1169
  if (!this.requestAllowed(clientKey || email) || !this.requestAllowed(`email:${email}`))
909
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' };
910
1173
  const message = String(input.message || '').trim().slice(0, 2000);
911
1174
  const source = String(input.source || 'storefront').trim().slice(0, 64);
912
1175
  const rawLines = Array.isArray(input.lines) ? input.lines.slice(0, 50) : [];
@@ -916,9 +1179,8 @@ let QuotationService = class QuotationService {
916
1179
  return { ok: false, reason: 'Tell us what you need a quote for' };
917
1180
  lines = [{ productVariantId: null, sku: '', description: `Customer enquiry — see request: ${message.slice(0, 120)}`, quantity: 1, unitPricePence: 0 }];
918
1181
  }
919
- const [existingCustomer] = await this.db.query(`SELECT id FROM customer WHERE \`emailAddress\` = ? AND \`deletedAt\` IS NULL LIMIT 1`, [email]).catch(() => []);
920
1182
  const q = await this.createQuote(channelId, {
921
- customerId: (existingCustomer === null || existingCustomer === void 0 ? void 0 : existingCustomer.id) ? Number(existingCustomer.id) : null,
1183
+ customerId: customerId || null,
922
1184
  customerName: String(input.name || '').trim().slice(0, 190) || email,
923
1185
  customerEmail: email,
924
1186
  customerCompany: String(input.company || '').trim().slice(0, 190),
@@ -1055,14 +1317,99 @@ let QuotationService = class QuotationService {
1055
1317
  WHERE \`deletedAt\` IS NULL AND (\`firstName\` LIKE ? OR \`lastName\` LIKE ? OR \`emailAddress\` LIKE ?)
1056
1318
  ORDER BY \`lastName\` ASC LIMIT 20`, [like, like, like]).catch(() => []);
1057
1319
  }
1058
- /** 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. */
1059
1321
  async testSend(quoteId, to) {
1060
1322
  const q = await this.getQuote(quoteId);
1061
1323
  if (!q)
1062
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 };
1063
1328
  const cfg = await this.getConfig(q.channelId);
1064
1329
  return this.deliverEmail(q, cfg, 'quote', to);
1065
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
+ }
1066
1413
  /** The customer email, rendered for preview. */
1067
1414
  async previewEmail(quoteId) {
1068
1415
  const q = await this.getQuote(quoteId);
@@ -1108,41 +1455,57 @@ let QuotationService = class QuotationService {
1108
1455
  return this.getQuote(quoteId);
1109
1456
  }
1110
1457
  // ── Crons ───────────────────────────────────────────────────────────
1111
- async expireOverdue() {
1112
- const res = await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW()
1113
- WHERE status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW()`, undefined, { needAffected: true });
1114
- 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
+ }
1115
1469
  if (n)
1116
1470
  core_1.Logger.info(`marked ${n} quote(s) expired`, loggerCtx);
1117
1471
  return n;
1118
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. */
1119
1486
  async runChasers() {
1120
1487
  const out = { chasers: 0, expiryReminders: 0 };
1121
1488
  const configs = await this.getAllConfigs();
1122
1489
  for (const cfg of configs) {
1123
1490
  if (cfg.chaserEnabled) {
1124
- const rows = await this.db.query(`SELECT * FROM quotation
1125
- 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
1126
1493
  AND sentAt IS NOT NULL AND sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
1127
- 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]);
1128
1495
  for (const r of rows) {
1129
- const res = await this.deliverEmail(r, cfg, 'chaser');
1130
- if (res.ok) {
1131
- await this.db.query(`UPDATE quotation SET chaserSentAt=NOW() WHERE id = ?`, [r.id]);
1496
+ if (await this.remind(r, cfg, 'chaserSentAt', 'chaser')) {
1132
1497
  await this.logEvent(r.id, 'chaser_sent', 'Unopened-quote reminder emailed');
1133
1498
  out.chasers++;
1134
1499
  }
1135
1500
  }
1136
1501
  }
1137
1502
  if (cfg.expiryReminderDays > 0) {
1138
- const rows = await this.db.query(`SELECT * FROM quotation
1503
+ const rows = await this.db.query(`SELECT id FROM quotation
1139
1504
  WHERE channelId = ? AND status IN ('sent','viewed') AND expiryReminderSentAt IS NULL
1140
1505
  AND validUntil IS NOT NULL AND validUntil > NOW()
1141
- 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]);
1142
1507
  for (const r of rows) {
1143
- const res = await this.deliverEmail(r, cfg, 'expiry');
1144
- if (res.ok) {
1145
- await this.db.query(`UPDATE quotation SET expiryReminderSentAt=NOW() WHERE id = ?`, [r.id]);
1508
+ if (await this.remind(r, cfg, 'expiryReminderSentAt', 'expiry')) {
1146
1509
  await this.logEvent(r.id, 'expiry_reminder_sent', 'Expiry reminder emailed');
1147
1510
  out.expiryReminders++;
1148
1511
  }
@@ -1152,49 +1515,150 @@ let QuotationService = class QuotationService {
1152
1515
  return out;
1153
1516
  }
1154
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
+ */
1155
1534
  async stats(channelId) {
1156
1535
  const where = channelId ? 'WHERE channelId = ?' : '';
1157
1536
  const params = channelId ? [channelId] : [];
1158
- 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'));
1159
1547
  const [resp] = await this.db.query(`SELECT COUNT(*) AS n, AVG(TIMESTAMPDIFF(SECOND, sentAt, respondedAt)) AS avgSeconds
1160
1548
  FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt IS NOT NULL AND sentAt IS NOT NULL`, params);
1161
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
1162
1550
  FROM quotation ${where ? where + ' AND' : 'WHERE'} sentAt > DATE_SUB(NOW(), INTERVAL 30 DAY)`, params);
1163
1551
  const sent30 = Number((last30 === null || last30 === void 0 ? void 0 : last30.sent) || 0);
1164
1552
  const [req] = await this.db.query(`SELECT COUNT(*) AS n, MIN(requestedAt) AS oldest FROM quotation ${where ? where + ' AND' : 'WHERE'} status = 'requested'`, params);
1165
- // Value won: quotes the customer accepted in the last 30 days (by response date, not send date).
1166
- const [won30] = await this.db.query(`SELECT SUM(CASE WHEN status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS wonPence,
1167
- SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS accepted
1168
- 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(() => []);
1169
1557
  return {
1170
1558
  byStatus,
1559
+ pipelineByCurrency: pipeline,
1171
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 },
1172
1561
  avgResponseHours: (resp === null || resp === void 0 ? void 0 : resp.avgSeconds) ? Math.round(Number(resp.avgSeconds) / 360) / 10 : null,
1173
1562
  last30: {
1174
1563
  sent: sent30, won: Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0),
1175
1564
  winRate: sent30 ? Math.round((Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0) / sent30) * 100) : null,
1176
- 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),
1177
1567
  },
1178
1568
  };
1179
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
+ }
1180
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
+ }
1181
1642
  /**
1182
1643
  * Counts for one period `[from, to)`:
1183
1644
  * - quotesCreated / quotesSent / requestsReceived — by their own timestamp
1184
- * - quotesAccepted + valueWonPence — accepted (or since converted) with the
1185
- * 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)
1186
1649
  * - winRatePct — of the quotes *sent* in the period, the share accepted so far
1187
1650
  * Every event also bumps `updatedAt`, so the scan is bounded by it.
1188
1651
  */
1189
1652
  async periodStats(from, to) {
1190
1653
  try {
1654
+ const currency = await this.primaryCurrency();
1191
1655
  const [row] = await this.db.query(`SELECT SUM(CASE WHEN createdAt >= ? AND createdAt < ? THEN 1 ELSE 0 END) AS created,
1192
1656
  SUM(CASE WHEN sentAt >= ? AND sentAt < ? THEN 1 ELSE 0 END) AS sent,
1193
1657
  SUM(CASE WHEN sentAt >= ? AND sentAt < ? AND status IN ('accepted','converted') THEN 1 ELSE 0 END) AS sentWon,
1194
1658
  SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') THEN 1 ELSE 0 END) AS accepted,
1195
- 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,
1196
1660
  SUM(CASE WHEN requestedAt >= ? AND requestedAt < ? THEN 1 ELSE 0 END) AS requests
1197
- 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]);
1198
1662
  const n = (v) => Number(v || 0);
1199
1663
  const sent = n(row === null || row === void 0 ? void 0 : row.sent);
1200
1664
  return {
@@ -1217,27 +1681,48 @@ let QuotationService = class QuotationService {
1217
1681
  const now = new Date();
1218
1682
  return this.periodStats(new Date(now.getTime() - 30 * DAY_MS), now);
1219
1683
  }
1220
- toDigestStats(current, previous) {
1221
- return exports.STAT_DEFS.map(d => ({
1222
- key: d.key, label: d.label, format: d.format,
1223
- value: Number(current[d.key] || 0),
1224
- previous: previous ? Number(previous[d.key] || 0) : null,
1225
- }));
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;
1226
1708
  }
1227
1709
  /** Top three non-zero 30-day figures, formatted for the admin banner. */
1228
1710
  async recentStats() {
1229
- 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));
1230
1714
  return stats.filter(s => s.value > 0).slice(0, 3).map(s => ({ label: s.label, value: (0, vendure_licence_sdk_1.formatStat)(s) }));
1231
1715
  }
1232
- /** 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. */
1233
1717
  async widgetStats() {
1234
1718
  const now = new Date();
1235
- const s = await this.periodStats(new Date(now.getTime() - 7 * DAY_MS), now);
1236
- const stat = (key, label) => {
1237
- const def = exports.STAT_DEFS.find(d => d.key === key);
1238
- 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) };
1239
1724
  };
1240
- 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')];
1241
1726
  }
1242
1727
  // ── Set-up checklist ────────────────────────────────────────────────
1243
1728
  adminUrl() {
@@ -1301,10 +1786,11 @@ let QuotationService = class QuotationService {
1301
1786
  async collectDigest(from, to) {
1302
1787
  var _a, _b, _c;
1303
1788
  const hooks = this.digestHooks;
1304
- const [current, previous, setup] = await Promise.all([
1789
+ const [current, previous, setup, won] = await Promise.all([
1305
1790
  this.periodStats(from, to),
1306
1791
  this.periodStats(new Date(from.getTime() - (to.getTime() - from.getTime())), from),
1307
1792
  this.setupChecklist(),
1793
+ this.periodWonByCurrency(from, to),
1308
1794
  ]);
1309
1795
  const adminUrl = this.adminUrl();
1310
1796
  const tips = setup.items.filter(i => !i.done).slice(0, 3)
@@ -1320,7 +1806,7 @@ let QuotationService = class QuotationService {
1320
1806
  }
1321
1807
  const status = (_a = hooks === null || hooks === void 0 ? void 0 : hooks.licence()) !== null && _a !== void 0 ? _a : null;
1322
1808
  return {
1323
- stats: this.toDigestStats(current, previous),
1809
+ stats: this.toDigestStats(current, previous, won),
1324
1810
  tips,
1325
1811
  tier: (_b = hooks === null || hooks === void 0 ? void 0 : hooks.tier()) !== null && _b !== void 0 ? _b : 'free',
1326
1812
  licence: (0, vendure_licence_sdk_1.describeLicence)(status),
@@ -1368,10 +1854,13 @@ let QuotationService = class QuotationService {
1368
1854
  }
1369
1855
  };
1370
1856
  exports.QuotationService = QuotationService;
1371
- exports.QuotationService = QuotationService = __decorate([
1857
+ exports.QuotationService = QuotationService = QuotationService_1 = __decorate([
1372
1858
  (0, common_1.Injectable)(),
1373
1859
  __metadata("design:paramtypes", [core_1.TransactionalConnection,
1374
1860
  core_1.ChannelService,
1375
- core_1.OrderService])
1861
+ core_1.OrderService,
1862
+ core_1.EventBus,
1863
+ core_1.RequestContextService,
1864
+ core_1.CustomerService])
1376
1865
  ], QuotationService);
1377
1866
  //# sourceMappingURL=quotation.service.js.map