RecordOUT.php 70 KB

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