feat: close the last four domain events, and the panel paths they describe

Every one of the fourteen named events now has an emit point. The four that
were missing all sat on paths owned by earlier tasks:

- AppointmentCompleted fires from both status-change routes, after the row is
  saved. A rejected transition or a version conflict leaves no event; otherwise
  the completed count runs ahead of the appointments themselves.
- AppointmentRescheduled is a third event, not a replacement. A rebook is a
  confirm plus a cancel, and a consumer that only hears the cancel messages a
  patient who still has an appointment.
- ResourceBlocked / ResourceReleased are a pair. Capacity coming back has to be
  as audible as capacity going away, or the resource reads as permanently taken.

Publishing is now on the scheduler rather than an unregistered command: the
logic moved out of PublishDomainEventsCommand into OutboxPublisher so the
recurring message and the manual command share it, and the existing
worker-scheduler container consumes it. The scheduler message carries no data
on purpose — what to publish is read from the table, so an event recorded
between two ticks is not skipped. DomainEventMessage routes to async, since a
slow consumer was otherwise slowing the drain itself and its failure marked a
row failed that had in fact been delivered.

Panel work that these paths made reachable:

- Cancelling from the appointment page now goes through the policy-aware
  endpoint and shows the penalty preview before the confirm, so the operator
  does not discover the patient's penalty after the fact. The cancellation
  service writes the timeline entry itself and accepts a reason, which that
  path previously dropped on the floor.
- Rescheduling reuses the booking page under ?rebook=<uuid> — the search and
  hold steps are identical and only the final step differs. The doctor picker
  is hidden there: a reschedule is not an invitation to change doctors.
- A new GET /appointment/{uuid}/segments exposes the recorded plan. An empty
  list is not an error, it means the appointment is slot-based, and that is
  exactly what gates the resource-mode reschedule button.

