@hintergrund/worker 0.3.6 → 0.3.8
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/setup.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/setup.handler.js +15 -23
- package/dist/api/cms/handlers/website-repo.handler.d.ts +7 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +45 -62
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +3 -2
- package/dist/api/emails/handlers/campaigns.handler.d.ts +6 -12
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +42 -132
- package/dist/api/emails/handlers/invoice.handler.d.ts +2 -2
- package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/invoice.handler.js +3 -2
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +5 -9
- package/dist/api/emails/handlers/settings.handler.d.ts +5 -46
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +12 -40
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +3 -11
- package/dist/api/shop/handlers/products.handler.d.ts +1 -38
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/products.handler.js +8 -243
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +16 -23
- package/dist/api/shop/routes.d.ts.map +1 -1
- package/dist/api/shop/routes.js +0 -10
- package/dist/lib/github.d.ts +19 -3
- package/dist/lib/github.d.ts.map +1 -1
- package/dist/lib/github.js +39 -6
- package/dist/lib/invoice.js +3 -3
- package/dist/lib/project-db.d.ts +1 -1
- package/dist/lib/project-db.d.ts.map +1 -1
- package/dist/lib/project-db.js +5 -9
- package/dist/lib/website-i18n.d.ts +1 -1
- package/dist/lib/website-i18n.d.ts.map +1 -1
- package/dist/lib/website-i18n.js +8 -11
- package/package.json +2 -2
|
@@ -4,13 +4,11 @@
|
|
|
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 {
|
|
8
|
-
import { DEFAULT_SUBSCRIPTION_TEMPLATES } from '@hintergrund/runtime-contracts';
|
|
7
|
+
import { readEmailTemplateData, readEmailTemplates } from './settings.handler';
|
|
9
8
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
10
9
|
/** POST /api/email/subscribe */
|
|
11
10
|
export async function subscribe(c) {
|
|
12
11
|
try {
|
|
13
|
-
const { settings } = await readEmailSettings(c.env);
|
|
14
12
|
const body = await c.req.json();
|
|
15
13
|
if (!body.email)
|
|
16
14
|
return c.json({ success: false, message: 'Email is required' }, 400);
|
|
@@ -56,14 +54,13 @@ async function sendConfirmation(c, email, token) {
|
|
|
56
54
|
const origin = new URL(c.req.url).origin;
|
|
57
55
|
const confirmUrl = `${origin}/emails/confirm?token=${token}`;
|
|
58
56
|
try {
|
|
59
|
-
const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
|
|
60
|
-
const
|
|
61
|
-
const bodyHtml = (automation?.confirmation?.bodyHtml || DEFAULT_SUBSCRIPTION_TEMPLATES.confirmation.bodyHtml).replaceAll('{{confirm_url}}', confirmUrl);
|
|
57
|
+
const [{ settings, logoDataUrl }, { confirmation }] = await Promise.all([readEmailTemplateData(c.env), readEmailTemplates(c.env)]);
|
|
58
|
+
const bodyHtml = confirmation.bodyHtml.replaceAll('{{confirm_url}}', confirmUrl);
|
|
62
59
|
const html = renderEmailTemplate({
|
|
63
60
|
bodyHtml,
|
|
64
61
|
template: settings.emailTemplate, logoDataUrl,
|
|
65
62
|
});
|
|
66
|
-
await sendEmail(c.env, { to: email, subject:
|
|
63
|
+
await sendEmail(c.env, { to: email, subject: confirmation.subject, html });
|
|
67
64
|
}
|
|
68
65
|
catch (err) {
|
|
69
66
|
console.error('Failed to send confirmation email:', err);
|
|
@@ -85,12 +82,11 @@ export async function confirm(c) {
|
|
|
85
82
|
if (!subscriber) {
|
|
86
83
|
return c.json({ success: false, message: 'Invalid or expired confirmation token' }, 400);
|
|
87
84
|
}
|
|
88
|
-
const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
|
|
85
|
+
const [{ settings, logoDataUrl }, { welcome }] = await Promise.all([readEmailTemplateData(c.env), readEmailTemplates(c.env)]);
|
|
89
86
|
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();
|
|
90
87
|
// Only the request that consumes the token sends a welcome. Confirmation stays
|
|
91
88
|
// successful if the provider fails; never undo consent or send it twice on refresh.
|
|
92
89
|
if (result.meta.changes > 0) {
|
|
93
|
-
const welcome = settings.automation?.welcome ?? DEFAULT_SUBSCRIPTION_TEMPLATES.welcome;
|
|
94
90
|
try {
|
|
95
91
|
await sendEmail(c.env, {
|
|
96
92
|
to: subscriber.email,
|
|
@@ -1,60 +1,21 @@
|
|
|
1
|
-
import type { Context } from 'hono';
|
|
2
1
|
import type { Bindings } from '../../../index';
|
|
3
2
|
import { type GitHubClient } from '../../../lib/github';
|
|
4
|
-
import {
|
|
5
|
-
export { EMAIL_SETTINGS_PATH };
|
|
6
|
-
export declare const DEFAULT_INVOICE: InvoiceConfig;
|
|
7
|
-
export declare const DEFAULT_EMAIL_SETTINGS: EmailSettings;
|
|
3
|
+
import { type BusinessDetails, type EmailTemplates } from '@hintergrund/runtime-contracts';
|
|
8
4
|
/** Reads the letterhead chosen in email settings and inlines it, as mail clients need a data URL. */
|
|
9
5
|
export declare function resolveLogoDataUrl(github: GitHubClient, logoPath: string | undefined): Promise<string | undefined>;
|
|
10
6
|
export declare function readEmailSettings(env: Bindings): Promise<{
|
|
11
7
|
settings: {
|
|
12
|
-
invoice: {
|
|
13
|
-
companyName?: string;
|
|
14
|
-
companyAddress?: string;
|
|
15
|
-
companyEmail?: string;
|
|
16
|
-
companyPhone?: string;
|
|
17
|
-
dueDays?: number;
|
|
18
|
-
};
|
|
19
8
|
emailTemplate: import("@hintergrund/runtime-contracts").EmailTemplateConfig;
|
|
20
|
-
automation?: {
|
|
21
|
-
confirmation?: {
|
|
22
|
-
subject: string;
|
|
23
|
-
bodyHtml: string;
|
|
24
|
-
};
|
|
25
|
-
welcome?: {
|
|
26
|
-
subject: string;
|
|
27
|
-
bodyHtml: string;
|
|
28
|
-
};
|
|
29
|
-
};
|
|
30
9
|
footerHtml?: string;
|
|
31
10
|
logoPath?: string;
|
|
32
11
|
fromEmail?: string;
|
|
33
12
|
fromName?: string;
|
|
34
13
|
replyTo?: string;
|
|
35
14
|
};
|
|
36
|
-
commitSha: string;
|
|
37
15
|
}>;
|
|
38
16
|
export declare function readEmailTemplateData(env: Bindings): Promise<{
|
|
39
17
|
settings: {
|
|
40
|
-
invoice: {
|
|
41
|
-
companyName?: string;
|
|
42
|
-
companyAddress?: string;
|
|
43
|
-
companyEmail?: string;
|
|
44
|
-
companyPhone?: string;
|
|
45
|
-
dueDays?: number;
|
|
46
|
-
};
|
|
47
18
|
emailTemplate: import("@hintergrund/runtime-contracts").EmailTemplateConfig;
|
|
48
|
-
automation?: {
|
|
49
|
-
confirmation?: {
|
|
50
|
-
subject: string;
|
|
51
|
-
bodyHtml: string;
|
|
52
|
-
};
|
|
53
|
-
welcome?: {
|
|
54
|
-
subject: string;
|
|
55
|
-
bodyHtml: string;
|
|
56
|
-
};
|
|
57
|
-
};
|
|
58
19
|
footerHtml?: string;
|
|
59
20
|
logoPath?: string;
|
|
60
21
|
fromEmail?: string;
|
|
@@ -63,10 +24,8 @@ export declare function readEmailTemplateData(env: Bindings): Promise<{
|
|
|
63
24
|
};
|
|
64
25
|
logoDataUrl: string | undefined;
|
|
65
26
|
}>;
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
export declare function
|
|
70
|
-
Bindings: Bindings;
|
|
71
|
-
}>): Promise<Response>;
|
|
27
|
+
/** The copy of every automated email; a missing message falls back to the default. */
|
|
28
|
+
export declare function readEmailTemplates(env: Bindings): Promise<EmailTemplates>;
|
|
29
|
+
/** The business behind the site, as the imprint shows it. */
|
|
30
|
+
export declare function readBusinessDetails(env: Bindings): Promise<BusinessDetails>;
|
|
72
31
|
//# sourceMappingURL=settings.handler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/settings.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"settings.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/settings.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,OAAO,EAAsB,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAE5E,OAAO,EAAmH,KAAK,eAAe,EAAsB,KAAK,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAGhO,qGAAqG;AACrG,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAKxH;AACD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ;;;;;;;;;GAKpD;AACD,wBAAsB,qBAAqB,CAAC,GAAG,EAAE,QAAQ;;;;;;;;;;GAIxD;AACD,sFAAsF;AACtF,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,cAAc,CAAC,CAG/E;AACD,6DAA6D;AAC7D,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,eAAe,CAAC,CAGjF"}
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import { getGitHubConfig } from '../../../lib/config';
|
|
2
2
|
import { createGitHubClient } from '../../../lib/github';
|
|
3
|
-
import { readJsonConfig
|
|
4
|
-
import { EMAIL_SETTINGS_PATH, emailTemplateFromDesign } from '@hintergrund/runtime-contracts';
|
|
3
|
+
import { readJsonConfig } from '../../../lib/github-config';
|
|
4
|
+
import { EMAIL_SETTINGS_PATH, EMAIL_TEMPLATES_PATH, LEGAL_CONTENT_PATH, emailTemplateFromDesign, normalizeEmailTemplates } from '@hintergrund/runtime-contracts';
|
|
5
5
|
import { readDesign } from '../../../lib/design';
|
|
6
|
-
export { EMAIL_SETTINGS_PATH };
|
|
7
|
-
export const DEFAULT_INVOICE = { companyName: '', companyAddress: '', companyEmail: '', companyPhone: '', dueDays: 14 };
|
|
8
|
-
export const DEFAULT_EMAIL_SETTINGS = { invoice: DEFAULT_INVOICE };
|
|
9
6
|
/** Reads the letterhead chosen in email settings and inlines it, as mail clients need a data URL. */
|
|
10
7
|
export async function resolveLogoDataUrl(github, logoPath) {
|
|
11
8
|
if (!logoPath)
|
|
@@ -17,47 +14,22 @@ export async function resolveLogoDataUrl(github, logoPath) {
|
|
|
17
14
|
}
|
|
18
15
|
export async function readEmailSettings(env) {
|
|
19
16
|
const github = createGitHubClient(getGitHubConfig(env));
|
|
20
|
-
const { data
|
|
17
|
+
const { data } = await readJsonConfig(github, EMAIL_SETTINGS_PATH, {});
|
|
21
18
|
const design = await readDesign(env);
|
|
22
|
-
return { settings: { ...data,
|
|
23
|
-
emailTemplate: emailTemplateFromDesign(design, data.footerHtml) }, commitSha };
|
|
19
|
+
return { settings: { ...data, emailTemplate: emailTemplateFromDesign(design, data.footerHtml) } };
|
|
24
20
|
}
|
|
25
21
|
export async function readEmailTemplateData(env) {
|
|
26
22
|
const { settings } = await readEmailSettings(env);
|
|
27
23
|
const logoDataUrl = await resolveLogoDataUrl(createGitHubClient(getGitHubConfig(env)), settings.logoPath);
|
|
28
24
|
return { settings, logoDataUrl };
|
|
29
25
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
return c.json({ settings, commitSha, logoDataUrl });
|
|
35
|
-
}
|
|
36
|
-
catch (error) {
|
|
37
|
-
console.error('Read email settings:', error);
|
|
38
|
-
return c.json({ error: 'Could not load email settings.' }, 500);
|
|
39
|
-
}
|
|
26
|
+
/** The copy of every automated email; a missing message falls back to the default. */
|
|
27
|
+
export async function readEmailTemplates(env) {
|
|
28
|
+
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), EMAIL_TEMPLATES_PATH, {});
|
|
29
|
+
return normalizeEmailTemplates(data);
|
|
40
30
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const { data: current } = await readJsonConfig(github, EMAIL_SETTINGS_PATH, DEFAULT_EMAIL_SETTINGS);
|
|
46
|
-
const next = { ...current, invoice: { ...DEFAULT_INVOICE, ...current.invoice, ...body.invoice } };
|
|
47
|
-
for (const key of ['fromEmail', 'fromName', 'replyTo', 'footerHtml']) {
|
|
48
|
-
if (body[key] !== undefined) {
|
|
49
|
-
if (typeof body[key] !== 'string')
|
|
50
|
-
return c.json({ error: `Invalid ${key}.` }, 400);
|
|
51
|
-
next[key] = body[key];
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
const commitSha = await writeJsonConfig(github, EMAIL_SETTINGS_PATH, next, 'Update email settings [skip ci]', body.commitSha);
|
|
55
|
-
return c.json({ success: true, settings: next, commitSha });
|
|
56
|
-
}
|
|
57
|
-
catch (error) {
|
|
58
|
-
if (error instanceof ConfigConflictError)
|
|
59
|
-
return c.json({ error: error.message, code: 'conflict' }, 409);
|
|
60
|
-
console.error('Save email settings:', error);
|
|
61
|
-
return c.json({ error: 'Could not save email settings.' }, 500);
|
|
62
|
-
}
|
|
31
|
+
/** The business behind the site, as the imprint shows it. */
|
|
32
|
+
export async function readBusinessDetails(env) {
|
|
33
|
+
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), LEGAL_CONTENT_PATH, {});
|
|
34
|
+
return data;
|
|
63
35
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/admin.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"admin.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/admin.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAoB5B,QAAA,MAAM,WAAW,4EAAa,CAAC;AA8B/B,eAAe,WAAW,CAAC"}
|
|
@@ -7,11 +7,9 @@ import { authMiddleware } from '../../../middleware/auth';
|
|
|
7
7
|
// Subscribers
|
|
8
8
|
import { getSubscribers, createSubscriber, updateSubscriber, deleteSubscriber, } from '../handlers/subscribers.handler';
|
|
9
9
|
// Campaigns
|
|
10
|
-
import { getCampaigns,
|
|
10
|
+
import { getCampaigns, sendCampaign, testCampaign } from '../handlers/campaigns.handler';
|
|
11
11
|
// Transactional send
|
|
12
12
|
import { sendTransactional, sendBulkEmail } from '../handlers/send.handler';
|
|
13
|
-
// Settings (generated email template + invoice)
|
|
14
|
-
import { getSettings, saveSettings } from '../handlers/settings.handler';
|
|
15
13
|
import { previewInvoice } from '../../../lib/invoice';
|
|
16
14
|
const adminRoutes = new Hono();
|
|
17
15
|
adminRoutes.use('*', authMiddleware);
|
|
@@ -26,21 +24,15 @@ adminRoutes.delete('/subscribers/:id', deleteSubscriber);
|
|
|
26
24
|
// Campaigns
|
|
27
25
|
// =============================================================================
|
|
28
26
|
adminRoutes.get('/campaigns', getCampaigns);
|
|
29
|
-
adminRoutes.
|
|
30
|
-
adminRoutes.post('/campaigns', createCampaign);
|
|
31
|
-
adminRoutes.patch('/campaigns/:id', updateCampaign);
|
|
32
|
-
adminRoutes.delete('/campaigns/:id', deleteCampaign);
|
|
27
|
+
adminRoutes.post('/campaigns/test', testCampaign);
|
|
33
28
|
adminRoutes.post('/campaigns/:id/send', sendCampaign);
|
|
34
|
-
adminRoutes.post('/campaigns/:id/test', testCampaign);
|
|
35
29
|
// =============================================================================
|
|
36
30
|
// Transactional send
|
|
37
31
|
// =============================================================================
|
|
38
32
|
adminRoutes.post('/send', sendTransactional);
|
|
39
33
|
adminRoutes.post('/send/bulk', sendBulkEmail);
|
|
40
34
|
// =============================================================================
|
|
41
|
-
//
|
|
35
|
+
// Invoice preview
|
|
42
36
|
// =============================================================================
|
|
43
37
|
adminRoutes.post('/invoices/preview', bodyLimit({ maxSize: 8 * 1024 * 1024 }), previewInvoice);
|
|
44
|
-
adminRoutes.get('/settings', getSettings);
|
|
45
|
-
adminRoutes.put('/settings', saveSettings);
|
|
46
38
|
export default adminRoutes;
|
|
@@ -1,47 +1,10 @@
|
|
|
1
|
-
import type { Context } from 'hono';
|
|
2
1
|
import type { Bindings } from '../../../index';
|
|
3
2
|
import type { ShopCatalog, ShopSettings } from '@hintergrund/runtime-contracts';
|
|
4
|
-
|
|
5
|
-
export { SHOP_PRODUCTS_PATH, SHOP_SETTINGS_PATH };
|
|
6
|
-
export declare const DEFAULT_SHOP_SETTINGS: ShopSettings & {
|
|
7
|
-
emailTemplates: {
|
|
8
|
-
purchase: {
|
|
9
|
-
subject: string;
|
|
10
|
-
bodyHtml: string;
|
|
11
|
-
};
|
|
12
|
-
paymentConfirmed: {
|
|
13
|
-
subject: string;
|
|
14
|
-
bodyHtml: string;
|
|
15
|
-
};
|
|
16
|
-
};
|
|
17
|
-
};
|
|
3
|
+
export declare const DEFAULT_SHOP_SETTINGS: ShopSettings;
|
|
18
4
|
export declare function readShopCatalog(env: Bindings): Promise<{
|
|
19
5
|
catalog: ShopCatalog;
|
|
20
|
-
commitSha: string;
|
|
21
6
|
}>;
|
|
22
7
|
export declare function readShopSettings(env: Bindings): Promise<{
|
|
23
8
|
settings: ShopSettings;
|
|
24
|
-
commitSha: string;
|
|
25
9
|
}>;
|
|
26
|
-
export declare function getProducts(c: Context<{
|
|
27
|
-
Bindings: Bindings;
|
|
28
|
-
}>): Promise<Response>;
|
|
29
|
-
export declare function getProduct(c: Context<{
|
|
30
|
-
Bindings: Bindings;
|
|
31
|
-
}>): Promise<Response>;
|
|
32
|
-
export declare function createProduct(c: Context<{
|
|
33
|
-
Bindings: Bindings;
|
|
34
|
-
}>): Promise<Response>;
|
|
35
|
-
export declare function updateProduct(c: Context<{
|
|
36
|
-
Bindings: Bindings;
|
|
37
|
-
}>): Promise<Response>;
|
|
38
|
-
export declare function deleteProduct(c: Context<{
|
|
39
|
-
Bindings: Bindings;
|
|
40
|
-
}>): Promise<Response>;
|
|
41
|
-
export declare function getSettings(c: Context<{
|
|
42
|
-
Bindings: Bindings;
|
|
43
|
-
}>): Promise<Response>;
|
|
44
|
-
export declare function updateSettings(c: Context<{
|
|
45
|
-
Bindings: Bindings;
|
|
46
|
-
}>): Promise<Response>;
|
|
47
10
|
//# sourceMappingURL=products.handler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"products.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/products.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"products.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/products.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAI/C,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAMhF,eAAO,MAAM,qBAAqB,EAAE,YAcnC,CAAC;AAEF,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,WAAW,CAAA;CAAE,CAAC,CAGtF;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,YAAY,CAAA;CAAE,CAAC,CAKzF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { getGitHubConfig } from '../../../lib/config';
|
|
2
|
-
import { translateWebsiteFiles } from '../../../lib/website-i18n';
|
|
3
2
|
import { createGitHubClient } from '../../../lib/github';
|
|
4
|
-
import {
|
|
3
|
+
import { readJsonConfig } from '../../../lib/github-config';
|
|
5
4
|
import { SHOP_PRODUCTS_PATH, SHOP_SETTINGS_PATH } from '@hintergrund/runtime-contracts';
|
|
6
|
-
|
|
5
|
+
// The catalog and shop settings are authored in the admin working copy and published
|
|
6
|
+
// with the website; the Worker only reads them.
|
|
7
7
|
export const DEFAULT_SHOP_SETTINGS = {
|
|
8
8
|
currency: 'eur',
|
|
9
9
|
enabledPaymentMethods: ['bank_transfer'],
|
|
@@ -18,249 +18,14 @@ export const DEFAULT_SHOP_SETTINGS = {
|
|
|
18
18
|
freeShippingThreshold: 0,
|
|
19
19
|
orderNumberPrefix: 'ORD',
|
|
20
20
|
invoiceNumberPrefix: 'INV',
|
|
21
|
-
emailTemplates: {
|
|
22
|
-
purchase: {
|
|
23
|
-
subject: 'Your order {{order_number}}',
|
|
24
|
-
bodyHtml: '<h2>Thank you for your order.</h2><p>Please find your invoice and payment instructions below.</p>'
|
|
25
|
-
},
|
|
26
|
-
paymentConfirmed: {
|
|
27
|
-
subject: 'Payment confirmed - {{order_number}}',
|
|
28
|
-
bodyHtml: '<h2>Payment confirmed</h2><p>We have received your payment of {{amount}} for order {{order_number}}. Thank you.</p>'
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
21
|
};
|
|
32
|
-
function getGitHub(c) {
|
|
33
|
-
return createGitHubClient(getGitHubConfig(c.env));
|
|
34
|
-
}
|
|
35
|
-
function nowSeconds() {
|
|
36
|
-
return Math.floor(Date.now() / 1000);
|
|
37
|
-
}
|
|
38
|
-
function slugify(value) {
|
|
39
|
-
return value
|
|
40
|
-
.toLowerCase()
|
|
41
|
-
.trim()
|
|
42
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
43
|
-
.replace(/^-+|-+$/g, '') || `product-${Date.now()}`;
|
|
44
|
-
}
|
|
45
|
-
function createId(prefix) {
|
|
46
|
-
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
47
|
-
}
|
|
48
|
-
async function readCatalog(github) {
|
|
49
|
-
const result = await github.readJsonFile(SHOP_PRODUCTS_PATH);
|
|
50
|
-
return {
|
|
51
|
-
catalog: result?.data ?? { products: [], updatedAt: Date.now() },
|
|
52
|
-
commitSha: await github.getCommitSha(),
|
|
53
|
-
fileSha: result?.sha
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
22
|
export async function readShopCatalog(env) {
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
return { catalog, commitSha };
|
|
23
|
+
const result = await createGitHubClient(getGitHubConfig(env)).readJsonFile(SHOP_PRODUCTS_PATH);
|
|
24
|
+
return { catalog: result?.data ?? { products: [] } };
|
|
60
25
|
}
|
|
61
26
|
export async function readShopSettings(env) {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
mergeNested: (raw, defaults) => ({
|
|
65
|
-
bankTransfer: { ...defaults.bankTransfer, ...(raw.bankTransfer ?? {}) },
|
|
66
|
-
shippingFlatRate: raw.shippingFlatRate ?? defaults.shippingFlatRate,
|
|
67
|
-
freeShippingThreshold: raw.freeShippingThreshold ?? defaults.freeShippingThreshold,
|
|
68
|
-
emailTemplates: {
|
|
69
|
-
purchase: { ...DEFAULT_SHOP_SETTINGS.emailTemplates.purchase, ...(raw.emailTemplates?.purchase ?? {}) },
|
|
70
|
-
paymentConfirmed: { ...DEFAULT_SHOP_SETTINGS.emailTemplates.paymentConfirmed, ...(raw.emailTemplates?.paymentConfirmed ?? {}) },
|
|
71
|
-
},
|
|
72
|
-
}),
|
|
27
|
+
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), SHOP_SETTINGS_PATH, DEFAULT_SHOP_SETTINGS, {
|
|
28
|
+
mergeNested: (raw, defaults) => ({ bankTransfer: { ...defaults.bankTransfer, ...(raw.bankTransfer ?? {}) } }),
|
|
73
29
|
});
|
|
74
|
-
return { settings: data
|
|
75
|
-
}
|
|
76
|
-
async function writeCatalog(github, catalog, message, expectedCommitSha, env) {
|
|
77
|
-
if (expectedCommitSha && !(await github.checkNoConflict(expectedCommitSha))) {
|
|
78
|
-
const error = new Error('Catalog changed upstream. Reload before publishing.');
|
|
79
|
-
error.status = 409;
|
|
80
|
-
throw error;
|
|
81
|
-
}
|
|
82
|
-
catalog.updatedAt = Date.now();
|
|
83
|
-
const revision = expectedCommitSha || await github.getCommitSha();
|
|
84
|
-
let files;
|
|
85
|
-
try {
|
|
86
|
-
files = await translateWebsiteFiles(github, [{ path: SHOP_PRODUCTS_PATH, content: JSON.stringify(catalog, null, 2) }], env, revision);
|
|
87
|
-
}
|
|
88
|
-
catch (error) {
|
|
89
|
-
// The catalog write has not happened: surface the cause as retryable, like website saves.
|
|
90
|
-
error.status = 422;
|
|
91
|
-
throw error;
|
|
92
|
-
}
|
|
93
|
-
return github.writeFilesAtomic(files, message, revision);
|
|
94
|
-
}
|
|
95
|
-
function normalizeProduct(body, existing) {
|
|
96
|
-
const timestamp = nowSeconds();
|
|
97
|
-
const name = body.name?.trim() || existing?.name || 'Untitled product';
|
|
98
|
-
const id = existing?.id ?? createId('prod');
|
|
99
|
-
return {
|
|
100
|
-
id,
|
|
101
|
-
slug: body.slug?.trim() || existing?.slug || slugify(name),
|
|
102
|
-
name,
|
|
103
|
-
description: body.description ?? existing?.description ?? '',
|
|
104
|
-
active: body.active ?? existing?.active ?? true,
|
|
105
|
-
images: body.images ?? existing?.images ?? [],
|
|
106
|
-
prices: (body.prices ?? existing?.prices ?? []).map((price) => ({
|
|
107
|
-
...price,
|
|
108
|
-
id: price.id || createId('price'),
|
|
109
|
-
label: price.label || 'Standard',
|
|
110
|
-
currency: price.currency.toLowerCase(),
|
|
111
|
-
unitAmount: Math.round(price.unitAmount),
|
|
112
|
-
active: price.active ?? true
|
|
113
|
-
})),
|
|
114
|
-
metadata: body.metadata ?? existing?.metadata ?? {},
|
|
115
|
-
createdAt: existing?.createdAt ?? timestamp,
|
|
116
|
-
updatedAt: timestamp
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
function conflictResponse(c, error) {
|
|
120
|
-
if (error?.status === 422) {
|
|
121
|
-
return c.json({ success: false, error: error.message }, 422);
|
|
122
|
-
}
|
|
123
|
-
if (error?.status !== 409)
|
|
124
|
-
return null;
|
|
125
|
-
return c.json({ success: false, error: error.message, code: 'conflict' }, 409);
|
|
126
|
-
}
|
|
127
|
-
export async function getProducts(c) {
|
|
128
|
-
try {
|
|
129
|
-
const active = c.req.query('active');
|
|
130
|
-
const { catalog, commitSha } = await readCatalog(getGitHub(c));
|
|
131
|
-
const products = active === undefined ? catalog.products : catalog.products.filter((product) => product.active === (active === 'true'));
|
|
132
|
-
const response = { products, hasMore: false, commitSha };
|
|
133
|
-
return c.json(response);
|
|
134
|
-
}
|
|
135
|
-
catch (error) {
|
|
136
|
-
console.error('Failed to fetch products:', error);
|
|
137
|
-
return c.json({ success: false, error: 'Failed to fetch products' }, 500);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
export async function getProduct(c) {
|
|
141
|
-
try {
|
|
142
|
-
const productId = c.req.param('id');
|
|
143
|
-
const { catalog, commitSha } = await readCatalog(getGitHub(c));
|
|
144
|
-
const product = catalog.products.find((item) => item.id === productId || item.slug === productId);
|
|
145
|
-
if (!product)
|
|
146
|
-
return c.json({ success: false, error: 'Product not found' }, 404);
|
|
147
|
-
const response = { product, commitSha };
|
|
148
|
-
return c.json(response);
|
|
149
|
-
}
|
|
150
|
-
catch (error) {
|
|
151
|
-
console.error('Failed to fetch product:', error);
|
|
152
|
-
return c.json({ success: false, error: 'Failed to fetch product' }, 500);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
export async function createProduct(c) {
|
|
156
|
-
try {
|
|
157
|
-
const github = getGitHub(c);
|
|
158
|
-
const body = await c.req.json();
|
|
159
|
-
const { catalog } = await readCatalog(github);
|
|
160
|
-
const product = normalizeProduct(body);
|
|
161
|
-
if (catalog.products.some((item) => item.id === product.id || item.slug === product.slug)) {
|
|
162
|
-
return c.json({ success: false, error: 'Product id or slug already exists' }, 409);
|
|
163
|
-
}
|
|
164
|
-
catalog.products = [product, ...catalog.products];
|
|
165
|
-
const commitSha = await writeCatalog(github, catalog, `Create shop product ${product.name} [skip ci]`, body.commitSha, c.env);
|
|
166
|
-
const response = { success: true, product, commitSha };
|
|
167
|
-
return c.json(response, 201);
|
|
168
|
-
}
|
|
169
|
-
catch (error) {
|
|
170
|
-
const conflict = conflictResponse(c, error);
|
|
171
|
-
if (conflict)
|
|
172
|
-
return conflict;
|
|
173
|
-
console.error('Failed to create product:', error);
|
|
174
|
-
return c.json({ success: false, error: 'Failed to create product' }, 500);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
export async function updateProduct(c) {
|
|
178
|
-
try {
|
|
179
|
-
const github = getGitHub(c);
|
|
180
|
-
const productId = c.req.param('id');
|
|
181
|
-
const body = await c.req.json();
|
|
182
|
-
const { catalog } = await readCatalog(github);
|
|
183
|
-
const index = catalog.products.findIndex((item) => item.id === productId || item.slug === productId);
|
|
184
|
-
if (index === -1)
|
|
185
|
-
return c.json({ success: false, error: 'Product not found' }, 404);
|
|
186
|
-
const product = normalizeProduct(body, catalog.products[index]);
|
|
187
|
-
const duplicate = catalog.products.find((item, itemIndex) => itemIndex !== index && item.slug === product.slug);
|
|
188
|
-
if (duplicate)
|
|
189
|
-
return c.json({ success: false, error: 'Product slug already exists' }, 409);
|
|
190
|
-
catalog.products[index] = product;
|
|
191
|
-
const commitSha = await writeCatalog(github, catalog, `Update shop product ${product.name} [skip ci]`, body.commitSha, c.env);
|
|
192
|
-
const response = { success: true, product, commitSha };
|
|
193
|
-
return c.json(response);
|
|
194
|
-
}
|
|
195
|
-
catch (error) {
|
|
196
|
-
const conflict = conflictResponse(c, error);
|
|
197
|
-
if (conflict)
|
|
198
|
-
return conflict;
|
|
199
|
-
console.error('Failed to update product:', error);
|
|
200
|
-
return c.json({ success: false, error: 'Failed to update product' }, 500);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
export async function deleteProduct(c) {
|
|
204
|
-
try {
|
|
205
|
-
const github = getGitHub(c);
|
|
206
|
-
const productId = c.req.param('id');
|
|
207
|
-
const commitShaParam = c.req.query('commitSha');
|
|
208
|
-
const { catalog } = await readCatalog(github);
|
|
209
|
-
const before = catalog.products.length;
|
|
210
|
-
catalog.products = catalog.products.filter((item) => item.id !== productId && item.slug !== productId);
|
|
211
|
-
if (catalog.products.length === before)
|
|
212
|
-
return c.json({ success: false, error: 'Product not found' }, 404);
|
|
213
|
-
const commitSha = await writeCatalog(github, catalog, `Delete shop product ${productId} [skip ci]`, commitShaParam, c.env);
|
|
214
|
-
const response = { success: true, message: 'Product deleted', commitSha };
|
|
215
|
-
return c.json(response);
|
|
216
|
-
}
|
|
217
|
-
catch (error) {
|
|
218
|
-
const conflict = conflictResponse(c, error);
|
|
219
|
-
if (conflict)
|
|
220
|
-
return conflict;
|
|
221
|
-
console.error('Failed to delete product:', error);
|
|
222
|
-
return c.json({ success: false, error: 'Failed to delete product' }, 500);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
export async function getSettings(c) {
|
|
226
|
-
try {
|
|
227
|
-
const { settings, commitSha } = await readShopSettings(c.env);
|
|
228
|
-
const response = {
|
|
229
|
-
settings,
|
|
230
|
-
commitSha,
|
|
231
|
-
stripeConfigured: !!c.env.STRIPE_SECRET_KEY
|
|
232
|
-
};
|
|
233
|
-
return c.json(response);
|
|
234
|
-
}
|
|
235
|
-
catch (error) {
|
|
236
|
-
console.error('Failed to fetch shop settings:', error);
|
|
237
|
-
return c.json({ success: false, error: 'Failed to fetch shop settings' }, 500);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
export async function updateSettings(c) {
|
|
241
|
-
try {
|
|
242
|
-
const github = getGitHub(c);
|
|
243
|
-
const body = await c.req.json();
|
|
244
|
-
const settings = {
|
|
245
|
-
...DEFAULT_SHOP_SETTINGS,
|
|
246
|
-
...body.settings,
|
|
247
|
-
bankTransfer: { ...DEFAULT_SHOP_SETTINGS.bankTransfer, ...body.settings.bankTransfer },
|
|
248
|
-
shippingFlatRate: body.settings.shippingFlatRate ?? 0,
|
|
249
|
-
freeShippingThreshold: body.settings.freeShippingThreshold ?? 0,
|
|
250
|
-
emailTemplates: {
|
|
251
|
-
purchase: { ...DEFAULT_SHOP_SETTINGS.emailTemplates.purchase, ...(body.settings.emailTemplates?.purchase ?? {}) },
|
|
252
|
-
paymentConfirmed: { ...DEFAULT_SHOP_SETTINGS.emailTemplates.paymentConfirmed, ...(body.settings.emailTemplates?.paymentConfirmed ?? {}) },
|
|
253
|
-
},
|
|
254
|
-
};
|
|
255
|
-
const commitSha = await writeJsonConfig(github, SHOP_SETTINGS_PATH, settings, 'Update shop settings [skip ci]', body.commitSha);
|
|
256
|
-
const response = { success: true, settings, commitSha };
|
|
257
|
-
return c.json(response);
|
|
258
|
-
}
|
|
259
|
-
catch (error) {
|
|
260
|
-
if (error instanceof ConfigConflictError) {
|
|
261
|
-
return c.json({ success: false, error: error.message, code: 'conflict' }, 409);
|
|
262
|
-
}
|
|
263
|
-
console.error('Failed to update shop settings:', error);
|
|
264
|
-
return c.json({ success: false, error: 'Failed to update shop settings' }, 500);
|
|
265
|
-
}
|
|
30
|
+
return { settings: data };
|
|
266
31
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/public.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/shop/handlers/public.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAsO/C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY7F;AAED,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiGjG;AAED,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoBrF;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAc1F;AAED,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAUzF;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqB7F;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmB1F;AAgHD,wBAAsB,oBAAoB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAehG;AAED,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY5F;AAED,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4B/F"}
|