@huloglobal/vendure-plugin-quotations 0.7.0 → 0.7.2
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.
- package/CHANGELOG.md +27 -0
- package/README.md +5 -0
- package/dist/catalogue-search.d.ts +26 -0
- package/dist/catalogue-search.d.ts.map +1 -0
- package/dist/catalogue-search.js +26 -0
- package/dist/catalogue-search.js.map +1 -0
- package/dist/crons.js +3 -1
- package/dist/crons.js.map +1 -1
- package/dist/pricing.d.ts.map +1 -1
- package/dist/pricing.js +4 -3
- package/dist/pricing.js.map +1 -1
- package/dist/pricing.test.d.ts +2 -0
- package/dist/pricing.test.d.ts.map +1 -0
- package/dist/pricing.test.js +16 -0
- package/dist/pricing.test.js.map +1 -0
- package/dist/quotation.controller.d.ts.map +1 -1
- package/dist/quotation.controller.js +4 -3
- package/dist/quotation.controller.js.map +1 -1
- package/dist/quotation.service.d.ts +9 -1
- package/dist/quotation.service.d.ts.map +1 -1
- package/dist/quotation.service.js +181 -85
- package/dist/quotation.service.js.map +1 -1
- package/package.json +2 -2
- package/ui/components/quotations.component.ts +9 -6
|
@@ -48,6 +48,7 @@ const core_1 = require("@vendure/core");
|
|
|
48
48
|
const crypto = __importStar(require("crypto"));
|
|
49
49
|
const nodemailer = __importStar(require("nodemailer"));
|
|
50
50
|
const vendure_licence_sdk_1 = require("@huloglobal/vendure-licence-sdk");
|
|
51
|
+
const catalogue_search_1 = require("./catalogue-search");
|
|
51
52
|
const pricing_1 = require("./pricing");
|
|
52
53
|
const templates_1 = require("./templates");
|
|
53
54
|
const types_1 = require("./types");
|
|
@@ -75,8 +76,12 @@ let QuotationService = class QuotationService {
|
|
|
75
76
|
// Buy-from-admin auto-install (hooks are supplied by the controller so
|
|
76
77
|
// this file never imports the plugin class).
|
|
77
78
|
this.purchaseClaim = null;
|
|
79
|
+
this.mailer = null;
|
|
78
80
|
// ── Customer-initiated quote requests ───────────────────────────────
|
|
79
81
|
this.requestHits = new Map();
|
|
82
|
+
// ── Product search for the editor ───────────────────────────────────
|
|
83
|
+
/** Per channel+language: which catalogue the search reads (see catalogue-search.ts); re-checked every minute. */
|
|
84
|
+
this.catalogueSources = new Map();
|
|
80
85
|
}
|
|
81
86
|
get db() { return (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection); }
|
|
82
87
|
setOptions(o) { this.options = o || {}; }
|
|
@@ -151,6 +156,10 @@ let QuotationService = class QuotationService {
|
|
|
151
156
|
INDEX idx_q_reference (reference),
|
|
152
157
|
INDEX idx_q_email (customerEmail)
|
|
153
158
|
)`);
|
|
159
|
+
// A duplicate reference must fail loudly rather than silently coexist.
|
|
160
|
+
await this.db.query(`ALTER TABLE quotation ADD UNIQUE INDEX IF NOT EXISTS uq_q_channel_ref (channelId, reference)`).catch((e) => core_1.Logger.warn(`could not add unique reference index: ${e.message}`, loggerCtx));
|
|
161
|
+
// expireOverdue / stats filter on status + validUntil without a channel.
|
|
162
|
+
await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_status_valid (status, validUntil)`).catch(() => undefined);
|
|
154
163
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS preparedByName VARCHAR(190) NOT NULL DEFAULT ''`);
|
|
155
164
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS preparedByEmail VARCHAR(190) NOT NULL DEFAULT ''`);
|
|
156
165
|
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS notifyOnView TINYINT NOT NULL DEFAULT 0`);
|
|
@@ -220,7 +229,7 @@ let QuotationService = class QuotationService {
|
|
|
220
229
|
};
|
|
221
230
|
}
|
|
222
231
|
async getConfig(channelId) {
|
|
223
|
-
const rows = await this.db.query(`SELECT * FROM quotation_config WHERE channelId = ?`, [channelId])
|
|
232
|
+
const rows = await this.db.query(`SELECT * FROM quotation_config WHERE channelId = ?`, [channelId]);
|
|
224
233
|
return rows.length ? this.rowToConfig(rows[0]) : { ...types_1.DEFAULT_CONFIG, channelId };
|
|
225
234
|
}
|
|
226
235
|
async getAllConfigs() {
|
|
@@ -246,10 +255,10 @@ let QuotationService = class QuotationService {
|
|
|
246
255
|
notifyOnView=VALUES(notifyOnView), websiteUrl=VALUES(websiteUrl), phone=VALUES(phone),
|
|
247
256
|
addressText=VALUES(addressText), footerNote=VALUES(footerNote),
|
|
248
257
|
acceptRequests=VALUES(acceptRequests), requestAckBody=VALUES(requestAckBody)`, [c.channelId, c.numberPrefix || 'Q-', Math.max(1, Number(c.nextNumber) || 1),
|
|
249
|
-
Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, c.defaultTerms || '',
|
|
258
|
+
Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, String(c.defaultTerms || '').slice(0, 4000),
|
|
250
259
|
c.businessName || '', c.replyTo || '', c.notifyEmail || '', (c.currency || 'GBP').toUpperCase().slice(0, 3),
|
|
251
260
|
c.logoUrl || '', c.accentColor || '#1d4ed8', c.chaserEnabled ? 1 : 0, Math.max(1, Number(c.chaserAfterDays) || 3),
|
|
252
|
-
Math.max(0, Number(c.expiryReminderDays) || 0), c.emailSubject || '', c.emailBody || '', c.notifyOnView ? 1 : 0,
|
|
261
|
+
Math.max(0, Number(c.expiryReminderDays) || 0), String(c.emailSubject || '').slice(0, 300), String(c.emailBody || '').slice(0, 4000), c.notifyOnView ? 1 : 0,
|
|
253
262
|
String(c.websiteUrl || '').slice(0, 300), String(c.phone || '').slice(0, 64),
|
|
254
263
|
String(c.addressText || '').slice(0, 500), String(c.footerNote || '').slice(0, 500),
|
|
255
264
|
c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000)], { conflictColumns: ['channelId'] });
|
|
@@ -257,16 +266,22 @@ let QuotationService = class QuotationService {
|
|
|
257
266
|
// ── Reference numbering ─────────────────────────────────────────────
|
|
258
267
|
/** Atomically claims the next quote number for a channel. */
|
|
259
268
|
async nextReference(channelId) {
|
|
260
|
-
var _a;
|
|
261
269
|
const cfg = await this.getConfig(channelId);
|
|
262
|
-
//
|
|
270
|
+
// Make sure the config row exists (no-op when it does).
|
|
263
271
|
await this.db.query(`INSERT INTO quotation_config (channelId, nextNumber) VALUES (?, ?)
|
|
264
|
-
ON DUPLICATE KEY UPDATE nextNumber = nextNumber
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
272
|
+
ON DUPLICATE KEY UPDATE nextNumber = quotation_config.nextNumber`, [channelId, cfg.nextNumber], { conflictColumns: ['channelId'] });
|
|
273
|
+
// Claim a number with a compare-and-set so two concurrent creates can
|
|
274
|
+
// never read the same value (portable across MariaDB and Postgres).
|
|
275
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
276
|
+
const [row] = await this.db.query(`SELECT numberPrefix, nextNumber FROM quotation_config WHERE channelId = ?`, [channelId]);
|
|
277
|
+
const current = Number((row === null || row === void 0 ? void 0 : row.nextNumber) || 1);
|
|
278
|
+
const res = await this.db.query(`UPDATE quotation_config SET nextNumber = ? WHERE channelId = ? AND nextNumber = ?`, [current + 1, channelId, current], { needAffected: true });
|
|
279
|
+
if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
|
|
280
|
+
const prefix = (row === null || row === void 0 ? void 0 : row.numberPrefix) || cfg.numberPrefix || 'Q-';
|
|
281
|
+
return `${prefix}${new Date().getFullYear()}-${String(current).padStart(4, '0')}`;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
throw new Error('Could not allocate a quote number — please try again');
|
|
270
285
|
}
|
|
271
286
|
// ── CRUD ────────────────────────────────────────────────────────────
|
|
272
287
|
sanitizeLines(lines) {
|
|
@@ -283,7 +298,7 @@ let QuotationService = class QuotationService {
|
|
|
283
298
|
}));
|
|
284
299
|
}
|
|
285
300
|
async createQuote(channelId, input, actor) {
|
|
286
|
-
var _a, _b;
|
|
301
|
+
var _a, _b, _c;
|
|
287
302
|
const cfg = await this.getConfig(channelId);
|
|
288
303
|
const lines = this.sanitizeLines(input.lines);
|
|
289
304
|
if (!lines.length)
|
|
@@ -302,7 +317,8 @@ let QuotationService = class QuotationService {
|
|
|
302
317
|
VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
|
|
303
318
|
String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
|
|
304
319
|
String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
|
|
305
|
-
String(input.notes || ''), String(input.internalNotes || ''), (_b = input.terms) !== null && _b !== void 0 ? _b : cfg.defaultTerms
|
|
320
|
+
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),
|
|
321
|
+
vatRate, discountType, discountValue, (input.currency || cfg.currency || 'GBP').toUpperCase().slice(0, 3),
|
|
306
322
|
validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
|
|
307
323
|
actor.slice(0, 190),
|
|
308
324
|
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190)], { needInsertId: true });
|
|
@@ -313,15 +329,17 @@ let QuotationService = class QuotationService {
|
|
|
313
329
|
}
|
|
314
330
|
async replaceLines(quoteId, lines) {
|
|
315
331
|
await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
332
|
+
if (!lines.length)
|
|
333
|
+
return;
|
|
334
|
+
// One statement for all lines: the window in which a quote has partial lines is a single INSERT.
|
|
335
|
+
const placeholders = lines.map(() => '(?, ?, ?, ?, ?, ?, ?, ?, ?)').join(',');
|
|
336
|
+
const params = lines.flatMap((l, pos) => [quoteId, pos, l.productVariantId || null, l.sku || '', l.description, l.quantity,
|
|
337
|
+
l.unitPricePence, l.lineDiscountPercent || 0, (0, pricing_1.lineTotal)(l)]);
|
|
338
|
+
await this.db.query(`INSERT INTO quotation_line (quoteId, position, productVariantId, sku, description, quantity, unitPricePence, lineDiscountPercent, totalPence)
|
|
339
|
+
VALUES ${placeholders}`, params);
|
|
322
340
|
}
|
|
323
341
|
async updateQuote(quoteId, input, actor) {
|
|
324
|
-
var _a, _b;
|
|
342
|
+
var _a, _b, _c;
|
|
325
343
|
const existing = await this.getQuote(quoteId);
|
|
326
344
|
if (!existing)
|
|
327
345
|
throw new Error('Quote not found');
|
|
@@ -335,16 +353,20 @@ let QuotationService = class QuotationService {
|
|
|
335
353
|
const discountType = input.discountType || 'none';
|
|
336
354
|
const discountValue = Number(input.discountValue || 0);
|
|
337
355
|
const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
|
|
356
|
+
// Validity only moves when the editor actually sets it; a typo fix must not push expiry out.
|
|
357
|
+
const newValidity = Number(input.validityDays);
|
|
358
|
+
const touchValidity = Number.isFinite(newValidity) && newValidity > 0;
|
|
338
359
|
await this.db.query(`UPDATE quotation SET customerId=?, customerName=?, customerEmail=?, customerCompany=?, customerPhone=?,
|
|
339
360
|
notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
|
|
340
|
-
validUntil
|
|
361
|
+
validUntil=${touchValidity ? 'DATE_ADD(NOW(), INTERVAL ? DAY)' : 'validUntil'},
|
|
341
362
|
subTotalPence=?, discountPence=?, vatPence=?, totalPence=?,
|
|
342
363
|
preparedByName=?, preparedByEmail=?, updatedAt=NOW()
|
|
343
364
|
WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
|
|
344
365
|
String(input.customerEmail || '').toLowerCase().slice(0, 190), String(input.customerCompany || '').slice(0, 190),
|
|
345
|
-
String(input.customerPhone || '').slice(0, 64), String(input.notes || ''), String(input.internalNotes || '')
|
|
366
|
+
String(input.customerPhone || '').slice(0, 64), String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000),
|
|
367
|
+
String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms) !== null && _c !== void 0 ? _c : '').slice(0, 20000), vatRate, discountType, discountValue,
|
|
346
368
|
(input.currency || existing.currency).toUpperCase().slice(0, 3),
|
|
347
|
-
Math.max(1,
|
|
369
|
+
...(touchValidity ? [Math.max(1, Math.floor(newValidity))] : []),
|
|
348
370
|
totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
|
|
349
371
|
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
|
|
350
372
|
quoteId]);
|
|
@@ -389,7 +411,9 @@ let QuotationService = class QuotationService {
|
|
|
389
411
|
}, actor);
|
|
390
412
|
if (asRevision) {
|
|
391
413
|
await this.db.query(`UPDATE quotation SET revisionOf = ? WHERE id = ?`, [quoteId, created.id]);
|
|
392
|
-
|
|
414
|
+
// The superseded quote must not remain acceptable alongside its revision.
|
|
415
|
+
const closed = await this.db.query(`UPDATE quotation SET status='cancelled', updatedAt=NOW() WHERE id = ? AND status IN ('draft','requested','sent','viewed')`, [quoteId], { needAffected: true });
|
|
416
|
+
await this.logEvent(quoteId, Number((closed === null || closed === void 0 ? void 0 : closed.affectedRows) || 0) ? 'cancelled' : 'duplicated', `Revision ${created.reference} created${Number((closed === null || closed === void 0 ? void 0 : closed.affectedRows) || 0) ? ' — this quote is superseded' : ''}`, actor);
|
|
393
417
|
}
|
|
394
418
|
else {
|
|
395
419
|
await this.logEvent(quoteId, 'duplicated', `Duplicated as ${created.reference}`, actor);
|
|
@@ -458,6 +482,35 @@ let QuotationService = class QuotationService {
|
|
|
458
482
|
}
|
|
459
483
|
return null;
|
|
460
484
|
}
|
|
485
|
+
/** One pooled transport per SMTP configuration, with sane timeouts (nodemailer defaults are 2 min / 10 min). */
|
|
486
|
+
transporter(smtp) {
|
|
487
|
+
var _a, _b, _c, _d;
|
|
488
|
+
const key = `${smtp.host}:${smtp.port}:${smtp.user}`;
|
|
489
|
+
if (((_a = this.mailer) === null || _a === void 0 ? void 0 : _a.key) !== key) {
|
|
490
|
+
try {
|
|
491
|
+
(_d = (_c = (_b = this.mailer) === null || _b === void 0 ? void 0 : _b.transport) === null || _c === void 0 ? void 0 : _c.close) === null || _d === void 0 ? void 0 : _d.call(_c);
|
|
492
|
+
}
|
|
493
|
+
catch { /* ignore */ }
|
|
494
|
+
this.mailer = {
|
|
495
|
+
key,
|
|
496
|
+
transport: nodemailer.createTransport({
|
|
497
|
+
host: smtp.host, port: smtp.port, secure: smtp.port === 465,
|
|
498
|
+
auth: { user: smtp.user, pass: smtp.pass },
|
|
499
|
+
pool: true, maxConnections: 2, maxMessages: 100,
|
|
500
|
+
connectionTimeout: 10000, greetingTimeout: 10000, socketTimeout: 30000,
|
|
501
|
+
}),
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
return this.mailer.transport;
|
|
505
|
+
}
|
|
506
|
+
/** sendMail with a hard deadline so a stuck SMTP host cannot hold a request or the cron. */
|
|
507
|
+
sendWithDeadline(transport, message, ms = 30000) {
|
|
508
|
+
let timer;
|
|
509
|
+
return Promise.race([
|
|
510
|
+
transport.sendMail(message).then(() => undefined),
|
|
511
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`SMTP send timed out after ${ms / 1000}s`)), ms); }),
|
|
512
|
+
]).finally(() => clearTimeout(timer));
|
|
513
|
+
}
|
|
461
514
|
async sendQuote(quoteId, actor) {
|
|
462
515
|
const q = await this.getQuote(quoteId);
|
|
463
516
|
if (!q)
|
|
@@ -486,7 +539,7 @@ let QuotationService = class QuotationService {
|
|
|
486
539
|
businessName: cfg.businessName || 'our team',
|
|
487
540
|
staffName: q.preparedByName || cfg.businessName || 'our team',
|
|
488
541
|
total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
|
|
489
|
-
validUntil: q.validUntil ? new Date(q.validUntil).
|
|
542
|
+
validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
|
|
490
543
|
quoteUrl: url,
|
|
491
544
|
};
|
|
492
545
|
let subject = cfg.emailSubject || types_1.DEFAULT_CONFIG.emailSubject;
|
|
@@ -501,16 +554,13 @@ let QuotationService = class QuotationService {
|
|
|
501
554
|
}
|
|
502
555
|
const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
503
556
|
try {
|
|
504
|
-
const transporter =
|
|
505
|
-
host: smtp.host, port: smtp.port, secure: smtp.port === 465,
|
|
506
|
-
auth: { user: smtp.user, pass: smtp.pass },
|
|
507
|
-
});
|
|
557
|
+
const transporter = this.transporter(smtp);
|
|
508
558
|
// Send as the member of staff who prepared the quote: their name
|
|
509
559
|
// fronts the From header and replies go straight to them.
|
|
510
560
|
const senderName = q.preparedByName
|
|
511
561
|
? (cfg.businessName ? `${q.preparedByName} — ${cfg.businessName}` : q.preparedByName)
|
|
512
562
|
: (cfg.businessName || '');
|
|
513
|
-
await
|
|
563
|
+
await this.sendWithDeadline(transporter, {
|
|
514
564
|
from: senderName ? `"${senderName.replace(/"/g, "'")}" <${smtp.from}>` : smtp.from,
|
|
515
565
|
to: overrideTo || q.customerEmail,
|
|
516
566
|
replyTo: q.preparedByEmail || cfg.replyTo || undefined,
|
|
@@ -534,11 +584,7 @@ let QuotationService = class QuotationService {
|
|
|
534
584
|
if (!smtp || !to)
|
|
535
585
|
return;
|
|
536
586
|
try {
|
|
537
|
-
|
|
538
|
-
host: smtp.host, port: smtp.port, secure: smtp.port === 465,
|
|
539
|
-
auth: { user: smtp.user, pass: smtp.pass },
|
|
540
|
-
});
|
|
541
|
-
await transporter.sendMail({ from: smtp.from, to, subject, text });
|
|
587
|
+
await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to, subject, text });
|
|
542
588
|
}
|
|
543
589
|
catch (e) {
|
|
544
590
|
core_1.Logger.warn(`merchant notification failed: ${e.message}`, loggerCtx);
|
|
@@ -550,12 +596,15 @@ let QuotationService = class QuotationService {
|
|
|
550
596
|
if (!q)
|
|
551
597
|
return null;
|
|
552
598
|
if (q.status === 'sent') {
|
|
553
|
-
|
|
554
|
-
await this.
|
|
599
|
+
// Conditional so two parallel first views produce one event and one notification.
|
|
600
|
+
const res = await this.db.query(`UPDATE quotation SET status='viewed', viewedAt=COALESCE(viewedAt, NOW()), updatedAt=NOW() WHERE id = ? AND status='sent'`, [q.id], { needAffected: true });
|
|
555
601
|
q.status = 'viewed';
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
602
|
+
if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
|
|
603
|
+
await this.logEvent(q.id, 'viewed', 'Opened by the customer', q.customerEmail);
|
|
604
|
+
const cfg = await this.getConfig(q.channelId);
|
|
605
|
+
if (cfg.notifyOnView) {
|
|
606
|
+
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.`);
|
|
607
|
+
}
|
|
559
608
|
}
|
|
560
609
|
}
|
|
561
610
|
return q;
|
|
@@ -566,8 +615,9 @@ let QuotationService = class QuotationService {
|
|
|
566
615
|
return { ok: false, reason: 'Quote not found' };
|
|
567
616
|
if (!OPEN_STATUSES.includes(q.status))
|
|
568
617
|
return { ok: false, reason: `This quote is ${q.status} and can no longer be responded to` };
|
|
569
|
-
|
|
570
|
-
|
|
618
|
+
// One clock decides expiry: the database's, the same one the hourly sweep uses.
|
|
619
|
+
const expired = await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW() WHERE id = ? AND validUntil IS NOT NULL AND validUntil < NOW() AND status IN ('sent','viewed')`, [q.id], { needAffected: true });
|
|
620
|
+
if (Number((expired === null || expired === void 0 ? void 0 : expired.affectedRows) || 0) === 1) {
|
|
571
621
|
await this.logEvent(q.id, 'expired', 'Response attempted after expiry');
|
|
572
622
|
return { ok: false, reason: 'This quote has expired — contact us and we will refresh it' };
|
|
573
623
|
}
|
|
@@ -576,12 +626,16 @@ let QuotationService = class QuotationService {
|
|
|
576
626
|
if (action === 'accept' && !cleanName)
|
|
577
627
|
return { ok: false, reason: 'Please type your name to accept — it acts as your signature' };
|
|
578
628
|
const status = action === 'accept' ? 'accepted' : 'declined';
|
|
579
|
-
await this.db.query(`UPDATE quotation SET status=?, respondedAt=NOW(), acceptedBy=?, responseComment=?, updatedAt=NOW() WHERE id =
|
|
629
|
+
const done = await this.db.query(`UPDATE quotation SET status=?, respondedAt=NOW(), acceptedBy=?, responseComment=?, updatedAt=NOW() WHERE id = ? AND status IN ('sent','viewed')`, [status, action === 'accept' ? cleanName : '', cleanComment, q.id], { needAffected: true });
|
|
630
|
+
if (Number((done === null || done === void 0 ? void 0 : done.affectedRows) || 0) !== 1) {
|
|
631
|
+
const now = await this.getQuote(q.id);
|
|
632
|
+
return { ok: false, reason: `This quote is ${(now === null || now === void 0 ? void 0 : now.status) || 'no longer open'} and can no longer be responded to` };
|
|
633
|
+
}
|
|
580
634
|
await this.logEvent(q.id, status, action === 'accept'
|
|
581
635
|
? `Accepted by "${cleanName}"${cleanComment ? ` — ${cleanComment}` : ''}`
|
|
582
636
|
: `Declined${cleanComment ? ` — ${cleanComment}` : ''}`, q.customerEmail);
|
|
583
637
|
const cfg = await this.getConfig(q.channelId);
|
|
584
|
-
|
|
638
|
+
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)}).` +
|
|
585
639
|
(action === 'accept' ? `\nSigned: ${cleanName}` : '') +
|
|
586
640
|
(cleanComment ? `\nComment: ${cleanComment}` : '') +
|
|
587
641
|
`\n\nAdmin: open the Quotations page to ${action === 'accept' ? 'convert it to an order' : 'follow up'}.`);
|
|
@@ -601,6 +655,11 @@ let QuotationService = class QuotationService {
|
|
|
601
655
|
return { ok: false, reason: 'Quote not found' };
|
|
602
656
|
if (q.status !== 'accepted')
|
|
603
657
|
return { ok: false, reason: 'Only accepted quotes can be converted' };
|
|
658
|
+
// Claim the quote before creating anything, so a double click or a retried request cannot make two draft orders.
|
|
659
|
+
const claim = await this.db.query(`UPDATE quotation SET status='converted', updatedAt=NOW() WHERE id = ? AND status='accepted'`, [quoteId], { needAffected: true });
|
|
660
|
+
if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) !== 1)
|
|
661
|
+
return { ok: false, reason: 'This quote is already being converted' };
|
|
662
|
+
const revert = () => this.db.query(`UPDATE quotation SET status='accepted', updatedAt=NOW() WHERE id = ? AND status='converted' AND convertedOrderId IS NULL`, [quoteId]).catch(() => undefined);
|
|
604
663
|
try {
|
|
605
664
|
const draft = await this.orderService.createDraft(ctx);
|
|
606
665
|
let catalogueTotalWithTax = 0;
|
|
@@ -609,6 +668,7 @@ let QuotationService = class QuotationService {
|
|
|
609
668
|
continue;
|
|
610
669
|
const result = await this.orderService.addItemToOrder(ctx, draft.id, line.productVariantId, line.quantity);
|
|
611
670
|
if (result === null || result === void 0 ? void 0 : result.errorCode) {
|
|
671
|
+
await revert();
|
|
612
672
|
return { ok: false, reason: `Could not add "${line.description}": ${result.message || result.errorCode}` };
|
|
613
673
|
}
|
|
614
674
|
}
|
|
@@ -624,11 +684,12 @@ let QuotationService = class QuotationService {
|
|
|
624
684
|
taxLines: [],
|
|
625
685
|
});
|
|
626
686
|
}
|
|
627
|
-
await this.db.query(`UPDATE quotation SET
|
|
687
|
+
await this.db.query(`UPDATE quotation SET convertedOrderId=?, updatedAt=NOW() WHERE id = ?`, [draft.id, quoteId]);
|
|
628
688
|
await this.logEvent(quoteId, 'converted', `Draft order ${(fresh === null || fresh === void 0 ? void 0 : fresh.code) || draft.id} created`, actor);
|
|
629
689
|
return { ok: true, orderId: Number(draft.id), orderCode: fresh === null || fresh === void 0 ? void 0 : fresh.code };
|
|
630
690
|
}
|
|
631
691
|
catch (e) {
|
|
692
|
+
await revert();
|
|
632
693
|
core_1.Logger.error(`convert failed for quote ${quoteId}: ${e.message}`, loggerCtx);
|
|
633
694
|
return { ok: false, reason: e.message };
|
|
634
695
|
}
|
|
@@ -643,8 +704,17 @@ let QuotationService = class QuotationService {
|
|
|
643
704
|
}
|
|
644
705
|
hits.push(now);
|
|
645
706
|
this.requestHits.set(clientKey, hits);
|
|
646
|
-
if (this.requestHits.size > 5000)
|
|
647
|
-
|
|
707
|
+
if (this.requestHits.size > 5000) {
|
|
708
|
+
// Evict idle keys first; never wipe live counters (that let a flood reset everyone).
|
|
709
|
+
for (const [k, v] of this.requestHits)
|
|
710
|
+
if (!v.length || now - v[v.length - 1] > 3600000)
|
|
711
|
+
this.requestHits.delete(k);
|
|
712
|
+
if (this.requestHits.size > 5000) {
|
|
713
|
+
for (const k of Array.from(this.requestHits.keys()).slice(0, this.requestHits.size - 4000))
|
|
714
|
+
if (k !== clientKey)
|
|
715
|
+
this.requestHits.delete(k);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
648
718
|
return true;
|
|
649
719
|
}
|
|
650
720
|
/** Resolve a storefront channel token (or nothing) to a channel id. */
|
|
@@ -661,13 +731,13 @@ let QuotationService = class QuotationService {
|
|
|
661
731
|
}
|
|
662
732
|
}
|
|
663
733
|
/** Live catalogue lookup for requested lines (by variant id or SKU). */
|
|
664
|
-
async priceRequestedLines(channelId, lines) {
|
|
734
|
+
async priceRequestedLines(channelId, lines, lang = 'en') {
|
|
665
735
|
const ids = [...new Set(lines.map(l => Number(l.productVariantId)).filter(n => Number.isInteger(n) && n > 0))];
|
|
666
736
|
const skus = [...new Set(lines.map(l => String(l.sku || '').trim().slice(0, 64)).filter(Boolean))];
|
|
667
737
|
let rows = [];
|
|
668
738
|
if (ids.length || skus.length) {
|
|
669
739
|
const conds = [];
|
|
670
|
-
const params = [channelId];
|
|
740
|
+
const params = [lang, channelId];
|
|
671
741
|
if (ids.length) {
|
|
672
742
|
conds.push(`pv.id IN (${ids.map(() => '?').join(',')})`);
|
|
673
743
|
params.push(...ids);
|
|
@@ -676,11 +746,12 @@ let QuotationService = class QuotationService {
|
|
|
676
746
|
conds.push(`pv.sku IN (${skus.map(() => '?').join(',')})`);
|
|
677
747
|
params.push(...skus);
|
|
678
748
|
}
|
|
679
|
-
rows = await this.db.query(`SELECT pv.id AS productVariantId, pv.sku, pvt.name AS name, pvp.price AS pricePence
|
|
749
|
+
rows = await this.db.query(`SELECT pv.id AS productVariantId, pv.sku, COALESCE(pvt.name, pvt_en.name) AS name, pvp.price AS pricePence
|
|
680
750
|
FROM product_variant pv
|
|
681
|
-
JOIN product_variant_translation pvt ON pvt
|
|
682
|
-
JOIN
|
|
683
|
-
|
|
751
|
+
LEFT JOIN product_variant_translation pvt ON pvt.\`baseId\` = pv.id AND pvt.\`languageCode\` = ?
|
|
752
|
+
LEFT JOIN product_variant_translation pvt_en ON pvt_en.\`baseId\` = pv.id AND pvt_en.\`languageCode\` = 'en'
|
|
753
|
+
JOIN product_variant_price pvp ON pvp.\`variantId\` = pv.id AND pvp.\`channelId\` = ?
|
|
754
|
+
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 []; });
|
|
684
755
|
}
|
|
685
756
|
const byId = new Map();
|
|
686
757
|
const bySku = new Map();
|
|
@@ -714,7 +785,7 @@ let QuotationService = class QuotationService {
|
|
|
714
785
|
const email = String(input.email || '').trim().toLowerCase().slice(0, 190);
|
|
715
786
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
716
787
|
return { ok: false, reason: 'Please enter a valid email address' };
|
|
717
|
-
if (!this.requestAllowed(clientKey || email))
|
|
788
|
+
if (!this.requestAllowed(clientKey || email) || !this.requestAllowed(`email:${email}`))
|
|
718
789
|
return { ok: false, reason: 'Too many requests — please try again later' };
|
|
719
790
|
const message = String(input.message || '').trim().slice(0, 2000);
|
|
720
791
|
const source = String(input.source || 'storefront').trim().slice(0, 64);
|
|
@@ -725,7 +796,7 @@ let QuotationService = class QuotationService {
|
|
|
725
796
|
return { ok: false, reason: 'Tell us what you need a quote for' };
|
|
726
797
|
lines = [{ productVariantId: null, sku: '', description: `Customer enquiry — see request: ${message.slice(0, 120)}`, quantity: 1, unitPricePence: 0 }];
|
|
727
798
|
}
|
|
728
|
-
const [existingCustomer] = await this.db.query(`SELECT id FROM customer WHERE emailAddress = ? AND deletedAt IS NULL LIMIT 1`, [email]).catch(() => []);
|
|
799
|
+
const [existingCustomer] = await this.db.query(`SELECT id FROM customer WHERE \`emailAddress\` = ? AND \`deletedAt\` IS NULL LIMIT 1`, [email]).catch(() => []);
|
|
729
800
|
const q = await this.createQuote(channelId, {
|
|
730
801
|
customerId: (existingCustomer === null || existingCustomer === void 0 ? void 0 : existingCustomer.id) ? Number(existingCustomer.id) : null,
|
|
731
802
|
customerName: String(input.name || '').trim().slice(0, 190) || email,
|
|
@@ -738,9 +809,9 @@ let QuotationService = class QuotationService {
|
|
|
738
809
|
await this.logEvent(q.id, 'requested', `Requested by the customer via ${source}${message ? ` — "${message.slice(0, 200)}"` : ''}`, email);
|
|
739
810
|
const summary = lines.map(l => `${l.quantity} × ${l.description}${l.unitPricePence ? ` @ ${(0, pricing_1.formatMoney)(l.unitPricePence, q.currency)}` : ''}`).join('\n');
|
|
740
811
|
const indicative = lines.some(l => l.unitPricePence > 0) ? ` — indicative ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)} at list` : '';
|
|
741
|
-
|
|
812
|
+
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` +
|
|
742
813
|
`${summary}\n\n${message ? `Message:\n${message}\n\n` : ''}Admin: open Quotations → ${q.reference}, price it and click Send.`);
|
|
743
|
-
|
|
814
|
+
void this.sendRequestAck(q, cfg, summary).catch((e) => core_1.Logger.warn(`request acknowledgement failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx));
|
|
744
815
|
return { ok: true, reference: q.reference };
|
|
745
816
|
}
|
|
746
817
|
/** Best-effort acknowledgement to the customer (never fails the request). */
|
|
@@ -753,10 +824,8 @@ let QuotationService = class QuotationService {
|
|
|
753
824
|
};
|
|
754
825
|
const text = String(cfg.requestAckBody).replace(/\{\{\s*(\w+)\s*\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
755
826
|
try {
|
|
756
|
-
const transporter =
|
|
757
|
-
|
|
758
|
-
});
|
|
759
|
-
await transporter.sendMail({
|
|
827
|
+
const transporter = this.transporter(smtp);
|
|
828
|
+
await this.sendWithDeadline(transporter, {
|
|
760
829
|
from: cfg.businessName ? `"${cfg.businessName.replace(/"/g, '')}" <${smtp.from}>` : smtp.from,
|
|
761
830
|
to: q.customerEmail,
|
|
762
831
|
replyTo: cfg.replyTo || cfg.notifyEmail || undefined,
|
|
@@ -769,27 +838,56 @@ let QuotationService = class QuotationService {
|
|
|
769
838
|
core_1.Logger.warn(`request acknowledgement failed: ${e.message}`, loggerCtx);
|
|
770
839
|
}
|
|
771
840
|
}
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
const
|
|
775
|
-
|
|
841
|
+
async catalogueSource(channelId, lang) {
|
|
842
|
+
const key = `${channelId}:${lang}`;
|
|
843
|
+
const hit = this.catalogueSources.get(key);
|
|
844
|
+
if (hit && Date.now() - hit.at < 60000)
|
|
845
|
+
return hit.pick;
|
|
846
|
+
// Missing table (no default search plugin) or any other failure → live variant tables.
|
|
847
|
+
const langs = await this.db.query(`SELECT DISTINCT \`languageCode\` AS languageCode FROM search_index_item WHERE \`channelId\` = ? AND \`languageCode\` IN (?, 'en')`, [channelId, lang]).catch(() => []);
|
|
848
|
+
const pick = (0, catalogue_search_1.pickCatalogueSource)(langs, lang);
|
|
849
|
+
if (this.catalogueSources.size > 200)
|
|
850
|
+
this.catalogueSources.clear();
|
|
851
|
+
this.catalogueSources.set(key, { at: Date.now(), pick });
|
|
852
|
+
return pick;
|
|
853
|
+
}
|
|
854
|
+
async searchVariants(channelId, term, lang = 'en') {
|
|
855
|
+
const t = String(term || '').slice(0, 80);
|
|
856
|
+
const pick = await this.catalogueSource(channelId, lang);
|
|
857
|
+
// SKU matches by prefix so the index can help; names still match anywhere.
|
|
858
|
+
if (pick.source === 'index') {
|
|
859
|
+
// The search index already carries the translated variant name per channel and language, so no
|
|
860
|
+
// translation joins; the variant row is still checked so a stale index cannot offer a deleted or
|
|
861
|
+
// disabled variant, and the price comes from the same channel price row as the fallback query.
|
|
862
|
+
const rows = await this.db.query(`SELECT si.\`productVariantId\` AS productVariantId, si.sku, si.\`productVariantName\` AS name, pvp.price AS pricePence
|
|
863
|
+
FROM search_index_item si
|
|
864
|
+
JOIN product_variant pv ON pv.id = si.\`productVariantId\` AND pv.\`deletedAt\` IS NULL AND pv.enabled IS TRUE
|
|
865
|
+
JOIN product_variant_price pvp ON pvp.\`variantId\` = si.\`productVariantId\` AND pvp.\`channelId\` = si.\`channelId\`
|
|
866
|
+
WHERE si.\`channelId\` = ? AND si.\`languageCode\` = ? AND si.enabled IS TRUE
|
|
867
|
+
AND (si.\`productVariantName\` LIKE ? OR si.sku LIKE ?)
|
|
868
|
+
ORDER BY name ASC LIMIT 20`, [channelId, pick.languageCode, `%${t}%`, `${t}%`]).catch((e) => { core_1.Logger.warn(`variant search (index) failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx); return null; });
|
|
869
|
+
if (rows)
|
|
870
|
+
return rows;
|
|
871
|
+
}
|
|
872
|
+
return this.db.query(`SELECT pv.id AS productVariantId, pv.sku, COALESCE(pvt.name, pvt_en.name) AS name, pvp.price AS pricePence
|
|
776
873
|
FROM product_variant pv
|
|
777
|
-
JOIN product_variant_translation pvt ON pvt
|
|
778
|
-
JOIN
|
|
779
|
-
|
|
780
|
-
|
|
874
|
+
LEFT JOIN product_variant_translation pvt ON pvt.\`baseId\` = pv.id AND pvt.\`languageCode\` = ?
|
|
875
|
+
LEFT JOIN product_variant_translation pvt_en ON pvt_en.\`baseId\` = pv.id AND pvt_en.\`languageCode\` = 'en'
|
|
876
|
+
JOIN product_variant_price pvp ON pvp.\`variantId\` = pv.id AND pvp.\`channelId\` = ?
|
|
877
|
+
WHERE pv.\`deletedAt\` IS NULL AND pv.enabled IS TRUE AND (COALESCE(pvt.name, pvt_en.name) LIKE ? OR pv.sku LIKE ?)
|
|
878
|
+
ORDER BY name ASC LIMIT 20`, [lang, channelId, `%${t}%`, `${t}%`]).catch((e) => { core_1.Logger.warn(`variant search failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx); return []; });
|
|
781
879
|
}
|
|
782
880
|
/** Administrators for the "send as" picker. */
|
|
783
881
|
async searchStaff(term) {
|
|
784
882
|
const like = `%${String(term || '').slice(0, 80)}%`;
|
|
785
|
-
return this.db.query(`SELECT a
|
|
786
|
-
FROM administrator a JOIN \`user\` u ON u.id = a
|
|
787
|
-
WHERE a
|
|
788
|
-
ORDER BY a
|
|
883
|
+
return this.db.query(`SELECT a.\`firstName\` AS firstName, a.\`lastName\` AS lastName, a.\`emailAddress\` AS emailAddress, u.id AS userId
|
|
884
|
+
FROM administrator a JOIN \`user\` u ON u.id = a.\`userId\`
|
|
885
|
+
WHERE a.\`deletedAt\` IS NULL AND (a.\`firstName\` LIKE ? OR a.\`lastName\` LIKE ? OR a.\`emailAddress\` LIKE ?)
|
|
886
|
+
ORDER BY a.\`firstName\` ASC LIMIT 20`, [like, like, like]).catch(() => []);
|
|
789
887
|
}
|
|
790
888
|
/** The signed-in administrator, for defaulting the "send as" picker. */
|
|
791
889
|
async staffForUser(userId) {
|
|
792
|
-
const [row] = await this.db.query(`SELECT a
|
|
890
|
+
const [row] = await this.db.query(`SELECT a.\`firstName\` AS firstName, a.\`lastName\` AS lastName, a.\`emailAddress\` AS emailAddress FROM administrator a WHERE a.\`userId\` = ? AND a.\`deletedAt\` IS NULL LIMIT 1`, [userId]).catch(() => []);
|
|
793
891
|
if (!row)
|
|
794
892
|
return null;
|
|
795
893
|
return { name: [row.firstName, row.lastName].filter(Boolean).join(' '), email: row.emailAddress };
|
|
@@ -797,11 +895,11 @@ let QuotationService = class QuotationService {
|
|
|
797
895
|
/** Existing Vendure customers for the editor's customer picker. */
|
|
798
896
|
async searchCustomers(term) {
|
|
799
897
|
const like = `%${String(term || '').slice(0, 80)}%`;
|
|
800
|
-
return this.db.query(`SELECT id AS customerId, firstName, lastName, emailAddress, phoneNumber,
|
|
801
|
-
(SELECT company FROM address WHERE customerId = customer.id AND company <> '' LIMIT 1) AS company
|
|
898
|
+
return this.db.query(`SELECT id AS customerId, \`firstName\` AS firstName, \`lastName\` AS lastName, \`emailAddress\` AS emailAddress, \`phoneNumber\` AS phoneNumber,
|
|
899
|
+
(SELECT company FROM address WHERE \`customerId\` = customer.id AND company <> '' LIMIT 1) AS company
|
|
802
900
|
FROM customer
|
|
803
|
-
WHERE deletedAt IS NULL AND (firstName LIKE ? OR lastName LIKE ? OR emailAddress LIKE ?)
|
|
804
|
-
ORDER BY lastName ASC LIMIT 20`, [like, like, like]).catch(() => []);
|
|
901
|
+
WHERE \`deletedAt\` IS NULL AND (\`firstName\` LIKE ? OR \`lastName\` LIKE ? OR \`emailAddress\` LIKE ?)
|
|
902
|
+
ORDER BY \`lastName\` ASC LIMIT 20`, [like, like, like]).catch(() => []);
|
|
805
903
|
}
|
|
806
904
|
/** Send the real quote email to a staff address instead of the customer. */
|
|
807
905
|
async testSend(quoteId, to) {
|
|
@@ -823,7 +921,7 @@ let QuotationService = class QuotationService {
|
|
|
823
921
|
businessName: cfg.businessName || 'our team',
|
|
824
922
|
staffName: q.preparedByName || cfg.businessName || 'our team',
|
|
825
923
|
total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
|
|
826
|
-
validUntil: q.validUntil ? new Date(q.validUntil).
|
|
924
|
+
validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
|
|
827
925
|
quoteUrl: url,
|
|
828
926
|
};
|
|
829
927
|
const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
@@ -869,13 +967,12 @@ let QuotationService = class QuotationService {
|
|
|
869
967
|
const configs = await this.getAllConfigs();
|
|
870
968
|
for (const cfg of configs) {
|
|
871
969
|
if (cfg.chaserEnabled) {
|
|
872
|
-
const rows = await this.db.query(`SELECT
|
|
970
|
+
const rows = await this.db.query(`SELECT * FROM quotation
|
|
873
971
|
WHERE channelId = ? AND status = 'sent' AND chaserSentAt IS NULL
|
|
874
972
|
AND sentAt IS NOT NULL AND sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
|
|
875
973
|
AND (validUntil IS NULL OR validUntil > NOW()) LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
|
|
876
974
|
for (const r of rows) {
|
|
877
|
-
const
|
|
878
|
-
const res = await this.deliverEmail(q, cfg, 'chaser');
|
|
975
|
+
const res = await this.deliverEmail(r, cfg, 'chaser');
|
|
879
976
|
if (res.ok) {
|
|
880
977
|
await this.db.query(`UPDATE quotation SET chaserSentAt=NOW() WHERE id = ?`, [r.id]);
|
|
881
978
|
await this.logEvent(r.id, 'chaser_sent', 'Unopened-quote reminder emailed');
|
|
@@ -884,13 +981,12 @@ let QuotationService = class QuotationService {
|
|
|
884
981
|
}
|
|
885
982
|
}
|
|
886
983
|
if (cfg.expiryReminderDays > 0) {
|
|
887
|
-
const rows = await this.db.query(`SELECT
|
|
984
|
+
const rows = await this.db.query(`SELECT * FROM quotation
|
|
888
985
|
WHERE channelId = ? AND status IN ('sent','viewed') AND expiryReminderSentAt IS NULL
|
|
889
986
|
AND validUntil IS NOT NULL AND validUntil > NOW()
|
|
890
987
|
AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
|
|
891
988
|
for (const r of rows) {
|
|
892
|
-
const
|
|
893
|
-
const res = await this.deliverEmail(q, cfg, 'expiry');
|
|
989
|
+
const res = await this.deliverEmail(r, cfg, 'expiry');
|
|
894
990
|
if (res.ok) {
|
|
895
991
|
await this.db.query(`UPDATE quotation SET expiryReminderSentAt=NOW() WHERE id = ?`, [r.id]);
|
|
896
992
|
await this.logEvent(r.id, 'expiry_reminder_sent', 'Expiry reminder emailed');
|