feat(patients): phase D — call-center tab (patient call log)
Add a record-scoped PatientCall entity (subject, summary, outcome
success/missed, called_at, personnel) with its repository and three
owner-gated endpoints on PatientController:
GET /patient/{uuid}/calls — call log, newest first, optional ?outcome
POST /patient/{uuid}/call — log a call (subject required)
DELETE /patient/call/{uuid} — delete an entry
Wire the previously-placeholder "کال سنتر" tab as a CallCenterTab: a register
form (date/time/subject/summary + success/missed toggle, personnel taken from
the logged-in user) beside a filterable call history (all / success / missed).
With this every patient-detail tab is now backed by a real endpoint, so the
generic Placeholder is no longer reachable. PatientCallTest covers create/list/
delete, the outcome filter, the invalid-outcome fallback, and ownership scoping.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -59,11 +59,14 @@ describe('PatientDetailPage (پرونده تبدار)', () => {
|
||||
expect(screen.getByText('اینستاگرام')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a placeholder for not-yet-built tabs', async () => {
|
||||
it('renders the call-center tab with a register form and history', async () => {
|
||||
renderDetail();
|
||||
await screen.findByText('ساغر صابری');
|
||||
fireEvent.click(screen.getByText('کال سنتر'));
|
||||
expect(screen.getByText(/بهزودی تکمیل میشود/)).toBeInTheDocument();
|
||||
expect(await screen.findByText('ثبت تماس جدید')).toBeInTheDocument();
|
||||
expect(screen.getByText('تاریخچه تماسها')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('موضوع تماس')).toBeInTheDocument();
|
||||
expect(await screen.findByText('تماسی ثبت نشده است.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the attachments tab with an upload button', async () => {
|
||||
|
||||
@@ -146,6 +146,8 @@ export default function PatientDetailPage() {
|
||||
row={(p) => ({ title: formatRial(p.amount_rials), meta: [p.created_at ? formatDate(p.created_at) : '', p.gateway].filter(Boolean).join(' · '), badge: PAYMENT_STATUS[p.status] || p.status })} />
|
||||
) : tab === 'wallet' ? (
|
||||
<WalletTab uuid={uuid!} />
|
||||
) : tab === 'callcenter' ? (
|
||||
<CallCenterTab uuid={uuid!} />
|
||||
) : tab === 'attach' ? (
|
||||
<AttachmentsTab uuid={uuid!} />
|
||||
) : tab === 'records' ? (
|
||||
@@ -403,6 +405,116 @@ function MessagesTab({ uuid }: { uuid: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
interface Call { uuid: string; subject: string; summary?: string | null; outcome: string; called_at: number; personnel?: string | null }
|
||||
|
||||
/** کال سنتر — patient call log: register a call + filterable history (all / success / missed). */
|
||||
function CallCenterTab({ uuid }: { uuid: string }) {
|
||||
const qc = useQueryClient();
|
||||
const userName = useAuthStore((s) => s.userName);
|
||||
const [filter, setFilter] = useState<'all' | 'success' | 'missed'>('all');
|
||||
const [date, setDate] = useState('');
|
||||
const [time, setTime] = useState('');
|
||||
const [subject, setSubject] = useState('');
|
||||
const [summary, setSummary] = useState('');
|
||||
const [outcome, setOutcome] = useState<'success' | 'missed'>('success');
|
||||
|
||||
const { data, isLoading } = useQuery<ApiResponse<Call[]>>({
|
||||
queryKey: ['patient-calls', uuid],
|
||||
queryFn: () => api.get(`/api/v1/patient/${uuid}/calls`),
|
||||
});
|
||||
const calls = data?.data ?? [];
|
||||
const shown = filter === 'all' ? calls : calls.filter((c) => c.outcome === filter);
|
||||
const successCount = calls.filter((c) => c.outcome === 'success').length;
|
||||
const missedCount = calls.filter((c) => c.outcome === 'missed').length;
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ['patient-calls', uuid] });
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () => {
|
||||
const iso = date ? `${date}T${time || '00:00'}` : null;
|
||||
const calledAt = iso ? Math.floor(new Date(iso).getTime() / 1000) : Math.floor(Date.now() / 1000);
|
||||
return api.post(`/api/v1/patient/${uuid}/call`, { subject, summary, outcome, called_at: calledAt, personnel: userName });
|
||||
},
|
||||
onSuccess: () => { invalidate(); setDate(''); setTime(''); setSubject(''); setSummary(''); setOutcome('success'); toast.success('تماس ثبت شد'); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
const del = useMutation({
|
||||
mutationFn: (u: string) => api.delete(`/api/v1/patient/call/${u}`),
|
||||
onSuccess: () => { invalidate(); toast.success('تماس حذف شد'); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const chip = (key: 'all' | 'success' | 'missed', label: string) => (
|
||||
<button onClick={() => setFilter(key)} style={{
|
||||
padding: '6px 14px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', cursor: 'pointer',
|
||||
fontFamily: 'inherit', fontSize: 13, fontWeight: filter === key ? 700 : 500,
|
||||
background: filter === key ? 'var(--primary-soft)' : 'var(--surface)',
|
||||
color: filter === key ? 'var(--primary)' : 'var(--text-2)',
|
||||
}}>{label}</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 20, alignItems: 'flex-start', flexWrap: 'wrap' }}>
|
||||
{/* register form */}
|
||||
<div style={{ width: 320, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 18 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, textAlign: 'center', marginBottom: 16 }}>ثبت تماس جدید</div>
|
||||
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>تاریخ تماس</label>
|
||||
<div style={{ margin: '6px 0 12px' }}><PersianDateInput value={date} onChange={setDate} /></div>
|
||||
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>ساعت تماس</label>
|
||||
<div className="field" style={{ margin: '6px 0 12px' }}><input type="time" value={time} onChange={(e) => setTime(e.target.value)} dir="ltr" /></div>
|
||||
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>موضوع تماس</label>
|
||||
<div className="field" style={{ margin: '6px 0 12px' }}><input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="موضوع تماس" /></div>
|
||||
<label style={{ fontSize: 12.5, color: 'var(--text-3)' }}>خلاصه تماس</label>
|
||||
<div className="field" style={{ height: 'auto', margin: '6px 0 12px' }}><textarea value={summary} onChange={(e) => setSummary(e.target.value)} rows={3} placeholder="خلاصه تماس" style={{ width: '100%', border: 'none', background: 'transparent', fontFamily: 'inherit', resize: 'vertical' }} /></div>
|
||||
<div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
|
||||
<button onClick={() => setOutcome('success')} style={{ flex: 1, padding: '8px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, background: outcome === 'success' ? 'var(--success-bg)' : 'var(--surface)', color: outcome === 'success' ? 'var(--success)' : 'var(--text-2)', fontWeight: outcome === 'success' ? 700 : 500 }}>موفق</button>
|
||||
<button onClick={() => setOutcome('missed')} style={{ flex: 1, padding: '8px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, background: outcome === 'missed' ? 'var(--danger-bg)' : 'var(--surface)', color: outcome === 'missed' ? 'var(--danger)' : 'var(--text-2)', fontWeight: outcome === 'missed' ? 700 : 500 }}>بیپاسخ</button>
|
||||
</div>
|
||||
<button className="btn primary" style={{ width: '100%' }} disabled={!subject.trim() || create.isPending} onClick={() => create.mutate()}><PlusIcon style={{ width: 16 }} /> ثبت تماس</button>
|
||||
</div>
|
||||
|
||||
{/* history */}
|
||||
<div style={{ flex: 1, minWidth: 320 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, flexWrap: 'wrap', gap: 8 }}>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
{chip('all', 'همه')}
|
||||
{chip('success', `تماسهای موفق (${successCount})`)}
|
||||
{chip('missed', `بیپاسخ (${missedCount})`)}
|
||||
</div>
|
||||
<div style={{ fontSize: 14, fontWeight: 700 }}>تاریخچه تماسها</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div style={{ padding: 16, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : shown.length === 0 ? (
|
||||
<div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>تماسی ثبت نشده است.</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{shown.map((c) => {
|
||||
const ok = c.outcome === 'success';
|
||||
return (
|
||||
<div key={c.uuid} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderInlineStart: `4px solid ${ok ? 'var(--success)' : 'var(--danger)'}`, borderRadius: 'var(--r-lg)', padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<PhoneArrowUpRightIcon style={{ width: 16, color: ok ? 'var(--success)' : 'var(--danger)' }} />
|
||||
<span style={{ fontSize: 13.5, fontWeight: 700 }}>{c.subject}</span>
|
||||
</div>
|
||||
{c.summary && <div style={{ fontSize: 12.5, color: 'var(--text-2)', marginTop: 4 }}>{c.summary}</div>}
|
||||
</div>
|
||||
<div style={{ textAlign: 'end', minWidth: 120 }}>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-3)' }}>{formatDate(c.called_at)}</div>
|
||||
{c.personnel && <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>{c.personnel}</div>}
|
||||
<button className="btn sm ghost" aria-label="حذف" style={{ color: 'var(--danger)', marginTop: 4 }} onClick={() => del.mutate(c.uuid)}><TrashIcon style={{ width: 14 }} /></button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface WalletTxn { uuid: string; amount_rials: number; type: string; description?: string | null; balance_after: number; created_at: number }
|
||||
|
||||
/** کیف پول — patient wallet balance card + recent-transaction ledger. */
|
||||
|
||||
@@ -586,3 +586,30 @@ Response: `{ success, data: [{ uuid, amount_rials, type, description, balance_af
|
||||
| HTTP | Code | Description |
|
||||
|------|------|-------------|
|
||||
| 404 | `ERR_PATIENT_001` | رکورد یافت نشد یا متعلق به مالک دیگر |
|
||||
|
||||
---
|
||||
|
||||
## کال سنتر بیمار (Call Center)
|
||||
|
||||
لاگ تماسهای تلفنی با بیمار (تب «کال سنتر»). scope به رکورد و مالک.
|
||||
|
||||
**Permission:** `IS_AUTHENTICATED_FULLY` (مالک رکورد)
|
||||
|
||||
### GET `/api/v1/patient/{uuid}/calls`
|
||||
لیست (جدیدترین بر اساس `called_at`). Query: `outcome` (اختیاری: `success|missed`).
|
||||
Response: `{ success, data: [{ uuid, subject, summary, outcome, called_at, personnel, created_at }] }`
|
||||
|
||||
### POST `/api/v1/patient/{uuid}/call`
|
||||
```json
|
||||
{ "subject": "پیگیری نوبت", "summary": "اختیاری", "outcome": "success|missed (پیشفرض success)", "called_at": 1731000000, "personnel": "نام ثبتکننده (اختیاری)" }
|
||||
```
|
||||
`subject` الزامی؛ `outcome` نامعتبر → `success`؛ `called_at` غایب → اکنون. Response `201`.
|
||||
|
||||
### DELETE `/api/v1/patient/call/{uuid}`
|
||||
حذف. فقط مالک؛ در غیر این صورت `404`.
|
||||
|
||||
### Errors
|
||||
| HTTP | Code | Description |
|
||||
|------|------|-------------|
|
||||
| 422 | `ERR_VALIDATION_001` | موضوع خالی (`field: subject`) |
|
||||
| 404 | `ERR_PATIENT_001` | رکورد/تماس یافت نشد یا مالک دیگر |
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Auto-generated Migration: Please modify to your needs!
|
||||
*/
|
||||
final class Version20260713122600 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// this up() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('CREATE TABLE patient_calls (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, subject VARCHAR(255) NOT NULL, summary LONGTEXT DEFAULT NULL, outcome VARCHAR(10) NOT NULL, called_at INT NOT NULL, personnel VARCHAR(120) DEFAULT NULL, created_at INT NOT NULL, record_id INT NOT NULL, UNIQUE INDEX UNIQ_4F958740D17F50A6 (uuid), INDEX idx_patient_calls_record (record_id), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
|
||||
$this->addSql('ALTER TABLE patient_calls ADD CONSTRAINT FK_4F9587404DFD750C FOREIGN KEY (record_id) REFERENCES patient_records (id) ON DELETE CASCADE');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// this down() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('ALTER TABLE patient_calls DROP FOREIGN KEY FK_4F9587404DFD750C');
|
||||
$this->addSql('DROP TABLE patient_calls');
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ class PatientController extends BaseController
|
||||
private readonly \App\Patient\Repository\PatientAttachmentRepository $attachmentRepo,
|
||||
private readonly \App\Patient\Repository\PatientMedicalRecordRepository $medicalRepo,
|
||||
private readonly \App\Patient\Repository\PatientMessageRepository $messageRepo,
|
||||
private readonly \App\Patient\Repository\PatientCallRepository $callRepo,
|
||||
private readonly \App\Shared\Service\FileUploadService $fileUpload,
|
||||
private readonly \App\Payment\Repository\PaymentRepository $paymentRepo,
|
||||
private readonly \App\Settlement\Repository\WalletTransactionRepository $walletRepo,
|
||||
@@ -133,6 +134,78 @@ class PatientController extends BaseController
|
||||
return $this->paginated($txns, $this->walletRepo->countByUser($patient), $page, $limit);
|
||||
}
|
||||
|
||||
// ── Call center (کال سنتر) ─────────────────────────────────────────────────
|
||||
|
||||
/** List the patient's call log (newest first, optional ?outcome=success|missed). */
|
||||
#[Route('/api/v1/patient/{uuid}/calls', methods: ['GET'])]
|
||||
public function listCalls(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$record = $this->recordRepo->findByUuid($uuid);
|
||||
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
$outcome = $request->query->get('outcome');
|
||||
$outcome = in_array($outcome, ['success', 'missed'], true) ? $outcome : null;
|
||||
|
||||
return $this->success(array_map(
|
||||
fn(\App\Patient\Entity\PatientCall $c) => $c->toArray(),
|
||||
$this->callRepo->findByRecord($record, $outcome)
|
||||
));
|
||||
}
|
||||
|
||||
/** Log a new call. `subject` required; `outcome` defaults to success; `personnel`/`summary`/`called_at` optional. */
|
||||
#[Route('/api/v1/patient/{uuid}/call', methods: ['POST'])]
|
||||
public function createCall(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$record = $this->recordRepo->findByUuid($uuid);
|
||||
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$subject = trim((string) ($data['subject'] ?? ''));
|
||||
if ($subject === '') {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'موضوع تماس الزامی است', 422, 'subject');
|
||||
}
|
||||
|
||||
$outcome = (string) ($data['outcome'] ?? 'success');
|
||||
if (!in_array($outcome, ['success', 'missed'], true)) {
|
||||
$outcome = 'success';
|
||||
}
|
||||
$calledAt = isset($data['called_at']) ? (int) $data['called_at'] : null;
|
||||
|
||||
$call = new \App\Patient\Entity\PatientCall($record, $subject, $outcome, $calledAt);
|
||||
$summary = trim((string) ($data['summary'] ?? ''));
|
||||
if ($summary !== '') {
|
||||
$call->setSummary($summary);
|
||||
}
|
||||
$personnel = trim((string) ($data['personnel'] ?? ''));
|
||||
if ($personnel !== '') {
|
||||
$call->setPersonnel($personnel);
|
||||
}
|
||||
$this->callRepo->save($call);
|
||||
|
||||
return $this->success($call->toArray(), 201);
|
||||
}
|
||||
|
||||
/** Delete a call log entry. Owner-scoped; otherwise 404. */
|
||||
#[Route('/api/v1/patient/call/{uuid}', methods: ['DELETE'])]
|
||||
public function deleteCall(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
$call = $this->callRepo->findByUuid($uuid);
|
||||
if ($call === null || !$this->ownsRecord($call->getRecord(), $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
$this->callRepo->remove($call);
|
||||
|
||||
return $this->success(['deleted' => true]);
|
||||
}
|
||||
|
||||
// ── Messages (پیامها) ─────────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/patient/{uuid}/messages', methods: ['GET'])]
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Patient\Entity;
|
||||
|
||||
use App\Patient\Repository\PatientCallRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/** A logged phone call with a patient (the «کال سنتر» tab). */
|
||||
#[ORM\Entity(repositoryClass: PatientCallRepository::class)]
|
||||
#[ORM\Table(name: 'patient_calls')]
|
||||
#[ORM\Index(columns: ['record_id'], name: 'idx_patient_calls_record')]
|
||||
class PatientCall
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: PatientRecord::class)]
|
||||
#[ORM\JoinColumn(name: 'record_id', nullable: false, onDelete: 'CASCADE')]
|
||||
private PatientRecord $record;
|
||||
|
||||
/** موضوع تماس — short subject (e.g. «پیگیری نوبت»). */
|
||||
#[ORM\Column(type: 'string', length: 255)]
|
||||
private string $subject;
|
||||
|
||||
/** خلاصه تماس — free-text call summary. */
|
||||
#[ORM\Column(type: 'text', nullable: true)]
|
||||
private ?string $summary = null;
|
||||
|
||||
/** Call outcome: success | missed. */
|
||||
#[ORM\Column(type: 'string', length: 10)]
|
||||
private string $outcome = 'success';
|
||||
|
||||
/** When the call happened (Unix seconds); may differ from createdAt. */
|
||||
#[ORM\Column(name: 'called_at', type: 'integer')]
|
||||
private int $calledAt;
|
||||
|
||||
/** Display name of the staff member who logged the call. */
|
||||
#[ORM\Column(type: 'string', length: 120, nullable: true)]
|
||||
private ?string $personnel = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
public function __construct(PatientRecord $record, string $subject, string $outcome = 'success', ?int $calledAt = null)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->record = $record;
|
||||
$this->subject = $subject;
|
||||
$this->outcome = $outcome;
|
||||
$this->calledAt = $calledAt ?? time();
|
||||
$this->createdAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getRecord(): PatientRecord { return $this->record; }
|
||||
|
||||
public function setSummary(?string $s): self { $this->summary = $s; return $this; }
|
||||
public function setPersonnel(?string $p): self { $this->personnel = $p; return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'subject' => $this->subject,
|
||||
'summary' => $this->summary,
|
||||
'outcome' => $this->outcome,
|
||||
'called_at' => $this->calledAt,
|
||||
'personnel' => $this->personnel,
|
||||
'created_at' => $this->createdAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Patient\Repository;
|
||||
|
||||
use App\Patient\Entity\PatientCall;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class PatientCallRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, PatientCall::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?PatientCall
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Newest-first call log for a record, optionally filtered by outcome.
|
||||
*
|
||||
* @return PatientCall[]
|
||||
*/
|
||||
public function findByRecord(PatientRecord $record, ?string $outcome = null): array
|
||||
{
|
||||
$qb = $this->createQueryBuilder('c')
|
||||
->where('c.record = :record')
|
||||
->setParameter('record', $record)
|
||||
->orderBy('c.calledAt', 'DESC')
|
||||
->addOrderBy('c.id', 'DESC');
|
||||
|
||||
if ($outcome !== null) {
|
||||
$qb->andWhere('c.outcome = :outcome')->setParameter('outcome', $outcome);
|
||||
}
|
||||
|
||||
return $qb->getQuery()->getResult();
|
||||
}
|
||||
|
||||
public function save(PatientCall $c): void
|
||||
{
|
||||
$this->getEntityManager()->persist($c);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
public function remove(PatientCall $c): void
|
||||
{
|
||||
$this->getEntityManager()->remove($c);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Patient;
|
||||
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* Patient call log (کال سنتر): create, list, outcome filter, delete + ownership scoping.
|
||||
*/
|
||||
class PatientCallTest extends ApiTestCase
|
||||
{
|
||||
/** @return array{0: \App\Auth\Entity\User, 1: PatientRecord} */
|
||||
private function recordFor(): array
|
||||
{
|
||||
$owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$doctor = new Doctor($owner, 'دکتر');
|
||||
$this->em->persist($doctor);
|
||||
$this->em->flush();
|
||||
|
||||
$patient = $this->createUser(['ROLE_USER']);
|
||||
$record = new PatientRecord('doctor', $doctor->getId(), $patient, 'doctor', $doctor->getId());
|
||||
$this->em->persist($record);
|
||||
$this->em->flush();
|
||||
|
||||
return [$owner, $record];
|
||||
}
|
||||
|
||||
public function testCreateListDelete(): void
|
||||
{
|
||||
[$owner, $record] = $this->recordFor();
|
||||
|
||||
$created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/call', $owner, [
|
||||
'subject' => 'پیگیری نوبت', 'summary' => 'جابهجایی تاریخ', 'outcome' => 'success', 'personnel' => 'مریم امینی',
|
||||
]);
|
||||
self::assertSame(201, $this->responseCode());
|
||||
self::assertSame('پیگیری نوبت', $created['data']['subject']);
|
||||
self::assertSame('success', $created['data']['outcome']);
|
||||
self::assertSame('مریم امینی', $created['data']['personnel']);
|
||||
$cUuid = $created['data']['uuid'];
|
||||
|
||||
$list = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/calls', $owner);
|
||||
self::assertCount(1, $list['data']);
|
||||
|
||||
$this->authJson('DELETE', '/api/v1/patient/call/' . $cUuid, $owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
|
||||
$after = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/calls', $owner);
|
||||
self::assertCount(0, $after['data']);
|
||||
}
|
||||
|
||||
public function testRequiresSubject(): void
|
||||
{
|
||||
[$owner, $record] = $this->recordFor();
|
||||
$this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/call', $owner, ['subject' => '']);
|
||||
self::assertSame(422, $this->responseCode());
|
||||
}
|
||||
|
||||
public function testOutcomeFilter(): void
|
||||
{
|
||||
[$owner, $record] = $this->recordFor();
|
||||
$this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/call', $owner, ['subject' => 'a', 'outcome' => 'success']);
|
||||
$this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/call', $owner, ['subject' => 'b', 'outcome' => 'missed']);
|
||||
|
||||
$missed = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/calls?outcome=missed', $owner);
|
||||
self::assertCount(1, $missed['data']);
|
||||
self::assertSame('missed', $missed['data'][0]['outcome']);
|
||||
}
|
||||
|
||||
public function testInvalidOutcomeFallsBackToSuccess(): void
|
||||
{
|
||||
[$owner, $record] = $this->recordFor();
|
||||
$created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/call', $owner, [
|
||||
'subject' => 'x', 'outcome' => 'garbage',
|
||||
]);
|
||||
self::assertSame('success', $created['data']['outcome']);
|
||||
}
|
||||
|
||||
public function testOwnershipScoped(): void
|
||||
{
|
||||
[$owner, $record] = $this->recordFor();
|
||||
$created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/call', $owner, ['subject' => 'x']);
|
||||
$cUuid = $created['data']['uuid'];
|
||||
|
||||
[$other] = $this->recordFor();
|
||||
$this->authJson('DELETE', '/api/v1/patient/call/' . $cUuid, $other);
|
||||
self::assertSame(404, $this->responseCode());
|
||||
$this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/calls', $other);
|
||||
self::assertSame(404, $this->responseCode());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user