Compare commits
3 Commits
v0.1.4
...
ccba9d443b
Author | SHA1 | Date | |
---|---|---|---|
ccba9d443b | |||
9583148e02 | |||
d153aad8b3 |
@@ -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 = false;
|
||||||
|
|
||||||
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}) => {
|
||||||
|
setSelectedTreatments((prev) => {
|
||||||
|
const isSelected = prev.some(t => t.id === treatment.id);
|
||||||
|
|
||||||
// Clear selectedTime when treatment changes
|
if (isSelected) {
|
||||||
const handleTreatmentChange = (treatmentId: string) => {
|
// Remove from selection
|
||||||
setSelectedTreatment(treatmentId);
|
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) {
|
||||||
|
if (selectedTreatments.length === 0) {
|
||||||
|
setErrorMessage("Bitte wähle mindestens eine Behandlung aus.");
|
||||||
|
} else {
|
||||||
setErrorMessage("Bitte fülle alle erforderlichen Felder aus.");
|
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">
|
||||||
|
Behandlungen auswählen (1-3) *
|
||||||
</label>
|
</label>
|
||||||
<select
|
<span className="text-sm text-gray-600">
|
||||||
value={selectedTreatment}
|
{selectedTreatments.length} von 3 ausgewählt
|
||||||
onChange={(e) => handleTreatmentChange(e.target.value)}
|
</span>
|
||||||
className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
|
</div>
|
||||||
required
|
|
||||||
>
|
{/* Checkbox List Container */}
|
||||||
<option value="">Wähle eine Behandlung</option>
|
<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">
|
||||||
{treatments?.map((treatment) => (
|
{treatments?.map((treatment) => {
|
||||||
<option key={treatment.id} value={treatment.id}>
|
const isSelected = selectedTreatments.some(t => t.id === treatment.id);
|
||||||
{treatment.name} - {(treatment.price / 100).toFixed(2)} € ({treatment.duration} Min)
|
const isDisabled = selectedTreatments.length >= 3 && !isSelected;
|
||||||
</option>
|
|
||||||
))}
|
return (
|
||||||
</select>
|
<div key={treatment.id} className="flex items-start space-x-3">
|
||||||
{selectedTreatmentData && (
|
<input
|
||||||
<p className="mt-2 text-sm text-gray-600">{selectedTreatmentData.description}</p>
|
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,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, 0);
|
||||||
|
|
||||||
|
const treatmentItems = treatments.map(t =>
|
||||||
|
options.showPrices
|
||||||
|
? `<li><strong>${t.name}</strong> - ${t.duration} Min - ${t.price.toFixed(2)} €</li>`
|
||||||
|
: `<li>${t.name} - ${t.duration} Min - ${t.price.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>` : ''}
|
||||||
|
@@ -29,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);
|
||||||
@@ -57,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, 0);
|
||||||
|
|
||||||
|
const treatmentDetails = treatments.map(t =>
|
||||||
|
`${icsEscape(t.name)} (${t.duration} Min, ${t.price.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',
|
||||||
@@ -69,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',
|
||||||
@@ -187,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();
|
||||||
|
@@ -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,11 +112,22 @@ 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;
|
|
||||||
|
// Handle both new bookings with treatments array and old bookings with treatmentId
|
||||||
|
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) {
|
if (existingBooking.bookedDurationMinutes) {
|
||||||
existingDuration = 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);
|
||||||
const existingEndMinutes = existingStartMinutes + existingDuration;
|
const existingEndMinutes = existingStartMinutes + existingDuration;
|
||||||
@@ -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}>;
|
||||||
|
for (const inputTreatment of input.treatments) {
|
||||||
|
const treatment = await treatmentsKV.getItem(inputTreatment.id);
|
||||||
if (!treatment) {
|
if (!treatment) {
|
||||||
throw new Error("Behandlung nicht gefunden.");
|
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.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, 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.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, 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.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, 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.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, 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.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, 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}>;
|
||||||
|
for (const inputTreatment of input.treatments) {
|
||||||
|
const treatment = await treatmentsKV.getItem(inputTreatment.id);
|
||||||
if (!treatment) {
|
if (!treatment) {
|
||||||
throw new Error("Behandlung nicht gefunden.");
|
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.toFixed(2)} €)`).join('\n');
|
||||||
|
const totalPrice = input.treatments.reduce((sum, t) => sum + t.price, 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.toFixed(2)} €)`).join('\n');
|
||||||
|
const totalPrice = updated.treatments.reduce((sum, t) => sum + t.price, 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.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, 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,
|
||||||
});
|
});
|
||||||
@@ -938,8 +1049,9 @@ export const router = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get treatment name for context
|
// Get treatment name for context
|
||||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
const treatmentName = booking.treatments && booking.treatments.length > 0
|
||||||
const treatmentName = treatment?.name || "Behandlung";
|
? booking.treatments.map(t => t.name).join(', ')
|
||||||
|
: "Behandlung";
|
||||||
|
|
||||||
// Prepare email with Reply-To header
|
// Prepare email with Reply-To header
|
||||||
const ownerName = process.env.OWNER_NAME || "Stargirlnails Kiel";
|
const ownerName = process.env.OWNER_NAME || "Stargirlnails Kiel";
|
||||||
|
@@ -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