RecordOUT.php 61 KB

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