@huloglobal/vendure-plugin-quotations 0.9.0 → 0.10.1

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 (59) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +57 -0
  3. package/dist/client-ip.d.ts +59 -0
  4. package/dist/client-ip.d.ts.map +1 -0
  5. package/dist/client-ip.js +145 -0
  6. package/dist/client-ip.js.map +1 -0
  7. package/dist/email-layout.d.ts +104 -0
  8. package/dist/email-layout.d.ts.map +1 -0
  9. package/dist/email-layout.js +250 -0
  10. package/dist/email-layout.js.map +1 -0
  11. package/dist/emails.d.ts +57 -0
  12. package/dist/emails.d.ts.map +1 -0
  13. package/dist/emails.js +124 -0
  14. package/dist/emails.js.map +1 -0
  15. package/dist/index.d.ts +3 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +8 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/payment.service.d.ts.map +1 -1
  20. package/dist/payment.service.js +4 -1
  21. package/dist/payment.service.js.map +1 -1
  22. package/dist/pdf.d.ts.map +1 -1
  23. package/dist/pdf.js +18 -9
  24. package/dist/pdf.js.map +1 -1
  25. package/dist/plugin.d.ts.map +1 -1
  26. package/dist/plugin.js +3 -0
  27. package/dist/plugin.js.map +1 -1
  28. package/dist/pricing.d.ts +58 -3
  29. package/dist/pricing.d.ts.map +1 -1
  30. package/dist/pricing.js +90 -9
  31. package/dist/pricing.js.map +1 -1
  32. package/dist/pro.service.d.ts.map +1 -1
  33. package/dist/pro.service.js +25 -5
  34. package/dist/pro.service.js.map +1 -1
  35. package/dist/quotation.controller.d.ts +5 -3
  36. package/dist/quotation.controller.d.ts.map +1 -1
  37. package/dist/quotation.controller.js +30 -27
  38. package/dist/quotation.controller.js.map +1 -1
  39. package/dist/quotation.service.d.ts +31 -5
  40. package/dist/quotation.service.d.ts.map +1 -1
  41. package/dist/quotation.service.js +161 -38
  42. package/dist/quotation.service.js.map +1 -1
  43. package/dist/quote-version.d.ts.map +1 -1
  44. package/dist/quote-version.js +3 -0
  45. package/dist/quote-version.js.map +1 -1
  46. package/dist/rate-limit.d.ts +15 -0
  47. package/dist/rate-limit.d.ts.map +1 -0
  48. package/dist/rate-limit.js +35 -0
  49. package/dist/rate-limit.js.map +1 -0
  50. package/dist/templates.d.ts +0 -3
  51. package/dist/templates.d.ts.map +1 -1
  52. package/dist/templates.js +2 -39
  53. package/dist/templates.js.map +1 -1
  54. package/dist/types.d.ts +20 -2
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +4 -4
  57. package/dist/types.js.map +1 -1
  58. package/package.json +5 -5
  59. package/ui/components/quotations.component.ts +51 -15
@@ -54,6 +54,7 @@ const pricing_1 = require("./pricing");
54
54
  const quote_version_1 = require("./quote-version");
55
55
  const quote_total_1 = require("./quote-total");
56
56
  const templates_1 = require("./templates");
57
+ const emails_1 = require("./emails");
57
58
  const events_1 = require("./events");
58
59
  const pdf_1 = require("./pdf");
59
60
  const types_1 = require("./types");
@@ -202,6 +203,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
202
203
  }
203
204
  async onModuleInit() {
204
205
  await this.ensureSchema();
206
+ await this.repairDoubleVatRequests();
205
207
  await this.licenceStore.ensureTable();
206
208
  await this.prefs.ensureTable();
207
209
  }
@@ -296,6 +298,10 @@ let QuotationService = QuotationService_1 = class QuotationService {
296
298
  await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_order (convertedOrderId)`).catch(() => undefined);
297
299
  await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_customer (customerId)`).catch(() => undefined);
298
300
  await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_requested (customerEmail, requestedAt)`).catch(() => undefined);
301
+ // 0.10.1: line prices that include VAT (a Vendure channel with prices including tax), and the
302
+ // requester's address on storefront requests. Existing quotes keep 0: they were priced ex-VAT.
303
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS pricesIncludeTax TINYINT NOT NULL DEFAULT 0`);
304
+ await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestIp VARCHAR(64) NOT NULL DEFAULT ''`);
299
305
  await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS payLinkOnAccept TINYINT NOT NULL DEFAULT 0`);
300
306
  await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS attachPdf TINYINT NOT NULL DEFAULT 0`);
301
307
  await this.db.query(`
@@ -361,12 +367,14 @@ let QuotationService = QuotationService_1 = class QuotationService {
361
367
  return rows.length ? this.rowToConfig(rows[0]) : { ...types_1.DEFAULT_CONFIG, channelId };
362
368
  }
