RecordOUT.php 53 KB

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