Compare commits
10 Commits
d153aad8b3
...
v0.1.5.2
Author | SHA1 | Date | |
---|---|---|---|
c1aeb7c38b | |||
889e110dd9 | |||
a603232ed8 | |||
f0037226a9 | |||
12da9812df | |||
ce019a2bd9 | |||
63384aa209 | |||
ebd9d8a72e | |||
ccba9d443b | |||
9583148e02 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "quests-template-basic",
|
||||
"private": true,
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.5.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"check:types": "tsc --noEmit",
|
||||
|
@@ -3,6 +3,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { queryClient } from "@/client/rpc-client";
|
||||
|
||||
export function AdminBookings() {
|
||||
const [filterMode, setFilterMode] = useState<"upcoming" | "all" | "date">("upcoming");
|
||||
const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
|
||||
const [selectedPhoto, setSelectedPhoto] = useState<string>("");
|
||||
const [showPhotoModal, setShowPhotoModal] = useState(false);
|
||||
@@ -64,8 +65,20 @@ export function AdminBookings() {
|
||||
})
|
||||
);
|
||||
|
||||
const getTreatmentName = (treatmentId: string) => {
|
||||
return treatments?.find(t => t.id === treatmentId)?.name || "Unbekannte Behandlung";
|
||||
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) => {
|
||||
@@ -127,9 +140,23 @@ export function AdminBookings() {
|
||||
return appointmentDate >= today;
|
||||
};
|
||||
|
||||
const filteredBookings = bookings?.filter(booking =>
|
||||
selectedDate ? booking.appointmentDate === selectedDate : true
|
||||
).sort((a, b) => {
|
||||
// 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) {
|
||||
return a.appointmentTime.localeCompare(b.appointmentTime);
|
||||
}
|
||||
@@ -206,22 +233,54 @@ export function AdminBookings() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Date Filter */}
|
||||
{/* Filter Section */}
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<div className="flex items-center space-x-4">
|
||||
<label className="text-sm font-medium text-gray-700">Filter by date:</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"
|
||||
/>
|
||||
<button
|
||||
onClick={() => setSelectedDate("")}
|
||||
className="text-sm text-pink-600 hover:text-pink-800"
|
||||
>
|
||||
Show All
|
||||
</button>
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<label className="text-sm font-medium text-gray-700">Filter:</label>
|
||||
<button
|
||||
onClick={() => setFilterMode("upcoming")}
|
||||
className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
filterMode === "upcoming"
|
||||
? "bg-pink-600 text-white"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
Zukünftige
|
||||
</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>
|
||||
|
||||
@@ -260,8 +319,8 @@ export function AdminBookings() {
|
||||
<div className="text-sm text-gray-500">{booking.customerPhone || '—'}</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-900">{getTreatmentName(booking.treatmentId)}</div>
|
||||
<td className="px-6 py-4">
|
||||
<div className="text-sm text-gray-900">{getTreatmentNames(booking)}</div>
|
||||
{booking.notes && (
|
||||
<div className="text-sm text-gray-500">Notizen: {booking.notes}</div>
|
||||
)}
|
||||
@@ -357,8 +416,10 @@ export function AdminBookings() {
|
||||
|
||||
{!filteredBookings?.length && (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
{selectedDate
|
||||
{filterMode === "date"
|
||||
? `Keine Buchungen für ${new Date(selectedDate).toLocaleDateString()} gefunden`
|
||||
: filterMode === "upcoming"
|
||||
? "Keine zukünftigen Buchungen verfügbar."
|
||||
: "Keine Buchungen verfügbar."
|
||||
}
|
||||
</div>
|
||||
@@ -445,6 +506,15 @@ export function AdminBookings() {
|
||||
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">
|
||||
@@ -456,9 +526,29 @@ export function AdminBookings() {
|
||||
<p className="text-sm text-gray-700">
|
||||
<strong>Termin:</strong> {new Date(booking.appointmentDate).toLocaleDateString()} um {booking.appointmentTime}
|
||||
</p>
|
||||
<p className="text-sm text-gray-700">
|
||||
<strong>Behandlung:</strong> {getTreatmentName(booking.treatmentId)}
|
||||
</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>
|
||||
);
|
||||
})()}
|
||||
|
@@ -47,7 +47,7 @@ export function AdminCalendar() {
|
||||
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
||||
input: {
|
||||
date: createFormData.appointmentDate,
|
||||
treatmentId: createFormData.treatmentId
|
||||
treatmentIds: createFormData.treatmentId ? [createFormData.treatmentId] : []
|
||||
}
|
||||
}),
|
||||
enabled: !!createFormData.appointmentDate && !!createFormData.treatmentId
|
||||
@@ -58,7 +58,16 @@ export function AdminCalendar() {
|
||||
...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
|
||||
input: {
|
||||
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
|
||||
@@ -86,8 +95,16 @@ export function AdminCalendar() {
|
||||
queryClient.bookings.generateCalDAVToken.mutationOptions()
|
||||
);
|
||||
|
||||
const getTreatmentName = (treatmentId: string) => {
|
||||
return treatments?.find(t => t.id === treatmentId)?.name || "Unbekannte Behandlung";
|
||||
const getTreatmentNames = (booking: any) => {
|
||||
// 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) => {
|
||||
@@ -219,9 +236,29 @@ export function AdminCalendar() {
|
||||
const sessionId = localStorage.getItem('sessionId');
|
||||
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({
|
||||
sessionId,
|
||||
...createFormData
|
||||
treatments: treatmentsArray,
|
||||
customerName: createFormData.customerName,
|
||||
appointmentDate: createFormData.appointmentDate,
|
||||
appointmentTime: createFormData.appointmentTime,
|
||||
customerEmail: createFormData.customerEmail,
|
||||
customerPhone: createFormData.customerPhone,
|
||||
notes: createFormData.notes
|
||||
}, {
|
||||
onSuccess: () => {
|
||||
setShowCreateModal(false);
|
||||
@@ -469,7 +506,7 @@ export function AdminCalendar() {
|
||||
<div
|
||||
key={booking.id}
|
||||
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="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>
|
||||
<strong>Behandlung:</strong> {getTreatmentName(booking.treatmentId)}
|
||||
<strong>Behandlung:</strong> {getTreatmentNames(booking)}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Uhrzeit:</strong> {booking.appointmentTime}
|
||||
@@ -842,7 +879,7 @@ export function AdminCalendar() {
|
||||
|
||||
{(() => {
|
||||
const booking = bookings?.find(b => b.id === showRescheduleModal);
|
||||
const treatmentName = booking ? getTreatmentName(booking.treatmentId) : '';
|
||||
const treatmentName = booking ? getTreatmentNames(booking) : '';
|
||||
return booking ? (
|
||||
<div className="mb-4 text-sm text-gray-700">
|
||||
<div className="mb-2"><strong>Kunde:</strong> {booking.customerName}</div>
|
||||
|
@@ -3,7 +3,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { queryClient } from "@/client/rpc-client";
|
||||
|
||||
// Feature flag for multi-treatments availability API compatibility
|
||||
const USE_MULTI_TREATMENTS_AVAILABILITY = false;
|
||||
const USE_MULTI_TREATMENTS_AVAILABILITY = true;
|
||||
|
||||
export function BookingForm() {
|
||||
const [selectedTreatments, setSelectedTreatments] = useState<Array<{id: string, name: string, duration: number, price: number}>>([]);
|
||||
|
@@ -8,6 +8,50 @@ interface BookingStatusPageProps {
|
||||
|
||||
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) {
|
||||
switch (status) {
|
||||
case "pending":
|
||||
@@ -57,7 +101,7 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
||||
const [showCancelConfirm, setShowCancelConfirm] = useState(false);
|
||||
const [isCancelling, setIsCancelling] = useState(false);
|
||||
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 [isAccepting, setIsAccepting] = 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
|
||||
const rescheduleQuery = useQuery({
|
||||
const rescheduleQuery = useQuery<RescheduleProposalDetails>({
|
||||
...queryClient.cancellation.getRescheduleProposal.queryOptions({ input: { token } }),
|
||||
enabled: !!token && (!!bookingError || !booking),
|
||||
});
|
||||
@@ -159,7 +203,7 @@ export default function BookingStatusPage({ token }: BookingStatusPageProps) {
|
||||
|
||||
if (oneClickAction === 'accept') {
|
||||
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) {
|
||||
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="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-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 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-gray-900 font-medium">{rescheduleProposal.proposed.date} um {rescheduleProposal.proposed.time} Uhr</div>
|
||||
<div className="text-gray-700 text-sm">{rescheduleProposal.booking.treatmentName}</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 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="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="font-medium text-gray-900">{booking?.appointmentTime} Uhr</span>
|
||||
</div>
|
||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-gray-600">Behandlung:</span>
|
||||
<span className="font-medium text-gray-900">{booking?.treatmentName}</span>
|
||||
|
||||
{/* Treatments List */}
|
||||
<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 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" && (
|
||||
<div className="flex justify-between py-2">
|
||||
<span className="text-gray-600">Verbleibende Zeit:</span>
|
||||
|
@@ -139,7 +139,11 @@ export default function ReviewSubmissionPage({ token }: ReviewSubmissionPageProp
|
||||
</div>
|
||||
<div className="flex justify-between py-2 border-b border-gray-100">
|
||||
<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 className="flex justify-between py-2">
|
||||
<span className="text-gray-600">Name:</span>
|
||||
|
@@ -8,6 +8,27 @@ function formatDateGerman(dateString: string): string {
|
||||
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;
|
||||
|
||||
async function getLogoDataUrl(): Promise<string | null> {
|
||||
@@ -86,8 +107,8 @@ async function renderBrandedEmail(title: string, bodyHtml: string): Promise<stri
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export async function renderBookingPendingHTML(params: { name: string; date: string; time: string; statusUrl?: string }) {
|
||||
const { name, date, time, statusUrl } = params;
|
||||
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, treatments } = params;
|
||||
const formattedDate = formatDateGerman(date);
|
||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||
@@ -96,6 +117,12 @@ export async function renderBookingPendingHTML(params: { name: string; date: str
|
||||
const inner = `
|
||||
<p>Hallo ${name},</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>
|
||||
${statusUrl ? `
|
||||
<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);
|
||||
}
|
||||
|
||||
export async function renderBookingConfirmedHTML(params: { name: string; date: string; time: string; cancellationUrl?: string; reviewUrl?: string }) {
|
||||
const { name, date, time, cancellationUrl, reviewUrl } = params;
|
||||
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, treatments } = params;
|
||||
const formattedDate = formatDateGerman(date);
|
||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||
@@ -123,6 +150,12 @@ export async function renderBookingConfirmedHTML(params: { name: string; date: s
|
||||
const inner = `
|
||||
<p>Hallo ${name},</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>
|
||||
<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>
|
||||
@@ -152,8 +185,8 @@ export async function renderBookingConfirmedHTML(params: { name: string; date: s
|
||||
return renderBrandedEmail("Termin bestätigt", inner);
|
||||
}
|
||||
|
||||
export async function renderBookingCancelledHTML(params: { name: string; date: string; time: string }) {
|
||||
const { name, date, time } = params;
|
||||
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, treatments } = params;
|
||||
const formattedDate = formatDateGerman(date);
|
||||
const domain = process.env.DOMAIN || 'localhost:5173';
|
||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||
@@ -162,6 +195,12 @@ export async function renderBookingCancelledHTML(params: { name: string; date: s
|
||||
const inner = `
|
||||
<p>Hallo ${name},</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>
|
||||
<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>
|
||||
@@ -176,13 +215,14 @@ export async function renderAdminBookingNotificationHTML(params: {
|
||||
name: string;
|
||||
date: string;
|
||||
time: string;
|
||||
treatment: string;
|
||||
treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||
phone: string;
|
||||
notes?: string;
|
||||
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 inner = `
|
||||
<p>Hallo Admin,</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;">
|
||||
<li><strong>Name:</strong> ${name}</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>Uhrzeit:</strong> ${time}</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`;
|
||||
}
|
||||
|
||||
// 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
|
||||
function createICSFile(params: {
|
||||
date: string; // YYYY-MM-DD
|
||||
time: string; // HH:MM
|
||||
durationMinutes: number;
|
||||
customerName: string;
|
||||
treatmentName: string;
|
||||
customerEmail?: string;
|
||||
treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||
}): 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
|
||||
const dtStart = formatDateForICS(date, time);
|
||||
@@ -57,6 +69,17 @@ function createICSFile(params: {
|
||||
const now = new Date();
|
||||
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
|
||||
const icsContent = [
|
||||
'BEGIN:VCALENDAR',
|
||||
@@ -69,11 +92,11 @@ function createICSFile(params: {
|
||||
`DTSTAMP:${dtstamp}`,
|
||||
`DTSTART;TZID=Europe/Berlin:${dtStart}`,
|
||||
`DTEND;TZID=Europe/Berlin:${dtEnd}`,
|
||||
`SUMMARY:${treatmentName} - Stargirlnails Kiel`,
|
||||
`DESCRIPTION:Termin für ${treatmentName} bei Stargirlnails Kiel`,
|
||||
`SUMMARY:${treatmentNames} - Stargirlnails Kiel`,
|
||||
`DESCRIPTION:${description}`,
|
||||
'LOCATION:Stargirlnails Kiel',
|
||||
`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',
|
||||
'SEQUENCE:0',
|
||||
'BEGIN:VALARM',
|
||||
@@ -187,9 +210,9 @@ export async function sendEmailWithAGBAndCalendar(
|
||||
calendarParams: {
|
||||
date: string;
|
||||
time: string;
|
||||
durationMinutes: number;
|
||||
customerName: string;
|
||||
treatmentName: string;
|
||||
customerEmail?: string;
|
||||
treatments: Array<{id: string; name: string; duration: number; price: number}>;
|
||||
}
|
||||
): Promise<{ success: boolean }> {
|
||||
const agbBase64 = await getAGBPDFBase64();
|
||||
|
@@ -5,7 +5,7 @@ import { assertOwner } from "../lib/auth.js";
|
||||
// Types für Buchungen (vereinfacht für CalDAV)
|
||||
type Booking = {
|
||||
id: string;
|
||||
treatmentId: string;
|
||||
treatments?: Array<{id: string, name: string, duration: number, price: number}>;
|
||||
customerName: string;
|
||||
customerEmail?: string;
|
||||
customerPhone?: string;
|
||||
@@ -13,6 +13,8 @@ type Booking = {
|
||||
appointmentTime: string; // HH:MM
|
||||
status: "pending" | "confirmed" | "cancelled" | "completed";
|
||||
notes?: string;
|
||||
// Deprecated fields for backward compatibility
|
||||
treatmentId?: string;
|
||||
bookedDurationMinutes?: number;
|
||||
createdAt: string;
|
||||
};
|
||||
@@ -44,6 +46,14 @@ function formatDateTime(dateStr: string, timeStr: string): string {
|
||||
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 {
|
||||
const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
||||
|
||||
@@ -63,14 +73,41 @@ X-WR-TIMEZONE:Europe/Berlin
|
||||
);
|
||||
|
||||
for (const booking of activeBookings) {
|
||||
const treatment = treatments.find(t => t.id === booking.treatmentId);
|
||||
const treatmentName = treatment?.name || 'Unbekannte Behandlung';
|
||||
const duration = booking.bookedDurationMinutes || treatment?.duration || 60;
|
||||
// Handle new treatments array structure
|
||||
let treatmentNames: string;
|
||||
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 endTime = formatDateTime(booking.appointmentDate,
|
||||
`${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 endTimeStr = addMinutesToTime(booking.appointmentTime, duration);
|
||||
const endTime = formatDateTime(booking.appointmentDate, endTimeStr);
|
||||
|
||||
// UID für jeden Termin (eindeutig)
|
||||
const uid = `booking-${booking.id}@stargirlnails.de`;
|
||||
@@ -83,8 +120,8 @@ UID:${uid}
|
||||
DTSTAMP:${now}
|
||||
DTSTART:${startTime}
|
||||
DTEND:${endTime}
|
||||
SUMMARY:${treatmentName} - ${booking.customerName}
|
||||
DESCRIPTION:Behandlung: ${treatmentName}\\nKunde: ${booking.customerName}${booking.customerPhone ? `\\nTelefon: ${booking.customerPhone}` : ''}${booking.notes ? `\\nNotizen: ${booking.notes}` : ''}
|
||||
SUMMARY:${treatmentNames} - ${booking.customerName}
|
||||
DESCRIPTION:${treatmentDetails}\\n\\nKunde: ${booking.customerName}${booking.customerPhone ? `\\nTelefon: ${booking.customerPhone}` : ''}${booking.notes ? `\\nNotizen: ${booking.notes}` : ''}
|
||||
STATUS:${status}
|
||||
TRANSP:OPAQUE
|
||||
END:VEVENT
|
||||
|
@@ -363,12 +363,18 @@ const create = os
|
||||
name: input.customerName,
|
||||
date: input.appointmentDate,
|
||||
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({
|
||||
to: input.customerEmail,
|
||||
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,
|
||||
}).catch(() => {});
|
||||
})();
|
||||
@@ -377,25 +383,26 @@ const create = os
|
||||
void (async () => {
|
||||
if (!process.env.ADMIN_EMAIL) return;
|
||||
|
||||
// Build treatment list string
|
||||
const treatmentsList = input.treatments.map(t => `${t.name} (${t.duration} Min, ${t.price.toFixed(2)} €)`).join(', ');
|
||||
|
||||
const adminHtml = await renderAdminBookingNotificationHTML({
|
||||
name: input.customerName,
|
||||
date: input.appointmentDate,
|
||||
time: input.appointmentTime,
|
||||
treatment: treatmentsList,
|
||||
treatments: input.treatments,
|
||||
phone: input.customerPhone || "Nicht angegeben",
|
||||
notes: input.notes,
|
||||
hasInspirationPhoto: !!input.inspirationPhoto
|
||||
});
|
||||
|
||||
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` +
|
||||
`Name: ${input.customerName}\n` +
|
||||
`Telefon: ${input.customerPhone || "Nicht angegeben"}\n` +
|
||||
`Behandlungen: ${treatmentsList}\n` +
|
||||
`Behandlungen:\n${treatmentsText}\n` +
|
||||
`Gesamt: ${totalDuration} Min, ${totalPrice.toFixed(2)} €\n` +
|
||||
`Datum: ${formatDateGerman(input.appointmentDate)}\n` +
|
||||
`Uhrzeit: ${input.appointmentTime}\n` +
|
||||
`${input.notes ? `Notizen: ${input.notes}\n` : ''}` +
|
||||
@@ -472,41 +479,48 @@ const updateStatus = os
|
||||
date: booking.appointmentDate,
|
||||
time: booking.appointmentTime,
|
||||
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 treatmentName = booking.treatments && booking.treatments.length > 0
|
||||
? booking.treatments.map(t => t.name).join(', ')
|
||||
: "Behandlung";
|
||||
const treatmentDuration = booking.treatments && booking.treatments.length > 0
|
||||
? booking.treatments.reduce((sum, t) => sum + t.duration, 0)
|
||||
: (booking.bookedDurationMinutes || 60);
|
||||
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) {
|
||||
await sendEmailWithAGBAndCalendar({
|
||||
to: booking.customerEmail,
|
||||
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,
|
||||
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
||||
}, {
|
||||
date: booking.appointmentDate,
|
||||
time: booking.appointmentTime,
|
||||
durationMinutes: treatmentDuration,
|
||||
customerName: booking.customerName,
|
||||
treatmentName: treatmentName
|
||||
customerEmail: booking.customerEmail,
|
||||
treatments: booking.treatments
|
||||
});
|
||||
}
|
||||
} else if (input.status === "cancelled") {
|
||||
const formattedDate = formatDateGerman(booking.appointmentDate);
|
||||
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) {
|
||||
await sendEmail({
|
||||
to: booking.customerEmail,
|
||||
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,
|
||||
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
||||
});
|
||||
@@ -550,11 +564,21 @@ const remove = os
|
||||
try {
|
||||
const formattedDate = formatDateGerman(booking.appointmentDate);
|
||||
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({
|
||||
to: booking.customerEmail,
|
||||
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,
|
||||
bcc: process.env.ADMIN_EMAIL ? [process.env.ADMIN_EMAIL] : undefined,
|
||||
});
|
||||
@@ -665,20 +689,24 @@ const createManual = os
|
||||
date: input.appointmentDate,
|
||||
time: input.appointmentTime,
|
||||
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({
|
||||
to: input.customerEmail!,
|
||||
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,
|
||||
}, {
|
||||
date: input.appointmentDate,
|
||||
time: input.appointmentTime,
|
||||
durationMinutes: totalDuration,
|
||||
customerName: input.customerName,
|
||||
treatmentName: input.treatments.map(t => t.name).join(', ')
|
||||
customerEmail: input.customerEmail,
|
||||
treatments: input.treatments
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Email send failed for manual booking:", e);
|
||||
@@ -843,21 +871,23 @@ export const router = {
|
||||
time: updated.appointmentTime,
|
||||
cancellationUrl: generateUrl(`/booking/${bookingAccessToken.token}`),
|
||||
reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`),
|
||||
treatments: updated.treatments,
|
||||
});
|
||||
const treatmentName = updated.treatments && updated.treatments.length > 0
|
||||
? updated.treatments.map(t => t.name).join(', ')
|
||||
: "Behandlung";
|
||||
|
||||
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({
|
||||
to: updated.customerEmail,
|
||||
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,
|
||||
}, {
|
||||
date: updated.appointmentDate,
|
||||
time: updated.appointmentTime,
|
||||
durationMinutes: duration,
|
||||
customerName: updated.customerName,
|
||||
treatmentName: treatmentName,
|
||||
customerEmail: updated.customerEmail,
|
||||
treatments: updated.treatments,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
@@ -898,11 +928,23 @@ export const router = {
|
||||
// Notify customer that original stays
|
||||
if (booking.customerEmail) {
|
||||
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({
|
||||
to: booking.customerEmail,
|
||||
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.`,
|
||||
html: await renderBookingConfirmedHTML({ name: booking.customerName, date: booking.appointmentDate, time: booking.appointmentTime, cancellationUrl: generateUrl(`/booking/${bookingAccessToken.token}`), reviewUrl: generateUrl(`/review/${bookingAccessToken.token}`) }),
|
||||
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}`),
|
||||
treatments: booking.treatments
|
||||
}),
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
|
@@ -28,7 +28,15 @@ const cancellationKV = createKV<BookingAccessToken>("cancellation_tokens");
|
||||
// Types for booking and availability
|
||||
type Booking = {
|
||||
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;
|
||||
customerEmail?: string;
|
||||
customerPhone?: string;
|
||||
@@ -120,9 +128,42 @@ const getBookingByToken = os
|
||||
throw new Error("Booking not found");
|
||||
}
|
||||
|
||||
// Get treatment details
|
||||
const treatmentsKV = createKV<any>("treatments");
|
||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
||||
// Handle treatments array
|
||||
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;
|
||||
}
|
||||
|
||||
// Calculate if cancellation is still possible
|
||||
const minStornoTimespan = parseInt(process.env.MIN_STORNO_TIMESPAN || "24");
|
||||
@@ -140,10 +181,9 @@ const getBookingByToken = os
|
||||
customerPhone: booking.customerPhone,
|
||||
appointmentDate: booking.appointmentDate,
|
||||
appointmentTime: booking.appointmentTime,
|
||||
treatmentId: booking.treatmentId,
|
||||
treatmentName: treatment?.name || "Unbekannte Behandlung",
|
||||
treatmentDuration: treatment?.duration || 60,
|
||||
treatmentPrice: treatment?.price || 0,
|
||||
treatments,
|
||||
totalDuration,
|
||||
totalPrice,
|
||||
status: booking.status,
|
||||
notes: booking.notes,
|
||||
formattedDate: formatDateGerman(booking.appointmentDate),
|
||||
@@ -284,8 +324,42 @@ export const router = {
|
||||
throw new Error("Booking not found");
|
||||
}
|
||||
|
||||
const treatmentsKV = createKV<any>("treatments");
|
||||
const treatment = await treatmentsKV.getItem(booking.treatmentId);
|
||||
// Handle treatments array
|
||||
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 isExpired = new Date(proposal.expiresAt) <= now;
|
||||
@@ -298,8 +372,9 @@ export const router = {
|
||||
customerEmail: booking.customerEmail,
|
||||
customerPhone: booking.customerPhone,
|
||||
status: booking.status,
|
||||
treatmentId: booking.treatmentId,
|
||||
treatmentName: treatment?.name || "Unbekannte Behandlung",
|
||||
treatments,
|
||||
totalDuration,
|
||||
totalPrice,
|
||||
},
|
||||
original: {
|
||||
date: proposal.originalDate || booking.appointmentDate,
|
||||
@@ -358,14 +433,22 @@ export const router = {
|
||||
const booking = await bookingsKV.getItem(proposal.bookingId);
|
||||
if (booking) {
|
||||
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({
|
||||
customerName: booking.customerName,
|
||||
originalDate: proposal.originalDate || booking.appointmentDate,
|
||||
originalTime: proposal.originalTime || booking.appointmentTime,
|
||||
proposedDate: proposal.proposedDate!,
|
||||
proposedTime: proposal.proposedTime!,
|
||||
treatmentName: treatment?.name || "Unbekannte Behandlung",
|
||||
treatmentName: treatmentName,
|
||||
customerEmail: booking.customerEmail,
|
||||
customerPhone: booking.customerPhone,
|
||||
expiredAt: proposal.expiresAt,
|
||||
|
@@ -272,7 +272,12 @@ const getAvailableTimes = os
|
||||
.input(
|
||||
z.object({
|
||||
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 }) => {
|
||||
@@ -287,13 +292,22 @@ const getAvailableTimes = os
|
||||
return [];
|
||||
}
|
||||
|
||||
// Get treatment duration
|
||||
const treatment = await treatmentsKV.getItem(input.treatmentId);
|
||||
if (!treatment) {
|
||||
throw new Error("Behandlung nicht gefunden.");
|
||||
// Get multiple treatments and calculate total duration
|
||||
const treatments = await Promise.all(
|
||||
input.treatmentIds.map(id => treatmentsKV.getItem(id))
|
||||
);
|
||||
|
||||
// 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
|
||||
const [year, month, day] = input.date.split('-').map(Number);
|
||||
@@ -344,36 +358,38 @@ const getAvailableTimes = os
|
||||
['pending', 'confirmed', 'completed'].includes(booking.status)
|
||||
);
|
||||
|
||||
// Optimize treatment duration lookup with Map caching
|
||||
const uniqueTreatmentIds = [...new Set(dateBookings.map(booking => booking.treatmentId))];
|
||||
// Build cache only for legacy treatmentId bookings
|
||||
const legacyTreatmentIds = [...new Set(dateBookings.filter(b => b.treatmentId).map(b => b.treatmentId as string))];
|
||||
const treatmentDurationMap = new Map<string, number>();
|
||||
|
||||
for (const treatmentId of uniqueTreatmentIds) {
|
||||
const treatment = await treatmentsKV.getItem(treatmentId);
|
||||
treatmentDurationMap.set(treatmentId, treatment?.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);
|
||||
// Only build cache if there are legacy bookings
|
||||
if (legacyTreatmentIds.length > 0) {
|
||||
for (const id of legacyTreatmentIds) {
|
||||
const t = await treatmentsKV.getItem(id);
|
||||
treatmentDurationMap.set(id, t?.duration || 60);
|
||||
}
|
||||
}
|
||||
|
||||
// Filter out booking conflicts
|
||||
const availableTimesFiltered = availableTimes.filter(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 bookingStartMinutes = parseTime(booking.appointmentTime);
|
||||
const bookingDuration = bookingTreatments.get(booking.id) || 60;
|
||||
const bookingEndMinutes = bookingStartMinutes + bookingDuration;
|
||||
let bookingDuration: number;
|
||||
if (booking.treatments && booking.treatments.length > 0) {
|
||||
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
|
||||
return slotStartMinutes < bookingEndMinutes && slotEndMinutes > bookingStartMinutes;
|
||||
const bookingStart = parseTime(booking.appointmentTime);
|
||||
const bookingEnd = bookingStart + bookingDuration;
|
||||
return slotStartMinutes < bookingEnd && slotEndMinutes > bookingStart;
|
||||
});
|
||||
|
||||
return !hasConflict;
|
||||
|
Reference in New Issue
Block a user