RecordOUT.php 51 KB

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