| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649 |
- <?php
- namespace App\Http\Livewire;
- use Livewire\Component;
- use Livewire\WithPagination;
- use Barryvdh\DomPDF\Facade\Pdf;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Facades\Mail;
- use Illuminate\Contracts\Validation\Validator;
- use Illuminate\Support\Facades\Log;
- use App\Http\Middleware\TenantMiddleware;
- use Illuminate\Support\Carbon;
- class RecordIN extends Component
- {
- use WithPagination;
- protected $paginationTheme = 'bootstrap';
- protected $listeners = ['setCausal' => 'setCausal', 'refreshMembers' => 'refreshMembers', 'scontoChanged' => 'updateSconto'];
- public $sortField = 'date';
- public $sortAsc = false;
- public $typeIN = "IN";
- public $fromPage = '';
- public $isDuplicate = false;
- public $multiP = false;
- public $from, $to;
- public $multiMonthTo = 0;
- public $multiYearTo = 0;
- public $multiMonthFrom = 0;
- public $multiYearFrom = 0;
- public $createSubscription = 0;
- public $corrispettivo_causal_id = 0;
- public function sortBy($field)
- {
- if ($this->sortField === $field) {
- $this->sortAsc = ! $this->sortAsc;
- } else {
- $this->sortAsc = true;
- }
- $this->sortField = $field;
- }
- public $courseId = 0;
- public $subscriptionId = 0;
- public $course = null;
- public $subscription = null;
- public $rateId = 0;
- public $months = array();
- public $records, $dataId, $member_id, $supplier_id,
- $causal_id,
- $payment_method_id,
- $destination_id,
- $date,
- $month,
- $year,
- $type,
- $deleted,
- $financial_movement,
- $amount,
- $vat,
- $virtual,
- $note,
- $parent,
- $corrispettivo_fiscale,
- $commercial, $update = false, $add = false;
- public $corrispettivo = [];
- public $corrispettivo_destination = [];
- public $currentReceip;
- public $filterMember = 0, $filterPaymentMethod = 0, $filterCausals = 0, $filterCourses = 0, $filterSubscriptions = 0, $filterFrom = '', $filterTo = '', $filterCommercial = 0;
- public $hasFilter = false;
- public $total = 0;
- public $selectedFilter = '';
- public $multipleIds = [];
- public $multipleAction = '';
- public $first = true;
- public $selectId = 0;
- public $refreshAfter = 0;
- public $sconto = 0;
- public $canSave = true;
- public $newMemberFirstName = '';
- public $newMemberLastName = '';
- public $newMemberEmail = '';
- public $newMemberToComplete = false;
- public $newMemberFiscalCode = '';
- public $newMemberFiscalCodeExist = false;
- public $causals = array();
- public $courses = array();
- public $subscriptions = array();
- public $payments = array();
- public $banks = array();
- public $members = array();
- public $vats = array();
- public $rows = array();
- public $fromCourse = false;
- public $backToRates = false;
- protected $rules = [
- 'member_id' => 'required',
- 'payment_method_id' => 'required',
- 'rows.*.causal_id' => 'required',
- 'rows.*.amount' => 'required'
- ];
- protected $messages = [
- 'member_id.required' => 'La persona è obbligatorio',
- 'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
- 'rows.*.causal_id.required' => 'La causale è obbligatoria',
- 'rows.*.amount.required' => 'L\'importo è obbligatorio',
- ];
- public function boot()
- {
- app(TenantMiddleware::class)->setupTenantConnection();
- }
- public function updatedMemberId()
- {
- $this->emit('refresh');
- if ($this->member_id > 0) {
- $member = \App\Models\Member::findOrFail($this->member_id);
- if (!$member->isAdult()) {
- if ($member->father_name != '')
- $this->parent = $member->father_name . " (C.F. " . $member->father_fiscal_code . ")";
- else if ($member->mother_name != '')
- $this->parent = $member->mother_name . " (C.F. " . $member->mother_fiscal_code . ")";
- else
- $this->parent = '';
- }
- $this->virtual = $member->getMoney();
- $this->newMemberFirstName = '';
- $this->newMemberLastName = '';
- $this->newMemberEmail = '';
- $this->newMemberToComplete = false;
- $this->newMemberFiscalCode = '';
- $this->newMemberFiscalCodeExist = false;
- }
- }
- public function updatedCausalId()
- {
- //$this->emit('refresh');
- }
- public function updatedDate()
- {
- //$this->emit('refresh');
- }
- public function hydrate()
- {
- $this->emit('load-select');
- foreach ($this->rows as $i => $row) {
- if (isset($row['course']) && is_array($row['course']) && isset($row['course']['id'])) {
- $this->rows[$i]['course'] = \App\Models\Course::find($row['course']['id']);
- }
- if (isset($row['subscription']) && is_array($row['subscription']) && isset($row['subscription']['id'])) {
- $this->rows[$i]['subscription'] = \App\Models\Subscription::find($row['subscription']['id']);
- }
- }
- }
- /*public function updated() {
- $this->emit('refresh');
- }*/
- public function updatedPaymentMethodId()
- {
- //$this->emit('refresh');
- if ($this->payment_method_id) {
- $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
- $this->destination_id = $payment_method->destination_id ?? null;
- }
- $this->canSave = $this->checkCanSave();
- }
- public function updatedCorrispettivoFiscale()
- {
- if ($this->corrispettivo_fiscale) {
- foreach ($this->payments as $payment) {
- if ($payment->corrispettivo_fiscale) {
- $this->corrispettivo_destination[$payment->id] = $payment->destination_id;
- }
- }
- }
- }
- public function updatedAmount()
- {
- // $this->emit('refresh');
- $this->canSave = $this->checkCanSave();
- }
- public function updatedCommercial($value)
- {
- $this->emitSelf('refreshMembers');
- }
- public function updateSconto()
- {
- $totalSconto = 0;
- foreach ($this->rows as $row) {
- if (isset($row['sconto']) && $row['sconto'] != null && $row['sconto'] != "") {
- $totalSconto += $this->currencyToDouble($row['sconto']);
- }
- }
- $this->sconto = formatPrice($totalSconto);
- Log::info("Total sconto updated to: " . $this->sconto);
- }
- public function checkCanSave()
- {
- $ret = true;
- if ($this->payment_method_id != null) {
- $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
- if ($payment_method->money) {
- $from = str_replace(".", "", str_replace(",", "", number_format($this->virtual, 2)));
- $this->from = $this->virtual;
- $from = $this->from;
- $to = str_replace(".", "", str_replace(",", "", $this->currencyToDouble($this->amount)));
- $this->to = $this->amount;
- $to = $this->to;
- $ret = $from >= $to;
- }
- }
- return $ret;
- }
- public function refreshMembers()
- {
- if ($this->add || $this->update) {
- if ($this->commercial) {
- $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
- } else {
- $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();
- }
- } else
- $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
- }
- public function setAmount()
- {
- $tot = 0;
- foreach ($this->rows as $r) {
- $tot += $this->currencyToDouble($r["amount"]);
- }
- $this->amount = $tot;
- $this->canSave = $this->checkCanSave();
- }
- public function resetFields()
- {
- $this->member_id = null;
- $this->supplier_id = null;
- $this->payment_method_id = null;
- $this->destination_id = null;
- $this->commercial = 0;
- $this->corrispettivo_fiscale = false;
- $this->date = date("Y-m-d");
- $this->type = 'IN';
- $this->deleted = false;
- $this->financial_movement = false;
- $this->newMemberFirstName = '';
- $this->newMemberLastName = '';
- $this->newMemberEmail = '';
- $this->newMemberToComplete = false;
- $this->newMemberFiscalCode = '';
- $this->newMemberFiscalCodeExist = false;
- $this->currentReceip = null;
- $this->parent = '';
- $this->courseId = 0;
- $this->subscriptionId = 0;
- $this->rateId = 0;
- $this->backToRates = false;
- $this->months = array();
- $this->rows = array();
- $this->rows[] = array('causal_id' => isset($_GET["causalId"]) ? $_GET["causalId"] : null, 'course_id' => null, 'course' => null, 'subscription_id' => null, 'subscription' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0, 'sconto' => 0);
- $this->corrispettivo = [];
- $this->corrispettivo_destination = [];
- $this->emit('load-data-table');
- }
- public function getMemberProperty()
- {
- $ret = null;
- if ($this->member_id > 0) {
- $ret = \App\Models\Member::findOrFail($this->member_id);
- }
- return $ret;
- }
- public function getCausalProperty()
- {
- $ret = null;
- if ($this->causal_id > 0) {
- $ret = \App\Models\Causal::findOrFail($this->causal_id);
- }
- return $ret;
- }
- public function getCausal($causal)
- {
- $ret = '';
- if ($causal > 0) {
- $ret = \App\Models\Causal::findOrFail($causal)->getTree();
- }
- return $ret;
- }
- public function getPaymentMethod($payment)
- {
- $ret = '';
- if ($payment > 0) {
- $ret = \App\Models\PaymentMethod::findOrFail($payment)->name;
- }
- return $ret;
- }
- public function getBankName($bank_id)
- {
- $ret = '';
- if ($bank_id > 0) {
- $ret = \App\Models\Bank::findOrFail($bank_id)->name;
- }
- return $ret;
- }
- function buildTree($records, $parentId = 0)
- {
- $this->causals = array();
- foreach ($records as $record) {
- if ($record->parent_id == $parentId) {
- $children = $this->buildTree($record, $record->id);
- if ($children) {
- $record->children = $children;
- }
- $this->causals[] = $record;
- }
- }
- return $this->causals;
- }
- public function getCausale($records, $indentation)
- {
- foreach ($records as $record) {
- $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
- if (count($record->childs))
- $this->getCausale($record->childs, $indentation + 1);
- }
- }
- public function getCourses($records, $indentation)
- {
- foreach ($records as $record) {
- $this->courses[] = array('id' => $record->id, 'name' => $record->getDetailsName(), 'text' => $record->getDetailsName(), 'level' => $indentation);
- if (count($record->childs))
- $this->getCourses($record->childs, $indentation + 1);
- }
- }
- public function getSubscriptions($records, $indentation)
- {
- foreach ($records as $record) {
- $this->subscriptions[] = array('id' => $record->id, 'name' => $record->name, 'text' => $record->name, 'level' => $indentation);
- }
- }
- public function mount()
- {
- if (isset($_GET["from"])) {
- $this->fromPage = $_GET["from"];
- }
- $this->causals = array();
- $this->courses = array();
- $this->subscriptions = array();
- $this->multiMonthFrom = date("n");
- $this->multiYearFrom = date("Y");
- $this->multiMonthTo = date("n");
- $this->multiYearTo = date("Y");
- $fisc = \App\Models\Causal::where('corrispettivo_fiscale', true)->first();
- if ($fisc)
- $this->corrispettivo_causal_id = $fisc->id;
- $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'IN')->get(), 0);
- $this->getCourses(\App\Models\Course::where('parent_id', null)->get(), 0);
- $this->getSubscriptions(\App\Models\Subscription::get(), 0);
- //$this->buildTree(\App\Models\Causal::all(), null);
- $this->refreshMembers();
- $this->payments = \App\Models\PaymentMethod::select('id', 'name')->where('enabled', true)->whereIn('type', array('ALL', 'IN'))->orderBy('name')->get();
- $this->banks = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', array('ALL', 'IN'))->orderBy('name')->get();
- $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
- if ($this->first) {
- if (isset($_GET["new"])) {
- $this->refreshAfter = 1;
- $this->add();
- }
- if (isset($_GET["memberId"])) {
- $this->refreshAfter = 1;
- $this->member_id = $_GET["memberId"];
- $member = \App\Models\Member::findOrFail($this->member_id);
- if (!$member->isAdult()) {
- if ($member->father_name != '')
- $this->parent = $member->father_name . " (C.F. " . $member->father_fiscal_code . ")";
- else if ($member->mother_name != '')
- $this->parent = $member->mother_name . " (C.F. " . $member->mother_fiscal_code . ")";
- else
- $this->parent = '';
- }
- }
- if (isset($_GET["causalId"])) {
- $this->refreshAfter = 1;
- $this->causal_id = $_GET["causalId"];
- }
- if (isset($_GET["id"])) {
- $this->refreshAfter = 1;
- $this->edit($_GET["id"]);
- }
- $count = 0;
- if (isset($_GET["courseId"]) && $_GET["courseId"] > 0) {
- $this->fromCourse = true;
- $this->courseId = $_GET["courseId"];
- $mc = \App\Models\MemberCourse::findOrFail($this->courseId);
- $this->course = \App\Models\Course::findOrFail($mc->course_id);
- $this->rows[0]['course_id'] = $this->course->id;
- $this->rows[0]['course'] = $this->course;
- }
- if (isset($_GET["subscriptionId"]) && $_GET["subscriptionId"] > 0) {
- $this->fromCourse = true;
- $this->subscriptionId = $_GET["subscriptionId"];
- $ms = \App\Models\MemberSubscription::findOrFail($this->subscriptionId);
- $this->subscription = \App\Models\Subscription::findOrFail($ms->subscription_id);
- $this->rows[0]['subscription_id'] = $this->subscription->id;
- $this->rows[0]['subscription'] = $this->subscription;
- }
- if (isset($_GET["rateId"])) {
- $this->rateId = $_GET["rateId"];
- }
- if (isset($_GET["backToRates"])) {
- $this->backToRates = true;
- }
- if (isset($_GET["months"]) && $_GET["months"] != '') {
- $this->fromCourse = true;
- $price = $_GET["price"] / 100 * 100;
- $this->refreshAfter = 1;
- $desc = "Pagamento";
- $months = explode("|", $_GET["months"]);
- $this->months = $months;
- //$this->rows[0]["amount"] = formatPrice($price * sizeof($months));
- $this->rows[0]["amount"] = formatPrice($price);
- $rates = [];
- if (isset($_GET["rateId"])) {
- try {
- $rateIds = explode(",", $_GET["rateId"]);
- $rates = \App\Models\Rate::whereIn('id', $rateIds)->orderBy('date', 'asc')->get();
- } catch (\Throwable $e) {
- }
- $order = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
- $index = 0;
- foreach ($rates as $rate) {
- $rate_date = Carbon::createFromFormat("Y-m-d H:i:s", $rate->date);
- $rate_months = json_decode($rate->months, true);
- usort($rate_months, function ($a, $b) use ($order) {
- $posA = array_search($a, $order);
- $posB = array_search($b, $order);
- return $posA <=> $posB;
- });
- foreach ($rate_months as $month) {
- $rate_year = $rate_date->year;
- $rate_month = $rate_date->month;
- if ($rate_month < 9 && $rate_month >= 1) {
- $rate_year -= 1;
- }
- if ($month >= 9 && $month <= 12) {
- } elseif ($month < 9 && $month >= 1) {
- $rate_year += 1;
- }
- $this->rows[0]["when"][$index]["month"] = $month;
- $this->rows[0]["when"][$index]["year"] = $rate_year;
- $index++;
- $desc .= " " . $this->getMonth($month) . " " . $rate_year;
- }
- }
- }
- // foreach ($months as $idx => $m) {
- // $this->rows[0]["when"][$idx]["month"] = $m;
- // if ($m >= date("m"))
- // $this->rows[0]["when"][$idx]["year"] = date("Y");
- // else
- // $this->rows[0]["when"][$idx]["year"] = date("Y") + 1;
- // if ($idx > 0) {
- // if ($this->rows[0]["when"][$idx - 1]["year"] != $this->rows[0]["when"][$idx]["year"])
- // $desc .= " " . $this->rows[0]["when"][$idx - 1]["year"] . " ";
- // }
- // $desc .= " " . $this->getMonth($m); // . " " . $this->rows[0]["when"][$idx]["year"];
- // }
- // $desc .= " " . $this->rows[0]["when"][$idx]["year"];
- $this->rows[0]["note"] = $desc;
- $count += 1;
- }
- if (isset($_GET["createSubscription"]) && $_GET["createSubscription"] == 1) {
- $this->createSubscription = 1;
- if (isset($_GET["courseId"]) && $_GET["courseId"] > 0) {
- $this->courseId = $_GET["courseId"];
- }
- if (isset($_GET["subscriptionId"]) && $_GET["subscriptionId"] > 0) {
- $this->subscriptionId = $_GET["subscriptionId"];
- }
- if ($this->courseId && $this->courseId > 0) {
- $mc = \App\Models\MemberCourse::findOrFail($this->courseId);
- $this->course = \App\Models\Course::findOrFail($mc->course_id);
- }
- if ($this->subscriptionId && $this->subscriptionId > 0) {
- $ms = \App\Models\MemberSubscription::findOrFail($this->subscriptionId);
- $this->subscription = \App\Models\Subscription::findOrFail($ms->subscription_id);
- }
- $this->rateId = $_GET["rateId"];
- $price = $_GET["subscription_price"] / 100 * 100;
- $this->refreshAfter = 1;
- if ($count == 1)
- $this->rows[] = array('causal_id' => null, 'course_id' => null, 'course' => null, 'subscription_id' => null, 'subscription' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
- $this->rows[$count]["causal_id"] = null;
- $this->rows[$count]["course_id"] = $this->course->id ?? null;
- $this->rows[$count]["course"] = $this->course ?? null;
- $this->rows[$count]["subscription_id"] = $this->subscription->id ?? null;
- $this->rows[$count]["subscription"] = $this->subscription ?? null;
- $this->rows[$count]["amount"] = formatPrice($price);
- $note = implode(", ", array_filter([
- $this->course ? $this->course->name : "",
- $this->subscription ? $this->subscription->name : ""
- ]));
- $this->rows[$count]["note"] = "Pagamento iscrizione " . $note;
- if (isset($_GET["subCausalId"])) {
- $this->refreshAfter = 1;
- $this->rows[$count]["causal_id"] = $_GET["subCausalId"];
- }
- }
- }
- $this->first = false;
- }
- public function search()
- {
- $this->hasFilter = true;
- }
- public function disableSearch()
- {
- $this->filterMember = 0;
- $this->filterPaymentMethod = 0;
- $this->filterCausals = 0;
- $this->filterCourses = 0;
- $this->filterSubscriptions = 0;
- $this->filterTo = '';
- $this->filterFrom = '';
- $this->filterCommercial = 0;
- $this->hasFilter = false;
- $this->total = 0;
- }
- public function render()
- {
- $datas = [];
- return view('livewire.records_in', ['datas' => $datas]);
- }
- public function executeMultipleAction()
- {
- if ($this->multipleAction == 'delete')
- $this->multipleDelete();
- }
- public function add()
- {
- $this->emit('load-select');
- //if ($this->hasFilter)
- $this->emit('hide-search');
- $this->resetFields();
- $this->dataId = 0;
- $this->add = true;
- $this->update = false;
- $this->emit('setEdit', true);
- }
- public function storeCorrispettivo()
- {
- $this->emit('refresh');
- $rules = [
- 'member_id' => 'required'
- ];
- $this->validate($rules);
- foreach ($this->payments as $p) {
- if ($p->corrispettivo_fiscale) {
- $price = isset($this->corrispettivo[$p->id]) ? $this->currencyToDouble($this->corrispettivo[$p->id]) : 0;
- $destination_id = isset($this->corrispettivo_destination[$p->id]) ? $this->corrispettivo_destination[$p->id] : null;
- if ($price > 0) {
- $record = \App\Models\Record::create([
- 'member_id' => $this->member_id,
- 'supplier_id' => null,
- 'payment_method_id' => $p->id,
- 'destination_id' => $destination_id,
- 'commercial' => $this->commercial,
- 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
- 'date' => $this->date,
- 'type' => $this->type,
- 'amount' => $price,
- 'financial_movement' => $this->financial_movement,
- 'deleted' => $this->deleted
- ]);
- if ($this->courseId && $this->courseId > 0) {
- $mc = \App\Models\MemberCourse::findOrFail($this->courseId);
- $this->course = \App\Models\Course::findOrFail($mc->course_id);
- }
- if ($this->subscriptionId && $this->subscriptionId > 0) {
- $ms = \App\Models\MemberSubscription::findOrFail($this->subscriptionId);
- $this->subscription = \App\Models\Subscription::findOrFail($ms->subscription_id);
- }
- \App\Models\RecordRow::create([
- 'record_id' => $record->id,
- 'causal_id' => $this->corrispettivo_causal_id,
- 'course_id' => $this->course->id ?? null,
- 'subscription_id' => $this->subscription->id ?? null,
- 'note' => '',
- 'amount' => $price,
- 'vat_id' => null,
- 'commercial' => $this->commercial,
- 'when' => json_encode([])
- ]);
- }
- }
- }
- $this->resetFields();
- $this->add = false;
- $this->isDuplicate = false;
- $this->emit('setEdit', false);
- }
- public function store($generate)
- {
- Log::info("Starting store method");
- $this->emit('refresh');
- $rules = [
- 'payment_method_id' => 'required',
- 'rows.*.causal_id' => 'required',
- 'rows.*.amount' => 'required'
- ];
- if (!$this->commercial)
- $rules["member_id"] = 'required';
- $this->validate($rules);
- /* Validazione campi azienda per generazione ricevuta */
- try {
- if (!$this->financial_movement && !$this->commercial) {
- $no_receipt_causal_azienda = false;
- foreach ($this->rows as $row) {
- $no_receipt_causal_azienda = false;
- $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
- if ($cau->no_receipt)
- $no_receipt_causal_azienda = true;
- }
- $azienda = \App\Models\Azienda::first();
- $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
- if (!$payment_method->money) {
- if (!$no_receipt_causal_azienda) {
- if (!$azienda->isValid()) {
- session()->flash('error_ricevuta', implode("", array_map(function ($item) {
- return "<li>$item</li>";
- }, $azienda->validate())));
- return false;
- }
- }
- }
- }
- } catch (\Exception $ex) {
- Log::error("Error in store method: " . $ex->getMessage());
- Log::error("Stack trace: " . $ex->getTraceAsString());
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- /* END - Validazione campi azienda per generazione ricevuta */
- try {
- $totalGross = 0;
- $totalSconto = 0;
- $totalNet = 0;
- foreach ($this->rows as $row) {
- $rowAmount = $this->currencyToDouble($row["amount"]);
- $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
- $rowNet = max(0, $rowAmount - $rowSconto);
- $totalGross += $rowAmount;
- $totalSconto += $rowSconto;
- $totalNet += $rowNet;
- }
- Log::info("Total gross: " . $totalGross . ", Total sconto: " . $totalSconto . ", Total net: " . $totalNet);
- $record = \App\Models\Record::create([
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- 'payment_method_id' => $this->payment_method_id,
- 'destination_id' => $this->destination_id,
- 'commercial' => $this->commercial,
- 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
- 'date' => $this->date,
- 'type' => $this->type,
- 'amount' => $totalNet,
- 'prediscount_amount' => $totalGross,
- 'financial_movement' => $this->financial_movement,
- 'deleted' => $this->deleted,
- 'numero_fattura' => '',
- ]);
- $this->dataId = $record->id;
- $no_receipt_causal = false;
- $vat = 0;
- foreach ($this->rows as $row) {
- foreach ($row["when"] as $x => $y) {
- $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
- }
- $rowAmount = $this->currencyToDouble($row["amount"]);
- $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
- $rowNet = max(0, $rowAmount - $rowSconto);
- Log::info("Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
- \App\Models\RecordRow::create([
- 'record_id' => $this->dataId,
- 'causal_id' => $row["causal_id"],
- 'course_id' => $row["course_id"],
- 'subscription_id' => $row["subscription_id"],
- 'note' => $row["note"],
- 'amount' => $rowNet,
- 'prediscount_amount' => $rowAmount,
- 'sconto' => $rowSconto,
- 'vat_id' => $row["vat_id"],
- 'commercial' => $this->commercial,
- 'when' => json_encode($row["when"])
- ]);
- $vat += getVatValue($rowNet, $row["vat_id"]);
- $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
- if ($cau->no_receipt)
- $no_receipt_causal = true;
- if ($cau->money) {
- if ($rowNet >= env('MIN_MONEY', 100)) {
- $money = new \App\Models\Money();
- $money->member_id = $this->member_id;
- $money->record_id = $this->dataId;
- $money->amount = env('EXTRA_MONEY', 10);
- $money->date = date("Y-m-d");
- $money->note = env('EXTRA_MONEY', 10) . ' in più per aver caricato ' . $rowNet;
- $money->save();
- }
- }
- }
- Log::info("Final amount saved to record: " . $totalNet);
- if (!$this->financial_movement) {
- $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
- if (!$payment_method->money) {
- if ($generate && !$no_receipt_causal)
- $this->createReceipt();
- }
- }
- if ($this->rateId > 0) {
- $rates = explode(",", $this->rateId);
- foreach ($rates as $rid) {
- $rate = \App\Models\Rate::findOrFail($rid);
- $rate->status = 1;
- $rate->record_id = $record->id;
- $rate->save();
- }
- }
- if ($this->backToRates) {
- if ($this->courseId > 0)
- return redirect()->to("/rates?member_id={$this->member_id}&member_course_id={$this->courseId}");
- if ($this->subscriptionId > 0)
- return redirect()->to("/rates?member_id={$this->member_id}&member_subscription_id={$this->subscriptionId}");
- }
- session()->flash('success', 'Movimento creato');
- $this->resetFields();
- $this->add = false;
- $this->isDuplicate = false;
- $this->emit('setEdit', false);
- } catch (\Exception $ex) {
- Log::error("Error in store method: " . $ex->getMessage());
- Log::error("Stack trace: " . $ex->getTraceAsString());
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function duplicate($id)
- {
- $record = \App\Models\Record::findOrFail($id);
- $newRecord = $record->replicate();
- $newRecord->save();
- $rows = \App\Models\RecordRow::where('record_id', $id)->get();
- foreach ($rows as $r) {
- $newRow = $r->replicate();
- $newRow->record_id = $newRecord->id;
- $newRow->save();
- }
- $this->edit($newRecord->id);
- $this->isDuplicate = true;
- }
- public function edit($id)
- {
- if (!isset($_GET["from"]) && $this->fromPage == '')
- $this->fromPage = 'in';
- $this->emit('setEdit', true);
- //if ($this->hasFilter)
- $this->emit('hide-search');
- $this->emit('load-select');
- try {
- $record = \App\Models\Record::findOrFail($id);
- if (!$record) {
- session()->flash('error', 'Movimento non trovato');
- } else {
- if ($record->member_id) {
- $member = \App\Models\Member::find($record->member_id);
- if (!$member || $member->status == 'archived') {
- $this->member_id = null;
- } else {
- $this->member_id = $record->member_id;
- }
- } else {
- $this->member_id = $record->member_id;
- }
- if ($record->payment_method_id) {
- $paymentMethod = \App\Models\PaymentMethod::find($record->payment_method_id);
- if (!$paymentMethod || (isset($paymentMethod->hidden) && $paymentMethod->hidden)) {
- $this->payment_method_id = null;
- } else {
- $this->payment_method_id = $record->payment_method_id;
- }
- } else {
- $this->payment_method_id = $record->payment_method_id;
- }
- $this->destination_id = $record->destination_id;
- $this->supplier_id = $record->supplier_id;
- $this->amount = $record->amount;
- $this->commercial = $record->commercial;
- $this->corrispettivo_fiscale = $record->corrispettivo_fiscale;
- $this->date = date("Y-m-d", strtotime($record->date));
- $this->type = $record->type;
- $this->deleted = $record->deleted;
- $this->financial_movement = $record->financial_movement;
- $this->dataId = $record->id;
- $this->update = true;
- $this->add = false;
- $rows = \App\Models\RecordRow::where('record_id', $this->dataId)
- ->select('causal_id', 'course_id', 'subscription_id', 'note', 'commercial', 'when', 'amount', 'prediscount_amount', 'sconto', 'vat_id')
- ->get();
- $this->rows = [];
- foreach ($rows as $i => $r) {
- $grossAmount = $r->prediscount_amount ?? ($r->amount + $r->sconto);
- $causalId = $r->causal_id;
- if ($causalId) {
- $causal = \App\Models\Causal::find($causalId);
- if (!$causal || (isset($causal->hidden) && $causal->hidden)) {
- $causalId = null;
- }
- }
- $course = null;
- if ($r->course_id) {
- try {
- $course = \App\Models\Course::findOrFail($r->course_id);
- } catch (\Throwable $th) {
- }
- }
- $subscription = null;
- if ($r->subscription_id) {
- try {
- $subscription = \App\Models\Subscription::findOrFail($r->subscription_id);
- } catch (\Throwable $th) {
- }
- }
- $this->rows[] = [
- 'causal_id' => $causalId,
- 'course_id' => $r->course_id,
- 'course' => $course,
- 'subscription_id' => $r->subscription_id,
- 'subscription' => $subscription,
- 'note' => $r->note,
- 'commercial' => $r->commercial,
- 'when' => json_decode($r->when),
- 'amount' => formatPrice($grossAmount),
- 'sconto' => formatPrice($r->sconto),
- 'vat_id' => $r->vat_id
- ];
- }
- $exist = \App\Models\Receipt::where('record_id', $id)->orderBy('id', 'DESC')->first();
- if ($exist != null) {
- $this->currentReceip = $exist;
- $this->parent = $this->currentReceip->parent;
- }
- $this->refreshEditOptions();
- }
- } catch (\Exception $ex) {
- Log::error("Error in edit method: " . $ex->getMessage());
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- private function refreshEditOptions()
- {
- $this->causals = array();
- $visibleCausals = \App\Models\Causal::select('id', 'name')
- ->where('parent_id', null)
- ->where('type', 'IN')
- ->where(function ($query) {
- $query->where('hidden', false)->orWhereNull('hidden');
- })
- ->get();
- $this->getCausale($visibleCausals, 0);
- $this->payments = \App\Models\PaymentMethod::select('id', 'name')
- ->where('enabled', true)
- ->whereIn('type', array('ALL', 'IN'))
- ->where(function ($query) {
- $query->where('hidden', false)->orWhereNull('hidden');
- })
- ->orderBy('name')
- ->get();
- if ($this->commercial) {
- $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
- ->where(function ($query) {
- $query->where('status', '!=', 'archived');
- })
- ->orderBy('last_name')
- ->orderBy('first_name')
- ->get();
- } else {
- $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
- ->where(function ($query) {
- $query->where('current_status', 2)->orWhere('current_status', 1);
- })
- ->where(function ($query) {
- $query->where('status', '!=', 'archived');
- })
- ->orderBy('last_name')
- ->orderBy('first_name')
- ->get();
- }
- }
- public function update($generate = false)
- {
- Log::info("Starting update method");
- $this->emit('refresh');
- $rules = [
- 'payment_method_id' => 'required',
- 'rows.*.causal_id' => 'required',
- 'rows.*.amount' => 'required'
- ];
- if (!$this->commercial)
- $rules["member_id"] = 'required';
- $this->validate($rules);
- /* Validazione campi azienda per generazione ricevuta */
- try {
- if (!$this->financial_movement && !$this->commercial) {
- $no_receipt_causal_azienda = false;
- foreach ($this->rows as $row) {
- $no_receipt_causal_azienda = false;
- $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
- if ($cau->no_receipt)
- $no_receipt_causal_azienda = true;
- }
- $azienda = \App\Models\Azienda::first();
- $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
- if (!$payment_method->money) {
- if (!$no_receipt_causal_azienda) {
- if (!$azienda->isValid()) {
- session()->flash('error_ricevuta', implode("", array_map(function ($item) {
- return "<li>$item</li>";
- }, $azienda->validate())));
- return false;
- }
- }
- }
- }
- } catch (\Exception $ex) {
- Log::error("Error in store method: " . $ex->getMessage());
- Log::error("Stack trace: " . $ex->getTraceAsString());
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- /* END - Validazione campi azienda per generazione ricevuta */
- try {
- $totalGross = 0;
- $totalSconto = 0;
- $totalNet = 0;
- foreach ($this->rows as $row) {
- $rowAmount = $this->currencyToDouble($row["amount"]);
- $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
- $rowNet = max(0, $rowAmount - $rowSconto);
- $totalGross += $rowAmount;
- $totalSconto += $rowSconto;
- $totalNet += $rowNet;
- }
- Log::info("Total gross: " . $totalGross . ", Total sconto: " . $totalSconto . ", Total net: " . $totalNet);
- \App\Models\Record::whereId($this->dataId)->update([
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- 'payment_method_id' => $this->payment_method_id,
- 'destination_id' => $this->destination_id,
- 'commercial' => $this->commercial,
- 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
- 'date' => date("Y-m-d", strtotime($this->date)),
- 'type' => $this->type,
- 'financial_movement' => $this->financial_movement,
- 'deleted' => $this->deleted,
- 'amount' => $totalNet,
- 'prediscount_amount' => $totalGross,
- ]);
- $no_receipt_causal = false;
- $vat = 0;
- \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
- foreach ($this->rows as $row) {
- foreach ($row["when"] as $x => $y) {
- $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
- }
- $rowAmount = $this->currencyToDouble($row["amount"]);
- $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
- $rowNet = max(0, $rowAmount - $rowSconto);
- Log::info("Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
- \App\Models\RecordRow::create([
- 'record_id' => $this->dataId,
- 'causal_id' => $row["causal_id"],
- 'course_id' => $row["course_id"],
- 'subscription_id' => $row["subscription_id"],
- 'note' => $row["note"],
- 'vat_id' => $row["vat_id"],
- 'amount' => $rowNet,
- 'prediscount_amount' => $rowAmount,
- 'sconto' => $rowSconto,
- 'commercial' => $this->commercial,
- 'when' => json_encode($row["when"])
- ]);
- $vat += getVatValue($rowNet, $row["vat_id"]);
- $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
- if ($cau->no_receipt)
- $no_receipt_causal = true;
- }
- Log::info("Final amount saved to record: " . $totalNet);
- if (!$this->financial_movement) {
- $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
- if (!$payment_method->money) {
- if ($generate && !$no_receipt_causal)
- $this->createReceipt();
- }
- }
- session()->flash('success', 'Movimento aggiornato');
- if ($this->backToRates) {
- if ($this->courseId > 0)
- return redirect()->to("/rates?member_id={$this->member_id}&member_course_id={$this->courseId}");
- if ($this->subscriptionId > 0)
- return redirect()->to("/rates?member_id={$this->member_id}&member_subscription_id={$this->subscriptionId}");
- }
- $this->resetFields();
- $this->update = false;
- $this->isDuplicate = false;
- $this->emit('setEdit', false);
- } catch (\Exception $ex) {
- Log::error("Error in update method: " . $ex->getMessage());
- Log::error("Stack trace: " . $ex->getTraceAsString());
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function rigenerate()
- {
- $this->emit('refresh');
- try {
- $record = \App\Models\Record::findOrFail($this->dataId);
- $newRecord = $record->replicate();
- $newRecord->date = date("Y-m-d");
- $newRecord->save();
- $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
- // Inserisco le righe
- foreach ($recordRows as $row) {
- $newRow = $row->replicate();
- $newRow->record_id = $newRecord->id;
- $newRow->save();
- }
- $this->dataId = $newRecord->id;
- $this->createReceipt();
- session()->flash('success', 'Movimento aggiornato');
- $this->resetFields();
- $this->update = false;
- $this->isDuplicate = false;
- $this->emit('setEdit', false);
- } catch (\Exception $ex) {
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function cancel()
- {
- // Se arrivo da duplica elimino
- if ($this->isDuplicate) {
- try {
- \App\Models\Record::find($this->dataId)->delete();
- session()->flash('success', "Movimento eliminato");
- } catch (\Exception $e) {
- session()->flash('error', 'Errore (' . $e->getMessage() . ')');
- }
- }
- $this->isDuplicate = false;
- $this->add = false;
- $this->update = false;
- $this->resetFields();
- $this->emit('setEdit', false);
- return redirect()->to('/in');
- }
- public function delete($id)
- {
- try {
- $r = \App\Models\Record::find($id);
- // Annullo la ricevuta
- $receipt = \App\Models\Receipt::where('record_id', $r->id)->first();
- if ($receipt) {
- $receipt->status = 99;
- sendReceiptDeleteEmail($receipt);
- $receipt->save();
- }
- if ($r->member_course_id > 0) {
- $months = json_decode($r->months);
- $c = \App\Models\MemberCourse::findOrFail($r->member_course_id);
- $xxx = json_decode($c->months);
- foreach ($xxx as $idx => $mm) {
- if (in_array($mm->m, $months)) {
- $xxx[$idx]->status = "";
- }
- }
- $c->months = json_encode($xxx);
- $c->save();
- }
- if ($r->member_subscription_id > 0) {
- $months = json_decode($r->months);
- $s = \App\Models\MemberSubscription::findOrFail($r->member_subscription_id);
- $xxx = json_decode($s->months);
- foreach ($xxx as $idx => $mm) {
- if (in_array($mm->m, $months)) {
- $xxx[$idx]->status = "";
- }
- }
- $s->months = json_encode($xxx);
- $s->save();
- }
- $r->deleted = true;
- $r->save();
- session()->flash('success', 'Movimento aggiornato');
- $this->resetFields();
- $this->update = false;
- $this->isDuplicate = false;
- $this->emit('setEdit', false);
- $this->emit('reload');
- //$this->emit('load-data-table');
- } catch (\Exception $ex) {
- session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
- }
- }
- public function multipleDelete()
- {
- try {
- foreach ($this->multipleIds as $id) {
- \App\Models\Record::find($id)->delete();
- }
- } catch (\Exception $e) {
- session()->flash('error', 'Errore (' . $e->getMessage() . ')');
- }
- $this->multipleAction = '';
- }
- public function createMember()
- {
- $this->newMemberFiscalCodeExist = false;
- $this->validate([
- // 'newMemberFiscalCode'=>'required|max:16',
- 'newMemberFirstName' => 'required',
- 'newMemberLastName' => 'required',
- //'newMemberEmail'=>'required',
- ]);
- // Check fiscal code exist
- $exist = false;
- if ($this->newMemberFiscalCode != '') {
- $check = \App\Models\Member::where('fiscal_code', $this->newMemberFiscalCode)->get();
- $exist = $check->count() > 0;
- }
- if (!$exist) {
- $member = \App\Models\Member::create([
- 'first_name' => strtoupper($this->newMemberFirstName),
- 'last_name' => strtoupper($this->newMemberLastName),
- 'email' => strtoupper($this->newMemberEmail),
- 'to_complete' => $this->newMemberToComplete,
- 'fiscal_code' => $this->newMemberFiscalCode,
- 'status' => true
- ]);
- $this->member_id = $member->id;
- $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->get();
- // $this->emit('reloadMembers');
- $this->emit('refresh');
- $this->newMemberFirstName = '';
- $this->newMemberLastName = '';
- $this->newMemberEmail = '';
- $this->newMemberToComplete = false;
- $this->newMemberFiscalCode = '';
- $this->emit('saved');
- //$this->validate();
- $this->selectId++;
- } else {
- $this->newMemberFiscalCodeExist = true;
- }
- }
- public function createReceipt()
- {
- // Ulteriore controllo commerciale/non commerciale
- if (!$this->commercial) {
- $create = false;
- $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->orderBy('id', 'DESC')->first();
- if ($receipt != null) {
- // Controllo lo stato, se 99 ne genero una nuova
- if ($receipt->status == 99) {
- $create = true;
- }
- } else {
- $create = true;
- }
- if ($create) {
- $number = 1;
- $exist = \App\Models\Receipt::where('year', date("Y"))->orderBy('number', 'DESC')->first();
- if ($exist != null)
- $number = $exist->number + 1;
- // Calculate totals for the receipt
- $totalGross = 0;
- $totalNet = 0;
- foreach ($this->rows as $row) {
- $rowAmount = $this->currencyToDouble($row["amount"]);
- $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
- $rowNet = max(0, $rowAmount - $rowSconto);
- $totalGross += $rowAmount;
- $totalNet += $rowNet;
- }
- $receipt = \App\Models\Receipt::create([
- 'record_id' => $this->dataId,
- 'member_id' => $this->member_id,
- 'supplier_id' => $this->supplier_id,
- 'payment_method_id' => $this->payment_method_id,
- 'number' => $number,
- 'date' => $this->date,
- 'year' => date("Y"),
- 'type' => $this->type,
- 'parent' => $this->parent,
- 'status' => 1,
- ]);
- foreach ($this->rows as $row) {
- $rowAmount = $this->currencyToDouble($row["amount"]);
- $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
- $rowNet = max(0, $rowAmount - $rowSconto);
- Log::info("Receipt Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
- \App\Models\ReceiptRow::create([
- 'receip_id' => $receipt->id,
- 'causal_id' => $row["causal_id"],
- 'course_id' => $row["course_id"],
- 'subscription_id' => $row["subscription_id"],
- 'note' => $row["note"],
- 'vat_id' => $row["vat_id"],
- 'amount' => $rowNet,
- 'prediscount_amount' => $rowAmount,
- 'sconto' => $rowSconto,
- 'commercial' => $row["commercial"],
- 'when' => json_encode($row["when"])
- ]);
- }
- $this->currentReceip = $receipt;
- sendReceiptEmail($receipt);
- session()->flash('receipt', "Ricevuta " . $number . "/" . date("Y") . " creata correttamente");
- $this->emit('showReceipt', $this->currentReceip->id);
- }
- }
- }
- public function removeReceipt()
- {
- $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
- $receipt->status = 99;
- $receipt->save();
- sendReceiptDeleteEmail($receipt);
- $this->currentReceip = $receipt;
- $this->emit('success');
- }
- function currencyToDouble($val)
- {
- $x = str_replace("€", "", $val);
- $x = str_replace(".", "", $x);
- $x = str_replace(",", ".", $x);
- return floatval(trim($x));
- }
- public function addRow()
- {
- $this->rows[] = array('causal_id' => null, 'course_id' => null, 'course' => null, 'subscription_id' => null, 'subscription' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
- $this->emit('load-select');
- }
- public function delRow($idx)
- {
- unset($this->rows[$idx]);
- // $this->emit('load-select');
- }
- public function addPeriod($idx)
- {
- $x = sizeof($this->rows[$idx]['when']) - 1;
- $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
- $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
- }
- public function delPeriod($idx, $xxx)
- {
- array_splice($this->rows[$idx]['when'], $xxx, $xxx);
- //unset($this->rows[$idx]['when'][$xxx]);
- // $this->emit('load-select');
- }
- public function getTotal()
- {
- $total = 0.00;
- foreach ($this->rows as $r) {
- if ($r["amount"] != null && $r["amount"] != "") {
- $rowAmount = $this->currencyToDouble($r["amount"]);
- $rowSconto = isset($r['sconto']) ? $this->currencyToDouble($r['sconto']) : 0;
- $netAmount = max(0, $rowAmount - $rowSconto);
- $total += $netAmount;
- if ($r["vat_id"] > 0)
- $total += getVatValue($netAmount, $r["vat_id"]);
- }
- }
- return formatPrice($total);
- }
- public function getTotalCorrispettivo()
- {
- $total = 0.00;
- foreach ($this->corrispettivo as $r) {
- $total += $this->currencyToDouble($r);
- }
- return formatPrice($total);
- // $this->emit('load-select');
- }
- public function getPrice()
- {
- $total = 0.00;
- foreach ($this->rows as $r) {
- if ($r["amount"] != null && $r["amount"] != "")
- $total += $this->currencyToDouble($r["amount"]);
- }
- return formatPrice($total);
- // $this->emit('load-select');
- }
- public function getVat()
- {
- $total = 0.00;
- foreach ($this->rows as $r) {
- if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
- $total += getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
- }
- return formatPrice($total);
- // $this->emit('load-select');
- }
- public function getVats()
- {
- $vats = array();
- foreach ($this->rows as $r) {
- if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0) {
- $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
- $vatName = "";
- foreach ($this->vats as $v) {
- if ($v->id == $r["vat_id"])
- $vatName = $v->name;
- }
- if (isset($vats[$vatName]))
- $vats[$vatName] += $vat;
- else
- $vats[$vatName] = $vat;
- }
- }
- return $vats;
- // $this->emit('load-select');
- }
- public function setCausal($id, $idx)
- {
- $this->rows[$idx]["causal_id"] = $id;
- }
- public function printReceipt()
- {
- //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
- $pdf = PDF::loadView('receipt', array('receipt' => $this->currentReceip)); //->output();
- $pdfName = "Ricevuta_" . $this->currentReceip->member->last_name . "_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf";
- return $pdf->stream();
- /*return response()->streamDownload(
- fn () => print($pdf),
- "ricevuta_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf"
- );*/
- /*return response()->streamDownload(function () {
- echo $pdf->stream();
- }, 'test.pdf');*/
- }
- public function multiPeriod()
- {
- $this->multiP = true;
- }
- public function multiPeriodCreate($idx)
- {
- $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
- $this->rows[$idx]['when'] = [];
- foreach ($period as $dt) {
- if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
- $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
- }
- $this->multiP = false;
- }
- public function multiPeriodCancel()
- {
- $this->multiP = false;
- }
- public function getMonth($m)
- {
- $ret = '';
- switch ($m) {
- case 1:
- $ret = 'Gennaio';
- break;
- case 2:
- $ret = 'Febbraio';
- break;
- case 3:
- $ret = 'Marzo';
- break;
- case 4:
- $ret = 'Aprile';
- break;
- case 5:
- $ret = 'Maggio';
- break;
- case 6:
- $ret = 'Giugno';
- break;
- case 7:
- $ret = 'Luglio';
- break;
- case 8:
- $ret = 'Agosto';
- break;
- case 9:
- $ret = 'Settembre';
- break;
- case 10:
- $ret = 'Ottobre';
- break;
- case 11:
- $ret = 'Novembre';
- break;
- case 12:
- $ret = 'Dicembre';
- break;
- default:
- $ret = '';
- break;
- }
- return $ret;
- }
- public function setYear($idx, $xxx)
- {
- $m = $this->rows[$idx]["when"][$xxx]["month"];
- $this->rows[$idx]["when"][$xxx]["year"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
- }
- }
|