RecordOUT.php 71 KB

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