Dr-Panel/app/Filament/Resources/PatientResource.php

1507 lines
79 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\PatientResource\Pages;
use App\Filament\Resources\PatientResource\RelationManagers\VisitsRelationManager;
use App\Models\LabTest;
use App\Models\Medication;
use App\Models\Patient;
use App\Models\PatientIllness;
use App\Models\Prescription;
use App\Models\SurgeryAppointment;
use App\Models\SurgeryCenter;
use App\Services\PdfService;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Illuminate\Support\Facades\Storage;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Radio;
use App\Filament\RichEditor\HighlightColorPlugin;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TimePicker;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Get;
use App\Filament\Infolists\Components\ExpandableHtmlEntry;
use App\Filament\Infolists\Components\MediaFilesEntry;
use App\Filament\Infolists\Components\PhotoGalleryEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Support\Enums\Width;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use Morilog\Jalali\Jalalian;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class PatientResource extends Resource
{
protected static ?string $model = Patient::class;
protected static ?string $recordTitleAttribute = 'first_name';
public static function previewHighlightedHtml(string $state, int $limit = 30): string
{
$plain = strip_tags($state);
if (! $plain) {
return '-';
}
$suffix = '<span class="text-primary-600 text-xs font-semibold cursor-pointer">... بیشتر</span>';
$preview = preg_replace('/<(?!\/?span[^>]*data-hbg|\/?mark\b)[^>]+>/i', '', $state);
$preview = trim(preg_replace('/\s+/', ' ', $preview));
if (mb_strlen($plain) <= $limit) {
return $preview;
}
$result = '';
$count = 0;
$inTag = false;
$tagBuf = '';
$openSpans = 0;
foreach (mb_str_split($preview) as $ch) {
if ($count >= $limit) {
break;
}
if ($ch === '<') {
$inTag = true;
$tagBuf = '<';
continue;
}
if ($inTag) {
$tagBuf .= $ch;
if ($ch === '>') {
$inTag = false;
$result .= $tagBuf;
if (str_contains($tagBuf, '</')) {
$openSpans = max(0, $openSpans - 1);
} else {
$openSpans++;
}
$tagBuf = '';
}
continue;
}
$result .= $ch;
$count++;
}
$result .= str_repeat('</span>', $openSpans);
return $result . ' ' . $suffix;
}
public static function getGloballySearchableAttributes(): array
{
return ['first_name', 'last_name', 'hand_phone', 'icno'];
}
public static function getGlobalSearchResultDetails(\Illuminate\Database\Eloquent\Model $record): array
{
return [
__('navigation.patients.last_name') => $record->last_name,
];
}
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-user-group';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.patients');
}
public static function getNavigationSort(): ?int
{
return 1;
}
public static function getNavigationLabel(): string
{
return __('navigation.patients.title');
}
public static function getModelLabel(): string
{
return __('navigation.patients.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.patients.title');
}
public static function form(Schema $schema): Schema
{
$yesNo = [
'بله' => 'بله',
'خیر' => 'خیر',
];
return $schema
->components([
Grid::make()
->schema([
Section::make(__('patients.sections.patient_info'))
->schema([
TextInput::make('first_name')
->label(__('patients.fields.first_name'))
->required()
->validationMessages([
'required' => __('patients.validation.first_name_required'),
])
->maxLength(50),
TextInput::make('last_name')
->label(__('patients.fields.last_name'))
->required()
->validationMessages([
'required' => __('patients.validation.last_name_required'),
])
->maxLength(50),
TextInput::make('father_name')
->label(__('patients.fields.father_name'))
->maxLength(50),
TextInput::make('icno')
->label(__('patients.fields.icno'))
->required()
->maxLength(11)
->unique(
table: Patient::class,
column: 'icno',
ignorable: fn ($record) => $record,
)
->validationMessages([
'unique' => __('patients.validation.icno_unique'),
]),
TextInput::make('hand_phone')
->label(__('patients.fields.hand_phone'))
->required()
->validationMessages([
'required' => __('patients.validation.hand_phone_required'),
])
->maxLength(50),
TextInput::make('age')
->label(__('patients.fields.age'))
->numeric()
->minValue(0),
DatePicker::make('birth_date')
->label(__('patients.fields.birth_date'))
->jalali(),
Radio::make('gender')
->label(__('patients.fields.gender'))
->options(['مرد' => 'مرد', 'زن' => 'زن'])
->inline(),
Radio::make('marital_status')
->label(__('patients.fields.marital_status'))
->options(['مجرد' => 'مجرد', 'متاهل' => 'متاهل'])
->inline(),
TextInput::make('insurance_no')
->label(__('patients.fields.insurance_no'))
->maxLength(50),
TextInput::make('insurance')
->label(__('patients.fields.insurance'))
->maxLength(50),
TextInput::make('education')
->label(__('patients.fields.education'))
->maxLength(50),
TextInput::make('job')
->label(__('patients.fields.job'))
->maxLength(50),
TextInput::make('home_phone')
->label(__('patients.fields.home_phone'))
->maxLength(50),
TextInput::make('work_phone')
->label(__('patients.fields.work_phone'))
->maxLength(50),
TextInput::make('other_phone')
->label(__('patients.fields.other_phone'))
->maxLength(50),
Textarea::make('home_address')
->label(__('patients.fields.home_address'))
->rows(2)
->columnSpan(2),
Textarea::make('work_address')
->label(__('patients.fields.work_address'))
->rows(2)
->columnSpan(2),
TextInput::make('refered_by')
->label(__('patients.fields.refered_by'))
->required()
->maxLength(50),
TextInput::make('doc_id')
->label(__('patients.fields.doc_id'))
->maxLength(50),
Textarea::make('referal_reason')
->label(__('patients.fields.referal_reason'))
->rows(2)
->columnSpan(2),
])
->columns(4)
->columnSpanFull(),
Section::make(__('patients.sections.illness'))
->schema([
CheckboxList::make('current_illness_1')
->label(__('patients.fields.current_illness_1'))
->options(fn () => \Illuminate\Support\Facades\Cache::remember(
'illness_options_1',
now()->addDay(),
fn () => PatientIllness::where('row_no', 1)->orderBy('priority')->pluck('illness', 'illness')->toArray()
)),
CheckboxList::make('current_illness_2')
->label(__('patients.fields.current_illness_2'))
->options(fn () => \Illuminate\Support\Facades\Cache::remember(
'illness_options_2',
now()->addDay(),
fn () => PatientIllness::where('row_no', 2)->orderBy('priority')->pluck('illness', 'illness')->toArray()
)),
TextInput::make('blood_sugar')
->label(__('patients.fields.blood_sugar'))
->numeric(),
TextInput::make('blood_pressure')
->label(__('patients.fields.blood_pressure'))
->numeric(),
Radio::make('is_undercare')
->label(__('patients.fields.is_undercare'))
->options($yesNo)
->inline(),
TextInput::make('undercare_reason')
->label(__('patients.fields.undercare_reason'))
->maxLength(50),
Radio::make('is_usingdrug')
->label(__('patients.fields.is_usingdrug'))
->options($yesNo)
->inline(),
TextInput::make('underdrug_reason')
->label(__('patients.fields.underdrug_reason'))
->maxLength(50),
CheckboxList::make('has_alergyto')
->label(__('patients.fields.has_alergyto'))
->options([
'پنی سیلین' => 'پنی سیلین',
'داروی بی حسی' => 'داروی بی حسی',
'مواد غذایی و دارویی دیگر' => 'مواد غذایی و دارویی دیگر',
])
->columns(3),
TextInput::make('alergy_reason')
->label(__('patients.fields.alergy_reason'))
->maxLength(50),
Textarea::make('description')
->label(__('patients.fields.description'))
->rows(2)
->columnSpanFull(),
])
->columns(2)
->columnSpanFull(),
Section::make(__('patients.sections.surgery_notes'))
->schema([
RichEditor::make('surgery_before')
->label(__('patients.fields.surgery_before'))
->extraInputAttributes(['style' => 'min-height: 150px'])
->plugins([HighlightColorPlugin::make()])
->toolbarButtons([
['bold', 'italic', 'underline', 'strike', 'link'],
['highlightYellow', 'highlightRed'],
['h2', 'h3', 'alignStart', 'alignCenter', 'alignEnd'],
['blockquote', 'bulletList', 'orderedList'],
['undo', 'redo'],
]),
RichEditor::make('sergery_after')
->label(__('patients.fields.sergery_after'))
->extraInputAttributes(['style' => 'min-height: 150px'])
->plugins([HighlightColorPlugin::make()])
->toolbarButtons([
['bold', 'italic', 'underline', 'strike', 'link'],
['highlightYellow', 'highlightRed'],
['h2', 'h3', 'alignStart', 'alignCenter', 'alignEnd'],
['blockquote', 'bulletList', 'orderedList'],
['undo', 'redo'],
]),
])
->columns(2)
->columnSpanFull(),
Section::make(__('patients.sections.media'))
->schema([
FileUpload::make('photos_before')
->label(__('patients.fields.photos_before'))
->multiple()
->image()
->panelLayout('grid')
->extraAttributes(fn (string $operation) => $operation === 'view'
? ['class' => 'fi-photo-gallery fi-photo-gallery-view', 'data-hide-dropzone' => 'true']
: ['class' => 'fi-photo-gallery']
)
->disk('public')
->directory(function ($record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
$icno = $record?->icno ?? '';
return "files/surgery_photos/{$year}/{$icno}/before";
})
->downloadable()
->openable()
->disabled(fn (string $operation) => $operation === 'view')
->deletable(fn (string $operation) => $operation !== 'view')
->fetchFileInformation(false),
FileUpload::make('photos_after')
->label(__('patients.fields.photos_after'))
->multiple()
->image()
->panelLayout('grid')
->extraAttributes(fn (string $operation) => $operation === 'view'
? ['class' => 'fi-photo-gallery fi-photo-gallery-view', 'data-hide-dropzone' => 'true']
: ['class' => 'fi-photo-gallery']
)
->disk('public')
->directory(function ($record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
$icno = $record?->icno ?? '';
return "files/surgery_photos/{$year}/{$icno}/after";
})
->downloadable()
->openable()
->disabled(fn (string $operation) => $operation === 'view')
->deletable(fn (string $operation) => $operation !== 'view')
->fetchFileInformation(false),
FileUpload::make('videos')
->label(__('patients.fields.videos'))
->multiple()
->disk('public')
->directory(function ($record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
$icno = $record?->icno ?? '';
return "files/surgery_photos/{$year}/{$icno}/videos";
})
->acceptedFileTypes([
'video/mp4', 'video/quicktime', 'video/x-msvideo',
'video/x-matroska', 'video/webm',
'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/x-wav',
'audio/ogg', 'audio/opus', 'audio/mp4', 'audio/x-m4a',
'audio/aac', 'audio/x-aac', 'audio/flac', 'audio/x-flac',
'audio/webm', 'audio/amr', 'audio/3gpp', 'audio/3gpp2',
'audio/aiff', 'audio/x-aiff',
])
->maxSize(102400)
->downloadable()
->openable()
->panelLayout('grid')
->extraAttributes(fn (string $operation) => $operation === 'view'
? ['class' => 'fi-video-gallery', 'data-hide-dropzone' => 'true']
: ['class' => 'fi-video-gallery']
)
->disabled(fn (string $operation) => $operation === 'view')
->deletable(fn (string $operation) => $operation !== 'view')
->fetchFileInformation(false),
FileUpload::make('audio_files')
->label(__('patients.fields.audio_files'))
->multiple()
->disk('public')
->directory(function ($record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
$icno = $record?->icno ?? '';
return "files/surgery_photos/{$year}/{$icno}/audio";
})
->acceptedFileTypes([
'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/x-wav',
'audio/ogg', 'audio/opus', 'audio/mp4', 'audio/x-m4a',
'audio/aac', 'audio/x-aac', 'audio/flac', 'audio/x-flac',
'audio/webm', 'audio/amr', 'audio/3gpp', 'audio/3gpp2',
'audio/aiff', 'audio/x-aiff',
])
->downloadable()
->openable()
->extraAttributes(fn (string $operation) => $operation === 'view'
? ['data-hide-dropzone' => 'true']
: []
)
->disabled(fn (string $operation) => $operation === 'view')
->deletable(fn (string $operation) => $operation !== 'view')
->fetchFileInformation(false),
])
->columns(2)
->columnSpanFull()
->footerActions([
fn (string $operation) => Action::make('create')
->label(__('filament-panels::resources/pages/create-record.form.actions.create.label'))
->submit('create')
->keyBindings(['mod+s'])
->visible($operation === 'create'),
fn (string $operation) => Action::make('createAnother')
->label(__('filament-panels::resources/pages/create-record.form.actions.create_another.label'))
->action('createAnother')
->keyBindings(['mod+shift+s'])
->color('gray')
->visible($operation === 'create'),
fn (string $operation) => Action::make('cancelCreate')
->label(__('filament-panels::resources/pages/create-record.form.actions.cancel.label'))
->url(static::getUrl('index'))
->color('gray')
->visible($operation === 'create'),
fn (string $operation) => Action::make('save')
->label(__('filament-panels::resources/pages/edit-record.form.actions.save.label'))
->submit('save')
->keyBindings(['mod+s'])
->visible($operation === 'edit'),
fn (string $operation) => Action::make('cancelEdit')
->label(__('filament-panels::resources/pages/edit-record.form.actions.cancel.label'))
->url(static::getUrl('index'))
->color('gray')
->visible($operation === 'edit'),
]),
])
->columnSpanFull(),
]);
}
public static function infolist(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make(__('patients.sections.patient_info'))
->schema([
TextEntry::make('file_number')
->label(__('patients.fields.file_number'))
->weight(FontWeight::Bold),
TextEntry::make('first_name')
->label(__('patients.fields.first_name')),
TextEntry::make('last_name')
->label(__('patients.fields.last_name')),
TextEntry::make('father_name')
->label(__('patients.fields.father_name'))
->placeholder('-'),
TextEntry::make('icno')
->label(__('patients.fields.icno'))
->placeholder('-'),
TextEntry::make('hand_phone')
->label(__('patients.fields.hand_phone'))
->placeholder('-'),
TextEntry::make('age')
->label(__('patients.fields.age'))
->placeholder('-'),
TextEntry::make('birth_date')
->label(__('patients.fields.birth_date'))
->placeholder('-')
->formatStateUsing(fn ($state) => $state
? Jalalian::fromCarbon(\Carbon\Carbon::parse($state))->format('Y/m/d')
: '-'
),
TextEntry::make('gender')
->label(__('patients.fields.gender'))
->placeholder('-'),
TextEntry::make('marital_status')
->label(__('patients.fields.marital_status'))
->placeholder('-'),
TextEntry::make('insurance_no')
->label(__('patients.fields.insurance_no'))
->placeholder('-'),
TextEntry::make('insurance')
->label(__('patients.fields.insurance'))
->placeholder('-'),
TextEntry::make('education')
->label(__('patients.fields.education'))
->placeholder('-'),
TextEntry::make('job')
->label(__('patients.fields.job'))
->placeholder('-'),
TextEntry::make('home_phone')
->label(__('patients.fields.home_phone'))
->placeholder('-'),
TextEntry::make('work_phone')
->label(__('patients.fields.work_phone'))
->placeholder('-'),
TextEntry::make('other_phone')
->label(__('patients.fields.other_phone'))
->placeholder('-'),
TextEntry::make('home_address')
->label(__('patients.fields.home_address'))
->columnSpan(2)
->placeholder('-'),
TextEntry::make('work_address')
->label(__('patients.fields.work_address'))
->columnSpan(2)
->placeholder('-'),
TextEntry::make('refered_by')
->label(__('patients.fields.refered_by'))
->placeholder('-'),
TextEntry::make('doc_id')
->label(__('patients.fields.doc_id'))
->placeholder('-'),
TextEntry::make('referal_reason')
->label(__('patients.fields.referal_reason'))
->columnSpan(2)
->placeholder('-'),
])
->columns(4)
->columnSpanFull(),
Section::make(__('patients.sections.illness'))
->schema([
TextEntry::make('current_illness_1')
->label(__('patients.fields.current_illness_1'))
->listWithLineBreaks()
->placeholder('-'),
TextEntry::make('current_illness_2')
->label(__('patients.fields.current_illness_2'))
->listWithLineBreaks()
->placeholder('-'),
TextEntry::make('blood_sugar')
->label(__('patients.fields.blood_sugar'))
->placeholder('-'),
TextEntry::make('blood_pressure')
->label(__('patients.fields.blood_pressure'))
->placeholder('-'),
TextEntry::make('is_undercare')
->label(__('patients.fields.is_undercare'))
->placeholder('-'),
TextEntry::make('undercare_reason')
->label(__('patients.fields.undercare_reason'))
->placeholder('-'),
TextEntry::make('is_usingdrug')
->label(__('patients.fields.is_usingdrug'))
->placeholder('-'),
TextEntry::make('underdrug_reason')
->label(__('patients.fields.underdrug_reason'))
->placeholder('-'),
TextEntry::make('has_alergyto')
->label(__('patients.fields.has_alergyto'))
->listWithLineBreaks()
->placeholder('-'),
TextEntry::make('alergy_reason')
->label(__('patients.fields.alergy_reason'))
->placeholder('-'),
TextEntry::make('description')
->label(__('patients.fields.description'))
->columnSpanFull()
->placeholder('-'),
])
->columns(2)
->columnSpanFull(),
Section::make(__('patients.sections.surgery_notes'))
->schema([
ExpandableHtmlEntry::make('surgery_before')
->label(__('patients.fields.surgery_before')),
ExpandableHtmlEntry::make('sergery_after')
->label(__('patients.fields.sergery_after')),
])
->columns(2)
->columnSpanFull(),
Section::make(__('patients.sections.media'))
->schema([
PhotoGalleryEntry::make('photos_before')
->label(__('patients.fields.photos_before')),
PhotoGalleryEntry::make('photos_after')
->label(__('patients.fields.photos_after')),
MediaFilesEntry::make('videos')
->label(__('patients.fields.videos')),
MediaFilesEntry::make('audio_files')
->label(__('patients.fields.audio_files')),
])
->columns(2)
->columnSpanFull(),
Section::make(__('patients.sections.record_info'))
->schema([
TextEntry::make('creator.name')
->label(__('patients.fields.created_by'))
->placeholder('-'),
TextEntry::make('updator.name')
->label(__('patients.fields.updated_by'))
->placeholder('-'),
TextEntry::make('surgeryAppointment.surgery_date')
->label(__('patients.fields.surgery_appointment'))
->placeholder('-')
->formatStateUsing(function ($state) {
if (! $state) {
return '-';
}
try {
return Jalalian::fromCarbon(\Carbon\Carbon::parse($state))->format('Y/m/d - H:i');
} catch (\Exception) {
return '-';
}
}),
TextEntry::make('updated_at')
->label(__('patients.fields.updated_at'))
->placeholder('-'),
])
->columns(4)
->columnSpanFull(),
])
->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table
->modifyQueryUsing(fn ($query) => $query->with(['creator', 'updator', 'surgeryAppointment']))
->deferLoading()
->columns([
TextColumn::make('file_number')
->label(__('patients.fields.file_number'))
->searchable()
->sortable(),
TextColumn::make('first_name')
->label(__('patients.fields.first_name'))
->searchable()
->sortable(),
TextColumn::make('last_name')
->label(__('patients.fields.last_name'))
->searchable()
->sortable(),
TextColumn::make('icno')
->label(__('patients.fields.icno'))
->searchable()
->placeholder('-'),
TextColumn::make('hand_phone')
->label(__('patients.fields.hand_phone'))
->searchable()
->placeholder('-'),
TextColumn::make('home_phone')
->label(__('patients.fields.home_phone'))
->placeholder('-')
->hidden(),
TextColumn::make('creator.name')
->label(__('patients.fields.created_by'))
->placeholder('-'),
TextColumn::make('updator.name')
->label(__('patients.fields.updated_by'))
->placeholder('-'),
TextColumn::make('updated_at')
->label(__('patients.fields.updated_at'))
->sortable()
->placeholder('-'),
TextColumn::make('refered_by')
->label(__('patients.fields.refered_by'))
->placeholder('-'),
TextColumn::make('surgery_before')
->label(__('patients.fields.surgery_before'))
->width('150px')
->extraAttributes(fn (Patient $record): array =>
empty(strip_tags($record->surgery_before ?? ''))
? ['class' => 'pointer-events-none']
: []
)
->formatStateUsing(fn ($state) => static::previewHighlightedHtml($state ?? ''))
->html()
->action(
Action::make('viewSurgeryBefore')
->label(__('patients.fields.surgery_before'))
->modalWidth(Width::Large)
->modalContent(fn (Patient $record): \Illuminate\Support\HtmlString =>
new \Illuminate\Support\HtmlString(
'<div dir="rtl" class="prose max-w-none p-4">'
. $record->surgery_before
. '</div>'
)
)
->modalSubmitAction(false)
->modalCancelActionLabel('بستن')
),
TextColumn::make('sergery_after')
->label(__('patients.fields.sergery_after'))
->width('150px')
->extraAttributes(fn (Patient $record): array =>
empty(strip_tags($record->sergery_after ?? ''))
? ['class' => 'pointer-events-none']
: []
)
->formatStateUsing(fn ($state) => static::previewHighlightedHtml($state ?? ''))
->html()
->action(
Action::make('viewSergeryAfter')
->label(__('patients.fields.sergery_after'))
->modalWidth(Width::Large)
->modalContent(fn (Patient $record): \Illuminate\Support\HtmlString =>
new \Illuminate\Support\HtmlString(
'<div dir="rtl" class="prose max-w-none p-4">'
. $record->sergery_after
. '</div>'
)
)
->modalSubmitAction(false)
->modalCancelActionLabel('بستن')
),
TextColumn::make('surgeryAppointment.surgery_date')
->label(__('patients.fields.surgery_appointment'))
->formatStateUsing(function ($state) {
if (! $state) {
return '-';
}
try {
$date = \Carbon\Carbon::parse($state);
return Jalalian::fromCarbon($date)->format('Y/m/d - H:i');
} catch (\Exception $e) {
return $state;
}
})
->icon(fn ($state) => $state ? 'heroicon-o-check-circle' : 'heroicon-o-clock')
->iconColor(fn ($state) => $state ? 'success' : 'gray')
->placeholder('-'),
])
->defaultSort('updated_at', 'desc')
->recordActions([
Action::make('surgeryAppointment')
->label(__('patients.actions.surgery_appointment'))
->icon('heroicon-o-calendar-days')
->iconButton()
->color(fn (Patient $record) => $record->surgeryAppointment ? 'success' : 'info')
->modalWidth(Width::Large)
->fillForm(function (Patient $record): array {
$appointment = $record->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([
\Filament\Forms\Components\Placeholder::make('patient_name')
->label(__('patients.fields.full_name'))
->content(fn (Patient $record) => $record->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 (Patient $record) => $record->surgeryAppointment === null),
Action::make('printAdmission')
->label(__('patients.actions.print_admission'))
->color('warning')
->icon('heroicon-o-printer')
->url(fn (Patient $record) => route('surgery-appointment.print.admission', $record), shouldOpenInNewTab: true)
->visible(fn (Patient $record) => $record->surgeryAppointment !== null),
$action->makeModalSubmitAction('deleteAppointment', arguments: ['delete' => true])
->label(__('patients.actions.delete_appointment'))
->color('danger')
->icon('heroicon-o-trash')
->visible(fn (Patient $record) => $record->surgeryAppointment !== null),
])
->action(function (Patient $record, array $data, array $arguments, Action $action): void {
if (! empty($arguments['delete'])) {
$existingAppointment = $record->surgeryAppointment;
$existingAppointment?->delete();
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\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(),
];
$appointment = SurgeryAppointment::updateOrCreate(
['patient_id' => $record->id],
[
'surgery_date' => $surgeryDateTime,
'surgery_center_id' => $data['surgery_center_id'],
]
);
try {
$response = \Illuminate\Support\Facades\Http::timeout(30)
->withHeader('X-API-Key', $apiKey)
->asJson()
->post($apiUrl . '/surgery-reminder', array_merge($smsPayload, [
'appointmentId' => $appointment->id,
]));
if (! ($response->json('success') ?? false)) {
\Filament\Notifications\Notification::make()
->title(__('patients.actions.api_failed'))
->body($response->json('message') ?? '')
->danger()
->send();
$action->halt();
return;
}
} catch (\Throwable $e) {
\Filament\Notifications\Notification::make()
->title(__('patients.actions.api_failed'))
->body($e->getMessage())
->danger()
->send();
$action->halt();
return;
}
\Filament\Notifications\Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.sms_sent'))
->success()
->send();
$record->refresh();
$action->halt();
}),
Action::make('prescription')
->label(__('prescriptions.actions.create'))
->icon('heroicon-o-document-text')
->iconButton()
->color('warning')
->slideOver()
->fillForm(function (Patient $record): array {
$prescription = Prescription::where('patient', $record->id)
->latest()
->first();
if ($prescription) {
$medicationIds = $prescription->medication_ids ?? [];
$labTestIds = $prescription->lab_test_ids ?? [];
$content = $prescription->content ?? '';
$labContent = $prescription->lab_content ?? '';
} else {
$defaultMeds = Medication::where('is_active', true)
->where('is_default', true)
->orderBy('name')
->get();
$medicationIds = $defaultMeds->pluck('id')->toArray();
$labTestIds = LabTest::where('is_active', true)
->where('is_default', true)
->orderBy('name')
->pluck('id')
->toArray();
$content = '';
$labContent = '';
}
if (empty($content) && ! empty($medicationIds)) {
$meds = Medication::whereIn('id', $medicationIds)->get()->keyBy('id');
$content = '<ul>' . collect($medicationIds)->map(fn ($id) => isset($meds[$id])
? '<li>' . implode(' ', array_filter([
$meds[$id]->dosage_form,
$meds[$id]->name,
$meds[$id]->strength,
$meds[$id]->quantity ? '#' . $meds[$id]->quantity : null,
$meds[$id]->timing,
])) . '</li>'
: ''
)->filter()->implode('') . '</ul>';
}
if (empty($labContent) && ! empty($labTestIds)) {
$tests = LabTest::whereIn('id', $labTestIds)->orderBy('name')->get();
$labContent = $tests->isNotEmpty()
? '<ul>' . $tests->map(fn ($t) => '<li>' . $t->name . '</li>')->implode('') . '</ul>'
: '';
}
return [
'medication_ids' => $medicationIds,
'medication_order' => $medicationIds,
'lab_test_ids' => $labTestIds,
'content' => $content,
'lab_content' => $labContent,
'issue_date' => now()->toDateString(),
];
})
->form([
Grid::make(2)
->schema([
\Filament\Forms\Components\Placeholder::make('patient_name')
->label(__('prescriptions.fields.patient'))
->content(fn (Patient $record) => $record->full_name),
\Filament\Forms\Components\DatePicker::make('issue_date')
->label(__('prescriptions.fields.issue_date'))
->jalali()
->required(),
]),
\Filament\Forms\Components\Hidden::make('medication_order'),
Tabs::make()
->tabs([
Tab::make(__('prescriptions.sections.medications'))
->icon('heroicon-o-clipboard-document-list')
->schema([
\Filament\Forms\Components\CheckboxList::make('medication_ids')
->label(__('prescriptions.fields.medication_ids'))
->options(fn () => Medication::where('is_active', true)
->orderBy('name')
->get()
->mapWithKeys(fn ($m) => [
$m->id => implode(' ', array_filter([
$m->dosage_form,
$m->name,
$m->strength,
$m->quantity ? '#' . $m->quantity : null,
$m->timing,
])),
])
->toArray()
)
->columns(2)
->live()
->afterStateUpdated(function (array $state, callable $set, callable $get) {
$currentOrder = array_map('intval', (array) ($get('medication_order') ?: []));
$state = array_map('intval', $state);
$newOrder = array_values(
array_filter($currentOrder, fn ($id) => in_array($id, $state))
);
foreach ($state as $id) {
if (! in_array($id, $newOrder)) {
$newOrder[] = $id;
}
}
$set('medication_order', $newOrder);
if (empty($newOrder)) {
$set('content', null);
return;
}
$medications = Medication::whereIn('id', $newOrder)->get()->keyBy('id');
$html = '<ul>' . collect($newOrder)
->map(fn ($id) => isset($medications[$id])
? '<li>' . implode(' ', array_filter([
$medications[$id]->dosage_form,
$medications[$id]->name,
$medications[$id]->strength,
$medications[$id]->quantity ? '#' . $medications[$id]->quantity : null,
$medications[$id]->timing,
])) . '</li>'
: ''
)
->filter()
->implode('') . '</ul>';
$set('content', $html);
})
->columnSpanFull(),
\Filament\Forms\Components\RichEditor::make('content')
->label(__('prescriptions.fields.content'))
->plugins([HighlightColorPlugin::make()])
->toolbarButtons([
['bold', 'italic', 'underline', 'strike'],
['highlightYellow', 'highlightRed'],
['bulletList', 'orderedList'],
['undo', 'redo'],
])
->columnSpanFull(),
]),
Tab::make(__('prescriptions.sections.lab_tests'))
->icon('heroicon-o-beaker')
->schema([
\Filament\Forms\Components\CheckboxList::make('lab_test_ids')
->label(__('prescriptions.fields.lab_test_ids'))
->options(fn () => LabTest::where('is_active', true)
->orderBy('name')
->get()
->mapWithKeys(fn ($t) => [$t->id => $t->name])
->toArray()
)
->columns(2)
->live()
->afterStateHydrated(function (array $state, callable $set, callable $get) {
if (empty($state) || ! empty($get('lab_content'))) {
return;
}
$tests = LabTest::whereIn('id', $state)->orderBy('name')->get();
$set('lab_content', '<ul>' . $tests->map(fn ($t) => '<li>' . $t->name . '</li>')->implode('') . '</ul>');
})
->afterStateUpdated(function (array $state, callable $set) {
if (empty($state)) {
$set('lab_content', null);
return;
}
$tests = LabTest::whereIn('id', $state)
->orderBy('name')
->get();
$html = '<ul>' . $tests->map(fn ($t) =>
'<li>' . $t->name . '</li>'
)->implode('') . '</ul>';
$set('lab_content', $html);
})
->columnSpanFull(),
\Filament\Forms\Components\RichEditor::make('lab_content')
->label(__('prescriptions.fields.lab_content'))
->plugins([HighlightColorPlugin::make()])
->toolbarButtons([
['bold', 'italic', 'underline', 'strike'],
['highlightYellow', 'highlightRed'],
['bulletList', 'orderedList'],
['undo', 'redo'],
])
->columnSpanFull(),
]),
])
->columnSpanFull(),
])
->modalSubmitAction(false)
->extraModalFooterActions(fn (Action $action): array => [
$action->makeModalSubmitAction('printPrescription', arguments: ['printType' => 'prescription'])
->label(__('prescriptions.actions.save_and_print'))
->color('info')
->icon('heroicon-o-printer'),
$action->makeModalSubmitAction('printAdmission', arguments: ['printType' => 'admission'])
->label(__('prescriptions.actions.print_admission'))
->color('warning')
->icon('heroicon-o-printer')
->visible(fn (Patient $record) => $record->surgeryAppointment !== null),
$action->makeModalSubmitAction('printLab', arguments: ['printType' => 'lab'])
->label(__('prescriptions.actions.print_lab'))
->color('gray')
->icon('heroicon-o-beaker'),
])
->action(function (Patient $record, array $data, array $arguments, $livewire): void {
$medicationOrder = $data['medication_order'] ?? $data['medication_ids'] ?? [];
$content = $data['content'] ?? '';
if (empty($content) && ! empty($medicationOrder)) {
$medications = Medication::whereIn('id', $medicationOrder)->get()->keyBy('id');
$content = '<ul>' . collect($medicationOrder)->map(fn ($id) => isset($medications[$id])
? '<li>' . implode(' ', array_filter([
$medications[$id]->dosage_form,
$medications[$id]->name,
$medications[$id]->strength,
$medications[$id]->quantity ? '#' . $medications[$id]->quantity : null,
$medications[$id]->timing,
])) . '</li>'
: ''
)->filter()->implode('') . '</ul>';
}
$labTestIds = $data['lab_test_ids'] ?? [];
$labContent = $data['lab_content'] ?? '';
if (empty($labContent) && ! empty($labTestIds)) {
$tests = LabTest::whereIn('id', $labTestIds)->orderBy('name')->get();
$labContent = '<ul>' . $tests->map(fn ($t) => '<li>' . $t->name . '</li>')->implode('') . '</ul>';
}
$prescription = Prescription::updateOrCreate(
['patient' => $record->id],
[
'doctor' => auth()->user()?->name,
'issue_date' => $data['issue_date'] ?? '',
'issue_datetime' => now(),
'medication_ids' => $medicationOrder,
'lab_test_ids' => $labTestIds,
'content' => $content,
'lab_content' => $labContent,
]
);
$printType = $arguments['printType'] ?? null;
if ($printType === 'prescription') {
$livewire->redirect(route('prescription.print', $prescription));
} elseif ($printType === 'admission') {
$livewire->redirect(route('prescription.print.admission', $prescription));
} elseif ($printType === 'lab') {
$livewire->redirect(route('prescription.print', ['prescription' => $prescription, 'type' => 'lab']));
}
})
->successNotificationTitle(__('prescriptions.actions.saved')),
Action::make('viewFiles')
->label(__('patients.actions.view_files'))
->icon('heroicon-o-paper-clip')
->iconButton()
->color('warning')
->visible(fn (Patient $record): bool =>
! empty(array_filter([
$record->photos_before,
$record->photos_after,
$record->videos,
$record->audio_files,
]))
)
->modalWidth(Width::ThreeExtraLarge)
->fillForm(fn (Patient $record): array => [
'photos_before' => \App\Filament\Resources\PatientResource\Pages\EditPatient::normalizeFileList($record->photos_before),
'photos_after' => \App\Filament\Resources\PatientResource\Pages\EditPatient::normalizeFileList($record->photos_after),
'videos' => \App\Filament\Resources\PatientResource\Pages\EditPatient::normalizeFileList($record->videos),
'audio_files' => \App\Filament\Resources\PatientResource\Pages\EditPatient::normalizeFileList($record->audio_files),
'surgery_before' => $record->surgery_before,
'sergery_after' => $record->sergery_after,
])
->schema([
\Filament\Forms\Components\Hidden::make('surgery_before'),
\Filament\Forms\Components\Hidden::make('sergery_after'),
Grid::make(2)
->schema([
FileUpload::make('photos_before')
->label(__('patients.fields.photos_before'))
->multiple()
->image()
->panelLayout('grid')
->disk('public')
->directory(function (Patient $record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
return "files/surgery_photos/{$year}/{$record->icno}/before";
})
->downloadable()
->openable()
->disabled()
->fetchFileInformation(false)
->extraAttributes(fn ($get): array => [
'class' => 'fi-photo-gallery fi-photo-gallery-view',
'data-hide-dropzone' => 'true',
'data-lb-section' => 'before',
'data-lb-caption' => htmlspecialchars($get('surgery_before') ?? '', ENT_QUOTES, 'UTF-8'),
]),
FileUpload::make('photos_after')
->label(__('patients.fields.photos_after'))
->multiple()
->image()
->panelLayout('grid')
->disk('public')
->directory(function (Patient $record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
return "files/surgery_photos/{$year}/{$record->icno}/after";
})
->downloadable()
->openable()
->disabled()
->fetchFileInformation(false)
->extraAttributes(fn ($get): array => [
'class' => 'fi-photo-gallery fi-photo-gallery-view',
'data-hide-dropzone' => 'true',
'data-lb-section' => 'after',
'data-lb-caption' => htmlspecialchars($get('sergery_after') ?? '', ENT_QUOTES, 'UTF-8'),
]),
FileUpload::make('videos')
->label(__('patients.fields.videos'))
->multiple()
->disk('public')
->directory(function (Patient $record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
return "files/surgery_photos/{$year}/{$record->icno}/videos";
})
->acceptedFileTypes([
'video/mp4', 'video/quicktime', 'video/x-msvideo',
'video/x-matroska', 'video/webm',
'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/x-wav',
'audio/ogg', 'audio/opus', 'audio/mp4', 'audio/x-m4a',
'audio/aac', 'audio/x-aac', 'audio/flac', 'audio/x-flac',
'audio/webm', 'audio/amr', 'audio/3gpp', 'audio/3gpp2',
'audio/aiff', 'audio/x-aiff',
])
->maxSize(102400)
->downloadable()
->disabled()
->fetchFileInformation(false)
->panelLayout('grid')
->extraAttributes(['class' => 'fi-video-gallery', 'data-hide-dropzone' => 'true']),
FileUpload::make('audio_files')
->label(__('patients.fields.audio_files'))
->multiple()
->disk('public')
->directory(function (Patient $record) {
$year = \Morilog\Jalali\Jalalian::now()->getYear();
return "files/surgery_photos/{$year}/{$record->icno}/audio";
})
->acceptedFileTypes([
'audio/mpeg',
'audio/mp3',
'audio/wav',
'audio/x-wav',
'audio/ogg',
'audio/opus',
'audio/mp4',
'audio/x-m4a',
'audio/aac',
'audio/x-aac',
'audio/flac',
'audio/x-flac',
'audio/webm',
'audio/amr',
'audio/3gpp',
'audio/3gpp2',
'audio/aiff',
'audio/x-aiff',
])
->downloadable()
->disabled()
->fetchFileInformation(false)
->extraAttributes(['data-hide-dropzone' => 'true']),
]),
])
->modalSubmitAction(false)
->modalCancelActionLabel('بستن'),
ViewAction::make()->iconButton()->color('gray'),
EditAction::make()->iconButton(),
DeleteAction::make()->iconButton(),
], position: \Filament\Tables\Enums\RecordActionsPosition::BeforeCells)
->toolbarActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
BulkAction::make('export_excel_selected')
->label(__('table.export_excel_selected'))
->icon('heroicon-o-table-cells')
->color('success')
->action(function (Collection $records) {
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('patients.fields.first_name'),
__('patients.fields.last_name'),
__('patients.fields.icno'),
__('patients.fields.gender'),
__('patients.fields.hand_phone'),
__('patients.fields.insurance'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->first_name,
$record->last_name,
$record->icno,
$record->gender,
$record->hand_phone,
$record->insurance,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'patients-' . now()->format('Y-m-d') . '.xlsx', [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}),
]),
ActionGroup::make([
Action::make('export_excel')
->label(__('table.export_excel'))
->color('success')
->icon('heroicon-o-table-cells')
->action(function () {
$records = Patient::orderBy('last_name')->orderBy('first_name')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('patients.fields.first_name'),
__('patients.fields.last_name'),
__('patients.fields.icno'),
__('patients.fields.gender'),
__('patients.fields.hand_phone'),
__('patients.fields.insurance'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->first_name,
$record->last_name,
$record->icno,
$record->gender,
$record->hand_phone,
$record->insurance,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'patients-' . now()->format('Y-m-d') . '.xlsx', [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}),
Action::make('export_pdf')
->label(__('table.export_pdf'))
->color('danger')
->icon('heroicon-o-document-arrow-down')
->action(function () {
$records = Patient::orderBy('last_name')->orderBy('first_name')->get();
return PdfService::download(
'exports.patients-pdf',
['records' => $records],
'patients-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getRelations(): array
{
return [
VisitsRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListPatients::route('/'),
'create' => Pages\CreatePatient::route('/create'),
'view' => Pages\ViewPatient::route('/{record}'),
'edit' => Pages\EditPatient::route('/{record}/edit'),
];
}
}