Implement SMS panel user flow and patient records system; add wallet charging, automatic reminders, and patient session management with detailed database schema and user flows.

This commit is contained in:
hamed
2026-06-14 21:15:40 +03:30
parent a72a6da621
commit b58aacc37f
28 changed files with 3169 additions and 0 deletions
@@ -0,0 +1,204 @@
# معماری — تسک ۱۵: پرونده بیمار
## ساختار فایل‌ها
```
src/Patient/
├── Controller/
│ └── PatientController.php
├── Entity/
│ ├── PatientRecord.php
│ ├── PatientSession.php
│ └── SessionService.php ← entity (سرویس‌های انجام‌شده در سشن)
├── Repository/
│ ├── PatientRecordRepository.php
│ └── PatientSessionRepository.php
└── Service/
└── PatientService.php
```
**فایل‌هایی که تغییر می‌کنند:**
- `src/Appointment/Controller/AppointmentController.php` — متد `updateStatus()` باید `PatientService::autoCreateOnAppointmentConfirm()` صدا بزند
## Entity: PatientRecord
```php
#[ORM\Entity]
#[ORM\Table(name: 'patient_records')]
#[ORM\UniqueConstraint(name: 'uniq_patient_record', columns: ['entity_type', 'entity_id', 'user_id'])]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_patient_records_entity')]
class PatientRecord
{
#[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(type: 'string', length: 10)]
private string $entityType; // 'doctor' | 'clinic'
#[ORM\Column(type: 'integer')]
private int $entityId;
#[ORM\ManyToOne(targetEntity: \App\Auth\Entity\User::class)]
#[ORM\JoinColumn(name: 'user_id', nullable: false, onDelete: 'RESTRICT')]
private \App\Auth\Entity\User $user;
// چه کسی پرونده را باز کرد
#[ORM\Column(type: 'string', length: 15)]
private string $createdByType; // 'doctor' | 'secretary' | 'system'
#[ORM\Column(type: 'integer')]
private int $createdById;
#[ORM\Column(type: 'integer')]
private int $createdAt;
}
```
## Entity: PatientSession
```php
#[ORM\Entity]
#[ORM\Table(name: 'patient_sessions')]
#[ORM\Index(columns: ['record_id', 'created_at'], name: 'idx_patient_sessions_record')]
class PatientSession
{
#[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: PatientRecord::class)]
#[ORM\JoinColumn(name: 'record_id', nullable: false, onDelete: 'CASCADE')]
private PatientRecord $record;
#[ORM\ManyToOne(targetEntity: \App\Appointment\Entity\Appointment::class)]
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
private ?\App\Appointment\Entity\Appointment $appointment = null;
// بیمه پایه — FK به categories bundle='insurance_type'
#[ORM\Column(type: 'integer', nullable: true)]
private ?int $insuranceBaseId = null;
#[ORM\Column(type: 'integer', nullable: true)]
private ?int $insuranceSupplementaryId = null;
#[ORM\Column(type: 'integer')]
private int $visitPriceRials = 0;
#[ORM\Column(type: 'decimal', precision: 5, scale: 2)]
private float $baseInsuranceDiscountPercent = 0;
#[ORM\Column(type: 'decimal', precision: 5, scale: 2)]
private float $supplementaryDiscountPercent = 0;
#[ORM\Column(type: 'integer')]
private int $servicesTotalRials = 0;
#[ORM\Column(type: 'integer')]
private int $finalPriceRials = 0;
#[ORM\Column(type: 'string', length: 15)]
private string $paymentMethod = 'pending'; // 'cash'|'card'|'insurance'|'pending'
#[ORM\Column(type: 'text', nullable: true)]
private ?string $notes = null;
#[ORM\Column(type: 'integer')]
private int $createdAt;
#[ORM\Column(type: 'integer')]
private int $updatedAt;
}
```
## Entity: SessionService (سرویس‌های انجام‌شده در سشن)
```php
#[ORM\Entity]
#[ORM\Table(name: 'session_services')]
class SessionService
{
#[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)]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private PatientSession $session;
#[ORM\ManyToOne(targetEntity: \App\ClinicService\Entity\ServiceItem::class)]
#[ORM\JoinColumn(name: 'service_item_id', nullable: false, onDelete: 'RESTRICT')]
private \App\ClinicService\Entity\ServiceItem $serviceItem;
#[ORM\ManyToOne(targetEntity: \App\Staff\Entity\ClinicStaff::class)]
#[ORM\JoinColumn(name: 'staff_id', nullable: true, onDelete: 'SET NULL')]
private ?\App\Staff\Entity\ClinicStaff $staff = null;
// کپی قیمت در زمان ثبت — تغییر قیمت سرویس بعداً اثر ندارد
#[ORM\Column(type: 'integer')]
private int $priceRials;
#[ORM\Column(type: 'integer')]
private int $createdAt;
}
```
## PatientService
```php
class PatientService
{
public function calculateFinalPrice(
int $visitPrice,
float $baseDiscount,
float $suppDiscount,
array $serviceItems // [{price_rials}]
): array {
$afterBase = $visitPrice * (1 - $baseDiscount / 100);
$afterSupp = $afterBase * (1 - $suppDiscount / 100);
$servicesTotal = array_sum(array_column($serviceItems, 'price_rials'));
$finalPrice = (int) round($afterSupp) + $servicesTotal;
return [
'services_total_rials' => $servicesTotal,
'final_price_rials' => $finalPrice,
];
}
public function autoCreateOnAppointmentConfirm(Appointment $appointment): void
{
[$entityType, $entityId] = $this->resolveEntityFromAppointment($appointment);
if (!$this->subscriptionService->hasFeature($entityType, $entityId, 'patient_records')) {
return; // پنل Free — ایجاد نشود
}
$userId = $appointment->getUser()->getId();
$record = $this->recordRepo->findOneBy([
'entityType' => $entityType,
'entityId' => $entityId,
'user' => $userId,
]) ?? $this->createRecord($entityType, $entityId, $userId, 'system');
// سشن با appointment_id، visit_price=0 (تکمیل بعداً)
$this->createSession($record, $appointment);
}
}
```
## تغییر در AppointmentController
```php
// src/Appointment/Controller/AppointmentController.php
// متد updateStatus() — بعد از ذخیره status جدید:
if ($newStatus === 'confirmed') {
$this->patientService->autoCreateOnAppointmentConfirm($appointment);
}
```
@@ -0,0 +1,116 @@
# پایگاه داده — تسک ۱۵: پرونده بیمار
## جدول: patient_records
| ستون | نوع | توضیح |
|------|-----|-------|
| id | INT UNSIGNED AUTO_INCREMENT PK | |
| uuid | CHAR(36) UNIQUE NOT NULL | |
| entity_type | VARCHAR(10) NOT NULL | `'doctor'` \| `'clinic'` |
| entity_id | INT NOT NULL | |
| user_id | INT NOT NULL FK→users.id ON DELETE RESTRICT | بیمار |
| created_by_type | VARCHAR(15) NOT NULL | `'doctor'` \| `'secretary'` \| `'system'` |
| created_by_id | INT NOT NULL | id ایجادکننده |
| created_at | INT NOT NULL | |
```sql
UNIQUE KEY uniq_patient_record (entity_type, entity_id, user_id)
INDEX idx_patient_records_entity (entity_type, entity_id)
```
## جدول: patient_sessions
| ستون | نوع | توضیح |
|------|-----|-------|
| id | INT UNSIGNED AUTO_INCREMENT PK | |
| uuid | CHAR(36) UNIQUE NOT NULL | |
| record_id | INT NOT NULL FK→patient_records.id ON DELETE CASCADE | |
| appointment_id | INT NULL FK→appointments.id ON DELETE SET NULL | |
| insurance_base_id | INT NULL FK→categories.id ON DELETE SET NULL | بیمه پایه |
| insurance_supplementary_id | INT NULL FK→categories.id ON DELETE SET NULL | بیمه مکمل |
| visit_price_rials | INT NOT NULL DEFAULT 0 | |
| base_insurance_discount_percent | DECIMAL(5,2) NOT NULL DEFAULT 0 | |
| supplementary_discount_percent | DECIMAL(5,2) NOT NULL DEFAULT 0 | |
| services_total_rials | INT NOT NULL DEFAULT 0 | کپی محاسبه‌شده |
| final_price_rials | INT NOT NULL DEFAULT 0 | |
| payment_method | VARCHAR(15) NOT NULL DEFAULT 'pending' | `'cash'`\|`'card'`\|`'insurance'`\|`'pending'` |
| notes | TEXT NULL | |
| created_at | INT NOT NULL | |
| updated_at | INT NOT NULL | |
```sql
INDEX idx_patient_sessions_record (record_id, created_at)
```
## جدول: session_services
| ستون | نوع | توضیح |
|------|-----|-------|
| id | INT UNSIGNED AUTO_INCREMENT PK | |
| uuid | CHAR(36) UNIQUE NOT NULL | |
| session_id | INT NOT NULL FK→patient_sessions.id ON DELETE CASCADE | |
| service_item_id | INT NOT NULL FK→service_items.id ON DELETE RESTRICT | |
| staff_id | INT NULL FK→clinic_staff.id ON DELETE SET NULL | |
| price_rials | INT NOT NULL | **کپی** قیمت در زمان ثبت |
| created_at | INT NOT NULL | |
## Migration نمونه
```sql
CREATE TABLE patient_records (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
uuid CHAR(36) NOT NULL UNIQUE,
entity_type VARCHAR(10) NOT NULL,
entity_id INT NOT NULL,
user_id INT NOT NULL,
created_by_type VARCHAR(15) NOT NULL,
created_by_id INT NOT NULL,
created_at INT NOT NULL,
UNIQUE KEY uniq_patient_record (entity_type, entity_id, user_id),
INDEX idx_patient_records_entity (entity_type, entity_id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE patient_sessions (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
uuid CHAR(36) NOT NULL UNIQUE,
record_id INT NOT NULL,
appointment_id INT NULL,
insurance_base_id INT NULL,
insurance_supplementary_id INT NULL,
visit_price_rials INT NOT NULL DEFAULT 0,
base_insurance_discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0,
supplementary_discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0,
services_total_rials INT NOT NULL DEFAULT 0,
final_price_rials INT NOT NULL DEFAULT 0,
payment_method VARCHAR(15) NOT NULL DEFAULT 'pending',
notes TEXT NULL,
created_at INT NOT NULL,
updated_at INT NOT NULL,
FOREIGN KEY (record_id) REFERENCES patient_records(id) ON DELETE CASCADE,
FOREIGN KEY (appointment_id) REFERENCES appointments(id) ON DELETE SET NULL,
FOREIGN KEY (insurance_base_id) REFERENCES categories(id) ON DELETE SET NULL,
FOREIGN KEY (insurance_supplementary_id) REFERENCES categories(id) ON DELETE SET NULL,
INDEX idx_patient_sessions_record (record_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE session_services (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
uuid CHAR(36) NOT NULL UNIQUE,
session_id INT NOT NULL,
service_item_id INT NOT NULL,
staff_id INT NULL,
price_rials INT NOT NULL,
created_at INT NOT NULL,
FOREIGN KEY (session_id) REFERENCES patient_sessions(id) ON DELETE CASCADE,
FOREIGN KEY (service_item_id) REFERENCES service_items(id) ON DELETE RESTRICT,
FOREIGN KEY (staff_id) REFERENCES clinic_staff(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
## نکات مهم
- **UNIQUE(entity_type, entity_id, user_id)** — یک بیمار یک پرونده در هر کلینیک/مطب دارد
- **price_rials در session_services کپی می‌شود** — تغییر قیمت سرویس در آینده روی سشن‌های قبلی اثر ندارد
- **services_total_rials و final_price_rials** در PatientSession کپی محاسبه‌شده هستند — برای گزارش‌گیری سریع
- **user_id ON DELETE RESTRICT** — نمی‌توان کاربری را که پرونده دارد حذف کرد
@@ -0,0 +1,155 @@
# تسک ۱۵: پرونده بیمار (Patient Records)
## توضیح
پیاده‌سازی سیستم پرونده الکترونیک بیمار. هر بیمار یک پرونده در هر کلینیک/مطب دارد.
هر مراجعه یک سشن است که شامل اطلاعات بیمه، مبلغ ویزیت و سرویس‌های انجام‌شده است.
دسترسی فقط در پنل **Basic+** — gate: `hasFeature('patient_records')`.
## Endpoint ها
| متد | مسیر | Gate | توضیح |
|-----|------|------|-------|
| GET | `/api/v1/patients` | Basic+ | لیست بیماران — `?search=name/phone` |
| POST | `/api/v1/patient` | Basic+ | ایجاد پرونده دستی |
| GET | `/api/v1/patient/{uuid}` | Basic+ | جزئیات پرونده |
| GET | `/api/v1/patient/{uuid}/sessions` | Basic+ | لیست مراجعات |
| POST | `/api/v1/patient/{uuid}/session` | Basic+ | ثبت مراجعه جدید |
| PATCH | `/api/v1/session/{uuid}` | Basic+ | ویرایش مراجعه |
## پیش‌نیازها
- **تسک ۱۰** (ClinicStaff — برای staff_id در SessionService)
- **تسک ۱۱** (Subscription — gate check)
- **تسک ۱۳** (ClinicService — ServiceItem در session)
## زمان تخمینی
۱۶ تا ۲۰ ساعت
## نمونه Request
### POST /api/v1/patient (ایجاد دستی)
```json
{
"user_uuid": "uuid-of-user"
}
```
### POST /api/v1/patient/{uuid}/session
```json
{
"appointment_uuid": null,
"insurance_base_uuid": "category-uuid-insurance-type",
"insurance_supplementary_uuid": null,
"visit_price_rials": 500000,
"base_insurance_discount_percent": 30,
"supplementary_discount_percent": 0,
"payment_method": "cash",
"notes": "بیمار شکایت از کمردرد داشت",
"services": [
{ "service_item_uuid": "uuid-of-service-item", "staff_uuid": "uuid-of-staff" },
{ "service_item_uuid": "uuid-of-another-item", "staff_uuid": null }
]
}
```
### PATCH /api/v1/session/{uuid}
```json
{
"notes": "ویرایش یادداشت",
"payment_method": "card"
}
```
## فرمول محاسبه final_price
```
after_base = visit_price_rials × (1 - base_insurance_discount_percent / 100)
after_supp = after_base × (1 - supplementary_discount_percent / 100)
services_total = Σ service_item.price_rials (قیمت در زمان ثبت — نه قیمت فعلی)
final_price = round(after_supp) + services_total
```
مثال عددی:
```
visit_price = 500,000
base_disc = 30% → after_base = 350,000
supp_disc = 10% → after_supp = 315,000
services = [85,000 + 45,000] = 130,000
final = 315,000 + 130,000 = 445,000
```
## نمونه Response
### GET /api/v1/patients?search=علی
```json
{
"success": true,
"data": [
{
"uuid": "...",
"user": { "uuid": "...", "name": "علی محمدی", "phone": "09121234567" },
"sessions_count": 5,
"last_session_at": 1718000000,
"created_at": 1710000000
}
],
"meta": { "totalRecords": 12, "totalPages": 2, "currentPage": 1 }
}
```
### GET /api/v1/patient/{uuid}
```json
{
"success": true,
"data": {
"uuid": "...",
"user": { "uuid": "...", "name": "علی محمدی", "phone": "09121234567" },
"sessions_count": 5,
"total_paid_rials": 2250000,
"created_at": 1710000000
}
}
```
### GET /api/v1/patient/{uuid}/sessions
```json
{
"success": true,
"data": [
{
"uuid": "...",
"appointment_uuid": null,
"visit_price_rials": 500000,
"base_insurance_discount_percent": 30,
"services_total_rials": 130000,
"final_price_rials": 445000,
"payment_method": "cash",
"notes": "...",
"services": [
{ "name": "سرم ۵۰۰cc", "price_rials": 85000, "staff_name": "علی رضایی" }
],
"created_at": 1718000000
}
],
"meta": { "totalRecords": 5, "totalPages": 1, "currentPage": 1 }
}
```
## ایجاد خودکار پرونده هنگام تأیید نوبت
```
AppointmentController::updateStatus(uuid, 'confirmed')
→ اگر entityType/entityId پنل Basic+ دارد:
→ PatientService::autoCreateOnAppointmentConfirm(appointment)
→ PatientRecord.findOrCreate(entityType, entityId, userId)
→ PatientSession جدید با appointment_id و visit_price پیش‌فرض (0)
→ کاربر بعداً در پرونده می‌تواند اطلاعات بیمه و قیمت را تکمیل کند
```
## کدهای خطا
| کد | HTTP | توضیح |
|----|------|-------|
| `ERR_SUBSCRIPTION_REQUIRED` | 403 | Basic+ لازم است |
| `ERR_PATIENT_NOT_FOUND` | 404 | پرونده پیدا نشد |
| `ERR_SESSION_NOT_FOUND` | 404 | مراجعه پیدا نشد |
| `ERR_SERVICE_ITEM_NOT_FOUND` | 404 | زیربخش سرویس پیدا نشد |
@@ -0,0 +1,123 @@
# جریان کاربری — تسک ۱۵: پرونده بیمار
## جریان خودکار — تأیید نوبت → ایجاد پرونده
```
دکتر/منشی نوبت را تأیید می‌کند
PATCH /api/v1/appointment/{uuid}/status { status: 'confirmed' }
AppointmentController::updateStatus()
آیا entity دارای پنل Basic+ است؟
خیر → پرونده ایجاد نمی‌شود (Free plan)
بله ↓
PatientService::autoCreateOnAppointmentConfirm()
آیا PatientRecord برای این (entity, user) وجود دارد؟
خیر → ایجاد PatientRecord جدید (created_by='system')
بله → همان پرونده استفاده می‌شود
ایجاد PatientSession با:
appointment_id = appointment.id
visit_price_rials = 0 ← کاربر بعداً تکمیل می‌کند
payment_method = 'pending'
```
## جریان دستی — ایجاد پرونده توسط منشی
```
منشی در صفحه «بیماران» کلیک می‌کند → [+ بیمار جدید]
Modal: جستجو بیمار با نام یا شماره تلفن
GET /api/v1/admin/users?search=09121234567
بیمار انتخاب می‌شود
POST /api/v1/patient { user_uuid: '...' }
├─► 409: این بیمار قبلاً پرونده دارد → نمایش پرونده موجود
└─► 201: پرونده ایجاد شد → redirect به PatientDetailPage
```
## جریان ثبت مراجعه (سشن)
```
منشی/دکتر در صفحه پرونده بیمار، روی «+ مراجعه جدید» کلیک می‌کند
Modal ثبت سشن:
┌──────────────────────────────────────────────────────┐
│ ثبت مراجعه جدید │
├──────────────────────────────────────────────────────┤
│ بیمه پایه: [تأمین اجتماعی ▼] │
│ درصد کسر: [۳۰%____________] │
│ بیمه مکمل: [---بدون مکمل--- ▼] │
├──────────────────────────────────────────────────────┤
│ مبلغ ویزیت: [500,000 ریال____] │
├──────────────────────────────────────────────────────┤
│ سرویس‌های انجام‌شده: │
│ [+ سرم ۵۰۰cc × علی رضایی] [+ سرویس دیگر] │
├──────────────────────────────────────────────────────┤
│ 📊 محاسبه: │
│ ویزیت: 500,000 → بعد از بیمه: 315,000 │
│ سرویس‌ها: 130,000 │
│ مجموع: 445,000 ریال │
├──────────────────────────────────────────────────────┤
│ روش پرداخت: [نقدی ▼] │
│ یادداشت: [____________________________] │
└──────────────────────────────────────────────────────┘
│ [لغو] [ثبت مراجعه] │
POST /api/v1/patient/{uuid}/session { ... }
سشن ثبت شد → لیست مراجعات refresh می‌شود
```
## محاسبه real-time در Frontend
```
هر بار که visit_price یا discount درصد تغییر می‌کند:
after_base = visit_price × (1 - base_discount / 100)
after_supp = after_base × (1 - supp_discount / 100)
final = round(after_supp) + services_total
نمایش: «مبلغ قابل پرداخت: ۴۴۵,۰۰۰ ریال»
```
## جریان جستجو بیمار
```
GET /api/v1/patients?search=علی&page=1
→ جستجو در نام و شماره تلفن user
→ نمایش paginated در DataTable
→ کلیک روی هر ردیف → PatientDetailPage
```
## نمایش صفحه بیمار (PatientDetailPage.tsx)
```
┌─────────────────────────────────────────────────────┐
│ علی محمدی — 09121234567 │
│ ۵ مراجعه | آخرین: ۱۴۰۵/۰۳/۱۵ | مجموع: ۲,۲۵۰,۰۰۰ │
├─────────────────────────────────────────────────────┤
│ [+ مراجعه جدید] │
├──────────────┬──────────────┬──────────────────────┤
│ تاریخ │ مبلغ نهایی │ روش پرداخت عملیات │
├──────────────┼──────────────┼──────────────────────┤
│ ۱۴۰۵/۰۳/۱۵ │ ۴۴۵,۰۰۰ ریال│ نقدی ✏️ 👁️ │
│ ۱۴۰۵/۰۲/۰۸ │ ۳۲۰,۰۰۰ ریال│ کارت ✏️ 👁️ │
└──────────────┴──────────────┴──────────────────────┘
```