@huloglobal/vendure-plugin-quotations 0.8.5 → 0.9.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +107 -10
  3. package/dist/approvals.d.ts +46 -0
  4. package/dist/approvals.d.ts.map +1 -0
  5. package/dist/approvals.js +136 -0
  6. package/dist/approvals.js.map +1 -0
  7. package/dist/crons.d.ts +5 -3
  8. package/dist/crons.d.ts.map +1 -1
  9. package/dist/crons.js +16 -10
  10. package/dist/crons.js.map +1 -1
  11. package/dist/csv.d.ts +7 -0
  12. package/dist/csv.d.ts.map +1 -0
  13. package/dist/csv.js +32 -0
  14. package/dist/csv.js.map +1 -0
  15. package/dist/deposits.d.ts +25 -0
  16. package/dist/deposits.d.ts.map +1 -0
  17. package/dist/deposits.js +59 -0
  18. package/dist/deposits.js.map +1 -0
  19. package/dist/events.d.ts +55 -0
  20. package/dist/events.d.ts.map +1 -0
  21. package/dist/events.js +58 -0
  22. package/dist/events.js.map +1 -0
  23. package/dist/index.d.ts +4 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +7 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/pay-links.d.ts +37 -0
  28. package/dist/pay-links.d.ts.map +1 -0
  29. package/dist/pay-links.js +61 -0
  30. package/dist/pay-links.js.map +1 -0
  31. package/dist/payment.service.d.ts +117 -0
  32. package/dist/payment.service.d.ts.map +1 -0
  33. package/dist/payment.service.js +476 -0
  34. package/dist/payment.service.js.map +1 -0
  35. package/dist/pdf.d.ts +15 -0
  36. package/dist/pdf.d.ts.map +1 -0
  37. package/dist/pdf.js +356 -0
  38. package/dist/pdf.js.map +1 -0
  39. package/dist/plugin.d.ts +5 -2
  40. package/dist/plugin.d.ts.map +1 -1
  41. package/dist/plugin.js +18 -6
  42. package/dist/plugin.js.map +1 -1
  43. package/dist/pro-settings.d.ts +72 -0
  44. package/dist/pro-settings.d.ts.map +1 -0
  45. package/dist/pro-settings.js +202 -0
  46. package/dist/pro-settings.js.map +1 -0
  47. package/dist/pro.service.d.ts +130 -0
  48. package/dist/pro.service.d.ts.map +1 -0
  49. package/dist/pro.service.js +732 -0
  50. package/dist/pro.service.js.map +1 -0
  51. package/dist/quotation.controller.d.ts +50 -6
  52. package/dist/quotation.controller.d.ts.map +1 -1
  53. package/dist/quotation.controller.js +618 -24
  54. package/dist/quotation.controller.js.map +1 -1
  55. package/dist/quotation.service.d.ts +188 -11
  56. package/dist/quotation.service.d.ts.map +1 -1
  57. package/dist/quotation.service.js +636 -99
  58. package/dist/quotation.service.js.map +1 -1
  59. package/dist/quote-total.d.ts +49 -0
  60. package/dist/quote-total.d.ts.map +1 -0
  61. package/dist/quote-total.js +81 -0
  62. package/dist/quote-total.js.map +1 -0
  63. package/dist/templates.d.ts +13 -1
  64. package/dist/templates.d.ts.map +1 -1
  65. package/dist/templates.js +17 -6
  66. package/dist/templates.js.map +1 -1
  67. package/dist/types.d.ts +12 -0
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js +2 -0
  70. package/dist/types.js.map +1 -1
  71. package/dist/webhooks.d.ts +61 -0
  72. package/dist/webhooks.d.ts.map +1 -0
  73. package/dist/webhooks.js +308 -0
  74. package/dist/webhooks.js.map +1 -0
  75. package/package.json +4 -3
  76. package/ui/components/quotations.component.ts +328 -19
