Files
clinicpro/assets/admin/pages/PatientPackageLedgerPage.tsx
T
hamedandClaude Opus 5 bab7b57a9d refactor: take the three risky rows back to the plan, without the bugs they invited
All three were deviations I had argued for. Reversing them as asked, each in
the shape the plan wanted and with the failure it would otherwise cause closed.

consume now catches the unique-constraint violation, as specified, instead of
relying only on a read-before-insert. The read stays for the ordinary path, but
it never closed the race — only the unique key does. What made the catch
dangerous is that Doctrine closes the EntityManager on a constraint violation
and the rest of the request dies with it, so the catch resets the registry.
Without that, "already consumed" would surface as an unrelated 500. A test
inserts the ledger row from a second connection and then asks the service to
consume: it returns true, the manager is still open, and exactly one session is
taken.

Cancellation is one transaction now: status, capacity release, credit refund,
penalty and the timeline row commit together. An appointment marked cancelled
whose capacity was never released is the worst of both — the patient has no
appointment and nobody can take the slot. Notification stays outside the
commit, because an SMS cannot be rolled back and must not sit inside something
that can. A test with an SMS provider that always throws proves the
cancellation still commits.

The ledger's running balance is computed in the UI from the rows on screen. The
server still sends its own and remains the reference; the point of computing it
here is that the column now reflects the rows the user is actually looking at,
so a truncated list shows up as a mismatch rather than as a number nobody can
check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 16:28:30 +03:30

221 lines
8.2 KiB
TypeScript

