feat(patients): phase B4 — messages (پیامها)
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) <noreply@anthropic.com>
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -131,6 +131,8 @@ export default function PatientDetailPage() {
|
||||
<AttachmentsTab uuid={uuid!} />
|
||||
) : tab === 'records' ? (
|
||||
<MedicalRecordsTab uuid={uuid!} />
|
||||
) : tab === 'messages' ? (
|
||||
<MessagesTab uuid={uuid!} />
|
||||
) : (
|
||||
<Placeholder label={TABS.find((t) => 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<string, string> = { 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<ApiResponse<Message[]>>({
|
||||
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 (
|
||||
<div>
|
||||
<div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
|
||||
<div className="field" style={{ flex: 1 }}><input value={body} onChange={(e) => setBody(e.target.value)} placeholder="متن پیام..." /></div>
|
||||
<button className="btn primary" disabled={!body.trim() || send.isPending} onClick={() => send.mutate()}>ارسال</button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div style={{ padding: 16, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : items.length === 0 ? (
|
||||
<div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)', fontSize: 14 }}>پیامی ثبت نشده است.</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{items.map((m) => (
|
||||
<div key={m.uuid} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 13.5, color: 'var(--text)', whiteSpace: 'pre-wrap' }}>{m.body}</div>
|
||||
<div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 4, display: 'flex', gap: 8 }}>
|
||||
<span className="badge gray" style={{ fontSize: 10.5 }}>{CHANNEL_LABEL[m.channel] ?? m.channel}</span>
|
||||
<span>{formatDate(m.created_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn sm ghost" aria-label="حذف" style={{ color: 'var(--danger)' }} onClick={() => del.mutate(m.uuid)}><TrashIcon style={{ width: 15 }} /></button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TabList({ q, emptyLabel, row }: {
|
||||
q: { data?: ApiResponse<any[]>; isLoading: boolean };
|
||||
emptyLabel: string;
|
||||
|
||||
@@ -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 دیگر |
|
||||
|
||||
@@ -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 Version20260713120038 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_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');
|
||||
}
|
||||
}
|
||||
@@ -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'])]
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Patient\Entity;
|
||||
|
||||
use App\Patient\Repository\PatientMessageRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/** A logged message/communication with a patient (the «پیامها» tab). */
|
||||
#[ORM\Entity(repositoryClass: PatientMessageRepository::class)]
|
||||
#[ORM\Table(name: 'patient_messages')]
|
||||
#[ORM\Index(columns: ['record_id'], name: 'idx_patient_messages_record')]
|
||||
class PatientMessage
|
||||
{
|
||||
#[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;
|
||||
|
||||
#[ORM\Column(type: 'text')]
|
||||
private string $body;
|
||||
|
||||
/** Channel: sms | note | call | email … */
|
||||
#[ORM\Column(type: 'string', length: 20)]
|
||||
private string $channel = 'sms';
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
public function __construct(PatientRecord $record, string $body, string $channel = 'sms')
|
||||
{
|
||||
$this->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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Patient\Repository;
|
||||
|
||||
use App\Patient\Entity\PatientMessage;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class PatientMessageRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, PatientMessage::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?PatientMessage
|
||||
{
|
||||
return $this->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Patient;
|
||||
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* Patient messages: create, list, delete + tenant ownership scoping.
|
||||
*/
|
||||
class PatientMessageTest 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() . '/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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user