RecordOUT.php 53 KB

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