feat: port tauri create-service payment flow to admin session settlement

Port the tauri /files/create-service page (payment mode) to the admin SPA
and back it with real multi-part session settlement:

Backend:
- New SessionPayment entity (session_payments table): partial payments
  per session with method (wallet/pos/cash/card), amount, paid_at, actor
- PatientSession: settlement discount (percent/fixed), discount_rials,
  paid_at, payments relation; remaining debt derived from
  final - discount - paid total
- POST /api/v1/session/{uuid}/payments: register a partial payment;
  wallet method debits the patient wallet; zero remaining marks paid
- PATCH /api/v1/session/{uuid}: accepts discount_type/discount_value
  (null removes) and paid_at, backward compatible
- New error codes: ERR_SESSION_PAYMENT_INVALID/_EXCEEDS,
  ERR_SESSION_DISCOUNT_INVALID
- Migration + 14 functional tests (partial/full/wallet/exceed/discount)

Frontend (admin):
- SessionPaymentPage: two-step stepper (پرداخت ← جزییات) ported from
  tauri AddService payment mode — service cost, settlement discount
  input, Jalali payment date, wallet balance, 4-method payment accordion,
  paid-list box, details summary
- SessionStepper + stepper/payment icons ported verbatim from tauri SVGs
- «تکمیل پرداخت» on SessionServiceCard now navigates to the payment page
  (replaces the small settle modal on PatientDetailPage)
