feat: unify wallet with real payment methods, full transaction transparency, pay-session-from-wallet
Address wallet feedback: use the clinic's real payment infrastructure,
redesign the tab to match the admin panel, and make every wallet movement
fully auditable.
Backend:
- WalletTransaction: add createdBy (acting user) + createdByName, payment_method,
reference, status; toArray exposes them (migration Version20260716083939).
- WalletService (Settlement): balance/charge/withdraw + settleSessionFromWallet,
records actor/method/reason; insufficient balance throws ERR_WALLET_INSUFFICIENT.
- PatientController: charge/withdraw delegate to WalletService and accept
payment_method/reference; PATCH /session/{uuid} with payment_method=wallet
debits the patient's final share from the wallet (reference=session:{uuid}).
- docs/api/patient.md updated.
Frontend:
- Wallet modal redesigned to panel style (no gradient); payment method now uses
the clinic's real bank accounts + POS devices (usePaymentMethods) plus cash.
- Wallet tab: panel balance card + DataTable ledger with columns مبلغ/نوع/روش/
دلیل/ثبتکننده/تاریخ/ساعت/وضعیت + همه/واریزی/برداشت filters.
- Session card «تکمیل پرداخت» opens a payment-method chooser incl. کیف پول.
Tests: backend transparency + session-from-wallet (success/insufficient/cash);
frontend modal (real methods, toman→rials) + wallet tab + settle chooser.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -58,6 +58,7 @@ class PatientController extends BaseController
|
||||
private readonly \App\Payment\Repository\PaymentRepository $paymentRepo,
|
||||
private readonly \App\Settlement\Repository\WalletTransactionRepository $walletRepo,
|
||||
private readonly \App\Settlement\Repository\SettlementRepository $settlementRepo,
|
||||
private readonly \App\Settlement\Service\WalletService $walletService,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
@@ -155,24 +156,24 @@ class PatientController extends BaseController
|
||||
}
|
||||
|
||||
$patient = $record->getUser();
|
||||
$balance = $this->settlementRepo->getWalletBalance($patient) + $amount;
|
||||
|
||||
$txn = new \App\Settlement\Entity\WalletTransaction($patient, $amount, 'credit', $balance);
|
||||
$description = trim((string) ($data['description'] ?? ''));
|
||||
$txn->setDescription($description !== '' ? $description : 'شارژ کیف پول');
|
||||
$this->walletRepo->save($txn);
|
||||
$txn = $this->walletService->charge(
|
||||
$patient, $amount, $user,
|
||||
trim((string) ($data['description'] ?? '')) ?: null,
|
||||
$this->normalizeMethod($data['payment_method'] ?? null),
|
||||
trim((string) ($data['reference'] ?? '')) ?: null,
|
||||
);
|
||||
|
||||
return $this->success([
|
||||
'transaction' => $txn->toArray(),
|
||||
'balance_rials' => $balance,
|
||||
'balance_rials' => $txn->getBalanceAfter(),
|
||||
], 201);
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual wallet withdrawal (برداشت از کیف پول) — e.g. a refund or cash
|
||||
* hand-back at the desk. Creates a debit WalletTransaction for the record's
|
||||
* owner User. Rejected (422) when the amount exceeds the current balance,
|
||||
* mirroring the offline app's balance guard.
|
||||
* owner User (with acting user + payment method recorded). Rejected (422)
|
||||
* when the amount exceeds the current balance, mirroring the offline app.
|
||||
*/
|
||||
#[Route('/api/v1/patient/{uuid}/wallet/withdraw', methods: ['POST'])]
|
||||
public function withdrawWallet(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
@@ -189,25 +190,28 @@ class PatientController extends BaseController
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'مبلغ برداشت باید بزرگتر از صفر باشد', 422, 'amount_rials');
|
||||
}
|
||||
|
||||
// Insufficient balance → WalletService throws AppException (422), handled globally.
|
||||
$patient = $record->getUser();
|
||||
$current = $this->settlementRepo->getWalletBalance($patient);
|
||||
if ($amount > $current) {
|
||||
return $this->error(ErrorCodes::ERR_WALLET_INSUFFICIENT, ErrorCodes::message(ErrorCodes::ERR_WALLET_INSUFFICIENT), 422, 'amount_rials');
|
||||
}
|
||||
|
||||
$balance = $current - $amount;
|
||||
|
||||
$txn = new \App\Settlement\Entity\WalletTransaction($patient, $amount, 'debit', $balance);
|
||||
$description = trim((string) ($data['description'] ?? ''));
|
||||
$txn->setDescription($description !== '' ? $description : 'برداشت از کیف پول');
|
||||
$this->walletRepo->save($txn);
|
||||
$txn = $this->walletService->withdraw(
|
||||
$patient, $amount, $user,
|
||||
trim((string) ($data['description'] ?? '')) ?: null,
|
||||
$this->normalizeMethod($data['payment_method'] ?? null),
|
||||
trim((string) ($data['reference'] ?? '')) ?: null,
|
||||
);
|
||||
|
||||
return $this->success([
|
||||
'transaction' => $txn->toArray(),
|
||||
'balance_rials' => $balance,
|
||||
'balance_rials' => $txn->getBalanceAfter(),
|
||||
], 201);
|
||||
}
|
||||
|
||||
/** روش پرداختِ مجاز برای کیف پول؛ ورودیِ ناشناخته نادیده گرفته میشود. */
|
||||
private function normalizeMethod(mixed $method): ?string
|
||||
{
|
||||
$method = is_string($method) ? trim($method) : '';
|
||||
return in_array($method, ['card', 'pos', 'cash', 'gateway', 'wallet'], true) ? $method : null;
|
||||
}
|
||||
|
||||
// ── Call center (کال سنتر) ─────────────────────────────────────────────────
|
||||
|
||||
/** List the patient's call log (newest first, optional ?outcome=success|missed). */
|
||||
@@ -958,8 +962,20 @@ class PatientController extends BaseController
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
|
||||
if (isset($data['notes'])) { $session->setNotes($data['notes']); }
|
||||
if (isset($data['payment_method'])) { $session->setPaymentMethod($data['payment_method']); }
|
||||
if (isset($data['notes'])) { $session->setNotes($data['notes']); }
|
||||
|
||||
if (isset($data['payment_method'])) {
|
||||
$method = (string) $data['payment_method'];
|
||||
// پرداخت از کیف پول: سهمِ بیمار را از موجودی کسر کن (فقط یکبار، اگر
|
||||
// مراجعه هنوز تسویه نشده). موجودیِ ناکافی → AppException (۴۲۲).
|
||||
if ($method === 'wallet'
|
||||
&& $session->getPaymentMethod() === 'pending'
|
||||
&& $session->getFinalPriceRials() > 0
|
||||
) {
|
||||
$this->walletService->settleSessionFromWallet($session, $user);
|
||||
}
|
||||
$session->setPaymentMethod($method);
|
||||
}
|
||||
|
||||
$this->sessionRepo->save($session);
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ class WalletTransaction
|
||||
public const TYPE_CREDIT = 'credit';
|
||||
public const TYPE_DEBIT = 'debit';
|
||||
|
||||
public const STATUS_CONFIRMED = 'confirmed';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
@@ -45,6 +47,26 @@ class WalletTransaction
|
||||
#[ORM\Column(name: 'balance_after', type: 'integer')]
|
||||
private int $balanceAfter;
|
||||
|
||||
/** کاربرِ عاملِ تراکنش (منشی/دکتر که شارژ/برداشت را ثبت کرده) — برای شفافیت. */
|
||||
#[ORM\ManyToOne(targetEntity: User::class)]
|
||||
#[ORM\JoinColumn(name: 'created_by_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
|
||||
private ?User $createdBy = null;
|
||||
|
||||
/** نامِ denormalizedِ کاربرِ عامل، تا خواندنِ دفتر تراکنش join نخواهد. */
|
||||
#[ORM\Column(name: 'created_by_name', type: 'string', length: 120, nullable: true)]
|
||||
private ?string $createdByName = null;
|
||||
|
||||
/** روش پرداخت: card | pos | cash | gateway | wallet. */
|
||||
#[ORM\Column(name: 'payment_method', type: 'string', length: 20, nullable: true)]
|
||||
private ?string $paymentMethod = null;
|
||||
|
||||
/** مرجع/دلیلِ ماشینی تراکنش (مثلاً session:{uuid} برای کسر بابت سرویس). */
|
||||
#[ORM\Column(type: 'string', length: 120, nullable: true)]
|
||||
private ?string $reference = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 15)]
|
||||
private string $status = self::STATUS_CONFIRMED;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
@@ -66,19 +88,33 @@ class WalletTransaction
|
||||
public function getType(): string { return $this->type; }
|
||||
public function getDescription(): ?string { return $this->description; }
|
||||
public function getBalanceAfter(): int { return $this->balanceAfter; }
|
||||
public function getCreatedBy(): ?User { return $this->createdBy; }
|
||||
public function getCreatedByName(): ?string { return $this->createdByName; }
|
||||
public function getPaymentMethod(): ?string { return $this->paymentMethod; }
|
||||
public function getReference(): ?string { return $this->reference; }
|
||||
public function getStatus(): string { return $this->status; }
|
||||
|
||||
public function setPayment(?Payment $p): self { $this->payment = $p; return $this; }
|
||||
public function setDescription(?string $d): self { $this->description = $d; return $this; }
|
||||
public function setCreatedBy(?User $u): self { $this->createdBy = $u; return $this; }
|
||||
public function setCreatedByName(?string $n): self { $this->createdByName = $n; return $this; }
|
||||
public function setPaymentMethod(?string $m): self { $this->paymentMethod = $m; return $this; }
|
||||
public function setReference(?string $r): self { $this->reference = $r; return $this; }
|
||||
public function setStatus(string $s): self { $this->status = $s; return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'amount_rials' => $this->amountRials,
|
||||
'type' => $this->type,
|
||||
'description' => $this->description,
|
||||
'balance_after' => $this->balanceAfter,
|
||||
'created_at' => $this->createdAt,
|
||||
'uuid' => $this->uuid,
|
||||
'amount_rials' => $this->amountRials,
|
||||
'type' => $this->type,
|
||||
'description' => $this->description,
|
||||
'balance_after' => $this->balanceAfter,
|
||||
'created_by_name' => $this->createdByName,
|
||||
'payment_method' => $this->paymentMethod,
|
||||
'reference' => $this->reference,
|
||||
'status' => $this->status,
|
||||
'created_at' => $this->createdAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Settlement\Service;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Patient\Entity\PatientSession;
|
||||
use App\Patient\Entity\SessionService;
|
||||
use App\Settlement\Entity\WalletTransaction;
|
||||
use App\Settlement\Repository\SettlementRepository;
|
||||
use App\Settlement\Repository\WalletTransactionRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
use App\UserProfile\Repository\UserProfileRepository;
|
||||
|
||||
/**
|
||||
* منطق کیف پولِ بیمار: موجودی، شارژ (credit)، برداشت (debit) و تسویهٔ سرویس از
|
||||
* کیف پول — همگی با ثبتِ کاربرِ عامل، روش پرداخت و دلیل برای شفافیت کامل.
|
||||
* موجودی همیشه از مجموع credit − debit مشتق میشود (SettlementRepository).
|
||||
*/
|
||||
class WalletService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly WalletTransactionRepository $walletRepo,
|
||||
private readonly SettlementRepository $settlementRepo,
|
||||
private readonly UserProfileRepository $profileRepo,
|
||||
) {}
|
||||
|
||||
public function balance(User $patient): int
|
||||
{
|
||||
return $this->settlementRepo->getWalletBalance($patient);
|
||||
}
|
||||
|
||||
/** نامِ نمایشیِ کاربرِ عامل (برای ستون «ثبتکننده»)؛ در نبودِ پروفایل، شماره موبایل. */
|
||||
public function resolveActorName(?User $actor): ?string
|
||||
{
|
||||
if ($actor === null) {
|
||||
return null;
|
||||
}
|
||||
$profile = $this->profileRepo->findByUser($actor);
|
||||
$name = trim(($profile?->getLabel() ?? '') . ' ' . ($profile?->getFamily() ?? ''));
|
||||
|
||||
return $name !== '' ? $name : $actor->getMobileNumber();
|
||||
}
|
||||
|
||||
/** شارژِ کیف پول (credit). فرض بر مثبت بودنِ مبلغ است (اعتبارسنجی در Controller). */
|
||||
public function charge(
|
||||
User $patient,
|
||||
int $amountRials,
|
||||
?User $actor = null,
|
||||
?string $description = null,
|
||||
?string $paymentMethod = null,
|
||||
?string $reference = null,
|
||||
): WalletTransaction {
|
||||
$balanceAfter = $this->balance($patient) + $amountRials;
|
||||
|
||||
return $this->record(
|
||||
$patient, $amountRials, WalletTransaction::TYPE_CREDIT, $balanceAfter, $actor,
|
||||
$description !== null && $description !== '' ? $description : 'شارژ کیف پول',
|
||||
$paymentMethod, $reference,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* برداشت از کیف پول (debit). اگر مبلغ از موجودی بیشتر باشد
|
||||
* AppException با کد ERR_WALLET_INSUFFICIENT (۴۲۲) پرتاب میشود.
|
||||
*/
|
||||
public function withdraw(
|
||||
User $patient,
|
||||
int $amountRials,
|
||||
?User $actor = null,
|
||||
?string $description = null,
|
||||
?string $paymentMethod = null,
|
||||
?string $reference = null,
|
||||
): WalletTransaction {
|
||||
$current = $this->balance($patient);
|
||||
if ($amountRials > $current) {
|
||||
throw new AppException(ErrorCodes::ERR_WALLET_INSUFFICIENT, null, 422, 'amount_rials');
|
||||
}
|
||||
|
||||
return $this->record(
|
||||
$patient, $amountRials, WalletTransaction::TYPE_DEBIT, $current - $amountRials, $actor,
|
||||
$description !== null && $description !== '' ? $description : 'برداشت از کیف پول',
|
||||
$paymentMethod, $reference,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* تسویهٔ یک مراجعه از کیف پول: مبلغِ نهاییِ سهمِ بیمار را بهصورت debit کسر
|
||||
* میکند و دلیل را به نامِ سرویسها و شناسهٔ مراجعه گره میزند. موجودیِ ناکافی → ۴۲۲.
|
||||
*/
|
||||
public function settleSessionFromWallet(PatientSession $session, ?User $actor = null): WalletTransaction
|
||||
{
|
||||
$patient = $session->getRecord()->getUser();
|
||||
$amount = $session->getFinalPriceRials();
|
||||
|
||||
$names = array_values(array_filter(array_map(
|
||||
fn(SessionService $s) => $s->toArray()['service_name'] ?? null,
|
||||
$session->getServices()->toArray(),
|
||||
)));
|
||||
$label = $names !== [] ? implode('، ', $names) : 'ویزیت';
|
||||
|
||||
return $this->withdraw(
|
||||
$patient, $amount, $actor,
|
||||
'پرداخت سرویس: ' . $label,
|
||||
'wallet',
|
||||
'session:' . $session->getUuid(),
|
||||
);
|
||||
}
|
||||
|
||||
private function record(
|
||||
User $patient,
|
||||
int $amountRials,
|
||||
string $type,
|
||||
int $balanceAfter,
|
||||
?User $actor,
|
||||
string $description,
|
||||
?string $paymentMethod,
|
||||
?string $reference,
|
||||
): WalletTransaction {
|
||||
$txn = new WalletTransaction($patient, $amountRials, $type, $balanceAfter);
|
||||
$txn->setDescription($description)
|
||||
->setCreatedBy($actor)
|
||||
->setCreatedByName($this->resolveActorName($actor))
|
||||
->setPaymentMethod($paymentMethod)
|
||||
->setReference($reference)
|
||||
->setStatus(WalletTransaction::STATUS_CONFIRMED);
|
||||
$this->walletRepo->save($txn);
|
||||
|
||||
return $txn;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user