RecordOUT.php 61 KB

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