feat(claims): add tracking number and status history for claims
- Introduced `tracking_number` field in the `claims` table to store the insurance tracking number. - Created `claim_status_logs` table to maintain a history of status changes for claims, including who made the change and when. - Implemented `ClaimStatusLog` entity and repository for managing status log entries. - Updated `ClaimService` to log transitions and handle tracking numbers during claim submissions. - Added new API endpoint for fetching claims by patient, including detailed claim history and status logs. - Enhanced frontend with a new `ClaimPatientDetailPage` to display claims and their status history. - Added tests to ensure correct aggregation of claims and proper handling of status transitions.
This commit is contained in:
@@ -5,6 +5,7 @@ namespace App\Billing\Controller;
|
||||
use App\Auth\Entity\User;
|
||||
use App\Billing\Entity\Claim;
|
||||
use App\Billing\Repository\ClaimRepository;
|
||||
use App\Billing\Repository\ClaimStatusLogRepository;
|
||||
use App\Billing\Repository\InvoiceItemRepository;
|
||||
use App\Billing\Repository\InvoiceRepository;
|
||||
use App\Billing\Service\ClaimService;
|
||||
@@ -35,6 +36,7 @@ class BillingController extends BaseController
|
||||
private readonly PatientSessionRepository $sessionRepo,
|
||||
private readonly PatientRecordRepository $recordRepo,
|
||||
private readonly InsuranceRepository $insuranceRepo,
|
||||
private readonly ClaimStatusLogRepository $statusLogRepo,
|
||||
private readonly PatientRecordScopeResolver $scopeResolver,
|
||||
) {}
|
||||
|
||||
@@ -279,6 +281,120 @@ class BillingController extends BaseController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* نمای سطحاول داشبورد مطالبات: یک ردیف بهازای هر بیمار با جمعهای تجمیعی.
|
||||
* فیلترها همان فیلترهای مطالبهاند و روی count هم اعمال میشوند.
|
||||
*/
|
||||
#[Route('/api/v1/billing/claims/by-patient', methods: ['GET'])]
|
||||
public function claimsByPatient(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$filters = $this->claimFilters($request);
|
||||
$page = max(1, (int) $request->query->get('page', 1));
|
||||
$limit = min(100, max(1, (int) $request->query->get('limit', 20)));
|
||||
$sort = (string) $request->query->get('sort', 'last_activity_at');
|
||||
$dir = (string) $request->query->get('dir', 'desc');
|
||||
|
||||
$rows = $this->claimRepo->aggregateByPatient($entityType, $entityId, $filters, $sort, $dir, $page, $limit);
|
||||
$total = $this->claimRepo->countPatientsWithClaims($entityType, $entityId, $filters);
|
||||
|
||||
return $this->paginated($rows, $total, $page, $limit);
|
||||
}
|
||||
|
||||
/** جزئیات کامل مطالبات یک بیمار، بههمراه تاریخچهی تغییر وضعیت هر مطالبه. */
|
||||
#[Route('/api/v1/billing/claims/by-patient/{patientUuid}', methods: ['GET'])]
|
||||
public function claimsForPatient(string $patientUuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$record = $this->recordRepo->findByUuid($patientUuid);
|
||||
if ($record === null || $record->getEntityType() !== $entityType || $record->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'پرونده بیمار یافت نشد', 404);
|
||||
}
|
||||
|
||||
$rows = $this->claimRepo->detailsForPatient($entityType, $entityId, (int) $record->getId(), $this->claimFilters($request));
|
||||
$timelines = $this->statusLogRepo->timelinesForClaims(array_map(static fn(array $r) => (int) $r['claim_id'], $rows));
|
||||
|
||||
$insuranceNames = $this->insuranceNamesFor(array_map(static fn(array $r) => (int) $r['insurance_id'], $rows));
|
||||
|
||||
$items = array_map(function (array $r) use ($timelines, $insuranceNames) {
|
||||
$claimed = (int) $r['total_claimed_rials'];
|
||||
$base = (int) $r['service_base_rials'];
|
||||
|
||||
return [
|
||||
'uuid' => $r['uuid'],
|
||||
'invoice_uuid' => $r['invoice_uuid'],
|
||||
'visit_date' => $r['visit_date'] !== null ? (int) $r['visit_date'] : null,
|
||||
'doctor_name' => $r['doctor_name'],
|
||||
'insurance_id' => (int) $r['insurance_id'],
|
||||
'insurance_name' => $insuranceNames[(int) $r['insurance_id']] ?? null,
|
||||
'insurance_kind' => $r['insurance_kind'],
|
||||
'service_base_rials' => $base,
|
||||
'coverage_percent' => $base > 0 ? round($claimed * 100 / $base, 2) : 0.0,
|
||||
'insurance_share_rials'=> $claimed,
|
||||
'patient_share_rials' => (int) $r['patient_share_rials'],
|
||||
'total_approved_rials' => $r['total_approved_rials'] !== null ? (int) $r['total_approved_rials'] : null,
|
||||
'total_paid_rials' => $r['total_paid_rials'] !== null ? (int) $r['total_paid_rials'] : null,
|
||||
'status' => $r['status'],
|
||||
'tracking_number' => $r['tracking_number'],
|
||||
'reject_reason' => $r['reject_reason'],
|
||||
'submitted_at' => $r['submitted_at'] !== null ? (int) $r['submitted_at'] : null,
|
||||
'settled_at' => $r['settled_at'] !== null ? (int) $r['settled_at'] : null,
|
||||
'created_at' => (int) $r['created_at'],
|
||||
'allowed_transitions' => Claim::transitionsFrom($r['status']),
|
||||
'logs' => $timelines[(int) $r['claim_id']] ?? [],
|
||||
];
|
||||
}, $rows);
|
||||
|
||||
return $this->success([
|
||||
'patient' => [
|
||||
'uuid' => $record->getUser()->getUuid(),
|
||||
'record_uuid' => $record->getUuid(),
|
||||
'full_name' => $record->getUser()->getRealName(),
|
||||
'mobile' => $record->getUser()->getMobileNumber(),
|
||||
'national_code' => $record->getUser()->getNationalCode(),
|
||||
],
|
||||
'claims' => $items,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param int[] $ids @return array<int, string> */
|
||||
private function insuranceNamesFor(array $ids): array
|
||||
{
|
||||
$unique = array_values(array_unique($ids));
|
||||
if ($unique === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$names = [];
|
||||
foreach ($this->insuranceRepo->findBy(['id' => $unique]) as $insurance) {
|
||||
$names[$insurance->getId()] = $insurance->getName();
|
||||
}
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function claimFilters(Request $request): array
|
||||
{
|
||||
return [
|
||||
'status' => $request->query->get('status') ?: null,
|
||||
'insurance_id' => $request->query->get('insurance_id') ?: null,
|
||||
'doctor_id' => $request->query->get('doctor_id') ?: null,
|
||||
'payment_status' => $request->query->get('payment_status') ?: null,
|
||||
'from' => $request->query->get('from') ?: null,
|
||||
'to' => $request->query->get('to') ?: null,
|
||||
'search' => $request->query->get('search') ?: null,
|
||||
];
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/claims/{uuid}/{action}', methods: ['POST'], requirements: ['action' => 'submit|approve|reject|pay'])]
|
||||
public function transitionClaim(string $uuid, string $action, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
@@ -296,10 +412,6 @@ class BillingController extends BaseController
|
||||
'pay' => Claim::STATUS_PAID,
|
||||
};
|
||||
|
||||
if ($action === 'reject' && trim($data['reason'] ?? '') === '') {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'دلیل رد الزامی است', 422);
|
||||
}
|
||||
|
||||
// Bound the financial figures: approved/paid cannot be negative, approved
|
||||
// cannot exceed the claimed total, and paid cannot exceed approved.
|
||||
if ($action === 'approve' && isset($data['approved_rials'])) {
|
||||
@@ -317,10 +429,12 @@ class BillingController extends BaseController
|
||||
}
|
||||
|
||||
$this->claimService->transition($claim, $target, [
|
||||
'approved_rials' => isset($data['approved_rials']) ? (int) $data['approved_rials'] : null,
|
||||
'paid_rials' => isset($data['paid_rials']) ? (int) $data['paid_rials'] : null,
|
||||
'reason' => trim($data['reason'] ?? ''),
|
||||
]);
|
||||
'approved_rials' => isset($data['approved_rials']) ? (int) $data['approved_rials'] : null,
|
||||
'paid_rials' => isset($data['paid_rials']) ? (int) $data['paid_rials'] : null,
|
||||
'reason' => trim($data['reason'] ?? ''),
|
||||
'tracking_number' => isset($data['tracking_number']) ? trim((string) $data['tracking_number']) : null,
|
||||
'note' => isset($data['note']) ? trim((string) $data['note']) : null,
|
||||
], $user);
|
||||
|
||||
return $this->success(['data' => $this->enrichClaims([$claim])[0]]);
|
||||
}
|
||||
|
||||
@@ -66,6 +66,10 @@ class Claim
|
||||
#[ORM\Column(name: 'reject_reason', type: 'text', nullable: true)]
|
||||
private ?string $rejectReason = null;
|
||||
|
||||
/** شماره پرونده/پیگیری نزد بیمهگر — هنگام ارسال وارد میشود. */
|
||||
#[ORM\Column(name: 'tracking_number', type: 'string', length: 60, nullable: true)]
|
||||
private ?string $trackingNumber = null;
|
||||
|
||||
#[ORM\Column(name: 'submitted_at', type: 'integer', nullable: true)]
|
||||
private ?int $submittedAt = null;
|
||||
|
||||
@@ -119,6 +123,41 @@ class Claim
|
||||
return in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* انتقالهای مجاز از وضعیت فعلی. پنل دکمهها را از همین میسازد تا فهرست
|
||||
* مجاز فقط یکجا تعریف شده باشد.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function allowedTransitions(): array
|
||||
{
|
||||
return self::transitionsFrom($this->status);
|
||||
}
|
||||
|
||||
/**
|
||||
* همان جدول انتقال، برای مسیرهایی که ردیف خام (array hydration) دارند و
|
||||
* موجودیت را هیدریت نمیکنند.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function transitionsFrom(string $status): array
|
||||
{
|
||||
return self::TRANSITIONS[$status] ?? [];
|
||||
}
|
||||
|
||||
public function getTrackingNumber(): ?string { return $this->trackingNumber; }
|
||||
public function getRejectReason(): ?string { return $this->rejectReason; }
|
||||
public function getSubmittedAt(): ?int { return $this->submittedAt; }
|
||||
public function getSettledAt(): ?int { return $this->settledAt; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
|
||||
public function setTrackingNumber(?string $v): self
|
||||
{
|
||||
$this->trackingNumber = $v !== null && trim($v) !== '' ? trim($v) : null;
|
||||
$this->updatedAt = time();
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function submit(): void
|
||||
{
|
||||
$this->status = self::STATUS_SUBMITTED;
|
||||
@@ -162,6 +201,8 @@ class Claim
|
||||
'total_paid_rials' => $this->totalPaidRials,
|
||||
'status' => $this->status,
|
||||
'reject_reason' => $this->rejectReason,
|
||||
'tracking_number' => $this->trackingNumber,
|
||||
'allowed_transitions' => $this->allowedTransitions(),
|
||||
'submitted_at' => $this->submittedAt,
|
||||
'settled_at' => $this->settledAt,
|
||||
'created_at' => $this->createdAt,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Entity;
|
||||
|
||||
use App\Billing\Repository\ClaimStatusLogRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* تاریخچهی تغییر وضعیت یک مطالبه.
|
||||
*
|
||||
* وضعیت روی خودِ Claim فقط «آخرین حالت» است؛ پیگیری پروندهی بیمه نیاز دارد بداند
|
||||
* چه کسی، کِی و با چه توضیحی آن را جابهجا کرده است.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: ClaimStatusLogRepository::class)]
|
||||
#[ORM\Table(name: 'claim_status_logs')]
|
||||
#[ORM\Index(columns: ['claim_id'], name: 'idx_claim_status_log_claim')]
|
||||
class ClaimStatusLog
|
||||
{
|
||||
#[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: 'claim_id', type: 'integer')]
|
||||
private int $claimId;
|
||||
|
||||
/** null فقط برای ردیف ساخت اولیه. */
|
||||
#[ORM\Column(name: 'from_status', type: 'string', length: 15, nullable: true)]
|
||||
private ?string $fromStatus = null;
|
||||
|
||||
#[ORM\Column(name: 'to_status', type: 'string', length: 15)]
|
||||
private string $toStatus;
|
||||
|
||||
#[ORM\Column(type: 'text', nullable: true)]
|
||||
private ?string $note = null;
|
||||
|
||||
/** null یعنی سیستمی (backfill یا اتوماسیون). */
|
||||
#[ORM\Column(name: 'created_by_id', type: 'integer', nullable: true)]
|
||||
private ?int $createdById = null;
|
||||
|
||||
#[ORM\Column(name: 'created_by_name', type: 'string', length: 120, nullable: true)]
|
||||
private ?string $createdByName = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
public function __construct(int $claimId, ?string $fromStatus, string $toStatus)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->claimId = $claimId;
|
||||
$this->fromStatus = $fromStatus;
|
||||
$this->toStatus = $toStatus;
|
||||
$this->createdAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getClaimId(): int { return $this->claimId; }
|
||||
public function getToStatus(): string { return $this->toStatus; }
|
||||
|
||||
public function setNote(?string $note): self
|
||||
{
|
||||
$this->note = $note !== null && trim($note) !== '' ? trim($note) : null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setActor(?int $userId, ?string $name): self
|
||||
{
|
||||
$this->createdById = $userId;
|
||||
$this->createdByName = $name;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCreatedAt(int $at): self
|
||||
{
|
||||
$this->createdAt = $at;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'from_status' => $this->fromStatus,
|
||||
'to_status' => $this->toStatus,
|
||||
'note' => $this->note,
|
||||
'by' => $this->createdByName,
|
||||
'at' => $this->createdAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,216 @@ class ClaimRepository extends ServiceEntityRepository
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* تجمیع مطالبات بر اساس بیمار — نمای سطحاول داشبورد.
|
||||
*
|
||||
* مبالغ خدمات/سهم بیمار از صورتحسابهای **یکتا** جمع میشوند، نه از مطالبات؛ یک
|
||||
* صورتحساب میتواند دو مطالبه (پایه و مکمل) داشته باشد و جمعزدن از سمت مطالبه
|
||||
* مبلغ خدمات را دوبار میشمرد.
|
||||
*
|
||||
* @param array<string, mixed> $filters
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function aggregateByPatient(string $entityType, int $entityId, array $filters, string $sort, string $dir, int $page, int $limit): array
|
||||
{
|
||||
[$where, $params] = $this->patientAggregateFilters($filters);
|
||||
|
||||
$orderBy = match ($sort) {
|
||||
'claims_count' => 'claims_count',
|
||||
'total_services_rials' => 'total_services_rials',
|
||||
'total_insurance_rials' => 'total_insurance_rials',
|
||||
'last_activity_at' => 'last_activity_at',
|
||||
default => 'full_name',
|
||||
};
|
||||
$direction = strtolower($dir) === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
// LIMIT/OFFSET بهصورت مقدار درج میشوند: MariaDB پارامتر رشتهای در LIMIT نمیپذیرد.
|
||||
// هر دو از قبل به int تبدیل شدهاند، پس تزریقی ممکن نیست.
|
||||
$offset = ($page - 1) * $limit;
|
||||
$sql = $this->patientAggregateSql($where)
|
||||
. " ORDER BY {$orderBy} {$direction} LIMIT {$limit} OFFSET {$offset}";
|
||||
|
||||
$params['type'] = $entityType;
|
||||
$params['id'] = $entityId;
|
||||
|
||||
$rows = $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchAllAssociative();
|
||||
|
||||
return array_map(static function (array $r): array {
|
||||
$statuses = array_filter(explode(',', (string) $r['statuses']));
|
||||
|
||||
return [
|
||||
'patient_uuid' => $r['patient_uuid'],
|
||||
'record_uuid' => $r['record_uuid'],
|
||||
'full_name' => $r['full_name'],
|
||||
'mobile' => $r['mobile'],
|
||||
'national_code' => $r['national_code'],
|
||||
'claims_count' => (int) $r['claims_count'],
|
||||
'total_services_rials' => (int) $r['total_services_rials'],
|
||||
'total_insurance_rials' => (int) $r['total_insurance_rials'],
|
||||
'total_patient_rials' => (int) $r['total_patient_rials'],
|
||||
'total_approved_rials' => (int) $r['total_approved_rials'],
|
||||
'total_paid_rials' => (int) $r['total_paid_rials'],
|
||||
'overall_status' => count($statuses) === 1 ? reset($statuses) : 'mixed',
|
||||
'last_activity_at' => (int) $r['last_activity_at'],
|
||||
];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
public function countPatientsWithClaims(string $entityType, int $entityId, array $filters): int
|
||||
{
|
||||
[$where, $params] = $this->patientAggregateFilters($filters);
|
||||
$params['type'] = $entityType;
|
||||
$params['id'] = $entityId;
|
||||
|
||||
$sql = 'SELECT COUNT(*) FROM (' . $this->patientAggregateSql($where) . ') agg';
|
||||
|
||||
return (int) $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchOne();
|
||||
}
|
||||
|
||||
private function patientAggregateSql(string $where): string
|
||||
{
|
||||
return <<<SQL
|
||||
WITH claim_map AS (
|
||||
SELECT c.id AS claim_id, MIN(inv.id) AS invoice_id, MIN(inv.patient_record_id) AS record_id
|
||||
FROM claims c
|
||||
JOIN claim_items ci ON ci.claim_id = c.id
|
||||
JOIN invoice_items ii ON ii.id = ci.invoice_item_id
|
||||
JOIN invoices inv ON inv.id = ii.invoice_id
|
||||
WHERE c.entity_type = :type AND c.entity_id = :id
|
||||
GROUP BY c.id
|
||||
)
|
||||
SELECT
|
||||
u.uuid AS patient_uuid,
|
||||
pr.uuid AS record_uuid,
|
||||
u.real_name AS full_name,
|
||||
u.mobile_number AS mobile,
|
||||
u.national_code AS national_code,
|
||||
COUNT(DISTINCT c.id) AS claims_count,
|
||||
COALESCE(SUM(c.total_claimed_rials), 0) AS total_insurance_rials,
|
||||
COALESCE(SUM(c.total_approved_rials), 0) AS total_approved_rials,
|
||||
COALESCE(SUM(c.total_paid_rials), 0) AS total_paid_rials,
|
||||
COALESCE((
|
||||
SELECT SUM(i2.total_rials) FROM invoices i2
|
||||
WHERE i2.id IN (SELECT DISTINCT cm2.invoice_id FROM claim_map cm2 WHERE cm2.record_id = pr.id)
|
||||
), 0) AS total_services_rials,
|
||||
COALESCE((
|
||||
SELECT SUM(i3.patient_rials) FROM invoices i3
|
||||
WHERE i3.id IN (SELECT DISTINCT cm3.invoice_id FROM claim_map cm3 WHERE cm3.record_id = pr.id)
|
||||
), 0) AS total_patient_rials,
|
||||
GROUP_CONCAT(DISTINCT c.status) AS statuses,
|
||||
MAX(c.updated_at) AS last_activity_at
|
||||
FROM claim_map cm
|
||||
JOIN claims c ON c.id = cm.claim_id
|
||||
JOIN invoices inv ON inv.id = cm.invoice_id
|
||||
JOIN patient_records pr ON pr.id = cm.record_id
|
||||
JOIN users u ON u.id = pr.user_id
|
||||
{$where}
|
||||
GROUP BY pr.id, u.uuid, pr.uuid, u.real_name, u.mobile_number, u.national_code
|
||||
SQL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $filters
|
||||
* @return array{0: string, 1: array<string, mixed>}
|
||||
*/
|
||||
private function patientAggregateFilters(array $filters): array
|
||||
{
|
||||
$conditions = [];
|
||||
$params = [];
|
||||
|
||||
if (!empty($filters['status'])) {
|
||||
$conditions[] = 'c.status = :status';
|
||||
$params['status'] = $filters['status'];
|
||||
}
|
||||
if (!empty($filters['insurance_id'])) {
|
||||
$conditions[] = 'c.insurance_id = :insId';
|
||||
$params['insId'] = (int) $filters['insurance_id'];
|
||||
}
|
||||
if (!empty($filters['from'])) {
|
||||
$conditions[] = 'c.created_at >= :from';
|
||||
$params['from'] = (int) $filters['from'];
|
||||
}
|
||||
if (!empty($filters['to'])) {
|
||||
$conditions[] = 'c.created_at <= :to';
|
||||
$params['to'] = (int) $filters['to'];
|
||||
}
|
||||
if (!empty($filters['doctor_id'])) {
|
||||
$conditions[] = 'EXISTS (SELECT 1 FROM patient_sessions ps '
|
||||
. 'JOIN appointments a ON a.id = ps.appointment_id '
|
||||
. 'WHERE ps.id = inv.patient_session_id AND a.doctor_id = :docId)';
|
||||
$params['docId'] = (int) $filters['doctor_id'];
|
||||
}
|
||||
if (!empty($filters['payment_status'])) {
|
||||
$conditions[] = $filters['payment_status'] === 'paid'
|
||||
? 'c.status = \'paid\''
|
||||
: 'c.status <> \'paid\'';
|
||||
}
|
||||
if (!empty($filters['search'])) {
|
||||
$conditions[] = '(u.real_name LIKE :search OR u.mobile_number LIKE :search OR u.national_code LIKE :search)';
|
||||
$params['search'] = '%' . trim((string) $filters['search']) . '%';
|
||||
}
|
||||
|
||||
return [$conditions === [] ? '' : 'WHERE ' . implode(' AND ', $conditions), $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* مطالبات یک بیمار با جزئیات نمایشی (پزشک، سرویس، تاریخ مراجعه، سهمها).
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function detailsForPatient(string $entityType, int $entityId, int $recordId, array $filters): array
|
||||
{
|
||||
[$where, $params] = $this->patientAggregateFilters($filters);
|
||||
$where = $where === '' ? 'WHERE pr.id = :recordId' : $where . ' AND pr.id = :recordId';
|
||||
|
||||
$params['type'] = $entityType;
|
||||
$params['id'] = $entityId;
|
||||
$params['recordId'] = $recordId;
|
||||
|
||||
$sql = <<<SQL
|
||||
WITH claim_map AS (
|
||||
SELECT c.id AS claim_id, MIN(inv.id) AS invoice_id, MIN(inv.patient_record_id) AS record_id
|
||||
FROM claims c
|
||||
JOIN claim_items ci ON ci.claim_id = c.id
|
||||
JOIN invoice_items ii ON ii.id = ci.invoice_item_id
|
||||
JOIN invoices inv ON inv.id = ii.invoice_id
|
||||
WHERE c.entity_type = :type AND c.entity_id = :id
|
||||
GROUP BY c.id
|
||||
)
|
||||
SELECT
|
||||
c.id AS claim_id,
|
||||
c.uuid,
|
||||
c.insurance_id,
|
||||
c.insurance_kind,
|
||||
c.status,
|
||||
c.total_claimed_rials,
|
||||
c.total_approved_rials,
|
||||
c.total_paid_rials,
|
||||
c.reject_reason,
|
||||
c.tracking_number,
|
||||
c.submitted_at,
|
||||
c.settled_at,
|
||||
c.created_at,
|
||||
inv.uuid AS invoice_uuid,
|
||||
inv.total_rials AS service_base_rials,
|
||||
inv.patient_rials AS patient_share_rials,
|
||||
ps.session_at AS visit_date,
|
||||
d.name AS doctor_name
|
||||
FROM claim_map cm
|
||||
JOIN claims c ON c.id = cm.claim_id
|
||||
JOIN invoices inv ON inv.id = cm.invoice_id
|
||||
JOIN patient_records pr ON pr.id = cm.record_id
|
||||
JOIN users u ON u.id = pr.user_id
|
||||
LEFT JOIN patient_sessions ps ON ps.id = inv.patient_session_id
|
||||
LEFT JOIN appointments a ON a.id = ps.appointment_id
|
||||
LEFT JOIN doctors d ON d.id = a.doctor_id
|
||||
{$where}
|
||||
ORDER BY c.created_at DESC, c.id DESC
|
||||
SQL;
|
||||
|
||||
return $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchAllAssociative();
|
||||
}
|
||||
|
||||
/** آیا برای این صورتحساب از قبل مطالبهای ساخته شده؟ (از طریق آیتمهای صورتحساب) */
|
||||
public function existsForInvoice(int $invoiceId): bool
|
||||
{
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\ClaimStatusLog;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class ClaimStatusLogRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, ClaimStatusLog::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* تاریخچهی چند مطالبه در یک رفتوآمد، گروهبندیشده بر اساس claim_id.
|
||||
*
|
||||
* @param int[] $claimIds
|
||||
* @return array<int, array<int, array<string, mixed>>>
|
||||
*/
|
||||
public function timelinesForClaims(array $claimIds): array
|
||||
{
|
||||
if ($claimIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$logs = $this->createQueryBuilder('l')
|
||||
->where('l.claimId IN (:ids)')
|
||||
->setParameter('ids', $claimIds)
|
||||
->orderBy('l.createdAt', 'ASC')
|
||||
->addOrderBy('l.id', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$grouped = [];
|
||||
foreach ($logs as $log) {
|
||||
$grouped[$log->getClaimId()][] = $log->toArray();
|
||||
}
|
||||
|
||||
return $grouped;
|
||||
}
|
||||
|
||||
public function save(ClaimStatusLog $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,10 @@ use App\Billing\Contract\ClaimSubmitterInterface;
|
||||
use App\Billing\Entity\Claim;
|
||||
use App\Billing\Entity\ClaimItem;
|
||||
use App\Billing\Entity\Invoice;
|
||||
use App\Billing\Entity\ClaimStatusLog;
|
||||
use App\Billing\Repository\ClaimRepository;
|
||||
use App\Billing\Repository\ClaimStatusLogRepository;
|
||||
use App\Auth\Entity\User;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
@@ -15,6 +18,7 @@ class ClaimService
|
||||
public function __construct(
|
||||
private readonly ClaimRepository $claimRepo,
|
||||
private readonly ClaimSubmitterInterface $submitter,
|
||||
private readonly ClaimStatusLogRepository $statusLogRepo,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -59,6 +63,12 @@ class ClaimService
|
||||
}
|
||||
$this->claimRepo->getEntityManager()->flush();
|
||||
|
||||
// بعد از flush تا id مطالبه موجود باشد.
|
||||
foreach ($claims as $claim) {
|
||||
$this->logTransition($claim, null, $claim->getStatus(), 'ایجاد مطالبه', null);
|
||||
}
|
||||
$this->claimRepo->getEntityManager()->flush();
|
||||
|
||||
return $claims;
|
||||
}
|
||||
|
||||
@@ -81,7 +91,7 @@ class ClaimService
|
||||
return $hasShare ? $claim : null;
|
||||
}
|
||||
|
||||
public function transition(Claim $claim, string $target, array $opts = []): void
|
||||
public function transition(Claim $claim, string $target, array $opts = [], ?User $actor = null): void
|
||||
{
|
||||
if (!$claim->canTransitionTo($target)) {
|
||||
throw new AppException(
|
||||
@@ -91,23 +101,43 @@ class ClaimService
|
||||
);
|
||||
}
|
||||
|
||||
if ($target === Claim::STATUS_REJECTED && trim((string) ($opts['reason'] ?? '')) === '') {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'دلیل رد الزامی است', 422, 'reason');
|
||||
}
|
||||
|
||||
$from = $claim->getStatus();
|
||||
|
||||
match ($target) {
|
||||
Claim::STATUS_SUBMITTED => $this->doSubmit($claim),
|
||||
Claim::STATUS_SUBMITTED => $this->doSubmit($claim, $opts['tracking_number'] ?? null),
|
||||
Claim::STATUS_APPROVED => $claim->approve($opts['approved_rials'] ?? null),
|
||||
Claim::STATUS_REJECTED => $claim->reject($opts['reason'] ?? ''),
|
||||
Claim::STATUS_PAID => $claim->pay($opts['paid_rials'] ?? null),
|
||||
default => throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'وضعیت نامعتبر', 422),
|
||||
};
|
||||
|
||||
$this->claimRepo->save($claim);
|
||||
$this->claimRepo->save($claim, false);
|
||||
$this->logTransition($claim, $from, $target, $opts['note'] ?? $opts['reason'] ?? null, $actor);
|
||||
$this->claimRepo->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
private function doSubmit(Claim $claim): void
|
||||
private function logTransition(Claim $claim, ?string $from, string $to, ?string $note, ?User $actor): void
|
||||
{
|
||||
$log = (new ClaimStatusLog((int) $claim->getId(), $from, $to))
|
||||
->setNote($note)
|
||||
->setActor($actor?->getId(), $actor?->getRealName() ?? $actor?->getMobileNumber());
|
||||
|
||||
$this->statusLogRepo->save($log, false);
|
||||
}
|
||||
|
||||
private function doSubmit(Claim $claim, ?string $trackingNumber): void
|
||||
{
|
||||
$result = $this->submitter->submit($claim);
|
||||
if (!$result->success) {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, $result->errorMessage ?? 'ارسال مطالبه ناموفق بود', 422);
|
||||
}
|
||||
$claim->submit();
|
||||
if ($trackingNumber !== null) {
|
||||
$claim->setTrackingNumber((string) $trackingNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user