refactor(pricing): make the service the only price source
Price lists, annual tariffs and per-branch price overrides each answered
"what does this service cost?" differently, so a single date could carry
several answers and nobody could say which one was right. Price now lives
only on ServiceItem.price_rials, edited from the services page.
- drop PriceList/PriceListItem, their repositories and the seven
/api/v1/price-list(s) endpoints; PricingController keeps only quote and
the appointment price snapshot
- drop Tariff, TariffRepository, TariffService and the two
/service-items/{uuid}/tariffs endpoints; creating or repricing a service
no longer upserts a current-year tariff
- drop price_rials from ServiceBranchOverride; the entity stays for its
duration columns, which DurationCalculator and ServiceSelectionValidator
still read
- InvoiceService reads the item price directly
- PricingEngine collapses to a single source; breakdown.sources always
reports service_item, keeping the response contract intact
- remove the price-lists admin page, its route and settings-menu entry, the
tariff modal and the service detail tariffs tab; useAppointmentInvoice
moves to its own hook file
Migration drops price_lists, price_list_items, service_tariffs and the
override price column.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -212,7 +212,7 @@ class Appointment
|
||||
#[ORM\Column(name: 'insurance_service_category', type: 'string', length: 30, nullable: true, enumType: ServiceCategory::class)]
|
||||
private ?ServiceCategory $insuranceServiceCategory = null;
|
||||
|
||||
/** بیمهٔ پایهٔ انتخابشده؛ ارجاع خام int مثل TenantInsurance/Tariff. */
|
||||
/** بیمهٔ پایهٔ انتخابشده؛ ارجاع خام int مثل TenantInsurance. */
|
||||
#[ORM\Column(name: 'insurance_base_id', type: 'integer', nullable: true)]
|
||||
private ?int $insuranceBaseId = null;
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ use App\Billing\Entity\InvoiceItem;
|
||||
use App\Billing\Event\InvoiceFinalized;
|
||||
use App\Billing\Repository\InvoiceRepository;
|
||||
use App\Billing\ValueObject\Money;
|
||||
use App\ClinicService\Service\TariffService;
|
||||
use App\Insurance\Enum\ServiceCategory;
|
||||
use App\Insurance\Repository\InsuranceRepository;
|
||||
use App\Insurance\Service\TenantInsuranceService;
|
||||
@@ -19,7 +18,6 @@ class InvoiceService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly InvoiceRepository $invoiceRepo,
|
||||
private readonly TariffService $tariffService,
|
||||
private readonly TenantInsuranceService $tenantInsuranceService,
|
||||
private readonly BillingCalculator $calculator,
|
||||
private readonly PatientSessionRepository $sessionRepo,
|
||||
@@ -41,7 +39,7 @@ class InvoiceService
|
||||
|
||||
/**
|
||||
* ساخت Invoice از یک Encounter (PatientSession).
|
||||
* تعرفهی هر خدمت از Tariff سال جاری (با fallback)، پوشش از قرارداد بیمهی tenant.
|
||||
* قیمت هر خدمت از خودِ سرویس، پوشش از قرارداد بیمهی tenant.
|
||||
* ویزیت بهعنوان یک آیتم جداگانه با همان قانون پوشش لحاظ میشود.
|
||||
*/
|
||||
public function createFromSession(PatientSession $session, string $entityType, int $entityId): Invoice
|
||||
@@ -76,7 +74,7 @@ class InvoiceService
|
||||
foreach ($session->getServices() as $sessionService) {
|
||||
$item = $sessionService->getServiceItem();
|
||||
$qty = max(1, $sessionService->getQuantity());
|
||||
$unitPrice = $this->tariffService->resolvePrice($item);
|
||||
$unitPrice = $item->getPriceRials();
|
||||
$total = new Money($unitPrice * $qty);
|
||||
|
||||
$baseRule = $this->tenantInsuranceService->coverageRuleForService($entityType, $entityId, $baseId, $item->getId());
|
||||
|
||||
@@ -8,7 +8,6 @@ use App\ClinicService\Entity\ServiceItemAuditLog;
|
||||
use App\ClinicService\Entity\ServiceSection;
|
||||
use App\Insurance\Entity\TenantServiceCoverage;
|
||||
use App\Insurance\Enum\ServiceCategory;
|
||||
use App\ClinicService\Entity\Tariff;
|
||||
use App\Clinic\Security\ClinicDoctorAccessChecker;
|
||||
use App\Secretary\Security\SecretaryAccessChecker;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
@@ -16,9 +15,7 @@ use App\ClinicService\Repository\CatalogCategoryRepository;
|
||||
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\Inventory\Repository\InventoryItemRepository;
|
||||
use App\Inventory\Repository\InventoryPackageRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
@@ -44,8 +41,6 @@ class ClinicServiceController extends BaseController
|
||||
private readonly ServiceItemRepository $itemRepo,
|
||||
private readonly ClinicStaffRepository $staffRepo,
|
||||
private readonly SubscriptionService $subscriptionService,
|
||||
private readonly TariffRepository $tariffRepo,
|
||||
private readonly TariffService $tariffService,
|
||||
private readonly InventoryPackageRepository $packageRepo,
|
||||
private readonly \App\Appointment\Plan\Repository\SegmentTemplateRepository $segmentRepo,
|
||||
private readonly InventoryItemRepository $inventoryItemRepo,
|
||||
@@ -426,8 +421,6 @@ class ClinicServiceController extends BaseController
|
||||
|
||||
$this->itemRepo->save($item);
|
||||
|
||||
// قیمت سرویس همان تعرفهی سال جاری است؛ هنگام ساخت، تعرفهی سال جاری ثبت میشود.
|
||||
$this->tariffService->upsert($item->getId(), $this->tariffService->currentJalaliYear(), $item->getPriceRials());
|
||||
$this->auditService->logCreate($item, $user);
|
||||
|
||||
return $this->success($this->serializeItems([$item])[0], 201);
|
||||
@@ -447,9 +440,8 @@ class ClinicServiceController extends BaseController
|
||||
$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'])); }
|
||||
if (isset($data['price_rials'])) { $item->setPriceRials((int) $data['price_rials']); $priceChanged = true; }
|
||||
if (isset($data['price_rials'])) { $item->setPriceRials((int) $data['price_rials']); }
|
||||
if (isset($data['active'])) { $item->setActive((bool) $data['active']); }
|
||||
if (array_key_exists('staff_uuids', $data) || array_key_exists('staff_uuid', $data)) {
|
||||
$staffError = $this->applyStaffMembers($item, $data, $entityType, $entityId);
|
||||
@@ -484,11 +476,6 @@ class ClinicServiceController extends BaseController
|
||||
|
||||
$this->itemRepo->save($item);
|
||||
|
||||
// اگر قیمت پایه تغییر کرد، تعرفهی سال جاری هم همگام میشود (قیمت واحد).
|
||||
if ($priceChanged) {
|
||||
$this->tariffService->upsert($item->getId(), $this->tariffService->currentJalaliYear(), $item->getPriceRials());
|
||||
}
|
||||
|
||||
$this->auditService->logChanges($item, $before, $this->auditService->snapshot($item), $user);
|
||||
|
||||
return $this->success($this->serializeItems([$item])[0]);
|
||||
@@ -508,59 +495,6 @@ class ClinicServiceController extends BaseController
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tariffs (تعرفهی نسخهدار سالانه) ──────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/service-items/{uuid}/tariffs', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function listTariffs(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$this->denyServices($user, 'view');
|
||||
[$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);
|
||||
}
|
||||
|
||||
$tariffs = $this->tariffRepo->findByService($item->getId());
|
||||
|
||||
return $this->success([
|
||||
'current_year' => $this->tariffService->currentJalaliYear(),
|
||||
'default_price_rials' => $item->getPriceRials(),
|
||||
'data' => array_map(fn($t) => $t->toArray(), $tariffs),
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/service-items/{uuid}/tariffs/{year}', methods: ['PUT'], requirements: ['year' => '\d+'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function setTariff(string $uuid, int $year, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$this->denyServices($user, 'update');
|
||||
[$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);
|
||||
}
|
||||
|
||||
if ($year < 1390 || $year > 1500) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'سال نامعتبر است', 422);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$price = (int) ($data['price_rials'] ?? 0);
|
||||
|
||||
$tariff = $this->tariffService->upsert($item->getId(), $year, $price);
|
||||
|
||||
// تعرفهی سال جاری = قیمت پایهی سرویس (قیمت واحد در همهجا).
|
||||
if ($year === $this->tariffService->currentJalaliYear()) {
|
||||
$item->setPriceRials($price);
|
||||
$this->itemRepo->save($item);
|
||||
}
|
||||
|
||||
return $this->success(['data' => $tariff->toArray()]);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -446,7 +446,7 @@ class ServiceCatalogController extends BaseController
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد address_uuid الزامی است', 422, 'address_uuid');
|
||||
}
|
||||
|
||||
foreach (['price_rials', 'solo_duration_minutes', 'additional_duration_minutes'] as $field) {
|
||||
foreach (['solo_duration_minutes', 'additional_duration_minutes'] as $field) {
|
||||
$value = $row[$field] ?? null;
|
||||
|
||||
if ($value !== null && (!is_numeric($value) || (int) $value < 0)) {
|
||||
@@ -464,7 +464,6 @@ class ServiceCatalogController extends BaseController
|
||||
|
||||
// `isset()` خودش null را رد میکند، پس مقایسهٔ اضافه لازم نیست.
|
||||
// `null` یعنی «همان مقدار خودِ سرویس» — صفر نیست.
|
||||
$override->setPriceRials(isset($row['price_rials']) ? (int) $row['price_rials'] : null);
|
||||
$override->setSoloDurationMinutes(isset($row['solo_duration_minutes']) ? (int) $row['solo_duration_minutes'] : null);
|
||||
$override->setAdditionalDurationMinutes(isset($row['additional_duration_minutes']) ? (int) $row['additional_duration_minutes'] : null);
|
||||
|
||||
|
||||
@@ -9,7 +9,9 @@ use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* قیمت و مدتِ اختصاصیِ یک سرویس در یک شعبه.
|
||||
* مدتِ اختصاصیِ یک سرویس در یک شعبه.
|
||||
*
|
||||
* قیمت اینجا نیست: تنها منبع قیمت `ServiceItem::priceRials` است.
|
||||
*
|
||||
* «شعبه» همان `doctor_addresses` است ({@see docs/new_feture/taskes/_shared/branch-is-doctor-address.md}).
|
||||
* هر ستون تهیپذیر است و `null` یعنی «همان مقدار خودِ سرویس» — نه صفر.
|
||||
@@ -38,9 +40,6 @@ class ServiceBranchOverride
|
||||
#[ORM\JoinColumn(name: 'address_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private DoctorAddress $address;
|
||||
|
||||
#[ORM\Column(name: 'price_rials', type: 'bigint', nullable: true)]
|
||||
private ?int $priceRials = null;
|
||||
|
||||
#[ORM\Column(name: 'solo_duration_minutes', type: 'smallint', nullable: true)]
|
||||
private ?int $soloDurationMinutes = null;
|
||||
|
||||
@@ -68,11 +67,9 @@ class ServiceBranchOverride
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getItem(): ServiceItem { return $this->item; }
|
||||
public function getAddress(): DoctorAddress { return $this->address; }
|
||||
public function getPriceRials(): ?int { return $this->priceRials === null ? null : (int) $this->priceRials; }
|
||||
public function getSoloDurationMinutes(): ?int { return $this->soloDurationMinutes; }
|
||||
public function getAdditionalDurationMinutes(): ?int { return $this->additionalDurationMinutes; }
|
||||
|
||||
public function setPriceRials(?int $v): self { $this->priceRials = $v; $this->touch(); return $this; }
|
||||
public function setSoloDurationMinutes(?int $v): self { $this->soloDurationMinutes = $v; $this->touch(); return $this; }
|
||||
public function setAdditionalDurationMinutes(?int $v): self { $this->additionalDurationMinutes = $v; $this->touch(); return $this; }
|
||||
|
||||
@@ -85,7 +82,6 @@ class ServiceBranchOverride
|
||||
'item_uuid' => $this->item->getUuid(),
|
||||
'address_uuid' => $this->address->getUuid(),
|
||||
'address_name' => $this->address->getName(),
|
||||
'price_rials' => $this->getPriceRials(),
|
||||
'solo_duration_minutes' => $this->soloDurationMinutes,
|
||||
'additional_duration_minutes' => $this->additionalDurationMinutes,
|
||||
];
|
||||
|
||||
@@ -104,7 +104,7 @@ class ServiceItem
|
||||
|
||||
/**
|
||||
* پکیج کالای مصرفی این خدمت ({@see \App\Inventory\Entity\InventoryPackage}).
|
||||
* ارجاع خام int بدون FK — همان الگوی Tariff و TenantServiceCoverage — تا دامنهٔ
|
||||
* ارجاع خام int بدون FK — همان الگوی TenantServiceCoverage — تا دامنهٔ
|
||||
* ClinicService به Inventory وابسته نشود.
|
||||
*/
|
||||
#[ORM\Column(name: 'inventory_package_id', type: 'integer', nullable: true)]
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\ClinicService\Entity;
|
||||
|
||||
use App\ClinicService\Repository\TariffRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: TariffRepository::class)]
|
||||
#[ORM\Table(name: 'service_tariffs')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_service_tariff_year', columns: ['service_item_id', 'year'])]
|
||||
#[ORM\Index(columns: ['service_item_id', 'is_active'], name: 'idx_tariff_service_active')]
|
||||
class Tariff
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(name: 'service_item_id', type: 'integer')]
|
||||
private int $serviceItemId;
|
||||
|
||||
#[ORM\Column(type: 'smallint')]
|
||||
private int $year;
|
||||
|
||||
#[ORM\Column(name: 'price_rials', type: 'integer')]
|
||||
private int $priceRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'is_active', type: 'boolean')]
|
||||
private bool $isActive = true;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(int $serviceItemId, int $year, int $priceRials = 0)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->serviceItemId = $serviceItemId;
|
||||
$this->year = $year;
|
||||
$this->priceRials = $priceRials;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getServiceItemId(): int { return $this->serviceItemId; }
|
||||
public function getYear(): int { return $this->year; }
|
||||
public function getPriceRials(): int { return $this->priceRials; }
|
||||
public function isActive(): bool { return $this->isActive; }
|
||||
|
||||
public function setPriceRials(int $v): self { $this->priceRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setActive(bool $v): self { $this->isActive = $v; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'service_item_id' => $this->serviceItemId,
|
||||
'year' => $this->year,
|
||||
'price_rials' => $this->priceRials,
|
||||
'is_active' => $this->isActive,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\ClinicService\Repository;
|
||||
|
||||
use App\ClinicService\Entity\Tariff;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class TariffRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Tariff::class);
|
||||
}
|
||||
|
||||
public function findForServiceYear(int $serviceItemId, int $year): ?Tariff
|
||||
{
|
||||
return $this->findOneBy([
|
||||
'serviceItemId' => $serviceItemId,
|
||||
'year' => $year,
|
||||
'isActive' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Tariff[] */
|
||||
public function findByService(int $serviceItemId): array
|
||||
{
|
||||
return $this->createQueryBuilder('t')
|
||||
->where('t.serviceItemId = :sid')
|
||||
->setParameter('sid', $serviceItemId)
|
||||
->orderBy('t.year', 'DESC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?Tariff
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function save(Tariff $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,16 +77,16 @@ final class DurationCalculator
|
||||
}
|
||||
|
||||
/**
|
||||
* قیمت فقط از خودِ سرویس میآید؛ شعبه دیگر قیمت اختصاصی ندارد.
|
||||
*
|
||||
* @param ServiceItem[] $items
|
||||
* @param array<int, ServiceBranchOverride> $overrides
|
||||
*/
|
||||
public function totalPriceRials(array $items, array $overrides = []): int
|
||||
public function totalPriceRials(array $items): int
|
||||
{
|
||||
$total = 0;
|
||||
|
||||
foreach ($items as $item) {
|
||||
$override = $overrides[(int) $item->getId()] ?? null;
|
||||
$total += $override?->getPriceRials() ?? $item->getPriceRials();
|
||||
$total += $item->getPriceRials();
|
||||
}
|
||||
|
||||
return $total;
|
||||
@@ -128,7 +128,7 @@ final class DurationCalculator
|
||||
'minutes' => $isAnchor
|
||||
? $solos[$index]
|
||||
: ($override?->getAdditionalDurationMinutes() ?? $item->effectiveAdditionalMinutes() ?? $solos[$index]),
|
||||
'price_rials' => $override?->getPriceRials() ?? $item->getPriceRials(),
|
||||
'price_rials' => $item->getPriceRials(),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -16,11 +16,11 @@ use App\Resource\Repository\ResourceServiceOfferingRepository;
|
||||
*
|
||||
* ۱. منبع + گزینه → `ResourceServiceOffering(resource, option)`
|
||||
* ۲. منبع + سرویس → `ResourceServiceOffering(resource, parent)`
|
||||
* ۳. شعبه + آیتم → `ServiceBranchOverride(item, address)`
|
||||
* ۳. شعبه + آیتم → `ServiceBranchOverride(item, address)` — فقط مدت
|
||||
* ۴. پیشفرض آیتم → `ServiceItem`
|
||||
*
|
||||
* **مدت و قیمت جدا حل میشوند.** منبعی که فقط مدتش فرق دارد نباید قیمتش هم از همان
|
||||
* سطح بیاید؛ اگر با هم حل شوند، اولین override باعث میشود تعرفهٔ شعبه بیصدا نادیده گرفته شود.
|
||||
* سطح بیاید. شعبه دیگر قیمت اختصاصی ندارد: قیمت روی خودِ سرویس مدیریت میشود.
|
||||
*
|
||||
* سطحِ والد را **صدازننده** میدهد، نه یک کوئری معکوس روی گروهها: جریان رزرو هر دو را
|
||||
* از قبل در دست دارد (سرویس انتخابشده و گزینهاش)، و کوئری معکوس فقط یک راه اضافه برای
|
||||
@@ -66,7 +66,6 @@ final class ResourceServiceResolver
|
||||
[$price, $priceSource] = $this->first([
|
||||
[$optionOffering?->getPriceRials(), ResolvedServiceSpec::SOURCE_RESOURCE_OPTION],
|
||||
[$parentOffering?->getPriceRials(), ResolvedServiceSpec::SOURCE_RESOURCE_SERVICE],
|
||||
[$branch?->getPriceRials(), ResolvedServiceSpec::SOURCE_BRANCH],
|
||||
[$item->getPriceRials(), ResolvedServiceSpec::SOURCE_SERVICE_DEFAULT],
|
||||
]);
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ final class ServiceSelectionValidator
|
||||
'valid' => $errors === [],
|
||||
'errors' => $errors,
|
||||
'total_duration_minutes' => $this->durations->totalMinutes($selected, $overrides),
|
||||
'total_price_rials' => $this->durations->totalPriceRials($selected, $overrides),
|
||||
'total_price_rials' => $this->durations->totalPriceRials($selected),
|
||||
'breakdown' => $this->durations->breakdown($selected, $overrides),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\ClinicService\Service;
|
||||
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Entity\Tariff;
|
||||
use App\ClinicService\Repository\TariffRepository;
|
||||
|
||||
class TariffService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TariffRepository $tariffRepo,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* تعرفهی یک خدمت برای یک سال شمسی.
|
||||
* اگر تعرفهی آن سال ثبت نشده باشد، به priceRials خود خدمت fallback میشود.
|
||||
*/
|
||||
public function resolvePrice(ServiceItem $service, ?int $year = null): int
|
||||
{
|
||||
$year ??= $this->currentJalaliYear();
|
||||
|
||||
$tariff = $service->getId() !== null
|
||||
? $this->tariffRepo->findForServiceYear($service->getId(), $year)
|
||||
: null;
|
||||
|
||||
return $tariff?->getPriceRials() ?? $service->getPriceRials();
|
||||
}
|
||||
|
||||
public function upsert(int $serviceItemId, int $year, int $priceRials): Tariff
|
||||
{
|
||||
$tariff = $this->tariffRepo->findForServiceYear($serviceItemId, $year);
|
||||
if ($tariff === null) {
|
||||
$tariff = new Tariff($serviceItemId, $year, $priceRials);
|
||||
} else {
|
||||
$tariff->setPriceRials($priceRials)->setActive(true);
|
||||
}
|
||||
$this->tariffRepo->save($tariff);
|
||||
return $tariff;
|
||||
}
|
||||
|
||||
public function currentJalaliYear(): int
|
||||
{
|
||||
$fmt = new \IntlDateFormatter(
|
||||
'en_US@calendar=persian',
|
||||
\IntlDateFormatter::FULL,
|
||||
\IntlDateFormatter::NONE,
|
||||
'Asia/Tehran',
|
||||
\IntlDateFormatter::TRADITIONAL,
|
||||
'yyyy'
|
||||
);
|
||||
return (int) $fmt->format(time());
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ final readonly class ResolvedServiceSpec
|
||||
/** ردیف همان منبع ولی روی سرویسِ والد — وقتی گزینه مقدار خودش را ندارد. */
|
||||
public const SOURCE_RESOURCE_SERVICE = 'resource_service';
|
||||
|
||||
/** `ServiceBranchOverride` — تنظیم این شعبه، مستقل از اینکه کدام منبع کار را میکند. */
|
||||
/** `ServiceBranchOverride` — مدتِ این شعبه، مستقل از اینکه کدام منبع کار را میکند. */
|
||||
public const SOURCE_BRANCH = 'branch';
|
||||
|
||||
/** مقدار خودِ `ServiceItem`. */
|
||||
|
||||
@@ -7,12 +7,7 @@ use App\Auth\Entity\User;
|
||||
use App\Doctor\Service\AddressResolver;
|
||||
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\Patient\Repository\PatientRecordRepository;
|
||||
use App\Pricing\Service\PricingEngine;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
@@ -31,160 +26,14 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
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 AddressResolver $branches,
|
||||
private readonly AddressResolver $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
|
||||
{
|
||||
@@ -236,18 +85,6 @@ class PricingController extends BaseController
|
||||
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);
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing\Entity;
|
||||
|
||||
use App\Doctor\Entity\DoctorAddress;
|
||||
use App\Pricing\Repository\PriceListRepository;
|
||||
use App\Shared\Tenant\TenantOwnedTrait;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* لیست قیمت با **بازهٔ تاریخ** — بند ۱۲ مستند.
|
||||
*
|
||||
* `Tariff` موجود فقط «سال» دارد، پس تغییر تعرفه از اول مهر قابل بیان نیست. این جدول
|
||||
* بازهٔ دقیق میگیرد و `Tariff` بهعنوان لایهٔ پشتیبان سرِ جایش میماند.
|
||||
*
|
||||
* `address` تهیپذیر است: `null` یعنی «همهٔ شعبههای این محیط». قیمت اختصاصی یک شعبه
|
||||
* از {@see \App\ClinicService\Entity\ServiceBranchOverride} میآید که بر این مقدم است.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: PriceListRepository::class)]
|
||||
#[ORM\Table(name: 'price_lists')]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id', 'active'], name: 'idx_price_list_tenant')]
|
||||
#[ORM\Index(columns: ['starts_at', 'ends_at'], name: 'idx_price_list_range')]
|
||||
class PriceList
|
||||
{
|
||||
use TenantOwnedTrait;
|
||||
|
||||
#[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: DoctorAddress::class)]
|
||||
#[ORM\JoinColumn(name: 'address_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')]
|
||||
private ?DoctorAddress $address = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 150)]
|
||||
private string $name;
|
||||
|
||||
#[ORM\Column(name: 'starts_at', type: 'integer')]
|
||||
private int $startsAt;
|
||||
|
||||
#[ORM\Column(name: 'ends_at', type: 'integer')]
|
||||
private int $endsAt;
|
||||
|
||||
/** تا فعال نشده هیچ اثری ندارد؛ ساختنِ پیشنویس نباید قیمت امروز را عوض کند. */
|
||||
#[ORM\Column(type: 'boolean', options: ['default' => false])]
|
||||
private bool $active = false;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
/** @var Collection<int, PriceListItem> */
|
||||
#[ORM\OneToMany(targetEntity: PriceListItem::class, mappedBy: 'priceList', cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $items;
|
||||
|
||||
public function __construct(string $entityType, int $entityId, string $name, int $startsAt, int $endsAt)
|
||||
{
|
||||
if ($endsAt <= $startsAt) {
|
||||
throw new \InvalidArgumentException('Price list end must be after its start.');
|
||||
}
|
||||
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->name = $name;
|
||||
$this->startsAt = $startsAt;
|
||||
$this->endsAt = $endsAt;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
$this->items = new ArrayCollection();
|
||||
|
||||
$this->assignTenantPair($entityType, $entityId);
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getAddress(): ?DoctorAddress { return $this->address; }
|
||||
public function getName(): string { return $this->name; }
|
||||
public function getStartsAt(): int { return $this->startsAt; }
|
||||
public function getEndsAt(): int { return $this->endsAt; }
|
||||
public function isActive(): bool { return $this->active; }
|
||||
|
||||
/** @return Collection<int, PriceListItem> */
|
||||
public function getItems(): Collection { return $this->items; }
|
||||
|
||||
public function setAddress(?DoctorAddress $v): self { $this->address = $v; $this->touch(); return $this; }
|
||||
public function setName(string $v): self { $this->name = $v; $this->touch(); return $this; }
|
||||
public function setActive(bool $v): self { $this->active = $v; $this->touch(); return $this; }
|
||||
|
||||
public function covers(int $at): bool
|
||||
{
|
||||
return $this->active && $at >= $this->startsAt && $at < $this->endsAt;
|
||||
}
|
||||
|
||||
public function overlaps(int $startsAt, int $endsAt): bool
|
||||
{
|
||||
return $startsAt < $this->endsAt && $endsAt > $this->startsAt;
|
||||
}
|
||||
|
||||
public function touch(): void { $this->updatedAt = time(); }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'name' => $this->name,
|
||||
'address_uuid' => $this->address?->getUuid(),
|
||||
'address_name' => $this->address?->getName(),
|
||||
'starts_at' => $this->startsAt,
|
||||
'ends_at' => $this->endsAt,
|
||||
'active' => $this->active,
|
||||
'items' => array_map(
|
||||
static fn (PriceListItem $i): array => $i->toArray(),
|
||||
$this->items->toArray(),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing\Entity;
|
||||
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\Pricing\Repository\PriceListItemRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
/**
|
||||
* قیمت یک سرویس در یک لیست قیمت. فرزند aggregate با ریشهٔ {@see PriceList} که خودش
|
||||
* جفت محیط دارد؛ uuid از request نمیگیرد.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: PriceListItemRepository::class)]
|
||||
#[ORM\Table(name: 'price_list_items')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_price_list_service', columns: ['price_list_id', 'service_item_id'])]
|
||||
class PriceListItem
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: PriceList::class, inversedBy: 'items')]
|
||||
#[ORM\JoinColumn(name: 'price_list_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private PriceList $priceList;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: ServiceItem::class)]
|
||||
#[ORM\JoinColumn(name: 'service_item_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private ServiceItem $serviceItem;
|
||||
|
||||
#[ORM\Column(name: 'price_rials', type: 'bigint')]
|
||||
private int $priceRials;
|
||||
|
||||
public function __construct(PriceList $priceList, ServiceItem $serviceItem, int $priceRials)
|
||||
{
|
||||
if ($priceRials < 0) {
|
||||
throw new \InvalidArgumentException('Price cannot be negative.');
|
||||
}
|
||||
|
||||
$this->priceList = $priceList;
|
||||
$this->serviceItem = $serviceItem;
|
||||
$this->priceRials = $priceRials;
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getPriceList(): PriceList { return $this->priceList; }
|
||||
public function getServiceItem(): ServiceItem { return $this->serviceItem; }
|
||||
public function getPriceRials(): int { return (int) $this->priceRials; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'service_uuid' => $this->serviceItem->getUuid(),
|
||||
'service_name' => $this->serviceItem->getName(),
|
||||
'price_rials' => $this->getPriceRials(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing\Repository;
|
||||
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\Pricing\Entity\PriceList;
|
||||
use App\Pricing\Entity\PriceListItem;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<PriceListItem>
|
||||
*/
|
||||
class PriceListItemRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, PriceListItem::class);
|
||||
}
|
||||
|
||||
public function deleteForList(PriceList $list): int
|
||||
{
|
||||
return (int) $this->createQueryBuilder('i')
|
||||
->delete()
|
||||
->where('i.priceList = :list')
|
||||
->setParameter('list', $list)
|
||||
->getQuery()
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* قیمت چند سرویس در یک لیست — یک کوئری، نه یکی per سرویس.
|
||||
*
|
||||
* @param ServiceItem[] $services
|
||||
* @return array<int, int> شناسهٔ سرویس => قیمت
|
||||
*/
|
||||
public function priceMap(PriceList $list, array $services): array
|
||||
{
|
||||
if ($services === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->createQueryBuilder('i')
|
||||
->select('IDENTITY(i.serviceItem) AS service_id, i.priceRials AS price')
|
||||
->where('i.priceList = :list')
|
||||
->andWhere('i.serviceItem IN (:services)')
|
||||
->setParameter('list', $list)
|
||||
->setParameter('services', $services)
|
||||
->getQuery()
|
||||
->getArrayResult();
|
||||
|
||||
$map = [];
|
||||
foreach ($rows as $row) {
|
||||
$map[(int) $row['service_id']] = (int) $row['price'];
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing\Repository;
|
||||
|
||||
use App\Doctor\Entity\DoctorAddress;
|
||||
use App\Pricing\Entity\PriceList;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<PriceList>
|
||||
*/
|
||||
class PriceListRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, PriceList::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?PriceList
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
/** @return PriceList[] */
|
||||
public function findForPair(string $entityType, int $entityId): array
|
||||
{
|
||||
return $this->createQueryBuilder('p')
|
||||
->where('p.entityType = :type')
|
||||
->andWhere('p.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->orderBy('p.startsAt', 'DESC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* لیست قیمتِ حاکم بر یک لحظه.
|
||||
*
|
||||
* لیستِ مخصوصِ همان شعبه بر لیست عمومیِ محیط مقدم است — وگرنه تعریف استثنا برای
|
||||
* یک شعبه هیچ اثری نداشت.
|
||||
*/
|
||||
public function findCovering(string $entityType, int $entityId, ?DoctorAddress $address, int $at): ?PriceList
|
||||
{
|
||||
$rows = $this->createQueryBuilder('p')
|
||||
->where('p.entityType = :type')
|
||||
->andWhere('p.entityId = :id')
|
||||
->andWhere('p.active = true')
|
||||
->andWhere('p.startsAt <= :at')
|
||||
->andWhere('p.endsAt > :at')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('at', $at)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$general = null;
|
||||
|
||||
foreach ($rows as $list) {
|
||||
if ($address !== null && $list->getAddress()?->getId() === $address->getId()) {
|
||||
return $list;
|
||||
}
|
||||
|
||||
if ($list->getAddress() === null) {
|
||||
$general = $list;
|
||||
}
|
||||
}
|
||||
|
||||
return $general;
|
||||
}
|
||||
|
||||
/**
|
||||
* لیستهای فعالِ همپوشان با یک بازه — برای جلوگیری از دو قیمتِ همزمان.
|
||||
*
|
||||
* @return PriceList[]
|
||||
*/
|
||||
public function findOverlapping(PriceList $candidate): array
|
||||
{
|
||||
$qb = $this->createQueryBuilder('p')
|
||||
->where('p.entityType = :type')
|
||||
->andWhere('p.entityId = :id')
|
||||
->andWhere('p.active = true')
|
||||
->andWhere('p.startsAt < :ends')
|
||||
->andWhere('p.endsAt > :starts')
|
||||
->setParameter('type', $candidate->getEntityType())
|
||||
->setParameter('id', $candidate->getEntityId())
|
||||
->setParameter('starts', $candidate->getStartsAt())
|
||||
->setParameter('ends', $candidate->getEndsAt());
|
||||
|
||||
if ($candidate->getId() !== null) {
|
||||
$qb->andWhere('p.id != :self')->setParameter('self', $candidate->getId());
|
||||
}
|
||||
|
||||
// فقط لیستهایی که دامنهٔ یکسانی دارند با هم تداخل دارند: لیست عمومی و لیست
|
||||
// یک شعبه عمداً کنار هم زندگی میکنند و اولویت دارند، نه تداخل.
|
||||
return array_values(array_filter(
|
||||
$qb->getQuery()->getResult(),
|
||||
static fn (PriceList $other): bool => $other->getAddress()?->getId() === $candidate->getAddress()?->getId(),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,8 @@
|
||||
namespace App\Pricing\Service;
|
||||
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Repository\ServiceBranchOverrideRepository;
|
||||
use App\ClinicService\Repository\TariffRepository;
|
||||
use App\Doctor\Entity\DoctorAddress;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Pricing\Repository\PriceListItemRepository;
|
||||
use App\Pricing\Repository\PriceListRepository;
|
||||
use App\Pricing\ValueObject\PriceQuote;
|
||||
use App\Representation\Service\JalaliDateService;
|
||||
|
||||
/**
|
||||
* زنجیرهٔ قیمتگذاری بند ۱۲ مستند.
|
||||
@@ -19,27 +13,14 @@ use App\Representation\Service\JalaliDateService;
|
||||
* قیمت پایه → + آیتمها → − تخفیف → − بیمهٔ پایه → − تکمیلی → + مالیات → بیعانه
|
||||
* ```
|
||||
*
|
||||
* ## زنجیرهٔ منبع قیمت
|
||||
* ## منبع قیمت
|
||||
*
|
||||
* برای هر سرویس، اولین چیزی که پیدا شود برنده است:
|
||||
*
|
||||
* ۱. override شعبه ({@see \App\ClinicService\Entity\ServiceBranchOverride}) — تسک ۰۴
|
||||
* ۲. لیست قیمتِ حاکم بر آن تاریخ — همین تسک
|
||||
* ۳. `Tariff` سال — لایهٔ موجود
|
||||
* ۴. `ServiceItem::priceRials` — همیشه هست
|
||||
*
|
||||
* مرحلهٔ چهارم ضامن است که **هرگز صفر یا خطا** برنگردد: تاریخی که هیچ لیستی نمیپوشاند
|
||||
* باید قیمت بدهد، نه استثنا.
|
||||
* تنها منبع قیمت، `ServiceItem::priceRials` است — قیمت روی خودِ سرویس مدیریت میشود.
|
||||
* لایههای پیشینِ «لیست قیمت»، «تعرفهٔ سالانه» و «قیمت اختصاصی شعبه» حذف شدهاند تا یک
|
||||
* تاریخ هرگز دو قیمت نداشته باشد.
|
||||
*/
|
||||
final class PricingEngine
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PriceListRepository $priceLists,
|
||||
private readonly PriceListItemRepository $priceListItems,
|
||||
private readonly ServiceBranchOverrideRepository $overrides,
|
||||
private readonly TariffRepository $tariffs,
|
||||
private readonly JalaliDateService $jalali,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param ServiceItem[] $items آیتمهای انتخابشده (بدون خودِ سرویس)
|
||||
@@ -57,18 +38,13 @@ final class PricingEngine
|
||||
int $at,
|
||||
array $policy = [],
|
||||
): PriceQuote {
|
||||
$entityType = $address->tenantEntityType();
|
||||
$entityId = $address->tenantEntityId();
|
||||
|
||||
$list = $this->priceLists->findCovering($entityType, $entityId, $address, $at);
|
||||
|
||||
$sources = [];
|
||||
|
||||
$base = $this->priceFor($service, $address, $list, $at, $sources);
|
||||
$base = $this->priceFor($service, $sources);
|
||||
$itemsTotal = 0;
|
||||
|
||||
foreach ($items as $item) {
|
||||
$itemsTotal += $this->priceFor($item, $address, $list, $at, $sources);
|
||||
$itemsTotal += $this->priceFor($item, $sources);
|
||||
}
|
||||
|
||||
$subtotal = $base + $itemsTotal;
|
||||
@@ -121,39 +97,8 @@ final class PricingEngine
|
||||
/**
|
||||
* @param array<string, string> $sources
|
||||
*/
|
||||
private function priceFor(
|
||||
ServiceItem $service,
|
||||
DoctorAddress $address,
|
||||
?\App\Pricing\Entity\PriceList $list,
|
||||
int $at,
|
||||
array &$sources,
|
||||
): int {
|
||||
$override = $this->overrides->mapForAddress([(int) $service->getId()], $address)[(int) $service->getId()] ?? null;
|
||||
|
||||
if ($override?->getPriceRials() !== null) {
|
||||
$sources[$service->getUuid()] = 'branch_override';
|
||||
|
||||
return $override->getPriceRials();
|
||||
}
|
||||
|
||||
if ($list !== null) {
|
||||
$price = $this->priceListItems->priceMap($list, [$service])[(int) $service->getId()] ?? null;
|
||||
|
||||
if ($price !== null) {
|
||||
$sources[$service->getUuid()] = 'price_list';
|
||||
|
||||
return $price;
|
||||
}
|
||||
}
|
||||
|
||||
$tariff = $this->tariffs->findForServiceYear((int) $service->getId(), $this->jalali->jalaliYear($at));
|
||||
|
||||
if ($tariff !== null) {
|
||||
$sources[$service->getUuid()] = 'tariff';
|
||||
|
||||
return (int) $tariff->getPriceRials();
|
||||
}
|
||||
|
||||
private function priceFor(ServiceItem $service, array &$sources): int
|
||||
{
|
||||
$sources[$service->getUuid()] = 'service_item';
|
||||
|
||||
return $service->getPriceRials();
|
||||
|
||||
@@ -18,8 +18,6 @@ use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Entity\ServiceItemRelation;
|
||||
use App\Doctor\Entity\DoctorAddress;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Pricing\Entity\PriceList;
|
||||
use App\Pricing\Entity\PriceListItem;
|
||||
use App\Pricing\Service\PriceSnapshotService;
|
||||
use App\Pricing\ValueObject\PriceQuote;
|
||||
use App\Resource\Entity\ClinicResource;
|
||||
@@ -87,7 +85,6 @@ final class BookingEngineSeeder
|
||||
$counts['catalog'] = $this->catalog($entityType, $entityId, $services, $address);
|
||||
$counts['resources'] = $this->skillsPoolsAndExceptions($entityType, $entityId, $address, $devices, $deviceType);
|
||||
$counts['segments'] = $this->multiSegmentPlan($flagship, $deviceType, $entityType, $entityId, $address);
|
||||
$counts['pricing'] = $this->priceList($entityType, $entityId, $services);
|
||||
$counts['offerings'] = $this->serviceOfferings($address, $devices, $services);
|
||||
$counts['booked'] = $this->realBookings($flagship, $address, $patients, $doctor, $clinic, $entityType, $entityId);
|
||||
|
||||
@@ -127,9 +124,9 @@ final class BookingEngineSeeder
|
||||
$this->em()->persist(new ServiceItemRelation($services[0], $services[1], ServiceItemRelation::TYPE_INCOMPATIBLE));
|
||||
}
|
||||
|
||||
// قیمت و مدت این سرویس در این شعبه فرق دارد — تا override واقعاً تست شود.
|
||||
// مدت این سرویس در این شعبه فرق دارد — تا override واقعاً تست شود.
|
||||
$override = new ServiceBranchOverride($services[1] ?? $services[0], $address);
|
||||
$override->setPriceRials((int) round(($services[1] ?? $services[0])->getPriceRials() * 1.2));
|
||||
$override->setSoloDurationMinutes(max(5, (($services[1] ?? $services[0])->getSoloDurationMinutes() ?? 20) + 10));
|
||||
$this->em()->persist($override);
|
||||
|
||||
$this->em()->flush();
|
||||
@@ -261,25 +258,6 @@ final class BookingEngineSeeder
|
||||
return $made;
|
||||
}
|
||||
|
||||
// ── تسک ۰۸: لیست قیمت ───────────────────────────────────────────────────
|
||||
|
||||
private function priceList(string $entityType, int $entityId, array $services): int
|
||||
{
|
||||
$list = new PriceList($entityType, $entityId, 'تعرفهٔ نیمسال دوم', strtotime('-30 days'), strtotime('+180 days'));
|
||||
$list->setActive(true);
|
||||
$this->em()->persist($list);
|
||||
$this->em()->flush();
|
||||
|
||||
foreach ($services as $service) {
|
||||
// قیمت لیست عمداً با قیمت پایهٔ سرویس فرق دارد: اگر یکی بودند، معلوم نمیشد
|
||||
// snapshot از کدام منبع خوانده است.
|
||||
$this->em()->persist(new PriceListItem($list, $service, (int) round($service->getPriceRials() * 0.9)));
|
||||
}
|
||||
$this->em()->flush();
|
||||
|
||||
return count($services);
|
||||
}
|
||||
|
||||
// ── تسک ۰۹: سیاستها، یکی از هر دسته ────────────────────────────────────
|
||||
|
||||
// ── تسک ۰۶ و ۰۷: رزرو واقعی روی تقویم منابع ─────────────────────────────
|
||||
|
||||
@@ -109,12 +109,10 @@ final class GlobalTables
|
||||
|
||||
\App\ClinicService\Entity\ServiceItemAuditLog::class => \App\ClinicService\Entity\ServiceItem::class,
|
||||
\App\ClinicService\Entity\ServiceItemConsumable::class => \App\ClinicService\Entity\ServiceItem::class,
|
||||
\App\ClinicService\Entity\Tariff::class => \App\ClinicService\Entity\ServiceItem::class,
|
||||
\App\ClinicService\Entity\ItemGroupMember::class => \App\ClinicService\Entity\ItemGroup::class,
|
||||
// یال «این دسته شامل آن دسته است» جزئی از تعریف دستهٔ والد است؛ هر دو سرِ یال
|
||||
// در یک محیطاند و سازندهٔ یال همین را اجبار میکند.
|
||||
\App\ClinicService\Entity\CatalogCategoryInclude::class => \App\ClinicService\Entity\CatalogCategory::class,
|
||||
\App\Pricing\Entity\PriceListItem::class => \App\Pricing\Entity\PriceList::class,
|
||||
|
||||
\App\Billing\Entity\ClaimItem::class => \App\Billing\Entity\Claim::class,
|
||||
\App\Billing\Entity\ClaimStatusLog::class => \App\Billing\Entity\Claim::class,
|
||||
|
||||
Reference in New Issue
Block a user