Skip to content

Commit

Permalink
validate excel data
Browse files Browse the repository at this point in the history
  • Loading branch information
alexPopaCode4 committed Apr 10, 2024
1 parent adf39e0 commit 30f0334
Show file tree
Hide file tree
Showing 6 changed files with 188 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

declare(strict_types=1);

namespace App\Filament\Resources\VolunteerResource\Actions;

use App\Models\Volunteer;
use pxlrbt\FilamentExcel\Actions\Pages\ExportAction;
use pxlrbt\FilamentExcel\Columns\Column;
use pxlrbt\FilamentExcel\Exports\ExcelExport;

class ExportVolunteersExample extends ExportAction
{
protected function setUp(): void
{
parent::setUp();
$this->label(__('volunteer.labels.download_example'));

$this->exports([
ExcelExport::make()
->withColumns([
Column::make('first_name'),
Column::make('last_name'),
Column::make('email'),
Column::make('phone'),
Column::make('cnp'),
Column::make('rol'),
Column::make('specialisations'),
Column::make('has_first_aid_accreditation'),
Column::make('county')
->formatStateUsing(fn ($state) => $state->name),
Column::make('city')
->formatStateUsing(fn ($state) => $state->name),
]),
]);
}

public function handleExport(array $data)
{
$examples = Volunteer::factory()
->count(10)
->make()
->each(function ($item) {
$item->load('county');
$item->load('city');

return $item;
});

$examplesArray = [];
foreach ($examples as $example) {
$examplesArray[] = $example;
}

$exportable = $this->getSelectedExport($data);
$livewire = $this->getLivewire();

return app()->call([$exportable, 'hydrate'], [
'livewire' => $this->getLivewire(),
'records' => $examples,
'formData' => data_get($data, $exportable->getName()),
])->export();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@
use App\Models\Organisation;
use App\Models\Volunteer;
use Filament\Forms\Components\Select;
use Illuminate\Validation\Rule;
use Konnco\FilamentImport\Actions\ImportAction;
use Konnco\FilamentImport\Actions\ImportField;

class ImportVolunteersAction extends ImportAction
{
protected function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
parent::setUp();

$this->label(__('volunteer.field.import'));
$this->label(__('volunteer.labels.import'));
$this->successNotificationTitle(__('volunteer.field.success_import'));
$this->visible(fn () => auth()->user()->isPlatformAdmin() || auth()->user()->isOrgAdmin());
$this->handleBlankRows(true);
$this->fields([
Select::make('organisation_id')
->options(function () {
Expand Down Expand Up @@ -66,22 +68,65 @@ protected function setUp(): void
]);

$this->handleRecordCreation(function (array $data) {
if (! isset($data['first_name']) ||
! isset($data['last_name']) ||
! isset($data['email']) ||
! isset($data['role']) ||
! isset($data['specializations'])) {
$validator = \Validator::make($data, [
'organisation_id' => [
'required',
Rule::in(Organisation::all()->pluck('id')),
],
'first_name' => [
'required',
'max:255',
'string',
],
'last_name' => [
'required',
'max:255',
'string',
],
'email' => [
'required',
'max:255',
'email',
],
'phone' => [
'numeric',
'min:10',
],
'role' => [
'required',
Rule::in(VolunteerRole::options()),
],
'specializations' => ['required'],
]);

$data = $validator->getData();
$messages = $validator->getMessageBag();
if ($messages->messages()) {
$this->setFailureMsg($messages->messages());

return new Volunteer();
}

$roles = VolunteerRole::options();
$role = array_search($data['role'], $roles);

$specializations = explode(',', $data['specializations']);
$allSpecializations = VolunteerSpecialization::options();
$newSpecializations = [];
foreach ($specializations as $specialization) {
$newSpecializations[] = array_search(trim($specialization), $allSpecializations);
$specializationFromEnum = array_search(trim($specialization), $allSpecializations);
if (! $specializationFromEnum) {
$this->setFailureMsg([
__(
'validation.in_array',
['attribute' => __('volunteer.field.specializations') . ' (' . $specialization . ')',
'other' => implode(', ', $allSpecializations),
]
),
]);

return new Volunteer();
}
$newSpecializations[] = $specializationFromEnum;
}

$firstAID = false;
Expand All @@ -96,32 +141,70 @@ protected function setUp(): void
'phone' => $data['phone'] ?? null,
'cnp' => $data['cnp'] ?? null,
'role' => $role,
'specializations' => array_filter($newSpecializations),
'specializations' => $newSpecializations,
'has_first_aid_accreditation' => $firstAID,
];

if (isset($data['county'])) {
$county = County::query()
->where('name', 'like', $data['county'])
->where('name', 'like', trim($data['county']))
->first();

if ($county) {
$fields['county_id'] = $county->id;

if ($data['city']) {
$city = City::query()
->search($data['city'])
->where('county_id', $county->id)
->first();

if ($city) {
$fields['city_id'] = $city->id;
}
if (! $county) {
$this->setFailureMsg([
__(
'validation.in_array',
[
'attribute' => __('general.county') . ' (' . $data['county'] . ')',
'other' => County::all()
->map(fn ($item) => $item->name)
->implode(', '),
]
),
]);

return new Volunteer();
}
$fields['county_id'] = $county->id;

if (isset($data['city'])) {
$city = City::query()
->search(trim($data['city']))
->where('county_id', $county->id)
->first();

if (! $city) {
$this->setFailureMsg([
__(
'validation.in_array',
[
'attribute' => __('general.city') . ' (' . $data['city'] . ')',
'other' => __(
'general.localities_from_county',
['county' => $data['county']]
),
]
),
]);

return new Volunteer();
}
$fields['city_id'] = $city->id;
}
}

return Volunteer::create($fields);
});
}

public function setFailureMsg(array $messages)
{
foreach ($messages as &$msg) {
$msg = \is_array($msg) ? implode(' ', $msg) : $msg;
}
$msgString = implode(' ', $messages);
$msgString = substr($msgString, 0, 100);
$this->failureNotificationTitle($msgString);
$this->failure();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Filament\Resources\VolunteerResource\Pages;

use App\Filament\Resources\VolunteerResource;
use App\Filament\Resources\VolunteerResource\Actions\ExportVolunteersExample;
use App\Filament\Resources\VolunteerResource\Actions\ImportVolunteersAction;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;
Expand All @@ -19,6 +20,7 @@ protected function getActions(): array
return [
Actions\CreateAction::make(),
ImportVolunteersAction::make(),
// ExportVolunteersExample::make(),
];
}

Expand Down
1 change: 1 addition & 0 deletions lang/ro/general.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
return [
'county' => 'Județ',
'city' => 'Localitate',
'localities_from_county' => 'Localitatile din județul :county',
'created_at' => 'Inregistrat la data de',
'updated_at' => 'Actualizat la data de',
'help' => [
Expand Down
4 changes: 4 additions & 0 deletions lang/ro/volunteer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@
'has_first_aid_accreditation' => 'Acreditare prim ajutor',
'updated_at' => 'Ultima actualizare',
'organisation' => 'Organizație',
],

'labels' => [
'import' => 'Importa voluntari',
'download_example' => 'Descarca exemplu de import',
],

'role' => [
Expand Down
11 changes: 11 additions & 0 deletions lang/vendor/filament-import/ro/actions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

return [
'import' => 'Import',
'skip_header' => 'Omite prima linie',
'match_to_column' => 'Mapeaza coloanele',
// 'import_failed' => 'Import failed, please check your import file and try again',
// 'import_failed_title' => 'Import Failed',
// 'import_succeeded' => 'Import of :count row(s) succeeded, :skipped skipped row(s)',
// 'import_succeeded_title' => 'Import Succeeded',
];

0 comments on commit 30f0334

Please sign in to comment.