RecordOUT.php 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Illuminate\Support\Facades\Auth;
  5. use Illuminate\Support\Facades\Log;
  6. use SimpleXMLElement;
  7. use Livewire\WithFileUploads;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Schema;
  10. class RecordOUT extends Component
  11. {
  12. use WithFileUploads;
  13. protected $listeners = [
  14. 'setCausal' => 'setCausal',
  15. 'closeImportModal' => 'closeImportModal',
  16. ];
  17. public $sortField = 'date';
  18. public $sortAsc = false;
  19. public $typeOUT = "OUT";
  20. public $fromPage = '';
  21. public $multiP = false;
  22. public $multiMonthTo = 0;
  23. public $multiYearTo = 0;
  24. public $multiMonthFrom = 0;
  25. public $multiYearFrom = 0;
  26. public function sortBy($field)
  27. {
  28. if ($this->sortField === $field) {
  29. $this->sortAsc = ! $this->sortAsc;
  30. } else {
  31. $this->sortAsc = true;
  32. }
  33. $this->sortField = $field;
  34. }
  35. public $records, $dataId, $member_id, $supplier_id,
  36. $causal_id,
  37. $payment_method_id,
  38. $date,
  39. $data_pagamento,
  40. $month,
  41. $year,
  42. $type,
  43. $amount,
  44. $note,
  45. $commercial, $update = false, $add = false;
  46. public $attachment;
  47. public $filterSupplier = 0, $filterPaymentMethod = 0, $filterCausals = [], $filterFrom = '', $filterTo = '', $filterCommercial = 0;
  48. public $hasFilter = false;
  49. public $total = 0;
  50. public $selectedFilter = '';
  51. public $multipleIds = [];
  52. public $multipleAction = '';
  53. public $selectId = 0;
  54. public $causals = array();
  55. public $payments = array();
  56. public $suppliers = array();
  57. public $rows = array();
  58. public $receiptFiles = [];
  59. public $selectedCausal = '';
  60. public $importCausals = array();
  61. protected $rules = [
  62. 'supplier_id' => 'required',
  63. 'payment_method_id' => 'required',
  64. 'rows.*.causal_id' => 'required',
  65. 'rows.*.amount' => 'required'
  66. //'causal_id' => 'required',
  67. //'amount' => 'required'
  68. ];
  69. protected $messages = [
  70. 'supplier_id.required' => 'Il fornitore è obbligatorio',
  71. 'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
  72. 'rows.*.amount.required' => 'L\'importo è obbligatorio',
  73. 'rows.*.causal_id.required' => 'La causale è obbligatoria'
  74. ];
  75. public function getSupplierProperty()
  76. {
  77. $ret = null;
  78. if ($this->supplier_id > 0) {
  79. $ret = \App\Models\Supplier::findOrFail($this->supplier_id);
  80. }
  81. return $ret;
  82. }
  83. public function getCausalProperty()
  84. {
  85. $ret = null;
  86. if ($this->causal_id > 0) {
  87. $ret = \App\Models\Causal::findOrFail($this->causal_id);
  88. }
  89. return $ret;
  90. }
  91. public function resetFields()
  92. {
  93. $this->member_id = null;
  94. $this->supplier_id = null;
  95. //$this->causal_id = null;
  96. $this->payment_method_id = null;
  97. $this->date = date("Y-m-d");
  98. $this->data_pagamento = date("Y-m-d");
  99. //$this->attachment = null;
  100. //$this->month = date("n");
  101. //$this->year = date("Y");
  102. $this->type = 'OUT';
  103. //$this->note = '';
  104. //$this->amount = null;
  105. $this->commercial = 1;
  106. $this->rows = array();
  107. $this->rows[] = array(
  108. 'causal_id' => null,
  109. 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
  110. 'amount' => null,
  111. 'imponibile' => null,
  112. 'aliquota_iva' => null,
  113. 'note' => '',
  114. 'commercial' => 0
  115. );
  116. $this->emit('load-data-table');
  117. }
  118. public function getCausale($records, $indentation)
  119. {
  120. foreach ($records as $record) {
  121. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree());
  122. if (count($record->childs))
  123. $this->getCausale($record->childs, $indentation + 1);
  124. }
  125. }
  126. public $isImportModalOpen = false;
  127. public function openImportModal()
  128. {
  129. $this->isImportModalOpen = true;
  130. }
  131. public function closeImportModal()
  132. {
  133. $this->isImportModalOpen = false;
  134. $this->reset(['selectedCausal', 'receiptFiles']);
  135. $this->resetValidation();
  136. $this->dispatchBrowserEvent('closeModal');
  137. }
  138. public function hydrate()
  139. {
  140. $this->emit('load-select');
  141. if (empty($this->importCausals)) {
  142. $this->loadImportCausals();
  143. }
  144. }
  145. public function mount()
  146. {
  147. if (isset($_GET["from"])) {
  148. $this->fromPage = $_GET["from"];
  149. }
  150. if (Auth::user()->level != env('LEVEL_ADMIN', 0))
  151. return redirect()->to('/dashboard');
  152. $this->multiMonthFrom = date("n");
  153. $this->multiYearFrom = date("Y");
  154. $this->multiMonthTo = date("n");
  155. $this->multiYearTo = date("Y");
  156. if (isset($_GET["new"]))
  157. $this->add();
  158. $this->causals = array();
  159. $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'OUT')->orderBy('name')->get(), 0);
  160. $this->suppliers = \App\Models\Supplier::select('name', 'id')->orderBy('name')->get();
  161. $this->payments = \App\Models\PaymentMethod::select('id', 'name')->whereIn('type', array('ALL', 'OUT'))->where('enabled', true)->orderBy('name')->get();
  162. $this->importCausals = [];
  163. $this->loadImportCausals();
  164. }
  165. public function loadImportCausals()
  166. {
  167. $causals = \App\Models\Causal::select('id', 'name', 'parent_id')
  168. ->where('type', 'OUT')
  169. ->orderBy('name')
  170. ->get();
  171. $this->importCausals = [];
  172. $this->buildCausalTree($causals);
  173. }
  174. private function buildCausalTree($causals, $parentId = null, $level = 0)
  175. {
  176. foreach ($causals as $causal) {
  177. if ($causal->parent_id == $parentId) {
  178. $dotString = str_repeat('● ', $level);
  179. $this->importCausals[] = [
  180. 'id' => $causal->id,
  181. 'name' => $dotString . $causal->name
  182. ];
  183. $this->buildCausalTree($causals, $causal->id, $level + 1);
  184. }
  185. }
  186. }
  187. private function getCausalLevel($causal, $level = 0)
  188. {
  189. if ($causal->parent_id == null) {
  190. return $level;
  191. }
  192. $parent = \App\Models\Causal::find($causal->parent_id);
  193. if (!$parent) {
  194. return $level;
  195. }
  196. return $this->getCausalLevel($parent, $level + 1);
  197. }
  198. public function getCausal($causal)
  199. {
  200. $ret = '';
  201. if ($causal > 0) {
  202. $ret = \App\Models\Causal::findOrFail($causal)->getTree();
  203. }
  204. return $ret;
  205. }
  206. public function search()
  207. {
  208. $this->hasFilter = true;
  209. }
  210. public function disableSearch()
  211. {
  212. $this->filterSupplier = 0;
  213. $this->filterPaymentMethod = 0;
  214. $this->filterCausals = [];
  215. $this->filterTo = '';
  216. $this->filterFrom = '';
  217. $this->filterCommercial = 0;
  218. $this->hasFilter = false;
  219. $this->hasFilter = false;
  220. }
  221. public function render()
  222. {
  223. $datas = [];
  224. if (false) {
  225. if ($this->hasFilter) {
  226. $datas = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method');
  227. /*if ($this->filterCommercial > 0)
  228. {
  229. $datas = $datas->where('commercial', $this->filterCommercial == 1 ? true : false);
  230. }*/
  231. if ($this->filterSupplier > 0) {
  232. $datas = $datas->where('supplier_id', $this->filterSupplier);
  233. }
  234. if ($this->filterPaymentMethod > 0) {
  235. $datas = $datas->where('payment_method_id', $this->filterPaymentMethod);
  236. }
  237. /*if (sizeof($this->filterCausals) > 0)
  238. {
  239. $datas = $datas->whereIn('causal_id', $this->filterCausals);
  240. }*/
  241. if ($this->filterFrom != '') {
  242. $datas = $datas->where('date', '>=', $this->filterFrom);
  243. }
  244. if ($this->filterTo != '') {
  245. $datas = $datas->where('date', '<=', $this->filterTo);
  246. }
  247. $this->records = $datas->get();
  248. $this->total = 0;
  249. foreach ($this->records as $r) {
  250. foreach ($r->rows as $rr) {
  251. $this->total += $rr->amount;
  252. }
  253. }
  254. } else {
  255. if ($this->selectedFilter == '') {
  256. $this->records = \App\Models\Record::where('type', 'OUT')->with('supplier', 'payment_method')->limit(20)->orderBy('date', 'DESC')->orderBy('id', 'DESC')->get();
  257. } else {
  258. if ($this->selectedFilter == 0) {
  259. $fromDate = date("Y-m-d");
  260. $toDate = date("Y-m-d");
  261. }
  262. if ($this->selectedFilter == 1) {
  263. $fromDate = date("Y-m-01");
  264. $toDate = date("Y-m-t");
  265. }
  266. if ($this->selectedFilter == 2) {
  267. $fromDate = date("Y-01-01");
  268. $toDate = date("Y-12-31");
  269. }
  270. if ($this->selectedFilter == 3) {
  271. $fromDate = date("2000-01-01");
  272. $toDate = date("Y-12-31");
  273. }
  274. $this->records = \App\Models\Record::where('type', 'OUT')->whereBetween('date', [$fromDate, $toDate])->with('supplier', 'payment_method')->get();
  275. }
  276. }
  277. foreach ($this->records as $r) {
  278. $r->total = $r->getTotal();
  279. $r->supplier = $r->supplier ? $r->supplier->name : '';
  280. $r->payment = $r->payment_method ? $r->payment_method->name : '';
  281. }
  282. }
  283. return view('livewire.records_out');
  284. }
  285. public function executeMultipleAction()
  286. {
  287. if ($this->multipleAction == 'delete')
  288. $this->multipleDelete();
  289. }
  290. public function add()
  291. {
  292. $this->emit('load-select');
  293. //if ($this->hasFilter)
  294. $this->emit('hide-search');
  295. $this->resetFields();
  296. $this->add = true;
  297. $this->update = false;
  298. $this->emit('setEdit', true);
  299. }
  300. public function store()
  301. {
  302. $this->emit('refresh');
  303. /*
  304. if ($this->attachment) {
  305. Log::info("Attachment: " . json_encode($this->attachment));
  306. $name = md5($this->attachment . microtime()) . '.' . $this->attachment->extension();
  307. $this->attachment->storeAs('public', $name);
  308. } */
  309. $invoiceNumber = null;
  310. // Option 1: Use current date and time as the invoice number
  311. $invoiceNumber = 'USC-' . date('YmdHis');
  312. if (empty($this->data_pagamento) || $this->data_pagamento == '1970-01-01') {
  313. $this->data_pagamento = null;
  314. Log::info("Setting data_pagamento to NULL in store");
  315. } else {
  316. Log::info("Using data_pagamento: " . $this->data_pagamento);
  317. }
  318. $this->validate();
  319. try {
  320. $record = \App\Models\Record::create([
  321. 'member_id' => $this->member_id,
  322. 'supplier_id' => $this->supplier_id,
  323. //'causal_id' => $this->causal_id,
  324. 'payment_method_id' => $this->payment_method_id,
  325. 'date' => $this->date,
  326. 'data_pagamento' =>$this->data_pagamento,
  327. //'month' => $this->month,
  328. //'year' => $this->year,
  329. //'note' => $this->note,
  330. //'attachment' => $this->attachment,
  331. 'type' => $this->type,
  332. 'amount' => $this->currencyToDouble($this->amount),
  333. 'commercial' => $this->commercial,
  334. 'numero_fattura' => $invoiceNumber,
  335. ]);
  336. Log::info("Record data being inserted: " . json_encode($record));
  337. $this->dataId = $record->id;
  338. $tot = 0;
  339. foreach ($this->rows as $row) {
  340. foreach ($row["when"] as $x => $y) {
  341. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  342. }
  343. $imponibile = isset($row["imponibile"]) ? $this->currencyToDouble($row["imponibile"]) : null;
  344. Log::info("Imponibile store: " . $imponibile);
  345. $aliquota_iva = isset($row["aliquota_iva"]) ? floatval(str_replace('%', '', $row["aliquota_iva"])) : null;
  346. Log::info("Aliquota IVA store: " . $aliquota_iva);
  347. \App\Models\RecordRow::create([
  348. 'record_id' => $this->dataId,
  349. 'causal_id' => $row["causal_id"],
  350. 'note' => $row["note"],
  351. 'amount' => $this->currencyToDouble($row["amount"]),
  352. 'imponibile' => $imponibile,
  353. 'aliquota_iva' => $aliquota_iva,
  354. 'commercial' => $row["commercial"],
  355. 'when' => json_encode($row["when"])
  356. ]);
  357. $tot += $this->currencyToDouble($row["amount"]);
  358. }
  359. $record->amount = $tot;
  360. $record->save();
  361. session()->flash('success', 'Movimento creato');
  362. $this->resetFields();
  363. $this->add = false;
  364. $this->emit('setEdit', false);
  365. } catch (\Exception $ex) {
  366. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  367. }
  368. }
  369. public function setDataPagamentoAttribute($value)
  370. {
  371. // Convert empty values to NULL
  372. if (empty($value) || $value == '1970-01-01' || $value == '0000-00-00') {
  373. $this->attributes['data_pagamento'] = null;
  374. } else {
  375. $this->attributes['data_pagamento'] = $value;
  376. }
  377. }
  378. // Optional: Also add an accessor to prevent returning 1970-01-01
  379. public function getDataPagamentoAttribute($value)
  380. {
  381. // Return null instead of Unix epoch date
  382. if ($value == '1970-01-01' || $value == '0000-00-00') {
  383. return null;
  384. }
  385. return $value;
  386. }
  387. public function edit($id)
  388. {
  389. if (!isset($_GET["from"]) && $this->fromPage == '')
  390. $this->fromPage = 'out';
  391. $this->emit('setEdit', true);
  392. $this->emit('load-select');
  393. //if ($this->hasFilter)
  394. $this->emit('hide-search');
  395. try {
  396. $record = \App\Models\Record::findOrFail($id);
  397. if (!$record) {
  398. $this->emit('flash-error', 'Movimento non trovato');
  399. } else {
  400. $this->member_id = $record->member_id;
  401. $this->supplier_id = $record->supplier_id;
  402. //$this->causal_id = $record->causal_id;
  403. $this->payment_method_id = $record->payment_method_id;
  404. $this->date = date("Y-m-d", strtotime($record->date));
  405. $this->data_pagamento = $record->data_pagamento;
  406. //$this->month = $record->month;
  407. //$this->year = $record->year;
  408. //$this->note = $record->note;
  409. $this->type = $record->type;
  410. //$attachment = $record->attachment;
  411. //$this->amount = formatPrice($record->amount);
  412. $this->commercial = $record->commercial;
  413. $this->dataId = $record->id;
  414. $this->update = true;
  415. $this->add = false;
  416. $this->rows = [];
  417. $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
  418. foreach ($recordRows as $recordRow) {
  419. $rowData = [
  420. 'causal_id' => $recordRow->causal_id,
  421. 'note' => $recordRow->note,
  422. 'commercial' => $recordRow->commercial,
  423. 'when' => json_decode($recordRow->when),
  424. 'amount' => formatPrice($recordRow->amount)
  425. ];
  426. // Add imponibile field if available in the database
  427. if (isset($recordRow->imponibile)) {
  428. $rowData['imponibile'] = formatPrice($recordRow->imponibile);
  429. }
  430. // Add aliquota_iva field if available in the database
  431. if (isset($recordRow->aliquota_iva)) {
  432. $rowData['aliquota_iva'] = $recordRow->aliquota_iva . '%';
  433. }
  434. $this->rows[] = $rowData;
  435. }
  436. }
  437. } catch (\Exception $ex) {
  438. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  439. }
  440. }
  441. public function update()
  442. {
  443. $this->emit('refresh');
  444. $this->validate();
  445. if (empty($this->data_pagamento) || $this->data_pagamento == '') {
  446. $this->data_pagamento = null;
  447. Log::info("Data pagamento vuota, imposto a NULL in update");
  448. } else {
  449. Log::info("Data pagamento in update: " . $this->data_pagamento);
  450. }
  451. try {
  452. \App\Models\Record::whereId($this->dataId)->update([
  453. 'member_id' => $this->member_id,
  454. 'supplier_id' => $this->supplier_id,
  455. 'payment_method_id' => $this->payment_method_id,
  456. 'date' => $this->date,
  457. 'data_pagamento' => $this->data_pagamento,
  458. 'type' => $this->type,
  459. 'commercial' => $this->commercial,
  460. //'attachment' => $this->attachment,
  461. ]);
  462. $tot = 0;
  463. $existingRows = \App\Models\RecordRow::where('record_id', $this->dataId)
  464. ->select('id', 'quantita', 'numero_linea')
  465. ->get()
  466. ->keyBy('id')
  467. ->toArray();
  468. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  469. foreach ($this->rows as $row) {
  470. foreach ($row["when"] as $x => $y) {
  471. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  472. }
  473. $imponibile = null;
  474. if (isset($row["imponibile"]) && $row["imponibile"] !== null && $row["imponibile"] !== '') {
  475. $imponibile = $this->currencyToDouble($row["imponibile"]);
  476. Log::info("Imponibile: " . $imponibile);
  477. }
  478. $aliquota_iva = null;
  479. if (isset($row["aliquota_iva"]) && $row["aliquota_iva"] !== null && $row["aliquota_iva"] !== '') {
  480. $aliquota_iva = floatval(str_replace('%', '', $row["aliquota_iva"]));
  481. Log::info("Aliquota IVA: " . $aliquota_iva);
  482. }
  483. $amount = $this->currencyToDouble($row["amount"]);
  484. $imposta = null;
  485. if ($imponibile !== null) {
  486. $imposta = $amount - $imponibile;
  487. Log::info("Imposta calculated: " . $imposta);
  488. }
  489. $recordRowData = [
  490. 'record_id' => $this->dataId,
  491. 'causal_id' => $row["causal_id"],
  492. 'note' => $row["note"],
  493. 'amount' => $this->currencyToDouble($row["amount"]),
  494. 'commercial' => $row["commercial"],
  495. 'when' => json_encode($row["when"]),
  496. 'imponibile' => $imponibile,
  497. 'aliquota_iva' => $aliquota_iva,
  498. 'imposta' => $imposta,
  499. 'divisa' => 'EUR',
  500. ];
  501. if (isset($row["id"]) && isset($existingRows[$row["id"]])) {
  502. $existingRow = $existingRows[$row["id"]];
  503. $recordRowData['quantita'] = $existingRow['quantita'];
  504. $recordRowData['numero_linea'] = $existingRow['numero_linea'];
  505. }
  506. Log::info("RecordRowData: " . json_encode($recordRowData));
  507. \App\Models\RecordRow::create($recordRowData);
  508. $tot += $this->currencyToDouble($row["amount"]);
  509. }
  510. $rec = \App\Models\Record::findOrFail($this->dataId);
  511. $rec->amount = $tot;
  512. $rec->save();
  513. session()->flash('success', 'Movimento aggiornato');
  514. $this->resetFields();
  515. $this->update = false;
  516. $this->emit('setEdit', false);
  517. } catch (\Exception $ex) {
  518. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  519. }
  520. }
  521. public function cancel()
  522. {
  523. $this->add = false;
  524. $this->update = false;
  525. $this->emit('setEdit', false);
  526. $this->resetFields();
  527. }
  528. public function delete($id)
  529. {
  530. try {
  531. \App\Models\Record::find($id)->delete();
  532. session()->flash('success', "Movimento eliminato");
  533. } catch (\Exception $e) {
  534. $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
  535. }
  536. }
  537. public function multipleDelete()
  538. {
  539. try {
  540. foreach ($this->multipleIds as $id) {
  541. \App\Models\Record::find($id)->delete();
  542. }
  543. } catch (\Exception $e) {
  544. $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
  545. }
  546. $this->multipleAction = '';
  547. }
  548. function currencyToDouble($val)
  549. {
  550. $x = str_replace("€", "", $val);
  551. $x = str_replace(".", "", $x);
  552. $x = str_replace(",", ".", $x);
  553. return floatval(trim($x));
  554. }
  555. public function addRow()
  556. {
  557. $this->rows[] = array(
  558. 'causal_id' => null,
  559. 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
  560. 'amount' => null,
  561. 'imponibile' => null,
  562. 'aliquota_iva' => null,
  563. 'note' => '',
  564. 'commercial' => 0
  565. );
  566. $this->emit('load-select');
  567. }
  568. public function delRow($idx)
  569. {
  570. unset($this->rows[$idx]);
  571. // $this->emit('load-select');
  572. }
  573. public function addPeriod($idx)
  574. {
  575. $x = sizeof($this->rows[$idx]['when']) - 1;
  576. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  577. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  578. //$this->rows[$idx]['when'][] = array('month' => date("n"), 'year' => date("Y"), 'period' => '');
  579. }
  580. public function delPeriod($idx, $xxx)
  581. {
  582. array_splice($this->rows[$idx]['when'], $xxx, 1);
  583. // $this->emit('load-select');
  584. }
  585. public function getTotal()
  586. {
  587. $total = 0.00;
  588. foreach ($this->rows as $r) {
  589. $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
  590. }
  591. return formatPrice($total);
  592. // $this->emit('load-select');
  593. }
  594. public function setCausal($id, $idx)
  595. {
  596. $this->rows[$idx]["causal_id"] = $id;
  597. }
  598. public function multiPeriod()
  599. {
  600. $this->multiP = true;
  601. }
  602. public function multiPeriodCreate($idx)
  603. {
  604. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  605. $this->rows[$idx]['when'] = [];
  606. foreach ($period as $dt) {
  607. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  608. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  609. }
  610. $this->multiP = false;
  611. }
  612. public function multiPeriodCancel()
  613. {
  614. $this->multiP = false;
  615. }
  616. public function importReceipts()
  617. {
  618. $this->validate([
  619. //'receiptFiles.*' => 'required|mimes:xml|max:2048',
  620. 'selectedCausal' => 'required|exists:causals,id',
  621. ]);
  622. Log::info("Importazione ricevute: " . json_encode($this->receiptFiles));
  623. try {
  624. $importCount = 0;
  625. $updateCount = 0;
  626. $errorsCount = 0;
  627. $errorMessages = [];
  628. $importedFiles = [];
  629. $updatedFiles = [];
  630. $errorFiles = [];
  631. $totalFiles = count($this->receiptFiles);
  632. // disabilita select
  633. $this->emit('import-started');
  634. Log::info("Import iniziato");
  635. foreach ($this->receiptFiles as $index => $receiptFile) {
  636. try {
  637. $fileName = $receiptFile->getClientOriginalName();
  638. Log::info("Elaborazione file: " . $fileName);
  639. // Carica e analizza il file XML
  640. $xmlString = file_get_contents($receiptFile->getRealPath());
  641. $xml = simplexml_load_string($xmlString);
  642. if (empty($xmlString)) {
  643. throw new \Exception("Il file è vuoto.");
  644. }
  645. // Verifica se il file sembra essere un XML
  646. if (strpos($xmlString, '<?xml') === false && strpos($xmlString, '<') === false) {
  647. throw new \Exception("Il file non sembra essere in formato XML.");
  648. }
  649. $xml = simplexml_load_string($xmlString);
  650. if (!$xml) {
  651. throw new \Exception("Impossibile analizzare il file XML");
  652. }
  653. // Estrai i dati dalla fattura elettronica
  654. $fatturaData = $this->extractFatturaData($xml);
  655. // Trova o crea il fornitorez
  656. $supplier = $this->findOrCreateSupplier($fatturaData);
  657. // Trova il metodo di pagamento
  658. $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
  659. // Crea il record principale
  660. $isUpdate = false;
  661. $existingRecord = \App\Models\Record::where('supplier_id', $supplier->id)
  662. ->where('numero_fattura', $fatturaData['numeroFattura'])
  663. ->first();
  664. if ($existingRecord) {
  665. $record = $this->updateRecord($existingRecord, $paymentMethodId, $fatturaData);
  666. $isUpdate = true;
  667. $updateCount++;
  668. $updatedFiles[] = $fileName; // Aggiungiamo il nome del file alla lista degli aggiornati
  669. Log::info("Fattura aggiornata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  670. } else {
  671. // Crea un nuovo record
  672. $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
  673. $importCount++;
  674. $importedFiles[] = $fileName; // Aggiungiamo il nome del file alla lista degli importati
  675. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  676. }
  677. // Crea il record row
  678. $this->createRecordRow($record->id, $fatturaData);
  679. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']} OR {$fatturaData['cognome']}, {$fatturaData['nome']}");
  680. } catch (\Exception $e) {
  681. $errorMsg = $e->getMessage();
  682. $friendlyErrorMsg = $this->getFriendlyErrorMessage($errorMsg);
  683. Log::error("Errore originale: " . $errorMsg);
  684. $errorMessages[] = $friendlyErrorMsg;
  685. $errorFiles[] = $fileName;
  686. $errorsCount++;
  687. }
  688. $progress = ($index + 1) / $totalFiles * 100;
  689. $this->emit('update-progress', $progress);
  690. }
  691. $this->showResultMessages($importCount, $updateCount, $errorsCount, $importedFiles, $updatedFiles, $errorFiles, $errorMessages);
  692. } catch (\Exception $e) {
  693. $errorMsg = 'Errore durante l\'importazione dei file XML: ' . $e->getMessage();
  694. Log::error($errorMsg);
  695. $this->emit('show-import-result', [
  696. 'message' => $errorMsg,
  697. 'type' => 'error'
  698. ]);
  699. } finally {
  700. $this->emit('load-data-table');
  701. }
  702. }
  703. /**
  704. * Estrae i dati dalla fattura elettronica XML
  705. */
  706. private function extractFatturaData($xml)
  707. {
  708. $data = [];
  709. try {
  710. // Stampa la struttura XML per debug
  711. Log::info("Nomi dei children dell'elemento radice: " . implode(", ", array_map(function ($node) {
  712. return $node->getName();
  713. }, iterator_to_array($xml->children()))));
  714. $headerNode = $xml->FatturaElettronicaHeader;
  715. $bodyNode = $xml->FatturaElettronicaBody;
  716. if (!$headerNode || !$bodyNode) {
  717. throw new \Exception("Struttura XML non standard, FatturaElettronicaHeader o FatturaElettronicaBody non trovati");
  718. }
  719. // Estrai dati del fornitore (cedente/prestatore)
  720. $cedenteNode = $headerNode->CedentePrestatore;
  721. $datiAnagrafici = $cedenteNode->DatiAnagrafici;
  722. $idFiscaleIVA = $datiAnagrafici->IdFiscaleIVA;
  723. $data['idPaese'] = (string)$idFiscaleIVA->IdPaese;
  724. $data['idCodice'] = (string)$idFiscaleIVA->IdCodice;
  725. $data['partitaIva'] = $data['idPaese'] . $data['idCodice'];
  726. $data['codiceFiscale'] = (string)$datiAnagrafici->CodiceFiscale;
  727. $data['denominazione'] = (string)$datiAnagrafici->Anagrafica->Denominazione;
  728. $data['cognome'] = (string)$datiAnagrafici->Anagrafica->Cognome;
  729. $data['nome'] = (string)$datiAnagrafici->Anagrafica->Nome;
  730. // Estrai dati della sede
  731. $sede = $cedenteNode->Sede;
  732. $data['indirizzo'] = (string)$sede->Indirizzo;
  733. $data['cap'] = (string)$sede->CAP;
  734. $data['comune'] = (string)$sede->Comune;
  735. $data['provincia'] = (string)$sede->Provincia;
  736. $data['nazione'] = (string)$sede->Nazione ?: 'IT';
  737. // Email, se presente
  738. $data['email'] = '';
  739. if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
  740. $data['email'] = (string)$cedenteNode->Contatti->Email;
  741. }
  742. // Dati generali della fattura
  743. $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
  744. $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
  745. $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
  746. $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
  747. $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
  748. $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
  749. // Dati di pagamento
  750. $data['condizioniPagamento'] = '';
  751. $data['modalitaPagamento'] = '';
  752. $data['dataScadenza'] = '';
  753. $data['iban'] = '';
  754. $data['bic'] = '';
  755. $data['istitutoFinanziario'] = '';
  756. if (isset($bodyNode->DatiPagamento)) {
  757. $datiPagamento = $bodyNode->DatiPagamento;
  758. $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
  759. if (isset($datiPagamento->DettaglioPagamento)) {
  760. $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
  761. $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
  762. $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
  763. $data['iban'] = (string)$dettaglioPagamento->IBAN;
  764. $data['bic'] = (string)$dettaglioPagamento->BIC;
  765. $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
  766. }
  767. }
  768. // Estrai le linee di dettaglio
  769. $data['linee'] = [];
  770. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
  771. foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
  772. if (isset($linea->Quantita)) {
  773. $lineaData = [
  774. 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
  775. 'descrizione' => (string)($linea->Descrizione ?? ''),
  776. 'quantita' => (float)($linea->Quantita ?? 1),
  777. 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
  778. 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
  779. 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
  780. ];
  781. // Calcola il prezzo totale se non presente
  782. if ($lineaData['prezzoTotale'] == 0) {
  783. $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
  784. }
  785. $data['linee'][] = $lineaData;
  786. } else {
  787. // Se la linea ha un campo Quantita, non la consideriamo
  788. Log::info("Linea con Quantita non considerata: " . json_encode($linea));
  789. }
  790. }
  791. }
  792. $data['riepilogo'] = null;
  793. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
  794. $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
  795. if ($riepilogoNode) {
  796. $data['riepilogo'] = [
  797. 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
  798. 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
  799. 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
  800. ];
  801. }
  802. }
  803. Log::info("Dati estratti dalla fattura: P.IVA={$data['partitaIva']}, Denominazione={$data['denominazione']},Nome={$data['nome']},Cognome={$data['cognome']} , Numero={$data['numeroFattura']}, Importo={$data['importoTotale']}");
  804. return $data;
  805. } catch (\Exception $e) {
  806. Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
  807. throw $e;
  808. }
  809. }
  810. /**
  811. * Trova o crea un fornitore basato sui dati della fattura
  812. */
  813. private function findOrCreateSupplier($fatturaData)
  814. {
  815. $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
  816. if (!$supplier) {
  817. Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']}) OR ({$fatturaData['nome']}), ({$fatturaData['cognome']})");
  818. $countryId = $this->getCountryId($fatturaData['nazione']);
  819. $provinceId = $this->getProvinceId($fatturaData['provincia']);
  820. $cityId = $this->getCityId($fatturaData['comune']);
  821. $supplier = new \App\Models\Supplier();
  822. $supplier->name = $fatturaData['denominazione'] ?: $fatturaData['cognome'] . ' ' . $fatturaData['nome'];
  823. Log::info("Nome fornitore: " . $supplier->name);
  824. $supplier->vat = $fatturaData['partitaIva'];
  825. $supplier->fiscal_code = $fatturaData['codiceFiscale'];
  826. $supplier->address = $fatturaData['indirizzo'];
  827. $supplier->city_id = $cityId;
  828. $supplier->zip_code = $fatturaData['cap'];
  829. $supplier->province_id = $provinceId;
  830. $supplier->nation_id = $countryId;
  831. $supplier->email = $fatturaData['email'];
  832. $supplier->save();
  833. Log::info("Fornitore creato con ID: " . $supplier->id);
  834. }
  835. return $supplier;
  836. }
  837. /**
  838. * Trova l'ID della nazione dal codice
  839. */
  840. private function getCountryId($nationCode)
  841. {
  842. $country = DB::table('nations')->where('code', $nationCode)->first();
  843. return $country ? $country->id : null;
  844. }
  845. /**
  846. * Trova l'ID della provincia dal codice
  847. */
  848. private function getProvinceId($provinceCode)
  849. {
  850. $province = DB::table('provinces')->where('code', $provinceCode)->first();
  851. return $province ? $province->id : null;
  852. }
  853. /**
  854. * Trova l'ID della città dal nome
  855. */
  856. private function getCityId($cityName)
  857. {
  858. if (empty($cityName)) return null;
  859. $city = DB::table('cities')->where('name', $cityName)->first();
  860. return $city ? $city->id : null;
  861. }
  862. /**
  863. * Trova l'ID del metodo di pagamento dal codice
  864. */
  865. private function findPaymentMethod($paymentCode)
  866. {
  867. if (!empty($paymentCode)) {
  868. $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
  869. if ($paymentMethod) {
  870. Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
  871. return $paymentMethod->id;
  872. }
  873. }
  874. // Cerca il metodo di pagamento predefinito - corretto per evitare l'errore della colonna 'default'
  875. // Verifica se esiste una colonna 'is_default' o simile
  876. $possibleDefaultColumns = ['is_default', 'is_default_method', 'default_method', 'primary'];
  877. $defaultPaymentMethod = null;
  878. foreach ($possibleDefaultColumns as $column) {
  879. if (Schema::hasColumn('payment_methods', $column)) {
  880. $defaultPaymentMethod = DB::table('payment_methods')->where($column, 1)->first();
  881. if ($defaultPaymentMethod) {
  882. Log::info("Usando metodo di pagamento predefinito (colonna $column) ID: {$defaultPaymentMethod->id}");
  883. break;
  884. }
  885. }
  886. }
  887. // Se non è stato trovato un metodo predefinito, prendi il primo disponibile
  888. if (!$defaultPaymentMethod) {
  889. $defaultPaymentMethod = DB::table('payment_methods')->first();
  890. if ($defaultPaymentMethod) {
  891. Log::info("Usando il primo metodo di pagamento disponibile ID: {$defaultPaymentMethod->id}");
  892. }
  893. }
  894. if ($defaultPaymentMethod) {
  895. return $defaultPaymentMethod->id;
  896. }
  897. throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
  898. }
  899. /**
  900. * Crea un record nella tabella records
  901. */
  902. private function createRecord($supplierId, $paymentMethodId, $fatturaData)
  903. {
  904. $record = new \App\Models\Record();
  905. $record->supplier_id = $supplierId;
  906. $record->payment_method_id = $paymentMethodId;
  907. $record->date = $fatturaData['dataDocumento'];
  908. $record->data_pagamento = $fatturaData['dataDocumento'];
  909. $record->numero_fattura = $fatturaData['numeroFattura'];
  910. $record->type = 'OUT';
  911. $record->commercial = 1;
  912. $record->corrispettivo_fiscale = 0;
  913. $record->deleted = 0;
  914. $record->financial_movement = 1;
  915. $record->amount = $fatturaData['importoTotale'];
  916. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  917. $record->is_ricevuta = true;
  918. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  919. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  920. }
  921. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  922. $record->IBAN = $fatturaData['iban'];
  923. }
  924. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  925. $record->BIC = $fatturaData['bic'];
  926. }
  927. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  928. $record->data_scadenza = $fatturaData['dataScadenza'];
  929. }
  930. $record->save();
  931. Log::info("Nuovo record creato con ID: " . $record->id);
  932. return $record;
  933. }
  934. /**
  935. * Aggiorna un record esistente nella tabella records
  936. */
  937. private function updateRecord($record, $paymentMethodId, $fatturaData)
  938. {
  939. $record->payment_method_id = $paymentMethodId;
  940. $record->date = $fatturaData['dataDocumento'];
  941. $record->data_pagamento = $fatturaData['dataDocumento'];
  942. $record->type = 'OUT';
  943. $record->commercial = 1;
  944. $record->corrispettivo_fiscale = 0;
  945. $record->deleted = 0;
  946. $record->financial_movement = 1;
  947. $record->amount = $fatturaData['importoTotale'];
  948. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  949. $record->is_ricevuta = true;
  950. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  951. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  952. }
  953. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  954. $record->IBAN = $fatturaData['iban'];
  955. }
  956. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  957. $record->BIC = $fatturaData['bic'];
  958. }
  959. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  960. $record->data_scadenza = $fatturaData['dataScadenza'];
  961. }
  962. $record->save();
  963. Log::info("Record esistente aggiornato con ID: " . $record->id);
  964. return $record;
  965. }
  966. /**
  967. * Crea un record row per il record specificato
  968. */
  969. private function createRecordRow($recordId, $fatturaData)
  970. {
  971. Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
  972. $existingRows = \App\Models\RecordRow::where('record_id', $recordId)->get();
  973. // Delete existing rows if they exist
  974. if ($existingRows->count() > 0) {
  975. Log::info("Eliminazione di " . $existingRows->count() . " righe record esistenti per Record ID: " . $recordId);
  976. foreach ($existingRows as $row) {
  977. $row->delete();
  978. }
  979. }
  980. if (!empty($fatturaData['linee'])) {
  981. foreach ($fatturaData['linee'] as $linea) {
  982. $this->createSingleRecordRow($recordId, $fatturaData, $linea);
  983. }
  984. } else if ($fatturaData['riepilogo']) {
  985. $this->createRecordRowFromRiepilogo($recordId, $fatturaData);
  986. Log::info("Creata una riga di record dai dati di riepilogo");
  987. } else {
  988. $this->createDefaultRecordRow($recordId, $fatturaData);
  989. Log::info("Creata una riga di record predefinita dall'importo totale");
  990. }
  991. }
  992. private function createSingleRecordRow($recordId, $fatturaData, $linea)
  993. {
  994. Log::info("Inizio creazione riga record singola per Record ID: " . $recordId . ", Linea: " . json_encode($linea));
  995. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  996. $month = $dataObj->format('n');
  997. $year = $dataObj->format('Y');
  998. $period = "$month-$year";
  999. $whenData = [[
  1000. 'month' => $month,
  1001. 'year' => $year,
  1002. 'period' => $period
  1003. ]];
  1004. $recordRow = new \App\Models\RecordRow();
  1005. $recordRow->record_id = $recordId;
  1006. $recordRow->causal_id = $this->selectedCausal;
  1007. $recordRow->amount = $linea['prezzoTotale'] + $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  1008. $recordRow->note = $linea['descrizione'];
  1009. $recordRow->commercial = 1;
  1010. $recordRow->when = json_encode($whenData);
  1011. $recordRow->aliquota_iva = $linea['aliquotaIva'];
  1012. $recordRow->imponibile = $linea['prezzoTotale'];
  1013. $recordRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  1014. $recordRow->divisa = $fatturaData['divisa'];
  1015. $recordRow->numero_linea = $linea['numeroLinea'];
  1016. $recordRow->prezzo_unitario = $linea['prezzoUnitario'];
  1017. $recordRow->quantita = $linea['quantita'];
  1018. Log::info("Dati riga record prima del salvataggio: " . json_encode([
  1019. 'record_id' => $recordRow->record_id,
  1020. 'causal_id' => $recordRow->causal_id,
  1021. 'amount' => $recordRow->amount,
  1022. 'note' => $recordRow->note,
  1023. 'aliquota_iva' => $recordRow->aliquota_iva,
  1024. 'imponibile' => $recordRow->imponibile,
  1025. 'imposta' => $recordRow->imposta,
  1026. 'divisa' => $recordRow->divisa,
  1027. 'numero_linea' => $recordRow->numero_linea,
  1028. 'prezzo_unitario' => $recordRow->prezzo_unitario,
  1029. 'quantita' => $recordRow->quantita,
  1030. ]));
  1031. $recordRow->save();
  1032. Log::info("Riga record creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
  1033. }
  1034. private function createRecordRowFromRiepilogo($recordId, $fatturaData)
  1035. {
  1036. Log::info("Inizio creazione riga record da riepilogo per Record ID: " . $recordId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
  1037. $riepilogo = $fatturaData['riepilogo'];
  1038. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1039. $month = $dataObj->format('n');
  1040. $year = $dataObj->format('Y');
  1041. $period = "$month-$year";
  1042. $whenData = [[
  1043. 'month' => $month,
  1044. 'year' => $year,
  1045. 'period' => $period
  1046. ]];
  1047. $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
  1048. $recordRow = new \App\Models\RecordRow();
  1049. $recordRow->record_id = $recordId;
  1050. $recordRow->causal_id = $this->selectedCausal;
  1051. $recordRow->amount = $total_amount;
  1052. $recordRow->commercial = 1;
  1053. $recordRow->when = json_encode($whenData);
  1054. $recordRow->aliquota_iva = $riepilogo['aliquotaIva'];
  1055. $recordRow->imponibile = $riepilogo['imponibile'];
  1056. $recordRow->imposta = $riepilogo['imposta'];
  1057. $recordRow->divisa = $fatturaData['divisa'];
  1058. $recordRow->numero_linea = 1;
  1059. $recordRow->quantita = 1;
  1060. Log::info("Dati riga record da riepilogo prima del salvataggio: " . json_encode([
  1061. 'record_id' => $recordRow->record_id,
  1062. 'causal_id' => $recordRow->causal_id,
  1063. 'amount' => $recordRow->amount,
  1064. 'aliquota_iva' => $recordRow->aliquota_iva,
  1065. 'imponibile' => $recordRow->imponibile,
  1066. 'imposta' => $recordRow->imposta,
  1067. 'divisa' => $recordRow->divisa,
  1068. ]));
  1069. $recordRow->save();
  1070. Log::info("Riga record creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
  1071. }
  1072. private function createDefaultRecordRow($recordId, $fatturaData)
  1073. {
  1074. Log::info("Inizio creazione riga record predefinita per Record ID: " . $recordId . ", Importo Totale: " . $fatturaData['importoTotale']);
  1075. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1076. $month = $dataObj->format('n');
  1077. $year = $dataObj->format('Y');
  1078. $period = "$month-$year";
  1079. $whenData = [[
  1080. 'month' => $month,
  1081. 'year' => $year,
  1082. 'period' => $period
  1083. ]];
  1084. $recordRow = new \App\Models\RecordRow();
  1085. $recordRow->record_id = $recordId;
  1086. $recordRow->causal_id = $this->selectedCausal;
  1087. $recordRow->amount = $fatturaData['importoTotale'];
  1088. $recordRow->commercial = 1;
  1089. $recordRow->when = json_encode($whenData);
  1090. $recordRow->divisa = $fatturaData['divisa'];
  1091. $recordRow->numero_linea = 1;
  1092. $recordRow->quantita = 1;
  1093. Log::info("Dati riga record predefinita prima del salvataggio: " . json_encode([
  1094. 'record_id' => $recordRow->record_id,
  1095. 'causal_id' => $recordRow->causal_id,
  1096. 'amount' => $recordRow->amount,
  1097. 'divisa' => $recordRow->divisa,
  1098. ]));
  1099. $recordRow->save();
  1100. Log::info("Riga record predefinita creata con importo totale: {$fatturaData['importoTotale']}");
  1101. }
  1102. private function mapTipoDocumento($codice)
  1103. {
  1104. $tipiDocumento = [
  1105. 'TD01' => 'Fattura',
  1106. 'TD02' => 'Acconto/Anticipo su fattura',
  1107. 'TD03' => 'Acconto/Anticipo su parcella',
  1108. 'TD04' => 'Nota di credito',
  1109. 'TD05' => 'Nota di debito',
  1110. 'TD06' => 'Parcella',
  1111. 'TD16' => 'Integrazione fattura reverse charge interno',
  1112. 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
  1113. 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
  1114. 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
  1115. 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
  1116. 'TD21' => 'Autofattura per splafonamento',
  1117. 'TD22' => 'Estrazione beni da Deposito IVA',
  1118. 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
  1119. 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
  1120. 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
  1121. 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
  1122. 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
  1123. ];
  1124. return $tipiDocumento[$codice] ?? $codice;
  1125. }
  1126. private function mapCondizioniPagamento($codice)
  1127. {
  1128. $condizioniPagamento = [
  1129. 'TP01' => 'Pagamento a rate',
  1130. 'TP02' => 'Pagamento completo',
  1131. 'TP03' => 'Anticipo'
  1132. ];
  1133. return $condizioniPagamento[$codice] ?? $codice;
  1134. }
  1135. private function showResultMessages($importCount, $updateCount, $errorsCount, $importedFiles = [], $updatedFiles = [], $errorFiles = [], $errorMessages = [])
  1136. {
  1137. $message = "";
  1138. $messageType = "success";
  1139. if ($importCount > 0) {
  1140. $message .= "Importate correttamente n° $importCount nuove fatture.<br>";
  1141. if (!empty($importedFiles)) {
  1142. $message .= "<details><summary>File importati (clicca per espandere)</summary><ul>";
  1143. foreach ($importedFiles as $file) {
  1144. $message .= "<li>" . htmlspecialchars($file) . "</li>";
  1145. }
  1146. $message .= "</ul></details><br>";
  1147. }
  1148. }
  1149. if ($updateCount > 0) {
  1150. $message .= "Aggiornate n° $updateCount fatture perchè già presenti.<br>";
  1151. if (!empty($updatedFiles)) {
  1152. $message .= "<details><summary>File aggiornati (clicca per espandere)</summary><ul>";
  1153. foreach ($updatedFiles as $file) {
  1154. $message .= "<li>" . htmlspecialchars($file) . "</li>";
  1155. }
  1156. $message .= "</ul></details><br>";
  1157. }
  1158. }
  1159. if ($errorsCount > 0) {
  1160. $message .= "Importazione fallita per n° $errorsCount fatture.<br>";
  1161. // Aggiungi i dettagli degli errori se disponibili
  1162. if (!empty($errorFiles)) {
  1163. $message .= "<details><summary>File con errori (clicca per espandere)</summary><ul>";
  1164. foreach ($errorFiles as $index => $file) {
  1165. $errorMessage = isset($errorMessages[$index]) ? ': ' . preg_replace('/^Errore durante l\'importazione della fattura \([^)]+\):/', '', $errorMessages[$index]) : '';
  1166. $message .= "<li>" . htmlspecialchars($file) . $errorMessage . "</li>";
  1167. }
  1168. $message .= "</ul></details><br>";
  1169. }
  1170. if ($importCount == 0 && $updateCount == 0) {
  1171. $messageType = "error";
  1172. } else {
  1173. $messageType = "warning";
  1174. }
  1175. }
  1176. if ($importCount > 0 || $updateCount > 0 || $errorsCount > 0) {
  1177. $this->emit('show-import-result', [
  1178. 'message' => $message,
  1179. 'type' => $messageType
  1180. ]);
  1181. } else {
  1182. $this->emit('show-import-result', [
  1183. 'message' => 'Nessuna fattura importata. Controlla i file XML e riprova.',
  1184. 'type' => 'error'
  1185. ]);
  1186. }
  1187. // Resetta i campi del form dopo l'importazione
  1188. $this->reset(['receiptFiles']);
  1189. }
  1190. private function getFriendlyErrorMessage($errorMessage) {
  1191. // Errore di parsing XML iniziale
  1192. if (strpos($errorMessage, "simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found") !== false) {
  1193. return "Il file non è in formato valido. Potrebbe essere danneggiato o in un formato diverso.";
  1194. }
  1195. // Errore di struttura XML
  1196. if (strpos($errorMessage, "FatturaElettronicaHeader o FatturaElettronicaBody non trovati") !== false) {
  1197. return "Il file non sembra essere una fattura elettronica valida. Mancano le sezioni principali.";
  1198. }
  1199. // Altri errori comuni di parsing XML
  1200. if (strpos($errorMessage, "parser error") !== false) {
  1201. return "Il file XML contiene errori di formattazione e non può essere letto correttamente.";
  1202. }
  1203. // Errori di struttura interna
  1204. if (strpos($errorMessage, "Undefined index") !== false ||
  1205. strpos($errorMessage, "Trying to get property") !== false) {
  1206. return "La fattura è incompleta o non contiene tutti i dati necessari.";
  1207. }
  1208. // Per altri errori, conserva il messaggio originale ma semplificalo
  1209. return $errorMessage;
  1210. }
  1211. }