RecordIN.php 54 KB

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