363
369
  async getAllConfigs() {
364
- const channels = await this.db.query(`SELECT id AS channelId, code AS channelCode FROM channel ORDER BY id`);
370
+ const channels = await this.db.query(`SELECT id AS channelId, code AS channelCode, \`pricesIncludeTax\` AS pricesIncludeTax FROM channel ORDER BY id`);
365
371
  const rows = await this.db.query(`SELECT * FROM quotation_config`).catch(() => []);
366
372
  return channels.map((ch) => {
367
373
  const existing = rows.find((r) => r.channelId === ch.channelId);
368
- return existing ? this.rowToConfig(existing, ch.channelCode)
374
+ const cfg = existing ? this.rowToConfig(existing, ch.channelCode)
369
375
  : { ...types_1.DEFAULT_CONFIG, channelId: ch.channelId, channelCode: ch.channelCode };
376
+ // Read-only: new quotes on this channel price catalogue lines inc. VAT when it is set.
377
+ return { ...cfg, channelPricesIncludeTax: (0, pricing_1.isInclusive)(ch) };
370
378
  });
371
379
  }
372
380
  async saveConfig(c) {
@@ -393,6 +401,42 @@ let QuotationService = QuotationService_1 = class QuotationService {
393
401
  c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000),
394
402
  c.payLinkOnAccept ? 1 : 0, c.attachPdf ? 1 : 0], { conflictColumns: ['channelId'] });
395
403
  }
404
+ /** Whether the channel's catalogue prices include tax (Vendure's Channel.pricesIncludeTax). */
405
+ async channelTax(channelId) {
406
+ const [row] = await this.db.query(`SELECT \`pricesIncludeTax\` AS pricesIncludeTax FROM channel WHERE id = ?`, [channelId]).catch(() => []);
407
+ return { pricesIncludeTax: (0, pricing_1.isInclusive)(row) };
408
+ }
409
+ /**
410
+ * Before 0.10.1 a storefront request on a "prices include tax" channel was
411
+ * priced from the VAT-inclusive catalogue price and VAT was added again.
412
+ * Requests nobody has touched yet (status `requested`, never edited, never
413
+ * sent) are re-priced here, once, with the VAT split out of the price; the
414
+ * trail records the old and new totals. Anything sent or edited is left
415
+ * alone (see the README for the read-only check). Returns the references fixed.
416
+ */
417
+ async repairDoubleVatRequests() {
418
+ const rows = await this.db.query(`SELECT q.id FROM quotation q JOIN channel ch ON ch.id = q.channelId
419
+ WHERE q.status = 'requested' AND q.pricesIncludeTax = 0 AND ch.\`pricesIncludeTax\` IS TRUE
420
+ AND q.createdBy LIKE 'customer:%' AND q.sentAt IS NULL
421
+ AND NOT EXISTS (SELECT 1 FROM quotation_event e WHERE e.quoteId = q.id AND e.type IN ('updated', 'sent', 'repriced'))`, []).catch((e) => { core_1.Logger.warn(`double-VAT request check failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx); return []; });
422
+ const fixed = [];
423
+ for (const r of rows) {
424
+ const q = await this.getQuote(Number(r.id));
425
+ if (!q)
426
+ continue;
427
+ const lines = (q.lines || []).map((l) => ({ ...l, quantity: Number(l.quantity), unitPricePence: Number(l.unitPricePence), lineDiscountPercent: Number(l.lineDiscountPercent) }));
428
+ const t = (0, pricing_1.quoteTotals)(lines, q.discountType || 'none', Number(q.discountValue || 0), Number(q.vatRate), true);
429
+ const res = await this.db.query(`UPDATE quotation SET pricesIncludeTax = 1, subTotalPence = ?, discountPence = ?, vatPence = ?, totalPence = ?, updatedAt = NOW()
430
+ WHERE id = ? AND status = 'requested' AND pricesIncludeTax = 0`, [t.subTotalPence, t.discountPence, t.vatPence, t.totalPence, q.id], { needAffected: true });
431
+ if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) !== 1)
432
+ continue;
433
+ await this.logEvent(Number(q.id), 'repriced', `Re-priced: the catalogue prices already include VAT, which had been added again (total ${(0, pricing_1.formatMoney)(Number(q.totalPence), q.currency)} → ${(0, pricing_1.formatMoney)(t.totalPence, q.currency)} inc. VAT ${(0, pricing_1.formatMoney)(t.vatPence, q.currency)})`, 'system');
434
+ fixed.push(String(q.reference));
435
+ }
436
+ if (fixed.length)
437
+ core_1.Logger.info(`Re-priced ${fixed.length} untouched storefront request(s) that had VAT added twice: ${fixed.join(', ')}`, loggerCtx);
438
+ return fixed;
439
+ }
396
440
  // ── Reference numbering ─────────────────────────────────────────────
397
441
  /** Atomically claims the next quote number for a channel. */
398
442
  async nextReference(channelId) {
@@ -436,7 +480,10 @@ let QuotationService = QuotationService_1 = class QuotationService {
436
480
  const vatRate = (_a = input.vatRate) !== null && _a !== void 0 ? _a : cfg.defaultVatRate;
437
481
  const discountType = input.discountType || 'none';
438
482
  const discountValue = Number(input.discountValue || 0);
439
- const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
483
+ // Catalogue prices on a "prices include tax" channel already carry VAT: a new quote follows the channel.
484
+ const pricesIncludeTax = typeof input.pricesIncludeTax === 'boolean'
485
+ ? input.pricesIncludeTax : (await this.channelTax(channelId)).pricesIncludeTax;
486
+ const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate, pricesIncludeTax);
440
487
  const reference = await this.nextReference(channelId);
441
488
  const token = crypto.randomBytes(24).toString('hex');
442
489
  // The validity period; it starts afresh when the quote is first sent (see sendQuote / markSent).
@@ -444,8 +491,8 @@ let QuotationService = QuotationService_1 = class QuotationService {
444
491
  const res = await this.db.query(`INSERT INTO quotation (channelId, reference, status, token, customerId, customerName, customerEmail,
445
492
  customerCompany, customerPhone, notes, internalNotes, terms, vatRate, discountType, discountValue,
446
493
  currency, validUntil, subTotalPence, discountPence, vatPence, totalPence, createdBy,
447
- preparedByName, preparedByEmail, validityDays, createdAt, updatedAt)
448
- VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
494
+ preparedByName, preparedByEmail, validityDays, pricesIncludeTax, createdAt, updatedAt)
495
+ VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
449
496
  String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
450
497
  String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
451
498
  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),
@@ -453,7 +500,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
453
500
  validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
454
501
  actor.slice(0, 190),
455
502
  String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
456
- validityDays], { needInsertId: true });
503
+ validityDays, pricesIncludeTax ? 1 : 0], { needInsertId: true });
457
504
  const quoteId = Number(res.insertId);
