@hintergrund/worker 0.1.0 → 0.1.2

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 (37) hide show
  1. package/dist/api/newsletter/handlers/emails.handler.d.ts +13 -3
  2. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +1 -1
  3. package/dist/api/newsletter/handlers/emails.handler.js +140 -12
  4. package/dist/api/newsletter/handlers/invoice.handler.d.ts +22 -0
  5. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +1 -0
  6. package/dist/api/newsletter/handlers/invoice.handler.js +455 -0
  7. package/dist/api/newsletter/handlers/public.handler.d.ts +4 -4
  8. package/dist/api/newsletter/handlers/public.handler.d.ts.map +1 -1
  9. package/dist/api/newsletter/handlers/public.handler.js +78 -20
  10. package/dist/api/newsletter/handlers/send.handler.d.ts +2 -2
  11. package/dist/api/newsletter/handlers/send.handler.js +3 -3
  12. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +4 -4
  13. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +1 -1
  14. package/dist/api/newsletter/handlers/subscribers.handler.js +8 -4
  15. package/dist/api/newsletter/routes/admin.routes.d.ts.map +1 -1
  16. package/dist/api/newsletter/routes/admin.routes.js +8 -1
  17. package/dist/api/shop/handlers/assets.handler.d.ts +3 -0
  18. package/dist/api/shop/handlers/assets.handler.d.ts.map +1 -0
  19. package/dist/api/shop/handlers/assets.handler.js +62 -0
  20. package/dist/api/shop/handlers/checkout.handler.d.ts +10 -0
  21. package/dist/api/shop/handlers/checkout.handler.d.ts.map +1 -0
  22. package/dist/api/shop/handlers/checkout.handler.js +50 -0
  23. package/dist/api/shop/handlers/products.handler.d.ts +0 -7
  24. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  25. package/dist/api/shop/handlers/products.handler.js +0 -23
  26. package/dist/api/shop/handlers/public.handler.d.ts +17 -0
  27. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -0
  28. package/dist/api/shop/handlers/public.handler.js +108 -0
  29. package/dist/api/shop/handlers/webhook.handler.d.ts +10 -0
  30. package/dist/api/shop/handlers/webhook.handler.d.ts.map +1 -0
  31. package/dist/api/shop/handlers/webhook.handler.js +227 -0
  32. package/dist/api/shop/routes.d.ts.map +1 -1
  33. package/dist/api/shop/routes.js +9 -12
  34. package/dist/index.js +4 -4
  35. package/dist/lib/config.js +3 -3
  36. package/dist/middleware/auth.js +2 -2
  37. package/package.json +3 -2
