RecordIN.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  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"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
  349. else
  350. $this->rows[0]["when"][$idx]["year"] = $m > env('FISCAL_YEAR_MONTH_TO', 1) ? (date("Y") - 1) : date("Y");
  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. $rate = \App\Models\Rate::findOrFail($this->rateId);
  572. $rate->status = 1;
  573. $rate->record_id = $record->id;
  574. $rate->save();
  575. }
  576. if ($this->backToRates) {
  577. return redirect()->to("/rates?member_id={$this->member_id}&member_course_id={$this->courseId}");
  578. }
  579. session()->flash('success', 'Movimento creato');
  580. $this->resetFields();
  581. $this->add = false;
  582. $this->isDuplicate = false;
  583. $this->emit('setEdit', false);
  584. } catch (\Exception $ex) {
  585. Log::error("Error in store method: " . $ex->getMessage());
  586. Log::error("Stack trace: " . $ex->getTraceAsString());
  587. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  588. }
  589. }
  590. public function duplicate($id)
  591. {
  592. $record = \App\Models\Record::findOrFail($id);
  593. $newRecord = $record->replicate();
  594. $newRecord->save();
  595. $rows = \App\Models\RecordRow::where('record_id', $id)->get();
  596. foreach ($rows as $r) {
  597. $newRow = $r->replicate();
  598. $newRow->record_id = $newRecord->id;
  599. $newRow->save();
  600. }
  601. $this->edit($newRecord->id);
  602. $this->isDuplicate = true;
  603. }
  604. public function edit($id)
  605. {
  606. if (!isset($_GET["from"]) && $this->fromPage == '')
  607. $this->fromPage = 'in';
  608. $this->emit('setEdit', true);
  609. //if ($this->hasFilter)
  610. $this->emit('hide-search');
  611. $this->emit('load-select');
  612. try {
  613. $record = \App\Models\Record::findOrFail($id);
  614. if (!$record) {
  615. session()->flash('error', 'Movimento non trovato');
  616. } else {
  617. if ($record->member_id) {
  618. $member = \App\Models\Member::find($record->member_id);
  619. if (!$member || $member->status == 'archived') {
  620. $this->member_id = null;
  621. } else {
  622. $this->member_id = $record->member_id;
  623. }
  624. } else {
  625. $this->member_id = $record->member_id;
  626. }
  627. if ($record->payment_method_id) {
  628. $paymentMethod = \App\Models\PaymentMethod::find($record->payment_method_id);
  629. if (!$paymentMethod || (isset($paymentMethod->hidden) && $paymentMethod->hidden)) {
  630. $this->payment_method_id = null;
  631. } else {
  632. $this->payment_method_id = $record->payment_method_id;
  633. }
  634. } else {
  635. $this->payment_method_id = $record->payment_method_id;
  636. }
  637. $this->supplier_id = $record->supplier_id;
  638. $this->amount = $record->amount;
  639. $this->commercial = $record->commercial;
  640. $this->corrispettivo_fiscale = $record->corrispettivo_fiscale;
  641. $this->date = date("Y-m-d", strtotime($record->date));
  642. $this->type = $record->type;
  643. $this->deleted = $record->deleted;
  644. $this->financial_movement = $record->financial_movement;
  645. $this->dataId = $record->id;
  646. $this->update = true;
  647. $this->add = false;
  648. $rows = \App\Models\RecordRow::where('record_id', $this->dataId)
  649. ->select('causal_id', 'note', 'commercial', 'when', 'amount', 'prediscount_amount', 'sconto', 'vat_id')
  650. ->get();
  651. $this->rows = [];
  652. foreach ($rows as $i => $r) {
  653. $grossAmount = $r->prediscount_amount ?? ($r->amount + $r->sconto);
  654. $causalId = $r->causal_id;
  655. if ($causalId) {
  656. $causal = \App\Models\Causal::find($causalId);
  657. if (!$causal || (isset($causal->hidden) && $causal->hidden)) {
  658. $causalId = null;
  659. }
  660. }
  661. $this->rows[] = [
  662. 'causal_id' => $causalId,
  663. 'note' => $r->note,
  664. 'commercial' => $r->commercial,
  665. 'when' => json_decode($r->when),
  666. 'amount' => formatPrice($grossAmount),
  667. 'sconto' => formatPrice($r->sconto),
  668. 'vat_id' => $r->vat_id
  669. ];
  670. }
  671. $exist = \App\Models\Receipt::where('record_id', $id)->orderBy('id', 'DESC')->first();
  672. if ($exist != null) {
  673. $this->currentReceip = $exist;
  674. $this->parent = $this->currentReceip->parent;
  675. }
  676. $this->refreshEditOptions();
  677. }
  678. } catch (\Exception $ex) {
  679. Log::error("Error in edit method: " . $ex->getMessage());
  680. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  681. }
  682. }
  683. private function refreshEditOptions()
  684. {
  685. $this->causals = array();
  686. $visibleCausals = \App\Models\Causal::select('id', 'name')
  687. ->where('parent_id', null)
  688. ->where('type', 'IN')
  689. ->where(function ($query) {
  690. $query->where('hidden', false)->orWhereNull('hidden');
  691. })
  692. ->get();
  693. $this->getCausale($visibleCausals, 0);
  694. $this->payments = \App\Models\PaymentMethod::select('id', 'name')
  695. ->where('enabled', true)
  696. ->whereIn('type', array('ALL', 'IN'))
  697. ->where(function ($query) {
  698. $query->where('hidden', false)->orWhereNull('hidden');
  699. })
  700. ->orderBy('name')
  701. ->get();
  702. if ($this->commercial) {
  703. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
  704. ->where(function ($query) {
  705. $query->where('status', '!=', 'archived');
  706. })
  707. ->orderBy('last_name')
  708. ->orderBy('first_name')
  709. ->get();
  710. } else {
  711. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
  712. ->where(function ($query) {
  713. $query->where('current_status', 2)->orWhere('current_status', 1);
  714. })
  715. ->where(function ($query) {
  716. $query->where('status', '!=', 'archived');
  717. })
  718. ->orderBy('last_name')
  719. ->orderBy('first_name')
  720. ->get();
  721. }
  722. }
  723. public function update($generate = false)
  724. {
  725. Log::info("Starting update method");
  726. $this->emit('refresh');
  727. $rules = [
  728. 'payment_method_id' => 'required',
  729. 'rows.*.causal_id' => 'required',
  730. 'rows.*.amount' => 'required'
  731. ];
  732. if (!$this->commercial)
  733. $rules["member_id"] = 'required';
  734. $this->validate($rules);
  735. /* Validazione campi azienda per generazione ricevuta */
  736. try {
  737. if (!$this->financial_movement && !$this->commercial) {
  738. $no_receipt_causal_azienda = false;
  739. foreach ($this->rows as $row) {
  740. $no_receipt_causal_azienda = false;
  741. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  742. if ($cau->no_receipt)
  743. $no_receipt_causal_azienda = true;
  744. }
  745. $azienda = \App\Models\Azienda::first();
  746. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  747. if (!$payment_method->money) {
  748. if (!$no_receipt_causal_azienda) {
  749. if (!$azienda->isValid()) {
  750. session()->flash('error_ricevuta', implode("", array_map(function ($item) {
  751. return "<li>$item</li>";
  752. }, $azienda->validate())));
  753. return false;
  754. }
  755. }
  756. }
  757. }
  758. } catch (\Exception $ex) {
  759. Log::error("Error in store method: " . $ex->getMessage());
  760. Log::error("Stack trace: " . $ex->getTraceAsString());
  761. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  762. }
  763. /* END - Validazione campi azienda per generazione ricevuta */
  764. try {
  765. $totalGross = 0;
  766. $totalSconto = 0;
  767. $totalNet = 0;
  768. foreach ($this->rows as $row) {
  769. $rowAmount = $this->currencyToDouble($row["amount"]);
  770. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  771. $rowNet = max(0, $rowAmount - $rowSconto);
  772. $totalGross += $rowAmount;
  773. $totalSconto += $rowSconto;
  774. $totalNet += $rowNet;
  775. }
  776. Log::info("Total gross: " . $totalGross . ", Total sconto: " . $totalSconto . ", Total net: " . $totalNet);
  777. \App\Models\Record::whereId($this->dataId)->update([
  778. 'member_id' => $this->member_id,
  779. 'supplier_id' => $this->supplier_id,
  780. 'payment_method_id' => $this->payment_method_id,
  781. 'commercial' => $this->commercial,
  782. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  783. 'date' => date("Y-m-d", strtotime($this->date)),
  784. 'type' => $this->type,
  785. 'financial_movement' => $this->financial_movement,
  786. 'deleted' => $this->deleted,
  787. 'amount' => $totalNet,
  788. 'prediscount_amount' => $totalGross,
  789. ]);
  790. $no_receipt_causal = false;
  791. $vat = 0;
  792. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  793. foreach ($this->rows as $row) {
  794. foreach ($row["when"] as $x => $y) {
  795. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  796. }
  797. $rowAmount = $this->currencyToDouble($row["amount"]);
  798. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  799. $rowNet = max(0, $rowAmount - $rowSconto);
  800. Log::info("Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  801. \App\Models\RecordRow::create([
  802. 'record_id' => $this->dataId,
  803. 'causal_id' => $row["causal_id"],
  804. 'note' => $row["note"],
  805. 'vat_id' => $row["vat_id"],
  806. 'amount' => $rowNet,
  807. 'prediscount_amount' => $rowAmount,
  808. 'sconto' => $rowSconto,
  809. 'commercial' => $this->commercial,
  810. 'when' => json_encode($row["when"])
  811. ]);
  812. $vat += getVatValue($rowNet, $row["vat_id"]);
  813. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  814. if ($cau->no_receipt)
  815. $no_receipt_causal = true;
  816. }
  817. Log::info("Final amount saved to record: " . $totalNet);
  818. if (!$this->financial_movement) {
  819. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  820. if (!$payment_method->money) {
  821. if ($generate && !$no_receipt_causal)
  822. $this->createReceipt();
  823. }
  824. }
  825. session()->flash('success', 'Movimento aggiornato');
  826. if ($this->backToRates) {
  827. return redirect()->to("/rates?member_id={$this->member_id}&member_course_id={$this->courseId}");
  828. }
  829. $this->resetFields();
  830. $this->update = false;
  831. $this->isDuplicate = false;
  832. $this->emit('setEdit', false);
  833. } catch (\Exception $ex) {
  834. Log::error("Error in update method: " . $ex->getMessage());
  835. Log::error("Stack trace: " . $ex->getTraceAsString());
  836. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  837. }
  838. }
  839. public function rigenerate()
  840. {
  841. $this->emit('refresh');
  842. try {
  843. $record = \App\Models\Record::findOrFail($this->dataId);
  844. $newRecord = $record->replicate();
  845. $newRecord->date = date("Y-m-d");
  846. $newRecord->save();
  847. $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
  848. // Inserisco le righe
  849. foreach ($recordRows as $row) {
  850. $newRow = $row->replicate();
  851. $newRow->record_id = $newRecord->id;
  852. $newRow->save();
  853. }
  854. $this->dataId = $newRecord->id;
  855. $this->createReceipt();
  856. session()->flash('success', 'Movimento aggiornato');
  857. $this->resetFields();
  858. $this->update = false;
  859. $this->isDuplicate = false;
  860. $this->emit('setEdit', false);
  861. } catch (\Exception $ex) {
  862. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  863. }
  864. }
  865. public function cancel()
  866. {
  867. // Se arrivo da duplica elimino
  868. if ($this->isDuplicate) {
  869. try {
  870. \App\Models\Record::find($this->dataId)->delete();
  871. session()->flash('success', "Movimento eliminato");
  872. } catch (\Exception $e) {
  873. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  874. }
  875. }
  876. $this->isDuplicate = false;
  877. $this->add = false;
  878. $this->update = false;
  879. $this->resetFields();
  880. $this->emit('setEdit', false);
  881. return redirect()->to('/in');
  882. }
  883. public function delete($id)
  884. {
  885. try {
  886. $r = \App\Models\Record::find($id);
  887. // Annullo la ricevuta
  888. $receipt = \App\Models\Receipt::where('record_id', $r->id)->first();
  889. if ($receipt) {
  890. $receipt->status = 99;
  891. sendReceiptDeleteEmail($receipt);
  892. $receipt->save();
  893. }
  894. if ($r->member_course_id > 0) {
  895. $months = json_decode($r->months);
  896. $c = \App\Models\MemberCourse::findOrFail($r->member_course_id);
  897. $xxx = json_decode($c->months);
  898. foreach ($xxx as $idx => $mm) {
  899. if (in_array($mm->m, $months)) {
  900. $xxx[$idx]->status = "";
  901. }
  902. }
  903. $c->months = json_encode($xxx);
  904. $c->save();
  905. }
  906. $r->deleted = true;
  907. $r->save();
  908. session()->flash('success', 'Movimento aggiornato');
  909. $this->resetFields();
  910. $this->update = false;
  911. $this->isDuplicate = false;
  912. $this->emit('setEdit', false);
  913. $this->emit('reload');
  914. //$this->emit('load-data-table');
  915. } catch (\Exception $ex) {
  916. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  917. }
  918. }
  919. public function multipleDelete()
  920. {
  921. try {
  922. foreach ($this->multipleIds as $id) {
  923. \App\Models\Record::find($id)->delete();
  924. }
  925. } catch (\Exception $e) {
  926. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  927. }
  928. $this->multipleAction = '';
  929. }
  930. public function createMember()
  931. {
  932. $this->newMemberFiscalCodeExist = false;
  933. $this->validate([
  934. // 'newMemberFiscalCode'=>'required|max:16',
  935. 'newMemberFirstName' => 'required',
  936. 'newMemberLastName' => 'required',
  937. //'newMemberEmail'=>'required',
  938. ]);
  939. // Check fiscal code exist
  940. $exist = false;
  941. if ($this->newMemberFiscalCode != '') {
  942. $check = \App\Models\Member::where('fiscal_code', $this->newMemberFiscalCode)->get();
  943. $exist = $check->count() > 0;
  944. }
  945. if (!$exist) {
  946. $member = \App\Models\Member::create([
  947. 'first_name' => strtoupper($this->newMemberFirstName),
  948. 'last_name' => strtoupper($this->newMemberLastName),
  949. 'email' => strtoupper($this->newMemberEmail),
  950. 'to_complete' => $this->newMemberToComplete,
  951. 'fiscal_code' => $this->newMemberFiscalCode,
  952. 'status' => true
  953. ]);
  954. $this->member_id = $member->id;
  955. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->get();
  956. // $this->emit('reloadMembers');
  957. $this->emit('refresh');
  958. $this->newMemberFirstName = '';
  959. $this->newMemberLastName = '';
  960. $this->newMemberEmail = '';
  961. $this->newMemberToComplete = false;
  962. $this->newMemberFiscalCode = '';
  963. $this->emit('saved');
  964. //$this->validate();
  965. $this->selectId++;
  966. } else {
  967. $this->newMemberFiscalCodeExist = true;
  968. }
  969. }
  970. public function createReceipt()
  971. {
  972. // Ulteriore controllo commerciale/non commerciale
  973. if (!$this->commercial) {
  974. $create = false;
  975. $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->orderBy('id', 'DESC')->first();
  976. if ($receipt != null) {
  977. // Controllo lo stato, se 99 ne genero una nuova
  978. if ($receipt->status == 99) {
  979. $create = true;
  980. }
  981. } else {
  982. $create = true;
  983. }
  984. if ($create) {
  985. $number = 1;
  986. $exist = \App\Models\Receipt::where('year', date("Y"))->orderBy('number', 'DESC')->first();
  987. if ($exist != null)
  988. $number = $exist->number + 1;
  989. // Calculate totals for the receipt
  990. $totalGross = 0;
  991. $totalNet = 0;
  992. foreach ($this->rows as $row) {
  993. $rowAmount = $this->currencyToDouble($row["amount"]);
  994. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  995. $rowNet = max(0, $rowAmount - $rowSconto);
  996. $totalGross += $rowAmount;
  997. $totalNet += $rowNet;
  998. }
  999. $receipt = \App\Models\Receipt::create([
  1000. 'record_id' => $this->dataId,
  1001. 'member_id' => $this->member_id,
  1002. 'supplier_id' => $this->supplier_id,
  1003. 'payment_method_id' => $this->payment_method_id,
  1004. 'number' => $number,
  1005. 'date' => $this->date,
  1006. 'year' => date("Y"),
  1007. 'type' => $this->type,
  1008. 'parent' => $this->parent,
  1009. 'status' => 1,
  1010. ]);
  1011. foreach ($this->rows as $row) {
  1012. $rowAmount = $this->currencyToDouble($row["amount"]);
  1013. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  1014. $rowNet = max(0, $rowAmount - $rowSconto);
  1015. Log::info("Receipt Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  1016. \App\Models\ReceiptRow::create([
  1017. 'receip_id' => $receipt->id,
  1018. 'causal_id' => $row["causal_id"],
  1019. 'note' => $row["note"],
  1020. 'vat_id' => $row["vat_id"],
  1021. 'amount' => $rowNet,
  1022. 'prediscount_amount' => $rowAmount,
  1023. 'sconto' => $rowSconto,
  1024. 'commercial' => $row["commercial"],
  1025. 'when' => json_encode($row["when"])
  1026. ]);
  1027. }
  1028. $this->currentReceip = $receipt;
  1029. sendReceiptEmail($receipt);
  1030. session()->flash('receipt', "Ricevuta " . $number . "/" . date("Y") . " creata correttamente");
  1031. $this->emit('showReceipt', $this->currentReceip->id);
  1032. }
  1033. }
  1034. }
  1035. public function removeReceipt()
  1036. {
  1037. $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
  1038. $receipt->status = 99;
  1039. $receipt->save();
  1040. sendReceiptDeleteEmail($receipt);
  1041. $this->currentReceip = $receipt;
  1042. }
  1043. function currencyToDouble($val)
  1044. {
  1045. $x = str_replace("€", "", $val);
  1046. $x = str_replace(".", "", $x);
  1047. $x = str_replace(",", ".", $x);
  1048. return floatval(trim($x));
  1049. }
  1050. public function addRow()
  1051. {
  1052. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  1053. $this->emit('load-select');
  1054. }
  1055. public function delRow($idx)
  1056. {
  1057. unset($this->rows[$idx]);
  1058. // $this->emit('load-select');
  1059. }
  1060. public function addPeriod($idx)
  1061. {
  1062. $x = sizeof($this->rows[$idx]['when']) - 1;
  1063. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  1064. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  1065. }
  1066. public function delPeriod($idx, $xxx)
  1067. {
  1068. array_splice($this->rows[$idx]['when'], $xxx, $xxx);
  1069. //unset($this->rows[$idx]['when'][$xxx]);
  1070. // $this->emit('load-select');
  1071. }
  1072. public function getTotal()
  1073. {
  1074. $total = 0.00;
  1075. foreach ($this->rows as $r) {
  1076. if ($r["amount"] != null && $r["amount"] != "") {
  1077. $rowAmount = $this->currencyToDouble($r["amount"]);
  1078. $rowSconto = isset($r['sconto']) ? $this->currencyToDouble($r['sconto']) : 0;
  1079. $netAmount = max(0, $rowAmount - $rowSconto);
  1080. $total += $netAmount;
  1081. if ($r["vat_id"] > 0)
  1082. $total += getVatValue($netAmount, $r["vat_id"]);
  1083. }
  1084. }
  1085. return formatPrice($total);
  1086. }
  1087. public function getTotalCorrispettivo()
  1088. {
  1089. $total = 0.00;
  1090. foreach ($this->corrispettivo as $r) {
  1091. $total += $this->currencyToDouble($r);
  1092. }
  1093. return formatPrice($total);
  1094. // $this->emit('load-select');
  1095. }
  1096. public function getPrice()
  1097. {
  1098. $total = 0.00;
  1099. foreach ($this->rows as $r) {
  1100. if ($r["amount"] != null && $r["amount"] != "")
  1101. $total += $this->currencyToDouble($r["amount"]);
  1102. }
  1103. return formatPrice($total);
  1104. // $this->emit('load-select');
  1105. }
  1106. public function getVat()
  1107. {
  1108. $total = 0.00;
  1109. foreach ($this->rows as $r) {
  1110. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
  1111. $total += getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  1112. }
  1113. return formatPrice($total);
  1114. // $this->emit('load-select');
  1115. }
  1116. public function getVats()
  1117. {
  1118. $vats = array();
  1119. foreach ($this->rows as $r) {
  1120. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0) {
  1121. $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  1122. $vatName = "";
  1123. foreach ($this->vats as $v) {
  1124. if ($v->id == $r["vat_id"])
  1125. $vatName = $v->name;
  1126. }
  1127. if (isset($vats[$vatName]))
  1128. $vats[$vatName] += $vat;
  1129. else
  1130. $vats[$vatName] = $vat;
  1131. }
  1132. }
  1133. return $vats;
  1134. // $this->emit('load-select');
  1135. }
  1136. public function setCausal($id, $idx)
  1137. {
  1138. $this->rows[$idx]["causal_id"] = $id;
  1139. }
  1140. public function printReceipt()
  1141. {
  1142. //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
  1143. $pdf = PDF::loadView('receipt', array('receipt' => $this->currentReceip)); //->output();
  1144. $pdfName = "Ricevuta_" . $this->currentReceip->member->last_name . "_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf";
  1145. return $pdf->stream();
  1146. /*return response()->streamDownload(
  1147. fn () => print($pdf),
  1148. "ricevuta_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf"
  1149. );*/
  1150. /*return response()->streamDownload(function () {
  1151. echo $pdf->stream();
  1152. }, 'test.pdf');*/
  1153. }
  1154. public function multiPeriod()
  1155. {
  1156. $this->multiP = true;
  1157. }
  1158. public function multiPeriodCreate($idx)
  1159. {
  1160. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  1161. $this->rows[$idx]['when'] = [];
  1162. foreach ($period as $dt) {
  1163. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  1164. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  1165. }
  1166. $this->multiP = false;
  1167. }
  1168. public function multiPeriodCancel()
  1169. {
  1170. $this->multiP = false;
  1171. }
  1172. public function getMonth($m)
  1173. {
  1174. $ret = '';
  1175. switch ($m) {
  1176. case 1:
  1177. $ret = 'Gennaio';
  1178. break;
  1179. case 2:
  1180. $ret = 'Febbraio';
  1181. break;
  1182. case 3:
  1183. $ret = 'Marzo';
  1184. break;
  1185. case 4:
  1186. $ret = 'Aprile';
  1187. break;
  1188. case 5:
  1189. $ret = 'Maggio';
  1190. break;
  1191. case 6:
  1192. $ret = 'Giugno';
  1193. break;
  1194. case 7:
  1195. $ret = 'Luglio';
  1196. break;
  1197. case 8:
  1198. $ret = 'Agosto';
  1199. break;
  1200. case 9:
  1201. $ret = 'Settembre';
  1202. break;
  1203. case 10:
  1204. $ret = 'Ottobre';
  1205. break;
  1206. case 11:
  1207. $ret = 'Novembre';
  1208. break;
  1209. case 12:
  1210. $ret = 'Dicembre';
  1211. break;
  1212. default:
  1213. $ret = '';
  1214. break;
  1215. }
  1216. return $ret;
  1217. }
  1218. public function setYear($idx, $xxx)
  1219. {
  1220. $m = $this->rows[$idx]["when"][$xxx]["month"];
  1221. $this->rows[$idx]["when"][$xxx]["year"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
  1222. }
  1223. }