feat(pricing): date-ranged price lists and immutable appointment invoices

Section 12 and the fifth closing rule: changing a price never changes an
already-booked appointment.

The pricing chain already existed and worked. Two things were missing. Tariff only
carries a year, so a rate change starting in Mehr could not be expressed — PriceList
now takes an explicit date range and Tariff remains the layer beneath it. And an
appointment stored a single number, so after a price change or a discount nobody
could say what those 2,400,000 rials were made of.

Price resolution walks four layers per service and takes the first hit: branch
override, then the covering price list, then the yearly tariff, then the service's own
price. The last one is the guarantee that a date no list covers still returns a price
rather than zero or an exception. breakdown.sources reports which layer answered, so a
surprising number can be traced instead of guessed at.

Two calculation decisions worth stating. Tax is computed on the patient's share, not
the gross — a patient does not pay tax on the portion the insurer covers. And a
discount larger than the amount floors the total at zero rather than going negative,
because a negative balance would mean the clinic owes the patient money, which nothing
downstream is built to mean.

A branch-specific list deliberately does not count as overlapping a general one; it
takes precedence instead. Treating them as a conflict would have made per-branch
exceptions impossible to express. Lists have no effect until activated, so drafting
next quarter's prices cannot disturb today's.

PriceSnapshot has no setters and a unique key on appointment_id: a snapshot that can
be edited is not a snapshot, and two invoices for one appointment would be two truths.
Corrections are a new row plus voiding the old one. Invoices are written during
confirm with the prices of that moment — computing later would let a rate change
between booking and invoicing produce a different number, which is exactly what rule
five forbids.

12 tests. The one that matters is
testBookedAppointmentKeepsItsOriginalInvoiceAfterAPriceChange: book, double the
service price, watch quote return the new number while the appointment's invoice
returns the old one. Without it rule five is only a claim.