@@ -0,0 +1,227 @@
1
+ import { getShopConfig } from '../../../lib/config';
2
+ import Stripe from 'stripe';
3
+ import { generateInvoicePdf } from '../../newsletter/handlers/invoice.handler';
4
+ function getStripe(env) {
5
+ const config = getShopConfig(env);
6
+ return new Stripe(config.stripeSecretKey, {
7
+ apiVersion: '2025-02-24.acacia'
8
+ });
9
+ }
10
+ /**
11
+ * POST /api/shop/webhook
12
+ * Handle Stripe webhook events
13
+ */
14
+ export async function handleStripeWebhook(c) {
15
+ const stripe = getStripe(c.env);
16
+ const webhookSecret = c.env.HG_SHOP_STRIPE_WEBHOOK_SECRET;
17
+ if (!webhookSecret) {
18
+ console.error('Stripe webhook secret not configured');
19
+ return c.json({ error: 'Webhook not configured' }, 500);
20
+ }
21
+ // Get the raw body and signature
22
+ const signature = c.req.header('stripe-signature');
23
+ if (!signature) {
24
+ return c.json({ error: 'Missing stripe-signature header' }, 400);
25
+ }
26
+ const rawBody = await c.req.text();
27
+ let event;
28
+ try {
29
+ event = await stripe.webhooks.constructEventAsync(rawBody, signature, webhookSecret);
30
+ }
31
+ catch (err) {
32
+ console.error('Webhook signature verification failed:', err.message);
33
+ return c.json({ error: 'Webhook signature verification failed' }, 400);
34
+ }
35
+ // Handle the event
36
+ switch (event.type) {
37
+ case 'checkout.session.completed': {
38
+ const session = event.data.object;
39
+ await handleCheckoutSessionCompleted(c, stripe, session);
40
+ break;
41
+ }
42
+ // Add more event handlers as needed
43
+ default:
44
+ console.log(`Unhandled event type: ${event.type}`);
45
+ }
46
+ return c.json({ received: true });
47
+ }
48
+ /**
49
+ * Handle checkout.session.completed event
50
+ * Generate and send invoice PDF to customer
51
+ */
52
+ async function handleCheckoutSessionCompleted(c, stripe, session) {
53
+ try {
54
+ // Get customer email
55
+ const customerEmail = session.customer_details?.email;
56
+ if (!customerEmail) {
57
+ console.error('No customer email in checkout session');
58
+ return;
59
+ }
60
+ // Get line items
61
+ const lineItems = await stripe.checkout.sessions.listLineItems(session.id, {
62
+ expand: ['data.price.product']
63
+ });
64
+ // Get invoice template
65
+ const db = c.env.DB;
66
+ if (!db) {
67
+ console.error('Database not configured');
68
+ return;
69
+ }
70
+ // Fetch invoice template from database
71
+ const templateResult = await db
72
+ .prepare("SELECT * FROM templates WHERE type = 'invoice'")
73
+ .first();
74
+ let template;
75
+ if (templateResult) {
76
+ template = {
77
+ id: templateResult.id,
78
+ config: JSON.parse(templateResult.config),
79
+ logo: templateResult.logo,
80
+ createdAt: templateResult.created_at,
81
+ updatedAt: templateResult.updated_at
82
+ };
83
+ }
84
+ else {
85
+ // Use default template
86
+ template = {
87
+ id: 'invoice',
88
+ config: {
89
+ primaryColor: '#1f2937',
90
+ accentColor: '#3b82f6',
91
+ fontFamily: 'helvetica',
92
+ logoPosition: 'left',
93
+ showLogo: false,
94
+ companyName: 'Your Company',
95
+ companyAddress: '123 Main Street, City, Country',
96
+ companyEmail: 'contact@company.com',
97
+ companyPhone: '+1 234 567 890',
98
+ footerText: 'Thank you for your business!',
99
+ currencySymbol: '€',
100
+ currencyPosition: 'before',
101
+ showTaxBreakdown: true,
102
+ taxLabel: 'VAT',
103
+ taxRate: 19,
104
+ dueDays: 14
105
+ },
106
+ createdAt: Date.now(),
107
+ updatedAt: Date.now()
108
+ };
109
+ }
110
+ // Build invoice data
111
+ const invoiceItems = lineItems.data.map((item) => {
112
+ const product = item.price?.product;
113
+ return {
114
+ description: product?.name || item.description || 'Item',
115
+ quantity: item.quantity || 1,
116
+ unitPrice: (item.price?.unit_amount || 0) / 100,
117
+ total: (item.amount_total || 0) / 100
118
+ };
119
+ });
120
+ const subtotal = (session.amount_subtotal || 0) / 100;
121
+ const tax = session.total_details?.amount_tax ? session.total_details.amount_tax / 100 : undefined;
122
+ const total = (session.amount_total || 0) / 100;
123
+ const invoiceData = {
124
+ invoiceNumber: `INV-${session.id.slice(-8).toUpperCase()}`,
125
+ invoiceDate: new Date().toLocaleDateString('en-US', {
126
+ year: 'numeric',
127
+ month: 'long',
128
+ day: 'numeric'
129
+ }),
130
+ customerName: session.customer_details?.name || 'Customer',
131
+ customerEmail,
132
+ customerAddress: session.customer_details?.address
133
+ ? formatAddress(session.customer_details.address)
134
+ : undefined,
135
+ items: invoiceItems,
136
+ subtotal,
137
+ tax,
138
+ total,
139
+ currency: session.currency?.toUpperCase() || 'EUR',
140
+ paymentMethod: session.payment_method_types?.[0] || 'card'
141
+ };
142
+ // Generate PDF
143
+ const pdfBytes = await generateInvoicePdf(template, invoiceData);
144
+ // Send email with PDF attachment
145
+ await sendInvoiceEmail(c, customerEmail, invoiceData, pdfBytes);
146
+ console.log(`Invoice sent to ${customerEmail} for session ${session.id}`);
147
+ }
148
+ catch (error) {
149
+ console.error('Failed to handle checkout session completed:', error);
150
+ }
151
+ }
152
+ /**
153
+ * Format Stripe address object to string
154
+ */
155
+ function formatAddress(address) {
156
+ const parts = [];
157
+ if (address.line1)
158
+ parts.push(address.line1);
159
+ if (address.line2)
160
+ parts.push(address.line2);
161
+ if (address.city)
162
+ parts.push(address.city);
163
+ if (address.postal_code)
164
+ parts.push(address.postal_code);
165
+ if (address.country)
166
+ parts.push(address.country);
167
+ return parts.join(', ');
168
+ }
169
+ /**
170
+ * Send invoice email with PDF attachment
171
+ */
172
+ async function sendInvoiceEmail(c, to, invoiceData, pdfBytes) {
173
+ const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
174
+ const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
175
+ const fromName = c.env.HG_NEWSLETTER_FROM_NAME || 'Shop';
176
+ if (!apiKey || !fromEmail) {
177
+ console.error('Email not configured');
178
+ return;
179
+ }
180
+ // Convert PDF to base64
181
+ const pdfBase64 = btoa(String.fromCharCode(...pdfBytes));
182
+ // Build email HTML
183
+ const html = `
184
+ <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
185
+ <h1 style="color: #1f2937;">Thank you for your purchase!</h1>
186
+ <p style="color: #4b5563;">Dear ${invoiceData.customerName},</p>
187
+ <p style="color: #4b5563;">Thank you for your order. Please find your invoice attached to this email.</p>
188
+
189
+ <div style="background-color: #f3f4f6; padding: 20px; border-radius: 8px; margin: 20px 0;">
190
+ <p style="margin: 0; color: #1f2937;"><strong>Invoice Number:</strong> ${invoiceData.invoiceNumber}</p>
191
+ <p style="margin: 8px 0 0; color: #1f2937;"><strong>Date:</strong> ${invoiceData.invoiceDate}</p>
192
+ <p style="margin: 8px 0 0; color: #1f2937;"><strong>Total:</strong> ${invoiceData.currency} ${invoiceData.total.toFixed(2)}</p>
193
+ </div>
194
+
195
+ <p style="color: #4b5563;">If you have any questions about your order, please don't hesitate to contact us.</p>
196
+
197
+ <p style="color: #9ca3af; font-size: 12px; margin-top: 40px;">
198
+ This is an automated email. Please do not reply directly to this message.
199
+ </p>
200
+ </div>
201
+ `;
202
+ const payload = {
203
+ from: `${fromName} <${fromEmail}>`,
204
+ to,
205
+ subject: `Your Invoice ${invoiceData.invoiceNumber}`,
206
+ html,
207
+ attachments: [
208
+ {
209
+ content: pdfBase64,
210
+ filename: `invoice-${invoiceData.invoiceNumber}.pdf`,
211
+ type: 'application/pdf'
212
+ }
213
+ ]
214
+ };
215
+ const response = await fetch('https://api.resend.com/emails', {
216
+ method: 'POST',
217
+ headers: {
218
+ Authorization: `Bearer ${apiKey}`,
219
+ 'Content-Type': 'application/json'
220
+ },
221
+ body: JSON.stringify(payload)
222
+ });
223
+ if (!response.ok) {
224
+ const error = await response.text();
225
+ throw new Error(`Failed to send invoice email: ${error}`);
226
+ }
227
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/api/shop/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAiB5C,QAAA,MAAM,UAAU;cAAwB,QAAQ;yCAAK,CAAC;AA8BtD,eAAe,UAAU,CAAC"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/api/shop/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAgB5C,QAAA,MAAM,UAAU;cAAwB,QAAQ;yCAAK,CAAC;AA0BtD,eAAe,UAAU,CAAC"}
@@ -1,18 +1,21 @@
1
1
  import { Hono } from 'hono';
