RecordOUT.php 52 KB

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