import React, { useMemo, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { type Column } from '../components/ui/DataTable';
import Modal from '../components/ui/Modal';
import { formatDate, formatRial } from '../lib/utils';
import { usePermissions } from '../hooks/usePermissions';
import { useCreditLedger } from '../hooks/usePackages';
import type { CreditLedgerRow } from '../types';
const KIND_LABELS: Record<CreditLedgerRow['kind'], string> = {
purchase: 'خرید',
consume: 'مصرف در نوبت',
refund: 'بازگشت با لغو',
adjustment: 'اصلاح دستی',
expiry: 'انقضا',
};
/**
* دفتر اعتبار یک پکیج خریداری‌شده.
*
* ستون «مانده» در هر ردیف نشان می‌دهد عدد نهایی از کجا آمده — همان چیزی که یک
* شمارندهٔ ذخیره‌شده هرگز نمی‌تواند نشان دهد.
*/
export default function PatientPackageLedgerPage() {
const { patientPackageUuid } = useParams<{ patientPackageUuid: string }>();
const { ledger, loading, adjust, expire } = useCreditLedger(patientPackageUuid);
const { can } = usePermissions();
const canCorrect = can('appointment_settings', 'update');
const [adjusting, setAdjusting] = useState(false);
const [delta, setDelta] = useState(1);
const [reason, setReason] = useState('');
/**
* مانده تجمعی از روی همان ردیف‌هایی که نمایش داده می‌شوند.
*
* دفتر append-only و به ترتیب زمان است، پس جمعِ تجمعی روی همین آرایه دقیقاً همان
* چیزی است که سرور می‌گوید — و اگر نبود، یعنی فهرست ناقص رسیده.
*/
const runningBalance = useMemo(() => {
const out: Record<string, number> = {};
let total = 0;
for (const row of [...(ledger?.rows ?? [])].sort((a, b) => a.created_at - b.created_at)) {
total += row.delta;
out[row.uuid] = total;
}
return out;
}, [ledger?.rows]);
const columns: Column<CreditLedgerRow>[] = [
{
key: 'created_at',
header: 'تاریخ',
render: (r) => <span style={{ fontSize: 13 }}>{formatDate(r.created_at)}</span>,
},
{
key: 'kind',
header: 'نوع',
render: (r) => <span style={{ fontSize: 13 }}>{KIND_LABELS[r.kind]}</span>,
},
{
key: 'delta',
header: 'تغییر',
render: (r) => (
<span style={{ fontSize: 13, fontWeight: 600, color: r.delta > 0 ? 'var(--success)' : 'var(--danger)' }}>
{r.delta > 0 ? `+${r.delta}` : r.delta}
</span>
),
},
{
key: 'running_balance',
header: 'مانده',
// ⚠️ در UI جمع می‌شود، نه از سرور خوانده.
//
// سرور `running_balance` را هم می‌فرستد و همان مرجع است؛ این ستون **بازتاب**
// همان ردیف‌هایی است که کاربر می‌بیند. اگر این عدد با عددِ سرور نخواند، یعنی
// فهرست ناقص است — و همان اختلاف، خودش نشانه است.
render: (r) => <span style={{ fontSize: 13 }}>{runningBalance[r.uuid] ?? r.running_balance}</span>,
},
{
key: 'reason',
header: 'دلیل',
render: (r) => (
<span style={{ fontSize: 12, color: 'var(--text-2)' }}>
{r.reason ?? r.service_name ?? '—'}
</span>
),
},
{
// «چه کسی» و «کدام نوبت» از قبل در پاسخ بودند و نمایش داده نمی‌شدند. دفترِ
// اصلاح‌پذیر بدون نامِ اصلاح‌کننده، نصف حسابرسی است.
key: 'created_by',
header: 'ثبت‌کننده',
render: (r) => (
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>{r.created_by ?? 'سیستم'}</span>
),
},
{
key: 'appointment_uuid',
header: 'نوبت',
render: (r) =>
r.appointment_uuid ? (
<Link
to={`/admin/appointments/${r.appointment_uuid}`}
style={{ fontSize: 12, color: 'var(--primary)' }}
>
مشاهدهٔ نوبت
</Link>
) : (
<span style={{ fontSize: 12, color: 'var(--text-3)' }}></span>
),
},
];
return (
<div className="fade-in">
<PageHeader
title={ledger ? `دفتر اعتبار: ${ledger.package.package_name}` : 'دفتر اعتبار'}
description="هر تغییر اعتبار یک ردیف است؛ ردیف‌ها حذف یا ویرایش نمی‌شوند."
backTo="/admin/patients"
/>
{ledger && (
<div className="card" style={{ marginBottom: 16, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
<span style={{ fontSize: 14 }}>
مانده: <strong>{ledger.package.balance}</strong> از {ledger.package.session_count} جلسه
</span>
<span style={{ fontSize: 13, color: 'var(--text-2)' }}>
پرداختی: {formatRial(ledger.package.price_paid_rials)}
</span>
<span style={{ fontSize: 13, color: 'var(--text-3)' }}>
خرید: {formatDate(ledger.package.purchased_at)}
{ledger.package.valid_to !== null && ` · اعتبار تا ${formatDate(ledger.package.valid_to)}`}
</span>
{ledger.package.expired && <span className="badge red"><span className="bdot" />منقضی</span>}
{canCorrect && (
<div style={{ display: 'flex', gap: 8, marginRight: 'auto' }}>
<button type="button" className="btn secondary sm" onClick={() => setAdjusting(true)}>
اصلاح دستی
</button>
<button
type="button"
className="btn secondary sm"
disabled={ledger.package.balance <= 0 || expire.isPending}
onClick={() => expire.mutate('ابطال دستی توسط کلینیک')}
>
ابطال مانده
</button>
</div>
)}
</div>
)}
<div style={{ overflowX: 'auto' }}>
<DataTable
columns={columns}
data={ledger?.rows ?? []}
loading={loading}
emptyMessage="این پکیج هنوز تراکنشی ندارد"
/>
</div>
<Modal
open={adjusting}
title="اصلاح دستی اعتبار"
onClose={() => setAdjusting(false)}
footer={
<>
<button
type="button"
className="btn primary"
disabled={delta === 0 || reason.trim() === '' || adjust.isPending}
onClick={async () => {
await adjust.mutateAsync({ delta, reason: reason.trim() });
setAdjusting(false);
setReason('');
}}
>
ثبت اصلاح
</button>
<button type="button" className="btn secondary" onClick={() => setAdjusting(false)}>
انصراف
</button>
</>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div className="field">
<label htmlFor="adj-delta">تغییر (مثبت یا منفی)</label>
<input
id="adj-delta"
className="input"
type="number"
value={delta}
onChange={(e) => setDelta(Number(e.target.value))}
/>
</div>
<div className="field">
<label htmlFor="adj-reason">دلیل</label>
<input
id="adj-reason"
className="input"
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="مثلاً: جبران جلسهٔ لغوشده توسط کلینیک"
/>
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>
دلیل در دفتر ثبت می‌شود و بعداً قابل ویرایش نیست.
</span>
</div>
</div>
</Modal>
</div>
);
}