2
2
  import { authMiddleware } from '../../middleware/auth';
3
3
  // Import handlers
4
- import { getProducts, getPublicProducts, getProduct, createProduct, updateProduct, deleteProduct } from './handlers/products.handler';
4
+ import { getProducts, getProduct, createProduct, updateProduct, deleteProduct } from './handlers/products.handler';
5
5
  import { createPrice, updatePrice } from './handlers/prices.handler';
6
- import { getOrders, getOrder } from './handlers/orders.handler';
7
- import { getCustomers, getCustomer } from './handlers/customers.handler';
8
- import { getStats } from './handlers/stats.handler';
6
+ import { uploadShopAsset } from './handlers/assets.handler';
7
+ import { getPublicProducts, createCheckoutSession } from './handlers/public.handler';
8
+ import { handleStripeWebhook } from './handlers/webhook.handler';
9
9
  const shopRoutes = new Hono();
10
10
  // Public routes (no auth required)
11
11
  shopRoutes.get('/products', getPublicProducts);
12
+ shopRoutes.post('/checkout', createCheckoutSession);
13
+ // Stripe webhook (no auth, but verified by signature)
14
+ shopRoutes.post('/webhook', handleStripeWebhook);
12
15
  // Apply auth middleware to all shop admin routes
13
16
  shopRoutes.use('/admin/*', authMiddleware);
14
- // Stats
15
- shopRoutes.get('/admin/stats', getStats);
17
+ // Assets
18
+ shopRoutes.post('/admin/assets', uploadShopAsset);
16
19
  // Products
