RecordOUT.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  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. // DEBUG: Check if we have an attachment
  324. Log::info("STORE DEBUG - Has attachment?: " . ($this->attachment ? 'YES' : 'NO'));
  325. if ($this->attachment) {
  326. Log::info("STORE DEBUG - Attachment original name: " . $this->attachment->getClientOriginalName());
  327. }
  328. // Create the record first WITHOUT attachment
  329. $record = \App\Models\Record::create([
  330. 'member_id' => $this->member_id,
  331. 'supplier_id' => $this->supplier_id,
  332. 'payment_method_id' => $this->payment_method_id,
  333. 'date' => $this->date,
  334. 'data_pagamento' => $this->data_pagamento,
  335. 'attachment' => '', // Empty initially
  336. 'type' => $this->type,
  337. 'amount' => $this->currencyToDouble($this->amount),
  338. 'commercial' => $this->commercial,
  339. 'numero_fattura' => $this->numero_fattura,
  340. 'is_paid' => $is_paid,
  341. ]);
  342. Log::info("STORE DEBUG - Record created with ID: " . $record->id);
  343. $this->dataId = $record->id;
  344. // Create record folders after record is created
  345. $this->recordFileService->createRecordFolders($record->id, 'OUT');
  346. Log::info("STORE DEBUG - Folders created for record ID: " . $record->id);
  347. // Now handle attachment upload if exists
  348. if ($this->attachment) {
  349. try {
  350. Log::info("STORE DEBUG - Starting attachment upload...");
  351. $attachmentPath = $this->recordFileService->uploadAttachment($this->attachment, $record->id, 'OUT');
  352. Log::info("STORE DEBUG - Attachment uploaded to path: " . $attachmentPath);
  353. // Use DB query builder instead of model update to ensure it works
  354. $updateResult = \DB::table('records')
  355. ->where('id', $record->id)
  356. ->update(['attachment' => $attachmentPath]);
  357. Log::info("STORE DEBUG - DB update result: " . ($updateResult ? 'SUCCESS' : 'FAILED'));
  358. // Verify the update worked by fetching fresh from database
  359. $updatedRecord = \App\Models\Record::where('id', $record->id)->first();
  360. Log::info("STORE DEBUG - Verified attachment in DB: '" . $updatedRecord->attachment . "'");
  361. // Also refresh the model instance
  362. $record->refresh();
  363. Log::info("STORE DEBUG - Model after refresh: '" . $record->attachment . "'");
  364. Log::info("Attachment uploaded and record updated: " . $attachmentPath);
  365. } catch (\Exception $ex) {
  366. Log::error("STORE ERROR - Error uploading attachment: " . $ex->getMessage());
  367. Log::error("STORE ERROR - Exception trace: " . $ex->getTraceAsString());
  368. session()->flash('warning', 'Record created but attachment upload failed: ' . $ex->getMessage());
  369. }
  370. } else {
  371. Log::info("STORE DEBUG - No attachment to upload");
  372. }
  373. // Create record rows
  374. $tot = 0;
  375. foreach ($this->rows as $row) {
  376. foreach ($row["when"] as $x => $y) {
  377. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  378. }
  379. $imponibile = isset($row["imponibile"]) ? $this->currencyToDouble($row["imponibile"]) : null;
  380. $aliquota_iva = isset($row["aliquota_iva"]) ? floatval(str_replace('%', '', $row["aliquota_iva"])) : null;
  381. \App\Models\RecordRow::create([
  382. 'record_id' => $this->dataId,
  383. 'causal_id' => $row["causal_id"],
  384. 'note' => $row["note"],
  385. 'amount' => $this->currencyToDouble($row["amount"]),
  386. 'imponibile' => $imponibile,
  387. 'aliquota_iva' => $aliquota_iva,
  388. 'commercial' => $row["commercial"],
  389. 'when' => json_encode($row["when"])
  390. ]);
  391. $tot += $this->currencyToDouble($row["amount"]);
  392. }
  393. // Update final amount
  394. $record->amount = $tot;
  395. $record->save();
  396. session()->flash('success', 'Movimento creato');
  397. $this->resetFields();
  398. $this->add = false;
  399. $this->emit('setEdit', false);
  400. } catch (\Exception $ex) {
  401. Log::error("STORE ERROR - General error: " . $ex->getMessage());
  402. Log::error("STORE ERROR - Exception trace: " . $ex->getTraceAsString());
  403. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  404. }
  405. }
  406. public function setDataPagamentoAttribute($value)
  407. {
  408. if (empty($value) || $value == '1970-01-01' || $value == '0000-00-00') {
  409. $this->attributes['data_pagamento'] = null;
  410. } else {
  411. $this->attributes['data_pagamento'] = $value;
  412. }
  413. }
  414. public function getDataPagamentoAttribute($value)
  415. {
  416. if ($value == '1970-01-01' || $value == '0000-00-00') {
  417. return null;
  418. }
  419. return $value;
  420. }
  421. public function edit($id)
  422. {
  423. if (!isset($_GET["from"]) && $this->fromPage == '')
  424. $this->fromPage = 'out';
  425. $this->emit('setEdit', true);
  426. $this->emit('load-select');
  427. $this->emit('hide-search');
  428. try {
  429. $record = \App\Models\Record::findOrFail($id);
  430. if (!$record) {
  431. $this->emit('flash-error', 'Movimento non trovato');
  432. } else {
  433. // DEBUG: Let's see what's in the database
  434. Log::info("EDIT DEBUG - Record ID: {$record->id}");
  435. Log::info("EDIT DEBUG - Database attachment value: '" . $record->attachment . "'");
  436. Log::info("EDIT DEBUG - Database attachment type: " . gettype($record->attachment));
  437. Log::info("EDIT DEBUG - Is attachment empty?: " . (empty($record->attachment) ? 'YES' : 'NO'));
  438. Log::info("EDIT DEBUG - Is attachment null?: " . (is_null($record->attachment) ? 'YES' : 'NO'));
  439. $this->member_id = $record->member_id;
  440. $this->supplier_id = $record->supplier_id;
  441. $this->payment_method_id = $record->payment_method_id;
  442. $this->date = date("Y-m-d", strtotime($record->date));
  443. $this->data_pagamento = $record->data_pagamento;
  444. $this->type = $record->type;
  445. $this->numero_fattura = $record->numero_fattura;
  446. // Set attachment_old - handle different cases
  447. if (!empty($record->attachment) && $record->attachment !== null && $record->attachment !== '') {
  448. $this->attachment_old = $record->attachment;
  449. Log::info("EDIT DEBUG - Setting attachment_old to: '" . $this->attachment_old . "'");
  450. } else {
  451. $this->attachment_old = '';
  452. Log::info("EDIT DEBUG - Setting attachment_old to empty string");
  453. }
  454. $this->attachment = null; // Clear any temporary attachment
  455. $this->commercial = $record->commercial;
  456. $this->dataId = $record->id;
  457. $this->update = true;
  458. $this->add = false;
  459. $this->rows = [];
  460. $this->recordFileService->createRecordFolders($record->id, 'OUT');
  461. $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
  462. foreach ($recordRows as $recordRow) {
  463. $rowData = [
  464. 'causal_id' => $recordRow->causal_id,
  465. 'note' => $recordRow->note,
  466. 'commercial' => $recordRow->commercial,
  467. 'when' => json_decode($recordRow->when),
  468. 'amount' => formatPrice($recordRow->amount)
  469. ];
  470. if (isset($recordRow->imponibile)) {
  471. $rowData['imponibile'] = formatPrice($recordRow->imponibile);
  472. }
  473. $vatLookup = [];
  474. foreach ($this->vats as $vat) {
  475. $vatLookup[(string)$vat->value] = $vat->value;
  476. }
  477. if (isset($recordRow->aliquota_iva)) {
  478. $dbVatValue = (string)$recordRow->aliquota_iva;
  479. if (isset($vatLookup[$dbVatValue])) {
  480. $rowData['aliquota_iva'] = (string)$vatLookup[$dbVatValue];
  481. } else {
  482. $dbVatValueFloat = floatval($dbVatValue);
  483. $closestMatch = null;
  484. $minDiff = PHP_FLOAT_MAX;
  485. foreach ($vatLookup as $vatValue) {
  486. $diff = abs($dbVatValueFloat - floatval($vatValue));
  487. if ($diff < $minDiff && $diff < 0.1) {
  488. $minDiff = $diff;
  489. $closestMatch = $vatValue;
  490. }
  491. }
  492. if ($closestMatch !== null) {
  493. $rowData['aliquota_iva'] = (string)$closestMatch;
  494. } else {
  495. $rowData['aliquota_iva'] = $dbVatValue;
  496. }
  497. }
  498. }
  499. $this->rows[] = $rowData;
  500. }
  501. // Final debug log
  502. Log::info("EDIT DEBUG - Final attachment_old value: '" . $this->attachment_old . "'");
  503. // Force Livewire to re-render
  504. $this->emit('refresh');
  505. }
  506. } catch (\Exception $ex) {
  507. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  508. Log::error("EDIT ERROR: " . $ex->getMessage());
  509. }
  510. }
  511. public function update()
  512. {
  513. $this->emit('refresh');
  514. $this->validate();
  515. if (empty($this->data_pagamento) || $this->data_pagamento == '') {
  516. $this->data_pagamento = null;
  517. Log::info("Data pagamento vuota, imposto a NULL in update");
  518. $is_paid = false;
  519. } else {
  520. Log::info("Data pagamento in update: " . $this->data_pagamento);
  521. $is_paid = true;
  522. }
  523. try {
  524. $attachmentPath = $this->attachment_old;
  525. if ($this->attachment) {
  526. try {
  527. if ($this->attachment_old) {
  528. $this->recordFileService->deleteAttachment($this->attachment_old);
  529. }
  530. $attachmentPath = $this->recordFileService->uploadAttachment($this->attachment, $this->dataId, 'OUT');
  531. } catch (\Exception $ex) {
  532. session()->flash('error', 'Errore caricamento allegato: ' . $ex->getMessage());
  533. return;
  534. }
  535. }
  536. \App\Models\Record::whereId($this->dataId)->update([
  537. 'member_id' => $this->member_id,
  538. 'supplier_id' => $this->supplier_id,
  539. 'payment_method_id' => $this->payment_method_id,
  540. 'date' => $this->date,
  541. 'data_pagamento' => $this->data_pagamento,
  542. 'type' => $this->type,
  543. 'commercial' => $this->commercial,
  544. 'is_paid' => $is_paid,
  545. 'numero_fattura' => $this->numero_fattura,
  546. 'attachment' => $attachmentPath,
  547. ]);
  548. $tot = 0;
  549. $existingRows = \App\Models\RecordRow::where('record_id', $this->dataId)
  550. ->select('id', 'quantita', 'numero_linea')
  551. ->get()
  552. ->keyBy('id')
  553. ->toArray();
  554. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  555. foreach ($this->rows as $row) {
  556. foreach ($row["when"] as $x => $y) {
  557. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  558. }
  559. $imponibile = null;
  560. if (isset($row["imponibile"]) && $row["imponibile"] !== null && $row["imponibile"] !== '') {
  561. $imponibile = $this->currencyToDouble($row["imponibile"]);
  562. Log::info("Imponibile: " . $imponibile);
  563. }
  564. $aliquota_iva = null;
  565. if (isset($row["aliquota_iva"]) && $row["aliquota_iva"] !== null && $row["aliquota_iva"] !== '') {
  566. $aliquota_iva = floatval(str_replace('%', '', $row["aliquota_iva"]));
  567. Log::info("Aliquota IVA: " . $aliquota_iva);
  568. }
  569. $amount = $this->currencyToDouble($row["amount"]);
  570. $imposta = null;
  571. if ($imponibile !== null) {
  572. $imposta = $amount - $imponibile;
  573. Log::info("Imposta calculated: " . $imposta);
  574. }
  575. $recordRowData = [
  576. 'record_id' => $this->dataId,
  577. 'causal_id' => $row["causal_id"],
  578. 'note' => $row["note"],
  579. 'amount' => $this->currencyToDouble($row["amount"]),
  580. 'commercial' => $row["commercial"],
  581. 'when' => json_encode($row["when"]),
  582. 'imponibile' => $imponibile,
  583. 'aliquota_iva' => $aliquota_iva,
  584. 'imposta' => $imposta,
  585. 'divisa' => 'EUR',
  586. ];
  587. if (isset($row["id"]) && isset($existingRows[$row["id"]])) {
  588. $existingRow = $existingRows[$row["id"]];
  589. $recordRowData['quantita'] = $existingRow['quantita'];
  590. $recordRowData['numero_linea'] = $existingRow['numero_linea'];
  591. }
  592. Log::info("RecordRowData: " . json_encode($recordRowData));
  593. \App\Models\RecordRow::create($recordRowData);
  594. $tot += $this->currencyToDouble($row["amount"]);
  595. }
  596. $rec = \App\Models\Record::findOrFail($this->dataId);
  597. $rec->amount = $tot;
  598. $rec->save();
  599. session()->flash('success', 'Movimento aggiornato');
  600. $this->resetFields();
  601. $this->update = false;
  602. $this->emit('setEdit', false);
  603. } catch (\Exception $ex) {
  604. $this->emit('flash-error', 'Errore (' . $ex->getMessage() . ')');
  605. }
  606. }
  607. public function cancel()
  608. {
  609. $this->add = false;
  610. $this->update = false;
  611. $this->emit('setEdit', false);
  612. $this->resetFields();
  613. }
  614. public function delete($id)
  615. {
  616. try {
  617. $record = \App\Models\Record::find($id);
  618. if ($record->attachment) {
  619. $this->recordFileService->deleteAttachment($record->attachment);
  620. }
  621. $record->delete();
  622. session()->flash('success', "Movimento eliminato");
  623. } catch (\Exception $e) {
  624. $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
  625. }
  626. }
  627. public function multipleDelete()
  628. {
  629. try {
  630. foreach ($this->multipleIds as $id) {
  631. $record = \App\Models\Record::find($id);
  632. if ($record->attachment) {
  633. $this->recordFileService->deleteAttachment($record->attachment);
  634. }
  635. $record->delete();
  636. }
  637. } catch (\Exception $e) {
  638. $this->emit('flash-error', 'Errore (' . $e->getMessage() . ')');
  639. }
  640. $this->multipleAction = '';
  641. }
  642. public function getAttachmentUrl($filePath)
  643. {
  644. if (!$filePath) {
  645. return null;
  646. }
  647. return $this->recordFileService->getAttachmentUrl($filePath);
  648. }
  649. /**
  650. * Remove attachment file
  651. */
  652. public function removeAttachment()
  653. {
  654. if ($this->attachment_old) {
  655. $this->recordFileService->deleteAttachment($this->attachment_old);
  656. }
  657. $this->attachment_old = '';
  658. }
  659. function currencyToDouble($val)
  660. {
  661. $x = str_replace("€", "", $val);
  662. $x = str_replace(".", "", $x);
  663. $x = str_replace(",", ".", $x);
  664. return floatval(trim($x));
  665. }
  666. public function addRow()
  667. {
  668. $this->rows[] = array(
  669. 'causal_id' => null,
  670. 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')),
  671. 'amount' => null,
  672. 'imponibile' => null,
  673. 'aliquota_iva' => null,
  674. 'note' => '',
  675. 'commercial' => 0
  676. );
  677. $this->emit('load-select');
  678. }
  679. public function delRow($idx)
  680. {
  681. unset($this->rows[$idx]);
  682. // $this->emit('load-select');
  683. }
  684. public function addPeriod($idx)
  685. {
  686. $x = sizeof($this->rows[$idx]['when']) - 1;
  687. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  688. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  689. //$this->rows[$idx]['when'][] = array('month' => date("n"), 'year' => date("Y"), 'period' => '');
  690. }
  691. public function delPeriod($idx, $xxx)
  692. {
  693. array_splice($this->rows[$idx]['when'], $xxx, 1);
  694. // $this->emit('load-select');
  695. }
  696. public function getTotal()
  697. {
  698. $total = 0.00;
  699. foreach ($this->rows as $r) {
  700. $total += $this->currencyToDouble($r["amount"] != null ? $r["amount"] : 0);
  701. }
  702. return formatPrice($total);
  703. // $this->emit('load-select');
  704. }
  705. public function setCausal($id, $idx)
  706. {
  707. $this->rows[$idx]["causal_id"] = $id;
  708. }
  709. public function multiPeriod()
  710. {
  711. $this->multiP = true;
  712. }
  713. public function multiPeriodCreate($idx)
  714. {
  715. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  716. $this->rows[$idx]['when'] = [];
  717. foreach ($period as $dt) {
  718. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  719. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  720. }
  721. $this->multiP = false;
  722. }
  723. public function multiPeriodCancel()
  724. {
  725. $this->multiP = false;
  726. }
  727. public function importReceipts()
  728. {
  729. $this->validate([
  730. 'selectedCausal' => 'required|exists:causals,id',
  731. ]);
  732. Log::info("Importazione ricevute: " . json_encode($this->receiptFiles));
  733. try {
  734. $importCount = 0;
  735. $updateCount = 0;
  736. $errorsCount = 0;
  737. $errorMessages = [];
  738. $importedFiles = [];
  739. $updatedFiles = [];
  740. $errorFiles = [];
  741. $totalFiles = count($this->receiptFiles);
  742. // disabilita select
  743. $this->emit('import-started');
  744. Log::info("Import iniziato");
  745. foreach ($this->receiptFiles as $index => $receiptFile) {
  746. try {
  747. $fileName = $receiptFile->getClientOriginalName();
  748. Log::info("Elaborazione file: " . $fileName);
  749. // Carica e analizza il file XML
  750. $xmlString = file_get_contents($receiptFile->getRealPath());
  751. $xml = simplexml_load_string($xmlString);
  752. if (empty($xmlString)) {
  753. throw new \Exception("Il file è vuoto.");
  754. }
  755. // Verifica se il file sembra essere un XML
  756. if (strpos($xmlString, '<?xml') === false && strpos($xmlString, '<') === false) {
  757. throw new \Exception("Il file non sembra essere in formato XML.");
  758. }
  759. $xml = simplexml_load_string($xmlString);
  760. if (!$xml) {
  761. throw new \Exception("Impossibile analizzare il file XML");
  762. }
  763. // Estrai i dati dalla fattura elettronica
  764. $fatturaData = $this->extractFatturaData($xml);
  765. // Trova o crea il fornitore
  766. $supplier = $this->findOrCreateSupplier($fatturaData);
  767. // Trova il metodo di pagamento
  768. $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
  769. // Crea il record principale
  770. $isUpdate = false;
  771. $existingRecord = \App\Models\Record::where('supplier_id', $supplier->id)
  772. ->where('numero_fattura', $fatturaData['numeroFattura'])
  773. ->first();
  774. if ($existingRecord) {
  775. $record = $this->updateRecord($existingRecord, $paymentMethodId, $fatturaData);
  776. $isUpdate = true;
  777. $updateCount++;
  778. $updatedFiles[] = $fileName;
  779. Log::info("Fattura aggiornata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  780. } else {
  781. // Crea un nuovo record
  782. $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
  783. $importCount++;
  784. $importedFiles[] = $fileName;
  785. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  786. }
  787. // ← NOW $record exists! Create folder structure for the record
  788. $this->recordFileService->createRecordFolders($record->id, 'OUT');
  789. // ← Store the XML file as an attachment to the record
  790. try {
  791. $xmlAttachmentPath = $this->recordFileService->uploadXmlReceipt($receiptFile, $record->id, 'OUT');
  792. // ← Update the record with the XML attachment path (if you have a field for it)
  793. // If you want to store XML separately from regular attachments, you could add a xml_attachment field
  794. // Or if you want to overwrite the attachment field:
  795. $record->update(['attachment' => $xmlAttachmentPath]);
  796. Log::info("XML receipt stored as attachment: " . $xmlAttachmentPath);
  797. } catch (\Exception $ex) {
  798. Log::warning("Could not store XML as attachment: " . $ex->getMessage());
  799. }
  800. // Crea il record row
  801. $this->createRecordRow($record->id, $fatturaData);
  802. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']} OR {$fatturaData['cognome']}, {$fatturaData['nome']}");
  803. } catch (\Exception $e) {
  804. $errorMsg = $e->getMessage();
  805. $friendlyErrorMsg = $this->getFriendlyErrorMessage($errorMsg);
  806. Log::error("Errore originale: " . $errorMsg);
  807. $errorMessages[] = $friendlyErrorMsg;
  808. $errorFiles[] = $fileName;
  809. $errorsCount++;
  810. }
  811. $progress = ($index + 1) / $totalFiles * 100;
  812. $this->emit('update-progress', $progress);
  813. }
  814. $this->showResultMessages($importCount, $updateCount, $errorsCount, $importedFiles, $updatedFiles, $errorFiles, $errorMessages);
  815. } catch (\Exception $e) {
  816. $errorMsg = 'Errore durante l\'importazione dei file XML: ' . $e->getMessage();
  817. Log::error($errorMsg);
  818. $this->emit('show-import-result', [
  819. 'message' => $errorMsg,
  820. 'type' => 'error'
  821. ]);
  822. } finally {
  823. $this->emit('load-data-table');
  824. }
  825. }
  826. /**
  827. * Estrae i dati dalla fattura elettronica XML
  828. */
  829. private function extractFatturaData($xml)
  830. {
  831. $data = [];
  832. try {
  833. // Stampa la struttura XML per debug
  834. Log::info("Nomi dei children dell'elemento radice: " . implode(", ", array_map(function ($node) {
  835. return $node->getName();
  836. }, iterator_to_array($xml->children()))));
  837. $headerNode = $xml->FatturaElettronicaHeader;
  838. $bodyNode = $xml->FatturaElettronicaBody;
  839. if (!$headerNode || !$bodyNode) {
  840. throw new \Exception("Struttura XML non standard, FatturaElettronicaHeader o FatturaElettronicaBody non trovati");
  841. }
  842. // Estrai dati del fornitore (cedente/prestatore)
  843. $cedenteNode = $headerNode->CedentePrestatore;
  844. $datiAnagrafici = $cedenteNode->DatiAnagrafici;
  845. $idFiscaleIVA = $datiAnagrafici->IdFiscaleIVA;
  846. $data['idPaese'] = (string)$idFiscaleIVA->IdPaese;
  847. $data['idCodice'] = (string)$idFiscaleIVA->IdCodice;
  848. $data['partitaIva'] = $data['idPaese'] . $data['idCodice'];
  849. $data['codiceFiscale'] = (string)$datiAnagrafici->CodiceFiscale;
  850. $data['denominazione'] = (string)$datiAnagrafici->Anagrafica->Denominazione;
  851. $data['cognome'] = (string)$datiAnagrafici->Anagrafica->Cognome;
  852. $data['nome'] = (string)$datiAnagrafici->Anagrafica->Nome;
  853. // Estrai dati della sede
  854. $sede = $cedenteNode->Sede;
  855. $data['indirizzo'] = (string)$sede->Indirizzo;
  856. $data['cap'] = (string)$sede->CAP;
  857. $data['comune'] = (string)$sede->Comune;
  858. $data['provincia'] = (string)$sede->Provincia;
  859. $data['nazione'] = (string)$sede->Nazione ?: 'IT';
  860. // Email, se presente
  861. $data['email'] = '';
  862. if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
  863. $data['email'] = (string)$cedenteNode->Contatti->Email;
  864. }
  865. // Dati generali della fattura
  866. $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
  867. $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
  868. $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
  869. $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
  870. $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
  871. $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
  872. // Dati di pagamento
  873. $data['condizioniPagamento'] = '';
  874. $data['modalitaPagamento'] = '';
  875. $data['dataScadenza'] = '';
  876. $data['iban'] = '';
  877. $data['bic'] = '';
  878. $data['istitutoFinanziario'] = '';
  879. if (isset($bodyNode->DatiPagamento)) {
  880. $datiPagamento = $bodyNode->DatiPagamento;
  881. $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
  882. if (isset($datiPagamento->DettaglioPagamento)) {
  883. $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
  884. $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
  885. $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
  886. $data['iban'] = (string)$dettaglioPagamento->IBAN;
  887. $data['bic'] = (string)$dettaglioPagamento->BIC;
  888. $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
  889. }
  890. }
  891. // Estrai le linee di dettaglio
  892. $data['linee'] = [];
  893. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
  894. foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
  895. if (isset($linea->Quantita)) {
  896. $lineaData = [
  897. 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
  898. 'descrizione' => (string)($linea->Descrizione ?? ''),
  899. 'quantita' => (float)($linea->Quantita ?? 1),
  900. 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
  901. 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
  902. 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
  903. ];
  904. // Calcola il prezzo totale se non presente
  905. if ($lineaData['prezzoTotale'] == 0) {
  906. $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
  907. }
  908. $data['linee'][] = $lineaData;
  909. } else {
  910. // Se la linea ha un campo Quantita, non la consideriamo
  911. Log::info("Linea con Quantita non considerata: " . json_encode($linea));
  912. }
  913. }
  914. }
  915. $data['riepilogo'] = null;
  916. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
  917. $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
  918. if ($riepilogoNode) {
  919. $data['riepilogo'] = [
  920. 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
  921. 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
  922. 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
  923. ];
  924. }
  925. }
  926. 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']}");
  927. return $data;
  928. } catch (\Exception $e) {
  929. Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
  930. throw $e;
  931. }
  932. }
  933. /**
  934. * Trova o crea un fornitore basato sui dati della fattura
  935. */
  936. private function findOrCreateSupplier($fatturaData)
  937. {
  938. $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
  939. if (!$supplier) {
  940. Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']}) OR ({$fatturaData['nome']}), ({$fatturaData['cognome']})");
  941. $countryId = $this->getCountryId($fatturaData['nazione']);
  942. $provinceId = $this->getProvinceId($fatturaData['provincia']);
  943. $cityId = $this->getCityId($fatturaData['comune']);
  944. $supplier = new \App\Models\Supplier();
  945. $supplier->name = $fatturaData['denominazione'] ?: $fatturaData['cognome'] . ' ' . $fatturaData['nome'];
  946. Log::info("Nome fornitore: " . $supplier->name);
  947. $supplier->vat = $fatturaData['partitaIva'];
  948. $supplier->fiscal_code = $fatturaData['codiceFiscale'];
  949. $supplier->address = $fatturaData['indirizzo'];
  950. $supplier->city_id = $cityId;
  951. $supplier->zip_code = $fatturaData['cap'];
  952. $supplier->province_id = $provinceId;
  953. $supplier->nation_id = $countryId;
  954. $supplier->email = $fatturaData['email'];
  955. $supplier->save();
  956. Log::info("Fornitore creato con ID: " . $supplier->id);
  957. }
  958. return $supplier;
  959. }
  960. /**
  961. * Trova l'ID della nazione dal codice
  962. */
  963. private function getCountryId($nationCode)
  964. {
  965. $country = DB::table('nations')->where('code', $nationCode)->first();
  966. return $country ? $country->id : null;
  967. }
  968. /**
  969. * Trova l'ID della provincia dal codice
  970. */
  971. private function getProvinceId($provinceCode)
  972. {
  973. $province = DB::table('provinces')->where('code', $provinceCode)->first();
  974. return $province ? $province->id : null;
  975. }
  976. /**
  977. * Trova l'ID della città dal nome
  978. */
  979. private function getCityId($cityName)
  980. {
  981. if (empty($cityName)) return null;
  982. $city = DB::table('cities')->where('name', $cityName)->first();
  983. return $city ? $city->id : null;
  984. }
  985. /**
  986. * Trova l'ID del metodo di pagamento dal codice
  987. */
  988. private function findPaymentMethod($paymentCode)
  989. {
  990. if (!empty($paymentCode)) {
  991. $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
  992. if ($paymentMethod) {
  993. Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
  994. return $paymentMethod->id;
  995. }
  996. }
  997. // Cerca il metodo di pagamento predefinito - corretto per evitare l'errore della colonna 'default'
  998. // Verifica se esiste una colonna 'is_default' o simile
  999. $possibleDefaultColumns = ['is_default', 'is_default_method', 'default_method', 'primary'];
  1000. $defaultPaymentMethod = null;
  1001. foreach ($possibleDefaultColumns as $column) {
  1002. if (Schema::hasColumn('payment_methods', $column)) {
  1003. $defaultPaymentMethod = DB::table('payment_methods')->where($column, 1)->first();
  1004. if ($defaultPaymentMethod) {
  1005. Log::info("Usando metodo di pagamento predefinito (colonna $column) ID: {$defaultPaymentMethod->id}");
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. // Se non è stato trovato un metodo predefinito, prendi il primo disponibile
  1011. if (!$defaultPaymentMethod) {
  1012. $defaultPaymentMethod = DB::table('payment_methods')->first();
  1013. if ($defaultPaymentMethod) {
  1014. Log::info("Usando il primo metodo di pagamento disponibile ID: {$defaultPaymentMethod->id}");
  1015. }
  1016. }
  1017. if ($defaultPaymentMethod) {
  1018. return $defaultPaymentMethod->id;
  1019. }
  1020. throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
  1021. }
  1022. /**
  1023. * Crea un record nella tabella records
  1024. */
  1025. private function createRecord($supplierId, $paymentMethodId, $fatturaData)
  1026. {
  1027. $record = new \App\Models\Record();
  1028. $record->supplier_id = $supplierId;
  1029. $record->payment_method_id = $paymentMethodId;
  1030. $record->date = $fatturaData['dataDocumento'];
  1031. //$record->data_pagamento = $fatturaData['dataDocumento'];
  1032. $record->numero_fattura = $fatturaData['numeroFattura'];
  1033. $record->type = 'OUT';
  1034. $record->commercial = 1;
  1035. $record->corrispettivo_fiscale = 0;
  1036. $record->deleted = 0;
  1037. $record->financial_movement = 1;
  1038. $record->amount = $fatturaData['importoTotale'];
  1039. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  1040. $record->is_ricevuta = true;
  1041. if ($record->data_pagamento != null) {
  1042. $record->is_paid = true;
  1043. } else {
  1044. $record->is_paid = false;
  1045. }
  1046. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  1047. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  1048. }
  1049. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  1050. $record->IBAN = $fatturaData['iban'];
  1051. }
  1052. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  1053. $record->BIC = $fatturaData['bic'];
  1054. }
  1055. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  1056. $record->data_scadenza = $fatturaData['dataScadenza'];
  1057. }
  1058. $record->save();
  1059. Log::info("Nuovo record creato con ID: " . $record->id);
  1060. return $record;
  1061. }
  1062. /**
  1063. * Aggiorna un record esistente nella tabella records
  1064. */
  1065. private function updateRecord($record, $paymentMethodId, $fatturaData)
  1066. {
  1067. $record->payment_method_id = $paymentMethodId;
  1068. $record->date = $fatturaData['dataDocumento'];
  1069. $record->data_pagamento = $fatturaData['dataDocumento'];
  1070. $record->type = 'OUT';
  1071. $record->commercial = 1;
  1072. $record->corrispettivo_fiscale = 0;
  1073. $record->deleted = 0;
  1074. $record->financial_movement = 1;
  1075. $record->amount = $fatturaData['importoTotale'];
  1076. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  1077. $record->is_ricevuta = true;
  1078. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  1079. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  1080. }
  1081. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  1082. $record->IBAN = $fatturaData['iban'];
  1083. }
  1084. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  1085. $record->BIC = $fatturaData['bic'];
  1086. }
  1087. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  1088. $record->data_scadenza = $fatturaData['dataScadenza'];
  1089. }
  1090. $record->save();
  1091. Log::info("Record esistente aggiornato con ID: " . $record->id);
  1092. return $record;
  1093. }
  1094. /**
  1095. * Crea un record row per il record specificato
  1096. */
  1097. private function createRecordRow($recordId, $fatturaData)
  1098. {
  1099. Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
  1100. $existingRows = \App\Models\RecordRow::where('record_id', $recordId)->get();
  1101. // Delete existing rows if they exist
  1102. if ($existingRows->count() > 0) {
  1103. Log::info("Eliminazione di " . $existingRows->count() . " righe record esistenti per Record ID: " . $recordId);
  1104. foreach ($existingRows as $row) {
  1105. $row->delete();
  1106. }
  1107. }
  1108. if (!empty($fatturaData['linee'])) {
  1109. foreach ($fatturaData['linee'] as $linea) {
  1110. $this->createSingleRecordRow($recordId, $fatturaData, $linea);
  1111. }
  1112. } else if ($fatturaData['riepilogo']) {
  1113. $this->createRecordRowFromRiepilogo($recordId, $fatturaData);
  1114. Log::info("Creata una riga di record dai dati di riepilogo");
  1115. } else {
  1116. $this->createDefaultRecordRow($recordId, $fatturaData);
  1117. Log::info("Creata una riga di record predefinita dall'importo totale");
  1118. }
  1119. }
  1120. private function createSingleRecordRow($recordId, $fatturaData, $linea)
  1121. {
  1122. Log::info("Inizio creazione riga record singola per Record ID: " . $recordId . ", Linea: " . json_encode($linea));
  1123. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1124. $month = $dataObj->format('n');
  1125. $year = $dataObj->format('Y');
  1126. $period = "$month-$year";
  1127. $whenData = [[
  1128. 'month' => $month,
  1129. 'year' => $year,
  1130. 'period' => $period
  1131. ]];
  1132. $vatId = null;
  1133. if (isset($linea['aliquotaIva']) && $linea['aliquotaIva'] > 0) {
  1134. $vatId = $this->findOrCreateVat($linea['aliquotaIva']);
  1135. Log::info("Using VAT ID: $vatId for rate: {$linea['aliquotaIva']}%");
  1136. }
  1137. $recordRow = new \App\Models\RecordRow();
  1138. $recordRow->record_id = $recordId;
  1139. $recordRow->causal_id = $this->selectedCausal;
  1140. $recordRow->amount = $linea['prezzoTotale'] + $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  1141. $recordRow->note = $linea['descrizione'];
  1142. $recordRow->commercial = 1;
  1143. $recordRow->when = json_encode($whenData);
  1144. $recordRow->aliquota_iva = $linea['aliquotaIva'];
  1145. $recordRow->imponibile = $linea['prezzoTotale'];
  1146. $recordRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  1147. $recordRow->divisa = $fatturaData['divisa'];
  1148. $recordRow->numero_linea = $linea['numeroLinea'];
  1149. $recordRow->prezzo_unitario = $linea['prezzoUnitario'];
  1150. $recordRow->quantita = $linea['quantita'];
  1151. Log::info("Dati riga record prima del salvataggio: " . json_encode([
  1152. 'record_id' => $recordRow->record_id,
  1153. 'causal_id' => $recordRow->causal_id,
  1154. 'amount' => $recordRow->amount,
  1155. 'note' => $recordRow->note,
  1156. 'aliquota_iva' => $recordRow->aliquota_iva,
  1157. 'imponibile' => $recordRow->imponibile,
  1158. 'imposta' => $recordRow->imposta,
  1159. 'divisa' => $recordRow->divisa,
  1160. 'numero_linea' => $recordRow->numero_linea,
  1161. 'prezzo_unitario' => $recordRow->prezzo_unitario,
  1162. 'quantita' => $recordRow->quantita,
  1163. ]));
  1164. $recordRow->save();
  1165. Log::info("Riga record creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
  1166. }
  1167. private function createRecordRowFromRiepilogo($recordId, $fatturaData)
  1168. {
  1169. Log::info("Inizio creazione riga record da riepilogo per Record ID: " . $recordId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
  1170. $riepilogo = $fatturaData['riepilogo'];
  1171. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1172. $month = $dataObj->format('n');
  1173. $year = $dataObj->format('Y');
  1174. $period = "$month-$year";
  1175. $whenData = [[
  1176. 'month' => $month,
  1177. 'year' => $year,
  1178. 'period' => $period
  1179. ]];
  1180. $vatId = null;
  1181. if (isset($riepilogo['aliquotaIva']) && $riepilogo['aliquotaIva'] > 0) {
  1182. $vatId = $this->findOrCreateVat($riepilogo['aliquotaIva']);
  1183. Log::info("Using VAT ID: $vatId for rate: {$riepilogo['aliquotaIva']}%");
  1184. }
  1185. $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
  1186. $recordRow = new \App\Models\RecordRow();
  1187. $recordRow->record_id = $recordId;
  1188. $recordRow->causal_id = $this->selectedCausal;
  1189. $recordRow->amount = $total_amount;
  1190. $recordRow->commercial = 1;
  1191. $recordRow->when = json_encode($whenData);
  1192. $recordRow->aliquota_iva = $riepilogo['aliquotaIva'];
  1193. $recordRow->imponibile = $riepilogo['imponibile'];
  1194. $recordRow->imposta = $riepilogo['imposta'];
  1195. $recordRow->divisa = $fatturaData['divisa'];
  1196. $recordRow->numero_linea = 1;
  1197. $recordRow->quantita = 1;
  1198. Log::info("Dati riga record da riepilogo prima del salvataggio: " . json_encode([
  1199. 'record_id' => $recordRow->record_id,
  1200. 'causal_id' => $recordRow->causal_id,
  1201. 'amount' => $recordRow->amount,
  1202. 'aliquota_iva' => $recordRow->aliquota_iva,
  1203. 'imponibile' => $recordRow->imponibile,
  1204. 'imposta' => $recordRow->imposta,
  1205. 'divisa' => $recordRow->divisa,
  1206. ]));
  1207. $recordRow->save();
  1208. Log::info("Riga record creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
  1209. }
  1210. private function createDefaultRecordRow($recordId, $fatturaData)
  1211. {
  1212. Log::info("Inizio creazione riga record predefinita per Record ID: " . $recordId . ", Importo Totale: " . $fatturaData['importoTotale']);
  1213. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1214. $month = $dataObj->format('n');
  1215. $year = $dataObj->format('Y');
  1216. $period = "$month-$year";
  1217. $whenData = [[
  1218. 'month' => $month,
  1219. 'year' => $year,
  1220. 'period' => $period
  1221. ]];
  1222. $recordRow = new \App\Models\RecordRow();
  1223. $recordRow->record_id = $recordId;
  1224. $recordRow->causal_id = $this->selectedCausal;
  1225. $recordRow->amount = $fatturaData['importoTotale'];
  1226. $recordRow->commercial = 1;
  1227. $recordRow->when = json_encode($whenData);
  1228. $recordRow->divisa = $fatturaData['divisa'];
  1229. $recordRow->numero_linea = 1;
  1230. $recordRow->quantita = 1;
  1231. Log::info("Dati riga record predefinita prima del salvataggio: " . json_encode([
  1232. 'record_id' => $recordRow->record_id,
  1233. 'causal_id' => $recordRow->causal_id,
  1234. 'amount' => $recordRow->amount,
  1235. 'divisa' => $recordRow->divisa,
  1236. ]));
  1237. $recordRow->save();
  1238. Log::info("Riga record predefinita creata con importo totale: {$fatturaData['importoTotale']}");
  1239. }
  1240. private function mapTipoDocumento($codice)
  1241. {
  1242. $tipiDocumento = [
  1243. 'TD01' => 'Fattura',
  1244. 'TD02' => 'Acconto/Anticipo su fattura',
  1245. 'TD03' => 'Acconto/Anticipo su parcella',
  1246. 'TD04' => 'Nota di credito',
  1247. 'TD05' => 'Nota di debito',
  1248. 'TD06' => 'Parcella',
  1249. 'TD16' => 'Integrazione fattura reverse charge interno',
  1250. 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
  1251. 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
  1252. 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
  1253. 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
  1254. 'TD21' => 'Autofattura per splafonamento',
  1255. 'TD22' => 'Estrazione beni da Deposito IVA',
  1256. 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
  1257. 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
  1258. 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
  1259. 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
  1260. 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
  1261. ];
  1262. return $tipiDocumento[$codice] ?? $codice;
  1263. }
  1264. private function mapCondizioniPagamento($codice)
  1265. {
  1266. $condizioniPagamento = [
  1267. 'TP01' => 'Pagamento a rate',
  1268. 'TP02' => 'Pagamento completo',
  1269. 'TP03' => 'Anticipo'
  1270. ];
  1271. return $condizioniPagamento[$codice] ?? $codice;
  1272. }
  1273. private function showResultMessages($importCount, $updateCount, $errorsCount, $importedFiles = [], $updatedFiles = [], $errorFiles = [], $errorMessages = [])
  1274. {
  1275. $message = "";
  1276. $messageType = "success";
  1277. if ($importCount > 0) {
  1278. $message .= "Importate correttamente n° $importCount nuove fatture.<br>";
  1279. if (!empty($importedFiles)) {
  1280. $message .= "<details><summary>File importati (clicca per espandere)</summary><ul>";
  1281. foreach ($importedFiles as $file) {
  1282. $message .= "<li>" . htmlspecialchars($file) . "</li>";
  1283. }
  1284. $message .= "</ul></details><br>";
  1285. }
  1286. }
  1287. if ($updateCount > 0) {
  1288. $message .= "Aggiornate n° $updateCount fatture perchè già presenti.<br>";
  1289. if (!empty($updatedFiles)) {
  1290. $message .= "<details><summary>File aggiornati (clicca per espandere)</summary><ul>";
  1291. foreach ($updatedFiles as $file) {
  1292. $message .= "<li>" . htmlspecialchars($file) . "</li>";
  1293. }
  1294. $message .= "</ul></details><br>";
  1295. }
  1296. }
  1297. if ($errorsCount > 0) {
  1298. $message .= "Importazione fallita per n° $errorsCount fatture.<br>";
  1299. // Aggiungi i dettagli degli errori se disponibili
  1300. if (!empty($errorFiles)) {
  1301. $message .= "<details><summary>File con errori (clicca per espandere)</summary><ul>";
  1302. foreach ($errorFiles as $index => $file) {
  1303. $errorMessage = isset($errorMessages[$index]) ? ': ' . preg_replace('/^Errore durante l\'importazione della fattura \([^)]+\):/', '', $errorMessages[$index]) : '';
  1304. $message .= "<li>" . htmlspecialchars($file) . $errorMessage . "</li>";
  1305. }
  1306. $message .= "</ul></details><br>";
  1307. }
  1308. if ($importCount == 0 && $updateCount == 0) {
  1309. $messageType = "error";
  1310. } else {
  1311. $messageType = "warning";
  1312. }
  1313. }
  1314. if ($importCount > 0 || $updateCount > 0 || $errorsCount > 0) {
  1315. $this->emit('show-import-result', [
  1316. 'message' => $message,
  1317. 'type' => $messageType
  1318. ]);
  1319. } else {
  1320. $this->emit('show-import-result', [
  1321. 'message' => 'Nessuna fattura importata. Controlla i file XML e riprova.',
  1322. 'type' => 'error'
  1323. ]);
  1324. }
  1325. // Resetta i campi del form dopo l'importazione
  1326. $this->reset(['receiptFiles']);
  1327. }
  1328. private function getFriendlyErrorMessage($errorMessage)
  1329. {
  1330. // Errore di parsing XML iniziale
  1331. if (strpos($errorMessage, "simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found") !== false) {
  1332. return "Il file non è in formato valido. Potrebbe essere danneggiato o in un formato diverso.";
  1333. }
  1334. // Errore di struttura XML
  1335. if (strpos($errorMessage, "FatturaElettronicaHeader o FatturaElettronicaBody non trovati") !== false) {
  1336. return "Il file non sembra essere una fattura elettronica valida. Mancano le sezioni principali.";
  1337. }
  1338. // Altri errori comuni di parsing XML
  1339. if (strpos($errorMessage, "parser error") !== false) {
  1340. return "Il file XML contiene errori di formattazione e non può essere letto correttamente.";
  1341. }
  1342. // Errori di struttura interna
  1343. if (
  1344. strpos($errorMessage, "Undefined index") !== false ||
  1345. strpos($errorMessage, "Trying to get property") !== false
  1346. ) {
  1347. return "La fattura è incompleta o non contiene tutti i dati necessari.";
  1348. }
  1349. // Per altri errori, conserva il messaggio originale ma semplificalo
  1350. return $errorMessage;
  1351. }
  1352. public function getVats()
  1353. {
  1354. $vats = array();
  1355. foreach ($this->rows as $r) {
  1356. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0) {
  1357. $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  1358. $vatName = "";
  1359. foreach ($this->vats as $v) {
  1360. if ($v->id == $r["vat_id"])
  1361. $vatName = $v->name;
  1362. }
  1363. if (isset($vats[$vatName]))
  1364. $vats[$vatName] += $vat;
  1365. else
  1366. $vats[$vatName] = $vat;
  1367. }
  1368. }
  1369. return $vats;
  1370. }
  1371. private function findOrCreateVat($vatRate)
  1372. {
  1373. $vatRate = (float)$vatRate;
  1374. Log::info("Searching for VAT rate: $vatRate%");
  1375. $existingVat = \App\Models\Vat::where(function ($query) use ($vatRate) {
  1376. $query->whereRaw('ABS(value - ?) < 0.01', [$vatRate]);
  1377. })->first();
  1378. if ($existingVat) {
  1379. Log::info("Found existing VAT rate: ID={$existingVat->id}, Name={$existingVat->name}, Value={$existingVat->value}");
  1380. return $existingVat->id;
  1381. }
  1382. Log::info("Creating new VAT rate: $vatRate%");
  1383. $vatName = "IVA $vatRate%";
  1384. $newVat = new \App\Models\Vat();
  1385. $newVat->name = $vatName;
  1386. $newVat->value = $vatRate;
  1387. $newVat->enabled = 1;
  1388. $newVat->save();
  1389. Log::info("Created new VAT rate: ID={$newVat->id}, Name={$newVat->name}, Value={$newVat->value}");
  1390. $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
  1391. return $newVat->id;
  1392. }
  1393. public function viewData($id)
  1394. {
  1395. Log::info("Visualizzazione dati per ID: " . $id);
  1396. try {
  1397. $record = \App\Models\Record::with(['supplier', 'payment_method', 'rows.causal'])->findOrFail($id);
  1398. if (!$record) {
  1399. $this->emit('flash-error', 'Movimento non trovato');
  1400. return;
  1401. }
  1402. $record->formatted_date = date("d/m/Y", strtotime($record->date));
  1403. $record->formatted_data_pagamento = $record->data_pagamento ? date("d/m/Y", strtotime($record->data_pagamento)) : 'Non impostata';
  1404. $record->supplier_name = $record->supplier ? $record->supplier->name : 'N/A';
  1405. $record->payment_method_name = $record->payment_method ? $record->payment_method->name : 'N/A';
  1406. $record->formatted_amount = formatPrice($record->amount);
  1407. $record->payment_status = $record->is_paid ? 'Pagato' : 'Da Pagare';
  1408. foreach ($record->rows as $row) {
  1409. $row->causal_name = $row->causal ? $row->causal->getTree() : 'N/A';
  1410. $row->formatted_imponibile = $row->imponibile ? formatPrice($row->imponibile) : 'N/A';
  1411. $row->iva = $row->aliquota_iva ? formatPrice($row->aliquota_iva) : 'N/A';
  1412. $row->formatted_imposta = $row->imposta ? formatPrice($row->imposta) : 'N/A';
  1413. $row->formatted_amount = formatPrice($row->amount);
  1414. }
  1415. if ($record->attachment) {
  1416. $record->attachment_url = $this->getAttachmentUrl($record->attachment);
  1417. }
  1418. Log::info("Emitting show-record-details event");
  1419. $this->dispatchBrowserEvent('show-record-details', ['record' => $record]);
  1420. } catch (\Exception $e) {
  1421. Log::error("Errore nel caricamento dei dettagli: " . $e->getMessage());
  1422. $this->emit('flash-error', 'Errore nel caricamento dei dettagli: ' . $e->getMessage());
  1423. }
  1424. }
  1425. }