Skip to content

Commit 60f13e5

Browse files
committed
fix: importazione fatture di vendita zip
1 parent af8c6c6 commit 60f13e5

7 files changed

Lines changed: 532 additions & 564 deletions

File tree

plugins/importFE_ZIP/actions.php

Lines changed: 76 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919
*/
2020

2121
include_once __DIR__.'/../../core.php';
22-
include __DIR__.'/settings.php';
22+
include_once __DIR__.'/init.php';
2323

2424
use Carbon\Carbon;
25+
use Models\Module;
2526
use Modules\Anagrafiche\Tipo;
2627
use Modules\DDT\DDT;
2728
use Modules\Fatture\Fattura;
@@ -38,42 +39,59 @@
3839
$file = null;
3940
switch (filter('op')) {
4041
case 'list':
41-
$list = Interaction::getRemoteList();
42+
$list = Interaction::getInvoiceList();
4243

4344
echo json_encode($list);
4445

4546
break;
4647

47-
case 'prepare':
48-
if (!isset($file)) {
49-
$name = filter('name');
50-
$file = Interaction::getInvoiceFile($name);
51-
}
52-
48+
case 'prepare-all':
49+
// Ottimizzazione: prepara tutte le fatture in una sola chiamata
5350
try {
54-
if (!FatturaElettronica::isValid($file, 'Fatture di vendita', 'Importazione FE')) {
51+
$list = Interaction::getInvoiceList();
52+
$total = count($list);
53+
54+
if ($total === 0) {
5555
echo json_encode([
56-
'already' => 1,
56+
'success' => false,
57+
'total' => 0,
58+
'message' => tr('Nessuna fattura da importare')
5759
]);
58-
59-
return;
60+
break;
6061
}
61-
} catch (Exception) {
62-
}
6362

64-
// Individuazione ID fisico
65-
$files = Interaction::getFileList([], 'Fatture di vendita', 'Importazione FE');
66-
foreach ($files as $key => $value) {
67-
if ($value['name'] == $file) {
68-
$index = $key;
63+
// Pre-validazione delle fatture per evitare errori durante l'importazione sequenziale
64+
$valid_count = 0;
65+
$errors = [];
6966

70-
break;
67+
foreach ($list as $invoice) {
68+
try {
69+
$file = Interaction::getInvoiceFile($invoice['name']);
70+
if (!FatturaElettronica::isValid($file, 'Fatture di vendita', 'Importazione FE')) {
71+
$valid_count++;
72+
}
73+
} catch (Exception $e) {
74+
$errors[] = $invoice['name'] . ': ' . $e->getMessage();
75+
}
7176
}
77+
78+
echo json_encode([
79+
'success' => true,
80+
'total' => $total,
81+
'valid_count' => $valid_count,
82+
'errors' => $errors,
83+
'message' => $valid_count > 0 ? tr('Fatture preparate per l\'importazione') : tr('Nessuna fattura valida trovata')
84+
]);
85+
86+
} catch (Exception $e) {
87+
echo json_encode([
88+
'success' => false,
89+
'total' => 0,
90+
'message' => tr('Errore durante la preparazione').': ' . $e->getMessage()
91+
]);
7292
}
7393

74-
echo json_encode([
75-
'id' => $index + 1,
76-
]);
94+
break;
7795

7896
case 'save':
7997
$directory = FatturaElettronica::getImportDirectory('Fatture di vendita', 'Importazione FE');
@@ -113,10 +131,10 @@
113131

114132
$data = $file['FatturaElettronicaBody']['DatiGenerali']['DatiGeneraliDocumento']['Data'];
115133

116-
$fattura_pa = FatturaElettronica::manage($xml, 'Fattura di vendita', 'Importazione FE');
134+
$fattura = FatturaElettronica::manage($xml, 'Fattura di vendita', 'Importazione FE');
117135

118136
// Tipo documento
119-
$fattura_body = $fattura_pa->getBody();
137+
$fattura_body = $fattura->getBody();
120138
$dati_generali = $fattura_body['DatiGenerali']['DatiGeneraliDocumento'];
121139
$id_tipo = $database->fetchOne('SELECT id FROM co_tipidocumento WHERE dir = "entrata" AND codice_tipo_documento_fe = '.prepare($dati_generali['TipoDocumento']))['id'];
122140

@@ -134,12 +152,16 @@
134152
if (!empty($pagamento)) {
135153
$id_pagamento = $pagamento->id;
136154
} else {
137-
$id_pagamento = $settings['id_pagamento'];
155+
$id_pagamento = setting('Tipo di pagamento predefinito');
138156
}
139157

140-
$fattura_pa->saveFattura($id_pagamento, $settings['id_segment'], $id_tipo, $data, false, false, 'Cliente');
158+
// Ottieni il sezionale predefinito per le fatture di vendita
159+
$id_module_fatture_vendita = Module::where('name', 'Fatture di vendita')->first()->id;
160+
$id_segment_predefinito = getSegmentPredefined($id_module_fatture_vendita);
161+
162+
$fattura->saveFattura($id_pagamento, $id_segment_predefinito, $id_tipo, $data, false, false, 'Cliente');
141163

142-
$righe = $fattura_pa->getRighe();
164+
$righe = $fattura->getRighe();
143165

144166
$articoli = [];
145167
$iva = [];
@@ -150,16 +172,16 @@
150172

151173
$aliquota_iva = $riga['AliquotaIVA'];
152174

153-
$iva[$key] = $settings['iva'][$aliquota_iva];
175+
$iva[$key] = setting('Iva predefinita');
154176

155-
$conti[$key] = $settings['id_conto'];
177+
$conti[$key] = setting('Conto predefinito fatture di vendita');
156178
}
157179

158-
$fattura_pa->saveRighe($articoli, $iva, $conti);
180+
$fattura->saveRighe($articoli, $iva, $conti);
159181

160-
$fattura_pa->saveAllegati('Fatture di vendita');
182+
$fattura->saveAllegati('Fatture di vendita');
161183

162-
$id_record = $fattura_pa->getFattura()->id;
184+
$id_record = $fattura->getFattura()->id;
163185
$fattura = Fattura::find($id_record);
164186
$fattura->gestoreMovimenti = new GestoreMovimenti($fattura);
165187

@@ -217,6 +239,7 @@
217239

218240
$directory = FatturaElettronica::getImportDirectory('Fatture di vendita');
219241
$files = Interaction::getFileList([], 'Fatture di vendita', 'Importazione FE');
242+
220243
$file = $files[$file_id];
221244

222245
if (!empty($file)) {
@@ -248,9 +271,9 @@
248271
'serial' => post('flag_crea_seriali') ? post('serial') : [],
249272
];
250273

251-
$fattura_pa = FatturaElettronica::manage($filename, 'Fatture di vendita', 'Importazione FE');
252-
$id_fattura = $fattura_pa->save($info, 'Cliente');
253-
$fattura_pa->delete();
274+
$fattura = FatturaElettronica::manage($filename, 'Fatture di vendita', 'Importazione FE');
275+
$id_fattura = $fattura->save($info, 'Cliente');
276+
$fattura->delete();
254277
$fattura = Fattura::find($id_fattura);
255278
$id_autofattura = post('autofattura');
256279
$new_stato = Stato::where('name', 'Pagato')->first()->id;
@@ -315,7 +338,6 @@
315338
flash()->info(tr('Tutte le fatture salvate sono state importate!'));
316339
redirect(base_path().'/controller.php?id_module='.$id_module);
317340
}
318-
319341
$record = null;
320342
break;
321343

@@ -340,7 +362,7 @@
340362
return;
341363
}
342364

