feat: add optional inventory package association to service items and implement audit logging

- Added `inventory_package_uuid` and `inventory_package_title` fields to the `ServiceItem` interface.
- Updated API documentation to reflect new fields in service item responses.
- Implemented methods in `ClinicServiceController` to handle inventory package associations.
- Created `ServiceItemAuditLog` entity and repository for tracking changes to service items.
- Added functionality to log changes to service items, including inventory package associations.
- Implemented tests for attaching/detaching inventory packages and auditing changes.
- Created database migrations for new fields and audit log table.
This commit is contained in:
hamed
2026-07-18 12:26:15 +03:30
parent 42d9ad26c5
commit c4a661b542
14 changed files with 885 additions and 24 deletions
@@ -4,16 +4,20 @@ namespace App\ClinicService\Controller;
use App\Auth\Entity\User;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceItemAuditLog;
use App\ClinicService\Entity\ServiceSection;
use App\Insurance\Entity\TenantServiceCoverage;
use App\ClinicService\Entity\Tariff;
use Doctrine\ORM\EntityManagerInterface;
use App\ClinicService\Repository\ServiceItemAuditLogRepository;
use App\ClinicService\Repository\ServiceItemRepository;
use App\ClinicService\Repository\ServiceSectionRepository;
use App\ClinicService\Repository\TariffRepository;
use App\ClinicService\Service\ServiceItemAuditService;
use App\ClinicService\Service\TariffService;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Inventory\Repository\InventoryPackageRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
@@ -39,9 +43,61 @@ class ClinicServiceController extends BaseController
private readonly ClinicRepository $clinicRepo,
private readonly TariffRepository $tariffRepo,
private readonly TariffService $tariffService,
private readonly InventoryPackageRepository $packageRepo,
private readonly ServiceItemAuditService $auditService,
private readonly ServiceItemAuditLogRepository $auditLogRepo,
private readonly EntityManagerInterface $em,
) {}
/**
* uuid و عنوان پکیج کالای هر سرویس را به آرایه‌ی خروجی اضافه می‌کند. پکیج‌ها با یک
* کوئری واکشی می‌شوند تا فهرست سرویس‌ها به N+1 نیفتد.
*
* @param ServiceItem[] $items
* @return array<int, array<string, mixed>>
*/
private function serializeItems(array $items): array
{
$packages = $this->packageRepo->findMapByIds(
array_map(fn(ServiceItem $i) => $i->getInventoryPackageId(), $items)
);
return array_map(function (ServiceItem $i) use ($packages) {
$row = $i->toArray();
$package = $packages[$i->getInventoryPackageId()] ?? null;
$row['inventory_package_uuid'] = $package?->getUuid();
$row['inventory_package_title'] = $package?->getTitle();
return $row;
}, $items);
}
/**
* `inventory_package_uuid` را به id داخلی تبدیل و روی سرویس ست می‌کند.
* مقدار null یعنی قطع اتصال. خطای دسترسی/نبود پکیج را برمی‌گرداند.
*/
private function applyInventoryPackage(ServiceItem $item, array $data, string $entityType, ?int $entityId): ?JsonResponse
{
if (!array_key_exists('inventory_package_uuid', $data)) {
return null;
}
$uuid = $data['inventory_package_uuid'];
if ($uuid === null || $uuid === '') {
$item->setInventoryPackageId(null);
return null;
}
$package = $this->packageRepo->findByUuid((string) $uuid);
if ($package === null || $package->getEntityType() !== $entityType || $package->getEntityId() !== $entityId) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پکیج کالا یافت نشد', 422, 'inventory_package_uuid');
}
$item->setInventoryPackageId($package->getId());
return null;
}
// ── Service Sections ─────────────────────────────────────────────────────
#[Route('/api/v1/service-sections', methods: ['GET'])]
@@ -128,12 +184,9 @@ class ClinicServiceController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$items = array_map(
fn(ServiceItem $i) => $i->toArray(),
return $this->success($this->serializeItems(
$this->itemRepo->findByEntity($entityType, $entityId)
);
return $this->success($items);
));
}
#[Route('/api/v1/service-items/{sectionUuid}', methods: ['GET'])]
@@ -146,12 +199,7 @@ class ClinicServiceController extends BaseController
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
}
$items = array_map(
fn(ServiceItem $i) => $i->toArray(),
$this->itemRepo->findBySection($section)
);
return $this->success($items);
return $this->success($this->serializeItems($this->itemRepo->findBySection($section)));
}
#[Route('/api/v1/service-item/{uuid}', methods: ['GET'])]
@@ -164,7 +212,24 @@ class ClinicServiceController extends BaseController
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
}
return $this->success($item->toArray());
return $this->success($this->serializeItems([$item])[0]);
}
/** تاریخچه‌ی تغییرات یک خدمت — تازه‌ترین رویداد اول. */
#[Route('/api/v1/service-item/{uuid}/audit-logs', methods: ['GET'])]
public function listItemAuditLogs(string $uuid, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
$item = $this->itemRepo->findByUuid($uuid);
if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
}
return $this->success(array_map(
fn(ServiceItemAuditLog $l) => $l->toArray(),
$this->auditLogRepo->findByItem($item)
));
}
#[Route('/api/v1/service-item', methods: ['POST'])]
@@ -206,13 +271,18 @@ class ClinicServiceController extends BaseController
if (array_key_exists('bookable', $data)) {
$item->setBookable((bool) $data['bookable']);
}
$packageError = $this->applyInventoryPackage($item, $data, $entityType, $entityId);
if ($packageError !== null) {
return $packageError;
}
$this->itemRepo->save($item);
// قیمت سرویس همان تعرفه‌ی سال جاری است؛ هنگام ساخت، تعرفه‌ی سال جاری ثبت می‌شود.
$this->tariffService->upsert($item->getId(), $this->tariffService->currentJalaliYear(), $item->getPriceRials());
$this->auditService->logCreate($item, $user);
return $this->success($item->toArray(), 201);
return $this->success($this->serializeItems([$item])[0], 201);
}
#[Route('/api/v1/service-item/{uuid}', methods: ['PATCH'])]
@@ -225,7 +295,8 @@ class ClinicServiceController extends BaseController
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
}
$data = json_decode($request->getContent(), true) ?? [];
$data = json_decode($request->getContent(), true) ?? [];
$before = $this->auditService->snapshot($item);
$priceChanged = false;
if (isset($data['name']) && trim($data['name']) !== '') { $item->setName(trim($data['name'])); }
@@ -250,6 +321,10 @@ class ClinicServiceController extends BaseController
if (array_key_exists('bookable', $data)) {
$item->setBookable((bool) $data['bookable']);
}
$packageError = $this->applyInventoryPackage($item, $data, $entityType, $entityId);
if ($packageError !== null) {
return $packageError;
}
$this->itemRepo->save($item);
@@ -258,7 +333,9 @@ class ClinicServiceController extends BaseController
$this->tariffService->upsert($item->getId(), $this->tariffService->currentJalaliYear(), $item->getPriceRials());
}
return $this->success($item->toArray());
$this->auditService->logChanges($item, $before, $this->auditService->snapshot($item), $user);
return $this->success($this->serializeItems([$item])[0]);
}
#[Route('/api/v1/service-item/{uuid}', methods: ['DELETE'])]
+11
View File
@@ -62,6 +62,14 @@ class ServiceItem
#[ORM\Column(type: 'boolean', options: ['default' => false])]
private bool $bookable = false;
/**
* پکیج کالای مصرفی این خدمت ({@see \App\Inventory\Entity\InventoryPackage}).
* ارجاع خام int بدون FK — همان الگوی Tariff و TenantServiceCoverage — تا دامنهٔ
* ClinicService به Inventory وابسته نشود.
*/
#[ORM\Column(name: 'inventory_package_id', type: 'integer', nullable: true)]
private ?int $inventoryPackageId = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
@@ -90,6 +98,7 @@ class ServiceItem
public function getInsurancePriceRials(): ?int { return $this->insurancePriceRials; }
public function getDurationMinutes(): ?int { return $this->durationMinutes; }
public function isBookable(): bool { return $this->bookable; }
public function getInventoryPackageId(): ?int { return $this->inventoryPackageId; }
public function getCreatedAt(): int { return $this->createdAt; }
public function getUpdatedAt(): int { return $this->updatedAt; }
@@ -128,6 +137,7 @@ class ServiceItem
public function setInsurancePriceRials(?int $v): self { $this->insurancePriceRials = $v; $this->updatedAt = time(); return $this; }
public function setDurationMinutes(?int $v): self { $this->durationMinutes = $v; $this->updatedAt = time(); return $this; }
public function setBookable(bool $v): self { $this->bookable = $v; $this->updatedAt = time(); return $this; }
public function setInventoryPackageId(?int $v): self { $this->inventoryPackageId = $v; $this->updatedAt = time(); return $this; }
public function toArray(): array
{
@@ -159,6 +169,7 @@ class ServiceItem
'insurance_price_rials' => $this->insurancePriceRials,
'duration_minutes' => $this->durationMinutes,
'bookable' => $this->bookable,
'inventory_package_id' => $this->inventoryPackageId,
'created_at' => $this->createdAt,
'updated_at' => $this->updatedAt,
];
@@ -0,0 +1,81 @@
<?php
namespace App\ClinicService\Entity;
use App\ClinicService\Repository\ServiceItemAuditLogRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* تاریخچه‌ی تغییرات یک خدمت: چه کسی، چه فیلدی را، کِی و از چه مقداری به چه مقداری
* تغییر داد. هم‌شکل {@see \App\Patient\Entity\SessionAuditLog} است تا الگوی لاگ در
* سراسر پروژه یکسان بماند.
*/
#[ORM\Entity(repositoryClass: ServiceItemAuditLogRepository::class)]
#[ORM\Table(name: 'service_item_audit_logs')]
#[ORM\Index(columns: ['service_item_id', 'created_at'], name: 'idx_service_item_audit_item')]
class ServiceItemAuditLog
{
public const OP_CREATE = 'create';
public const OP_UPDATE = 'update';
#[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: ServiceItem::class)]
#[ORM\JoinColumn(name: 'service_item_id', nullable: false, onDelete: 'CASCADE')]
private ServiceItem $serviceItem;
#[ORM\Column(type: 'string', length: 40)]
private string $field;
#[ORM\Column(type: 'string', length: 10)]
private string $operation;
#[ORM\Column(name: 'old_value', type: 'text', nullable: true)]
private ?string $oldValue = null;
#[ORM\Column(name: 'new_value', type: 'text', nullable: true)]
private ?string $newValue = null;
#[ORM\Column(name: 'actor_user_id', type: 'integer', nullable: true)]
private ?int $actorUserId = null;
#[ORM\Column(name: 'actor_name', type: 'string', length: 191, nullable: true)]
private ?string $actorName = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(ServiceItem $serviceItem, string $field, string $operation)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->serviceItem = $serviceItem;
$this->field = $field;
$this->operation = $operation;
$this->createdAt = time();
}
public function setActor(?int $userId, ?string $name): self { $this->actorUserId = $userId; $this->actorName = $name; return $this; }
public function setValues(?string $old, ?string $new): self { $this->oldValue = $old; $this->newValue = $new; return $this; }
public function getUuid(): string { return $this->uuid; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'field' => $this->field,
'operation' => $this->operation,
'old_value' => $this->oldValue,
'new_value' => $this->newValue,
'actor_name' => $this->actorName,
'created_at' => $this->createdAt,
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\ClinicService\Repository;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceItemAuditLog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class ServiceItemAuditLogRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ServiceItemAuditLog::class);
}
public function save(ServiceItemAuditLog $log, bool $flush = true): void
{
$this->getEntityManager()->persist($log);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function flush(): void
{
$this->getEntityManager()->flush();
}
/** @return ServiceItemAuditLog[] تازه‌ترین رویداد اول. */
public function findByItem(ServiceItem $item, int $limit = 100): array
{
return $this->createQueryBuilder('l')
->where('l.serviceItem = :item')
->setParameter('item', $item)
->orderBy('l.createdAt', 'DESC')
->addOrderBy('l.id', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
}
@@ -0,0 +1,89 @@
<?php
namespace App\ClinicService\Service;
use App\Auth\Entity\User;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceItemAuditLog;
use App\ClinicService\Repository\ServiceItemAuditLogRepository;
/**
* ثبت تاریخچه‌ی تغییرات خدمات. کنترلر فقط snapshot قبل و بعد را می‌دهد؛ تشخیص
* فیلدهای تغییریافته اینجا انجام می‌شود.
*/
class ServiceItemAuditService
{
/** فیلدهایی که تغییرشان لاگ می‌شود (کلید = نام فیلد در لاگ). */
private const TRACKED = [
'name' => 'نام سرویس',
'price_rials' => 'قیمت پایه',
'active' => 'وضعیت',
'duration_minutes' => 'زمان متوسط',
'bookable' => 'نمایش در نوبت‌دهی',
'insurance_covered' => 'پوشش بیمه',
'inventory_package' => 'پکیج کالا',
];
public function __construct(private readonly ServiceItemAuditLogRepository $repo) {}
/** @return array<string, string|null> snapshot قابل مقایسه از وضعیت فعلی خدمت. */
public function snapshot(ServiceItem $item): array
{
return [
'name' => $item->getName(),
'price_rials' => (string) $item->getPriceRials(),
'active' => $item->isActive() ? '1' : '0',
'duration_minutes' => $item->getDurationMinutes() === null ? null : (string) $item->getDurationMinutes(),
'bookable' => $item->isBookable() ? '1' : '0',
'insurance_covered' => $item->isInsuranceCovered() ? '1' : '0',
'inventory_package' => $item->getInventoryPackageId() === null ? null : (string) $item->getInventoryPackageId(),
];
}
public function logCreate(ServiceItem $item, ?User $actor): void
{
$this->repo->save(
(new ServiceItemAuditLog($item, 'name', ServiceItemAuditLog::OP_CREATE))
->setActor($actor?->getId(), $this->actorName($actor))
->setValues(null, $item->getName())
);
}
/**
* تفاوت دو snapshot را لاگ می‌کند. فیلد بدون تغییر ردیف نمی‌سازد.
*
* @param array<string, string|null> $before
* @param array<string, string|null> $after
*/
public function logChanges(ServiceItem $item, array $before, array $after, ?User $actor): void
{
$logged = false;
foreach (array_keys(self::TRACKED) as $field) {
if (($before[$field] ?? null) === ($after[$field] ?? null)) {
continue;
}
$this->repo->save(
(new ServiceItemAuditLog($item, $field, ServiceItemAuditLog::OP_UPDATE))
->setActor($actor?->getId(), $this->actorName($actor))
->setValues($before[$field] ?? null, $after[$field] ?? null),
false,
);
$logged = true;
}
if ($logged) {
$this->repo->flush();
}
}
private function actorName(?User $actor): ?string
{
if ($actor === null) {
return null;
}
return $actor->getRealName() ?: $actor->getMobileNumber();
}
}
@@ -32,6 +32,28 @@ class InventoryPackageRepository extends ServiceEntityRepository
->getResult();
}
/**
* پکیج‌ها را با یک کوئری برمی‌گرداند (کلید = id) تا سریالایز کردن فهرست سرویس‌ها
* به find()-per-row نیفتد.
*
* @param int[] $ids
* @return array<int, InventoryPackage>
*/
public function findMapByIds(array $ids): array
{
$ids = array_values(array_unique(array_filter($ids)));
if ($ids === []) {
return [];
}
$map = [];
foreach ($this->findBy(['id' => $ids]) as $package) {
$map[$package->getId()] = $package;
}
return $map;
}
public function save(InventoryPackage $package): void
{
$this->getEntityManager()->persist($package);