RecordOUT.php 51 KB

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