RecordOUT.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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 fornitorez
  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']} OR {$fatturaData['cognome']}, {$fatturaData['nome']}");
  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. $data['cognome'] = (string)$datiAnagrafici->Anagrafica->Cognome;
  706. $data['nome'] = (string)$datiAnagrafici->Anagrafica->Nome;
  707. // Estrai dati della sede
  708. $sede = $cedenteNode->Sede;
  709. $data['indirizzo'] = (string)$sede->Indirizzo;
  710. $data['cap'] = (string)$sede->CAP;
  711. $data['comune'] = (string)$sede->Comune;
  712. $data['provincia'] = (string)$sede->Provincia;
  713. $data['nazione'] = (string)$sede->Nazione ?: 'IT';
  714. // Email, se presente
  715. $data['email'] = '';
  716. if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
  717. $data['email'] = (string)$cedenteNode->Contatti->Email;
  718. }
  719. // Dati generali della fattura
  720. $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
  721. $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
  722. $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
  723. $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
  724. $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
  725. $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
  726. // Dati di pagamento
  727. $data['condizioniPagamento'] = '';
  728. $data['modalitaPagamento'] = '';
  729. $data['dataScadenza'] = '';
  730. $data['iban'] = '';
  731. $data['bic'] = '';
  732. $data['istitutoFinanziario'] = '';
  733. if (isset($bodyNode->DatiPagamento)) {
  734. $datiPagamento = $bodyNode->DatiPagamento;
  735. $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
  736. if (isset($datiPagamento->DettaglioPagamento)) {
  737. $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
  738. $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
  739. $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
  740. $data['iban'] = (string)$dettaglioPagamento->IBAN;
  741. $data['bic'] = (string)$dettaglioPagamento->BIC;
  742. $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
  743. }
  744. }
  745. // Estrai le linee di dettaglio
  746. $data['linee'] = [];
  747. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
  748. foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
  749. $lineaData = [
  750. 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
  751. 'descrizione' => (string)($linea->Descrizione ?? ''),
  752. 'quantita' => (float)($linea->Quantita ?? 1),
  753. 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
  754. 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
  755. 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
  756. ];
  757. // Calcola il prezzo totale se non presente
  758. if ($lineaData['prezzoTotale'] == 0) {
  759. $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
  760. }
  761. $data['linee'][] = $lineaData;
  762. }
  763. }
  764. $data['riepilogo'] = null;
  765. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
  766. $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
  767. if ($riepilogoNode) {
  768. $data['riepilogo'] = [
  769. 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
  770. 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
  771. 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
  772. ];
  773. }
  774. }
  775. Log::info("Dati estratti dalla fattura: P.IVA={$data['partitaIva']}, Denominazione={$data['denominazione']},Nome={$data['nome']},Cognome={$data['cognome']} , Numero={$data['numeroFattura']}, Importo={$data['importoTotale']}");
  776. return $data;
  777. } catch (\Exception $e) {
  778. Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
  779. throw $e;
  780. }
  781. }
  782. /**
  783. * Trova o crea un fornitore basato sui dati della fattura
  784. */
  785. private function findOrCreateSupplier($fatturaData)
  786. {
  787. $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
  788. if (!$supplier) {
  789. Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']}) OR ({$fatturaData['nome']}), ({$fatturaData['cognome']})");
  790. $countryId = $this->getCountryId($fatturaData['nazione']);
  791. $provinceId = $this->getProvinceId($fatturaData['provincia']);
  792. $cityId = $this->getCityId($fatturaData['comune']);
  793. $supplier = new \App\Models\Supplier();
  794. $supplier->name = $fatturaData['denominazione'] ?: $fatturaData['cognome'] . ' ' . $fatturaData['nome'];
  795. Log::info("Nome fornitore: " . $supplier->name);
  796. $supplier->vat = $fatturaData['partitaIva'];
  797. $supplier->fiscal_code = $fatturaData['codiceFiscale'];
  798. $supplier->address = $fatturaData['indirizzo'];
  799. $supplier->city_id = $cityId;
  800. $supplier->zip_code = $fatturaData['cap'];
  801. $supplier->province_id = $provinceId;
  802. $supplier->nation_id = $countryId;
  803. $supplier->email = $fatturaData['email'];
  804. $supplier->save();
  805. Log::info("Fornitore creato con ID: " . $supplier->id);
  806. }
  807. return $supplier;
  808. }
  809. /**
  810. * Trova l'ID della nazione dal codice
  811. */
  812. private function getCountryId($nationCode)
  813. {
  814. $country = DB::table('nations')->where('code', $nationCode)->first();
  815. return $country ? $country->id : null;
  816. }
  817. /**
  818. * Trova l'ID della provincia dal codice
  819. */
  820. private function getProvinceId($provinceCode)
  821. {
  822. $province = DB::table('provinces')->where('code', $provinceCode)->first();
  823. return $province ? $province->id : null;
  824. }
  825. /**
  826. * Trova l'ID della città dal nome
  827. */
  828. private function getCityId($cityName)
  829. {
  830. if (empty($cityName)) return null;
  831. $city = DB::table('cities')->where('name', $cityName)->first();
  832. return $city ? $city->id : null;
  833. }
  834. /**
  835. * Trova l'ID del metodo di pagamento dal codice
  836. */
  837. private function findPaymentMethod($paymentCode)
  838. {
  839. if (!empty($paymentCode)) {
  840. $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
  841. if ($paymentMethod) {
  842. Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
  843. return $paymentMethod->id;
  844. }
  845. }
  846. $defaultPaymentMethod = DB::table('payment_methods')->where('default', 1)->first()
  847. ?? DB::table('payment_methods')->first();
  848. if ($defaultPaymentMethod) {
  849. Log::info("Usando metodo di pagamento predefinito ID: {$defaultPaymentMethod->id}");
  850. return $defaultPaymentMethod->id;
  851. }
  852. throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
  853. }
  854. /**
  855. * Crea un record nella tabella records
  856. */
  857. private function createRecord($supplierId, $paymentMethodId, $fatturaData)
  858. {
  859. $existingRecord = \App\Models\Record::where('supplier_id', $supplierId)
  860. ->where('numero_fattura', $fatturaData['numeroFattura'])
  861. ->first();
  862. if ($existingRecord) {
  863. Log::info("Trovato record esistente con ID: " . $existingRecord->id . " per fornitore ID: " . $supplierId . " e numero fattura: " . $fatturaData['numeroFattura']);
  864. $existingRecord->payment_method_id = $paymentMethodId;
  865. $existingRecord->date = $fatturaData['dataDocumento'];
  866. $existingRecord->data_pagamento = $fatturaData['dataDocumento'];
  867. $existingRecord->type = 'OUT';
  868. $existingRecord->commercial = 1;
  869. $existingRecord->corrispettivo_fiscale = 0;
  870. $existingRecord->deleted = 0;
  871. $existingRecord->financial_movement = 1;
  872. $existingRecord->amount = $fatturaData['importoTotale'];
  873. $existingRecord->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  874. $existingRecord->is_ricevuta = true;
  875. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  876. $existingRecord->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  877. }
  878. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  879. $existingRecord->IBAN = $fatturaData['iban'];
  880. }
  881. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  882. $existingRecord->BIC = $fatturaData['bic'];
  883. }
  884. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  885. $existingRecord->data_scadenza = $fatturaData['dataScadenza'];
  886. }
  887. $existingRecord->save();
  888. Log::info("Record esistente aggiornato con ID: " . $existingRecord->id);
  889. return $existingRecord;
  890. }
  891. $record = new \App\Models\Record();
  892. $record->supplier_id = $supplierId;
  893. $record->payment_method_id = $paymentMethodId;
  894. $record->date = $fatturaData['dataDocumento'];
  895. $record->data_pagamento = $fatturaData['dataDocumento'];
  896. $record->numero_fattura = $fatturaData['numeroFattura'];
  897. $record->type = 'OUT';
  898. $record->commercial = 1;
  899. $record->corrispettivo_fiscale = 0;
  900. $record->deleted = 0;
  901. $record->financial_movement = 1;
  902. $record->amount = $fatturaData['importoTotale'];
  903. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  904. $record->is_ricevuta = true;
  905. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  906. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  907. }
  908. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  909. $record->IBAN = $fatturaData['iban'];
  910. }
  911. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  912. $record->BIC = $fatturaData['bic'];
  913. }
  914. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  915. $record->data_scadenza = $fatturaData['dataScadenza'];
  916. }
  917. $record->save();
  918. Log::info("Record creato con ID: " . $record->id);
  919. return $record;
  920. }
  921. /**
  922. * Crea un record row per il record specificato
  923. */
  924. private function createRecordRow($recordId, $fatturaData)
  925. {
  926. Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
  927. $existingRows = \App\Models\RecordRow::where('record_id', $recordId)->get();
  928. // Delete existing rows if they exist
  929. if ($existingRows->count() > 0) {
  930. Log::info("Eliminazione di " . $existingRows->count() . " righe record esistenti per Record ID: " . $recordId);
  931. foreach ($existingRows as $row) {
  932. $row->delete();
  933. }
  934. }
  935. if (!empty($fatturaData['linee'])) {
  936. foreach ($fatturaData['linee'] as $linea) {
  937. $this->createSingleRecordRow($recordId, $fatturaData, $linea);
  938. }
  939. } else if ($fatturaData['riepilogo']) {
  940. $this->createRecordRowFromRiepilogo($recordId, $fatturaData);
  941. Log::info("Creata una riga di record dai dati di riepilogo");
  942. } else {
  943. $this->createDefaultRecordRow($recordId, $fatturaData);
  944. Log::info("Creata una riga di record predefinita dall'importo totale");
  945. }
  946. }
  947. private function createSingleRecordRow($recordId, $fatturaData, $linea)
  948. {
  949. Log::info("Inizio creazione riga record singola per Record ID: " . $recordId . ", Linea: " . json_encode($linea));
  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. $recordRow = new \App\Models\RecordRow();
  960. $recordRow->record_id = $recordId;
  961. $recordRow->causal_id = $this->selectedCausal;
  962. $recordRow->amount = $linea['prezzoTotale'] + $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  963. $recordRow->note = $linea['descrizione'];
  964. $recordRow->commercial = 1;
  965. $recordRow->when = json_encode($whenData);
  966. $recordRow->aliquota_iva = $linea['aliquotaIva'];
  967. $recordRow->imponibile = $linea['prezzoTotale'];
  968. $recordRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  969. $recordRow->divisa = $fatturaData['divisa'];
  970. $recordRow->numero_linea = $linea['numeroLinea'];
  971. $recordRow->prezzo_unitario = $linea['prezzoUnitario'];
  972. $recordRow->quantita = $linea['quantita'];
  973. Log::info("Dati riga record prima del salvataggio: " . json_encode([
  974. 'record_id' => $recordRow->record_id,
  975. 'causal_id' => $recordRow->causal_id,
  976. 'amount' => $recordRow->amount,
  977. 'note' => $recordRow->note,
  978. 'aliquota_iva' => $recordRow->aliquota_iva,
  979. 'imponibile' => $recordRow->imponibile,
  980. 'imposta' => $recordRow->imposta,
  981. 'divisa' => $recordRow->divisa,
  982. 'numero_linea' => $recordRow->numero_linea,
  983. 'prezzo_unitario' => $recordRow->prezzo_unitario,
  984. 'quantita' => $recordRow->quantita,
  985. ]));
  986. $recordRow->save();
  987. Log::info("Riga record creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
  988. }
  989. private function createRecordRowFromRiepilogo($recordId, $fatturaData)
  990. {
  991. Log::info("Inizio creazione riga record da riepilogo per Record ID: " . $recordId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
  992. $riepilogo = $fatturaData['riepilogo'];
  993. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  994. $month = $dataObj->format('n');
  995. $year = $dataObj->format('Y');
  996. $period = "$month-$year";
  997. $whenData = [[
  998. 'month' => $month,
  999. 'year' => $year,
  1000. 'period' => $period
  1001. ]];
  1002. $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
  1003. $recordRow = new \App\Models\RecordRow();
  1004. $recordRow->record_id = $recordId;
  1005. $recordRow->causal_id = $this->selectedCausal;
  1006. $recordRow->amount = $total_amount;
  1007. $recordRow->commercial = 1;
  1008. $recordRow->when = json_encode($whenData);
  1009. $recordRow->aliquota_iva = $riepilogo['aliquotaIva'];
  1010. $recordRow->imponibile = $riepilogo['imponibile'];
  1011. $recordRow->imposta = $riepilogo['imposta'];
  1012. $recordRow->divisa = $fatturaData['divisa'];
  1013. $recordRow->numero_linea = 1;
  1014. $recordRow->quantita = 1;
  1015. Log::info("Dati riga record da riepilogo prima del salvataggio: " . json_encode([
  1016. 'record_id' => $recordRow->record_id,
  1017. 'causal_id' => $recordRow->causal_id,
  1018. 'amount' => $recordRow->amount,
  1019. 'aliquota_iva' => $recordRow->aliquota_iva,
  1020. 'imponibile' => $recordRow->imponibile,
  1021. 'imposta' => $recordRow->imposta,
  1022. 'divisa' => $recordRow->divisa,
  1023. ]));
  1024. $recordRow->save();
  1025. Log::info("Riga record creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
  1026. }
  1027. private function createDefaultRecordRow($recordId, $fatturaData)
  1028. {
  1029. Log::info("Inizio creazione riga record predefinita per Record ID: " . $recordId . ", Importo Totale: " . $fatturaData['importoTotale']);
  1030. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1031. $month = $dataObj->format('n');
  1032. $year = $dataObj->format('Y');
  1033. $period = "$month-$year";
  1034. $whenData = [[
  1035. 'month' => $month,
  1036. 'year' => $year,
  1037. 'period' => $period
  1038. ]];
  1039. $recordRow = new \App\Models\RecordRow();
  1040. $recordRow->record_id = $recordId;
  1041. $recordRow->causal_id = $this->selectedCausal;
  1042. $recordRow->amount = $fatturaData['importoTotale'];
  1043. $recordRow->commercial = 1;
  1044. $recordRow->when = json_encode($whenData);
  1045. $recordRow->divisa = $fatturaData['divisa'];
  1046. $recordRow->numero_linea = 1;
  1047. $recordRow->quantita = 1;
  1048. Log::info("Dati riga record predefinita prima del salvataggio: " . json_encode([
  1049. 'record_id' => $recordRow->record_id,
  1050. 'causal_id' => $recordRow->causal_id,
  1051. 'amount' => $recordRow->amount,
  1052. 'divisa' => $recordRow->divisa,
  1053. ]));
  1054. $recordRow->save();
  1055. Log::info("Riga record predefinita creata con importo totale: {$fatturaData['importoTotale']}");
  1056. }
  1057. private function mapTipoDocumento($codice)
  1058. {
  1059. $tipiDocumento = [
  1060. 'TD01' => 'Fattura',
  1061. 'TD02' => 'Acconto/Anticipo su fattura',
  1062. 'TD03' => 'Acconto/Anticipo su parcella',
  1063. 'TD04' => 'Nota di credito',
  1064. 'TD05' => 'Nota di debito',
  1065. 'TD06' => 'Parcella',
  1066. 'TD16' => 'Integrazione fattura reverse charge interno',
  1067. 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
  1068. 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
  1069. 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
  1070. 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
  1071. 'TD21' => 'Autofattura per splafonamento',
  1072. 'TD22' => 'Estrazione beni da Deposito IVA',
  1073. 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
  1074. 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
  1075. 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
  1076. 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
  1077. 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
  1078. ];
  1079. return $tipiDocumento[$codice] ?? $codice;
  1080. }
  1081. private function mapCondizioniPagamento($codice)
  1082. {
  1083. $condizioniPagamento = [
  1084. 'TP01' => 'Pagamento a rate',
  1085. 'TP02' => 'Pagamento completo',
  1086. 'TP03' => 'Anticipo'
  1087. ];
  1088. return $condizioniPagamento[$codice] ?? $codice;
  1089. }
  1090. private function showResultMessages($importCount, $errorsCount)
  1091. {
  1092. if ($importCount > 0) {
  1093. $message = "Importate $importCount fatture con successo.";
  1094. if ($errorsCount > 0) {
  1095. $message .= " $errorsCount fatture non sono state importate.";
  1096. }
  1097. session()->flash('message', $message);
  1098. } else {
  1099. $this->emit('flash-error','Nessuna fattura importata. Controlla i file XML e riprova.');
  1100. }
  1101. }
  1102. }