RecordIN.php 58 KB

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