RecordOUT.php 58 KB

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