343-
$fatture = $anagrafica->fattureAcquisto()
365+
$fatture = $anagrafica->fattureVendita()
344366
->contabile()
345367
->orderBy('created_at', 'DESC')
346368
->take(10)
@@ -365,21 +387,13 @@
365387
$id_tipo = $tipi->sort()->keys()->last();
366388

367389
// Ricerca del conto più utilizzato
368-
// Filtro le righe che hanno un conto valido (maggiore di 0)
369-
$righe_con_conto = $righe->filter(fn ($item) => !empty($item->idconto) && $item->idconto > 0);
370-
371-
$conto = null;
372-
if ($righe_con_conto->isNotEmpty()) {
373-
$conti = $righe_con_conto->groupBy(fn ($item, $key) => $item->idconto)->transform(fn ($item, $key) => $item->count());
374-
$id_conto = $conti->sort()->keys()->last();
375-
$conto = $database->fetchOne('SELECT * FROM co_pianodeiconti3 WHERE id = '.prepare($id_conto));
376-
}
390+
$conti = $righe->groupBy(fn ($item, $key) => $item->idconto)->transform(fn ($item, $key) => $item->count());
391+
$id_conto = $conti->sort()->keys()->last();
392+
$conto = $database->fetchOne('SELECT * FROM co_pianodeiconti3 WHERE id = '.prepare($id_conto));
377393