458
505
  await this.replaceLines(quoteId, lines);
459
506
  await this.logEvent(quoteId, 'created', `Quote ${reference} created`, actor);
@@ -484,7 +531,8 @@ let QuotationService = QuotationService_1 = class QuotationService {
484
531
  const vatRate = (_a = input.vatRate) !== null && _a !== void 0 ? _a : existing.vatRate;
485
532
  const discountType = input.discountType || 'none';
486
533
  const discountValue = Number(input.discountValue || 0);
487
- const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
534
+ const pricesIncludeTax = typeof input.pricesIncludeTax === 'boolean' ? input.pricesIncludeTax : (0, pricing_1.isInclusive)(existing);
535
+ const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate, pricesIncludeTax);
488
536
  // Validity only moves when the editor actually sets it; a typo fix must not push expiry out.
489
537
  const newValidity = Number(input.validityDays);
490
538
  const touchValidity = Number.isFinite(newValidity) && newValidity > 0;
@@ -492,7 +540,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
492
540
  notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
493
541
  validUntil=${touchValidity ? 'DATE_ADD(NOW(), INTERVAL ? DAY)' : 'validUntil'},
494
542
  validityDays=${touchValidity ? '?' : 'validityDays'},
495
- subTotalPence=?, discountPence=?, vatPence=?, totalPence=?,
543
+ subTotalPence=?, discountPence=?, vatPence=?, totalPence=?, pricesIncludeTax=?,
496
544
  preparedByName=?, preparedByEmail=?, updatedAt=NOW()
497
545
  WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
498
546
  String(input.customerEmail || '').toLowerCase().slice(0, 190), String(input.customerCompany || '').slice(0, 190),
@@ -500,7 +548,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
500
548
  String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms) !== null && _c !== void 0 ? _c : '').slice(0, 20000), vatRate, discountType, discountValue,
501
549
  (input.currency || existing.currency).toUpperCase().slice(0, 3),
502
550
  ...(touchValidity ? [Math.min(365, Math.max(1, Math.floor(newValidity))), Math.min(365, Math.max(1, Math.floor(newValidity)))] : []),
503
- totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
551
+ totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence, pricesIncludeTax ? 1 : 0,
504
552
  String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
505
553
  quoteId]);
506
554
  await this.replaceLines(quoteId, lines);
@@ -539,7 +587,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
539
587
  customerId: q.customerId, customerName: q.customerName, customerEmail: q.customerEmail,
540
588
  customerCompany: q.customerCompany, customerPhone: q.customerPhone,
541
589
  notes: q.notes, internalNotes: q.internalNotes, terms: q.terms,
542
- vatRate: q.vatRate, discountType: q.discountType, discountValue: q.discountValue,
590
+ vatRate: q.vatRate, pricesIncludeTax: (0, pricing_1.isInclusive)(q), discountType: q.discountType, discountValue: q.discountValue,
543
591
  currency: q.currency, validityDays: this.validityDaysOf(q),
