RecordOUT.php 70 KB

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