99 lines
3.0 KiB
PHP
99 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace Database\Seeders;
|
|
|
|
use App\Models\Articolo;
|
|
use Illuminate\Database\Seeder;
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
|
|
class ArticoloSeeder extends Seeder
|
|
{
|
|
/**
|
|
* Run the database seeds.
|
|
*/
|
|
public function run(): void
|
|
{
|
|
$filePath = base_path('STRUTTURA DATABASE.xlsx');
|
|
|
|
if (!file_exists($filePath)) {
|
|
$this->command->error('File Excel non trovato: ' . $filePath);
|
|
return;
|
|
}
|
|
|
|
$this->importFromExcel($filePath);
|
|
}
|
|
|
|
/**
|
|
* Import articoli from Excel file.
|
|
*/
|
|
public function importFromExcel(string $filePath, bool $cleanImport = false): array
|
|
{
|
|
$spreadsheet = IOFactory::load($filePath);
|
|
$worksheet = $spreadsheet->getActiveSheet();
|
|
$rows = $worksheet->toArray();
|
|
|
|
$imported = 0;
|
|
$updated = 0;
|
|
$errors = [];
|
|
|
|
// If clean import, delete all existing records
|
|
if ($cleanImport) {
|
|
Articolo::truncate();
|
|
}
|
|
|
|
// Skip header rows (first 2 rows)
|
|
foreach (array_slice($rows, 2) as $index => $row) {
|
|
// Skip empty rows
|
|
if (empty($row[0])) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
$exists = Articolo::where('codice_articolo', $row[0])->exists();
|
|
|
|
Articolo::updateOrCreate(
|
|
['codice_articolo' => $row[0]],
|
|
[
|
|
'ciclo' => $row[1] ?? null,
|
|
'diametro' => $row[2] ?? null,
|
|
'descrizione' => $row[3] ?? null,
|
|
'posizione' => $row[4] ?? null,
|
|
'quantita' => is_numeric($row[5]) ? (int) $row[5] : 0,
|
|
'tipo_lavorazione' => $row[6] ?? null,
|
|
'materiale_lavorare' => $row[7] ?? null,
|
|
'maximum_thickness' => $row[8] ?? null,
|
|
'speed_rpm' => is_numeric($row[9]) ? (int) $row[9] : null,
|
|
'feed' => is_numeric($row[10]) ? (float) $row[10] : null,
|
|
'max_thrust_a' => $row[11] ?? null,
|
|
'min_torque_a' => $row[12] ?? null,
|
|
'quantita_fori' => is_numeric($row[13]) ? (int) $row[13] : null,
|
|
]
|
|
);
|
|
|
|
if ($exists && !$cleanImport) {
|
|
$updated++;
|
|
} else {
|
|
$imported++;
|
|
}
|
|
|
|
if (isset($this->command)) {
|
|
$this->command->info('Importato articolo: ' . $row[0]);
|
|
}
|
|
} catch (\Exception $e) {
|
|
$errors[] = "Riga " . ($index + 3) . ": " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
if (isset($this->command)) {
|
|
$this->command->info('Import completato! Totale articoli: ' . Articolo::count());
|
|
}
|
|
|
|
return [
|
|
'imported' => $imported,
|
|
'updated' => $updated,
|
|
'errors' => $errors,
|
|
'total' => Articolo::count(),
|
|
];
|
|
}
|
|
}
|