544
592
  lines: q.lines.map((l) => ({
545
593
  productVariantId: l.productVariantId, sku: l.sku, description: l.description,
@@ -561,6 +609,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
561
609
  const [q] = await this.db.query(`SELECT * FROM quotation WHERE id = ?`, [quoteId]).catch(() => []);
562
610
  if (!q)
563
611
  return null;
612
+ q.pricesIncludeTax = (0, pricing_1.isInclusive)(q);
564
613
  q.lines = await this.db.query(`SELECT * FROM quotation_line WHERE quoteId = ? ORDER BY position`, [quoteId]);
565
614
  q.events = await this.db.query(`SELECT type, detail, actor, createdAt FROM quotation_event WHERE quoteId = ? ORDER BY createdAt DESC, id DESC LIMIT 50`, [quoteId]);
566
615
  return q;
@@ -571,6 +620,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
571
620
  const [q] = await this.db.query(`SELECT * FROM quotation WHERE token = ? LIMIT 1`, [token]).catch(() => []);
572
621
  if (!q)
573
622
  return null;
623
+ q.pricesIncludeTax = (0, pricing_1.isInclusive)(q);
574
624
  q.lines = await this.db.query(`SELECT * FROM quotation_line WHERE quoteId = ? ORDER BY position`, [q.id]);
575
625
  return q;
576
626
  }
@@ -779,21 +829,22 @@ let QuotationService = QuotationService_1 = class QuotationService {
779
829
  let body = cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody;
780
830
  if (kind === 'chaser') {
781
831
  subject = `Reminder: quotation {{reference}} from {{businessName}}`;
782
- body = 'Hi {{customerName}},\n\nJust a gentle nudge — your quotation {{reference}} for {{total}} is waiting for you:\n\n{{quoteUrl}}\n\nIt stays valid until {{validUntil}}. Any questions, simply reply.\n\nBest regards,\n{{businessName}}';
832
+ body = 'Hi {{customerName}},\n\nJust a gentle reminder: your quotation {{reference}} for {{total}} is waiting for you:\n\n{{quoteUrl}}\n\nIt stays valid until {{validUntil}}. If you have any questions, simply reply to this e-mail.\n\nKind regards,\n{{businessName}}';
783
833
  }
784
834
  else if (kind === 'expiry') {
785
835
  subject = `Your quotation {{reference}} expires soon`;
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}}';
836
+ body = 'Hi {{customerName}},\n\nA quick reminder: quotation {{reference}} for {{total}} expires on {{validUntil}}.\n\nYou can accept it online here:\n\n{{quoteUrl}}\n\nIf the timing does not work for you, reply and we will extend it.\n\nKind regards,\n{{businessName}}';
787
837
  }
788
- return this.emailCustomer(q, cfg, subject, body, { to: overrideTo, test: !!overrideTo, attachPdf: cfg.attachPdf });
838
+ return this.emailCustomer(q, cfg, subject, body, { to: overrideTo, test: !!overrideTo, attachPdf: cfg.attachPdf, kind });
789
839
  }
790
840
  /**
791
841
  * One e-mail to the customer (or `to`, for a test), as the member of staff
792
842
  * who prepared the quote: their name fronts the From header and replies go
793
- * straight to them. Templates use {{placeholders}} (see emailVars).
843
+ * straight to them. Templates use {{placeholders}} (see emailVars). The
844
+ * template text sits in the shared e-mail design (emails.ts) with the
845
+ * quote's summary and button; a plain-text part goes with it.
794
846
  */
795
847
  async emailCustomer(q, cfg, subjectTpl, bodyTpl, opts = {}) {
796
- var _a, _b;
797
848
  const smtp = this.smtpSettings();
798
849
  if (!smtp)
799
850
  return { ok: false, reason: 'SMTP is not configured (SMTP_SERVER / SMTP_USER env or plugin options)' };
@@ -805,13 +856,17 @@ let QuotationService = QuotationService_1 = class QuotationService {
805
856
  const senderName = q.preparedByName
806
857
  ? (cfg.businessName ? `${q.preparedByName} — ${cfg.businessName}` : q.preparedByName)
807
858
  : (cfg.businessName || '');
859
+ const mail = (0, emails_1.customerQuoteMail)({
860
+ q, cfg, kind: opts.kind || (opts.button ? 'custom' : 'quote'), body: render(bodyTpl), quoteUrl: url,
861
+ test: opts.test, button: opts.button, amountDue: opts.amountDue,
862
+ });
808
863
  await this.sendWithDeadline(transporter, {
809
864
  from: senderName ? `"${senderName.replace(/["\r\n]/g, "'")}" <${smtp.from}>` : smtp.from,
810
865
  to: opts.to || q.customerEmail,
811
866
  replyTo: q.preparedByEmail || cfg.replyTo || undefined,
812
867
  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),
868
+ text: mail.text,
869
+ html: mail.html,
815
870
  attachments: opts.attachPdf
816
871
  ? [{ filename: `Quotation-${String(q.reference).replace(/[^A-Za-z0-9._-]/g, '_')}.pdf`, content: (0, pdf_1.renderQuotePdf)(q, cfg, url), contentType: 'application/pdf' }]
817
872
  : undefined,
@@ -822,14 +877,15 @@ let QuotationService = QuotationService_1 = class QuotationService {
822
877
  return { ok: false, reason: e.message };
823
878
  }
824
879
  }
825
- /** A plain-text note to members of staff (approvals). Never throws. */
826
- async mailStaff(to, subject, text) {
880
+ /** A note to members of staff (approvals), in the compact e-mail design. Never throws. */
881
+ async mailStaff(to, subject, mail) {
827
882
  const smtp = this.smtpSettings();
828
883
  const list = [...new Set(to.map(t => String(t || '').trim().toLowerCase()).filter(t => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)))].slice(0, 50);
829
884
  if (!smtp || !list.length)
830
885
  return false;
886
+ const body = typeof mail === 'string' ? { text: mail } : mail;
831
887
  try {
832
- await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to: list.join(', '), subject: subject.replace(/[\r\n]+/g, ' '), text });
888
+ await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to: list.join(', '), subject: subject.replace(/[\r\n]+/g, ' '), ...body });
833
889
  return true;
