@huloglobal/vendure-plugin-quotations 0.1.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.
@@ -0,0 +1,676 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.QuotationService = void 0;
46
+ const common_1 = require("@nestjs/common");
47
+ const core_1 = require("@vendure/core");
48
+ const crypto = __importStar(require("crypto"));
49
+ const nodemailer = __importStar(require("nodemailer"));
50
+ const vendure_licence_sdk_1 = require("@huloglobal/vendure-licence-sdk");
51
+ const pricing_1 = require("./pricing");
52
+ const templates_1 = require("./templates");
53
+ const types_1 = require("./types");
54
+ const loggerCtx = 'Quotations';
55
+ const PLUGIN_ID = 'vendure-plugin-quotations';
56
+ /** statuses a customer can still respond from */
57
+ const OPEN_STATUSES = ['sent', 'viewed'];
58
+ /** statuses an admin can still edit */
59
+ const EDITABLE_STATUSES = ['draft', 'sent', 'viewed'];
60
+ let QuotationService = class QuotationService {
61
+ constructor(connection, channelService, orderService) {
62
+ this.connection = connection;
63
+ this.channelService = channelService;
64
+ this.orderService = orderService;
65
+ this.options = {};
66
+ this.licenceStore = new vendure_licence_sdk_1.LicenceStore((sql, params, opts) => (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection).query(sql, params, opts));
67
+ }
68
+ get db() { return (0, vendure_licence_sdk_1.adapterFor)(this.connection.rawConnection); }
69
+ setOptions(o) { this.options = o || {}; }
70
+ getOptions() { return this.options; }
71
+ async onModuleInit() {
72
+ await this.ensureSchema();
73
+ await this.licenceStore.ensureTable();
74
+ }
75
+ async loadStoredLicenceKey() { return this.licenceStore.load(PLUGIN_ID); }
76
+ async storeLicenceKey(key) { return this.licenceStore.save(PLUGIN_ID, key); }
77
+ async clearStoredLicenceKey() { return this.licenceStore.clear(PLUGIN_ID); }
78
+ // ── Schema ──────────────────────────────────────────────────────────
79
+ async ensureSchema() {
80
+ await this.db.query(`
81
+ CREATE TABLE IF NOT EXISTS quotation_config (
82
+ channelId INT PRIMARY KEY,
83
+ numberPrefix VARCHAR(12) NOT NULL DEFAULT 'Q-',
84
+ nextNumber INT NOT NULL DEFAULT 1,
85
+ defaultValidityDays INT NOT NULL DEFAULT 30,
86
+ defaultVatRate DECIMAL(5,2) NOT NULL DEFAULT 20,
87
+ defaultTerms TEXT,
88
+ businessName VARCHAR(190) NOT NULL DEFAULT '',
89
+ replyTo VARCHAR(190) NOT NULL DEFAULT '',
90
+ notifyEmail VARCHAR(190) NOT NULL DEFAULT '',
91
+ currency VARCHAR(3) NOT NULL DEFAULT 'GBP',
92
+ logoUrl VARCHAR(500) NOT NULL DEFAULT '',
93
+ accentColor VARCHAR(16) NOT NULL DEFAULT '#1d4ed8',
94
+ chaserEnabled TINYINT NOT NULL DEFAULT 1,
95
+ chaserAfterDays INT NOT NULL DEFAULT 3,
96
+ expiryReminderDays INT NOT NULL DEFAULT 3,
97
+ emailSubject VARCHAR(255) NOT NULL DEFAULT '',
98
+ emailBody TEXT
99
+ )`);
100
+ await this.db.query(`
101
+ CREATE TABLE IF NOT EXISTS quotation (
102
+ id INT AUTO_INCREMENT PRIMARY KEY,
103
+ channelId INT NOT NULL,
104
+ reference VARCHAR(32) NOT NULL,
105
+ status VARCHAR(16) NOT NULL DEFAULT 'draft',
106
+ token VARCHAR(64) NOT NULL,
107
+ customerId INT NULL,
108
+ customerName VARCHAR(190) NOT NULL DEFAULT '',
109
+ customerEmail VARCHAR(190) NOT NULL DEFAULT '',
110
+ customerCompany VARCHAR(190) NOT NULL DEFAULT '',
111
+ customerPhone VARCHAR(64) NOT NULL DEFAULT '',
112
+ notes TEXT,
113
+ internalNotes TEXT,
114
+ terms TEXT,
115
+ vatRate DECIMAL(5,2) NOT NULL DEFAULT 20,
116
+ discountType VARCHAR(8) NOT NULL DEFAULT 'none',
117
+ discountValue DECIMAL(12,2) NOT NULL DEFAULT 0,
118
+ currency VARCHAR(3) NOT NULL DEFAULT 'GBP',
119
+ validUntil DATETIME NULL,
120
+ subTotalPence INT NOT NULL DEFAULT 0,
121
+ discountPence INT NOT NULL DEFAULT 0,
122
+ vatPence INT NOT NULL DEFAULT 0,
123
+ totalPence INT NOT NULL DEFAULT 0,
124
+ sentAt DATETIME NULL,
125
+ viewedAt DATETIME NULL,
126
+ respondedAt DATETIME NULL,
127
+ acceptedBy VARCHAR(190) NOT NULL DEFAULT '',
128
+ responseComment VARCHAR(1000) NOT NULL DEFAULT '',
129
+ chaserSentAt DATETIME NULL,
130
+ expiryReminderSentAt DATETIME NULL,
131
+ convertedOrderId INT NULL,
132
+ revisionOf INT NULL,
133
+ createdBy VARCHAR(190) NOT NULL DEFAULT '',
134
+ createdAt DATETIME NOT NULL,
135
+ updatedAt DATETIME NOT NULL,
136
+ INDEX idx_q_channel_status (channelId, status),
137
+ INDEX idx_q_token (token),
138
+ INDEX idx_q_reference (reference),
139
+ INDEX idx_q_email (customerEmail)
140
+ )`);
141
+ await this.db.query(`
142
+ CREATE TABLE IF NOT EXISTS quotation_line (
143
+ id INT AUTO_INCREMENT PRIMARY KEY,
144
+ quoteId INT NOT NULL,
145
+ position INT NOT NULL DEFAULT 0,
146
+ productVariantId INT NULL,
147
+ sku VARCHAR(64) NOT NULL DEFAULT '',
148
+ description VARCHAR(500) NOT NULL DEFAULT '',
149
+ quantity INT NOT NULL DEFAULT 1,
150
+ unitPricePence INT NOT NULL DEFAULT 0,
151
+ lineDiscountPercent DECIMAL(5,2) NOT NULL DEFAULT 0,
152
+ totalPence INT NOT NULL DEFAULT 0,
153
+ INDEX idx_ql_quote (quoteId)
154
+ )`);
155
+ await this.db.query(`
156
+ CREATE TABLE IF NOT EXISTS quotation_event (
157
+ id INT AUTO_INCREMENT PRIMARY KEY,
158
+ quoteId INT NOT NULL,
159
+ type VARCHAR(24) NOT NULL,
160
+ detail VARCHAR(1000) NOT NULL DEFAULT '',
161
+ actor VARCHAR(190) NOT NULL DEFAULT '',
162
+ createdAt DATETIME NOT NULL,
163
+ INDEX idx_qe_quote (quoteId, createdAt)
164
+ )`);
165
+ }
166
+ // ── Config ──────────────────────────────────────────────────────────
167
+ rowToConfig(row, code) {
168
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _o, _p, _q;
169
+ return {
170
+ channelId: row.channelId,
171
+ channelCode: code,
172
+ numberPrefix: (_a = row.numberPrefix) !== null && _a !== void 0 ? _a : types_1.DEFAULT_CONFIG.numberPrefix,
173
+ nextNumber: Number((_b = row.nextNumber) !== null && _b !== void 0 ? _b : 1),
174
+ defaultValidityDays: Number((_c = row.defaultValidityDays) !== null && _c !== void 0 ? _c : types_1.DEFAULT_CONFIG.defaultValidityDays),
175
+ defaultVatRate: Number((_d = row.defaultVatRate) !== null && _d !== void 0 ? _d : types_1.DEFAULT_CONFIG.defaultVatRate),
176
+ defaultTerms: (_e = row.defaultTerms) !== null && _e !== void 0 ? _e : types_1.DEFAULT_CONFIG.defaultTerms,
177
+ businessName: (_f = row.businessName) !== null && _f !== void 0 ? _f : '',
178
+ replyTo: (_g = row.replyTo) !== null && _g !== void 0 ? _g : '',
179
+ notifyEmail: (_h = row.notifyEmail) !== null && _h !== void 0 ? _h : '',
180
+ currency: (_j = row.currency) !== null && _j !== void 0 ? _j : 'GBP',
181
+ logoUrl: (_k = row.logoUrl) !== null && _k !== void 0 ? _k : '',
182
+ accentColor: (_l = row.accentColor) !== null && _l !== void 0 ? _l : types_1.DEFAULT_CONFIG.accentColor,
183
+ chaserEnabled: !!Number((_o = row.chaserEnabled) !== null && _o !== void 0 ? _o : 1),
184
+ chaserAfterDays: Number((_p = row.chaserAfterDays) !== null && _p !== void 0 ? _p : 3),
185
+ expiryReminderDays: Number((_q = row.expiryReminderDays) !== null && _q !== void 0 ? _q : 3),
186
+ emailSubject: row.emailSubject || types_1.DEFAULT_CONFIG.emailSubject,
187
+ emailBody: row.emailBody || types_1.DEFAULT_CONFIG.emailBody,
188
+ };
189
+ }
190
+ async getConfig(channelId) {
191
+ const rows = await this.db.query(`SELECT * FROM quotation_config WHERE channelId = ?`, [channelId]).catch(() => []);
192
+ return rows.length ? this.rowToConfig(rows[0]) : { ...types_1.DEFAULT_CONFIG, channelId };
193
+ }
194
+ async getAllConfigs() {
195
+ const channels = await this.db.query(`SELECT id AS channelId, code AS channelCode FROM channel ORDER BY id`);
196
+ const rows = await this.db.query(`SELECT * FROM quotation_config`).catch(() => []);
197
+ return channels.map((ch) => {
198
+ const existing = rows.find((r) => r.channelId === ch.channelId);
199
+ return existing ? this.rowToConfig(existing, ch.channelCode)
200
+ : { ...types_1.DEFAULT_CONFIG, channelId: ch.channelId, channelCode: ch.channelCode };
201
+ });
202
+ }
203
+ async saveConfig(c) {
204
+ await this.db.query(`INSERT INTO quotation_config (channelId, numberPrefix, nextNumber, defaultValidityDays, defaultVatRate, defaultTerms,
205
+ businessName, replyTo, notifyEmail, currency, logoUrl, accentColor, chaserEnabled, chaserAfterDays,
206
+ expiryReminderDays, emailSubject, emailBody)
207
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
208
+ ON DUPLICATE KEY UPDATE numberPrefix=VALUES(numberPrefix), defaultValidityDays=VALUES(defaultValidityDays),
209
+ defaultVatRate=VALUES(defaultVatRate), defaultTerms=VALUES(defaultTerms), businessName=VALUES(businessName),
210
+ replyTo=VALUES(replyTo), notifyEmail=VALUES(notifyEmail), currency=VALUES(currency), logoUrl=VALUES(logoUrl),
211
+ accentColor=VALUES(accentColor), chaserEnabled=VALUES(chaserEnabled), chaserAfterDays=VALUES(chaserAfterDays),
212
+ expiryReminderDays=VALUES(expiryReminderDays), emailSubject=VALUES(emailSubject), emailBody=VALUES(emailBody)`, [c.channelId, c.numberPrefix || 'Q-', Math.max(1, Number(c.nextNumber) || 1),
213
+ Math.max(1, Number(c.defaultValidityDays) || 30), Number(c.defaultVatRate) || 0, c.defaultTerms || '',
214
+ c.businessName || '', c.replyTo || '', c.notifyEmail || '', (c.currency || 'GBP').toUpperCase().slice(0, 3),
215
+ c.logoUrl || '', c.accentColor || '#1d4ed8', c.chaserEnabled ? 1 : 0, Math.max(1, Number(c.chaserAfterDays) || 3),
216
+ Math.max(0, Number(c.expiryReminderDays) || 0), c.emailSubject || '', c.emailBody || ''], { conflictColumns: ['channelId'] });
217
+ }
218
+ // ── Reference numbering ─────────────────────────────────────────────
219
+ /** Atomically claims the next quote number for a channel. */
220
+ async nextReference(channelId) {
221
+ var _a;
222
+ const cfg = await this.getConfig(channelId);
223
+ // Ensure the row exists, then bump atomically.
224
+ await this.db.query(`INSERT INTO quotation_config (channelId, nextNumber) VALUES (?, ?)
225
+ ON DUPLICATE KEY UPDATE nextNumber = nextNumber + 1`, [channelId, cfg.nextNumber + 1], { conflictColumns: ['channelId'] });
226
+ const [row] = await this.db.query(`SELECT numberPrefix, nextNumber FROM quotation_config WHERE channelId = ?`, [channelId]);
227
+ const n = Number((_a = row === null || row === void 0 ? void 0 : row.nextNumber) !== null && _a !== void 0 ? _a : cfg.nextNumber + 1) - 1;
228
+ const prefix = (row === null || row === void 0 ? void 0 : row.numberPrefix) || cfg.numberPrefix || 'Q-';
229
+ const year = new Date().getFullYear();
230
+ return `${prefix}${year}-${String(n).padStart(4, '0')}`;
231
+ }
232
+ // ── CRUD ────────────────────────────────────────────────────────────
233
+ sanitizeLines(lines) {
234
+ return (lines || [])
235
+ .filter(l => l && (l.description || l.productVariantId))
236
+ .slice(0, 200)
237
+ .map(l => ({
238
+ productVariantId: l.productVariantId ? Number(l.productVariantId) : null,
239
+ sku: String(l.sku || '').slice(0, 64),
240
+ description: String(l.description || '').slice(0, 500),
241
+ quantity: Math.max(1, Math.min(100000, Math.floor(Number(l.quantity) || 1))),
242
+ unitPricePence: Math.max(0, Math.floor(Number(l.unitPricePence) || 0)),
243
+ lineDiscountPercent: Math.min(100, Math.max(0, Number(l.lineDiscountPercent) || 0)),
244
+ }));
245
+ }
246
+ async createQuote(channelId, input, actor) {
247
+ var _a, _b;
248
+ const cfg = await this.getConfig(channelId);
249
+ const lines = this.sanitizeLines(input.lines);
250
+ if (!lines.length)
251
+ throw new Error('A quote needs at least one line');
252
+ const vatRate = (_a = input.vatRate) !== null && _a !== void 0 ? _a : cfg.defaultVatRate;
253
+ const discountType = input.discountType || 'none';
254
+ const discountValue = Number(input.discountValue || 0);
255
+ const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
256
+ const reference = await this.nextReference(channelId);
257
+ const token = crypto.randomBytes(24).toString('hex');
258
+ const validityDays = Math.max(1, Number(input.validityDays) || cfg.defaultValidityDays);
259
+ const res = await this.db.query(`INSERT INTO quotation (channelId, reference, status, token, customerId, customerName, customerEmail,
260
+ customerCompany, customerPhone, notes, internalNotes, terms, vatRate, discountType, discountValue,
261
+ currency, validUntil, subTotalPence, discountPence, vatPence, totalPence, createdBy, createdAt, updatedAt)
262
+ VALUES (?, ?, 'draft', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?, ?, ?, ?, ?, NOW(), NOW())`, [channelId, reference, token, input.customerId || null,
263
+ String(input.customerName || '').slice(0, 190), String(input.customerEmail || '').toLowerCase().slice(0, 190),
264
+ String(input.customerCompany || '').slice(0, 190), String(input.customerPhone || '').slice(0, 64),
265
+ String(input.notes || ''), String(input.internalNotes || ''), (_b = input.terms) !== null && _b !== void 0 ? _b : cfg.defaultTerms, vatRate, discountType, discountValue, (input.currency || cfg.currency || 'GBP').toUpperCase().slice(0, 3),
266
+ validityDays, totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence,
267
+ actor.slice(0, 190)], { needInsertId: true });
268
+ const quoteId = Number(res.insertId);
269
+ await this.replaceLines(quoteId, lines);
270
+ await this.logEvent(quoteId, 'created', `Quote ${reference} created`, actor);
271
+ return this.getQuote(quoteId);
272
+ }
273
+ async replaceLines(quoteId, lines) {
274
+ await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
275
+ let pos = 0;
276
+ for (const l of lines) {
277
+ await this.db.query(`INSERT INTO quotation_line (quoteId, position, productVariantId, sku, description, quantity, unitPricePence, lineDiscountPercent, totalPence)
278
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [quoteId, pos++, l.productVariantId || null, l.sku || '', l.description, l.quantity,
279
+ l.unitPricePence, l.lineDiscountPercent || 0, (0, pricing_1.lineTotal)(l)]);
280
+ }
281
+ }
282
+ async updateQuote(quoteId, input, actor) {
283
+ var _a, _b;
284
+ const existing = await this.getQuote(quoteId);
285
+ if (!existing)
286
+ throw new Error('Quote not found');
287
+ if (!EDITABLE_STATUSES.includes(existing.status)) {
288
+ throw new Error(`A ${existing.status} quote can no longer be edited — create a revision instead`);
289
+ }
290
+ const lines = this.sanitizeLines(input.lines);
291
+ if (!lines.length)
292
+ throw new Error('A quote needs at least one line');
293
+ const vatRate = (_a = input.vatRate) !== null && _a !== void 0 ? _a : existing.vatRate;
294
+ const discountType = input.discountType || 'none';
295
+ const discountValue = Number(input.discountValue || 0);
296
+ const totals = (0, pricing_1.quoteTotals)(lines, discountType, discountValue, vatRate);
297
+ await this.db.query(`UPDATE quotation SET customerId=?, customerName=?, customerEmail=?, customerCompany=?, customerPhone=?,
298
+ notes=?, internalNotes=?, terms=?, vatRate=?, discountType=?, discountValue=?, currency=?,
299
+ validUntil=DATE_ADD(NOW(), INTERVAL ? DAY),
300
+ subTotalPence=?, discountPence=?, vatPence=?, totalPence=?, updatedAt=NOW()
301
+ WHERE id = ?`, [input.customerId || null, String(input.customerName || '').slice(0, 190),
302
+ String(input.customerEmail || '').toLowerCase().slice(0, 190), String(input.customerCompany || '').slice(0, 190),
303
+ String(input.customerPhone || '').slice(0, 64), String(input.notes || ''), String(input.internalNotes || ''), (_b = input.terms) !== null && _b !== void 0 ? _b : existing.terms, vatRate, discountType, discountValue,
304
+ (input.currency || existing.currency).toUpperCase().slice(0, 3),
305
+ Math.max(1, Number(input.validityDays) || 30),
306
+ totals.subTotalPence, totals.discountPence, totals.vatPence, totals.totalPence, quoteId]);
307
+ await this.replaceLines(quoteId, lines);
308
+ await this.logEvent(quoteId, 'updated', 'Quote updated', actor);
309
+ return this.getQuote(quoteId);
310
+ }
311
+ async deleteQuote(quoteId) {
312
+ const q = await this.getQuote(quoteId);
313
+ if (!q)
314
+ return;
315
+ if (q.status !== 'draft')
316
+ throw new Error('Only draft quotes can be deleted — cancel instead');
317
+ await this.db.query(`DELETE FROM quotation_line WHERE quoteId = ?`, [quoteId]);
318
+ await this.db.query(`DELETE FROM quotation_event WHERE quoteId = ?`, [quoteId]);
319
+ await this.db.query(`DELETE FROM quotation WHERE id = ?`, [quoteId]);
320
+ }
321
+ async cancelQuote(quoteId, actor) {
322
+ const q = await this.getQuote(quoteId);
323
+ if (!q)
324
+ throw new Error('Quote not found');
325
+ if (['accepted', 'converted'].includes(q.status))
326
+ throw new Error(`Cannot cancel an ${q.status} quote`);
327
+ await this.db.query(`UPDATE quotation SET status='cancelled', updatedAt=NOW() WHERE id = ?`, [quoteId]);
328
+ await this.logEvent(quoteId, 'cancelled', 'Quote cancelled', actor);
329
+ return this.getQuote(quoteId);
330
+ }
331
+ async duplicateQuote(quoteId, actor, asRevision = false) {
332
+ const q = await this.getQuote(quoteId);
333
+ if (!q)
334
+ throw new Error('Quote not found');
335
+ const created = await this.createQuote(q.channelId, {
336
+ customerId: q.customerId, customerName: q.customerName, customerEmail: q.customerEmail,
337
+ customerCompany: q.customerCompany, customerPhone: q.customerPhone,
338
+ notes: q.notes, internalNotes: q.internalNotes, terms: q.terms,
339
+ vatRate: q.vatRate, discountType: q.discountType, discountValue: q.discountValue,
340
+ currency: q.currency, validityDays: 30,
341
+ lines: q.lines.map((l) => ({
342
+ productVariantId: l.productVariantId, sku: l.sku, description: l.description,
343
+ quantity: l.quantity, unitPricePence: l.unitPricePence, lineDiscountPercent: l.lineDiscountPercent,
344
+ })),
345
+ }, actor);
346
+ if (asRevision) {
347
+ await this.db.query(`UPDATE quotation SET revisionOf = ? WHERE id = ?`, [quoteId, created.id]);
348
+ await this.logEvent(quoteId, 'duplicated', `Revision ${created.reference} created`, actor);
349
+ }
350
+ else {
351
+ await this.logEvent(quoteId, 'duplicated', `Duplicated as ${created.reference}`, actor);
352
+ }
353
+ return this.getQuote(created.id);
354
+ }
355
+ async getQuote(quoteId) {
356
+ const [q] = await this.db.query(`SELECT * FROM quotation WHERE id = ?`, [quoteId]).catch(() => []);
357
+ if (!q)
358
+ return null;
359
+ q.lines = await this.db.query(`SELECT * FROM quotation_line WHERE quoteId = ? ORDER BY position`, [quoteId]);
360
+ q.events = await this.db.query(`SELECT type, detail, actor, createdAt FROM quotation_event WHERE quoteId = ? ORDER BY createdAt DESC, id DESC LIMIT 50`, [quoteId]);
361
+ return q;
362
+ }
363
+ async getQuoteByToken(token) {
364
+ if (!/^[a-f0-9]{48}$/.test(token))
365
+ return null;
366
+ const [q] = await this.db.query(`SELECT * FROM quotation WHERE token = ? LIMIT 1`, [token]).catch(() => []);
367
+ if (!q)
368
+ return null;
369
+ q.lines = await this.db.query(`SELECT * FROM quotation_line WHERE quoteId = ? ORDER BY position`, [q.id]);
370
+ return q;
371
+ }
372
+ async listQuotes(channelId, opts) {
373
+ const where = [];
374
+ const params = [];
375
+ if (channelId) {
376
+ where.push('channelId = ?');
377
+ params.push(channelId);
378
+ }
379
+ if (opts.status && opts.status !== 'all') {
380
+ where.push('status = ?');
381
+ params.push(opts.status);
382
+ }
383
+ if (opts.search) {
384
+ where.push('(reference LIKE ? OR customerName LIKE ? OR customerEmail LIKE ? OR customerCompany LIKE ?)');
385
+ const like = `%${opts.search.slice(0, 100)}%`;
386
+ params.push(like, like, like, like);
387
+ }
388
+ const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';
389
+ const perPage = Math.min(100, Math.max(5, Number(opts.perPage) || 25));
390
+ const page = Math.max(1, Number(opts.page) || 1);
391
+ const [count] = await this.db.query(`SELECT COUNT(*) AS n FROM quotation ${whereSql}`, params);
392
+ const items = await this.db.query(`SELECT id, channelId, reference, status, customerName, customerEmail, customerCompany, totalPence, currency,
393
+ validUntil, sentAt, viewedAt, respondedAt, convertedOrderId, createdAt, updatedAt
394
+ FROM quotation ${whereSql} ORDER BY id DESC LIMIT ${perPage} OFFSET ${(page - 1) * perPage}`, params);
395
+ return { items, totalItems: Number((count === null || count === void 0 ? void 0 : count.n) || 0), page, perPage };
396
+ }
397
+ async logEvent(quoteId, type, detail, actor = '') {
398
+ await this.db.query(`INSERT INTO quotation_event (quoteId, type, detail, actor, createdAt) VALUES (?, ?, ?, ?, NOW())`, [quoteId, type.slice(0, 24), detail.slice(0, 1000), actor.slice(0, 190)]).catch(() => undefined);
399
+ }
400
+ // ── Sending ─────────────────────────────────────────────────────────
401
+ quoteUrl(token) {
402
+ const base = (this.options.publicBaseUrl || '').replace(/\/$/, '');
403
+ return `${base}/quotations/quote/${token}`;
404
+ }
405
+ smtpSettings() {
406
+ if (this.options.smtp)
407
+ return this.options.smtp;
408
+ if (process.env.SMTP_SERVER && process.env.SMTP_USER) {
409
+ return {
410
+ host: process.env.SMTP_SERVER, port: Number(process.env.SMTP_PORT || 587),
411
+ user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD || '',
412
+ from: process.env.SMTP_FROM || process.env.SMTP_USER,
413
+ };
414
+ }
415
+ return null;
416
+ }
417
+ async sendQuote(quoteId, actor) {
418
+ const q = await this.getQuote(quoteId);
419
+ if (!q)
420
+ return { ok: false, reason: 'Quote not found' };
421
+ if (!q.customerEmail)
422
+ return { ok: false, reason: 'The quote has no customer email' };
423
+ if (['accepted', 'declined', 'converted', 'cancelled', 'expired'].includes(q.status)) {
424
+ return { ok: false, reason: `A ${q.status} quote cannot be sent` };
425
+ }
426
+ const cfg = await this.getConfig(q.channelId);
427
+ const res = await this.deliverEmail(q, cfg, 'quote');
428
+ if (!res.ok)
429
+ return res;
430
+ await this.db.query(`UPDATE quotation SET status='sent', sentAt=NOW(), updatedAt=NOW() WHERE id = ?`, [quoteId]);
431
+ await this.logEvent(quoteId, 'sent', `Sent to ${q.customerEmail}`, actor);
432
+ return { ok: true };
433
+ }
434
+ async deliverEmail(q, cfg, kind) {
435
+ const smtp = this.smtpSettings();
436
+ if (!smtp)
437
+ return { ok: false, reason: 'SMTP is not configured (SMTP_SERVER / SMTP_USER env or plugin options)' };
438
+ const url = this.quoteUrl(q.token);
439
+ const vars = {
440
+ reference: q.reference,
441
+ customerName: q.customerName || 'there',
442
+ businessName: cfg.businessName || 'our team',
443
+ total: (0, pricing_1.formatMoney)(q.totalPence, q.currency),
444
+ validUntil: q.validUntil ? new Date(q.validUntil).toISOString().slice(0, 10) : '',
445
+ quoteUrl: url,
446
+ };
447
+ let subject = cfg.emailSubject || types_1.DEFAULT_CONFIG.emailSubject;
448
+ let body = cfg.emailBody || types_1.DEFAULT_CONFIG.emailBody;
449
+ if (kind === 'chaser') {
450
+ subject = `Reminder: quotation {{reference}} from {{businessName}}`;
451
+ body = 'Hi {{customerName}},\n\nJust a gentle nudge — your quotation {{reference}} for {{total}} is waiting for you:\n\n{{quoteUrl}}\n\nIt stays valid until {{validUntil}}. Any questions, simply reply.\n\nBest regards,\n{{businessName}}';
452
+ }
453
+ else if (kind === 'expiry') {
454
+ subject = `Your quotation {{reference}} expires soon`;
455
+ body = 'Hi {{customerName}},\n\nA quick heads-up: quotation {{reference}} for {{total}} expires on {{validUntil}}.\n\nAccept it online here:\n\n{{quoteUrl}}\n\nIf the timing does not work, reply and we will extend it.\n\nBest regards,\n{{businessName}}';
456
+ }
457
+ const render = (t) => t.replace(/\{\{(\w+)\}\}/g, (_m, k) => { var _a; return (_a = vars[k]) !== null && _a !== void 0 ? _a : ''; });
458
+ try {
459
+ const transporter = nodemailer.createTransport({
460
+ host: smtp.host, port: smtp.port, secure: smtp.port === 465,
461
+ auth: { user: smtp.user, pass: smtp.pass },
462
+ });
463
+ await transporter.sendMail({
464
+ from: cfg.businessName ? `"${cfg.businessName}" <${smtp.from}>` : smtp.from,
465
+ to: q.customerEmail,
466
+ replyTo: cfg.replyTo || undefined,
467
+ subject: render(subject),
468
+ text: (0, templates_1.renderQuoteEmailText)(render(body)),
469
+ html: (0, templates_1.renderQuoteEmailHtml)(render(body), q, cfg, url),
470
+ });
471
+ return { ok: true };
472
+ }
473
+ catch (e) {
474
+ return { ok: false, reason: e.message };
475
+ }
476
+ }
477
+ /** Fire-and-forget notification to the merchant on accept/decline. */
478
+ async notifyMerchant(q, cfg, subject, text) {
479
+ const smtp = this.smtpSettings();
480
+ const to = cfg.notifyEmail || cfg.replyTo;
481
+ if (!smtp || !to)
482
+ return;
483
+ try {
484
+ const transporter = nodemailer.createTransport({
485
+ host: smtp.host, port: smtp.port, secure: smtp.port === 465,
486
+ auth: { user: smtp.user, pass: smtp.pass },
487
+ });
488
+ await transporter.sendMail({ from: smtp.from, to, subject, text });
489
+ }
490
+ catch (e) {
491
+ core_1.Logger.warn(`merchant notification failed: ${e.message}`, loggerCtx);
492
+ }
493
+ }
494
+ // ── Customer actions ────────────────────────────────────────────────
495
+ async markViewed(token) {
496
+ const q = await this.getQuoteByToken(token);
497
+ if (!q)
498
+ return null;
499
+ if (q.status === 'sent') {
500
+ await this.db.query(`UPDATE quotation SET status='viewed', viewedAt=COALESCE(viewedAt, NOW()), updatedAt=NOW() WHERE id = ?`, [q.id]);
501
+ await this.logEvent(q.id, 'viewed', 'Opened by the customer', q.customerEmail);
502
+ q.status = 'viewed';
503
+ }
504
+ return q;
505
+ }
506
+ async respond(token, action, name, comment) {
507
+ const q = await this.getQuoteByToken(token);
508
+ if (!q)
509
+ return { ok: false, reason: 'Quote not found' };
510
+ if (!OPEN_STATUSES.includes(q.status))
511
+ return { ok: false, reason: `This quote is ${q.status} and can no longer be responded to` };
512
+ if (q.validUntil && new Date(q.validUntil) < new Date()) {
513
+ await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW() WHERE id = ?`, [q.id]);
514
+ await this.logEvent(q.id, 'expired', 'Response attempted after expiry');
515
+ return { ok: false, reason: 'This quote has expired — contact us and we will refresh it' };
516
+ }
517
+ const cleanName = String(name || '').trim().slice(0, 190);
518
+ const cleanComment = String(comment || '').trim().slice(0, 1000);
519
+ if (action === 'accept' && !cleanName)
520
+ return { ok: false, reason: 'Please type your name to accept — it acts as your signature' };
521
+ const status = action === 'accept' ? 'accepted' : 'declined';
522
+ await this.db.query(`UPDATE quotation SET status=?, respondedAt=NOW(), acceptedBy=?, responseComment=?, updatedAt=NOW() WHERE id = ?`, [status, action === 'accept' ? cleanName : '', cleanComment, q.id]);
523
+ await this.logEvent(q.id, status, action === 'accept'
524
+ ? `Accepted by "${cleanName}"${cleanComment ? ` — ${cleanComment}` : ''}`
525
+ : `Declined${cleanComment ? ` — ${cleanComment}` : ''}`, q.customerEmail);
526
+ const cfg = await this.getConfig(q.channelId);
527
+ await 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)}).` +
528
+ (action === 'accept' ? `\nSigned: ${cleanName}` : '') +
529
+ (cleanComment ? `\nComment: ${cleanComment}` : '') +
530
+ `\n\nAdmin: open the Quotations page to ${action === 'accept' ? 'convert it to an order' : 'follow up'}.`);
531
+ return { ok: true, quote: await this.getQuote(q.id) };
532
+ }
533
+ // ── Conversion to a Vendure draft order ─────────────────────────────
534
+ /**
535
+ * Creates a draft Order from an accepted quote. Catalogue-linked lines
536
+ * are added as real order lines; the difference between catalogue and
537
+ * quoted pricing (plus any free-text lines) lands as a single
538
+ * "Quotation …" surcharge, so the draft order total equals the quote
539
+ * total exactly. The admin completes the draft as usual.
540
+ */
541
+ async convertToDraftOrder(ctx, quoteId, actor) {
542
+ const q = await this.getQuote(quoteId);
543
+ if (!q)
544
+ return { ok: false, reason: 'Quote not found' };
545
+ if (q.status !== 'accepted')
546
+ return { ok: false, reason: 'Only accepted quotes can be converted' };
547
+ try {
548
+ const draft = await this.orderService.createDraft(ctx);
549
+ let catalogueTotalWithTax = 0;
550
+ for (const line of q.lines) {
551
+ if (!line.productVariantId)
552
+ continue;
553
+ const result = await this.orderService.addItemToOrder(ctx, draft.id, line.productVariantId, line.quantity);
554
+ if (result === null || result === void 0 ? void 0 : result.errorCode) {
555
+ return { ok: false, reason: `Could not add "${line.description}": ${result.message || result.errorCode}` };
556
+ }
557
+ }
558
+ const fresh = await this.orderService.findOne(ctx, draft.id);
559
+ catalogueTotalWithTax = Number((fresh === null || fresh === void 0 ? void 0 : fresh.totalWithTax) || 0);
560
+ const delta = q.totalPence - catalogueTotalWithTax;
561
+ if (delta !== 0 || q.lines.some((l) => !l.productVariantId)) {
562
+ await this.orderService.addSurchargeToOrder(ctx, draft.id, {
563
+ description: `Quotation ${q.reference} pricing`,
564
+ listPrice: delta,
565
+ listPriceIncludesTax: true,
566
+ sku: q.reference,
567
+ taxLines: [],
568
+ });
569
+ }
570
+ await this.db.query(`UPDATE quotation SET status='converted', convertedOrderId=?, updatedAt=NOW() WHERE id = ?`, [draft.id, quoteId]);
571
+ await this.logEvent(quoteId, 'converted', `Draft order ${(fresh === null || fresh === void 0 ? void 0 : fresh.code) || draft.id} created`, actor);
572
+ return { ok: true, orderId: Number(draft.id), orderCode: fresh === null || fresh === void 0 ? void 0 : fresh.code };
573
+ }
574
+ catch (e) {
575
+ core_1.Logger.error(`convert failed for quote ${quoteId}: ${e.message}`, loggerCtx);
576
+ return { ok: false, reason: e.message };
577
+ }
578
+ }
579
+ // ── Product search for the editor ───────────────────────────────────
580
+ async searchVariants(channelId, term) {
581
+ const like = `%${String(term || '').slice(0, 80)}%`;
582
+ return this.db.query(`SELECT pv.id AS productVariantId, pv.sku, pvt.name AS name, pvp.price AS pricePence
583
+ FROM product_variant pv
584
+ JOIN product_variant_translation pvt ON pvt.baseId = pv.id AND pvt.languageCode = 'en'
585
+ JOIN product_variant_price pvp ON pvp.variantId = pv.id AND pvp.channelId = ?
586
+ WHERE pv.deletedAt IS NULL AND pv.enabled = 1 AND (pvt.name LIKE ? OR pv.sku LIKE ?)
587
+ ORDER BY pvt.name ASC LIMIT 20`, [channelId, like, like]).catch(() => []);
588
+ }
589
+ // ── Crons ───────────────────────────────────────────────────────────
590
+ async expireOverdue() {
591
+ const res = await this.db.query(`UPDATE quotation SET status='expired', updatedAt=NOW()
592
+ WHERE status IN ('sent','viewed') AND validUntil IS NOT NULL AND validUntil < NOW()`, undefined, { needAffected: true });
593
+ const n = Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0);
594
+ if (n)
595
+ core_1.Logger.info(`marked ${n} quote(s) expired`, loggerCtx);
596
+ return n;
597
+ }
598
+ async runChasers() {
599
+ const out = { chasers: 0, expiryReminders: 0 };
600
+ const configs = await this.getAllConfigs();
601
+ for (const cfg of configs) {
602
+ if (cfg.chaserEnabled) {
603
+ const rows = await this.db.query(`SELECT id FROM quotation
604
+ WHERE channelId = ? AND status = 'sent' AND chaserSentAt IS NULL
605
+ AND sentAt IS NOT NULL AND sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
606
+ AND (validUntil IS NULL OR validUntil > NOW()) LIMIT 25`, [cfg.channelId, cfg.chaserAfterDays]);
607
+ for (const r of rows) {
608
+ const q = await this.getQuote(r.id);
609
+ const res = await this.deliverEmail(q, cfg, 'chaser');
610
+ if (res.ok) {
611
+ await this.db.query(`UPDATE quotation SET chaserSentAt=NOW() WHERE id = ?`, [r.id]);
612
+ await this.logEvent(r.id, 'chaser_sent', 'Unopened-quote reminder emailed');
613
+ out.chasers++;
614
+ }
615
+ }
616
+ }
617
+ if (cfg.expiryReminderDays > 0) {
618
+ const rows = await this.db.query(`SELECT id FROM quotation
619
+ WHERE channelId = ? AND status IN ('sent','viewed') AND expiryReminderSentAt IS NULL
620
+ AND validUntil IS NOT NULL AND validUntil > NOW()
621
+ AND validUntil < DATE_ADD(NOW(), INTERVAL ? DAY) LIMIT 25`, [cfg.channelId, cfg.expiryReminderDays]);
622
+ for (const r of rows) {
623
+ const q = await this.getQuote(r.id);
624
+ const res = await this.deliverEmail(q, cfg, 'expiry');
625
+ if (res.ok) {
626
+ await this.db.query(`UPDATE quotation SET expiryReminderSentAt=NOW() WHERE id = ?`, [r.id]);
627
+ await this.logEvent(r.id, 'expiry_reminder_sent', 'Expiry reminder emailed');
628
+ out.expiryReminders++;
629
+ }
630
+ }
631
+ }
632
+ }
633
+ return out;
634
+ }
635
+ // ── Stats ───────────────────────────────────────────────────────────
636
+ async stats(channelId) {
637
+ const where = channelId ? 'WHERE channelId = ?' : '';
638
+ const params = channelId ? [channelId] : [];
639
+ const byStatus = await this.db.query(`SELECT status, COUNT(*) AS n, SUM(totalPence) AS value FROM quotation ${where} GROUP BY status`, params);
640
+ const [resp] = await this.db.query(`SELECT COUNT(*) AS n, AVG(TIMESTAMPDIFF(SECOND, sentAt, respondedAt)) AS avgSeconds
641
+ FROM quotation ${where ? where + ' AND' : 'WHERE'} respondedAt IS NOT NULL AND sentAt IS NOT NULL`, params);
642
+ const [last30] = await this.db.query(`SELECT COUNT(*) AS sent, SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won
643
+ FROM quotation ${where ? where + ' AND' : 'WHERE'} sentAt > DATE_SUB(NOW(), INTERVAL 30 DAY)`, params);
644
+ const sent30 = Number((last30 === null || last30 === void 0 ? void 0 : last30.sent) || 0);
645
+ return {
646
+ byStatus,
647
+ avgResponseHours: (resp === null || resp === void 0 ? void 0 : resp.avgSeconds) ? Math.round(Number(resp.avgSeconds) / 360) / 10 : null,
648
+ 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 },
649
+ };
650
+ }
651
+ /** Anonymous aggregates for evaluation-reminder emails. Numbers only. */
652
+ async evalStats() {
653
+ try {
654
+ const [row] = await this.db.query(`SELECT COUNT(*) AS quotes,
655
+ SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS accepted,
656
+ SUM(CASE WHEN status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS wonPence
657
+ FROM quotation`);
658
+ return {
659
+ quotes_created: Number((row === null || row === void 0 ? void 0 : row.quotes) || 0),
660
+ quotes_accepted: Number((row === null || row === void 0 ? void 0 : row.accepted) || 0),
661
+ value_won_pence: Number((row === null || row === void 0 ? void 0 : row.wonPence) || 0),
662
+ };
663
+ }
664
+ catch {
665
+ return {};
666
+ }
667
+ }
668
+ };
669
+ exports.QuotationService = QuotationService;
670
+ exports.QuotationService = QuotationService = __decorate([
671
+ (0, common_1.Injectable)(),
672
+ __metadata("design:paramtypes", [core_1.TransactionalConnection,
673
+ core_1.ChannelService,
674
+ core_1.OrderService])
675
+ ], QuotationService);
676
+ //# sourceMappingURL=quotation.service.js.map