@@ -0,0 +1,732 @@
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
+ var QuotationProService_1;
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.QuotationProService = exports.PremiumRequired = exports.MAX_TEMPLATES = void 0;
47
+ const common_1 = require("@nestjs/common");
48
+ const core_1 = require("@vendure/core");
49
+ const crypto = __importStar(require("crypto"));
50
+ const approvals_1 = require("./approvals");
51
+ const csv_1 = require("./csv");
52
+ const pricing_1 = require("./pricing");
53
+ const pro_settings_1 = require("./pro-settings");
54
+ const quotation_service_1 = require("./quotation.service");
55
+ const webhooks_1 = require("./webhooks");
56
+ const loggerCtx = 'Quotations';
57
+ const DAY_MS = 86400000;
58
+ exports.MAX_TEMPLATES = 500;
59
+ /** A premium feature was used without a licence or evaluation. */
60
+ class PremiumRequired extends Error {
61
+ constructor(feature) {
62
+ super(`${feature} needs a licence (or the 14-day evaluation).`);
63
+ this.feature = feature;
64
+ }
65
+ }
66
+ exports.PremiumRequired = PremiumRequired;
67
+ /**
68
+ * The premium features: quote templates, follow-up sequences, discount
69
+ * approval, webhooks (JSON, Slack, Teams) and sales reports with CSV. All of
70
+ * them sit on top of QuotationService (its trail, its mailer, its pre-send
71
+ * gate), the same way the WordPress Pro add-on sits on the free plugin.
72
+ */
73
+ let QuotationProService = QuotationProService_1 = class QuotationProService {
74
+ constructor(core) {
75
+ this.core = core;
76
+ // ── settings ────────────────────────────────────────────────────────
77
+ this.cached = null;
78
+ this.nudgeTimer = null;
79
+ }
80
+ get db() { return this.core.sql; }
81
+ async onModuleInit() {
82
+ await this.ensureSchema();
83
+ this.core.addPreSendGate((q, mode) => this.approvalGate(q, mode));
84
+ this.core.onTrail(e => this.onTrail(e));
85
+ }
86
+ async ensureSchema() {
87
+ await this.db.query(`
88
+ CREATE TABLE IF NOT EXISTS quotation_template (
89
+ id INT AUTO_INCREMENT PRIMARY KEY,
90
+ name VARCHAR(190) NOT NULL DEFAULT '',
91
+ data TEXT,
92
+ createdBy VARCHAR(190) NOT NULL DEFAULT '',
93
+ createdAt DATETIME NOT NULL,
94
+ updatedAt DATETIME NOT NULL
95
+ )`);
96
+ await this.db.query(`
97
+ CREATE TABLE IF NOT EXISTS quotation_followup (
98
+ quoteId INT NOT NULL,
99
+ step INT NOT NULL,
100
+ state VARCHAR(12) NOT NULL DEFAULT 'sending',
101
+ claimedAt DATETIME NOT NULL,
102
+ sentAt DATETIME NULL,
103
+ PRIMARY KEY (quoteId, step)
104
+ )`);
105
+ await this.db.query(`
106
+ CREATE TABLE IF NOT EXISTS quotation_approval (
107
+ quoteId INT PRIMARY KEY,
108
+ state VARCHAR(12) NOT NULL DEFAULT 'pending',
109
+ hash VARCHAR(64) NOT NULL DEFAULT '',
110
+ reasons VARCHAR(1000) NOT NULL DEFAULT '',
111
+ requestedBy VARCHAR(190) NOT NULL DEFAULT '',
112
+ requestedAt DATETIME NULL,
113
+ decidedBy VARCHAR(190) NOT NULL DEFAULT '',
114
+ decidedAt DATETIME NULL,
115
+ comment VARCHAR(1000) NOT NULL DEFAULT '',
116
+ updatedAt DATETIME NOT NULL
117
+ )`);
118
+ await this.db.query(`
119
+ CREATE TABLE IF NOT EXISTS quotation_webhook_log (
120
+ id INT AUTO_INCREMENT PRIMARY KEY,
121
+ hookId VARCHAR(16) NOT NULL,
122
+ event VARCHAR(40) NOT NULL,
123
+ eventKey VARCHAR(40) NOT NULL,
124
+ quoteId INT NOT NULL DEFAULT 0,
125
+ url VARCHAR(500) NOT NULL DEFAULT '',
126
+ format VARCHAR(8) NOT NULL DEFAULT 'json',
127
+ payload TEXT,
128
+ state VARCHAR(12) NOT NULL DEFAULT 'pending',
129
+ attempts INT NOT NULL DEFAULT 0,
130
+ code INT NOT NULL DEFAULT 0,
131
+ error VARCHAR(255) NOT NULL DEFAULT '',
132
+ nextAt DATETIME NOT NULL,
133
+ createdAt DATETIME NOT NULL,
134
+ updatedAt DATETIME NOT NULL,
135
+ UNIQUE (hookId, eventKey),
136
+ INDEX idx_qwl_due (state, nextAt)
137
+ )`);
138
+ }
139
+ async settings() {
140
+ if (this.cached && Date.now() - this.cached.at < 5000)
141
+ return this.cached.s;
142
+ let raw = null;
143
+ try {
144
+ raw = JSON.parse((await this.core.prefs.get('pro.settings')) || 'null');
145
+ }
146
+ catch {
147
+ raw = null;
148
+ }
149
+ const s = raw ? (0, pro_settings_1.sanitizeProSettings)(raw) : (0, pro_settings_1.defaultProSettings)();
150
+ this.cached = { at: Date.now(), s };
151
+ return s;
152
+ }
153
+ /**
154
+ * Save a patch of the settings. Webhook URLs are checked (scheme, port,
155
+ * public address); refused ones are left out and reported in `errors`.
156
+ */
157
+ async saveSettings(patch) {
158
+ const prev = await this.settings();
159
+ const next = (0, pro_settings_1.sanitizeProSettings)(patch || {}, prev);
160
+ const errors = [];
161
+ if (patch && 'webhooks' in patch) {
162
+ const kept = [];
163
+ for (const [i, h] of next.webhooks.entries()) {
164
+ const v = await (0, webhooks_1.validateWebhookUrl)(h.url, { allowPrivate: !!this.core.getOptions().allowPrivateWebhooks });
165
+ if (!v.ok) {
166
+ errors.push(`Webhook ${i + 1} was not saved: ${v.reason}`);
167
+ continue;
168
+ }
169
+ kept.push({ ...h, url: v.url });
170
+ }
171
+ next.webhooks = kept;
172
+ if (kept.length)
173
+ await this.webhookCursor(); // start the cursor now: history before the first webhook is not replayed
174
+ }
175
+ await this.core.prefs.set('pro.settings', JSON.stringify(next));
176
+ this.cached = null;
177
+ return { settings: next, errors };
178
+ }
179
+ requirePremium(feature) {
180
+ if (!this.core.isPremium())
181
+ throw new PremiumRequired(feature);
182
+ }
183
+ adminUrl() {
184
+ const base = (this.core.getOptions().publicBaseUrl || '').replace(/\/$/, '');
185
+ return base ? `${base}/admin/extensions/quotations` : null;
186
+ }
187
+ // ── templates ───────────────────────────────────────────────────────
188
+ /** The reusable part of a quote: lines, discounts, VAT, notes, terms, validity, currency. Never the customer or internal notes. */
189
+ static templateData(q) {
190
+ return {
191
+ lines: (q.lines || []).map((l) => ({
192
+ productVariantId: l.productVariantId ? Number(l.productVariantId) : null, sku: String(l.sku || ''),
193
+ description: String(l.description || ''), quantity: Number(l.quantity) || 1,
194
+ unitPricePence: Number(l.unitPricePence) || 0, lineDiscountPercent: Number(l.lineDiscountPercent) || 0,
195
+ })),
196
+ discountType: q.discountType || 'none', discountValue: Number(q.discountValue) || 0, vatRate: Number(q.vatRate),
197
+ notes: String(q.notes || ''), terms: String(q.terms || ''), validityDays: Number(q.validityDays) || null,
198
+ currency: String(q.currency || 'GBP'),
199
+ };
200
+ }
201
+ async listTemplates() {
202
+ const rows = await this.db.query(`SELECT * FROM quotation_template ORDER BY name, id LIMIT ${exports.MAX_TEMPLATES}`);
203
+ return rows.map((r) => {
204
+ let data = {};
205
+ try {
206
+ data = JSON.parse(r.data || '{}');
207
+ }
208
+ catch {
209
+ data = {};
210
+ }
211
+ return { id: Number(r.id), name: r.name, createdBy: r.createdBy, createdAt: r.createdAt, updatedAt: r.updatedAt, lines: (data.lines || []).length, currency: data.currency, data };
212
+ });
213
+ }
214
+ async saveTemplateFromQuote(quoteId, name, actor) {
215
+ this.requirePremium('Quote templates');
216
+ const q = await this.core.getQuote(quoteId);
217
+ if (!q)
218
+ throw new Error('Quote not found');
219
+ const [count] = await this.db.query(`SELECT COUNT(*) AS n FROM quotation_template`);
220
+ if (Number((count === null || count === void 0 ? void 0 : count.n) || 0) >= exports.MAX_TEMPLATES)
221
+ throw new Error('You have reached the maximum number of templates. Delete one first.');
222
+ const clean = String(name || '').replace(/[\r\n\t]+/g, ' ').trim().slice(0, 190) || q.reference;
223
+ const res = await this.db.query(`INSERT INTO quotation_template (name, data, createdBy, createdAt, updatedAt) VALUES (?, ?, ?, NOW(), NOW())`, [clean, JSON.stringify(QuotationProService_1.templateData(q)), actor.slice(0, 190)], { needInsertId: true });
224
+ await this.core.logEvent(quoteId, 'comment', `Saved as template "${clean}"`, actor);
225
+ return { id: Number(res.insertId), name: clean };
226
+ }
227
+ async renameTemplate(id, name) {
228
+ this.requirePremium('Quote templates');
229
+ const clean = String(name || '').replace(/[\r\n\t]+/g, ' ').trim().slice(0, 190);
230
+ if (!clean)
231
+ throw new Error('A template needs a name.');
232
+ const res = await this.db.query(`UPDATE quotation_template SET name = ?, updatedAt = NOW() WHERE id = ?`, [clean, id], { needAffected: true });
233
+ if (!Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0))
234
+ throw new Error('Template not found');
235
+ }
236
+ async deleteTemplate(id) {
237
+ this.requirePremium('Quote templates');
238
+ await this.db.query(`DELETE FROM quotation_template WHERE id = ?`, [id]);
239
+ }
240
+ /** A draft quote from a template; the customer is left empty for staff to fill in. */
241
+ async quoteFromTemplate(id, channelId, actor, preparedBy = {}) {
242
+ this.requirePremium('Quote templates');
243
+ const [t] = await this.db.query(`SELECT * FROM quotation_template WHERE id = ?`, [id]);
244
+ if (!t)
245
+ throw new Error('Template not found');
246
+ let d = {};
247
+ try {
248
+ d = JSON.parse(t.data || '{}');
249
+ }
250
+ catch {
251
+ d = {};
252
+ }
253
+ const q = await this.core.createQuote(channelId, {
254
+ customerName: '', customerEmail: '',
255
+ lines: Array.isArray(d.lines) ? d.lines : [],
256
+ discountType: d.discountType, discountValue: d.discountValue, vatRate: d.vatRate,
257
+ notes: d.notes, terms: d.terms, validityDays: d.validityDays || undefined, currency: d.currency,
258
+ preparedByName: preparedBy.name || '', preparedByEmail: preparedBy.email || '',
259
+ }, actor);
260
+ await this.core.logEvent(q.id, 'comment', `Created from template "${t.name}"`, actor);
261
+ return this.core.getQuote(q.id);
262
+ }
263
+ // ── follow-up sequences ─────────────────────────────────────────────
264
+ /**
265
+ * Up to three extra e-mails after a quote is sent, each N days after the
266
+ * (latest) send, only while the quote is still open and unpaid. Each step
267
+ * is claimed (quote + step primary key) before it goes and released when
268
+ * the e-mail fails; steps go in order, at most one e-mail a quote a day,
269
+ * never within a day of the chaser or expiry reminder. Premium.
270
+ */
271
+ async runFollowUps(batch = 25) {
272
+ if (!this.core.isPremium())
273
+ return 0;
274
+ const s = await this.settings();
275
+ const steps = (0, pro_settings_1.activeSteps)(s);
276
+ if (!steps.length || !s.followupsSince)
277
+ return 0;
278
+ const since = new Date(s.followupsSince);
279
+ let sent = 0;
280
+ const earlier = [];
281
+ for (const st of steps) {
282
+ const list = earlier.length ? earlier : [0];
283
+ const rows = await this.db.query(`SELECT q.id FROM quotation q
284
+ WHERE q.status IN ('sent','viewed') AND q.paidAt IS NULL AND q.customerEmail <> ''
285
+ AND q.sentAt IS NOT NULL AND q.sentAt >= ? AND q.sentAt < DATE_SUB(NOW(), INTERVAL ? DAY)
286
+ AND (q.validUntil IS NULL OR q.validUntil > NOW())
287
+ AND (q.chaserSentAt IS NULL OR q.chaserSentAt < DATE_SUB(NOW(), INTERVAL 1 DAY))
288
+ AND (q.expiryReminderSentAt IS NULL OR q.expiryReminderSentAt < DATE_SUB(NOW(), INTERVAL 1 DAY))
289
+ AND NOT EXISTS (SELECT 1 FROM quotation_followup f WHERE f.quoteId = q.id AND (f.step = ? OR f.claimedAt > DATE_SUB(NOW(), INTERVAL 1 DAY)))
290
+ AND (SELECT COUNT(*) FROM quotation_followup e WHERE e.quoteId = q.id AND e.state = 'sent' AND e.step IN (${list.map(() => '?').join(',')})) = ?
291
+ ORDER BY q.sentAt, q.id LIMIT ${Math.max(1, Math.min(100, batch))}`, [since, st.days, st.n, ...list, earlier.length]);
292
+ for (const r of rows)
293
+ if (await this.sendStep(Number(r.id), st, steps.length))
294
+ sent++;
295
+ earlier.push(st.n);
296
+ }
297
+ return sent;
298
+ }
299
+ async sendStep(quoteId, st, of) {
300
+ const claim = await this.db.query(`INSERT IGNORE INTO quotation_followup (quoteId, step, state, claimedAt) VALUES (?, ?, 'sending', NOW())`, [quoteId, st.n], { needAffected: true });
301
+ if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) !== 1)
302
+ return false;
303
+ const q = await this.core.getQuote(quoteId);
304
+ const open = q && ['sent', 'viewed'].includes(q.status) && !q.paidAt && q.customerEmail
305
+ && (!q.validUntil || new Date(q.validUntil).getTime() > Date.now());
306
+ const res = open ? await this.core.emailCustomer(q, await this.core.getConfig(q.channelId), st.subject, st.body) : { ok: false };
307
+ if (!res.ok) {
308
+ await this.db.query(`DELETE FROM quotation_followup WHERE quoteId = ? AND step = ? AND state = 'sending'`, [quoteId, st.n]);
309
+ return false;
310
+ }
311
+ await this.db.query(`UPDATE quotation_followup SET state = 'sent', sentAt = NOW() WHERE quoteId = ? AND step = ?`, [quoteId, st.n]);
312
+ await this.core.logEvent(quoteId, 'followup', `Follow-up ${st.n} of ${Math.max(st.n, of)} e-mailed to ${q.customerEmail}`);
313
+ return true;
314
+ }
315
+ async followUpsSent(quoteId) {
316
+ const rows = await this.db.query(`SELECT step FROM quotation_followup WHERE quoteId = ? AND state = 'sent' ORDER BY step`, [quoteId]).catch(() => []);
317
+ return rows.map((r) => Number(r.step));
318
+ }
319
+ // ── discount approval ───────────────────────────────────────────────
320
+ async approvalRow(quoteId) {
321
+ const [r] = await this.db.query(`SELECT * FROM quotation_approval WHERE quoteId = ?`, [quoteId]).catch(() => []);
322
+ return r || null;
323
+ }
324
+ /** Approval is enforced: premium is on and at least one limit is set. */
325
+ async approvalActive() {
326
+ return this.core.isPremium() && (0, approvals_1.approvalConfigured)(await this.settings());
327
+ }
328
+ /** The pre-send gate: hold a send or mark-as-sent that needs approval (never a test send). */
329
+ async approvalGate(q, mode) {
330
+ if (mode === 'test' || !(await this.approvalActive()))
331
+ return null;
332
+ const s = await this.settings();
333
+ const st = (0, approvals_1.approvalStatus)(q, s, await this.approvalRow(Number(q.id)));
334
+ return (0, approvals_1.approvalGateMessage)(st, (0, approvals_1.approvalReasons)(q, s));
335
+ }
336
+ /** Where the quote stands, for the quote screen. */
337
+ async approvalInfo(quoteId) {
338
+ const s = await this.settings();
339
+ const q = await this.core.getQuote(quoteId);
340
+ if (!q)
341
+ throw new Error('Quote not found');
342
+ const row = await this.approvalRow(quoteId);
343
+ return {
344
+ configured: (0, approvals_1.approvalConfigured)(s), active: await this.approvalActive(),
345
+ status: (0, approvals_1.approvalStatus)(q, s, row), reasons: (0, approvals_1.approvalReasons)(q, s), row,
346
+ };
347
+ }
348
+ /** Administrators who may approve: the list in the settings, else every SuperAdmin. */
349
+ async approverEmails() {
350
+ const s = await this.settings();
351
+ if (s.approvers.length)
352
+ return s.approvers;
353
+ const rows = await this.db.query(`SELECT DISTINCT a.\`emailAddress\` AS emailAddress FROM administrator a
354
+ JOIN user_roles_role ur ON ur.\`userId\` = a.\`userId\`
355
+ JOIN role r ON r.id = ur.\`roleId\`
356
+ WHERE a.\`deletedAt\` IS NULL AND r.permissions LIKE ?`, ['%SuperAdmin%']).catch(() => []);
357
+ return rows.map((r) => String(r.emailAddress || '').toLowerCase()).filter(Boolean);
358
+ }
359
+ async requestApproval(quoteId, actor) {
360
+ this.requirePremium('Discount approval');
361
+ const q = await this.core.getQuote(quoteId);
362
+ if (!q)
363
+ throw new Error('Quote not found');
364
+ const s = await this.settings();
365
+ if (!(0, approvals_1.approvalConfigured)(s))
366
+ throw new Error('Discount approval is not set up: add a limit in Settings → Discount approval.');
367
+ const reasons = (0, approvals_1.approvalReasons)(q, s);
368
+ if (!reasons.length)
369
+ throw new Error('This quote does not need approval.');
370
+ if (!['draft', 'requested', 'sent', 'viewed', 'expired'].includes(q.status))
371
+ throw new Error('Approval is only needed before a quote is sent.');
372
+ const st = (0, approvals_1.approvalStatus)(q, s, await this.approvalRow(quoteId));
373
+ if (st === 'approved')
374
+ throw new Error('This version of the quote is already approved.');
375
+ if (st === 'pending')
376
+ throw new Error('Approval has already been requested for this version.');
377
+ const why = reasons.join('; ').slice(0, 1000);
378
+ await this.db.query(`INSERT INTO quotation_approval (quoteId, state, hash, reasons, requestedBy, requestedAt, decidedBy, decidedAt, comment, updatedAt)
379
+ VALUES (?, 'pending', ?, ?, ?, NOW(), '', NULL, '', NOW())
380
+ ON DUPLICATE KEY UPDATE state = 'pending', hash = VALUES(hash), reasons = VALUES(reasons), requestedBy = VALUES(requestedBy),
381
+ requestedAt = VALUES(requestedAt), decidedBy = '', decidedAt = NULL, comment = '', updatedAt = VALUES(updatedAt)`, [quoteId, (0, approvals_1.approvalHash)(q), why, actor.slice(0, 190)], { conflictColumns: ['quoteId'] });
382
+ await this.core.logEvent(quoteId, 'approval', `Discount approval requested: ${why}`, actor);
383
+ const preparer = String(q.preparedByEmail || actor).toLowerCase();
384
+ const approvers = (await this.approverEmails()).filter(e => e !== preparer || (s.approvers.length === 1 && s.approvalSelfSole));
385
+ const cur = String(q.currency || 'GBP');
386
+ const subject = `Approval needed: quote ${q.reference} (${(0, pricing_1.formatMoney)(Number(q.totalPence), cur)})`;
387
+ void this.core.mailStaff(approvers, subject, `${actor} asks for approval of quote ${q.reference} for ${q.customerCompany || q.customerName || 'a customer'} (${(0, pricing_1.formatMoney)(Number(q.totalPence), cur)}): ${why}.\n\n` +
388
+ `Open the quote to approve or reject it. It cannot be sent until it is approved.${this.adminUrl() ? `\n\n${this.adminUrl()}?quote=${q.id}` : ''}`);
389
+ }
390
+ /**
391
+ * Approve or reject the version the request was made for. One conditional
392
+ * UPDATE (pending + same hash), so a double click or two approvers at once
393
+ * record one decision; the second gets an error.
394
+ */
395
+ async decideApproval(quoteId, approve, comment, approver) {
396
+ this.requirePremium('Discount approval');
397
+ const q = await this.core.getQuote(quoteId);
398
+ if (!q)
399
+ throw new Error('Quote not found');
400
+ const s = await this.settings();
401
+ const row = await this.approvalRow(quoteId);
402
+ const can = (0, approvals_1.canDecide)({ approverEmail: approver.email, isSuperAdmin: approver.isSuperAdmin, settings: s, preparerEmail: q.preparedByEmail || (row === null || row === void 0 ? void 0 : row.requestedBy) || '' });
403
+ if (!can.ok)
404
+ throw new Error(can.reason);
405
+ if (!row || row.state !== 'pending')
406
+ throw new Error('There is no pending approval request for this quote (it may have been decided already).');
407
+ const hash = (0, approvals_1.approvalHash)(q);
408
+ if (row.hash !== hash)
409
+ throw new Error('The quote changed after approval was requested. It needs a new request.');
410
+ const clean = String(comment || '').trim().slice(0, 1000);
411
+ const won = await this.db.query(`UPDATE quotation_approval SET state = ?, decidedBy = ?, decidedAt = NOW(), comment = ?, updatedAt = NOW() WHERE quoteId = ? AND state = 'pending' AND hash = ?`, [approve ? 'approved' : 'rejected', approver.email.toLowerCase().slice(0, 190), clean, quoteId, hash], { needAffected: true });
412
+ if (Number((won === null || won === void 0 ? void 0 : won.affectedRows) || 0) !== 1)
413
+ throw new Error('This approval request was decided already.');
414
+ await this.core.logEvent(quoteId, 'approval', `${approve ? 'Discount approved' : 'Discount approval rejected'}${clean ? ` — ${clean}` : ''}`, approver.email);
415
+ const to = String(q.preparedByEmail || row.requestedBy || '').toLowerCase();
416
+ const by = approver.name || approver.email;
417
+ void this.core.mailStaff([to], approve ? `Approved: quote ${q.reference} can be sent` : `Not approved: quote ${q.reference}`, (approve ? `${by} approved quote ${q.reference}. You can send it now.` : `${by} rejected the discount on quote ${q.reference}. Change the quote and request approval again.`) +
418
+ (clean ? `\n\nComment: ${clean}` : ''));
419
+ }
420
+ /** Quotes waiting for a decision (newest request first) that are still on the version asked about. */
421
+ async pendingApprovals(limit = 50) {
422
+ const s = await this.settings();
423
+ const rows = await this.db.query(`SELECT quoteId FROM quotation_approval WHERE state = 'pending' ORDER BY requestedAt DESC LIMIT ${Math.max(1, Math.min(200, limit))}`).catch(() => []);
424
+ const out = [];
425
+ for (const r of rows) {
426
+ const q = await this.core.getQuote(Number(r.quoteId));
427
+ if (q && (0, approvals_1.approvalStatus)(q, s, await this.approvalRow(q.id)) === 'pending') {
428
+ out.push({ id: q.id, reference: q.reference, customerName: q.customerName, customerCompany: q.customerCompany, totalPence: q.totalPence, currency: q.currency, reasons: (0, approvals_1.approvalReasons)(q, s) });
429
+ }
430
+ }
431
+ return out;
432
+ }
433
+ // ── trail → approvals invalidation + webhooks ───────────────────────
434
+ onTrail(e) {
435
+ if (e.type === 'updated')
436
+ void this.invalidateApproval(e.quoteId).catch(() => undefined);
437
+ this.nudgeWebhooks();
438
+ }
439
+ /** An edit after approval was given or requested makes the snapshot stale; record it once. */
440
+ async invalidateApproval(quoteId) {
441
+ const row = await this.approvalRow(quoteId);
442
+ if (!row || !['pending', 'approved'].includes(row.state))
443
+ return;
444
+ const q = await this.core.getQuote(quoteId);
445
+ if (!q || (0, approvals_1.approvalHash)(q) === row.hash)
446
+ return;
447
+ const res = await this.db.query(`UPDATE quotation_approval SET state = 'stale', updatedAt = NOW() WHERE quoteId = ? AND state = ? AND hash = ?`, [quoteId, row.state, row.hash], { needAffected: true });
448
+ if (Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1) {
449
+ await this.core.logEvent(quoteId, 'approval', `Approval ${row.state === 'approved' ? 'given' : 'requested'} for an earlier version no longer counts: the quote changed. Request approval again.`);
450
+ }
451
+ }
452
+ // ── webhooks ────────────────────────────────────────────────────────
453
+ async webhookSecret() {
454
+ let s = await this.core.prefs.get('webhooks.secret');
455
+ if (!s || s.length < 32) {
456
+ const fresh = crypto.randomBytes(32).toString('hex');
457
+ await this.core.prefs.cas('webhooks.secret', s || null, fresh);
458
+ s = (await this.core.prefs.get('webhooks.secret')) || fresh;
459
+ }
460
+ return s;
461
+ }
462
+ async regenerateWebhookSecret() {
463
+ this.requirePremium('Webhooks');
464
+ await this.core.prefs.set('webhooks.secret', crypto.randomBytes(32).toString('hex'));
465
+ return this.webhookSecret();
466
+ }
467
+ /** The trail cursor; created at the newest entry so history is never replayed. */
468
+ async webhookCursor() {
469
+ const v = await this.core.prefs.get('webhooks.cursor');
470
+ if (v !== null && v !== undefined && /^\d+$/.test(v))
471
+ return Number(v);
472
+ const [row] = await this.db.query(`SELECT MAX(id) AS id FROM quotation_event`).catch(() => [{ id: 0 }]);
473
+ const start = String(Number((row === null || row === void 0 ? void 0 : row.id) || 0));
474
+ await this.core.prefs.cas('webhooks.cursor', null, start);
475
+ return Number((await this.core.prefs.get('webhooks.cursor')) || start);
476
+ }
477
+ /** Something landed on a trail: sweep and deliver shortly, in this process. */
478
+ nudgeWebhooks() {
479
+ if (this.nudgeTimer)
480
+ return;
481
+ this.nudgeTimer = setTimeout(() => {
482
+ this.nudgeTimer = null;
483
+ void (async () => {
484
+ const s = await this.settings();
485
+ if (!s.webhooks.some(h => h.enabled))
486
+ return;
487
+ if ((await this.sweepWebhooks()) > 0)
488
+ await this.dispatchWebhooks();
489
+ })().catch(e => core_1.Logger.warn(`webhook delivery failed: ${e === null || e === void 0 ? void 0 : e.message}`, loggerCtx));
490
+ }, 1500);
491
+ if (typeof this.nudgeTimer.unref === 'function')
492
+ this.nudgeTimer.unref();
493
+ }
494
+ /**
495
+ * Read the trail from the cursor and queue one delivery per event per
496
+ * webhook that wants it (UNIQUE hook + event, so a sweep that runs twice
497
+ * queues nothing twice). Without premium the cursor moves on and nothing
498
+ * is queued: events from a lapse are not sent later. Returns queued count.
499
+ */
500
+ async sweepWebhooks(max = 500) {
501
+ const s = await this.settings();
502
+ const hooks = s.webhooks.filter(h => h.enabled && h.events.length);
503
+ if (!hooks.length)
504
+ return 0;
505
+ const cursor = await this.webhookCursor();
506
+ const rows = await this.db.query(`SELECT id, quoteId, type, detail, createdAt FROM quotation_event WHERE id > ? ORDER BY id LIMIT ${Math.max(1, Math.min(2000, max))}`, [cursor]);
507
+ if (!rows.length)
508
+ return 0;
509
+ const last = Number(rows[rows.length - 1].id);
510
+ // Move the cursor first, only if nobody moved it meanwhile; the UNIQUE key stops duplicates either way.
511
+ await this.core.prefs.cas('webhooks.cursor', String(cursor), String(last));
512
+ if (!this.core.isPremium())
513
+ return 0;
514
+ const cfg = await this.core.getConfig(1).catch(() => null);
515
+ let n = 0;
516
+ for (const e of rows) {
517
+ let event = pro_settings_1.TRAIL_TO_WEBHOOK[e.type] || '';
518
+ if (e.type === 'approval' && String(e.detail).startsWith('Discount approval requested'))
519
+ event = 'approval_requested';
520
+ if (!event)
521
+ continue;
522
+ const q = await this.core.getQuote(Number(e.quoteId));
523
+ if (!q)
524
+ continue;
525
+ for (const h of hooks) {
526
+ if (!h.events.includes(event))
527
+ continue;
528
+ n += (await this.queueDelivery(h, event, `e${e.id}`, q, String(e.detail || ''), new Date(e.createdAt), cfg === null || cfg === void 0 ? void 0 : cfg.accentColor)) ? 1 : 0;
529
+ }
530
+ }
531
+ return n;
532
+ }
533
+ async queueDelivery(hook, event, key, q, detail, at, accent) {
534
+ const payload = (0, webhooks_1.webhookPayload)(hook.format, event, q, detail, at, {
535
+ adminUrl: this.adminUrl(), site: (this.core.getOptions().publicBaseUrl || '').replace(/\/$/, ''), accent,
536
+ });
537
+ const res = await this.db.query(`INSERT IGNORE INTO quotation_webhook_log (hookId, event, eventKey, quoteId, url, format, payload, state, attempts, code, error, nextAt, createdAt, updatedAt)
538
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, 0, '', NOW(), NOW(), NOW())`, [hook.id, event, key.slice(0, 40), Number(q.id) || 0, hook.url, hook.format, JSON.stringify(payload)], { needAffected: true });
539
+ return Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1;
540
+ }
541
+ /** Send what is due; each delivery is claimed pending → sending first, so two runs never send the same one. */
542
+ async dispatchWebhooks(batch = 20) {
543
+ await this.db.query(`UPDATE quotation_webhook_log SET state = 'pending' WHERE state = 'sending' AND updatedAt < DATE_SUB(NOW(), INTERVAL 15 MINUTE)`);
544
+ const rows = await this.db.query(`SELECT id FROM quotation_webhook_log WHERE state = 'pending' AND nextAt <= NOW() ORDER BY id LIMIT ${Math.max(1, Math.min(100, batch))}`);
545
+ let n = 0;
546
+ for (const r of rows) {
547
+ const claim = await this.db.query(`UPDATE quotation_webhook_log SET state = 'sending', updatedAt = NOW() WHERE id = ? AND state = 'pending'`, [r.id], { needAffected: true });
548
+ if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) !== 1)
549
+ continue;
550
+ await this.deliver(Number(r.id));
551
+ n++;
552
+ }
553
+ return n;
554
+ }
555
+ async deliver(id) {
556
+ var _a;
557
+ const [r] = await this.db.query(`SELECT * FROM quotation_webhook_log WHERE id = ?`, [id]);
558
+ if (!r)
559
+ return;
560
+ const attempts = Number(r.attempts || 0) + 1;
561
+ const body = String(r.payload || '{}');
562
+ const ts = Math.floor(Date.now() / 1000);
563
+ let result;
564
+ try {
565
+ result = await (0, webhooks_1.deliverWebhook)(String(r.url), body, {
566
+ 'Content-Type': 'application/json; charset=utf-8',
567
+ 'User-Agent': 'HULO-Quotations-Vendure',
568
+ 'X-Hulo-Event': String(r.event),
569
+ 'X-Hulo-Delivery': String(id),
570
+ 'X-Hulo-Timestamp': String(ts),
571
+ 'X-Hulo-Signature': (0, webhooks_1.signWebhook)(await this.webhookSecret(), body, ts),
572
+ }, { allowPrivate: !!this.core.getOptions().allowPrivateWebhooks });
573
+ }
574
+ catch (e) {
575
+ result = { ok: false, code: 0, error: String((e === null || e === void 0 ? void 0 : e.message) || 'failed') };
576
+ }
577
+ const state = result.ok ? 'sent' : attempts >= webhooks_1.WEBHOOK_MAX_ATTEMPTS ? 'failed' : 'pending';
578
+ const wait = (_a = webhooks_1.WEBHOOK_BACKOFF[Math.min(attempts, webhooks_1.WEBHOOK_BACKOFF.length - 1)]) !== null && _a !== void 0 ? _a : 3600;
579
+ await this.db.query(`UPDATE quotation_webhook_log SET state = ?, attempts = ?, code = ?, error = ?, nextAt = DATE_ADD(NOW(), INTERVAL ? SECOND), updatedAt = NOW() WHERE id = ?`, [state, attempts, Math.max(0, Math.min(65535, result.code)), result.error.slice(0, 255), wait, id]);
580
+ }
581
+ /** Hourly: sweep, deliver, and drop log rows older than 30 days. */
582
+ async hourlyWebhooks() {
583
+ await this.sweepWebhooks();
584
+ await this.dispatchWebhooks(100);
585
+ await this.db.query(`DELETE FROM quotation_webhook_log WHERE createdAt < DATE_SUB(NOW(), INTERVAL ? DAY)`, [webhooks_1.WEBHOOK_KEEP_DAYS]);
586
+ }
587
+ /** Queue a test delivery to one webhook and send it now. */
588
+ async testWebhook(hookId) {
589
+ this.requirePremium('Webhooks');
590
+ const hook = (await this.settings()).webhooks.find(h => h.id === hookId);
591
+ if (!hook)
592
+ return null;
593
+ const cur = await this.core.primaryCurrency();
594
+ const q = {
595
+ id: 0, channelId: 1, reference: 'TEST-0001', status: 'sent', customerName: 'Test Customer', customerCompany: 'Example Ltd',
596
+ customerEmail: 'customer@example.com', currency: cur, totalPence: 12000, subTotalPence: 10000, discountPence: 0, vatPence: 2000,
597
+ validUntil: new Date(Date.now() + 30 * DAY_MS), sentAt: new Date(), paidAt: null, preparedByName: '', preparedByEmail: '', requestSource: '',
598
+ };
599
+ const key = `test-${crypto.randomBytes(5).toString('hex')}`;
600
+ await this.queueDelivery(hook, 'quote_sent', key, q, 'Test delivery from HULO Quotations', new Date());
601
+ const [row] = await this.db.query(`SELECT id FROM quotation_webhook_log WHERE hookId = ? AND eventKey = ?`, [hook.id, key]);
602
+ if (!row)
603
+ return null;
604
+ const claim = await this.db.query(`UPDATE quotation_webhook_log SET state = 'sending', updatedAt = NOW() WHERE id = ? AND state = 'pending'`, [row.id], { needAffected: true });
605
+ if (Number((claim === null || claim === void 0 ? void 0 : claim.affectedRows) || 0) === 1)
606
+ await this.deliver(Number(row.id));
607
+ const [out] = await this.db.query(`SELECT id, hookId, event, quoteId, url, state, attempts, code, error, nextAt, createdAt, updatedAt FROM quotation_webhook_log WHERE id = ?`, [row.id]);
608
+ return out || null;
609
+ }
610
+ async webhookLog(limit = 50) {
611
+ return this.db.query(`SELECT id, hookId, event, quoteId, url, state, attempts, code, error, nextAt, createdAt, updatedAt
612
+ FROM quotation_webhook_log ORDER BY id DESC LIMIT ${Math.max(1, Math.min(500, limit))}`);
613
+ }
614
+ /** Retry a failed delivery now. */
615
+ async retryWebhook(id) {
616
+ this.requirePremium('Webhooks');
617
+ const res = await this.db.query(`UPDATE quotation_webhook_log SET state = 'pending', attempts = 0, nextAt = NOW(), updatedAt = NOW() WHERE id = ? AND state = 'failed'`, [id], { needAffected: true });
618
+ const ok = Number((res === null || res === void 0 ? void 0 : res.affectedRows) || 0) === 1;
619
+ if (ok)
620
+ void this.dispatchWebhooks().catch(() => undefined);
621
+ return ok;
622
+ }
623
+ // ── sales reports ───────────────────────────────────────────────────
624
+ /** `YYYY-MM-DD` strings (UTC) → [from, to) dates; default the last 90 days. */
625
+ static range(from, to, now = new Date()) {
626
+ const ok = (d) => !!d && /^\d{4}-\d{2}-\d{2}$/.test(d) && !Number.isNaN(Date.parse(`${d}T00:00:00Z`));
627
+ const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
628
+ let t = ok(to) ? new Date(`${to}T00:00:00Z`) : today;
629
+ let f = ok(from) ? new Date(`${from}T00:00:00Z`) : new Date(t.getTime() - 89 * DAY_MS);
630
+ if (f > t)
631
+ [f, t] = [t, f];
632
+ const day = (d) => d.toISOString().slice(0, 10);
633
+ return { from: f, to: new Date(t.getTime() + DAY_MS), fromDay: day(f), toDay: day(t) };
634
+ }
635
+ /** Per member of staff ("prepared by", by e-mail; '' = the store): quotes sent in the range, won, win rate, value won per currency, average hours to acceptance. */
636
+ async reportByStaff(from, to) {
637
+ this.requirePremium('Sales reports');
638
+ const rows = await this.db.query(`SELECT LOWER(preparedByEmail) AS email, MAX(preparedByName) AS name, currency,
639
+ COUNT(*) AS sent,
640
+ SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won,
641
+ SUM(CASE WHEN status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS value,
642
+ SUM(CASE WHEN status IN ('accepted','converted') AND respondedAt IS NOT NULL AND respondedAt >= sentAt THEN TIMESTAMPDIFF(SECOND, sentAt, respondedAt) ELSE 0 END) AS secs,
643
+ SUM(CASE WHEN status IN ('accepted','converted') AND respondedAt IS NOT NULL AND respondedAt >= sentAt THEN 1 ELSE 0 END) AS timed
644
+ FROM quotation WHERE sentAt >= ? AND sentAt < ?
645
+ GROUP BY LOWER(preparedByEmail), currency`, [from, to]);
646
+ const out = new Map();
647
+ for (const r of rows) {
648
+ const k = String(r.email || '');
649
+ const o = out.get(k) || { email: k, name: '', sent: 0, won: 0, wonByCurrency: {}, secs: 0, timed: 0 };
650
+ o.name = o.name || String(r.name || '');
651
+ o.sent += Number(r.sent || 0);
652
+ o.won += Number(r.won || 0);
653
+ o.secs += Number(r.secs || 0);
654
+ o.timed += Number(r.timed || 0);
655
+ const c = String(r.currency || 'GBP').toUpperCase();
656
+ if (Number(r.value || 0))
657
+ o.wonByCurrency[c] = (o.wonByCurrency[c] || 0) + Number(r.value);
658
+ out.set(k, o);
659
+ }
660
+ return [...out.values()].map(o => ({
661
+ email: o.email, name: o.name, sent: o.sent, won: o.won,
662
+ winRatePct: o.sent ? Math.round((o.won / o.sent) * 1000) / 10 : 0,
663
+ wonByCurrency: Object.fromEntries(Object.entries(o.wonByCurrency).sort(([a], [b]) => a.localeCompare(b))),
664
+ avgAcceptHours: o.timed ? Math.round((o.secs / o.timed / 3600) * 10) / 10 : null,
665
+ })).sort((a, b) => (b.sent - a.sent) || a.email.localeCompare(b.email));
666
+ }
667
+ /** Per request source: quotes created in the range, sent, won, win rate (won of those sent), value won per currency. */
668
+ async reportBySource(from, to) {
669
+ this.requirePremium('Sales reports');
670
+ const rows = await this.db.query(`SELECT requestSource, currency, COUNT(*) AS created,
671
+ SUM(CASE WHEN sentAt IS NOT NULL THEN 1 ELSE 0 END) AS sent,
672
+ SUM(CASE WHEN status IN ('accepted','converted') THEN 1 ELSE 0 END) AS won,
673
+ SUM(CASE WHEN status IN ('accepted','converted') THEN totalPence ELSE 0 END) AS value
674
+ FROM quotation WHERE createdAt >= ? AND createdAt < ?
675
+ GROUP BY requestSource, currency`, [from, to]);
676
+ const out = new Map();
677
+ for (const r of rows) {
678
+ const k = (0, webhooks_1.reportSource)(String(r.requestSource || ''));
679
+ const o = out.get(k) || { source: k, created: 0, sent: 0, won: 0, wonByCurrency: {} };
680
+ o.created += Number(r.created || 0);
681
+ o.sent += Number(r.sent || 0);
682
+ o.won += Number(r.won || 0);
683
+ const c = String(r.currency || 'GBP').toUpperCase();
684
+ if (Number(r.value || 0))
685
+ o.wonByCurrency[c] = (o.wonByCurrency[c] || 0) + Number(r.value);
686
+ out.set(k, o);
687
+ }
688
+ const order = ['form', 'product', 'cart', 'calculator', 'other', 'manual'];
689
+ return [...out.values()].sort((a, b) => order.indexOf(a.source) - order.indexOf(b.source)).map(o => ({
690
+ ...o, winRatePct: o.sent ? Math.round((o.won / o.sent) * 1000) / 10 : 0,
691
+ }));
692
+ }
693
+ /** The CSV of quotes created in [from, to): a header line, then one line per quote (amounts as plain numbers, per row currency). */
694
+ async reportCsv(from, to) {
695
+ this.requirePremium('Sales reports');
696
+ let csv = '' + (0, csv_1.csvLine)(QuotationProService_1.CSV_HEADERS);
697
+ let last = 0;
698
+ const iso = (v) => (v ? new Date(v).toISOString().replace('T', ' ').slice(0, 19) : '');
699
+ for (;;) {
700
+ const rows = await this.db.query(`SELECT q.*, d.depositPence AS proDeposit, d.balancePence AS proBalance, r.reference AS revisionRef
701
+ FROM quotation q
702
+ LEFT JOIN quotation_deposit d ON d.quoteId = q.id AND d.depositRef <> ''
703
+ LEFT JOIN quotation r ON r.id = q.revisionOf
704
+ WHERE q.createdAt >= ? AND q.createdAt < ? AND q.id > ? ORDER BY q.id LIMIT 500`, [from, to, last]);
705
+ for (const q of rows) {
706
+ last = Number(q.id);
707
+ csv += (0, csv_1.csvLine)([
708
+ q.reference, q.status, iso(q.createdAt), iso(q.sentAt), iso(q.viewedAt), iso(q.respondedAt), iso(q.validUntil), iso(q.paidAt),
709
+ q.customerName, q.customerEmail, q.customerCompany, q.customerPhone, q.preparedByName, q.preparedByEmail,
710
+ (0, webhooks_1.reportSource)(String(q.requestSource || '')), q.currency,
711
+ (0, csv_1.csvAmount)(q.subTotalPence), (0, csv_1.csvAmount)(q.discountPence), (0, csv_1.csvAmount)(q.vatPence), (0, csv_1.csvAmount)(q.totalPence),
712
+ (0, csv_1.csvAmount)(q.proDeposit), (0, csv_1.csvAmount)(q.proBalance), q.acceptedBy, q.convertedOrderId || '', q.revisionRef || '', q.channelId,
713
+ ], QuotationProService_1.CSV_AMOUNTS);
714
+ }
715
+ if (rows.length < 500)
716
+ break;
717
+ }
718
+ return csv;
719
+ }
720
+ /** The webhook event list for the settings screen. */
721
+ static webhookEvents() { return pro_settings_1.WEBHOOK_EVENTS; }
722
+ };
723
+ exports.QuotationProService = QuotationProService;
724
+ QuotationProService.CSV_HEADERS = ['Reference', 'Status', 'Created (UTC)', 'Sent (UTC)', 'Opened (UTC)', 'Responded (UTC)', 'Valid until (UTC)', 'Paid (UTC)',
725
+ 'Customer', 'E-mail', 'Company', 'Phone', 'Prepared by', 'Prepared by e-mail', 'Source', 'Currency', 'Subtotal', 'Discount', 'VAT', 'Total',
726
+ 'Deposit', 'Balance', 'Accepted by', 'Order id', 'Revision of', 'Channel'];
727
+ QuotationProService.CSV_AMOUNTS = [16, 17, 18, 19, 20, 21];
728
+ exports.QuotationProService = QuotationProService = QuotationProService_1 = __decorate([
729
+ (0, common_1.Injectable)(),
730
+ __metadata("design:paramtypes", [quotation_service_1.QuotationService])
731
+ ], QuotationProService);
732
+ //# sourceMappingURL=pro.service.js.map