feat(patients): phase B2 — attachments (ضمیمه)

Add patient file attachments: a new PatientAttachment entity (record-scoped,
CASCADE) + repository, and endpoints GET /patient/{uuid}/attachments,
POST /patient/{uuid}/attachment (raw-body upload) and DELETE
/patient/attachment/{uuid} (owner-scoped). Factor the shared raw-body upload
logic into FileUploadService. Wire the "ضمیمه" tab in PatientDetailPage
(upload + list + delete). PHPUnit covers list/delete/ownership; Vitest covers
the tab. API docs updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-13 15:20:00 +03:30
co-authored by Claude Opus 4.8
parent 4c52316a49
commit 537bb8c7b3
10 changed files with 446 additions and 2 deletions
@@ -50,9 +50,64 @@ class PatientController extends BaseController
private readonly \App\Appointment\Repository\AppointmentRepository $appointmentRepo,
private readonly \App\ClinicInvitation\Repository\ClinicDoctorInvitationRepository $invitationRepo,
private readonly \App\Tag\Repository\TenantTagRepository $tenantTagRepo,
private readonly \App\Patient\Repository\PatientAttachmentRepository $attachmentRepo,
private readonly \App\Shared\Service\FileUploadService $fileUpload,
private readonly LoggerInterface $logger,
) {}
// ── Attachments (ضمیمه) ───────────────────────────────────────────────────
#[Route('/api/v1/patient/{uuid}/attachments', methods: ['GET'])]
public function listAttachments(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\PatientAttachment $a) => $a->toArray(),
$this->attachmentRepo->findByRecord($record)
));
}
#[Route('/api/v1/patient/{uuid}/attachment', methods: ['POST'])]
public function uploadAttachment(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);
}
try {
$stored = $this->fileUpload->storeFromRequest($request, 'patients/attachments');
} catch (\RuntimeException $e) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, $e->getMessage(), 422);
}
$name = trim((string) $request->query->get('name', '')) ?: $stored['filename'];
$attachment = new \App\Patient\Entity\PatientAttachment($record, $name, $stored['url'], $stored['filemime'], $stored['size']);
$this->attachmentRepo->save($attachment);
return $this->success($attachment->toArray(), 201);
}
#[Route('/api/v1/patient/attachment/{uuid}', methods: ['DELETE'])]
public function deleteAttachment(string $uuid, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
$attachment = $this->attachmentRepo->findByUuid($uuid);
if ($attachment === null || !$this->ownsRecord($attachment->getRecord(), $entityType, $entityId)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'ضمیمه یافت نشد', 404);
}
$this->attachmentRepo->remove($attachment);
return $this->success(['message' => 'ضمیمه حذف شد']);
}
/**
* Assign record labels from the payload (`tags` = array of TenantTag uuids),
* scoped to the caller's entity. Returns a 422 response on a foreign tag,
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace App\Patient\Entity;
use App\Patient\Repository\PatientAttachmentRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/** A file attached to a patient record (the «ضمیمه» tab). */
#[ORM\Entity(repositoryClass: PatientAttachmentRepository::class)]
#[ORM\Table(name: 'patient_attachments')]
#[ORM\Index(columns: ['record_id'], name: 'idx_patient_attachments_record')]
class PatientAttachment
{
#[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: 'string', length: 200)]
private string $name;
#[ORM\Column(type: 'string', length: 500)]
private string $url;
#[ORM\Column(type: 'string', length: 100, nullable: true)]
private ?string $mime = null;
#[ORM\Column(type: 'integer', nullable: true)]
private ?int $size = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(PatientRecord $record, string $name, string $url, ?string $mime = null, ?int $size = null)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->record = $record;
$this->name = $name;
$this->url = $url;
$this->mime = $mime;
$this->size = $size;
$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 getUrl(): string { return $this->url; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'name' => $this->name,
'url' => $this->url,
'mime' => $this->mime,
'size' => $this->size,
'created_at' => $this->createdAt,
];
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Patient\Repository;
use App\Patient\Entity\PatientAttachment;
use App\Patient\Entity\PatientRecord;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class PatientAttachmentRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, PatientAttachment::class);
}
public function findByUuid(string $uuid): ?PatientAttachment
{
return $this->findOneBy(['uuid' => $uuid]);
}
/** @return PatientAttachment[] */
public function findByRecord(PatientRecord $record): array
{
return $this->createQueryBuilder('a')
->where('a.record = :record')
->setParameter('record', $record)
->orderBy('a.id', 'DESC')
->getQuery()
->getResult();
}
public function save(PatientAttachment $a): void
{
$this->getEntityManager()->persist($a);
$this->getEntityManager()->flush();
}
public function remove(PatientAttachment $a): void
{
$this->getEntityManager()->remove($a);
$this->getEntityManager()->flush();
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Shared\Service;
use Symfony\Component\HttpFoundation\Request;
/**
* Stores a raw-body file upload (the `/file/upload/...` convention: the file is
* sent as the request body with a Content-Disposition filename) under
* public/uploads/<subDir>/<year>-<month>/ and returns its public URL + metadata.
*/
class FileUploadService
{
public function __construct(
private readonly FileValidatorService $fileValidator,
private readonly string $projectDir,
) {}
/**
* @return array{url: string, filename: string, filemime: string, size: int}
* @throws \RuntimeException on an invalid/oversized file
*/
public function storeFromRequest(Request $request, string $subDir): array
{
$content = $request->getContent();
preg_match('/filename=["\']?([^"\';\s]+)["\']?/i', $request->headers->get('Content-Disposition', ''), $m);
$filename = $m[1] ?? 'file';
$tmpPath = sys_get_temp_dir() . '/' . uniqid('upload_', true);
file_put_contents($tmpPath, $content);
try {
$safeFilename = $this->fileValidator->sanitizeFilename($filename);
$mime = $this->fileValidator->detectMimeType($tmpPath);
$year = date('Y');
$month = date('m');
$dir = $this->projectDir . '/public/uploads/' . $subDir . '/' . $year . '-' . $month;
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$storedName = uniqid('', true) . '_' . $safeFilename;
rename($tmpPath, $dir . '/' . $storedName);
return [
'url' => '/uploads/' . $subDir . '/' . $year . '-' . $month . '/' . $storedName,
'filename' => $safeFilename,
'filemime' => $mime,
'size' => strlen($content),
];
} catch (\Throwable $e) {
if (file_exists($tmpPath)) {
unlink($tmpPath);
}
throw new \RuntimeException($e->getMessage(), 0, $e);
}
}
}