RecordOUT.php 53 KB

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