RecordOUT.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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. $totalFiles = count($this->receiptFiles);
  656. // disabilita select
  657. $this->emit('import-started');
  658. Log::info("Import iniziato");
  659. foreach ($this->receiptFiles as $index => $receiptFile) {
  660. try {
  661. $fileName = $receiptFile->getClientOriginalName();
  662. Log::info("Elaborazione file: " . $fileName);
  663. // Carica e analizza il file XML
  664. $xmlString = file_get_contents($receiptFile->getRealPath());
  665. $xml = simplexml_load_string($xmlString);
  666. if (!$xml) {
  667. throw new \Exception("Impossibile analizzare il file XML");
  668. }
  669. // Estrai i dati dalla fattura elettronica
  670. $fatturaData = $this->extractFatturaData($xml);
  671. // Trova o crea il fornitorez
  672. $supplier = $this->findOrCreateSupplier($fatturaData);
  673. // Trova il metodo di pagamento
  674. $paymentMethodId = $this->findPaymentMethod($fatturaData['modalitaPagamento']);
  675. // Crea il record principale
  676. $isUpdate = false;
  677. $existingRecord = \App\Models\Record::where('supplier_id', $supplier->id)
  678. ->where('numero_fattura', $fatturaData['numeroFattura'])
  679. ->first();
  680. if ($existingRecord) {
  681. $record = $this->updateRecord($existingRecord, $paymentMethodId, $fatturaData);
  682. $isUpdate = true;
  683. $updateCount++;
  684. Log::info("Fattura aggiornata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  685. } else {
  686. // Crea un nuovo record
  687. $record = $this->createRecord($supplier->id, $paymentMethodId, $fatturaData);
  688. $importCount++;
  689. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$supplier->name}");
  690. }
  691. // Crea il record row
  692. $this->createRecordRow($record->id, $fatturaData);
  693. //$importCount++;
  694. Log::info("Fattura importata con successo: {$fatturaData['numeroFattura']}, Fornitore: {$fatturaData['denominazione']} OR {$fatturaData['cognome']}, {$fatturaData['nome']}");
  695. } catch (\Exception $e) {
  696. $errorMsg = 'Errore durante l\'importazione della fattura';
  697. if (isset($fileName)) {
  698. $errorMsg .= " ($fileName)";
  699. }
  700. $errorMsg .= ': ' . $e->getMessage();
  701. Log::error($errorMsg);
  702. $errorMessages[] = $errorMsg;
  703. $errorsCount++;
  704. }
  705. $progress = ($index + 1) / $totalFiles * 100;
  706. $this->emit('update-progress', $progress);
  707. }
  708. $this->showResultMessages($importCount, $updateCount, $errorsCount);
  709. } catch (\Exception $e) {
  710. $errorMsg = 'Errore durante l\'importazione dei file XML: ' . $e->getMessage();
  711. Log::error($errorMsg);
  712. $this->emit('show-import-result', [
  713. 'message' => $errorMsg,
  714. 'type' => 'error'
  715. ]);
  716. } finally {
  717. $this->emit('load-data-table');
  718. // Non chiamiamo più closeImportModal() qui, perché la chiusura è gestita dal JavaScript
  719. }
  720. }
  721. /**
  722. * Estrae i dati dalla fattura elettronica XML
  723. */
  724. private function extractFatturaData($xml)
  725. {
  726. $data = [];
  727. try {
  728. // Stampa la struttura XML per debug
  729. Log::info("Nomi dei children dell'elemento radice: " . implode(", ", array_map(function ($node) {
  730. return $node->getName();
  731. }, iterator_to_array($xml->children()))));
  732. $headerNode = $xml->FatturaElettronicaHeader;
  733. $bodyNode = $xml->FatturaElettronicaBody;
  734. if (!$headerNode || !$bodyNode) {
  735. throw new \Exception("Struttura XML non standard, FatturaElettronicaHeader o FatturaElettronicaBody non trovati");
  736. }
  737. // Estrai dati del fornitore (cedente/prestatore)
  738. $cedenteNode = $headerNode->CedentePrestatore;
  739. $datiAnagrafici = $cedenteNode->DatiAnagrafici;
  740. $idFiscaleIVA = $datiAnagrafici->IdFiscaleIVA;
  741. $data['idPaese'] = (string)$idFiscaleIVA->IdPaese;
  742. $data['idCodice'] = (string)$idFiscaleIVA->IdCodice;
  743. $data['partitaIva'] = $data['idPaese'] . $data['idCodice'];
  744. $data['codiceFiscale'] = (string)$datiAnagrafici->CodiceFiscale;
  745. $data['denominazione'] = (string)$datiAnagrafici->Anagrafica->Denominazione;
  746. $data['cognome'] = (string)$datiAnagrafici->Anagrafica->Cognome;
  747. $data['nome'] = (string)$datiAnagrafici->Anagrafica->Nome;
  748. // Estrai dati della sede
  749. $sede = $cedenteNode->Sede;
  750. $data['indirizzo'] = (string)$sede->Indirizzo;
  751. $data['cap'] = (string)$sede->CAP;
  752. $data['comune'] = (string)$sede->Comune;
  753. $data['provincia'] = (string)$sede->Provincia;
  754. $data['nazione'] = (string)$sede->Nazione ?: 'IT';
  755. // Email, se presente
  756. $data['email'] = '';
  757. if (isset($cedenteNode->Contatti) && isset($cedenteNode->Contatti->Email)) {
  758. $data['email'] = (string)$cedenteNode->Contatti->Email;
  759. }
  760. // Dati generali della fattura
  761. $datiGeneraliDocumento = $bodyNode->DatiGenerali->DatiGeneraliDocumento;
  762. $data['tipoDocumento'] = (string)$datiGeneraliDocumento->TipoDocumento;
  763. $data['divisa'] = (string)$datiGeneraliDocumento->Divisa ?: 'EUR';
  764. $data['dataDocumento'] = (string)$datiGeneraliDocumento->Data;
  765. $data['numeroFattura'] = (string)$datiGeneraliDocumento->Numero;
  766. $data['importoTotale'] = (float)$datiGeneraliDocumento->ImportoTotaleDocumento;
  767. // Dati di pagamento
  768. $data['condizioniPagamento'] = '';
  769. $data['modalitaPagamento'] = '';
  770. $data['dataScadenza'] = '';
  771. $data['iban'] = '';
  772. $data['bic'] = '';
  773. $data['istitutoFinanziario'] = '';
  774. if (isset($bodyNode->DatiPagamento)) {
  775. $datiPagamento = $bodyNode->DatiPagamento;
  776. $data['condizioniPagamento'] = (string)$datiPagamento->CondizioniPagamento;
  777. if (isset($datiPagamento->DettaglioPagamento)) {
  778. $dettaglioPagamento = $datiPagamento->DettaglioPagamento;
  779. $data['modalitaPagamento'] = (string)$dettaglioPagamento->ModalitaPagamento;
  780. $data['dataScadenza'] = (string)$dettaglioPagamento->DataScadenzaPagamento;
  781. $data['iban'] = (string)$dettaglioPagamento->IBAN;
  782. $data['bic'] = (string)$dettaglioPagamento->BIC;
  783. $data['istitutoFinanziario'] = (string)$dettaglioPagamento->IstitutoFinanziario;
  784. }
  785. }
  786. // Estrai le linee di dettaglio
  787. $data['linee'] = [];
  788. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DettaglioLinee)) {
  789. foreach ($bodyNode->DatiBeniServizi->DettaglioLinee as $index => $linea) {
  790. if(isset($linea->Quantita)) {
  791. $lineaData = [
  792. 'numeroLinea' => (int)($linea->NumeroLinea ?? ($index + 1)),
  793. 'descrizione' => (string)($linea->Descrizione ?? ''),
  794. 'quantita' => (float)($linea->Quantita ?? 1),
  795. 'prezzoUnitario' => (float)($linea->PrezzoUnitario ?? 0),
  796. 'prezzoTotale' => (float)($linea->PrezzoTotale ?? 0),
  797. 'aliquotaIva' => (float)($linea->AliquotaIVA ?? 0),
  798. ];
  799. // Calcola il prezzo totale se non presente
  800. if ($lineaData['prezzoTotale'] == 0) {
  801. $lineaData['prezzoTotale'] = $lineaData['quantita'] * $lineaData['prezzoUnitario'];
  802. }
  803. $data['linee'][] = $lineaData;
  804. } else {
  805. // Se la linea ha un campo Quantita, non la consideriamo
  806. Log::info("Linea con Quantita non considerata: " . json_encode($linea));
  807. }
  808. }
  809. }
  810. $data['riepilogo'] = null;
  811. if (isset($bodyNode->DatiBeniServizi) && isset($bodyNode->DatiBeniServizi->DatiRiepilogo)) {
  812. $riepilogoNode = $bodyNode->DatiBeniServizi->DatiRiepilogo;
  813. if ($riepilogoNode) {
  814. $data['riepilogo'] = [
  815. 'aliquotaIva' => (float)($riepilogoNode->AliquotaIVA ?? 0),
  816. 'imponibile' => (float)($riepilogoNode->ImponibileImporto ?? 0),
  817. 'imposta' => (float)($riepilogoNode->Imposta ?? 0),
  818. ];
  819. }
  820. }
  821. 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']}");
  822. return $data;
  823. } catch (\Exception $e) {
  824. Log::error("Errore nell'estrazione dei dati XML: " . $e->getMessage());
  825. throw $e;
  826. }
  827. }
  828. /**
  829. * Trova o crea un fornitore basato sui dati della fattura
  830. */
  831. private function findOrCreateSupplier($fatturaData)
  832. {
  833. $supplier = \App\Models\Supplier::where('vat', $fatturaData['partitaIva'])->first();
  834. if (!$supplier) {
  835. Log::info("Creazione nuovo fornitore con P.IVA: {$fatturaData['partitaIva']} ({$fatturaData['denominazione']}) OR ({$fatturaData['nome']}), ({$fatturaData['cognome']})");
  836. $countryId = $this->getCountryId($fatturaData['nazione']);
  837. $provinceId = $this->getProvinceId($fatturaData['provincia']);
  838. $cityId = $this->getCityId($fatturaData['comune']);
  839. $supplier = new \App\Models\Supplier();
  840. $supplier->name = $fatturaData['denominazione'] ?: $fatturaData['cognome'] . ' ' . $fatturaData['nome'];
  841. Log::info("Nome fornitore: " . $supplier->name);
  842. $supplier->vat = $fatturaData['partitaIva'];
  843. $supplier->fiscal_code = $fatturaData['codiceFiscale'];
  844. $supplier->address = $fatturaData['indirizzo'];
  845. $supplier->city_id = $cityId;
  846. $supplier->zip_code = $fatturaData['cap'];
  847. $supplier->province_id = $provinceId;
  848. $supplier->nation_id = $countryId;
  849. $supplier->email = $fatturaData['email'];
  850. $supplier->save();
  851. Log::info("Fornitore creato con ID: " . $supplier->id);
  852. }
  853. return $supplier;
  854. }
  855. /**
  856. * Trova l'ID della nazione dal codice
  857. */
  858. private function getCountryId($nationCode)
  859. {
  860. $country = DB::table('nations')->where('code', $nationCode)->first();
  861. return $country ? $country->id : null;
  862. }
  863. /**
  864. * Trova l'ID della provincia dal codice
  865. */
  866. private function getProvinceId($provinceCode)
  867. {
  868. $province = DB::table('provinces')->where('code', $provinceCode)->first();
  869. return $province ? $province->id : null;
  870. }
  871. /**
  872. * Trova l'ID della città dal nome
  873. */
  874. private function getCityId($cityName)
  875. {
  876. if (empty($cityName)) return null;
  877. $city = DB::table('cities')->where('name', $cityName)->first();
  878. return $city ? $city->id : null;
  879. }
  880. /**
  881. * Trova l'ID del metodo di pagamento dal codice
  882. */
  883. private function findPaymentMethod($paymentCode)
  884. {
  885. if (!empty($paymentCode)) {
  886. $paymentMethod = DB::table('payment_methods')->where('code', $paymentCode)->first();
  887. if ($paymentMethod) {
  888. Log::info("Metodo di pagamento trovato: $paymentCode (ID: {$paymentMethod->id})");
  889. return $paymentMethod->id;
  890. }
  891. }
  892. // Cerca il metodo di pagamento predefinito - corretto per evitare l'errore della colonna 'default'
  893. // Verifica se esiste una colonna 'is_default' o simile
  894. $possibleDefaultColumns = ['is_default', 'is_default_method', 'default_method', 'primary'];
  895. $defaultPaymentMethod = null;
  896. foreach ($possibleDefaultColumns as $column) {
  897. if (Schema::hasColumn('payment_methods', $column)) {
  898. $defaultPaymentMethod = DB::table('payment_methods')->where($column, 1)->first();
  899. if ($defaultPaymentMethod) {
  900. Log::info("Usando metodo di pagamento predefinito (colonna $column) ID: {$defaultPaymentMethod->id}");
  901. break;
  902. }
  903. }
  904. }
  905. // Se non è stato trovato un metodo predefinito, prendi il primo disponibile
  906. if (!$defaultPaymentMethod) {
  907. $defaultPaymentMethod = DB::table('payment_methods')->first();
  908. if ($defaultPaymentMethod) {
  909. Log::info("Usando il primo metodo di pagamento disponibile ID: {$defaultPaymentMethod->id}");
  910. }
  911. }
  912. if ($defaultPaymentMethod) {
  913. return $defaultPaymentMethod->id;
  914. }
  915. throw new \Exception("Nessun metodo di pagamento disponibile nel sistema");
  916. }
  917. /**
  918. * Crea un record nella tabella records
  919. */
  920. private function createRecord($supplierId, $paymentMethodId, $fatturaData)
  921. {
  922. $record = new \App\Models\Record();
  923. $record->supplier_id = $supplierId;
  924. $record->payment_method_id = $paymentMethodId;
  925. $record->date = $fatturaData['dataDocumento'];
  926. $record->data_pagamento = $fatturaData['dataDocumento'];
  927. $record->numero_fattura = $fatturaData['numeroFattura'];
  928. $record->type = 'OUT';
  929. $record->commercial = 1;
  930. $record->corrispettivo_fiscale = 0;
  931. $record->deleted = 0;
  932. $record->financial_movement = 1;
  933. $record->amount = $fatturaData['importoTotale'];
  934. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  935. $record->is_ricevuta = true;
  936. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  937. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  938. }
  939. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  940. $record->IBAN = $fatturaData['iban'];
  941. }
  942. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  943. $record->BIC = $fatturaData['bic'];
  944. }
  945. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  946. $record->data_scadenza = $fatturaData['dataScadenza'];
  947. }
  948. $record->save();
  949. Log::info("Nuovo record creato con ID: " . $record->id);
  950. return $record;
  951. }
  952. /**
  953. * Aggiorna un record esistente nella tabella records
  954. */
  955. private function updateRecord($record, $paymentMethodId, $fatturaData)
  956. {
  957. $record->payment_method_id = $paymentMethodId;
  958. $record->date = $fatturaData['dataDocumento'];
  959. $record->data_pagamento = $fatturaData['dataDocumento'];
  960. $record->type = 'OUT';
  961. $record->commercial = 1;
  962. $record->corrispettivo_fiscale = 0;
  963. $record->deleted = 0;
  964. $record->financial_movement = 1;
  965. $record->amount = $fatturaData['importoTotale'];
  966. $record->tipo_documento = $this->mapTipoDocumento($fatturaData['tipoDocumento']);
  967. $record->is_ricevuta = true;
  968. if (isset($fatturaData['condizioniPagamento']) && !empty($fatturaData['condizioniPagamento'])) {
  969. $record->condizioni_pagamento = $this->mapCondizioniPagamento($fatturaData['condizioniPagamento']);
  970. }
  971. if (isset($fatturaData['iban']) && !empty($fatturaData['iban'])) {
  972. $record->IBAN = $fatturaData['iban'];
  973. }
  974. if (isset($fatturaData['bic']) && !empty($fatturaData['bic'])) {
  975. $record->BIC = $fatturaData['bic'];
  976. }
  977. if (isset($fatturaData['dataScadenza']) && !empty($fatturaData['dataScadenza'])) {
  978. $record->data_scadenza = $fatturaData['dataScadenza'];
  979. }
  980. $record->save();
  981. Log::info("Record esistente aggiornato con ID: " . $record->id);
  982. return $record;
  983. }
  984. /**
  985. * Crea un record row per il record specificato
  986. */
  987. private function createRecordRow($recordId, $fatturaData)
  988. {
  989. Log::info("Inizio creazione RecordRow per Record ID: " . $recordId);
  990. $existingRows = \App\Models\RecordRow::where('record_id', $recordId)->get();
  991. // Delete existing rows if they exist
  992. if ($existingRows->count() > 0) {
  993. Log::info("Eliminazione di " . $existingRows->count() . " righe record esistenti per Record ID: " . $recordId);
  994. foreach ($existingRows as $row) {
  995. $row->delete();
  996. }
  997. }
  998. if (!empty($fatturaData['linee'])) {
  999. foreach ($fatturaData['linee'] as $linea) {
  1000. $this->createSingleRecordRow($recordId, $fatturaData, $linea);
  1001. }
  1002. } else if ($fatturaData['riepilogo']) {
  1003. $this->createRecordRowFromRiepilogo($recordId, $fatturaData);
  1004. Log::info("Creata una riga di record dai dati di riepilogo");
  1005. } else {
  1006. $this->createDefaultRecordRow($recordId, $fatturaData);
  1007. Log::info("Creata una riga di record predefinita dall'importo totale");
  1008. }
  1009. }
  1010. private function createSingleRecordRow($recordId, $fatturaData, $linea)
  1011. {
  1012. Log::info("Inizio creazione riga record singola per Record ID: " . $recordId . ", Linea: " . json_encode($linea));
  1013. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1014. $month = $dataObj->format('n');
  1015. $year = $dataObj->format('Y');
  1016. $period = "$month-$year";
  1017. $whenData = [[
  1018. 'month' => $month,
  1019. 'year' => $year,
  1020. 'period' => $period
  1021. ]];
  1022. $recordRow = new \App\Models\RecordRow();
  1023. $recordRow->record_id = $recordId;
  1024. $recordRow->causal_id = $this->selectedCausal;
  1025. $recordRow->amount = $linea['prezzoTotale'] + $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  1026. $recordRow->note = $linea['descrizione'];
  1027. $recordRow->commercial = 1;
  1028. $recordRow->when = json_encode($whenData);
  1029. $recordRow->aliquota_iva = $linea['aliquotaIva'];
  1030. $recordRow->imponibile = $linea['prezzoTotale'];
  1031. $recordRow->imposta = $linea['prezzoTotale'] * ($linea['aliquotaIva'] / 100);
  1032. $recordRow->divisa = $fatturaData['divisa'];
  1033. $recordRow->numero_linea = $linea['numeroLinea'];
  1034. $recordRow->prezzo_unitario = $linea['prezzoUnitario'];
  1035. $recordRow->quantita = $linea['quantita'];
  1036. Log::info("Dati riga record prima del salvataggio: " . json_encode([
  1037. 'record_id' => $recordRow->record_id,
  1038. 'causal_id' => $recordRow->causal_id,
  1039. 'amount' => $recordRow->amount,
  1040. 'note' => $recordRow->note,
  1041. 'aliquota_iva' => $recordRow->aliquota_iva,
  1042. 'imponibile' => $recordRow->imponibile,
  1043. 'imposta' => $recordRow->imposta,
  1044. 'divisa' => $recordRow->divisa,
  1045. 'numero_linea' => $recordRow->numero_linea,
  1046. 'prezzo_unitario' => $recordRow->prezzo_unitario,
  1047. 'quantita' => $recordRow->quantita,
  1048. ]));
  1049. $recordRow->save();
  1050. Log::info("Riga record creata per linea {$linea['numeroLinea']}: {$linea['descrizione']} (€{$linea['prezzoTotale']})");
  1051. }
  1052. private function createRecordRowFromRiepilogo($recordId, $fatturaData)
  1053. {
  1054. Log::info("Inizio creazione riga record da riepilogo per Record ID: " . $recordId . ", Riepilogo: " . json_encode($fatturaData['riepilogo']));
  1055. $riepilogo = $fatturaData['riepilogo'];
  1056. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1057. $month = $dataObj->format('n');
  1058. $year = $dataObj->format('Y');
  1059. $period = "$month-$year";
  1060. $whenData = [[
  1061. 'month' => $month,
  1062. 'year' => $year,
  1063. 'period' => $period
  1064. ]];
  1065. $total_amount = $riepilogo['imponibile'] + $riepilogo['imposta'];
  1066. $recordRow = new \App\Models\RecordRow();
  1067. $recordRow->record_id = $recordId;
  1068. $recordRow->causal_id = $this->selectedCausal;
  1069. $recordRow->amount = $total_amount;
  1070. $recordRow->commercial = 1;
  1071. $recordRow->when = json_encode($whenData);
  1072. $recordRow->aliquota_iva = $riepilogo['aliquotaIva'];
  1073. $recordRow->imponibile = $riepilogo['imponibile'];
  1074. $recordRow->imposta = $riepilogo['imposta'];
  1075. $recordRow->divisa = $fatturaData['divisa'];
  1076. $recordRow->numero_linea = 1;
  1077. $recordRow->quantita = 1;
  1078. Log::info("Dati riga record da riepilogo prima del salvataggio: " . json_encode([
  1079. 'record_id' => $recordRow->record_id,
  1080. 'causal_id' => $recordRow->causal_id,
  1081. 'amount' => $recordRow->amount,
  1082. 'aliquota_iva' => $recordRow->aliquota_iva,
  1083. 'imponibile' => $recordRow->imponibile,
  1084. 'imposta' => $recordRow->imposta,
  1085. 'divisa' => $recordRow->divisa,
  1086. ]));
  1087. $recordRow->save();
  1088. Log::info("Riga record creata da riepilogo: Imponibile={$riepilogo['imponibile']}, IVA={$riepilogo['aliquotaIva']}%");
  1089. }
  1090. private function createDefaultRecordRow($recordId, $fatturaData)
  1091. {
  1092. Log::info("Inizio creazione riga record predefinita per Record ID: " . $recordId . ", Importo Totale: " . $fatturaData['importoTotale']);
  1093. $dataObj = new \DateTime($fatturaData['dataDocumento']);
  1094. $month = $dataObj->format('n');
  1095. $year = $dataObj->format('Y');
  1096. $period = "$month-$year";
  1097. $whenData = [[
  1098. 'month' => $month,
  1099. 'year' => $year,
  1100. 'period' => $period
  1101. ]];
  1102. $recordRow = new \App\Models\RecordRow();
  1103. $recordRow->record_id = $recordId;
  1104. $recordRow->causal_id = $this->selectedCausal;
  1105. $recordRow->amount = $fatturaData['importoTotale'];
  1106. $recordRow->commercial = 1;
  1107. $recordRow->when = json_encode($whenData);
  1108. $recordRow->divisa = $fatturaData['divisa'];
  1109. $recordRow->numero_linea = 1;
  1110. $recordRow->quantita = 1;
  1111. Log::info("Dati riga record predefinita prima del salvataggio: " . json_encode([
  1112. 'record_id' => $recordRow->record_id,
  1113. 'causal_id' => $recordRow->causal_id,
  1114. 'amount' => $recordRow->amount,
  1115. 'divisa' => $recordRow->divisa,
  1116. ]));
  1117. $recordRow->save();
  1118. Log::info("Riga record predefinita creata con importo totale: {$fatturaData['importoTotale']}");
  1119. }
  1120. private function mapTipoDocumento($codice)
  1121. {
  1122. $tipiDocumento = [
  1123. 'TD01' => 'Fattura',
  1124. 'TD02' => 'Acconto/Anticipo su fattura',
  1125. 'TD03' => 'Acconto/Anticipo su parcella',
  1126. 'TD04' => 'Nota di credito',
  1127. 'TD05' => 'Nota di debito',
  1128. 'TD06' => 'Parcella',
  1129. 'TD16' => 'Integrazione fattura reverse charge interno',
  1130. 'TD17' => 'Integrazione/autofattura per acquisto servizi dall\'estero',
  1131. 'TD18' => 'Integrazione per acquisto di beni intracomunitari',
  1132. 'TD19' => 'Integrazione/autofattura per acquisto di beni ex art.17 c.2 DPR 633/72',
  1133. 'TD20' => 'Autofattura per regolarizzazione e integrazione delle fatture',
  1134. 'TD21' => 'Autofattura per splafonamento',
  1135. 'TD22' => 'Estrazione beni da Deposito IVA',
  1136. 'TD23' => 'Estrazione beni da Deposito IVA con versamento dell\'IVA',
  1137. 'TD24' => 'Fattura differita di cui all\'art.21, comma 4, lett. a)',
  1138. 'TD25' => 'Fattura differita di cui all\'art.21, comma 4, terzo periodo lett. b)',
  1139. 'TD26' => 'Cessione di beni ammortizzabili e per passaggi interni',
  1140. 'TD27' => 'Fattura per autoconsumo o per cessioni gratuite senza rivalsa'
  1141. ];
  1142. return $tipiDocumento[$codice] ?? $codice;
  1143. }
  1144. private function mapCondizioniPagamento($codice)
  1145. {
  1146. $condizioniPagamento = [
  1147. 'TP01' => 'Pagamento a rate',
  1148. 'TP02' => 'Pagamento completo',
  1149. 'TP03' => 'Anticipo'
  1150. ];
  1151. return $condizioniPagamento[$codice] ?? $codice;
  1152. }
  1153. private function showResultMessages($importCount, $updateCount, $errorsCount)
  1154. {
  1155. $message = "";
  1156. $messageType = "success";
  1157. if ($importCount > 0) {
  1158. $message .= "Importate $importCount nuove fatture.<br>";
  1159. }
  1160. if ($updateCount > 0) {
  1161. $message .= "Aggiornate $updateCount fatture esistenti.<br>";
  1162. }
  1163. if ($errorsCount > 0) {
  1164. $message .= "$errorsCount fatture non sono state importate a causa di errori.<br>";
  1165. // Aggiungi i dettagli degli errori se disponibili
  1166. if (!empty($errorMessages)) {
  1167. $message .= "<details><summary>Dettagli errori (clicca per espandere)</summary><ul>";
  1168. foreach ($errorMessages as $errorMsg) {
  1169. $message .= "<li>" . htmlspecialchars($errorMsg) . "</li>";
  1170. }
  1171. $message .= "</ul></details>";
  1172. }
  1173. if ($importCount == 0 && $updateCount == 0) {
  1174. $messageType = "error";
  1175. } else {
  1176. $messageType = "warning";
  1177. }
  1178. }
  1179. if ($importCount > 0 || $updateCount > 0) {
  1180. $this->emit('show-import-result', [
  1181. 'message' => $message,
  1182. 'type' => $messageType
  1183. ]);
  1184. } else {
  1185. $this->emit('show-import-result', [
  1186. 'message' => 'Nessuna fattura importata. Controlla i file XML e riprova.',
  1187. 'type' => 'error'
  1188. ]);
  1189. }
  1190. // Resetta i campi del form dopo l'importazione
  1191. $this->reset(['receiptFiles']);
  1192. }
  1193. }