RecordOUT.php 70 KB

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