Skip to content

Commit

Permalink
indicazione sulle colonne attese per l'importazione csv. ref #250
Browse files Browse the repository at this point in the history
  • Loading branch information
madbob committed Jan 27, 2024
1 parent c2b2b38 commit 54b7abb
Show file tree
Hide file tree
Showing 7 changed files with 117 additions and 68 deletions.
49 changes: 35 additions & 14 deletions code/app/Importers/CSV/CSVImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,34 @@

abstract class CSVImporter
{
public function extraInformations()
{
return null;
}

public static function getImporter($type)
{
$ret = null;

switch($type) {
case 'products':
return new Products();
$ret = new Products();
break;
case 'users':
return new Users();
$ret = new Users();
break;
case 'movements':
return new Movements();
$ret = new Movements();
break;
case 'deliveries':
return new Deliveries();
$ret = new Deliveries();
break;
default:
Log::error('Unexpected type for CSV import: ' . $type);
break;
}

Log::error('Unexpected type for CSV import: ' . $type);
return null;
return $ret;
}

private function guessCsvFileSeparator($path)
Expand Down Expand Up @@ -108,20 +121,28 @@ protected function getColumnsIndex($columns, $search)
return $ret;
}

protected function initRead($request)
private function mandatoryFields()
{
$path = $request->input('path');
$columns = $request->input('column');
$ret = [];

$testable = [];
foreach($this->fields() as $key => $meta) {
$mandatory = $meta->mandatory ?? false;
if ($mandatory) {
$testable[] = $key;
$ret[] = $key;
}
}

return $ret;
}

