RecordIN.php 61 KB

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