RecordIN.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Livewire\WithPagination;
  5. use Barryvdh\DomPDF\Facade\Pdf;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Facades\Mail;
  8. use Illuminate\Contracts\Validation\Validator;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Http\Middleware\TenantMiddleware;
  11. class RecordIN extends Component
  12. {
  13. use WithPagination;
  14. protected $paginationTheme = 'bootstrap';
  15. protected $listeners = ['setCausal' => 'setCausal', 'refreshMembers' => 'refreshMembers', 'scontoChanged' => 'updateSconto'];
  16. public $sortField = 'date';
  17. public $sortAsc = false;
  18. public $typeIN = "IN";
  19. public $fromPage = '';
  20. public $isDuplicate = false;
  21. public $multiP = false;
  22. public $from, $to;
  23. public $multiMonthTo = 0;
  24. public $multiYearTo = 0;
  25. public $multiMonthFrom = 0;
  26. public $multiYearFrom = 0;
  27. public $createSubscription = 0;
  28. public $corrispettivo_causal_id = 0;
  29. public function sortBy($field)
  30. {
  31. if ($this->sortField === $field) {
  32. $this->sortAsc = ! $this->sortAsc;
  33. } else {
  34. $this->sortAsc = true;
  35. }
  36. $this->sortField = $field;
  37. }
  38. public $courseId = 0;
  39. public $rateId = 0;
  40. public $months = array();
  41. public $records, $dataId, $member_id, $supplier_id,
  42. $causal_id,
  43. $payment_method_id,
  44. $date,
  45. $month,
  46. $year,
  47. $type,
  48. $deleted,
  49. $financial_movement,
  50. $amount,
  51. $vat,
  52. $virtual,
  53. $note,
  54. $parent,
  55. $corrispettivo_fiscale,
  56. $commercial, $update = false, $add = false;
  57. public $corrispettivo = [];
  58. public $currentReceip;
  59. public $filterMember = 0, $filterPaymentMethod = 0, $filterCausals = 0, $filterFrom = '', $filterTo = '', $filterCommercial = 0;
  60. public $hasFilter = false;
  61. public $total = 0;
  62. public $selectedFilter = '';
  63. public $multipleIds = [];
  64. public $multipleAction = '';
  65. public $first = true;
  66. public $selectId = 0;
  67. public $refreshAfter = 0;
  68. public $sconto = 0;
  69. public $canSave = true;
  70. public $newMemberFirstName = '';
  71. public $newMemberLastName = '';
  72. public $newMemberEmail = '';
  73. public $newMemberToComplete = false;
  74. public $newMemberFiscalCode = '';
  75. public $newMemberFiscalCodeExist = false;
  76. public $causals = array();
  77. public $payments = array();
  78. public $members = array();
  79. public $vats = array();
  80. public $rows = array();
  81. public $fromCourse = false;
  82. public $backToRates = false;
  83. protected $rules = [
  84. 'member_id' => 'required',
  85. 'payment_method_id' => 'required',
  86. 'rows.*.causal_id' => 'required',
  87. 'rows.*.amount' => 'required'
  88. ];
  89. protected $messages = [
  90. 'member_id.required' => 'La persona è obbligatorio',
  91. 'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
  92. 'rows.*.causal_id.required' => 'La causale è obbligatoria',
  93. 'rows.*.amount.required' => 'L\'importo è obbligatorio',
  94. ];
  95. public function boot()
  96. {
  97. app(TenantMiddleware::class)->setupTenantConnection();
  98. }
  99. public function updatedMemberId()
  100. {
  101. $this->emit('refresh');
  102. if ($this->member_id > 0) {
  103. $member = \App\Models\Member::findOrFail($this->member_id);
  104. if (!$member->isAdult()) {
  105. if ($member->father_name != '')
  106. $this->parent = $member->father_name . " (C.F. " . $member->father_fiscal_code . ")";
  107. else if ($member->mother_name != '')
  108. $this->parent = $member->mother_name . " (C.F. " . $member->mother_fiscal_code . ")";
  109. else
  110. $this->parent = '';
  111. }
  112. $this->virtual = $member->getMoney();
  113. $this->newMemberFirstName = '';
  114. $this->newMemberLastName = '';
  115. $this->newMemberEmail = '';
  116. $this->newMemberToComplete = false;
  117. $this->newMemberFiscalCode = '';
  118. $this->newMemberFiscalCodeExist = false;
  119. }
  120. }
  121. public function updatedCausalId()
  122. {
  123. //$this->emit('refresh');
  124. }
  125. public function updatedDate()
  126. {
  127. //$this->emit('refresh');
  128. }
  129. public function hydrate()
  130. {
  131. $this->emit('load-select');
  132. }
  133. /*public function updated() {
  134. $this->emit('refresh');
  135. }*/
  136. public function updatedPaymentMethodId()
  137. {
  138. //$this->emit('refresh');
  139. $this->canSave = $this->checkCanSave();
  140. }
  141. public function updatedAmount()
  142. {
  143. // $this->emit('refresh');
  144. $this->canSave = $this->checkCanSave();
  145. }
  146. public function updatedCommercial($value)
  147. {
  148. $this->emitSelf('refreshMembers');
  149. }
  150. public function updateSconto()
  151. {
  152. $totalSconto = 0;
  153. foreach ($this->rows as $row) {
  154. if (isset($row['sconto']) && $row['sconto'] != null && $row['sconto'] != "") {
  155. $totalSconto += $this->currencyToDouble($row['sconto']);
  156. }
  157. }
  158. $this->sconto = formatPrice($totalSconto);
  159. Log::info("Total sconto updated to: " . $this->sconto);
  160. }
  161. public function checkCanSave()
  162. {
  163. $ret = true;
  164. if ($this->payment_method_id != null) {
  165. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  166. if ($payment_method->money) {
  167. $from = str_replace(".", "", str_replace(",", "", number_format($this->virtual, 2)));
  168. $this->from = $this->virtual;
  169. $from = $this->from;
  170. $to = str_replace(".", "", str_replace(",", "", $this->currencyToDouble($this->amount)));
  171. $this->to = $this->amount;
  172. $to = $this->to;
  173. $ret = $from >= $to;
  174. }
  175. }
  176. return $ret;
  177. }
  178. public function refreshMembers()
  179. {
  180. if ($this->add || $this->update) {
  181. if ($this->commercial) {
  182. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
  183. } else {
  184. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->where('current_status', 2)->orWhere('current_status', 1)->orderBy('last_name')->orderBy('first_name')->get();
  185. }
  186. } else
  187. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
  188. }
  189. public function setAmount()
  190. {
  191. $tot = 0;
  192. foreach ($this->rows as $r) {
  193. $tot += $this->currencyToDouble($r["amount"]);
  194. }
  195. $this->amount = $tot;
  196. $this->canSave = $this->checkCanSave();
  197. }
  198. public function resetFields()
  199. {
  200. $this->member_id = null;
  201. $this->supplier_id = null;
  202. $this->payment_method_id = null;
  203. $this->commercial = 0;
  204. $this->corrispettivo_fiscale = false;
  205. $this->date = date("Y-m-d");
  206. $this->type = 'IN';
  207. $this->deleted = false;
  208. $this->financial_movement = false;
  209. $this->newMemberFirstName = '';
  210. $this->newMemberLastName = '';
  211. $this->newMemberEmail = '';
  212. $this->newMemberToComplete = false;
  213. $this->newMemberFiscalCode = '';
  214. $this->newMemberFiscalCodeExist = false;
  215. $this->currentReceip = null;
  216. $this->parent = '';
  217. $this->courseId = 0;
  218. $this->rateId = 0;
  219. $this->backToRates = false;
  220. $this->months = array();
  221. $this->rows = array();
  222. $this->rows[] = array('causal_id' => isset($_GET["causalId"]) ? $_GET["causalId"] : null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0, 'sconto' => 0);
  223. $this->corrispettivo = [];
  224. $this->emit('load-data-table');
  225. }
  226. public function getMemberProperty()
  227. {
  228. $ret = null;
  229. if ($this->member_id > 0) {
  230. $ret = \App\Models\Member::findOrFail($this->member_id);
  231. }
  232. return $ret;
  233. }
  234. public function getCausalProperty()
  235. {
  236. $ret = null;
  237. if ($this->causal_id > 0) {
  238. $ret = \App\Models\Causal::findOrFail($this->causal_id);
  239. }
  240. return $ret;
  241. }
  242. public function getCausal($causal)
  243. {
  244. $ret = '';
  245. if ($causal > 0) {
  246. $ret = \App\Models\Causal::findOrFail($causal)->getTree();
  247. }
  248. return $ret;
  249. }
  250. public function getPaymentMethod($payment)
  251. {
  252. $ret = '';
  253. if ($payment > 0) {
  254. $ret = \App\Models\PaymentMethod::findOrFail($payment)->name;
  255. }
  256. return $ret;
  257. }
  258. function buildTree($records, $parentId = 0)
  259. {
  260. $this->causals = array();
  261. foreach ($records as $record) {
  262. if ($record->parent_id == $parentId) {
  263. $children = $this->buildTree($record, $record->id);
  264. if ($children) {
  265. $record->children = $children;
  266. }
  267. $this->causals[] = $record;
  268. }
  269. }
  270. return $this->causals;
  271. }
  272. public function getCausale($records, $indentation)
  273. {
  274. foreach ($records as $record) {
  275. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  276. if (count($record->childs))
  277. $this->getCausale($record->childs, $indentation + 1);
  278. }
  279. }
  280. public function mount()
  281. {
  282. if (isset($_GET["from"])) {
  283. $this->fromPage = $_GET["from"];
  284. }
  285. $this->causals = array();
  286. $this->multiMonthFrom = date("n");
  287. $this->multiYearFrom = date("Y");
  288. $this->multiMonthTo = date("n");
  289. $this->multiYearTo = date("Y");
  290. $fisc = \App\Models\Causal::where('corrispettivo_fiscale', true)->first();
  291. if ($fisc)
  292. $this->corrispettivo_causal_id = $fisc->id;
  293. $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'IN')->get(), 0);
  294. //$this->buildTree(\App\Models\Causal::all(), null);
  295. $this->refreshMembers();
  296. $this->payments = \App\Models\PaymentMethod::select('id', 'name')->where('enabled', true)->whereIn('type', array('ALL', 'IN'))->orderBy('name')->get();
  297. $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
  298. if ($this->first) {
  299. if (isset($_GET["new"])) {
  300. $this->refreshAfter = 1;
  301. $this->add();
  302. }
  303. if (isset($_GET["memberId"])) {
  304. $this->refreshAfter = 1;
  305. $this->member_id = $_GET["memberId"];
  306. $member = \App\Models\Member::findOrFail($this->member_id);
  307. if (!$member->isAdult()) {
  308. if ($member->father_name != '')
  309. $this->parent = $member->father_name . " (C.F. " . $member->father_fiscal_code . ")";
  310. else if ($member->mother_name != '')
  311. $this->parent = $member->mother_name . " (C.F. " . $member->mother_fiscal_code . ")";
  312. else
  313. $this->parent = '';
  314. }
  315. }
  316. if (isset($_GET["causalId"])) {
  317. $this->refreshAfter = 1;
  318. $this->causal_id = $_GET["causalId"];
  319. }
  320. if (isset($_GET["id"])) {
  321. $this->refreshAfter = 1;
  322. $this->edit($_GET["id"]);
  323. }
  324. $count = 0;
  325. if (isset($_GET["courseId"])) {
  326. $this->courseId = $_GET["courseId"];
  327. $mc = \App\Models\MemberCourse::findOrFail($this->courseId);
  328. $course = \App\Models\Course::findOrFail($mc->course_id);
  329. }
  330. if (isset($_GET["rateId"])) {
  331. $this->rateId = $_GET["rateId"];
  332. }
  333. if (isset($_GET["backToRates"])) {
  334. $this->backToRates = true;
  335. }
  336. if (isset($_GET["months"]) && $_GET["months"] != '') {
  337. $this->fromCourse = true;
  338. $price = $_GET["price"] / 100 * 100;
  339. $this->refreshAfter = 1;
  340. $desc = "Pagamento";
  341. $months = explode("|", $_GET["months"]);
  342. $this->months = $months;
  343. //$this->rows[0]["amount"] = formatPrice($price * sizeof($months));
  344. $this->rows[0]["amount"] = formatPrice($price);
  345. foreach ($months as $idx => $m) {
  346. $this->rows[0]["when"][$idx]["month"] = $m;
  347. if ($m >= date("m"))
  348. $this->rows[0]["when"][$idx]["year"] = date("Y");
  349. else
  350. $this->rows[0]["when"][$idx]["year"] = date("Y") + 1;
  351. if ($idx > 0) {
  352. if ($this->rows[0]["when"][$idx - 1]["year"] != $this->rows[0]["when"][$idx]["year"])
  353. $desc .= " " . $this->rows[0]["when"][$idx - 1]["year"] . " ";
  354. }
  355. $desc .= " " . $this->getMonth($m); // . " " . $this->rows[0]["when"][$idx]["year"];
  356. }
  357. $desc .= " " . $this->rows[0]["when"][$idx]["year"];
  358. $this->rows[0]["note"] = $desc;
  359. $count += 1;
  360. }
  361. if (isset($_GET["createSubscription"]) && $_GET["createSubscription"] == 1) {
  362. $this->createSubscription = 1;
  363. $this->courseId = $_GET["courseId"];
  364. $this->rateId = $_GET["rateId"];
  365. $price = $_GET["subscription_price"] / 100 * 100;
  366. $this->refreshAfter = 1;
  367. if ($count == 1)
  368. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  369. $this->rows[$count]["causal_id"] = null;
  370. $this->rows[$count]["amount"] = formatPrice($price);
  371. $this->rows[$count]["note"] = "Pagamento iscrizione " . $course->name;
  372. if (isset($_GET["subCausalId"])) {
  373. $this->refreshAfter = 1;
  374. $this->rows[$count]["causal_id"] = $_GET["subCausalId"];
  375. }
  376. }
  377. }
  378. $this->first = false;
  379. }
  380. public function search()
  381. {
  382. $this->hasFilter = true;
  383. }
  384. public function disableSearch()
  385. {
  386. $this->filterMember = 0;
  387. $this->filterPaymentMethod = 0;
  388. $this->filterCausals = 0;
  389. $this->filterTo = '';
  390. $this->filterFrom = '';
  391. $this->filterCommercial = 0;
  392. $this->hasFilter = false;
  393. $this->total = 0;
  394. }
  395. public function render()
  396. {
  397. $datas = [];
  398. return view('livewire.records_in', ['datas' => $datas]);
  399. }
  400. public function executeMultipleAction()
  401. {
  402. if ($this->multipleAction == 'delete')
  403. $this->multipleDelete();
  404. }
  405. public function add()
  406. {
  407. $this->emit('load-select');
  408. //if ($this->hasFilter)
  409. $this->emit('hide-search');
  410. $this->resetFields();
  411. $this->dataId = 0;
  412. $this->add = true;
  413. $this->update = false;
  414. $this->emit('setEdit', true);
  415. }
  416. public function storeCorrispettivo()
  417. {
  418. $this->emit('refresh');
  419. $rules = [
  420. 'member_id' => 'required'
  421. ];
  422. $this->validate($rules);
  423. foreach ($this->payments as $p) {
  424. if ($p->corrispettivo_fiscale) {
  425. $price = isset($this->corrispettivo[$p->id]) ? $this->currencyToDouble($this->corrispettivo[$p->id]) : 0;
  426. if ($price > 0) {
  427. $record = \App\Models\Record::create([
  428. 'member_id' => $this->member_id,
  429. 'supplier_id' => null,
  430. 'payment_method_id' => $p->id,
  431. 'commercial' => $this->commercial,
  432. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  433. 'date' => $this->date,
  434. 'type' => $this->type,
  435. 'amount' => $price,
  436. 'financial_movement' => $this->financial_movement,
  437. 'deleted' => $this->deleted
  438. ]);
  439. \App\Models\RecordRow::create([
  440. 'record_id' => $record->id,
  441. 'causal_id' => $this->corrispettivo_causal_id,
  442. 'note' => '',
  443. 'amount' => $price,
  444. 'vat_id' => null,
  445. 'commercial' => $this->commercial,
  446. 'when' => json_encode([])
  447. ]);
  448. }
  449. }
  450. }
  451. $this->resetFields();
  452. $this->add = false;
  453. $this->isDuplicate = false;
  454. $this->emit('setEdit', false);
  455. }
  456. public function store($generate)
  457. {
  458. Log::info("Starting store method");
  459. $this->emit('refresh');
  460. $rules = [
  461. 'payment_method_id' => 'required',
  462. 'rows.*.causal_id' => 'required',
  463. 'rows.*.amount' => 'required'
  464. ];
  465. if (!$this->commercial)
  466. $rules["member_id"] = 'required';
  467. $this->validate($rules);
  468. /* Validazione campi azienda per generazione ricevuta */
  469. try {
  470. if (!$this->financial_movement && !$this->commercial) {
  471. $no_receipt_causal_azienda = false;
  472. foreach ($this->rows as $row) {
  473. $no_receipt_causal_azienda = false;
  474. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  475. if ($cau->no_receipt)
  476. $no_receipt_causal_azienda = true;
  477. }
  478. $azienda = \App\Models\Azienda::first();
  479. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  480. if (!$payment_method->money) {
  481. if (!$no_receipt_causal_azienda) {
  482. if (!$azienda->isValid()) {
  483. session()->flash('error_ricevuta', implode("", array_map(function ($item) {
  484. return "<li>$item</li>";
  485. }, $azienda->validate())));
  486. return false;
  487. }
  488. }
  489. }
  490. }
  491. } catch (\Exception $ex) {
  492. Log::error("Error in store method: " . $ex->getMessage());
  493. Log::error("Stack trace: " . $ex->getTraceAsString());
  494. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  495. }
  496. /* END - Validazione campi azienda per generazione ricevuta */
  497. try {
  498. $totalGross = 0;
  499. $totalSconto = 0;
  500. $totalNet = 0;
  501. foreach ($this->rows as $row) {
  502. $rowAmount = $this->currencyToDouble($row["amount"]);
  503. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  504. $rowNet = max(0, $rowAmount - $rowSconto);
  505. $totalGross += $rowAmount;
  506. $totalSconto += $rowSconto;
  507. $totalNet += $rowNet;
  508. }
  509. Log::info("Total gross: " . $totalGross . ", Total sconto: " . $totalSconto . ", Total net: " . $totalNet);
  510. $record = \App\Models\Record::create([
  511. 'member_id' => $this->member_id,
  512. 'supplier_id' => $this->supplier_id,
  513. 'payment_method_id' => $this->payment_method_id,
  514. 'commercial' => $this->commercial,
  515. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  516. 'date' => $this->date,
  517. 'type' => $this->type,
  518. 'amount' => $totalNet,
  519. 'prediscount_amount' => $totalGross,
  520. 'financial_movement' => $this->financial_movement,
  521. 'deleted' => $this->deleted,
  522. 'numero_fattura' => '',
  523. ]);
  524. $this->dataId = $record->id;
  525. $no_receipt_causal = false;
  526. $vat = 0;
  527. foreach ($this->rows as $row) {
  528. foreach ($row["when"] as $x => $y) {
  529. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  530. }
  531. $rowAmount = $this->currencyToDouble($row["amount"]);
  532. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  533. $rowNet = max(0, $rowAmount - $rowSconto);
  534. Log::info("Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  535. \App\Models\RecordRow::create([
  536. 'record_id' => $this->dataId,
  537. 'causal_id' => $row["causal_id"],
  538. 'note' => $row["note"],
  539. 'amount' => $rowNet,
  540. 'prediscount_amount' => $rowAmount,
  541. 'sconto' => $rowSconto,
  542. 'vat_id' => $row["vat_id"],
  543. 'commercial' => $this->commercial,
  544. 'when' => json_encode($row["when"])
  545. ]);
  546. $vat += getVatValue($rowNet, $row["vat_id"]);
  547. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  548. if ($cau->no_receipt)
  549. $no_receipt_causal = true;
  550. if ($cau->money) {
  551. if ($rowNet >= env('MIN_MONEY', 100)) {
  552. $money = new \App\Models\Money();
  553. $money->member_id = $this->member_id;
  554. $money->record_id = $this->dataId;
  555. $money->amount = env('EXTRA_MONEY', 10);
  556. $money->date = date("Y-m-d");
  557. $money->note = env('EXTRA_MONEY', 10) . ' in più per aver caricato ' . $rowNet;
  558. $money->save();
  559. }
  560. }
  561. }
  562. Log::info("Final amount saved to record: " . $totalNet);
  563. if (!$this->financial_movement) {
  564. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  565. if (!$payment_method->money) {
  566. if ($generate && !$no_receipt_causal)
  567. $this->createReceipt();
  568. }
  569. }
  570. if ($this->rateId > 0) {
  571. $rates = explode(",", $this->rateId);
  572. foreach($rates as $rid)
  573. {
  574. $rate = \App\Models\Rate::findOrFail($rid);
  575. $rate->status = 1;
  576. $rate->record_id = $record->id;
  577. $rate->save();
  578. }
  579. }
  580. if ($this->backToRates) {
  581. return redirect()->to("/rates?member_id={$this->member_id}&member_course_id={$this->courseId}");
  582. }
  583. session()->flash('success', 'Movimento creato');
  584. $this->resetFields();
  585. $this->add = false;
  586. $this->isDuplicate = false;
  587. $this->emit('setEdit', false);
  588. } catch (\Exception $ex) {
  589. Log::error("Error in store method: " . $ex->getMessage());
  590. Log::error("Stack trace: " . $ex->getTraceAsString());
  591. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  592. }
  593. }
  594. public function duplicate($id)
  595. {
  596. $record = \App\Models\Record::findOrFail($id);
  597. $newRecord = $record->replicate();
  598. $newRecord->save();
  599. $rows = \App\Models\RecordRow::where('record_id', $id)->get();
  600. foreach ($rows as $r) {
  601. $newRow = $r->replicate();
  602. $newRow->record_id = $newRecord->id;
  603. $newRow->save();
  604. }
  605. $this->edit($newRecord->id);
  606. $this->isDuplicate = true;
  607. }
  608. public function edit($id)
  609. {
  610. if (!isset($_GET["from"]) && $this->fromPage == '')
  611. $this->fromPage = 'in';
  612. $this->emit('setEdit', true);
  613. //if ($this->hasFilter)
  614. $this->emit('hide-search');
  615. $this->emit('load-select');
  616. try {
  617. $record = \App\Models\Record::findOrFail($id);
  618. if (!$record) {
  619. session()->flash('error', 'Movimento non trovato');
  620. } else {
  621. if ($record->member_id) {
  622. $member = \App\Models\Member::find($record->member_id);
  623. if (!$member || $member->status == 'archived') {
  624. $this->member_id = null;
  625. } else {
  626. $this->member_id = $record->member_id;
  627. }
  628. } else {
  629. $this->member_id = $record->member_id;
  630. }
  631. if ($record->payment_method_id) {
  632. $paymentMethod = \App\Models\PaymentMethod::find($record->payment_method_id);
  633. if (!$paymentMethod || (isset($paymentMethod->hidden) && $paymentMethod->hidden)) {
  634. $this->payment_method_id = null;
  635. } else {
  636. $this->payment_method_id = $record->payment_method_id;
  637. }
  638. } else {
  639. $this->payment_method_id = $record->payment_method_id;
  640. }
  641. $this->supplier_id = $record->supplier_id;
  642. $this->amount = $record->amount;
  643. $this->commercial = $record->commercial;
  644. $this->corrispettivo_fiscale = $record->corrispettivo_fiscale;
  645. $this->date = date("Y-m-d", strtotime($record->date));
  646. $this->type = $record->type;
  647. $this->deleted = $record->deleted;
  648. $this->financial_movement = $record->financial_movement;
  649. $this->dataId = $record->id;
  650. $this->update = true;
  651. $this->add = false;
  652. $rows = \App\Models\RecordRow::where('record_id', $this->dataId)
  653. ->select('causal_id', 'note', 'commercial', 'when', 'amount', 'prediscount_amount', 'sconto', 'vat_id')
  654. ->get();
  655. $this->rows = [];
  656. foreach ($rows as $i => $r) {
  657. $grossAmount = $r->prediscount_amount ?? ($r->amount + $r->sconto);
  658. $causalId = $r->causal_id;
  659. if ($causalId) {
  660. $causal = \App\Models\Causal::find($causalId);
  661. if (!$causal || (isset($causal->hidden) && $causal->hidden)) {
  662. $causalId = null;
  663. }
  664. }
  665. $this->rows[] = [
  666. 'causal_id' => $causalId,
  667. 'note' => $r->note,
  668. 'commercial' => $r->commercial,
  669. 'when' => json_decode($r->when),
  670. 'amount' => formatPrice($grossAmount),
  671. 'sconto' => formatPrice($r->sconto),
  672. 'vat_id' => $r->vat_id
  673. ];
  674. }
  675. $exist = \App\Models\Receipt::where('record_id', $id)->orderBy('id', 'DESC')->first();
  676. if ($exist != null) {
  677. $this->currentReceip = $exist;
  678. $this->parent = $this->currentReceip->parent;
  679. }
  680. $this->refreshEditOptions();
  681. }
  682. } catch (\Exception $ex) {
  683. Log::error("Error in edit method: " . $ex->getMessage());
  684. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  685. }
  686. }
  687. private function refreshEditOptions()
  688. {
  689. $this->causals = array();
  690. $visibleCausals = \App\Models\Causal::select('id', 'name')
  691. ->where('parent_id', null)
  692. ->where('type', 'IN')
  693. ->where(function ($query) {
  694. $query->where('hidden', false)->orWhereNull('hidden');
  695. })
  696. ->get();
  697. $this->getCausale($visibleCausals, 0);
  698. $this->payments = \App\Models\PaymentMethod::select('id', 'name')
  699. ->where('enabled', true)
  700. ->whereIn('type', array('ALL', 'IN'))
  701. ->where(function ($query) {
  702. $query->where('hidden', false)->orWhereNull('hidden');
  703. })
  704. ->orderBy('name')
  705. ->get();
  706. if ($this->commercial) {
  707. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
  708. ->where(function ($query) {
  709. $query->where('status', '!=', 'archived');
  710. })
  711. ->orderBy('last_name')
  712. ->orderBy('first_name')
  713. ->get();
  714. } else {
  715. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
  716. ->where(function ($query) {
  717. $query->where('current_status', 2)->orWhere('current_status', 1);
  718. })
  719. ->where(function ($query) {
  720. $query->where('status', '!=', 'archived');
  721. })
  722. ->orderBy('last_name')
  723. ->orderBy('first_name')
  724. ->get();
  725. }
  726. }
  727. public function update($generate = false)
  728. {
  729. Log::info("Starting update method");
  730. $this->emit('refresh');
  731. $rules = [
  732. 'payment_method_id' => 'required',
  733. 'rows.*.causal_id' => 'required',
  734. 'rows.*.amount' => 'required'
  735. ];
  736. if (!$this->commercial)
  737. $rules["member_id"] = 'required';
  738. $this->validate($rules);
  739. /* Validazione campi azienda per generazione ricevuta */
  740. try {
  741. if (!$this->financial_movement && !$this->commercial) {
  742. $no_receipt_causal_azienda = false;
  743. foreach ($this->rows as $row) {
  744. $no_receipt_causal_azienda = false;
  745. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  746. if ($cau->no_receipt)
  747. $no_receipt_causal_azienda = true;
  748. }
  749. $azienda = \App\Models\Azienda::first();
  750. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  751. if (!$payment_method->money) {
  752. if (!$no_receipt_causal_azienda) {
  753. if (!$azienda->isValid()) {
  754. session()->flash('error_ricevuta', implode("", array_map(function ($item) {
  755. return "<li>$item</li>";
  756. }, $azienda->validate())));
  757. return false;
  758. }
  759. }
  760. }
  761. }
  762. } catch (\Exception $ex) {
  763. Log::error("Error in store method: " . $ex->getMessage());
  764. Log::error("Stack trace: " . $ex->getTraceAsString());
  765. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  766. }
  767. /* END - Validazione campi azienda per generazione ricevuta */
  768. try {
  769. $totalGross = 0;
  770. $totalSconto = 0;
  771. $totalNet = 0;
  772. foreach ($this->rows as $row) {
  773. $rowAmount = $this->currencyToDouble($row["amount"]);
  774. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  775. $rowNet = max(0, $rowAmount - $rowSconto);
  776. $totalGross += $rowAmount;
  777. $totalSconto += $rowSconto;
  778. $totalNet += $rowNet;
  779. }
  780. Log::info("Total gross: " . $totalGross . ", Total sconto: " . $totalSconto . ", Total net: " . $totalNet);
  781. \App\Models\Record::whereId($this->dataId)->update([
  782. 'member_id' => $this->member_id,
  783. 'supplier_id' => $this->supplier_id,
  784. 'payment_method_id' => $this->payment_method_id,
  785. 'commercial' => $this->commercial,
  786. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  787. 'date' => date("Y-m-d", strtotime($this->date)),
  788. 'type' => $this->type,
  789. 'financial_movement' => $this->financial_movement,
  790. 'deleted' => $this->deleted,
  791. 'amount' => $totalNet,
  792. 'prediscount_amount' => $totalGross,
  793. ]);
  794. $no_receipt_causal = false;
  795. $vat = 0;
  796. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  797. foreach ($this->rows as $row) {
  798. foreach ($row["when"] as $x => $y) {
  799. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  800. }
  801. $rowAmount = $this->currencyToDouble($row["amount"]);
  802. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  803. $rowNet = max(0, $rowAmount - $rowSconto);
  804. Log::info("Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  805. \App\Models\RecordRow::create([
  806. 'record_id' => $this->dataId,
  807. 'causal_id' => $row["causal_id"],
  808. 'note' => $row["note"],
  809. 'vat_id' => $row["vat_id"],
  810. 'amount' => $rowNet,
  811. 'prediscount_amount' => $rowAmount,
  812. 'sconto' => $rowSconto,
  813. 'commercial' => $this->commercial,
  814. 'when' => json_encode($row["when"])
  815. ]);
  816. $vat += getVatValue($rowNet, $row["vat_id"]);
  817. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  818. if ($cau->no_receipt)
  819. $no_receipt_causal = true;
  820. }
  821. Log::info("Final amount saved to record: " . $totalNet);
  822. if (!$this->financial_movement) {
  823. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  824. if (!$payment_method->money) {
  825. if ($generate && !$no_receipt_causal)
  826. $this->createReceipt();
  827. }
  828. }
  829. session()->flash('success', 'Movimento aggiornato');
  830. if ($this->backToRates) {
  831. return redirect()->to("/rates?member_id={$this->member_id}&member_course_id={$this->courseId}");
  832. }
  833. $this->resetFields();
  834. $this->update = false;
  835. $this->isDuplicate = false;
  836. $this->emit('setEdit', false);
  837. } catch (\Exception $ex) {
  838. Log::error("Error in update method: " . $ex->getMessage());
  839. Log::error("Stack trace: " . $ex->getTraceAsString());
  840. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  841. }
  842. }
  843. public function rigenerate()
  844. {
  845. $this->emit('refresh');
  846. try {
  847. $record = \App\Models\Record::findOrFail($this->dataId);
  848. $newRecord = $record->replicate();
  849. $newRecord->date = date("Y-m-d");
  850. $newRecord->save();
  851. $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
  852. // Inserisco le righe
  853. foreach ($recordRows as $row) {
  854. $newRow = $row->replicate();
  855. $newRow->record_id = $newRecord->id;
  856. $newRow->save();
  857. }
  858. $this->dataId = $newRecord->id;
  859. $this->createReceipt();
  860. session()->flash('success', 'Movimento aggiornato');
  861. $this->resetFields();
  862. $this->update = false;
  863. $this->isDuplicate = false;
  864. $this->emit('setEdit', false);
  865. } catch (\Exception $ex) {
  866. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  867. }
  868. }
  869. public function cancel()
  870. {
  871. // Se arrivo da duplica elimino
  872. if ($this->isDuplicate) {
  873. try {
  874. \App\Models\Record::find($this->dataId)->delete();
  875. session()->flash('success', "Movimento eliminato");
  876. } catch (\Exception $e) {
  877. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  878. }
  879. }
  880. $this->isDuplicate = false;
  881. $this->add = false;
  882. $this->update = false;
  883. $this->resetFields();
  884. $this->emit('setEdit', false);
  885. return redirect()->to('/in');
  886. }
  887. public function delete($id)
  888. {
  889. try {
  890. $r = \App\Models\Record::find($id);
  891. // Annullo la ricevuta
  892. $receipt = \App\Models\Receipt::where('record_id', $r->id)->first();
  893. if ($receipt) {
  894. $receipt->status = 99;
  895. sendReceiptDeleteEmail($receipt);
  896. $receipt->save();
  897. }
  898. if ($r->member_course_id > 0) {
  899. $months = json_decode($r->months);
  900. $c = \App\Models\MemberCourse::findOrFail($r->member_course_id);
  901. $xxx = json_decode($c->months);
  902. foreach ($xxx as $idx => $mm) {
  903. if (in_array($mm->m, $months)) {
  904. $xxx[$idx]->status = "";
  905. }
  906. }
  907. $c->months = json_encode($xxx);
  908. $c->save();
  909. }
  910. $r->deleted = true;
  911. $r->save();
  912. session()->flash('success', 'Movimento aggiornato');
  913. $this->resetFields();
  914. $this->update = false;
  915. $this->isDuplicate = false;
  916. $this->emit('setEdit', false);
  917. $this->emit('reload');
  918. //$this->emit('load-data-table');
  919. } catch (\Exception $ex) {
  920. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  921. }
  922. }
  923. public function multipleDelete()
  924. {
  925. try {
  926. foreach ($this->multipleIds as $id) {
  927. \App\Models\Record::find($id)->delete();
  928. }
  929. } catch (\Exception $e) {
  930. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  931. }
  932. $this->multipleAction = '';
  933. }
  934. public function createMember()
  935. {
  936. $this->newMemberFiscalCodeExist = false;
  937. $this->validate([
  938. // 'newMemberFiscalCode'=>'required|max:16',
  939. 'newMemberFirstName' => 'required',
  940. 'newMemberLastName' => 'required',
  941. //'newMemberEmail'=>'required',
  942. ]);
  943. // Check fiscal code exist
  944. $exist = false;
  945. if ($this->newMemberFiscalCode != '') {
  946. $check = \App\Models\Member::where('fiscal_code', $this->newMemberFiscalCode)->get();
  947. $exist = $check->count() > 0;
  948. }
  949. if (!$exist) {
  950. $member = \App\Models\Member::create([
  951. 'first_name' => strtoupper($this->newMemberFirstName),
  952. 'last_name' => strtoupper($this->newMemberLastName),
  953. 'email' => strtoupper($this->newMemberEmail),
  954. 'to_complete' => $this->newMemberToComplete,
  955. 'fiscal_code' => $this->newMemberFiscalCode,
  956. 'status' => true
  957. ]);
  958. $this->member_id = $member->id;
  959. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->get();
  960. // $this->emit('reloadMembers');
  961. $this->emit('refresh');
  962. $this->newMemberFirstName = '';
  963. $this->newMemberLastName = '';
  964. $this->newMemberEmail = '';
  965. $this->newMemberToComplete = false;
  966. $this->newMemberFiscalCode = '';
  967. $this->emit('saved');
  968. //$this->validate();
  969. $this->selectId++;
  970. } else {
  971. $this->newMemberFiscalCodeExist = true;
  972. }
  973. }
  974. public function createReceipt()
  975. {
  976. // Ulteriore controllo commerciale/non commerciale
  977. if (!$this->commercial) {
  978. $create = false;
  979. $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->orderBy('id', 'DESC')->first();
  980. if ($receipt != null) {
  981. // Controllo lo stato, se 99 ne genero una nuova
  982. if ($receipt->status == 99) {
  983. $create = true;
  984. }
  985. } else {
  986. $create = true;
  987. }
  988. if ($create) {
  989. $number = 1;
  990. $exist = \App\Models\Receipt::where('year', date("Y"))->orderBy('number', 'DESC')->first();
  991. if ($exist != null)
  992. $number = $exist->number + 1;
  993. // Calculate totals for the receipt
  994. $totalGross = 0;
  995. $totalNet = 0;
  996. foreach ($this->rows as $row) {
  997. $rowAmount = $this->currencyToDouble($row["amount"]);
  998. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  999. $rowNet = max(0, $rowAmount - $rowSconto);
  1000. $totalGross += $rowAmount;
  1001. $totalNet += $rowNet;
  1002. }
  1003. $receipt = \App\Models\Receipt::create([
  1004. 'record_id' => $this->dataId,
  1005. 'member_id' => $this->member_id,
  1006. 'supplier_id' => $this->supplier_id,
  1007. 'payment_method_id' => $this->payment_method_id,
  1008. 'number' => $number,
  1009. 'date' => $this->date,
  1010. 'year' => date("Y"),
  1011. 'type' => $this->type,
  1012. 'parent' => $this->parent,
  1013. 'status' => 1,
  1014. ]);
  1015. foreach ($this->rows as $row) {
  1016. $rowAmount = $this->currencyToDouble($row["amount"]);
  1017. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  1018. $rowNet = max(0, $rowAmount - $rowSconto);
  1019. Log::info("Receipt Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  1020. \App\Models\ReceiptRow::create([
  1021. 'receip_id' => $receipt->id,
  1022. 'causal_id' => $row["causal_id"],
  1023. 'note' => $row["note"],
  1024. 'vat_id' => $row["vat_id"],
  1025. 'amount' => $rowNet,
  1026. 'prediscount_amount' => $rowAmount,
  1027. 'sconto' => $rowSconto,
  1028. 'commercial' => $row["commercial"],
  1029. 'when' => json_encode($row["when"])
  1030. ]);
  1031. }
  1032. $this->currentReceip = $receipt;
  1033. sendReceiptEmail($receipt);
  1034. session()->flash('receipt', "Ricevuta " . $number . "/" . date("Y") . " creata correttamente");
  1035. $this->emit('showReceipt', $this->currentReceip->id);
  1036. }
  1037. }
  1038. }
  1039. public function removeReceipt()
  1040. {
  1041. $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
  1042. $receipt->status = 99;
  1043. $receipt->save();
  1044. sendReceiptDeleteEmail($receipt);
  1045. $this->currentReceip = $receipt;
  1046. }
  1047. function currencyToDouble($val)
  1048. {
  1049. $x = str_replace("€", "", $val);
  1050. $x = str_replace(".", "", $x);
  1051. $x = str_replace(",", ".", $x);
  1052. return floatval(trim($x));
  1053. }
  1054. public function addRow()
  1055. {
  1056. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  1057. $this->emit('load-select');
  1058. }
  1059. public function delRow($idx)
  1060. {
  1061. unset($this->rows[$idx]);
  1062. // $this->emit('load-select');
  1063. }
  1064. public function addPeriod($idx)
  1065. {
  1066. $x = sizeof($this->rows[$idx]['when']) - 1;
  1067. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  1068. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  1069. }
  1070. public function delPeriod($idx, $xxx)
  1071. {
  1072. array_splice($this->rows[$idx]['when'], $xxx, $xxx);
  1073. //unset($this->rows[$idx]['when'][$xxx]);
  1074. // $this->emit('load-select');
  1075. }
  1076. public function getTotal()
  1077. {
  1078. $total = 0.00;
  1079. foreach ($this->rows as $r) {
  1080. if ($r["amount"] != null && $r["amount"] != "") {
  1081. $rowAmount = $this->currencyToDouble($r["amount"]);
  1082. $rowSconto = isset($r['sconto']) ? $this->currencyToDouble($r['sconto']) : 0;
  1083. $netAmount = max(0, $rowAmount - $rowSconto);
  1084. $total += $netAmount;
  1085. if ($r["vat_id"] > 0)
  1086. $total += getVatValue($netAmount, $r["vat_id"]);
  1087. }
  1088. }
  1089. return formatPrice($total);
  1090. }
  1091. public function getTotalCorrispettivo()
  1092. {
  1093. $total = 0.00;
  1094. foreach ($this->corrispettivo as $r) {
  1095. $total += $this->currencyToDouble($r);
  1096. }
  1097. return formatPrice($total);
  1098. // $this->emit('load-select');
  1099. }
  1100. public function getPrice()
  1101. {
  1102. $total = 0.00;
  1103. foreach ($this->rows as $r) {
  1104. if ($r["amount"] != null && $r["amount"] != "")
  1105. $total += $this->currencyToDouble($r["amount"]);
  1106. }
  1107. return formatPrice($total);
  1108. // $this->emit('load-select');
  1109. }
  1110. public function getVat()
  1111. {
  1112. $total = 0.00;
  1113. foreach ($this->rows as $r) {
  1114. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
  1115. $total += getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  1116. }
  1117. return formatPrice($total);
  1118. // $this->emit('load-select');
  1119. }
  1120. public function getVats()
  1121. {
  1122. $vats = array();
  1123. foreach ($this->rows as $r) {
  1124. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0) {
  1125. $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  1126. $vatName = "";
  1127. foreach ($this->vats as $v) {
  1128. if ($v->id == $r["vat_id"])
  1129. $vatName = $v->name;
  1130. }
  1131. if (isset($vats[$vatName]))
  1132. $vats[$vatName] += $vat;
  1133. else
  1134. $vats[$vatName] = $vat;
  1135. }
  1136. }
  1137. return $vats;
  1138. // $this->emit('load-select');
  1139. }
  1140. public function setCausal($id, $idx)
  1141. {
  1142. $this->rows[$idx]["causal_id"] = $id;
  1143. }
  1144. public function printReceipt()
  1145. {
  1146. //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
  1147. $pdf = PDF::loadView('receipt', array('receipt' => $this->currentReceip)); //->output();
  1148. $pdfName = "Ricevuta_" . $this->currentReceip->member->last_name . "_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf";
  1149. return $pdf->stream();
  1150. /*return response()->streamDownload(
  1151. fn () => print($pdf),
  1152. "ricevuta_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf"
  1153. );*/
  1154. /*return response()->streamDownload(function () {
  1155. echo $pdf->stream();
  1156. }, 'test.pdf');*/
  1157. }
  1158. public function multiPeriod()
  1159. {
  1160. $this->multiP = true;
  1161. }
  1162. public function multiPeriodCreate($idx)
  1163. {
  1164. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  1165. $this->rows[$idx]['when'] = [];
  1166. foreach ($period as $dt) {
  1167. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  1168. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  1169. }
  1170. $this->multiP = false;
  1171. }
  1172. public function multiPeriodCancel()
  1173. {
  1174. $this->multiP = false;
  1175. }
  1176. public function getMonth($m)
  1177. {
  1178. $ret = '';
  1179. switch ($m) {
  1180. case 1:
  1181. $ret = 'Gennaio';
  1182. break;
  1183. case 2:
  1184. $ret = 'Febbraio';
  1185. break;
  1186. case 3:
  1187. $ret = 'Marzo';
  1188. break;
  1189. case 4:
  1190. $ret = 'Aprile';
  1191. break;
  1192. case 5:
  1193. $ret = 'Maggio';
  1194. break;
  1195. case 6:
  1196. $ret = 'Giugno';
  1197. break;
  1198. case 7:
  1199. $ret = 'Luglio';
  1200. break;
  1201. case 8:
  1202. $ret = 'Agosto';
  1203. break;
  1204. case 9:
  1205. $ret = 'Settembre';
  1206. break;
  1207. case 10:
  1208. $ret = 'Ottobre';
  1209. break;
  1210. case 11:
  1211. $ret = 'Novembre';
  1212. break;
  1213. case 12:
  1214. $ret = 'Dicembre';
  1215. break;
  1216. default:
  1217. $ret = '';
  1218. break;
  1219. }
  1220. return $ret;
  1221. }
  1222. public function setYear($idx, $xxx)
  1223. {
  1224. $m = $this->rows[$idx]["when"][$xxx]["month"];
  1225. $this->rows[$idx]["when"][$xxx]["year"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
  1226. }
  1227. }