@hintergrund/worker 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/api/builder/handlers/generate.handler.d.ts +12 -0
- package/dist/api/builder/handlers/generate.handler.d.ts.map +1 -0
- package/dist/api/builder/handlers/generate.handler.js +203 -0
- package/dist/api/builder/handlers/template.handler.d.ts +12 -0
- package/dist/api/builder/handlers/template.handler.d.ts.map +1 -0
- package/dist/api/builder/handlers/template.handler.js +208 -0
- package/dist/api/builder/routes.d.ts +7 -0
- package/dist/api/builder/routes.d.ts.map +1 -0
- package/dist/api/builder/routes.js +15 -0
- package/dist/api/cms/handlers/assets.handler.d.ts +8 -0
- package/dist/api/cms/handlers/assets.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/assets.handler.js +299 -0
- package/dist/api/cms/handlers/auth.handler.d.ts +11 -0
- package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/auth.handler.js +214 -0
- package/dist/api/cms/handlers/config.handler.d.ts +3 -0
- package/dist/api/cms/handlers/config.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/config.handler.js +88 -0
- package/dist/api/cms/handlers/content.handler.d.ts +10 -0
- package/dist/api/cms/handlers/content.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/content.handler.js +293 -0
- package/dist/api/cms/handlers/dashboard.handler.d.ts +6 -0
- package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/dashboard.handler.js +15 -0
- package/dist/api/cms/routes/assets.routes.d.ts +4 -0
- package/dist/api/cms/routes/assets.routes.d.ts.map +1 -0
- package/dist/api/cms/routes/assets.routes.js +13 -0
- package/dist/api/cms/routes/auth.routes.d.ts +4 -0
- package/dist/api/cms/routes/auth.routes.d.ts.map +1 -0
- package/dist/api/cms/routes/auth.routes.js +7 -0
- package/dist/api/cms/routes/content.routes.d.ts +4 -0
- package/dist/api/cms/routes/content.routes.d.ts.map +1 -0
- package/dist/api/cms/routes/content.routes.js +11 -0
- package/dist/api/cms/routes/index.d.ts +4 -0
- package/dist/api/cms/routes/index.d.ts.map +1 -0
- package/dist/api/cms/routes/index.js +16 -0
- package/dist/api/newsletter/handlers/email.handler.d.ts +7 -0
- package/dist/api/newsletter/handlers/email.handler.d.ts.map +1 -0
- package/dist/api/newsletter/handlers/email.handler.js +102 -0
- package/dist/api/newsletter/handlers/emails.handler.d.ts +21 -0
- package/dist/api/newsletter/handlers/emails.handler.d.ts.map +1 -0
- package/dist/api/newsletter/handlers/emails.handler.js +134 -0
- package/dist/api/newsletter/handlers/public.handler.d.ts +22 -0
- package/dist/api/newsletter/handlers/public.handler.d.ts.map +1 -0
- package/dist/api/newsletter/handlers/public.handler.js +242 -0
- package/dist/api/newsletter/handlers/send.handler.d.ts +12 -0
- package/dist/api/newsletter/handlers/send.handler.d.ts.map +1 -0
- package/dist/api/newsletter/handlers/send.handler.js +153 -0
- package/dist/api/newsletter/handlers/subscribers.handler.d.ts +22 -0
- package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +1 -0
- package/dist/api/newsletter/handlers/subscribers.handler.js +191 -0
- package/dist/api/newsletter/routes/admin.routes.d.ts +4 -0
- package/dist/api/newsletter/routes/admin.routes.d.ts.map +1 -0
- package/dist/api/newsletter/routes/admin.routes.js +21 -0
- package/dist/api/newsletter/routes/index.d.ts +4 -0
- package/dist/api/newsletter/routes/index.d.ts.map +1 -0
- package/dist/api/newsletter/routes/index.js +9 -0
- package/dist/api/newsletter/routes/public.routes.d.ts +4 -0
- package/dist/api/newsletter/routes/public.routes.d.ts.map +1 -0
- package/dist/api/newsletter/routes/public.routes.js +9 -0
- package/dist/api/shop/handlers/customers.handler.d.ts +17 -0
- package/dist/api/shop/handlers/customers.handler.d.ts.map +1 -0
- package/dist/api/shop/handlers/customers.handler.js +89 -0
- package/dist/api/shop/handlers/orders.handler.d.ts +17 -0
- package/dist/api/shop/handlers/orders.handler.d.ts.map +1 -0
- package/dist/api/shop/handlers/orders.handler.js +84 -0
- package/dist/api/shop/handlers/prices.handler.d.ts +17 -0
- package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -0
- package/dist/api/shop/handlers/prices.handler.js +87 -0
- package/dist/api/shop/handlers/products.handler.d.ts +45 -0
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -0
- package/dist/api/shop/handlers/products.handler.js +243 -0
- package/dist/api/shop/handlers/stats.handler.d.ts +10 -0
- package/dist/api/shop/handlers/stats.handler.d.ts.map +1 -0
- package/dist/api/shop/handlers/stats.handler.js +71 -0
- package/dist/api/shop/routes.d.ts +7 -0
- package/dist/api/shop/routes.d.ts.map +1 -0
- package/dist/api/shop/routes.js +31 -0
- package/dist/cms-assets.d.ts +4 -0
- package/dist/cms-assets.d.ts.map +1 -0
- package/dist/cms-assets.js +5 -0
- package/dist/cms-bundle.d.ts +3 -0
- package/dist/cms-bundle.d.ts.map +1 -0
- package/dist/cms-bundle.js +4 -0
- package/dist/config-loader.d.ts +26 -0
- package/dist/config-loader.d.ts.map +1 -0
- package/dist/config-loader.js +98 -0
- package/dist/hintergrund-assets.d.ts +4 -0
- package/dist/hintergrund-assets.d.ts.map +1 -0
- package/dist/hintergrund-assets.js +9 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +66 -0
- package/dist/jwt.d.ts +26 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +102 -0
- package/dist/lib/auth/crypto.d.ts +23 -0
- package/dist/lib/auth/crypto.d.ts.map +1 -0
- package/dist/lib/auth/crypto.js +110 -0
- package/dist/lib/auth/jwt.d.ts +38 -0
- package/dist/lib/auth/jwt.d.ts.map +1 -0
- package/dist/lib/auth/jwt.js +120 -0
- package/dist/lib/config.d.ts +31 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +174 -0
- package/dist/lib/email.d.ts +16 -0
- package/dist/lib/email.d.ts.map +1 -0
- package/dist/lib/email.js +83 -0
- package/dist/lib/template.d.ts +2 -0
- package/dist/lib/template.d.ts.map +1 -0
- package/dist/lib/template.js +226 -0
- package/dist/middleware/auth.d.ts +9 -0
- package/dist/middleware/auth.d.ts.map +1 -0
- package/dist/middleware/auth.js +93 -0
- package/dist/template.d.ts +2 -0
- package/dist/template.d.ts.map +1 -0
- package/dist/template.js +61 -0
- package/dist/utils.d.ts +23 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +110 -0
- package/package.json +32 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Generate email ID
|
|
2
|
+
function generateId() {
|
|
3
|
+
return Math.random().toString(36).substring(2, 14);
|
|
4
|
+
}
|
|
5
|
+
// Parse D1 row to EmailRecord
|
|
6
|
+
function parseEmailRecord(row) {
|
|
7
|
+
return {
|
|
8
|
+
id: row.id,
|
|
9
|
+
subject: row.subject,
|
|
10
|
+
htmlContent: row.html_content,
|
|
11
|
+
status: row.status,
|
|
12
|
+
config: row.config ? JSON.parse(row.config) : undefined,
|
|
13
|
+
recipientCount: row.recipient_count || undefined,
|
|
14
|
+
sentAt: row.sent_at || undefined,
|
|
15
|
+
scheduledFor: row.scheduled_for || undefined,
|
|
16
|
+
createdAt: row.created_at,
|
|
17
|
+
updatedAt: row.updated_at,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* GET /api/newsletter/admin/emails
|
|
22
|
+
* Get all emails (sent emails and drafts)
|
|
23
|
+
*/
|
|
24
|
+
export async function getEmails(c) {
|
|
25
|
+
try {
|
|
26
|
+
const db = c.env.DB;
|
|
27
|
+
const result = await db.prepare('SELECT * FROM emails ORDER BY created_at DESC').all();
|
|
28
|
+
const emails = result.results.map((row) => parseEmailRecord(row));
|
|
29
|
+
return c.json({ emails });
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
console.error('Get emails error:', error);
|
|
33
|
+
return c.json({
|
|
34
|
+
success: false,
|
|
35
|
+
message: error instanceof Error ? error.message : 'Failed to fetch emails',
|
|
36
|
+
}, 500);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* POST /api/newsletter/admin/emails/draft
|
|
41
|
+
* Save email as draft
|
|
42
|
+
*/
|
|
43
|
+
export async function saveDraft(c) {
|
|
44
|
+
try {
|
|
45
|
+
const body = (await c.req.json());
|
|
46
|
+
const { subject, htmlContent, id, config } = body;
|
|
47
|
+
if (!subject || !htmlContent) {
|
|
48
|
+
return c.json({ success: false, message: 'Subject and content are required' }, 400);
|
|
49
|
+
}
|
|
50
|
+
const db = c.env.DB;
|
|
51
|
+
const now = Date.now();
|
|
52
|
+
if (id) {
|
|
53
|
+
// Update existing draft
|
|
54
|
+
const configJson = config ? JSON.stringify(config) : null;
|
|
55
|
+
await db
|
|
56
|
+
.prepare(`UPDATE emails
|
|
57
|
+
SET subject = ?, html_content = ?, config = ?, updated_at = ?
|
|
58
|
+
WHERE id = ? AND status = 'draft'`)
|
|
59
|
+
.bind(subject, htmlContent, configJson, now, id)
|
|
60
|
+
.run();
|
|
61
|
+
const row = await db.prepare('SELECT * FROM emails WHERE id = ?').bind(id).first();
|
|
62
|
+
if (!row) {
|
|
63
|
+
return c.json({ success: false, message: 'Draft not found' }, 404);
|
|
64
|
+
}
|
|
65
|
+
const email = parseEmailRecord(row);
|
|
66
|
+
return c.json({ success: true, email });
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
// Create new draft
|
|
70
|
+
const newId = generateId();
|
|
71
|
+
const configJson = config ? JSON.stringify(config) : null;
|
|
72
|
+
await db
|
|
73
|
+
.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)
|
|
77
|
+
.run();
|
|
78
|
+
const row = await db.prepare('SELECT * FROM emails WHERE id = ?').bind(newId).first();
|
|
79
|
+
if (!row) {
|
|
80
|
+
return c.json({ success: false, message: 'Failed to create draft' }, 500);
|
|
81
|
+
}
|
|
82
|
+
const email = parseEmailRecord(row);
|
|
83
|
+
return c.json({ success: true, email, message: 'Draft saved' });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
console.error('Save draft error:', error);
|
|
88
|
+
return c.json({
|
|
89
|
+
success: false,
|
|
90
|
+
message: error instanceof Error ? error.message : 'Failed to save draft',
|
|
91
|
+
}, 500);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* DELETE /api/newsletter/admin/emails/:id
|
|
96
|
+
* Delete email (draft or sent)
|
|
97
|
+
*/
|
|
98
|
+
export async function deleteEmail(c) {
|
|
99
|
+
try {
|
|
100
|
+
const id = c.req.param('id');
|
|
101
|
+
if (!id) {
|
|
102
|
+
return c.json({ success: false, message: 'Missing email ID' }, 400);
|
|
103
|
+
}
|
|
104
|
+
const db = c.env.DB;
|
|
105
|
+
// Check if email exists
|
|
106
|
+
const existing = await db.prepare('SELECT id FROM emails WHERE id = ?').bind(id).first();
|
|
107
|
+
if (!existing) {
|
|
108
|
+
return c.json({ success: false, message: 'Email not found' }, 404);
|
|
109
|
+
}
|
|
110
|
+
// Delete email
|
|
111
|
+
await db.prepare('DELETE FROM emails WHERE id = ?').bind(id).run();
|
|
112
|
+
return c.json({ success: true });
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
console.error('Delete email error:', error);
|
|
116
|
+
return c.json({
|
|
117
|
+
success: false,
|
|
118
|
+
message: error instanceof Error ? error.message : 'Failed to delete email',
|
|
119
|
+
}, 500);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Save sent email record to database
|
|
124
|
+
*/
|
|
125
|
+
export async function saveSentEmail(db, subject, htmlContent, recipientCount) {
|
|
126
|
+
const emailId = generateId();
|
|
127
|
+
const now = Date.now();
|
|
128
|
+
await db
|
|
129
|
+
.prepare(`INSERT INTO emails
|
|
130
|
+
(id, subject, html_content, status, recipient_count, sent_at, created_at, updated_at)
|
|
131
|
+
VALUES (?, ?, ?, 'sent', ?, ?, ?, ?)`)
|
|
132
|
+
.bind(emailId, subject, htmlContent, recipientCount, now, now, now)
|
|
133
|
+
.run();
|
|
134
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Context } from 'hono';
|
|
2
|
+
/**
|
|
3
|
+
* POST /api/newsletter/subscribe
|
|
4
|
+
* Public endpoint to subscribe to newsletter
|
|
5
|
+
*/
|
|
6
|
+
export declare function subscribe(c: Context): Promise<Response>;
|
|
7
|
+
/**
|
|
8
|
+
* GET /api/newsletter/confirm?token=xxx
|
|
9
|
+
* Public endpoint to confirm subscription
|
|
10
|
+
*/
|
|
11
|
+
export declare function confirm(c: Context): Promise<Response>;
|
|
12
|
+
/**
|
|
13
|
+
* GET /api/newsletter/unsubscribe?token=xxx
|
|
14
|
+
* Public endpoint to show unsubscribe confirmation page
|
|
15
|
+
*/
|
|
16
|
+
export declare function showUnsubscribePage(c: Context): Promise<Response>;
|
|
17
|
+
/**
|
|
18
|
+
* POST /api/newsletter/unsubscribe
|
|
19
|
+
* Public endpoint to unsubscribe from newsletter
|
|
20
|
+
*/
|
|
21
|
+
export declare function unsubscribe(c: Context): Promise<Response>;
|
|
22
|
+
//# sourceMappingURL=public.handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/newsletter/handlers/public.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAyD/B;;;GAGG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuH7D;AAED;;;GAGG;AACH,wBAAsB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6C3D;AAED;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAcvE;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqD/D"}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// Utility functions for token generation
|
|
2
|
+
function generateToken() {
|
|
3
|
+
const array = new Uint8Array(32);
|
|
4
|
+
crypto.getRandomValues(array);
|
|
5
|
+
return Array.from(array, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
6
|
+
}
|
|
7
|
+
function generateId() {
|
|
8
|
+
return Math.random().toString(36).substring(2, 14);
|
|
9
|
+
}
|
|
10
|
+
// Email validation
|
|
11
|
+
function isValidEmail(email) {
|
|
12
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
13
|
+
return emailRegex.test(email);
|
|
14
|
+
}
|
|
15
|
+
// Send confirmation email via Resend
|
|
16
|
+
async function sendConfirmationEmail(email, token, apiKey, from, fromName, confirmationUrl) {
|
|
17
|
+
const confirmLink = `${confirmationUrl}?token=${token}`;
|
|
18
|
+
const html = `
|
|
19
|
+
<h2>Confirm your subscription</h2>
|
|
20
|
+
<p>Thank you for subscribing! Please confirm your email address by clicking the link below:</p>
|
|
21
|
+
<p><a href="${confirmLink}">${confirmLink}</a></p>
|
|
22
|
+
<p>If you didn't request this, you can safely ignore this email.</p>
|
|
23
|
+
`;
|
|
24
|
+
const response = await fetch('https://api.resend.com/emails', {
|
|
25
|
+
method: 'POST',
|
|
26
|
+
headers: {
|
|
27
|
+
Authorization: `Bearer ${apiKey}`,
|
|
28
|
+
'Content-Type': 'application/json',
|
|
29
|
+
},
|
|
30
|
+
body: JSON.stringify({
|
|
31
|
+
from: `${fromName} <${from}>`,
|
|
32
|
+
to: email,
|
|
33
|
+
subject: 'Confirm your subscription',
|
|
34
|
+
html,
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const error = await response.text();
|
|
39
|
+
throw new Error(`Failed to send confirmation email: ${error}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* POST /api/newsletter/subscribe
|
|
44
|
+
* Public endpoint to subscribe to newsletter
|
|
45
|
+
*/
|
|
46
|
+
export async function subscribe(c) {
|
|
47
|
+
try {
|
|
48
|
+
const body = (await c.req.json());
|
|
49
|
+
const { email, name } = body;
|
|
50
|
+
// Validate email
|
|
51
|
+
if (!email || !isValidEmail(email)) {
|
|
52
|
+
return c.json({ success: false, message: 'Invalid email address' }, 400);
|
|
53
|
+
}
|
|
54
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
55
|
+
// Get environment variables
|
|
56
|
+
const db = c.env.DB;
|
|
57
|
+
const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
|
|
58
|
+
const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
|
|
59
|
+
const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
|
|
60
|
+
const confirmationUrl = c.env.HG_NEWSLETTER_CONFIRMATION_URL;
|
|
61
|
+
if (!db || !apiKey || !fromEmail || !confirmationUrl) {
|
|
62
|
+
return c.json({ success: false, message: 'Newsletter not configured' }, 500);
|
|
63
|
+
}
|
|
64
|
+
// Check if subscriber already exists
|
|
65
|
+
const existing = await db
|
|
66
|
+
.prepare('SELECT id, status FROM subscribers WHERE email = ?')
|
|
67
|
+
.bind(normalizedEmail)
|
|
68
|
+
.first();
|
|
69
|
+
if (existing) {
|
|
70
|
+
// If already subscribed, return success
|
|
71
|
+
if (existing.status === 'subscribed') {
|
|
72
|
+
return c.json({
|
|
73
|
+
success: true,
|
|
74
|
+
message: 'You are already subscribed!',
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
// If pending, resend confirmation
|
|
78
|
+
if (existing.status === 'pending') {
|
|
79
|
+
// Generate new token
|
|
80
|
+
const token = generateToken();
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
await db
|
|
83
|
+
.prepare(`UPDATE subscribers
|
|
84
|
+
SET confirmation_token = ?, confirmation_sent_at = ?, updated_at = ?
|
|
85
|
+
WHERE email = ?`)
|
|
86
|
+
.bind(token, now, now, normalizedEmail)
|
|
87
|
+
.run();
|
|
88
|
+
// Send confirmation email
|
|
89
|
+
await sendConfirmationEmail(normalizedEmail, token, apiKey, fromEmail, fromName || 'Newsletter', confirmationUrl);
|
|
90
|
+
return c.json({
|
|
91
|
+
success: true,
|
|
92
|
+
message: 'Please check your email to confirm your subscription',
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
// If unsubscribed, allow re-subscription
|
|
96
|
+
if (existing.status === 'unsubscribed') {
|
|
97
|
+
// Generate new confirmation token
|
|
98
|
+
const token = generateToken();
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
await db
|
|
101
|
+
.prepare(`UPDATE subscribers
|
|
102
|
+
SET status = 'pending', confirmation_token = ?, confirmation_sent_at = ?, updated_at = ?
|
|
103
|
+
WHERE email = ?`)
|
|
104
|
+
.bind(token, now, now, normalizedEmail)
|
|
105
|
+
.run();
|
|
106
|
+
// Send confirmation email
|
|
107
|
+
await sendConfirmationEmail(normalizedEmail, token, apiKey, fromEmail, fromName || 'Newsletter', confirmationUrl);
|
|
108
|
+
return c.json({
|
|
109
|
+
success: true,
|
|
110
|
+
message: 'Please check your email to confirm your subscription',
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Create new pending subscriber
|
|
115
|
+
const id = generateId();
|
|
116
|
+
const token = generateToken();
|
|
117
|
+
const unsubscribeToken = generateToken();
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
await db
|
|
120
|
+
.prepare(`INSERT INTO subscribers
|
|
121
|
+
(id, email, name, status, source, confirmation_token, unsubscribe_token, confirmation_sent_at, created_at, updated_at)
|
|
122
|
+
VALUES (?, ?, ?, 'pending', 'website', ?, ?, ?, ?, ?)`)
|
|
123
|
+
.bind(id, normalizedEmail, name || null, token, unsubscribeToken, now, now, now)
|
|
124
|
+
.run();
|
|
125
|
+
// Send confirmation email
|
|
126
|
+
await sendConfirmationEmail(normalizedEmail, token, apiKey, fromEmail, fromName || 'Newsletter', confirmationUrl);
|
|
127
|
+
return c.json({
|
|
128
|
+
success: true,
|
|
129
|
+
message: 'Please check your email to confirm your subscription',
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
console.error('Subscribe error:', error);
|
|
134
|
+
return c.json({
|
|
135
|
+
success: false,
|
|
136
|
+
message: error instanceof Error ? error.message : 'Failed to subscribe',
|
|
137
|
+
}, 500);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* GET /api/newsletter/confirm?token=xxx
|
|
142
|
+
* Public endpoint to confirm subscription
|
|
143
|
+
*/
|
|
144
|
+
export async function confirm(c) {
|
|
145
|
+
try {
|
|
146
|
+
const token = c.req.query('token');
|
|
147
|
+
if (!token) {
|
|
148
|
+
return c.json({ success: false, message: 'Missing confirmation token' }, 400);
|
|
149
|
+
}
|
|
150
|
+
const db = c.env.DB;
|
|
151
|
+
// Find subscriber by confirmation token
|
|
152
|
+
const subscriber = await db
|
|
153
|
+
.prepare('SELECT id, status FROM subscribers WHERE confirmation_token = ?')
|
|
154
|
+
.bind(token)
|
|
155
|
+
.first();
|
|
156
|
+
if (!subscriber) {
|
|
157
|
+
return c.json({ success: false, message: 'Invalid or expired confirmation token' }, 404);
|
|
158
|
+
}
|
|
159
|
+
// Update subscriber status
|
|
160
|
+
const now = Date.now();
|
|
161
|
+
await db
|
|
162
|
+
.prepare(`UPDATE subscribers
|
|
163
|
+
SET status = 'subscribed', confirmed_at = ?, subscribed_at = ?, confirmation_token = NULL, updated_at = ?
|
|
164
|
+
WHERE id = ?`)
|
|
165
|
+
.bind(now, now, now, subscriber.id)
|
|
166
|
+
.run();
|
|
167
|
+
return c.json({
|
|
168
|
+
success: true,
|
|
169
|
+
message: 'Your subscription has been confirmed! Thank you for subscribing.',
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
console.error('Confirm error:', error);
|
|
174
|
+
return c.json({
|
|
175
|
+
success: false,
|
|
176
|
+
message: error instanceof Error ? error.message : 'Failed to confirm subscription',
|
|
177
|
+
}, 500);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* GET /api/newsletter/unsubscribe?token=xxx
|
|
182
|
+
* Public endpoint to show unsubscribe confirmation page
|
|
183
|
+
*/
|
|
184
|
+
export async function showUnsubscribePage(c) {
|
|
185
|
+
const token = c.req.query('token');
|
|
186
|
+
if (!token) {
|
|
187
|
+
return c.text('Missing unsubscribe token', 400);
|
|
188
|
+
}
|
|
189
|
+
// Import template function
|
|
190
|
+
const { getTemplate } = await import('../../../lib/template');
|
|
191
|
+
// Pass token as a script variable
|
|
192
|
+
const tokenScript = `const token = '${token}';`;
|
|
193
|
+
return c.html(getTemplate('unsubscribe', '', tokenScript));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* POST /api/newsletter/unsubscribe
|
|
197
|
+
* Public endpoint to unsubscribe from newsletter
|
|
198
|
+
*/
|
|
199
|
+
export async function unsubscribe(c) {
|
|
200
|
+
try {
|
|
201
|
+
const body = (await c.req.json());
|
|
202
|
+
const { token, email } = body;
|
|
203
|
+
if (!token && !email) {
|
|
204
|
+
return c.json({ success: false, message: 'Missing token or email' }, 400);
|
|
205
|
+
}
|
|
206
|
+
const db = c.env.DB;
|
|
207
|
+
let query;
|
|
208
|
+
let param;
|
|
209
|
+
if (token) {
|
|
210
|
+
query = 'SELECT id FROM subscribers WHERE unsubscribe_token = ?';
|
|
211
|
+
param = token;
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
const normalizedEmail = email.toLowerCase().trim();
|
|
215
|
+
query = 'SELECT id FROM subscribers WHERE email = ?';
|
|
216
|
+
param = normalizedEmail;
|
|
217
|
+
}
|
|
218
|
+
const subscriber = await db.prepare(query).bind(param).first();
|
|
219
|
+
if (!subscriber) {
|
|
220
|
+
return c.json({ success: false, message: 'Subscriber not found' }, 404);
|
|
221
|
+
}
|
|
222
|
+
// Soft-delete: set status to 'unsubscribed' instead of deleting
|
|
223
|
+
const now = Date.now();
|
|
224
|
+
await db
|
|
225
|
+
.prepare(`UPDATE subscribers
|
|
226
|
+
SET status = 'unsubscribed', unsubscribed_at = ?, updated_at = ?
|
|
227
|
+
WHERE id = ?`)
|
|
228
|
+
.bind(now, now, subscriber.id)
|
|
229
|
+
.run();
|
|
230
|
+
return c.json({
|
|
231
|
+
success: true,
|
|
232
|
+
message: 'You have been unsubscribed successfully',
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
console.error('Unsubscribe error:', error);
|
|
237
|
+
return c.json({
|
|
238
|
+
success: false,
|
|
239
|
+
message: error instanceof Error ? error.message : 'Failed to unsubscribe',
|
|
240
|
+
}, 500);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Context } from 'hono';
|
|
2
|
+
/**
|
|
3
|
+
* POST /api/newsletter/admin/send
|
|
4
|
+
* Send bulk email to all subscribed users (admin only)
|
|
5
|
+
*/
|
|
6
|
+
export declare function sendBulkEmail(c: Context): Promise<Response>;
|
|
7
|
+
/**
|
|
8
|
+
* POST /api/newsletter/admin/emails/test
|
|
9
|
+
* Send test email to a single email address
|
|
10
|
+
*/
|
|
11
|
+
export declare function sendTestEmail(c: Context): Promise<Response>;
|
|
12
|
+
//# sourceMappingURL=send.handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/newsletter/handlers/send.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAqE/B;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8FjE;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6DjE"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { saveSentEmail } from './emails.handler';
|
|
2
|
+
// Send email via Resend with optional inline attachments
|
|
3
|
+
async function sendEmail(to, subject, html, apiKey, from, fromName, replyTo, attachments) {
|
|
4
|
+
const payload = {
|
|
5
|
+
from: `${fromName} <${from}>`,
|
|
6
|
+
to,
|
|
7
|
+
subject,
|
|
8
|
+
html,
|
|
9
|
+
reply_to: replyTo,
|
|
10
|
+
};
|
|
11
|
+
// Add attachments if present
|
|
12
|
+
if (attachments && attachments.length > 0) {
|
|
13
|
+
payload.attachments = attachments;
|
|
14
|
+
}
|
|
15
|
+
const response = await fetch('https://api.resend.com/emails', {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
headers: {
|
|
18
|
+
Authorization: `Bearer ${apiKey}`,
|
|
19
|
+
'Content-Type': 'application/json',
|
|
20
|
+
},
|
|
21
|
+
body: JSON.stringify(payload),
|
|
22
|
+
});
|
|
23
|
+
if (!response.ok) {
|
|
24
|
+
const error = await response.text();
|
|
25
|
+
throw new Error(`Failed to send email to ${to}: ${error}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Convert EmailAttachment array to Resend attachment format
|
|
30
|
+
*/
|
|
31
|
+
function toResendAttachments(images) {
|
|
32
|
+
if (!images || images.length === 0)
|
|
33
|
+
return undefined;
|
|
34
|
+
return images.map((img) => ({
|
|
35
|
+
content: img.content,
|
|
36
|
+
filename: img.filename,
|
|
37
|
+
type: img.type,
|
|
38
|
+
disposition: 'inline',
|
|
39
|
+
id: img.id,
|
|
40
|
+
}));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* POST /api/newsletter/admin/send
|
|
44
|
+
* Send bulk email to all subscribed users (admin only)
|
|
45
|
+
*/
|
|
46
|
+
export async function sendBulkEmail(c) {
|
|
47
|
+
try {
|
|
48
|
+
const body = (await c.req.json());
|
|
49
|
+
const { subject, html, images } = body;
|
|
50
|
+
if (!subject || !html) {
|
|
51
|
+
return c.json({ success: false, message: 'Subject and HTML content are required' }, 400);
|
|
52
|
+
}
|
|
53
|
+
const db = c.env.DB;
|
|
54
|
+
const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
|
|
55
|
+
const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
|
|
56
|
+
const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
|
|
57
|
+
const replyTo = c.env.HG_NEWSLETTER_REPLY_TO;
|
|
58
|
+
if (!db || !apiKey || !fromEmail) {
|
|
59
|
+
return c.json({ success: false, message: 'Newsletter not configured' }, 500);
|
|
60
|
+
}
|
|
61
|
+
// Fetch all subscribed users
|
|
62
|
+
const result = await db.prepare('SELECT id, email, unsubscribe_token FROM subscribers WHERE status = \'subscribed\'').all();
|
|
63
|
+
const subscribers = result.results;
|
|
64
|
+
if (subscribers.length === 0) {
|
|
65
|
+
return c.json({ success: true, sent: 0, message: 'No subscribed users found' });
|
|
66
|
+
}
|
|
67
|
+
// Convert images to Resend format
|
|
68
|
+
const resendAttachments = toResendAttachments(images);
|
|
69
|
+
// Send emails to all subscribers
|
|
70
|
+
let sent = 0;
|
|
71
|
+
const errors = [];
|
|
72
|
+
for (const subscriber of subscribers) {
|
|
73
|
+
try {
|
|
74
|
+
// Append unsubscribe link to HTML
|
|
75
|
+
const unsubscribeUrl = `${c.req.url.split('/api')[0]}/api/newsletter/unsubscribe?token=${subscriber.unsubscribe_token}`;
|
|
76
|
+
const htmlWithUnsubscribe = `
|
|
77
|
+
${html}
|
|
78
|
+
<hr style="margin-top: 2rem; margin-bottom: 1rem; border: none; border-top: 1px solid #eee;">
|
|
79
|
+
<p style="font-size: 0.875rem; color: #666;">
|
|
80
|
+
<a href="${unsubscribeUrl}" style="color: #666;">Unsubscribe from this newsletter</a>
|
|
81
|
+
</p>
|
|
82
|
+
`;
|
|
83
|
+
await sendEmail(subscriber.email, subject, htmlWithUnsubscribe, apiKey, fromEmail, fromName || 'Newsletter', replyTo, resendAttachments);
|
|
84
|
+
sent++;
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
console.error(`Failed to send email to ${subscriber.email}:`, error);
|
|
88
|
+
errors.push(subscriber.email);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// Save sent email to database
|
|
92
|
+
await saveSentEmail(db, subject, html, sent);
|
|
93
|
+
if (errors.length > 0) {
|
|
94
|
+
return c.json({
|
|
95
|
+
success: true,
|
|
96
|
+
sent,
|
|
97
|
+
message: `Sent to ${sent} subscribers. Failed to send to: ${errors.join(', ')}`,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return c.json({
|
|
101
|
+
success: true,
|
|
102
|
+
sent,
|
|
103
|
+
message: `Successfully sent email to ${sent} subscriber${sent === 1 ? '' : 's'}`,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
console.error('Send bulk email error:', error);
|
|
108
|
+
return c.json({
|
|
109
|
+
success: false,
|
|
110
|
+
message: error instanceof Error ? error.message : 'Failed to send emails',
|
|
111
|
+
}, 500);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* POST /api/newsletter/admin/emails/test
|
|
116
|
+
* Send test email to a single email address
|
|
117
|
+
*/
|
|
118
|
+
export async function sendTestEmail(c) {
|
|
119
|
+
try {
|
|
120
|
+
const body = (await c.req.json());
|
|
121
|
+
const { subject, html, testEmail, images } = body;
|
|
122
|
+
if (!subject || !html || !testEmail) {
|
|
123
|
+
return c.json({ success: false, message: 'Subject, HTML content, and test email are required' }, 400);
|
|
124
|
+
}
|
|
125
|
+
// Validate email
|
|
126
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
127
|
+
if (!emailRegex.test(testEmail)) {
|
|
128
|
+
return c.json({ success: false, message: 'Invalid test email address' }, 400);
|
|
129
|
+
}
|
|
130
|
+
const apiKey = c.env.HG_NEWSLETTER_EMAIL_API_KEY;
|
|
131
|
+
const fromEmail = c.env.HG_NEWSLETTER_FROM_EMAIL;
|
|
132
|
+
const fromName = c.env.HG_NEWSLETTER_FROM_NAME;
|
|
133
|
+
const replyTo = c.env.HG_NEWSLETTER_REPLY_TO;
|
|
134
|
+
if (!apiKey || !fromEmail) {
|
|
135
|
+
return c.json({ success: false, message: 'Newsletter not configured' }, 500);
|
|
136
|
+
}
|
|
137
|
+
// Convert images to Resend format
|
|
138
|
+
const resendAttachments = toResendAttachments(images);
|
|
139
|
+
// Send test email with attachments
|
|
140
|
+
await sendEmail(testEmail, subject, html, apiKey, fromEmail, fromName || 'Newsletter', replyTo, resendAttachments);
|
|
141
|
+
return c.json({
|
|
142
|
+
success: true,
|
|
143
|
+
message: `Test email sent to ${testEmail}`,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
console.error('Send test email error:', error);
|
|
148
|
+
return c.json({
|
|
149
|
+
success: false,
|
|
150
|
+
message: error instanceof Error ? error.message : 'Failed to send test email',
|
|
151
|
+
}, 500);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Context } from 'hono';
|
|
2
|
+
/**
|
|
3
|
+
* GET /api/newsletter/admin/subscribers
|
|
4
|
+
* Get all subscribers (admin only)
|
|
5
|
+
*/
|
|
6
|
+
export declare function getSubscribers(c: Context): Promise<Response>;
|
|
7
|
+
/**
|
|
8
|
+
* POST /api/newsletter/admin/subscribers
|
|
9
|
+
* Manually add subscriber (admin only, bypasses confirmation)
|
|
10
|
+
*/
|
|
11
|
+
export declare function addSubscriber(c: Context): Promise<Response>;
|
|
12
|
+
/**
|
|
13
|
+
* DELETE /api/newsletter/admin/subscribers/:id
|
|
14
|
+
* Delete subscriber by ID (admin only)
|
|
15
|
+
*/
|
|
16
|
+
export declare function deleteSubscriber(c: Context): Promise<Response>;
|
|
17
|
+
/**
|
|
18
|
+
* PATCH /api/newsletter/admin/subscribers/:id
|
|
19
|
+
* Update subscriber (admin only)
|
|
20
|
+
*/
|
|
21
|
+
export declare function updateSubscriber(c: Context): Promise<Response>;
|
|
22
|
+
//# sourceMappingURL=subscribers.handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscribers.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/newsletter/handlers/subscribers.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAwC/B;;;GAGG;AACH,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmBlE;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6DjE;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+BpE;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4EpE"}
|