From 5fb4c522468998f850400f78867e94fd1b895a2a Mon Sep 17 00:00:00 2001 From: hamed <15238-genius.ha@users.noreply.drupalcode.org> Date: Mon, 13 Jul 2026 15:35:10 +0330 Subject: [PATCH] =?UTF-8?q?feat(patients):=20phase=20B4=20=E2=80=94=20mess?= =?UTF-8?q?ages=20(=D9=BE=DB=8C=D8=A7=D9=85=E2=80=8C=D9=87=D8=A7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a patient message/communication log: a new PatientMessage entity (record-scoped, CASCADE) + repository, and owner-scoped endpoints (GET messages, POST message, DELETE message) with a validated channel (sms/note/call/email). Wire the "پیام‌ها" tab in PatientDetailPage (send box + list + delete). PHPUnit covers create/list/delete + ownership + validation; Vitest covers the tab. API docs updated. Co-Authored-By: Claude Opus 4.8 (1M context) --- assets/admin/pages/PatientDetailPage.test.tsx | 11 ++- assets/admin/pages/PatientDetailPage.tsx | 60 ++++++++++++++++ docs/api/patient.md | 26 +++++++ migrations/Version20260713120038.php | 33 +++++++++ src/Patient/Controller/PatientController.php | 57 +++++++++++++++ src/Patient/Entity/PatientMessage.php | 59 ++++++++++++++++ .../Repository/PatientMessageRepository.php | 44 ++++++++++++ tests/Patient/PatientMessageTest.php | 69 +++++++++++++++++++ 8 files changed, 358 insertions(+), 1 deletion(-) create mode 100644 migrations/Version20260713120038.php create mode 100644 src/Patient/Entity/PatientMessage.php create mode 100644 src/Patient/Repository/PatientMessageRepository.php create mode 100644 tests/Patient/PatientMessageTest.php diff --git a/assets/admin/pages/PatientDetailPage.test.tsx b/assets/admin/pages/PatientDetailPage.test.tsx index bad053b4..978bd91b 100644 --- a/assets/admin/pages/PatientDetailPage.test.tsx +++ b/assets/admin/pages/PatientDetailPage.test.tsx @@ -55,7 +55,7 @@ describe('PatientDetailPage (پرونده تب‌دار)', () => { it('shows a placeholder for not-yet-built tabs', async () => { renderDetail(); await screen.findByText('ساغر صابری'); - fireEvent.click(screen.getByText('پیام‌ها')); + fireEvent.click(screen.getByText('کال سنتر')); expect(screen.getByText(/به‌زودی تکمیل می‌شود/)).toBeInTheDocument(); }); @@ -75,4 +75,13 @@ describe('PatientDetailPage (پرونده تب‌دار)', () => { // modal opens with a title field expect(await screen.findByPlaceholderText('مثلاً: معاینه اولیه')).toBeInTheDocument(); }); + + it('renders the messages tab with a send box', async () => { + renderDetail(); + await screen.findByText('ساغر صابری'); + fireEvent.click(screen.getByText('پیام‌ها')); + expect(await screen.findByPlaceholderText('متن پیام...')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'ارسال' })).toBeInTheDocument(); + expect(await screen.findByText('پیامی ثبت نشده است.')).toBeInTheDocument(); + }); }); diff --git a/assets/admin/pages/PatientDetailPage.tsx b/assets/admin/pages/PatientDetailPage.tsx index e2bd7f6a..46bb3e85 100644 --- a/assets/admin/pages/PatientDetailPage.tsx +++ b/assets/admin/pages/PatientDetailPage.tsx @@ -131,6 +131,8 @@ export default function PatientDetailPage() { ) : tab === 'records' ? ( + ) : tab === 'messages' ? ( + ) : ( t.key === tab)!.label} /> )} @@ -324,6 +326,64 @@ function MedicalRecordsTab({ uuid }: { uuid: string }) { ); } +interface Message { uuid: string; body: string; channel: string; created_at: number } + +const CHANNEL_LABEL: Record = { sms: 'پیامک', note: 'یادداشت', call: 'تماس', email: 'ایمیل' }; + +/** پیام‌ها — patient message/communication log: send + list + delete. */ +function MessagesTab({ uuid }: { uuid: string }) { + const qc = useQueryClient(); + const [body, setBody] = useState(''); + + const { data, isLoading } = useQuery>({ + queryKey: ['patient-messages', uuid], + queryFn: () => api.get(`/api/v1/patient/${uuid}/messages`), + }); + const items = data?.data ?? []; + const invalidate = () => qc.invalidateQueries({ queryKey: ['patient-messages', uuid] }); + + const send = useMutation({ + mutationFn: () => api.post(`/api/v1/patient/${uuid}/message`, { body, channel: 'sms' }), + onSuccess: () => { invalidate(); setBody(''); toast.success('پیام ثبت شد'); }, + onError: (e: any) => toast.error(e.message), + }); + const del = useMutation({ + mutationFn: (u: string) => api.delete(`/api/v1/patient/message/${u}`), + onSuccess: () => { invalidate(); toast.success('پیام حذف شد'); }, + onError: (e: any) => toast.error(e.message), + }); + + return ( +
+
+
setBody(e.target.value)} placeholder="متن پیام..." />
+ +
+ + {isLoading ? ( +
در حال بارگذاری...
+ ) : items.length === 0 ? ( +
پیامی ثبت نشده است.
+ ) : ( +
+ {items.map((m) => ( +
+
+
{m.body}
+
+ {CHANNEL_LABEL[m.channel] ?? m.channel} + {formatDate(m.created_at)} +
+
+ +
+ ))} +
+ )} +
+ ); +} + function TabList({ q, emptyLabel, row }: { q: { data?: ApiResponse; isLoading: boolean }; emptyLabel: string; diff --git a/docs/api/patient.md b/docs/api/patient.md index 8e7f9233..0101464e 100644 --- a/docs/api/patient.md +++ b/docs/api/patient.md @@ -535,3 +535,29 @@ When an appointment's status changes to `confirmed` via `PATCH /api/v1/appointme |------|------|-------------| | 422 | `ERR_VALIDATION_001` | عنوان خالی (`field: title`) | | 404 | `ERR_PATIENT_001` / `ERR_NOT_FOUND_001` | رکورد/رکورد پزشکی یافت نشد یا tenant دیگر | + +--- + +## پیام‌های بیمار (Messages) + +لاگ پیام‌ها/ارتباطات با بیمار (SMS/یادداشت/تماس). scope به رکورد و tenant. + +**Permission:** `IS_AUTHENTICATED_FULLY` (مالک رکورد) + +### GET `/api/v1/patient/{uuid}/messages` +لیست (جدیدترین اول). Response: `{ success, data: [{ uuid, body, channel, created_at }] }` + +### POST `/api/v1/patient/{uuid}/message` +```json +{ "body": "متن پیام", "channel": "sms|note|call|email (اختیاری، پیش‌فرض sms)" } +``` +`body` الزامی؛ `channel` نامعتبر → `sms`. Response `201`. + +### DELETE `/api/v1/patient/message/{uuid}` +حذف. فقط مالک؛ در غیر این صورت `404`. + +### Errors +| HTTP | Code | Description | +|------|------|-------------| +| 422 | `ERR_VALIDATION_001` | متن خالی (`field: body`) | +| 404 | `ERR_PATIENT_001` / `ERR_NOT_FOUND_001` | رکورد/پیام یافت نشد یا tenant دیگر | diff --git a/migrations/Version20260713120038.php b/migrations/Version20260713120038.php new file mode 100644 index 00000000..a94f4e3a --- /dev/null +++ b/migrations/Version20260713120038.php @@ -0,0 +1,33 @@ +addSql('CREATE TABLE patient_messages (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, body LONGTEXT NOT NULL, channel VARCHAR(20) NOT NULL, created_at INT NOT NULL, record_id INT NOT NULL, UNIQUE INDEX UNIQ_EC874633D17F50A6 (uuid), INDEX idx_patient_messages_record (record_id), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4'); + $this->addSql('ALTER TABLE patient_messages ADD CONSTRAINT FK_EC8746334DFD750C 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_messages DROP FOREIGN KEY FK_EC8746334DFD750C'); + $this->addSql('DROP TABLE patient_messages'); + } +} diff --git a/src/Patient/Controller/PatientController.php b/src/Patient/Controller/PatientController.php index 2e20205e..eaeb9956 100644 --- a/src/Patient/Controller/PatientController.php +++ b/src/Patient/Controller/PatientController.php @@ -52,10 +52,67 @@ class PatientController extends BaseController private readonly \App\Tag\Repository\TenantTagRepository $tenantTagRepo, private readonly \App\Patient\Repository\PatientAttachmentRepository $attachmentRepo, private readonly \App\Patient\Repository\PatientMedicalRecordRepository $medicalRepo, + private readonly \App\Patient\Repository\PatientMessageRepository $messageRepo, private readonly \App\Shared\Service\FileUploadService $fileUpload, private readonly LoggerInterface $logger, ) {} + // ── Messages (پیام‌ها) ───────────────────────────────────────────────────── + + #[Route('/api/v1/patient/{uuid}/messages', methods: ['GET'])] + public function listMessages(string $uuid, #[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); + } + + return $this->success(array_map( + fn(\App\Patient\Entity\PatientMessage $m) => $m->toArray(), + $this->messageRepo->findByRecord($record) + )); + } + + #[Route('/api/v1/patient/{uuid}/message', methods: ['POST'])] + public function createMessage(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) ?? []; + $body = trim((string) ($data['body'] ?? '')); + if ($body === '') { + return $this->error(ErrorCodes::ERR_VALIDATION_001, 'متن پیام الزامی است', 422, 'body'); + } + + $channel = (string) ($data['channel'] ?? 'sms'); + if (!in_array($channel, ['sms', 'note', 'call', 'email'], true)) { + $channel = 'sms'; + } + $message = new \App\Patient\Entity\PatientMessage($record, $body, $channel); + $this->messageRepo->save($message); + + return $this->success($message->toArray(), 201); + } + + #[Route('/api/v1/patient/message/{uuid}', methods: ['DELETE'])] + public function deleteMessage(string $uuid, #[CurrentUser] User $user): JsonResponse + { + [$entityType, $entityId] = $this->resolveEntity($user); + $message = $this->messageRepo->findByUuid($uuid); + if ($message === null || !$this->ownsRecord($message->getRecord(), $entityType, $entityId)) { + return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'پیام یافت نشد', 404); + } + + $this->messageRepo->remove($message); + + return $this->success(['message' => 'پیام حذف شد']); + } + // ── Medical records (پرونده پزشکی) ──────────────────────────────────────── #[Route('/api/v1/patient/{uuid}/medical-records', methods: ['GET'])] diff --git a/src/Patient/Entity/PatientMessage.php b/src/Patient/Entity/PatientMessage.php new file mode 100644 index 00000000..a30b46f1 --- /dev/null +++ b/src/Patient/Entity/PatientMessage.php @@ -0,0 +1,59 @@ +uuid = Uuid::v4()->toRfc4122(); + $this->record = $record; + $this->body = $body; + $this->channel = $channel; + $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 toArray(): array + { + return [ + 'uuid' => $this->uuid, + 'body' => $this->body, + 'channel' => $this->channel, + 'created_at' => $this->createdAt, + ]; + } +} diff --git a/src/Patient/Repository/PatientMessageRepository.php b/src/Patient/Repository/PatientMessageRepository.php new file mode 100644 index 00000000..b830fb37 --- /dev/null +++ b/src/Patient/Repository/PatientMessageRepository.php @@ -0,0 +1,44 @@ +findOneBy(['uuid' => $uuid]); + } + + /** @return PatientMessage[] */ + public function findByRecord(PatientRecord $record): array + { + return $this->createQueryBuilder('m') + ->where('m.record = :record') + ->setParameter('record', $record) + ->orderBy('m.id', 'DESC') + ->getQuery() + ->getResult(); + } + + public function save(PatientMessage $m): void + { + $this->getEntityManager()->persist($m); + $this->getEntityManager()->flush(); + } + + public function remove(PatientMessage $m): void + { + $this->getEntityManager()->remove($m); + $this->getEntityManager()->flush(); + } +} diff --git a/tests/Patient/PatientMessageTest.php b/tests/Patient/PatientMessageTest.php new file mode 100644 index 00000000..733bebff --- /dev/null +++ b/tests/Patient/PatientMessageTest.php @@ -0,0 +1,69 @@ +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() . '/message', $owner, [ + 'body' => 'یادآوری نوبت فردا', 'channel' => 'sms', + ]); + self::assertSame(201, $this->responseCode()); + self::assertSame('یادآوری نوبت فردا', $created['data']['body']); + self::assertSame('sms', $created['data']['channel']); + $mUuid = $created['data']['uuid']; + + $list = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/messages', $owner); + self::assertCount(1, $list['data']); + + $this->authJson('DELETE', '/api/v1/patient/message/' . $mUuid, $owner); + self::assertSame(200, $this->responseCode()); + + $after = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/messages', $owner); + self::assertCount(0, $after['data']); + } + + public function testRequiresBody(): void + { + [$owner, $record] = $this->recordFor(); + $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/message', $owner, ['body' => '']); + self::assertSame(422, $this->responseCode()); + } + + public function testOwnershipScoped(): void + { + [$owner, $record] = $this->recordFor(); + $created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/message', $owner, ['body' => 'x']); + $mUuid = $created['data']['uuid']; + + [$other] = $this->recordFor(); + $this->authJson('DELETE', '/api/v1/patient/message/' . $mUuid, $other); + self::assertSame(404, $this->responseCode()); + } +}