- Routes for patients/ and my-patients/ variants; vitest coverage
- docs/api/patient.md updated

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-16 13:32:06 +03:30
co-authored by Claude Opus 4.8
parent 73ae4baa66
commit 27d088c6dd
18 changed files with 1425 additions and 55 deletions
+41 -3
View File
@@ -979,10 +979,10 @@ class PatientController extends BaseController
if ($data['is_paid']) {
$data['patient_debt_rials'] = 0;
} elseif ($invoice !== null) {
$data['patient_debt_rials'] = $invoice->getPatientRials();
} else {
$data['patient_debt_rials'] = $session->getFinalPriceRials();
// سهم بیمار (از فاکتور در صورت وجود) منهای تخفیف تسویه و پرداخت‌های جزئی
$share = $invoice !== null ? $invoice->getPatientRials() : $session->getFinalPriceRials();
$data['patient_debt_rials'] = max(0, $share - $session->getDiscountRials() - $session->getPaidTotalRials());
}
return $data;
@@ -1046,6 +1046,14 @@ class PatientController extends BaseController
if (isset($data['notes'])) { $session->setNotes($data['notes']); }
// تخفیف تسویه: discount_type = percent|fixed|null (null = حذف تخفیف)
if (array_key_exists('discount_type', $data)) {
$type = $data['discount_type'] !== null ? (string) $data['discount_type'] : null;
$this->patientService->applyDiscount($session, $type, (int) ($data['discount_value'] ?? 0));
}
if (isset($data['paid_at'])) { $session->setPaidAt((int) $data['paid_at']); }
if (isset($data['payment_method'])) {
$method = (string) $data['payment_method'];
// پرداخت از کیف پول: سهمِ بیمار را از موجودی کسر کن (فقط یک‌بار، اگر
@@ -1064,6 +1072,36 @@ class PatientController extends BaseController
return $this->success($session->toArray());
}
/**
* ثبت پرداخت جزئی روی مراجعه (تسویه چندتکه).
* body: { method: wallet|pos|cash|card, amount_rials: int, paid_at?: int }
* روش wallet همان مبلغ را از کیف پول بیمار کسر می‌کند. وقتی مانده صفر شود
* مراجعه تسویه‌شده (is_paid) می‌شود.
*/
#[Route('/api/v1/session/{uuid}/payments', methods: ['POST'])]
public function addSessionPayment(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
$this->assertPatientGate($entityType, $entityId);
$session = $this->sessionRepo->findByUuid($uuid);
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId)) {
return $this->error(ErrorCodes::ERR_SESSION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SESSION_NOT_FOUND), 404);
}
$data = json_decode($request->getContent(), true) ?? [];
$this->patientService->addSessionPayment(
$session,
(string) ($data['method'] ?? ''),
(int) ($data['amount_rials'] ?? 0),
isset($data['paid_at']) ? (int) $data['paid_at'] : null,
$user,
);
return $this->success($this->sessionWithBilling($session), 201);
}
private function resolveEntity(User $user): array
{
if ($user->hasRole('ROLE_DOCTOR')) {
+67
View File
@@ -54,6 +54,22 @@ class PatientSession
#[ORM\Column(name: 'payment_method', type: 'string', length: 15)]
private string $paymentMethod = 'pending';
/** نوع تخفیف تسویه: percent | fixed | null (بدون تخفیف) */
#[ORM\Column(name: 'discount_type', type: 'string', length: 10, nullable: true)]
private ?string $discountType = null;
/** مقدار خام تخفیف (درصد یا ریال، بسته به نوع) */
#[ORM\Column(name: 'discount_value', type: 'integer')]
private int $discountValue = 0;
/** مبلغ محاسبه‌شده‌ی تخفیف به ریال (سقف: مبلغ نهایی) */
#[ORM\Column(name: 'discount_rials', type: 'integer')]
private int $discountRials = 0;
/** زمان تسویه‌ی کامل (unix)؛ تا قبل از صفر شدن بدهی null است */
#[ORM\Column(name: 'paid_at', type: 'integer', nullable: true)]
private ?int $paidAt = null;
#[ORM\Column(type: 'text', nullable: true)]
private ?string $notes = null;
@@ -66,6 +82,9 @@ class PatientSession
#[ORM\OneToMany(targetEntity: SessionService::class, mappedBy: 'session', cascade: ['remove'])]
private Collection $services;
#[ORM\OneToMany(targetEntity: SessionPayment::class, mappedBy: 'session', cascade: ['remove'])]
private Collection $payments;
public function __construct(PatientRecord $record, ?Appointment $appointment = null)
{
$this->uuid = Uuid::v4()->toRfc4122();
@@ -74,6 +93,7 @@ class PatientSession
$this->createdAt = time();
$this->updatedAt = time();
$this->services = new ArrayCollection();
$this->payments = new ArrayCollection();
}
public function getId(): ?int { return $this->id; }
@@ -97,6 +117,35 @@ class PatientSession
public function getServicesTotalRials(): int { return $this->servicesTotalRials; }
public function getFinalPriceRials(): int { return $this->finalPriceRials; }
public function getPaymentMethod(): string { return $this->paymentMethod; }
public function getDiscountType(): ?string { return $this->discountType; }
public function getDiscountValue(): int { return $this->discountValue; }
public function getDiscountRials(): int { return $this->discountRials; }
public function getPaidAt(): ?int { return $this->paidAt; }
public function getPayments(): Collection { return $this->payments; }
public function addPayment(SessionPayment $payment): self
{
if (!$this->payments->contains($payment)) {
$this->payments->add($payment);
}
return $this;
}
/** مجموع پرداخت‌های ثبت‌شده روی این مراجعه (ریال) */
public function getPaidTotalRials(): int
{
return array_sum(array_map(
fn(SessionPayment $p) => $p->getAmountRials(),
$this->payments->toArray(),
));
}
/** مانده‌ی بدهی پس از کسر تخفیف و پرداخت‌ها؛ هرگز منفی نمی‌شود */
public function getRemainingRials(): int
{
return max(0, $this->finalPriceRials - $this->discountRials - $this->getPaidTotalRials());
}
public function getNotes(): ?string { return $this->notes; }
public function getCreatedAt(): int { return $this->createdAt; }
public function getUpdatedAt(): int { return $this->updatedAt; }
@@ -109,6 +158,15 @@ class PatientSession
public function setServicesTotalRials(int $v): self { $this->servicesTotalRials = $v; $this->updatedAt = time(); return $this; }
public function setFinalPriceRials(int $v): self { $this->finalPriceRials = $v; $this->updatedAt = time(); return $this; }
public function setPaymentMethod(string $v): self { $this->paymentMethod = $v; $this->updatedAt = time(); return $this; }
public function setDiscount(?string $type, int $value, int $rials): self
{
$this->discountType = $type;
$this->discountValue = $type === null ? 0 : $value;
$this->discountRials = $type === null ? 0 : $rials;
$this->updatedAt = time();
return $this;
}
public function setPaidAt(?int $v): self { $this->paidAt = $v; $this->updatedAt = time(); return $this; }
public function setNotes(?string $v): self { $this->notes = $v; $this->updatedAt = time(); return $this; }
public function toArray(): array
@@ -128,6 +186,15 @@ class PatientSession
'final_price_rials' => $this->finalPriceRials,
'payment_method' => $this->paymentMethod,
'is_paid' => $this->paymentMethod !== 'pending',
'discount_type' => $this->discountType,
'discount_value' => $this->discountValue,
'discount_rials' => $this->discountRials,
'paid_at' => $this->paidAt,
'paid_total_rials' => $this->getPaidTotalRials(),
'payments' => array_map(
fn(SessionPayment $p) => $p->toArray(),
$this->payments->toArray()
),
'services' => array_map(
fn(SessionService $s) => $s->toArray(),
$this->services->toArray()
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Patient\Entity;
use App\Auth\Entity\User;
use App\Patient\Repository\SessionPaymentRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* یک پرداختِ جزئی روی یک مراجعه (تسویه‌ی چندتکه). مجموع پرداخت‌ها به‌علاوه‌ی
* تخفیف، بدهیِ مراجعه را صفر می‌کند.
*/
#[ORM\Entity(repositoryClass: SessionPaymentRepository::class)]
#[ORM\Table(name: 'session_payments')]
class SessionPayment
{
public const METHODS = ['wallet', 'pos', 'cash', 'card'];
#[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: PatientSession::class, inversedBy: 'payments')]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private PatientSession $session;
#[ORM\Column(type: 'string', length: 15)]
private string $method;
#[ORM\Column(name: 'amount_rials', type: 'integer')]
private int $amountRials;
#[ORM\Column(name: 'paid_at', type: 'integer')]
private int $paidAt;
#[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(name: 'created_by_id', nullable: true, onDelete: 'SET NULL')]
private ?User $createdBy = null;
#[ORM\Column(name: 'created_by_name', type: 'string', length: 255, nullable: true)]
private ?string $createdByName = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(PatientSession $session, string $method, int $amountRials, ?int $paidAt = null)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->session = $session;
$this->method = $method;
$this->amountRials = $amountRials;
$this->paidAt = $paidAt ?? time();
$this->createdAt = time();
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getSession(): PatientSession { return $this->session; }
public function getMethod(): string { return $this->method; }
public function getAmountRials(): int { return $this->amountRials; }
public function getPaidAt(): int { return $this->paidAt; }
public function getCreatedBy(): ?User { return $this->createdBy; }
public function getCreatedByName(): ?string { return $this->createdByName; }
public function getCreatedAt(): int { return $this->createdAt; }
public function setCreatedBy(?User $u): self { $this->createdBy = $u; return $this; }
public function setCreatedByName(?string $n): self { $this->createdByName = $n; return $this; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'method' => $this->method,
'amount_rials' => $this->amountRials,
'paid_at' => $this->paidAt,
'created_by_name' => $this->createdByName,
'created_at' => $this->createdAt,
];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Patient\Repository;
use App\Patient\Entity\SessionPayment;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class SessionPaymentRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, SessionPayment::class);
}
public function save(SessionPayment $payment): void
{
$this->getEntityManager()->persist($payment);
$this->getEntityManager()->flush();
}
}
+109
View File
@@ -10,12 +10,18 @@ use App\ClinicService\Repository\ServiceItemRepository;
use App\Clinic\Repository\ClinicRepository;
use App\Insurance\Service\TenantInsuranceService;
use App\Doctor\Repository\DoctorAddressRepository;
use App\Auth\Entity\User;
use App\Patient\Entity\PatientRecord;
use App\Patient\Entity\PatientSession;
use App\Patient\Entity\SessionPayment;
use App\Patient\Entity\SessionService;
use App\Patient\Repository\PatientRecordRepository;
use App\Patient\Repository\PatientSessionRepository;
use App\Patient\Repository\SessionPaymentRepository;
use App\Patient\Repository\SessionServiceRepository;
use App\Settlement\Service\WalletService;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Exception\AppException;
use App\Staff\Repository\ClinicStaffRepository;
use App\Subscription\Service\SubscriptionService;
@@ -25,6 +31,7 @@ class PatientService
private readonly PatientRecordRepository $recordRepo,
private readonly PatientSessionRepository $sessionRepo,
private readonly SessionServiceRepository $sessionServiceRepo,
private readonly SessionPaymentRepository $sessionPaymentRepo,
private readonly ServiceItemRepository $serviceItemRepo,
private readonly ClinicStaffRepository $staffRepo,
private readonly UserRepository $userRepo,
@@ -33,6 +40,7 @@ class PatientService
private readonly ClinicRepository $clinicRepo,
private readonly TenantInsuranceService $tenantInsuranceService,
private readonly BillingCalculator $billingCalculator,
private readonly WalletService $walletService,
) {}
/**
@@ -178,4 +186,105 @@ class PatientService
return $session;
}
/**
* اعمال/حذف تخفیف تسویه روی مراجعه.
* type=null → حذف تخفیف. percent باید 0..100 و fixed حداکثر برابر مبلغ نهایی باشد.
* تخفیف نمی‌تواند از مانده‌ی قابل‌تخفیف (مبلغ نهایی منهای پرداخت‌های ثبت‌شده) بیشتر شود.
*/
public function applyDiscount(PatientSession $session, ?string $type, int $value): PatientSession
{
if ($type === null) {
$session->setDiscount(null, 0, 0);
$this->sessionRepo->save($session);
return $session;
}
if (!in_array($type, ['percent', 'fixed'], true) || $value < 0) {
throw new AppException(ErrorCodes::ERR_SESSION_DISCOUNT_INVALID, null, 422, 'discount_type');
}
$final = $session->getFinalPriceRials();
if ($type === 'percent') {
if ($value > 100) {
throw new AppException(ErrorCodes::ERR_SESSION_DISCOUNT_INVALID, null, 422, 'discount_value');
}
$rials = (int) round($final * $value / 100);
} else {
if ($value > $final) {
throw new AppException(ErrorCodes::ERR_SESSION_DISCOUNT_INVALID, null, 422, 'discount_value');
}
$rials = $value;
}
// تخفیف نباید از آنچه هنوز پرداخت نشده بیشتر باشد (پرداخت‌ها برگشت‌ناپذیرند)
if ($rials > $final - $session->getPaidTotalRials()) {
throw new AppException(ErrorCodes::ERR_SESSION_DISCOUNT_INVALID, null, 422, 'discount_value');
}
$session->setDiscount($type, $value, $rials);
if ($session->getRemainingRials() === 0 && $session->getPaymentMethod() === 'pending') {
// تخفیف صددرصدی بدهی را صفر کرد — مراجعه تسویه‌شده تلقی می‌شود
$session->setPaymentMethod('cash');
$session->setPaidAt(time());
}
$this->sessionRepo->save($session);
return $session;
}
/**
* ثبت یک پرداخت جزئی روی مراجعه. روش wallet همان مبلغ را از کیف پول بیمار
* کسر می‌کند (موجودی ناکافی → ۴۲۲). وقتی مانده صفر شود، payment_method و
* paid_at مراجعه ست می‌شوند تا is_paid برای مصرف‌کننده‌های فعلی درست بماند.
*/
public function addSessionPayment(
PatientSession $session,
string $method,
int $amountRials,
?int $paidAt = null,
?User $actor = null,
): SessionPayment {
if (!in_array($method, SessionPayment::METHODS, true)) {
throw new AppException(ErrorCodes::ERR_SESSION_PAYMENT_INVALID, null, 422, 'method');
}
if ($amountRials <= 0) {
throw new AppException(ErrorCodes::ERR_SESSION_PAYMENT_INVALID, null, 422, 'amount_rials');
}
$remaining = $session->getRemainingRials();
if ($amountRials > $remaining) {
throw new AppException(ErrorCodes::ERR_SESSION_PAYMENT_EXCEEDS, null, 422, 'amount_rials');
}
if ($method === 'wallet') {
$names = array_values(array_filter(array_map(
fn(SessionService $s) => $s->toArray()['service_name'] ?? null,
$session->getServices()->toArray(),
)));
$label = $names !== [] ? implode('، ', $names) : 'ویزیت';
$this->walletService->withdraw(
$session->getRecord()->getUser(),
$amountRials,
$actor,
'پرداخت سرویس: ' . $label,
'wallet',
'session:' . $session->getUuid(),
);
}
$payment = new SessionPayment($session, $method, $amountRials, $paidAt);
$payment->setCreatedBy($actor)
->setCreatedByName($this->walletService->resolveActorName($actor));
$this->sessionPaymentRepo->save($payment);
$session->addPayment($payment);
if ($session->getRemainingRials() === 0) {
$session->setPaymentMethod($method);
$session->setPaidAt($paidAt ?? time());
}
$this->sessionRepo->save($session);
return $payment;
}
}
+6
View File
@@ -62,6 +62,9 @@ class ErrorCodes
// Patient
public const ERR_PATIENT_NOT_FOUND = 'ERR_PATIENT_NOT_FOUND';
public const ERR_SESSION_NOT_FOUND = 'ERR_SESSION_NOT_FOUND';
public const ERR_SESSION_PAYMENT_INVALID = 'ERR_SESSION_PAYMENT_INVALID';
public const ERR_SESSION_PAYMENT_EXCEEDS = 'ERR_SESSION_PAYMENT_EXCEEDS';
public const ERR_SESSION_DISCOUNT_INVALID = 'ERR_SESSION_DISCOUNT_INVALID';
// Profile
public const ERR_PROFILE_NATIONAL_CODE_TAKEN = 'ERR_PROFILE_001';
@@ -146,6 +149,9 @@ class ErrorCodes
self::ERR_PROFILE_NATIONAL_CODE_TAKEN => 'این کد ملی قبلاً برای کاربر دیگری ثبت شده است',
self::ERR_PROFILE_MOBILE_TAKEN => 'این شماره موبایل قبلاً برای کاربر دیگری ثبت شده است',
self::ERR_SESSION_NOT_FOUND => 'مراجعه یافت نشد',
self::ERR_SESSION_PAYMENT_INVALID => 'مبلغ یا روش پرداخت نامعتبر است',
self::ERR_SESSION_PAYMENT_EXCEEDS => 'مبلغ پرداخت از مانده بدهی بیشتر است',
self::ERR_SESSION_DISCOUNT_INVALID => 'مقدار تخفیف نامعتبر است',
self::ERR_SMS_WALLET_INSUFFICIENT => 'موجودی کیف پیامک کافی نیست',
self::ERR_WALLET_INSUFFICIENT => 'موجودی کیف پول کافی نیست',
self::ERR_RATING_NOT_ELIGIBLE => 'برای ثبت نظر یا امتیاز باید در یک ماه گذشته نوبت تایید‌شده نزد این پزشک داشته باشید',