98 lines
2.9 KiB
PHP
98 lines
2.9 KiB
PHP
<?php
|
|
|
|
use Illuminate\Database\Seeder;
|
|
use League\Csv\Reader;
|
|
use App\Proveedor;
|
|
|
|
class CanastaSeeder extends Seeder
|
|
{
|
|
const FILA_HEADER = "Tipo";
|
|
const ULTIMA_FILA = "TOTAL";
|
|
|
|
/**
|
|
* Run the database seeds.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function run()
|
|
{
|
|
$csv = Reader::createFromPath(resource_path('csv/productos.csv'), 'r');
|
|
$csv->setDelimiter("|");
|
|
$iHeader = $this->obtenerIndiceDeHeader($csv);
|
|
$csv->setHeaderOffset($iHeader);
|
|
$registros = $csv->getRecords();
|
|
|
|
$toInsert = [];
|
|
$categoria = '';
|
|
foreach($registros as $i => $registro){
|
|
//filas que están arriba del header
|
|
if ($i <= $iHeader){
|
|
continue;
|
|
}
|
|
|
|
//finalizar
|
|
if ($registro[$this::FILA_HEADER] == $this::ULTIMA_FILA){
|
|
break;
|
|
}
|
|
|
|
//filas que no tienen tipo
|
|
if (!Arr::has($registro,$this::FILA_HEADER)|| trim($registro[$this::FILA_HEADER]) == ''){
|
|
var_dump("no hay tipo en la fila " . $i);
|
|
continue;
|
|
}
|
|
|
|
//saltear bono de transporte
|
|
if ($registro[$this::FILA_HEADER] == "T"){
|
|
continue;
|
|
}
|
|
|
|
//obtener categoria
|
|
if ($registro['Producto'] == '') {
|
|
//es la pregunta de la copa?
|
|
if (Str::contains($registro[$this::FILA_HEADER],"¿")) { continue; }
|
|
$categoria = $registro[$this::FILA_HEADER];
|
|
continue;
|
|
}
|
|
|
|
//completar producto
|
|
$toInsert[] = [
|
|
'fila' => $i,
|
|
'categoria' => $categoria,
|
|
'nombre' => trim(str_replace('*', ' ',$registro['Producto'])),
|
|
'precio' => $registro['Precio'],
|
|
'proveedor_id' => $this->obtenerProveedor($registro['Producto']),
|
|
'bono' => $registro[$this::FILA_HEADER] == "B"
|
|
];
|
|
}
|
|
|
|
foreach (array_chunk($toInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
|
|
{
|
|
DB::table('productos')->insert($chunk);
|
|
}
|
|
}
|
|
|
|
private function obtenerIndiceDeHeader($csv){
|
|
$registros = $csv->getRecords();
|
|
$iheader = 0;
|
|
foreach ($registros as $i => $registro){
|
|
if (strtolower($registro[0]) == strtolower($this::FILA_HEADER)) {
|
|
$iheader = $i;
|
|
break;
|
|
}
|
|
}
|
|
return $iheader;
|
|
}
|
|
|
|
private function obtenerProveedor($nombre) {
|
|
$result = null;
|
|
if (Str::contains($nombre,"*")){
|
|
$result = Proveedor::firstOrCreate([
|
|
'nombre' => 'Proveedor de economía solidaria',
|
|
'economia_solidaria' => 1,
|
|
'nacional' => 1
|
|
])->id;
|
|
}
|
|
return $result;
|
|
}
|
|
}
|