834
890
  }
835
891
  catch (e) {
@@ -837,8 +893,13 @@ let QuotationService = QuotationService_1 = class QuotationService {
837
893
  return false;
838
894
  }
839
895
  }
840
- /** Fire-and-forget notification to the merchant on accept/decline. */
841
- async notifyMerchant(q, cfg, subject, text) {
896
+ /** The admin link to one quote, when the admin URL is known. */
897
+ quoteAdminUrl(quoteId) {
898
+ const base = this.adminUrl();
899
+ return base ? `${base}?quote=${quoteId}` : '';
900
+ }
901
+ /** Fire-and-forget notification to the merchant (request, first view, accept/decline). */
902
+ async notifyMerchant(q, cfg, subject, mail) {
842
903
  const smtp = this.smtpSettings();
843
904
  // The preparing member of staff always hears about it; the channel
844
905
  // notify address is copied in when it differs.
@@ -847,12 +908,26 @@ let QuotationService = QuotationService_1 = class QuotationService {
847
908
  if (!smtp || !to)
848
909
  return;
849
910
  try {
850
- await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to, subject, text });
911
+ await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to, subject: subject.replace(/[\r\n]+/g, ' '), text: mail.text, html: mail.html });
851
912
  }
852
913
  catch (e) {
853
914
  core_1.Logger.warn(`merchant notification failed: ${e.message}`, loggerCtx);
854
915
  }
855
916
  }
917
+ /** The rows every store notification about a quote shows. */
918
+ quoteRows(q, extra = []) {
919
+ return [
920
+ { label: 'Quotation', value: String(q.reference || ''), mono: true },
921
+ { label: 'Customer', value: [q.customerName, q.customerEmail ? `<${q.customerEmail}>` : ''].filter(Boolean).join(' ') },
922
+ { label: 'Company', value: String(q.customerCompany || '') },
923
+ { label: 'Total', value: (0, pricing_1.formatMoney)(q.totalPence, q.currency) },
924
+ ...extra,
925
+ ];
926
+ }
927
+ adminButton(q, label = 'Open the quote') {
928
+ const url = this.quoteAdminUrl(Number(q.id));
929
+ return url ? { url, label } : undefined;
930
+ }
856
931
  // ── Customer actions ────────────────────────────────────────────────
857
932
  async markViewed(token) {
858
933
  const q = await this.getQuoteByToken(token);
@@ -866,7 +941,12 @@ let QuotationService = QuotationService_1 = class QuotationService {
866
941
  await this.logEvent(q.id, 'viewed', 'Opened by the customer', q.customerEmail);
867
942
  const cfg = await this.getConfig(q.channelId);
868
943
  if (cfg.notifyOnView) {
869
- void this.notifyMerchant(q, cfg, `Quote ${q.reference} was just opened`, `${q.customerName} <${q.customerEmail}> opened quote ${q.reference} (${(0, pricing_1.formatMoney)(q.totalPence, q.currency)}) for the first time — a good moment to follow up.`);
944
+ void this.notifyMerchant(q, cfg, `Quote ${q.reference} was just opened`, (0, emails_1.staffMail)(cfg, {
945
+ heading: `Quote ${q.reference} was just opened`,
946
+ intro: `${q.customerName || q.customerEmail} opened the quote for the first time. This is a good moment to follow up.`,
947
+ rows: this.quoteRows(q),
948
+ button: this.adminButton(q),
949
+ }));
870
950
  }
871
951
  }
872
952
  }
