@hintergrund/worker 0.3.18 → 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.
Files changed (171) hide show
  1. package/dist/api/appointments/admin.d.ts +171 -0
  2. package/dist/api/appointments/admin.d.ts.map +1 -0
  3. package/dist/api/appointments/admin.js +275 -0
  4. package/dist/api/appointments/core.d.ts +114 -0
  5. package/dist/api/appointments/core.d.ts.map +1 -0
  6. package/dist/api/appointments/core.js +208 -0
  7. package/dist/api/appointments/cron.d.ts +9 -0
  8. package/dist/api/appointments/cron.d.ts.map +1 -0
  9. package/dist/api/appointments/cron.js +71 -0
  10. package/dist/api/appointments/emails.d.ts +5 -0
  11. package/dist/api/appointments/emails.d.ts.map +1 -0
  12. package/dist/api/appointments/emails.js +53 -0
  13. package/dist/api/appointments/public.d.ts +104 -0
  14. package/dist/api/appointments/public.d.ts.map +1 -0
  15. package/dist/api/appointments/public.js +129 -0
  16. package/dist/api/appointments/routes.d.ts +7 -0
  17. package/dist/api/appointments/routes.d.ts.map +1 -0
  18. package/dist/api/appointments/routes.js +28 -0
  19. package/dist/api/cms/handlers/agent-provider.handler.d.ts +0 -2
  20. package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -1
  21. package/dist/api/cms/handlers/agent-provider.handler.js +5 -10
  22. package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
  23. package/dist/api/cms/handlers/github-secrets.handler.js +3 -17
  24. package/dist/api/cms/handlers/integrations.handler.d.ts +2 -2
  25. package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -1
  26. package/dist/api/cms/handlers/integrations.handler.js +5 -11
  27. package/dist/api/cms/handlers/runtime.handler.d.ts +6 -0
  28. package/dist/api/cms/handlers/runtime.handler.d.ts.map +1 -0
  29. package/dist/api/cms/handlers/runtime.handler.js +42 -0
  30. package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -0
  31. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
  32. package/dist/api/cms/handlers/website-repo.handler.js +31 -14
  33. package/dist/api/cms/routes/index.d.ts.map +1 -1
  34. package/dist/api/cms/routes/index.js +6 -6
  35. package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -6
  36. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  37. package/dist/api/emails/handlers/campaigns.handler.js +127 -30
  38. package/dist/api/emails/handlers/public.handler.d.ts +0 -2
  39. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  40. package/dist/api/emails/handlers/public.handler.js +32 -77
  41. package/dist/api/emails/handlers/send.handler.js +2 -2
  42. package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -1
  43. package/dist/api/emails/handlers/subscribers.handler.js +9 -0
  44. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  45. package/dist/api/emails/routes/admin.routes.js +3 -1
  46. package/dist/api/emails/routes/mail.routes.d.ts.map +1 -1
  47. package/dist/api/emails/routes/mail.routes.js +19 -17
  48. package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
  49. package/dist/api/emails/routes/public.routes.js +1 -2
  50. package/dist/api/enquiries/routes.d.ts +7 -0
  51. package/dist/api/enquiries/routes.d.ts.map +1 -0
  52. package/dist/api/enquiries/routes.js +73 -0
  53. package/dist/api/members/handlers.d.ts +36 -0
  54. package/dist/api/members/handlers.d.ts.map +1 -0
  55. package/dist/api/members/handlers.js +322 -0
  56. package/dist/api/members/routes.d.ts +5 -0
  57. package/dist/api/members/routes.d.ts.map +1 -0
  58. package/dist/api/members/routes.js +20 -0
  59. package/dist/api/reservations/core.d.ts +25 -0
  60. package/dist/api/reservations/core.d.ts.map +1 -0
  61. package/dist/api/reservations/core.js +59 -0
  62. package/dist/api/reservations/mail.d.ts +7 -0
  63. package/dist/api/reservations/mail.d.ts.map +1 -0
  64. package/dist/api/reservations/mail.js +63 -0
  65. package/dist/api/reservations/routes.d.ts +7 -0
  66. package/dist/api/reservations/routes.d.ts.map +1 -0
  67. package/dist/api/reservations/routes.js +186 -0
  68. package/dist/api/shop/handlers/products.handler.d.ts +1 -1
  69. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  70. package/dist/api/shop/handlers/products.handler.js +3 -3
  71. package/dist/api/shop/handlers/public.handler.d.ts +3 -3
  72. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  73. package/dist/api/shop/handlers/public.handler.js +25 -28
  74. package/dist/api/shop/routes.d.ts +2 -4
  75. package/dist/api/shop/routes.d.ts.map +1 -1
  76. package/dist/api/shop/routes.js +8 -11
  77. package/dist/api/stays/actions.d.ts +13 -0
  78. package/dist/api/stays/actions.d.ts.map +1 -0
  79. package/dist/api/stays/actions.js +28 -0
  80. package/dist/api/stays/admin.d.ts +209 -0
  81. package/dist/api/stays/admin.d.ts.map +1 -0
  82. package/dist/api/stays/admin.js +228 -0
  83. package/dist/api/stays/bookings.d.ts +113 -0
  84. package/dist/api/stays/bookings.d.ts.map +1 -0
  85. package/dist/api/stays/bookings.js +254 -0
  86. package/dist/api/stays/core.d.ts +214 -0
  87. package/dist/api/stays/core.d.ts.map +1 -0
  88. package/dist/api/stays/core.js +361 -0
  89. package/dist/api/stays/cron.d.ts +7 -0
  90. package/dist/api/stays/cron.d.ts.map +1 -0
  91. package/dist/api/stays/cron.js +56 -0
  92. package/dist/api/stays/mail.d.ts +8 -0
  93. package/dist/api/stays/mail.d.ts.map +1 -0
  94. package/dist/api/stays/mail.js +50 -0
  95. package/dist/api/stays/offers.d.ts +27 -0
  96. package/dist/api/stays/offers.d.ts.map +1 -0
  97. package/dist/api/stays/offers.js +56 -0
  98. package/dist/api/stays/payments.d.ts +47 -0
  99. package/dist/api/stays/payments.d.ts.map +1 -0
  100. package/dist/api/stays/payments.js +148 -0
  101. package/dist/api/stays/public.d.ts +207 -0
  102. package/dist/api/stays/public.d.ts.map +1 -0
  103. package/dist/api/stays/public.js +137 -0
  104. package/dist/api/stays/routes.d.ts +7 -0
  105. package/dist/api/stays/routes.d.ts.map +1 -0
  106. package/dist/api/stays/routes.js +39 -0
  107. package/dist/api/stripe/webhook.d.ts +5 -0
  108. package/dist/api/stripe/webhook.d.ts.map +1 -0
  109. package/dist/api/stripe/webhook.js +45 -0
  110. package/dist/api/tickets/core.d.ts +40 -0
  111. package/dist/api/tickets/core.d.ts.map +1 -0
  112. package/dist/api/tickets/core.js +115 -0
  113. package/dist/api/tickets/routes.d.ts +5 -0
  114. package/dist/api/tickets/routes.d.ts.map +1 -0
  115. package/dist/api/tickets/routes.js +70 -0
  116. package/dist/index.d.ts +14 -10
  117. package/dist/index.d.ts.map +1 -1
  118. package/dist/index.js +40 -27
  119. package/dist/lib/appointments-schema.d.ts +6 -0
  120. package/dist/lib/appointments-schema.d.ts.map +1 -0
  121. package/dist/lib/appointments-schema.js +96 -0
  122. package/dist/lib/config.js +4 -4
  123. package/dist/lib/email-template.d.ts +2 -2
  124. package/dist/lib/email-template.d.ts.map +1 -1
  125. package/dist/lib/email-template.js +3 -3
  126. package/dist/lib/email.d.ts.map +1 -1
  127. package/dist/lib/email.js +12 -3
  128. package/dist/lib/features.d.ts +13 -0
  129. package/dist/lib/features.d.ts.map +1 -0
  130. package/dist/lib/features.js +19 -0
  131. package/dist/lib/mail-schema.d.ts +1 -1
  132. package/dist/lib/mail-schema.d.ts.map +1 -1
  133. package/dist/lib/mail-schema.js +0 -1
  134. package/dist/lib/mail.d.ts +23 -3
  135. package/dist/lib/mail.d.ts.map +1 -1
  136. package/dist/lib/mail.js +69 -23
  137. package/dist/lib/members.d.ts +41 -0
  138. package/dist/lib/members.d.ts.map +1 -0
  139. package/dist/lib/members.js +92 -0
  140. package/dist/lib/project-db.d.ts +1 -1
  141. package/dist/lib/project-db.d.ts.map +1 -1
  142. package/dist/lib/project-db.js +67 -8
  143. package/dist/lib/reservations-schema.d.ts +3 -0
  144. package/dist/lib/reservations-schema.d.ts.map +1 -0
  145. package/dist/lib/reservations-schema.js +35 -0
  146. package/dist/lib/stays-schema.d.ts +3 -0
  147. package/dist/lib/stays-schema.d.ts.map +1 -0
  148. package/dist/lib/stays-schema.js +247 -0
  149. package/dist/lib/stripe.d.ts +6 -0
  150. package/dist/lib/stripe.d.ts.map +1 -0
  151. package/dist/lib/stripe.js +9 -0
  152. package/dist/lib/template.d.ts +2 -1
  153. package/dist/lib/template.d.ts.map +1 -1
  154. package/dist/lib/template.js +4 -82
  155. package/dist/lib/user-recovery.d.ts.map +1 -1
  156. package/dist/lib/user-recovery.js +4 -2
  157. package/dist/lib/website-i18n.d.ts +17 -0
  158. package/dist/lib/website-i18n.d.ts.map +1 -1
  159. package/dist/lib/website-i18n.js +36 -3
  160. package/dist/middleware/auth.d.ts.map +1 -1
  161. package/dist/middleware/auth.js +8 -1
  162. package/dist/version.d.ts +2 -0
  163. package/dist/version.d.ts.map +1 -0
  164. package/dist/version.js +1 -0
  165. package/package.json +2 -2
  166. package/dist/api/cms/handlers/setup.handler.d.ts +0 -8
  167. package/dist/api/cms/handlers/setup.handler.d.ts.map +0 -1
  168. package/dist/api/cms/handlers/setup.handler.js +0 -278
  169. package/dist/lib/integration-health.d.ts +0 -15
  170. package/dist/lib/integration-health.d.ts.map +0 -1
  171. package/dist/lib/integration-health.js +0 -60
