feat: initial project setup with Laravel 12 and Filament v4

This commit is contained in:
SajjadMahmoody
2026-04-03 17:25:17 +03:30
parent eca5d74b36
commit 09ee1cb743
324 changed files with 78304 additions and 23 deletions
+290
View File
@@ -0,0 +1,290 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\DoctorResource\Pages;
use App\Models\Doctor;
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\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class DoctorResource extends Resource
{
protected static ?string $model = Doctor::class;
protected static ?string $recordTitleAttribute = 'first_name';
public static function getGloballySearchableAttributes(): array
{
return ['first_name', 'last_name', 'speciality'];
}
public static function getGlobalSearchResultDetails(\Illuminate\Database\Eloquent\Model $record): array
{
return [
__('navigation.doctors.last_name') => $record->last_name,
];
}
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-user-circle';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.clinic');
}
public static function getNavigationSort(): ?int
{
return 1;
}
public static function getNavigationLabel(): string
{
return __('navigation.doctors.title');
}
public static function getModelLabel(): string
{
return __('navigation.doctors.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.doctors.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('first_name')
->label(__('doctors.fields.first_name'))
->required()
->maxLength(50),
TextInput::make('last_name')
->label(__('doctors.fields.last_name'))
->required()
->maxLength(50),
TextInput::make('speciality')
->label(__('doctors.fields.speciality'))
->maxLength(100),
TextInput::make('license_id')
->label(__('doctors.fields.license_id'))
->maxLength(50),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('first_name')
->label(__('doctors.fields.first_name'))
->weight(FontWeight::Medium)
->searchable()
->sortable(),
TextColumn::make('last_name')
->label(__('doctors.fields.last_name'))
->weight(FontWeight::Medium)
->searchable()
->sortable(),
TextColumn::make('speciality')
->label(__('doctors.fields.speciality'))
->searchable()
->sortable(),
TextColumn::make('license_id')
->label(__('doctors.fields.license_id'))
->badge()
->color('primary'),
TextColumn::make('created_at')
->label(__('doctors.fields.created_at'))
->sortable(),
])
->defaultSort('last_name')
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('doctors.fields.first_name'),
__('doctors.fields.last_name'),
__('doctors.fields.speciality'),
__('doctors.fields.license_id'),
__('doctors.fields.created_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->first_name,
$record->last_name,
$record->speciality,
$record->license_id,
$record->created_at,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'doctors-' . 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 = Doctor::all();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('doctors.fields.first_name'),
__('doctors.fields.last_name'),
__('doctors.fields.speciality'),
__('doctors.fields.license_id'),
__('doctors.fields.created_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->first_name,
$record->last_name,
$record->speciality,
$record->license_id,
$record->created_at,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'doctors-' . 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 = Doctor::all();
return PdfService::download(
'exports.doctors-pdf',
['records' => $records],
'doctors-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListDoctors::route('/'),
'create' => Pages\CreateDoctor::route('/create'),
'edit' => Pages\EditDoctor::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\DoctorResource\Pages;
use App\Filament\Resources\DoctorResource;
use Filament\Resources\Pages\CreateRecord;
class CreateDoctor extends CreateRecord
{
protected static string $resource = DoctorResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\DoctorResource\Pages;
use App\Filament\Resources\DoctorResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditDoctor extends EditRecord
{
protected static string $resource = DoctorResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\DoctorResource\Pages;
use App\Filament\Resources\DoctorResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListDoctors extends ListRecords
{
protected static string $resource = DoctorResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,202 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\MedicationResource\Pages;
use App\Models\Medication;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class MedicationResource extends Resource
{
protected static ?string $model = Medication::class;
protected static ?string $recordTitleAttribute = 'name';
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-beaker';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.diseases');
}
public static function getNavigationSort(): ?int
{
return 3;
}
public static function getNavigationLabel(): string
{
return __('navigation.medications.title');
}
public static function getModelLabel(): string
{
return __('navigation.medications.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.medications.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make(__('medications.sections.info'))
->schema([
TextInput::make('name')
->label(__('medications.fields.name'))
->required()
->maxLength(255),
TextInput::make('dosage_form')
->label(__('medications.fields.dosage_form'))
->maxLength(50)
->placeholder('Tab, Cap, Amp, Drop, Serum, Cream ...'),
TextInput::make('strength')
->label(__('medications.fields.strength'))
->maxLength(100)
->placeholder('500mg, 5mg/5ml ...'),
TextInput::make('quantity')
->label(__('medications.fields.quantity'))
->numeric()
->minValue(0),
TextInput::make('timing')
->label(__('medications.fields.timing'))
->maxLength(100)
->placeholder('q8h, q12h, q24h ...'),
Textarea::make('notes')
->label(__('medications.fields.notes'))
->rows(2)
->columnSpanFull(),
Toggle::make('is_default')
->label(__('medications.fields.is_default')),
Toggle::make('is_active')
->label(__('medications.fields.is_active'))
->default(true),
])
->columns(3)
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->label(__('medications.fields.name'))
->searchable()
->sortable(),
TextColumn::make('dosage_form')
->label(__('medications.fields.dosage_form'))
->badge()
->placeholder('-'),
TextColumn::make('strength')
->label(__('medications.fields.strength'))
->placeholder('-'),
TextColumn::make('quantity')
->label(__('medications.fields.quantity'))
->placeholder('-'),
TextColumn::make('timing')
->label(__('medications.fields.timing'))
->placeholder('-'),
IconColumn::make('is_default')
->label(__('medications.fields.is_default'))
->boolean(),
IconColumn::make('is_active')
->label(__('medications.fields.is_active'))
->boolean(),
TextColumn::make('created_at')
->label(__('medications.fields.created_at'))
->sortable(),
])
->defaultSort('name')
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->toolbarActions([
\Filament\Actions\BulkActionGroup::make([
DeleteBulkAction::make(),
]),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListMedications::route('/'),
'create' => Pages\CreateMedication::route('/create'),
'edit' => Pages\EditMedication::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\MedicationResource\Pages;
use App\Filament\Resources\MedicationResource;
use Filament\Resources\Pages\CreateRecord;
use Filament\Support\Enums\Width;
class CreateMedication extends CreateRecord
{
protected static string $resource = MedicationResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\MedicationResource\Pages;
use App\Filament\Resources\MedicationResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
class EditMedication extends EditRecord
{
protected static string $resource = MedicationResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\MedicationResource\Pages;
use App\Filament\Resources\MedicationResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Enums\Width;
class ListMedications extends ListRecords
{
protected static string $resource = MedicationResource::class;
protected Width|string|null $maxContentWidth = Width::Full;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\OsurgAuditResource\Pages;
use App\Models\SyncLog;
use Filament\Resources\Resource;
use Morilog\Jalali\Jalalian;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class OsurgAuditResource extends Resource
{
protected static ?string $model = SyncLog::class;
protected static bool $isGloballySearchable = false;
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-clipboard-document-list';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.settings');
}
public static function getNavigationSort(): ?int
{
return 20;
}
public static function getNavigationLabel(): string
{
return __('navigation.osurg_audit.title');
}
public static function getModelLabel(): string
{
return __('navigation.osurg_audit.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.osurg_audit.title');
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('id')
->label(__('sync_log.fields.id'))
->sortable(),
TextColumn::make('datetime')
->label(__('sync_log.fields.datetime'))
->sortable()
->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;
}
}),
TextColumn::make('ip')
->label(__('sync_log.fields.ip'))
->searchable(),
TextColumn::make('user')
->label(__('sync_log.fields.user'))
->searchable(),
TextColumn::make('table_name')
->label(__('sync_log.fields.table_name'))
->searchable(),
TextColumn::make('action')
->label(__('sync_log.fields.action'))
->badge()
->searchable()
->color(fn (string $state): string => match ($state) {
'created' => 'success',
'updated' => 'warning',
'deleted' => 'danger',
'synced' => 'gray',
default => 'primary',
}),
TextColumn::make('record_id')
->label(__('sync_log.fields.record_id')),
])
->defaultSort('id', 'desc');
}
public static function getPages(): array
{
return [
'index' => Pages\ListOsurgAudits::route('/'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\OsurgAuditResource\Pages;
use App\Filament\Resources\OsurgAuditResource;
use Filament\Resources\Pages\ListRecords;
class ListOsurgAudits extends ListRecords
{
protected static string $resource = OsurgAuditResource::class;
protected function getHeaderActions(): array
{
return [];
}
}
@@ -0,0 +1,264 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\OsurgInitialResource\Pages;
use App\Models\OsurgInitial;
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\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class OsurgInitialResource extends Resource
{
protected static ?string $model = OsurgInitial::class;
protected static ?string $recordTitleAttribute = 'init_parameter';
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-adjustments-horizontal';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.settings');
}
public static function getNavigationSort(): ?int
{
return 1;
}
public static function getNavigationLabel(): string
{
return __('navigation.osurg_initials.title');
}
public static function getModelLabel(): string
{
return __('navigation.osurg_initials.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.osurg_initials.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('init_parameter')
->label(__('osurg_initials.fields.init_parameter'))
->required()
->maxLength(50)
->unique(table: OsurgInitial::class, column: 'init_parameter', ignoreRecord: true),
TextInput::make('init_value')
->label(__('osurg_initials.fields.init_value'))
->maxLength(50),
FileUpload::make('attachment')
->label(__('osurg_initials.fields.attachment'))
->disk('public')
->directory('initials')
->image()
->imagePreviewHeight('120')
->columnSpanFull(),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('init_parameter')
->label(__('osurg_initials.fields.init_parameter'))
->searchable()
->sortable(),
TextColumn::make('init_value')
->label(__('osurg_initials.fields.init_value'))
->searchable()
->placeholder('—'),
ImageColumn::make('attachment')
->label(__('osurg_initials.fields.attachment'))
->disk('public')
->square()
->size(48),
TextColumn::make('created_at')
->label(__('osurg_initials.fields.created_at'))
->sortable(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('osurg_initials.fields.init_parameter'),
__('osurg_initials.fields.init_value'),
__('osurg_initials.fields.created_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->init_parameter,
$record->init_value,
$record->created_at,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'osurg-initials-' . 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 = OsurgInitial::all();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('osurg_initials.fields.init_parameter'),
__('osurg_initials.fields.init_value'),
__('osurg_initials.fields.created_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->init_parameter,
$record->init_value,
$record->created_at,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'osurg-initials-' . 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 = OsurgInitial::all();
return PdfService::download(
'exports.osurg-initials-pdf',
['records' => $records],
'osurg-initials-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListOsurgInitials::route('/'),
'create' => Pages\CreateOsurgInitial::route('/create'),
'edit' => Pages\EditOsurgInitial::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\OsurgInitialResource\Pages;
use App\Filament\Resources\OsurgInitialResource;
use Filament\Resources\Pages\CreateRecord;
class CreateOsurgInitial extends CreateRecord
{
protected static string $resource = OsurgInitialResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\OsurgInitialResource\Pages;
use App\Filament\Resources\OsurgInitialResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditOsurgInitial extends EditRecord
{
protected static string $resource = OsurgInitialResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\OsurgInitialResource\Pages;
use App\Filament\Resources\OsurgInitialResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListOsurgInitials extends ListRecords
{
protected static string $resource = OsurgInitialResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,278 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\PatientIllnessResource\Pages;
use App\Models\PatientIllness;
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\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class PatientIllnessResource extends Resource
{
protected static ?string $model = PatientIllness::class;
protected static ?string $recordTitleAttribute = 'illness';
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-heart';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.diseases');
}
public static function getNavigationSort(): ?int
{
return 1;
}
public static function getNavigationLabel(): string
{
return __('navigation.patient_illness.title');
}
public static function getModelLabel(): string
{
return __('navigation.patient_illness.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.patient_illness.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('illness')
->label(__('patient_illness.fields.illness'))
->required()
->maxLength(200)
->columnSpanFull(),
Select::make('row_no')
->label(__('patient_illness.fields.row_no'))
->options([
1 => __('patient_illness.row_options.first'),
2 => __('patient_illness.row_options.second'),
])
->required(),
TextInput::make('priority')
->label(__('patient_illness.fields.priority'))
->numeric()
->minValue(1),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('illness')
->label(__('patient_illness.fields.illness'))
->weight(FontWeight::Medium)
->searchable()
->sortable(),
TextColumn::make('row_no')
->label(__('patient_illness.fields.row_no'))
->badge()
->color('gray')
->formatStateUsing(fn (int $state): string => $state === 1
? __('patient_illness.row_options.first')
: __('patient_illness.row_options.second'))
->sortable(),
TextColumn::make('priority')
->label(__('patient_illness.fields.priority'))
->badge()
->color('primary')
->sortable(),
])
->reorderable('priority')
->defaultSort('priority')
->groups([
Group::make('row_no')
->label(__('patient_illness.fields.row_no'))
->getTitleFromRecordUsing(fn (PatientIllness $record): string => $record->row_no === 1
? __('patient_illness.row_options.first')
: __('patient_illness.row_options.second')),
])
->defaultGroup('row_no')
->groupingSettingsHidden()
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('patient_illness.fields.illness'),
__('patient_illness.fields.row_no'),
__('patient_illness.fields.priority'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->illness,
$record->row_no,
$record->priority,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'patient-illness-' . 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 = PatientIllness::orderBy('row_no')->orderBy('priority')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('patient_illness.fields.illness'),
__('patient_illness.fields.row_no'),
__('patient_illness.fields.priority'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->illness,
$record->row_no,
$record->priority,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'patient-illness-' . 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 = PatientIllness::orderBy('row_no')->orderBy('priority')->get();
return PdfService::download(
'exports.patient-illness-pdf',
['records' => $records],
'patient-illness-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListPatientIllnesses::route('/'),
'create' => Pages\CreatePatientIllness::route('/create'),
'edit' => Pages\EditPatientIllness::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientIllnessResource\Pages;
use App\Filament\Resources\PatientIllnessResource;
use Filament\Resources\Pages\CreateRecord;
class CreatePatientIllness extends CreateRecord
{
protected static string $resource = PatientIllnessResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientIllnessResource\Pages;
use App\Filament\Resources\PatientIllnessResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditPatientIllness extends EditRecord
{
protected static string $resource = PatientIllnessResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientIllnessResource\Pages;
use App\Filament\Resources\PatientIllnessResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListPatientIllnesses extends ListRecords
{
protected static string $resource = PatientIllnessResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
+998
View File
@@ -0,0 +1,998 @@
<?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\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 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 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\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
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 getGloballySearchableAttributes(): array
{
return ['first_name', 'last_name', 'hand_phone'];
}
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'))
->required()
->validationMessages([
'required' => __('patients.validation.father_name_required'),
])
->maxLength(50),
TextInput::make('icno')
->label(__('patients.fields.icno'))
->required()
->maxLength(11),
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'))
->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']),
RichEditor::make('sergery_after')
->label(__('patients.fields.sergery_after'))
->extraInputAttributes(['style' => 'min-height: 150px']),
])
->columns(2)
->columnSpanFull(),
Section::make(__('patients.sections.media'))
->schema([
FileUpload::make('photos_before')
->label(__('patients.fields.photos_before'))
->multiple()
->image()
->disk('public')
->directory('surgery_photos/before')
->downloadable()
->openable(),
FileUpload::make('photos_after')
->label(__('patients.fields.photos_after'))
->multiple()
->image()
->disk('public')
->directory('surgery_photos/after')
->downloadable()
->openable(),
FileUpload::make('videos')
->label(__('patients.fields.videos'))
->multiple()
->disk('public')
->directory('surgery_photos/videos')
->acceptedFileTypes(['video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska', 'video/webm', 'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/aac'])
->downloadable(),
FileUpload::make('audio_files')
->label(__('patients.fields.audio_files'))
->multiple()
->disk('public')
->directory('audio_files')
->acceptedFileTypes(['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/mp4', 'audio/aac'])
->downloadable(),
])
->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 table(Table $table): Table
{
return $table
->modifyQueryUsing(fn ($query) => $query->with(['creator', 'updator', 'surgeryAppointment']))
->deferLoading()
->columns([
TextColumn::make('first_name')
->label(__('patients.fields.first_name'))
->searchable()
->sortable(),
TextColumn::make('last_name')
->label(__('patients.fields.last_name'))
->searchable()
->sortable(),
TextColumn::make('hand_phone')
->label(__('patients.fields.hand_phone'))
->placeholder('-'),
TextColumn::make('home_phone')
->label(__('patients.fields.home_phone'))
->placeholder('-'),
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(function ($state) {
$text = strip_tags($state ?? '');
if (! $text) {
return '-';
}
if (mb_strlen($text) > 30) {
return mb_substr($text, 0, 30)
. ' <span class="text-primary-600 text-xs font-semibold cursor-pointer">... بیشتر</span>';
}
return $text;
})
->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(function ($state) {
$text = strip_tags($state ?? '');
if (! $text) {
return '-';
}
if (mb_strlen($text) > 30) {
return mb_substr($text, 0, 30)
. ' <span class="text-primary-600 text-xs font-semibold cursor-pointer">... بیشتر</span>';
}
return $text;
})
->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('created_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'])) {
SurgeryAppointment::where('patient_id', $record->id)->delete();
\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');
$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', \App\Models\OsurgInitial::val('sms_api_key', config('sms.api_key')))
->post(\App\Models\OsurgInitial::val('sms_api_url', config('sms.api_url')) . '/surgery-reminder', [
'phoneNumber' => $record->hand_phone ?? '',
'patientName' => $record->full_name,
'surgeryDate' => $jalaliDate,
'appointmentId' => $appointment->id,
'patientId' => $record->id,
'surgeryDateFull' => $surgeryDateTime->toDateTimeString(),
]);
if (! ($response->json('success') ?? false)) {
\Filament\Notifications\Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.api_failed') . ': ' . ($response->json('message') ?? ''))
->warning()
->send();
} else {
\Filament\Notifications\Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.sms_sent'))
->success()
->send();
}
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('Surgery appointment API failed', [
'patient_id' => $record->id,
'appointment_id' => $appointment->id,
'error' => $e->getMessage(),
]);
\Filament\Notifications\Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.api_failed') . ': ' . $e->getMessage())
->warning()
->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 ?? [];
$content = $prescription->content ?? '';
} else {
$defaultMeds = Medication::where('is_active', true)
->where('is_default', true)
->orderBy('name')
->get();
$medicationIds = $defaultMeds->pluck('id')->toArray();
$content = $defaultMeds->isNotEmpty()
? '<ul>' . $defaultMeds->map(fn ($m) =>
'<li>' . implode(' ', array_filter([
$m->dosage_form,
$m->name,
$m->strength,
$m->quantity ? '#' . $m->quantity : null,
$m->timing,
])) . '</li>'
)->implode('') . '</ul>'
: '';
}
return [
'medication_ids' => $medicationIds,
'medication_order' => $medicationIds,
'content' => $content,
'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'),
\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'))
->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 {
$prescription = Prescription::updateOrCreate(
['patient' => $record->id],
[
'doctor' => auth()->user()?->name,
'issue_date' => $data['issue_date'] ?? '',
'issue_datetime' => now(),
'medication_ids' => $data['medication_order'] ?? $data['medication_ids'] ?? [],
'content' => $data['content'] ?? '',
]
);
$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::Large)
->fillForm(fn (Patient $record): array => [
'photos_before' => $record->photos_before ?? [],
'photos_after' => $record->photos_after ?? [],
'videos' => $record->videos ?? [],
'audio_files' => $record->audio_files ?? [],
])
->schema([
Grid::make(2)
->schema([
FileUpload::make('photos_before')
->label(__('patients.fields.photos_before'))
->multiple()
->image()
->imagePreviewHeight('150')
->disk('public')
->directory('surgery_photos/before')
->downloadable()
->openable()
->disabled()
->extraAttributes(['data-hide-dropzone' => 'true']),
FileUpload::make('photos_after')
->label(__('patients.fields.photos_after'))
->multiple()
->image()
->imagePreviewHeight('150')
->disk('public')
->directory('surgery_photos/after')
->downloadable()
->openable()
->disabled()
->extraAttributes(['data-hide-dropzone' => 'true']),
FileUpload::make('videos')
->label(__('patients.fields.videos'))
->multiple()
->disk('public')
->directory('surgery_photos/videos')
->acceptedFileTypes(['video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska', 'video/webm', 'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/aac'])
->downloadable()
->disabled()
->extraAttributes(['data-hide-dropzone' => 'true']),
FileUpload::make('audio_files')
->label(__('patients.fields.audio_files'))
->multiple()
->disk('public')
->directory('audio_files')
->acceptedFileTypes(['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/mp4', 'audio/aac'])
->downloadable()
->disabled()
->extraAttributes(['data-hide-dropzone' => 'true']),
]),
])
->modalSubmitAction(false)
->modalCancelActionLabel('بستن'),
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'),
'edit' => Pages\EditPatient::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientResource\Pages;
use App\Filament\Resources\PatientResource;
use Filament\Resources\Pages\CreateRecord;
use Filament\Support\Enums\Width;
class CreatePatient extends CreateRecord
{
protected static string $resource = PatientResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientResource\Pages;
use App\Filament\Resources\PatientResource;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
class EditPatient extends EditRecord
{
protected static string $resource = PatientResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getHeaderActions(): array
{
return [
Action::make('printPrescription')
->label(__('prescriptions.actions.print_prescription'))
->icon('heroicon-o-printer')
->color('info')
->visible(fn () => $this->getRecord()->prescriptions()->exists())
->url(fn () => route('prescription.print', $this->getRecord()->prescriptions()->latest()->first()))
->openUrlInNewTab(),
Action::make('printAdmission')
->label(__('prescriptions.actions.print_admission'))
->icon('heroicon-o-printer')
->color('warning')
->visible(fn () => $this->getRecord()->surgeryAppointment !== null)
->url(fn () => route('surgery-appointment.print.admission', $this->getRecord()))
->openUrlInNewTab(),
Action::make('printLab')
->label(__('prescriptions.actions.print_lab'))
->icon('heroicon-o-beaker')
->color('gray')
->url(fn () => route('patient.print.lab', $this->getRecord()))
->openUrlInNewTab(),
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientResource\Pages;
use App\Filament\Resources\PatientResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Enums\Width;
class ListPatients extends ListRecords
{
protected static string $resource = PatientResource::class;
protected Width|string|null $maxContentWidth = Width::Full;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,202 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PatientResource\RelationManagers;
use App\Models\Doctor;
use App\Models\PaymentType;
use App\Models\Treatment;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\TimePicker;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\Summarizers\Sum;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class VisitsRelationManager extends RelationManager
{
protected static string $relationship = 'visits';
public static function getTitle(\Illuminate\Database\Eloquent\Model $ownerRecord, string $pageClass): string
{
return __('navigation.visits.title');
}
public function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make(__('visits.sections.visit_info'))
->schema([
DatePicker::make('visit_date')
->label(__('visits.fields.visit_date'))
->jalali()
->default(now())
->required(),
TimePicker::make('visit_time')
->label(__('visits.fields.visit_time'))
->nullable()
->native(false)
->seconds(false)
->minutesStep(15),
Select::make('doctor')
->label(__('visits.fields.doctor'))
->options(fn () => Doctor::all()->mapWithKeys(
fn ($d) => [$d->id => $d->full_name]
)->toArray())
->searchable()
->nullable(),
Select::make('treatment')
->label(__('visits.fields.treatment'))
->options(fn () => Treatment::all()->mapWithKeys(
fn ($t) => [$t->id => ($t->treatment_name ?: $t->treatment_type)]
)->toArray())
->searchable()
->nullable()
->live()
->afterStateUpdated(function ($state, callable $set) {
if ($state) {
$treatment = Treatment::find($state);
if ($treatment && $treatment->treatment_cost > 0) {
$set('treatment_cost', $treatment->treatment_cost);
}
}
}),
])
->columns(2)
->columnSpanFull(),
Section::make(__('visits.sections.financial_info'))
->schema([
TextInput::make('treatment_cost')
->label(__('visits.fields.treatment_cost'))
->numeric()
->nullable()
->suffix(__('visits.fields.currency')),
TextInput::make('paid_amount')
->label(__('visits.fields.paid_amount'))
->numeric()
->nullable()
->suffix(__('visits.fields.currency')),
Select::make('payment_type')
->label(__('visits.fields.payment_type'))
->options(fn () => PaymentType::all()->mapWithKeys(
fn ($p) => [$p->id => $p->payment_type]
)->toArray())
->searchable()
->nullable(),
])
->columns(3)
->columnSpanFull(),
Section::make(__('visits.sections.treatment_details'))
->schema([
Textarea::make('treatment_description')
->label(__('visits.fields.treatment_description'))
->rows(3)
->columnSpanFull(),
])
->columnSpanFull(),
])
->columnSpanFull(),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('visit_date')
->columns([
TextColumn::make('visit_date')
->label(__('visits.fields.visit_date'))
->sortable()
->formatStateUsing(function ($state) {
if (! $state) {
return '-';
}
try {
$date = \Carbon\Carbon::parse($state);
return \Morilog\Jalali\Jalalian::fromCarbon($date)->format('Y/m/d');
} catch (\Exception $e) {
return $state;
}
})
->placeholder('-'),
TextColumn::make('doctorRecord.first_name')
->label(__('visits.fields.doctor'))
->formatStateUsing(fn ($record) => $record->doctorRecord?->full_name ?? '-')
->placeholder('-'),
TextColumn::make('treatmentRecord.treatment_name')
->label(__('visits.fields.treatment'))
->formatStateUsing(fn ($record) => $record->treatmentRecord
? ($record->treatmentRecord->treatment_name ?: $record->treatmentRecord->treatment_type)
: '-')
->placeholder('-'),
TextColumn::make('treatment_cost')
->label(__('visits.fields.treatment_cost'))
->formatStateUsing(fn ($state) => $state !== null ? number_format((int) $state) : '-')
->placeholder('-')
->summarize(
Sum::make()
->label(__('visits.fields.treatment_cost'))
->formatStateUsing(fn ($state) => number_format((int) ($state ?? 0)))
),
TextColumn::make('paid_amount')
->label(__('visits.fields.paid_amount'))
->formatStateUsing(fn ($state) => $state !== null ? number_format((int) $state) : '-')
->placeholder('-')
->summarize(
Sum::make()
->label(__('visits.fields.paid_amount'))
->formatStateUsing(fn ($state) => number_format((int) ($state ?? 0)))
),
TextColumn::make('remained_amount')
->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'),
TextColumn::make('paymentTypeRecord.payment_type')
->label(__('visits.fields.payment_type'))
->placeholder('-'),
])
->defaultSort('visit_date', 'desc')
->headerActions([
CreateAction::make()
->label(__('visits.actions.create'))
->icon('heroicon-o-plus')
->slideOver()
->modalWidth('4xl'),
])
->recordActions([
EditAction::make()
->slideOver()
->modalWidth('4xl'),
DeleteAction::make(),
])
->toolbarActions([]);
}
}
@@ -0,0 +1,271 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\PaymentTypeResource\Pages;
use App\Models\PaymentType;
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\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class PaymentTypeResource extends Resource
{
protected static ?string $model = PaymentType::class;
protected static ?string $recordTitleAttribute = 'payment_type';
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-credit-card';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.clinic');
}
public static function getNavigationSort(): ?int
{
return 2;
}
public static function getNavigationLabel(): string
{
return __('navigation.payment_types.title');
}
public static function getModelLabel(): string
{
return __('navigation.payment_types.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.payment_types.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('payment_type')
->label(__('payment_types.fields.payment_type'))
->required()
->maxLength(50),
TextInput::make('account_no')
->label(__('payment_types.fields.account_no'))
->maxLength(50),
TextInput::make('pos_no')
->label(__('payment_types.fields.pos_no'))
->maxLength(50),
Textarea::make('description')
->label(__('payment_types.fields.description'))
->rows(3)
->columnSpanFull(),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('payment_type')
->label(__('payment_types.fields.payment_type'))
->weight(FontWeight::Medium)
->searchable()
->sortable(),
TextColumn::make('account_no')
->label(__('payment_types.fields.account_no'))
->placeholder('-'),
TextColumn::make('pos_no')
->label(__('payment_types.fields.pos_no'))
->placeholder('-'),
TextColumn::make('description')
->label(__('payment_types.fields.description'))
->limit(50)
->placeholder('-'),
TextColumn::make('created_at')
->label(__('payment_types.fields.created_at'))
->sortable(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('payment_types.fields.payment_type'),
__('payment_types.fields.account_no'),
__('payment_types.fields.pos_no'),
__('payment_types.fields.description'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->payment_type,
$record->account_no,
$record->pos_no,
$record->description,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'payment-types-' . 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 = PaymentType::all();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('payment_types.fields.payment_type'),
__('payment_types.fields.account_no'),
__('payment_types.fields.pos_no'),
__('payment_types.fields.description'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->payment_type,
$record->account_no,
$record->pos_no,
$record->description,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'payment-types-' . 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 = PaymentType::all();
return PdfService::download(
'exports.payment-types-pdf',
['records' => $records],
'payment-types-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListPaymentTypes::route('/'),
'create' => Pages\CreatePaymentType::route('/create'),
'edit' => Pages\EditPaymentType::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PaymentTypeResource\Pages;
use App\Filament\Resources\PaymentTypeResource;
use Filament\Resources\Pages\CreateRecord;
class CreatePaymentType extends CreateRecord
{
protected static string $resource = PaymentTypeResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PaymentTypeResource\Pages;
use App\Filament\Resources\PaymentTypeResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditPaymentType extends EditRecord
{
protected static string $resource = PaymentTypeResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PaymentTypeResource\Pages;
use App\Filament\Resources\PaymentTypeResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListPaymentTypes extends ListRecords
{
protected static string $resource = PaymentTypeResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,373 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\PrescriptionResource\Pages;
use App\Models\Medication;
use App\Models\Patient;
use App\Models\Prescription;
use App\Services\PdfService;
use Morilog\Jalali\Jalalian;
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\Forms\Components\CheckboxList;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class PrescriptionResource extends Resource
{
protected static ?string $model = Prescription::class;
protected static ?string $recordTitleAttribute = 'doctor';
public static function getGloballySearchableAttributes(): array
{
return ['doctor', 'patientRecord.first_name', 'patientRecord.last_name'];
}
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-document-text';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.patients');
}
public static function getNavigationSort(): ?int
{
return 2;
}
public static function getNavigationLabel(): string
{
return __('navigation.prescriptions.title');
}
public static function getModelLabel(): string
{
return __('navigation.prescriptions.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.prescriptions.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make(__('prescriptions.sections.info'))
->schema([
Select::make('patient')
->label(__('prescriptions.fields.patient'))
->options(fn () => Patient::all()->mapWithKeys(
fn ($p) => [$p->id => $p->full_name]
)->toArray())
->searchable()
->nullable(),
DatePicker::make('issue_date')
->label(__('prescriptions.fields.issue_date'))
->jalali()
->default(now()),
])
->columns(2)
->columnSpanFull(),
Section::make(__('prescriptions.sections.medications'))
->schema([
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(3)
->live()
->afterStateUpdated(function (array $state, callable $set) {
if (empty($state)) {
$set('content', null);
return;
}
$medications = Medication::whereIn('id', $state)
->orderBy('name')
->get();
$html = '<ul>' . $medications->map(fn ($m) =>
'<li>' . implode(' ', array_filter([
$m->dosage_form,
$m->name,
$m->strength,
$m->quantity ? '#' . $m->quantity : null,
$m->timing,
])) . '</li>'
)->implode('') . '</ul>';
$set('content', $html);
})
->columnSpanFull(),
])
->columnSpanFull(),
Section::make(__('prescriptions.sections.content'))
->schema([
RichEditor::make('content')
->label(__('prescriptions.fields.content'))
->columnSpanFull(),
])
->columnSpanFull()
->footerActions([
fn (string $operation) => Action::make('createAndPrint')
->label(__('prescriptions.actions.save_and_print'))
->color('warning')
->icon('heroicon-o-printer')
->action(function ($livewire) {
$livewire->printType = 'prescription';
$livewire->create();
})
->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 table(Table $table): Table
{
return $table
->modifyQueryUsing(fn ($query) => $query->with(['patientRecord', 'creator']))
->deferLoading()
->columns([
TextColumn::make('patientRecord.first_name')
->label(__('prescriptions.fields.patient'))
->formatStateUsing(fn ($record) => $record->patientRecord?->full_name ?? '-')
->searchable()
->sortable(),
TextColumn::make('doctor')
->label(__('prescriptions.fields.doctor'))
->searchable()
->sortable(),
TextColumn::make('issue_date')
->label(__('prescriptions.fields.issue_date'))
->sortable()
->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;
}
})
->placeholder('-'),
TextColumn::make('content')
->label(__('prescriptions.fields.content'))
->formatStateUsing(fn ($state) => strip_tags($state ?? ''))
->limit(80)
->placeholder('-'),
TextColumn::make('creator.name')
->label(__('prescriptions.fields.created_by'))
->sortable(),
TextColumn::make('created_at')
->label(__('prescriptions.fields.created_at'))
->sortable()
->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;
}
}),
])
->defaultSort('created_at', 'desc')
->recordActions([
Action::make('printPrescription')
->label(__('prescriptions.actions.print_prescription'))
->icon('heroicon-o-printer')
->color('info')
->url(fn ($record) => route('prescription.print', $record))
->openUrlInNewTab(),
Action::make('printAdmission')
->label(__('prescriptions.actions.print_admission'))
->icon('heroicon-o-printer')
->color('warning')
->url(fn ($record) => route('prescription.print.admission', $record))
->openUrlInNewTab(),
Action::make('printLab')
->label(__('prescriptions.actions.print_lab'))
->icon('heroicon-o-beaker')
->color('gray')
->url(fn ($record) => route('prescription.print', ['prescription' => $record, 'type' => 'lab']))
->openUrlInNewTab(),
EditAction::make(),
DeleteAction::make(),
])
->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',
__('prescriptions.fields.patient'),
__('prescriptions.fields.doctor'),
__('prescriptions.fields.issue_date'),
__('prescriptions.fields.content'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->patientRecord?->full_name ?? '',
$record->doctor,
$record->issue_date,
strip_tags($record->content ?? ''),
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'prescriptions-' . 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 = Prescription::with('patientRecord')->orderBy('created_at', 'desc')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('prescriptions.fields.patient'),
__('prescriptions.fields.doctor'),
__('prescriptions.fields.issue_date'),
__('prescriptions.fields.content'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->patientRecord?->full_name ?? '',
$record->doctor,
$record->issue_date,
strip_tags($record->content ?? ''),
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'prescriptions-' . 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 = Prescription::with('patientRecord')->orderBy('created_at', 'desc')->get();
return PdfService::download(
'exports.prescriptions-pdf',
['records' => $records],
'prescriptions-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListPrescriptions::route('/'),
'create' => Pages\CreatePrescription::route('/create'),
'edit' => Pages\EditPrescription::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PrescriptionResource\Pages;
use App\Filament\Resources\PrescriptionResource;
use Filament\Resources\Pages\CreateRecord;
use Filament\Support\Enums\Width;
class CreatePrescription extends CreateRecord
{
protected static string $resource = PrescriptionResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
public string $printType = '';
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['doctor'] = auth()->user()?->name;
$data['issue_datetime'] = now();
return $data;
}
protected function getFormActions(): array
{
return [];
}
protected function getRedirectUrl(): string
{
$record = $this->getRecord();
if ($this->printType === 'prescription') {
return route('prescription.print', $record);
}
if ($this->printType === 'lab') {
return route('prescription.print', ['prescription' => $record, 'type' => 'lab']);
}
if ($this->printType === 'admission') {
return route('prescription.print.admission', $record);
}
return static::getResource()::getUrl('index');
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PrescriptionResource\Pages;
use App\Filament\Resources\PrescriptionResource;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
class EditPrescription extends EditRecord
{
protected static string $resource = PrescriptionResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function mutateFormDataBeforeSave(array $data): array
{
$data['doctor'] = auth()->user()?->name;
$data['issue_datetime'] = now();
return $data;
}
protected function getHeaderActions(): array
{
return [
Action::make('printPrescription')
->label(__('prescriptions.actions.print_prescription'))
->icon('heroicon-o-printer')
->color('info')
->url(fn () => route('prescription.print', $this->getRecord()))
->openUrlInNewTab(),
Action::make('printAdmission')
->label(__('prescriptions.actions.print_admission'))
->icon('heroicon-o-printer')
->color('warning')
->visible(fn () => $this->getRecord()->patientRecord?->surgeryAppointment !== null)
->url(fn () => route('prescription.print.admission', $this->getRecord()))
->openUrlInNewTab(),
Action::make('printLab')
->label(__('prescriptions.actions.print_lab'))
->icon('heroicon-o-beaker')
->color('gray')
->url(fn () => route('prescription.print', ['prescription' => $this->getRecord(), 'type' => 'lab']))
->openUrlInNewTab(),
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\PrescriptionResource\Pages;
use App\Filament\Resources\PrescriptionResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListPrescriptions extends ListRecords
{
protected static string $resource = PrescriptionResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
+335
View File
@@ -0,0 +1,335 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\RoleResource\Pages;
use App\Services\PdfService;
use Morilog\Jalali\Jalalian;
use BezhanSalleh\FilamentShield\Resources\Roles\RoleResource as ShieldRoleResource;
use BezhanSalleh\FilamentShield\Support\Utils;
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 Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
use Filament\Facades\Filament;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Unique;
use Livewire\Component as Livewire;
use Spatie\Permission\Models\Role;
class RoleResource extends ShieldRoleResource
{
public static function getNavigationLabel(): string
{
return __('navigation.roles.title');
}
public static function getModelLabel(): string
{
return __('navigation.roles.title');
}
public static function getPluralModelLabel(): string
{
return __('navigation.roles.title');
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.settings');
}
public static function getNavigationSort(): ?int
{
return 2;
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('name')
->label(__('filament-shield::filament-shield.field.name'))
->unique(
ignoreRecord: true,
modifyRuleUsing: fn (Unique $rule): Unique => Utils::isTenancyEnabled()
? $rule->where(Utils::getTenantModelForeignKey(), Filament::getTenant()?->id)
: $rule
)
->required()
->maxLength(255),
TextInput::make('guard_name')
->label(__('filament-shield::filament-shield.field.guard_name'))
->default(Utils::getFilamentAuthGuard())
->nullable()
->maxLength(255),
Select::make(config('permission.column_names.team_foreign_key'))
->label(__('filament-shield::filament-shield.field.team'))
->placeholder(__('filament-shield::filament-shield.field.team.placeholder'))
->default(Filament::getTenant()?->id)
->options(fn (): array => in_array(Utils::getTenantModel(), [null, '', '0'], true) ? [] : Utils::getTenantModel()::pluck('name', 'id')->toArray())
->visible(fn (): bool => static::shield()->isCentralApp() && Utils::isTenancyEnabled())
->dehydrated(fn (): bool => static::shield()->isCentralApp() && Utils::isTenancyEnabled()),
static::getSelectAllFormComponent(),
])
->columns(['sm' => 2, 'lg' => 3])
->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(),
static::getShieldFormComponents(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->weight(FontWeight::Medium)
->label(__('filament-shield::filament-shield.column.name'))
->formatStateUsing(fn (string $state): string => Str::headline($state))
->searchable(),
TextColumn::make('guard_name')
->badge()
->color('warning')
->label(__('filament-shield::filament-shield.column.guard_name')),
TextColumn::make('team.name')
->default('Global')
->badge()
->color(fn (mixed $state): string => str($state)->contains('Global') ? 'gray' : 'primary')
->label(__('filament-shield::filament-shield.column.team'))
->searchable()
->visible(fn (): bool => static::shield()->isCentralApp() && Utils::isTenancyEnabled()),
TextColumn::make('permissions_count')
->badge()
->label(__('filament-shield::filament-shield.column.permissions'))
->counts('permissions')
->color('primary'),
TextColumn::make('updated_at')
->label(__('filament-shield::filament-shield.column.updated_at'))
->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;
}
}),
])
->filters([
//
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->paginationPageOptions([5, 10, 25, 50, 100])
->defaultPaginationPageOption(25)
->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',
__('filament-shield::filament-shield.column.name'),
__('filament-shield::filament-shield.column.guard_name'),
__('filament-shield::filament-shield.column.permissions'),
__('filament-shield::filament-shield.column.updated_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->name,
$record->guard_name,
$record->permissions_count ?? $record->permissions()->count(),
$record->updated_at?->format('Y-m-d H:i:s'),
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'roles-' . 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 = Role::with('permissions')->withCount('permissions')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('filament-shield::filament-shield.column.name'),
__('filament-shield::filament-shield.column.guard_name'),
__('filament-shield::filament-shield.column.permissions'),
__('filament-shield::filament-shield.column.updated_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->name,
$record->guard_name,
$record->permissions_count,
$record->updated_at?->format('Y-m-d H:i:s'),
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'roles-' . 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 = Role::with('permissions')->get();
return PdfService::download(
'exports.roles-pdf',
['records' => $records],
'roles-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListRoles::route('/'),
'create' => Pages\CreateRole::route('/create'),
'view' => Pages\ViewRole::route('/{record}'),
'edit' => Pages\EditRole::route('/{record}/edit'),
];
}
public static function toggleSelectAllViaEntities(Livewire $livewire, Set $set): void
{
/** @phpstan-ignore-next-line */
$entitiesStates = collect($livewire->form->getFlatComponents())
->filter(fn (mixed $component): bool => $component instanceof Component)
->reduce(function (mixed $counts, Component $component) {
if ($component instanceof CheckboxList) {
$counts[$component->getName()] = count(array_keys($component->getOptions())) === count(collect($component->getState())->values()->unique()->toArray());
}
return $counts;
}, collect())
->values();
if ($entitiesStates->containsStrict(false)) {
$set('select_all', false);
} else {
$set('select_all', true);
}
}
public static function toggleEntitiesViaSelectAll(Livewire $livewire, Set $set, bool $state): void
{
/** @phpstan-ignore-next-line */
$entitiesComponents = collect($livewire->form->getFlatComponents())
->filter(fn (mixed $component): bool => $component instanceof CheckboxList);
if ($state) {
$entitiesComponents->each(function (CheckboxList $component) use ($set): void {
$set($component->getName(), array_keys($component->getOptions()));
});
} else {
$entitiesComponents->each(fn (CheckboxList $component) => $component->state([]));
}
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use BezhanSalleh\FilamentShield\Resources\Roles\Pages\CreateRole as ShieldCreateRole;
class CreateRole extends ShieldCreateRole
{
protected static string $resource = RoleResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use BezhanSalleh\FilamentShield\Resources\Roles\Pages\EditRole as ShieldEditRole;
use Filament\Actions\DeleteAction;
class EditRole extends ShieldEditRole
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use BezhanSalleh\FilamentShield\Resources\Roles\Pages\ListRoles as ShieldListRoles;
class ListRoles extends ShieldListRoles
{
protected static string $resource = RoleResource::class;
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use BezhanSalleh\FilamentShield\Resources\Roles\Pages\ViewRole as ShieldViewRole;
class ViewRole extends ShieldViewRole
{
protected static string $resource = RoleResource::class;
}
@@ -0,0 +1,194 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\SurgeryAppointmentResource\Pages;
use App\Models\Patient;
use App\Models\SurgeryAppointment;
use App\Models\SurgeryCenter;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TimePicker;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Morilog\Jalali\Jalalian;
class SurgeryAppointmentResource extends Resource
{
protected static ?string $model = SurgeryAppointment::class;
protected static bool $isGloballySearchable = false;
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-calendar-days';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.patients');
}
public static function getNavigationSort(): ?int
{
return 3;
}
public static function getNavigationLabel(): string
{
return __('navigation.surgery_appointments.title');
}
public static function getModelLabel(): string
{
return __('navigation.surgery_appointments.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.surgery_appointments.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make(__('surgery_appointments.sections.info'))
->schema([
Select::make('patient_id')
->label(__('surgery_appointments.fields.patient'))
->options(fn () => Patient::all()->mapWithKeys(
fn ($p) => [$p->id => $p->full_name]
)->toArray())
->searchable()
->required(),
Select::make('surgery_center_id')
->label(__('surgery_appointments.fields.surgery_center'))
->options(fn () => SurgeryCenter::pluck('name', 'id')->toArray())
->searchable()
->required(),
DatePicker::make('surgery_date_date')
->label(__('surgery_appointments.fields.surgery_date'))
->jalali()
->minDate(today())
->required(),
TimePicker::make('surgery_date_time')
->label(__('surgery_appointments.fields.surgery_time'))
->native(false)
->seconds(false)
->minutesStep(15)
->default('09:00'),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('patient.first_name')
->label(__('surgery_appointments.fields.patient'))
->formatStateUsing(fn ($record) => $record->patient?->full_name ?? '-')
->searchable()
->sortable(),
TextColumn::make('surgeryCenter.name')
->label(__('surgery_appointments.fields.surgery_center'))
->searchable()
->sortable()
->placeholder('-'),
TextColumn::make('surgery_date')
->label(__('surgery_appointments.fields.surgery_date'))
->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;
}
})
->sortable(),
TextColumn::make('creator.name')
->label(__('surgery_appointments.fields.created_by'))
->placeholder('-'),
TextColumn::make('created_at')
->label(__('surgery_appointments.fields.created_at'))
->sortable(),
])
->defaultSort('surgery_date', 'desc')
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->toolbarActions([
DeleteBulkAction::make(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListSurgeryAppointments::route('/'),
'create' => Pages\CreateSurgeryAppointment::route('/create'),
'edit' => Pages\EditSurgeryAppointment::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\SurgeryAppointmentResource\Pages;
use App\Filament\Resources\SurgeryAppointmentResource;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Filament\Support\Enums\Width;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Morilog\Jalali\Jalalian;
class CreateSurgeryAppointment extends CreateRecord
{
protected static string $resource = SurgeryAppointmentResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function mutateFormDataBeforeCreate(array $data): array
{
$dateStr = $data['surgery_date_date'] ?? '';
$timeStr = $data['surgery_date_time'] ?? '09:00';
$data['surgery_date'] = \Carbon\Carbon::parse($dateStr . ' ' . $timeStr);
unset($data['surgery_date_date'], $data['surgery_date_time']);
return $data;
}
protected function afterCreate(): void
{
$record = $this->record;
$patient = $record->patient;
$surgeryDateTime = $record->getRawOriginal('surgery_date')
? \Carbon\Carbon::parse($record->getRawOriginal('surgery_date'))
: \Carbon\Carbon::parse($record->surgery_date);
$jalaliDate = Jalalian::fromCarbon($surgeryDateTime)->format('Y/m/d');
try {
$response = Http::timeout(30)
->withHeader('X-API-Key', \App\Models\OsurgInitial::val('sms_api_key', config('sms.api_key')))
->asJson()
->post(\App\Models\OsurgInitial::val('sms_api_url', config('sms.api_url')) . '/surgery-reminder', [
'phoneNumber' => $patient->hand_phone ?? '',
'patientName' => $patient->full_name,
'surgeryDate' => $jalaliDate,
'appointmentId' => $record->id,
'patientId' => $patient->id,
'surgeryDateFull' => $surgeryDateTime->toDateTimeString(),
]);
if (! ($response->json('success') ?? false)) {
Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.api_failed') . ': ' . ($response->json('message') ?? ''))
->warning()
->send();
return;
}
} catch (\Throwable $e) {
Log::warning('Surgery appointment API failed', [
'appointment_id' => $record->id,
'patient_id' => $patient->id,
'error' => $e->getMessage(),
]);
Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.api_failed') . ': ' . $e->getMessage())
->warning()
->send();
return;
}
Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.sms_sent'))
->success()
->send();
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\SurgeryAppointmentResource\Pages;
use App\Filament\Resources\SurgeryAppointmentResource;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Morilog\Jalali\Jalalian;
class EditSurgeryAppointment extends EditRecord
{
protected static string $resource = SurgeryAppointmentResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function mutateFormDataBeforeFill(array $data): array
{
if (! empty($data['surgery_date'])) {
$date = \Carbon\Carbon::parse($data['surgery_date']);
$data['surgery_date_date'] = $date->format('Y-m-d');
$data['surgery_date_time'] = $date->format('H:i');
}
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
$dateStr = $data['surgery_date_date'] ?? '';
$timeStr = $data['surgery_date_time'] ?? '09:00';
$data['surgery_date'] = \Carbon\Carbon::parse($dateStr . ' ' . $timeStr);
unset($data['surgery_date_date'], $data['surgery_date_time']);
return $data;
}
protected function beforeSave(): void
{
$data = $this->form->getState();
$dateStr = $data['surgery_date_date'] ?? '';
$timeStr = $data['surgery_date_time'] ?? '09:00';
$surgeryDateTime = \Carbon\Carbon::parse($dateStr . ' ' . $timeStr);
$jalaliDate = Jalalian::fromCarbon($surgeryDateTime)->format('Y/m/d');
$patient = $this->getRecord()->patient;
try {
$response = Http::timeout(30)
->withHeader('X-API-Key', \App\Models\OsurgInitial::val('sms_api_key', config('sms.api_key')))
->asJson()
->post(\App\Models\OsurgInitial::val('sms_api_url', config('sms.api_url')) . '/surgery-reminder', [
'phoneNumber' => $patient->hand_phone ?? '',
'patientName' => $patient->full_name,
'surgeryDate' => $jalaliDate,
'appointmentId' => $this->getRecord()->id,
'patientId' => $patient->id,
'surgeryDateFull' => $surgeryDateTime->toDateTimeString(),
]);
if (! ($response->json('success') ?? false)) {
Notification::make()
->title(__('patients.actions.api_failed'))
->body($response->json('message') ?? '')
->danger()
->send();
$this->halt();
}
} catch (\Throwable $e) {
Log::warning('Surgery appointment API failed', [
'patient_id' => $patient->id,
'error' => $e->getMessage(),
]);
Notification::make()
->title(__('patients.actions.api_failed'))
->body($e->getMessage())
->danger()
->send();
$this->halt();
}
}
protected function afterSave(): void
{
Notification::make()
->title(__('patients.actions.appointment_saved'))
->body(__('patients.actions.sms_sent'))
->success()
->send();
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\SurgeryAppointmentResource\Pages;
use App\Filament\Resources\SurgeryAppointmentResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListSurgeryAppointments extends ListRecords
{
protected static string $resource = SurgeryAppointmentResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,291 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\SurgeryCenterResource\Pages;
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\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class SurgeryCenterResource extends Resource
{
protected static ?string $model = SurgeryCenter::class;
protected static ?string $recordTitleAttribute = 'name';
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-building-office-2';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.clinic');
}
public static function getNavigationSort(): ?int
{
return 4;
}
public static function getNavigationLabel(): string
{
return __('navigation.surgery_centers.title');
}
public static function getModelLabel(): string
{
return __('navigation.surgery_centers.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.surgery_centers.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('name')
->label(__('surgery_centers.fields.name'))
->required()
->maxLength(255)
->columnSpanFull(),
TextInput::make('phone')
->label(__('surgery_centers.fields.phone'))
->maxLength(50),
TextInput::make('email')
->label(__('surgery_centers.fields.email'))
->email()
->maxLength(100),
TextInput::make('contact_person')
->label(__('surgery_centers.fields.contact_person'))
->maxLength(100)
->columnSpanFull(),
Textarea::make('address')
->label(__('surgery_centers.fields.address'))
->rows(2)
->columnSpanFull(),
Textarea::make('description')
->label(__('surgery_centers.fields.description'))
->rows(3)
->columnSpanFull(),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->label(__('surgery_centers.fields.name'))
->weight(FontWeight::Medium)
->searchable()
->sortable(),
TextColumn::make('phone')
->label(__('surgery_centers.fields.phone'))
->placeholder('-'),
TextColumn::make('email')
->label(__('surgery_centers.fields.email'))
->placeholder('-'),
TextColumn::make('contact_person')
->label(__('surgery_centers.fields.contact_person'))
->placeholder('-'),
TextColumn::make('address')
->label(__('surgery_centers.fields.address'))
->limit(40)
->placeholder('-'),
TextColumn::make('created_at')
->label(__('surgery_centers.fields.created_at'))
->sortable(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('surgery_centers.fields.name'),
__('surgery_centers.fields.phone'),
__('surgery_centers.fields.email'),
__('surgery_centers.fields.contact_person'),
__('surgery_centers.fields.address'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->name,
$record->phone,
$record->email,
$record->contact_person,
$record->address,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'surgery-centers-' . 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 = SurgeryCenter::orderBy('name')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('surgery_centers.fields.name'),
__('surgery_centers.fields.phone'),
__('surgery_centers.fields.email'),
__('surgery_centers.fields.contact_person'),
__('surgery_centers.fields.address'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->name,
$record->phone,
$record->email,
$record->contact_person,
$record->address,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'surgery-centers-' . 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 = SurgeryCenter::orderBy('name')->get();
return PdfService::download(
'exports.surgery-centers-pdf',
['records' => $records],
'surgery-centers-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListSurgeryCenters::route('/'),
'create' => Pages\CreateSurgeryCenter::route('/create'),
'edit' => Pages\EditSurgeryCenter::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\SurgeryCenterResource\Pages;
use App\Filament\Resources\SurgeryCenterResource;
use Filament\Resources\Pages\CreateRecord;
class CreateSurgeryCenter extends CreateRecord
{
protected static string $resource = SurgeryCenterResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\SurgeryCenterResource\Pages;
use App\Filament\Resources\SurgeryCenterResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditSurgeryCenter extends EditRecord
{
protected static string $resource = SurgeryCenterResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\SurgeryCenterResource\Pages;
use App\Filament\Resources\SurgeryCenterResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListSurgeryCenters extends ListRecords
{
protected static string $resource = SurgeryCenterResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,277 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\TreatmentResource\Pages;
use App\Models\Treatment;
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\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class TreatmentResource extends Resource
{
protected static ?string $model = Treatment::class;
protected static ?string $recordTitleAttribute = 'treatment_name';
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-clipboard-document-list';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.diseases');
}
public static function getNavigationSort(): ?int
{
return 2;
}
public static function getNavigationLabel(): string
{
return __('navigation.treatments.title');
}
public static function getModelLabel(): string
{
return __('navigation.treatments.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.treatments.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('treatment_type')
->label(__('treatments.fields.treatment_type'))
->maxLength(50),
TextInput::make('treatment_name')
->label(__('treatments.fields.treatment_name'))
->required()
->maxLength(50),
TextInput::make('treatment_cost')
->label(__('treatments.fields.treatment_cost'))
->numeric()
->minValue(0),
Textarea::make('descriptions')
->label(__('treatments.fields.descriptions'))
->rows(3)
->columnSpanFull(),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('treatment_name')
->label(__('treatments.fields.treatment_name'))
->weight(FontWeight::Medium)
->searchable()
->sortable(),
TextColumn::make('treatment_type')
->label(__('treatments.fields.treatment_type'))
->badge()
->color('primary')
->placeholder('-')
->sortable(),
TextColumn::make('treatment_cost')
->label(__('treatments.fields.treatment_cost'))
->numeric(thousandsSeparator: ',')
->placeholder('-')
->sortable(),
TextColumn::make('descriptions')
->label(__('treatments.fields.descriptions'))
->limit(40)
->placeholder('-'),
TextColumn::make('created_at')
->label(__('treatments.fields.created_at'))
->sortable(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('treatments.fields.treatment_name'),
__('treatments.fields.treatment_type'),
__('treatments.fields.treatment_cost'),
__('treatments.fields.descriptions'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->treatment_name,
$record->treatment_type,
$record->treatment_cost,
$record->descriptions,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'treatments-' . 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 = Treatment::orderBy('treatment_type')->orderBy('treatment_name')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('treatments.fields.treatment_name'),
__('treatments.fields.treatment_type'),
__('treatments.fields.treatment_cost'),
__('treatments.fields.descriptions'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->treatment_name,
$record->treatment_type,
$record->treatment_cost,
$record->descriptions,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'treatments-' . 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 = Treatment::orderBy('treatment_type')->orderBy('treatment_name')->get();
return PdfService::download(
'exports.treatments-pdf',
['records' => $records],
'treatments-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListTreatments::route('/'),
'create' => Pages\CreateTreatment::route('/create'),
'edit' => Pages\EditTreatment::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\TreatmentResource\Pages;
use App\Filament\Resources\TreatmentResource;
use Filament\Resources\Pages\CreateRecord;
class CreateTreatment extends CreateRecord
{
protected static string $resource = TreatmentResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\TreatmentResource\Pages;
use App\Filament\Resources\TreatmentResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditTreatment extends EditRecord
{
protected static string $resource = TreatmentResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\TreatmentResource\Pages;
use App\Filament\Resources\TreatmentResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListTreatments extends ListRecords
{
protected static string $resource = TreatmentResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
+279
View File
@@ -0,0 +1,279 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
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 Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Hash;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static ?string $recordTitleAttribute = 'name';
public static function getGloballySearchableAttributes(): array
{
return ['name', 'username'];
}
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-users';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.clinic');
}
public static function getNavigationSort(): ?int
{
return 1;
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make()
->schema([
TextInput::make('name')
->label(__('users.fields.name'))
->required()
->maxLength(255),
TextInput::make('username')
->label(__('users.fields.username'))
->required()
->maxLength(255)
->unique(table: User::class, column: 'username', ignoreRecord: true),
TextInput::make('password')
->label(__('users.fields.password'))
->password()
->required(fn (string $operation): bool => $operation === 'create')
->dehydrateStateUsing(fn (string $state): string => Hash::make($state))
->dehydrated(fn (?string $state): bool => filled($state))
->maxLength(255),
Select::make('roles')
->label(__('users.fields.roles'))
->relationship('roles', 'name')
->multiple()
->preload(),
])
->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 table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->label(__('users.fields.name'))
->searchable()
->sortable(),
TextColumn::make('username')
->label(__('users.fields.username'))
->searchable()
->sortable(),
TextColumn::make('roles.name')
->label(__('users.fields.roles'))
->badge()
->separator(','),
TextColumn::make('created_at')
->label(__('users.fields.created_at'))
->sortable(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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',
__('users.fields.name'),
__('users.fields.username'),
__('users.fields.roles'),
__('users.fields.created_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->name,
$record->username,
$record->roles->pluck('name')->join(', '),
$record->created_at,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'users-' . 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 = User::with('roles')->get();
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('users.fields.name'),
__('users.fields.username'),
__('users.fields.roles'),
__('users.fields.created_at'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->name,
$record->username,
$record->roles->pluck('name')->join(', '),
$record->created_at,
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'users-' . 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 = User::with('roles')->get();
return PdfService::download(
'exports.users-pdf',
['records' => $records],
'users-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListUsers::route('/'),
'create' => Pages\CreateUser::route('/create'),
'edit' => Pages\EditUser::route('/{record}/edit'),
];
}
public static function getNavigationLabel(): string
{
return __('navigation.users.title');
}
public static function getModelLabel(): string
{
return __('navigation.users.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.users.title');
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Resources\Pages\CreateRecord;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditUser extends EditRecord
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListUsers extends ListRecords
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}
+406
View File
@@ -0,0 +1,406 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\VisitResource\Pages;
use App\Models\Doctor;
use App\Models\Patient;
use App\Models\PaymentType;
use App\Models\Treatment;
use App\Models\Visit;
use App\Services\PdfService;
use Morilog\Jalali\Jalalian;
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\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\TimePicker;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
class VisitResource extends Resource
{
protected static ?string $model = Visit::class;
protected static ?string $recordTitleAttribute = 'visit_date';
public static function getGloballySearchableAttributes(): array
{
return ['visit_date', 'patientRecord.first_name', 'patientRecord.last_name', 'treatment_description'];
}
public static function getNavigationIcon(): \BackedEnum|string|null
{
return 'heroicon-o-calendar';
}
public static function getNavigationGroup(): ?string
{
return __('navigation.groups.patients');
}
public static function getNavigationSort(): ?int
{
return 3;
}
public static function getNavigationLabel(): string
{
return __('navigation.visits.title');
}
public static function getModelLabel(): string
{
return __('navigation.visits.singular');
}
public static function getPluralModelLabel(): string
{
return __('navigation.visits.title');
}
public static function form(Schema $schema): Schema
{
return $schema
->components([
Grid::make()
->schema([
Section::make(__('visits.sections.visit_info'))
->schema([
Select::make('patient')
->label(__('visits.fields.patient'))
->options(fn () => Patient::all()->mapWithKeys(
fn ($p) => [$p->id => $p->full_name . ($p->icno ? ' - ' . $p->icno : '')]
)->toArray())
->searchable()
->nullable()
->columnSpan(2),
DatePicker::make('visit_date')
->label(__('visits.fields.visit_date'))
->jalali()
->default(now())
->required(),
TimePicker::make('visit_time')
->label(__('visits.fields.visit_time'))
->nullable()
->native(false)
->seconds(false)
->minutesStep(15),
Select::make('doctor')
->label(__('visits.fields.doctor'))
->options(fn () => Doctor::all()->mapWithKeys(
fn ($d) => [$d->id => $d->full_name]
)->toArray())
->searchable()
->nullable(),
Select::make('treatment')
->label(__('visits.fields.treatment'))
->options(fn () => Treatment::all()->mapWithKeys(
fn ($t) => [$t->id => ($t->treatment_name ?: $t->treatment_type)]
)->toArray())
->searchable()
->nullable()
->live()
->afterStateUpdated(function ($state, callable $set) {
if ($state) {
$treatment = Treatment::find($state);
if ($treatment && $treatment->treatment_cost > 0) {
$set('treatment_cost', $treatment->treatment_cost);
}
}
}),
])
->columns(2)
->columnSpanFull(),
Section::make(__('visits.sections.financial_info'))
->schema([
TextInput::make('treatment_cost')
->label(__('visits.fields.treatment_cost'))
->numeric()
->nullable()
->suffix(__('visits.fields.currency')),
TextInput::make('paid_amount')
->label(__('visits.fields.paid_amount'))
->numeric()
->nullable()
->suffix(__('visits.fields.currency')),
Select::make('payment_type')
->label(__('visits.fields.payment_type'))
->options(fn () => PaymentType::all()->mapWithKeys(
fn ($p) => [$p->id => $p->payment_type]
)->toArray())
->searchable()
->nullable(),
])
->columns(3)
->columnSpanFull(),
Section::make(__('visits.sections.treatment_details'))
->schema([
Textarea::make('treatment_description')
->label(__('visits.fields.treatment_description'))
->rows(4)
->columnSpanFull(),
])
->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('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 table(Table $table): Table
{
return $table
->modifyQueryUsing(fn ($query) => $query->with(['patientRecord', 'doctorRecord', 'treatmentRecord', 'paymentTypeRecord']))
->deferLoading()
->columns([
TextColumn::make('visit_date')
->label(__('visits.fields.visit_date'))
->sortable()
->searchable()
->formatStateUsing(function ($state) {
if (! $state) {
return '-';
}
try {
$date = \Carbon\Carbon::parse($state);
return Jalalian::fromCarbon($date)->format('Y/m/d');
} catch (\Exception $e) {
return $state;
}
})
->placeholder('-'),
TextColumn::make('patientRecord.first_name')
->label(__('visits.fields.patient'))
->formatStateUsing(fn ($record) => $record->patientRecord?->full_name ?? '-')
->searchable()
->sortable(),
TextColumn::make('doctorRecord.first_name')
->label(__('visits.fields.doctor'))
->formatStateUsing(fn ($record) => $record->doctorRecord?->full_name ?? '-')
->sortable()
->placeholder('-'),
TextColumn::make('treatmentRecord.treatment_name')
->label(__('visits.fields.treatment'))
->formatStateUsing(fn ($record) => $record->treatmentRecord
? ($record->treatmentRecord->treatment_name ?: $record->treatmentRecord->treatment_type)
: '-')
->sortable()
->placeholder('-'),
TextColumn::make('treatment_cost')
->label(__('visits.fields.treatment_cost'))
->formatStateUsing(fn ($state) => $state !== null ? number_format((int) $state) : '-')
->sortable()
->placeholder('-'),
TextColumn::make('paid_amount')
->label(__('visits.fields.paid_amount'))
->formatStateUsing(fn ($state) => $state !== null ? number_format((int) $state) : '-')
->sortable()
->placeholder('-'),
TextColumn::make('remained_amount')
->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')
->placeholder('-'),
TextColumn::make('paymentTypeRecord.payment_type')
->label(__('visits.fields.payment_type'))
->placeholder('-'),
TextColumn::make('created_at')
->label(__('visits.fields.created_at'))
->sortable()
->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;
}
})
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
SelectFilter::make('doctor')
->label(__('visits.fields.doctor'))
->options(fn () => Doctor::all()->mapWithKeys(
fn ($d) => [$d->id => $d->full_name]
)->toArray()),
SelectFilter::make('treatment')
->label(__('visits.fields.treatment'))
->options(fn () => Treatment::all()->mapWithKeys(
fn ($t) => [$t->id => ($t->treatment_name ?: $t->treatment_type)]
)->toArray()),
SelectFilter::make('payment_type')
->label(__('visits.fields.payment_type'))
->options(fn () => PaymentType::all()->mapWithKeys(
fn ($p) => [$p->id => $p->payment_type]
)->toArray()),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
])
->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) {
return self::exportToExcel($records);
}),
]),
ActionGroup::make([
Action::make('export_excel')
->label(__('table.export_excel'))
->color('success')
->icon('heroicon-o-table-cells')
->action(function () {
$records = Visit::with(['patientRecord', 'doctorRecord', 'treatmentRecord', 'paymentTypeRecord'])
->orderBy('created_at', 'desc')
->get();
return self::exportToExcel($records);
}),
Action::make('export_pdf')
->label(__('table.export_pdf'))
->color('danger')
->icon('heroicon-o-document-arrow-down')
->action(function () {
$records = Visit::with(['patientRecord', 'doctorRecord', 'treatmentRecord', 'paymentTypeRecord'])
->orderBy('created_at', 'desc')
->get();
return PdfService::download(
'exports.visits-pdf',
['records' => $records],
'visits-' . now()->format('Y-m-d') . '.pdf',
);
}),
])
->label(__('table.export'))
->color('orange')
->button(),
]);
}
private static function exportToExcel(Collection $records): mixed
{
$tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
$writer = new Writer();
$writer->openToFile($tempPath);
$writer->addRow(Row::fromValues([
'ID',
__('visits.fields.visit_date'),
__('visits.fields.patient'),
__('visits.fields.doctor'),
__('visits.fields.treatment'),
__('visits.fields.treatment_cost'),
__('visits.fields.paid_amount'),
__('visits.fields.remained_amount'),
__('visits.fields.payment_type'),
__('visits.fields.treatment_description'),
]));
foreach ($records as $record) {
$writer->addRow(Row::fromValues([
$record->id,
$record->visit_date ?? '',
$record->patientRecord?->full_name ?? '',
$record->doctorRecord?->full_name ?? '',
$record->treatmentRecord
? ($record->treatmentRecord->treatment_name ?: $record->treatmentRecord->treatment_type)
: '',
$record->treatment_cost ?? 0,
$record->paid_amount ?? 0,
$record->remained_amount,
$record->paymentTypeRecord?->payment_type ?? '',
$record->treatment_description ?? '',
]));
}
$writer->close();
return response()->streamDownload(function () use ($tempPath) {
readfile($tempPath);
@unlink($tempPath);
}, 'visits-' . now()->format('Y-m-d') . '.xlsx', [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}
public static function getPages(): array
{
return [
'index' => Pages\ListVisits::route('/'),
'create' => Pages\CreateVisit::route('/create'),
'edit' => Pages\EditVisit::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\VisitResource\Pages;
use App\Filament\Resources\VisitResource;
use Filament\Resources\Pages\CreateRecord;
use Filament\Support\Enums\Width;
class CreateVisit extends CreateRecord
{
protected static string $resource = VisitResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getFormActions(): array
{
return [];
}
protected function getRedirectUrl(): string
{
return static::getResource()::getUrl('index');
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\VisitResource\Pages;
use App\Filament\Resources\VisitResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
class EditVisit extends EditRecord
{
protected static string $resource = VisitResource::class;
protected Width|string|null $maxContentWidth = Width::SevenExtraLarge;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
protected function getFormActions(): array
{
return [];
}
protected function getRedirectUrl(): string
{
return static::getResource()::getUrl('index');
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\VisitResource\Pages;
use App\Filament\Resources\VisitResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListVisits extends ListRecords
{
protected static string $resource = VisitResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->icon('heroicon-o-plus'),
];
}
}