@huloglobal/vendure-plugin-quotations 0.8.6 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +115 -0
- package/README.md +123 -9
- package/dist/approvals.d.ts +46 -0
- package/dist/approvals.d.ts.map +1 -0
- package/dist/approvals.js +136 -0
- package/dist/approvals.js.map +1 -0
- package/dist/crons.d.ts +5 -3
- package/dist/crons.d.ts.map +1 -1
- package/dist/crons.js +16 -10
- package/dist/crons.js.map +1 -1
- package/dist/csv.d.ts +7 -0
- package/dist/csv.d.ts.map +1 -0
- package/dist/csv.js +32 -0
- package/dist/csv.js.map +1 -0
- package/dist/deposits.d.ts +25 -0
- package/dist/deposits.d.ts.map +1 -0
- package/dist/deposits.js +59 -0
- package/dist/deposits.js.map +1 -0
- package/dist/email-layout.d.ts +104 -0
- package/dist/email-layout.d.ts.map +1 -0
- package/dist/email-layout.js +250 -0
- package/dist/email-layout.js.map +1 -0
- package/dist/emails.d.ts +57 -0
- package/dist/emails.d.ts.map +1 -0
- package/dist/emails.js +124 -0
- package/dist/emails.js.map +1 -0
- package/dist/events.d.ts +55 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +58 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/pay-links.d.ts +37 -0
- package/dist/pay-links.d.ts.map +1 -0
- package/dist/pay-links.js +61 -0
- package/dist/pay-links.js.map +1 -0
- package/dist/payment.service.d.ts +117 -0
- package/dist/payment.service.d.ts.map +1 -0
- package/dist/payment.service.js +479 -0
- package/dist/payment.service.js.map +1 -0
- package/dist/pdf.d.ts +15 -0
- package/dist/pdf.d.ts.map +1 -0
- package/dist/pdf.js +356 -0
- package/dist/pdf.js.map +1 -0
- package/dist/plugin.d.ts +5 -2
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js +9 -6
- package/dist/plugin.js.map +1 -1
- package/dist/pro-settings.d.ts +72 -0
- package/dist/pro-settings.d.ts.map +1 -0
- package/dist/pro-settings.js +202 -0
- package/dist/pro-settings.js.map +1 -0
- package/dist/pro.service.d.ts +130 -0
- package/dist/pro.service.d.ts.map +1 -0
- package/dist/pro.service.js +749 -0
- package/dist/pro.service.js.map +1 -0
- package/dist/quotation.controller.d.ts +54 -8
- package/dist/quotation.controller.d.ts.map +1 -1
- package/dist/quotation.controller.js +626 -32
- package/dist/quotation.controller.js.map +1 -1
- package/dist/quotation.service.d.ts +192 -12
- package/dist/quotation.service.d.ts.map +1 -1
- package/dist/quotation.service.js +648 -103
- package/dist/quotation.service.js.map +1 -1
- package/dist/rate-limit.d.ts +15 -0
- package/dist/rate-limit.d.ts.map +1 -0
- package/dist/rate-limit.js +35 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/templates.d.ts +12 -3
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +15 -38
- package/dist/templates.js.map +1 -1
- package/dist/types.d.ts +13 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -4
- package/dist/types.js.map +1 -1
- package/dist/webhooks.d.ts +61 -0
- package/dist/webhooks.d.ts.map +1 -0
- package/dist/webhooks.js +308 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +7 -6
- package/ui/components/quotations.component.ts +328 -19
|
@@ -41,6 +41,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
41
41
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
42
42
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
43
43
|
};
|
|
44
|
+
var QuotationService_1;
|
|
44
45
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
45
46
|
exports.QuotationService = exports.STAT_DEFS = exports.PREMIUM_FEATURES = void 0;
|
|
46
47
|
const common_1 = require("@nestjs/common");
|
|
@@ -53,17 +54,30 @@ const pricing_1 = require("./pricing");
|
|
|
53
54
|
const quote_version_1 = require("./quote-version");
|
|
54
55
|
const quote_total_1 = require("./quote-total");
|
|
55
56
|
const templates_1 = require("./templates");
|
|
57
|
+
const emails_1 = require("./emails");
|
|
58
|
+
const events_1 = require("./events");
|
|
59
|
+
const pdf_1 = require("./pdf");
|
|
56
60
|
const types_1 = require("./types");
|
|
57
61
|
const loggerCtx = 'Quotations';
|
|
58
62
|
const PLUGIN_ID = 'vendure-plugin-quotations';
|
|
59
63
|
const PLUGIN_NAME = 'Quotations';
|
|
60
64
|
const DAY_MS = 86400000;
|
|
61
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* What the free tier does not have — shown on the admin banners and in the
|
|
67
|
+
* weekly report. Free: building, sending (and test-sending, marking as sent),
|
|
68
|
+
* the customer page with accept/decline, the PDF, storefront requests,
|
|
69
|
+
* "My quotes", the chaser and expiry reminder, auto-expiry, HULO Payments pay
|
|
70
|
+
* links on acceptance, EventBus events, KPIs and the 12-month report.
|
|
71
|
+
*/
|
|
62
72
|
exports.PREMIUM_FEATURES = [
|
|
63
|
-
'
|
|
64
|
-
'
|
|
65
|
-
'
|
|
66
|
-
'
|
|
73
|
+
'Convert accepted quotes to draft orders from the admin',
|
|
74
|
+
'Quote templates',
|
|
75
|
+
'Follow-up sequences',
|
|
76
|
+
'Discount approval',
|
|
77
|
+
'Webhooks with Slack and Teams alerts',
|
|
78
|
+
'Sales reports by staff and source, with CSV export',
|
|
79
|
+
'Deposits and balance payments',
|
|
80
|
+
'Weekly report and set-up checklist',
|
|
67
81
|
];
|
|
68
82
|
/** The usage figures this plugin reports (evaluation + heartbeat stats,
|
|
69
83
|
* weekly report, dashboard widget). Keys are stable; every value is a
|
|
@@ -76,6 +90,22 @@ exports.STAT_DEFS = [
|
|
|
76
90
|
{ key: 'requestsReceived', label: 'quote requests received from your storefront', format: 'count' },
|
|
77
91
|
{ key: 'winRatePct', label: 'win rate on quotes sent', format: 'percent' },
|
|
78
92
|
];
|
|
93
|
+
/**
|
|
94
|
+
* The weekly report scheduler, held back while premium is off (the report is
|
|
95
|
+
* a premium feature): ticks do nothing then, and the clock is not moved, so
|
|
96
|
+
* the report resumes on the next due Monday once a licence is active.
|
|
97
|
+
*/
|
|
98
|
+
class PremiumDigest extends vendure_licence_sdk_1.WeeklyDigest {
|
|
99
|
+
constructor(opts, premium) {
|
|
100
|
+
super(opts);
|
|
101
|
+
this.premium = premium;
|
|
102
|
+
}
|
|
103
|
+
async tick(now = new Date()) {
|
|
104
|
+
if (!this.premium())
|
|
105
|
+
return false;
|
|
106
|
+
return super.tick(now);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
79
109
|
/** statuses a customer can still respond from */
|
|
80
110
|
const OPEN_STATUSES = ['sent', 'viewed'];
|
|
81
111
|
/** statuses an admin can still edit */
|
|
@@ -84,16 +114,18 @@ const EDITABLE_STATUSES = ['requested', 'draft', 'sent', 'viewed'];
|
|
|
84
114
|
const REQUESTS_PER_HOUR = 10;
|
|
85
115
|
/** request acknowledgements: at most one per recipient per day, and this many per hour per process */
|
|
86
116
|
const ACKS_PER_HOUR = 30;
|
|
87
|
-
|
|
117
|
+
/** quote requests per e-mail address per hour, counted in the database (so across processes and restarts) */
|
|
118
|
+
const REQUESTS_PER_EMAIL_PER_HOUR = 10;
|
|
119
|
+
let QuotationService = QuotationService_1 = class QuotationService {
|
|
88
120
|
initDigest(hooks) {
|
|
89
121
|
this.digestHooks = hooks;
|
|
90
122
|
if (!this.weeklyDigest) {
|
|
91
|
-
this.weeklyDigest = new
|
|
123
|
+
this.weeklyDigest = new PremiumDigest({
|
|
92
124
|
pluginId: PLUGIN_ID, pluginName: PLUGIN_NAME, prefs: this.prefs,
|
|
93
125
|
collect: (from, to) => this.collectDigest(from, to),
|
|
94
126
|
send: (to, mail) => this.sendDigest(to, mail),
|
|
95
127
|
defaultRecipient: () => this.digestDefaultRecipient(),
|
|
96
|
-
});
|
|
128
|
+
}, () => this.isPremium());
|
|
97
129
|
}
|
|
98
130
|
return this.weeklyDigest;
|
|
99
131
|
}
|
|
@@ -104,10 +136,13 @@ let QuotationService = class QuotationService {
|
|
|
104
136
|
}
|
|
105
137
|
return this.purchaseClaim;
|
|
106
138
|
}
|
|
107
|
-
constructor(connection, channelService, orderService) {
|
|
139
|
+
constructor(connection, channelService, orderService, eventBus, requestContextService, customerService) {
|
|
108
140
|
this.connection = connection;
|
|
109
141
|
this.channelService = channelService;
|
|
110
142
|
this.orderService = orderService;
|
|
143
|
+
this.eventBus = eventBus;
|
|
144
|
+
this.requestContextService = requestContextService;
|
|
145
|
+
this.customerService = customerService;
|
|
111
146
|
this.options = {};
|
|
112
147
|
this.licenceStore = new vendure_licence_sdk_1.LicenceStore((sql, params, opts) => (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection).query(sql, params, opts));
|
|
113
148
|
/** Small per-plugin settings (weekly report recipient, dismissed set-up items, trial lead). */
|
|
@@ -118,6 +153,10 @@ let QuotationService = class QuotationService {
|
|
|
118
153
|
// Buy-from-admin auto-install (hooks are supplied by the controller so
|
|
119
154
|
// this file never imports the plugin class).
|
|
120
155
|
this.purchaseClaim = null;
|
|
156
|
+
// ── Premium + extension hooks (supplied by the plugin class and the companion services) ──
|
|
157
|
+
this.premiumCheck = () => false;
|
|
158
|
+
this.preSendGates = [];
|
|
159
|
+
this.trailListeners = [];
|
|
121
160
|
this.mailer = null;
|
|
122
161
|
// ── Customer-initiated quote requests ───────────────────────────────
|
|
123
162
|
this.requestHits = new Map();
|
|
@@ -126,10 +165,42 @@ let QuotationService = class QuotationService {
|
|
|
126
165
|
// ── Product search for the editor ───────────────────────────────────
|
|
127
166
|
/** Per channel+language: which catalogue the search reads (see catalogue-search.ts); re-checked every minute. */
|
|
128
167
|
this.catalogueSources = new Map();
|
|
168
|
+
/** Payment / deposit text and buttons for the customer page (filled in by the payment service). */
|
|
169
|
+
this.pageExtrasProvider = null;
|
|
129
170
|
}
|
|
130
171
|
get db() { return (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection); }
|
|
172
|
+
/** The SQL adapter (MariaDB/MySQL/Postgres) the companion services share. */
|
|
173
|
+
get sql() { return this.db; }
|
|
131
174
|
setOptions(o) { this.options = o || {}; }
|
|
132
175
|
getOptions() { return this.options; }
|
|
176
|
+
setPremiumCheck(fn) { this.premiumCheck = fn; }
|
|
177
|
+
/** Licensed, or inside the evaluation. */
|
|
178
|
+
isPremium() { try {
|
|
179
|
+
return !!this.premiumCheck();
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return false;
|
|
183
|
+
} }
|
|
184
|
+
addPreSendGate(gate) { this.preSendGates.push(gate); }
|
|
185
|
+
/** The first refusal from a gate, or null. Test sends go through the gates too (they decide whether to hold them). */
|
|
186
|
+
async preSend(q, mode, actor) {
|
|
187
|
+
for (const g of this.preSendGates) {
|
|
188
|
+
const r = await g(q, mode, actor).catch((e) => `Could not check the quote before sending: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
|
|
189
|
+
if (r)
|
|
190
|
+
return r;
|
|
191
|
+
}
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
onTrail(fn) { this.trailListeners.push(fn); }
|
|
195
|
+
/** A request context on the quote's channel for work no admin started (the customer page, the cron, payment events). */
|
|
196
|
+
async systemCtx(channelId) {
|
|
197
|
+
const channel = await this.channelService.findOne(core_1.RequestContext.empty(), channelId).catch(() => undefined)
|
|
198
|
+
|| await this.channelService.getDefaultChannel().catch(() => undefined);
|
|
199
|
+
if (this.requestContextService && channel) {
|
|
200
|
+
return this.requestContextService.create({ apiType: 'admin', channelOrToken: channel });
|
|
201
|
+
}
|
|
202
|
+
return core_1.RequestContext.empty();
|
|
203
|
+
}
|
|
133
204
|
async onModuleInit() {
|
|
134
205
|
await this.ensureSchema();
|
|
135
206
|
await this.licenceStore.ensureTable();
|
|
@@ -217,6 +288,17 @@ let QuotationService = class QuotationService {
|
|
|
217
288
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestMessage VARCHAR(2000) NOT NULL DEFAULT ''`);
|
|
218
289
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestSource VARCHAR(64) NOT NULL DEFAULT ''`);
|
|
219
290
|
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS requestedAt DATETIME NULL`);
|
|
291
|
+
// 0.9.0: validity counted from the send, payment (pay link + paid), My quotes and payment lookups.
|
|
292
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS validityDays INT NULL`);
|
|
293
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS paidAt DATETIME NULL`);
|
|
294
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS payUrl VARCHAR(1000) NOT NULL DEFAULT ''`);
|
|
295
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS payRef VARCHAR(190) NOT NULL DEFAULT ''`);
|
|
296
|
+
await this.db.query(`ALTER TABLE quotation ADD COLUMN IF NOT EXISTS payProvider VARCHAR(120) NOT NULL DEFAULT ''`);
|
|
297
|
+
await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_order (convertedOrderId)`).catch(() => undefined);
|
|
298
|
+
await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_customer (customerId)`).catch(() => undefined);
|
|
299
|
+
await this.db.query(`ALTER TABLE quotation ADD INDEX IF NOT EXISTS idx_q_requested (customerEmail, requestedAt)`).catch(() => undefined);
|
|
300
|
+
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS payLinkOnAccept TINYINT NOT NULL DEFAULT 0`);
|
|
301
|
+
await this.db.query(`ALTER TABLE quotation_config ADD COLUMN IF NOT EXISTS attachPdf TINYINT NOT NULL DEFAULT 0`);
|
|
220
302
|
await this.db.query(`
|
|
221
303
|
CREATE TABLE IF NOT EXISTS quotation_line (
|
|
222
304
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
@@ -244,7 +326,7 @@ let QuotationService = class QuotationService {
|
|
|
244
326
|
}
|
|
245
327
|
// ── Config ──────────────────────────────────────────────────────────
|
|
246
328
|
rowToConfig(row, code) {
|
|
247
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v, _w;
|
|
329
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
|
|
248
330
|
return {
|
|
249
331
|
channelId: row.channelId,
|
|
250
332
|
channelCode: code,
|
|
@@ -271,6 +353,8 @@ let QuotationService = class QuotationService {
|
|
|
271
353
|
footerNote: (_v = row.footerNote) !== null && _v !== void 0 ? _v : '',
|
|
272
354
|
acceptRequests: !!Number((_w = row.acceptRequests) !== null && _w !== void 0 ? _w : 1),
|
|
273
355
|
requestAckBody: row.requestAckBody || types_1.DEFAULT_CONFIG.requestAckBody,
|
|
356
|
+
payLinkOnAccept: !!Number((_x = row.payLinkOnAccept) !== null && _x !== void 0 ? _x : 0),
|
|
357
|
+
attachPdf: !!Number((_y = row.attachPdf) !== null && _y !== void 0 ? _y : 0),
|
|
274
358
|
};
|
|
275
359
|
}
|
|
276
360
|
async getConfig(channelId) {
|
|
@@ -290,8 +374,8 @@ let QuotationService = class QuotationService {
|
|
|
290
374
|
await this.db.query(`INSERT INTO quotation_config (channelId, numberPrefix, nextNumber, defaultValidityDays, defaultVatRate, defaultTerms,
|
|
291
375
|
businessName, replyTo, notifyEmail, currency, logoUrl, accentColor, chaserEnabled, chaserAfterDays,
|
|
292
376
|
expiryReminderDays, emailSubject, emailBody, notifyOnView, websiteUrl, phone, addressText, footerNote,
|
|
293
|
-
acceptRequests, requestAckBody)
|
|
294
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
377
|
+
acceptRequests, requestAckBody, payLinkOnAccept, attachPdf)
|
|
378
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
295
379
|
ON DUPLICATE KEY UPDATE numberPrefix=VALUES(numberPrefix), defaultValidityDays=VALUES(defaultValidityDays),
|
|
296
380
|
defaultVatRate=VALUES(defaultVatRate), defaultTerms=VALUES(defaultTerms), businessName=VALUES(businessName),
|
|
297
381
|
replyTo=VALUES(replyTo), notifyEmail=VALUES(notifyEmail), currency=VALUES(currency), logoUrl=VALUES(logoUrl),
|
|
@@ -299,14 +383,16 @@ let QuotationService = class QuotationService {
|
|
|
299
383
|
expiryReminderDays=VALUES(expiryReminderDays), emailSubject=VALUES(emailSubject), emailBody=VALUES(emailBody),
|
|
300
384
|
notifyOnView=VALUES(notifyOnView), websiteUrl=VALUES(websiteUrl), phone=VALUES(phone),
|
|
301
385
|
addressText=VALUES(addressText), footerNote=VALUES(footerNote),
|
|
302
|
-
acceptRequests=VALUES(acceptRequests), requestAckBody=VALUES(requestAckBody)
|
|
386
|
+
acceptRequests=VALUES(acceptRequests), requestAckBody=VALUES(requestAckBody),
|
|
387
|
+
payLinkOnAccept=VALUES(payLinkOnAccept), attachPdf=VALUES(attachPdf)`, [c.channelId, c.numberPrefix || 'Q-', Math.max(1, Number(c.nextNumber) || 1),
|
|
303
388
|
Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, String(c.defaultTerms || '').slice(0, 4000),
|
|
304
389
|
c.businessName || '', c.replyTo || '', c.notifyEmail || '', (c.currency || 'GBP').toUpperCase().slice(0, 3),
|
|
305
390
|
c.logoUrl || '', c.accentColor || '#1d4ed8', c.chaserEnabled ? 1 : 0, Math.max(1, Number(c.chaserAfterDays) || 3),
|
|
306
391
|
Math.max(0, Number(c.expiryReminderDays) || 0), String(c.emailSubject || '').slice(0, 300), String(c.emailBody || '').slice(0, 4000), c.notifyOnView ? 1 : 0,
|
|
307
392
|
String(c.websiteUrl || '').slice(0, 300), String(c.phone || '').slice(0, 64),
|
|
308
393
|
String(c.addressText || '').slice(0, 500), String(c.footerNote || '').slice(0, 500),
|
|
309
|
-
c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000)
|
|
394
|
+
c.acceptRequests === false ? 0 : 1, String(c.requestAckBody || '').slice(0, 4000),
|
|
395
|
+
c.payLinkOnAccept ? 1 : 0, c.attachPdf ? 1 : 0], { conflictColumns: ['channelId'] });
|
|
310
396
|
}
|
|
311
397
|
// ── Reference numbering ─────────────────────────────────────────────
|
|
312
398
|
/** Atomically claims the next quote number for a channel. */
|
|
@@ -354,19 +440,21 @@ let QuotationService = class QuotationService {
|
|
|
354
440
|
const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
|
|
355
441
|
const reference = await this.nextReference(channelId);
|
|
356
442
|
const token = crypto.randomBytes(24).toString('hex');
|
|
357
|
-
|
|
443
|
+
// The validity period; it starts afresh when the quote is first sent (see sendQuote / markSent).
|
|
444
|
+
const validityDays = Math.min(365, Math.max(1, Math.floor(Number(input.validityDays) || cfg.defaultValidityDays || 30)));
|
|
358
445
|
const res = await this.db.query(`INSERT INTO quotation (channelId, reference, status, token, customerId, customerName, customerEmail,
|
|
359
446
|
customerCompany, customerPhone, notes, internalNotes, terms, vatRate, discountType, discountValue,
|
|
360
447
|
currency, validUntil, subTotalPence, discountPence, vatPence, totalPence, createdBy,
|
|
361
|
-
preparedByName, preparedByEmail, createdAt, updatedAt)
|
|
362
|
-
VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
|
|
448
|
+
preparedByName, preparedByEmail, validityDays, createdAt, updatedAt)
|
|
449
|
+
VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
|
|
363
450
|
String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
|
|
364
451
|
String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
|
|
365
452
|
String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000), String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : cfg.defaultTerms) !== null && _c !== void 0 ? _c : '').slice(0, 20000),
|
|
366
453
|
vatRate, discountType, discountValue, (input.currency || cfg.currency || 'GBP').toUpperCase().slice(0, 3),
|
|
367
454
|
validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
|
|
368
455
|
actor.slice(0, 190),
|
|
369
|
-
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190)
|
|
456
|
+
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
|
|
457
|
+
validityDays], { needInsertId: true });
|
|
370
458
|
const quoteId = Number(res.insertId);
|
|
371
459
|
await this.replaceLines(quoteId, lines);
|
|
372
460
|
await this.logEvent(quoteId, 'created', `Quote ${reference} created`, actor);
|
|
@@ -404,6 +492,7 @@ let QuotationService = class QuotationService {
|
|
|
404
492
|
await this.db.query(`UPDATE quotation SET customerId=?, customerName=?, customerEmail=?, customerCompany=?, customerPhone=?,
|
|
405
493
|
notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
|
|
406
494
|
validUntil=${touchValidity ? 'DATE_ADD(NOW(), INTERVAL ? DAY)' : 'validUntil'},
|
|
495
|
+
validityDays=${touchValidity ? '?' : 'validityDays'},
|
|
407
496
|
subTotalPence=?, discountPence=?, vatPence=?, totalPence=?,
|
|
408
497
|
preparedByName=?, preparedByEmail=?, updatedAt=NOW()
|
|
409
498
|
WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
|
|
@@ -411,7 +500,7 @@ let QuotationService = class QuotationService {
|
|
|
411
500
|
String(input.customerPhone || '').slice(0, 64), String(input.notes || '').slice(0, 20000), String(input.internalNotes || '').slice(0, 20000),
|
|
412
501
|
String((_c = (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms) !== null && _c !== void 0 ? _c : '').slice(0, 20000), vatRate, discountType, discountValue,
|
|
413
502
|
(input.currency || existing.currency).toUpperCase().slice(0, 3),
|
|
414
|
-
...(touchValidity ? [Math.max(1, Math.floor(newValidity))] : []),
|
|
503
|
+
...(touchValidity ? [Math.min(365, Math.max(1, Math.floor(newValidity))), Math.min(365, Math.max(1, Math.floor(newValidity)))] : []),
|
|
415
504
|
totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
|
|
416
505
|
String(input.preparedByName || '').slice(0, 190), String(input.preparedByEmail || '').toLowerCase().slice(0, 190),
|
|
417
506
|
quoteId]);
|
|
@@ -425,8 +514,12 @@ let QuotationService = class QuotationService {
|
|
|
425
514
|
return;
|
|
426
515
|
if (q.status !== 'draft' && q.status !== 'requested')
|
|
427
516
|
throw new Error('Only draft quotes and requests can be deleted — cancel instead');
|
|
517
|
+
await this.publishEvent({ ...q, status: 'deleted' }, 'deleted', `Quote ${q.reference} deleted`);
|
|
428
518
|
await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
|
|
429
519
|
await this.db.query(`DELETE FROM quotation_event WHERE quoteId = ?`, [quoteId]);
|
|
520
|
+
for (const t of ['quotation_followup', 'quotation_approval', 'quotation_deposit']) {
|
|
521
|
+
await this.db.query(`DELETE FROM ${t} WHERE quoteId = ?`, [quoteId]).catch(() => undefined);
|
|
522
|
+
}
|
|
430
523
|
await this.db.query(`DELETE FROM quotation WHERE id = ?`, [quoteId]);
|
|
431
524
|
}
|
|
432
525
|
async cancelQuote(quoteId, actor) {
|
|
@@ -448,7 +541,7 @@ let QuotationService = class QuotationService {
|
|
|
448
541
|
customerCompany: q.customerCompany, customerPhone: q.customerPhone,
|
|
449
542
|
notes: q.notes, internalNotes: q.internalNotes, terms: q.terms,
|
|
450
543
|
vatRate: q.vatRate, discountType: q.discountType, discountValue: q.discountValue,
|
|
451
|
-
currency: q.currency, validityDays:
|
|
544
|
+
currency: q.currency, validityDays: this.validityDaysOf(q),
|
|
452
545
|
lines: q.lines.map((l) => ({
|
|
453
546
|
productVariantId: l.productVariantId, sku: l.sku, description: l.description,
|
|
454
547
|
quantity: l.quantity, unitPricePence: l.unitPricePence, lineDiscountPercent: l.lineDiscountPercent,
|
|
@@ -507,8 +600,40 @@ let QuotationService = class QuotationService {
|
|
|
507
600
|
FROM quotation ${whereSql} ORDER BY id DESC LIMIT ${perPage} OFFSET ${(page - 1) * perPage}`, params);
|
|
508
601
|
return { items, totalItems: Number((count === null || count === void 0 ? void 0 : count.n) || 0), page, perPage };
|
|
509
602
|
}
|
|
603
|
+
/**
|
|
604
|
+
* Add an entry to the quote's activity trail, then tell the listeners
|
|
605
|
+
* (webhooks, pay links) and publish a {@link QuotationEvent} on the
|
|
606
|
+
* EventBus for the types subscribers care about.
|
|
607
|
+
*/
|
|
510
608
|
async logEvent(quoteId, type, detail, actor = '') {
|
|
511
|
-
await this.db.query(`INSERT INTO quotation_event (quoteId, type, detail, actor, createdAt) VALUES (?, ?, ?, ?, NOW())`, [quoteId, type.slice(0, 24), detail.slice(0, 1000), actor.slice(0, 190)]).catch(() =>
|
|
609
|
+
const res = await this.db.query(`INSERT INTO quotation_event (quoteId, type, detail, actor, createdAt) VALUES (?, ?, ?, ?, NOW())`, [quoteId, type.slice(0, 24), detail.slice(0, 1000), actor.slice(0, 190)], { needInsertId: true }).catch(() => null);
|
|
610
|
+
const id = Number((res === null || res === void 0 ? void 0 : res.insertId) || 0);
|
|
611
|
+
for (const fn of this.trailListeners) {
|
|
612
|
+
try {
|
|
613
|
+
fn({ id, quoteId, type, detail, actor });
|
|
614
|
+
}
|
|
615
|
+
catch (e) {
|
|
616
|
+
core_1.Logger.warn(`trail listener failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (events_1.PUBLISHED_EVENT_TYPES.has(type))
|
|
620
|
+
void this.publishEvent(quoteId, type, detail, actor);
|
|
621
|
+
}
|
|
622
|
+
/** Publish a QuotationEvent (never throws; subscribers run after this request's work). */
|
|
623
|
+
async publishEvent(quoteIdOrQuote, type, detail, actor = '') {
|
|
624
|
+
if (!this.eventBus)
|
|
625
|
+
return;
|
|
626
|
+
try {
|
|
627
|
+
const q = typeof quoteIdOrQuote === 'object' ? quoteIdOrQuote
|
|
628
|
+
: (await this.db.query(`SELECT * FROM quotation WHERE id = ?`, [quoteIdOrQuote]))[0];
|
|
629
|
+
if (!q)
|
|
630
|
+
return;
|
|
631
|
+
const ctx = await this.systemCtx(Number(q.channelId) || 1);
|
|
632
|
+
await this.eventBus.publish(new events_1.QuotationEvent(ctx, type, (0, events_1.eventQuote)(q), detail, actor));
|
|
633
|
+
}
|
|
634
|
+
catch (e) {
|
|
635
|
+
core_1.Logger.warn(`could not publish the ${type} quotation event: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
|
|
636
|
+
}
|
|
512
637
|
}
|
|
513
638
|
// ── Sending ─────────────────────────────────────────────────────────
|
|
514
639
|
quoteUrl(token) {
|
|
@@ -556,62 +681,146 @@ let QuotationService = class QuotationService {
|
|
|
556
681
|
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`SMTP send timed out after ${ms / 1000}s`)), ms); }),
|
|
557
682
|
]).finally(() => clearTimeout(timer));
|
|
558
683
|
}
|
|
684
|
+
/**
|
|
685
|
+
* The quote's validity period in days: as set in the editor, else derived
|
|
686
|
+
* from the stored dates (quotes made before 0.9.0), else the channel default.
|
|
687
|
+
*/
|
|
688
|
+
validityDaysOf(q, cfg) {
|
|
689
|
+
let d = Number(q.validityDays || 0);
|
|
690
|
+
if (d < 1 && q.validUntil && q.createdAt)
|
|
691
|
+
d = Math.round((new Date(q.validUntil).getTime() - new Date(q.createdAt).getTime()) / DAY_MS);
|
|
692
|
+
if (d < 1)
|
|
693
|
+
d = Number((cfg === null || cfg === void 0 ? void 0 : cfg.defaultValidityDays) || types_1.DEFAULT_CONFIG.defaultValidityDays);
|
|
694
|
+
return Math.max(1, Math.min(365, Math.floor(d)));
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* E-mail the quote to the customer and open it for their response. A
|
|
698
|
+
* first send (draft or request) starts the validity period, so the e-mail
|
|
699
|
+
* (and its PDF) carry the new date; a resend keeps the date, and a quote
|
|
700
|
+
* whose date has passed must be extended first. Free.
|
|
701
|
+
*/
|
|
559
702
|
async sendQuote(quoteId, actor) {
|
|
560
703
|
const q = await this.getQuote(quoteId);
|
|
561
704
|
if (!q)
|
|
562
705
|
return { ok: false, reason: 'Quote not found' };
|
|
563
|
-
if (!q.customerEmail)
|
|
564
|
-
return { ok: false, reason: 'The quote has no customer email' };
|
|
706
|
+
if (!q.customerEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q.customerEmail))
|
|
707
|
+
return { ok: false, reason: 'The quote has no valid customer email' };
|
|
565
708
|
if (['accepted', 'declined', 'converted', 'cancelled', 'expired'].includes(q.status)) {
|
|
566
709
|
return { ok: false, reason: `A ${q.status} quote cannot be sent` };
|
|
567
710
|
}
|
|
711
|
+
const held = await this.preSend(q, 'send', actor);
|
|
712
|
+
if (held)
|
|
713
|
+
return { ok: false, reason: held };
|
|
568
714
|
const cfg = await this.getConfig(q.channelId);
|
|
715
|
+
const first = q.status === 'draft' || q.status === 'requested';
|
|
716
|
+
const days = this.validityDaysOf(q, cfg);
|
|
717
|
+
if (first) {
|
|
718
|
+
q.validUntil = new Date(Date.now() + days * DAY_MS);
|
|
719
|
+
}
|
|
720
|
+
else if (q.validUntil && new Date(q.validUntil).getTime() <= Date.now()) {
|
|
721
|
+
return { ok: false, reason: `This quote's validity ended on ${new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })}. Extend it first, then send it again.` };
|
|
722
|
+
}
|
|
569
723
|
const res = await this.deliverEmail(q, cfg, 'quote');
|
|
570
724
|
if (!res.ok)
|
|
571
725
|
return res;
|
|
572
|
-
|
|
573
|
-
|
|
726
|
+
if (first) {
|
|
727
|
+
await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), validUntil=DATE_ADD(NOW(), INTERVAL ? DAY), validityDays=?, expiryReminderSentAt=NULL, updatedAt=NOW()
|
|
728
|
+
WHERE id = ? AND status IN ('draft','requested')`, [days, days, quoteId]);
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
await this.db.query(`UPDATE quotation SET sentAt=NOW(), updatedAt=NOW() WHERE id = ? AND status IN ('sent','viewed')`, [quoteId]);
|
|
732
|
+
}
|
|
733
|
+
const until = new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
|
|
734
|
+
await this.logEvent(quoteId, 'sent', first ? `Sent to ${q.customerEmail}; valid until ${until}` : `Sent again to ${q.customerEmail}`, actor);
|
|
574
735
|
return { ok: true };
|
|
575
736
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
737
|
+
/**
|
|
738
|
+
* The store shared the quote itself (the PDF, or the customer link by its
|
|
739
|
+
* own e-mail): open it for the customer's response without e-mailing.
|
|
740
|
+
* Only a draft or a request moves, and its validity starts now. Free.
|
|
741
|
+
*/
|
|
742
|
+
async markSent(quoteId, actor) {
|
|
743
|
+
const q = await this.getQuote(quoteId);
|
|
744
|
+
if (!q)
|
|
745
|
+
return { ok: false, reason: 'Quote not found' };
|
|
746
|
+
const held = await this.preSend(q, 'mark_sent', actor);
|
|
747
|
+
if (held)
|
|
748
|
+
return { ok: false, reason: held };
|
|
749
|
+
const cfg = await this.getConfig(q.channelId);
|
|
750
|
+
const days = this.validityDaysOf(q, cfg);
|
|
751
|
+
const res = await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), validUntil=DATE_ADD(NOW(), INTERVAL ? DAY), validityDays=?, expiryReminderSentAt=NULL, updatedAt=NOW()
|
|
752
|
+
WHERE id = ? AND status IN ('draft','requested')`, [days, days, quoteId], { needAffected: true });
|
|
753
|
+
if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) !== 1) {
|
|
754
|
+
const now = await this.getQuote(quoteId);
|
|
755
|
+
if (now && OPEN_STATUSES.includes(now.status))
|
|
756
|
+
return { ok: false, reason: 'This quote is already marked as sent: the customer can open the link.' };
|
|
757
|
+
if ((now === null || now === void 0 ? void 0 : now.status) === 'expired')
|
|
758
|
+
return { ok: false, reason: 'This quote has expired. Extend it to open it for the customer again.' };
|
|
759
|
+
return { ok: false, reason: `A ${(now === null || now === void 0 ? void 0 : now.status) || 'missing'} quote cannot be marked as sent.` };
|
|
760
|
+
}
|
|
761
|
+
const until = new Date(Date.now() + days * DAY_MS).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
|
|
762
|
+
await this.logEvent(quoteId, 'sent', `Marked as sent (shared by the store); valid until ${until}`, actor);
|
|
763
|
+
return { ok: true };
|
|
764
|
+
}
|
|
765
|
+
/** The {{placeholders}} every customer e-mail can use. */
|
|
766
|
+
emailVars(q, cfg, extra = {}) {
|
|
767
|
+
return {
|
|
582
768
|
reference: q.reference,
|
|
583
769
|
customerName: q.customerName || 'there',
|
|
584
770
|
businessName: cfg.businessName || 'our team',
|
|
585
771
|
staffName: q.preparedByName || cfg.businessName || 'our team',
|
|
586
772
|
total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
|
|
587
773
|
validUntil: q.validUntil ? new Date(q.validUntil).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '',
|
|
588
|
-
quoteUrl:
|
|
774
|
+
quoteUrl: this.quoteUrl(q.token),
|
|
775
|
+
...extra,
|
|
589
776
|
};
|
|
777
|
+
}
|
|
778
|
+
async deliverEmail(q, cfg, kind, overrideTo) {
|
|
590
779
|
let subject = cfg.emailSubject || types_1.DEFAULT_CONFIG.emailSubject;
|
|
591
780
|
let body = cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody;
|
|
592
781
|
if (kind === 'chaser') {
|
|
593
782
|
subject = `Reminder: quotation {{reference}} from {{businessName}}`;
|
|
594
|
-
body = 'Hi {{customerName}},\n\nJust a gentle
|
|
783
|
+
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}}';
|
|
595
784
|
}
|
|
596
785
|
else if (kind === 'expiry') {
|
|
597
786
|
subject = `Your quotation {{reference}} expires soon`;
|
|
598
|
-
body = 'Hi {{customerName}},\n\nA quick
|
|
787
|
+
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}}';
|
|
599
788
|
}
|
|
600
|
-
|
|
789
|
+
return this.emailCustomer(q, cfg, subject, body, { to: overrideTo, test: !!overrideTo, attachPdf: cfg.attachPdf, kind });
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* One e-mail to the customer (or `to`, for a test), as the member of staff
|
|
793
|
+
* who prepared the quote: their name fronts the From header and replies go
|
|
794
|
+
* straight to them. Templates use {{placeholders}} (see emailVars). The
|
|
795
|
+
* template text sits in the shared e-mail design (emails.ts) with the
|
|
796
|
+
* quote's summary and button; a plain-text part goes with it.
|
|
797
|
+
*/
|
|
798
|
+
async emailCustomer(q, cfg, subjectTpl, bodyTpl, opts = {}) {
|
|
799
|
+
const smtp = this.smtpSettings();
|
|
800
|
+
if (!smtp)
|
|
801
|
+
return { ok: false, reason: 'SMTP is not configured (SMTP_SERVER / SMTP_USER env or plugin options)' };
|
|
802
|
+
const url = this.quoteUrl(q.token);
|
|
803
|
+
const vars = this.emailVars(q, cfg, opts.vars);
|
|
804
|
+
const render = (t) => String(t || '').replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
601
805
|
try {
|
|
602
806
|
const transporter = this.transporter(smtp);
|
|
603
|
-
// Send as the member of staff who prepared the quote: their name
|
|
604
|
-
// fronts the From header and replies go straight to them.
|
|
605
807
|
const senderName = q.preparedByName
|
|
606
808
|
? (cfg.businessName ? `${q.preparedByName} — ${cfg.businessName}` : q.preparedByName)
|
|
607
809
|
: (cfg.businessName || '');
|
|
810
|
+
const mail = (0, emails_1.customerQuoteMail)({
|
|
811
|
+
q, cfg, kind: opts.kind || (opts.button ? 'custom' : 'quote'), body: render(bodyTpl), quoteUrl: url,
|
|
812
|
+
test: opts.test, button: opts.button, amountDue: opts.amountDue,
|
|
813
|
+
});
|
|
608
814
|
await this.sendWithDeadline(transporter, {
|
|
609
|
-
from: senderName ? `"${senderName.replace(/"/g, "'")}" <${smtp.from}>` : smtp.from,
|
|
610
|
-
to:
|
|
815
|
+
from: senderName ? `"${senderName.replace(/["\r\n]/g, "'")}" <${smtp.from}>` : smtp.from,
|
|
816
|
+
to: opts.to || q.customerEmail,
|
|
611
817
|
replyTo: q.preparedByEmail || cfg.replyTo || undefined,
|
|
612
|
-
subject: (
|
|
613
|
-
text:
|
|
614
|
-
html:
|
|
818
|
+
subject: ((opts.test ? '[TEST] ' : '') + render(subjectTpl)).replace(/[\r\n]+/g, ' '),
|
|
819
|
+
text: mail.text,
|
|
820
|
+
html: mail.html,
|
|
821
|
+
attachments: opts.attachPdf
|
|
822
|
+
? [{ filename: `Quotation-${String(q.reference).replace(/[^A-Za-z0-9._-]/g, '_')}.pdf`, content: (0, pdf_1.renderQuotePdf)(q, cfg, url), contentType: 'application/pdf' }]
|
|
823
|
+
: undefined,
|
|
615
824
|
});
|
|
616
825
|
return { ok: true };
|
|
617
826
|
}
|
|
@@ -619,8 +828,29 @@ let QuotationService = class QuotationService {
|
|
|
619
828
|
return { ok: false, reason: e.message };
|
|
620
829
|
}
|
|
621
830
|
}
|
|
622
|
-
/**
|
|
623
|
-
async
|
|
831
|
+
/** A note to members of staff (approvals), in the compact e-mail design. Never throws. */
|
|
832
|
+
async mailStaff(to, subject, mail) {
|
|
833
|
+
const smtp = this.smtpSettings();
|
|
834
|
+
const list = [...new Set(to.map(t => String(t || '').trim().toLowerCase()).filter(t => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)))].slice(0, 50);
|
|
835
|
+
if (!smtp || !list.length)
|
|
836
|
+
return false;
|
|
837
|
+
const body = typeof mail === 'string' ? { text: mail } : mail;
|
|
838
|
+
try {
|
|
839
|
+
await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to: list.join(', '), subject: subject.replace(/[\r\n]+/g, ' '), ...body });
|
|
840
|
+
return true;
|
|
841
|
+
}
|
|
842
|
+
catch (e) {
|
|
843
|
+
core_1.Logger.warn(`staff e-mail failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
|
|
844
|
+
return false;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
/** The admin link to one quote, when the admin URL is known. */
|
|
848
|
+
quoteAdminUrl(quoteId) {
|
|
849
|
+
const base = this.adminUrl();
|
|
850
|
+
return base ? `${base}?quote=${quoteId}` : '';
|
|
851
|
+
}
|
|
852
|
+
/** Fire-and-forget notification to the merchant (request, first view, accept/decline). */
|
|
853
|
+
async notifyMerchant(q, cfg, subject, mail) {
|
|
624
854
|
const smtp = this.smtpSettings();
|
|
625
855
|
// The preparing member of staff always hears about it; the channel
|
|
626
856
|
// notify address is copied in when it differs.
|
|
@@ -629,12 +859,26 @@ let QuotationService = class QuotationService {
|
|
|
629
859
|
if (!smtp || !to)
|
|
630
860
|
return;
|
|
631
861
|
try {
|
|
632
|
-
await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to, subject, text });
|
|
862
|
+
await this.sendWithDeadline(this.transporter(smtp), { from: smtp.from, to, subject: subject.replace(/[\r\n]+/g, ' '), text: mail.text, html: mail.html });
|
|
633
863
|
}
|
|
634
864
|
catch (e) {
|
|
635
865
|
core_1.Logger.warn(`merchant notification failed: ${e.message}`, loggerCtx);
|
|
636
866
|
}
|
|
637
867
|
}
|
|
868
|
+
/** The rows every store notification about a quote shows. */
|
|
869
|
+
quoteRows(q, extra = []) {
|
|
870
|
+
return [
|
|
871
|
+
{ label: 'Quotation', value: String(q.reference || ''), mono: true },
|
|
872
|
+
{ label: 'Customer', value: [q.customerName, q.customerEmail ? `<${q.customerEmail}>` : ''].filter(Boolean).join(' ') },
|
|
873
|
+
{ label: 'Company', value: String(q.customerCompany || '') },
|
|
874
|
+
{ label: 'Total', value: (0, pricing_1.formatMoney)(q.totalPence, q.currency) },
|
|
875
|
+
...extra,
|
|
876
|
+
];
|
|
877
|
+
}
|
|
878
|
+
adminButton(q, label = 'Open the quote') {
|
|
879
|
+
const url = this.quoteAdminUrl(Number(q.id));
|
|
880
|
+
return url ? { url, label } : undefined;
|
|
881
|
+
}
|
|
638
882
|
// ── Customer actions ────────────────────────────────────────────────
|
|
639
883
|
async markViewed(token) {
|
|
640
884
|
const q = await this.getQuoteByToken(token);
|
|
@@ -648,7 +892,12 @@ let QuotationService = class QuotationService {
|
|
|
648
892
|
await this.logEvent(q.id, 'viewed', 'Opened by the customer', q.customerEmail);
|
|
649
893
|
const cfg = await this.getConfig(q.channelId);
|
|
650
894
|
if (cfg.notifyOnView) {
|
|
651
|
-
void this.notifyMerchant(q, cfg, `Quote ${q.reference} was just opened`,
|
|
895
|
+
void this.notifyMerchant(q, cfg, `Quote ${q.reference} was just opened`, (0, emails_1.staffMail)(cfg, {
|
|
896
|
+
heading: `Quote ${q.reference} was just opened`,
|
|
897
|
+
intro: `${q.customerName || q.customerEmail} opened the quote for the first time. This is a good moment to follow up.`,
|
|
898
|
+
rows: this.quoteRows(q),
|
|
899
|
+
button: this.adminButton(q),
|
|
900
|
+
}));
|
|
652
901
|
}
|
|
653
902
|
}
|
|
654
903
|
}
|
|
@@ -685,10 +934,14 @@ let QuotationService = class QuotationService {
|
|
|
685
934
|
? `Accepted by "${cleanName}"${cleanComment ? ` — ${cleanComment}` : ''}`
|
|
686
935
|
: `Declined${cleanComment ? ` — ${cleanComment}` : ''}`, q.customerEmail);
|
|
687
936
|
const cfg = await this.getConfig(q.channelId);
|
|
688
|
-
void this.notifyMerchant(q, cfg, `Quote ${q.reference} ${status} — ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)}`,
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
937
|
+
void this.notifyMerchant(q, cfg, `Quote ${q.reference} ${status} — ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)}`, (0, emails_1.staffMail)(cfg, {
|
|
938
|
+
heading: `Quote ${q.reference} ${status}`,
|
|
939
|
+
intro: `${q.customerName || q.customerEmail} ${status} quote ${q.reference}.`,
|
|
940
|
+
rows: this.quoteRows(q, action === 'accept' ? [{ label: 'Signed by', value: cleanName }] : []),
|
|
941
|
+
note: cleanComment ? { title: 'Their comment', text: cleanComment } : undefined,
|
|
942
|
+
outro: action === 'accept' ? 'Open the quote in Admin → Quotations to convert it to an order.' : 'Open the quote in Admin → Quotations to follow up.',
|
|
943
|
+
button: this.adminButton(q),
|
|
944
|
+
}));
|
|
692
945
|
return { ok: true, quote: await this.getQuote(q.id) };
|
|
693
946
|
}
|
|
694
947
|
// ── Conversion to a Vendure draft order ─────────────────────────────
|
|
@@ -699,7 +952,7 @@ let QuotationService = class QuotationService {
|
|
|
699
952
|
* "Quotation …" surcharge, so the draft order total equals the quote
|
|
700
953
|
* total exactly. The admin completes the draft as usual.
|
|
701
954
|
*/
|
|
702
|
-
async convertToDraftOrder(ctx, quoteId, actor) {
|
|
955
|
+
async convertToDraftOrder(ctx, quoteId, actor, opts = {}) {
|
|
703
956
|
var _a;
|
|
704
957
|
const q = await this.getQuote(quoteId);
|
|
705
958
|
if (!q)
|
|
@@ -719,7 +972,8 @@ let QuotationService = class QuotationService {
|
|
|
719
972
|
req: ctx.req, apiType: ctx.apiType, channel, session: ctx.session, languageCode: ctx.languageCode,
|
|
720
973
|
currencyCode: currency, isAuthorized: ctx.isAuthorized, authorizedAsOwnerOnly: ctx.authorizedAsOwnerOnly,
|
|
721
974
|
});
|
|
722
|
-
|
|
975
|
+
// The pay link on acceptance converts on the customer's click: no administrator, no permission to check.
|
|
976
|
+
if (!opts.system && !octx.userHasPermissions([core_1.Permission.CreateOrder])) {
|
|
723
977
|
return { ok: false, reason: `You need the CreateOrder permission on channel ${channel.code} to convert this quote` };
|
|
724
978
|
}
|
|
725
979
|
// Claim the quote before creating anything, so a double click or a retried request cannot make two draft orders.
|
|
@@ -749,6 +1003,7 @@ let QuotationService = class QuotationService {
|
|
|
749
1003
|
taxLines: surcharge.taxLines,
|
|
750
1004
|
});
|
|
751
1005
|
}
|
|
1006
|
+
await this.attachCustomer(octx, Number(draft.id), q);
|
|
752
1007
|
await this.db.query(`UPDATE quotation SET convertedOrderId=?, updatedAt=NOW() WHERE id = ?`, [draft.id, quoteId]);
|
|
753
1008
|
await this.logEvent(quoteId, 'converted', `Draft order ${(fresh === null || fresh === void 0 ? void 0 : fresh.code) || draft.id} created`, actor);
|
|
754
1009
|
return { ok: true, orderId: Number(draft.id), orderCode: fresh === null || fresh === void 0 ? void 0 : fresh.code };
|
|
@@ -759,6 +1014,37 @@ let QuotationService = class QuotationService {
|
|
|
759
1014
|
return { ok: false, reason: e.message };
|
|
760
1015
|
}
|
|
761
1016
|
}
|
|
1017
|
+
/**
|
|
1018
|
+
* Put the quote's customer on the draft order: the linked account, else an
|
|
1019
|
+
* existing customer with the quote's e-mail address (never renamed), else
|
|
1020
|
+
* a new guest customer. Best effort: a failure leaves the draft without a
|
|
1021
|
+
* customer, as before, for the admin to set.
|
|
1022
|
+
*/
|
|
1023
|
+
async attachCustomer(ctx, orderId, q) {
|
|
1024
|
+
try {
|
|
1025
|
+
const repo = this.connection.getRepository(ctx, core_1.Customer);
|
|
1026
|
+
let customer = null;
|
|
1027
|
+
if (q.customerId)
|
|
1028
|
+
customer = await repo.findOne({ where: { id: q.customerId } });
|
|
1029
|
+
const email = String(q.customerEmail || '').trim().toLowerCase();
|
|
1030
|
+
if (!customer && email)
|
|
1031
|
+
customer = await repo.findOne({ where: { emailAddress: email } });
|
|
1032
|
+
if (!customer && email && this.customerService) {
|
|
1033
|
+
const parts = String(q.customerName || '').trim().split(/\s+/);
|
|
1034
|
+
const created = await this.customerService.createOrUpdate(ctx, {
|
|
1035
|
+
emailAddress: email, firstName: parts[0] || '', lastName: parts.slice(1).join(' ') || '',
|
|
1036
|
+
phoneNumber: q.customerPhone || undefined,
|
|
1037
|
+
}, false);
|
|
1038
|
+
if (created && !created.errorCode)
|
|
1039
|
+
customer = created;
|
|
1040
|
+
}
|
|
1041
|
+
if ((customer === null || customer === void 0 ? void 0 : customer.id) && !customer.deletedAt)
|
|
1042
|
+
await this.orderService.addCustomerToOrder(ctx, orderId, customer);
|
|
1043
|
+
}
|
|
1044
|
+
catch (e) {
|
|
1045
|
+
core_1.Logger.warn(`could not put the customer of quote ${q.reference} on its draft order: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx);
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
762
1048
|
/**
|
|
763
1049
|
* Keep a converted draft order at the quoted price when it leaves Draft. Vendure 3.8+
|
|
764
1050
|
* recalculates every order on the transition to ArrangingPayment, so catalogue price or
|
|
@@ -896,7 +1182,17 @@ let QuotationService = class QuotationService {
|
|
|
896
1182
|
* gets an acknowledgement carrying the reference. Never throws for
|
|
897
1183
|
* bots: honeypot hits look successful and persist nothing.
|
|
898
1184
|
*/
|
|
899
|
-
|
|
1185
|
+
/** Requests from this address in the last hour, from the database (shared by every process, kept across restarts). */
|
|
1186
|
+
async recentRequestsFor(email) {
|
|
1187
|
+
const [row] = await this.db.query(`SELECT COUNT(*) AS n FROM quotation WHERE customerEmail = ? AND requestedAt IS NOT NULL AND requestedAt > DATE_SUB(NOW(), INTERVAL 1 HOUR)`, [email]).catch(() => [{ n: 0 }]);
|
|
1188
|
+
return Number((row === null || row === void 0 ? void 0 : row.n) || 0);
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* `customerId` is the signed-in storefront customer, when the request
|
|
1192
|
+
* carried a shop session: the request is then linked to that account (and
|
|
1193
|
+
* shows under "My quotes"). Guest requests are never linked by e-mail.
|
|
1194
|
+
*/
|
|
1195
|
+
async createRequest(channelId, input, clientKey, customerId = null) {
|
|
900
1196
|
const cfg = await this.getConfig(channelId);
|
|
901
1197
|
if (!cfg.acceptRequests)
|
|
902
1198
|
return { ok: false, reason: 'Quote requests are not accepted on this channel' };
|
|
@@ -907,6 +1203,8 @@ let QuotationService = class QuotationService {
|
|
|
907
1203
|
return { ok: false, reason: 'Please enter a valid email address' };
|
|
908
1204
|
if (!this.requestAllowed(clientKey || email) || !this.requestAllowed(`email:${email}`))
|
|
909
1205
|
return { ok: false, reason: 'Too many requests — please try again later' };
|
|
1206
|
+
if (await this.recentRequestsFor(email) >= REQUESTS_PER_EMAIL_PER_HOUR)
|
|
1207
|
+
return { ok: false, reason: 'Too many requests — please try again later' };
|
|
910
1208
|
const message = String(input.message || '').trim().slice(0, 2000);
|
|
911
1209
|
const source = String(input.source || 'storefront').trim().slice(0, 64);
|
|
912
1210
|
const rawLines = Array.isArray(input.lines) ? input.lines.slice(0, 50) : [];
|
|
@@ -916,9 +1214,8 @@ let QuotationService = class QuotationService {
|
|
|
916
1214
|
return { ok: false, reason: 'Tell us what you need a quote for' };
|
|
917
1215
|
lines = [{ productVariantId: null, sku: '', description: `Customer enquiry — see request: ${message.slice(0, 120)}`, quantity: 1, unitPricePence: 0 }];
|
|
918
1216
|
}
|
|
919
|
-
const [existingCustomer] = await this.db.query(`SELECT id FROM customer WHERE \`emailAddress\` = ? AND \`deletedAt\` IS NULL LIMIT 1`, [email]).catch(() => []);
|
|
920
1217
|
const q = await this.createQuote(channelId, {
|
|
921
|
-
customerId:
|
|
1218
|
+
customerId: customerId || null,
|
|
922
1219
|
customerName: String(input.name || '').trim().slice(0, 190) || email,
|
|
923
1220
|
customerEmail: email,
|
|
924
1221
|
customerCompany: String(input.company || '').trim().slice(0, 190),
|
|
@@ -929,8 +1226,21 @@ let QuotationService = class QuotationService {
|
|
|
929
1226
|
await this.logEvent(q.id, 'requested', `Requested by the customer via ${source}${message ? ` — "${message.slice(0, 200)}"` : ''}`, email);
|
|
930
1227
|
const summary = lines.map(l => `${l.quantity} × ${l.description}${l.unitPricePence ? ` @ ${(0, pricing_1.formatMoney)(l.unitPricePence, q.currency)}` : ''}`).join('\n');
|
|
931
1228
|
const indicative = lines.some(l => l.unitPricePence > 0) ? ` — indicative ${(0, pricing_1.formatMoney)(q.totalPence, q.currency)} at list` : '';
|
|
932
|
-
void this.notifyMerchant(q, cfg, `New quote request ${q.reference} from ${q.customerCompany || q.customerName}`,
|
|
933
|
-
|
|
1229
|
+
void this.notifyMerchant(q, cfg, `New quote request ${q.reference} from ${q.customerCompany || q.customerName}`, (0, emails_1.staffMail)(cfg, {
|
|
1230
|
+
heading: `New quote request ${q.reference}`,
|
|
1231
|
+
intro: `${q.customerName || email} asked for a quote via ${source}${indicative}.`,
|
|
1232
|
+
rows: [
|
|
1233
|
+
{ label: 'Reference', value: String(q.reference || ''), mono: true },
|
|
1234
|
+
{ label: 'Name', value: String(q.customerName || '') },
|
|
1235
|
+
{ label: 'E-mail', value: email },
|
|
1236
|
+
{ label: 'Company', value: String(q.customerCompany || '') },
|
|
1237
|
+
{ label: 'Phone', value: String(q.customerPhone || '') },
|
|
1238
|
+
],
|
|
1239
|
+
list: { title: 'Requested', items: summary ? summary.split('\n') : [] },
|
|
1240
|
+
note: message ? { title: 'Message', text: message } : undefined,
|
|
1241
|
+
outro: `Open Quotations → ${q.reference}, price it and click Send.`,
|
|
1242
|
+
button: this.adminButton(q, 'Price the request'),
|
|
1243
|
+
}));
|
|
934
1244
|
// The endpoint is public, so the acknowledgement must not relay anything the requester typed (name,
|
|
935
1245
|
// free-text lines, message) to an address they chose: it lists catalogue lines by their catalogue name only.
|
|
936
1246
|
const catalogueLines = lines.filter(l => l.productVariantId && l.unitPricePence > 0);
|
|
@@ -976,7 +1286,7 @@ let QuotationService = class QuotationService {
|
|
|
976
1286
|
// Not the requester-supplied name: anyone can post any name for any address.
|
|
977
1287
|
customerName: 'there', reference: q.reference, businessName: cfg.businessName || '', summary,
|
|
978
1288
|
};
|
|
979
|
-
const
|
|
1289
|
+
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 : ''; }));
|
|
980
1290
|
try {
|
|
981
1291
|
const transporter = this.transporter(smtp);
|
|
982
1292
|
await this.sendWithDeadline(transporter, {
|
|
@@ -984,7 +1294,8 @@ let QuotationService = class QuotationService {
|
|
|
984
1294
|
to,
|
|
985
1295
|
replyTo: cfg.replyTo || cfg.notifyEmail || undefined,
|
|
986
1296
|
subject: `We've received your quote request (${q.reference})`,
|
|
987
|
-
text,
|
|
1297
|
+
text: mail.text,
|
|
1298
|
+
html: mail.html,
|
|
988
1299
|
});
|
|
989
1300
|
await this.logEvent(q.id, 'ack', `Acknowledgement emailed to ${q.customerEmail}`);
|
|
990
1301
|
}
|
|
@@ -1055,14 +1366,99 @@ let QuotationService = class QuotationService {
|
|
|
1055
1366
|
WHERE \`deletedAt\` IS NULL AND (\`firstName\` LIKE ? OR \`lastName\` LIKE ? OR \`emailAddress\` LIKE ?)
|
|
1056
1367
|
ORDER BY \`lastName\` ASC LIMIT 20`, [like, like, like]).catch(() => []);
|
|
1057
1368
|
}
|
|
1058
|
-
/** Send the real quote email to a staff address instead of the customer. */
|
|
1369
|
+
/** Send the real quote email to a staff address instead of the customer. The quote does not change. Free. */
|
|
1059
1370
|
async testSend(quoteId, to) {
|
|
1060
1371
|
const q = await this.getQuote(quoteId);
|
|
1061
1372
|
if (!q)
|
|
1062
1373
|
return { ok: false, reason: 'Quote not found' };
|
|
1374
|
+
const held = await this.preSend(q, 'test', to);
|
|
1375
|
+
if (held)
|
|
1376
|
+
return { ok: false, reason: held };
|
|
1063
1377
|
const cfg = await this.getConfig(q.channelId);
|
|
1064
1378
|
return this.deliverEmail(q, cfg, 'quote', to);
|
|
1065
1379
|
}
|
|
1380
|
+
/**
|
|
1381
|
+
* The customer quote page exactly as the customer would see it, for staff:
|
|
1382
|
+
* it does not count as an opening and its accept form is switched off.
|
|
1383
|
+
*/
|
|
1384
|
+
async staffPreviewHtml(quoteId) {
|
|
1385
|
+
const q = await this.getQuote(quoteId);
|
|
1386
|
+
if (!q)
|
|
1387
|
+
return null;
|
|
1388
|
+
const cfg = await this.getConfig(q.channelId);
|
|
1389
|
+
if (q.status === 'draft' || q.status === 'requested') {
|
|
1390
|
+
// Not sent yet: show the dates the customer will get when it goes out now.
|
|
1391
|
+
q.validUntil = new Date(Date.now() + this.validityDaysOf(q, cfg) * DAY_MS);
|
|
1392
|
+
q.status = 'sent';
|
|
1393
|
+
}
|
|
1394
|
+
return (0, templates_1.renderQuotePage)(q, cfg, { preview: true, extra: await this.pageExtras(q) });
|
|
1395
|
+
}
|
|
1396
|
+
async pageExtras(q) {
|
|
1397
|
+
const base = this.pageExtrasProvider ? await this.pageExtrasProvider(q).catch(() => ({})) : {};
|
|
1398
|
+
return { ...base, pdfUrl: q.token ? `${this.quoteUrl(q.token)}/pdf` : undefined };
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* The quote as a PDF (free). The "accept online" line is printed while the
|
|
1402
|
+
* customer can still respond. Drafts render with the dates they would get
|
|
1403
|
+
* if sent now.
|
|
1404
|
+
*/
|
|
1405
|
+
async quotePdf(quoteId, token) {
|
|
1406
|
+
const q = quoteId ? await this.getQuote(quoteId) : token ? await this.getQuoteByToken(token) : null;
|
|
1407
|
+
if (!q)
|
|
1408
|
+
return null;
|
|
1409
|
+
const cfg = await this.getConfig(q.channelId);
|
|
1410
|
+
if (q.status === 'draft' || q.status === 'requested')
|
|
1411
|
+
q.validUntil = new Date(Date.now() + this.validityDaysOf(q, cfg) * DAY_MS);
|
|
1412
|
+
const extras = this.pageExtrasProvider ? await this.pageExtrasProvider(q).catch(() => ({})) : {};
|
|
1413
|
+
const acceptUrl = OPEN_STATUSES.includes(q.status) ? this.quoteUrl(q.token) : null;
|
|
1414
|
+
return {
|
|
1415
|
+
filename: `Quotation-${String(q.reference).replace(/[^A-Za-z0-9._-]/g, '_')}.pdf`,
|
|
1416
|
+
pdf: (0, pdf_1.renderQuotePdf)(q, cfg, acceptUrl, { depositText: extras === null || extras === void 0 ? void 0 : extras.depositText }),
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
// ── "My quotes" for signed-in customers ─────────────────────────────
|
|
1420
|
+
/** The customer id behind a storefront session's user, or null. */
|
|
1421
|
+
async customerIdForUser(userId) {
|
|
1422
|
+
if (!userId)
|
|
1423
|
+
return null;
|
|
1424
|
+
const [row] = await this.db.query(`SELECT id FROM customer WHERE \`userId\` = ? AND \`deletedAt\` IS NULL LIMIT 1`, [Number(userId)]).catch(() => []);
|
|
1425
|
+
return (row === null || row === void 0 ? void 0 : row.id) ? Number(row.id) : null;
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* Quotes linked to one customer account (customerId), never matched by
|
|
1429
|
+
* e-mail: each row carries the quote's secret link. Drafts are the store's
|
|
1430
|
+
* work in progress and never shown; requests show as "awaiting price".
|
|
1431
|
+
*/
|
|
1432
|
+
async quotesForCustomer(customerId, channelId) {
|
|
1433
|
+
if (!customerId)
|
|
1434
|
+
return [];
|
|
1435
|
+
const params = [customerId];
|
|
1436
|
+
let chan = '';
|
|
1437
|
+
if (channelId) {
|
|
1438
|
+
chan = ' AND channelId = ?';
|
|
1439
|
+
params.push(channelId);
|
|
1440
|
+
}
|
|
1441
|
+
const rows = await this.db.query(`SELECT id, channelId, reference, status, token, currency, totalPence, validUntil, sentAt, createdAt, respondedAt, paidAt, payUrl, convertedOrderId
|
|
1442
|
+
FROM quotation WHERE customerId = ?${chan} AND status <> 'draft' ORDER BY id DESC LIMIT 100`, params);
|
|
1443
|
+
const out = [];
|
|
1444
|
+
for (const r of rows) {
|
|
1445
|
+
const extras = this.pageExtrasProvider ? await this.pageExtrasProvider(r).catch(() => ({})) : {};
|
|
1446
|
+
const visible = r.status !== 'requested';
|
|
1447
|
+
out.push({
|
|
1448
|
+
id: Number(r.id), reference: r.reference, status: r.status,
|
|
1449
|
+
statusLabel: r.paidAt || (extras === null || extras === void 0 ? void 0 : extras.paid) ? 'Paid' : r.status === 'requested' ? 'Awaiting price' : r.status,
|
|
1450
|
+
date: r.sentAt || r.createdAt,
|
|
1451
|
+
validUntil: r.status === 'requested' ? null : r.validUntil,
|
|
1452
|
+
totalPence: r.status === 'requested' ? null : Number(r.totalPence), currency: r.currency,
|
|
1453
|
+
url: visible ? this.quoteUrl(r.token) : null,
|
|
1454
|
+
pdfUrl: visible ? `${this.quoteUrl(r.token)}/pdf` : null,
|
|
1455
|
+
payUrl: !r.paidAt && (extras === null || extras === void 0 ? void 0 : extras.payUrl) ? extras.payUrl : null,
|
|
1456
|
+
paid: !!(r.paidAt || (extras === null || extras === void 0 ? void 0 : extras.paid)),
|
|
1457
|
+
canRespond: OPEN_STATUSES.includes(r.status),
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
return out;
|
|
1461
|
+
}
|
|
1066
1462
|
/** The customer email, rendered for preview. */
|
|
1067
1463
|
async previewEmail(quoteId) {
|
|
1068
1464
|
const q = await this.getQuote(quoteId);
|
|
@@ -1079,7 +1475,7 @@ let QuotationService = class QuotationService {
|
|
|
1079
1475
|
quoteUrl: url,
|
|
1080
1476
|
};
|
|
1081
1477
|
const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
|
|
1082
|
-
return { ok: true, html: (0,
|
|
1478
|
+
return { ok: true, html: (0, emails_1.customerQuoteMail)({ q, cfg, kind: 'quote', body: render(cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody), quoteUrl: url }).html };
|
|
1083
1479
|
}
|
|
1084
1480
|
/** Extend an open (or expired) quote's validity; expired quotes revive. */
|
|
1085
1481
|
async extendValidity(quoteId, days, actor) {
|
|
@@ -1108,41 +1504,57 @@ let QuotationService = class QuotationService {
|
|
|
1108
1504
|
return this.getQuote(quoteId);
|
|
1109
1505
|
}
|
|
1110
1506
|
// ── Crons ───────────────────────────────────────────────────────────
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1507
|
+
/** Expire quotes whose validity has passed (free), one by one so each gets its trail entry and event. */
|
|
1508
|
+
async expireOverdue(batch = 500) {
|
|
1509
|
+
const rows = await this.db.query(`SELECT id FROM quotation WHERE status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW() ORDER BY id LIMIT ${Math.max(1, Math.min(5000, batch))}`);
|
|
1510
|
+
let n = 0;
|
|
1511
|
+
for (const r of rows) {
|
|
1512
|
+
const res = await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW() WHERE id = ? AND status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW()`, [r.id], { needAffected: true });
|
|
1513
|
+
if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
|
|
1514
|
+
n++;
|
|
1515
|
+
await this.logEvent(Number(r.id), 'expired', 'Validity ended');
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1115
1518
|
if (n)
|
|
1116
1519
|
core_1.Logger.info(`marked ${n} quote(s) expired`, loggerCtx);
|
|
1117
1520
|
return n;
|
|
1118
1521
|
}
|
|
1522
|
+
/** Claim one reminder (its column still empty), send it, and release the claim when the e-mail fails. */
|
|
1523
|
+
async remind(r, cfg, column, kind) {
|
|
1524
|
+
const claim = await this.db.query(`UPDATE quotation SET ${column} = NOW() WHERE id = ? AND ${column} IS NULL`, [r.id], { needAffected: true });
|
|
1525
|
+
if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) !== 1)
|
|
1526
|
+
return false;
|
|
1527
|
+
const q = await this.getQuote(Number(r.id));
|
|
1528
|
+
const res = q ? await this.deliverEmail(q, cfg, kind) : { ok: false };
|
|
1529
|
+
if (res.ok)
|
|
1530
|
+
return true;
|
|
1531
|
+
await this.db.query(`UPDATE quotation SET ${column} = NULL WHERE id = ?`, [r.id]).catch(() => undefined);
|
|
1532
|
+
return false;
|
|
1533
|
+
}
|
|
1534
|
+
/** The hourly reminders (free): one chaser for an unopened quote, one expires-soon reminder. */
|
|
1119
1535
|
async runChasers() {
|
|
1120
1536
|
const out = { chasers: 0, expiryReminders: 0 };
|
|
1121
1537
|
const configs = await this.getAllConfigs();
|
|
1122
1538
|
for (const cfg of configs) {
|
|
1123
1539
|
if (cfg.chaserEnabled) {
|
|
1124
|
-
const rows = await this.db.query(`SELECT
|
|
1125
|
-
WHERE channelId = ? AND status = 'sent' AND chaserSentAt IS NULL
|
|
1540
|
+
const rows = await this.db.query(`SELECT id FROM quotation
|
|
1541
|
+
WHERE channelId = ? AND status = 'sent' AND viewedAt IS NULL AND chaserSentAt IS NULL
|
|
1126
1542
|
AND sentAt IS NOT NULL AND sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
|
|
1127
|
-
AND (validUntil IS NULL OR validUntil > NOW()) LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
|
|
1543
|
+
AND (validUntil IS NULL OR validUntil > NOW()) ORDER BY id LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
|
|
1128
1544
|
for (const r of rows) {
|
|
1129
|
-
|
|
1130
|
-
if (res.ok) {
|
|
1131
|
-
await this.db.query(`UPDATE quotation SET chaserSentAt=NOW() WHERE id = ?`, [r.id]);
|
|
1545
|
+
if (await this.remind(r, cfg, 'chaserSentAt', 'chaser')) {
|
|
1132
1546
|
await this.logEvent(r.id, 'chaser_sent', 'Unopened-quote reminder emailed');
|
|
1133
1547
|
out.chasers++;
|
|
1134
1548
|
}
|
|
1135
1549
|
}
|
|
1136
1550
|
}
|
|
1137
1551
|
if (cfg.expiryReminderDays > 0) {
|
|
1138
|
-
const rows = await this.db.query(`SELECT
|
|
1552
|
+
const rows = await this.db.query(`SELECT id FROM quotation
|
|
1139
1553
|
WHERE channelId = ? AND status IN ('sent','viewed') AND expiryReminderSentAt IS NULL
|
|
1140
1554
|
AND validUntil IS NOT NULL AND validUntil > NOW()
|
|
1141
|
-
AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
|
|
1555
|
+
AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) ORDER BY validUntil LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
|
|
1142
1556
|
for (const r of rows) {
|
|
1143
|
-
|
|
1144
|
-
if (res.ok) {
|
|
1145
|
-
await this.db.query(`UPDATE quotation SET expiryReminderSentAt=NOW() WHERE id = ?`, [r.id]);
|
|
1557
|
+
if (await this.remind(r, cfg, 'expiryReminderSentAt', 'expiry')) {
|
|
1146
1558
|
await this.logEvent(r.id, 'expiry_reminder_sent', 'Expiry reminder emailed');
|
|
1147
1559
|
out.expiryReminders++;
|
|
1148
1560
|
}
|
|
@@ -1152,49 +1564,150 @@ let QuotationService = class QuotationService {
|
|
|
1152
1564
|
return out;
|
|
1153
1565
|
}
|
|
1154
1566
|
// ── Stats ───────────────────────────────────────────────────────────
|
|
1567
|
+
/** Per-currency sums: money is never added across currencies. */
|
|
1568
|
+
static byCurrency(rows, value = 'value') {
|
|
1569
|
+
const out = {};
|
|
1570
|
+
for (const r of rows) {
|
|
1571
|
+
const v = Number((r === null || r === void 0 ? void 0 : r[value]) || 0);
|
|
1572
|
+
if (!v)
|
|
1573
|
+
continue;
|
|
1574
|
+
const c = String(r.currency || 'GBP').toUpperCase();
|
|
1575
|
+
out[c] = (out[c] || 0) + v;
|
|
1576
|
+
}
|
|
1577
|
+
return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b)));
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* KPIs for the Quotes tab. Money is reported per currency (B5): every
|
|
1581
|
+
* value is a `{ GBP: …, EUR: … }` map in minor units.
|
|
1582
|
+
*/
|
|
1155
1583
|
async stats(channelId) {
|
|
1156
1584
|
const where = channelId ? 'WHERE channelId = ?' : '';
|
|
1157
1585
|
const params = channelId ? [channelId] : [];
|
|
1158
|
-
const
|
|
1586
|
+
const rows = await this.db.query(`SELECT status, currency, COUNT(*) AS n, SUM(totalPence) AS value FROM quotation ${where} GROUP BY status, currency`, params);
|
|
1587
|
+
const statusMap = new Map();
|
|
1588
|
+
for (const r of rows) {
|
|
1589
|
+
const e = statusMap.get(r.status) || { status: r.status, n: 0, rows: [] };
|
|
1590
|
+
e.n += Number(r.n || 0);
|
|
1591
|
+
e.rows.push(r);
|
|
1592
|
+
statusMap.set(r.status, e);
|
|
1593
|
+
}
|
|
1594
|
+
const byStatus = [...statusMap.values()].map(e => ({ status: e.status, n: e.n, valueByCurrency: QuotationService_1.byCurrency(e.rows) }));
|
|
1595
|
+
const pipeline = QuotationService_1.byCurrency(rows.filter((r) => r.status === 'sent' || r.status === 'viewed'));
|
|
1159
1596
|
const [resp] = await this.db.query(`SELECT COUNT(*) AS n, AVG(TIMESTAMPDIFF(SECOND, sentAt, respondedAt)) AS avgSeconds
|
|
1160
1597
|
FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt IS NOT NULL AND sentAt IS NOT NULL`, params);
|
|
1161
1598
|
const [last30] = await this.db.query(`SELECT COUNT(*) AS sent, SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won
|
|
1162
1599
|
FROM quotation ${where ? where + ' AND' : 'WHERE'} sentAt > DATE_SUB(NOW(), INTERVAL 30 DAY)`, params);
|
|
1163
1600
|
const sent30 = Number((last30 === null || last30 === void 0 ? void 0 : last30.sent) || 0);
|
|
1164
1601
|
const [req] = await this.db.query(`SELECT COUNT(*) AS n, MIN(requestedAt) AS oldest FROM quotation ${where ? where + ' AND' : 'WHERE'} status = 'requested'`, params);
|
|
1165
|
-
// Value won: quotes the customer accepted in the last 30 days (by response date, not send date).
|
|
1166
|
-
const
|
|
1167
|
-
|
|
1168
|
-
|
|
1602
|
+
// Value won: quotes the customer accepted in the last 30 days (by response date, not send date), per currency.
|
|
1603
|
+
const won30 = await this.db.query(`SELECT currency, COUNT(*) AS n, SUM(totalPence) AS value
|
|
1604
|
+
FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt > DATE_SUB(NOW(), INTERVAL 30 DAY) AND status IN ('accepted','converted')
|
|
1605
|
+
GROUP BY currency`, params).catch(() => []);
|
|
1169
1606
|
return {
|
|
1170
1607
|
byStatus,
|
|
1608
|
+
pipelineByCurrency: pipeline,
|
|
1171
1609
|
requests: { open: Number((req === null || req === void 0 ? void 0 : req.n) || 0), oldestAt: (req === null || req === void 0 ? void 0 : req.oldest) || null },
|
|
1172
1610
|
avgResponseHours: (resp === null || resp === void 0 ? void 0 : resp.avgSeconds) ? Math.round(Number(resp.avgSeconds) / 360) / 10 : null,
|
|
1173
1611
|
last30: {
|
|
1174
1612
|
sent: sent30, won: Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0),
|
|
1175
1613
|
winRate: sent30 ? Math.round((Number((last30 === null || last30 === void 0 ? void 0 : last30.won) || 0) / sent30) * 100) : null,
|
|
1176
|
-
|
|
1614
|
+
valueWonByCurrency: QuotationService_1.byCurrency(won30),
|
|
1615
|
+
accepted: won30.reduce((a, r) => a + Number(r.n || 0), 0),
|
|
1177
1616
|
},
|
|
1178
1617
|
};
|
|
1179
1618
|
}
|
|
1619
|
+
/**
|
|
1620
|
+
* The last 12 calendar months (free): per month, quotes created, sent and
|
|
1621
|
+
* accepted, the win rate on quotes sent that month, and the value won per
|
|
1622
|
+
* currency (by the month the customer accepted).
|
|
1623
|
+
*/
|
|
1624
|
+
async monthlyReport(channelId, now = new Date()) {
|
|
1625
|
+
const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 11, 1));
|
|
1626
|
+
const chan = channelId ? ' AND channelId = ?' : '';
|
|
1627
|
+
const p = (extra = []) => [start, ...(channelId ? [channelId] : []), ...extra];
|
|
1628
|
+
const created = await this.db.query(`SELECT EXTRACT(YEAR FROM createdAt) AS y, EXTRACT(MONTH FROM createdAt) AS m, COUNT(*) AS n
|
|
1629
|
+
FROM quotation WHERE createdAt >= ?${chan} GROUP BY EXTRACT(YEAR FROM createdAt), EXTRACT(MONTH FROM createdAt)`, p());
|
|
1630
|
+
const sent = await this.db.query(`SELECT EXTRACT(YEAR FROM sentAt) AS y, EXTRACT(MONTH FROM sentAt) AS m, COUNT(*) AS n,
|
|
1631
|
+
SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won
|
|
1632
|
+
FROM quotation WHERE sentAt >= ?${chan} GROUP BY EXTRACT(YEAR FROM sentAt), EXTRACT(MONTH FROM sentAt)`, p());
|
|
1633
|
+
const won = await this.db.query(`SELECT EXTRACT(YEAR FROM respondedAt) AS y, EXTRACT(MONTH FROM respondedAt) AS m, currency, COUNT(*) AS n, SUM(totalPence) AS value
|
|
1634
|
+
FROM quotation WHERE respondedAt >= ?${chan} AND status IN ('accepted','converted')
|
|
1635
|
+
GROUP BY EXTRACT(YEAR FROM respondedAt), EXTRACT(MONTH FROM respondedAt), currency`, p());
|
|
1636
|
+
const key = (y, m) => `${Number(y)}-${String(Number(m)).padStart(2, '0')}`;
|
|
1637
|
+
const months = [];
|
|
1638
|
+
for (let i = 0; i < 12; i++) {
|
|
1639
|
+
const d = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + i, 1));
|
|
1640
|
+
months.push({ month: key(d.getUTCFullYear(), d.getUTCMonth() + 1), created: 0, sent: 0, sentWon: 0, accepted: 0, winRatePct: null, wonByCurrency: {} });
|
|
1641
|
+
}
|
|
1642
|
+
const at = (y, m) => months.find(x => x.month === key(y, m));
|
|
1643
|
+
for (const r of created) {
|
|
1644
|
+
const e = at(r.y, r.m);
|
|
1645
|
+
if (e)
|
|
1646
|
+
e.created += Number(r.n || 0);
|
|
1647
|
+
}
|
|
1648
|
+
for (const r of sent) {
|
|
1649
|
+
const e = at(r.y, r.m);
|
|
1650
|
+
if (e) {
|
|
1651
|
+
e.sent += Number(r.n || 0);
|
|
1652
|
+
e.sentWon += Number(r.won || 0);
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
const currencies = new Set();
|
|
1656
|
+
for (const r of won) {
|
|
1657
|
+
const e = at(r.y, r.m);
|
|
1658
|
+
if (!e)
|
|
1659
|
+
continue;
|
|
1660
|
+
e.accepted += Number(r.n || 0);
|
|
1661
|
+
const c = String(r.currency || 'GBP').toUpperCase();
|
|
1662
|
+
if (Number(r.value || 0)) {
|
|
1663
|
+
e.wonByCurrency[c] = (e.wonByCurrency[c] || 0) + Number(r.value);
|
|
1664
|
+
currencies.add(c);
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
for (const e of months)
|
|
1668
|
+
e.winRatePct = e.sent ? Math.round((e.sentWon / e.sent) * 1000) / 10 : null;
|
|
1669
|
+
return { months, currencies: [...currencies].sort() };
|
|
1670
|
+
}
|
|
1180
1671
|
// ── Usage figures (evaluation + heartbeat stats, weekly report, widget) ──
|
|
1672
|
+
/** The store's main currency: the default channel's, else the first channel config's, else GBP. */
|
|
1673
|
+
async primaryCurrency() {
|
|
1674
|
+
try {
|
|
1675
|
+
const ch = await this.channelService.getDefaultChannel();
|
|
1676
|
+
if (ch === null || ch === void 0 ? void 0 : ch.defaultCurrencyCode)
|
|
1677
|
+
return String(ch.defaultCurrencyCode).toUpperCase();
|
|
1678
|
+
const cfg = await this.getConfig(Number(ch === null || ch === void 0 ? void 0 : ch.id) || 1);
|
|
1679
|
+
return String(cfg.currency || 'GBP').toUpperCase();
|
|
1680
|
+
}
|
|
1681
|
+
catch {
|
|
1682
|
+
return 'GBP';
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
/** Value won (accepted, by response date) in `[from, to)`, per currency. */
|
|
1686
|
+
async periodWonByCurrency(from, to) {
|
|
1687
|
+
const rows = await this.db.query(`SELECT currency, SUM(totalPence) AS value FROM quotation
|
|
1688
|
+
WHERE respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') GROUP BY currency`, [from, to]).catch(() => []);
|
|
1689
|
+
return QuotationService_1.byCurrency(rows);
|
|
1690
|
+
}
|
|
1181
1691
|
/**
|
|
1182
1692
|
* Counts for one period `[from, to)`:
|
|
1183
1693
|
* - quotesCreated / quotesSent / requestsReceived — by their own timestamp
|
|
1184
|
-
* - quotesAccepted
|
|
1185
|
-
*
|
|
1694
|
+
* - quotesAccepted — accepted (or since converted) with the customer's
|
|
1695
|
+
* response inside the period
|
|
1696
|
+
* - valueWonPence — the value of those, in the store's main currency only
|
|
1697
|
+
* (never summed across currencies; see periodWonByCurrency for the rest)
|
|
1186
1698
|
* - winRatePct — of the quotes *sent* in the period, the share accepted so far
|
|
1187
1699
|
* Every event also bumps `updatedAt`, so the scan is bounded by it.
|
|
1188
1700
|
*/
|
|
1189
1701
|
async periodStats(from, to) {
|
|
1190
1702
|
try {
|
|
1703
|
+
const currency = await this.primaryCurrency();
|
|
1191
1704
|
const [row] = await this.db.query(`SELECT SUM(CASE WHEN createdAt >= ? AND createdAt < ? THEN 1 ELSE 0 END) AS created,
|
|
1192
1705
|
SUM(CASE WHEN sentAt >= ? AND sentAt < ? THEN 1 ELSE 0 END) AS sent,
|
|
1193
1706
|
SUM(CASE WHEN sentAt >= ? AND sentAt < ? AND status IN ('accepted','converted') THEN 1 ELSE 0 END) AS sentWon,
|
|
1194
1707
|
SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') THEN 1 ELSE 0 END) AS accepted,
|
|
1195
|
-
SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS wonPence,
|
|
1708
|
+
SUM(CASE WHEN respondedAt >= ? AND respondedAt < ? AND status IN ('accepted','converted') AND currency = ? THEN totalPence ELSE 0 END) AS wonPence,
|
|
1196
1709
|
SUM(CASE WHEN requestedAt >= ? AND requestedAt < ? THEN 1 ELSE 0 END) AS requests
|
|
1197
|
-
FROM quotation WHERE updatedAt >= ?`, [from, to, from, to, from, to, from, to, from, to, from, to, from]);
|
|
1710
|
+
FROM quotation WHERE updatedAt >= ?`, [from, to, from, to, from, to, from, to, from, to, currency, from, to, from]);
|
|
1198
1711
|
const n = (v) => Number(v || 0);
|
|
1199
1712
|
const sent = n(row === null || row === void 0 ? void 0 : row.sent);
|
|
1200
1713
|
return {
|
|
@@ -1217,27 +1730,48 @@ let QuotationService = class QuotationService {
|
|
|
1217
1730
|
const now = new Date();
|
|
1218
1731
|
return this.periodStats(new Date(now.getTime() - 30 * DAY_MS), now);
|
|
1219
1732
|
}
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1733
|
+
/**
|
|
1734
|
+
* The figures as report lines. Value won is one line per currency when
|
|
1735
|
+
* quotes were won in more than one currency, or in a currency other than
|
|
1736
|
+
* GBP (the report's money format): never one sum across currencies.
|
|
1737
|
+
*/
|
|
1738
|
+
toDigestStats(current, previous, wonByCurrency) {
|
|
1739
|
+
const out = [];
|
|
1740
|
+
for (const d of exports.STAT_DEFS) {
|
|
1741
|
+
const won = wonByCurrency ? Object.entries(wonByCurrency).filter(([, v]) => v) : [];
|
|
1742
|
+
if (d.key === 'valueWonPence' && (won.length > 1 || (won.length === 1 && won[0][0] !== 'GBP'))) {
|
|
1743
|
+
out.push({
|
|
1744
|
+
key: d.key, label: d.label, format: 'text',
|
|
1745
|
+
value: won.length, previous: null,
|
|
1746
|
+
text: won.map(([c, v]) => (0, pricing_1.formatMoney)(v, c)).join(' + '),
|
|
1747
|
+
});
|
|
1748
|
+
continue;
|
|
1749
|
+
}
|
|
1750
|
+
out.push({
|
|
1751
|
+
key: d.key, label: d.label, format: d.format,
|
|
1752
|
+
value: d.key === 'valueWonPence' && wonByCurrency ? Number(wonByCurrency.GBP || 0) : Number(current[d.key] || 0),
|
|
1753
|
+
previous: previous ? Number(previous[d.key] || 0) : null,
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
return out;
|
|
1226
1757
|
}
|
|
1227
1758
|
/** Top three non-zero 30-day figures, formatted for the admin banner. */
|
|
1228
1759
|
async recentStats() {
|
|
1229
|
-
const
|
|
1760
|
+
const now = new Date();
|
|
1761
|
+
const from = new Date(now.getTime() - 30 * DAY_MS);
|
|
1762
|
+
const stats = this.toDigestStats(await this.evalStats(), undefined, await this.periodWonByCurrency(from, now));
|
|
1230
1763
|
return stats.filter(s => s.value > 0).slice(0, 3).map(s => ({ label: s.label, value: (0, vendure_licence_sdk_1.formatStat)(s) }));
|
|
1231
1764
|
}
|
|
1232
|
-
/** Three headline figures for the dashboard widget (last 7 days). */
|
|
1765
|
+
/** Three headline figures for the dashboard widget (last 7 days); value won per currency. */
|
|
1233
1766
|
async widgetStats() {
|
|
1234
1767
|
const now = new Date();
|
|
1235
|
-
const
|
|
1236
|
-
const
|
|
1237
|
-
|
|
1238
|
-
|
|
1768
|
+
const from = new Date(now.getTime() - 7 * DAY_MS);
|
|
1769
|
+
const stats = this.toDigestStats(await this.periodStats(from, now), undefined, await this.periodWonByCurrency(from, now));
|
|
1770
|
+
const pick = (key, label) => {
|
|
1771
|
+
const st = stats.find(x => x.key === key);
|
|
1772
|
+
return { label, value: (0, vendure_licence_sdk_1.formatStat)(st) };
|
|
1239
1773
|
};
|
|
1240
|
-
return [
|
|
1774
|
+
return [pick('quotesSent', 'Quotes sent'), pick('quotesAccepted', 'Accepted'), pick('valueWonPence', 'Value won')];
|
|
1241
1775
|
}
|
|
1242
1776
|
// ── Set-up checklist ────────────────────────────────────────────────
|
|
1243
1777
|
adminUrl() {
|
|
@@ -1301,26 +1835,32 @@ let QuotationService = class QuotationService {
|
|
|
1301
1835
|
async collectDigest(from, to) {
|
|
1302
1836
|
var _a, _b, _c;
|
|
1303
1837
|
const hooks = this.digestHooks;
|
|
1304
|
-
const [current, previous, setup] = await Promise.all([
|
|
1838
|
+
const [current, previous, setup, won] = await Promise.all([
|
|
1305
1839
|
this.periodStats(from, to),
|
|
1306
1840
|
this.periodStats(new Date(from.getTime() - (to.getTime() - from.getTime())), from),
|
|
1307
1841
|
this.setupChecklist(),
|
|
1842
|
+
this.periodWonByCurrency(from, to),
|
|
1308
1843
|
]);
|
|
1309
1844
|
const adminUrl = this.adminUrl();
|
|
1310
1845
|
const tips = setup.items.filter(i => !i.done).slice(0, 3)
|
|
1311
1846
|
.map(i => ({ title: i.label, body: i.hint, url: i.url || adminUrl || undefined, linkLabel: i.url && i.url !== adminUrl ? 'Read how' : 'Open in Admin' }));
|
|
1312
1847
|
let storeName = null;
|
|
1848
|
+
let logoUrl = null;
|
|
1849
|
+
let accentColor = null;
|
|
1313
1850
|
try {
|
|
1314
1851
|
const ch = await this.channelService.getDefaultChannel();
|
|
1315
1852
|
const cfg = await this.getConfig(Number(ch === null || ch === void 0 ? void 0 : ch.id) || 1);
|
|
1316
1853
|
storeName = cfg.businessName || null;
|
|
1854
|
+
// The report wears the store's own look, as the quote e-mails do.
|
|
1855
|
+
logoUrl = cfg.logoUrl || null;
|
|
1856
|
+
accentColor = cfg.accentColor || null;
|
|
1317
1857
|
}
|
|
1318
1858
|
catch {
|
|
1319
1859
|
storeName = null;
|
|
1320
1860
|
}
|
|
1321
1861
|
const status = (_a = hooks === null || hooks === void 0 ? void 0 : hooks.licence()) !== null && _a !== void 0 ? _a : null;
|
|
1322
1862
|
return {
|
|
1323
|
-
stats: this.toDigestStats(current, previous),
|
|
1863
|
+
stats: this.toDigestStats(current, previous, won),
|
|
1324
1864
|
tips,
|
|
1325
1865
|
tier: (_b = hooks === null || hooks === void 0 ? void 0 : hooks.tier()) !== null && _b !== void 0 ? _b : 'free',
|
|
1326
1866
|
licence: (0, vendure_licence_sdk_1.describeLicence)(status),
|
|
@@ -1328,6 +1868,8 @@ let QuotationService = class QuotationService {
|
|
|
1328
1868
|
adminUrl,
|
|
1329
1869
|
premiumFeatures: exports.PREMIUM_FEATURES,
|
|
1330
1870
|
storeName,
|
|
1871
|
+
logoUrl,
|
|
1872
|
+
accentColor,
|
|
1331
1873
|
settingsHint: 'Change the recipient or stop this weekly report in Admin → Quotations → Settings → Weekly report.',
|
|
1332
1874
|
};
|
|
1333
1875
|
}
|
|
@@ -1368,10 +1910,13 @@ let QuotationService = class QuotationService {
|
|
|
1368
1910
|
}
|
|
1369
1911
|
};
|
|
1370
1912
|
exports.QuotationService = QuotationService;
|
|
1371
|
-
exports.QuotationService = QuotationService = __decorate([
|
|
1913
|
+
exports.QuotationService = QuotationService = QuotationService_1 = __decorate([
|
|
1372
1914
|
(0, common_1.Injectable)(),
|
|
1373
1915
|
__metadata("design:paramtypes", [core_1.TransactionalConnection,
|
|
1374
1916
|
core_1.ChannelService,
|
|
1375
|
-
core_1.OrderService
|
|
1917
|
+
core_1.OrderService,
|
|
1918
|
+
core_1.EventBus,
|
|
1919
|
+
core_1.RequestContextService,
|
|
1920
|
+
core_1.CustomerService])
|
|
1376
1921
|
], QuotationService);
|
|
1377
1922
|
//# sourceMappingURL=quotation.service.js.map
|