RecordOUT.php 53 KB

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