378394
// Ricerca dell'IVA più utilizzata secondo percentuali
379395
$iva = [];
380-
// Filtro le righe che hanno un'aliquota IVA valida
381-
$righe_con_iva = $righe->filter(fn ($item) => !empty($item->idiva) && $item->idiva > 0 && !empty($item->aliquota));
382-
$percentuali_iva = $righe_con_iva->groupBy(fn ($item, $key) => $item->aliquota->percentuale);
396+
$percentuali_iva = $righe->groupBy(fn ($item, $key) => $item->aliquota->percentuale);
383397
foreach ($percentuali_iva as $key => $values) {
384398
$aliquote = $values->mapToGroups(fn ($item, $key) => [$item->aliquota->id => $item->aliquota]);
385399
$id_aliquota = $aliquote->map(fn ($item, $key) => $item->count())->sort()->keys()->last();
@@ -391,20 +405,14 @@
391405
];
392406
}
393407

394-
$response = [
408+
echo json_encode([
395409
'id_tipo' => $id_tipo,
396-
'iva' => $iva,
397-
];
398-
399-
// Aggiungo il conto solo se è stato trovato
400-
if (!empty($conto)) {
401-
$response['conto'] = [
410+
'conto' => [
402411
'id' => $conto['id'],
403412
'descrizione' => $conto['descrizione'],
404-
];
405-
}
406-
407-
echo json_encode($response);
413+
],
414+
'iva' => $iva,
415+
]);
408416
break;
409417

410418
case 'riferimenti-automatici':
@@ -417,8 +425,8 @@
417425
$results = [];
418426

419427
// Dati ordini
420-
$DatiOrdini = XML::forceArray($fattura_pa->getBody()['DatiGenerali']['DatiOrdineAcquisto']);
421-
$DatiDDT = XML::forceArray($fattura_pa->getBody()['DatiGenerali']['DatiDDT']);
428+
$DatiOrdini = XML::forceArray($fattura->getBody()['DatiGenerali']['DatiOrdineAcquisto']);
429+
$DatiDDT = XML::forceArray($fattura->getBody()['DatiGenerali']['DatiDDT']);
422430

423431
$replaces = ['n ', 'N ', 'n. ', 'N. ', 'nr ', 'NR ', 'nr. ', 'NR. ', 'num ', 'NUM ', 'num. ', 'NUM. ', 'numero ', 'NUMERO '];
424432

@@ -510,7 +518,7 @@
510518
}
511519

