@huloglobal/vendure-plugin-quotations 0.6.1 → 0.7.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.
- package/CHANGELOG.md +29 -0
- package/README.md +34 -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 +4 -1
- package/dist/quotation.controller.d.ts.map +1 -1
- package/dist/quotation.controller.js +30 -1
- package/dist/quotation.controller.js.map +1 -1
- package/dist/quotation.service.d.ts +28 -2
- package/dist/quotation.service.d.ts.map +1 -1
- package/dist/quotation.service.js +283 -66
- package/dist/quotation.service.js.map +1 -1
- package/dist/types.d.ts +25 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/ui/components/quotations.component.ts +35 -12
|
@@ -56,7 +56,9 @@ const PLUGIN_ID = 'vendure-plugin-quotations';
|
|
|
56
56
|
/** statuses a customer can still respond from */
|
|
57
57
|
const OPEN_STATUSES = ['sent', 'viewed'];
|
|
58
58
|
/** statuses an admin can still edit */
|
|
59
|
-
const EDITABLE_STATUSES = ['draft', 'sent', 'viewed'];
|
|
59
|
+
const EDITABLE_STATUSES = ['requested', 'draft', 'sent', 'viewed'];
|
|
60
|
+
/** public quote-request throttle: per client address, sliding hour */
|
|
61
|
+
const REQUESTS_PER_HOUR = 10;
|
|
60
62
|
let QuotationService = class QuotationService {
|
|
61
63
|
initPurchaseClaim(hooks) {
|
|
62
64
|
if (!this.purchaseClaim) {
|
|
@@ -73,6 +75,9 @@ let QuotationService = class QuotationService {
|
|
|
73
75
|
// Buy-from-admin auto-install (hooks are supplied by the controller so
|
|
74
76
|
// this file never imports the plugin class).
|
|
75
77
|
this.purchaseClaim = null;
|
|
78
|
+
this.mailer = null;
|
|
79
|
+
// ── Customer-initiated quote requests ───────────────────────────────
|
|
80
|
+
this.requestHits = new Map();
|
|
76
81
|
}
|
|
77
82
|
get db() { return (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection); }
|
|
78
83
|
setOptions(o) { this.options = o || {}; }
|
|
@@ -147,6 +152,10 @@ let QuotationService = class QuotationService {
|
|
|
147
152
|
INDEX idx_q_reference (reference),
|
|
148
153
|
INDEX idx_q_email (customerEmail)
|
|
149
154
|
)`);
|
|
155
|
+
// A duplicate reference must fail loudly rather than silently coexist.
|
|
156
|
+
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));
|
|
157
|
+
// expireOverdue / stats filter on status + validUntil without a channel.
|
|
158
|
+
await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_status_valid (status, validUntil)`).catch(() => undefined);
|
|
150
159
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS preparedByName VARCHAR(190) NOT NULL DEFAULT ''`);
|
|
151
160
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS preparedByEmail VARCHAR(190) NOT NULL DEFAULT ''`);
|
|
152
161
|
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS notifyOnView TINYINT NOT NULL DEFAULT 0`);
|
|
@@ -154,6 +163,11 @@ let QuotationService = class QuotationService {
|
|
|
154
163
|
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS phone VARCHAR(64) NOT NULL DEFAULT ''`);
|
|
155
164
|
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS addressText VARCHAR(500) NOT NULL DEFAULT ''`);
|
|
156
165
|
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS footerNote VARCHAR(500) NOT NULL DEFAULT ''`);
|
|
166
|
+
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS acceptRequests TINYINT NOT NULL DEFAULT 1`);
|
|
167
|
+
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS requestAckBody TEXT NULL`);
|
|
168
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestMessage VARCHAR(2000) NOT NULL DEFAULT ''`);
|
|
169
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestSource VARCHAR(64) NOT NULL DEFAULT ''`);
|
|
170
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestedAt DATETIME NULL`);
|
|
157
171
|
await this.db.query(`
|
|
158
172
|
CREATE TABLE IF NOT EXISTS quotation_line (
|
|
159
173
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
@@ -181,7 +195,7 @@ let QuotationService = class QuotationService {
|
|
|
181
195
|
}
|
|
182
196
|
// ── Config ──────────────────────────────────────────────────────────
|
|
183
197
|
rowToConfig(row, code) {
|
|
184
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v;
|
|
198
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v, _w;
|
|
185
199
|
return {
|
|
186
200
|
channelId: row.channelId,
|
|
187
201
|
channelCode: code,
|
|
@@ -206,10 +220,12 @@ let QuotationService = class QuotationService {
|
|
|
206
220
|
phone: (_t = row.phone) !== null && _t !== void 0 ? _t : '',
|
|
207
221
|
addressText: (_u = row.addressText) !== null && _u !== void 0 ? _u : '',
|
|
208
222
|
footerNote: (_v = row.footerNote) !== null && _v !== void 0 ? _v : '',
|
|
223
|
+
acceptRequests: !!Number((_w = row.acceptRequests) !== null && _w !== void 0 ? _w : 1),
|
|
224
|
+
requestAckBody: row.requestAckBody || types_1.DEFAULT_CONFIG.requestAckBody,
|
|
209
225
|
};
|
|
210
226
|
}
|
|
211
227
|
async getConfig(channelId) {
|
|
212
|
-
const rows = await this.db.query(`SELECT * FROM quotation_config WHERE channelId = ?`, [channelId])
|
|
228
|
+
const rows = await this.db.query(`SELECT * FROM quotation_config WHERE channelId = ?`, [channelId]);
|
|
213
229
|
return rows.length ? this.rowToConfig(rows[0]) : { ...types_1.DEFAULT_CONFIG, channelId };
|
|
214
230
|
}
|
|
215
231
|
async getAllConfigs() {
|
|
@@ -224,35 +240,44 @@ let QuotationService = class QuotationService {
|
|
|
224
240
|
async saveConfig(c) {
|
|
225
241
|
await this.db.query(`INSERT INTO quotation_config (channelId, numberPrefix, nextNumber, defaultValidityDays, defaultVatRate, defaultTerms,
|
|
226
242
|
businessName, replyTo, notifyEmail, currency, logoUrl, accentColor, chaserEnabled, chaserAfterDays,
|
|
227
|
-
expiryReminderDays, emailSubject, emailBody, notifyOnView, websiteUrl, phone, addressText, footerNote
|
|
228
|
-
|
|
243
|
+
expiryReminderDays, emailSubject, emailBody, notifyOnView, websiteUrl, phone, addressText, footerNote,
|
|
244
|
+
acceptRequests, requestAckBody)
|
|
245
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
229
246
|
ON DUPLICATE KEY UPDATE numberPrefix=VALUES(numberPrefix), defaultValidityDays=VALUES(defaultValidityDays),
|
|
230
247
|
defaultVatRate=VALUES(defaultVatRate), defaultTerms=VALUES(defaultTerms), businessName=VALUES(businessName),
|
|
231
248
|
replyTo=VALUES(replyTo), notifyEmail=VALUES(notifyEmail), currency=VALUES(currency), logoUrl=VALUES(logoUrl),
|
|
232
249
|
accentColor=VALUES(accentColor), chaserEnabled=VALUES(chaserEnabled), chaserAfterDays=VALUES(chaserAfterDays),
|
|
233
250
|
expiryReminderDays=VALUES(expiryReminderDays), emailSubject=VALUES(emailSubject), emailBody=VALUES(emailBody),
|
|
234
251
|
notifyOnView=VALUES(notifyOnView), websiteUrl=VALUES(websiteUrl), phone=VALUES(phone),
|
|
235
|
-
addressText=VALUES(addressText), footerNote=VALUES(footerNote)
|
|
236
|
-
|
|
252
|
+
addressText=VALUES(addressText), footerNote=VALUES(footerNote),
|
|
253
|
+
acceptRequests=VALUES(acceptRequests), requestAckBody=VALUES(requestAckBody)`, [c.channelId, c.numberPrefix || 'Q-', Math.max(1, Number(c.nextNumber) || 1),
|
|
254
|
+
Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, String(c.defaultTerms || '').slice(0, 4000),
|
|
237
255
|
c.businessName || '', c.replyTo || '', c.notifyEmail || '', (c.currency || 'GBP').toUpperCase().slice(0, 3),
|
|
238
256
|
c.logoUrl || '', c.accentColor || '#1d4ed8', c.chaserEnabled ? 1 : 0, Math.max(1, Number(c.chaserAfterDays) || 3),
|
|
239
|
-
Math.max(0, Number(c.expiryReminderDays) || 0), c.emailSubject || '', c.emailBody || '', c.notifyOnView ? 1 : 0,
|
|
257
|
+
Math.max(0, Number(c.expiryReminderDays) || 0), String(c.emailSubject || '').slice(0, 300), String(c.emailBody || '').slice(0, 4000), c.notifyOnView ? 1 : 0,
|
|
240
258
|
String(c.websiteUrl || '').slice(0, 300), String(c.phone || '').slice(0, 64),
|
|
241
|
-
String(c.addressText || '').slice(0, 500), String(c.footerNote || '').slice(0, 500)
|
|
259
|
+
String(c.addressText || '').slice(0, 500), String(c.footerNote || '').slice(0, 500),
|
|
260
|
+
c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000)], { conflictColumns: ['channelId'] });
|
|
242
261
|
}
|
|
243
262
|
// ── Reference numbering ─────────────────────────────────────────────
|
|
244
263
|
/** Atomically claims the next quote number for a channel. */
|
|
245
264
|
async nextReference(channelId) {
|
|
246
|
-
var _a;
|
|
247
265
|
const cfg = await this.getConfig(channelId);
|
|
248
|
-
//
|
|
266
|
+
// Make sure the config row exists (no-op when it does).
|
|
249
267
|
await this.db.query(`INSERT INTO quotation_config (channelId, nextNumber) VALUES (?, ?)
|
|
250
|
-
ON DUPLICATE KEY UPDATE nextNumber = nextNumber
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
268
|
+
ON DUPLICATE KEY UPDATE nextNumber = nextNumber`, [channelId, cfg.nextNumber], { conflictColumns: ['channelId'] });
|
|
269
|
+
// Claim a number with a compare-and-set so two concurrent creates can
|
|
270
|
+
// never read the same value (portable across MariaDB and Postgres).
|
|
271
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
272
|
+
const [row] = await this.db.query(`SELECT numberPrefix, nextNumber FROM quotation_config WHERE channelId = ?`, [channelId]);
|
|
273
|
+
const current = Number((row === null || row === void 0 ? void 0 : row.nextNumber) || 1);
|
|
274
|
+
const res = await this.db.query(`UPDATE quotation_config SET nextNumber = ? WHERE channelId = ? AND nextNumber = ?`, [current + 1, channelId, current], { needAffected: true });
|
|
275
|
+
if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
|
|
276
|
+
const prefix = (row === null || row === void 0 ? void 0 : row.numberPrefix) || cfg.numberPrefix || 'Q-';
|
|
277
|
+
return `${prefix}${new Date().getFullYear()}-${String(current).padStart(4, '0')}`;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
throw new Error('Could not allocate a quote number — please try again');
|
|
256
281
|
}
|
|
257
282
|
// ── CRUD ────────────────────────────────────────────────────────────
|
|
258
283
|
sanitizeLines(lines) {
|
|
@@ -269,7 +294,7 @@ let QuotationService = class QuotationService {
|
|
|
269
294
|
}));
|
|
270
295
|
}
|
|
271
296
|
async createQuote(channelId, input, actor) {
|
|
272
|
-
var _a, _b;
|
|
297
|
+
var _a, _b, _c;
|
|
273
298
|
const cfg = await this.getConfig(channelId);
|
|
274
299
|
const lines = this.sanitizeLines(input.lines);
|
|
275
300
|
if (!lines.length)
|
|
@@ -288,7 +313,8 @@ let QuotationService = class QuotationService {
|
|
|
288
313
|
VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
|
|
289
314
|
String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
|
|
290
315
|
String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
|
|
291
|
-
String(input.notes || ''), String(input.internalNotes || ''), (_b = input.terms) !== null && _b !== void 0 ? _b : cfg.defaultTerms
|
|
316
|
+
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),
|
|
317
|
+
vatRate, discountType, discountValue, (input.currency || cfg.currency || 'GBP').toUpperCase().slice(0, 3),
|
|
292
318
|
validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
|
|
293
319
|
actor.slice(0, 190),
|
|
294
320
|
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190)], { needInsertId: true });
|
|
@@ -299,15 +325,17 @@ let QuotationService = class QuotationService {
|
|
|
299
325
|
}
|
|
300
326
|
async replaceLines(quoteId, lines) {
|
|
301
327
|
await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
328
|
+
if (!lines.length)
|
|
329
|
+
return;
|
|
330
|
+
// One statement for all lines: the window in which a quote has partial lines is a single INSERT.
|
|
331
|
+
const placeholders = lines.map(() => '(?, ?, ?, ?, ?, ?, ?, ?, ?)').join(',');
|
|
332
|
+
const params = lines.flatMap((l, pos) => [quoteId, pos, l.productVariantId || null, l.sku || '', l.description, l.quantity,
|
|
333
|
+
l.unitPricePence, l.lineDiscountPercent || 0, (0, pricing_1.lineTotal)(l)]);
|
|
334
|
+
await this.db.query(`INSERT INTO quotation_line (quoteId, position, productVariantId, sku, description, quantity, unitPricePence, lineDiscountPercent, totalPence)
|
|
335
|
+
VALUES ${placeholders}`, params);
|
|
308
336
|
}
|
|
309
337
|
async updateQuote(quoteId, input, actor) {
|
|
310
|
-
var _a, _b;
|
|
338
|
+
var _a, _b, _c;
|
|
311
339
|
const existing = await this.getQuote(quoteId);
|
|
312
340
|
if (!existing)
|
|
313
341
|
throw new Error('Quote not found');
|
|
@@ -321,16 +349,20 @@ let QuotationService = class QuotationService {
|
|
|
321
349
|
const discountType = input.discountType || 'none';
|
|
322
350
|
const discountValue = Number(input.discountValue || 0);
|
|
323
351
|
const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
|
|
352
|
+
// Validity only moves when the editor actually sets it; a typo fix must not push expiry out.
|
|
353
|
+
const newValidity = Number(input.validityDays);
|
|
354
|
+
const touchValidity = Number.isFinite(newValidity) && newValidity > 0;
|
|
324
355
|
await this.db.query(`UPDATE quotation SET customerId=?, customerName=?, customerEmail=?, customerCompany=?, customerPhone=?,
|
|
325
356
|
notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
|
|
326
|
-
validUntil
|
|
357
|
+
validUntil=${touchValidity ? 'DATE_ADD(NOW(), INTERVAL ? DAY)' : 'validUntil'},
|
|
327
358
|
subTotalPence=?, discountPence=?, vatPence=?, totalPence=?,
|
|
328
359
|
preparedByName=?, preparedByEmail=?, updatedAt=NOW()
|
|
329
360
|
WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
|
|
330
361
|
String(input.customerEmail || '').toLowerCase().slice(0, 190), String(input.customerCompany || '').slice(0, 190),
|
|
331
|
-
String(input.customerPhone || '').slice(0, 64), String(input.notes || ''), String(input.internalNotes || '')
|
|
362
|
+
String(input.customerPhone || '').slice(0, 64), String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000),
|
|
363
|
+
String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms) !== null && _c !== void 0 ? _c : '').slice(0, 20000), vatRate, discountType, discountValue,
|
|
332
364
|
(input.currency || existing.currency).toUpperCase().slice(0, 3),
|
|
333
|
-
Math.max(1,
|
|
365
|
+
...(touchValidity ? [Math.max(1, Math.floor(newValidity))] : []),
|
|
334
366
|
totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
|
|
335
367
|
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
|
|
336
368
|
quoteId]);
|
|
@@ -342,8 +374,8 @@ let QuotationService = class QuotationService {
|
|
|
342
374
|
const q = await this.getQuote(quoteId);
|
|
343
375
|
if (!q)
|
|
344
376
|
return;
|
|
345
|
-
if (q.status !== 'draft')
|
|
346
|
-
throw new Error('Only draft quotes can be deleted — cancel instead');
|
|
377
|
+
if (q.status !== 'draft' && q.status !== 'requested')
|
|
378
|
+
throw new Error('Only draft quotes and requests can be deleted — cancel instead');
|
|
347
379
|
await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
|
|
348
380
|
await this.db.query(`DELETE FROM quotation_event WHERE quoteId = ?`, [quoteId]);
|
|
349
381
|
await this.db.query(`DELETE FROM quotation WHERE id = ?`, [quoteId]);
|
|
@@ -375,7 +407,9 @@ let QuotationService = class QuotationService {
|
|
|
375
407
|
}, actor);
|
|
376
408
|
if (asRevision) {
|
|
377
409
|
await this.db.query(`UPDATE quotation SET revisionOf = ? WHERE id = ?`, [quoteId, created.id]);
|
|
378
|
-
|
|
410
|
+
// The superseded quote must not remain acceptable alongside its revision.
|
|
411
|
+
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 });
|
|
412
|
+
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);
|
|
379
413
|
}
|
|
380
414
|
else {
|
|
381
415
|
await this.logEvent(quoteId, 'duplicated', `Duplicated as ${created.reference}`, actor);
|
|
@@ -444,6 +478,35 @@ let QuotationService = class QuotationService {
|
|
|
444
478
|
}
|
|
445
479
|
return null;
|
|
446
480
|
}
|
|
481
|
+
/** One pooled transport per SMTP configuration, with sane timeouts (nodemailer defaults are 2 min / 10 min). */
|
|
482
|
+
transporter(smtp) {
|
|
483
|
+
var _a, _b, _c, _d;
|
|
484
|
+
const key = `${smtp.host}:${smtp.port}:${smtp.user}`;
|
|
485
|
+
if (((_a = this.mailer) === null || _a === void 0 ? void 0 : _a.key) !== key) {
|
|
486
|
+
try {
|
|
487
|
+
(_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);
|
|
488
|
+
}
|
|
489
|
+
catch { /* ignore */ }
|
|
490
|
+
this.mailer = {
|
|
491
|
+
key,
|
|
492
|
+
transport: nodemailer.createTransport({
|
|
493
|
+
host: smtp.host, port: smtp.port, secure: smtp.port === 465,
|
|
494
|
+
auth: { user: smtp.user, pass: smtp.pass },
|
|
495
|
+
pool: true, maxConnections: 2, maxMessages: 100,
|
|
496
|
+
connectionTimeout: 10000, greetingTimeout: 10000, socketTimeout: 30000,
|
|
497
|
+
}),
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
return this.mailer.transport;
|
|
501
|
+
}
|
|
502
|
+
/** sendMail with a hard deadline so a stuck SMTP host cannot hold a request or the cron. */
|
|
503
|
+
sendWithDeadline(transport, message, ms = 30000) {
|
|
504
|
+
let timer;
|
|
505
|
+
return Promise.race([
|
|
506
|
+
transport.sendMail(message).then(() => undefined),
|
|
507
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`SMTP send timed out after ${ms / 1000}s`)), ms); }),
|
|
508
|
+
]).finally(() => clearTimeout(timer));
|
|
509
|
+
}
|
|
447
510
|
async sendQuote(quoteId, actor) {
|
|
448
511
|
const q = await this.getQuote(quoteId);
|
|
449
512
|
if (!q)
|
|
@@ -472,7 +535,7 @@ let QuotationService = class QuotationService {
|
|
|
472
535
|
businessName: cfg.businessName || 'our team',
|
|
473
536
|
staffName: q.preparedByName || cfg.businessName || 'our team',
|
|
474
537
|
total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
|
|
475
|
-
validUntil: q.validUntil ? new Date(q.validUntil).
|
|
538
|
+
validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
|
|
476
539
|
quoteUrl: url,
|
|
477
540
|
};
|
|
478
541
|
let subject = cfg.emailSubject || types_1.DEFAULT_CONFIG.emailSubject;
|
|
@@ -487,16 +550,13 @@ let QuotationService = class QuotationService {
|
|
|
487
550
|
}
|
|
488
551
|
const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
489
552
|
try {
|
|
490
|
-
const transporter =
|
|
491
|
-
host: smtp.host, port: smtp.port, secure: smtp.port === 465,
|
|
492
|
-
auth: { user: smtp.user, pass: smtp.pass },
|
|
493
|
-
});
|
|
553
|
+
const transporter = this.transporter(smtp);
|
|
494
554
|
// Send as the member of staff who prepared the quote: their name
|
|
495
555
|
// fronts the From header and replies go straight to them.
|
|
496
556
|
const senderName = q.preparedByName
|
|
497
557
|
? (cfg.businessName ? `${q.preparedByName} — ${cfg.businessName}` : q.preparedByName)
|
|
498
558
|
: (cfg.businessName || '');
|
|
499
|
-
await
|
|
559
|
+
await this.sendWithDeadline(transporter, {
|
|
500
560
|
from: senderName ? `"${senderName.replace(/"/g, "'")}" <${smtp.from}>` : smtp.from,
|
|
501
561
|
to: overrideTo || q.customerEmail,
|
|
502
562
|
replyTo: q.preparedByEmail || cfg.replyTo || undefined,
|
|
@@ -520,11 +580,7 @@ let QuotationService = class QuotationService {
|
|
|
520
580
|
if (!smtp || !to)
|
|
521
581
|
return;
|
|
522
582
|
try {
|
|
523
|
-
|
|
524
|
-
host: smtp.host, port: smtp.port, secure: smtp.port === 465,
|
|
525
|
-
auth: { user: smtp.user, pass: smtp.pass },
|
|
526
|
-
});
|
|
527
|
-
await transporter.sendMail({ from: smtp.from, to, subject, text });
|
|
583
|
+
await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to, subject, text });
|
|
528
584
|
}
|
|
529
585
|
catch (e) {
|
|
530
586
|
core_1.Logger.warn(`merchant notification failed: ${e.message}`, loggerCtx);
|
|
@@ -536,12 +592,15 @@ let QuotationService = class QuotationService {
|
|
|
536
592
|
if (!q)
|
|
537
593
|
return null;
|
|
538
594
|
if (q.status === 'sent') {
|
|
539
|
-
|
|
540
|
-
await this.
|
|
595
|
+
// Conditional so two parallel first views produce one event and one notification.
|
|
596
|
+
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 });
|
|
541
597
|
q.status = 'viewed';
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
598
|
+
if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
|
|
599
|
+
await this.logEvent(q.id, 'viewed', 'Opened by the customer', q.customerEmail);
|
|
600
|
+
const cfg = await this.getConfig(q.channelId);
|
|
601
|
+
if (cfg.notifyOnView) {
|
|
602
|
+
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.`);
|
|
603
|
+
}
|
|
545
604
|
}
|
|
546
605
|
}
|
|
547
606
|
return q;
|
|
@@ -552,8 +611,9 @@ let QuotationService = class QuotationService {
|
|
|
552
611
|
return { ok: false, reason: 'Quote not found' };
|
|
553
612
|
if (!OPEN_STATUSES.includes(q.status))
|
|
554
613
|
return { ok: false, reason: `This quote is ${q.status} and can no longer be responded to` };
|
|
555
|
-
|
|
556
|
-
|
|
614
|
+
// One clock decides expiry: the database's, the same one the hourly sweep uses.
|
|
615
|
+
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 });
|
|
616
|
+
if (Number((expired === null || expired === void 0 ? void 0 : expired.affectedRows) || 0) === 1) {
|
|
557
617
|
await this.logEvent(q.id, 'expired', 'Response attempted after expiry');
|
|
558
618
|
return { ok: false, reason: 'This quote has expired — contact us and we will refresh it' };
|
|
559
619
|
}
|
|
@@ -562,12 +622,16 @@ let QuotationService = class QuotationService {
|
|
|
562
622
|
if (action === 'accept' && !cleanName)
|
|
563
623
|
return { ok: false, reason: 'Please type your name to accept — it acts as your signature' };
|
|
564
624
|
const status = action === 'accept' ? 'accepted' : 'declined';
|
|
565
|
-
await this.db.query(`UPDATE quotation SET status=?, respondedAt=NOW(), acceptedBy=?, responseComment=?, updatedAt=NOW() WHERE id =
|
|
625
|
+
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 });
|
|
626
|
+
if (Number((done === null || done === void 0 ? void 0 : done.affectedRows) || 0) !== 1) {
|
|
627
|
+
const now = await this.getQuote(q.id);
|
|
628
|
+
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` };
|
|
629
|
+
}
|
|
566
630
|
await this.logEvent(q.id, status, action === 'accept'
|
|
567
631
|
? `Accepted by "${cleanName}"${cleanComment ? ` — ${cleanComment}` : ''}`
|
|
568
632
|
: `Declined${cleanComment ? ` — ${cleanComment}` : ''}`, q.customerEmail);
|
|
569
633
|
const cfg = await this.getConfig(q.channelId);
|
|
570
|
-
|
|
634
|
+
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)}).` +
|
|
571
635
|
(action === 'accept' ? `\nSigned: ${cleanName}` : '') +
|
|
572
636
|
(cleanComment ? `\nComment: ${cleanComment}` : '') +
|
|
573
637
|
`\n\nAdmin: open the Quotations page to ${action === 'accept' ? 'convert it to an order' : 'follow up'}.`);
|
|
@@ -587,6 +651,11 @@ let QuotationService = class QuotationService {
|
|
|
587
651
|
return { ok: false, reason: 'Quote not found' };
|
|
588
652
|
if (q.status !== 'accepted')
|
|
589
653
|
return { ok: false, reason: 'Only accepted quotes can be converted' };
|
|
654
|
+
// Claim the quote before creating anything, so a double click or a retried request cannot make two draft orders.
|
|
655
|
+
const claim = await this.db.query(`UPDATE quotation SET status='converted', updatedAt=NOW() WHERE id = ? AND status='accepted'`, [quoteId], { needAffected: true });
|
|
656
|
+
if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) !== 1)
|
|
657
|
+
return { ok: false, reason: 'This quote is already being converted' };
|
|
658
|
+
const revert = () => this.db.query(`UPDATE quotation SET status='accepted', updatedAt=NOW() WHERE id = ? AND status='converted' AND convertedOrderId IS NULL`, [quoteId]).catch(() => undefined);
|
|
590
659
|
try {
|
|
591
660
|
const draft = await this.orderService.createDraft(ctx);
|
|
592
661
|
let catalogueTotalWithTax = 0;
|
|
@@ -595,6 +664,7 @@ let QuotationService = class QuotationService {
|
|
|
595
664
|
continue;
|
|
596
665
|
const result = await this.orderService.addItemToOrder(ctx, draft.id, line.productVariantId, line.quantity);
|
|
597
666
|
if (result === null || result === void 0 ? void 0 : result.errorCode) {
|
|
667
|
+
await revert();
|
|
598
668
|
return { ok: false, reason: `Could not add "${line.description}": ${result.message || result.errorCode}` };
|
|
599
669
|
}
|
|
600
670
|
}
|
|
@@ -610,24 +680,171 @@ let QuotationService = class QuotationService {
|
|
|
610
680
|
taxLines: [],
|
|
611
681
|
});
|
|
612
682
|
}
|
|
613
|
-
await this.db.query(`UPDATE quotation SET
|
|
683
|
+
await this.db.query(`UPDATE quotation SET convertedOrderId=?, updatedAt=NOW() WHERE id = ?`, [draft.id, quoteId]);
|
|
614
684
|
await this.logEvent(quoteId, 'converted', `Draft order ${(fresh === null || fresh === void 0 ? void 0 : fresh.code) || draft.id} created`, actor);
|
|
615
685
|
return { ok: true, orderId: Number(draft.id), orderCode: fresh === null || fresh === void 0 ? void 0 : fresh.code };
|
|
616
686
|
}
|
|
617
687
|
catch (e) {
|
|
688
|
+
await revert();
|
|
618
689
|
core_1.Logger.error(`convert failed for quote ${quoteId}: ${e.message}`, loggerCtx);
|
|
619
690
|
return { ok: false, reason: e.message };
|
|
620
691
|
}
|
|
621
692
|
}
|
|
693
|
+
/** Sliding-window throttle for the public request endpoint. */
|
|
694
|
+
requestAllowed(clientKey) {
|
|
695
|
+
const now = Date.now();
|
|
696
|
+
const hits = (this.requestHits.get(clientKey) || []).filter(t => now - t < 3600000);
|
|
697
|
+
if (hits.length >= REQUESTS_PER_HOUR) {
|
|
698
|
+
this.requestHits.set(clientKey, hits);
|
|
699
|
+
return false;
|
|
700
|
+
}
|
|
701
|
+
hits.push(now);
|
|
702
|
+
this.requestHits.set(clientKey, hits);
|
|
703
|
+
if (this.requestHits.size > 5000) {
|
|
704
|
+
// Evict idle keys first; never wipe live counters (that let a flood reset everyone).
|
|
705
|
+
for (const [k, v] of this.requestHits)
|
|
706
|
+
if (!v.length || now - v[v.length - 1] > 3600000)
|
|
707
|
+
this.requestHits.delete(k);
|
|
708
|
+
if (this.requestHits.size > 5000) {
|
|
709
|
+
for (const k of Array.from(this.requestHits.keys()).slice(0, this.requestHits.size - 4000))
|
|
710
|
+
if (k !== clientKey)
|
|
711
|
+
this.requestHits.delete(k);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return true;
|
|
715
|
+
}
|
|
716
|
+
/** Resolve a storefront channel token (or nothing) to a channel id. */
|
|
717
|
+
async channelIdForToken(token) {
|
|
718
|
+
try {
|
|
719
|
+
const ch = token
|
|
720
|
+
? await this.channelService.getChannelFromToken(token)
|
|
721
|
+
: await this.channelService.getDefaultChannel();
|
|
722
|
+
return Number(ch === null || ch === void 0 ? void 0 : ch.id) || 1;
|
|
723
|
+
}
|
|
724
|
+
catch {
|
|
725
|
+
const ch = await this.channelService.getDefaultChannel().catch(() => null);
|
|
726
|
+
return Number(ch === null || ch === void 0 ? void 0 : ch.id) || 1;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/** Live catalogue lookup for requested lines (by variant id or SKU). */
|
|
730
|
+
async priceRequestedLines(channelId, lines, lang = 'en') {
|
|
731
|
+
const ids = [...new Set(lines.map(l => Number(l.productVariantId)).filter(n => Number.isInteger(n) && n > 0))];
|
|
732
|
+
const skus = [...new Set(lines.map(l => String(l.sku || '').trim().slice(0, 64)).filter(Boolean))];
|
|
733
|
+
let rows = [];
|
|
734
|
+
if (ids.length || skus.length) {
|
|
735
|
+
const conds = [];
|
|
736
|
+
const params = [lang, channelId];
|
|
737
|
+
if (ids.length) {
|
|
738
|
+
conds.push(`pv.id IN (${ids.map(() => '?').join(',')})`);
|
|
739
|
+
params.push(...ids);
|
|
740
|
+
}
|
|
741
|
+
if (skus.length) {
|
|
742
|
+
conds.push(`pv.sku IN (${skus.map(() => '?').join(',')})`);
|
|
743
|
+
params.push(...skus);
|
|
744
|
+
}
|
|
745
|
+
rows = await this.db.query(`SELECT pv.id AS productVariantId, pv.sku, COALESCE(pvt.name, pvt_en.name) AS name, pvp.price AS pricePence
|
|
746
|
+
FROM product_variant pv
|
|
747
|
+
LEFT JOIN product_variant_translation pvt ON pvt.baseId = pv.id AND pvt.languageCode = ?
|
|
748
|
+
LEFT JOIN product_variant_translation pvt_en ON pvt_en.baseId = pv.id AND pvt_en.languageCode = 'en'
|
|
749
|
+
JOIN product_variant_price pvp ON pvp.variantId = pv.id AND pvp.channelId = ?
|
|
750
|
+
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 []; });
|
|
751
|
+
}
|
|
752
|
+
const byId = new Map();
|
|
753
|
+
const bySku = new Map();
|
|
754
|
+
for (const r of rows) {
|
|
755
|
+
if (!byId.has(Number(r.productVariantId)))
|
|
756
|
+
byId.set(Number(r.productVariantId), r);
|
|
757
|
+
if (r.sku && !bySku.has(String(r.sku)))
|
|
758
|
+
bySku.set(String(r.sku), r);
|
|
759
|
+
}
|
|
760
|
+
return lines.map(l => {
|
|
761
|
+
const hit = byId.get(Number(l.productVariantId)) || bySku.get(String(l.sku || '').trim());
|
|
762
|
+
const quantity = Math.max(1, Math.min(100000, Math.floor(Number(l.quantity) || 1)));
|
|
763
|
+
return hit
|
|
764
|
+
? { productVariantId: Number(hit.productVariantId), sku: String(hit.sku || ''), description: String(hit.name || l.description || hit.sku), quantity, unitPricePence: Math.max(0, Math.floor(Number(hit.pricePence) || 0)) }
|
|
765
|
+
: { productVariantId: null, sku: String(l.sku || '').slice(0, 64), description: String(l.description || l.sku || 'Requested item').slice(0, 500), quantity, unitPricePence: 0 };
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Public entry point: a storefront (or any site) posts what the customer
|
|
770
|
+
* wants; a `requested` quote lands in the admin inbox with catalogue
|
|
771
|
+
* lines pre-priced at list, the merchant is notified and the customer
|
|
772
|
+
* gets an acknowledgement carrying the reference. Never throws for
|
|
773
|
+
* bots: honeypot hits look successful and persist nothing.
|
|
774
|
+
*/
|
|
775
|
+
async createRequest(channelId, input, clientKey) {
|
|
776
|
+
const cfg = await this.getConfig(channelId);
|
|
777
|
+
if (!cfg.acceptRequests)
|
|
778
|
+
return { ok: false, reason: 'Quote requests are not accepted on this channel' };
|
|
779
|
+
if (input.website)
|
|
780
|
+
return { ok: true, reference: '' };
|
|
781
|
+
const email = String(input.email || '').trim().toLowerCase().slice(0, 190);
|
|
782
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
783
|
+
return { ok: false, reason: 'Please enter a valid email address' };
|
|
784
|
+
if (!this.requestAllowed(clientKey || email) || !this.requestAllowed(`email:${email}`))
|
|
785
|
+
return { ok: false, reason: 'Too many requests — please try again later' };
|
|
786
|
+
const message = String(input.message || '').trim().slice(0, 2000);
|
|
787
|
+
const source = String(input.source || 'storefront').trim().slice(0, 64);
|
|
788
|
+
const rawLines = Array.isArray(input.lines) ? input.lines.slice(0, 50) : [];
|
|
789
|
+
let lines = await this.priceRequestedLines(channelId, rawLines.filter(l => l && (l.productVariantId || l.sku || l.description)));
|
|
790
|
+
if (!lines.length) {
|
|
791
|
+
if (!message)
|
|
792
|
+
return { ok: false, reason: 'Tell us what you need a quote for' };
|
|
793
|
+
lines = [{ productVariantId: null, sku: '', description: `Customer enquiry — see request: ${message.slice(0, 120)}`, quantity: 1, unitPricePence: 0 }];
|
|
794
|
+
}
|
|
795
|
+
const [existingCustomer] = await this.db.query(`SELECT id FROM customer WHERE emailAddress = ? AND deletedAt IS NULL LIMIT 1`, [email]).catch(() => []);
|
|
796
|
+
const q = await this.createQuote(channelId, {
|
|
797
|
+
customerId: (existingCustomer === null || existingCustomer === void 0 ? void 0 : existingCustomer.id) ? Number(existingCustomer.id) : null,
|
|
798
|
+
customerName: String(input.name || '').trim().slice(0, 190) || email,
|
|
799
|
+
customerEmail: email,
|
|
800
|
+
customerCompany: String(input.company || '').trim().slice(0, 190),
|
|
801
|
+
customerPhone: String(input.phone || '').trim().slice(0, 64),
|
|
802
|
+
lines,
|
|
803
|
+
}, `customer:${email}`);
|
|
804
|
+
await this.db.query(`UPDATE quotation SET status='requested', requestMessage=?, requestSource=?, requestedAt=NOW(), updatedAt=NOW() WHERE id = ?`, [message, source, q.id]);
|
|
805
|
+
await this.logEvent(q.id, 'requested', `Requested by the customer via ${source}${message ? ` — "${message.slice(0, 200)}"` : ''}`, email);
|
|
806
|
+
const summary = lines.map(l => `${l.quantity} × ${l.description}${l.unitPricePence ? ` @ ${(0, pricing_1.formatMoney)(l.unitPricePence, q.currency)}` : ''}`).join('\n');
|
|
807
|
+
const indicative = lines.some(l => l.unitPricePence > 0) ? ` — indicative ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)} at list` : '';
|
|
808
|
+
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` +
|
|
809
|
+
`${summary}\n\n${message ? `Message:\n${message}\n\n` : ''}Admin: open Quotations → ${q.reference}, price it and click Send.`);
|
|
810
|
+
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));
|
|
811
|
+
return { ok: true, reference: q.reference };
|
|
812
|
+
}
|
|
813
|
+
/** Best-effort acknowledgement to the customer (never fails the request). */
|
|
814
|
+
async sendRequestAck(q, cfg, summary) {
|
|
815
|
+
const smtp = this.smtpSettings();
|
|
816
|
+
if (!smtp || !cfg.requestAckBody)
|
|
817
|
+
return;
|
|
818
|
+
const vars = {
|
|
819
|
+
customerName: q.customerName || 'there', reference: q.reference, businessName: cfg.businessName || '', summary,
|
|
820
|
+
};
|
|
821
|
+
const text = String(cfg.requestAckBody).replace(/\{\{\s*(\w+)\s*\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
822
|
+
try {
|
|
823
|
+
const transporter = this.transporter(smtp);
|
|
824
|
+
await this.sendWithDeadline(transporter, {
|
|
825
|
+
from: cfg.businessName ? `"${cfg.businessName.replace(/"/g, '')}" <${smtp.from}>` : smtp.from,
|
|
826
|
+
to: q.customerEmail,
|
|
827
|
+
replyTo: cfg.replyTo || cfg.notifyEmail || undefined,
|
|
828
|
+
subject: `We've received your quote request (${q.reference})`,
|
|
829
|
+
text,
|
|
830
|
+
});
|
|
831
|
+
await this.logEvent(q.id, 'ack', `Acknowledgement emailed to ${q.customerEmail}`);
|
|
832
|
+
}
|
|
833
|
+
catch (e) {
|
|
834
|
+
core_1.Logger.warn(`request acknowledgement failed: ${e.message}`, loggerCtx);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
622
837
|
// ── Product search for the editor ───────────────────────────────────
|
|
623
|
-
async searchVariants(channelId, term) {
|
|
624
|
-
const
|
|
625
|
-
|
|
838
|
+
async searchVariants(channelId, term, lang = 'en') {
|
|
839
|
+
const t = String(term || '').slice(0, 80);
|
|
840
|
+
// SKU matches by prefix so the index can help; names still match anywhere.
|
|
841
|
+
return this.db.query(`SELECT pv.id AS productVariantId, pv.sku, COALESCE(pvt.name, pvt_en.name) AS name, pvp.price AS pricePence
|
|
626
842
|
FROM product_variant pv
|
|
627
|
-
JOIN product_variant_translation pvt ON pvt.baseId = pv.id AND pvt.languageCode =
|
|
843
|
+
LEFT JOIN product_variant_translation pvt ON pvt.baseId = pv.id AND pvt.languageCode = ?
|
|
844
|
+
LEFT JOIN product_variant_translation pvt_en ON pvt_en.baseId = pv.id AND pvt_en.languageCode = 'en'
|
|
628
845
|
JOIN product_variant_price pvp ON pvp.variantId = pv.id AND pvp.channelId = ?
|
|
629
|
-
WHERE pv.deletedAt IS NULL AND pv.enabled
|
|
630
|
-
ORDER BY
|
|
846
|
+
WHERE pv.deletedAt IS NULL AND pv.enabled IS TRUE AND (COALESCE(pvt.name, pvt_en.name) LIKE ? OR pv.sku LIKE ?)
|
|
847
|
+
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 []; });
|
|
631
848
|
}
|
|
632
849
|
/** Administrators for the "send as" picker. */
|
|
633
850
|
async searchStaff(term) {
|
|
@@ -673,7 +890,7 @@ let QuotationService = class QuotationService {
|
|
|
673
890
|
businessName: cfg.businessName || 'our team',
|
|
674
891
|
staffName: q.preparedByName || cfg.businessName || 'our team',
|
|
675
892
|
total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
|
|
676
|
-
validUntil: q.validUntil ? new Date(q.validUntil).
|
|
893
|
+
validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
|
|
677
894
|
quoteUrl: url,
|
|
678
895
|
};
|
|
679
896
|
const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
@@ -719,13 +936,12 @@ let QuotationService = class QuotationService {
|
|
|
719
936
|
const configs = await this.getAllConfigs();
|
|
720
937
|
for (const cfg of configs) {
|
|
721
938
|
if (cfg.chaserEnabled) {
|
|
722
|
-
const rows = await this.db.query(`SELECT
|
|
939
|
+
const rows = await this.db.query(`SELECT * FROM quotation
|
|
723
940
|
WHERE channelId = ? AND status = 'sent' AND chaserSentAt IS NULL
|
|
724
941
|
AND sentAt IS NOT NULL AND sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
|
|
725
942
|
AND (validUntil IS NULL OR validUntil > NOW()) LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
|
|
726
943
|
for (const r of rows) {
|
|
727
|
-
const
|
|
728
|
-
const res = await this.deliverEmail(q, cfg, 'chaser');
|
|
944
|
+
const res = await this.deliverEmail(r, cfg, 'chaser');
|
|
729
945
|
if (res.ok) {
|
|
730
946
|
await this.db.query(`UPDATE quotation SET chaserSentAt=NOW() WHERE id = ?`, [r.id]);
|
|
731
947
|
await this.logEvent(r.id, 'chaser_sent', 'Unopened-quote reminder emailed');
|
|
@@ -734,13 +950,12 @@ let QuotationService = class QuotationService {
|
|
|
734
950
|
}
|
|
735
951
|
}
|
|
736
952
|
if (cfg.expiryReminderDays > 0) {
|
|
737
|
-
const rows = await this.db.query(`SELECT
|
|
953
|
+
const rows = await this.db.query(`SELECT * FROM quotation
|
|
738
954
|
WHERE channelId = ? AND status IN ('sent','viewed') AND expiryReminderSentAt IS NULL
|
|
739
955
|
AND validUntil IS NOT NULL AND validUntil > NOW()
|
|
740
956
|
AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
|
|
741
957
|
for (const r of rows) {
|
|
742
|
-
const
|
|
743
|
-
const res = await this.deliverEmail(q, cfg, 'expiry');
|
|
958
|
+
const res = await this.deliverEmail(r, cfg, 'expiry');
|
|
744
959
|
if (res.ok) {
|
|
745
960
|
await this.db.query(`UPDATE quotation SET expiryReminderSentAt=NOW() WHERE id = ?`, [r.id]);
|
|
746
961
|
await this.logEvent(r.id, 'expiry_reminder_sent', 'Expiry reminder emailed');
|
|
@@ -761,8 +976,10 @@ let QuotationService = class QuotationService {
|
|
|
761
976
|
const [last30] = await this.db.query(`SELECT COUNT(*) AS sent, SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won
|
|
762
977
|
FROM quotation ${where ? where + ' AND' : 'WHERE'} sentAt > DATE_SUB(NOW(), INTERVAL 30 DAY)`, params);
|
|
763
978
|
const sent30 = Number((last30 === null || last30 === void 0 ? void 0 : last30.sent) || 0);
|
|
979
|
+
const [req] = await this.db.query(`SELECT COUNT(*) AS n, MIN(requestedAt) AS oldest FROM quotation ${where ? where + ' AND' : 'WHERE'} status = 'requested'`, params);
|
|
764
980
|
return {
|
|
765
981
|
byStatus,
|
|
982
|
+
requests: { open: Number((req === null || req === void 0 ? void 0 : req.n) || 0), oldestAt: (req === null || req === void 0 ? void 0 : req.oldest) || null },
|
|
766
983
|
avgResponseHours: (resp === null || resp === void 0 ? void 0 : resp.avgSeconds) ? Math.round(Number(resp.avgSeconds) / 360) / 10 : null,
|
|
767
984
|
last30: { sent: sent30, won: Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0), winRate: sent30 ? Math.round((Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0) / sent30) * 100) : null },
|
|
768
985
|
};
|