feat: add lab tests, patient file management, and prescription improvements

This commit is contained in:
SajjadMahmoody
2026-04-17 20:15:38 +03:30
parent 6a301c5529
commit bf0ada051f
53 changed files with 3201 additions and 387 deletions
@@ -5,10 +5,20 @@
namespace App\Filament\Resources\PatientResource\Pages;
use App\Filament\Resources\PatientResource;
use App\Models\SurgeryAppointment;
use App\Models\SurgeryCenter;
use Carbon\Carbon;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Forms\Components\DatePicker;
use Filament\Schemas\Components\Grid;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TimePicker;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
use Illuminate\Support\Facades\Http;
use Morilog\Jalali\Jalalian;
class EditPatient extends EditRecord
{
@@ -19,6 +29,168 @@ class EditPatient extends EditRecord
protected function getHeaderActions(): array
{
return [
$this->getSaveFormAction()
->formId('form'),
Action::make('surgeryAppointment')
->label(__('patients.actions.surgery_appointment'))
->icon('heroicon-o-calendar-days')
->color(fn () => $this->getRecord()->surgeryAppointment ? 'success' : 'info')
->modalWidth(Width::Large)
->fillForm(function (): array {
$appointment = $this->getRecord()->surgeryAppointment;
if ($appointment) {
$surgeryDate = $appointment->surgery_date;
return [
'surgery_date' => $surgeryDate?->format('Y-m-d'),
'surgery_time' => $surgeryDate?->format('H:i'),
'surgery_center_id' => $appointment->surgery_center_id,
];
}
return [
'surgery_date' => null,
'surgery_time' => '09:00',
'surgery_center_id' => null,
];
})
->form([
Placeholder::make('patient_name')
->label(__('patients.fields.full_name'))
->content(fn () => $this->getRecord()->full_name),
Grid::make(2)
->schema([
DatePicker::make('surgery_date')
->label(__('patients.fields.surgery_date'))
->jalali()
->minDate(today())
->required(),
TimePicker::make('surgery_time')
->label(__('patients.fields.surgery_time'))
->native(false)
->seconds(false)
->minutesStep(15),
]),
Select::make('surgery_center_id')
->label(__('patients.fields.surgery_center'))
->options(fn () => SurgeryCenter::pluck('name', 'id')->toArray())
->searchable()
->required(),
])
->modalSubmitAction(false)
->extraModalFooterActions(fn (Action $action): array => [
$action->makeModalSubmitAction('saveAppointment', arguments: ['save' => true])
->label(__('patients.actions.save_appointment'))
->color('primary')
->icon('heroicon-o-check')
->visible(fn () => $this->getRecord()->surgeryAppointment === null),
Action::make('printAdmissionFromModal')
->label(__('patients.actions.print_admission'))
->color('warning')
->icon('heroicon-o-printer')
->url(fn () => route('surgery-appointment.print.admission', $this->getRecord()), shouldOpenInNewTab: true)
->visible(fn () => $this->getRecord()->surgeryAppointment !== null),
$action->makeModalSubmitAction('deleteAppointment', arguments: ['delete' => true])
->label(__('patients.actions.delete_appointment'))
->color('danger')
->icon('heroicon-o-trash')
->visible(fn () => $this->getRecord()->surgeryAppointment !== null),
])
->action(function (array $data, array $arguments): void {
$record = $this->getRecord();
if (! empty($arguments['delete'])) {
$existingAppointment = $record->surgeryAppointment;
SurgeryAppointment::where('patient_id', $record->id)->delete();
$record->unsetRelation('surgeryAppointment');
if ($existingAppointment) {
\App\Filament\Pages\SmsLogsPage::cancelAppointmentMessages(
$record->hand_phone ?? '',
$existingAppointment->surgery_date->toDateTimeString(),
);
}
\Filament\Notifications\Notification::make()
->title(__('patients.actions.appointment_deleted'))
->success()
->send();
return;
}
$dateStr = $data['surgery_date'];
$timeStr = $data['surgery_time'] ?? '00:00';
$surgeryDateTime = Carbon::parse($dateStr . ' ' . $timeStr);
$jalaliDate = Jalalian::fromCarbon($surgeryDateTime)->format('Y/m/d');
$apiKey = \App\Models\OsurgInitial::val('sms_api_key', config('sms.api_key'));
$apiUrl = \App\Models\OsurgInitial::val('sms_api_url', config('sms.api_url'));
$smsPayload = [
'phoneNumber' => $record->hand_phone ?? '',
'patientName' => $record->full_name,
'surgeryDate' => $jalaliDate,
'patientId' => $record->id,
'surgeryDateFull' => $surgeryDateTime->toDateTimeString(),
];
// مرحله ۱: ارسال پیامک اولیه
try {
$response = Http::timeout(30)
->withHeader('X-API-Key', $apiKey)
->asJson()
->post($apiUrl . '/surgery-reminder', $smsPayload);
if (! ($response->json('success') ?? false)) {
\Filament\Notifications\Notification::make()
->title(__('patients.actions.api_failed'))
->body($response->json('message') ?? '')
->danger()
->send();
return;
}
} catch (\Throwable $e) {
\Filament\Notifications\Notification::make()
->title(__('patients.actions.api_failed'))
->body($e->getMessage())
->danger()
->send();
return;
}
$appointment = SurgeryAppointment::updateOrCreate(
['patient_id' => $record->id],
[
'surgery_date' => $surgeryDateTime,
'surgery_center_id' => $data['surgery_center_id'],
]
);
$record->unsetRelation('surgeryAppointment');
try {
Http::timeout(30)
->withHeader('X-API-Key', $apiKey)
->asJson()
->post($apiUrl . '/surgery-reminder', array_merge($smsPayload, [
'appointmentId' => $appointment->id,
]));
} catch (\Throwable) {
}
\Filament\Notifications\Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.sms_sent'))
->success()
->send();
}),
Action::make('printPrescription')
->label(__('prescriptions.actions.print_prescription'))
->icon('heroicon-o-printer')
@@ -46,6 +218,59 @@ protected function getHeaderActions(): array
];
}
protected function mutateFormDataBeforeFill(array $data): array
{
foreach (['birth_date'] as $field) {
if (($data[$field] ?? null) === '') {
$data[$field] = null;
}
}
foreach (['surgery_before', 'sergery_after'] as $field) {
if (($data[$field] ?? null) === '') {
$data[$field] = null;
}
}
foreach (['current_illness_1', 'current_illness_2', 'has_alergyto'] as $field) {
if (is_null($data[$field] ?? null)) {
$data[$field] = [];
}
}
foreach (['photos_before', 'photos_after', 'videos', 'audio_files'] as $field) {
$data[$field] = static::normalizeFileList($data[$field] ?? null);
}
return $data;
}
public static function normalizeFileList(mixed $value): array
{
if (empty($value)) {
return [];
}
if (is_string($value)) {
$decoded = json_decode($value, true);
$value = is_array($decoded) ? $decoded : [$value];
}
return collect((array) $value)
->map(function ($item) {
if (is_array($item) && isset($item['name'])) {
return $item['name'];
}
if (is_string($item) && $item !== '') {
return $item;
}
return null;
})
->filter()
->values()
->toArray();
}
protected function getFormActions(): array
{
return [];
@@ -4,6 +4,8 @@
namespace App\Filament\Resources\PatientResource\RelationManagers;
use App\Filament\Resources\PatientResource\Pages\CreatePatient;
use App\Filament\Resources\PatientResource\Pages\EditPatient;
use App\Models\Doctor;
use App\Models\PaymentType;
use App\Models\Treatment;
@@ -28,6 +30,11 @@ class VisitsRelationManager extends RelationManager
{
protected static string $relationship = 'visits';
public static function canViewForRecord(\Illuminate\Database\Eloquent\Model $ownerRecord, string $pageClass): bool
{
return in_array($pageClass, [CreatePatient::class, EditPatient::class]);
}
public static function getTitle(\Illuminate\Database\Eloquent\Model $ownerRecord, string $pageClass): string
{
return __('navigation.visits.title');
@@ -49,32 +56,42 @@ public function form(Schema $schema): Schema
TimePicker::make('visit_time')
->label(__('visits.fields.visit_time'))
->nullable()
->native(false)
->seconds(false)
->minutesStep(15),
->minutesStep(15)
->afterStateHydrated(function ($component, $state) {
if (blank($state)) {
$component->state(now()->format('Y-m-d H:i:s'));
}
}),
Select::make('doctor')
->label(__('visits.fields.doctor'))
->options(fn () => Doctor::all()->mapWithKeys(
fn ($d) => [$d->id => $d->full_name]
)->toArray())
->searchable()
->default(fn () => Doctor::where('is_default', true)->first()?->id)
->nullable(),
Select::make('treatment')
->label(__('visits.fields.treatment'))
->options(fn () => Treatment::all()->mapWithKeys(
fn ($t) => [$t->id => ($t->treatment_name ?: $t->treatment_type)]
fn ($t) => [$t->id => ($t->descriptions ? '★ ' : '') . ($t->treatment_name ?: $t->treatment_type)]
)->toArray())
->searchable()
->nullable()
->required()
->live()
->afterStateUpdated(function ($state, callable $set) {
if ($state) {
$treatment = Treatment::find($state);
if ($treatment && $treatment->treatment_cost > 0) {
$set('treatment_cost', $treatment->treatment_cost);
if ($treatment) {
if ($treatment->treatment_cost > 0) {
$set('treatment_cost', $treatment->treatment_cost);
$set('paid_amount', $treatment->treatment_cost);
}
if ($treatment->descriptions) {
$set('treatment_description', $treatment->descriptions);
}
}
}
}),
@@ -102,7 +119,7 @@ public function form(Schema $schema): Schema
fn ($p) => [$p->id => $p->payment_type]
)->toArray())
->searchable()
->nullable(),
->required(),
])
->columns(3)
->columnSpanFull(),
@@ -124,10 +141,13 @@ public function table(Table $table): Table
{
return $table
->recordTitleAttribute('visit_date')
->modifyQueryUsing(fn ($query) => $query->with(['doctorRecord', 'treatmentRecord', 'paymentTypeRecord']))
->deferLoading()
->columns([
TextColumn::make('visit_date')
->label(__('visits.fields.visit_date'))
->sortable()
->wrap(false)
->formatStateUsing(function ($state) {
if (! $state) {
return '-';
@@ -144,6 +164,7 @@ public function table(Table $table): Table
TextColumn::make('doctorRecord.first_name')
->label(__('visits.fields.doctor'))
->formatStateUsing(fn ($record) => $record->doctorRecord?->full_name ?? '-')
->wrap(false)
->placeholder('-'),
TextColumn::make('treatmentRecord.treatment_name')
@@ -151,11 +172,13 @@ public function table(Table $table): Table
->formatStateUsing(fn ($record) => $record->treatmentRecord
? ($record->treatmentRecord->treatment_name ?: $record->treatmentRecord->treatment_type)
: '-')
->wrap(false)
->placeholder('-'),
TextColumn::make('treatment_cost')
->label(__('visits.fields.treatment_cost'))
->formatStateUsing(fn ($state) => $state !== null ? number_format((int) $state) : '-')
->wrap(false)
->placeholder('-')
->summarize(
Sum::make()
@@ -166,6 +189,7 @@ public function table(Table $table): Table
TextColumn::make('paid_amount')
->label(__('visits.fields.paid_amount'))
->formatStateUsing(fn ($state) => $state !== null ? number_format((int) $state) : '-')
->wrap(false)
->placeholder('-')
->summarize(
Sum::make()
@@ -177,10 +201,12 @@ public function table(Table $table): Table
->label(__('visits.fields.remained_amount'))
->state(fn ($record) => $record->remained_amount)
->formatStateUsing(fn ($state) => number_format((int) $state))
->color(fn ($record) => $record->remained_amount > 0 ? 'danger' : 'success'),
->color(fn ($record) => $record->remained_amount > 0 ? 'danger' : 'success')
->wrap(false),
TextColumn::make('paymentTypeRecord.payment_type')
->label(__('visits.fields.payment_type'))
->wrap(false)
->placeholder('-'),
])
->defaultSort('visit_date', 'desc')