512520
// Iterazione sulle singole righe
513-
$righe = $fattura_pa->getRighe();
521+
$righe = $fattura->getRighe();
514522
foreach ($righe as $key => $riga) {
515523
// Se la riga è descrittiva non la collego a documenti
516524
if ($riga['PrezzoTotale'] == 0) {
@@ -740,8 +748,9 @@
740748
$riga = $documento->getRiga($namespace.$type, $collegamento['id']);
741749
$riga_origine = $riga->getOriginalComponent();
742750

751+
$desc_conto = '';
743752
if (!empty($riga->idarticolo)) {
744-
$desc_conto = $dbo->fetchOne('SELECT CONCAT( co_pianodeiconti2.numero, ".", co_pianodeiconti3.numero, " ", co_pianodeiconti3.descrizione ) AS descrizione FROM co_pianodeiconti3 INNER JOIN co_pianodeiconti2 ON co_pianodeiconti3.idpianodeiconti2=co_pianodeiconti2.id WHERE co_pianodeiconti3.id = '.prepare($riga->articolo->idconto_acquisto))['descrizione'];
753+
$desc_conto = $dbo->fetchOne('SELECT CONCAT( co_pianodeiconti2.numero, ".", co_pianodeiconti3.numero, " ", co_pianodeiconti3.descrizione ) AS descrizione FROM co_pianodeiconti3 INNER JOIN co_pianodeiconti2 ON co_pianodeiconti3.idpianodeiconti2=co_pianodeiconti2.id WHERE co_pianodeiconti3.id = '.prepare($riga->articolo->idconto_vendita))['descrizione'];
745754
}
746755

747756
// Compilazione dei dati
@@ -764,8 +773,8 @@
764773
'iva_percentuale' => $riga->aliquota->percentuale,
765774
'id_articolo' => $riga->idarticolo,
766775
'desc_articolo' => str_replace(' ', '_', $riga->articolo->codice.' - '.$riga->articolo->getTranslation('title')),
767-
'id_conto' => $riga->articolo->idconto_acquisto,
768-
'desc_conto' => str_replace(' ', '_', $desc_conto),
776+
'id_conto' => $riga->articolo->idconto_vendita,
777+
'desc_conto' => str_replace(' ', '_', $desc_conto ?: ''),
769778
],
770779
];
771780
}

plugins/importFE_ZIP/buttons.php

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,19 +64,15 @@ function compile(btn) {
6464
$("#id_tipo").selectSet(response.id_tipo);
6565
}
6666
67-
// Compila i campi IVA - prova a impostare la prima IVA disponibile per tutti i campi vuoti
6867
$("select[name^=iva]").each(function(){
69-
if (!$(this).val() && response.iva){
70-
// Prende la prima aliquota IVA disponibile
71-
var firstIva = Object.values(response.iva)[0];
72-
if (firstIva) {
73-
$(this).selectSetNew(firstIva.id, firstIva.descrizione);
74-
}
68+
var aliquota = $(this).closest("tr").find("[id^=aliquota]").text();
69+
if (response.iva[aliquota] !== undefined && !$(this).val()){
70+
$(this).selectSet(response.iva[aliquota].id);
7571
}
7672
});
7773
7874
$("select[name^=conto]").each(function(){
79-
if (!$(this).val()){
75+
if (!$(this).val() && response.conto){
8076
$(this).selectSetNew(response.conto.id, response.conto.descrizione);
8177
}
8278
});
@@ -113,7 +109,7 @@ function compilaRiferimenti(btn) {
113109
data = response[id_riga];
114110
115111
// Selezione dinamica
116-
$("#selezione_riferimento" + id_riga).addClass("already-loaded").selectSetNew(data.documento.id, data.documento.opzione).removeClass("already-loaded");
112+
$("#selezione_riferimento[" + id_riga + "]").addClass("already-loaded").selectSetNew(data.documento.id, data.documento.opzione).removeClass("already-loaded");
117113
118114
// Impostazione del riferimento
119115
impostaRiferimento(id_riga, data.documento, data.riga);

0 commit comments

Comments
 (0)