@@ -0,0 +1,208 @@
1
+ import { addDays, localParts, weekdayOf, zonedToUtc } from '@hintergrund/runtime-contracts';
2
+ import { featureEnabled, randomToken } from '../../lib/features';
3
+ import { creditsLeft, SEAT_STATUSES } from '../../lib/appointments-schema';
4
+ import { createId, ensureSchema } from '../../lib/project-db';
5
+ import { sendBookingEmails } from './emails';
6
+ export const MIN = 60000;
7
+ export async function getSettings(db, origin, fallbackOrigin) {
8
+ await db.prepare('INSERT OR IGNORE INTO appt_settings (id) VALUES (1)').run();
9
+ let settings = (await db.prepare('SELECT timezone, origin FROM appt_settings WHERE id = 1').first());
10
+ const wanted = fallbackOrigin || origin;
11
+ if (wanted && settings.origin !== wanted) {
12
+ await db.prepare('UPDATE appt_settings SET origin = ? WHERE id = 1').bind(wanted).run();
13
+ settings = { ...settings, origin: wanted };
14
+ }
15
+ return settings;
16
+ }
17
+ const overlaps = (aFrom, aTo, bFrom, bTo) => aFrom < bTo && bFrom < aTo;
18
+ /**
19
+ * Bookable starts of an appointment offering between two local dates (inclusive), each with the
20
+ * people free for it: working hours (or the day's override) minus blocks and busy sessions,
21
+ * stepped by the slot interval, after the minimum notice and within the horizon.
22
+ */
23
+ export async function computeSlots(db, offering, resourceIds, from, to, tz, now = Date.now()) {
24
+ const result = new Map();
25
+ if (!resourceIds.length)
26
+ return result;
27
+ const marks = resourceIds.map(() => '?').join(',');
28
+ const lo = zonedToUtc(addDays(from, -1), 0, tz), hi = zonedToUtc(addDays(to, 2), 0, tz);
29
+ const [rules, overrides, blocks, busy] = await Promise.all([
30
+ db.prepare(`SELECT resource_id, weekday, start_min, end_min FROM appt_rules WHERE resource_id IN (${marks})`).bind(...resourceIds).all(),
31
+ db.prepare(`SELECT resource_id, date, start_min, end_min FROM appt_overrides WHERE resource_id IN (${marks}) AND date BETWEEN ? AND ?`).bind(...resourceIds, from, to).all(),
32
+ db.prepare(`SELECT resource_id, starts_at AS a, ends_at AS b FROM appt_blocks WHERE resource_id IN (${marks}) AND starts_at < ? AND ends_at > ?`).bind(...resourceIds, hi, lo).all(),
33
+ db.prepare(`SELECT resource_id, busy_from AS a, busy_to AS b FROM appt_session_resources WHERE resource_id IN (${marks}) AND busy_from < ? AND busy_to > ?`).bind(...resourceIds, hi, lo).all(),
34
+ ]);
35
+ const taken = [...blocks.results, ...busy.results];
36
+ const earliest = now + offering.min_notice_min * MIN, latest = now + offering.horizon_days * 86400000;
37
+ const duration = offering.duration_min * MIN;
38
+ for (let date = from; date <= to; date = addDays(date, 1)) {
39
+ for (const resourceId of resourceIds) {
40
+ const override = overrides.results.filter(item => item.resource_id === resourceId && item.date === date);
41
+ const windows = override.length
42
+ ? override.filter(item => item.start_min !== null && item.end_min !== null).map(item => [item.start_min, item.end_min])
43
+ : rules.results.filter(rule => rule.resource_id === resourceId && rule.weekday === weekdayOf(date)).map(rule => [rule.start_min, rule.end_min]);
44
+ for (const [start, end] of windows) {
45
+ for (let minute = start; minute + offering.duration_min <= end; minute += offering.slot_interval_min) {
46
+ const startsAt = zonedToUtc(date, minute, tz);
47
+ if (startsAt < earliest || startsAt > latest)
48
+ continue;
49
+ const from_ = startsAt - offering.buffer_before_min * MIN, to_ = startsAt + duration + offering.buffer_after_min * MIN;
50
+ if (taken.some(item => item.resource_id === resourceId && overlaps(from_, to_, item.a, item.b)))
51
+ continue;
52
+ result.set(startsAt, [...(result.get(startsAt) ?? []), resourceId]);
53
+ }
54
+ }
55
+ }
56
+ }
57
+ return result;
58
+ }
59
+ export async function offeringResourceIds(db, offeringId) {
60
+ const rows = await db.prepare('SELECT r.id FROM appt_offering_resources o JOIN appt_resources r ON r.id = o.resource_id WHERE o.offering_id = ? AND r.active = 1 ORDER BY r.name').bind(offeringId).all();
61
+ return rows.results.map(row => row.id);
62
+ }
63
+ const errorText = (error) => String(error?.message ?? error);
64
+ const fail = (http, code, error) => ({ ok: false, http, code, error });
65
+ const customerUpsert = (db, input, now) => db.prepare(`INSERT INTO appt_customers (id, name, email, phone, created_at) VALUES (?, ?, ?, ?, ?)
66
+ ON CONFLICT(email) DO UPDATE SET name = excluded.name, phone = CASE WHEN excluded.phone <> '' THEN excluded.phone ELSE phone END`).bind(createId('cus'), input.name, input.email, input.phone, now);
67
+ const bookingInsert = (db, id, sessionId, input, status, passId, token, now) => db.prepare(`INSERT INTO appt_bookings (id, session_id, customer_id, pass_id, status, patient_type, insurance, reminder_consent_at, locale, cancel_token, created_at, updated_at)
68
+ VALUES (?, ?, (SELECT id FROM appt_customers WHERE email = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(id, sessionId, input.email, passId, status, input.patientType, input.insurance, input.consent ? now : null, input.locale, token, now, now);
69
+ /** Creates one appointment or class seat. A conflict rolls the batch back and surfaces as 409. */
70
+ export async function createBooking(env, db, tz, input) {
71
+ const now = Date.now();
72
+ const { offering } = input;
73
+ const token = randomToken(), id = createId('bk');
74
+ const approval = !input.manual && offering.requires_approval === 1;
75
+ if (!input.manual && offering.audience !== 'all' && input.patientType !== offering.audience)
76
+ return fail(400, 'invalid', `This offering is for ${offering.audience} patients only.`);
77
+ if (offering.kind === 'appointment') {
78
+ if (!input.startsAt)
79
+ return fail(400, 'invalid', 'startsAt is required.');
80
+ let candidates;
81
+ if (input.manual)
82
+ candidates = input.resourceId ? [input.resourceId] : await offeringResourceIds(db, offering.id);
83
+ else {
84
+ const date = localParts(input.startsAt, tz).date;
85
+ const ids = input.resourceId ? [input.resourceId] : await offeringResourceIds(db, offering.id);
86
+ const allowed = await offeringResourceIds(db, offering.id);
87
+ candidates = (await computeSlots(db, offering, ids.filter(item => allowed.includes(item)), date, date, tz, now)).get(input.startsAt) ?? [];
88
+ }
89
+ if (!candidates.length)
90
+ return fail(409, 'slot_taken', 'This time is no longer available.');
91
+ const status = approval ? 'pending' : 'booked';
92
+ const endsAt = input.startsAt + offering.duration_min * MIN;
93
+ for (const resourceId of candidates) {
94
+ const sessionId = createId('ses');
95
+ try {
96
+ await db.batch([
97
+ customerUpsert(db, input, now),
98
+ db.prepare('INSERT INTO appt_sessions (id, offering_id, starts_at, ends_at, capacity, created_at) VALUES (?, ?, ?, ?, 1, ?)').bind(sessionId, offering.id, input.startsAt, endsAt, now),
99
+ db.prepare('INSERT INTO appt_session_resources (session_id, resource_id, busy_from, busy_to) VALUES (?, ?, ?, ?)').bind(sessionId, resourceId, input.startsAt - offering.buffer_before_min * MIN, endsAt + offering.buffer_after_min * MIN),
100
+ bookingInsert(db, id, sessionId, input, status, null, token, now),
101
+ ]);
102
+ return { ok: true, id, token, status, startsAt: input.startsAt, endsAt };
103
+ }
104
+ catch (error) {
105
+ if (!errorText(error).includes('appt_overlap'))
106
+ throw error;
107
+ }
108
+ }
109
+ return fail(409, 'slot_taken', 'This time is no longer available.');
110
+ }
111
+ const session = input.session;
112
+ if (!session || session.status !== 'active' || session.offering_id !== offering.id)
113
+ return fail(404, 'not_found', 'Class not found.');
114
+ if (session.starts_at < now)
115
+ return fail(409, 'too_late', 'This class has already started.');
116
+ if (!input.manual && (session.starts_at < now + offering.min_notice_min * MIN || session.starts_at > now + offering.horizon_days * 86400000))
117
+ return fail(409, 'too_late', 'Booking for this class is closed.');
118
+ const passRow = input.usePass ? await db.prepare(`SELECT p.id FROM appt_passes p JOIN appt_customers c ON c.id = p.customer_id WHERE c.email = ? AND p.expires_at >= ? AND ${creditsLeft('p.id')} > 0 ORDER BY p.expires_at LIMIT 1`).bind(input.email, session.starts_at).first() : null;
119
+ let passId = passRow?.id ?? null;
120
+ const status = approval ? 'pending' : 'booked';
121
+ const done = (state) => ({ ok: true, id, token, status: state, startsAt: session.starts_at, endsAt: session.ends_at, payment: passId ? 'pass' : 'dropin' });
122
+ for (let attempt = 0; attempt < 3; attempt++) {
123
+ try {
124
+ await db.batch([customerUpsert(db, input, now), bookingInsert(db, id, session.id, input, status, passId, token, now)]);
125
+ return done(status);
126
+ }
127
+ catch (error) {
128
+ const text = errorText(error);
129
+ if (text.includes('appt_no_credit') && passId) {
130
+ passId = null;
131
+ continue;
132
+ }
133
+ if (text.includes('UNIQUE'))
134
+ return fail(409, 'already_booked', 'You already have a booking for this class.');
135
+ if (!text.includes('appt_full'))
136
+ throw error;
137
+ if (offering.waitlist_lock_min === null || (!input.manual && session.starts_at - offering.waitlist_lock_min * MIN <= now))
138
+ return fail(409, 'full', 'This class is full.');
139
+ try {
140
+ await db.batch([customerUpsert(db, input, now), bookingInsert(db, id, session.id, input, 'waitlisted', passId, token, now)]);
141
+ return done('waitlisted');
142
+ }
143
+ catch (waitError) {
144
+ if (errorText(waitError).includes('UNIQUE'))
145
+ return fail(409, 'already_booked', 'You already have a booking for this class.');
146
+ throw waitError;
147
+ }
148
+ }
149
+ }
150
+ return fail(409, 'full', 'This class is full.');
151
+ }
152
+ export const BOOKING_CONTEXT_SQL = `SELECT b.id, b.status, b.session_id, b.cancel_token, b.locale, b.pass_id, s.starts_at, s.ends_at, s.status AS session_status, s.offering_id,
153
+ o.kind, o.name AS offering_name, o.cancel_cutoff_min, o.waitlist_lock_min, c.name, c.email
154
+ FROM appt_bookings b JOIN appt_sessions s ON s.id = b.session_id JOIN appt_offerings o ON o.id = s.offering_id JOIN appt_customers c ON c.id = b.customer_id`;
155
+ const ACTIVE = ['pending', 'booked', 'waitlisted'];
156
+ const SEATED = ['pending', 'booked', 'attended', 'no_show'];
157
+ export const isActive = (status) => ACTIVE.includes(status);
158
+ /**
159
+ * Ends a booking and, for a class, promotes the first person in line into the freed seat in the same batch
160
+ * (until the waitlist lock window). A free appointment slot is released. Returns the promoted booking id.
161
+ */
162
+ export async function endBooking(env, db, booking, to, now = Date.now()) {
163
+ const statements = [db.prepare('UPDATE appt_bookings SET status = ?, updated_at = ? WHERE id = ? AND status IN (\'pending\',\'booked\',\'waitlisted\')').bind(to, now, booking.id)];
164
+ let head = null;
165
+ if (booking.kind === 'appointment') {
166
+ statements.push(db.prepare('DELETE FROM appt_session_resources WHERE session_id = ?').bind(booking.session_id), db.prepare('UPDATE appt_sessions SET status = \'cancelled\' WHERE id = ?').bind(booking.session_id));
167
+ }
168
+ else if (SEATED.includes(booking.status) && booking.waitlist_lock_min !== null && booking.starts_at - booking.waitlist_lock_min * MIN > now) {
169
+ head = await db.prepare(`SELECT b.id FROM appt_bookings b WHERE b.session_id = ? AND b.status = 'waitlisted' AND (b.pass_id IS NULL OR ${creditsLeft('b.pass_id')} > 0) ORDER BY b.created_at LIMIT 1`).bind(booking.session_id).first();
170
+ if (head)
171
+ statements.push(db.prepare(`UPDATE appt_bookings SET status = 'booked', updated_at = ? WHERE id = ? AND status = 'waitlisted'
172
+ AND (SELECT count(*) FROM appt_bookings WHERE session_id = ? AND status IN (${SEAT_STATUSES})) < (SELECT capacity FROM appt_sessions WHERE id = ?)`).bind(now, head.id, booking.session_id, booking.session_id));
173
+ }
174
+ const results = await db.batch(statements);
175
+ const promoted = head && results[results.length - 1].meta.changes === 1 ? head.id : null;
176
+ if (promoted)
177
+ await sendBookingEmails(env, db, [promoted], 'promoted').catch(error => console.error('Appointment email failed:', error));
178
+ return promoted;
179
+ }
180
+ /** Local dates from today for `days` days. */
181
+ export function datesAhead(tz, days, now = Date.now()) {
182
+ const today = localParts(now, tz).date;
183
+ return Array.from({ length: days }, (_, index) => addDays(today, index));
184
+ }
185
+ /** Gives `email` a pass from `product`: staff grants and paid shop orders share this. */
186
+ export function passStatements(db, product, name, email) {
187
+ const now = Date.now();
188
+ return [
189
+ db.prepare(`INSERT INTO appt_customers (id, name, email, phone, created_at) VALUES (?, ?, ?, '', ?) ON CONFLICT(email) DO UPDATE SET name = excluded.name`).bind(createId('cus'), name, email, now),
190
+ db.prepare('INSERT INTO appt_passes (id, product_id, customer_id, name, credits, expires_at, created_at) VALUES (?, ?, (SELECT id FROM appt_customers WHERE email = ?), ?, ?, ?, ?)')
191
+ .bind(createId('pas'), product.id, email, product.name, product.credits, now + product.validity_days * 86400000, now),
192
+ ];
193
+ }
194
+ /** A paid shop order grants a pass for every item whose shop product sells a class pack. */
195
+ export async function grantPurchasedPasses(env, order) {
196
+ if (!await featureEnabled(env, 'appointments'))
197
+ return;
198
+ const db = await ensureSchema(env);
199
+ const email = order.customer.email.trim().toLowerCase();
200
+ const statements = [];
201
+ for (const item of order.items) {
202
+ const product = await db.prepare('SELECT * FROM appt_products WHERE shop_product_id = ?').bind(item.productId).first();
203
+ for (let i = 0; product && i < item.quantity; i++)
204
+ statements.push(...passStatements(db, product, order.customer.name || email, email));
205
+ }
206
+ if (statements.length)
207
+ await db.batch(statements);
208
+ }
@@ -0,0 +1,9 @@
1
+ import type { Bindings } from '../../index';
2
+ /** Creates class sessions from the timetable `WEEKS_AHEAD` weeks ahead; existing ones (also cancelled) are left alone. */
3
+ export declare function materialise(db: D1Database, tz: string, only?: {
4
+ scheduleId?: string;
5
+ offeringId?: string;
6
+ }, now?: number): Promise<void>;
7
+ /** Scheduled entry point: timetable sessions, reminders and the retention purge. */
8
+ export declare function runAppointmentsCron(env: Bindings): Promise<void>;
9
+ //# sourceMappingURL=cron.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron.d.ts","sourceRoot":"","sources":["../../../src/api/appointments/cron.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAQ5C,0HAA0H;AAC1H,wBAAsB,WAAW,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAO,EAAE,GAAG,SAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BtJ;AA2BD,oFAAoF;AACpF,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOtE"}
@@ -0,0 +1,71 @@
1
+ import { APPOINTMENT_RETENTION_DAYS, addDays, localParts, weekdayOf, zonedToUtc } from '@hintergrund/runtime-contracts';
2
+ import { ensureSchema, createId } from '../../lib/project-db';
3
+ import { MIN, getSettings } from './core';
4
+ import { featureEnabled } from '../../lib/features';
5
+ import { sendBookingEmails } from './emails';
6
+ const WEEKS_AHEAD = 6;
7
+ /** Creates class sessions from the timetable `WEEKS_AHEAD` weeks ahead; existing ones (also cancelled) are left alone. */
8
+ export async function materialise(db, tz, only = {}, now = Date.now()) {
9
+ const schedules = (await db.prepare(`SELECT sc.*, o.duration_min, o.buffer_before_min, o.buffer_after_min, o.capacity FROM appt_schedules sc JOIN appt_offerings o ON o.id = sc.offering_id
10
+ WHERE o.active = 1 AND o.kind = 'class' AND (? IS NULL OR sc.id = ?) AND (? IS NULL OR sc.offering_id = ?)`).bind(only.scheduleId ?? null, only.scheduleId ?? null, only.offeringId ?? null, only.offeringId ?? null).all()).results;
11
+ const today = localParts(now, tz).date;
12
+ for (const schedule of schedules) {
13
+ const existing = new Set((await db.prepare('SELECT starts_at FROM appt_sessions WHERE schedule_id = ?').bind(schedule.id).all()).results.map(row => row.starts_at));
14
+ const people = [schedule.teacher_id, schedule.room_id].filter((id) => !!id);
15
+ for (let index = 0; index < WEEKS_AHEAD * 7; index++) {
16
+ const date = addDays(today, index);
17
+ if (weekdayOf(date) !== schedule.weekday || (schedule.valid_from && date < schedule.valid_from) || (schedule.valid_to && date > schedule.valid_to))
18
+ continue;
19
+ const startsAt = zonedToUtc(date, schedule.start_min, tz), endsAt = startsAt + schedule.duration_min * MIN;
20
+ if (startsAt <= now || existing.has(startsAt))
21
+ continue;
22
+ // Vacations and blocks keep a class from being created; a clash with another session is refused by the trigger.
23
+ if (people.length && await db.prepare(`SELECT 1 FROM appt_blocks WHERE resource_id IN (${people.map(() => '?').join(',')}) AND starts_at < ? AND ends_at > ? LIMIT 1`).bind(...people, endsAt, startsAt).first())
24
+ continue;
25
+ const id = createId('ses');
26
+ try {
27
+ await db.batch([
28
+ db.prepare('INSERT INTO appt_sessions (id, offering_id, schedule_id, starts_at, ends_at, capacity, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)').bind(id, schedule.offering_id, schedule.id, startsAt, endsAt, schedule.capacity, now),
29
+ ...people.map(resourceId => db.prepare('INSERT INTO appt_session_resources (session_id, resource_id, busy_from, busy_to) VALUES (?, ?, ?, ?)').bind(id, resourceId, startsAt - schedule.buffer_before_min * MIN, endsAt + schedule.buffer_after_min * MIN)),
30
+ ]);
31
+ }
32
+ catch (error) {
33
+ console.error(`Class on ${date} skipped:`, error.message);
34
+ }
35
+ }
36
+ }
37
+ }
38
+ /** Reminders go only to bookings that consented to one, in the last 24 hours before the start. */
39
+ async function sendReminders(env, db, now) {
40
+ const due = (await db.prepare(`SELECT b.id FROM appt_bookings b JOIN appt_sessions s ON s.id = b.session_id
41
+ WHERE b.status = 'booked' AND b.reminder_consent_at IS NOT NULL AND b.reminder_sent_at IS NULL AND s.status = 'active' AND s.starts_at > ? AND s.starts_at <= ?`).bind(now, now + 24 * 60 * MIN).all()).results;
42
+ for (const { id } of due) {
43
+ try {
44
+ await sendBookingEmails(env, db, [id], 'reminder');
45
+ await db.prepare('UPDATE appt_bookings SET reminder_sent_at = ? WHERE id = ?').bind(now, id).run();
46
+ }
47
+ catch (error) {
48
+ console.error('Appointment reminder failed:', error);
49
+ }
50
+ }
51
+ }
52
+ /** Bookings go 90 days after the appointment; passes in use keep theirs until the pass has run out too. */
53
+ async function purge(db, now) {
54
+ const cutoff = now - APPOINTMENT_RETENTION_DAYS * 86400000;
55
+ await db.batch([
56
+ db.prepare('DELETE FROM appt_bookings WHERE session_id IN (SELECT id FROM appt_sessions WHERE ends_at < ?1) AND (pass_id IS NULL OR pass_id IN (SELECT id FROM appt_passes WHERE expires_at < ?1))').bind(cutoff),
57
+ db.prepare('DELETE FROM appt_passes WHERE expires_at < ? AND id NOT IN (SELECT pass_id FROM appt_bookings WHERE pass_id IS NOT NULL)').bind(cutoff),
58
+ db.prepare('DELETE FROM appt_sessions WHERE ends_at < ? AND id NOT IN (SELECT session_id FROM appt_bookings)').bind(cutoff),
59
+ db.prepare('DELETE FROM appt_customers WHERE id NOT IN (SELECT customer_id FROM appt_bookings) AND id NOT IN (SELECT customer_id FROM appt_passes)'),
60
+ ]);
61
+ }
62
+ /** Scheduled entry point: timetable sessions, reminders and the retention purge. */
63
+ export async function runAppointmentsCron(env) {
64
+ if (!env.PROJECT_DB || !await featureEnabled(env, 'appointments'))
65
+ return;
66
+ const db = await ensureSchema(env);
67
+ const now = Date.now();
68
+ await materialise(db, (await getSettings(db)).timezone, {}, now);
69
+ await sendReminders(env, db, now);
70
+ await purge(db, now);
71
+ }
@@ -0,0 +1,5 @@
1
+ import type { Bindings } from '../../index';
2
+ export type BookingMail = 'confirmed' | 'requested' | 'waitlisted' | 'approved' | 'rejected' | 'cancelled' | 'promoted' | 'reminder';
3
+ /** One email per recipient; several bookings of one person (a series) share a single message. */
4
+ export declare function sendBookingEmails(env: Bindings, db: D1Database, bookingIds: string[], kind: BookingMail): Promise<void>;
5
+ //# sourceMappingURL=emails.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emails.d.ts","sourceRoot":"","sources":["../../../src/api/appointments/emails.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK5C,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG,WAAW,GAAG,YAAY,GAAG,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,UAAU,CAAC;AA6BrI,iGAAiG;AACjG,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAuB7H"}
@@ -0,0 +1,53 @@
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
+ // Subjects never name the service: an email subject can reveal that someone is a patient.
6
+ const TEXT = {
7
+ en: {
8
+ confirmed: ['Booking confirmation', 'Your booking is confirmed.'],
9
+ requested: ['Booking request received', 'We received your request. You will get another email once it is confirmed.'],
10
+ waitlisted: ['You are on the waiting list', 'The class is full. We will email you if a place becomes free.'],
11
+ approved: ['Booking confirmed', 'Your booking request was accepted.'],
12
+ rejected: ['Booking request declined', 'Unfortunately we could not accept your booking request.'],
13
+ cancelled: ['Booking cancelled', 'Your booking was cancelled.'],
14
+ promoted: ['A place is available', 'A place became free and your booking is now confirmed.'],
15
+ reminder: ['Reminder: your booking', 'This is a reminder of your booking.'],
16
+ },
17
+ de: {
18
+ confirmed: ['Buchungsbestätigung', 'Ihre Buchung ist bestätigt.'],
19
+ requested: ['Buchungsanfrage erhalten', 'Wir haben Ihre Anfrage erhalten. Sie bekommen eine weitere E-Mail, sobald sie bestätigt ist.'],
20
+ waitlisted: ['Sie stehen auf der Warteliste', 'Der Kurs ist voll. Wir schreiben Ihnen, wenn ein Platz frei wird.'],
21
+ approved: ['Buchung bestätigt', 'Ihre Buchungsanfrage wurde angenommen.'],
22
+ rejected: ['Buchungsanfrage abgelehnt', 'Leider konnten wir Ihre Buchungsanfrage nicht annehmen.'],
23
+ cancelled: ['Buchung storniert', 'Ihre Buchung wurde storniert.'],
24
+ promoted: ['Ein Platz ist frei', 'Ein Platz ist frei geworden und Ihre Buchung ist jetzt bestätigt.'],
25
+ reminder: ['Erinnerung an Ihre Buchung', 'Dies ist eine Erinnerung an Ihre Buchung.'],
26
+ },
27
+ };
28
+ const LINK = { en: 'Manage or cancel booking', de: 'Buchung ansehen oder stornieren' };
29
+ /** One email per recipient; several bookings of one person (a series) share a single message. */
30
+ export async function sendBookingEmails(env, db, bookingIds, kind) {
31
+ if (!bookingIds.length)
32
+ return;
33
+ const marks = bookingIds.map(() => '?').join(',');
34
+ const rows = (await db.prepare(`SELECT b.id, c.name, c.email, b.locale, b.cancel_token, s.starts_at, o.kind, o.name AS offering_name
35
+ FROM appt_bookings b JOIN appt_sessions s ON s.id = b.session_id JOIN appt_offerings o ON o.id = s.offering_id JOIN appt_customers c ON c.id = b.customer_id
36
+ WHERE b.id IN (${marks}) ORDER BY s.starts_at`).bind(...bookingIds).all()).results;
37
+ if (!rows.length)
38
+ return;
39
+ const settings = (await db.prepare('SELECT timezone, origin FROM appt_settings WHERE id = 1').first()) ?? { timezone: 'Europe/Berlin', origin: '' };
40
+ const origin = env.PUBLIC_ORIGIN || settings.origin;
41
+ const layout = await readEmailLayout(env);
42
+ const first = rows[0];
43
+ const locale = first.locale === 'de' ? 'de' : 'en';
44
+ const format = new Intl.DateTimeFormat(locale, { dateStyle: 'full', timeStyle: 'short', timeZone: settings.timezone });
45
+ const [subject, intro] = TEXT[locale][kind];
46
+ const items = rows.map(row => {
47
+ const link = kind === 'rejected' || kind === 'cancelled' || !origin ? '' : ` — <a href="${escapeHtml(`${origin.replace(/\/$/, '')}/appointment/manage?token=${row.cancel_token}`)}">${LINK[locale]}</a>`;
48
+ // Class names are public timetable entries; an appointment's service is not named.
49
+ return `<li>${escapeHtml(format.format(row.starts_at))}${row.kind === 'class' ? ` · ${escapeHtml(row.offering_name)}` : ''}${link}</li>`;
50
+ }).join('');
51
+ const html = `<p>${escapeHtml(first.name)},</p><p>${intro}</p><ul>${items}</ul>`;
52
+ await sendEmail(env, { to: first.email, toName: first.name, subject, html: renderEmail(layout, html) });
53
+ }
@@ -0,0 +1,104 @@
1
+ import type { Context } from 'hono';
2
+ import type { Bindings } from '../../index';
3
+ type C = Context<{
4
+ Bindings: Bindings;
5
+ }>;
6
+ export declare function listOfferings(c: C): Promise<Response & import("hono").TypedResponse<{
7
+ timezone: string;
8
+ offerings: {
9
+ id: string;
10
+ kind: import("@hintergrund/runtime-contracts").AppointmentKind;
11
+ name: string;
12
+ description: string;
13
+ durationMin: number;
14
+ priceCents: number;
15
+ capacity: number;
16
+ audience: import("@hintergrund/runtime-contracts").AppointmentAudience;
17
+ requiresApproval: boolean;
18
+ waitlist: boolean;
19
+ cancelCutoffMin: number;
20
+ resources: {
21
+ id: string;
22
+ name: string;
23
+ }[];
24
+ }[];
25
+ }, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
26
+ export declare function listSlots(c: C): Promise<(Response & import("hono").TypedResponse<{
27
+ error: string;
28
+ code: string;
29
+ }, 404, "json">) | (Response & import("hono").TypedResponse<{
30
+ timezone: string;
31
+ slots: {
32
+ startsAt: number;
33
+ endsAt: number;
34
+ }[];
35
+ }, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
36
+ export declare function listSessions(c: C): Promise<Response & import("hono").TypedResponse<{
37
+ timezone: string;
38
+ sessions: {
39
+ id: string;
40
+ offeringId: string;
41
+ startsAt: number;
42
+ endsAt: number;
43
+ teacher: string | null;
44
+ room: string | null;
45
+ capacity: number;
46
+ free: number;
47
+ waitlistOpen: boolean;
48
+ }[];
49
+ }, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
50
+ export declare function book(c: C): Promise<(Response & import("hono").TypedResponse<{
51
+ error: string;
52
+ code: string;
53
+ }, 400, "json">) | (Response & import("hono").TypedResponse<{
54
+ status: "booked";
55
+ token: string;
56
+ startsAt: number;
57
+ endsAt: number;
58
+ }, 201, "json">) | (Response & import("hono").TypedResponse<{
59
+ error: string;
60
+ code: string;
61
+ }, 429, "json">) | (Response & import("hono").TypedResponse<{
62
+ error: string;
63
+ code: string;
64
+ }, 404, "json">) | (Response & import("hono").TypedResponse<{
65
+ error: string;
66
+ code: "invalid" | "full" | "not_found" | "slot_taken" | "already_booked" | "too_late";
67
+ }, 400 | 404 | 409, "json">) | (Response & import("hono").TypedResponse<{
68
+ status: "pending" | "waitlisted" | "booked";
69
+ token: string;
70
+ startsAt: number;
71
+ endsAt: number;
72
+ payment: "pass" | "dropin" | undefined;
73
+ }, 201, "json">)>;
74
+ export declare function manage(c: C): Promise<(Response & import("hono").TypedResponse<{
75
+ error: string;
76
+ code: string;
77
+ }, 429, "json">) | (Response & import("hono").TypedResponse<{
78
+ error: string;
79
+ code: string;
80
+ }, 404, "json">) | (Response & import("hono").TypedResponse<{
81
+ status: import("@hintergrund/runtime-contracts").BookingStatus;
82
+ kind: import("@hintergrund/runtime-contracts").AppointmentKind;
83
+ offeringName: string;
84
+ startsAt: number;
85
+ endsAt: number;
86
+ timezone: string;
87
+ cancellable: boolean;
88
+ late: boolean;
89
+ cancelCutoffMin: number;
90
+ }, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
91
+ export declare function cancel(c: C): Promise<(Response & import("hono").TypedResponse<{
92
+ error: string;
93
+ code: string;
94
+ }, 429, "json">) | (Response & import("hono").TypedResponse<{
95
+ error: string;
96
+ code: string;
97
+ }, 404, "json">) | (Response & import("hono").TypedResponse<{
98
+ error: string;
99
+ code: string;
100
+ }, 409, "json">) | (Response & import("hono").TypedResponse<{
101
+ status: "cancelled" | "late_cancelled";
102
+ }, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
103
+ export {};
104
+ //# sourceMappingURL=public.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public.d.ts","sourceRoot":"","sources":["../../../src/api/appointments/public.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAO5C,KAAK,CAAC,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,CAAC;AAOzC,wBAAsB,aAAa,CAAC,CAAC,EAAE,CAAC;;;;;;;;;;;;;;;;;;;mEAcvC;AAUD,wBAAsB,SAAS,CAAC,CAAC,EAAE,CAAC;;;;;;;;;oEAWnC;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,CAAC;;;;;;;;;;;;;mEAmBtC;AAED,wBAAsB,IAAI,CAAC,CAAC,EAAE,CAAC;;;;;;;;;;;;;;;;;;;;;;;kBAuB9B;AAOD,wBAAsB,MAAM,CAAC,CAAC,EAAE,CAAC;;;;;;;;;;;;;;;;oEAahC;AAED,wBAAsB,MAAM,CAAC,CAAC,EAAE,CAAC;;;;;;;;;;;oEAWhC"}
@@ -0,0 +1,129 @@
1
+ import { APPOINTMENT_LIMITS, addDays, localParts, zonedToUtc } from '@hintergrund/runtime-contracts';
2
+ import { SEAT_STATUSES } from '../../lib/appointments-schema';
3
+ import { ensureSchema } from '../../lib/project-db';
4
+ import { rateLimit, validEmail } from '../../lib/user-recovery';
5
+ import { BOOKING_CONTEXT_SQL, MIN, computeSlots, createBooking, endBooking, getSettings, isActive, offeringResourceIds } from './core';
6
+ import { sendBookingEmails } from './emails';
7
+ const text = (value, max) => typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '';
8
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
9
+ const ip = (c) => c.req.header('CF-Connecting-IP') || 'local';
10
+ const settingsOf = async (c, db) => getSettings(db, new URL(c.req.url).origin, c.env.PUBLIC_ORIGIN);
11
+ const quiet = (promise) => promise.catch(error => console.error('Appointment email failed:', error));
12
+ export async function listOfferings(c) {
13
+ const db = await ensureSchema(c.env);
14
+ const { timezone } = await settingsOf(c, db);
15
+ const offerings = (await db.prepare('SELECT * FROM appt_offerings WHERE active = 1 ORDER BY sort, name').all()).results;
16
+ const people = (await db.prepare(`SELECT o.offering_id, r.id, r.name FROM appt_offering_resources o JOIN appt_resources r ON r.id = o.resource_id WHERE r.active = 1 AND r.kind = 'person' ORDER BY r.name`).all()).results;
17
+ const body = {
18
+ timezone,
19
+ offerings: offerings.map((o) => ({
20
+ id: o.id, kind: o.kind, name: o.name, description: o.description, durationMin: o.duration_min, priceCents: o.price_cents, capacity: o.capacity,
21
+ audience: o.audience, requiresApproval: o.requires_approval === 1, waitlist: o.kind === 'class' && o.waitlist_lock_min !== null, cancelCutoffMin: o.cancel_cutoff_min,
22
+ resources: o.kind === 'appointment' ? people.filter(p => p.offering_id === o.id).map(p => ({ id: p.id, name: p.name })) : [],
23
+ })),
24
+ };
25
+ return c.json(body);
26
+ }
27
+ /** from/to default to today and 14 days later; the range is capped at 62 days. */
28
+ function range(c, tz) {
29
+ const today = localParts(Date.now(), tz).date;
30
+ const from = DATE.test(c.req.query('from') ?? '') ? c.req.query('from') : today;
31
+ const to = DATE.test(c.req.query('to') ?? '') ? c.req.query('to') : addDays(from, 14);
32
+ return { from, to: to > addDays(from, 62) ? addDays(from, 62) : to };
33
+ }
34
+ export async function listSlots(c) {
35
+ const db = await ensureSchema(c.env);
36
+ const { timezone } = await settingsOf(c, db);
37
+ const offering = await db.prepare(`SELECT * FROM appt_offerings WHERE id = ? AND kind = 'appointment' AND active = 1`).bind(c.req.query('offering') ?? '').first();
38
+ if (!offering)
39
+ return c.json({ error: 'Offering not found.', code: 'not_found' }, 404);
40
+ const people = await offeringResourceIds(db, offering.id);
41
+ const wanted = c.req.query('resource');
42
+ const { from, to } = range(c, timezone);
43
+ const slots = await computeSlots(db, offering, wanted ? people.filter(id => id === wanted) : people, from, to, timezone);
44
+ const body = { timezone, slots: [...slots.keys()].sort((a, b) => a - b).map(startsAt => ({ startsAt, endsAt: startsAt + offering.duration_min * MIN })) };
45
+ return c.json(body);
46
+ }
47
+ export async function listSessions(c) {
48
+ const db = await ensureSchema(c.env);
49
+ const { timezone } = await settingsOf(c, db);
50
+ const { from, to } = range(c, timezone);
51
+ const now = Date.now();
52
+ const offering = c.req.query('offering');
53
+ const rows = (await db.prepare(`SELECT s.id, s.offering_id, s.starts_at, s.ends_at, s.capacity, o.waitlist_lock_min, o.min_notice_min,
54
+ (SELECT count(*) FROM appt_bookings WHERE session_id = s.id AND status IN (${SEAT_STATUSES})) AS seated,
55
+ (SELECT r.name FROM appt_session_resources sr JOIN appt_resources r ON r.id = sr.resource_id WHERE sr.session_id = s.id AND r.kind = 'person' LIMIT 1) AS teacher,
56
+ (SELECT r.name FROM appt_session_resources sr JOIN appt_resources r ON r.id = sr.resource_id WHERE sr.session_id = s.id AND r.kind = 'room' LIMIT 1) AS room
57
+ FROM appt_sessions s JOIN appt_offerings o ON o.id = s.offering_id
58
+ WHERE o.kind = 'class' AND o.active = 1 AND s.status = 'active' AND s.starts_at >= ? AND s.starts_at < ? AND s.starts_at >= ? ${offering ? 'AND s.offering_id = ?' : ''} ORDER BY s.starts_at`).bind(zonedToUtc(from, 0, timezone), zonedToUtc(addDays(to, 1), 0, timezone), now, ...(offering ? [offering] : [])).all()).results;
59
+ const sessions = rows.filter(row => row.starts_at >= now + row.min_notice_min * MIN).map(row => ({
60
+ id: row.id, offeringId: row.offering_id, startsAt: row.starts_at, endsAt: row.ends_at, teacher: row.teacher, room: row.room, capacity: row.capacity,
61
+ free: Math.max(0, row.capacity - row.seated), waitlistOpen: row.seated >= row.capacity && row.waitlist_lock_min !== null && row.starts_at - row.waitlist_lock_min * MIN > now,
62
+ }));
63
+ return c.json({ timezone, sessions });
64
+ }
65
+ export async function book(c) {
66
+ const body = await c.req.json().catch(() => null);
67
+ if (!body || typeof body !== 'object')
68
+ return c.json({ error: 'Invalid request.', code: 'invalid' }, 400);
69
+ // Bots fill the hidden field; answer as if it worked and store nothing.
70
+ if (body.website)
71
+ return c.json({ status: 'booked', token: 'x', startsAt: 0, endsAt: 0 }, 201);
72
+ if (!await rateLimit(c.env, `appt-book:${ip(c)}`, 10, 3600))
73
+ return c.json({ error: 'Too many requests. Try again later.', code: 'rate_limited' }, 429);
74
+ const name = text(body.name, APPOINTMENT_LIMITS.name), email = text(body.email, APPOINTMENT_LIMITS.email).toLowerCase();
75
+ if (!name || !validEmail(email))
76
+ return c.json({ error: 'Name and a valid email are required.', code: 'invalid' }, 400);
77
+ const db = await ensureSchema(c.env);
78
+ const settings = await settingsOf(c, db);
79
+ const offering = await db.prepare('SELECT * FROM appt_offerings WHERE id = ? AND active = 1').bind(body.offeringId ?? '').first();
80
+ if (!offering)
81
+ return c.json({ error: 'Offering not found.', code: 'not_found' }, 404);
82
+ const session = offering.kind === 'class' ? await db.prepare('SELECT * FROM appt_sessions WHERE id = ?').bind(body.sessionId ?? '').first() ?? undefined : undefined;
83
+ const result = await createBooking(c.env, db, settings.timezone, {
84
+ offering, session, startsAt: typeof body.startsAt === 'number' ? body.startsAt : undefined, resourceId: text(body.resourceId, 80) || undefined,
85
+ name, email, phone: text(body.phone, APPOINTMENT_LIMITS.phone),
86
+ patientType: body.patientType === 'new' || body.patientType === 'returning' ? body.patientType : null,
87
+ insurance: body.insurance === 'statutory' || body.insurance === 'private' || body.insurance === 'self_pay' ? body.insurance : null,
88
+ consent: body.reminderConsent === true, usePass: body.usePass !== false, locale: body.locale === 'de' ? 'de' : 'en', manual: false,
89
+ });
90
+ if (!result.ok)
91
+ return c.json({ error: result.error, code: result.code }, result.http);
92
+ await quiet(sendBookingEmails(c.env, db, [result.id], result.status === 'pending' ? 'requested' : result.status === 'waitlisted' ? 'waitlisted' : 'confirmed'));
93
+ return c.json({ status: result.status, token: result.token, startsAt: result.startsAt, endsAt: result.endsAt, payment: result.payment }, 201);
94
+ }
95
+ async function byToken(c, db) {
96
+ const token = c.req.param('token') ?? '';
97
+ return token.length < 32 ? null : await db.prepare(`${BOOKING_CONTEXT_SQL} WHERE b.cancel_token = ?`).bind(token).first();
98
+ }
99
+ export async function manage(c) {
100
+ if (!await rateLimit(c.env, `appt-manage:${ip(c)}`, 60, 3600))
101
+ return c.json({ error: 'Too many requests. Try again later.', code: 'rate_limited' }, 429);
102
+ const db = await ensureSchema(c.env);
103
+ const booking = await byToken(c, db);
104
+ if (!booking)
105
+ return c.json({ error: 'Booking not found.', code: 'not_found' }, 404);
106
+ const { timezone } = await settingsOf(c, db);
107
+ const now = Date.now();
108
+ return c.json({
109
+ status: booking.status, kind: booking.kind, offeringName: booking.offering_name, startsAt: booking.starts_at, endsAt: booking.ends_at, timezone,
110
+ cancellable: isActive(booking.status) && booking.starts_at > now,
111
+ late: booking.status === 'booked' && now > booking.starts_at - booking.cancel_cutoff_min * MIN,
112
+ cancelCutoffMin: booking.cancel_cutoff_min,
113
+ });
114
+ }
115
+ export async function cancel(c) {
116
+ if (!await rateLimit(c.env, `appt-manage:${ip(c)}`, 60, 3600))
117
+ return c.json({ error: 'Too many requests. Try again later.', code: 'rate_limited' }, 429);
118
+ const db = await ensureSchema(c.env);
119
+ const booking = await byToken(c, db);
120
+ if (!booking)
121
+ return c.json({ error: 'Booking not found.', code: 'not_found' }, 404);
122
+ const now = Date.now();
123
+ if (!isActive(booking.status) || booking.starts_at <= now)
124
+ return c.json({ error: 'This booking can no longer be cancelled.', code: 'too_late' }, 409);
125
+ const status = booking.status === 'booked' && now > booking.starts_at - booking.cancel_cutoff_min * MIN ? 'late_cancelled' : 'cancelled';
126
+ await endBooking(c.env, db, booking, status, now);
127
+ await quiet(sendBookingEmails(c.env, db, [booking.id], 'cancelled'));
128
+ return c.json({ status });
129
+ }
@@ -0,0 +1,7 @@
1
+ import { Hono } from 'hono';
2
+ import type { Bindings } from '../../index';
3
+ declare const appointmentRoutes: Hono<{
4
+ Bindings: Bindings;
5
+ }, import("hono/types").BlankSchema, "/">;
6
+ export default appointmentRoutes;
7
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/api/appointments/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAM5C,QAAA,MAAM,iBAAiB;cAAwB,QAAQ;yCAAK,CAAC;AAyB7D,eAAe,iBAAiB,CAAC"}