AppointmentInvoiceCard no longer crashes the whole detail page when an older
invoice has no discount breakdown.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-31 21:27:55 +03:30
co-authored by Claude Opus 5
parent b55c33f686
commit 4049daf071
29 changed files with 977 additions and 118 deletions
@@ -69,7 +69,8 @@ export default function AppointmentInvoiceCard({ appointmentUuid }: Props) {
</div>
))}
{invoice.breakdown.discounts.map((line, index) => (
{/* فاکتور قدیمی ممکن است ریز تخفیف نداشته باشد؛ نبودنش نباید کل صفحه را ببندد. */}
{(invoice.breakdown?.discounts ?? []).map((line, index) => (
<div
key={index}
style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-3)' }}
@@ -0,0 +1,63 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
vi.mock('../lib/api', () => ({
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
ApiError: class extends Error {},
}));
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
import { api } from '../lib/api';
import AppointmentSegmentsCard from './AppointmentSegmentsCard';
const get = api.get as ReturnType<typeof vi.fn>;
const segment = (over: Record<string, unknown>) => ({
sequence: 1,
name: 'ویزیت',
starts_at: 1_800_000_000,
ends_at: 1_800_001_200,
duration_minutes: 20,
patient_present: true,
...over,
});
describe('AppointmentSegmentsCard', () => {
beforeEach(() => vi.clearAllMocks());
it('sums the recorded segments rather than the service duration', async () => {
get.mockResolvedValue({
data: [
segment({ sequence: 1, duration_minutes: 20 }),
segment({ sequence: 2, name: 'انتظار', duration_minutes: 40, patient_present: false }),
],
});
renderWithProviders(<AppointmentSegmentsCard appointmentUuid="a-1" />);
await waitFor(() => expect(screen.getByText('60 دقیقه')).toBeInTheDocument());
});
/** ⭐ مدتی که بیمار روی صندلی نیست باید دیده شود، وگرنه «۹۰ دقیقه» گمراه‌کننده است. */
it('marks the segments the patient is not present for', async () => {
get.mockResolvedValue({
data: [segment({ sequence: 1, name: 'انتظار', patient_present: false })],
});
renderWithProviders(<AppointmentSegmentsCard appointmentUuid="a-1" />);
await waitFor(() => expect(screen.getByText('بدون حضور بیمار')).toBeInTheDocument());
});
/** نوبت اسلاتی بخشی ندارد؛ کارتِ خالی یعنی «چیزی خراب است». */
it('renders nothing for an appointment with no segments', async () => {
get.mockResolvedValue({ data: [] });
const { container } = renderWithProviders(<AppointmentSegmentsCard appointmentUuid="a-1" />);
await waitFor(() => expect(get).toHaveBeenCalled());
expect(container.textContent).toBe('');
});
});
@@ -0,0 +1,63 @@
import React from 'react';
import { useAppointmentSegments } from '../hooks/useResourceBooking';
const timeOf = (ts: number) =>
new Date(ts * 1000).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' });
/**
* بخش‌های ثبت‌شدهٔ نوبت — همان چیزی که لحظهٔ رزرو تثبیت شد، نه الگوی امروزِ خدمت.
*
* بخشی که بیمار در آن حاضر نیست کم‌رنگ می‌آید: اپراتوری که «۹۰ دقیقه» را روی نوبت
* می‌بیند باید بفهمد بیمار همهٔ آن مدت روی صندلی نیست.
*
* نوبت اسلاتی بخشی ندارد و کارت اصلاً رندر نمی‌شود — جدول خالی یعنی چیزی خراب است.
*/
export default function AppointmentSegmentsCard({ appointmentUuid }: { appointmentUuid: string }) {
const { segments, loading } = useAppointmentSegments(appointmentUuid);
if (loading || segments.length === 0) return null;
const total = segments.reduce((sum, s) => sum + s.duration_minutes, 0);
return (
<div className="bg-[var(--surface)] rounded-2xl border border-[var(--border)] shadow-sm p-6">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-[var(--text)]">بخشهای نوبت</h3>
<span className="text-sm text-[var(--text-2)]">{total} دقیقه</span>
</div>
<div style={{ display: 'flex', gap: 2, marginBottom: 14 }}>
{segments.map((s) => (
<div
key={s.sequence}
title={`${s.name}${s.duration_minutes} دقیقه`}
style={{
flex: s.duration_minutes,
height: 10,
borderRadius: 'var(--r-pill)',
background: 'var(--primary)',
opacity: s.patient_present ? 1 : 0.35,
}}
/>
))}
</div>
<ol style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13 }}>
{segments.map((s) => (
<li key={s.sequence} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<span style={{ color: 'var(--text-3)', minWidth: 18 }}>{s.sequence}</span>
<span style={{ flex: 1 }}>{s.name}</span>
<span dir="ltr" style={{ color: 'var(--text-2)' }}>
{timeOf(s.starts_at)} {timeOf(s.ends_at)}
</span>
{!s.patient_present && (
<span className="badge" style={{ fontSize: 11 }}>
بدون حضور بیمار
</span>
)}
</li>
))}
</ol>
</div>
);
}
@@ -0,0 +1,96 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../test/utils';
vi.mock('../lib/api', () => ({
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
ApiError: class extends Error {},
}));
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
import { api } from '../lib/api';
import CancelAppointmentDialog from './CancelAppointmentDialog';
const get = api.get as ReturnType<typeof vi.fn>;
const post = api.post as ReturnType<typeof vi.fn>;
const preview = (over: Record<string, unknown> = {}) => ({
data: {
penalty_rials: 250_000,
deposit_refundable: true,
credit_refundable: true,
within_free_window: false,
notes: [],
paid_rials: 1_000_000,
...over,
},
});
describe('CancelAppointmentDialog', () => {
beforeEach(() => {
vi.clearAllMocks();
post.mockResolvedValue({ data: { waitlist_notified: 0 } });
});
/** ⭐ عددی که اپراتور می‌بیند باید همان باشد که کسر می‌شود. */
it('shows the penalty from the server before anything is cancelled', async () => {
get.mockResolvedValue(preview());
renderWithProviders(
<CancelAppointmentDialog open appointmentUuid="a-1" onClose={() => {}} />,
);
// مبلغ‌ها به تومان نمایش داده می‌شوند: ۲۵۰٬۰۰۰ ریال ⇒ ۲۵٬۰۰۰ تومان.
await waitFor(() => expect(screen.getByText(/۲۵٬۰۰۰ تومان/)).toBeInTheDocument());
expect(post).not.toHaveBeenCalled();
});
it('says "بدون جریمه" inside the free window instead of showing a zero', async () => {
get.mockResolvedValue(preview({ penalty_rials: 0, within_free_window: true }));
renderWithProviders(
<CancelAppointmentDialog open appointmentUuid="a-1" onClose={() => {}} />,
);
await waitFor(() => expect(screen.getByText('بدون جریمه')).toBeInTheDocument());
expect(screen.getByText('در بازهٔ لغو رایگان است.')).toBeInTheDocument();
});
it('sends the typed reason along with the cancellation', async () => {
get.mockResolvedValue(preview());
const user = userEvent.setup();
renderWithProviders(
<CancelAppointmentDialog open appointmentUuid="a-1" onClose={() => {}} />,
);
await waitFor(() => expect(screen.getByText(/مبلغ پرداخت‌شده/)).toBeInTheDocument());
await user.type(screen.getByLabelText(/دلیل لغو/), 'بیمار تماس گرفت');
await user.click(screen.getByRole('button', { name: 'لغو نوبت' }));
await waitFor(() =>
expect(post).toHaveBeenCalledWith('/api/v1/appointment/a-1/cancel', {
by: 'doctor',
reason: 'بیمار تماس گرفت',
}),
);
});
/** پیش‌نمایشی که نیامده نباید لغو را قفل کند — ولی باید صریح بگوید که نیامده. */
it('still allows cancelling when the preview fails, and says so', async () => {
get.mockRejectedValue(new Error('down'));
renderWithProviders(
<CancelAppointmentDialog open appointmentUuid="a-1" onClose={() => {}} />,
);
await waitFor(() =>
expect(screen.getByText(/پیامد مالی لغو در دسترس نیست/)).toBeInTheDocument(),
);
expect(screen.getByRole('button', { name: 'لغو نوبت' })).not.toBeDisabled();
});
});
@@ -0,0 +1,123 @@
import React, { useState } from 'react';
import ConfirmDialog from './ui/ConfirmDialog';
import { useCancellationPreview, useCancelAppointment } from '../hooks/useCancellation';
import { formatRial } from '../lib/utils';
interface Props {
open: boolean;
appointmentUuid: string;
/** چه کسی لغو می‌کند — جریمه برای لغو کلینیک همیشه صفر است. */
by?: 'user' | 'doctor';
onClose: () => void;
onCancelled?: () => void;
}
/**
* لغو نوبت با نمایش پیامد مالی **قبل از** تأیید.
*
* پیش‌نمایش از همان محاسبه‌ای می‌آید که خودِ لغو انجام می‌دهد، پس عددی که اپراتور
* می‌بیند همان است که کسر می‌شود. دکمهٔ لغوِ بی‌پیش‌نمایش یعنی اپراتور جریمهٔ بیمار را
* بعد از وقوعش کشف می‌کند.
*/
export default function CancelAppointmentDialog({
open,
appointmentUuid,
by = 'doctor',
onClose,
onCancelled,
}: Props) {
const [reason, setReason] = useState('');
const { preview, loading } = useCancellationPreview(open ? appointmentUuid : undefined, by);
const cancel = useCancelAppointment();
const close = () => {
setReason('');
onClose();
};
return (
<ConfirmDialog
open={open}
title="لغو نوبت"
message="آیا از لغو این نوبت اطمینان دارید؟"
confirmLabel="لغو نوبت"
danger
loading={cancel.isPending}
onConfirm={() =>
cancel.mutate(
{ uuid: appointmentUuid, by, reason },
{
onSuccess: () => {
close();
onCancelled?.();
},
},
)
}
onCancel={close}
>
<div
style={{
marginTop: 14,
padding: 12,
borderRadius: 'var(--r-sm)',
background: 'var(--surface-2)',
fontSize: 13,
lineHeight: 1.9,
}}
>
{loading ? (
<span style={{ color: 'var(--text-3)' }}>در حال محاسبهٔ پیامد لغو</span>
) : !preview ? (
<span style={{ color: 'var(--text-3)' }}>
پیامد مالی لغو در دسترس نیست؛ لغو انجام میشود ولی مبلغ را دستی بررسی کنید.
</span>
) : (
<>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: 'var(--text-2)' }}>جریمهٔ لغو</span>
<strong style={{ color: preview.penalty_rials > 0 ? 'var(--danger)' : 'var(--success)' }}>
{preview.penalty_rials > 0 ? formatRial(preview.penalty_rials) : 'بدون جریمه'}
</strong>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: 'var(--text-2)' }}>مبلغ پرداختشده</span>
<span>{formatRial(preview.paid_rials)}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: 'var(--text-2)' }}>بازگشت اعتبار پکیج</span>
<span>{preview.credit_refundable ? 'بله' : 'خیر'}</span>
</div>
{preview.within_free_window && (
<div style={{ color: 'var(--success)' }}>در بازهٔ لغو رایگان است.</div>
)}
{preview.notes.map((note, i) => (
<div key={i} style={{ color: 'var(--text-3)', fontSize: 12 }}>
{note}
</div>
))}
</>
)}
</div>
<div style={{ marginTop: 14 }}>
<label className="cp-label mb-2" htmlFor="cancel-reason">
دلیل لغو (اختیاری)
</label>
<textarea
id="cancel-reason"
className="cp-input"
rows={2}
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="دلیل لغو نوبت را وارد کنید..."
style={{ width: '100%', resize: 'vertical' }}
/>
</div>
</ConfirmDialog>
);
}