RecordIN.php 54 KB

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