ifnex/04_Laravel/app/Filament/Pages/ImportRatesPage.php
2026-10-03 07:05:27 +03:30

96 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Filament\Pages;
use App\Exports\ShippingRatesTemplateExport;
use App\Imports\ShippingRatesImport;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Maatwebsite\Excel\Facades\Excel;
class ImportRatesPage extends Page implements HasForms
{
use InteractsWithForms;
protected static ?string $navigationIcon = 'heroicon-o-arrow-up-on-square';
protected static ?string $navigationLabel = 'ایمپورت زون ها';
protected static ?int $navigationSort = 8;
protected static string $view = 'filament.pages.import-rates';
public ?array $formData = [];
public function mount(): void
{
$this->form->fill();
}
public function form(Form $form): Form
{
return $form
->schema([
FileUpload::make('file')
->label('فایل اکسل نرخ‌ها')
->acceptedFileTypes([
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
])
->maxSize(5120)
->required()
->disk('local')
->directory('imports'),
])
->statePath('formData');
}
public function downloadTemplate(): void
{
(new ShippingRatesTemplateExport)->download('IFNEX_Rate_Template.xlsx');
}
public function import(): void
{
$data = $this->form->getState();
if (empty($data['file'])) {
Notification::make()
->title('خطا')
->body('لطفاً فایل اکسل را انتخاب کنید.')
->danger()
->send();
return;
}
$filePath = storage_path('app/' . $data['file']);
if (!file_exists($filePath)) {
Notification::make()
->title('خطا')
->body('فایل پیدا نشد.')
->danger()
->send();
return;
}
try {
Excel::import(new ShippingRatesImport, $filePath);
Notification::make()
->title('موفق')
->body('نرخ‌ها با موفقیت ایمپورت شدند.')
->success()
->send();
$this->form->fill();
} catch (\Exception $e) {
Notification::make()
->title('خطا در ایمپورت')
->body($e->getMessage())
->danger()
->send();
}
}
}