@hintergrund/worker 0.3.17 → 0.3.19
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/appointments/admin.d.ts +171 -0
- package/dist/api/appointments/admin.d.ts.map +1 -0
- package/dist/api/appointments/admin.js +275 -0
- package/dist/api/appointments/core.d.ts +114 -0
- package/dist/api/appointments/core.d.ts.map +1 -0
- package/dist/api/appointments/core.js +208 -0
- package/dist/api/appointments/cron.d.ts +9 -0
- package/dist/api/appointments/cron.d.ts.map +1 -0
- package/dist/api/appointments/cron.js +71 -0
- package/dist/api/appointments/emails.d.ts +5 -0
- package/dist/api/appointments/emails.d.ts.map +1 -0
- package/dist/api/appointments/emails.js +53 -0
- package/dist/api/appointments/public.d.ts +104 -0
- package/dist/api/appointments/public.d.ts.map +1 -0
- package/dist/api/appointments/public.js +129 -0
- package/dist/api/appointments/routes.d.ts +7 -0
- package/dist/api/appointments/routes.d.ts.map +1 -0
- package/dist/api/appointments/routes.js +28 -0
- package/dist/api/cms/handlers/agent-provider.handler.d.ts +1 -0
- package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/agent-provider.handler.js +13 -23
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +3 -18
- package/dist/api/cms/handlers/integrations.handler.d.ts +2 -2
- package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/integrations.handler.js +5 -11
- package/dist/api/cms/handlers/runtime.handler.d.ts +6 -0
- package/dist/api/cms/handlers/runtime.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/runtime.handler.js +42 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +31 -14
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +6 -6
- package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -6
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +127 -30
- package/dist/api/emails/handlers/public.handler.d.ts +0 -2
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +32 -77
- package/dist/api/emails/handlers/send.handler.js +2 -2
- package/dist/api/emails/handlers/settings.handler.d.ts +1 -3
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +1 -6
- package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/subscribers.handler.js +9 -0
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +3 -1
- package/dist/api/emails/routes/mail.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/mail.routes.js +19 -17
- package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/public.routes.js +1 -2
- package/dist/api/enquiries/routes.d.ts +7 -0
- package/dist/api/enquiries/routes.d.ts.map +1 -0
- package/dist/api/enquiries/routes.js +73 -0
- package/dist/api/members/handlers.d.ts +36 -0
- package/dist/api/members/handlers.d.ts.map +1 -0
- package/dist/api/members/handlers.js +322 -0
- package/dist/api/members/routes.d.ts +5 -0
- package/dist/api/members/routes.d.ts.map +1 -0
- package/dist/api/members/routes.js +20 -0
- package/dist/api/reservations/core.d.ts +25 -0
- package/dist/api/reservations/core.d.ts.map +1 -0
- package/dist/api/reservations/core.js +59 -0
- package/dist/api/reservations/mail.d.ts +7 -0
- package/dist/api/reservations/mail.d.ts.map +1 -0
- package/dist/api/reservations/mail.js +63 -0
- package/dist/api/reservations/routes.d.ts +7 -0
- package/dist/api/reservations/routes.d.ts.map +1 -0
- package/dist/api/reservations/routes.js +186 -0
- package/dist/api/shop/handlers/products.handler.d.ts +1 -1
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/products.handler.js +3 -3
- package/dist/api/shop/handlers/public.handler.d.ts +3 -3
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +25 -28
- package/dist/api/shop/routes.d.ts +2 -4
- package/dist/api/shop/routes.d.ts.map +1 -1
- package/dist/api/shop/routes.js +8 -11
- package/dist/api/stays/actions.d.ts +13 -0
- package/dist/api/stays/actions.d.ts.map +1 -0
- package/dist/api/stays/actions.js +28 -0
- package/dist/api/stays/admin.d.ts +209 -0
- package/dist/api/stays/admin.d.ts.map +1 -0
- package/dist/api/stays/admin.js +228 -0
- package/dist/api/stays/bookings.d.ts +113 -0
- package/dist/api/stays/bookings.d.ts.map +1 -0
- package/dist/api/stays/bookings.js +254 -0
- package/dist/api/stays/core.d.ts +214 -0
- package/dist/api/stays/core.d.ts.map +1 -0
- package/dist/api/stays/core.js +361 -0
- package/dist/api/stays/cron.d.ts +7 -0
- package/dist/api/stays/cron.d.ts.map +1 -0
- package/dist/api/stays/cron.js +56 -0
- package/dist/api/stays/mail.d.ts +8 -0
- package/dist/api/stays/mail.d.ts.map +1 -0
- package/dist/api/stays/mail.js +50 -0
- package/dist/api/stays/offers.d.ts +27 -0
- package/dist/api/stays/offers.d.ts.map +1 -0
- package/dist/api/stays/offers.js +56 -0
- package/dist/api/stays/payments.d.ts +47 -0
- package/dist/api/stays/payments.d.ts.map +1 -0
- package/dist/api/stays/payments.js +148 -0
- package/dist/api/stays/public.d.ts +207 -0
- package/dist/api/stays/public.d.ts.map +1 -0
- package/dist/api/stays/public.js +137 -0
- package/dist/api/stays/routes.d.ts +7 -0
- package/dist/api/stays/routes.d.ts.map +1 -0
- package/dist/api/stays/routes.js +39 -0
- package/dist/api/stripe/webhook.d.ts +5 -0
- package/dist/api/stripe/webhook.d.ts.map +1 -0
- package/dist/api/stripe/webhook.js +45 -0
- package/dist/api/tickets/core.d.ts +40 -0
- package/dist/api/tickets/core.d.ts.map +1 -0
- package/dist/api/tickets/core.js +115 -0
- package/dist/api/tickets/routes.d.ts +5 -0
- package/dist/api/tickets/routes.d.ts.map +1 -0
- package/dist/api/tickets/routes.js +70 -0
- package/dist/index.d.ts +16 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +40 -27
- package/dist/lib/appointments-schema.d.ts +6 -0
- package/dist/lib/appointments-schema.d.ts.map +1 -0
- package/dist/lib/appointments-schema.js +96 -0
- package/dist/lib/config.js +4 -4
- package/dist/lib/email-template.d.ts +2 -2
- package/dist/lib/email-template.d.ts.map +1 -1
- package/dist/lib/email-template.js +3 -3
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +12 -3
- package/dist/lib/features.d.ts +13 -0
- package/dist/lib/features.d.ts.map +1 -0
- package/dist/lib/features.js +19 -0
- package/dist/lib/invoice.js +3 -3
- package/dist/lib/mail-schema.d.ts +1 -1
- package/dist/lib/mail-schema.d.ts.map +1 -1
- package/dist/lib/mail-schema.js +0 -1
- package/dist/lib/mail.d.ts +23 -3
- package/dist/lib/mail.d.ts.map +1 -1
- package/dist/lib/mail.js +69 -23
- package/dist/lib/members.d.ts +41 -0
- package/dist/lib/members.d.ts.map +1 -0
- package/dist/lib/members.js +92 -0
- 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 +67 -8
- package/dist/lib/reservations-schema.d.ts +3 -0
- package/dist/lib/reservations-schema.d.ts.map +1 -0
- package/dist/lib/reservations-schema.js +35 -0
- package/dist/lib/stays-schema.d.ts +3 -0
- package/dist/lib/stays-schema.d.ts.map +1 -0
- package/dist/lib/stays-schema.js +247 -0
- package/dist/lib/stripe.d.ts +6 -0
- package/dist/lib/stripe.d.ts.map +1 -0
- package/dist/lib/stripe.js +9 -0
- package/dist/lib/template.d.ts +2 -1
- package/dist/lib/template.d.ts.map +1 -1
- package/dist/lib/template.js +4 -82
- package/dist/lib/user-recovery.d.ts.map +1 -1
- package/dist/lib/user-recovery.js +4 -2
- package/dist/lib/website-i18n.d.ts +17 -0
- package/dist/lib/website-i18n.d.ts.map +1 -1
- package/dist/lib/website-i18n.js +90 -19
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +8 -1
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +1 -0
- package/package.json +2 -2
- package/dist/api/cms/handlers/setup.handler.d.ts +0 -8
- package/dist/api/cms/handlers/setup.handler.d.ts.map +0 -1
- package/dist/api/cms/handlers/setup.handler.js +0 -291
- package/dist/api/emails/handlers/invoice.handler.d.ts +0 -9
- package/dist/api/emails/handlers/invoice.handler.d.ts.map +0 -1
- package/dist/api/emails/handlers/invoice.handler.js +0 -154
- package/dist/lib/brand.d.ts +0 -6
- package/dist/lib/brand.d.ts.map +0 -1
- package/dist/lib/brand.js +0 -31
- package/dist/lib/integration-health.d.ts +0 -18
- package/dist/lib/integration-health.d.ts.map +0 -1
- package/dist/lib/integration-health.js +0 -51
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type Stripe from 'stripe';
|
|
2
|
+
import type { StayChargeResult, StayGuarantee, StayLocale } from '@hintergrund/runtime-contracts';
|
|
3
|
+
import type { Bindings } from '../../index';
|
|
4
|
+
import { type Draft, type Row } from './core';
|
|
5
|
+
export interface HoldPayload {
|
|
6
|
+
arrival: string;
|
|
7
|
+
departure: string;
|
|
8
|
+
drafts: Draft[];
|
|
9
|
+
guest: {
|
|
10
|
+
name: string;
|
|
11
|
+
email: string;
|
|
12
|
+
phone?: string;
|
|
13
|
+
country?: string;
|
|
14
|
+
};
|
|
15
|
+
locale: StayLocale;
|
|
16
|
+
note: string;
|
|
17
|
+
promo: string;
|
|
18
|
+
currency: string;
|
|
19
|
+
guarantee: StayGuarantee;
|
|
20
|
+
dueNow: number;
|
|
21
|
+
successPath: string;
|
|
22
|
+
cancelPath: string;
|
|
23
|
+
}
|
|
24
|
+
/** The strictest guarantee among the rooms decides how the guest pays. */
|
|
25
|
+
export declare const strictest: (drafts: Draft[]) => StayGuarantee;
|
|
26
|
+
/** Stripe Checkout for a hold: saves the card, and takes the deposit or the full price when the policy asks for it. Stripe's minimum session life (30 min) is longer than a hold, hence the re-acquire below. */
|
|
27
|
+
export declare function startCheckout(env: Bindings, db: D1Database, origin: string, holdId: string, p: HoldPayload): Promise<string>;
|
|
28
|
+
export interface Paid {
|
|
29
|
+
customerId?: string;
|
|
30
|
+
paymentMethodId?: string;
|
|
31
|
+
paymentIntentId?: string;
|
|
32
|
+
sessionId?: string;
|
|
33
|
+
amount?: number;
|
|
34
|
+
setupId?: string;
|
|
35
|
+
}
|
|
36
|
+
/** Turns a hold into a booking, once: a repeated call (webhook retry) finds the booking and does nothing. Late payment tries to re-acquire, else refunds. */
|
|
37
|
+
export declare function finalizeHold(env: Bindings, db: D1Database, origin: string, holdId: string, paid?: Paid): Promise<'confirmed' | 'refunded'>;
|
|
38
|
+
/** Webhook: a finished Checkout Session is either a hold's payment/card setup or a payment link for a fee. */
|
|
39
|
+
export declare function applyStayCheckout(env: Bindings, origin: string, session: Stripe.Checkout.Session): Promise<void>;
|
|
40
|
+
export declare function charge(env: Bindings, db: D1Database, origin: string, booking: Row, amount: number, note: string): Promise<StayChargeResult>;
|
|
41
|
+
/** Brings what the guest paid in line with what is owed after a cancellation: refunds the excess, charges the shortfall. */
|
|
42
|
+
export declare function settle(env: Bindings, db: D1Database, origin: string, bookingId: string): Promise<{
|
|
43
|
+
refunded: number;
|
|
44
|
+
charged: number;
|
|
45
|
+
paymentLink: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
//# sourceMappingURL=payments.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payments.d.ts","sourceRoot":"","sources":["../../../src/api/stays/payments.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EAAwD,KAAK,KAAK,EAAE,KAAK,GAAG,EAAE,MAAM,QAAQ,CAAC;AAKpG,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,KAAK,EAAE,CAAC;IAAC,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAAC,MAAM,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAC/K,QAAQ,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;CACpG;AACD,0EAA0E;AAC1E,eAAO,MAAM,SAAS,GAAI,QAAQ,KAAK,EAAE,KAAG,aAAqH,CAAC;AAIlK,iNAAiN;AACjN,wBAAsB,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAclI;AAYD,MAAM,WAAW,IAAI;IAAG,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE;AAExJ,6JAA6J;AAC7J,wBAAsB,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,IAAS,GAAG,OAAO,CAAC,WAAW,GAAG,UAAU,CAAC,CAqBpJ;AAED,8GAA8G;AAC9G,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBtH;AAID,wBAAsB,MAAM,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAuBjJ;AAED,4HAA4H;AAC5H,wBAAsB,MAAM,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,CAAC,CAoBnK"}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { ensureSchema } from '../../lib/project-db';
|
|
2
|
+
import { stripeClient } from '../../lib/stripe';
|
|
3
|
+
import { acquireStmts, autoAssign, bookingStmts, newReference } from './core';
|
|
4
|
+
import { randomToken } from '../../lib/features';
|
|
5
|
+
import { sendStayMail } from './mail';
|
|
6
|
+
const ORDER = ['none', 'card', 'deposit', 'prepay'];
|
|
7
|
+
/** The strictest guarantee among the rooms decides how the guest pays. */
|
|
8
|
+
export const strictest = (drafts) => drafts.map(d => d.policy.guarantee).sort((a, b) => ORDER.indexOf(b) - ORDER.indexOf(a))[0] ?? 'none';
|
|
9
|
+
const idOf = (value) => typeof value === 'string' ? value : value?.id;
|
|
10
|
+
/** Stripe Checkout for a hold: saves the card, and takes the deposit or the full price when the policy asks for it. Stripe's minimum session life (30 min) is longer than a hold, hence the re-acquire below. */
|
|
11
|
+
export async function startCheckout(env, db, origin, holdId, p) {
|
|
12
|
+
const stripe = stripeClient(env);
|
|
13
|
+
const customer = await stripe.customers.create({ email: p.guest.email, name: p.guest.name, metadata: { stayHold: holdId } });
|
|
14
|
+
const base = {
|
|
15
|
+
customer: customer.id, payment_method_types: ['card'], metadata: { stayHold: holdId }, expires_at: Math.floor(Date.now() / 1000) + 31 * 60, locale: (p.locale === 'de' ? 'de' : 'en'),
|
|
16
|
+
success_url: `${origin}${p.successPath}${p.successPath.includes('?') ? '&' : '?'}hold=${holdId}`, cancel_url: `${origin}${p.cancelPath}`,
|
|
17
|
+
};
|
|
18
|
+
const session = await stripe.checkout.sessions.create(p.dueNow > 0 ? {
|
|
19
|
+
...base, mode: 'payment',
|
|
20
|
+
line_items: [{ quantity: 1, price_data: { currency: p.currency, unit_amount: p.dueNow, product_data: { name: `${p.arrival} - ${p.departure}` } } }],
|
|
21
|
+
payment_intent_data: { metadata: { stayHold: holdId }, ...(p.guarantee === 'prepay' ? {} : { setup_future_usage: 'off_session' }) },
|
|
22
|
+
} : { ...base, mode: 'setup', setup_intent_data: { metadata: { stayHold: holdId } } });
|
|
23
|
+
await db.prepare('UPDATE stay_holds SET stripe_session_id = ? WHERE id = ?').bind(session.id, holdId).run();
|
|
24
|
+
return session.url;
|
|
25
|
+
}
|
|
26
|
+
/** Takes the nights back for an expired hold whose payment arrived late; false when they are gone. */
|
|
27
|
+
async function reacquire(db, hold) {
|
|
28
|
+
const expiresAt = Date.now() + 60000, items = (await db.prepare('SELECT * FROM stay_hold_items WHERE hold_id = ?').bind(hold.id).all()).results;
|
|
29
|
+
try {
|
|
30
|
+
await db.batch([db.prepare("UPDATE stay_holds SET status = 'active', expires_at = ? WHERE id = ? AND status = 'expired'").bind(expiresAt, hold.id),
|
|
31
|
+
...acquireStmts(db, items.map(i => ({ roomTypeId: i.room_type_id, arrival: i.arrival, departure: i.departure, qty: i.qty })), { holdId: hold.id, expiresAt })]);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
return !!await db.prepare("SELECT 1 FROM stay_holds WHERE id = ? AND status = 'active' AND expires_at = ?").bind(hold.id, expiresAt).first();
|
|
37
|
+
}
|
|
38
|
+
/** Turns a hold into a booking, once: a repeated call (webhook retry) finds the booking and does nothing. Late payment tries to re-acquire, else refunds. */
|
|
39
|
+
export async function finalizeHold(env, db, origin, holdId, paid = {}) {
|
|
40
|
+
let hold = await db.prepare('SELECT * FROM stay_holds WHERE id = ?').bind(holdId).first();
|
|
41
|
+
if (!hold)
|
|
42
|
+
return 'refunded';
|
|
43
|
+
if (hold.status === 'converted')
|
|
44
|
+
return 'confirmed';
|
|
45
|
+
const refund = async () => { if (paid.paymentIntentId)
|
|
46
|
+
await stripeClient(env).refunds.create({ payment_intent: paid.paymentIntentId }); return 'refunded'; };
|
|
47
|
+
if (hold.status === 'expired' && !await reacquire(db, hold))
|
|
48
|
+
return refund();
|
|
49
|
+
const payload = JSON.parse(hold.payload_json);
|
|
50
|
+
const b = { id: crypto.randomUUID(), guestId: crypto.randomUUID(), reference: newReference(), manageToken: randomToken() };
|
|
51
|
+
const { stmts, reservationIds } = bookingStmts(db, {
|
|
52
|
+
...b, source: 'online', currency: payload.currency, guest: payload.guest, drafts: payload.drafts, promo: payload.promo, note: payload.note, locale: payload.locale, guarantee: payload.guarantee,
|
|
53
|
+
stripe: { customerId: paid.customerId, paymentMethodId: paid.paymentMethodId, paymentIntentId: paid.paymentIntentId, sessionId: paid.sessionId },
|
|
54
|
+
pays: [...(paid.paymentMethodId ? [{ kind: 'guarantee', stripeId: paid.setupId ?? paid.paymentMethodId, amount: 0 }] : []), ...(paid.amount ? [{ kind: 'deposit', stripeId: paid.paymentIntentId ?? '', amount: paid.amount }] : [])],
|
|
55
|
+
}, holdId);
|
|
56
|
+
try {
|
|
57
|
+
await db.batch(stmts);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (/UNIQUE/i.test(String(error) + String(error?.cause)))
|
|
61
|
+
return 'confirmed';
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
if (!await db.prepare('SELECT 1 FROM stay_bookings WHERE id = ?').bind(b.id).first()) {
|
|
65
|
+
hold = (await db.prepare('SELECT status FROM stay_holds WHERE id = ?').bind(holdId).first());
|
|
66
|
+
return hold.status === 'converted' ? 'confirmed' : refund();
|
|
67
|
+
}
|
|
68
|
+
for (const id of reservationIds)
|
|
69
|
+
await autoAssign(db, id);
|
|
70
|
+
await sendStayMail(env, db, origin, b.id, 'confirmation');
|
|
71
|
+
return 'confirmed';
|
|
72
|
+
}
|
|
73
|
+
/** Webhook: a finished Checkout Session is either a hold's payment/card setup or a payment link for a fee. */
|
|
74
|
+
export async function applyStayCheckout(env, origin, session) {
|
|
75
|
+
const holdId = session.metadata?.stayHold, chargeId = session.metadata?.stayCharge;
|
|
76
|
+
if (!holdId && !chargeId)
|
|
77
|
+
return;
|
|
78
|
+
const db = await ensureSchema(env), stripe = stripeClient(env);
|
|
79
|
+
if (chargeId) {
|
|
80
|
+
await db.prepare("UPDATE stay_payments SET status = 'succeeded', stripe_id = ? WHERE id = ? AND status != 'succeeded'").bind(idOf(session.payment_intent) ?? session.id, chargeId).run();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const paid = { customerId: idOf(session.customer), sessionId: session.id };
|
|
84
|
+
if (session.mode === 'setup' && session.setup_intent) {
|
|
85
|
+
paid.setupId = idOf(session.setup_intent);
|
|
86
|
+
paid.paymentMethodId = idOf((await stripe.setupIntents.retrieve(paid.setupId)).payment_method);
|
|
87
|
+
}
|
|
88
|
+
else if (session.mode === 'payment' && session.payment_status === 'paid' && session.payment_intent) {
|
|
89
|
+
paid.paymentIntentId = idOf(session.payment_intent);
|
|
90
|
+
const pi = await stripe.paymentIntents.retrieve(paid.paymentIntentId);
|
|
91
|
+
paid.paymentMethodId = idOf(pi.payment_method);
|
|
92
|
+
paid.amount = pi.amount_received;
|
|
93
|
+
}
|
|
94
|
+
else
|
|
95
|
+
return;
|
|
96
|
+
await finalizeHold(env, db, origin, holdId, paid);
|
|
97
|
+
}
|
|
98
|
+
// --- Fees, refunds ---
|
|
99
|
+
export async function charge(env, db, origin, booking, amount, note) {
|
|
100
|
+
const stripe = stripeClient(env), paymentId = crypto.randomUUID(), now = Date.now();
|
|
101
|
+
const record = (status, stripeId, kind = 'charge') => db.prepare('INSERT INTO stay_payments (id, booking_id, kind, stripe_id, amount, status, note, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').bind(paymentId, booking.id, kind, stripeId, amount, status, note, now).run();
|
|
102
|
+
if (booking.stripe_customer_id && booking.stripe_payment_method_id) {
|
|
103
|
+
try {
|
|
104
|
+
const pi = await stripe.paymentIntents.create({ amount, currency: booking.currency, customer: booking.stripe_customer_id, payment_method: booking.stripe_payment_method_id, off_session: true, confirm: true, description: `${booking.reference}: ${note}`, metadata: { stayBooking: booking.id } });
|
|
105
|
+
await record(pi.status === 'succeeded' ? 'succeeded' : 'pending', pi.id);
|
|
106
|
+
return { status: 'succeeded', paymentId };
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (error?.type !== 'StripeCardError') {
|
|
110
|
+
await record('failed', '');
|
|
111
|
+
return { status: 'failed', paymentId, error: String(error?.message ?? error) };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// No card, or the bank wants the guest to authenticate: send a payment link instead.
|
|
116
|
+
const url = `${origin}/book/manage?token=${booking.manage_token}`;
|
|
117
|
+
const guest = await db.prepare('SELECT email FROM stay_guests WHERE id = ?').bind(booking.guest_id).first();
|
|
118
|
+
const session = await stripe.checkout.sessions.create({
|
|
119
|
+
mode: 'payment', payment_method_types: ['card'], ...(booking.stripe_customer_id ? { customer: booking.stripe_customer_id } : { customer_email: guest?.email }), metadata: { stayCharge: paymentId },
|
|
120
|
+
line_items: [{ quantity: 1, price_data: { currency: booking.currency, unit_amount: amount, product_data: { name: `${booking.reference}: ${note}` } } }],
|
|
121
|
+
expires_at: Math.floor(now / 1000) + 23 * 3600, success_url: url, cancel_url: url,
|
|
122
|
+
});
|
|
123
|
+
await record('requires_action', session.id);
|
|
124
|
+
await sendStayMail(env, db, origin, booking.id, 'payment_link', { url: session.url, amount });
|
|
125
|
+
return { status: 'payment_link', paymentId, url: session.url };
|
|
126
|
+
}
|
|
127
|
+
/** Brings what the guest paid in line with what is owed after a cancellation: refunds the excess, charges the shortfall. */
|
|
128
|
+
export async function settle(env, db, origin, bookingId) {
|
|
129
|
+
const booking = (await db.prepare('SELECT * FROM stay_bookings WHERE id = ?').bind(bookingId).first());
|
|
130
|
+
const [res, pays] = await Promise.all([db.prepare('SELECT status, due_now, fee FROM stay_reservations WHERE booking_id = ?').bind(bookingId).all(),
|
|
131
|
+
db.prepare("SELECT kind, amount FROM stay_payments WHERE booking_id = ? AND status = 'succeeded'").bind(bookingId).all()]);
|
|
132
|
+
const required = res.results.reduce((sum, r) => sum + (r.status === 'cancelled' || r.status === 'no_show' ? r.fee : r.due_now), 0);
|
|
133
|
+
const sum = (kinds) => pays.results.filter(p => kinds.includes(p.kind)).reduce((total, p) => total + p.amount, 0);
|
|
134
|
+
const delta = sum(['deposit', 'charge']) - sum(['refund']) - required;
|
|
135
|
+
if (delta > 0 && booking.stripe_payment_intent_id) {
|
|
136
|
+
const amount = Math.min(delta, sum(['deposit']) - sum(['refund']));
|
|
137
|
+
if (amount > 0) {
|
|
138
|
+
const refund = await stripeClient(env).refunds.create({ payment_intent: booking.stripe_payment_intent_id, amount });
|
|
139
|
+
await db.prepare("INSERT INTO stay_payments (id, booking_id, kind, stripe_id, amount, status, created_at) VALUES (?, ?, 'refund', ?, ?, 'succeeded', ?)").bind(crypto.randomUUID(), bookingId, refund.id, amount, Date.now()).run();
|
|
140
|
+
return { refunded: amount, charged: 0, paymentLink: false };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (delta < 0) {
|
|
144
|
+
const result = await charge(env, db, origin, booking, -delta, 'fee');
|
|
145
|
+
return { refunded: 0, charged: result.status === 'succeeded' ? -delta : 0, paymentLink: result.status === 'payment_link' };
|
|
146
|
+
}
|
|
147
|
+
return { refunded: 0, charged: 0, paymentLink: false };
|
|
148
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { Bindings } from '../../index';
|
|
3
|
+
type Ctx = Context<{
|
|
4
|
+
Bindings: Bindings;
|
|
5
|
+
}>;
|
|
6
|
+
export declare function info(c: Ctx): Promise<Response & import("hono").TypedResponse<{
|
|
7
|
+
property: {
|
|
8
|
+
name: string;
|
|
9
|
+
currency: string;
|
|
10
|
+
timezone: string;
|
|
11
|
+
maxNights: number;
|
|
12
|
+
checkInTime: string;
|
|
13
|
+
checkOutTime: string;
|
|
14
|
+
childMaxAge: number;
|
|
15
|
+
maxRooms: number;
|
|
16
|
+
policyText: string;
|
|
17
|
+
};
|
|
18
|
+
today: string;
|
|
19
|
+
roomTypes: {
|
|
20
|
+
name: string;
|
|
21
|
+
id: string;
|
|
22
|
+
baseOccupancy: number;
|
|
23
|
+
maxAdults: number;
|
|
24
|
+
maxChildren: number;
|
|
25
|
+
maxOccupancy: number;
|
|
26
|
+
extraBed: boolean;
|
|
27
|
+
}[];
|
|
28
|
+
extras: {
|
|
29
|
+
name: string;
|
|
30
|
+
id: string;
|
|
31
|
+
price: number;
|
|
32
|
+
per: import("@hintergrund/runtime-contracts").StayExtraPer;
|
|
33
|
+
}[];
|
|
34
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
35
|
+
export declare function offers(c: Ctx): Promise<(Response & import("hono").TypedResponse<{
|
|
36
|
+
error: string;
|
|
37
|
+
code?: typeof import("@hintergrund/runtime-contracts").STAY_ERRORS[number] | undefined;
|
|
38
|
+
warnings?: string[] | undefined;
|
|
39
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
|
|
40
|
+
arrival: string;
|
|
41
|
+
departure: string;
|
|
42
|
+
nights: number;
|
|
43
|
+
currency: string;
|
|
44
|
+
rooms: {
|
|
45
|
+
index: number;
|
|
46
|
+
request: {
|
|
47
|
+
adults: number;
|
|
48
|
+
childrenAges: number[];
|
|
49
|
+
};
|
|
50
|
+
options: {
|
|
51
|
+
roomTypeId: string;
|
|
52
|
+
name: string;
|
|
53
|
+
available: number;
|
|
54
|
+
plans: {
|
|
55
|
+
ratePlanId: string;
|
|
56
|
+
name: string;
|
|
57
|
+
board: import("@hintergrund/runtime-contracts").StayBoard;
|
|
58
|
+
promo: boolean;
|
|
59
|
+
nightly: {
|
|
60
|
+
date: string;
|
|
61
|
+
price: number;
|
|
62
|
+
}[];
|
|
63
|
+
total: number;
|
|
64
|
+
vat: {
|
|
65
|
+
rate: number;
|
|
66
|
+
gross: number;
|
|
67
|
+
vat: number;
|
|
68
|
+
}[];
|
|
69
|
+
cityTax: number;
|
|
70
|
+
cancellation: {
|
|
71
|
+
policyId: string | null;
|
|
72
|
+
name: string;
|
|
73
|
+
guarantee: import("@hintergrund/runtime-contracts").StayGuarantee;
|
|
74
|
+
depositPct: number;
|
|
75
|
+
tiers: {
|
|
76
|
+
hoursBeforeArrival: number;
|
|
77
|
+
feeType: import("@hintergrund/runtime-contracts").StayFeeType;
|
|
78
|
+
value: number;
|
|
79
|
+
}[];
|
|
80
|
+
noShow: {
|
|
81
|
+
feeType: import("@hintergrund/runtime-contracts").StayFeeType;
|
|
82
|
+
value: number;
|
|
83
|
+
};
|
|
84
|
+
freeUntil: number | null;
|
|
85
|
+
dueNow: number;
|
|
86
|
+
};
|
|
87
|
+
}[];
|
|
88
|
+
}[];
|
|
89
|
+
}[];
|
|
90
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
|
|
91
|
+
export declare function hold(c: Ctx): Promise<(Response & import("hono").TypedResponse<{
|
|
92
|
+
error: string;
|
|
93
|
+
code?: typeof import("@hintergrund/runtime-contracts").STAY_ERRORS[number] | undefined;
|
|
94
|
+
warnings?: string[] | undefined;
|
|
95
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
|
|
96
|
+
status: "confirmed" | "payment_required";
|
|
97
|
+
holdId: string;
|
|
98
|
+
expiresAt: number;
|
|
99
|
+
url?: string | undefined;
|
|
100
|
+
manageToken?: string | undefined;
|
|
101
|
+
reference?: string | undefined;
|
|
102
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
|
|
103
|
+
export declare function holdStatus(c: Ctx): Promise<(Response & import("hono").TypedResponse<{
|
|
104
|
+
error: string;
|
|
105
|
+
code?: typeof import("@hintergrund/runtime-contracts").STAY_ERRORS[number] | undefined;
|
|
106
|
+
warnings?: string[] | undefined;
|
|
107
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
|
|
108
|
+
status: "pending" | "confirmed" | "expired";
|
|
109
|
+
manageToken?: string | undefined;
|
|
110
|
+
reference?: string | undefined;
|
|
111
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
|
|
112
|
+
export declare function booking(c: Ctx): Promise<(Response & import("hono").TypedResponse<{
|
|
113
|
+
error: string;
|
|
114
|
+
code?: typeof import("@hintergrund/runtime-contracts").STAY_ERRORS[number] | undefined;
|
|
115
|
+
warnings?: string[] | undefined;
|
|
116
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
|
|
117
|
+
reference: string;
|
|
118
|
+
status: import("@hintergrund/runtime-contracts").StayBookingStatus;
|
|
119
|
+
currency: string;
|
|
120
|
+
guest: {
|
|
121
|
+
name: string;
|
|
122
|
+
email: string;
|
|
123
|
+
};
|
|
124
|
+
reservations: {
|
|
125
|
+
id: string;
|
|
126
|
+
roomTypeName: string;
|
|
127
|
+
ratePlanName: string;
|
|
128
|
+
board: import("@hintergrund/runtime-contracts").StayBoard;
|
|
129
|
+
arrival: string;
|
|
130
|
+
departure: string;
|
|
131
|
+
adults: number;
|
|
132
|
+
childrenAges: number[];
|
|
133
|
+
status: import("@hintergrund/runtime-contracts").StayReservationStatus;
|
|
134
|
+
nightly: {
|
|
135
|
+
date: string;
|
|
136
|
+
price: number;
|
|
137
|
+
}[];
|
|
138
|
+
extras: {
|
|
139
|
+
name: string;
|
|
140
|
+
quantity: number;
|
|
141
|
+
total: number;
|
|
142
|
+
}[];
|
|
143
|
+
total: number;
|
|
144
|
+
cityTax: number;
|
|
145
|
+
cancelFee: number;
|
|
146
|
+
canCancel: boolean;
|
|
147
|
+
}[];
|
|
148
|
+
total: number;
|
|
149
|
+
cityTax: number;
|
|
150
|
+
paid: number;
|
|
151
|
+
checkInTime: string;
|
|
152
|
+
checkOutTime: string;
|
|
153
|
+
policyText: string;
|
|
154
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
|
|
155
|
+
export declare function cancel(c: Ctx): Promise<(Response & import("hono").TypedResponse<{
|
|
156
|
+
error: string;
|
|
157
|
+
code?: typeof import("@hintergrund/runtime-contracts").STAY_ERRORS[number] | undefined;
|
|
158
|
+
warnings?: string[] | undefined;
|
|
159
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
|
|
160
|
+
booking: {
|
|
161
|
+
reference: string;
|
|
162
|
+
status: import("@hintergrund/runtime-contracts").StayBookingStatus;
|
|
163
|
+
currency: string;
|
|
164
|
+
guest: {
|
|
165
|
+
name: string;
|
|
166
|
+
email: string;
|
|
167
|
+
};
|
|
168
|
+
reservations: {
|
|
169
|
+
id: string;
|
|
170
|
+
roomTypeName: string;
|
|
171
|
+
ratePlanName: string;
|
|
172
|
+
board: import("@hintergrund/runtime-contracts").StayBoard;
|
|
173
|
+
arrival: string;
|
|
174
|
+
departure: string;
|
|
175
|
+
adults: number;
|
|
176
|
+
childrenAges: number[];
|
|
177
|
+
status: import("@hintergrund/runtime-contracts").StayReservationStatus;
|
|
178
|
+
nightly: {
|
|
179
|
+
date: string;
|
|
180
|
+
price: number;
|
|
181
|
+
}[];
|
|
182
|
+
extras: {
|
|
183
|
+
name: string;
|
|
184
|
+
quantity: number;
|
|
185
|
+
total: number;
|
|
186
|
+
}[];
|
|
187
|
+
total: number;
|
|
188
|
+
cityTax: number;
|
|
189
|
+
cancelFee: number;
|
|
190
|
+
canCancel: boolean;
|
|
191
|
+
}[];
|
|
192
|
+
total: number;
|
|
193
|
+
cityTax: number;
|
|
194
|
+
paid: number;
|
|
195
|
+
checkInTime: string;
|
|
196
|
+
checkOutTime: string;
|
|
197
|
+
policyText: string;
|
|
198
|
+
};
|
|
199
|
+
fee: number;
|
|
200
|
+
refunded: number;
|
|
201
|
+
charged: number;
|
|
202
|
+
paymentLink?: boolean | undefined;
|
|
203
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
|
|
204
|
+
/** iCal feed of one unit's reservations and blocks (no guest data). */
|
|
205
|
+
export declare function icalExport(c: Ctx): Promise<Response>;
|
|
206
|
+
export {};
|
|
207
|
+
//# sourceMappingURL=public.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"public.d.ts","sourceRoot":"","sources":["../../../src/api/stays/public.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAIpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAU5C,KAAK,GAAG,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,CAAC;AAK3C,wBAAsB,IAAI,CAAC,CAAC,EAAE,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;mEAShC;AAED,wBAAsB,MAAM,CAAC,CAAC,EAAE,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oEAQlC;AAED,wBAAsB,IAAI,CAAC,CAAC,EAAE,GAAG;;;;;;;;;;;oEA+ChC;AAED,wBAAsB,UAAU,CAAC,CAAC,EAAE,GAAG;;;;;;;;oEAKtC;AAUD,wBAAsB,OAAO,CAAC,CAAC,EAAE,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oEAGnC;AAED,wBAAsB,MAAM,CAAC,CAAC,EAAE,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oEAUlC;AAED,uEAAuE;AACvE,wBAAsB,UAAU,CAAC,CAAC,EAAE,GAAG,qBAYtC"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { addDays, localParts, } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { ensureSchema } from '../../lib/project-db';
|
|
3
|
+
import { rateLimit, validEmail } from '../../lib/user-recovery';
|
|
4
|
+
import { cancelReservations } from './actions';
|
|
5
|
+
import { acquireStmts, aggregateItems, arrivalAt, bookingView, isOverbooked, loadCtx, loadSettings, parseSearch, releaseExpiredHolds, text } from './core';
|
|
6
|
+
import { randomToken } from '../../lib/features';
|
|
7
|
+
import { buildDrafts, computeOffers } from './offers';
|
|
8
|
+
import { finalizeHold, startCheckout, strictest } from './payments';
|
|
9
|
+
import { releaseHold } from './core';
|
|
10
|
+
const clientKey = (c) => c.req.header('CF-Connecting-IP') || 'local';
|
|
11
|
+
const fail = (c, status, error, code, warnings) => c.json({ error, code, ...(warnings ? { warnings } : {}) }, status);
|
|
12
|
+
const safePath = (value, fallback) => typeof value === 'string' && /^\/(?!\/)[\w\-./?=&%]*$/.test(value) ? value : fallback;
|
|
13
|
+
export async function info(c) {
|
|
14
|
+
const db = await ensureSchema(c.env), s = await loadSettings(db);
|
|
15
|
+
const [types, extras] = await Promise.all([db.prepare('SELECT * FROM stay_room_types ORDER BY sort, name').all(), db.prepare('SELECT * FROM stay_extras WHERE active = 1 ORDER BY sort, name').all()]);
|
|
16
|
+
return c.json({
|
|
17
|
+
property: { name: s.name, timezone: s.timezone, currency: s.currency, checkInTime: s.checkInTime, checkOutTime: s.checkOutTime, childMaxAge: s.childMaxAge, maxRooms: s.maxRooms, maxNights: s.maxNights, policyText: s.policyText },
|
|
18
|
+
today: localParts(Date.now(), s.timezone).date,
|
|
19
|
+
roomTypes: types.results.map(t => ({ id: t.id, name: t.name, baseOccupancy: t.base_occupancy, maxAdults: t.max_adults, maxChildren: t.max_children, maxOccupancy: t.max_occupancy, extraBed: !!t.extra_bed })),
|
|
20
|
+
extras: extras.results.map(e => ({ id: e.id, name: e.name, price: e.price, per: e.per })),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
export async function offers(c) {
|
|
24
|
+
if (!await rateLimit(c.env, `stays-offers:${clientKey(c)}`, 120, 3600))
|
|
25
|
+
return fail(c, 429, 'Too many requests. Try again later.', 'rate_limited');
|
|
26
|
+
const body = await c.req.json().catch(() => null);
|
|
27
|
+
const db = await ensureSchema(c.env), s = await loadSettings(db);
|
|
28
|
+
const search = parseSearch(body, s, localParts(Date.now(), s.timezone).date);
|
|
29
|
+
if (typeof search === 'string')
|
|
30
|
+
return fail(c, 400, search, 'invalid');
|
|
31
|
+
await releaseExpiredHolds(db);
|
|
32
|
+
return c.json(computeOffers(await loadCtx(db, search.arrival, search.departure), search));
|
|
33
|
+
}
|
|
34
|
+
export async function hold(c) {
|
|
35
|
+
const body = await c.req.json().catch(() => null);
|
|
36
|
+
if (!body || typeof body !== 'object' || body.website)
|
|
37
|
+
return fail(c, 400, 'Invalid request.', 'invalid');
|
|
38
|
+
if (!await rateLimit(c.env, `stays-hold:${clientKey(c)}`, 15, 3600))
|
|
39
|
+
return fail(c, 429, 'Too many requests. Try again later.', 'rate_limited');
|
|
40
|
+
const name = text(body.guest?.name, 120), email = text(body.guest?.email, 254).toLowerCase();
|
|
41
|
+
if (!name || !validEmail(email) || body.acceptTerms !== true)
|
|
42
|
+
return fail(c, 400, 'Name, a valid email and acceptance of the conditions are required.', 'invalid');
|
|
43
|
+
const db = await ensureSchema(c.env), s = await loadSettings(db), now = Date.now();
|
|
44
|
+
const search = parseSearch({ arrival: body.arrival, departure: body.departure, rooms: body.rooms, promo: body.promo }, s, localParts(now, s.timezone).date);
|
|
45
|
+
if (typeof search === 'string')
|
|
46
|
+
return fail(c, 400, search, 'invalid');
|
|
47
|
+
await releaseExpiredHolds(db);
|
|
48
|
+
const ctx = await loadCtx(db, search.arrival, search.departure, now);
|
|
49
|
+
const built = buildDrafts(ctx, search.arrival, search.departure, body.rooms.map(r => ({ ...r })), search.promo);
|
|
50
|
+
if (!('drafts' in built))
|
|
51
|
+
return fail(c, 409, built.error, built.code, built.warnings);
|
|
52
|
+
const { drafts } = built, origin = new URL(c.req.url).origin;
|
|
53
|
+
const payload = {
|
|
54
|
+
arrival: search.arrival, departure: search.departure, drafts, guest: { name, email, phone: text(body.guest?.phone, 40), country: text(body.guest?.country, 2).toUpperCase() }, locale: body.locale === 'de' ? 'de' : 'en',
|
|
55
|
+
note: text(body.note, 500), promo: search.promo, currency: s.currency, guarantee: strictest(drafts), dueNow: drafts.reduce((sum, d) => sum + d.dueNow, 0),
|
|
56
|
+
successPath: safePath(body.successPath, '/book/confirmation'), cancelPath: safePath(body.cancelPath, '/book'),
|
|
57
|
+
};
|
|
58
|
+
const id = randomToken(), expiresAt = now + s.holdMinutes * 60000, items = aggregateItems(drafts);
|
|
59
|
+
try {
|
|
60
|
+
const results = await db.batch([
|
|
61
|
+
...acquireStmts(db, items),
|
|
62
|
+
db.prepare('INSERT INTO stay_holds (id, expires_at, payload_json, created_at) VALUES (?, ?, ?, ?)').bind(id, expiresAt, JSON.stringify(payload), now),
|
|
63
|
+
...items.map(i => db.prepare('INSERT INTO stay_hold_items (hold_id, room_type_id, arrival, departure, qty) VALUES (?, ?, ?, ?, ?)').bind(id, i.roomTypeId, i.arrival, i.departure, i.qty)),
|
|
64
|
+
]);
|
|
65
|
+
// Every night must have been taken; a missing inventory row means the night is not for sale.
|
|
66
|
+
if (items.some((i, n) => results[n].meta.changes !== (Date.parse(i.departure) - Date.parse(i.arrival)) / 86400000)) {
|
|
67
|
+
await releaseHold(db, id);
|
|
68
|
+
return fail(c, 409, 'This room is no longer available.', 'unavailable');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (isOverbooked(error))
|
|
73
|
+
return fail(c, 409, 'This room is no longer available.', 'unavailable');
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
if (payload.guarantee === 'none') {
|
|
77
|
+
await finalizeHold(c.env, db, origin, id);
|
|
78
|
+
const done = await db.prepare('SELECT b.manage_token, b.reference FROM stay_holds h JOIN stay_bookings b ON b.id = h.booking_id WHERE h.id = ?').bind(id).first();
|
|
79
|
+
return c.json({ status: 'confirmed', holdId: id, expiresAt, manageToken: done?.manage_token, reference: done?.reference });
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
return c.json({ status: 'payment_required', holdId: id, expiresAt, url: await startCheckout(c.env, db, origin, id, payload) });
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
console.error('Stays checkout failed:', error);
|
|
86
|
+
await releaseHold(db, id);
|
|
87
|
+
return fail(c, 502, 'Payment is unavailable right now.', 'payment_failed');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export async function holdStatus(c) {
|
|
91
|
+
const db = await ensureSchema(c.env);
|
|
92
|
+
const row = await db.prepare('SELECT h.status, b.manage_token, b.reference FROM stay_holds h LEFT JOIN stay_bookings b ON b.id = h.booking_id WHERE h.id = ?').bind(c.req.param('id') ?? '').first();
|
|
93
|
+
if (!row)
|
|
94
|
+
return fail(c, 404, 'Not found.', 'not_found');
|
|
95
|
+
return c.json(row.status === 'converted' ? { status: 'confirmed', manageToken: row.manage_token, reference: row.reference } : { status: row.status === 'active' ? 'pending' : 'expired' });
|
|
96
|
+
}
|
|
97
|
+
async function byToken(c) {
|
|
98
|
+
const value = c.req.param('token') ?? '';
|
|
99
|
+
if (value.length < 32 || !await rateLimit(c.env, `stays-manage:${clientKey(c)}`, 60, 3600))
|
|
100
|
+
return null;
|
|
101
|
+
const db = await ensureSchema(c.env);
|
|
102
|
+
const booking = await db.prepare('SELECT * FROM stay_bookings WHERE manage_token = ?').bind(value).first();
|
|
103
|
+
return booking ? { db, booking, s: await loadSettings(db) } : null;
|
|
104
|
+
}
|
|
105
|
+
export async function booking(c) {
|
|
106
|
+
const found = await byToken(c);
|
|
107
|
+
return found ? c.json(await bookingView(found.db, found.s, found.booking)) : fail(c, 404, 'Booking not found.', 'not_found');
|
|
108
|
+
}
|
|
109
|
+
export async function cancel(c) {
|
|
110
|
+
const found = await byToken(c);
|
|
111
|
+
if (!found)
|
|
112
|
+
return fail(c, 404, 'Booking not found.', 'not_found');
|
|
113
|
+
const body = await c.req.json().catch(() => ({}));
|
|
114
|
+
const { db, booking, s } = found, now = Date.now();
|
|
115
|
+
const rows = (await db.prepare("SELECT * FROM stay_reservations WHERE booking_id = ? AND status = 'booked' AND (? IS NULL OR id = ?)").bind(booking.id, body.reservationId ?? null, body.reservationId ?? null).all()).results;
|
|
116
|
+
if (!rows.length)
|
|
117
|
+
return fail(c, 404, 'Nothing to cancel.', 'not_found');
|
|
118
|
+
if (rows.some(r => arrivalAt(s, r.arrival) <= now))
|
|
119
|
+
return fail(c, 409, 'This booking can no longer be cancelled online. Please call us.', 'too_late');
|
|
120
|
+
const result = await cancelReservations(c.env, db, new URL(c.req.url).origin, booking, rows);
|
|
121
|
+
return c.json({ booking: await bookingView(db, s, booking), fee: result.fee, refunded: result.refunded, charged: result.charged, ...(result.paymentLink ? { paymentLink: true } : {}) });
|
|
122
|
+
}
|
|
123
|
+
/** iCal feed of one unit's reservations and blocks (no guest data). */
|
|
124
|
+
export async function icalExport(c) {
|
|
125
|
+
const db = await ensureSchema(c.env);
|
|
126
|
+
const feed = await db.prepare("SELECT * FROM stay_ical_feeds WHERE token = ? AND direction = 'out'").bind((c.req.param('file') ?? '').replace(/\.ics$/, '')).first();
|
|
127
|
+
if (!feed)
|
|
128
|
+
return c.notFound();
|
|
129
|
+
const s = await loadSettings(db), from = addDays(localParts(Date.now(), s.timezone).date, -7);
|
|
130
|
+
const [res, blocks] = await Promise.all([
|
|
131
|
+
db.prepare("SELECT id, arrival, departure FROM stay_reservations WHERE unit_id = ? AND status IN ('booked', 'checked_in', 'checked_out') AND departure >= ?").bind(feed.unit_id, from).all(),
|
|
132
|
+
db.prepare("SELECT id, date_from AS arrival, date_to AS departure FROM stay_blocks WHERE unit_id = ? AND source = 'manual' AND date_to >= ?").bind(feed.unit_id, from).all(),
|
|
133
|
+
]);
|
|
134
|
+
const day = (d) => d.replaceAll('-', ''), stamp = new Date().toISOString().replace(/[-:]|\.\d{3}/g, '');
|
|
135
|
+
const events = [...res.results, ...blocks.results].flatMap(e => ['BEGIN:VEVENT', `UID:${e.id}@stays`, `DTSTAMP:${stamp}`, `DTSTART;VALUE=DATE:${day(e.arrival)}`, `DTEND;VALUE=DATE:${day(e.departure)}`, 'SUMMARY:Reserved', 'END:VEVENT']);
|
|
136
|
+
return new Response(['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Hintergrund//Stays//EN', ...events, 'END:VCALENDAR', ''].join('\r\n'), { headers: { 'Content-Type': 'text/calendar; charset=utf-8', 'Cache-Control': 'private, max-age=300' } });
|
|
137
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/api/stays/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAO5C,QAAA,MAAM,WAAW;cAAwB,QAAQ;yCAAK,CAAC;AAmCvD,eAAe,WAAW,CAAC"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { authMiddleware, requirePermission } from '../../middleware/auth';
|
|
3
|
+
import { applySeason, createBlock, createEntity, deleteBlock, deleteEntity, getConfig, getRates, putRates, putSettings, syncFeed, updateEntity } from './admin';
|
|
4
|
+
import { cancelBooking, chargeFee, getBooking, invoicePdf, issueInvoice, listBookings, manualBooking, moveUnit, reservationAction, tape, updateGuest } from './bookings';
|
|
5
|
+
import { requireFeature } from '../../lib/features';
|
|
6
|
+
import { booking, cancel, hold, holdStatus, icalExport, info, offers } from './public';
|
|
7
|
+
const staysRoutes = new Hono();
|
|
8
|
+
const feature = requireFeature('stays');
|
|
9
|
+
staysRoutes.get('/info', feature, info);
|
|
10
|
+
staysRoutes.post('/offers', feature, offers);
|
|
11
|
+
staysRoutes.post('/hold', feature, hold);
|
|
12
|
+
staysRoutes.get('/hold/:id', feature, holdStatus);
|
|
13
|
+
staysRoutes.get('/booking/:token', feature, booking);
|
|
14
|
+
staysRoutes.post('/booking/:token/cancel', feature, cancel);
|
|
15
|
+
staysRoutes.get('/ical/:file', feature, icalExport);
|
|
16
|
+
staysRoutes.use('/admin/*', feature, authMiddleware, requirePermission('stays'));
|
|
17
|
+
staysRoutes.get('/admin/config', getConfig);
|
|
18
|
+
staysRoutes.put('/admin/settings', putSettings);
|
|
19
|
+
staysRoutes.post('/admin/entities/:entity', createEntity);
|
|
20
|
+
staysRoutes.put('/admin/entities/:entity/:id', updateEntity);
|
|
21
|
+
staysRoutes.delete('/admin/entities/:entity/:id', deleteEntity);
|
|
22
|
+
staysRoutes.get('/admin/rates', getRates);
|
|
23
|
+
staysRoutes.put('/admin/rates', putRates);
|
|
24
|
+
staysRoutes.post('/admin/rates/season', applySeason);
|
|
25
|
+
staysRoutes.get('/admin/tape', tape);
|
|
26
|
+
staysRoutes.post('/admin/blocks', createBlock);
|
|
27
|
+
staysRoutes.delete('/admin/blocks/:id', deleteBlock);
|
|
28
|
+
staysRoutes.post('/admin/feeds/:id/sync', syncFeed);
|
|
29
|
+
staysRoutes.get('/admin/bookings', listBookings);
|
|
30
|
+
staysRoutes.post('/admin/bookings', manualBooking);
|
|
31
|
+
staysRoutes.get('/admin/bookings/:id', getBooking);
|
|
32
|
+
staysRoutes.post('/admin/bookings/:id/cancel', cancelBooking);
|
|
33
|
+
staysRoutes.post('/admin/bookings/:id/charge', chargeFee);
|
|
34
|
+
staysRoutes.post('/admin/bookings/:id/invoice', issueInvoice);
|
|
35
|
+
staysRoutes.get('/admin/invoices/:id/pdf', invoicePdf);
|
|
36
|
+
staysRoutes.put('/admin/reservations/:id/unit', moveUnit);
|
|
37
|
+
staysRoutes.post('/admin/reservations/:id/action', reservationAction);
|
|
38
|
+
staysRoutes.put('/admin/guests/:id', updateGuest);
|
|
39
|
+
export default staysRoutes;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { HonoEnv } from '../../index';
|
|
3
|
+
/** POST /api/stripe/webhook — the project's only Stripe endpoint; dispatches by event type. */
|
|
4
|
+
export declare function handleStripeWebhook(c: Context<HonoEnv>): Promise<Response>;
|
|
5
|
+
//# sourceMappingURL=webhook.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../../src/api/stripe/webhook.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAM3C,+FAA+F;AAC/F,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqChF"}
|