17
20
  shopRoutes.get('/admin/products', getProducts);
18
21
  shopRoutes.get('/admin/products/:id', getProduct);
@@ -22,10 +25,4 @@ shopRoutes.delete('/admin/products/:id', deleteProduct);
22
25
  // Prices
23
26
  shopRoutes.post('/admin/prices', createPrice);
24
27
  shopRoutes.patch('/admin/prices/:id', updatePrice);
25
- // Orders
26
- shopRoutes.get('/admin/orders', getOrders);
27
- shopRoutes.get('/admin/orders/:id', getOrder);
28
- // Customers
29
- shopRoutes.get('/admin/customers', getCustomers);
30
- shopRoutes.get('/admin/customers/:id', getCustomer);
31
28
  export default shopRoutes;
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { cors } from 'hono/cors';
3
3
  import cmsRoutes from './api/cms/routes';
4
4
  import newsletterRoutes from './api/newsletter/routes';
5
5
  import shopRoutes from './api/shop/routes';
6
- import builderRoutes from './api/builder/routes';
6
+ // import builderRoutes from './api/builder/routes';
7
7
  import { authMiddleware } from './middleware/auth';
8
8
  import { getTemplate } from './lib/template';
9
9
  export function createApp() {
@@ -14,12 +14,12 @@ export function createApp() {
14
14
  app.get('/login', (c) => c.html(getTemplate('login', c.env.UI_BASE_URL)));
15
15
  // Mount CMS routes under /api/admin
16
16
  app.route('/api/admin', cmsRoutes);
17
- // Mount newsletter routes under /api/newsletter
18
- app.route('/api/newsletter', newsletterRoutes);
17
+ // Mount newsletter routes under /api/email
18
+ app.route('/api/email', newsletterRoutes);
19
19
  // Mount shop routes under /api/shop
20
20
  app.route('/api/shop', shopRoutes);
21
21
  // Mount builder routes under /api/builder
22
- app.route('/api/builder', builderRoutes);
22
+ // app.route('/api/builder', builderRoutes);
23
23
  // Admin main page (protected)
24
24
  app.get('/admin', async (c) => {
25
25
  // Check authentication
@@ -103,7 +103,7 @@ function loadFromEnvVars(env) {
103
103
  };
104
104
  }
105
105
  // Load Builder module config (auto-detect based on required vars)
106
- const builderMissing = getMissingVars(env, BUILDER_REQUIRED_VARS);
106
+ /* const builderMissing = getMissingVars(env, BUILDER_REQUIRED_VARS);
107
107
  if (builderMissing.length === 0) {
108
108
  config.builder = {
109
109
  enabled: true,
@@ -112,7 +112,7 @@ function loadFromEnvVars(env) {
112
112
  templateRepo: env.HG_BUILDER_TEMPLATE_REPO || 'hintergrund-cloud/demo-shop',
113
113
  gitBranch: env.HG_BUILDER_GIT_BRANCH || 'main',
114
114
  };
115
- }
115
+ } */
116
116
  return config;
117
117
  }
118
118
  /**
@@ -123,7 +123,7 @@ export function getAdminConfig(appConfig) {
123
123
  cms: appConfig.cms?.enabled ?? false,
124
124
  newsletter: appConfig.newsletter?.enabled ?? false,
125
125
  shop: appConfig.shop?.enabled ?? false,
126
- builder: appConfig.builder?.enabled ?? false,
126
+ builder: false, // appConfig.builder?.enabled ?? false,
127
127
  loginMethod: appConfig.global.auth?.loginMethod ?? 'password',
128
128
  userGroups: appConfig.global.auth?.userGroups?.map(g => g.name),
129
129
  };
@@ -14,9 +14,9 @@ function getModuleFromPath(pathname) {
14
14
  if (pathname.includes('/api/admin/shop')) {
15
15
  return 'shop';
16
16
  }
17
- if (pathname.includes('/api/admin/builder')) {
17
+ /* if (pathname.includes('/api/admin/builder')) {
18
18
  return 'builder';
19
- }
19
+ } */
20
20
  return null;
21
21
  }
22
22
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hintergrund/worker",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -22,8 +22,9 @@
22
22
  "@octokit/rest": "^22.0.0",
23
23
  "cookie": "^1.0.2",
24
24
  "hono": "^4.10.2",
25
+ "pdf-lib": "^1.17.1",
25
26
  "stripe": "^17.5.0",
26
- "@hintergrund/shared": "0.0.1"
27
+ "@hintergrund/shared": "0.1.1"
27
28
  },
28
29
  "scripts": {
29
30
  "build": "tsc",