RecordOUT.php 50 KB

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