@@ -903,10 +983,14 @@ let QuotationService = QuotationService_1 = class QuotationService {
903
983
  ? `Accepted by "${cleanName}"${cleanComment ? ` — ${cleanComment}` : ''}`
904
984
  : `Declined${cleanComment ? ` — ${cleanComment}` : ''}`, q.customerEmail);
905
985
  const cfg = await this.getConfig(q.channelId);
906
- void this.notifyMerchant(q, cfg, `Quote ${q.reference} ${status} — ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)}`, `${q.customerName} <${q.customerEmail}> ${status} quote ${q.reference} (${(0, pricing_1.formatMoney)(q.totalPence, q.currency)}).` +
907
- (action === 'accept' ? `\nSigned: ${cleanName}` : '') +
908
- (cleanComment ? `\nComment: ${cleanComment}` : '') +
909
- `\n\nAdmin: open the Quotations page to ${action === 'accept' ? 'convert it to an order' : 'follow up'}.`);
986
+ void this.notifyMerchant(q, cfg, `Quote ${q.reference} ${status} — ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)}`, (0, emails_1.staffMail)(cfg, {
987
+ heading: `Quote ${q.reference} ${status}`,
988
+ intro: `${q.customerName || q.customerEmail} ${status} quote ${q.reference}.`,
989
+ rows: this.quoteRows(q, action === 'accept' ? [{ label: 'Signed by', value: cleanName }] : []),
990
+ note: cleanComment ? { title: 'Their comment', text: cleanComment } : undefined,
991
+ outro: action === 'accept' ? 'Open the quote in Admin → Quotations to convert it to an order.' : 'Open the quote in Admin → Quotations to follow up.',
992
+ button: this.adminButton(q),
993
+ }));
910
994
  return { ok: true, quote: await this.getQuote(q.id) };
911
995
  }
912
996
  // ── Conversion to a Vendure draft order ─────────────────────────────