protected function initRead($request)
{
$path = $request->input('path');
$columns = $request->input('column');

$testable = $this->mandatoryFields();
$tested = $this->getColumnsIndex($columns, $testable);

foreach($tested as $t) {
if ($t == -1) {
throw new MissingFieldException(1);
Expand All @@ -139,8 +160,8 @@ protected function mapNewElements($value, &$cached, $createNew)
{
if (Str::startsWith($value, 'new:')) {
$name = Str::after($value, 'new:');
if (!empty($name)) {
if (!isset($cached[$name])) {
if (empty($name) == false) {
if (isset($cached[$name]) == false) {
$obj = $createNew($name);
$cached[$name] = $obj->id;
}
Expand All @@ -160,7 +181,7 @@ public function finalTemplate()
return 'import.csvimportfinal';
}

protected abstract function fields();
public abstract function fields();
public abstract function testAccess($request);
public abstract function guess($request);
public abstract function select($request);
Expand Down
17 changes: 7 additions & 10 deletions code/app/Importers/CSV/Deliveries.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

class Deliveries extends CSVImporter
{
protected function fields()
public function fields()
{
$ret = [
'username' => (object) [
Expand All @@ -31,6 +31,11 @@ protected function fields()
return $ret;
}

public function extraInformations()
{
return _i('Da qui puoi reimportare un CSV generato dalla funzione "Tabella Complessiva Prodotti" dell\'ordine, dopo averlo manualmente elaborato con le quantità consegnate per ogni utente.');
}

public function testAccess($request)
{
$user = $request->user();
Expand Down Expand Up @@ -122,15 +127,11 @@ public function select($request)
];

$target_user = null;
$skip_row = false;

foreach ($columns as $index => $field) {
if ($field == 'username') {
$username = trim($line[$index]);
$target_user = User::where('username', $username)->first();
if (is_null($target_user)) {
$skip_row = true;
}
}
elseif ($index >= $first_product_index) {
if (isset($mapped_products[$index])) {
Expand All @@ -157,10 +158,6 @@ public function select($request)
}
}
}

if ($skip_row == true) {
break;
}
}

if ($target_user) {
Expand Down Expand Up @@ -203,7 +200,6 @@ public function run($request)

$data = json_decode($request->input('data', '[]'), true);
$users = $request->input('user', []);
$action = $request->input('action', 'save');

$order_id = $request->input('order_id');
$target_order = Order::findOrFail($order_id);
Expand All @@ -226,6 +222,7 @@ public function run($request)

DB::commit();

$action = $request->input('action', 'save');
if ($action == 'close') {
app()->make('FastBookingsService')->fastShipping($user, $target_order->aggregate, null);
}
Expand Down
75 changes: 42 additions & 33 deletions code/app/Importers/CSV/Movements.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

class Movements extends CSVImporter
{
protected function fields()
public function fields()
{
$ret = [
'date' => (object) [
Expand Down Expand Up @@ -190,6 +190,40 @@ public function formatSelect($parameters)
return view('import.csvmovementsselect', $parameters);
}

private function assignPeers($m, $senders, $targets, $index)
{
$t = MovementType::find($m->type);

foreach(['sender', 'target'] as $f) {
$id_field = $f . '_id';
$type_field = $f . '_type';

switch($t->$type_field) {
case 'App\User':
if ($senders[$index] !== '0') {
$m->$id_field = $senders[$index];
$m->$type_field = 'App\User';
}
break;

case 'App\Supplier':
if ($targets[$index] !== '0') {
$m->$id_field = $targets[$index];
$m->$type_field = 'App\Supplier';
}
break;

case 'App\Gas':
$current_gas = request()->user()->gas;
$m->$id_field = $current_gas->id;
$m->$type_field = 'App\Gas';
break;
}
}

return $m;
}

public function run($request)
{
$imports = $request->input('import', []);
Expand All @@ -204,7 +238,6 @@ public function run($request)

$errors = [];
$movements = [];
$current_gas = $request->user()->gas;

DB::beginTransaction();

Expand All @@ -219,39 +252,15 @@ public function run($request)
$m->method = $methods[$index];
$m->currency_id = $currencies[$index];
$m->notes = $notes[$index];

$t = MovementType::find($m->type);

$fields = ['sender', 'target'];

foreach($fields as $f) {
$id_field = $f . '_id';
$type_field = $f . '_type';

switch($t->$type_field) {
case 'App\User':
if ($senders[$index] !== '0') {
$m->$id_field = $senders[$index];
$m->$type_field = 'App\User';
}
break;

case 'App\Supplier':
if ($targets[$index] !== '0') {
$m->$id_field = $targets[$index];
$m->$type_field = 'App\Supplier';
}
break;

case 'App\Gas':
$m->$id_field = $current_gas->id;
$m->$type_field = 'App\Gas';
break;
}
}

$m = $this->assignPeers($m, $senders, $targets, $index);
$m->save();

/*
Ricordarsi sempre che la funzione di salvataggio dei
Movements non necessariamente salva per davvero il
movimento, intervenendo in questa fase le callback di
controllo· Qui è lecito fare un controllo
*/
if ($m->exists) {
$movements[] = $m;
}
Expand Down
2 changes: 1 addition & 1 deletion code/app/Importers/CSV/Products.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

class Products extends CSVImporter
{
protected function fields()
public function fields()
{
return [
'name' => (object) [
Expand Down
2 changes: 1 addition & 1 deletion code/app/Importers/CSV/Users.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private function otherFields(&$ret)
];
}

protected function fields()
public function fields()
{
$ret = [];
$this->essentialFields($ret);
Expand Down
1 change: 0 additions & 1 deletion code/resources/views/booking/list.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
@include('commons.importcsv', [
'modal_id' => 'importCSVdeliveries',
'import_target' => 'deliveries',
'explain_extras' => _i('Da qui puoi reimportare un CSV generato dalla funzione "Tabella Complessiva Prodotti" dell\'ordine, dopo averlo manualmente elaborato con le quantità consegnate per ogni utente.'),
'modal_extras' => [
'aggregate_id' => $aggregate->id,
],
Expand Down
39 changes: 31 additions & 8 deletions code/resources/views/commons/importcsv.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
$modal_extras = [];
}
if (!isset($explain_extras)) {
$explain_extras = '';
}
$importer = \App\Importers\CSV\CSVImporter::getImporter($import_target);
$explain_extras = $importer->extraInformations();
?>

Expand All @@ -19,7 +18,7 @@
<input type="hidden" name="{{ $name }}" value="{{ $value }}" />
@endforeach

@if(filled($explain_extras))
@if($explain_extras)
<p>
{!! $explain_extras !!}
</p>
Expand All @@ -30,11 +29,12 @@
<p>
{{ _i('Sono ammessi solo files in formato CSV. Si raccomanda di formattare la propria tabella in modo omogeneo, senza usare celle unite, celle vuote, intestazioni: ogni riga deve contenere tutte le informazioni relative al soggetto. Eventuali prezzi e somme vanno espresse senza includere il simbolo dell\'euro.') }}
</p>
<p>
{{ _i('Una volta caricato il file sarà possibile specificare quale attributo rappresenta ogni colonna trovata nel documento.') }}
</p>

<p class="text-center">
<img src="{{ url('images/csv_explain.png') }}" alt="{{ _i('Sono ammessi solo files in formato CSV. Si raccomanda di formattare la propria tabella in modo omogeneo, senza usare celle unite, celle vuote, intestazioni: ogni riga deve contenere tutte le informazioni relative al soggetto. Eventuali prezzi e somme vanno espresse senza includere il simbolo dell\'euro.') }}">
<img src="{{ url('images/csv_explain.png') }}" />
</p>
<p>
{{ _i('Una volta caricato il file sarà possibile specificare quale attributo rappresenta ogni colonna trovata nel documento. Non è necessario specificare tutte le colonne previste, tranne quelle obbligatorie.') }}
</p>

<hr/>
Expand All @@ -49,6 +49,29 @@
?>

<x-larastrap::file name="file" :label="_i('File da Caricare')" classes="immediate-run" required :data-url="sprintf('import/csv?type=%s&step=guess', $import_target)" :data-form-data="json_encode($data)" />

<hr />

<div class="small">
<p>
{{ _i('Le colonne ammesse per questo tipo di CSV sono:') }}
</p>
<ul>
@foreach($importer->fields() as $meta)
<li>
{{ $meta->label }}

@if(isset($meta->explain))
- {{ $meta->explain }}
@endif

@if(isset($meta->mandatory) && $meta->mandatory)
<span class="badge text-bg-danger">{{ _i('Obbligatorio') }}</span>
@endif
</li>
@endforeach
</ul>
</div>
</x-larastrap::form>
</div>
</x-larastrap::modal>

0 comments on commit 54b7abb

Please sign in to comment.