Cancelling worked but had no policy behind it: no window, no penalty, nothing happened to the deposit, and the no_show status had no effect at all. Two rules that are expensive to get wrong, and both are load-bearing: - The clinic cancelling its own appointment is never charged. That check is the first line of the calculation, not somewhere in the middle, so a later refactor cannot reorder it into charging patients for the clinic's decision. - A penalty never exceeds what was actually paid. Anything above that is a debt, and debt belongs to billing, not to cancellation. An unpaid appointment is charged nothing and the response says why. The default is no penalty at all — a penalising default would have made every patient with a near appointment liable the moment this deployed. No-shows are rows, not a counter on the patient: a counter loses which appointment and when, which makes the 12-month window impossible. Crossing the threshold adds an existing TenantTag; it never blocks the patient, because blocking is an eligibility policy (task 09) written on top of that same tag. Waitlist notifies up to ten matching people and the first to book wins. An exclusive queue reads fairer but means a freed slot sits locked for half an hour while someone ignores their phone — so the SMS says so explicitly instead. Insufficient wallet balance does not fail the cancellation: the slot is freed either way. A slot should not be held hostage to money. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
102 lines
3.5 KiB
TypeScript
102 lines
3.5 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { toast } from 'sonner';
|
|
import { api, ApiError, type ApiResponse } from '../lib/api';
|
|
import type { CancellationPolicy, CancellationPreview, CancellationResult, WaitlistEntry } from '../types';
|
|
|
|
/**
|
|
* سیاست لغو و لیست انتظار.
|
|
*
|
|
* پیشنمایش لغو همیشه از سرور میآید — همان محاسبهای که خودِ لغو انجام میدهد، تا عددی
|
|
* که کاربر میبیند با آنچه کسر میشود یکی باشد.
|
|
*/
|
|
const POLICY_KEY = ['cancellation-policy'];
|
|
const WAITLIST_KEY = ['waitlist'];
|
|
|
|
function fail(e: unknown, fallback: string) {
|
|
toast.error(e instanceof ApiError ? e.message : fallback);
|
|
}
|
|
|
|
interface PolicyResponse {
|
|
default: CancellationPolicy | null;
|
|
overrides: CancellationPolicy[];
|
|
}
|
|
|
|
export function useCancellationPolicy() {
|
|
const qc = useQueryClient();
|
|
|
|
const query = useQuery({
|
|
queryKey: POLICY_KEY,
|
|
queryFn: () => api.get<ApiResponse<PolicyResponse>>('/api/v1/cancellation-policy'),
|
|
});
|
|
|
|
const save = useMutation({
|
|
mutationFn: (body: Record<string, unknown>) =>
|
|
api.put<ApiResponse<CancellationPolicy>>('/api/v1/cancellation-policy', body),
|
|
onSuccess: () => {
|
|
toast.success('سیاست لغو ذخیره شد');
|
|
qc.invalidateQueries({ queryKey: POLICY_KEY });
|
|
},
|
|
onError: (e) => fail(e, 'ذخیرهٔ سیاست ناموفق بود'),
|
|
});
|
|
|
|
return {
|
|
policy: query.data?.data?.default ?? null,
|
|
overrides: query.data?.data?.overrides ?? [],
|
|
loading: query.isLoading,
|
|
save,
|
|
};
|
|
}
|
|
|
|
export function useCancellationPreview(appointmentUuid: string | undefined, by: 'user' | 'doctor') {
|
|
const query = useQuery({
|
|
queryKey: ['cancellation-preview', appointmentUuid, by],
|
|
queryFn: () =>
|
|
api.get<ApiResponse<CancellationPreview>>(
|
|
`/api/v1/appointment/${appointmentUuid}/cancellation-preview?by=${by}`,
|
|
),
|
|
enabled: !!appointmentUuid,
|
|
});
|
|
|
|
return { preview: query.data?.data, loading: query.isLoading };
|
|
}
|
|
|
|
export function useCancelAppointment() {
|
|
const qc = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: ({ uuid, by }: { uuid: string; by: 'user' | 'doctor' }) =>
|
|
api.post<ApiResponse<CancellationResult>>(`/api/v1/appointment/${uuid}/cancel`, { by }),
|
|
onSuccess: (res) => {
|
|
const notified = res.data.waitlist_notified;
|
|
toast.success(
|
|
notified > 0 ? `نوبت لغو شد و ${notified} نفر از لیست انتظار خبر شدند` : 'نوبت لغو شد',
|
|
);
|
|
qc.invalidateQueries({ queryKey: ['appointments'] });
|
|
qc.invalidateQueries({ queryKey: WAITLIST_KEY });
|
|
},
|
|
onError: (e) => fail(e, 'لغو نوبت ناموفق بود'),
|
|
});
|
|
}
|
|
|
|
export function useWaitlist(status?: string) {
|
|
const qc = useQueryClient();
|
|
const key = [...WAITLIST_KEY, status ?? ''];
|
|
|
|
const query = useQuery({
|
|
queryKey: key,
|
|
queryFn: () =>
|
|
api.get<ApiResponse<WaitlistEntry[]>>(`/api/v1/waitlist${status ? `?status=${status}` : ''}`),
|
|
});
|
|
|
|
const remove = useMutation({
|
|
mutationFn: (uuid: string) => api.delete<ApiResponse<null>>(`/api/v1/waitlist/${uuid}`),
|
|
onSuccess: () => {
|
|
toast.success('از لیست انتظار حذف شد');
|
|
qc.invalidateQueries({ queryKey: WAITLIST_KEY });
|
|
},
|
|
onError: (e) => fail(e, 'حذف ناموفق بود'),
|
|
});
|
|
|
|
return { entries: query.data?.data ?? [], loading: query.isLoading, remove };
|
|
}
|