@@ -1030,7 +1114,10 @@ let QuotationService = QuotationService_1 = class QuotationService {
1030
1114
  return 'not-a-quote';
1031
1115
  const wantGross = Number(q.totalPence);
1032
1116
  const wantNet = Number(q.subTotalPence) - Number(q.discountPence);
1033
- if (Number(order.subTotalWithTax) === wantGross && Number(order.subTotal) === wantNet)
1117
+ // Vendure derives each line's net from its gross price, so on a VAT-inclusive quote the order's
1118
+ // net can differ from the quote's by rounding (a penny per line) while the total is exact.
1119
+ const netSlack = (0, pricing_1.isInclusive)(q) ? (q.lines || []).length : 0;
1120
+ if (Number(order.subTotalWithTax) === wantGross && Math.abs(Number(order.subTotal) - wantNet) <= netSlack)
1034
1121
  return 'unchanged';
1035
1122
  if (!(0, quote_total_1.orderLinesMatchQuote)(order.lines || [], q.lines || [])) {
1036
1123
  core_1.Logger.info(`Order ${order.code} (quote ${q.reference}) no longer holds the quoted lines; its total follows the catalogue`, loggerCtx);
@@ -1116,11 +1203,17 @@ let QuotationService = QuotationService_1 = class QuotationService {
1116
1203
  conds.push(`pv.sku IN (${skus.map(() => '?').join(',')})`);
1117
1204
  params.push(...skus);
1118
1205
  }
1119
- rows = await this.db.query(`SELECT pv.id AS productVariantId, pv.sku, COALESCE(pvt.name, pvt_en.name) AS name, pvp.price AS pricePence
1206
+ rows = await this.db.query(
1207
+ // The variant's tax rate is the one for its tax category in the channel's default tax zone,
1208
+ // as Vendure prices it (customer-group-specific rates are left out: a request has no group).
1209
+ `SELECT pv.id AS productVariantId, pv.sku, COALESCE(pvt.name, pvt_en.name) AS name, pvp.price AS pricePence, tr.value AS taxRate
1120
1210
  FROM product_variant pv
1121
1211
  LEFT JOIN product_variant_translation pvt ON pvt.\`baseId\` = pv.id AND pvt.\`languageCode\` = ?
1122
1212
  LEFT JOIN product_variant_translation pvt_en ON pvt_en.\`baseId\` = pv.id AND pvt_en.\`languageCode\` = 'en'
1123
1213
  JOIN product_variant_price pvp ON pvp.\`variantId\` = pv.id AND pvp.\`channelId\` = ?
1214
+ LEFT JOIN channel ch ON ch.id = pvp.\`channelId\`
1215
+ LEFT JOIN tax_rate tr ON tr.\`categoryId\` = pv.\`taxCategoryId\` AND tr.\`zoneId\` = ch.\`defaultTaxZoneId\`
1216
+ AND tr.enabled IS TRUE AND tr.\`customerGroupId\` IS NULL
1124
1217
  WHERE pv.\`deletedAt\` IS NULL AND pv.enabled IS TRUE AND (${conds.join(' OR ')})`, params).catch((e) => { core_1.Logger.warn(`request pricing lookup failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx); return []; });
1125
1218
  }
1126
1219
  const byId = new Map();
@@ -1136,7 +1229,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
1136
1229
  const quantity = Math.max(1, Math.min(100000, Math.floor(Number(l.quantity) || 1)));
1137
1230
  return hit
1138
1231
  // Catalogue lines are described by the catalogue, never by the requester's text.
1139
- ? { productVariantId: Number(hit.productVariantId), sku: String(hit.sku || ''), description: String(hit.name || hit.sku || 'Catalogue item').slice(0, 500), quantity, unitPricePence: Math.max(0, Math.floor(Number(hit.pricePence) || 0)) }
1232
+ ? { productVariantId: Number(hit.productVariantId), sku: String(hit.sku || ''), description: String(hit.name || hit.sku || 'Catalogue item').slice(0, 500), quantity, unitPricePence: Math.max(0, Math.floor(Number(hit.pricePence) || 0)), taxRate: hit.taxRate == null ? null : Number(hit.taxRate) }
1140
1233
  : { productVariantId: null, sku: String(l.sku || '').slice(0, 64), description: String(l.description || l.sku || 'Requested item').slice(0, 500), quantity, unitPricePence: 0 };
1141
1234
  });
1142
1235
  }
@@ -1157,7 +1250,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
1157
1250
  * carried a shop session: the request is then linked to that account (and
1158
1251
  * shows under "My quotes"). Guest requests are never linked by e-mail.
1159
1252
  */
1160
- async createRequest(channelId, input, clientKey, customerId = null) {
1253
+ async createRequest(channelId, input, clientKey, customerId = null, clientIp = null) {
1161
1254
  const cfg = await this.getConfig(channelId);
1162
1255
  if (!cfg.acceptRequests)
1163
1256
  return { ok: false, reason: 'Quote requests are not accepted on this channel' };
@@ -1179,7 +1272,13 @@ let QuotationService = QuotationService_1 = class QuotationService {
1179
1272
  return { ok: false, reason: 'Tell us what you need a quote for' };
1180
1273
  lines = [{ productVariantId: null, sku: '', description: `Customer enquiry — see request: ${message.slice(0, 120)}`, quantity: 1, unitPricePence: 0 }];
1181
1274
  }
1275
+ // Priced the way the channel prices them: catalogue prices include VAT when the channel says so,
1276
+ // and the VAT rate is the catalogue lines' own rate rather than the quote default.
1277
+ const tax = await this.channelTax(channelId);
1278
+ const rated = (0, pricing_1.requestVatRate)(lines, cfg.defaultVatRate);
1182
1279
  const q = await this.createQuote(channelId, {
1280
+ pricesIncludeTax: tax.pricesIncludeTax,
1281
+ vatRate: rated.rate,
1183
1282
  customerId: customerId || null,
1184
1283
  customerName: String(input.name || '').trim().slice(0, 190) || email,
1185
1284
  customerEmail: email,
@@ -1187,12 +1286,28 @@ let QuotationService = QuotationService_1 = class QuotationService {
1187
1286
  customerPhone: String(input.phone || '').trim().slice(0, 64),
1188
1287
  lines,
1189
1288
  }, `customer:${email}`);
1190
- await this.db.query(`UPDATE quotation SET status='requested', requestMessage=?, requestSource=?, requestedAt=NOW(), updatedAt=NOW() WHERE id = ?`, [message, source, q.id]);
1289
+ await this.db.query(`UPDATE quotation SET status='requested', requestMessage=?, requestSource=?, requestIp=?, requestedAt=NOW(), updatedAt=NOW() WHERE id = ?`, [message, source, String(clientIp || '').slice(0, 64), q.id]);
1191
1290
  await this.logEvent(q.id, 'requested', `Requested by the customer via ${source}${message ? ` — "${message.slice(0, 200)}"` : ''}`, email);
1291
+ if (rated.mixed) {
1292
+ await this.logEvent(q.id, 'comment', `The requested items carry different VAT rates (${rated.rates.join('%, ')}%); the quote uses ${rated.rate}% for all of them — check the VAT before sending`, 'system');
1293
+ }
1192
1294
  const summary = lines.map(l => `${l.quantity} × ${l.description}${l.unitPricePence ? ` @ ${(0, pricing_1.formatMoney)(l.unitPricePence, q.currency)}` : ''}`).join('\n');
1193
1295
  const indicative = lines.some(l => l.unitPricePence > 0) ? ` — indicative ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)} at list` : '';
1194
- void this.notifyMerchant(q, cfg, `New quote request ${q.reference} from ${q.customerCompany || q.customerName}`, `${q.customerName} <${email}>${q.customerCompany ? ` (${q.customerCompany})` : ''}${q.customerPhone ? `, ${q.customerPhone}` : ''} asked for a quote via ${source}${indicative}.\n\n` +
1195
- `${summary}\n\n${message ? `Message:\n${message}\n\n` : ''}Admin: open Quotations → ${q.reference}, price it and click Send.`);
1296
+ void this.notifyMerchant(q, cfg, `New quote request ${q.reference} from ${q.customerCompany || q.customerName}`, (0, emails_1.staffMail)(cfg, {
1297
+ heading: `New quote request ${q.reference}`,
1298
+ intro: `${q.customerName || email} asked for a quote via ${source}${indicative}.`,
1299
+ rows: [
1300
+ { label: 'Reference', value: String(q.reference || ''), mono: true },
1301
+ { label: 'Name', value: String(q.customerName || '') },
1302
+ { label: 'E-mail', value: email },
1303
+ { label: 'Company', value: String(q.customerCompany || '') },
1304
+ { label: 'Phone', value: String(q.customerPhone || '') },
1305
+ ],
1306
+ list: { title: 'Requested', items: summary ? summary.split('\n') : [] },
1307
+ note: message ? { title: 'Message', text: message } : undefined,
1308
+ outro: `Open Quotations → ${q.reference}, price it and click Send.`,
1309
+ button: this.adminButton(q, 'Price the request'),
1310
+ }));
1196
1311
  // The endpoint is public, so the acknowledgement must not relay anything the requester typed (name,
1197
1312
  // free-text lines, message) to an address they chose: it lists catalogue lines by their catalogue name only.
1198
1313
  const catalogueLines = lines.filter(l => l.productVariantId && l.unitPricePence > 0);
@@ -1238,7 +1353,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
1238
1353
  // Not the requester-supplied name: anyone can post any name for any address.
1239
1354
  customerName: 'there', reference: q.reference, businessName: cfg.businessName || '', summary,
1240
1355
  };
1241
- const text = String(cfg.requestAckBody).replace(/\{\{\s*(\w+)\s*\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
1356
+ const mail = (0, emails_1.requestAckMail)(q, cfg, String(cfg.requestAckBody).replace(/\{\{\s*(\w+)\s*\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; }));
1242
1357
  try {
1243
1358
  const transporter = this.transporter(smtp);
1244
1359
  await this.sendWithDeadline(transporter, {
@@ -1246,7 +1361,8 @@ let QuotationService = QuotationService_1 = class QuotationService {
1246
1361
  to,
1247
1362
  replyTo: cfg.replyTo || cfg.notifyEmail || undefined,
1248
1363
  subject: `We've received your quote request (${q.reference})`,
1249
- text,
1364
+ text: mail.text,
1365
+ html: mail.html,
1250
1366
  });
1251
1367
  await this.logEvent(q.id, 'ack', `Acknowledgement emailed to ${q.customerEmail}`);
1252
1368
  }
