@hintergrund/worker 0.3.18 → 0.3.20
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 +0 -2
- package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/agent-provider.handler.js +5 -10
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +3 -17
- 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/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 +14 -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/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 +36 -3
- 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 -278
- package/dist/lib/integration-health.d.ts +0 -15
- package/dist/lib/integration-health.d.ts.map +0 -1
- package/dist/lib/integration-health.js +0 -60
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import { DEFAULT_STAY_SETTINGS, STAY_ENTITIES, addDays, dayDiff, localParts, zonedToUtc, } from '@hintergrund/runtime-contracts';
|
|
2
|
+
export const HOUR = 3600000;
|
|
3
|
+
export const DAY = 86400000;
|
|
4
|
+
export const MAX_HORIZON_DAYS = 730;
|
|
5
|
+
export function newReference() {
|
|
6
|
+
const bytes = crypto.getRandomValues(new Uint8Array(6));
|
|
7
|
+
return Array.from(bytes, b => 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'[b % 32]).join('');
|
|
8
|
+
}
|
|
9
|
+
export const validDate = (value) => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) && new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value;
|
|
10
|
+
export const text = (value, max) => typeof value === 'string' ? value.replace(/[\r\n]+/g, ' ').trim().slice(0, max) : '';
|
|
11
|
+
export const int = (value, fallback = 0) => Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : fallback;
|
|
12
|
+
export const marks = (n) => Array(n).fill('?').join(',');
|
|
13
|
+
export const minutesOf = (hhmm) => { const [h, m] = hhmm.split(':').map(Number); return (h || 0) * 60 + (m || 0); };
|
|
14
|
+
export const ENTITY_DEFS = {
|
|
15
|
+
roomTypes: { table: 'stay_room_types', order: 'sort, name', cols: { name: ['name', 's'], baseOccupancy: ['base_occupancy', 'i'], maxAdults: ['max_adults', 'i'], maxChildren: ['max_children', 'i'], maxOccupancy: ['max_occupancy', 'i'], extraBed: ['extra_bed', 'b'], sort: ['sort', 'i'] } },
|
|
16
|
+
units: { table: 'stay_units', order: 'sort, name', cols: { roomTypeId: ['room_type_id', 's'], name: ['name', 's'], active: ['active', 'b'], sort: ['sort', 'i'] } },
|
|
17
|
+
ratePlans: { table: 'stay_rate_plans', order: 'sort, name', cols: { name: ['name', 's'], parentId: ['parent_id', 'ns'], adjType: ['adj_type', 's'], adjValue: ['adj_value', 'i'], isPublic: ['is_public', 'b'], promoCode: ['promo_code', 'ns'], board: ['board', 's'], cancellationPolicyId: ['cancellation_policy_id', 'ns'], boardSharePct: ['board_share_pct', 'i'], active: ['active', 'b'], sort: ['sort', 'i'] } },
|
|
18
|
+
policies: { table: 'stay_cancel_policies', order: 'name', cols: { name: ['name', 's'], tiers: ['tiers_json', 'j'], noShow: ['no_show_json', 'j'], guarantee: ['guarantee', 's'], depositPct: ['deposit_pct', 'i'] } },
|
|
19
|
+
extras: { table: 'stay_extras', order: 'sort, name', cols: { name: ['name', 's'], price: ['price', 'i'], per: ['per', 's'], vatRate: ['vat_rate', 'i'], active: ['active', 'b'], sort: ['sort', 'i'] } },
|
|
20
|
+
cityTax: { table: 'stay_city_tax', order: 'date_from, age_min', cols: { label: ['label', 's'], dateFrom: ['date_from', 's'], dateTo: ['date_to', 's'], amount: ['amount', 'i'], ageMin: ['age_min', 'i'], ageMax: ['age_max', 'i'], maxNights: ['max_nights', 'i'] } },
|
|
21
|
+
yieldRules: { table: 'stay_yield_rules', order: 'threshold_pct', cols: { roomTypeId: ['room_type_id', 'ns'], thresholdPct: ['threshold_pct', 'i'], upliftPct: ['uplift_pct', 'i'], active: ['active', 'b'] } },
|
|
22
|
+
seasons: { table: 'stay_seasons', order: 'date_from', cols: { name: ['name', 's'], roomTypeId: ['room_type_id', 's'], ratePlanId: ['rate_plan_id', 's'], dateFrom: ['date_from', 's'], dateTo: ['date_to', 's'], price: ['price', 'i'], weekdayDeltas: ['weekday_deltas_json', 'j'] } },
|
|
23
|
+
feeds: { table: 'stay_ical_feeds', order: 'unit_id, direction', cols: { unitId: ['unit_id', 's'], direction: ['direction', 's'], url: ['url', 's'], token: ['token', 'r'], lastSyncedAt: ['last_synced_at', 'r'], lastError: ['last_error', 'r'] } },
|
|
24
|
+
};
|
|
25
|
+
const entityOut = (entity, row) => ({
|
|
26
|
+
id: row.id,
|
|
27
|
+
...Object.fromEntries(Object.entries(ENTITY_DEFS[entity].cols).map(([key, [col, kind]]) => [key, kind === 'b' ? !!row[col] : kind === 'j' ? JSON.parse(row[col]) : row[col]])),
|
|
28
|
+
});
|
|
29
|
+
/** Writable `[column, value]` pairs of the keys the body carries. */
|
|
30
|
+
export function entityFields(entity, body) {
|
|
31
|
+
return Object.entries(ENTITY_DEFS[entity].cols).filter(([key, [, kind]]) => kind !== 'r' && key in body).map(([key, [col, kind]]) => {
|
|
32
|
+
const v = body[key];
|
|
33
|
+
return [col, kind === 'i' ? int(v) : kind === 'b' ? (v ? 1 : 0) : kind === 'j' ? JSON.stringify(v ?? (col === 'tiers_json' ? [] : {})) : kind === 'ns' ? (text(v, 200) || null) : text(v, 200)];
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
export async function loadSettings(db) {
|
|
37
|
+
const row = await db.prepare('SELECT data_json FROM stay_settings WHERE id = 1').first();
|
|
38
|
+
const saved = JSON.parse(row?.data_json ?? '{}');
|
|
39
|
+
return { ...DEFAULT_STAY_SETTINGS, ...saved, vat: { ...DEFAULT_STAY_SETTINGS.vat, ...saved.vat } };
|
|
40
|
+
}
|
|
41
|
+
export async function loadConfig(db) {
|
|
42
|
+
const [settings, rooms, ...lists] = await Promise.all([loadSettings(db), db.prepare('SELECT * FROM stay_rate_plan_rooms').all(),
|
|
43
|
+
...STAY_ENTITIES.map(n => db.prepare(`SELECT * FROM ${ENTITY_DEFS[n].table} ORDER BY ${ENTITY_DEFS[n].order}`).all())]);
|
|
44
|
+
const by = Object.fromEntries(STAY_ENTITIES.map((n, i) => [n, lists[i].results.map(r => entityOut(n, r))]));
|
|
45
|
+
by.ratePlans = by.ratePlans.map(p => ({ ...p, rooms: rooms.results.filter(r => r.rate_plan_id === p.id).map(r => ({ roomTypeId: r.room_type_id, extraAdult: r.extra_adult, childBands: JSON.parse(r.child_bands_json) })) }));
|
|
46
|
+
return { settings, roomTypes: by.roomTypes, units: by.units, ratePlans: by.ratePlans, policies: by.policies, extras: by.extras, cityTax: by.cityTax, yieldRules: by.yieldRules, seasons: by.seasons, feeds: by.feeds };
|
|
47
|
+
}
|
|
48
|
+
// --- Inventory ---
|
|
49
|
+
/** SQL: units that can be sold (active) minus those blocked out of order, for `?1` = room type and the given date column. */
|
|
50
|
+
const capacitySql = (dateCol) => `(SELECT COUNT(*) FROM stay_units WHERE room_type_id = ?1 AND active = 1)
|
|
51
|
+
- (SELECT COUNT(*) FROM stay_unit_nights n JOIN stay_units u ON u.id = n.unit_id WHERE u.room_type_id = ?1 AND u.active = 1 AND n.reservation_id IS NULL AND n.date = ${dateCol})`;
|
|
52
|
+
/** Recomputes capacity of a room type from `from` on; the CHECK throws when more is sold than the new capacity (409 for the caller). */
|
|
53
|
+
export const syncCapacity = (db, roomTypeId, from) => db.prepare(`UPDATE stay_inventory SET capacity = MAX(0, ${capacitySql('stay_inventory.date')}) WHERE room_type_id = ?1 AND date >= ?2`).bind(roomTypeId, from);
|
|
54
|
+
/** Creates the inventory rows up to 24 months ahead for every room type; existing rows are left alone. */
|
|
55
|
+
export async function seedInventory(db, today) {
|
|
56
|
+
const types = (await db.prepare('SELECT id FROM stay_room_types').all()).results;
|
|
57
|
+
await db.batch(types.map(t => db.prepare(`WITH RECURSIVE d(date) AS (SELECT ?2 UNION ALL SELECT date(date, '+1 day') FROM d WHERE date < ?3)
|
|
58
|
+
INSERT OR IGNORE INTO stay_inventory (room_type_id, date, capacity, sold) SELECT ?1, d.date, MAX(0, ${capacitySql('d.date')}), 0 FROM d`).bind(t.id, today, addDays(today, MAX_HORIZON_DAYS))));
|
|
59
|
+
}
|
|
60
|
+
/** Statement inserting one unit_night per night of [from, to) for a reservation or block. */
|
|
61
|
+
export const nightsInsert = (db, unitId, from, to, ref, ignore = false) => db.prepare(`WITH RECURSIVE d(date) AS (SELECT ?1 UNION ALL SELECT date(date, '+1 day') FROM d WHERE date < date(?2, '-1 day'))
|
|
62
|
+
INSERT ${ignore ? 'OR IGNORE ' : ''}INTO stay_unit_nights (unit_id, date, reservation_id, block_id) SELECT ?3, date, ?4, ?5 FROM d`).bind(from, to, unitId, ref.reservationId ?? null, ref.blockId ?? null);
|
|
63
|
+
/** Puts a reservation on a free unit of its room type when one exists; a lost race leaves it unassigned. */
|
|
64
|
+
export async function autoAssign(db, reservationId) {
|
|
65
|
+
const r = await db.prepare('SELECT * FROM stay_reservations WHERE id = ? AND unit_id IS NULL').bind(reservationId).first();
|
|
66
|
+
if (!r)
|
|
67
|
+
return;
|
|
68
|
+
const unit = await db.prepare(`SELECT id FROM stay_units u WHERE room_type_id = ? AND active = 1 AND NOT EXISTS
|
|
69
|
+
(SELECT 1 FROM stay_unit_nights n WHERE n.unit_id = u.id AND n.date >= ? AND n.date < ?) ORDER BY sort, name LIMIT 1`).bind(r.room_type_id, r.arrival, r.departure).first();
|
|
70
|
+
if (!unit)
|
|
71
|
+
return;
|
|
72
|
+
try {
|
|
73
|
+
await db.batch([nightsInsert(db, unit.id, r.arrival, r.departure, { reservationId }), db.prepare('UPDATE stay_reservations SET unit_id = ? WHERE id = ?').bind(unit.id, reservationId)]);
|
|
74
|
+
}
|
|
75
|
+
catch { /* taken meanwhile */ }
|
|
76
|
+
}
|
|
77
|
+
/** Everything the offer engine needs for stays touching [from, to] (both inclusive: the departure day carries the CTD flag). */
|
|
78
|
+
export async function loadCtx(db, from, to, now = Date.now()) {
|
|
79
|
+
const s = await loadSettings(db);
|
|
80
|
+
const [types, plans, planRooms, days, inv, yields, policies, tax, extras] = await db.batch([
|
|
81
|
+
db.prepare('SELECT * FROM stay_room_types ORDER BY sort, name'), db.prepare('SELECT * FROM stay_rate_plans WHERE active = 1 ORDER BY sort, name'), db.prepare('SELECT * FROM stay_rate_plan_rooms'),
|
|
82
|
+
db.prepare('SELECT * FROM stay_rate_days WHERE date BETWEEN ? AND ?').bind(from, to), db.prepare('SELECT * FROM stay_inventory WHERE date BETWEEN ? AND ?').bind(from, to),
|
|
83
|
+
db.prepare('SELECT * FROM stay_yield_rules WHERE active = 1'), db.prepare('SELECT * FROM stay_cancel_policies'), db.prepare('SELECT * FROM stay_city_tax WHERE date_to >= ? AND date_from <= ?').bind(from, to),
|
|
84
|
+
db.prepare('SELECT * FROM stay_extras WHERE active = 1 ORDER BY sort, name'),
|
|
85
|
+
]);
|
|
86
|
+
const map = (rows, key) => new Map(rows.map(r => [key(r), r]));
|
|
87
|
+
return {
|
|
88
|
+
s, now, today: localParts(now, s.timezone).date,
|
|
89
|
+
types: map(types.results, r => r.id), plans: map(plans.results, r => r.id), planRooms: map(planRooms.results, r => `${r.rate_plan_id}|${r.room_type_id}`),
|
|
90
|
+
days: map(days.results, r => `${r.room_type_id}|${r.rate_plan_id}|${r.date}`), inv: map(inv.results, r => `${r.room_type_id}|${r.date}`),
|
|
91
|
+
yields: yields.results, policies: map(policies.results, r => r.id), tax: tax.results, extras: map(extras.results, r => r.id),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const nightsOf = (arrival, departure) => Array.from({ length: dayDiff(arrival, departure) }, (_, i) => addDays(arrival, i));
|
|
95
|
+
/** Rooms of a type free on every night; holds are inside `sold`. */
|
|
96
|
+
export function available(ctx, roomTypeId, arrival, departure) {
|
|
97
|
+
let free = Infinity;
|
|
98
|
+
for (const date of nightsOf(arrival, departure)) {
|
|
99
|
+
const row = ctx.inv.get(`${roomTypeId}|${date}`);
|
|
100
|
+
free = Math.min(free, row ? row.capacity - row.sold : 0);
|
|
101
|
+
}
|
|
102
|
+
return Number.isFinite(free) ? Math.max(0, free) : 0;
|
|
103
|
+
}
|
|
104
|
+
function basePrice(ctx, roomTypeId, plan, date, depth = 0) {
|
|
105
|
+
const own = ctx.days.get(`${roomTypeId}|${plan.id}|${date}`)?.price;
|
|
106
|
+
if (own != null)
|
|
107
|
+
return own;
|
|
108
|
+
const parent = plan.parent_id && depth < 4 ? ctx.plans.get(plan.parent_id) : undefined;
|
|
109
|
+
const base = parent ? basePrice(ctx, roomTypeId, parent, date, depth + 1) : null;
|
|
110
|
+
if (base == null)
|
|
111
|
+
return null;
|
|
112
|
+
return Math.max(0, Math.round(plan.adj_type === 'pct' ? base * (1 + plan.adj_value / 100) : base + plan.adj_value));
|
|
113
|
+
}
|
|
114
|
+
/** Yield: the biggest uplift of a rule whose occupancy threshold the night has reached. */
|
|
115
|
+
export function yieldUplift(ctx, roomTypeId, date) {
|
|
116
|
+
const inv = ctx.inv.get(`${roomTypeId}|${date}`);
|
|
117
|
+
const occupancy = inv && inv.capacity > 0 ? inv.sold * 100 / inv.capacity : 0;
|
|
118
|
+
return Math.max(0, ...ctx.yields.filter(y => (!y.room_type_id || y.room_type_id === roomTypeId) && occupancy >= y.threshold_pct).map(y => y.uplift_pct));
|
|
119
|
+
}
|
|
120
|
+
/** Room price of a night (derived plans and yield applied, no occupancy supplements); null when not sellable. */
|
|
121
|
+
export function nightPrice(ctx, roomTypeId, plan, date) {
|
|
122
|
+
const base = basePrice(ctx, roomTypeId, plan, date);
|
|
123
|
+
return base == null ? null : Math.round(base * (1 + yieldUplift(ctx, roomTypeId, date) / 100));
|
|
124
|
+
}
|
|
125
|
+
/** Children from `childMaxAge` count as adults. */
|
|
126
|
+
export function splitGuests(s, room) {
|
|
127
|
+
const kids = room.childrenAges.filter(age => age < s.childMaxAge), grown = room.childrenAges.length - kids.length;
|
|
128
|
+
return { adults: room.adults + grown, kids };
|
|
129
|
+
}
|
|
130
|
+
export const vatLines = (parts) => {
|
|
131
|
+
const byRate = new Map();
|
|
132
|
+
for (const p of parts)
|
|
133
|
+
byRate.set(p.rate, (byRate.get(p.rate) ?? 0) + p.gross);
|
|
134
|
+
return [...byRate].filter(([, gross]) => gross).map(([rate, gross]) => ({ rate, gross, vat: Math.round(gross - gross / (1 + rate / 100)) }));
|
|
135
|
+
};
|
|
136
|
+
export function cityTax(ctx, arrival, departure, adults, kids) {
|
|
137
|
+
const ages = [...Array(adults).fill(99), ...kids];
|
|
138
|
+
let total = 0;
|
|
139
|
+
nightsOf(arrival, departure).forEach((date, index) => {
|
|
140
|
+
for (const rule of ctx.tax)
|
|
141
|
+
if (date >= rule.date_from && date <= rule.date_to && (!rule.max_nights || index < rule.max_nights))
|
|
142
|
+
total += rule.amount * ages.filter(age => age >= rule.age_min && age <= rule.age_max).length;
|
|
143
|
+
});
|
|
144
|
+
return total;
|
|
145
|
+
}
|
|
146
|
+
const HARD = new Set(['no_price', 'sold_out', 'not_attached']);
|
|
147
|
+
export function policyOf(ctx, plan) {
|
|
148
|
+
const p = plan.cancellation_policy_id ? ctx.policies.get(plan.cancellation_policy_id) : undefined;
|
|
149
|
+
return p ? { id: p.id, name: p.name, tiers: JSON.parse(p.tiers_json), noShow: JSON.parse(p.no_show_json), guarantee: p.guarantee, depositPct: p.deposit_pct }
|
|
150
|
+
: { id: null, name: '', tiers: [], noShow: { feeType: 'percent', value: 100 }, guarantee: 'none', depositPct: 0 };
|
|
151
|
+
}
|
|
152
|
+
/** Prices one room of a stay on one plan and lists every rule it breaks. */
|
|
153
|
+
export function quote(ctx, roomType, plan, room, arrival, departure) {
|
|
154
|
+
const problems = [];
|
|
155
|
+
const { adults, kids } = splitGuests(ctx.s, room);
|
|
156
|
+
const nights = nightsOf(arrival, departure);
|
|
157
|
+
const attached = ctx.planRooms.get(`${plan.id}|${roomType.id}`);
|
|
158
|
+
const out = { roomTypeId: roomType.id, ratePlanId: plan.id, planName: plan.name, board: plan.board, nightly: [], roomTotal: 0, vat: [], cityTax: 0, adults, kids, policy: policyOf(ctx, plan), problems, hard: false };
|
|
159
|
+
if (!attached) {
|
|
160
|
+
problems.push('not_attached');
|
|
161
|
+
out.hard = true;
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
if (adults < 1 || adults > roomType.max_adults || kids.length > roomType.max_children || adults + kids.length > roomType.max_occupancy)
|
|
165
|
+
problems.push('occupancy');
|
|
166
|
+
if (!available(ctx, roomType.id, arrival, departure))
|
|
167
|
+
problems.push('sold_out');
|
|
168
|
+
const bands = JSON.parse(attached.child_bands_json);
|
|
169
|
+
let uncovered = 0, childSum = 0;
|
|
170
|
+
for (const age of kids) {
|
|
171
|
+
const band = bands.find(b => age >= b.minAge && age <= b.maxAge);
|
|
172
|
+
if (band)
|
|
173
|
+
childSum += band.price;
|
|
174
|
+
else
|
|
175
|
+
uncovered++;
|
|
176
|
+
}
|
|
177
|
+
const extra = Math.max(0, adults + uncovered - roomType.base_occupancy) * attached.extra_adult + childSum;
|
|
178
|
+
for (const date of nights) {
|
|
179
|
+
const price = nightPrice(ctx, roomType.id, plan, date);
|
|
180
|
+
if (price == null) {
|
|
181
|
+
problems.push('no_price');
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
out.nightly.push({ date, price: price + extra });
|
|
185
|
+
}
|
|
186
|
+
const n = nights.length, rows = nights.map(d => ctx.days.get(`${roomType.id}|${plan.id}|${d}`));
|
|
187
|
+
const first = rows[0], last = ctx.days.get(`${roomType.id}|${plan.id}|${departure}`);
|
|
188
|
+
const daysAhead = dayDiff(ctx.today, arrival);
|
|
189
|
+
if (rows.some(r => r?.closed))
|
|
190
|
+
problems.push('closed');
|
|
191
|
+
if (first?.cta)
|
|
192
|
+
problems.push('cta');
|
|
193
|
+
if (last?.ctd)
|
|
194
|
+
problems.push('ctd');
|
|
195
|
+
if (first?.min_los_arrival && n < first.min_los_arrival)
|
|
196
|
+
problems.push('min_los_arrival');
|
|
197
|
+
if (rows.some(r => r?.min_los_through && n < r.min_los_through))
|
|
198
|
+
problems.push('min_los_through');
|
|
199
|
+
if (first?.max_los && n > first.max_los)
|
|
200
|
+
problems.push('max_los');
|
|
201
|
+
if (first?.min_advance != null && daysAhead < first.min_advance)
|
|
202
|
+
problems.push('min_advance');
|
|
203
|
+
if (first?.max_advance != null && daysAhead > first.max_advance)
|
|
204
|
+
problems.push('max_advance');
|
|
205
|
+
out.roomTotal = out.nightly.reduce((sum, night) => sum + night.price, 0);
|
|
206
|
+
const board = Math.round(out.roomTotal * plan.board_share_pct / 100);
|
|
207
|
+
out.vat = vatLines([{ rate: ctx.s.vat.accommodation, gross: out.roomTotal - board }, { rate: ctx.s.vat.board, gross: board }]);
|
|
208
|
+
out.cityTax = cityTax(ctx, arrival, departure, adults, kids);
|
|
209
|
+
out.hard = problems.some(p => HARD.has(p));
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
/** Instant the stay begins: arrival date at the check-in time. */
|
|
213
|
+
export const arrivalAt = (s, arrival) => zonedToUtc(arrival, minutesOf(s.checkInTime), s.timezone);
|
|
214
|
+
/** Fee of a cancellation (or no-show) made at `now`, from the policy snapshot and nightly prices. */
|
|
215
|
+
export function cancelFee(s, policy, r, now, noShow = false) {
|
|
216
|
+
const hours = (arrivalAt(s, r.arrival) - now) / HOUR;
|
|
217
|
+
const tier = noShow ? policy.noShow : [...policy.tiers].filter(t => t.hoursBeforeArrival >= hours).sort((a, b) => a.hoursBeforeArrival - b.hoursBeforeArrival)[0];
|
|
218
|
+
if (!tier)
|
|
219
|
+
return 0;
|
|
220
|
+
const fee = tier.feeType === 'nights' ? r.nightly.slice(0, Math.round(tier.value)).reduce((sum, n) => sum + n.price, 0) : tier.feeType === 'percent' ? Math.round(r.total * tier.value / 100) : Math.round(tier.value);
|
|
221
|
+
return Math.min(r.total, Math.max(0, fee));
|
|
222
|
+
}
|
|
223
|
+
export function dueNow(policy, total) {
|
|
224
|
+
return policy.guarantee === 'prepay' ? total : policy.guarantee === 'deposit' ? Math.round(total * policy.depositPct / 100) : 0;
|
|
225
|
+
}
|
|
226
|
+
export function summary(s, policy, arrival, total, now) {
|
|
227
|
+
const lead = policy.tiers.length ? Math.max(...policy.tiers.map(t => t.hoursBeforeArrival)) : 0;
|
|
228
|
+
const free = arrivalAt(s, arrival) - lead * HOUR;
|
|
229
|
+
return { policyId: policy.id, name: policy.name, guarantee: policy.guarantee, depositPct: policy.depositPct, tiers: policy.tiers, noShow: policy.noShow, freeUntil: free > now ? free : null, dueNow: dueNow(policy, total) };
|
|
230
|
+
}
|
|
231
|
+
export function parseSearch(body, s, today) {
|
|
232
|
+
if (!body || typeof body !== 'object' || !validDate(body.arrival) || !validDate(body.departure) || !Array.isArray(body.rooms))
|
|
233
|
+
return 'Invalid request.';
|
|
234
|
+
const nights = dayDiff(body.arrival, body.departure);
|
|
235
|
+
if (nights < 1 || nights > s.maxNights || body.arrival < today || dayDiff(today, body.arrival) > MAX_HORIZON_DAYS - s.maxNights)
|
|
236
|
+
return 'Invalid dates.';
|
|
237
|
+
if (!body.rooms.length || body.rooms.length > s.maxRooms)
|
|
238
|
+
return 'Invalid number of rooms.';
|
|
239
|
+
const rooms = body.rooms.map(r => ({ adults: int(r?.adults), childrenAges: (Array.isArray(r?.childrenAges) ? r.childrenAges : []).slice(0, 10).map((a) => Math.min(120, Math.max(0, int(a)))) }));
|
|
240
|
+
if (rooms.some(r => r.adults < 1 || r.adults > 10))
|
|
241
|
+
return 'Invalid guests.';
|
|
242
|
+
return { arrival: body.arrival, departure: body.departure, rooms, promo: text(body.promo, 40).toLowerCase() };
|
|
243
|
+
}
|
|
244
|
+
/** Private plans need their code; staff (no promo given) can use any. */
|
|
245
|
+
export const planEligible = (plan, promo) => (promo && plan.promo_code?.toLowerCase() === promo) || (!!plan.is_public && !plan.promo_code);
|
|
246
|
+
// --- Extras ---
|
|
247
|
+
export function priceExtras(ctx, picks, persons, nights) {
|
|
248
|
+
return (picks ?? []).slice(0, 10).flatMap(pick => {
|
|
249
|
+
const extra = ctx.extras.get(pick.extraId);
|
|
250
|
+
if (!extra)
|
|
251
|
+
return [];
|
|
252
|
+
const quantity = Math.min(20, Math.max(1, int(pick.quantity, 1)));
|
|
253
|
+
const total = extra.price * quantity * (extra.per === 'stay' ? 1 : extra.per === 'night' ? nights : persons * nights);
|
|
254
|
+
return [{ extraId: extra.id, name: extra.name, quantity, total, vatRate: extra.vat_rate }];
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
export function toDraft(ctx, q, arrival, departure, room, totalOverride) {
|
|
258
|
+
let nightly = q.nightly, roomTotal = q.roomTotal;
|
|
259
|
+
let vat = q.vat;
|
|
260
|
+
if (totalOverride != null && nightly.length) {
|
|
261
|
+
const each = Math.floor(totalOverride / nightly.length);
|
|
262
|
+
nightly = nightly.map((n, i) => ({ date: n.date, price: each + (i === 0 ? totalOverride - each * nightly.length : 0) }));
|
|
263
|
+
roomTotal = totalOverride;
|
|
264
|
+
const plan = ctx.plans.get(q.ratePlanId), board = Math.round(roomTotal * plan.board_share_pct / 100);
|
|
265
|
+
vat = vatLines([{ rate: ctx.s.vat.accommodation, gross: roomTotal - board }, { rate: ctx.s.vat.board, gross: board }]);
|
|
266
|
+
}
|
|
267
|
+
const extras = priceExtras(ctx, room.extras, q.adults + q.kids.length, nightly.length);
|
|
268
|
+
const total = roomTotal + extras.reduce((sum, e) => sum + e.total, 0);
|
|
269
|
+
return {
|
|
270
|
+
roomTypeId: q.roomTypeId, ratePlanId: q.ratePlanId, planName: q.planName, board: q.board, adults: q.adults, kids: q.kids, arrival, departure, nightly, roomTotal, total,
|
|
271
|
+
cityTax: q.cityTax, vat: vatLines([...vat.map(v => ({ rate: v.rate, gross: v.gross })), ...extras.map(e => ({ rate: e.vatRate, gross: e.total }))]), dueNow: dueNow(q.policy, total), policy: q.policy, extras,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
// --- Holds ---
|
|
275
|
+
/** Statements adding `qty` sold per night; the CHECK aborts the batch when a night is full. `guard` limits them to a still-valid hold. */
|
|
276
|
+
export function acquireStmts(db, items, guard) {
|
|
277
|
+
return items.map(i => db.prepare(`UPDATE stay_inventory SET sold = sold + ? WHERE room_type_id = ? AND date >= ? AND date < ?${guard ? " AND EXISTS (SELECT 1 FROM stay_holds WHERE id = ? AND status = 'active' AND expires_at = ?)" : ''}`)
|
|
278
|
+
.bind(i.qty, i.roomTypeId, i.arrival, i.departure, ...(guard ? [guard.holdId, guard.expiresAt] : [])));
|
|
279
|
+
}
|
|
280
|
+
export function aggregateItems(drafts) {
|
|
281
|
+
const map = new Map();
|
|
282
|
+
for (const d of drafts) {
|
|
283
|
+
const key = `${d.roomTypeId}|${d.arrival}|${d.departure}`;
|
|
284
|
+
map.set(key, { roomTypeId: d.roomTypeId, arrival: d.arrival, departure: d.departure, qty: (map.get(key)?.qty ?? 0) + 1 });
|
|
285
|
+
}
|
|
286
|
+
return [...map.values()];
|
|
287
|
+
}
|
|
288
|
+
/** Returns an expired hold's nights to the inventory, atomically with marking it expired. */
|
|
289
|
+
export async function releaseHold(db, holdId) {
|
|
290
|
+
const items = (await db.prepare('SELECT * FROM stay_hold_items WHERE hold_id = ?').bind(holdId).all()).results;
|
|
291
|
+
await db.batch([
|
|
292
|
+
...items.map(i => db.prepare("UPDATE stay_inventory SET sold = sold - ? WHERE room_type_id = ? AND date >= ? AND date < ? AND EXISTS (SELECT 1 FROM stay_holds WHERE id = ? AND status = 'active')").bind(i.qty, i.room_type_id, i.arrival, i.departure, holdId)),
|
|
293
|
+
db.prepare("UPDATE stay_holds SET status = 'expired' WHERE id = ? AND status = 'active'").bind(holdId),
|
|
294
|
+
]);
|
|
295
|
+
}
|
|
296
|
+
export async function releaseExpiredHolds(db, now = Date.now()) {
|
|
297
|
+
const due = (await db.prepare("SELECT id FROM stay_holds WHERE status = 'active' AND expires_at <= ? LIMIT 50").bind(now).all()).results;
|
|
298
|
+
for (const h of due)
|
|
299
|
+
await releaseHold(db, h.id);
|
|
300
|
+
}
|
|
301
|
+
/** Statements creating the booking, guest, reservations, extras and payments. With `holdId` they take effect only if this call converts the active hold (the previous statement is the claim). */
|
|
302
|
+
export function bookingStmts(db, b, holdId) {
|
|
303
|
+
const now = Date.now(), reservationIds = b.drafts.map(() => crypto.randomUUID());
|
|
304
|
+
const total = b.drafts.reduce((sum, d) => sum + d.total, 0), tax = b.drafts.reduce((sum, d) => sum + d.cityTax, 0);
|
|
305
|
+
const guarded = (sql, ...args) => db.prepare(`INSERT INTO ${sql} WHERE EXISTS (SELECT 1 FROM stay_bookings WHERE id = ?)`).bind(...args, b.id);
|
|
306
|
+
const ph = (n) => marks(n);
|
|
307
|
+
return {
|
|
308
|
+
reservationIds,
|
|
309
|
+
stmts: [
|
|
310
|
+
...(holdId ? [db.prepare("UPDATE stay_holds SET status = 'converted', booking_id = ? WHERE id = ? AND status = 'active'").bind(b.id, holdId)] : []),
|
|
311
|
+
db.prepare(`INSERT INTO stay_bookings (id, reference, guest_id, source, currency, total, city_tax, promo, guarantee, stripe_customer_id, stripe_payment_method_id, stripe_payment_intent_id, stripe_session_id, note, locale, manage_token, created_at)
|
|
312
|
+
SELECT ${ph(17)}${holdId ? ' WHERE changes() = 1' : ''}`).bind(b.id, b.reference, b.guestId, b.source, b.currency, total, tax, b.promo ?? null, b.guarantee, b.stripe?.customerId ?? null, b.stripe?.paymentMethodId ?? null, b.stripe?.paymentIntentId ?? null, b.stripe?.sessionId ?? null, b.note ?? '', b.locale, b.manageToken, now),
|
|
313
|
+
guarded(`stay_guests (id, name, email, phone, country, created_at) SELECT ${ph(6)}`, b.guestId, b.guest.name, b.guest.email, b.guest.phone ?? '', b.guest.country ?? '', now),
|
|
314
|
+
...b.drafts.flatMap((d, i) => [
|
|
315
|
+
guarded(`stay_reservations (id, booking_id, room_type_id, rate_plan_id, arrival, departure, adults, children_ages_json, nightly_json, total, city_tax, vat_json, due_now, policy_json, plan_name, board) SELECT ${ph(16)}`, reservationIds[i], b.id, d.roomTypeId, d.ratePlanId, d.arrival, d.departure, d.adults, JSON.stringify(d.kids), JSON.stringify(d.nightly), d.total, d.cityTax, JSON.stringify(d.vat), d.dueNow, JSON.stringify(d.policy), d.planName, d.board),
|
|
316
|
+
...d.extras.map(e => guarded(`stay_reservation_extras (reservation_id, extra_id, name, quantity, total, vat_rate) SELECT ${ph(6)}`, reservationIds[i], e.extraId, e.name, e.quantity, e.total, e.vatRate)),
|
|
317
|
+
]),
|
|
318
|
+
...(b.pays ?? []).map(p => guarded('stay_payments (id, booking_id, kind, stripe_id, amount, status, created_at) SELECT ?, ?, ?, ?, ?, ?, ?', crypto.randomUUID(), b.id, p.kind, p.stripeId, p.amount, 'succeeded', now)),
|
|
319
|
+
],
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/** Creates a booking in one batch (inventory taken with it, CHECK aborts on oversell), then assigns units. Throws when a night is full. */
|
|
323
|
+
export async function createBooking(db, b) {
|
|
324
|
+
const { stmts, reservationIds } = bookingStmts(db, b);
|
|
325
|
+
await db.batch([...acquireStmts(db, aggregateItems(b.drafts)), ...stmts]);
|
|
326
|
+
for (const [i, d] of b.drafts.entries()) {
|
|
327
|
+
if (d.unitId) {
|
|
328
|
+
try {
|
|
329
|
+
await db.batch([nightsInsert(db, d.unitId, d.arrival, d.departure, { reservationId: reservationIds[i] }), db.prepare('UPDATE stay_reservations SET unit_id = ? WHERE id = ?').bind(d.unitId, reservationIds[i])]);
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
catch { /* taken: fall through */ }
|
|
333
|
+
}
|
|
334
|
+
await autoAssign(db, reservationIds[i]);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
export const isOverbooked = (error) => /CHECK constraint/i.test(`${error} ${error?.cause ?? ''}`);
|
|
338
|
+
// --- Views ---
|
|
339
|
+
export async function bookingView(db, s, booking, now = Date.now()) {
|
|
340
|
+
const [guest, res, extras, pays, types] = await Promise.all([
|
|
341
|
+
db.prepare('SELECT name, email FROM stay_guests WHERE id = ?').bind(booking.guest_id).first(),
|
|
342
|
+
db.prepare('SELECT * FROM stay_reservations WHERE booking_id = ? ORDER BY arrival, id').bind(booking.id).all(),
|
|
343
|
+
db.prepare('SELECT e.* FROM stay_reservation_extras e JOIN stay_reservations r ON r.id = e.reservation_id WHERE r.booking_id = ?').bind(booking.id).all(),
|
|
344
|
+
db.prepare("SELECT kind, amount FROM stay_payments WHERE booking_id = ? AND status = 'succeeded'").bind(booking.id).all(),
|
|
345
|
+
db.prepare('SELECT id, name FROM stay_room_types').all(),
|
|
346
|
+
]);
|
|
347
|
+
const typeName = new Map(types.results.map(t => [t.id, t.name]));
|
|
348
|
+
return {
|
|
349
|
+
reference: booking.reference, status: booking.status, currency: booking.currency, guest: { name: guest?.name ?? '', email: guest?.email ?? '' },
|
|
350
|
+
reservations: res.results.map(r => {
|
|
351
|
+
const nightly = JSON.parse(r.nightly_json), live = r.status === 'booked';
|
|
352
|
+
return {
|
|
353
|
+
id: r.id, roomTypeName: typeName.get(r.room_type_id) ?? '', ratePlanName: r.plan_name, board: r.board, arrival: r.arrival, departure: r.departure, adults: r.adults, childrenAges: JSON.parse(r.children_ages_json),
|
|
354
|
+
status: r.status, nightly, extras: extras.results.filter(e => e.reservation_id === r.id).map(e => ({ name: e.name, quantity: e.quantity, total: e.total })), total: r.total, cityTax: r.city_tax,
|
|
355
|
+
cancelFee: live ? cancelFee(s, JSON.parse(r.policy_json), { arrival: r.arrival, nightly, total: r.total }, now) : 0, canCancel: live && arrivalAt(s, r.arrival) > now,
|
|
356
|
+
};
|
|
357
|
+
}),
|
|
358
|
+
total: booking.total, cityTax: booking.city_tax, paid: pays.results.reduce((sum, p) => sum + (p.kind === 'refund' ? -p.amount : p.kind === 'guarantee' ? 0 : p.amount), 0),
|
|
359
|
+
checkInTime: s.checkInTime, checkOutTime: s.checkOutTime, policyText: s.policyText,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Bindings } from '../../index';
|
|
2
|
+
import { type Row } from './core';
|
|
3
|
+
/** Fetches an import feed and replaces that feed's blocks: every event blocks the unit and lowers its room type's capacity. */
|
|
4
|
+
export declare function importFeed(db: D1Database, feed: Row): Promise<void>;
|
|
5
|
+
/** Scheduled: release expired holds, keep inventory 24 months ahead, import iCal feeds, purge ID data after retention. */
|
|
6
|
+
export declare function runStaysCron(env: Bindings): Promise<void>;
|
|
7
|
+
//# sourceMappingURL=cron.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cron.d.ts","sourceRoot":"","sources":["../../../src/api/stays/cron.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAuG,KAAK,GAAG,EAAE,MAAM,QAAQ,CAAC;AAKvI,+HAA+H;AAC/H,wBAAsB,UAAU,CAAC,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CA2BzE;AAED,0HAA0H;AAC1H,wBAAsB,YAAY,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAa/D"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { addDays, dayDiff, localParts } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { ensureSchema, createId } from '../../lib/project-db';
|
|
3
|
+
import { DAY, MAX_HORIZON_DAYS, loadSettings, nightsInsert, releaseExpiredHolds, seedInventory, syncCapacity } from './core';
|
|
4
|
+
import { featureEnabled } from '../../lib/features';
|
|
5
|
+
const dateOf = (v) => `${v.slice(0, 4)}-${v.slice(4, 6)}-${v.slice(6, 8)}`;
|
|
6
|
+
/** Fetches an import feed and replaces that feed's blocks: every event blocks the unit and lowers its room type's capacity. */
|
|
7
|
+
export async function importFeed(db, feed) {
|
|
8
|
+
const now = Date.now();
|
|
9
|
+
const fail = (message) => db.prepare('UPDATE stay_ical_feeds SET last_synced_at = ?, last_error = ? WHERE id = ?').bind(now, message.slice(0, 200), feed.id).run();
|
|
10
|
+
try {
|
|
11
|
+
const unit = await db.prepare('SELECT * FROM stay_units WHERE id = ?').bind(feed.unit_id).first();
|
|
12
|
+
if (!unit)
|
|
13
|
+
return void await fail('Unit not found.');
|
|
14
|
+
const response = await fetch(feed.url, { signal: AbortSignal.timeout(10000), headers: { Accept: 'text/calendar' } });
|
|
15
|
+
const body = await response.text();
|
|
16
|
+
if (!response.ok || body.length > 2_000_000 || !body.includes('BEGIN:VCALENDAR'))
|
|
17
|
+
return void await fail(`Feed unavailable (${response.status}).`);
|
|
18
|
+
const today = localParts(now, (await loadSettings(db)).timezone).date, last = addDays(today, MAX_HORIZON_DAYS);
|
|
19
|
+
const events = body.replace(/\r?\n[ \t]/g, '').split('BEGIN:VEVENT').slice(1).flatMap(raw => {
|
|
20
|
+
const start = /^DTSTART[^:\n]*:(\d{8})/m.exec(raw)?.[1], end = /^DTEND[^:\n]*:(\d{8})/m.exec(raw)?.[1];
|
|
21
|
+
if (!start || /^STATUS:CANCELLED/m.test(raw))
|
|
22
|
+
return [];
|
|
23
|
+
const from = dateOf(start) < today ? today : dateOf(start), to = end ? dateOf(end) : addDays(dateOf(start), 1);
|
|
24
|
+
return from < to && from < last ? [{ from, to: to > last ? last : to }] : [];
|
|
25
|
+
}).sort((a, b) => a.from.localeCompare(b.from)).slice(0, 100);
|
|
26
|
+
await db.batch([
|
|
27
|
+
db.prepare('DELETE FROM stay_unit_nights WHERE block_id IN (SELECT id FROM stay_blocks WHERE feed_id = ?)').bind(feed.id), db.prepare('DELETE FROM stay_blocks WHERE feed_id = ?').bind(feed.id),
|
|
28
|
+
...events.flatMap(e => { const id = createId('blk'); return [db.prepare("INSERT INTO stay_blocks (id, unit_id, date_from, date_to, reason, source, feed_id) VALUES (?, ?, ?, ?, 'iCal', 'ical', ?)").bind(id, unit.id, e.from, e.to, feed.id), nightsInsert(db, unit.id, e.from, e.to, { blockId: id }, true)]; }),
|
|
29
|
+
syncCapacity(db, unit.room_type_id, today),
|
|
30
|
+
]);
|
|
31
|
+
const expected = events.reduce((sum, e) => sum + dayDiff(e.from, e.to), 0);
|
|
32
|
+
const blocked = (await db.prepare('SELECT COUNT(*) AS n FROM stay_unit_nights WHERE block_id IN (SELECT id FROM stay_blocks WHERE feed_id = ?)').bind(feed.id).first())?.n ?? 0;
|
|
33
|
+
await db.prepare('UPDATE stay_ical_feeds SET last_synced_at = ?, last_error = ? WHERE id = ?').bind(now, blocked < expected ? `${expected - blocked} night(s) overlap bookings or other blocks.` : '', feed.id).run();
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
await fail(/CHECK|constraint/i.test(String(error)) ? 'Rooms are already sold on blocked nights.' : String(error.message ?? error));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Scheduled: release expired holds, keep inventory 24 months ahead, import iCal feeds, purge ID data after retention. */
|
|
40
|
+
export async function runStaysCron(env) {
|
|
41
|
+
if (!env.PROJECT_DB || !await featureEnabled(env, 'stays'))
|
|
42
|
+
return;
|
|
43
|
+
const db = await ensureSchema(env), now = Date.now();
|
|
44
|
+
await releaseExpiredHolds(db, now);
|
|
45
|
+
const today = localParts(now, (await loadSettings(db)).timezone).date;
|
|
46
|
+
if (await db.prepare("SELECT 1 FROM stay_room_types t WHERE COALESCE((SELECT MAX(date) FROM stay_inventory WHERE room_type_id = t.id), '') < ? LIMIT 1").bind(addDays(today, MAX_HORIZON_DAYS - 1)).first())
|
|
47
|
+
await seedInventory(db, today);
|
|
48
|
+
const feeds = (await db.prepare("SELECT * FROM stay_ical_feeds WHERE direction = 'in' AND (last_synced_at IS NULL OR last_synced_at < ?) LIMIT 5").bind(now - 15 * 60000).all()).results;
|
|
49
|
+
for (const feed of feeds)
|
|
50
|
+
await importFeed(db, feed);
|
|
51
|
+
await db.batch([
|
|
52
|
+
db.prepare('UPDATE stay_guests SET birthdate = NULL, id_doc = NULL, purge_after = NULL WHERE purge_after IS NOT NULL AND purge_after < ?').bind(now),
|
|
53
|
+
db.prepare("DELETE FROM stay_hold_items WHERE hold_id IN (SELECT id FROM stay_holds WHERE status = 'expired' AND expires_at < ?)").bind(now - 7 * DAY),
|
|
54
|
+
db.prepare("DELETE FROM stay_holds WHERE status = 'expired' AND expires_at < ?").bind(now - 7 * DAY),
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Bindings } from '../../index';
|
|
2
|
+
export type StayMail = 'confirmation' | 'cancelled' | 'payment_link';
|
|
3
|
+
/** Sends one booking email; a failed send is logged and never undoes the booking. */
|
|
4
|
+
export declare function sendStayMail(env: Bindings, db: D1Database, origin: string, bookingId: string, kind: StayMail, extra?: {
|
|
5
|
+
url?: string;
|
|
6
|
+
amount?: number;
|
|
7
|
+
}): Promise<void>;
|
|
8
|
+
//# sourceMappingURL=mail.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mail.d.ts","sourceRoot":"","sources":["../../../src/api/stays/mail.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAM5C,MAAM,MAAM,QAAQ,GAAG,cAAc,GAAG,WAAW,GAAG,cAAc,CAAC;AAyBrE,qFAAqF;AACrF,wBAAsB,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB7K"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { renderEmail } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { sendEmail } from '../../lib/email';
|
|
3
|
+
import { escapeHtml } from '../../lib/user-recovery';
|
|
4
|
+
import { readEmailLayout } from '../emails/handlers/settings.handler';
|
|
5
|
+
import { bookingView, loadSettings } from './core';
|
|
6
|
+
// Transactional copy: no marketing, no review requests.
|
|
7
|
+
const COPY = {
|
|
8
|
+
en: {
|
|
9
|
+
locale: 'en-GB', hello: (n) => `Hello ${n},`, manage: 'View or cancel your booking', ref: 'Booking reference', night: 'nights', adults: 'adults', children: 'children', total: 'Total (incl. VAT)',
|
|
10
|
+
tax: 'Tourist tax (payable at the hotel, not included)', checkin: 'Check-in from', checkout: 'Check-out until', pay: 'Pay now', paid: 'Paid',
|
|
11
|
+
confirmation: { subject: 'Your booking', text: 'Your booking is confirmed.' }, cancelled: { subject: 'Your booking was cancelled', text: 'Your booking has been cancelled.' },
|
|
12
|
+
payment_link: { subject: 'Payment request', text: 'Please complete this payment.' },
|
|
13
|
+
},
|
|
14
|
+
de: {
|
|
15
|
+
locale: 'de-DE', hello: (n) => `Hallo ${n},`, manage: 'Buchung ansehen oder stornieren', ref: 'Buchungsnummer', night: 'Nächte', adults: 'Erwachsene', children: 'Kinder', total: 'Gesamt (inkl. MwSt.)',
|
|
16
|
+
tax: 'Kurtaxe (vor Ort zu zahlen, nicht enthalten)', checkin: 'Check-in ab', checkout: 'Check-out bis', pay: 'Jetzt bezahlen', paid: 'Bezahlt',
|
|
17
|
+
confirmation: { subject: 'Ihre Buchung', text: 'Ihre Buchung ist bestätigt.' }, cancelled: { subject: 'Ihre Buchung wurde storniert', text: 'Ihre Buchung wurde storniert.' },
|
|
18
|
+
payment_link: { subject: 'Zahlungsaufforderung', text: 'Bitte schließen Sie diese Zahlung ab.' },
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
const money = (cents, currency, locale) => new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100);
|
|
22
|
+
function policyLines(view, booking, copy) {
|
|
23
|
+
return view.reservations.filter(r => r.status === 'booked').map(r => `<p>${escapeHtml(r.roomTypeName)}: ${escapeHtml(r.arrival)} - ${escapeHtml(r.departure)}, ${r.nightly.length} ${copy.night}, ${r.adults} ${copy.adults}${r.childrenAges.length ? `, ${r.childrenAges.length} ${copy.children}` : ''}<br>`
|
|
24
|
+
+ `${escapeHtml(r.ratePlanName)}: ${money(r.total, view.currency, copy.locale)}</p>`).join('');
|
|
25
|
+
}
|
|
26
|
+
/** Sends one booking email; a failed send is logged and never undoes the booking. */
|
|
27
|
+
export async function sendStayMail(env, db, origin, bookingId, kind, extra) {
|
|
28
|
+
try {
|
|
29
|
+
const booking = await db.prepare('SELECT * FROM stay_bookings WHERE id = ?').bind(bookingId).first();
|
|
30
|
+
if (!booking)
|
|
31
|
+
return;
|
|
32
|
+
const s = await loadSettings(db), view = await bookingView(db, s, booking);
|
|
33
|
+
if (!view.guest.email)
|
|
34
|
+
return;
|
|
35
|
+
const copy = COPY[booking.locale] ?? COPY.en;
|
|
36
|
+
const base = (env.PUBLIC_ORIGIN || origin).replace(/\/$/, '');
|
|
37
|
+
const manage = `${base}/book/manage?token=${booking.manage_token}`;
|
|
38
|
+
const body = `<p>${escapeHtml(copy.hello(view.guest.name))}</p><p>${copy[kind].text}</p><p><strong>${copy.ref}: ${escapeHtml(view.reference)}</strong></p>`
|
|
39
|
+
+ (kind === 'payment_link' ? `<p><a href="${escapeHtml(extra?.url ?? '')}">${copy.pay}: ${money(extra?.amount ?? 0, view.currency, copy.locale)}</a></p>`
|
|
40
|
+
: (kind === 'confirmation' ? policyLines(view, booking, copy) + `<p><strong>${copy.total}: ${money(view.total, view.currency, copy.locale)}</strong>${view.paid ? `<br>${copy.paid}: ${money(view.paid, view.currency, copy.locale)}` : ''}`
|
|
41
|
+
+ (view.cityTax ? `<br>${copy.tax}: ${money(view.cityTax, view.currency, copy.locale)}` : '') + `</p><p>${copy.checkin} ${escapeHtml(view.checkInTime)} · ${copy.checkout} ${escapeHtml(view.checkOutTime)}</p>`
|
|
42
|
+
+ (view.policyText ? `<p>${escapeHtml(view.policyText).replace(/\n/g, '<br>')}</p>` : '') : ''))
|
|
43
|
+
+ (kind === 'cancelled' ? '' : `<p><a href="${escapeHtml(manage)}">${copy.manage}</a></p>`);
|
|
44
|
+
const layout = await readEmailLayout(env).catch(() => undefined);
|
|
45
|
+
await sendEmail(env, { to: view.guest.email, toName: view.guest.name, subject: `${copy[kind].subject} ${view.reference}`, html: renderEmail(layout, body), idempotencyKey: `stay-${kind}-${bookingId}-${extra?.url ?? booking.status}` });
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
console.error(`Stay ${kind} email failed:`, error);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { StayHoldRoom, StayManualRoom, StayOffersResponse } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { type Ctx, type Draft } from './core';
|
|
3
|
+
/** Room types × rate plans that fit each requested room, with every restriction applied. */
|
|
4
|
+
export declare function computeOffers(ctx: Ctx, search: {
|
|
5
|
+
arrival: string;
|
|
6
|
+
departure: string;
|
|
7
|
+
rooms: {
|
|
8
|
+
adults: number;
|
|
9
|
+
childrenAges: number[];
|
|
10
|
+
}[];
|
|
11
|
+
promo: string;
|
|
12
|
+
}): StayOffersResponse;
|
|
13
|
+
export type DraftResult = {
|
|
14
|
+
drafts: Draft[];
|
|
15
|
+
} | {
|
|
16
|
+
error: string;
|
|
17
|
+
code: 'invalid' | 'unavailable' | 'restricted';
|
|
18
|
+
warnings?: string[];
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Re-prices the chosen rooms. Online (`staff` false) every rule is binding; staff only lose to missing prices and full nights,
|
|
22
|
+
* and the rules they override come back as warnings (`force` turns them into a go).
|
|
23
|
+
*/
|
|
24
|
+
export declare function buildDrafts(ctx: Ctx, arrival: string, departure: string, rooms: (StayHoldRoom | StayManualRoom)[], promo: string, staff?: boolean, force?: boolean): DraftResult & {
|
|
25
|
+
warnings?: string[];
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=offers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"offers.d.ts","sourceRoot":"","sources":["../../../src/api/stays/offers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAiB,MAAM,gCAAgC,CAAC;AAEtH,OAAO,EAAyD,KAAK,GAAG,EAAE,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAErG,4FAA4F;AAC5F,wBAAgB,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,EAAE,CAAA;KAAE,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,kBAAkB,CAqB9K;AAED,MAAM,MAAM,WAAW,GAAG;IAAE,MAAM,EAAE,KAAK,EAAE,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,SAAS,GAAG,aAAa,GAAG,YAAY,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAEvI;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,YAAY,GAAG,cAAc,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,UAAQ,EAAE,KAAK,UAAQ,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAoBtM"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { dayDiff } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { available, int, planEligible, quote, summary, toDraft } from './core';
|
|
3
|
+
/** Room types × rate plans that fit each requested room, with every restriction applied. */
|
|
4
|
+
export function computeOffers(ctx, search) {
|
|
5
|
+
const { arrival, departure } = search;
|
|
6
|
+
const plans = [...ctx.plans.values()].filter(plan => planEligible(plan, search.promo));
|
|
7
|
+
return {
|
|
8
|
+
arrival, departure, nights: dayDiff(arrival, departure), currency: ctx.s.currency,
|
|
9
|
+
rooms: search.rooms.map((request, index) => ({
|
|
10
|
+
index, request,
|
|
11
|
+
options: [...ctx.types.values()].flatMap(type => {
|
|
12
|
+
const free = available(ctx, type.id, arrival, departure);
|
|
13
|
+
const offers = free < 1 ? [] : plans.flatMap(plan => {
|
|
14
|
+
const q = quote(ctx, type, plan, request, arrival, departure);
|
|
15
|
+
if (q.problems.length)
|
|
16
|
+
return [];
|
|
17
|
+
return [{
|
|
18
|
+
ratePlanId: plan.id, name: plan.name, board: plan.board, promo: !!plan.promo_code, nightly: q.nightly, total: q.roomTotal, vat: q.vat, cityTax: q.cityTax,
|
|
19
|
+
cancellation: summary(ctx.s, q.policy, arrival, q.roomTotal, ctx.now),
|
|
20
|
+
}];
|
|
21
|
+
});
|
|
22
|
+
return offers.length ? [{ roomTypeId: type.id, name: type.name, available: free, plans: offers }] : [];
|
|
23
|
+
}),
|
|
24
|
+
})),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Re-prices the chosen rooms. Online (`staff` false) every rule is binding; staff only lose to missing prices and full nights,
|
|
29
|
+
* and the rules they override come back as warnings (`force` turns them into a go).
|
|
30
|
+
*/
|
|
31
|
+
export function buildDrafts(ctx, arrival, departure, rooms, promo, staff = false, force = false) {
|
|
32
|
+
const drafts = [], warnings = [];
|
|
33
|
+
for (const room of rooms) {
|
|
34
|
+
const type = ctx.types.get(room.roomTypeId);
|
|
35
|
+
const plan = room.ratePlanId ? ctx.plans.get(room.ratePlanId) : [...ctx.plans.values()].find(p => ctx.planRooms.has(`${p.id}|${room.roomTypeId}`) && (!p.parent_id));
|
|
36
|
+
if (!type || !plan || (!staff && !planEligible(plan, promo)))
|
|
37
|
+
return { error: 'Offer not available.', code: 'invalid' };
|
|
38
|
+
const request = { adults: int(room.adults), childrenAges: Array.isArray(room.childrenAges) ? room.childrenAges.slice(0, 10).map(a => int(a)) : [] };
|
|
39
|
+
const q = quote(ctx, type, plan, request, arrival, departure);
|
|
40
|
+
if (q.hard)
|
|
41
|
+
return { error: 'This room is no longer available.', code: 'unavailable', warnings: q.problems };
|
|
42
|
+
if (q.problems.length && !(staff && force))
|
|
43
|
+
return { error: 'Restrictions apply.', code: 'restricted', warnings: q.problems };
|
|
44
|
+
warnings.push(...q.problems);
|
|
45
|
+
const draft = toDraft(ctx, q, arrival, departure, room, 'totalOverride' in room ? room.totalOverride : undefined);
|
|
46
|
+
if ('unitId' in room && room.unitId)
|
|
47
|
+
draft.unitId = room.unitId;
|
|
48
|
+
drafts.push(draft);
|
|
49
|
+
}
|
|
50
|
+
// The same room type may be chosen for several rooms: together they must still fit.
|
|
51
|
+
for (const type of new Set(drafts.map(d => d.roomTypeId))) {
|
|
52
|
+
if (drafts.filter(d => d.roomTypeId === type).length > available(ctx, type, arrival, departure))
|
|
53
|
+
return { error: 'Not enough rooms left.', code: 'unavailable' };
|
|
54
|
+
}
|
|
55
|
+
return { drafts, warnings };
|
|
56
|
+
}
|