RecordOUT.php 63 KB

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