@@ -1426,7 +1542,7 @@ let QuotationService = QuotationService_1 = class QuotationService {
1426
1542
  quoteUrl: url,
1427
1543
  };
1428
1544
  const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
1429
- return { ok: true, html: (0, templates_1.renderQuoteEmailHtml)(render(cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody), q, cfg, url) };
1545
+ return { ok: true, html: (0, emails_1.customerQuoteMail)({ q, cfg, kind: 'quote', body: render(cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody), quoteUrl: url }).html };
1430
1546
  }
1431
1547
  /** Extend an open (or expired) quote's validity; expired quotes revive. */
1432
1548
  async extendValidity(quoteId, days, actor) {
@@ -1796,10 +1912,15 @@ let QuotationService = QuotationService_1 = class QuotationService {
1796
1912
  const tips = setup.items.filter(i => !i.done).slice(0, 3)
1797
1913
  .map(i => ({ title: i.label, body: i.hint, url: i.url || adminUrl || undefined, linkLabel: i.url && i.url !== adminUrl ? 'Read how' : 'Open in Admin' }));
1798
1914
  let storeName = null;
1915
+ let logoUrl = null;
1916
+ let accentColor = null;
1799
1917
  try {
1800
1918
  const ch = await this.channelService.getDefaultChannel();
1801
1919
  const cfg = await this.getConfig(Number(ch === null || ch === void 0 ? void 0 : ch.id) || 1);
1802
1920
  storeName = cfg.businessName || null;
1921
+ // The report wears the store's own look, as the quote e-mails do.
1922
+ logoUrl = cfg.logoUrl || null;
1923
+ accentColor = cfg.accentColor || null;
1803
1924
  }
1804
1925
  catch {
1805
1926
  storeName = null;
@@ -1814,6 +1935,8 @@ let QuotationService = QuotationService_1 = class QuotationService {
1814
1935
  adminUrl,
1815
1936
  premiumFeatures: exports.PREMIUM_FEATURES,
1816
1937
  storeName,
1938
+ logoUrl,
1939
+ accentColor,
1817
1940
  settingsHint: 'Change the recipient or stop this weekly report in Admin → Quotations → Settings → Weekly report.',
1818
1941
  };
1819
1942
  }