RecordOUT.php 58 KB

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