@hintergrund/worker 0.2.3 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/cms/handlers/admin-users.handler.d.ts +1 -0
- package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/admin-users.handler.js +60 -79
- package/dist/api/cms/handlers/auth.handler.d.ts +1 -1
- package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/auth.handler.js +13 -94
- package/dist/api/cms/handlers/dashboard.handler.d.ts +1 -1
- package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/dashboard.handler.js +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +8 -1
- package/dist/api/cms/handlers/integrations.handler.d.ts +5 -0
- package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/integrations.handler.js +24 -0
- package/dist/api/cms/handlers/recovery.handler.d.ts +5 -0
- package/dist/api/cms/handlers/recovery.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/recovery.handler.js +53 -0
- package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/setup.handler.js +97 -35
- package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -1
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +64 -55
- package/dist/api/cms/routes/auth.routes.d.ts +1 -1
- package/dist/api/cms/routes/auth.routes.d.ts.map +1 -1
- package/dist/api/cms/routes/auth.routes.js +7 -2
- package/dist/api/cms/routes/index.d.ts +1 -1
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +7 -11
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +3 -4
- package/dist/api/emails/handlers/invoice.handler.d.ts +8 -15
- package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/invoice.handler.js +142 -170
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +27 -8
- package/dist/api/emails/handlers/send.handler.d.ts +1 -3
- package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/send.handler.js +18 -65
- package/dist/api/emails/handlers/settings.handler.d.ts +60 -12
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +35 -94
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +5 -6
- package/dist/api/emails/routes/mail.routes.d.ts +5 -0
- package/dist/api/emails/routes/mail.routes.d.ts.map +1 -0
- package/dist/api/emails/routes/mail.routes.js +188 -0
- package/dist/api/shop/handlers/products.handler.d.ts +2 -2
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/products.handler.js +21 -8
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +17 -66
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -18
- package/dist/lib/auth/crypto.d.ts +0 -1
- package/dist/lib/auth/crypto.d.ts.map +1 -1
- package/dist/lib/auth/crypto.js +1 -4
- package/dist/lib/brand.d.ts +6 -0
- package/dist/lib/brand.d.ts.map +1 -0
- package/dist/lib/brand.js +31 -0
- package/dist/lib/config.d.ts +1 -2
- package/dist/lib/config.d.ts.map +1 -1
- package/dist/lib/config.js +1 -8
- package/dist/lib/email-template.d.ts +4 -7
- package/dist/lib/email-template.d.ts.map +1 -1
- package/dist/lib/email-template.js +9 -31
- package/dist/lib/email.d.ts +20 -11
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +29 -19
- package/dist/lib/github.d.ts +1 -1
- package/dist/lib/github.d.ts.map +1 -1
- package/dist/lib/github.js +13 -4
- package/dist/lib/integration-health.d.ts +18 -0
- package/dist/lib/integration-health.d.ts.map +1 -0
- package/dist/lib/integration-health.js +51 -0
- package/dist/lib/invoice.d.ts +13 -0
- package/dist/lib/invoice.d.ts.map +1 -0
- package/dist/lib/invoice.js +41 -0
- package/dist/lib/mail-schema.d.ts +2 -0
- package/dist/lib/mail-schema.d.ts.map +1 -0
- package/dist/lib/mail-schema.js +56 -0
- package/dist/lib/mail.d.ts +83 -0
- package/dist/lib/mail.d.ts.map +1 -0
- package/dist/lib/mail.js +211 -0
- package/dist/lib/project-db.d.ts +3 -4
- package/dist/lib/project-db.d.ts.map +1 -1
- package/dist/lib/project-db.js +14 -43
- package/dist/lib/template.d.ts.map +1 -1
- package/dist/lib/template.js +28 -0
- package/dist/lib/user-recovery.d.ts +9 -0
- package/dist/lib/user-recovery.d.ts.map +1 -0
- package/dist/lib/user-recovery.js +42 -0
- package/dist/lib/website-i18n.d.ts +10 -0
- package/dist/lib/website-i18n.d.ts.map +1 -0
- package/dist/lib/website-i18n.js +195 -0
- package/dist/middleware/auth.d.ts +3 -1
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +8 -4
- package/package.json +4 -2
- package/dist/api/cms/handlers/agent-conversations.handler.d.ts +0 -6
- package/dist/api/cms/handlers/agent-conversations.handler.d.ts.map +0 -1
- package/dist/api/cms/handlers/agent-conversations.handler.js +0 -87
- package/dist/api/cms/handlers/website-templates.handler.d.ts +0 -6
- package/dist/api/cms/handlers/website-templates.handler.d.ts.map +0 -1
- package/dist/api/cms/handlers/website-templates.handler.js +0 -53
- package/dist/api/shop/handlers/prices.handler.d.ts +0 -4
- package/dist/api/shop/handlers/prices.handler.d.ts.map +0 -1
- package/dist/api/shop/handlers/prices.handler.js +0 -6
- package/dist/hintergrund-assets.d.ts +0 -5
- package/dist/hintergrund-assets.d.ts.map +0 -1
- package/dist/hintergrund-assets.js +0 -11
|
@@ -1,181 +1,153 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
export async function generateInvoicePdf(config, data, branding) {
|
|
44
|
-
const mergedConfig = { ...DEFAULT_INVOICE_CONFIG, ...config };
|
|
45
|
-
const pdfDoc = await PDFDocument.create();
|
|
46
|
-
const page = pdfDoc.addPage([595.28, 841.89]);
|
|
47
|
-
const { width, height } = page.getSize();
|
|
48
|
-
let font;
|
|
49
|
-
let boldFont;
|
|
50
|
-
switch (mergedConfig.fontFamily) {
|
|
51
|
-
case 'times':
|
|
52
|
-
font = await pdfDoc.embedFont(StandardFonts.TimesRoman);
|
|
53
|
-
boldFont = await pdfDoc.embedFont(StandardFonts.TimesRomanBold);
|
|
54
|
-
break;
|
|
55
|
-
case 'courier':
|
|
56
|
-
font = await pdfDoc.embedFont(StandardFonts.Courier);
|
|
57
|
-
boldFont = await pdfDoc.embedFont(StandardFonts.CourierBold);
|
|
58
|
-
break;
|
|
59
|
-
default:
|
|
60
|
-
font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
|
61
|
-
boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
|
62
|
-
}
|
|
63
|
-
const primaryColor = hexToRgb(branding?.primaryColor || mergedConfig.primaryColor);
|
|
64
|
-
const accentColor = hexToRgb(mergedConfig.accentColor);
|
|
65
|
-
const margin = 50;
|
|
66
|
-
let yPos = height - margin;
|
|
67
|
-
// Logo
|
|
68
|
-
const logo = mergedConfig.showLogo ? branding?.logo : undefined;
|
|
69
|
-
if (logo) {
|
|
70
|
-
try {
|
|
71
|
-
const logoData = logo.split(',')[1];
|
|
72
|
-
const logoBytes = Uint8Array.from(atob(logoData), (c) => c.charCodeAt(0));
|
|
73
|
-
let logoImage;
|
|
74
|
-
if (logo.includes('image/png')) {
|
|
75
|
-
logoImage = await pdfDoc.embedPng(logoBytes);
|
|
1
|
+
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
|
|
2
|
+
import fontkit from '@pdf-lib/fontkit';
|
|
3
|
+
import { validateBrand, validateInvoiceDesign } from '@hintergrund/runtime-contracts';
|
|
4
|
+
/** Same deterministic renderer for preview, downloads and email attachments. */
|
|
5
|
+
export async function generateInvoicePdf(config, data, brand, design, assets = {}) {
|
|
6
|
+
validateBrand(brand);
|
|
7
|
+
validateInvoiceDesign(design);
|
|
8
|
+
const pdf = await PDFDocument.create();
|
|
9
|
+
pdf.registerFontkit(fontkit);
|
|
10
|
+
const standard = (name) => name === 'Georgia' ? StandardFonts.TimesRoman : name === 'Courier New' ? StandardFonts.Courier : StandardFonts.Helvetica;
|
|
11
|
+
if ((brand.bodyFontPath && !assets.bodyFont) || (brand.displayFontPath && !assets.displayFont))
|
|
12
|
+
throw new Error('Missing brand font asset.');
|
|
13
|
+
const font = await pdf.embedFont(assets.bodyFont ?? standard(brand.bodyFont), { subset: true });
|
|
14
|
+
const heading = await pdf.embedFont(assets.displayFont ?? standard(brand.displayFont), { subset: true });
|
|
15
|
+
const color = (hex) => rgb(...[1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255));
|
|
16
|
+
const ink = color(brand.colors.text), primary = color(brand.colors.primary), muted = color(brand.colors.muted);
|
|
17
|
+
const [width, height] = design.pageSize === 'A4' ? [595.28, 841.89] : [612, 792];
|
|
18
|
+
const margin = design.margin, size = design.fontSize, line = size * design.lineHeight;
|
|
19
|
+
const contentWidth = width - 2 * margin;
|
|
20
|
+
let page, y;
|
|
21
|
+
const wrap = (text, maxWidth, face = font, fontSize = size) => {
|
|
22
|
+
const lines = [];
|
|
23
|
+
for (const paragraph of String(text).replace(/\r/g, '').split('\n')) {
|
|
24
|
+
let current = '';
|
|
25
|
+
for (const word of paragraph.split(/\s+/)) {
|
|
26
|
+
const candidate = current ? `${current} ${word}` : word;
|
|
27
|
+
if (face.widthOfTextAtSize(candidate, fontSize) <= maxWidth) {
|
|
28
|
+
current = candidate;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (current) {
|
|
32
|
+
lines.push(current);
|
|
33
|
+
current = '';
|
|
34
|
+
}
|
|
35
|
+
// Only split within a word when a single token cannot fit the column.
|
|
36
|
+
for (const char of word) {
|
|
37
|
+
if (current && face.widthOfTextAtSize(current + char, fontSize) > maxWidth) {
|
|
38
|
+
lines.push(current);
|
|
39
|
+
current = '';
|
|
40
|
+
}
|
|
41
|
+
current += char;
|
|
42
|
+
}
|
|
76
43
|
}
|
|
77
|
-
|
|
78
|
-
logoImage = await pdfDoc.embedJpg(logoBytes);
|
|
79
|
-
}
|
|
80
|
-
const logoMaxHeight = 50;
|
|
81
|
-
const logoMaxWidth = 150;
|
|
82
|
-
const scale = Math.min(logoMaxWidth / logoImage.width, logoMaxHeight / logoImage.height);
|
|
83
|
-
const logoWidth = logoImage.width * scale;
|
|
84
|
-
const logoHeight = logoImage.height * scale;
|
|
85
|
-
page.drawImage(logoImage, { x: margin, y: yPos - logoHeight, width: logoWidth, height: logoHeight });
|
|
86
|
-
yPos -= logoHeight + 20;
|
|
44
|
+
lines.push(current);
|
|
87
45
|
}
|
|
88
|
-
|
|
89
|
-
|
|
46
|
+
return lines;
|
|
47
|
+
};
|
|
48
|
+
const footerLines = wrap(design.footerText, contentWidth, font, 8);
|
|
49
|
+
const bottom = margin + footerLines.length * 11 + 22;
|
|
50
|
+
function newPage() {
|
|
51
|
+
page = pdf.addPage([width, height]);
|
|
52
|
+
page.drawRectangle({ x: 0, y: 0, width, height, color: color(brand.colors.surface) });
|
|
53
|
+
y = height - margin;
|
|
54
|
+
}
|
|
55
|
+
function ensure(space) { if (y - space < bottom)
|
|
56
|
+
newPage(); }
|
|
57
|
+
function text(value, face = font, fontSize = size, tone = ink) {
|
|
58
|
+
for (const row of wrap(value, contentWidth, face, fontSize)) {
|
|
59
|
+
ensure(fontSize * design.lineHeight);
|
|
60
|
+
page.drawText(row, { x: margin, y: y - fontSize, size: fontSize, font: face, color: tone });
|
|
61
|
+
y -= fontSize * design.lineHeight;
|
|
90
62
|
}
|
|
91
63
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
page.drawText(line, { x: companyInfoX - font.widthOfTextAtSize(line, 10), y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
103
|
-
yPos -= 12;
|
|
64
|
+
newPage();
|
|
65
|
+
if (design.showLogo && brand.logoPath) {
|
|
66
|
+
if (!assets.logo)
|
|
67
|
+
throw new Error('Missing brand logo asset.');
|
|
68
|
+
const image = /\.png$/i.test(brand.logoPath) ? await pdf.embedPng(assets.logo) : await pdf.embedJpg(assets.logo);
|
|
69
|
+
const scale = Math.min(design.logoWidth / image.width, 64 / image.height);
|
|
70
|
+
const w = image.width * scale, h = image.height * scale;
|
|
71
|
+
const x = design.logoPosition === 'right' ? width - margin - w : design.logoPosition === 'center' ? (width - w) / 2 : margin;
|
|
72
|
+
page.drawImage(image, { x, y: y - h, width: w, height: h });
|
|
73
|
+
y -= h + line;
|
|
104
74
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
75
|
+
for (const value of [config.companyName, config.companyAddress, config.companyEmail, config.companyPhone])
|
|
76
|
+
if (value)
|
|
77
|
+
text(value);
|
|
78
|
+
y -= line;
|
|
79
|
+
text('INVOICE', heading, design.titleSize, primary);
|
|
80
|
+
text(`Invoice: ${data.invoiceNumber}`);
|
|
81
|
+
text(`Date: ${data.invoiceDate}`);
|
|
82
|
+
if (data.dueDate)
|
|
83
|
+
text(`Due: ${data.dueDate}`);
|
|
84
|
+
y -= line;
|
|
85
|
+
text('Bill to', heading);
|
|
86
|
+
for (const value of [data.customerName, data.customerEmail, data.customerAddress])
|
|
87
|
+
if (value)
|
|
88
|
+
text(value);
|
|
89
|
+
y -= line;
|
|
90
|
+
const descriptionWidth = contentWidth * .45;
|
|
91
|
+
const qtyX = margin + contentWidth * .59, priceX = margin + contentWidth * .78, totalX = width - margin - 6;
|
|
92
|
+
function right(value, x, at) {
|
|
93
|
+
page.drawText(value, { x: x - font.widthOfTextAtSize(value, size), y: at, size, font, color: ink });
|
|
108
94
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
95
|
+
function tableHeader() {
|
|
96
|
+
ensure(line * 3);
|
|
97
|
+
page.drawRectangle({ x: margin, y: y - line - 10, width: contentWidth, height: line + 10, color: primary });
|
|
98
|
+
const headerColor = (() => { const c = brand.colors.primary; const brightness = .299 * parseInt(c.slice(1, 3), 16) + .587 * parseInt(c.slice(3, 5), 16) + .114 * parseInt(c.slice(5, 7), 16); return brightness > 155 ? rgb(0, 0, 0) : rgb(1, 1, 1); })();
|
|
99
|
+
for (const [label, x] of [['Description', margin + 6], ['Qty', qtyX - 20], ['Price', priceX - 30], ['Total', totalX - 30]])
|
|
100
|
+
page.drawText(label, { x, y: y - size - 5, size, font, color: headerColor });
|
|
101
|
+
y -= line + 16;
|
|
112
102
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
103
|
+
const money = (amount) => new Intl.NumberFormat('en', { style: 'currency', currency: data.currency }).format(amount);
|
|
104
|
+
tableHeader();
|
|
105
|
+
for (const [index, item] of data.items.entries()) {
|
|
106
|
+
const lines = wrap(item.description, descriptionWidth - 12);
|
|
107
|
+
const rowHeight = lines.length * line + 6;
|
|
108
|
+
if (rowHeight < height - margin - bottom - line - 16 && y - rowHeight < bottom) {
|
|
109
|
+
newPage();
|
|
110
|
+
tableHeader();
|
|
111
|
+
}
|
|
112
|
+
for (let i = 0; i < lines.length; i++) {
|
|
113
|
+
if (y - line - 6 < bottom) {
|
|
114
|
+
newPage();
|
|
115
|
+
tableHeader();
|
|
116
|
+
}
|
|
117
|
+
if (design.tableStyle === 'striped' && index % 2 === 0)
|
|
118
|
+
page.drawRectangle({ x: margin, y: y - line, width: contentWidth, height: line, color: primary, opacity: .06 });
|
|
119
|
+
page.drawText(lines[i], { x: margin + 6, y: y - size, size, font, color: ink });
|
|
120
|
+
if (i === 0) {
|
|
121
|
+
right(String(item.quantity), qtyX, y - size);
|
|
122
|
+
right(money(item.unitPrice), priceX, y - size);
|
|
123
|
+
right(money(item.total), totalX, y - size);
|
|
124
|
+
}
|
|
125
|
+
y -= line;
|
|
126
|
+
}
|
|
127
|
+
y -= 6;
|
|
131
128
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
page.drawText('Qty', { x: colQty, y: yPos - 17, size: 10, font: boldFont, color: rgb(1, 1, 1) });
|
|
142
|
-
page.drawText('Price', { x: colPrice, y: yPos - 17, size: 10, font: boldFont, color: rgb(1, 1, 1) });
|
|
143
|
-
page.drawText('Total', { x: colTotal - font.widthOfTextAtSize('Total', 10), y: yPos - 17, size: 10, font: boldFont, color: rgb(1, 1, 1) });
|
|
144
|
-
yPos -= tableHeaderHeight + 15;
|
|
145
|
-
// Table rows
|
|
146
|
-
for (const item of data.items) {
|
|
147
|
-
page.drawText(item.description, { x: colDescription + 10, y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
148
|
-
page.drawText(item.quantity.toString(), { x: colQty, y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
149
|
-
const priceStr = formatCurrency(item.unitPrice, mergedConfig.currencySymbol, mergedConfig.currencyPosition);
|
|
150
|
-
page.drawText(priceStr, { x: colPrice, y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
151
|
-
const totalStr = formatCurrency(item.total, mergedConfig.currencySymbol, mergedConfig.currencyPosition);
|
|
152
|
-
page.drawText(totalStr, { x: colTotal - font.widthOfTextAtSize(totalStr, 10), y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
153
|
-
yPos -= 20;
|
|
129
|
+
ensure(line * 5 + 16);
|
|
130
|
+
y -= 12;
|
|
131
|
+
page.drawLine({ start: { x: margin, y: y }, end: { x: width - margin, y: y }, color: muted, thickness: .5 });
|
|
132
|
+
y -= line;
|
|
133
|
+
// Display recorded monetary values, never recompute them using design/settings.
|
|
134
|
+
for (const [label, amount] of [['Subtotal', data.subtotal], ['Tax', data.tax], ['Total', data.total]]) {
|
|
135
|
+
if (amount === undefined)
|
|
136
|
+
continue;
|
|
137
|
+
text(`${label}: ${money(amount)}`);
|
|
154
138
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
if (
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const taxLabel = `${mergedConfig.taxLabel} (${mergedConfig.taxRate}%):`;
|
|
167
|
-
const taxValue = formatCurrency(data.tax, mergedConfig.currencySymbol, mergedConfig.currencyPosition);
|
|
168
|
-
page.drawText(taxLabel, { x: colPrice - font.widthOfTextAtSize(taxLabel, 10), y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
169
|
-
page.drawText(taxValue, { x: colTotal - font.widthOfTextAtSize(taxValue, 10), y: yPos, size: 10, font, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
170
|
-
yPos -= 15;
|
|
171
|
-
}
|
|
139
|
+
if (data.paymentMethod) {
|
|
140
|
+
y -= line;
|
|
141
|
+
text(`Payment method: ${data.paymentMethod}`);
|
|
142
|
+
}
|
|
143
|
+
if (data.notes) {
|
|
144
|
+
y -= line;
|
|
145
|
+
text(data.notes);
|
|
146
|
+
}
|
|
147
|
+
for (const [index, p] of pdf.getPages().entries()) {
|
|
148
|
+
footerLines.forEach((row, i) => p.drawText(row, { x: margin, y: margin + (footerLines.length - i) * 11, size: 8, font, color: muted }));
|
|
149
|
+
p.drawText(`${index + 1} / ${pdf.getPageCount()}`, { x: width - margin - 35, y: margin - 10, size: 8, font, color: muted });
|
|
172
150
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
page.drawText(totalLabel, { x: colPrice - boldFont.widthOfTextAtSize(totalLabel, 12), y: yPos, size: 12, font: boldFont, color: rgb(primaryColor.r, primaryColor.g, primaryColor.b) });
|
|
176
|
-
page.drawText(totalValue, { x: colTotal - boldFont.widthOfTextAtSize(totalValue, 12), y: yPos, size: 12, font: boldFont, color: rgb(accentColor.r, accentColor.g, accentColor.b) });
|
|
177
|
-
// Footer
|
|
178
|
-
const footerText = mergedConfig.footerText || 'Thank you for your business!';
|
|
179
|
-
page.drawText(footerText, { x: (width - font.widthOfTextAtSize(footerText, 10)) / 2, y: margin, size: 10, font, color: rgb(0.5, 0.5, 0.5) });
|
|
180
|
-
return await pdfDoc.save();
|
|
151
|
+
pdf.setTitle(`Invoice ${data.invoiceNumber}`);
|
|
152
|
+
return pdf.save();
|
|
181
153
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/public.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/public.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAS/B,gCAAgC;AAChC,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqD7D;AAsBD,6BAA6B;AAC7B,wBAAsB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA0C3D;AAED,kCAAkC;AAClC,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoC/D;AAED,yDAAyD;AACzD,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA2DvE"}
|
|
@@ -4,11 +4,16 @@
|
|
|
4
4
|
import { getProjectDb, createId } from '../../../lib/project-db';
|
|
5
5
|
import { sendEmail } from '../../../lib/email';
|
|
6
6
|
import { renderEmailTemplate } from '../../../lib/email-template';
|
|
7
|
-
import { readEmailTemplateData } from './settings.handler';
|
|
7
|
+
import { readEmailSettings, readEmailTemplateData } from './settings.handler';
|
|
8
|
+
import { DEFAULT_SUBSCRIPTION_TEMPLATES } from '@hintergrund/runtime-contracts';
|
|
8
9
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
9
10
|
/** POST /api/email/subscribe */
|
|
10
11
|
export async function subscribe(c) {
|
|
11
12
|
try {
|
|
13
|
+
const { settings } = await readEmailSettings(c.env);
|
|
14
|
+
if (settings.automation?.newsletterEnabled === false) {
|
|
15
|
+
return c.json({ success: false, message: 'Newsletter signup is disabled.' }, 403);
|
|
16
|
+
}
|
|
12
17
|
const body = await c.req.json();
|
|
13
18
|
if (!body.email)
|
|
14
19
|
return c.json({ success: false, message: 'Email is required' }, 400);
|
|
@@ -56,20 +61,17 @@ async function sendConfirmation(c, email, token) {
|
|
|
56
61
|
try {
|
|
57
62
|
const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
|
|
58
63
|
const automation = settings.automation;
|
|
59
|
-
const bodyHtml = (automation?.confirmation?.bodyHtml ||
|
|
60
|
-
<h2>Confirm your subscription</h2>
|
|
61
|
-
<p>Click the button below to confirm your subscription.</p>
|
|
62
|
-
<p><a href="{{confirm_url}}" style="display:inline-block;background:${settings.emailTemplate?.primaryColor ?? '#111827'};color:white;padding:12px 24px;border-radius:4px;text-decoration:none;">Confirm subscription</a></p>
|
|
63
|
-
<p style="font-size:12px;color:#888;">If you didn't subscribe, you can safely ignore this email.</p>`).replaceAll('{{confirm_url}}', confirmUrl);
|
|
64
|
+
const bodyHtml = (automation?.confirmation?.bodyHtml || DEFAULT_SUBSCRIPTION_TEMPLATES.confirmation.bodyHtml).replaceAll('{{confirm_url}}', confirmUrl);
|
|
64
65
|
const html = renderEmailTemplate({
|
|
65
66
|
bodyHtml,
|
|
66
67
|
template: settings.emailTemplate,
|
|
67
68
|
logoDataUrl,
|
|
68
69
|
});
|
|
69
|
-
await sendEmail(c.env, { to: email, subject: automation?.confirmation?.subject ||
|
|
70
|
+
await sendEmail(c.env, { to: email, subject: automation?.confirmation?.subject || DEFAULT_SUBSCRIPTION_TEMPLATES.confirmation.subject, html });
|
|
70
71
|
}
|
|
71
72
|
catch (err) {
|
|
72
73
|
console.error('Failed to send confirmation email:', err);
|
|
74
|
+
throw err;
|
|
73
75
|
}
|
|
74
76
|
}
|
|
75
77
|
/** GET /api/email/confirm */
|
|
@@ -87,7 +89,24 @@ export async function confirm(c) {
|
|
|
87
89
|
if (!subscriber) {
|
|
88
90
|
return c.json({ success: false, message: 'Invalid or expired confirmation token' }, 400);
|
|
89
91
|
}
|
|
90
|
-
|
|
92
|
+
const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
|
|
93
|
+
const result = await db.prepare(`UPDATE subscribers SET status = 'subscribed', confirmed_at = ?, subscribed_at = ?, confirmation_token = NULL, updated_at = ? WHERE id = ? AND status = 'pending' AND confirmation_token = ?`).bind(now, now, now, subscriber.id, token).run();
|
|
94
|
+
// Only the request that consumes the token sends a welcome. Confirmation stays
|
|
95
|
+
// successful if the provider fails; never undo consent or send it twice on refresh.
|
|
96
|
+
if (result.meta.changes > 0 && settings.automation?.newsletterEnabled !== false) {
|
|
97
|
+
const welcome = settings.automation?.welcome ?? DEFAULT_SUBSCRIPTION_TEMPLATES.welcome;
|
|
98
|
+
try {
|
|
99
|
+
await sendEmail(c.env, {
|
|
100
|
+
to: subscriber.email,
|
|
101
|
+
subject: welcome.subject,
|
|
102
|
+
html: renderEmailTemplate({ bodyHtml: welcome.bodyHtml, template: settings.emailTemplate, logoDataUrl,
|
|
103
|
+
unsubscribeUrl: `${new URL(c.req.url).origin}/api/email/unsubscribe?email=${encodeURIComponent(subscriber.email)}` }),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
console.error('Failed to send welcome email:', error);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
91
110
|
return c.json({ success: true, message: 'Your subscription has been confirmed!' });
|
|
92
111
|
}
|
|
93
112
|
catch (error) {
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Send Handler — transactional + bulk email,
|
|
2
|
+
* Send Handler — transactional + bulk email, no Plunk
|
|
3
3
|
*/
|
|
4
4
|
import { Context } from 'hono';
|
|
5
|
-
/** GET /api/email/admin/sends */
|
|
6
|
-
export declare function getSends(c: Context): Promise<Response>;
|
|
7
5
|
/** POST /api/email/admin/send — transactional single email */
|
|
8
6
|
export declare function sendTransactional(c: Context): Promise<Response>;
|
|
9
7
|
/** POST /api/email/admin/send/bulk — send to all subscribed contacts */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/send.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/send.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAQ/B,8DAA8D;AAC9D,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsCrE;AAED,wEAAwE;AACxE,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiDjE"}
|
|
@@ -1,38 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Send Handler — transactional + bulk email,
|
|
2
|
+
* Send Handler — transactional + bulk email, no Plunk
|
|
3
3
|
*/
|
|
4
|
-
import { getProjectDb
|
|
4
|
+
import { getProjectDb } from '../../../lib/project-db';
|
|
5
5
|
import { sendEmail } from '../../../lib/email';
|
|
6
6
|
import { renderEmailTemplate } from '../../../lib/email-template';
|
|
7
7
|
import { readEmailTemplateData } from './settings.handler';
|
|
8
8
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
9
|
-
function rowToSend(row) {
|
|
10
|
-
return {
|
|
11
|
-
id: row.id,
|
|
12
|
-
type: row.type,
|
|
13
|
-
campaignId: row.campaign_id,
|
|
14
|
-
subject: row.subject,
|
|
15
|
-
recipientCount: row.recipient_count,
|
|
16
|
-
status: row.status,
|
|
17
|
-
error: row.error,
|
|
18
|
-
sentAt: row.sent_at,
|
|
19
|
-
createdAt: row.created_at,
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
/** GET /api/email/admin/sends */
|
|
23
|
-
export async function getSends(c) {
|
|
24
|
-
try {
|
|
25
|
-
const db = getProjectDb(c.env);
|
|
26
|
-
const { results } = await db
|
|
27
|
-
.prepare('SELECT * FROM email_sends ORDER BY created_at DESC LIMIT 100')
|
|
28
|
-
.all();
|
|
29
|
-
return c.json({ sends: (results ?? []).map(rowToSend) });
|
|
30
|
-
}
|
|
31
|
-
catch (error) {
|
|
32
|
-
console.error('Get sends error:', error);
|
|
33
|
-
return c.json({ success: false, message: 'Failed to fetch send history' }, 500);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
9
|
/** POST /api/email/admin/send — transactional single email */
|
|
37
10
|
export async function sendTransactional(c) {
|
|
38
11
|
try {
|
|
@@ -43,40 +16,24 @@ export async function sendTransactional(c) {
|
|
|
43
16
|
if (!EMAIL_REGEX.test(body.to)) {
|
|
44
17
|
return c.json({ success: false, message: 'Invalid email format' }, 400);
|
|
45
18
|
}
|
|
46
|
-
const db = getProjectDb(c.env);
|
|
47
19
|
const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
logoDataUrl,
|
|
61
|
-
}),
|
|
62
|
-
from: body.from,
|
|
63
|
-
replyTo: body.replyTo,
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
catch (err) {
|
|
67
|
-
status = 'failed';
|
|
68
|
-
error = err instanceof Error ? err.message : 'Unknown error';
|
|
69
|
-
}
|
|
70
|
-
await db.prepare(`INSERT INTO email_sends (id, type, subject, recipient_count, status, error, sent_at, created_at)
|
|
71
|
-
VALUES (?, 'transactional', ?, 1, ?, ?, ?, ?)`).bind(sendId, body.subject, status, error ?? null, status === 'sent' ? now : null, now).run();
|
|
72
|
-
if (status === 'failed') {
|
|
73
|
-
return c.json({ success: false, message: error ?? 'Failed to send email' }, 500);
|
|
74
|
-
}
|
|
20
|
+
await sendEmail(c.env, {
|
|
21
|
+
to: body.to,
|
|
22
|
+
toName: body.name,
|
|
23
|
+
subject: body.subject,
|
|
24
|
+
html: renderEmailTemplate({
|
|
25
|
+
bodyHtml: body.bodyHtml,
|
|
26
|
+
template: settings.emailTemplate,
|
|
27
|
+
logoDataUrl,
|
|
28
|
+
}),
|
|
29
|
+
from: body.from,
|
|
30
|
+
replyTo: body.replyTo,
|
|
31
|
+
});
|
|
75
32
|
return c.json({ success: true, message: `Email sent to ${body.to}` });
|
|
76
33
|
}
|
|
77
34
|
catch (error) {
|
|
78
35
|
console.error('Send transactional error:', error);
|
|
79
|
-
return c.json({ success: false, message: 'Failed to send email' }, 500);
|
|
36
|
+
return c.json({ success: false, message: error instanceof Error ? error.message : 'Failed to send email' }, 500);
|
|
80
37
|
}
|
|
81
38
|
}
|
|
82
39
|
/** POST /api/email/admin/send/bulk — send to all subscribed contacts */
|
|
@@ -88,16 +45,16 @@ export async function sendBulkEmail(c) {
|
|
|
88
45
|
}
|
|
89
46
|
const db = getProjectDb(c.env);
|
|
90
47
|
const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
|
|
48
|
+
if (settings.automation?.newsletterEnabled === false) {
|
|
49
|
+
return c.json({ success: false, message: 'Newsletters are disabled.' }, 403);
|
|
50
|
+
}
|
|
91
51
|
const { results: subscribers } = await db
|
|
92
52
|
.prepare("SELECT email, name FROM subscribers WHERE status = 'subscribed'")
|
|
93
53
|
.all();
|
|
94
54
|
if (!subscribers || subscribers.length === 0) {
|
|
95
55
|
return c.json({ success: false, message: 'No subscribed contacts found' }, 400);
|
|
96
56
|
}
|
|
97
|
-
const now = Date.now();
|
|
98
|
-
const sendId = createId('snd');
|
|
99
57
|
let sentCount = 0;
|
|
100
|
-
let lastError;
|
|
101
58
|
const origin = new URL(c.req.url).origin;
|
|
102
59
|
for (const subscriber of subscribers) {
|
|
103
60
|
const unsubscribeUrl = `${origin}/api/email/unsubscribe?email=${encodeURIComponent(subscriber.email)}`;
|
|
@@ -117,12 +74,8 @@ export async function sendBulkEmail(c) {
|
|
|
117
74
|
}
|
|
118
75
|
catch (err) {
|
|
119
76
|
console.error(`Failed to send to ${subscriber.email}:`, err);
|
|
120
|
-
lastError = err instanceof Error ? err.message : 'Unknown error';
|
|
121
77
|
}
|
|
122
78
|
}
|
|
123
|
-
const status = sentCount > 0 ? 'sent' : 'failed';
|
|
124
|
-
await db.prepare(`INSERT INTO email_sends (id, type, subject, recipient_count, status, error, sent_at, created_at)
|
|
125
|
-
VALUES (?, 'transactional', ?, ?, ?, ?, ?, ?)`).bind(sendId, body.subject, sentCount, status, lastError ?? null, status === 'sent' ? now : null, now).run();
|
|
126
79
|
return c.json({ success: true, sent: sentCount, total: subscribers.length });
|
|
127
80
|
}
|
|
128
81
|
catch (error) {
|
|
@@ -1,30 +1,78 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Settings Handler — GitHub-backed email template + invoice config.
|
|
3
|
-
*/
|
|
4
1
|
import type { Context } from 'hono';
|
|
5
2
|
import type { Bindings } from '../../../index';
|
|
6
3
|
import { type GitHubClient } from '../../../lib/github';
|
|
7
|
-
import type
|
|
8
|
-
|
|
9
|
-
export declare const EMAIL_SETTINGS_PATH = "frontend/src/lib/emails/settings.json";
|
|
4
|
+
import { EMAIL_SETTINGS_PATH, type EmailSettings, type InvoiceConfig } from '@hintergrund/runtime-contracts';
|
|
5
|
+
export { EMAIL_SETTINGS_PATH };
|
|
10
6
|
export declare const DEFAULT_INVOICE: InvoiceConfig;
|
|
11
7
|
export declare const DEFAULT_EMAIL_SETTINGS: EmailSettings;
|
|
12
8
|
export declare function resolveLogoDataUrl(github: GitHubClient, logoPath: string | undefined): Promise<string | undefined>;
|
|
13
9
|
export declare function readEmailSettings(env: Bindings): Promise<{
|
|
14
|
-
settings:
|
|
10
|
+
settings: {
|
|
11
|
+
invoice: {
|
|
12
|
+
companyName: string;
|
|
13
|
+
companyAddress: string;
|
|
14
|
+
companyEmail: string;
|
|
15
|
+
companyPhone: string;
|
|
16
|
+
dueDays: number;
|
|
17
|
+
};
|
|
18
|
+
logoPath: string | undefined;
|
|
19
|
+
emailTemplate: import("@hintergrund/runtime-contracts").EmailTemplateConfig;
|
|
20
|
+
emailBrand?: import("@hintergrund/runtime-contracts").Brand;
|
|
21
|
+
automation?: {
|
|
22
|
+
newsletterEnabled?: boolean;
|
|
23
|
+
doubleOptIn?: boolean;
|
|
24
|
+
confirmation?: {
|
|
25
|
+
subject: string;
|
|
26
|
+
bodyHtml: string;
|
|
27
|
+
};
|
|
28
|
+
welcome?: {
|
|
29
|
+
subject: string;
|
|
30
|
+
bodyHtml: string;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
footerHtml?: string;
|
|
34
|
+
fromEmail?: string;
|
|
35
|
+
fromName?: string;
|
|
36
|
+
replyTo?: string;
|
|
37
|
+
updatedAt: number;
|
|
38
|
+
};
|
|
15
39
|
commitSha: string;
|
|
16
40
|
}>;
|
|
17
41
|
export declare function readEmailTemplateData(env: Bindings): Promise<{
|
|
18
|
-
settings:
|
|
19
|
-
|
|
42
|
+
settings: {
|
|
43
|
+
invoice: {
|
|
44
|
+
companyName: string;
|
|
45
|
+
companyAddress: string;
|
|
46
|
+
companyEmail: string;
|
|
47
|
+
companyPhone: string;
|
|
48
|
+
dueDays: number;
|
|
49
|
+
};
|
|
50
|
+
logoPath: string | undefined;
|
|
51
|
+
emailTemplate: import("@hintergrund/runtime-contracts").EmailTemplateConfig;
|
|
52
|
+
emailBrand?: import("@hintergrund/runtime-contracts").Brand;
|
|
53
|
+
automation?: {
|
|
54
|
+
newsletterEnabled?: boolean;
|
|
55
|
+
doubleOptIn?: boolean;
|
|
56
|
+
confirmation?: {
|
|
57
|
+
subject: string;
|
|
58
|
+
bodyHtml: string;
|
|
59
|
+
};
|
|
60
|
+
welcome?: {
|
|
61
|
+
subject: string;
|
|
62
|
+
bodyHtml: string;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
footerHtml?: string;
|
|
66
|
+
fromEmail?: string;
|
|
67
|
+
fromName?: string;
|
|
68
|
+
replyTo?: string;
|
|
69
|
+
updatedAt: number;
|
|
20
70
|
};
|
|
21
|
-
logoDataUrl
|
|
71
|
+
logoDataUrl: string | undefined;
|
|
22
72
|
}>;
|
|
23
|
-
/** GET /api/email/admin/settings */
|
|
24
73
|
export declare function getSettings(c: Context<{
|
|
25
74
|
Bindings: Bindings;
|
|
26
75
|
}>): Promise<Response>;
|
|
27
|
-
/** PUT /api/email/admin/settings */
|
|
28
76
|
export declare function saveSettings(c: Context<{
|
|
29
77
|
Bindings: Bindings;
|
|
30
78
|
}>): Promise<Response>;
|