RecordIN.php 63 KB

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