@hintergrund/worker 0.1.1 → 0.1.3

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 (94) hide show
  1. package/dist/api/cms/handlers/assets.handler.d.ts +24 -1
  2. package/dist/api/cms/handlers/assets.handler.d.ts.map +1 -1
  3. package/dist/api/cms/handlers/assets.handler.js +111 -210
  4. package/dist/api/cms/handlers/config.handler.d.ts +4 -0
  5. package/dist/api/cms/handlers/config.handler.d.ts.map +1 -1
  6. package/dist/api/cms/handlers/config.handler.js +20 -71
  7. package/dist/api/cms/handlers/content.handler.d.ts +12 -1
  8. package/dist/api/cms/handlers/content.handler.d.ts.map +1 -1
  9. package/dist/api/cms/handlers/content.handler.js +57 -233
  10. package/dist/api/cms/handlers/dashboard.handler.js +1 -1
  11. package/dist/api/emails/handlers/branding.handler.d.ts +17 -0
  12. package/dist/api/emails/handlers/branding.handler.d.ts.map +1 -0
  13. package/dist/api/emails/handlers/branding.handler.js +120 -0
  14. package/dist/api/emails/handlers/campaigns.handler.d.ts +32 -0
  15. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -0
  16. package/dist/api/emails/handlers/campaigns.handler.js +139 -0
  17. package/dist/api/emails/handlers/contacts.handler.d.ts +37 -0
  18. package/dist/api/emails/handlers/contacts.handler.d.ts.map +1 -0
  19. package/dist/api/emails/handlers/contacts.handler.js +161 -0
  20. package/dist/api/emails/handlers/invoice.handler.d.ts +30 -0
  21. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -0
  22. package/dist/api/emails/handlers/invoice.handler.js +463 -0
  23. package/dist/api/emails/handlers/public.handler.d.ts +36 -0
  24. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -0
  25. package/dist/api/emails/handlers/public.handler.js +350 -0
  26. package/dist/api/emails/handlers/send.handler.d.ts +23 -0
  27. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -0
  28. package/dist/api/emails/handlers/send.handler.js +117 -0
  29. package/dist/api/emails/handlers/settings.handler.d.ts +36 -0
  30. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -0
  31. package/dist/api/emails/handlers/settings.handler.js +312 -0
  32. package/dist/api/emails/handlers/templates.handler.d.ts +32 -0
  33. package/dist/api/emails/handlers/templates.handler.d.ts.map +1 -0
  34. package/dist/api/emails/handlers/templates.handler.js +132 -0
  35. package/dist/api/emails/routes/admin.routes.d.ts +9 -0
  36. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -0
  37. package/dist/api/emails/routes/admin.routes.js +77 -0
  38. package/dist/api/emails/routes/index.d.ts +9 -0
  39. package/dist/api/emails/routes/index.d.ts.map +1 -0
  40. package/dist/api/emails/routes/index.js +14 -0
  41. package/dist/api/emails/routes/public.routes.d.ts +9 -0
  42. package/dist/api/emails/routes/public.routes.d.ts.map +1 -0
  43. package/dist/api/emails/routes/public.routes.js +15 -0
  44. package/dist/api/newsletter/handlers/emails.handler.d.ts +13 -3
  45. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +1 -1
  46. package/dist/api/newsletter/handlers/emails.handler.js +140 -12
  47. package/dist/api/newsletter/handlers/invoice.handler.d.ts +22 -0
  48. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +1 -0
  49. package/dist/api/newsletter/handlers/invoice.handler.js +455 -0
  50. package/dist/api/newsletter/handlers/public.handler.d.ts +4 -4
  51. package/dist/api/newsletter/handlers/public.handler.d.ts.map +1 -1
  52. package/dist/api/newsletter/handlers/public.handler.js +78 -20
  53. package/dist/api/newsletter/handlers/send.handler.d.ts +2 -2
  54. package/dist/api/newsletter/handlers/send.handler.js +3 -3
  55. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +4 -4
  56. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +1 -1
  57. package/dist/api/newsletter/handlers/subscribers.handler.js +8 -4
  58. package/dist/api/newsletter/routes/admin.routes.d.ts.map +1 -1
  59. package/dist/api/newsletter/routes/admin.routes.js +8 -1
  60. package/dist/api/shop/handlers/assets.handler.d.ts +3 -0
  61. package/dist/api/shop/handlers/assets.handler.d.ts.map +1 -0
  62. package/dist/api/shop/handlers/assets.handler.js +62 -0
  63. package/dist/api/shop/handlers/checkout.handler.d.ts +10 -0
  64. package/dist/api/shop/handlers/checkout.handler.d.ts.map +1 -0
  65. package/dist/api/shop/handlers/checkout.handler.js +50 -0
  66. package/dist/api/shop/handlers/products.handler.d.ts +0 -7
  67. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  68. package/dist/api/shop/handlers/products.handler.js +0 -23
  69. package/dist/api/shop/handlers/public.handler.d.ts +17 -0
  70. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -0
  71. package/dist/api/shop/handlers/public.handler.js +108 -0
  72. package/dist/api/shop/handlers/webhook.handler.d.ts +10 -0
  73. package/dist/api/shop/handlers/webhook.handler.d.ts.map +1 -0
  74. package/dist/api/shop/handlers/webhook.handler.js +233 -0
  75. package/dist/api/shop/routes.d.ts.map +1 -1
  76. package/dist/api/shop/routes.js +9 -12
  77. package/dist/hintergrund-assets.d.ts +2 -2
  78. package/dist/hintergrund-assets.d.ts.map +1 -1
  79. package/dist/hintergrund-assets.js +2 -2
  80. package/dist/index.d.ts +9 -17
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +4 -7
  83. package/dist/lib/config.d.ts +13 -7
  84. package/dist/lib/config.d.ts.map +1 -1
  85. package/dist/lib/config.js +39 -44
  86. package/dist/lib/github.d.ts +124 -0
  87. package/dist/lib/github.d.ts.map +1 -0
  88. package/dist/lib/github.js +286 -0
  89. package/dist/lib/plunk.d.ts +207 -0
  90. package/dist/lib/plunk.d.ts.map +1 -0
  91. package/dist/lib/plunk.js +262 -0
  92. package/dist/middleware/auth.d.ts.map +1 -1
  93. package/dist/middleware/auth.js +2 -5
  94. package/package.json +32 -31