1220 tests / 3551 assertions. phpstan back at its 14-error baseline. Frozen slot
contract green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-31 09:42:21 +03:30
co-authored by Claude Opus 5
parent cd12fabe14
commit 34b07421bd
17 changed files with 1765 additions and 66 deletions
@@ -0,0 +1,264 @@
<?php
namespace App\Pricing\Controller;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Branch\Service\BranchResolver;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Repository\ServiceItemRepository;
use App\Pricing\Entity\PriceList;
use App\Pricing\Entity\PriceListItem;
use App\Pricing\Repository\PriceListItemRepository;
use App\Pricing\Repository\PriceListRepository;
use App\Pricing\Repository\PriceSnapshotRepository;
use App\Pricing\Service\PricingEngine;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
use App\Shared\Tenant\TenantOwnershipChecker;
use Doctrine\ORM\EntityManagerInterface;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[OA\Tag(name: 'Pricing')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class PricingController extends BaseController
{
public function __construct(
private readonly PriceListRepository $lists,
private readonly PriceListItemRepository $listItems,
private readonly PriceSnapshotRepository $snapshots,
private readonly ServiceItemRepository $items,
private readonly PricingEngine $engine,
private readonly BranchResolver $branches,
private readonly TenantOwnershipChecker $ownership,
private readonly EntityManagerInterface $em,
) {}
#[Route('/api/v1/price-lists', name: 'price_list_index', methods: ['GET'])]
public function index(#[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->branches->pair($user);
return $this->success(array_map(
static fn (PriceList $l): array => $l->toArray(),
$this->lists->findForPair($entityType, $entityId),
));
}
#[Route('/api/v1/price-lists', name: 'price_list_create', methods: ['POST'])]
public function create(#[CurrentUser] User $user, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_string($data['name'] ?? null) || trim($data['name']) === '') {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'نام لیست قیمت الزامی است', 422, 'name');
}
if (!is_numeric($data['starts_at'] ?? null) || !is_numeric($data['ends_at'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بازهٔ تاریخ الزامی است', 422, 'starts_at');
}
[$entityType, $entityId] = $this->branches->pair($user);
try {
$list = new PriceList($entityType, $entityId, trim($data['name']), (int) $data['starts_at'], (int) $data['ends_at']);
} catch (\InvalidArgumentException) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پایان بازه باید بعد از شروع آن باشد', 422, 'ends_at');
}
if (is_string($data['address_uuid'] ?? null)) {
$list->setAddress($this->branches->resolve($user, $data['address_uuid']));
}
$this->em->persist($list);
$this->em->flush();
return $this->success($list->toArray(), 201);
}
#[Route('/api/v1/price-list/{uuid}', name: 'price_list_show', methods: ['GET'])]
public function show(#[CurrentUser] User $user, string $uuid): JsonResponse
{
return $this->success($this->requireList($user, $uuid)->toArray());
}
#[Route('/api/v1/price-list/{uuid}', name: 'price_list_update', methods: ['PATCH'])]
public function update(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$list = $this->requireList($user, $uuid);
if (!is_array($data)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'بدنهٔ درخواست نامعتبر است', 422);
}
if (is_string($data['name'] ?? null) && trim($data['name']) !== '') {
$list->setName(trim($data['name']));
}
if (array_key_exists('active', $data)) {
$list->setActive((bool) $data['active']);
}
$this->em->flush();
return $this->success($list->toArray());
}
#[Route('/api/v1/price-list/{uuid}', name: 'price_list_delete', methods: ['DELETE'])]
public function delete(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$this->em->remove($this->requireList($user, $uuid));
$this->em->flush();
return $this->success(null);
}
#[Route('/api/v1/price-list/{uuid}/items', name: 'price_list_items_replace', methods: ['PUT'])]
public function replaceItems(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_array($data['items'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد items الزامی است', 422, 'items');
}
$list = $this->requireList($user, $uuid);
$resolved = [];
foreach ($data['items'] as $row) {
if (!is_array($row) || !is_string($row['service_uuid'] ?? null) || !is_numeric($row['price_rials'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'service_uuid و price_rials الزامی‌اند', 422, 'items');
}
if ((int) $row['price_rials'] < 0) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'قیمت نمی‌تواند منفی باشد', 422, 'price_rials');
}
$resolved[] = [$this->requireItem($user, $row['service_uuid']), (int) $row['price_rials']];
}
$this->listItems->deleteForList($list);
$list->getItems()->clear();
foreach ($resolved as [$service, $price]) {
$item = new PriceListItem($list, $service, $price);
$this->em->persist($item);
$list->getItems()->add($item);
}
$list->touch();
$this->em->flush();
return $this->success($list->toArray());
}
/**
* فعال‌سازی با بررسی تداخل: دو لیستِ فعالِ هم‌پوشان یعنی یک تاریخ دو قیمت دارد و
* هیچ‌کس نمی‌تواند بگوید کدام درست است.
*/
#[Route('/api/v1/price-list/{uuid}/activate', name: 'price_list_activate', methods: ['POST'])]
public function activate(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$list = $this->requireList($user, $uuid);
$conflicts = $this->lists->findOverlapping($list);
if ($conflicts !== []) {
return $this->error(
ErrorCodes::ERR_VALIDATION_001,
sprintf('بازهٔ این لیست با «%s» هم‌پوشانی دارد', $conflicts[0]->getName()),
422,
'starts_at',
);
}
$list->setActive(true);
$this->em->flush();
return $this->success($list->toArray());
}
#[Route('/api/v1/pricing/quote', name: 'pricing_quote', methods: ['POST'])]
public function quote(#[CurrentUser] User $user, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_string($data['service_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد service_uuid الزامی است', 422, 'service_uuid');
}
if (!is_string($data['branch_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد branch_uuid الزامی است', 422, 'branch_uuid');
}
$service = $this->requireItem($user, $data['service_uuid']);
$address = $this->branches->resolve($user, $data['branch_uuid']);
$items = [];
foreach (($data['item_uuids'] ?? []) as $itemUuid) {
if (is_string($itemUuid)) {
$items[] = $this->requireItem($user, $itemUuid);
}
}
$at = is_numeric($data['at'] ?? null) ? (int) $data['at'] : time();
$policy = is_array($data['policy'] ?? null) ? $data['policy'] : [];
return $this->success($this->engine->quote($service, $items, $address, $at, $policy)->toArray());
}
/**
* فاکتور تفکیک‌شدهٔ نوبت — همان اعدادِ لحظهٔ ثبت، حتی اگر قیمت‌ها بعداً عوض شده باشند.
*/
#[Route('/api/v1/appointment/{uuid}/price-snapshot', name: 'appointment_price_snapshot', methods: ['GET'])]
public function snapshot(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$appointment = $this->em->getRepository(Appointment::class)->findOneBy(['uuid' => $uuid]);
[$entityType, $entityId] = $this->branches->pair($user);
if ($appointment === null || !$this->ownership->belongsToPair($entityType, $entityId, $appointment)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'نوبت یافت نشد', 404);
}
$snapshot = $this->snapshots->findForAppointment($appointment);
if ($snapshot === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'برای این نوبت فاکتوری ثبت نشده است', 404);
}
return $this->success($snapshot->toArray());
}
private function requireList(User $user, string $uuid): PriceList
{
$list = $this->lists->findByUuid($uuid);
[$entityType, $entityId] = $this->branches->pair($user);
if ($list === null || !$this->ownership->belongsToPair($entityType, $entityId, $list)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'لیست قیمت یافت نشد', 404);
}
return $list;
}
private function requireItem(User $user, string $uuid): ServiceItem
{
$item = $this->items->findByUuid($uuid);
[$entityType, $entityId] = $this->branches->pair($user);
if ($item === null
|| $item->getSection()->getEntityType() !== $entityType
|| $item->getSection()->getEntityId() !== $entityId
) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'سرویس یافت نشد', 404);
}
return $item;
}
}