Compare commits
17 Commits
8aea5bb400
...
v0.1.5.2
Author | SHA1 | Date | |
---|---|---|---|
c1aeb7c38b | |||
889e110dd9 | |||
a603232ed8 | |||
f0037226a9 | |||
12da9812df | |||
ce019a2bd9 | |||
63384aa209 | |||
ebd9d8a72e | |||
ccba9d443b | |||
9583148e02 | |||
d153aad8b3 | |||
94e269697a | |||
ad79531f33 | |||
db1a401230 | |||
cceb4d4e60 | |||
ca20516080 | |||
f2963ca951 |
@@ -40,6 +40,7 @@ stargirlnails.de {
|
|||||||
log {
|
log {
|
||||||
output file /var/log/caddy/access.log
|
output file /var/log/caddy/access.log
|
||||||
format json
|
format json
|
||||||
|
level INFO
|
||||||
}
|
}
|
||||||
|
|
||||||
# Favicon-Konfiguration (innerhalb der Hauptdomain)
|
# Favicon-Konfiguration (innerhalb der Hauptdomain)
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "quests-template-basic",
|
"name": "quests-template-basic",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.1.5.2",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"check:types": "tsc --noEmit",
|
"check:types": "tsc --noEmit",
|
||||||
|
@@ -55,6 +55,9 @@ if (process.env.NODE_ENV === 'production') {
|
|||||||
app.use('/assets/*', serveStatic({ root: './dist' }));
|
app.use('/assets/*', serveStatic({ root: './dist' }));
|
||||||
}
|
}
|
||||||
app.use('/favicon.png', serveStatic({ path: './public/favicon.png' }));
|
app.use('/favicon.png', serveStatic({ path: './public/favicon.png' }));
|
||||||
|
app.use('/AGB.pdf', serveStatic({ path: './public/AGB.pdf' }));
|
||||||
|
app.use('/icons/*', serveStatic({ root: './public' }));
|
||||||
|
app.use('/manifest.json', serveStatic({ path: './public/manifest.json' }));
|
||||||
app.route("/rpc", rpcApp);
|
app.route("/rpc", rpcApp);
|
||||||
app.route("/caldav", caldavApp);
|
app.route("/caldav", caldavApp);
|
||||||
app.get("/*", clientEntry);
|
app.get("/*", clientEntry);
|
||||||
|
@@ -28,13 +28,17 @@ async function renderBrandedEmail(title, bodyHtml) {
|
|||||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||||
const homepageUrl = `${protocol}://${domain}`;
|
const homepageUrl = `${protocol}://${domain}`;
|
||||||
|
const instagramProfile = process.env.INSTAGRAM_PROFILE;
|
||||||
|
const tiktokProfile = process.env.TIKTOK_PROFILE;
|
||||||
|
const companyName = process.env.COMPANY_NAME || 'Stargirlnails Kiel';
|
||||||
return `
|
return `
|
||||||
<div style="font-family: Arial, sans-serif; color: #0f172a; background:#fdf2f8; padding:24px;">
|
<div style="font-family: Arial, sans-serif; color: #0f172a; background:#fdf2f8; padding:24px;">
|
||||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:640px; margin:0 auto; background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,0.06)">
|
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:640px; margin:0 auto; background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,0.06)">
|
||||||
<tr>
|
<tr>
|
||||||
<td style="padding:24px 24px 0 24px; text-align:center;">
|
<td style="padding:24px 24px 0 24px; text-align:center;">
|
||||||
${logo ? `<img src="${logo}" alt="Stargirlnails" style="width:120px; height:auto; display:inline-block;" />` : `<div style=\"font-size:24px\">💅</div>`}
|
${logo ? `<img src="${logo}" alt="${companyName}" style="width:120px; height:auto; display:inline-block;" />` : `<div style=\"font-size:24px\">💅</div>`}
|
||||||
<h1 style="margin:16px 0 0 0; font-size:22px; color:#db2777;">${title}</h1>
|
<div style="margin:16px 0 4px 0; font-size:16px; font-weight:600; color:#64748b;">${companyName}</div>
|
||||||
|
<h1 style="margin:0; font-size:22px; color:#db2777;">${title}</h1>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -46,6 +50,29 @@ async function renderBrandedEmail(title, bodyHtml) {
|
|||||||
<div style="text-align:center; margin-bottom:16px;">
|
<div style="text-align:center; margin-bottom:16px;">
|
||||||
<a href="${homepageUrl}" style="display: inline-block; background-color: #db2777; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 14px;">Zur Website</a>
|
<a href="${homepageUrl}" style="display: inline-block; background-color: #db2777; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 14px;">Zur Website</a>
|
||||||
</div>
|
</div>
|
||||||
|
${(instagramProfile || tiktokProfile) ? `
|
||||||
|
<div style="text-align:center; margin-bottom:16px;">
|
||||||
|
<p style="font-size:14px; color:#64748b; margin:0 0 8px 0;">Folge uns auf Social Media:</p>
|
||||||
|
<div style="display:inline-block;">
|
||||||
|
${instagramProfile ? `
|
||||||
|
<a href="${instagramProfile}" target="_blank" rel="noopener noreferrer" style="display:inline-block; margin:0 6px; background:linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%); color:white; padding:10px 20px; text-decoration:none; border-radius:20px; font-size:14px; font-weight:600;">
|
||||||
|
<svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24" style="vertical-align:middle; margin-right:6px;">
|
||||||
|
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/>
|
||||||
|
</svg>
|
||||||
|
Instagram
|
||||||
|
</a>
|
||||||
|
` : ''}
|
||||||
|
${tiktokProfile ? `
|
||||||
|
<a href="${tiktokProfile}" target="_blank" rel="noopener noreferrer" style="display:inline-block; margin:0 6px; background:#000000; color:white; padding:10px 20px; text-decoration:none; border-radius:20px; font-size:14px; font-weight:600;">
|
||||||
|
<svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24" style="vertical-align:middle; margin-right:6px;">
|
||||||
|
<path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5 20.1a6.34 6.34 0 0 0 10.86-4.43v-7a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1-.1z"/>
|
||||||
|
</svg>
|
||||||
|
TikTok
|
||||||
|
</a>
|
||||||
|
` : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
` : ''}
|
||||||
<div style="font-size:12px; color:#64748b; text-align:center;">
|
<div style="font-size:12px; color:#64748b; text-align:center;">
|
||||||
© ${new Date().getFullYear()} Stargirlnails Kiel • Professional Nail Care
|
© ${new Date().getFullYear()} Stargirlnails Kiel • Professional Nail Care
|
||||||
</div>
|
</div>
|
||||||
@@ -256,3 +283,35 @@ export async function renderAdminRescheduleExpiredHTML(params) {
|
|||||||
`;
|
`;
|
||||||
return renderBrandedEmail("Abgelaufene Terminänderungsvorschläge", inner);
|
return renderBrandedEmail("Abgelaufene Terminänderungsvorschläge", inner);
|
||||||
}
|
}
|
||||||
|
export async function renderCustomerMessageHTML(params) {
|
||||||
|
const { customerName, message, appointmentDate, appointmentTime, treatmentName } = params;
|
||||||
|
const formattedDate = appointmentDate ? formatDateGerman(appointmentDate) : null;
|
||||||
|
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||||
|
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||||
|
const legalUrl = `${protocol}://${domain}/legal`;
|
||||||
|
const ownerName = process.env.OWNER_NAME || 'Stargirlnails Kiel';
|
||||||
|
const inner = `
|
||||||
|
<p>Hallo ${customerName},</p>
|
||||||
|
${(appointmentDate && appointmentTime && treatmentName) ? `
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0; font-weight: 600; color: #db2777;">📅 Zu deinem Termin:</p>
|
||||||
|
<ul style="margin: 8px 0 0 0; color: #475569; list-style: none; padding: 0;">
|
||||||
|
<li><strong>Behandlung:</strong> ${treatmentName}</li>
|
||||||
|
<li><strong>Datum:</strong> ${formattedDate}</li>
|
||||||
|
<li><strong>Uhrzeit:</strong> ${appointmentTime}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
` : ''}
|
||||||
|
<div style="background-color: #fef9f5; border-left: 4px solid #f59e0b; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0; font-weight: 600; color: #f59e0b;">💬 Nachricht von ${ownerName}:</p>
|
||||||
|
<div style="margin: 12px 0 0 0; color: #475569; white-space: pre-wrap; line-height: 1.6;">${message.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')}</div>
|
||||||
|
</div>
|
||||||
|
<p>Bei Fragen oder Anliegen kannst du einfach auf diese E-Mail antworten – wir helfen dir gerne weiter!</p>
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #3b82f6; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0; font-weight: 600; color: #3b82f6;">📋 Rechtliche Informationen:</p>
|
||||||
|
<p style="margin: 8px 0 12px 0; color: #475569;">Weitere Informationen findest du in unserem <a href="${legalUrl}" style="color: #3b82f6; text-decoration: underline;">Impressum und Datenschutz</a>.</p>
|
||||||
|
</div>
|
||||||
|
<p>Liebe Grüße,<br/>${ownerName}</p>
|
||||||
|
`;
|
||||||
|
return renderBrandedEmail("Nachricht zu deinem Termin", inner);
|
||||||
|
}
|
||||||
|
@@ -97,28 +97,33 @@ export async function sendEmail(params) {
|
|||||||
console.warn("Resend API key not configured. Skipping email send.");
|
console.warn("Resend API key not configured. Skipping email send.");
|
||||||
return { success: false };
|
return { success: false };
|
||||||
}
|
}
|
||||||
|
const payload = {
|
||||||
|
from: params.from || DEFAULT_FROM,
|
||||||
|
to: Array.isArray(params.to) ? params.to : [params.to],
|
||||||
|
subject: params.subject,
|
||||||
|
text: params.text,
|
||||||
|
html: params.html,
|
||||||
|
cc: params.cc ? (Array.isArray(params.cc) ? params.cc : [params.cc]) : undefined,
|
||||||
|
bcc: params.bcc ? (Array.isArray(params.bcc) ? params.bcc : [params.bcc]) : undefined,
|
||||||
|
reply_to: params.replyTo ? (Array.isArray(params.replyTo) ? params.replyTo : [params.replyTo]) : undefined,
|
||||||
|
attachments: params.attachments,
|
||||||
|
};
|
||||||
|
console.log(`Sending email via Resend: to=${JSON.stringify(payload.to)}, subject="${params.subject}"`);
|
||||||
const response = await fetch("https://api.resend.com/emails", {
|
const response = await fetch("https://api.resend.com/emails", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Authorization": `Bearer ${RESEND_API_KEY}`,
|
"Authorization": `Bearer ${RESEND_API_KEY}`,
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(payload),
|
||||||
from: params.from || DEFAULT_FROM,
|
|
||||||
to: Array.isArray(params.to) ? params.to : [params.to],
|
|
||||||
subject: params.subject,
|
|
||||||
text: params.text,
|
|
||||||
html: params.html,
|
|
||||||
cc: params.cc ? (Array.isArray(params.cc) ? params.cc : [params.cc]) : undefined,
|
|
||||||
bcc: params.bcc ? (Array.isArray(params.bcc) ? params.bcc : [params.bcc]) : undefined,
|
|
||||||
attachments: params.attachments,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const body = await response.text().catch(() => "");
|
const body = await response.text().catch(() => "");
|
||||||
console.error("Resend send error:", response.status, body);
|
console.error("Resend send error:", response.status, body);
|
||||||
return { success: false };
|
return { success: false };
|
||||||
}
|
}
|
||||||
|
const responseData = await response.json().catch(() => ({}));
|
||||||
|
console.log("Resend email sent successfully:", responseData);
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
export async function sendEmailWithAGB(params) {
|
export async function sendEmailWithAGB(params) {
|
||||||
|
@@ -24,5 +24,5 @@ export function clientEntry(c) {
|
|||||||
cssFiles = ["/assets/index-RdX4PbOO.css"];
|
cssFiles = ["/assets/index-RdX4PbOO.css"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return c.html(_jsxs("html", { lang: "en", children: [_jsxs("head", { children: [_jsx("meta", { charSet: "utf-8" }), _jsx("meta", { content: "width=device-width, initial-scale=1", name: "viewport" }), _jsx("title", { children: "Stargirlnails Kiel" }), _jsx("link", { rel: "icon", type: "image/png", href: "/favicon.png" }), cssFiles && cssFiles.map((css) => (_jsx("link", { rel: "stylesheet", href: css }, css))), process.env.NODE_ENV === 'production' ? (_jsx("script", { src: jsFile, type: "module" })) : (_jsxs(_Fragment, { children: [_jsx("script", { src: "/@vite/client", type: "module" }), _jsx("script", { src: jsFile, type: "module" })] }))] }), _jsx("body", { children: _jsx("div", { id: "root" }) })] }));
|
return c.html(_jsxs("html", { lang: "de", children: [_jsxs("head", { children: [_jsx("meta", { charSet: "utf-8" }), _jsx("meta", { content: "width=device-width, initial-scale=1", name: "viewport" }), _jsx("meta", { name: "theme-color", content: "#ec4899" }), _jsx("meta", { name: "apple-mobile-web-app-capable", content: "yes" }), _jsx("meta", { name: "apple-mobile-web-app-status-bar-style", content: "default" }), _jsx("meta", { name: "apple-mobile-web-app-title", content: "Stargirlnails" }), _jsx("title", { children: "Stargirlnails Kiel" }), _jsx("link", { rel: "icon", type: "image/png", href: "/favicon.png" }), _jsx("link", { rel: "apple-touch-icon", href: "/icons/apple-touch-icon.png" }), _jsx("link", { rel: "manifest", href: "/manifest.json" }), cssFiles && cssFiles.map((css) => (_jsx("link", { rel: "stylesheet", href: css }, css))), process.env.NODE_ENV === 'production' ? (_jsx("script", { src: jsFile, type: "module" })) : (_jsxs(_Fragment, { children: [_jsx("script", { src: "/@vite/client", type: "module" }), _jsx("script", { src: jsFile, type: "module" })] }))] }), _jsx("body", { children: _jsx("div", { id: "root" }) })] }));
|
||||||
}
|
}
|
||||||
|
@@ -3,7 +3,7 @@ import { z } from "zod";
|
|||||||
import { randomUUID } from "crypto";
|
import { randomUUID } from "crypto";
|
||||||
import { createKV } from "../lib/create-kv.js";
|
import { createKV } from "../lib/create-kv.js";
|
||||||
import { sendEmail, sendEmailWithAGBAndCalendar, sendEmailWithInspirationPhoto } from "../lib/email.js";
|
import { sendEmail, sendEmailWithAGBAndCalendar, sendEmailWithInspirationPhoto } from "../lib/email.js";
|
||||||
import { renderBookingPendingHTML, renderBookingConfirmedHTML, renderBookingCancelledHTML, renderAdminBookingNotificationHTML, renderBookingRescheduleProposalHTML, renderAdminRescheduleAcceptedHTML, renderAdminRescheduleDeclinedHTML } from "../lib/email-templates.js";
|
import { renderBookingPendingHTML, renderBookingConfirmedHTML, renderBookingCancelledHTML, renderAdminBookingNotificationHTML, renderBookingRescheduleProposalHTML, renderAdminRescheduleAcceptedHTML, renderAdminRescheduleDeclinedHTML, renderCustomerMessageHTML } from "../lib/email-templates.js";
|
||||||
import { createORPCClient } from "@orpc/client";
|
import { createORPCClient } from "@orpc/client";
|
||||||
import { RPCLink } from "@orpc/client/fetch";
|
import { RPCLink } from "@orpc/client/fetch";
|
||||||
import { checkBookingRateLimit } from "../lib/rate-limiter.js";
|
import { checkBookingRateLimit } from "../lib/rate-limiter.js";
|
||||||
@@ -745,4 +745,63 @@ export const router = {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
// Admin sendet Nachricht an Kunden
|
||||||
|
sendCustomerMessage: os
|
||||||
|
.input(z.object({
|
||||||
|
sessionId: z.string(),
|
||||||
|
bookingId: z.string(),
|
||||||
|
message: z.string().min(1, "Nachricht darf nicht leer sein").max(5000, "Nachricht ist zu lang (max. 5000 Zeichen)"),
|
||||||
|
}))
|
||||||
|
.handler(async ({ input }) => {
|
||||||
|
await assertOwner(input.sessionId);
|
||||||
|
const booking = await kv.getItem(input.bookingId);
|
||||||
|
if (!booking)
|
||||||
|
throw new Error("Buchung nicht gefunden");
|
||||||
|
// Check if booking has customer email
|
||||||
|
if (!booking.customerEmail) {
|
||||||
|
throw new Error("Diese Buchung hat keine E-Mail-Adresse. Bitte kontaktiere den Kunden telefonisch.");
|
||||||
|
}
|
||||||
|
// Check if booking is in the future
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
const bookingDate = booking.appointmentDate;
|
||||||
|
if (bookingDate < today) {
|
||||||
|
throw new Error("Nachrichten können nur für zukünftige Termine gesendet werden.");
|
||||||
|
}
|
||||||
|
// Get treatment name for context
|
||||||
|
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
||||||
|
const treatmentName = treatment?.name || "Behandlung";
|
||||||
|
// Prepare email with Reply-To header
|
||||||
|
const ownerName = process.env.OWNER_NAME || "Stargirlnails Kiel";
|
||||||
|
const emailFrom = process.env.EMAIL_FROM || "Stargirlnails <no-reply@stargirlnails.de>";
|
||||||
|
const replyToEmail = process.env.ADMIN_EMAIL;
|
||||||
|
const formattedDate = formatDateGerman(bookingDate);
|
||||||
|
const html = await renderCustomerMessageHTML({
|
||||||
|
customerName: booking.customerName,
|
||||||
|
message: input.message,
|
||||||
|
appointmentDate: bookingDate,
|
||||||
|
appointmentTime: booking.appointmentTime,
|
||||||
|
treatmentName: treatmentName,
|
||||||
|
});
|
||||||
|
const textContent = `Hallo ${booking.customerName},\n\nZu deinem Termin:\nBehandlung: ${treatmentName}\nDatum: ${formattedDate}\nUhrzeit: ${booking.appointmentTime}\n\nNachricht von ${ownerName}:\n${input.message}\n\nBei Fragen oder Anliegen kannst du einfach auf diese E-Mail antworten – wir helfen dir gerne weiter!\n\nLiebe Grüße,\n${ownerName}`;
|
||||||
|
// Send email with BCC to admin for monitoring
|
||||||
|
// Note: Not using explicit 'from' or 'replyTo' to match behavior of other system emails
|
||||||
|
console.log(`Sending customer message to ${booking.customerEmail} for booking ${input.bookingId}`);
|
||||||
|
console.log(`Email config: from=${emailFrom}, replyTo=${replyToEmail}, bcc=${replyToEmail}`);
|
||||||
|
const emailResult = await sendEmail({
|
||||||
|
to: booking.customerEmail,
|
||||||
|
subject: `Nachricht zu deinem Termin am ${formattedDate}`,
|
||||||
|
text: textContent,
|
||||||
|
html: html,
|
||||||
|
bcc: replyToEmail ? [replyToEmail] : undefined,
|
||||||
|
});
|
||||||
|
if (!emailResult.success) {
|
||||||
|
console.error(`Failed to send customer message to ${booking.customerEmail}`);
|
||||||
|
throw new Error("E-Mail konnte nicht versendet werden. Bitte überprüfe die E-Mail-Konfiguration oder versuche es später erneut.");
|
||||||
|
}
|
||||||
|
console.log(`Successfully sent customer message to ${booking.customerEmail}`);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `Nachricht wurde erfolgreich an ${booking.customerEmail} gesendet.`
|
||||||
|
};
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
|
@@ -7,6 +7,7 @@ import { router as cancellation } from "./cancellation.js";
|
|||||||
import { router as legal } from "./legal.js";
|
import { router as legal } from "./legal.js";
|
||||||
import { router as gallery } from "./gallery.js";
|
import { router as gallery } from "./gallery.js";
|
||||||
import { router as reviews } from "./reviews.js";
|
import { router as reviews } from "./reviews.js";
|
||||||
|
import { router as social } from "./social.js";
|
||||||
export const router = {
|
export const router = {
|
||||||
demo,
|
demo,
|
||||||
treatments,
|
treatments,
|
||||||
@@ -17,4 +18,5 @@ export const router = {
|
|||||||
legal,
|
legal,
|
||||||
gallery,
|
gallery,
|
||||||
reviews,
|
reviews,
|
||||||
|
social,
|
||||||
};
|
};
|
||||||
|
10
server-dist/rpc/social.js
Normal file
10
server-dist/rpc/social.js
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { os } from "@orpc/server";
|
||||||
|
const getSocialMedia = os.handler(async () => {
|
||||||
|
return {
|
||||||
|
tiktokProfile: process.env.TIKTOK_PROFILE,
|
||||||
|
instagramProfile: process.env.INSTAGRAM_PROFILE,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
export const router = os.router({
|
||||||
|
getSocialMedia,
|
||||||
|
});
|
@@ -3,10 +3,13 @@ import { useMutation, useQuery } from "@tanstack/react-query";
|
|||||||
import { queryClient } from "@/client/rpc-client";
|
import { queryClient } from "@/client/rpc-client";
|
||||||
|
|
||||||
export function AdminBookings() {
|
export function AdminBookings() {
|
||||||
|
const [filterMode, setFilterMode] = useState<"upcoming" | "all" | "date">("upcoming");
|
||||||
const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
|
const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
|
||||||
const [selectedPhoto, setSelectedPhoto] = useState<string>("");
|
const [selectedPhoto, setSelectedPhoto] = useState<string>("");
|
||||||
const [showPhotoModal, setShowPhotoModal] = useState(false);
|
const [showPhotoModal, setShowPhotoModal] = useState(false);
|
||||||
const [showCancelConfirm, setShowCancelConfirm] = useState<string | null>(null);
|
const [showCancelConfirm, setShowCancelConfirm] = useState<string | null>(null);
|
||||||
|
const [showMessageModal, setShowMessageModal] = useState<string | null>(null);
|
||||||
|
const [messageText, setMessageText] = useState<string>("");
|
||||||
const [successMsg, setSuccessMsg] = useState<string>("");
|
const [successMsg, setSuccessMsg] = useState<string>("");
|
||||||
const [errorMsg, setErrorMsg] = useState<string>("");
|
const [errorMsg, setErrorMsg] = useState<string>("");
|
||||||
|
|
||||||
@@ -49,8 +52,33 @@ export function AdminBookings() {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
const getTreatmentName = (treatmentId: string) => {
|
const { mutate: sendMessage, isPending: isSendingMessage } = useMutation(
|
||||||
return treatments?.find(t => t.id === treatmentId)?.name || "Unbekannte Behandlung";
|
queryClient.bookings.sendCustomerMessage.mutationOptions({
|
||||||
|
onSuccess: () => {
|
||||||
|
setSuccessMsg("Nachricht wurde erfolgreich gesendet.");
|
||||||
|
setShowMessageModal(null);
|
||||||
|
setMessageText("");
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
setErrorMsg(error?.message || "Fehler beim Senden der Nachricht.");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const getTreatmentNames = (booking: any) => {
|
||||||
|
// Handle new treatments array structure
|
||||||
|
if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
|
||||||
|
const names = booking.treatments
|
||||||
|
.map((t: any) => t.name)
|
||||||
|
.filter((name: string) => name && name.trim())
|
||||||
|
.join(", ");
|
||||||
|
return names || "Keine Behandlung";
|
||||||
|
}
|
||||||
|
// Fallback to deprecated treatmentId for backward compatibility
|
||||||
|
if (booking.treatmentId) {
|
||||||
|
return treatments?.find(t => t.id === booking.treatmentId)?.name || "Unbekannte Behandlung";
|
||||||
|
}
|
||||||
|
return "Keine Behandlung";
|
||||||
};
|
};
|
||||||
|
|
||||||
const getStatusColor = (status: string) => {
|
const getStatusColor = (status: string) => {
|
||||||
@@ -83,9 +111,52 @@ export function AdminBookings() {
|
|||||||
setSelectedPhoto("");
|
setSelectedPhoto("");
|
||||||
};
|
};
|
||||||
|
|
||||||
const filteredBookings = bookings?.filter(booking =>
|
const openMessageModal = (bookingId: string) => {
|
||||||
selectedDate ? booking.appointmentDate === selectedDate : true
|
setShowMessageModal(bookingId);
|
||||||
).sort((a, b) => {
|
setMessageText("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeMessageModal = () => {
|
||||||
|
setShowMessageModal(null);
|
||||||
|
setMessageText("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSendMessage = () => {
|
||||||
|
if (!showMessageModal || !messageText.trim()) {
|
||||||
|
setErrorMsg("Bitte gib eine Nachricht ein.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendMessage({
|
||||||
|
sessionId: localStorage.getItem("sessionId") || "",
|
||||||
|
bookingId: showMessageModal,
|
||||||
|
message: messageText.trim(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if booking is in the future
|
||||||
|
const isFutureBooking = (appointmentDate: string) => {
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
return appointmentDate >= today;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filter bookings based on selected filter mode
|
||||||
|
const filteredBookings = bookings?.filter(booking => {
|
||||||
|
if (filterMode === "upcoming") {
|
||||||
|
// Show all future bookings (not cancelled)
|
||||||
|
const bookingDate = new Date(booking.appointmentDate);
|
||||||
|
const today = new Date();
|
||||||
|
today.setHours(0, 0, 0, 0);
|
||||||
|
bookingDate.setHours(0, 0, 0, 0);
|
||||||
|
return bookingDate >= today && booking.status !== "cancelled";
|
||||||
|
} else if (filterMode === "date") {
|
||||||
|
// Show bookings for specific date
|
||||||
|
return booking.appointmentDate === selectedDate;
|
||||||
|
} else {
|
||||||
|
// Show all bookings
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}).sort((a, b) => {
|
||||||
if (a.appointmentDate === b.appointmentDate) {
|
if (a.appointmentDate === b.appointmentDate) {
|
||||||
return a.appointmentTime.localeCompare(b.appointmentTime);
|
return a.appointmentTime.localeCompare(b.appointmentTime);
|
||||||
}
|
}
|
||||||
@@ -162,22 +233,54 @@ export function AdminBookings() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Date Filter */}
|
{/* Filter Section */}
|
||||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||||
<div className="flex items-center space-x-4">
|
<div className="flex flex-col space-y-4">
|
||||||
<label className="text-sm font-medium text-gray-700">Filter by date:</label>
|
<div className="flex items-center space-x-2">
|
||||||
<input
|
<label className="text-sm font-medium text-gray-700">Filter:</label>
|
||||||
type="date"
|
<button
|
||||||
value={selectedDate}
|
onClick={() => setFilterMode("upcoming")}
|
||||||
onChange={(e) => setSelectedDate(e.target.value)}
|
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||||
className="p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
filterMode === "upcoming"
|
||||||
/>
|
? "bg-pink-600 text-white"
|
||||||
<button
|
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||||
onClick={() => setSelectedDate("")}
|
}`}
|
||||||
className="text-sm text-pink-600 hover:text-pink-800"
|
>
|
||||||
>
|
Zukünftige
|
||||||
Show All
|
</button>
|
||||||
</button>
|
<button
|
||||||
|
onClick={() => setFilterMode("all")}
|
||||||
|
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||||
|
filterMode === "all"
|
||||||
|
? "bg-pink-600 text-white"
|
||||||
|
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Alle
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setFilterMode("date")}
|
||||||
|
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||||
|
filterMode === "date"
|
||||||
|
? "bg-pink-600 text-white"
|
||||||
|
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Datum
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{filterMode === "date" && (
|
||||||
|
<div className="flex items-center space-x-4 pl-16">
|
||||||
|
<label className="text-sm font-medium text-gray-700">Wähle Datum:</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={selectedDate}
|
||||||
|
onChange={(e) => setSelectedDate(e.target.value)}
|
||||||
|
className="p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -216,8 +319,8 @@ export function AdminBookings() {
|
|||||||
<div className="text-sm text-gray-500">{booking.customerPhone || '—'}</div>
|
<div className="text-sm text-gray-500">{booking.customerPhone || '—'}</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="px-6 py-4">
|
||||||
<div className="text-sm text-gray-900">{getTreatmentName(booking.treatmentId)}</div>
|
<div className="text-sm text-gray-900">{getTreatmentNames(booking)}</div>
|
||||||
{booking.notes && (
|
{booking.notes && (
|
||||||
<div className="text-sm text-gray-500">Notizen: {booking.notes}</div>
|
<div className="text-sm text-gray-500">Notizen: {booking.notes}</div>
|
||||||
)}
|
)}
|
||||||
@@ -251,45 +354,57 @@ export function AdminBookings() {
|
|||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
|
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
|
||||||
<div className="flex space-x-2">
|
<div className="flex flex-col space-y-2">
|
||||||
{booking.status === "pending" && (
|
<div className="flex space-x-2">
|
||||||
<>
|
{booking.status === "pending" && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "confirmed" })}
|
||||||
|
className="text-green-600 hover:text-green-900"
|
||||||
|
>
|
||||||
|
Confirm
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCancelConfirm(booking.id)}
|
||||||
|
className="text-red-600 hover:text-red-900"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{booking.status === "confirmed" && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "completed" })}
|
||||||
|
className="text-blue-600 hover:text-blue-900"
|
||||||
|
>
|
||||||
|
Complete
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCancelConfirm(booking.id)}
|
||||||
|
className="text-red-600 hover:text-red-900"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(booking.status === "cancelled" || booking.status === "completed") && (
|
||||||
<button
|
<button
|
||||||
onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "confirmed" })}
|
onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "confirmed" })}
|
||||||
className="text-green-600 hover:text-green-900"
|
className="text-green-600 hover:text-green-900"
|
||||||
>
|
>
|
||||||
Confirm
|
Reactivate
|
||||||
</button>
|
</button>
|
||||||
<button
|
)}
|
||||||
onClick={() => setShowCancelConfirm(booking.id)}
|
</div>
|
||||||
className="text-red-600 hover:text-red-900"
|
{/* Show message button for future bookings with email */}
|
||||||
>
|
{isFutureBooking(booking.appointmentDate) && booking.customerEmail && (
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{booking.status === "confirmed" && (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "completed" })}
|
|
||||||
className="text-blue-600 hover:text-blue-900"
|
|
||||||
>
|
|
||||||
Complete
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowCancelConfirm(booking.id)}
|
|
||||||
className="text-red-600 hover:text-red-900"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{(booking.status === "cancelled" || booking.status === "completed") && (
|
|
||||||
<button
|
<button
|
||||||
onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "confirmed" })}
|
onClick={() => openMessageModal(booking.id)}
|
||||||
className="text-green-600 hover:text-green-900"
|
className="text-pink-600 hover:text-pink-900 text-left"
|
||||||
|
title="Nachricht an Kunden senden"
|
||||||
>
|
>
|
||||||
Reactivate
|
💬 Nachricht
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -301,8 +416,10 @@ export function AdminBookings() {
|
|||||||
|
|
||||||
{!filteredBookings?.length && (
|
{!filteredBookings?.length && (
|
||||||
<div className="text-center py-8 text-gray-500">
|
<div className="text-center py-8 text-gray-500">
|
||||||
{selectedDate
|
{filterMode === "date"
|
||||||
? `Keine Buchungen für ${new Date(selectedDate).toLocaleDateString()} gefunden`
|
? `Keine Buchungen für ${new Date(selectedDate).toLocaleDateString()} gefunden`
|
||||||
|
: filterMode === "upcoming"
|
||||||
|
? "Keine zukünftigen Buchungen verfügbar."
|
||||||
: "Keine Buchungen verfügbar."
|
: "Keine Buchungen verfügbar."
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
@@ -369,6 +486,116 @@ export function AdminBookings() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Message Modal */}
|
||||||
|
{showMessageModal && (
|
||||||
|
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||||
|
<div className="bg-white rounded-lg p-6 max-w-2xl w-full mx-4">
|
||||||
|
<div className="flex justify-between items-center mb-4">
|
||||||
|
<h3 className="text-lg font-medium text-gray-900">Nachricht an Kunden senden</h3>
|
||||||
|
<button
|
||||||
|
onClick={closeMessageModal}
|
||||||
|
className="text-gray-400 hover:text-gray-600 text-2xl"
|
||||||
|
disabled={isSendingMessage}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(() => {
|
||||||
|
const booking = bookings?.find(b => b.id === showMessageModal);
|
||||||
|
if (!booking) return null;
|
||||||
|
|
||||||
|
// Calculate totals for multiple treatments
|
||||||
|
const hasTreatments = booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0;
|
||||||
|
const totalDuration = hasTreatments
|
||||||
|
? booking.treatments.reduce((sum: number, t: any) => sum + (t.duration || 0), 0)
|
||||||
|
: (booking.bookedDurationMinutes || 0);
|
||||||
|
const totalPrice = hasTreatments
|
||||||
|
? booking.treatments.reduce((sum: number, t: any) => sum + (t.price || 0), 0)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mb-4 bg-gray-50 p-4 rounded-md">
|
||||||
|
<p className="text-sm text-gray-700">
|
||||||
|
<strong>Kunde:</strong> {booking.customerName}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-700">
|
||||||
|
<strong>E-Mail:</strong> {booking.customerEmail}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-gray-700">
|
||||||
|
<strong>Termin:</strong> {new Date(booking.appointmentDate).toLocaleDateString()} um {booking.appointmentTime}
|
||||||
|
</p>
|
||||||
|
<div className="text-sm text-gray-700 mt-2">
|
||||||
|
<strong>Behandlungen:</strong>
|
||||||
|
{hasTreatments ? (
|
||||||
|
<div className="mt-1 ml-2">
|
||||||
|
{booking.treatments.map((treatment: any, index: number) => (
|
||||||
|
<div key={index} className="mb-1">
|
||||||
|
• {treatment.name} ({treatment.duration} Min., {treatment.price}€)
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{booking.treatments.length > 1 && (
|
||||||
|
<div className="mt-2 pt-2 border-t border-gray-300 font-semibold">
|
||||||
|
Gesamt: {totalDuration} Min., {totalPrice.toFixed(2)}€
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : booking.treatmentId ? (
|
||||||
|
<div className="mt-1 ml-2">
|
||||||
|
• {treatments?.find(t => t.id === booking.treatmentId)?.name || "Unbekannte Behandlung"}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="ml-2 text-gray-500">Keine Behandlung</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||||
|
Deine Nachricht
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={messageText}
|
||||||
|
onChange={(e) => setMessageText(e.target.value)}
|
||||||
|
placeholder="Schreibe hier deine Nachricht an den Kunden..."
|
||||||
|
rows={6}
|
||||||
|
maxLength={5000}
|
||||||
|
className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
||||||
|
disabled={isSendingMessage}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
|
{messageText.length} / 5000 Zeichen
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-blue-50 border-l-4 border-blue-400 p-3 mb-4">
|
||||||
|
<p className="text-sm text-blue-700">
|
||||||
|
💡 <strong>Hinweis:</strong> Der Kunde kann direkt auf diese E-Mail antworten. Die Antwort geht an die in den Einstellungen hinterlegte Admin-E-Mail-Adresse.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex space-x-3">
|
||||||
|
<button
|
||||||
|
onClick={handleSendMessage}
|
||||||
|
disabled={isSendingMessage || !messageText.trim()}
|
||||||
|
className="flex-1 bg-pink-600 text-white py-2 px-4 rounded-md hover:bg-pink-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{isSendingMessage ? "Wird gesendet..." : "Nachricht senden"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={closeMessageModal}
|
||||||
|
disabled={isSendingMessage}
|
||||||
|
className="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-md hover:bg-gray-300 transition-colors disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
@@ -47,7 +47,7 @@ export function AdminCalendar() {
|
|||||||
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
||||||
input: {
|
input: {
|
||||||
date: createFormData.appointmentDate,
|
date: createFormData.appointmentDate,
|
||||||
treatmentId: createFormData.treatmentId
|
treatmentIds: createFormData.treatmentId ? [createFormData.treatmentId] : []
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
enabled: !!createFormData.appointmentDate && !!createFormData.treatmentId
|
enabled: !!createFormData.appointmentDate && !!createFormData.treatmentId
|
||||||
@@ -58,7 +58,16 @@ export function AdminCalendar() {
|
|||||||
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
||||||
input: {
|
input: {
|
||||||
date: rescheduleFormData.appointmentDate,
|
date: rescheduleFormData.appointmentDate,
|
||||||
treatmentId: (showRescheduleModal ? bookings?.find(b => b.id === showRescheduleModal)?.treatmentId : '') || ''
|
treatmentIds: (() => {
|
||||||
|
const booking = showRescheduleModal ? bookings?.find(b => b.id === showRescheduleModal) : null;
|
||||||
|
if (!booking) return [];
|
||||||
|
// Use new treatments array if available
|
||||||
|
if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
|
||||||
|
return booking.treatments.map((t: any) => t.id);
|
||||||
|
}
|
||||||
|
// Fallback to deprecated treatmentId for backward compatibility
|
||||||
|
return booking.treatmentId ? [booking.treatmentId] : [];
|
||||||
|
})()
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
enabled: !!showRescheduleModal && !!rescheduleFormData.appointmentDate
|
enabled: !!showRescheduleModal && !!rescheduleFormData.appointmentDate
|
||||||
@@ -86,8 +95,16 @@ export function AdminCalendar() {
|
|||||||
queryClient.bookings.generateCalDAVToken.mutationOptions()
|
queryClient.bookings.generateCalDAVToken.mutationOptions()
|
||||||
);
|
);
|
||||||
|
|
||||||
const getTreatmentName = (treatmentId: string) => {
|
const getTreatmentNames = (booking: any) => {
|
||||||
return treatments?.find(t => t.id === treatmentId)?.name || "Unbekannte Behandlung";
|
// Handle new treatments array structure
|
||||||
|
if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
|
||||||
|
return booking.treatments.map((t: any) => t.name).join(", ");
|
||||||
|
}
|
||||||
|
// Fallback to deprecated treatmentId for backward compatibility
|
||||||
|
if (booking.treatmentId) {
|
||||||
|
return treatments?.find(t => t.id === booking.treatmentId)?.name || "Unbekannte Behandlung";
|
||||||
|
}
|
||||||
|
return "Keine Behandlung";
|
||||||
};
|
};
|
||||||
|
|
||||||
const getStatusColor = (status: string) => {
|
const getStatusColor = (status: string) => {
|
||||||
@@ -219,9 +236,29 @@ export function AdminCalendar() {
|
|||||||
const sessionId = localStorage.getItem('sessionId');
|
const sessionId = localStorage.getItem('sessionId');
|
||||||
if (!sessionId) return;
|
if (!sessionId) return;
|
||||||
|
|
||||||
|
// Convert treatmentId to treatments array
|
||||||
|
const selectedTreatment = treatments?.find(t => t.id === createFormData.treatmentId);
|
||||||
|
if (!selectedTreatment) {
|
||||||
|
setCreateError('Bitte wähle eine Behandlung aus.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const treatmentsArray = [{
|
||||||
|
id: selectedTreatment.id,
|
||||||
|
name: selectedTreatment.name,
|
||||||
|
duration: selectedTreatment.duration,
|
||||||
|
price: selectedTreatment.price
|
||||||
|
}];
|
||||||
|
|
||||||
createManualBooking({
|
createManualBooking({
|
||||||
sessionId,
|
sessionId,
|
||||||
...createFormData
|
treatments: treatmentsArray,
|
||||||
|
customerName: createFormData.customerName,
|
||||||
|
appointmentDate: createFormData.appointmentDate,
|
||||||
|
appointmentTime: createFormData.appointmentTime,
|
||||||
|
customerEmail: createFormData.customerEmail,
|
||||||
|
customerPhone: createFormData.customerPhone,
|
||||||
|
notes: createFormData.notes
|
||||||
}, {
|
}, {
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setShowCreateModal(false);
|
setShowCreateModal(false);
|
||||||
@@ -469,7 +506,7 @@ export function AdminCalendar() {
|
|||||||
<div
|
<div
|
||||||
key={booking.id}
|
key={booking.id}
|
||||||
className={`text-xs p-1 rounded border-l-2 ${getStatusColor(booking.status)} truncate`}
|
className={`text-xs p-1 rounded border-l-2 ${getStatusColor(booking.status)} truncate`}
|
||||||
title={`${booking.customerName} - ${getTreatmentName(booking.treatmentId)} (${booking.appointmentTime})`}
|
title={`${booking.customerName} - ${getTreatmentNames(booking)} (${booking.appointmentTime})`}
|
||||||
>
|
>
|
||||||
<div className="font-medium">{booking.appointmentTime}</div>
|
<div className="font-medium">{booking.appointmentTime}</div>
|
||||||
<div className="truncate">{booking.customerName}</div>
|
<div className="truncate">{booking.customerName}</div>
|
||||||
@@ -526,7 +563,7 @@ export function AdminCalendar() {
|
|||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
|
||||||
<div>
|
<div>
|
||||||
<strong>Behandlung:</strong> {getTreatmentName(booking.treatmentId)}
|
<strong>Behandlung:</strong> {getTreatmentNames(booking)}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Uhrzeit:</strong> {booking.appointmentTime}
|
<strong>Uhrzeit:</strong> {booking.appointmentTime}
|
||||||
@@ -842,7 +879,7 @@ export function AdminCalendar() {
|
|||||||
|
|
||||||
{(() => {
|
{(() => {
|
||||||
const booking = bookings?.find(b => b.id === showRescheduleModal);
|
const booking = bookings?.find(b => b.id === showRescheduleModal);
|
||||||
const treatmentName = booking ? getTreatmentName(booking.treatmentId) : '';
|
const treatmentName = booking ? getTreatmentNames(booking) : '';
|
||||||
return booking ? (
|
return booking ? (
|
||||||
<div className="mb-4 text-sm text-gray-700">
|
<div className="mb-4 text-sm text-gray-700">
|
||||||
<div className="mb-2"><strong>Kunde:</strong> {booking.customerName}</div>
|
<div className="mb-2"><strong>Kunde:</strong> {booking.customerName}</div>
|
||||||
|
@@ -1,9 +1,12 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
import { queryClient } from "@/client/rpc-client";
|
import { queryClient } from "@/client/rpc-client";
|
||||||
|
|
||||||
|
// Feature flag for multi-treatments availability API compatibility
|
||||||
|
const USE_MULTI_TREATMENTS_AVAILABILITY = true;
|
||||||
|
|
||||||
export function BookingForm() {
|
export function BookingForm() {
|
||||||
const [selectedTreatment, setSelectedTreatment] = useState("");
|
const [selectedTreatments, setSelectedTreatments] = useState<Array<{id: string, name: string, duration: number, price: number}>>([]);
|
||||||
const [customerName, setCustomerName] = useState("");
|
const [customerName, setCustomerName] = useState("");
|
||||||
const [customerEmail, setCustomerEmail] = useState("");
|
const [customerEmail, setCustomerEmail] = useState("");
|
||||||
const [customerPhone, setCustomerPhone] = useState("");
|
const [customerPhone, setCustomerPhone] = useState("");
|
||||||
@@ -62,29 +65,80 @@ export function BookingForm() {
|
|||||||
queryClient.treatments.live.list.experimental_liveOptions()
|
queryClient.treatments.live.list.experimental_liveOptions()
|
||||||
);
|
);
|
||||||
|
|
||||||
// Dynamische Verfügbarkeitsabfrage für das gewählte Datum und die Behandlung
|
// Comment 3: Compute total duration and price once per render
|
||||||
|
const totalDuration = useMemo(
|
||||||
|
() => selectedTreatments.reduce((sum, t) => sum + t.duration, 0),
|
||||||
|
[selectedTreatments]
|
||||||
|
);
|
||||||
|
|
||||||
|
const totalPrice = useMemo(
|
||||||
|
() => selectedTreatments.reduce((sum, t) => sum + t.price, 0),
|
||||||
|
[selectedTreatments]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Comment 1: Dynamische Verfügbarkeitsabfrage mit Kompatibilitäts-Fallback
|
||||||
|
const availabilityQueryInput = USE_MULTI_TREATMENTS_AVAILABILITY
|
||||||
|
? { date: appointmentDate, treatmentIds: selectedTreatments.map(t => t.id) }
|
||||||
|
: { date: appointmentDate, treatmentId: selectedTreatments[0]?.id ?? "" };
|
||||||
|
|
||||||
|
const availabilityQueryEnabled = USE_MULTI_TREATMENTS_AVAILABILITY
|
||||||
|
? !!appointmentDate && selectedTreatments.length > 0
|
||||||
|
: !!appointmentDate && selectedTreatments.length > 0;
|
||||||
|
|
||||||
const { data: availableTimes, isLoading, isFetching, error } = useQuery({
|
const { data: availableTimes, isLoading, isFetching, error } = useQuery({
|
||||||
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
||||||
input: {
|
input: availabilityQueryInput as any
|
||||||
date: appointmentDate,
|
|
||||||
treatmentId: selectedTreatment
|
|
||||||
}
|
|
||||||
}),
|
}),
|
||||||
enabled: !!appointmentDate && !!selectedTreatment
|
enabled: availabilityQueryEnabled
|
||||||
});
|
});
|
||||||
|
|
||||||
const { mutate: createBooking, isPending } = useMutation(
|
const { mutate: createBooking, isPending } = useMutation(
|
||||||
queryClient.bookings.create.mutationOptions()
|
queryClient.bookings.create.mutationOptions()
|
||||||
);
|
);
|
||||||
|
|
||||||
const selectedTreatmentData = treatments?.find((t) => t.id === selectedTreatment);
|
// Comment 2: Handle treatment checkbox toggle with functional state updates
|
||||||
|
const handleTreatmentToggle = (treatment: {id: string, name: string, duration: number, price: number}) => {
|
||||||
// Clear selectedTime when treatment changes
|
setSelectedTreatments((prev) => {
|
||||||
const handleTreatmentChange = (treatmentId: string) => {
|
const isSelected = prev.some(t => t.id === treatment.id);
|
||||||
setSelectedTreatment(treatmentId);
|
|
||||||
|
if (isSelected) {
|
||||||
|
// Remove from selection
|
||||||
|
return prev.filter(t => t.id !== treatment.id);
|
||||||
|
} else if (prev.length < 3) {
|
||||||
|
// Add to selection (only if limit not reached)
|
||||||
|
return [...prev, {
|
||||||
|
id: treatment.id,
|
||||||
|
name: treatment.name,
|
||||||
|
duration: treatment.duration,
|
||||||
|
price: treatment.price
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return unchanged if limit reached
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Clear selected time when treatments change
|
||||||
setSelectedTime("");
|
setSelectedTime("");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Comment 4: Reconcile selectedTreatments when treatments list changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (!treatments) return;
|
||||||
|
|
||||||
|
setSelectedTreatments((prev) => {
|
||||||
|
const validTreatments = prev.filter((selected) =>
|
||||||
|
treatments.some((t) => t.id === selected.id)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only update state if something changed to avoid unnecessary re-renders
|
||||||
|
if (validTreatments.length !== prev.length) {
|
||||||
|
return validTreatments;
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
}, [treatments]);
|
||||||
|
|
||||||
// Clear selectedTime when it becomes invalid
|
// Clear selectedTime when it becomes invalid
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedTime && availableTimes && !availableTimes.includes(selectedTime)) {
|
if (selectedTime && availableTimes && !availableTimes.includes(selectedTime)) {
|
||||||
@@ -173,7 +227,7 @@ export function BookingForm() {
|
|||||||
setErrorMessage(""); // Clear any previous error messages
|
setErrorMessage(""); // Clear any previous error messages
|
||||||
|
|
||||||
// console.log("Form submitted with data:", {
|
// console.log("Form submitted with data:", {
|
||||||
// selectedTreatment,
|
// selectedTreatments,
|
||||||
// customerName,
|
// customerName,
|
||||||
// customerEmail,
|
// customerEmail,
|
||||||
// customerPhone,
|
// customerPhone,
|
||||||
@@ -182,8 +236,12 @@ export function BookingForm() {
|
|||||||
// agbAccepted
|
// agbAccepted
|
||||||
// });
|
// });
|
||||||
|
|
||||||
if (!selectedTreatment || !customerName || !customerEmail || !customerPhone || !appointmentDate || !selectedTime) {
|
if (selectedTreatments.length === 0 || !customerName || !customerEmail || !customerPhone || !appointmentDate || !selectedTime) {
|
||||||
setErrorMessage("Bitte fülle alle erforderlichen Felder aus.");
|
if (selectedTreatments.length === 0) {
|
||||||
|
setErrorMessage("Bitte wähle mindestens eine Behandlung aus.");
|
||||||
|
} else {
|
||||||
|
setErrorMessage("Bitte fülle alle erforderlichen Felder aus.");
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!agbAccepted) {
|
if (!agbAccepted) {
|
||||||
@@ -198,7 +256,7 @@ export function BookingForm() {
|
|||||||
// Email validation now handled in backend before booking creation
|
// Email validation now handled in backend before booking creation
|
||||||
const appointmentTime = selectedTime;
|
const appointmentTime = selectedTime;
|
||||||
// console.log("Creating booking with data:", {
|
// console.log("Creating booking with data:", {
|
||||||
// treatmentId: selectedTreatment,
|
// treatments: selectedTreatments,
|
||||||
// customerName,
|
// customerName,
|
||||||
// customerEmail,
|
// customerEmail,
|
||||||
// customerPhone,
|
// customerPhone,
|
||||||
@@ -209,7 +267,7 @@ export function BookingForm() {
|
|||||||
// });
|
// });
|
||||||
createBooking(
|
createBooking(
|
||||||
{
|
{
|
||||||
treatmentId: selectedTreatment,
|
treatments: selectedTreatments,
|
||||||
customerName,
|
customerName,
|
||||||
customerEmail,
|
customerEmail,
|
||||||
customerPhone,
|
customerPhone,
|
||||||
@@ -220,7 +278,7 @@ export function BookingForm() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setSelectedTreatment("");
|
setSelectedTreatments([]);
|
||||||
setCustomerName("");
|
setCustomerName("");
|
||||||
setCustomerEmail("");
|
setCustomerEmail("");
|
||||||
setCustomerPhone("");
|
setCustomerPhone("");
|
||||||
@@ -265,24 +323,65 @@ export function BookingForm() {
|
|||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
{/* Treatment Selection */}
|
{/* Treatment Selection */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
<div className="flex justify-between items-center mb-2">
|
||||||
Behandlung auswählen *
|
<label className="block text-sm font-medium text-gray-700">
|
||||||
</label>
|
Behandlungen auswählen (1-3) *
|
||||||
<select
|
</label>
|
||||||
value={selectedTreatment}
|
<span className="text-sm text-gray-600">
|
||||||
onChange={(e) => handleTreatmentChange(e.target.value)}
|
{selectedTreatments.length} von 3 ausgewählt
|
||||||
className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
</span>
|
||||||
required
|
</div>
|
||||||
>
|
|
||||||
<option value="">Wähle eine Behandlung</option>
|
{/* Checkbox List Container */}
|
||||||
{treatments?.map((treatment) => (
|
<div className="max-h-96 overflow-y-auto border border-gray-300 rounded-md p-3 space-y-2" aria-label="Wähle bis zu 3 Behandlungen">
|
||||||
<option key={treatment.id} value={treatment.id}>
|
{treatments?.map((treatment) => {
|
||||||
{treatment.name} - {(treatment.price / 100).toFixed(2)} € ({treatment.duration} Min)
|
const isSelected = selectedTreatments.some(t => t.id === treatment.id);
|
||||||
</option>
|
const isDisabled = selectedTreatments.length >= 3 && !isSelected;
|
||||||
))}
|
|
||||||
</select>
|
return (
|
||||||
{selectedTreatmentData && (
|
<div key={treatment.id} className="flex items-start space-x-3">
|
||||||
<p className="mt-2 text-sm text-gray-600">{selectedTreatmentData.description}</p>
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id={`treatment-${treatment.id}`}
|
||||||
|
checked={isSelected}
|
||||||
|
disabled={isDisabled}
|
||||||
|
onChange={() => handleTreatmentToggle({
|
||||||
|
id: treatment.id,
|
||||||
|
name: treatment.name,
|
||||||
|
duration: treatment.duration,
|
||||||
|
price: treatment.price
|
||||||
|
})}
|
||||||
|
className="h-4 w-4 text-pink-600 border-gray-300 rounded flex-shrink-0 mt-1"
|
||||||
|
/>
|
||||||
|
<label htmlFor={`treatment-${treatment.id}`} className={`flex-1 text-sm cursor-pointer ${isDisabled ? 'text-gray-400' : 'text-gray-700'}`}>
|
||||||
|
{treatment.name} - {treatment.duration} Min - {(treatment.price / 100).toFixed(2)} €
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Treatment Descriptions */}
|
||||||
|
{selectedTreatments.length > 0 && (
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
{selectedTreatments.map((selectedTreatment) => {
|
||||||
|
const fullTreatment = treatments?.find(t => t.id === selectedTreatment.id);
|
||||||
|
return fullTreatment ? (
|
||||||
|
<p key={selectedTreatment.id} className="text-sm text-gray-600">
|
||||||
|
<span className="font-medium">{fullTreatment.name}:</span> {fullTreatment.description}
|
||||||
|
</p>
|
||||||
|
) : null;
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Live Calculation Display */}
|
||||||
|
{selectedTreatments.length > 0 && (
|
||||||
|
<div className="mt-3 bg-pink-50 border border-pink-200 rounded-lg p-4">
|
||||||
|
<p className="font-semibold text-pink-700">
|
||||||
|
📊 Gesamt: {totalDuration} Min | {(totalPrice / 100).toFixed(2)} €
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -350,7 +449,7 @@ export function BookingForm() {
|
|||||||
value={selectedTime}
|
value={selectedTime}
|
||||||
onChange={(e) => setSelectedTime(e.target.value)}
|
onChange={(e) => setSelectedTime(e.target.value)}
|
||||||
className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
||||||
disabled={!appointmentDate || !selectedTreatment || isLoading || isFetching}
|
disabled={!appointmentDate || selectedTreatments.length === 0 || isLoading || isFetching}
|
||||||
required
|
required
|
||||||
>
|
>
|
||||||
<option value="">Zeit auswählen</option>
|
<option value="">Zeit auswählen</option>
|
||||||
@@ -360,23 +459,23 @@ export function BookingForm() {
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
{appointmentDate && selectedTreatment && isLoading && (
|
{appointmentDate && selectedTreatments.length > 0 && isLoading && (
|
||||||
<p className="mt-2 text-sm text-gray-500">
|
<p className="mt-2 text-sm text-gray-500">
|
||||||
Lade verfügbare Zeiten...
|
Lade verfügbare Zeiten...
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{appointmentDate && selectedTreatment && error && (
|
{appointmentDate && selectedTreatments.length > 0 && error && (
|
||||||
<p className="mt-2 text-sm text-red-500">
|
<p className="mt-2 text-sm text-red-500">
|
||||||
Fehler beim Laden der verfügbaren Zeiten. Bitte versuche es erneut.
|
Fehler beim Laden der verfügbaren Zeiten. Bitte versuche es erneut.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{appointmentDate && selectedTreatment && !isLoading && !isFetching && !error && (!availableTimes || availableTimes.length === 0) && (
|
{appointmentDate && selectedTreatments.length > 0 && !isLoading && !isFetching && !error && (!availableTimes || availableTimes.length === 0) && (
|
||||||
<p className="mt-2 text-sm text-gray-500">
|
<p className="mt-2 text-sm text-gray-500">
|
||||||
Keine verfügbaren Zeiten für dieses Datum. Bitte wähle ein anderes Datum.
|
Keine verfügbaren Zeiten für dieses Datum. Bitte wähle ein anderes Datum.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{selectedTreatmentData && (
|
{selectedTreatments.length > 0 && (
|
||||||
<p className="mt-1 text-xs text-gray-500">Dauer: {selectedTreatmentData.duration} Minuten</p>
|
<p className="mt-1 text-xs text-gray-500">Gesamtdauer: {totalDuration} Minuten</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@@ -8,6 +8,50 @@ interface BookingStatusPageProps {
|
|||||||
|
|
||||||
type BookingStatus = "pending" | "confirmed" | "cancelled" | "completed";
|
type BookingStatus = "pending" | "confirmed" | "cancelled" | "completed";
|
||||||
|
|
||||||
|
interface Treatment {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
duration: number;
|
||||||
|
price: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookingDetails {
|
||||||
|
id: string;
|
||||||
|
customerName: string;
|
||||||
|
customerEmail?: string;
|
||||||
|
customerPhone?: string;
|
||||||
|
appointmentDate: string;
|
||||||
|
appointmentTime: string;
|
||||||
|
treatments: Treatment[];
|
||||||
|
totalDuration: number;
|
||||||
|
totalPrice: number;
|
||||||
|
status: BookingStatus;
|
||||||
|
notes?: string;
|
||||||
|
formattedDate: string;
|
||||||
|
createdAt: string;
|
||||||
|
canCancel: boolean;
|
||||||
|
hoursUntilAppointment: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RescheduleProposalDetails {
|
||||||
|
booking: {
|
||||||
|
id: string;
|
||||||
|
customerName: string;
|
||||||
|
customerEmail?: string;
|
||||||
|
customerPhone?: string;
|
||||||
|
status: BookingStatus;
|
||||||
|
treatments: Treatment[];
|
||||||
|
totalDuration: number;
|
||||||
|
totalPrice: number;
|
||||||
|
};
|
||||||
|
original: { date: string; time: string };
|
||||||
|
proposed: { date?: string; time?: string };
|
||||||
|
expiresAt: string;
|
||||||
|
hoursUntilExpiry: number;
|
||||||
|
isExpired: boolean;
|
||||||
|
canRespond: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
function getStatusInfo(status: BookingStatus) {
|
function getStatusInfo(status: BookingStatus) {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case "pending":
|
case "pending":
|
||||||
@@ -57,7 +101,7 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
|||||||
const [showCancelConfirm, setShowCancelConfirm] = useState(false);
|
const [showCancelConfirm, setShowCancelConfirm] = useState(false);
|
||||||
const [isCancelling, setIsCancelling] = useState(false);
|
const [isCancelling, setIsCancelling] = useState(false);
|
||||||
const [cancellationResult, setCancellationResult] = useState<{ success: boolean; message: string; formattedDate?: string } | null>(null);
|
const [cancellationResult, setCancellationResult] = useState<{ success: boolean; message: string; formattedDate?: string } | null>(null);
|
||||||
const [rescheduleProposal, setRescheduleProposal] = useState<any | null>(null);
|
const [rescheduleProposal, setRescheduleProposal] = useState<RescheduleProposalDetails | null>(null);
|
||||||
const [rescheduleResult, setRescheduleResult] = useState<{ success: boolean; message: string } | null>(null);
|
const [rescheduleResult, setRescheduleResult] = useState<{ success: boolean; message: string } | null>(null);
|
||||||
const [isAccepting, setIsAccepting] = useState(false);
|
const [isAccepting, setIsAccepting] = useState(false);
|
||||||
const [isDeclining, setIsDeclining] = useState(false);
|
const [isDeclining, setIsDeclining] = useState(false);
|
||||||
@@ -71,7 +115,7 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Try fetching reschedule proposal if booking not found or error
|
// Try fetching reschedule proposal if booking not found or error
|
||||||
const rescheduleQuery = useQuery({
|
const rescheduleQuery = useQuery<RescheduleProposalDetails>({
|
||||||
...queryClient.cancellation.getRescheduleProposal.queryOptions({ input: { token } }),
|
...queryClient.cancellation.getRescheduleProposal.queryOptions({ input: { token } }),
|
||||||
enabled: !!token && (!!bookingError || !booking),
|
enabled: !!token && (!!bookingError || !booking),
|
||||||
});
|
});
|
||||||
@@ -159,7 +203,7 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
|||||||
|
|
||||||
if (oneClickAction === 'accept') {
|
if (oneClickAction === 'accept') {
|
||||||
const confirmAccept = window.confirm(
|
const confirmAccept = window.confirm(
|
||||||
`Möchtest du den neuen Termin am ${rescheduleProposal.proposed.date} um ${rescheduleProposal.proposed.time} Uhr akzeptieren?`
|
`Möchtest du den neuen Termin am ${rescheduleProposal.proposed.date || 'TBD'} um ${rescheduleProposal.proposed.time || 'TBD'} Uhr akzeptieren?`
|
||||||
);
|
);
|
||||||
if (confirmAccept) {
|
if (confirmAccept) {
|
||||||
acceptMutation.mutate({ token });
|
acceptMutation.mutate({ token });
|
||||||
@@ -311,12 +355,56 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
|||||||
<div className="border rounded-lg p-4 bg-gray-50">
|
<div className="border rounded-lg p-4 bg-gray-50">
|
||||||
<div className="text-sm text-gray-500 font-semibold mb-1">Aktueller Termin</div>
|
<div className="text-sm text-gray-500 font-semibold mb-1">Aktueller Termin</div>
|
||||||
<div className="text-gray-900 font-medium">{rescheduleProposal.original.date} um {rescheduleProposal.original.time} Uhr</div>
|
<div className="text-gray-900 font-medium">{rescheduleProposal.original.date} um {rescheduleProposal.original.time} Uhr</div>
|
||||||
<div className="text-gray-700 text-sm">{rescheduleProposal.booking.treatmentName}</div>
|
<div className="text-gray-700 text-sm mt-2">
|
||||||
|
{rescheduleProposal.booking.treatments && rescheduleProposal.booking.treatments.length > 0 ? (
|
||||||
|
<>
|
||||||
|
{rescheduleProposal.booking.treatments.length <= 2 ? (
|
||||||
|
rescheduleProposal.booking.treatments.map((t, i) => (
|
||||||
|
<div key={i}>{t.name}</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{rescheduleProposal.booking.treatments.slice(0, 2).map((t, i) => (
|
||||||
|
<div key={i}>{t.name}</div>
|
||||||
|
))}
|
||||||
|
<div className="text-gray-500 italic">+{rescheduleProposal.booking.treatments.length - 2} weitere</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="text-gray-600 mt-1 text-xs">
|
||||||
|
{rescheduleProposal.booking.totalDuration} Min
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="text-gray-400 italic">Keine Behandlungen</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border rounded-lg p-4 bg-orange-50">
|
<div className="border rounded-lg p-4 bg-orange-50">
|
||||||
<div className="text-sm text-orange-700 font-semibold mb-1">Neuer Vorschlag</div>
|
<div className="text-sm text-orange-700 font-semibold mb-1">Neuer Vorschlag</div>
|
||||||
<div className="text-gray-900 font-medium">{rescheduleProposal.proposed.date} um {rescheduleProposal.proposed.time} Uhr</div>
|
<div className="text-gray-900 font-medium">{rescheduleProposal.proposed.date || 'TBD'} um {rescheduleProposal.proposed.time || 'TBD'} Uhr</div>
|
||||||
<div className="text-gray-700 text-sm">{rescheduleProposal.booking.treatmentName}</div>
|
<div className="text-gray-700 text-sm mt-2">
|
||||||
|
{rescheduleProposal.booking.treatments && rescheduleProposal.booking.treatments.length > 0 ? (
|
||||||
|
<>
|
||||||
|
{rescheduleProposal.booking.treatments.length <= 2 ? (
|
||||||
|
rescheduleProposal.booking.treatments.map((t, i) => (
|
||||||
|
<div key={i}>{t.name}</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{rescheduleProposal.booking.treatments.slice(0, 2).map((t, i) => (
|
||||||
|
<div key={i}>{t.name}</div>
|
||||||
|
))}
|
||||||
|
<div className="text-gray-500 italic">+{rescheduleProposal.booking.treatments.length - 2} weitere</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="text-gray-600 mt-1 text-xs">
|
||||||
|
{rescheduleProposal.booking.totalDuration} Min
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="text-gray-400 italic">Keine Behandlungen</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-4 bg-yellow-50 border border-yellow-200 rounded-lg p-3 text-sm text-yellow-800">
|
<div className="mt-4 bg-yellow-50 border border-yellow-200 rounded-lg p-3 text-sm text-yellow-800">
|
||||||
@@ -478,20 +566,44 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
|||||||
<span className="text-gray-600">Uhrzeit:</span>
|
<span className="text-gray-600">Uhrzeit:</span>
|
||||||
<span className="font-medium text-gray-900">{booking?.appointmentTime} Uhr</span>
|
<span className="font-medium text-gray-900">{booking?.appointmentTime} Uhr</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
|
||||||
<span className="text-gray-600">Behandlung:</span>
|
{/* Treatments List */}
|
||||||
<span className="font-medium text-gray-900">{booking?.treatmentName}</span>
|
<div className="py-2 border-b border-gray-100">
|
||||||
|
<div className="text-gray-600 mb-2">Behandlungen:</div>
|
||||||
|
{booking?.treatments && booking.treatments.length > 0 ? (
|
||||||
|
<div className="bg-gray-50 rounded-lg p-3 space-y-2">
|
||||||
|
{booking.treatments.map((treatment, index) => (
|
||||||
|
<div key={index} className="flex justify-between items-center text-sm">
|
||||||
|
<span className="font-medium text-gray-900">• {treatment.name}</span>
|
||||||
|
<span className="text-gray-600">
|
||||||
|
{treatment.duration} Min - {treatment.price.toFixed(2)} €
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-between items-center pt-2 mt-2 border-t border-gray-200 font-semibold">
|
||||||
|
<span className="text-gray-900">Gesamt:</span>
|
||||||
|
<span className="text-gray-900">
|
||||||
|
{booking.totalDuration} Min - {booking.totalPrice.toFixed(2)} €
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<span className="text-gray-400 text-sm italic">Keine Behandlungen angegeben</span>
|
||||||
|
{((booking?.totalDuration ?? 0) > 0 || (booking?.totalPrice ?? 0) > 0) && (
|
||||||
|
<div className="bg-gray-50 rounded-lg p-3">
|
||||||
|
<div className="flex justify-between items-center font-semibold text-sm">
|
||||||
|
<span className="text-gray-900">Gesamt:</span>
|
||||||
|
<span className="text-gray-900">
|
||||||
|
{booking?.totalDuration ?? 0} Min - {(booking?.totalPrice ?? 0).toFixed(2)} €
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
|
||||||
<span className="text-gray-600">Dauer:</span>
|
|
||||||
<span className="font-medium text-gray-900">{booking?.treatmentDuration} Minuten</span>
|
|
||||||
</div>
|
|
||||||
{booking?.treatmentPrice && booking.treatmentPrice > 0 && (
|
|
||||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
|
||||||
<span className="text-gray-600">Preis:</span>
|
|
||||||
<span className="font-medium text-gray-900">{booking.treatmentPrice.toFixed(2)} €</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{booking?.hoursUntilAppointment && booking.hoursUntilAppointment > 0 && booking.status !== "cancelled" && booking.status !== "completed" && (
|
{booking?.hoursUntilAppointment && booking.hoursUntilAppointment > 0 && booking.status !== "cancelled" && booking.status !== "completed" && (
|
||||||
<div className="flex justify-between py-2">
|
<div className="flex justify-between py-2">
|
||||||
<span className="text-gray-600">Verbleibende Zeit:</span>
|
<span className="text-gray-600">Verbleibende Zeit:</span>
|
||||||
|
@@ -1,10 +1,19 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
interface BeforeInstallPromptEvent extends Event {
|
||||||
|
prompt: () => Promise<void>;
|
||||||
|
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
|
||||||
|
}
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Navigator { standalone?: boolean }
|
interface Navigator { standalone?: boolean }
|
||||||
|
interface WindowEventMap {
|
||||||
|
beforeinstallprompt: BeforeInstallPromptEvent;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const LAST_SHOWN_KEY = 'pwaInstallPrompt_lastShown';
|
const LAST_SHOWN_KEY = 'pwaInstallPrompt_lastShown';
|
||||||
|
const ANDROID_DISMISSED_KEY = 'pwaInstallPrompt_androidDismissed';
|
||||||
|
|
||||||
function isIOS(): boolean {
|
function isIOS(): boolean {
|
||||||
if (typeof navigator === 'undefined') return false;
|
if (typeof navigator === 'undefined') return false;
|
||||||
@@ -31,59 +40,144 @@ function isStandalone(): boolean {
|
|||||||
export function PWAInstallPrompt({ hidden = false }: { hidden?: boolean }) {
|
export function PWAInstallPrompt({ hidden = false }: { hidden?: boolean }) {
|
||||||
if (hidden) return null;
|
if (hidden) return null;
|
||||||
const [show, setShow] = useState(false);
|
const [show, setShow] = useState(false);
|
||||||
|
const [promptType, setPromptType] = useState<'ios' | 'android' | null>(null);
|
||||||
|
const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);
|
||||||
const [initialized, setInitialized] = useState(false);
|
const [initialized, setInitialized] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Only run on client
|
// Only run on client
|
||||||
if (typeof window === 'undefined') return;
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
const eligible = isIOS() && isSafari() && !isStandalone();
|
// Check if already in standalone mode
|
||||||
if (!eligible) {
|
if (isStandalone()) {
|
||||||
setInitialized(true);
|
setInitialized(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let lastShown = 0;
|
// Handle iOS
|
||||||
try {
|
const isIOSDevice = isIOS() && isSafari();
|
||||||
lastShown = Number(localStorage.getItem(LAST_SHOWN_KEY) || 0);
|
if (isIOSDevice) {
|
||||||
} catch {}
|
let lastShown = 0;
|
||||||
const oneWeek = 7 * 24 * 60 * 60 * 1000;
|
try {
|
||||||
const shouldShow = !lastShown || Date.now() - lastShown > oneWeek;
|
lastShown = Number(localStorage.getItem(LAST_SHOWN_KEY) || 0);
|
||||||
|
} catch {}
|
||||||
|
const oneWeek = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
const shouldShow = !lastShown || Date.now() - lastShown > oneWeek;
|
||||||
|
|
||||||
setShow(shouldShow);
|
if (shouldShow) {
|
||||||
|
setPromptType('ios');
|
||||||
|
setShow(true);
|
||||||
|
}
|
||||||
|
setInitialized(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle Android (beforeinstallprompt)
|
||||||
|
const handleBeforeInstall = (e: BeforeInstallPromptEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
// Check if user has dismissed Android prompt before
|
||||||
|
let dismissed = false;
|
||||||
|
try {
|
||||||
|
dismissed = localStorage.getItem(ANDROID_DISMISSED_KEY) === 'true';
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if (!dismissed) {
|
||||||
|
setDeferredPrompt(e);
|
||||||
|
setPromptType('android');
|
||||||
|
setShow(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('beforeinstallprompt', handleBeforeInstall);
|
||||||
setInitialized(true);
|
setInitialized(true);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('beforeinstallprompt', handleBeforeInstall);
|
||||||
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const dismiss = () => {
|
const dismiss = () => {
|
||||||
try { localStorage.setItem(LAST_SHOWN_KEY, String(Date.now())); } catch {}
|
if (promptType === 'ios') {
|
||||||
|
try { localStorage.setItem(LAST_SHOWN_KEY, String(Date.now())); } catch {}
|
||||||
|
} else if (promptType === 'android') {
|
||||||
|
try { localStorage.setItem(ANDROID_DISMISSED_KEY, 'true'); } catch {}
|
||||||
|
}
|
||||||
setShow(false);
|
setShow(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!initialized || !show) return null;
|
const handleAndroidInstall = async () => {
|
||||||
|
if (!deferredPrompt) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deferredPrompt.prompt();
|
||||||
|
const choiceResult = await deferredPrompt.userChoice;
|
||||||
|
|
||||||
|
if (choiceResult.outcome === 'accepted') {
|
||||||
|
console.log('PWA installation accepted');
|
||||||
|
}
|
||||||
|
|
||||||
|
setDeferredPrompt(null);
|
||||||
|
setShow(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error during PWA installation:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!initialized || !show || !promptType) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
role="dialog"
|
role="dialog"
|
||||||
aria-label="PWA Installation Anleitung"
|
aria-label={promptType === 'android' ? 'PWA Installation' : 'PWA Installation Anleitung'}
|
||||||
className="fixed bottom-0 left-0 right-0 z-50 px-4 pb-4"
|
className="fixed bottom-0 left-0 right-0 z-50 px-4 pb-4"
|
||||||
style={{ paddingBottom: `max(env(safe-area-inset-bottom), 1rem)` }}
|
style={{ paddingBottom: `max(env(safe-area-inset-bottom), 1rem)` }}
|
||||||
>
|
>
|
||||||
<div className="relative max-w-3xl mx-auto rounded-xl shadow-lg bg-gradient-to-r from-pink-500 to-purple-600 text-white p-4 sm:p-6">
|
<div className="relative max-w-3xl mx-auto rounded-xl shadow-lg bg-gradient-to-r from-pink-500 to-purple-600 text-white p-4 sm:p-6">
|
||||||
<button aria-label="Hinweis schließen" onClick={dismiss} className="absolute top-2 right-2 text-white/90 hover:text-white text-2xl leading-none">×</button>
|
<button aria-label="Hinweis schließen" onClick={dismiss} className="absolute top-2 right-2 text-white/90 hover:text-white text-2xl leading-none">×</button>
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
<div className="text-2xl">📱</div>
|
{promptType === 'android' ? (
|
||||||
<div className="flex-1">
|
// Android: Direct install button
|
||||||
<h3 className="text-lg sm:text-xl font-bold mb-2">App installieren</h3>
|
<div className="flex items-center gap-4">
|
||||||
<p className="text-white/90 mb-2">So installierst du Stargirlnails als App auf deinem iPhone/iPad:</p>
|
<div className="text-3xl">📱</div>
|
||||||
<ol className="list-decimal pl-5 space-y-1 text-white/95">
|
<div className="flex-1">
|
||||||
<li>Öffne diese Seite in Safari (nicht Chrome oder andere Browser).</li>
|
<h3 className="text-lg sm:text-xl font-bold mb-2">App installieren</h3>
|
||||||
<li>Tippe auf das Teilen-Symbol (□↑) unten in der Mitte.</li>
|
<p className="text-white/90 mb-3">
|
||||||
<li>Scrolle nach unten und wähle „Zum Home-Bildschirm".</li>
|
Installiere Stargirlnails als App für schnellen Zugriff direkt vom Startbildschirm!
|
||||||
<li>Tippe auf „Hinzufügen".</li>
|
</p>
|
||||||
</ol>
|
<div className="flex gap-2">
|
||||||
<p className="mt-3 text-sm text-white/90">✨ Schneller Zugriff, keine App-Store-Installation nötig, automatische Updates.</p>
|
<button
|
||||||
|
onClick={handleAndroidInstall}
|
||||||
|
className="bg-white text-pink-600 px-4 py-2 rounded-lg font-semibold hover:bg-pink-50 transition-colors"
|
||||||
|
>
|
||||||
|
Jetzt installieren
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={dismiss}
|
||||||
|
className="bg-white/20 text-white px-4 py-2 rounded-lg font-semibold hover:bg-white/30 transition-colors"
|
||||||
|
>
|
||||||
|
Später
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
) : (
|
||||||
|
// iOS: Manual instructions
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="text-2xl">📱</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<h3 className="text-lg sm:text-xl font-bold mb-2">App installieren</h3>
|
||||||
|
<p className="text-white/90 mb-2">So installierst du Stargirlnails als App auf deinem iPhone/iPad:</p>
|
||||||
|
<ol className="list-decimal pl-5 space-y-1 text-white/95">
|
||||||
|
<li>Öffne diese Seite in Safari (nicht Chrome oder andere Browser).</li>
|
||||||
|
<li>Tippe auf das Teilen-Symbol (□↑) unten in der Mitte.</li>
|
||||||
|
<li>Scrolle nach unten und wähle „Zum Home-Bildschirm".</li>
|
||||||
|
<li>Tippe auf „Hinzufügen".</li>
|
||||||
|
</ol>
|
||||||
|
<p className="mt-3 text-sm text-white/90">✨ Schneller Zugriff, keine App-Store-Installation nötig, automatische Updates.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
@@ -139,7 +139,11 @@ export default function ReviewSubmissionPage({ token }: ReviewSubmissionPageProp
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
<div className="flex justify-between py-2 border-b border-gray-100">
|
||||||
<span className="text-gray-600">Behandlung:</span>
|
<span className="text-gray-600">Behandlung:</span>
|
||||||
<span className="font-medium text-gray-900">{booking.treatmentName}</span>
|
<span className="font-medium text-gray-900">
|
||||||
|
{booking.treatments && booking.treatments.length > 0
|
||||||
|
? booking.treatments.map((t: any) => t.name).join(", ")
|
||||||
|
: "Keine Behandlung"}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between py-2">
|
<div className="flex justify-between py-2">
|
||||||
<span className="text-gray-600">Name:</span>
|
<span className="text-gray-600">Name:</span>
|
||||||
|
@@ -8,6 +8,27 @@ function formatDateGerman(dateString: string): string {
|
|||||||
return `${day}.${month}.${year}`;
|
return `${day}.${month}.${year}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper function to render treatment list HTML
|
||||||
|
function renderTreatmentList(
|
||||||
|
treatments: Array<{id: string; name: string; duration: number; price: number}>,
|
||||||
|
options: { showPrices: boolean } = { showPrices: true }
|
||||||
|
): string {
|
||||||
|
const totalDuration = treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
|
const treatmentItems = treatments.map(t =>
|
||||||
|
options.showPrices
|
||||||
|
? `<li><strong>${t.name}</strong> - ${t.duration} Min - ${(t.price / 100).toFixed(2)} €</li>`
|
||||||
|
: `<li>${t.name} - ${t.duration} Min - ${(t.price / 100).toFixed(2)} €</li>`
|
||||||
|
).join('');
|
||||||
|
|
||||||
|
const totalLine = options.showPrices
|
||||||
|
? `<li style="border-top: 1px solid #e2e8f0; margin-top: 8px; padding-top: 8px;"><strong>Gesamt:</strong> ${totalDuration} Min - ${totalPrice.toFixed(2)} €</li>`
|
||||||
|
: `<li style="font-weight: 600; margin-top: 4px;">Gesamt: ${totalDuration} Min - ${totalPrice.toFixed(2)} €</li>`;
|
||||||
|
|
||||||
|
return `${treatmentItems}${totalLine}`;
|
||||||
|
}
|
||||||
|
|
||||||
let cachedLogoDataUrl: string | null = null;
|
let cachedLogoDataUrl: string | null = null;
|
||||||
|
|
||||||
async function getLogoDataUrl(): Promise<string | null> {
|
async function getLogoDataUrl(): Promise<string | null> {
|
||||||
@@ -86,8 +107,8 @@ async function renderBrandedEmail(title: string, bodyHtml: string): Promise<stri
|
|||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function renderBookingPendingHTML(params: { name: string; date: string; time: string; statusUrl?: string }) {
|
export async function renderBookingPendingHTML(params: { name: string; date: string; time: string; statusUrl?: string; treatments: Array<{id: string; name: string; duration: number; price: number}> }) {
|
||||||
const { name, date, time, statusUrl } = params;
|
const { name, date, time, statusUrl, treatments } = params;
|
||||||
const formattedDate = formatDateGerman(date);
|
const formattedDate = formatDateGerman(date);
|
||||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||||
@@ -96,6 +117,12 @@ export async function renderBookingPendingHTML(params: { name: string; date: str
|
|||||||
const inner = `
|
const inner = `
|
||||||
<p>Hallo ${name},</p>
|
<p>Hallo ${name},</p>
|
||||||
<p>wir haben deine Anfrage für <strong>${formattedDate}</strong> um <strong>${time}</strong> erhalten.</p>
|
<p>wir haben deine Anfrage für <strong>${formattedDate}</strong> um <strong>${time}</strong> erhalten.</p>
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0 0 8px 0; font-weight: 600; color: #db2777;">💅 Deine Behandlungen:</p>
|
||||||
|
<ul style="margin: 0; color: #475569; list-style: none; padding: 0;">
|
||||||
|
${renderTreatmentList(treatments, { showPrices: true })}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
<p>Wir bestätigen deinen Termin in Kürze. Du erhältst eine weitere E-Mail, sobald der Termin bestätigt ist.</p>
|
<p>Wir bestätigen deinen Termin in Kürze. Du erhältst eine weitere E-Mail, sobald der Termin bestätigt ist.</p>
|
||||||
${statusUrl ? `
|
${statusUrl ? `
|
||||||
<div style="background-color: #fef9f5; border-left: 4px solid #f59e0b; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
<div style="background-color: #fef9f5; border-left: 4px solid #f59e0b; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
@@ -113,8 +140,8 @@ export async function renderBookingPendingHTML(params: { name: string; date: str
|
|||||||
return renderBrandedEmail("Deine Terminanfrage ist eingegangen", inner);
|
return renderBrandedEmail("Deine Terminanfrage ist eingegangen", inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function renderBookingConfirmedHTML(params: { name: string; date: string; time: string; cancellationUrl?: string; reviewUrl?: string }) {
|
export async function renderBookingConfirmedHTML(params: { name: string; date: string; time: string; cancellationUrl?: string; reviewUrl?: string; treatments: Array<{id: string; name: string; duration: number; price: number}> }) {
|
||||||
const { name, date, time, cancellationUrl, reviewUrl } = params;
|
const { name, date, time, cancellationUrl, reviewUrl, treatments } = params;
|
||||||
const formattedDate = formatDateGerman(date);
|
const formattedDate = formatDateGerman(date);
|
||||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||||
@@ -123,6 +150,12 @@ export async function renderBookingConfirmedHTML(params: { name: string; date: s
|
|||||||
const inner = `
|
const inner = `
|
||||||
<p>Hallo ${name},</p>
|
<p>Hallo ${name},</p>
|
||||||
<p>wir haben deinen Termin am <strong>${formattedDate}</strong> um <strong>${time}</strong> bestätigt.</p>
|
<p>wir haben deinen Termin am <strong>${formattedDate}</strong> um <strong>${time}</strong> bestätigt.</p>
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0 0 8px 0; font-weight: 600; color: #db2777;">💅 Deine Behandlungen:</p>
|
||||||
|
<ul style="margin: 0; color: #475569; list-style: none; padding: 0;">
|
||||||
|
${renderTreatmentList(treatments, { showPrices: true })}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
<p>Wir freuen uns auf dich!</p>
|
<p>Wir freuen uns auf dich!</p>
|
||||||
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
<p style="margin: 0; font-weight: 600; color: #db2777;">📋 Wichtiger Hinweis:</p>
|
<p style="margin: 0; font-weight: 600; color: #db2777;">📋 Wichtiger Hinweis:</p>
|
||||||
@@ -152,8 +185,8 @@ export async function renderBookingConfirmedHTML(params: { name: string; date: s
|
|||||||
return renderBrandedEmail("Termin bestätigt", inner);
|
return renderBrandedEmail("Termin bestätigt", inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function renderBookingCancelledHTML(params: { name: string; date: string; time: string }) {
|
export async function renderBookingCancelledHTML(params: { name: string; date: string; time: string; treatments: Array<{id: string; name: string; duration: number; price: number}> }) {
|
||||||
const { name, date, time } = params;
|
const { name, date, time, treatments } = params;
|
||||||
const formattedDate = formatDateGerman(date);
|
const formattedDate = formatDateGerman(date);
|
||||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||||
@@ -162,6 +195,12 @@ export async function renderBookingCancelledHTML(params: { name: string; date: s
|
|||||||
const inner = `
|
const inner = `
|
||||||
<p>Hallo ${name},</p>
|
<p>Hallo ${name},</p>
|
||||||
<p>dein Termin am <strong>${formattedDate}</strong> um <strong>${time}</strong> wurde abgesagt.</p>
|
<p>dein Termin am <strong>${formattedDate}</strong> um <strong>${time}</strong> wurde abgesagt.</p>
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0 0 8px 0; font-weight: 600; color: #db2777;">💅 Abgesagte Behandlungen:</p>
|
||||||
|
<ul style="margin: 0; color: #475569; list-style: none; padding: 0;">
|
||||||
|
${renderTreatmentList(treatments, { showPrices: true })}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
<p>Bitte buche einen neuen Termin. Bei Fragen helfen wir dir gerne weiter.</p>
|
<p>Bitte buche einen neuen Termin. Bei Fragen helfen wir dir gerne weiter.</p>
|
||||||
<div style="background-color: #f8fafc; border-left: 4px solid #3b82f6; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
<div style="background-color: #f8fafc; border-left: 4px solid #3b82f6; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
<p style="margin: 0; font-weight: 600; color: #3b82f6;">📋 Rechtliche Informationen:</p>
|
<p style="margin: 0; font-weight: 600; color: #3b82f6;">📋 Rechtliche Informationen:</p>
|
||||||
@@ -176,13 +215,14 @@ export async function renderAdminBookingNotificationHTML(params: {
|
|||||||
name: string;
|
name: string;
|
||||||
date: string;
|
date: string;
|
||||||
time: string;
|
time: string;
|
||||||
treatment: string;
|
treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
phone: string;
|
phone: string;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
hasInspirationPhoto: boolean;
|
hasInspirationPhoto: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { name, date, time, treatment, phone, notes, hasInspirationPhoto } = params;
|
const { name, date, time, treatments, phone, notes, hasInspirationPhoto } = params;
|
||||||
const formattedDate = formatDateGerman(date);
|
const formattedDate = formatDateGerman(date);
|
||||||
|
|
||||||
const inner = `
|
const inner = `
|
||||||
<p>Hallo Admin,</p>
|
<p>Hallo Admin,</p>
|
||||||
<p>eine neue Buchungsanfrage ist eingegangen:</p>
|
<p>eine neue Buchungsanfrage ist eingegangen:</p>
|
||||||
@@ -191,7 +231,11 @@ export async function renderAdminBookingNotificationHTML(params: {
|
|||||||
<ul style="margin: 8px 0 0 0; color: #475569; list-style: none; padding: 0;">
|
<ul style="margin: 8px 0 0 0; color: #475569; list-style: none; padding: 0;">
|
||||||
<li><strong>Name:</strong> ${name}</li>
|
<li><strong>Name:</strong> ${name}</li>
|
||||||
<li><strong>Telefon:</strong> ${phone}</li>
|
<li><strong>Telefon:</strong> ${phone}</li>
|
||||||
<li><strong>Behandlung:</strong> ${treatment}</li>
|
<li><strong>Behandlungen:</strong>
|
||||||
|
<ul style="margin: 4px 0 0 0; list-style: none; padding: 0 0 0 16px;">
|
||||||
|
${renderTreatmentList(treatments, { showPrices: false })}
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
<li><strong>Datum:</strong> ${formattedDate}</li>
|
<li><strong>Datum:</strong> ${formattedDate}</li>
|
||||||
<li><strong>Uhrzeit:</strong> ${time}</li>
|
<li><strong>Uhrzeit:</strong> ${time}</li>
|
||||||
${notes ? `<li><strong>Notizen:</strong> ${notes}</li>` : ''}
|
${notes ? `<li><strong>Notizen:</strong> ${notes}</li>` : ''}
|
||||||
@@ -347,3 +391,43 @@ export async function renderAdminRescheduleExpiredHTML(params: {
|
|||||||
return renderBrandedEmail("Abgelaufene Terminänderungsvorschläge", inner);
|
return renderBrandedEmail("Abgelaufene Terminänderungsvorschläge", inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function renderCustomerMessageHTML(params: {
|
||||||
|
customerName: string;
|
||||||
|
message: string;
|
||||||
|
appointmentDate?: string;
|
||||||
|
appointmentTime?: string;
|
||||||
|
treatmentName?: string;
|
||||||
|
}) {
|
||||||
|
const { customerName, message, appointmentDate, appointmentTime, treatmentName } = params;
|
||||||
|
const formattedDate = appointmentDate ? formatDateGerman(appointmentDate) : null;
|
||||||
|
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||||
|
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||||
|
const legalUrl = `${protocol}://${domain}/legal`;
|
||||||
|
const ownerName = process.env.OWNER_NAME || 'Stargirlnails Kiel';
|
||||||
|
|
||||||
|
const inner = `
|
||||||
|
<p>Hallo ${customerName},</p>
|
||||||
|
${(appointmentDate && appointmentTime && treatmentName) ? `
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0; font-weight: 600; color: #db2777;">📅 Zu deinem Termin:</p>
|
||||||
|
<ul style="margin: 8px 0 0 0; color: #475569; list-style: none; padding: 0;">
|
||||||
|
<li><strong>Behandlung:</strong> ${treatmentName}</li>
|
||||||
|
<li><strong>Datum:</strong> ${formattedDate}</li>
|
||||||
|
<li><strong>Uhrzeit:</strong> ${appointmentTime}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
` : ''}
|
||||||
|
<div style="background-color: #fef9f5; border-left: 4px solid #f59e0b; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0; font-weight: 600; color: #f59e0b;">💬 Nachricht von ${ownerName}:</p>
|
||||||
|
<div style="margin: 12px 0 0 0; color: #475569; white-space: pre-wrap; line-height: 1.6;">${message.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')}</div>
|
||||||
|
</div>
|
||||||
|
<p>Bei Fragen oder Anliegen kannst du einfach auf diese E-Mail antworten – wir helfen dir gerne weiter!</p>
|
||||||
|
<div style="background-color: #f8fafc; border-left: 4px solid #3b82f6; padding: 16px; margin: 20px 0; border-radius: 4px;">
|
||||||
|
<p style="margin: 0; font-weight: 600; color: #3b82f6;">📋 Rechtliche Informationen:</p>
|
||||||
|
<p style="margin: 8px 0 12px 0; color: #475569;">Weitere Informationen findest du in unserem <a href="${legalUrl}" style="color: #3b82f6; text-decoration: underline;">Impressum und Datenschutz</a>.</p>
|
||||||
|
</div>
|
||||||
|
<p>Liebe Grüße,<br/>${ownerName}</p>
|
||||||
|
`;
|
||||||
|
return renderBrandedEmail("Nachricht zu deinem Termin", inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
@@ -6,6 +6,7 @@ type SendEmailParams = {
|
|||||||
from?: string;
|
from?: string;
|
||||||
cc?: string | string[];
|
cc?: string | string[];
|
||||||
bcc?: string | string[];
|
bcc?: string | string[];
|
||||||
|
replyTo?: string | string[];
|
||||||
attachments?: Array<{
|
attachments?: Array<{
|
||||||
filename: string;
|
filename: string;
|
||||||
content: string; // base64 encoded
|
content: string; // base64 encoded
|
||||||
@@ -28,15 +29,27 @@ function formatDateForICS(date: string, time: string): string {
|
|||||||
return `${year}${month}${day}T${hours}${minutes}00`;
|
return `${year}${month}${day}T${hours}${minutes}00`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper function to escape text values for ICS files (RFC 5545)
|
||||||
|
function icsEscape(text: string): string {
|
||||||
|
return text
|
||||||
|
.replace(/\\/g, '\\\\') // Backslash must be escaped first
|
||||||
|
.replace(/;/g, '\\;') // Semicolon
|
||||||
|
.replace(/,/g, '\\,') // Comma
|
||||||
|
.replace(/\n/g, '\\n'); // Newline
|
||||||
|
}
|
||||||
|
|
||||||
// Helper function to create ICS (iCalendar) file content
|
// Helper function to create ICS (iCalendar) file content
|
||||||
function createICSFile(params: {
|
function createICSFile(params: {
|
||||||
date: string; // YYYY-MM-DD
|
date: string; // YYYY-MM-DD
|
||||||
time: string; // HH:MM
|
time: string; // HH:MM
|
||||||
durationMinutes: number;
|
|
||||||
customerName: string;
|
customerName: string;
|
||||||
treatmentName: string;
|
customerEmail?: string;
|
||||||
|
treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
}): string {
|
}): string {
|
||||||
const { date, time, durationMinutes, customerName, treatmentName } = params;
|
const { date, time, customerName, customerEmail, treatments } = params;
|
||||||
|
|
||||||
|
// Calculate duration from treatments
|
||||||
|
const durationMinutes = treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
|
||||||
// Calculate start and end times in Europe/Berlin timezone
|
// Calculate start and end times in Europe/Berlin timezone
|
||||||
const dtStart = formatDateForICS(date, time);
|
const dtStart = formatDateForICS(date, time);
|
||||||
@@ -56,6 +69,17 @@ function createICSFile(params: {
|
|||||||
const now = new Date();
|
const now = new Date();
|
||||||
const dtstamp = now.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
|
const dtstamp = now.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
|
||||||
|
|
||||||
|
// Build treatments list for SUMMARY and DESCRIPTION
|
||||||
|
const treatmentNames = icsEscape(treatments.map(t => t.name).join(', '));
|
||||||
|
const totalDuration = treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
|
const treatmentDetails = treatments.map(t =>
|
||||||
|
`${icsEscape(t.name)} (${t.duration} Min, ${(t.price / 100).toFixed(2)} EUR)`
|
||||||
|
).join('\\n');
|
||||||
|
|
||||||
|
const description = `Behandlungen:\\n${treatmentDetails}\\n\\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} EUR\\n\\nTermin bei Stargirlnails Kiel`;
|
||||||
|
|
||||||
// ICS content
|
// ICS content
|
||||||
const icsContent = [
|
const icsContent = [
|
||||||
'BEGIN:VCALENDAR',
|
'BEGIN:VCALENDAR',
|
||||||
@@ -68,11 +92,11 @@ function createICSFile(params: {
|
|||||||
`DTSTAMP:${dtstamp}`,
|
`DTSTAMP:${dtstamp}`,
|
||||||
`DTSTART;TZID=Europe/Berlin:${dtStart}`,
|
`DTSTART;TZID=Europe/Berlin:${dtStart}`,
|
||||||
`DTEND;TZID=Europe/Berlin:${dtEnd}`,
|
`DTEND;TZID=Europe/Berlin:${dtEnd}`,
|
||||||
`SUMMARY:${treatmentName} - Stargirlnails Kiel`,
|
`SUMMARY:${treatmentNames} - Stargirlnails Kiel`,
|
||||||
`DESCRIPTION:Termin für ${treatmentName} bei Stargirlnails Kiel`,
|
`DESCRIPTION:${description}`,
|
||||||
'LOCATION:Stargirlnails Kiel',
|
'LOCATION:Stargirlnails Kiel',
|
||||||
`ORGANIZER;CN=Stargirlnails Kiel:mailto:${process.env.EMAIL_FROM?.match(/<(.+)>/)?.[1] || 'no-reply@stargirlnails.de'}`,
|
`ORGANIZER;CN=Stargirlnails Kiel:mailto:${process.env.EMAIL_FROM?.match(/<(.+)>/)?.[1] || 'no-reply@stargirlnails.de'}`,
|
||||||
`ATTENDEE;CN=${customerName};RSVP=TRUE:mailto:${customerName}`,
|
...(customerEmail ? [`ATTENDEE;CN=${customerName};RSVP=TRUE:mailto:${customerEmail}`] : []),
|
||||||
'STATUS:CONFIRMED',
|
'STATUS:CONFIRMED',
|
||||||
'SEQUENCE:0',
|
'SEQUENCE:0',
|
||||||
'BEGIN:VALARM',
|
'BEGIN:VALARM',
|
||||||
@@ -130,22 +154,27 @@ export async function sendEmail(params: SendEmailParams): Promise<{ success: boo
|
|||||||
return { success: false };
|
return { success: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
from: params.from || DEFAULT_FROM,
|
||||||
|
to: Array.isArray(params.to) ? params.to : [params.to],
|
||||||
|
subject: params.subject,
|
||||||
|
text: params.text,
|
||||||
|
html: params.html,
|
||||||
|
cc: params.cc ? (Array.isArray(params.cc) ? params.cc : [params.cc]) : undefined,
|
||||||
|
bcc: params.bcc ? (Array.isArray(params.bcc) ? params.bcc : [params.bcc]) : undefined,
|
||||||
|
reply_to: params.replyTo ? (Array.isArray(params.replyTo) ? params.replyTo : [params.replyTo]) : undefined,
|
||||||
|
attachments: params.attachments,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(`Sending email via Resend: to=${JSON.stringify(payload.to)}, subject="${params.subject}"`);
|
||||||
|
|
||||||
const response = await fetch("https://api.resend.com/emails", {
|
const response = await fetch("https://api.resend.com/emails", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Authorization": `Bearer ${RESEND_API_KEY}`,
|
"Authorization": `Bearer ${RESEND_API_KEY}`,
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(payload),
|
||||||
from: params.from || DEFAULT_FROM,
|
|
||||||
to: Array.isArray(params.to) ? params.to : [params.to],
|
|
||||||
subject: params.subject,
|
|
||||||
text: params.text,
|
|
||||||
html: params.html,
|
|
||||||
cc: params.cc ? (Array.isArray(params.cc) ? params.cc : [params.cc]) : undefined,
|
|
||||||
bcc: params.bcc ? (Array.isArray(params.bcc) ? params.bcc : [params.bcc]) : undefined,
|
|
||||||
attachments: params.attachments,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -153,6 +182,9 @@ export async function sendEmail(params: SendEmailParams): Promise<{ success: boo
|
|||||||
console.error("Resend send error:", response.status, body);
|
console.error("Resend send error:", response.status, body);
|
||||||
return { success: false };
|
return { success: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const responseData = await response.json().catch(() => ({}));
|
||||||
|
console.log("Resend email sent successfully:", responseData);
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,9 +210,9 @@ export async function sendEmailWithAGBAndCalendar(
|
|||||||
calendarParams: {
|
calendarParams: {
|
||||||
date: string;
|
date: string;
|
||||||
time: string;
|
time: string;
|
||||||
durationMinutes: number;
|
|
||||||
customerName: string;
|
customerName: string;
|
||||||
treatmentName: string;
|
customerEmail?: string;
|
||||||
|
treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
}
|
}
|
||||||
): Promise<{ success: boolean }> {
|
): Promise<{ success: boolean }> {
|
||||||
const agbBase64 = await getAGBPDFBase64();
|
const agbBase64 = await getAGBPDFBase64();
|
||||||
|
@@ -5,7 +5,7 @@ import { assertOwner } from "../lib/auth.js";
|
|||||||
// Types für Buchungen (vereinfacht für CalDAV)
|
// Types für Buchungen (vereinfacht für CalDAV)
|
||||||
type Booking = {
|
type Booking = {
|
||||||
id: string;
|
id: string;
|
||||||
treatmentId: string;
|
treatments?: Array<{id: string, name: string, duration: number, price: number}>;
|
||||||
customerName: string;
|
customerName: string;
|
||||||
customerEmail?: string;
|
customerEmail?: string;
|
||||||
customerPhone?: string;
|
customerPhone?: string;
|
||||||
@@ -13,6 +13,8 @@ type Booking = {
|
|||||||
appointmentTime: string; // HH:MM
|
appointmentTime: string; // HH:MM
|
||||||
status: "pending" | "confirmed" | "cancelled" | "completed";
|
status: "pending" | "confirmed" | "cancelled" | "completed";
|
||||||
notes?: string;
|
notes?: string;
|
||||||
|
// Deprecated fields for backward compatibility
|
||||||
|
treatmentId?: string;
|
||||||
bookedDurationMinutes?: number;
|
bookedDurationMinutes?: number;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
};
|
};
|
||||||
@@ -44,6 +46,14 @@ function formatDateTime(dateStr: string, timeStr: string): string {
|
|||||||
return date.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
return date.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function addMinutesToTime(timeStr: string, minutesToAdd: number): string {
|
||||||
|
const [hours, minutes] = timeStr.split(':').map(Number);
|
||||||
|
const totalMinutes = hours * 60 + minutes + minutesToAdd;
|
||||||
|
const newHours = Math.floor(totalMinutes / 60);
|
||||||
|
const newMinutes = totalMinutes % 60;
|
||||||
|
return `${String(newHours).padStart(2, '0')}:${String(newMinutes).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
function generateICSContent(bookings: Booking[], treatments: Treatment[]): string {
|
function generateICSContent(bookings: Booking[], treatments: Treatment[]): string {
|
||||||
const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
||||||
|
|
||||||
@@ -63,14 +73,41 @@ X-WR-TIMEZONE:Europe/Berlin
|
|||||||
);
|
);
|
||||||
|
|
||||||
for (const booking of activeBookings) {
|
for (const booking of activeBookings) {
|
||||||
const treatment = treatments.find(t => t.id === booking.treatmentId);
|
// Handle new treatments array structure
|
||||||
const treatmentName = treatment?.name || 'Unbekannte Behandlung';
|
let treatmentNames: string;
|
||||||
const duration = booking.bookedDurationMinutes || treatment?.duration || 60;
|
let duration: number;
|
||||||
|
let treatmentDetails: string;
|
||||||
|
let totalPrice = 0;
|
||||||
|
|
||||||
|
if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
|
||||||
|
// Use new treatments array
|
||||||
|
treatmentNames = booking.treatments.map(t => t.name).join(', ');
|
||||||
|
|
||||||
|
duration = booking.treatments.reduce((sum, t) => sum + (t.duration || 0), 0);
|
||||||
|
totalPrice = booking.treatments.reduce((sum, t) => sum + ((t.price || 0) / 100), 0);
|
||||||
|
|
||||||
|
// Build detailed treatment list for description
|
||||||
|
treatmentDetails = booking.treatments
|
||||||
|
.map(t => `- ${t.name} (${t.duration} Min., ${(t.price / 100).toFixed(2)}€)`)
|
||||||
|
.join('\\n');
|
||||||
|
|
||||||
|
if (booking.treatments.length > 1) {
|
||||||
|
treatmentDetails += `\\n\\nGesamt: ${duration} Min., ${totalPrice.toFixed(2)}€`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fallback to deprecated treatmentId for backward compatibility
|
||||||
|
const treatment = booking.treatmentId ? treatments.find(t => t.id === booking.treatmentId) : null;
|
||||||
|
treatmentNames = treatment?.name || 'Unbekannte Behandlung';
|
||||||
|
duration = booking.bookedDurationMinutes || treatment?.duration || 60;
|
||||||
|
treatmentDetails = `Behandlung: ${treatmentNames}`;
|
||||||
|
if (treatment?.price) {
|
||||||
|
treatmentDetails += ` (${duration} Min., ${(treatment.price / 100).toFixed(2)}€)`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const startTime = formatDateTime(booking.appointmentDate, booking.appointmentTime);
|
const startTime = formatDateTime(booking.appointmentDate, booking.appointmentTime);
|
||||||
const endTime = formatDateTime(booking.appointmentDate,
|
const endTimeStr = addMinutesToTime(booking.appointmentTime, duration);
|
||||||
`${String(Math.floor((parseInt(booking.appointmentTime.split(':')[0]) * 60 + parseInt(booking.appointmentTime.split(':')[1]) + duration) / 60)).padStart(2, '0')}:${String((parseInt(booking.appointmentTime.split(':')[0]) * 60 + parseInt(booking.appointmentTime.split(':')[1]) + duration) % 60).padStart(2, '0')}`
|
const endTime = formatDateTime(booking.appointmentDate, endTimeStr);
|
||||||
);
|
|
||||||
|
|
||||||
// UID für jeden Termin (eindeutig)
|
// UID für jeden Termin (eindeutig)
|
||||||
const uid = `booking-${booking.id}@stargirlnails.de`;
|
const uid = `booking-${booking.id}@stargirlnails.de`;
|
||||||
@@ -83,8 +120,8 @@ UID:${uid}
|
|||||||
DTSTAMP:${now}
|
DTSTAMP:${now}
|
||||||
DTSTART:${startTime}
|
DTSTART:${startTime}
|
||||||
DTEND:${endTime}
|
DTEND:${endTime}
|
||||||
SUMMARY:${treatmentName} - ${booking.customerName}
|
SUMMARY:${treatmentNames} - ${booking.customerName}
|
||||||
DESCRIPTION:Behandlung: ${treatmentName}\\nKunde: ${booking.customerName}${booking.customerPhone ? `\\nTelefon: ${booking.customerPhone}` : ''}${booking.notes ? `\\nNotizen: ${booking.notes}` : ''}
|
DESCRIPTION:${treatmentDetails}\\n\\nKunde: ${booking.customerName}${booking.customerPhone ? `\\nTelefon: ${booking.customerPhone}` : ''}${booking.notes ? `\\nNotizen: ${booking.notes}` : ''}
|
||||||
STATUS:${status}
|
STATUS:${status}
|
||||||
TRANSP:OPAQUE
|
TRANSP:OPAQUE
|
||||||
END:VEVENT
|
END:VEVENT
|
||||||
|
@@ -3,7 +3,7 @@ import { z } from "zod";
|
|||||||
import { randomUUID } from "crypto";
|
import { randomUUID } from "crypto";
|
||||||
import { createKV } from "../lib/create-kv.js";
|
import { createKV } from "../lib/create-kv.js";
|
||||||
import { sendEmail, sendEmailWithAGB, sendEmailWithAGBAndCalendar, sendEmailWithInspirationPhoto } from "../lib/email.js";
|
import { sendEmail, sendEmailWithAGB, sendEmailWithAGBAndCalendar, sendEmailWithInspirationPhoto } from "../lib/email.js";
|
||||||
import { renderBookingPendingHTML, renderBookingConfirmedHTML, renderBookingCancelledHTML, renderAdminBookingNotificationHTML, renderBookingRescheduleProposalHTML, renderAdminRescheduleAcceptedHTML, renderAdminRescheduleDeclinedHTML } from "../lib/email-templates.js";
|
import { renderBookingPendingHTML, renderBookingConfirmedHTML, renderBookingCancelledHTML, renderAdminBookingNotificationHTML, renderBookingRescheduleProposalHTML, renderAdminRescheduleAcceptedHTML, renderAdminRescheduleDeclinedHTML, renderCustomerMessageHTML } from "../lib/email-templates.js";
|
||||||
import { router as rootRouter } from "./index.js";
|
import { router as rootRouter } from "./index.js";
|
||||||
import { createORPCClient } from "@orpc/client";
|
import { createORPCClient } from "@orpc/client";
|
||||||
import { RPCLink } from "@orpc/client/fetch";
|
import { RPCLink } from "@orpc/client/fetch";
|
||||||
@@ -44,7 +44,7 @@ function isDateInTimeOffPeriod(date: string, periods: TimeOffPeriod[]): boolean
|
|||||||
async function validateBookingAgainstRules(
|
async function validateBookingAgainstRules(
|
||||||
date: string,
|
date: string,
|
||||||
time: string,
|
time: string,
|
||||||
treatmentDuration: number
|
totalDuration: number
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Parse date to get day of week
|
// Parse date to get day of week
|
||||||
const [year, month, day] = date.split('-').map(Number);
|
const [year, month, day] = date.split('-').map(Number);
|
||||||
@@ -69,7 +69,7 @@ async function validateBookingAgainstRules(
|
|||||||
|
|
||||||
// Check if booking time falls within any rule's time span
|
// Check if booking time falls within any rule's time span
|
||||||
const bookingStartMinutes = parseTime(time);
|
const bookingStartMinutes = parseTime(time);
|
||||||
const bookingEndMinutes = bookingStartMinutes + treatmentDuration;
|
const bookingEndMinutes = bookingStartMinutes + totalDuration;
|
||||||
|
|
||||||
const isWithinRules = matchingRules.some(rule => {
|
const isWithinRules = matchingRules.some(rule => {
|
||||||
const ruleStartMinutes = parseTime(rule.startTime);
|
const ruleStartMinutes = parseTime(rule.startTime);
|
||||||
@@ -88,7 +88,7 @@ async function validateBookingAgainstRules(
|
|||||||
async function checkBookingConflicts(
|
async function checkBookingConflicts(
|
||||||
date: string,
|
date: string,
|
||||||
time: string,
|
time: string,
|
||||||
treatmentDuration: number,
|
totalDuration: number,
|
||||||
excludeBookingId?: string
|
excludeBookingId?: string
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const allBookings = await kv.getAllItems();
|
const allBookings = await kv.getAllItems();
|
||||||
@@ -99,10 +99,10 @@ async function checkBookingConflicts(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const bookingStartMinutes = parseTime(time);
|
const bookingStartMinutes = parseTime(time);
|
||||||
const bookingEndMinutes = bookingStartMinutes + treatmentDuration;
|
const bookingEndMinutes = bookingStartMinutes + totalDuration;
|
||||||
|
|
||||||
// Cache treatment durations by ID to avoid N+1 lookups
|
// Cache treatment durations by ID to avoid N+1 lookups (for backward compatibility with old bookings)
|
||||||
const uniqueTreatmentIds = [...new Set(dateBookings.map(booking => booking.treatmentId))];
|
const uniqueTreatmentIds = [...new Set(dateBookings.filter(b => b.treatmentId).map(booking => booking.treatmentId!))];
|
||||||
const treatmentDurationMap = new Map<string, number>();
|
const treatmentDurationMap = new Map<string, number>();
|
||||||
|
|
||||||
for (const treatmentId of uniqueTreatmentIds) {
|
for (const treatmentId of uniqueTreatmentIds) {
|
||||||
@@ -112,10 +112,21 @@ async function checkBookingConflicts(
|
|||||||
|
|
||||||
// Check for overlaps with existing bookings
|
// Check for overlaps with existing bookings
|
||||||
for (const existingBooking of dateBookings) {
|
for (const existingBooking of dateBookings) {
|
||||||
// Use cached duration or fallback to bookedDurationMinutes if available
|
let existingDuration: number;
|
||||||
let existingDuration = treatmentDurationMap.get(existingBooking.treatmentId) || 60;
|
|
||||||
if (existingBooking.bookedDurationMinutes) {
|
// Handle both new bookings with treatments array and old bookings with treatmentId
|
||||||
existingDuration = existingBooking.bookedDurationMinutes;
|
if (existingBooking.treatments && existingBooking.treatments.length > 0) {
|
||||||
|
// New format: calculate duration from treatments array
|
||||||
|
existingDuration = existingBooking.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
} else if (existingBooking.treatmentId) {
|
||||||
|
// Old format: use cached duration or fallback to bookedDurationMinutes if available
|
||||||
|
existingDuration = treatmentDurationMap.get(existingBooking.treatmentId) || 60;
|
||||||
|
if (existingBooking.bookedDurationMinutes) {
|
||||||
|
existingDuration = existingBooking.bookedDurationMinutes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fallback for bookings without treatment info
|
||||||
|
existingDuration = existingBooking.bookedDurationMinutes || 60;
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingStartMinutes = parseTime(existingBooking.appointmentTime);
|
const existingStartMinutes = parseTime(existingBooking.appointmentTime);
|
||||||
@@ -128,8 +139,22 @@ async function checkBookingConflicts(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reusable treatments array schema with duplicate validation
|
||||||
|
const TreatmentsArraySchema = z.array(z.object({
|
||||||
|
id: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
duration: z.number().positive(),
|
||||||
|
price: z.number().nonnegative(),
|
||||||
|
}))
|
||||||
|
.min(1, "Mindestens eine Behandlung muss ausgewählt werden")
|
||||||
|
.max(3, "Maximal 3 Behandlungen können ausgewählt werden")
|
||||||
|
.refine(list => {
|
||||||
|
const ids = list.map(t => t.id);
|
||||||
|
return ids.length === new Set(ids).size;
|
||||||
|
}, { message: "Doppelte Behandlungen sind nicht erlaubt" });
|
||||||
|
|
||||||
const CreateBookingInputSchema = z.object({
|
const CreateBookingInputSchema = z.object({
|
||||||
treatmentId: z.string(),
|
treatments: TreatmentsArraySchema,
|
||||||
customerName: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein"),
|
customerName: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein"),
|
||||||
customerEmail: z.string().email("Ungültige E-Mail-Adresse"),
|
customerEmail: z.string().email("Ungültige E-Mail-Adresse"),
|
||||||
customerPhone: z.string().min(5, "Telefonnummer muss mindestens 5 Zeichen lang sein").optional(),
|
customerPhone: z.string().min(5, "Telefonnummer muss mindestens 5 Zeichen lang sein").optional(),
|
||||||
@@ -141,7 +166,12 @@ const CreateBookingInputSchema = z.object({
|
|||||||
|
|
||||||
const BookingSchema = z.object({
|
const BookingSchema = z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
treatmentId: z.string(),
|
treatments: z.array(z.object({
|
||||||
|
id: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
duration: z.number().positive(),
|
||||||
|
price: z.number().nonnegative()
|
||||||
|
})),
|
||||||
customerName: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein"),
|
customerName: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein"),
|
||||||
customerEmail: z.string().email("Ungültige E-Mail-Adresse").optional(),
|
customerEmail: z.string().email("Ungültige E-Mail-Adresse").optional(),
|
||||||
customerPhone: z.string().min(5, "Telefonnummer muss mindestens 5 Zeichen lang sein").optional(),
|
customerPhone: z.string().min(5, "Telefonnummer muss mindestens 5 Zeichen lang sein").optional(),
|
||||||
@@ -150,10 +180,12 @@ const BookingSchema = z.object({
|
|||||||
status: z.enum(["pending", "confirmed", "cancelled", "completed"]),
|
status: z.enum(["pending", "confirmed", "cancelled", "completed"]),
|
||||||
notes: z.string().optional(),
|
notes: z.string().optional(),
|
||||||
inspirationPhoto: z.string().optional(), // Base64 encoded image data
|
inspirationPhoto: z.string().optional(), // Base64 encoded image data
|
||||||
bookedDurationMinutes: z.number().optional(), // Snapshot of treatment duration at booking time
|
|
||||||
createdAt: z.string(),
|
createdAt: z.string(),
|
||||||
// DEPRECATED: slotId is no longer used for validation, kept for backward compatibility
|
// DEPRECATED: slotId is no longer used for validation, kept for backward compatibility
|
||||||
slotId: z.string().optional(),
|
slotId: z.string().optional(),
|
||||||
|
// DEPRECATED: treatmentId and bookedDurationMinutes kept for backward compatibility
|
||||||
|
treatmentId: z.string().optional(),
|
||||||
|
bookedDurationMinutes: z.number().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type Booking = z.output<typeof BookingSchema>;
|
type Booking = z.output<typeof BookingSchema>;
|
||||||
@@ -272,31 +304,46 @@ const create = os
|
|||||||
throw new Error("Du hast bereits eine Buchung für dieses Datum. Bitte wähle einen anderen Tag oder storniere zuerst.");
|
throw new Error("Du hast bereits eine Buchung für dieses Datum. Bitte wähle einen anderen Tag oder storniere zuerst.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Get treatment duration for validation
|
// Validate all treatments exist and snapshot them from KV
|
||||||
const treatment = await treatmentsKV.getItem(input.treatmentId);
|
const snapshottedTreatments = [] as Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
if (!treatment) {
|
for (const inputTreatment of input.treatments) {
|
||||||
throw new Error("Behandlung nicht gefunden.");
|
const treatment = await treatmentsKV.getItem(inputTreatment.id);
|
||||||
|
if (!treatment) {
|
||||||
|
throw new Error(`Behandlung "${inputTreatment.name}" nicht gefunden.`);
|
||||||
|
}
|
||||||
|
// Verify snapshot data matches current treatment data
|
||||||
|
if (treatment.name !== inputTreatment.name || treatment.duration !== inputTreatment.duration || treatment.price !== inputTreatment.price) {
|
||||||
|
throw new Error(`Behandlungsdaten für "${inputTreatment.name}" stimmen nicht überein. Bitte lade die Seite neu.`);
|
||||||
|
}
|
||||||
|
snapshottedTreatments.push({ id: treatment.id, name: treatment.name, duration: treatment.duration, price: treatment.price });
|
||||||
}
|
}
|
||||||
|
const totalDuration = snapshottedTreatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
|
||||||
// Validate booking time against recurring rules
|
// Validate booking time against recurring rules
|
||||||
await validateBookingAgainstRules(
|
await validateBookingAgainstRules(
|
||||||
input.appointmentDate,
|
input.appointmentDate,
|
||||||
input.appointmentTime,
|
input.appointmentTime,
|
||||||
treatment.duration
|
totalDuration
|
||||||
);
|
);
|
||||||
|
|
||||||
// Check for booking conflicts
|
// Check for booking conflicts
|
||||||
await checkBookingConflicts(
|
await checkBookingConflicts(
|
||||||
input.appointmentDate,
|
input.appointmentDate,
|
||||||
input.appointmentTime,
|
input.appointmentTime,
|
||||||
treatment.duration
|
totalDuration
|
||||||
);
|
);
|
||||||
|
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const booking = {
|
const booking = {
|
||||||
id,
|
id,
|
||||||
...input,
|
treatments: snapshottedTreatments,
|
||||||
bookedDurationMinutes: treatment.duration, // Snapshot treatment duration
|
customerName: input.customerName,
|
||||||
|
customerEmail: input.customerEmail,
|
||||||
|
customerPhone: input.customerPhone,
|
||||||
|
appointmentDate: input.appointmentDate,
|
||||||
|
appointmentTime: input.appointmentTime,
|
||||||
|
notes: input.notes,
|
||||||
|
inspirationPhoto: input.inspirationPhoto,
|
||||||
status: "pending" as const,
|
status: "pending" as const,
|
||||||
createdAt: new Date().toISOString()
|
createdAt: new Date().toISOString()
|
||||||
};
|
};
|
||||||
@@ -316,12 +363,18 @@ const create = os
|
|||||||
name: input.customerName,
|
name: input.customerName,
|
||||||
date: input.appointmentDate,
|
date: input.appointmentDate,
|
||||||
time: input.appointmentTime,
|
time: input.appointmentTime,
|
||||||
statusUrl: bookingUrl
|
statusUrl: bookingUrl,
|
||||||
|
treatments: input.treatments
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const treatmentsText = input.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalDuration = input.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = input.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
await sendEmail({
|
await sendEmail({
|
||||||
to: input.customerEmail,
|
to: input.customerEmail,
|
||||||
subject: "Deine Terminanfrage ist eingegangen",
|
subject: "Deine Terminanfrage ist eingegangen",
|
||||||
text: `Hallo ${input.customerName},\n\nwir haben deine Anfrage für ${formattedDate} um ${input.appointmentTime} erhalten. Wir bestätigen deinen Termin in Kürze. Du erhältst eine weitere E-Mail, sobald der Termin bestätigt ist.\n\nTermin-Status ansehen: ${bookingUrl}\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nLiebe Grüße\nStargirlnails Kiel`,
|
text: `Hallo ${input.customerName},\n\nwir haben deine Anfrage für ${formattedDate} um ${input.appointmentTime} erhalten.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n\nWir bestätigen deinen Termin in Kürze. Du erhältst eine weitere E-Mail, sobald der Termin bestätigt ist.\n\nTermin-Status ansehen: ${bookingUrl}\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nLiebe Grüße\nStargirlnails Kiel`,
|
||||||
html,
|
html,
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
})();
|
})();
|
||||||
@@ -330,27 +383,26 @@ const create = os
|
|||||||
void (async () => {
|
void (async () => {
|
||||||
if (!process.env.ADMIN_EMAIL) return;
|
if (!process.env.ADMIN_EMAIL) return;
|
||||||
|
|
||||||
// Get treatment name from KV
|
|
||||||
const allTreatments = await treatmentsKV.getAllItems();
|
|
||||||
const treatment = allTreatments.find(t => t.id === input.treatmentId);
|
|
||||||
const treatmentName = treatment?.name || "Unbekannte Behandlung";
|
|
||||||
|
|
||||||
const adminHtml = await renderAdminBookingNotificationHTML({
|
const adminHtml = await renderAdminBookingNotificationHTML({
|
||||||
name: input.customerName,
|
name: input.customerName,
|
||||||
date: input.appointmentDate,
|
date: input.appointmentDate,
|
||||||
time: input.appointmentTime,
|
time: input.appointmentTime,
|
||||||
treatment: treatmentName,
|
treatments: input.treatments,
|
||||||
phone: input.customerPhone || "Nicht angegeben",
|
phone: input.customerPhone || "Nicht angegeben",
|
||||||
notes: input.notes,
|
notes: input.notes,
|
||||||
hasInspirationPhoto: !!input.inspirationPhoto
|
hasInspirationPhoto: !!input.inspirationPhoto
|
||||||
});
|
});
|
||||||
|
|
||||||
const homepageUrl = generateUrl();
|
const homepageUrl = generateUrl();
|
||||||
|
const treatmentsText = input.treatments.map(t => ` - ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalDuration = input.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = input.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
const adminText = `Neue Buchungsanfrage eingegangen:\n\n` +
|
const adminText = `Neue Buchungsanfrage eingegangen:\n\n` +
|
||||||
`Name: ${input.customerName}\n` +
|
`Name: ${input.customerName}\n` +
|
||||||
`Telefon: ${input.customerPhone || "Nicht angegeben"}\n` +
|
`Telefon: ${input.customerPhone || "Nicht angegeben"}\n` +
|
||||||
`Behandlung: ${treatmentName}\n` +
|
`Behandlungen:\n${treatmentsText}\n` +
|
||||||
|
`Gesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n` +
|
||||||
`Datum: ${formatDateGerman(input.appointmentDate)}\n` +
|
`Datum: ${formatDateGerman(input.appointmentDate)}\n` +
|
||||||
`Uhrzeit: ${input.appointmentTime}\n` +
|
`Uhrzeit: ${input.appointmentTime}\n` +
|
||||||
`${input.notes ? `Notizen: ${input.notes}\n` : ''}` +
|
`${input.notes ? `Notizen: ${input.notes}\n` : ''}` +
|
||||||
@@ -427,40 +479,48 @@ const updateStatus = os
|
|||||||
date: booking.appointmentDate,
|
date: booking.appointmentDate,
|
||||||
time: booking.appointmentTime,
|
time: booking.appointmentTime,
|
||||||
cancellationUrl: bookingUrl, // Now points to booking status page
|
cancellationUrl: bookingUrl, // Now points to booking status page
|
||||||
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`)
|
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`),
|
||||||
|
treatments: booking.treatments
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get treatment information for ICS file
|
const treatmentsText = booking.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
const allTreatments = await treatmentsKV.getAllItems();
|
const totalDuration = booking.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
const treatment = allTreatments.find(t => t.id === booking.treatmentId);
|
const totalPrice = booking.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
const treatmentName = treatment?.name || "Behandlung";
|
|
||||||
// Use bookedDurationMinutes if available, otherwise fallback to treatment duration
|
|
||||||
const treatmentDuration = booking.bookedDurationMinutes || treatment?.duration || 60;
|
|
||||||
|
|
||||||
if (booking.customerEmail) {
|
if (booking.customerEmail) {
|
||||||
await sendEmailWithAGBAndCalendar({
|
await sendEmailWithAGBAndCalendar({
|
||||||
to: booking.customerEmail,
|
to: booking.customerEmail,
|
||||||
subject: "Dein Termin wurde bestätigt - AGB im Anhang",
|
subject: "Dein Termin wurde bestätigt - AGB im Anhang",
|
||||||
text: `Hallo ${booking.customerName},\n\nwir haben deinen Termin am ${formattedDate} um ${booking.appointmentTime} bestätigt.\n\nWichtiger Hinweis: Die Allgemeinen Geschäftsbedingungen (AGB) findest du im Anhang dieser E-Mail. Bitte lies sie vor deinem Termin durch.\n\nTermin-Status ansehen und verwalten: ${bookingUrl}\nFalls du den Termin stornieren möchtest, kannst du das über den obigen Link tun.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nBis bald!\nStargirlnails Kiel`,
|
text: `Hallo ${booking.customerName},\n\nwir haben deinen Termin am ${formattedDate} um ${booking.appointmentTime} bestätigt.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n\nWichtiger Hinweis: Die Allgemeinen Geschäftsbedingungen (AGB) findest du im Anhang dieser E-Mail. Bitte lies sie vor deinem Termin durch.\n\nTermin-Status ansehen und verwalten: ${bookingUrl}\nFalls du den Termin stornieren möchtest, kannst du das über den obigen Link tun.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nBis bald!\nStargirlnails Kiel`,
|
||||||
html,
|
html,
|
||||||
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
||||||
}, {
|
}, {
|
||||||
date: booking.appointmentDate,
|
date: booking.appointmentDate,
|
||||||
time: booking.appointmentTime,
|
time: booking.appointmentTime,
|
||||||
durationMinutes: treatmentDuration,
|
|
||||||
customerName: booking.customerName,
|
customerName: booking.customerName,
|
||||||
treatmentName: treatmentName
|
customerEmail: booking.customerEmail,
|
||||||
|
treatments: booking.treatments
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else if (input.status === "cancelled") {
|
} else if (input.status === "cancelled") {
|
||||||
const formattedDate = formatDateGerman(booking.appointmentDate);
|
const formattedDate = formatDateGerman(booking.appointmentDate);
|
||||||
const homepageUrl = generateUrl();
|
const homepageUrl = generateUrl();
|
||||||
const html = await renderBookingCancelledHTML({ name: booking.customerName, date: booking.appointmentDate, time: booking.appointmentTime });
|
const html = await renderBookingCancelledHTML({
|
||||||
|
name: booking.customerName,
|
||||||
|
date: booking.appointmentDate,
|
||||||
|
time: booking.appointmentTime,
|
||||||
|
treatments: booking.treatments
|
||||||
|
});
|
||||||
|
|
||||||
|
const treatmentsText = booking.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalDuration = booking.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = booking.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
if (booking.customerEmail) {
|
if (booking.customerEmail) {
|
||||||
await sendEmail({
|
await sendEmail({
|
||||||
to: booking.customerEmail,
|
to: booking.customerEmail,
|
||||||
subject: "Dein Termin wurde abgesagt",
|
subject: "Dein Termin wurde abgesagt",
|
||||||
text: `Hallo ${booking.customerName},\n\nleider wurde dein Termin am ${formattedDate} um ${booking.appointmentTime} abgesagt. Bitte buche einen neuen Termin.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nLiebe Grüße\nStargirlnails Kiel`,
|
text: `Hallo ${booking.customerName},\n\nleider wurde dein Termin am ${formattedDate} um ${booking.appointmentTime} abgesagt.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n\nBitte buche einen neuen Termin.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nLiebe Grüße\nStargirlnails Kiel`,
|
||||||
html,
|
html,
|
||||||
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
||||||
});
|
});
|
||||||
@@ -504,11 +564,21 @@ const remove = os
|
|||||||
try {
|
try {
|
||||||
const formattedDate = formatDateGerman(booking.appointmentDate);
|
const formattedDate = formatDateGerman(booking.appointmentDate);
|
||||||
const homepageUrl = generateUrl();
|
const homepageUrl = generateUrl();
|
||||||
const html = await renderBookingCancelledHTML({ name: booking.customerName, date: booking.appointmentDate, time: booking.appointmentTime });
|
const html = await renderBookingCancelledHTML({
|
||||||
|
name: booking.customerName,
|
||||||
|
date: booking.appointmentDate,
|
||||||
|
time: booking.appointmentTime,
|
||||||
|
treatments: booking.treatments
|
||||||
|
});
|
||||||
|
|
||||||
|
const treatmentsText = booking.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalDuration = booking.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = booking.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
await sendEmail({
|
await sendEmail({
|
||||||
to: booking.customerEmail,
|
to: booking.customerEmail,
|
||||||
subject: "Dein Termin wurde abgesagt",
|
subject: "Dein Termin wurde abgesagt",
|
||||||
text: `Hallo ${booking.customerName},\n\nleider wurde dein Termin am ${formattedDate} um ${booking.appointmentTime} abgesagt. Bitte buche einen neuen Termin.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nLiebe Grüße\nStargirlnails Kiel`,
|
text: `Hallo ${booking.customerName},\n\nleider wurde dein Termin am ${formattedDate} um ${booking.appointmentTime} abgesagt.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n\nBitte buche einen neuen Termin.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nLiebe Grüße\nStargirlnails Kiel`,
|
||||||
html,
|
html,
|
||||||
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
||||||
});
|
});
|
||||||
@@ -524,7 +594,7 @@ const remove = os
|
|||||||
const createManual = os
|
const createManual = os
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
sessionId: z.string(),
|
sessionId: z.string(),
|
||||||
treatmentId: z.string(),
|
treatments: TreatmentsArraySchema,
|
||||||
customerName: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein"),
|
customerName: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein"),
|
||||||
customerEmail: z.string().email("Ungültige E-Mail-Adresse").optional(),
|
customerEmail: z.string().email("Ungültige E-Mail-Adresse").optional(),
|
||||||
customerPhone: z.string().min(5, "Telefonnummer muss mindestens 5 Zeichen lang sein").optional(),
|
customerPhone: z.string().min(5, "Telefonnummer muss mindestens 5 Zeichen lang sein").optional(),
|
||||||
@@ -557,37 +627,45 @@ const createManual = os
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get treatment duration for validation
|
// Validate all treatments exist and snapshot them from KV
|
||||||
const treatment = await treatmentsKV.getItem(input.treatmentId);
|
const snapshottedTreatments = [] as Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
if (!treatment) {
|
for (const inputTreatment of input.treatments) {
|
||||||
throw new Error("Behandlung nicht gefunden.");
|
const treatment = await treatmentsKV.getItem(inputTreatment.id);
|
||||||
|
if (!treatment) {
|
||||||
|
throw new Error(`Behandlung "${inputTreatment.name}" nicht gefunden.`);
|
||||||
|
}
|
||||||
|
// Verify snapshot data matches current treatment data
|
||||||
|
if (treatment.name !== inputTreatment.name || treatment.duration !== inputTreatment.duration || treatment.price !== inputTreatment.price) {
|
||||||
|
throw new Error(`Behandlungsdaten für "${inputTreatment.name}" stimmen nicht überein. Bitte lade die Seite neu.`);
|
||||||
|
}
|
||||||
|
snapshottedTreatments.push({ id: treatment.id, name: treatment.name, duration: treatment.duration, price: treatment.price });
|
||||||
}
|
}
|
||||||
|
const totalDuration = snapshottedTreatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
|
||||||
// Validate booking time against recurring rules
|
// Validate booking time against recurring rules
|
||||||
await validateBookingAgainstRules(
|
await validateBookingAgainstRules(
|
||||||
input.appointmentDate,
|
input.appointmentDate,
|
||||||
input.appointmentTime,
|
input.appointmentTime,
|
||||||
treatment.duration
|
totalDuration
|
||||||
);
|
);
|
||||||
|
|
||||||
// Check for booking conflicts
|
// Check for booking conflicts
|
||||||
await checkBookingConflicts(
|
await checkBookingConflicts(
|
||||||
input.appointmentDate,
|
input.appointmentDate,
|
||||||
input.appointmentTime,
|
input.appointmentTime,
|
||||||
treatment.duration
|
totalDuration
|
||||||
);
|
);
|
||||||
|
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const booking = {
|
const booking = {
|
||||||
id,
|
id,
|
||||||
treatmentId: input.treatmentId,
|
treatments: snapshottedTreatments,
|
||||||
customerName: input.customerName,
|
customerName: input.customerName,
|
||||||
customerEmail: input.customerEmail,
|
customerEmail: input.customerEmail,
|
||||||
customerPhone: input.customerPhone,
|
customerPhone: input.customerPhone,
|
||||||
appointmentDate: input.appointmentDate,
|
appointmentDate: input.appointmentDate,
|
||||||
appointmentTime: input.appointmentTime,
|
appointmentTime: input.appointmentTime,
|
||||||
notes: input.notes,
|
notes: input.notes,
|
||||||
bookedDurationMinutes: treatment.duration,
|
|
||||||
status: "confirmed" as const,
|
status: "confirmed" as const,
|
||||||
createdAt: new Date().toISOString()
|
createdAt: new Date().toISOString()
|
||||||
} as Booking;
|
} as Booking;
|
||||||
@@ -611,20 +689,24 @@ const createManual = os
|
|||||||
date: input.appointmentDate,
|
date: input.appointmentDate,
|
||||||
time: input.appointmentTime,
|
time: input.appointmentTime,
|
||||||
cancellationUrl: bookingUrl,
|
cancellationUrl: bookingUrl,
|
||||||
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`)
|
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`),
|
||||||
|
treatments: input.treatments
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const treatmentsText = input.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalPrice = input.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
await sendEmailWithAGBAndCalendar({
|
await sendEmailWithAGBAndCalendar({
|
||||||
to: input.customerEmail!,
|
to: input.customerEmail!,
|
||||||
subject: "Dein Termin wurde bestätigt - AGB im Anhang",
|
subject: "Dein Termin wurde bestätigt - AGB im Anhang",
|
||||||
text: `Hallo ${input.customerName},\n\nwir haben deinen Termin am ${formattedDate} um ${input.appointmentTime} bestätigt.\n\nWichtiger Hinweis: Die Allgemeinen Geschäftsbedingungen (AGB) findest du im Anhang dieser E-Mail. Bitte lies sie vor deinem Termin durch.\n\nTermin-Status ansehen und verwalten: ${bookingUrl}\nFalls du den Termin stornieren möchtest, kannst du das über den obigen Link tun.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nBis bald!\nStargirlnails Kiel`,
|
text: `Hallo ${input.customerName},\n\nwir haben deinen Termin am ${formattedDate} um ${input.appointmentTime} bestätigt.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n\nWichtiger Hinweis: Die Allgemeinen Geschäftsbedingungen (AGB) findest du im Anhang dieser E-Mail. Bitte lies sie vor deinem Termin durch.\n\nTermin-Status ansehen und verwalten: ${bookingUrl}\nFalls du den Termin stornieren möchtest, kannst du das über den obigen Link tun.\n\nRechtliche Informationen: ${generateUrl('/legal')}\nZur Website: ${homepageUrl}\n\nBis bald!\nStargirlnails Kiel`,
|
||||||
html,
|
html,
|
||||||
}, {
|
}, {
|
||||||
date: input.appointmentDate,
|
date: input.appointmentDate,
|
||||||
time: input.appointmentTime,
|
time: input.appointmentTime,
|
||||||
durationMinutes: treatment.duration,
|
|
||||||
customerName: input.customerName,
|
customerName: input.customerName,
|
||||||
treatmentName: treatment.name
|
customerEmail: input.customerEmail,
|
||||||
|
treatments: input.treatments
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Email send failed for manual booking:", e);
|
console.error("Email send failed for manual booking:", e);
|
||||||
@@ -695,8 +777,10 @@ export const router = {
|
|||||||
if (!booking) throw new Error("Booking not found");
|
if (!booking) throw new Error("Booking not found");
|
||||||
if (booking.status !== "confirmed") throw new Error("Nur bestätigte Termine können umgebucht werden.");
|
if (booking.status !== "confirmed") throw new Error("Nur bestätigte Termine können umgebucht werden.");
|
||||||
|
|
||||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
// Calculate total duration from treatments array
|
||||||
if (!treatment) throw new Error("Behandlung nicht gefunden.");
|
const totalDuration = booking.treatments && booking.treatments.length > 0
|
||||||
|
? booking.treatments.reduce((sum, t) => sum + t.duration, 0)
|
||||||
|
: (booking.bookedDurationMinutes || 60);
|
||||||
|
|
||||||
// Validate grid and not in past
|
// Validate grid and not in past
|
||||||
const appointmentMinutes = parseTime(input.proposedTime);
|
const appointmentMinutes = parseTime(input.proposedTime);
|
||||||
@@ -715,8 +799,8 @@ export const router = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await validateBookingAgainstRules(input.proposedDate, input.proposedTime, booking.bookedDurationMinutes || treatment.duration);
|
await validateBookingAgainstRules(input.proposedDate, input.proposedTime, totalDuration);
|
||||||
await checkBookingConflicts(input.proposedDate, input.proposedTime, booking.bookedDurationMinutes || treatment.duration, booking.id);
|
await checkBookingConflicts(input.proposedDate, input.proposedTime, totalDuration, booking.id);
|
||||||
|
|
||||||
// Invalidate and create new reschedule token via cancellation router
|
// Invalidate and create new reschedule token via cancellation router
|
||||||
const res = await queryClient.cancellation.createRescheduleToken({
|
const res = await queryClient.cancellation.createRescheduleToken({
|
||||||
@@ -729,13 +813,16 @@ export const router = {
|
|||||||
|
|
||||||
// Send proposal email to customer
|
// Send proposal email to customer
|
||||||
if (booking.customerEmail) {
|
if (booking.customerEmail) {
|
||||||
|
const treatmentName = booking.treatments && booking.treatments.length > 0
|
||||||
|
? booking.treatments.map(t => t.name).join(', ')
|
||||||
|
: "Behandlung";
|
||||||
const html = await renderBookingRescheduleProposalHTML({
|
const html = await renderBookingRescheduleProposalHTML({
|
||||||
name: booking.customerName,
|
name: booking.customerName,
|
||||||
originalDate: booking.appointmentDate,
|
originalDate: booking.appointmentDate,
|
||||||
originalTime: booking.appointmentTime,
|
originalTime: booking.appointmentTime,
|
||||||
proposedDate: input.proposedDate,
|
proposedDate: input.proposedDate,
|
||||||
proposedTime: input.proposedTime,
|
proposedTime: input.proposedTime,
|
||||||
treatmentName: (await treatmentsKV.getItem(booking.treatmentId))?.name || "Behandlung",
|
treatmentName: treatmentName,
|
||||||
acceptUrl,
|
acceptUrl,
|
||||||
declineUrl,
|
declineUrl,
|
||||||
expiresAt: res.expiresAt,
|
expiresAt: res.expiresAt,
|
||||||
@@ -761,8 +848,9 @@ export const router = {
|
|||||||
if (!booking) throw new Error("Booking not found");
|
if (!booking) throw new Error("Booking not found");
|
||||||
if (booking.status !== "confirmed") throw new Error("Buchung ist nicht mehr in bestätigtem Zustand.");
|
if (booking.status !== "confirmed") throw new Error("Buchung ist nicht mehr in bestätigtem Zustand.");
|
||||||
|
|
||||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
const duration = booking.treatments && booking.treatments.length > 0
|
||||||
const duration = booking.bookedDurationMinutes || treatment?.duration || 60;
|
? booking.treatments.reduce((sum, t) => sum + t.duration, 0)
|
||||||
|
: (booking.bookedDurationMinutes || 60);
|
||||||
|
|
||||||
// Re-validate slot to ensure still available
|
// Re-validate slot to ensure still available
|
||||||
await validateBookingAgainstRules(proposal.proposed.date, proposal.proposed.time, duration);
|
await validateBookingAgainstRules(proposal.proposed.date, proposal.proposed.time, duration);
|
||||||
@@ -783,29 +871,37 @@ export const router = {
|
|||||||
time: updated.appointmentTime,
|
time: updated.appointmentTime,
|
||||||
cancellationUrl: generateUrl(`/booking/${bookingAccessToken.token}`),
|
cancellationUrl: generateUrl(`/booking/${bookingAccessToken.token}`),
|
||||||
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`),
|
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`),
|
||||||
|
treatments: updated.treatments,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const treatmentsText = updated.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalPrice = updated.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
await sendEmailWithAGBAndCalendar({
|
await sendEmailWithAGBAndCalendar({
|
||||||
to: updated.customerEmail,
|
to: updated.customerEmail,
|
||||||
subject: "Terminänderung bestätigt",
|
subject: "Terminänderung bestätigt",
|
||||||
text: `Hallo ${updated.customerName}, dein neuer Termin ist am ${formatDateGerman(updated.appointmentDate)} um ${updated.appointmentTime}.`,
|
text: `Hallo ${updated.customerName}, dein neuer Termin ist am ${formatDateGerman(updated.appointmentDate)} um ${updated.appointmentTime}.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${duration} Min, ${totalPrice.toFixed(2)} €`,
|
||||||
html,
|
html,
|
||||||
}, {
|
}, {
|
||||||
date: updated.appointmentDate,
|
date: updated.appointmentDate,
|
||||||
time: updated.appointmentTime,
|
time: updated.appointmentTime,
|
||||||
durationMinutes: duration,
|
|
||||||
customerName: updated.customerName,
|
customerName: updated.customerName,
|
||||||
treatmentName: (await treatmentsKV.getItem(updated.treatmentId))?.name || "Behandlung",
|
customerEmail: updated.customerEmail,
|
||||||
|
treatments: updated.treatments,
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.ADMIN_EMAIL) {
|
if (process.env.ADMIN_EMAIL) {
|
||||||
|
const treatmentName = updated.treatments && updated.treatments.length > 0
|
||||||
|
? updated.treatments.map(t => t.name).join(', ')
|
||||||
|
: "Behandlung";
|
||||||
const adminHtml = await renderAdminRescheduleAcceptedHTML({
|
const adminHtml = await renderAdminRescheduleAcceptedHTML({
|
||||||
customerName: updated.customerName,
|
customerName: updated.customerName,
|
||||||
originalDate: proposal.original.date,
|
originalDate: proposal.original.date,
|
||||||
originalTime: proposal.original.time,
|
originalTime: proposal.original.time,
|
||||||
newDate: updated.appointmentDate,
|
newDate: updated.appointmentDate,
|
||||||
newTime: updated.appointmentTime,
|
newTime: updated.appointmentTime,
|
||||||
treatmentName: (await treatmentsKV.getItem(updated.treatmentId))?.name || "Behandlung",
|
treatmentName: treatmentName,
|
||||||
});
|
});
|
||||||
await sendEmail({
|
await sendEmail({
|
||||||
to: process.env.ADMIN_EMAIL,
|
to: process.env.ADMIN_EMAIL,
|
||||||
@@ -832,23 +928,38 @@ export const router = {
|
|||||||
// Notify customer that original stays
|
// Notify customer that original stays
|
||||||
if (booking.customerEmail) {
|
if (booking.customerEmail) {
|
||||||
const bookingAccessToken = await queryClient.cancellation.createToken({ bookingId: booking.id });
|
const bookingAccessToken = await queryClient.cancellation.createToken({ bookingId: booking.id });
|
||||||
|
|
||||||
|
const treatmentsText = booking.treatments.map(t => `- ${t.name} (${t.duration} Min, ${(t.price / 100).toFixed(2)} €)`).join('\n');
|
||||||
|
const totalDuration = booking.treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
const totalPrice = booking.treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
|
||||||
await sendEmail({
|
await sendEmail({
|
||||||
to: booking.customerEmail,
|
to: booking.customerEmail,
|
||||||
subject: "Terminänderung abgelehnt",
|
subject: "Terminänderung abgelehnt",
|
||||||
text: `Du hast den Vorschlag zur Terminänderung abgelehnt. Dein ursprünglicher Termin am ${formatDateGerman(booking.appointmentDate)} um ${booking.appointmentTime} bleibt bestehen.`,
|
text: `Du hast den Vorschlag zur Terminänderung abgelehnt. Dein ursprünglicher Termin am ${formatDateGerman(booking.appointmentDate)} um ${booking.appointmentTime} bleibt bestehen.\n\nBehandlungen:\n${treatmentsText}\n\nGesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €`,
|
||||||
html: await renderBookingConfirmedHTML({ name: booking.customerName, date: booking.appointmentDate, time: booking.appointmentTime, cancellationUrl: generateUrl(`/booking/${bookingAccessToken.token}`), reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`) }),
|
html: await renderBookingConfirmedHTML({
|
||||||
|
name: booking.customerName,
|
||||||
|
date: booking.appointmentDate,
|
||||||
|
time: booking.appointmentTime,
|
||||||
|
cancellationUrl: generateUrl(`/booking/${bookingAccessToken.token}`),
|
||||||
|
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`),
|
||||||
|
treatments: booking.treatments
|
||||||
|
}),
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify admin
|
// Notify admin
|
||||||
if (process.env.ADMIN_EMAIL) {
|
if (process.env.ADMIN_EMAIL) {
|
||||||
|
const treatmentName = booking.treatments && booking.treatments.length > 0
|
||||||
|
? booking.treatments.map(t => t.name).join(', ')
|
||||||
|
: "Behandlung";
|
||||||
const html = await renderAdminRescheduleDeclinedHTML({
|
const html = await renderAdminRescheduleDeclinedHTML({
|
||||||
customerName: booking.customerName,
|
customerName: booking.customerName,
|
||||||
originalDate: proposal.original.date,
|
originalDate: proposal.original.date,
|
||||||
originalTime: proposal.original.time,
|
originalTime: proposal.original.time,
|
||||||
proposedDate: proposal.proposed.date!,
|
proposedDate: proposal.proposed.date!,
|
||||||
proposedTime: proposal.proposed.time!,
|
proposedTime: proposal.proposed.time!,
|
||||||
treatmentName: (await treatmentsKV.getItem(booking.treatmentId))?.name || "Behandlung",
|
treatmentName: treatmentName,
|
||||||
customerEmail: booking.customerEmail,
|
customerEmail: booking.customerEmail,
|
||||||
customerPhone: booking.customerPhone,
|
customerPhone: booking.customerPhone,
|
||||||
});
|
});
|
||||||
@@ -911,4 +1022,75 @@ export const router = {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
// Admin sendet Nachricht an Kunden
|
||||||
|
sendCustomerMessage: os
|
||||||
|
.input(z.object({
|
||||||
|
sessionId: z.string(),
|
||||||
|
bookingId: z.string(),
|
||||||
|
message: z.string().min(1, "Nachricht darf nicht leer sein").max(5000, "Nachricht ist zu lang (max. 5000 Zeichen)"),
|
||||||
|
}))
|
||||||
|
.handler(async ({ input }) => {
|
||||||
|
await assertOwner(input.sessionId);
|
||||||
|
|
||||||
|
const booking = await kv.getItem(input.bookingId);
|
||||||
|
if (!booking) throw new Error("Buchung nicht gefunden");
|
||||||
|
|
||||||
|
// Check if booking has customer email
|
||||||
|
if (!booking.customerEmail) {
|
||||||
|
throw new Error("Diese Buchung hat keine E-Mail-Adresse. Bitte kontaktiere den Kunden telefonisch.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if booking is in the future
|
||||||
|
const today = new Date().toISOString().split("T")[0];
|
||||||
|
const bookingDate = booking.appointmentDate;
|
||||||
|
if (bookingDate < today) {
|
||||||
|
throw new Error("Nachrichten können nur für zukünftige Termine gesendet werden.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get treatment name for context
|
||||||
|
const treatmentName = booking.treatments && booking.treatments.length > 0
|
||||||
|
? booking.treatments.map(t => t.name).join(', ')
|
||||||
|
: "Behandlung";
|
||||||
|
|
||||||
|
// Prepare email with Reply-To header
|
||||||
|
const ownerName = process.env.OWNER_NAME || "Stargirlnails Kiel";
|
||||||
|
const emailFrom = process.env.EMAIL_FROM || "Stargirlnails <no-reply@stargirlnails.de>";
|
||||||
|
const replyToEmail = process.env.ADMIN_EMAIL;
|
||||||
|
|
||||||
|
const formattedDate = formatDateGerman(bookingDate);
|
||||||
|
|
||||||
|
const html = await renderCustomerMessageHTML({
|
||||||
|
customerName: booking.customerName,
|
||||||
|
message: input.message,
|
||||||
|
appointmentDate: bookingDate,
|
||||||
|
appointmentTime: booking.appointmentTime,
|
||||||
|
treatmentName: treatmentName,
|
||||||
|
});
|
||||||
|
|
||||||
|
const textContent = `Hallo ${booking.customerName},\n\nZu deinem Termin:\nBehandlung: ${treatmentName}\nDatum: ${formattedDate}\nUhrzeit: ${booking.appointmentTime}\n\nNachricht von ${ownerName}:\n${input.message}\n\nBei Fragen oder Anliegen kannst du einfach auf diese E-Mail antworten – wir helfen dir gerne weiter!\n\nLiebe Grüße,\n${ownerName}`;
|
||||||
|
|
||||||
|
// Send email with BCC to admin for monitoring
|
||||||
|
// Note: Not using explicit 'from' or 'replyTo' to match behavior of other system emails
|
||||||
|
console.log(`Sending customer message to ${booking.customerEmail} for booking ${input.bookingId}`);
|
||||||
|
console.log(`Email config: from=${emailFrom}, replyTo=${replyToEmail}, bcc=${replyToEmail}`);
|
||||||
|
const emailResult = await sendEmail({
|
||||||
|
to: booking.customerEmail,
|
||||||
|
subject: `Nachricht zu deinem Termin am ${formattedDate}`,
|
||||||
|
text: textContent,
|
||||||
|
html: html,
|
||||||
|
bcc: replyToEmail ? [replyToEmail] : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!emailResult.success) {
|
||||||
|
console.error(`Failed to send customer message to ${booking.customerEmail}`);
|
||||||
|
throw new Error("E-Mail konnte nicht versendet werden. Bitte überprüfe die E-Mail-Konfiguration oder versuche es später erneut.");
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Successfully sent customer message to ${booking.customerEmail}`);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `Nachricht wurde erfolgreich an ${booking.customerEmail} gesendet.`
|
||||||
|
};
|
||||||
|
}),
|
||||||
};
|
};
|
@@ -28,7 +28,15 @@ const cancellationKV = createKV<BookingAccessToken>("cancellation_tokens");
|
|||||||
// Types for booking and availability
|
// Types for booking and availability
|
||||||
type Booking = {
|
type Booking = {
|
||||||
id: string;
|
id: string;
|
||||||
treatmentId: string;
|
treatments: Array<{
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
duration: number;
|
||||||
|
price: number;
|
||||||
|
}>;
|
||||||
|
// Deprecated fields for backward compatibility
|
||||||
|
treatmentId?: string;
|
||||||
|
bookedDurationMinutes?: number;
|
||||||
customerName: string;
|
customerName: string;
|
||||||
customerEmail?: string;
|
customerEmail?: string;
|
||||||
customerPhone?: string;
|
customerPhone?: string;
|
||||||
@@ -120,9 +128,42 @@ const getBookingByToken = os
|
|||||||
throw new Error("Booking not found");
|
throw new Error("Booking not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get treatment details
|
// Handle treatments array
|
||||||
const treatmentsKV = createKV<any>("treatments");
|
let treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
let totalDuration: number;
|
||||||
|
let totalPrice: number;
|
||||||
|
|
||||||
|
if (booking.treatments && booking.treatments.length > 0) {
|
||||||
|
// New bookings with treatments array
|
||||||
|
treatments = booking.treatments;
|
||||||
|
totalDuration = treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
totalPrice = treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
} else if (booking.treatmentId) {
|
||||||
|
// Old bookings with single treatmentId (backward compatibility)
|
||||||
|
const treatmentsKV = createKV<any>("treatments");
|
||||||
|
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
||||||
|
|
||||||
|
if (treatment) {
|
||||||
|
treatments = [{
|
||||||
|
id: treatment.id,
|
||||||
|
name: treatment.name,
|
||||||
|
duration: treatment.duration,
|
||||||
|
price: treatment.price,
|
||||||
|
}];
|
||||||
|
totalDuration = treatment.duration;
|
||||||
|
totalPrice = treatment.price / 100;
|
||||||
|
} else {
|
||||||
|
// Fallback if treatment not found
|
||||||
|
treatments = [];
|
||||||
|
totalDuration = booking.bookedDurationMinutes || 60;
|
||||||
|
totalPrice = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Edge case: no treatments and no treatmentId
|
||||||
|
treatments = [];
|
||||||
|
totalDuration = 0;
|
||||||
|
totalPrice = 0;
|
||||||
|
}
|
||||||
|
|
||||||
// Calculate if cancellation is still possible
|
// Calculate if cancellation is still possible
|
||||||
const minStornoTimespan = parseInt(process.env.MIN_STORNO_TIMESPAN || "24");
|
const minStornoTimespan = parseInt(process.env.MIN_STORNO_TIMESPAN || "24");
|
||||||
@@ -140,10 +181,9 @@ const getBookingByToken = os
|
|||||||
customerPhone: booking.customerPhone,
|
customerPhone: booking.customerPhone,
|
||||||
appointmentDate: booking.appointmentDate,
|
appointmentDate: booking.appointmentDate,
|
||||||
appointmentTime: booking.appointmentTime,
|
appointmentTime: booking.appointmentTime,
|
||||||
treatmentId: booking.treatmentId,
|
treatments,
|
||||||
treatmentName: treatment?.name || "Unbekannte Behandlung",
|
totalDuration,
|
||||||
treatmentDuration: treatment?.duration || 60,
|
totalPrice,
|
||||||
treatmentPrice: treatment?.price || 0,
|
|
||||||
status: booking.status,
|
status: booking.status,
|
||||||
notes: booking.notes,
|
notes: booking.notes,
|
||||||
formattedDate: formatDateGerman(booking.appointmentDate),
|
formattedDate: formatDateGerman(booking.appointmentDate),
|
||||||
@@ -284,8 +324,42 @@ export const router = {
|
|||||||
throw new Error("Booking not found");
|
throw new Error("Booking not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const treatmentsKV = createKV<any>("treatments");
|
// Handle treatments array
|
||||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
let treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||||
|
let totalDuration: number;
|
||||||
|
let totalPrice: number;
|
||||||
|
|
||||||
|
if (booking.treatments && booking.treatments.length > 0) {
|
||||||
|
// New bookings with treatments array
|
||||||
|
treatments = booking.treatments;
|
||||||
|
totalDuration = treatments.reduce((sum, t) => sum + t.duration, 0);
|
||||||
|
totalPrice = treatments.reduce((sum, t) => sum + (t.price / 100), 0);
|
||||||
|
} else if (booking.treatmentId) {
|
||||||
|
// Old bookings with single treatmentId (backward compatibility)
|
||||||
|
const treatmentsKV = createKV<any>("treatments");
|
||||||
|
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
||||||
|
|
||||||
|
if (treatment) {
|
||||||
|
treatments = [{
|
||||||
|
id: treatment.id,
|
||||||
|
name: treatment.name,
|
||||||
|
duration: treatment.duration,
|
||||||
|
price: treatment.price,
|
||||||
|
}];
|
||||||
|
totalDuration = treatment.duration;
|
||||||
|
totalPrice = treatment.price / 100;
|
||||||
|
} else {
|
||||||
|
// Fallback if treatment not found
|
||||||
|
treatments = [];
|
||||||
|
totalDuration = booking.bookedDurationMinutes || 60;
|
||||||
|
totalPrice = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Edge case: no treatments and no treatmentId
|
||||||
|
treatments = [];
|
||||||
|
totalDuration = 0;
|
||||||
|
totalPrice = 0;
|
||||||
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const isExpired = new Date(proposal.expiresAt) <= now;
|
const isExpired = new Date(proposal.expiresAt) <= now;
|
||||||
@@ -298,8 +372,9 @@ export const router = {
|
|||||||
customerEmail: booking.customerEmail,
|
customerEmail: booking.customerEmail,
|
||||||
customerPhone: booking.customerPhone,
|
customerPhone: booking.customerPhone,
|
||||||
status: booking.status,
|
status: booking.status,
|
||||||
treatmentId: booking.treatmentId,
|
treatments,
|
||||||
treatmentName: treatment?.name || "Unbekannte Behandlung",
|
totalDuration,
|
||||||
|
totalPrice,
|
||||||
},
|
},
|
||||||
original: {
|
original: {
|
||||||
date: proposal.originalDate || booking.appointmentDate,
|
date: proposal.originalDate || booking.appointmentDate,
|
||||||
@@ -358,14 +433,22 @@ export const router = {
|
|||||||
const booking = await bookingsKV.getItem(proposal.bookingId);
|
const booking = await bookingsKV.getItem(proposal.bookingId);
|
||||||
if (booking) {
|
if (booking) {
|
||||||
const treatmentsKV = createKV<any>("treatments");
|
const treatmentsKV = createKV<any>("treatments");
|
||||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
// Get treatment name(s) from new treatments array or fallback to deprecated treatmentId
|
||||||
|
let treatmentName = "Unbekannte Behandlung";
|
||||||
|
if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
|
||||||
|
treatmentName = booking.treatments.map((t: any) => t.name).join(", ");
|
||||||
|
} else if (booking.treatmentId) {
|
||||||
|
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
||||||
|
treatmentName = treatment?.name || "Unbekannte Behandlung";
|
||||||
|
}
|
||||||
|
|
||||||
expiredDetails.push({
|
expiredDetails.push({
|
||||||
customerName: booking.customerName,
|
customerName: booking.customerName,
|
||||||
originalDate: proposal.originalDate || booking.appointmentDate,
|
originalDate: proposal.originalDate || booking.appointmentDate,
|
||||||
originalTime: proposal.originalTime || booking.appointmentTime,
|
originalTime: proposal.originalTime || booking.appointmentTime,
|
||||||
proposedDate: proposal.proposedDate!,
|
proposedDate: proposal.proposedDate!,
|
||||||
proposedTime: proposal.proposedTime!,
|
proposedTime: proposal.proposedTime!,
|
||||||
treatmentName: treatment?.name || "Unbekannte Behandlung",
|
treatmentName: treatmentName,
|
||||||
customerEmail: booking.customerEmail,
|
customerEmail: booking.customerEmail,
|
||||||
customerPhone: booking.customerPhone,
|
customerPhone: booking.customerPhone,
|
||||||
expiredAt: proposal.expiresAt,
|
expiredAt: proposal.expiresAt,
|
||||||
|
@@ -272,7 +272,12 @@ const getAvailableTimes = os
|
|||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
treatmentId: z.string(),
|
treatmentIds: z.array(z.string())
|
||||||
|
.min(1, "Mindestens eine Behandlung muss ausgewählt werden")
|
||||||
|
.max(3, "Maximal 3 Behandlungen können ausgewählt werden")
|
||||||
|
.refine(list => {
|
||||||
|
return list.length === new Set(list).size;
|
||||||
|
}, { message: "Doppelte Behandlungen sind nicht erlaubt" }),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.handler(async ({ input }) => {
|
.handler(async ({ input }) => {
|
||||||
@@ -287,13 +292,22 @@ const getAvailableTimes = os
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get treatment duration
|
// Get multiple treatments and calculate total duration
|
||||||
const treatment = await treatmentsKV.getItem(input.treatmentId);
|
const treatments = await Promise.all(
|
||||||
if (!treatment) {
|
input.treatmentIds.map(id => treatmentsKV.getItem(id))
|
||||||
throw new Error("Behandlung nicht gefunden.");
|
);
|
||||||
|
|
||||||
|
// Validate that all treatments exist
|
||||||
|
const missingTreatments = treatments
|
||||||
|
.map((t, i) => t ? null : input.treatmentIds[i])
|
||||||
|
.filter(id => id !== null);
|
||||||
|
|
||||||
|
if (missingTreatments.length > 0) {
|
||||||
|
throw new Error(`Behandlung(en) nicht gefunden: ${missingTreatments.join(', ')}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const treatmentDuration = treatment.duration;
|
// Calculate total duration by summing all treatment durations
|
||||||
|
const treatmentDuration = treatments.reduce((sum, t) => sum + (t?.duration || 0), 0);
|
||||||
|
|
||||||
// Parse the date to get day of week
|
// Parse the date to get day of week
|
||||||
const [year, month, day] = input.date.split('-').map(Number);
|
const [year, month, day] = input.date.split('-').map(Number);
|
||||||
@@ -344,36 +358,38 @@ const getAvailableTimes = os
|
|||||||
['pending', 'confirmed', 'completed'].includes(booking.status)
|
['pending', 'confirmed', 'completed'].includes(booking.status)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Optimize treatment duration lookup with Map caching
|
// Build cache only for legacy treatmentId bookings
|
||||||
const uniqueTreatmentIds = [...new Set(dateBookings.map(booking => booking.treatmentId))];
|
const legacyTreatmentIds = [...new Set(dateBookings.filter(b => b.treatmentId).map(b => b.treatmentId as string))];
|
||||||
const treatmentDurationMap = new Map<string, number>();
|
const treatmentDurationMap = new Map<string, number>();
|
||||||
|
|
||||||
for (const treatmentId of uniqueTreatmentIds) {
|
// Only build cache if there are legacy bookings
|
||||||
const treatment = await treatmentsKV.getItem(treatmentId);
|
if (legacyTreatmentIds.length > 0) {
|
||||||
treatmentDurationMap.set(treatmentId, treatment?.duration || 60);
|
for (const id of legacyTreatmentIds) {
|
||||||
}
|
const t = await treatmentsKV.getItem(id);
|
||||||
|
treatmentDurationMap.set(id, t?.duration || 60);
|
||||||
// Get treatment durations for all bookings using the cached map
|
}
|
||||||
const bookingTreatments = new Map();
|
|
||||||
for (const booking of dateBookings) {
|
|
||||||
// Use bookedDurationMinutes if available, otherwise fallback to treatment duration
|
|
||||||
const duration = booking.bookedDurationMinutes || treatmentDurationMap.get(booking.treatmentId) || 60;
|
|
||||||
bookingTreatments.set(booking.id, duration);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter out booking conflicts
|
// Filter out booking conflicts
|
||||||
const availableTimesFiltered = availableTimes.filter(slotTime => {
|
const availableTimesFiltered = availableTimes.filter(slotTime => {
|
||||||
const slotStartMinutes = parseTime(slotTime);
|
const slotStartMinutes = parseTime(slotTime);
|
||||||
const slotEndMinutes = slotStartMinutes + treatmentDuration;
|
const slotEndMinutes = slotStartMinutes + treatmentDuration; // total from selected treatments
|
||||||
|
|
||||||
// Check if this slot overlaps with any existing booking
|
|
||||||
const hasConflict = dateBookings.some(booking => {
|
const hasConflict = dateBookings.some(booking => {
|
||||||
const bookingStartMinutes = parseTime(booking.appointmentTime);
|
let bookingDuration: number;
|
||||||
const bookingDuration = bookingTreatments.get(booking.id) || 60;
|
if (booking.treatments && booking.treatments.length > 0) {
|
||||||
const bookingEndMinutes = bookingStartMinutes + bookingDuration;
|
bookingDuration = booking.treatments.reduce((sum: number, t: { duration: number }) => sum + t.duration, 0);
|
||||||
|
} else if (booking.bookedDurationMinutes) {
|
||||||
|
bookingDuration = booking.bookedDurationMinutes;
|
||||||
|
} else if (booking.treatmentId) {
|
||||||
|
bookingDuration = treatmentDurationMap.get(booking.treatmentId) || 60;
|
||||||
|
} else {
|
||||||
|
bookingDuration = 60;
|
||||||
|
}
|
||||||
|
|
||||||
// Check overlap: slotStart < bookingEnd && slotEnd > bookingStart
|
const bookingStart = parseTime(booking.appointmentTime);
|
||||||
return slotStartMinutes < bookingEndMinutes && slotEndMinutes > bookingStartMinutes;
|
const bookingEnd = bookingStart + bookingDuration;
|
||||||
|
return slotStartMinutes < bookingEnd && slotEndMinutes > bookingStart;
|
||||||
});
|
});
|
||||||
|
|
||||||
return !hasConflict;
|
return !hasConflict;
|
||||||
|
Reference in New Issue
Block a user