@@ -9,7 +9,7 @@ function parseEmailRecord(row) {
9
9
  subject: row.subject,
10
10
  htmlContent: row.html_content,
11
11
  status: row.status,
12
- config: row.config ? JSON.parse(row.config) : undefined,
12
+ emailType: row.email_type || undefined,
13
13
  recipientCount: row.recipient_count || undefined,
14
14
  sentAt: row.sent_at || undefined,
15
15
  scheduledFor: row.scheduled_for || undefined,
@@ -18,7 +18,7 @@ function parseEmailRecord(row) {
18
18
  };
19
19
  }
20
20
  /**
21
- * GET /api/newsletter/admin/emails
21
+ * GET /api/email/admin/emails
22
22
  * Get all emails (sent emails and drafts)
23
23
  */
24
24
  export async function getEmails(c) {
@@ -37,26 +37,58 @@ export async function getEmails(c) {
37
37
  }
38
38
  }
39
39
  /**
40
- * POST /api/newsletter/admin/emails/draft
40
+ * POST /api/email/admin/emails/draft
41
41
  * Save email as draft
42
42
  */
43
43
  export async function saveDraft(c) {
44
44
  try {
45
45
  const body = (await c.req.json());
46
- const { subject, htmlContent, id, config } = body;
46
+ const { subject, htmlContent, id, emailType } = body;
47
47
  if (!subject || !htmlContent) {
48
48
  return c.json({ success: false, message: 'Subject and content are required' }, 400);
49
49
  }
50
50
  const db = c.env.DB;
51
51
  const now = Date.now();
52
+ // Handle auto emails (upsert by type)
53
+ if (emailType) {
54
+ const existing = await db
55
+ .prepare('SELECT id FROM emails WHERE email_type = ?')
56
+ .bind(emailType)
57
+ .first();
58
+ if (existing) {
59
+ // Update existing auto email
60
+ await db
61
+ .prepare(`UPDATE emails
62
+ SET subject = ?, html_content = ?, updated_at = ?
63
+ WHERE id = ?`)
64
+ .bind(subject, htmlContent, now, existing.id)
65
+ .run();
66
+ const row = await db.prepare('SELECT * FROM emails WHERE id = ?').bind(existing.id).first();
67
+ const email = parseEmailRecord(row);
68
+ return c.json({ success: true, email });
69
+ }
70
+ else {
71
+ // Create new auto email
72
+ const newId = generateId();
73
+ await db
74
+ .prepare(`INSERT INTO emails
75
+ (id, subject, html_content, status, email_type, created_at, updated_at)
76
+ VALUES (?, ?, ?, 'auto', ?, ?, ?)`)
77
+ .bind(newId, subject, htmlContent, emailType, now, now)
78
+ .run();
79
+ const row = await db.prepare('SELECT * FROM emails WHERE id = ?').bind(newId).first();
80
+ const email = parseEmailRecord(row);
81
+ return c.json({ success: true, email });
82
+ }
83
+ }
84
+ // Handle regular drafts
52
85
  if (id) {
53
86
  // Update existing draft
54
- const configJson = config ? JSON.stringify(config) : null;
55
87
  await db
56
88
  .prepare(`UPDATE emails
57
- SET subject = ?, html_content = ?, config = ?, updated_at = ?
89
+ SET subject = ?, html_content = ?, updated_at = ?
58
90
  WHERE id = ? AND status = 'draft'`)
59
- .bind(subject, htmlContent, configJson, now, id)
91
+ .bind(subject, htmlContent, now, id)
60
92
  .run();
61
93
  const row = await db.prepare('SELECT * FROM emails WHERE id = ?').bind(id).first();
62
94
  if (!row) {
@@ -68,12 +100,11 @@ export async function saveDraft(c) {
68
100
  else {
69
101
  // Create new draft
70
102
  const newId = generateId();
71
- const configJson = config ? JSON.stringify(config) : null;
72
103
  await db
73
104
  .prepare(`INSERT INTO emails
74
- (id, subject, html_content, config, status, created_at, updated_at)
75
- VALUES (?, ?, ?, ?, 'draft', ?, ?)`)
76
- .bind(newId, subject, htmlContent, configJson, now, now)
105
+ (id, subject, html_content, status, created_at, updated_at)
106
+ VALUES (?, ?, ?, 'draft', ?, ?)`)
107
+ .bind(newId, subject, htmlContent, now, now)
77
108
  .run();
78
109
  const row = await db.prepare('SELECT * FROM emails WHERE id = ?').bind(newId).first();
79
110
  if (!row) {
@@ -92,7 +123,7 @@ export async function saveDraft(c) {
92
123
  }
93
124
  }
94
125
  /**
95
- * DELETE /api/newsletter/admin/emails/:id
126
+ * DELETE /api/email/admin/emails/:id
96
127
  * Delete email (draft or sent)
97
128
  */
98
129
  export async function deleteEmail(c) {
@@ -132,3 +163,100 @@ export async function saveSentEmail(db, subject, htmlContent, recipientCount) {
132
163
  .bind(emailId, subject, htmlContent, recipientCount, now, now, now)
133
164
  .run();
134
165
  }
166
+ function parseTemplateRecord(row) {
167
+ return {
168
+ id: row.id,
169
+ config: row.config ? JSON.parse(row.config) : null,
170
+ logo: row.logo || null,
171
+ createdAt: row.created_at,
172
+ updatedAt: row.updated_at,
173
+ };
174
+ }
175
+ /**
176
+ * GET /api/email/admin/template
177
+ * Get the global email template settings
178
+ */
179
+ export async function getTemplate(c) {
180
+ try {
181
+ const db = c.env.DB;
182
+ const row = await db.prepare("SELECT * FROM templates WHERE type = 'email'").first();
183
+ if (!row) {
184
+ // Return default template if none exists
185
+ return c.json({
186
+ template: {
187
+ id: 'email',
188
+ config: {
189
+ backgroundColor: '#f6f6f6',
190
+ contentBackgroundColor: '#ffffff',
191
+ borderColor: '#ffffff',
192
+ borderWidth: '0px',
193
+ borderRadius: '3px',
194
+ maxWidth: '580px',
195
+ h1Color: '#000000',
196
+ h2Color: '#000000',
197
+ h3Color: '#000000',
198
+ h4Color: '#000000',
199
+ pColor: '#1f2328',
200
+ linkColor: '#3498db',
201
+ },
202
+ logo: null,
203
+ createdAt: null,
204
+ updatedAt: null,
205
+ },
206
+ });
207
+ }
208
+ const template = parseTemplateRecord(row);
209
+ return c.json({ template });
210
+ }
211
+ catch (error) {
212
+ console.error('Get template error:', error);
213
+ return c.json({
214
+ success: false,
215
+ message: error instanceof Error ? error.message : 'Failed to fetch template',
216
+ }, 500);
217
+ }
218
+ }
219
+ /**
220
+ * PUT /api/email/admin/template
221
+ * Save/update the global email template settings
222
+ */
223
+ export async function saveTemplate(c) {
224
+ try {
225
+ const body = (await c.req.json());
226
+ const { config, logo } = body;
227
+ if (!config) {
228
+ return c.json({ success: false, message: 'Config is required' }, 400);
229
+ }
230
+ const db = c.env.DB;
231
+ const now = Date.now();
232
+ const configJson = JSON.stringify(config);
233
+ // Upsert: check if email template exists
234
+ const existing = await db.prepare("SELECT id FROM templates WHERE type = 'email'").first();
235
+ if (existing) {
236
+ await db
237
+ .prepare(`UPDATE templates
238
+ SET config = ?, logo = ?, updated_at = ?
239
+ WHERE type = 'email'`)
240
+ .bind(configJson, logo ?? null, now)
241
+ .run();
242
+ }
243
+ else {
244
+ await db
245
+ .prepare(`INSERT INTO templates
246
+ (id, type, config, logo, created_at, updated_at)
247
+ VALUES ('email', 'email', ?, ?, ?, ?)`)
248
+ .bind(configJson, logo ?? null, now, now)
249
+ .run();
250
+ }
251
+ const row = await db.prepare("SELECT * FROM templates WHERE type = 'email'").first();
252
+ const template = parseTemplateRecord(row);
253
+ return c.json({ success: true, template });
254
+ }
255
+ catch (error) {
256
+ console.error('Save template error:', error);
257
+ return c.json({
258
+ success: false,
259
+ message: error instanceof Error ? error.message : 'Failed to save template',
260
+ }, 500);
261
+ }
262
+ }
@@ -0,0 +1,22 @@
1
+ import type { Context } from 'hono';
2
+ import type { Bindings } from '../../../index';
3
+ import type { InvoiceTemplate, InvoiceData } from '@hintergrund/shared';
4
+ /**
5
+ * GET /api/email/admin/invoice-template
6
+ * Fetch the invoice template configuration
7
+ */
8
+ export declare function getInvoiceTemplate(c: Context<{
9
+ Bindings: Bindings;
10
+ }>): Promise<Response>;
11
+ /**
12
+ * POST /api/email/admin/invoice-template
13
+ * Save the invoice template configuration
14
+ */
15
+ export declare function saveInvoiceTemplate(c: Context<{
16
+ Bindings: Bindings;
17
+ }>): Promise<Response>;
18
+ /**
19
+ * Generate PDF invoice
20
+ */
21
+ export declare function generateInvoicePdf(template: InvoiceTemplate, data: InvoiceData): Promise<Uint8Array>;
22
+ //# sourceMappingURL=invoice.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoice.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/newsletter/handlers/invoice.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,KAAK,EAAiB,eAAe,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAuBvF;;;GAGG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmC9F;AAED;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwD/F;AAwBD;;GAEG;AACH,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,eAAe,EACzB,IAAI,EAAE,WAAW,GACf,OAAO,CAAC,UAAU,CAAC,CA6WrB"}
@@ -0,0 +1,455 @@
1
+ import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
2
+ // Default invoice configuration
3
+ const DEFAULT_INVOICE_CONFIG = {
4
+ primaryColor: '#1f2937',
5
+ accentColor: '#3b82f6',
6
+ fontFamily: 'helvetica',
7
+ logoPosition: 'left',
8
+ showLogo: true,
9
+ companyName: 'Your Company',
10
+ companyAddress: '123 Main Street, City, Country',
11
+ companyEmail: 'contact@company.com',
12
+ companyPhone: '+1 234 567 890',
13
+ footerText: 'Thank you for your business!',
14
+ currencySymbol: '€',
15
+ currencyPosition: 'before',
16
+ showTaxBreakdown: true,
17
+ taxLabel: 'VAT',
18
+ taxRate: 19,
19
+ dueDays: 14
20
+ };
21
+ /**
22
+ * GET /api/email/admin/invoice-template
23
+ * Fetch the invoice template configuration
24
+ */
25
+ export async function getInvoiceTemplate(c) {
26
+ try {
27
+ const db = c.env.DB;
28
+ if (!db) {
29
+ return c.json({ success: false, error: 'Database not configured' }, 500);
30
+ }
31
+ const result = await db
32
+ .prepare("SELECT * FROM templates WHERE type = 'invoice'")
33
+ .first();
34
+ if (!result) {
35
+ // Return default template if none exists
36
+ const template = {
37
+ id: 'invoice',
38
+ config: DEFAULT_INVOICE_CONFIG,
39
+ createdAt: Date.now(),
40
+ updatedAt: Date.now()
41
+ };
42
+ return c.json({ success: true, template });
43
+ }
44
+ const template = {
45
+ id: result.id,
46
+ config: JSON.parse(result.config),
47
+ logo: result.logo,
48
+ createdAt: result.created_at,
49
+ updatedAt: result.updated_at
50
+ };
51
+ return c.json({ success: true, template });
52
+ }
53
+ catch (error) {
54
+ console.error('Failed to fetch invoice template:', error);
55
+ return c.json({ success: false, error: 'Failed to fetch invoice template' }, 500);
56
+ }
57
+ }
58
+ /**
59
+ * POST /api/email/admin/invoice-template
60
+ * Save the invoice template configuration
61
+ */
62
+ export async function saveInvoiceTemplate(c) {
63
+ try {
64
+ const db = c.env.DB;
65
+ if (!db) {
66
+ return c.json({ success: false, error: 'Database not configured' }, 500);
67
+ }
68
+ const body = await c.req.json();
69
+ const { config, logo } = body;
70
+ if (!config) {
71
+ return c.json({ success: false, error: 'Config is required' }, 400);
72
+ }
73
+ const now = Date.now();
74
+ const configJson = JSON.stringify(config);
75
+ // Check if template exists
76
+ const existing = await db
77
+ .prepare("SELECT id FROM templates WHERE type = 'invoice'")
78
+ .first();
79
+ if (existing) {
80
+ // Update existing template
81
+ await db
82
+ .prepare(`UPDATE templates
83
+ SET config = ?, logo = ?, updated_at = ?
84
+ WHERE type = 'invoice'`)
85
+ .bind(configJson, logo || null, now)
86
+ .run();
87
+ }
88
+ else {
89
+ // Insert new template
90
+ await db
91
+ .prepare(`INSERT INTO templates (id, type, config, logo, created_at, updated_at)
92
+ VALUES ('invoice', 'invoice', ?, ?, ?, ?)`)
93
+ .bind(configJson, logo || null, now, now)
94
+ .run();
95
+ }
96
+ const template = {
97
+ id: 'invoice',
98
+ config,
99
+ logo,
100
+ createdAt: existing ? existing.created_at : now,
101
+ updatedAt: now
102
+ };
103
+ return c.json({ success: true, template });
104
+ }
105
+ catch (error) {
106
+ console.error('Failed to save invoice template:', error);
107
+ return c.json({ success: false, error: 'Failed to save invoice template' }, 500);
108
+ }
109
+ }
110
+ /**
111
+ * Helper to parse hex color to RGB values
112
+ */
113
+ function hexToRgb(hex) {
114
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
115
+ return result
116
+ ? {
117
+ r: parseInt(result[1], 16) / 255,
118
+ g: parseInt(result[2], 16) / 255,
119
+ b: parseInt(result[3], 16) / 255
120
+ }
121
+ : { r: 0, g: 0, b: 0 };
122
+ }
123
+ /**
124
+ * Format currency amount
125
+ */
126
+ function formatCurrency(amount, symbol, position) {
127
+ const formattedAmount = amount.toFixed(2);
128
+ return position === 'before' ? `${symbol}${formattedAmount}` : `${formattedAmount}${symbol}`;
129
+ }
130
+ /**
131
+ * Generate PDF invoice
132
+ */
133
+ export async function generateInvoicePdf(template, data) {
134
+ const pdfDoc = await PDFDocument.create();
135
+ const page = pdfDoc.addPage([595.28, 841.89]); // A4 size in points
136
+ const { width, height } = page.getSize();
137
+ // Get fonts
138
+ const config = template.config;
139
+ let font;
140
+ let boldFont;
141
+ switch (config.fontFamily) {
142
+ case 'times':
143
+ font = await pdfDoc.embedFont(StandardFonts.TimesRoman);
144
+ boldFont = await pdfDoc.embedFont(StandardFonts.TimesRomanBold);
145
+ break;
146
+ case 'courier':
147
+ font = await pdfDoc.embedFont(StandardFonts.Courier);
148
+ boldFont = await pdfDoc.embedFont(StandardFonts.CourierBold);
149
+ break;
150
+ default:
151
+ font = await pdfDoc.embedFont(StandardFonts.Helvetica);
152
+ boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
153
+ }
154
+ const primaryColor = hexToRgb(config.primaryColor);
155
+ const accentColor = hexToRgb(config.accentColor);
156
+ const margin = 50;
157
+ let yPos = height - margin;
158
+ // Logo (if available and enabled)
159
+ if (config.showLogo && template.logo) {
160
+ try {
161
+ // Try to embed logo
162
+ const logoData = template.logo.split(',')[1]; // Remove data:image/... prefix
163
+ const logoBytes = Uint8Array.from(atob(logoData), (c) => c.charCodeAt(0));
164
+ let logoImage;
165
+ if (template.logo.includes('image/png')) {
166
+ logoImage = await pdfDoc.embedPng(logoBytes);
167
+ }
168
+ else {
169
+ logoImage = await pdfDoc.embedJpg(logoBytes);
170
+ }
171
+ const logoMaxHeight = 50;
172
+ const logoMaxWidth = 150;
173
+ const scale = Math.min(logoMaxWidth / logoImage.width, logoMaxHeight / logoImage.height);
174
+ const logoWidth = logoImage.width * scale;
175
+ const logoHeight = logoImage.height * scale;
176
+ let logoX = margin;
177
+ if (config.logoPosition === 'center') {
178
+ logoX = (width - logoWidth) / 2;
179
+ }
180
+ else if (config.logoPosition === 'right') {
181
+ logoX = width - margin - logoWidth;
182
+ }
183
+ page.drawImage(logoImage, {
184
+ x: logoX,
185
+ y: yPos - logoHeight,
186
+ width: logoWidth,
187
+ height: logoHeight
188
+ });
189
+ yPos -= logoHeight + 20;
190
+ }
191
+ catch (e) {
192
+ console.error('Failed to embed logo:', e);
193
+ }
194
+ }
195
+ // Company info (right-aligned)
196
+ const companyInfoX = width - margin;
197
+ page.drawText(config.companyName, {
198
+ x: companyInfoX - boldFont.widthOfTextAtSize(config.companyName, 12),
199
+ y: yPos,
200
+ size: 12,
201
+ font: boldFont,
202
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
203
+ });
204
+ yPos -= 15;
205
+ const addressLines = config.companyAddress.split(',').map((s) => s.trim());
206
+ for (const line of addressLines) {
207
+ page.drawText(line, {
208
+ x: companyInfoX - font.widthOfTextAtSize(line, 10),
209
+ y: yPos,
210
+ size: 10,
211
+ font,
212
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
213
+ });
214
+ yPos -= 12;
215
+ }
216
+ if (config.companyEmail) {
217
+ page.drawText(config.companyEmail, {
218
+ x: companyInfoX - font.widthOfTextAtSize(config.companyEmail, 10),
219
+ y: yPos,
220
+ size: 10,
221
+ font,
222
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
223
+ });
224
+ yPos -= 12;
225
+ }
226
+ if (config.companyPhone) {
227
+ page.drawText(config.companyPhone, {
228
+ x: companyInfoX - font.widthOfTextAtSize(config.companyPhone, 10),
229
+ y: yPos,
230
+ size: 10,
231
+ font,
232
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
233
+ });
234
+ yPos -= 12;
235
+ }
236
+ yPos -= 30;
237
+ // Invoice title
238
+ page.drawText('INVOICE', {
239
+ x: margin,
240
+ y: yPos,
241
+ size: 24,
242
+ font: boldFont,
243
+ color: rgb(accentColor.r, accentColor.g, accentColor.b)
244
+ });
245
+ yPos -= 30;
246
+ // Invoice details
247
+ page.drawText(`Invoice #: ${data.invoiceNumber}`, {
248
+ x: margin,
249
+ y: yPos,
250
+ size: 10,
251
+ font,
252
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
253
+ });
254
+ yPos -= 15;
255
+ page.drawText(`Date: ${data.invoiceDate}`, {
256
+ x: margin,
257
+ y: yPos,
258
+ size: 10,
259
+ font,
260
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
261
+ });
262
+ yPos -= 30;
263
+ // Bill To
264
+ page.drawText('Bill To:', {
265
+ x: margin,
266
+ y: yPos,
267
+ size: 10,
268
+ font: boldFont,
269
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
270
+ });
271
+ yPos -= 15;
272
+ page.drawText(data.customerName, {
273
+ x: margin,
274
+ y: yPos,
275
+ size: 10,
276
+ font,
277
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
278
+ });
279
+ yPos -= 12;
280
+ page.drawText(data.customerEmail, {
281
+ x: margin,
282
+ y: yPos,
283
+ size: 10,
284
+ font,
285
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
286
+ });
287
+ yPos -= 12;
288
+ if (data.customerAddress) {
289
+ page.drawText(data.customerAddress, {
290
+ x: margin,
291
+ y: yPos,
292
+ size: 10,
293
+ font,
294
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
295
+ });
296
+ yPos -= 12;
297
+ }
298
+ yPos -= 30;
299
+ // Table header
300
+ const tableTop = yPos;
301
+ const tableHeaderHeight = 25;
302
+ const colDescription = margin;
303
+ const colQty = width - margin - 200;
304
+ const colPrice = width - margin - 120;
305
+ const colTotal = width - margin - 40;
306
+ // Header background
307
+ page.drawRectangle({
308
+ x: margin,
309
+ y: yPos - tableHeaderHeight,
310
+ width: width - 2 * margin,
311
+ height: tableHeaderHeight,
312
+ color: rgb(accentColor.r, accentColor.g, accentColor.b)
313
+ });
314
+ // Header text
315
+ page.drawText('Description', {
316
+ x: colDescription + 10,
317
+ y: yPos - 17,
318
+ size: 10,
319
+ font: boldFont,
320
+ color: rgb(1, 1, 1)
321
+ });
322
+ page.drawText('Qty', {
323
+ x: colQty,
324
+ y: yPos - 17,
325
+ size: 10,
326
+ font: boldFont,
327
+ color: rgb(1, 1, 1)
328
+ });
329
+ page.drawText('Price', {
330
+ x: colPrice,
331
+ y: yPos - 17,
332
+ size: 10,
333
+ font: boldFont,
334
+ color: rgb(1, 1, 1)
335
+ });
336
+ page.drawText('Total', {
337
+ x: colTotal - font.widthOfTextAtSize('Total', 10),
338
+ y: yPos - 17,
339
+ size: 10,
340
+ font: boldFont,
341
+ color: rgb(1, 1, 1)
342
+ });
343
+ yPos -= tableHeaderHeight + 15;
344
+ // Table rows
345
+ for (const item of data.items) {
346
+ page.drawText(item.description, {
347
+ x: colDescription + 10,
348
+ y: yPos,
349
+ size: 10,
350
+ font,
351
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
352
+ });
353
+ page.drawText(item.quantity.toString(), {
354
+ x: colQty,
355
+ y: yPos,
356
+ size: 10,
357
+ font,
358
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
359
+ });
360
+ const priceStr = formatCurrency(item.unitPrice, config.currencySymbol, config.currencyPosition);
361
+ page.drawText(priceStr, {
362
+ x: colPrice,
363
+ y: yPos,
364
+ size: 10,
365
+ font,
366
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
367
+ });
368
+ const totalStr = formatCurrency(item.total, config.currencySymbol, config.currencyPosition);
369
+ page.drawText(totalStr, {
370
+ x: colTotal - font.widthOfTextAtSize(totalStr, 10),
371
+ y: yPos,
372
+ size: 10,
373
+ font,
374
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
375
+ });
376
+ yPos -= 20;
377
+ }
378
+ // Line separator
379
+ yPos -= 10;
380
+ page.drawLine({
381
+ start: { x: margin, y: yPos },
382
+ end: { x: width - margin, y: yPos },
383
+ thickness: 1,
384
+ color: rgb(0.8, 0.8, 0.8)
385
+ });
386
+ yPos -= 20;
387
+ // Subtotal
388
+ if (config.showTaxBreakdown) {
389
+ const subtotalLabel = 'Subtotal:';
390
+ const subtotalValue = formatCurrency(data.subtotal, config.currencySymbol, config.currencyPosition);
391
+ page.drawText(subtotalLabel, {
392
+ x: colPrice - font.widthOfTextAtSize(subtotalLabel, 10),
393
+ y: yPos,
394
+ size: 10,
395
+ font,
396
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
397
+ });
398
+ page.drawText(subtotalValue, {
399
+ x: colTotal - font.widthOfTextAtSize(subtotalValue, 10),
400
+ y: yPos,
401
+ size: 10,
402
+ font,
403
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
404
+ });
405
+ yPos -= 15;
406
+ // Tax
407
+ if (data.tax !== undefined) {
408
+ const taxLabel = `${config.taxLabel} (${config.taxRate}%):`;
409
+ const taxValue = formatCurrency(data.tax, config.currencySymbol, config.currencyPosition);
410
+ page.drawText(taxLabel, {
411
+ x: colPrice - font.widthOfTextAtSize(taxLabel, 10),
412
+ y: yPos,
413
+ size: 10,
414
+ font,
415
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
416
+ });
417
+ page.drawText(taxValue, {
418
+ x: colTotal - font.widthOfTextAtSize(taxValue, 10),
419
+ y: yPos,
420
+ size: 10,
421
+ font,
422
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
423
+ });
424
+ yPos -= 15;
425
+ }
426
+ }
427
+ // Total
428
+ const totalLabel = 'Total:';
429
+ const totalValue = formatCurrency(data.total, config.currencySymbol, config.currencyPosition);
430
+ page.drawText(totalLabel, {
431
+ x: colPrice - boldFont.widthOfTextAtSize(totalLabel, 12),
432
+ y: yPos,
433
+ size: 12,
434
+ font: boldFont,
435
+ color: rgb(primaryColor.r, primaryColor.g, primaryColor.b)
436
+ });
437
+ page.drawText(totalValue, {
438
+ x: colTotal - boldFont.widthOfTextAtSize(totalValue, 12),
439
+ y: yPos,
440
+ size: 12,
441
+ font: boldFont,
442
+ color: rgb(accentColor.r, accentColor.g, accentColor.b)
443
+ });
444
+ // Footer
445
+ if (config.footerText) {
446
+ page.drawText(config.footerText, {
447
+ x: (width - font.widthOfTextAtSize(config.footerText, 10)) / 2,
448
+ y: margin,
449
+ size: 10,
450
+ font,
451
+ color: rgb(0.5, 0.5, 0.5)
452
+ });
453
+ }
454
+ return await pdfDoc.save();
455
+ }