RecordOUT.php 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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. $this->validate();
  310. try {
  311. $record = \App\Models\Record::create([
  312. 'member_id' => $this->member_id,
  313. 'supplier_id' => $this->supplier_id,
  314. //'causal_id' => $this->causal_id,
  315. 'payment_method_id' => $this->payment_method_id,
  316. 'date' => $this->date,
  317. 'data_pagamento' => $this->data_pagamento,
  318. //'month' => $this->month,
  319. //'year' => $this->year,
  320. //'note' => $this->note,
  321. //'attachment' => $this->attachment,
  322. 'type' => $this->type,
  323. 'amount' => $this->currencyToDouble($this->amount),
  324. 'commercial' => $this->commercial,
  325. ]);
  326. $this->dataId = $record->id;
  327. $tot = 0;
  328. foreach ($this->rows as $row) {
  329. foreach ($row["when"] as $x => $y) {
  330. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  331. }
  332. $imponibile = isset($row["imponibile"]) ? $this->currencyToDouble($row["imponibile"]) : null;
  333. Log::info("Imponibile store: " . $imponibile);
  334. $aliquota_iva = isset($row["aliquota_iva"]) ? floatval(str_replace('%', '', $row["aliquota_iva"])) : null;
  335. Log::info("Aliquota IVA store: " . $aliquota_iva);
  336. \App\Models\RecordRow::create([
  337. 'record_id' => $this->dataId,
  338. 'causal_id' => $row["causal_id"],
  339. 'note' => $row["note"],
  340. 'amount' => $this->currencyToDouble($row["amount"]),
  341. 'imponibile' => $imponibile,
  342. 'aliquota_iva' => $aliquota_iva,
  343. 'commercial' => $row["commercial"],
  344. 'when' => json_encode($row["when"])
  345. ]);
  346. $tot += $this->currencyToDouble($row["amount"]);
  347. }
  348. $record->amount = $tot;
  349. $record->save();
  350. session()->flash('success', 'Movimento creato');
  351. $this->resetFields();
  352. $this->add = false;
  353. $this->emit('setEdit', false);
  354. } catch (\Exception $ex) {
  355. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  356. }
  357. }
  358. public function edit($id)
  359. {
  360. if (!isset($_GET["from"]) && $this->fromPage == '')
  361. $this->fromPage = 'out';
  362. $this->emit('setEdit', true);
  363. $this->emit('load-select');
  364. //if ($this->hasFilter)
  365. $this->emit('hide-search');
  366. try {
  367. $record = \App\Models\Record::findOrFail($id);
  368. if (!$record) {
  369. $this->emit('flash-error', 'Movimento non trovato');
  370. } else {
  371. $this->member_id = $record->member_id;
  372. $this->supplier_id = $record->supplier_id;
  373. //$this->causal_id = $record->causal_id;
  374. $this->payment_method_id = $record->payment_method_id;
  375. $this->date = date("Y-m-d", strtotime($record->date));
  376. $this->data_pagamento = date("Y-m-d", strtotime($record->data_pagamento));
  377. //$this->month = $record->month;
  378. //$this->year = $record->year;
  379. //$this->note = $record->note;
  380. $this->type = $record->type;
  381. //$attachment = $record->attachment;
  382. //$this->amount = formatPrice($record->amount);
  383. $this->commercial = $record->commercial;
  384. $this->dataId = $record->id;
  385. $this->update = true;
  386. $this->add = false;
  387. $this->rows = [];
  388. $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
  389. foreach ($recordRows as $recordRow) {
  390. $rowData = [
  391. 'causal_id' => $recordRow->causal_id,
  392. 'note' => $recordRow->note,
  393. 'commercial' => $recordRow->commercial,
  394. 'when' => json_decode($recordRow->when),
  395. 'amount' => formatPrice($recordRow->amount)
  396. ];
  397. // Add imponibile field if available in the database
  398. if (isset($recordRow->imponibile)) {
  399. $rowData['imponibile'] = formatPrice($recordRow->imponibile);
  400. }
  401. // Add aliquota_iva field if available in the database
  402. if (isset($recordRow->aliquota_iva)) {
  403. $rowData['aliquota_iva'] = $recordRow->aliquota_iva . '%';
  404. }
  405. $this->rows[] = $rowData;
  406. }
  407. }
  408. } catch (\Exception $ex) {
  409. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  410. }
  411. }
  412. public function update()
  413. {
  414. $this->emit('refresh');
  415. $this->validate();
  416. try {
  417. \App\Models\Record::whereId($this->dataId)->update([
  418. 'member_id' => $this->member_id,
  419. 'supplier_id' => $this->supplier_id,
  420. 'payment_method_id' => $this->payment_method_id,
  421. 'date' => $this->date,
  422. 'data_pagamento' => $this->data_pagamento,
  423. 'type' => $this->type,
  424. 'commercial' => $this->commercial,
  425. //'attachment' => $this->attachment,
  426. ]);
  427. $tot = 0;
  428. $existingRows = \App\Models\RecordRow::where('record_id', $this->dataId)
  429. ->select('id', 'quantita', 'numero_linea')
  430. ->get()
  431. ->keyBy('id')
  432. ->toArray();
  433. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  434. foreach ($this->rows as $row) {
  435. foreach ($row["when"] as $x => $y) {
  436. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  437. }
  438. $imponibile = null;
  439. if (isset($row["imponibile"]) && $row["imponibile"] !== null && $row["imponibile"] !== '') {
  440. $imponibile = $this->currencyToDouble($row["imponibile"]);
  441. Log::info("Imponibile: " . $imponibile);
  442. }
  443. $aliquota_iva = null;
  444. if (isset($row["aliquota_iva"]) && $row["aliquota_iva"] !== null && $row["aliquota_iva"] !== '') {
  445. $aliquota_iva = floatval(str_replace('%', '', $row["aliquota_iva"]));
  446. Log::info("Aliquota IVA: " . $aliquota_iva);
  447. }
  448. $amount = $this->currencyToDouble($row["amount"]);
  449. $imposta = null;
  450. if ($imponibile !== null) {
  451. $imposta = $amount - $imponibile;
  452. Log::info("Imposta calculated: " . $imposta);
  453. }
  454. $recordRowData = [
  455. 'record_id' => $this->dataId,
  456. 'causal_id' => $row["causal_id"],
  457. 'note' => $row["note"],
  458. 'amount' => $this->currencyToDouble($row["amount"]),
  459. 'commercial' => $row["commercial"],
  460. 'when' => json_encode($row["when"]),
  461. 'imponibile' => $imponibile,
  462. 'aliquota_iva' => $aliquota_iva,
  463. 'imposta' => $imposta,
  464. 'divisa' => 'EUR',
  465. ];
  466. if (isset($row["id"]) && isset($existingRows[$row["id"]])) {
  467. $existingRow = $existingRows[$row["id"]];
  468. $recordRowData['quantita'] = $existingRow['quantita'];
  469. $recordRowData['numero_linea'] = $existingRow['numero_linea'];
  470. }
  471. Log::info("RecordRowData: " . json_encode($recordRowData));
  472. \App\Models\RecordRow::create($recordRowData);
  473. $tot += $this->currencyToDouble($row["amount"]);
  474. }
  475. $rec = \App\Models\Record::findOrFail($this->dataId);
  476. $rec->amount = $tot;
  477. $rec->save();
  478. session()->flash('success', 'Movimento aggiornato');
  479. $this->resetFields();
  480. $this->update = false;
  481. $this->emit('setEdit', false);
  482. } catch (\Exception $ex) {
  483. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  484. }
  485. }
  486. public function cancel()
  487. {
  488. $this->add = false;
  489. $this->update = false;
  490. $this->emit('setEdit', false);
  491. $this->resetFields();
  492. }
  493. public function delete($id)
  494. {
  495. try {
  496. \App\Models\Record::find($id)->delete();
  497. session()->flash('success', "Movimento eliminato");
  498. } catch (\Exception $e) {
  499. $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
  500. }
  501. }
  502. public function multipleDelete()
  503. {
  504. try {
  505. foreach ($this->multipleIds as $id) {
  506. \App\Models\Record::find($id)->delete();
  507. }
  508. } catch (\Exception $e) {
  509. $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
  510. }
  511. $this->multipleAction = '';
  512. }
  513. function currencyToDouble($val)
  514. {
  515. $x = str_replace("€", "", $val);
  516. $x = str_replace(".", "", $x);
  517. $x = str_replace(",", ".", $x);
  518. return floatval(trim($x));
  519. }
  520. public function addRow()
  521. {
  522. $this->rows[] = array(
  523. 'causal_id' => null,
  524. 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
  525. 'amount' => null,
  526. 'imponibile' => null,
  527. 'aliquota_iva' => null,
  528. 'note' => '',
  529. 'commercial' => 0
  530. );
  531. $this->emit('load-select');
  532. }
  533. public function delRow($idx)
  534. {
  535. unset($this->rows[$idx]);
  536. // $this->emit('load-select');
  537. }
  538. public function addPeriod($idx)
  539. {
  540. $x = sizeof($this->rows[$idx]['when']) - 1;
  541. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  542. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  543. //$this->rows[$idx]['when'][] = array('month' => date("n"), 'year' => date("Y"), 'period' => '');
  544. }
  545. public function delPeriod($idx, $xxx)
  546. {
  547. array_splice($this->rows[$idx]['when'], $xxx, 1);
  548. // $this->emit('load-select');
  549. }
  550. public function getTotal()
  551. {
  552. $total = 0.00;
  553. foreach ($this->rows as $r) {
  554. $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
  555. }
  556. return formatPrice($total);
  557. // $this->emit('load-select');
  558. }
  559. public function setCausal($id, $idx)
  560. {
  561. $this->rows[$idx]["causal_id"] = $id;
  562. }
  563. public function multiPeriod()
  564. {
  565. $this->multiP = true;
  566. }
  567. public function multiPeriodCreate($idx)
  568. {
  569. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  570. $this->rows[$idx]['when'] = [];
  571. foreach ($period as $dt) {
  572. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  573. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  574. }
  575. $this->multiP = false;
  576. }
  577. public function multiPeriodCancel()
  578. {
  579. $this->multiP = false;
  580. }
  581. public function importReceipts()
  582. {
  583. $this->validate([
  584. //'receiptFiles.*' => 'required|mimes:xml|max:2048',
  585. 'selectedCausal' => 'required|exists:causals,id',
  586. ]);
  587. Log::info("Importazione ricevute: " . json_encode($this->receiptFiles));
  588. try {
  589. $importCount = 0;
  590. $updateCount = 0;
  591. $errorsCount = 0;
  592. $errorMessages = [];
  593. $importedFiles = [];
  594. $updatedFiles = [];
  595. $errorFiles = [];
  596. $totalFiles = count($this->receiptFiles);
  597. // disabilita select
  598. $this->emit('import-started');
  599. Log::info("Import iniziato");
  600. foreach ($this->receiptFiles as $index => $receiptFile) {
  601. try {
  602. $fileName = $receiptFile->getClientOriginalName();
  603. Log::info("Elaborazione file: " . $fileName);
  604. // Carica e analizza il file XML
  605. $xmlString = file_get_contents($receiptFile->getRealPath());
  606. $xml = simplexml_load_string($xmlString);
  607. if (empty($xmlString)) {
  608. throw new \Exception("Il file è vuoto.");
  609. }
  610. // Verifica se il file sembra essere un XML
  611. if (strpos($xmlString, '<?xml') === false && strpos($xmlString, '<') === false) {
  612. throw new \Exception("Il file non sembra essere in formato XML.");
  613. }
  614. $xml = simplexml_load_string($xmlString);
  615. if (!$xml) {
  616. throw new \Exception("Impossibile analizzare il file XML");
  617. }
  618. // Estrai i dati dalla fattura elettronica
  619. $fatturaData = $this->extractFatturaData($xml);
  620. // Trova o crea il fornitorez
  621. $supplier = $this->findOrCreateSupplier($fatturaData);
  622. // Trova il metodo di pagamento
  623. $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
  624. // Crea il record principale
  625. $isUpdate = false;
  626. $existingRecord = \App\Models\Record::where('supplier_id', $supplier->id)
  627. ->where('numero_fattura', $fatturaData['numeroFattura'])
  628. ->first();
  629. if ($existingRecord) {
  630. $record = $this->updateRecord($existingRecord, $paymentMethodId, $fatturaData);
  631. $isUpdate = true;
  632. $updateCount++;
  633. $updatedFiles[] = $fileName; // Aggiungiamo il nome del file alla lista degli aggiornati
  634. Log::info("Fattura aggiornata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  635. } else {
  636. // Crea un nuovo record
  637. $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
  638. $importCount++;
  639. $importedFiles[] = $fileName; // Aggiungiamo il nome del file alla lista degli importati
  640. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  641. }
  642. // Crea il record row
  643. $this->createRecordRow($record->id, $fatturaData);
  644. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']} OR {$fatturaData['cognome']}, {$fatturaData['nome']}");
  645. } catch (\Exception $e) {
  646. $errorMsg = $e->getMessage();
  647. $friendlyErrorMsg = $this->getFriendlyErrorMessage($errorMsg);
  648. Log::error("Errore originale: " . $errorMsg);
  649. $errorMessages[] = $friendlyErrorMsg;
  650. $errorFiles[] = $fileName;
  651. $errorsCount++;
  652. }
  653. $progress = ($index + 1) / $totalFiles * 100;
  654. $this->emit('update-progress', $progress);
  655. }
  656. $this->showResultMessages($importCount, $updateCount, $errorsCount, $importedFiles, $updatedFiles, $errorFiles, $errorMessages);
  657. } catch (\Exception $e) {
  658. $errorMsg = 'Errore durante l\'importazione dei file XML: ' . $e->getMessage();
  659. Log::error($errorMsg);
  660. $this->emit('show-import-result', [
  661. 'message' => $errorMsg,
  662. 'type' => 'error'
  663. ]);
  664. } finally {
  665. $this->emit('load-data-table');
  666. }
  667. }
  668. /**
  669. * Estrae i dati dalla fattura elettronica XML
  670. */
  671. private function extractFatturaData($xml)
  672. {
  673. $data = [];
  674. try {
  675. // Stampa la struttura XML per debug
  676. Log::info("Nomi dei children dell'elemento radice: " . implode(", ", array_map(function ($node) {
  677. return $node->getName();
  678. }, iterator_to_array($xml->children()))));
  679. $headerNode = $xml->FatturaElettronicaHeader;
  680. $bodyNode = $xml->FatturaElettronicaBody;
  681. if (!$headerNode || !$bodyNode) {
  682. throw new \Exception("Struttura XML non standard, FatturaElettronicaHeader o FatturaElettronicaBody non trovati");
  683. }
  684. // Estrai dati del fornitore (cedente/prestatore)
  685. $cedenteNode = $headerNode->CedentePrestatore;
  686. $datiAnagrafici = $cedenteNode->DatiAnagrafici;
  687. $idFiscaleIVA = $datiAnagrafici->IdFiscaleIVA;
  688. $data['idPaese'] = (string)$idFiscaleIVA->IdPaese;
  689. $data['idCodice'] = (string)$idFiscaleIVA->IdCodice;
  690. $data['partitaIva'] = $data['idPaese'] . $data['idCodice'];
  691. $data['codiceFiscale'] = (string)$datiAnagrafici->CodiceFiscale;
  692. $data['denominazione'] = (string)$datiAnagrafici->Anagrafica->Denominazione;
  693. $data['cognome'] = (string)$datiAnagrafici->Anagrafica->Cognome;
  694. $data['nome'] = (string)$datiAnagrafici->Anagrafica->Nome;
  695. // Estrai dati della sede
  696. $sede = $cedenteNode->Sede;
  697. $data['indirizzo'] = (string)$sede->Indirizzo;
  698. $data['cap'] = (string)$sede->CAP;
  699. $data['comune'] = (string)$sede->Comune;
  700. $data['provincia'] = (string)$sede->Provincia;
  701. $data['nazione'] = (string)$sede->Nazione ?: 'IT';
  702. // Email, se presente
  703. $data['email'] = '';
  704. if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
  705. $data['email'] = (string)$cedenteNode->Contatti->Email;
  706. }
  707. // Dati generali della fattura
  708. $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
  709. $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
  710. $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
  711. $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
  712. $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
  713. $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
  714. // Dati di pagamento
  715. $data['condizioniPagamento'] = '';
  716. $data['modalitaPagamento'] = '';
  717. $data['dataScadenza'] = '';
  718. $data['iban'] = '';
  719. $data['bic'] = '';
  720. $data['istitutoFinanziario'] = '';
  721. if (isset($bodyNode->DatiPagamento)) {
  722. $datiPagamento = $bodyNode->DatiPagamento;
  723. $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
  724. if (isset($datiPagamento->DettaglioPagamento)) {
  725. $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
  726. $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
  727. $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
  728. $data['iban'] = (string)$dettaglioPagamento->IBAN;
  729. $data['bic'] = (string)$dettaglioPagamento->BIC;
  730. $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
  731. }
  732. }
  733. // Estrai le linee di dettaglio
  734. $data['linee'] = [];
  735. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
  736. foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
  737. if (isset($linea->Quantita)) {
  738. $lineaData = [
  739. 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
  740. 'descrizione' => (string)($linea->Descrizione ?? ''),
  741. 'quantita' => (float)($linea->Quantita ?? 1),
  742. 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
  743. 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
  744. 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
  745. ];
  746. // Calcola il prezzo totale se non presente
  747. if ($lineaData['prezzoTotale'] == 0) {
  748. $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
  749. }
  750. $data['linee'][] = $lineaData;
  751. } else {
  752. // Se la linea ha un campo Quantita, non la consideriamo
  753. Log::info("Linea con Quantita non considerata: " . json_encode($linea));
  754. }
  755. }
  756. }
  757. $data['riepilogo'] = null;
  758. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
  759. $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
  760. if ($riepilogoNode) {
  761. $data['riepilogo'] = [
  762. 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
  763. 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
  764. 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
  765. ];
  766. }
  767. }
  768. 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']}");
  769. return $data;
  770. } catch (\Exception $e) {
  771. Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
  772. throw $e;
  773. }
  774. }
  775. /**
  776. * Trova o crea un fornitore basato sui dati della fattura
  777. */
  778. private function findOrCreateSupplier($fatturaData)
  779. {
  780. $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
  781. if (!$supplier) {
  782. Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']}) OR ({$fatturaData['nome']}), ({$fatturaData['cognome']})");
  783. $countryId = $this->getCountryId($fatturaData['nazione']);
  784. $provinceId = $this->getProvinceId($fatturaData['provincia']);
  785. $cityId = $this->getCityId($fatturaData['comune']);
  786. $supplier = new \App\Models\Supplier();
  787. $supplier->name = $fatturaData['denominazione'] ?: $fatturaData['cognome'] . ' ' . $fatturaData['nome'];
  788. Log::info("Nome fornitore: " . $supplier->name);
  789. $supplier->vat = $fatturaData['partitaIva'];
  790. $supplier->fiscal_code = $fatturaData['codiceFiscale'];
  791. $supplier->address = $fatturaData['indirizzo'];
  792. $supplier->city_id = $cityId;
  793. $supplier->zip_code = $fatturaData['cap'];
  794. $supplier->province_id = $provinceId;
  795. $supplier->nation_id = $countryId;
  796. $supplier->email = $fatturaData['email'];
  797. $supplier->save();
  798. Log::info("Fornitore creato con ID: " . $supplier->id);
  799. }
  800. return $supplier;
  801. }
  802. /**
  803. * Trova l'ID della nazione dal codice
  804. */
  805. private function getCountryId($nationCode)
  806. {
  807. $country = DB::table('nations')->where('code', $nationCode)->first();
  808. return $country ? $country->id : null;
  809. }
  810. /**
  811. * Trova l'ID della provincia dal codice
  812. */
  813. private function getProvinceId($provinceCode)
  814. {
  815. $province = DB::table('provinces')->where('code', $provinceCode)->first();
  816. return $province ? $province->id : null;
  817. }
  818. /**
  819. * Trova l'ID della città dal nome
  820. */
  821. private function getCityId($cityName)
  822. {
  823. if (empty($cityName)) return null;
  824. $city = DB::table('cities')->where('name', $cityName)->first();
  825. return $city ? $city->id : null;
  826. }
  827. /**
  828. * Trova l'ID del metodo di pagamento dal codice
  829. */
  830. private function findPaymentMethod($paymentCode)
  831. {
  832. if (!empty($paymentCode)) {
  833. $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
  834. if ($paymentMethod) {
  835. Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
  836. return $paymentMethod->id;
  837. }
  838. }
  839. // Cerca il metodo di pagamento predefinito - corretto per evitare l'errore della colonna 'default'
  840. // Verifica se esiste una colonna 'is_default' o simile
  841. $possibleDefaultColumns = ['is_default', 'is_default_method', 'default_method', 'primary'];
  842. $defaultPaymentMethod = null;
  843. foreach ($possibleDefaultColumns as $column) {
  844. if (Schema::hasColumn('payment_methods', $column)) {
  845. $defaultPaymentMethod = DB::table('payment_methods')->where($column, 1)->first();
  846. if ($defaultPaymentMethod) {
  847. Log::info("Usando metodo di pagamento predefinito (colonna $column) ID: {$defaultPaymentMethod->id}");
  848. break;
  849. }
  850. }
  851. }
  852. // Se non è stato trovato un metodo predefinito, prendi il primo disponibile
  853. if (!$defaultPaymentMethod) {
  854. $defaultPaymentMethod = DB::table('payment_methods')->first();
  855. if ($defaultPaymentMethod) {
  856. Log::info("Usando il primo metodo di pagamento disponibile ID: {$defaultPaymentMethod->id}");
  857. }
  858. }
  859. if ($defaultPaymentMethod) {
  860. return $defaultPaymentMethod->id;
  861. }
  862. throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
  863. }
  864. /**
  865. * Crea un record nella tabella records
  866. */
  867. private function createRecord($supplierId, $paymentMethodId, $fatturaData)
  868. {
  869. $record = new \App\Models\Record();
  870. $record->supplier_id = $supplierId;
  871. $record->payment_method_id = $paymentMethodId;
  872. $record->date = $fatturaData['dataDocumento'];
  873. $record->data_pagamento = $fatturaData['dataDocumento'];
  874. $record->numero_fattura = $fatturaData['numeroFattura'];
  875. $record->type = 'OUT';
  876. $record->commercial = 1;
  877. $record->corrispettivo_fiscale = 0;
  878. $record->deleted = 0;
  879. $record->financial_movement = 1;
  880. $record->amount = $fatturaData['importoTotale'];
  881. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  882. $record->is_ricevuta = true;
  883. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  884. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  885. }
  886. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  887. $record->IBAN = $fatturaData['iban'];
  888. }
  889. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  890. $record->BIC = $fatturaData['bic'];
  891. }
  892. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  893. $record->data_scadenza = $fatturaData['dataScadenza'];
  894. }
  895. $record->save();
  896. Log::info("Nuovo record creato con ID: " . $record->id);
  897. return $record;
  898. }
  899. /**
  900. * Aggiorna un record esistente nella tabella records
  901. */
  902. private function updateRecord($record, $paymentMethodId, $fatturaData)
  903. {
  904. $record->payment_method_id = $paymentMethodId;
  905. $record->date = $fatturaData['dataDocumento'];
  906. $record->data_pagamento = $fatturaData['dataDocumento'];
  907. $record->type = 'OUT';
  908. $record->commercial = 1;
  909. $record->corrispettivo_fiscale = 0;
  910. $record->deleted = 0;
  911. $record->financial_movement = 1;
  912. $record->amount = $fatturaData['importoTotale'];
  913. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  914. $record->is_ricevuta = true;
  915. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  916. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  917. }
  918. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  919. $record->IBAN = $fatturaData['iban'];
  920. }
  921. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  922. $record->BIC = $fatturaData['bic'];
  923. }
  924. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  925. $record->data_scadenza = $fatturaData['dataScadenza'];
  926. }
  927. $record->save();
  928. Log::info("Record esistente aggiornato con ID: " . $record->id);
  929. return $record;
  930. }
  931. /**
  932. * Crea un record row per il record specificato
  933. */
  934. private function createRecordRow($recordId, $fatturaData)
  935. {
  936. Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
  937. $existingRows = \App\Models\RecordRow::where('record_id', $recordId)->get();
  938. // Delete existing rows if they exist
  939. if ($existingRows->count() > 0) {
  940. Log::info("Eliminazione di " . $existingRows->count() . " righe record esistenti per Record ID: " . $recordId);
  941. foreach ($existingRows as $row) {
  942. $row->delete();
  943. }
  944. }
  945. if (!empty($fatturaData['linee'])) {
  946. foreach ($fatturaData['linee'] as $linea) {
  947. $this->createSingleRecordRow($recordId, $fatturaData, $linea);
  948. }
  949. } else if ($fatturaData['riepilogo']) {
  950. $this->createRecordRowFromRiepilogo($recordId, $fatturaData);
  951. Log::info("Creata una riga di record dai dati di riepilogo");
  952. } else {
  953. $this->createDefaultRecordRow($recordId, $fatturaData);
  954. Log::info("Creata una riga di record predefinita dall'importo totale");
  955. }
  956. }
  957. private function createSingleRecordRow($recordId, $fatturaData, $linea)
  958. {
  959. Log::info("Inizio creazione riga record singola per Record ID: " . $recordId . ", Linea: " . json_encode($linea));
  960. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  961. $month = $dataObj->format('n');
  962. $year = $dataObj->format('Y');
  963. $period = "$month-$year";
  964. $whenData = [[
  965. 'month' => $month,
  966. 'year' => $year,
  967. 'period' => $period
  968. ]];
  969. $recordRow = new \App\Models\RecordRow();
  970. $recordRow->record_id = $recordId;
  971. $recordRow->causal_id = $this->selectedCausal;
  972. $recordRow->amount = $linea['prezzoTotale'] + $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  973. $recordRow->note = $linea['descrizione'];
  974. $recordRow->commercial = 1;
  975. $recordRow->when = json_encode($whenData);
  976. $recordRow->aliquota_iva = $linea['aliquotaIva'];
  977. $recordRow->imponibile = $linea['prezzoTotale'];
  978. $recordRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  979. $recordRow->divisa = $fatturaData['divisa'];
  980. $recordRow->numero_linea = $linea['numeroLinea'];
  981. $recordRow->prezzo_unitario = $linea['prezzoUnitario'];
  982. $recordRow->quantita = $linea['quantita'];
  983. Log::info("Dati riga record prima del salvataggio: " . json_encode([
  984. 'record_id' => $recordRow->record_id,
  985. 'causal_id' => $recordRow->causal_id,
  986. 'amount' => $recordRow->amount,
  987. 'note' => $recordRow->note,
  988. 'aliquota_iva' => $recordRow->aliquota_iva,
  989. 'imponibile' => $recordRow->imponibile,
  990. 'imposta' => $recordRow->imposta,
  991. 'divisa' => $recordRow->divisa,
  992. 'numero_linea' => $recordRow->numero_linea,
  993. 'prezzo_unitario' => $recordRow->prezzo_unitario,
  994. 'quantita' => $recordRow->quantita,
  995. ]));
  996. $recordRow->save();
  997. Log::info("Riga record creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
  998. }
  999. private function createRecordRowFromRiepilogo($recordId, $fatturaData)
  1000. {
  1001. Log::info("Inizio creazione riga record da riepilogo per Record ID: " . $recordId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
  1002. $riepilogo = $fatturaData['riepilogo'];
  1003. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1004. $month = $dataObj->format('n');
  1005. $year = $dataObj->format('Y');
  1006. $period = "$month-$year";
  1007. $whenData = [[
  1008. 'month' => $month,
  1009. 'year' => $year,
  1010. 'period' => $period
  1011. ]];
  1012. $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
  1013. $recordRow = new \App\Models\RecordRow();
  1014. $recordRow->record_id = $recordId;
  1015. $recordRow->causal_id = $this->selectedCausal;
  1016. $recordRow->amount = $total_amount;
  1017. $recordRow->commercial = 1;
  1018. $recordRow->when = json_encode($whenData);
  1019. $recordRow->aliquota_iva = $riepilogo['aliquotaIva'];
  1020. $recordRow->imponibile = $riepilogo['imponibile'];
  1021. $recordRow->imposta = $riepilogo['imposta'];
  1022. $recordRow->divisa = $fatturaData['divisa'];
  1023. $recordRow->numero_linea = 1;
  1024. $recordRow->quantita = 1;
  1025. Log::info("Dati riga record da riepilogo prima del salvataggio: " . json_encode([
  1026. 'record_id' => $recordRow->record_id,
  1027. 'causal_id' => $recordRow->causal_id,
  1028. 'amount' => $recordRow->amount,
  1029. 'aliquota_iva' => $recordRow->aliquota_iva,
  1030. 'imponibile' => $recordRow->imponibile,
  1031. 'imposta' => $recordRow->imposta,
  1032. 'divisa' => $recordRow->divisa,
  1033. ]));
  1034. $recordRow->save();
  1035. Log::info("Riga record creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
  1036. }
  1037. private function createDefaultRecordRow($recordId, $fatturaData)
  1038. {
  1039. Log::info("Inizio creazione riga record predefinita per Record ID: " . $recordId . ", Importo Totale: " . $fatturaData['importoTotale']);
  1040. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1041. $month = $dataObj->format('n');
  1042. $year = $dataObj->format('Y');
  1043. $period = "$month-$year";
  1044. $whenData = [[
  1045. 'month' => $month,
  1046. 'year' => $year,
  1047. 'period' => $period
  1048. ]];
  1049. $recordRow = new \App\Models\RecordRow();
  1050. $recordRow->record_id = $recordId;
  1051. $recordRow->causal_id = $this->selectedCausal;
  1052. $recordRow->amount = $fatturaData['importoTotale'];
  1053. $recordRow->commercial = 1;
  1054. $recordRow->when = json_encode($whenData);
  1055. $recordRow->divisa = $fatturaData['divisa'];
  1056. $recordRow->numero_linea = 1;
  1057. $recordRow->quantita = 1;
  1058. Log::info("Dati riga record predefinita prima del salvataggio: " . json_encode([
  1059. 'record_id' => $recordRow->record_id,
  1060. 'causal_id' => $recordRow->causal_id,
  1061. 'amount' => $recordRow->amount,
  1062. 'divisa' => $recordRow->divisa,
  1063. ]));
  1064. $recordRow->save();
  1065. Log::info("Riga record predefinita creata con importo totale: {$fatturaData['importoTotale']}");
  1066. }
  1067. private function mapTipoDocumento($codice)
  1068. {
  1069. $tipiDocumento = [
  1070. 'TD01' => 'Fattura',
  1071. 'TD02' => 'Acconto/Anticipo su fattura',
  1072. 'TD03' => 'Acconto/Anticipo su parcella',
  1073. 'TD04' => 'Nota di credito',
  1074. 'TD05' => 'Nota di debito',
  1075. 'TD06' => 'Parcella',
  1076. 'TD16' => 'Integrazione fattura reverse charge interno',
  1077. 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
  1078. 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
  1079. 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
  1080. 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
  1081. 'TD21' => 'Autofattura per splafonamento',
  1082. 'TD22' => 'Estrazione beni da Deposito IVA',
  1083. 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
  1084. 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
  1085. 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
  1086. 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
  1087. 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
  1088. ];
  1089. return $tipiDocumento[$codice] ?? $codice;
  1090. }
  1091. private function mapCondizioniPagamento($codice)
  1092. {
  1093. $condizioniPagamento = [
  1094. 'TP01' => 'Pagamento a rate',
  1095. 'TP02' => 'Pagamento completo',
  1096. 'TP03' => 'Anticipo'
  1097. ];
  1098. return $condizioniPagamento[$codice] ?? $codice;
  1099. }
  1100. private function showResultMessages($importCount, $updateCount, $errorsCount, $importedFiles = [], $updatedFiles = [], $errorFiles = [], $errorMessages = [])
  1101. {
  1102. $message = "";
  1103. $messageType = "success";
  1104. if ($importCount > 0) {
  1105. $message .= "Importate correttamente n° $importCount nuove fatture.<br>";
  1106. if (!empty($importedFiles)) {
  1107. $message .= "<details><summary>File importati (clicca per espandere)</summary><ul>";
  1108. foreach ($importedFiles as $file) {
  1109. $message .= "<li>" . htmlspecialchars($file) . "</li>";
  1110. }
  1111. $message .= "</ul></details><br>";
  1112. }
  1113. }
  1114. if ($updateCount > 0) {
  1115. $message .= "Aggiornate n° $updateCount fatture perchè già presenti.<br>";
  1116. if (!empty($updatedFiles)) {
  1117. $message .= "<details><summary>File aggiornati (clicca per espandere)</summary><ul>";
  1118. foreach ($updatedFiles as $file) {
  1119. $message .= "<li>" . htmlspecialchars($file) . "</li>";
  1120. }
  1121. $message .= "</ul></details><br>";
  1122. }
  1123. }
  1124. if ($errorsCount > 0) {
  1125. $message .= "Importazione fallita per n° $errorsCount fatture.<br>";
  1126. // Aggiungi i dettagli degli errori se disponibili
  1127. if (!empty($errorFiles)) {
  1128. $message .= "<details><summary>File con errori (clicca per espandere)</summary><ul>";
  1129. foreach ($errorFiles as $index => $file) {
  1130. $errorMessage = isset($errorMessages[$index]) ? ': ' . preg_replace('/^Errore durante l\'importazione della fattura \([^)]+\):/', '', $errorMessages[$index]) : '';
  1131. $message .= "<li>" . htmlspecialchars($file) . $errorMessage . "</li>";
  1132. }
  1133. $message .= "</ul></details><br>";
  1134. }
  1135. if ($importCount == 0 && $updateCount == 0) {
  1136. $messageType = "error";
  1137. } else {
  1138. $messageType = "warning";
  1139. }
  1140. }
  1141. if ($importCount > 0 || $updateCount > 0 || $errorsCount > 0) {
  1142. $this->emit('show-import-result', [
  1143. 'message' => $message,
  1144. 'type' => $messageType
  1145. ]);
  1146. } else {
  1147. $this->emit('show-import-result', [
  1148. 'message' => 'Nessuna fattura importata. Controlla i file XML e riprova.',
  1149. 'type' => 'error'
  1150. ]);
  1151. }
  1152. // Resetta i campi del form dopo l'importazione
  1153. $this->reset(['receiptFiles']);
  1154. }
  1155. private function getFriendlyErrorMessage($errorMessage) {
  1156. // Errore di parsing XML iniziale
  1157. if (strpos($errorMessage, "simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found") !== false) {
  1158. return "Il file non è in formato valido. Potrebbe essere danneggiato o in un formato diverso.";
  1159. }
  1160. // Errore di struttura XML
  1161. if (strpos($errorMessage, "FatturaElettronicaHeader o FatturaElettronicaBody non trovati") !== false) {
  1162. return "Il file non sembra essere una fattura elettronica valida. Mancano le sezioni principali.";
  1163. }
  1164. // Altri errori comuni di parsing XML
  1165. if (strpos($errorMessage, "parser error") !== false) {
  1166. return "Il file XML contiene errori di formattazione e non può essere letto correttamente.";
  1167. }
  1168. // Errori di struttura interna
  1169. if (strpos($errorMessage, "Undefined index") !== false ||
  1170. strpos($errorMessage, "Trying to get property") !== false) {
  1171. return "La fattura è incompleta o non contiene tutti i dati necessari.";
  1172. }
  1173. // Per altri errori, conserva il messaggio originale ma semplificalo
  1174. return $errorMessage;
  1175. }
  1176. }