RecordOUT.php 52 KB

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