RecordOUT.php 54 KB

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