RecordOUT.php 52 KB

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