RecordIN.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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. class RecordIN extends Component
  10. {
  11. use WithPagination;
  12. protected $paginationTheme = 'bootstrap';
  13. protected $listeners = ['setCausal' => 'setCausal'];
  14. public $sortField ='date';
  15. public $sortAsc = false;
  16. public $typeIN = "IN";
  17. public $isDuplicate = false;
  18. public $multiP = false;
  19. public $multiMonthTo = 0;
  20. public $multiYearTo = 0;
  21. public $multiMonthFrom = 0;
  22. public $multiYearFrom = 0;
  23. public $createSubscription = 0;
  24. public $corrispettivo_causal_id = 0;
  25. public function sortBy($field)
  26. {
  27. if($this->sortField === $field)
  28. {
  29. $this->sortAsc = ! $this->sortAsc;
  30. } else {
  31. $this->sortAsc = true;
  32. }
  33. $this->sortField = $field;
  34. }
  35. public $courseId = 0;
  36. public $months = array();
  37. public $records, $dataId, $member_id, $supplier_id,
  38. $causal_id,
  39. $payment_method_id,
  40. $date,
  41. $month,
  42. $year,
  43. $type,
  44. $deleted,
  45. $financial_movement,
  46. $amount,
  47. $vat,
  48. $virtual,
  49. $note,
  50. $parent,
  51. $corrispettivo_fiscale,
  52. $commercial, $update = false, $add = false;
  53. public $corrispettivo = [];
  54. public $currentReceip;
  55. public $filterMember = 0, $filterPaymentMethod = 0, $filterCausals = 0, $filterFrom = '', $filterTo = '', $filterCommercial = 0;
  56. public $hasFilter = false;
  57. public $total = 0;
  58. public $selectedFilter = '';
  59. public $multipleIds = [];
  60. public $multipleAction = '';
  61. public $first = true;
  62. public $selectId = 0;
  63. public $refreshAfter = 0;
  64. public $canSave = true;
  65. public $newMemberFirstName = '';
  66. public $newMemberLastName = '';
  67. public $newMemberEmail = '';
  68. public $newMemberToComplete = false;
  69. public $newMemberFiscalCode = '';
  70. public $newMemberFiscalCodeExist = false;
  71. public $causals = array();
  72. public $payments = array();
  73. public $members = array();
  74. public $vats = array();
  75. public $rows = array();
  76. protected $rules = [
  77. 'member_id' => 'required',
  78. 'payment_method_id' => 'required',
  79. 'rows.*.causal_id' => 'required',
  80. 'rows.*.amount' => 'required'
  81. ];
  82. protected $messages = [
  83. 'member_id.required' => 'La persona è obbligatorio',
  84. 'payment_method_id.required' => 'Il metodo di pagamento è obbligatorio',
  85. 'rows.*.causal_id.required' => 'La causale è obbligatoria',
  86. 'rows.*.amount.required' => 'L\'importo è obbligatorio',
  87. ];
  88. public function updatedMemberId() {
  89. $this->emit('refresh');
  90. if ($this->member_id > 0)
  91. {
  92. $member = \App\Models\Member::findOrFail($this->member_id);
  93. if (!$member->isAdult())
  94. {
  95. if($member->father_name != '')
  96. $this->parent = $member->father_name . " (C.F. " . $member->father_fiscal_code . ")";
  97. else if($member->mother_name != '')
  98. $this->parent = $member->mother_name . " (C.F. " . $member->mother_fiscal_code . ")";
  99. else
  100. $this->parent = '';
  101. }
  102. $this->virtual = $member->getMoney();
  103. $this->newMemberFirstName = '';
  104. $this->newMemberLastName = '';
  105. $this->newMemberEmail = '';
  106. $this->newMemberToComplete = false;
  107. $this->newMemberFiscalCode = '';
  108. $this->newMemberFiscalCodeExist = false;
  109. }
  110. }
  111. public function updatedCausalId() {
  112. //$this->emit('refresh');
  113. }
  114. public function updatedDate() {
  115. //$this->emit('refresh');
  116. }
  117. public function hydrate()
  118. {
  119. $this->emit('load-select');
  120. }
  121. /*public function updated() {
  122. $this->emit('refresh');
  123. }*/
  124. public function updatedPaymentMethodId() {
  125. //$this->emit('refresh');
  126. $this->canSave = $this->checkCanSave();
  127. }
  128. public function updatedAmount() {
  129. // $this->emit('refresh');
  130. $this->canSave = $this->checkCanSave();
  131. }
  132. public function checkCanSave()
  133. {
  134. $ret = true;
  135. if ($this->payment_method_id != null)
  136. {
  137. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  138. if ($payment_method->money)
  139. {
  140. $from = str_replace(".", "", str_replace(",", "", number_format($this->virtual, 2)));
  141. $to = str_replace(".", "", str_replace(",", "", $this->currencyToDouble($this->amount)));
  142. $ret = $from >= $to;
  143. }
  144. }
  145. return $ret;
  146. }
  147. public function setAmount()
  148. {
  149. $tot = 0;
  150. foreach($this->rows as $r)
  151. {
  152. $tot += $this->currencyToDouble($r["amount"]);
  153. }
  154. $this->amount = $tot;
  155. $this->canSave = $this->checkCanSave();
  156. }
  157. public function resetFields(){
  158. $this->member_id = null;
  159. $this->supplier_id = null;
  160. $this->payment_method_id = null;
  161. $this->commercial = 0;
  162. $this->corrispettivo_fiscale = false;
  163. $this->date = date("Y-m-d");
  164. $this->type = 'IN';
  165. $this->deleted = false;
  166. $this->financial_movement = false;
  167. $this->newMemberFirstName = '';
  168. $this->newMemberLastName = '';
  169. $this->newMemberEmail = '';
  170. $this->newMemberToComplete = false;
  171. $this->newMemberFiscalCode = '';
  172. $this->newMemberFiscalCodeExist = false;
  173. $this->currentReceip = null;
  174. $this->parent = '';
  175. $this->courseId = 0;
  176. $this->months = array();
  177. $this->rows = array();
  178. $this->rows[] = array('causal_id' => isset($_GET["causalId"]) ? $_GET["causalId"] : null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  179. $this->corrispettivo = [];
  180. $this->emit('load-data-table');
  181. }
  182. public function getMemberProperty()
  183. {
  184. $ret = null;
  185. if ($this->member_id > 0)
  186. {
  187. $ret = \App\Models\Member::findOrFail($this->member_id);
  188. }
  189. return $ret;
  190. }
  191. public function getCausalProperty()
  192. {
  193. $ret = null;
  194. if ($this->causal_id > 0)
  195. {
  196. $ret = \App\Models\Causal::findOrFail($this->causal_id);
  197. }
  198. return $ret;
  199. }
  200. public function getCausal($causal)
  201. {
  202. $ret = '';
  203. if ($causal > 0)
  204. {
  205. $ret = \App\Models\Causal::findOrFail($causal)->getTree();
  206. }
  207. return $ret;
  208. }
  209. public function getPaymentMethod($payment)
  210. {
  211. $ret = '';
  212. if ($payment > 0)
  213. {
  214. $ret = \App\Models\PaymentMethod::findOrFail($payment)->name;
  215. }
  216. return $ret;
  217. }
  218. function buildTree($records, $parentId = 0) {
  219. $this->causals = array();
  220. foreach ($records as $record)
  221. {
  222. if ($record->parent_id == $parentId)
  223. {
  224. $children = $this->buildTree($record, $record->id);
  225. if ($children) {
  226. $record->children = $children;
  227. }
  228. $this->causals[] = $record;
  229. }
  230. }
  231. return $this->causals;
  232. }
  233. public function getCausale($records, $indentation)
  234. {
  235. foreach($records as $record)
  236. {
  237. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  238. if(count($record->childs))
  239. $this->getCausale($record->childs, $indentation + 1);
  240. }
  241. }
  242. public function mount()
  243. {
  244. $this->causals = array();
  245. $this->multiMonthFrom = date("n");
  246. $this->multiYearFrom = date("Y");
  247. $this->multiMonthTo = date("n");
  248. $this->multiYearTo = date("Y");
  249. $fisc = \App\Models\Causal::where('corrispettivo_fiscale', true)->first();
  250. if ($fisc)
  251. $this->corrispettivo_causal_id = $fisc->id;
  252. $this->getCausale(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->where('type', 'IN')->get(), 0);
  253. //$this->buildTree(\App\Models\Causal::all(), null);
  254. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
  255. $this->payments = \App\Models\PaymentMethod::select('id', 'name')->where('enabled', true)->whereIn('type', array('ALL', 'IN'))->orderBy('name')->get();
  256. $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
  257. if ($this->first)
  258. {
  259. if (isset($_GET["new"]))
  260. {
  261. $this->refreshAfter = 1;
  262. $this->add();
  263. }
  264. if (isset($_GET["memberId"]))
  265. {
  266. $this->refreshAfter = 1;
  267. $this->member_id = $_GET["memberId"];
  268. $member = \App\Models\Member::findOrFail($this->member_id);
  269. if (!$member->isAdult())
  270. {
  271. if($member->father_name != '')
  272. $this->parent = $member->father_name . " (C.F. " . $member->father_fiscal_code . ")";
  273. else if($member->mother_name != '')
  274. $this->parent = $member->mother_name . " (C.F. " . $member->mother_fiscal_code . ")";
  275. else
  276. $this->parent = '';
  277. }
  278. }
  279. if (isset($_GET["causalId"]))
  280. {
  281. $this->refreshAfter = 1;
  282. $this->causal_id = $_GET["causalId"];
  283. }
  284. if (isset($_GET["id"]))
  285. {
  286. $this->refreshAfter = 1;
  287. $this->edit($_GET["id"]);
  288. }
  289. $count = 0;
  290. if (isset($_GET["courseId"]))
  291. {
  292. $this->courseId = $_GET["courseId"];
  293. $mc = \App\Models\MemberCourse::findOrFail($this->courseId);
  294. $course = \App\Models\Course::findOrFail($mc->course_id);
  295. }
  296. if (isset($_GET["months"]))
  297. {
  298. $price = $_GET["price"] / 100 * 100;
  299. $this->refreshAfter = 1;
  300. $desc = "Pagamento";
  301. $months = explode("|", $_GET["months"]);
  302. $this->months = $months;
  303. $this->rows[0]["amount"] = formatPrice($price * sizeof($months));
  304. foreach($months as $idx => $m)
  305. {
  306. $this->rows[0]["when"][$idx]["month"] = $m;
  307. $this->rows[0]["when"][$idx]["year"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
  308. $desc .= " " . $this->getMonth($m);
  309. }
  310. $this->rows[0]["note"] = $desc;
  311. $count += 1;
  312. }
  313. if (isset($_GET["createSubscription"]) && $_GET["createSubscription"] == 1)
  314. {
  315. $this->createSubscription = 1;
  316. $this->courseId = $_GET["courseId"];
  317. $price = $_GET["subscription_price"] / 100 * 100;
  318. $this->refreshAfter = 1;
  319. if ($count == 1)
  320. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  321. $this->rows[$count]["causal_id"] = null;
  322. $this->rows[$count]["amount"] = formatPrice($price);
  323. $this->rows[$count]["note"] = "Pagamento iscrizione " . $course->name;
  324. if (isset($_GET["subCausalId"]))
  325. {
  326. $this->refreshAfter = 1;
  327. $this->rows[$count]["causal_id"] = $_GET["subCausalId"];
  328. }
  329. }
  330. }
  331. $this->first = false;
  332. }
  333. public function search()
  334. {
  335. $this->hasFilter = true;
  336. }
  337. public function disableSearch()
  338. {
  339. $this->filterMember = 0;
  340. $this->filterPaymentMethod = 0;
  341. $this->filterCausals = 0;
  342. $this->filterTo = '';
  343. $this->filterFrom = '';
  344. $this->filterCommercial = 0;
  345. $this->hasFilter = false;
  346. $this->total = 0;
  347. }
  348. public function render()
  349. {
  350. $datas = [];
  351. return view('livewire.records_in', ['datas' => $datas]);
  352. }
  353. public function executeMultipleAction(){
  354. if ($this->multipleAction == 'delete')
  355. $this->multipleDelete();
  356. }
  357. public function add()
  358. {
  359. $this->emit('load-select');
  360. //if ($this->hasFilter)
  361. $this->emit('hide-search');
  362. $this->resetFields();
  363. $this->dataId = 0;
  364. $this->add = true;
  365. $this->update = false;
  366. $this->emit('setEdit', true);
  367. }
  368. public function storeCorrispettivo()
  369. {
  370. $this->emit('refresh');
  371. $rules = [
  372. 'member_id' => 'required'
  373. ];
  374. $this->validate($rules);
  375. foreach($this->payments as $p)
  376. {
  377. if ($p->corrispettivo_fiscale)
  378. {
  379. $price = isset($this->corrispettivo[$p->id]) ? $this->currencyToDouble($this->corrispettivo[$p->id]) : 0;
  380. if ($price > 0)
  381. {
  382. $record = \App\Models\Record::create([
  383. 'member_id' => $this->member_id,
  384. 'supplier_id' => null,
  385. 'payment_method_id' => $p->id,
  386. 'commercial' => $this->commercial,
  387. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  388. 'date' => $this->date,
  389. 'type' => $this->type,
  390. 'amount' => $price,
  391. 'financial_movement' => $this->financial_movement,
  392. 'deleted' => $this->deleted
  393. ]);
  394. \App\Models\RecordRow::create([
  395. 'record_id' => $record->id,
  396. 'causal_id' => $this->corrispettivo_causal_id,
  397. 'note' => '',
  398. 'amount' => $price,
  399. 'vat_id' => null,
  400. 'commercial' => $this->commercial,
  401. 'when' => json_encode([])
  402. ]);
  403. }
  404. }
  405. }
  406. $this->resetFields();
  407. $this->add = false;
  408. $this->isDuplicate = false;
  409. $this->emit('setEdit', false);
  410. }
  411. public function store($generate)
  412. {
  413. $this->emit('refresh');
  414. $rules = [
  415. 'payment_method_id' => 'required',
  416. 'rows.*.causal_id' => 'required',
  417. 'rows.*.amount' => 'required'
  418. ];
  419. /*$f = false;
  420. foreach($this->rows as $row)
  421. {
  422. if ($row["commercial"]) $f = true;
  423. }
  424. if ($f)
  425. $rules["member_id"] = 'required';*/
  426. if(!$this->commercial)
  427. $rules["member_id"] = 'required';
  428. //dd($this->getErrorBag());
  429. /*$validator = Validator::make($request->all(), $rules);
  430. if ($validator->fails())
  431. {
  432. $this->emit('goToAnchor');
  433. }*/
  434. //if (!$this->validate($rules))
  435. //$this->emit('goToAnchor');
  436. $this->validate($rules);
  437. //dd("£ASDSDFS");
  438. try {
  439. $record = \App\Models\Record::create([
  440. 'member_id' => $this->member_id,
  441. 'supplier_id' => $this->supplier_id,
  442. 'payment_method_id' => $this->payment_method_id,
  443. 'commercial' => $this->commercial,
  444. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  445. 'date' => $this->date,
  446. 'type' => $this->type,
  447. 'financial_movement' => $this->financial_movement,
  448. 'deleted' => $this->deleted
  449. ]);
  450. $this->dataId = $record->id;
  451. $no_receipt_causal = false;
  452. // Inserisco le righe
  453. $tot = 0;
  454. $vat = 0;
  455. foreach($this->rows as $row)
  456. {
  457. foreach($row["when"] as $x => $y)
  458. {
  459. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  460. }
  461. \App\Models\RecordRow::create([
  462. 'record_id' => $this->dataId,
  463. 'causal_id' => $row["causal_id"],
  464. 'note' => $row["note"],
  465. 'amount' => $this->currencyToDouble($row["amount"]),
  466. 'vat_id' => $row["vat_id"],
  467. 'commercial' => $this->commercial,
  468. 'when' => json_encode($row["when"])
  469. ]);
  470. $tot += $this->currencyToDouble($row["amount"]);
  471. $vat += getVatValue($this->currencyToDouble($row["amount"]), $row["vat_id"]);
  472. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  473. if ($cau->no_receipt)
  474. $no_receipt_causal = true;
  475. // Se la causale ricarica a borsellino, se il totale supera y euro, inserisco x euro gratis
  476. if ($cau->money)
  477. {
  478. if ($this->currencyToDouble($row["amount"]) >= env('MIN_MONEY', 100))
  479. {
  480. $money = new \App\Models\Money();
  481. $money->member_id = $this->member_id;
  482. $money->record_id = $this->dataId;
  483. $money->amount = env('EXTRA_MONEY', 10);
  484. $money->date = date("Y-m-d");
  485. $money->note = env('EXTRA_MONEY', 10) . ' in più per aver caricato ' . $this->currencyToDouble($row["amount"]);
  486. $money->save();
  487. }
  488. }
  489. }
  490. $record->amount = $tot;
  491. $record->save();
  492. // se sto pagando un corso, aggiorno lo status dei mesi
  493. if ($this->courseId > 0)
  494. {
  495. $record->months = json_encode($this->months);
  496. $record->member_course_id = $this->courseId;
  497. $record->save();
  498. $c = \App\Models\MemberCourse::findOrFail($this->courseId);
  499. $xxx = json_decode($c->months);
  500. foreach($xxx as $idx => $mm)
  501. {
  502. if (in_array($mm->m, $this->months))
  503. {
  504. $xxx[$idx]->status = 1;
  505. }
  506. }
  507. $c->months = json_encode($xxx);
  508. if ($this->createSubscription == 1)
  509. $c->subscribed = true;
  510. $c->save();
  511. }
  512. if (!$this->financial_movement)
  513. {
  514. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  515. if (!$payment_method->money)
  516. {
  517. if ($generate && !$no_receipt_causal)
  518. $this->createReceipt();
  519. }
  520. }
  521. session()->flash('success','Movimento creato');
  522. $this->resetFields();
  523. $this->add = false;
  524. $this->isDuplicate = false;
  525. $this->emit('setEdit', false);
  526. } catch (\Exception $ex) {
  527. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  528. }
  529. }
  530. public function duplicate($id){
  531. $record = \App\Models\Record::findOrFail($id);
  532. $newRecord = $record->replicate();
  533. $newRecord->save();
  534. $rows = \App\Models\RecordRow::where('record_id', $id)->get();
  535. foreach($rows as $r)
  536. {
  537. $newRow = $r->replicate();
  538. $newRow->record_id = $newRecord->id;
  539. $newRow->save();
  540. }
  541. $this->edit($newRecord->id);
  542. $this->isDuplicate = true;
  543. }
  544. public function edit($id){
  545. $this->emit('setEdit', true);
  546. //if ($this->hasFilter)
  547. $this->emit('hide-search');
  548. $this->emit('load-select');
  549. try {
  550. $record = \App\Models\Record::findOrFail($id);
  551. if( !$record) {
  552. session()->flash('error','Movimento non trovato');
  553. } else {
  554. $this->member_id = $record->member_id;
  555. $this->supplier_id = $record->supplier_id;
  556. $this->payment_method_id = $record->payment_method_id;
  557. $this->amount = $record->amount;
  558. $this->commercial = $record->commercial;
  559. $this->corrispettivo_fiscale = $record->corrispettivo_fiscale;
  560. $this->date = date("Y-m-d", strtotime($record->date));
  561. $this->type = $record->type;
  562. $this->deleted = $record->deleted;
  563. $this->financial_movement = $record->financial_movement;
  564. $this->dataId = $record->id;
  565. $this->update = true;
  566. $this->add = false;
  567. $this->rows = \App\Models\RecordRow::where('record_id', $this->dataId)->select('causal_id', 'note', 'commercial', 'when', 'amount', 'vat_id')->get()->toArray();
  568. foreach($this->rows as $i => $r)
  569. {
  570. $this->rows[$i]['amount'] = formatPrice($this->rows[$i]['amount']);
  571. $this->rows[$i]['vat_id'] = $this->rows[$i]['vat_id'];
  572. $this->rows[$i]['when'] = json_decode($this->rows[$i]['when']);
  573. }
  574. $exist = \App\Models\Receipt::where('record_id', $id)->orderBy('id', 'DESC')->first();
  575. if ($exist != null)
  576. {
  577. $this->currentReceip = $exist;
  578. $this->parent = $this->currentReceip->parent;
  579. }
  580. }
  581. } catch (\Exception $ex) {
  582. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  583. }
  584. }
  585. public function update($generate = false)
  586. {
  587. $this->emit('refresh');
  588. $rules = [
  589. 'payment_method_id' => 'required',
  590. 'rows.*.causal_id' => 'required',
  591. 'rows.*.amount' => 'required'
  592. ];
  593. if(!$this->commercial)
  594. $rules["member_id"] = 'required';
  595. $this->validate($rules);
  596. try {
  597. \App\Models\Record::whereId($this->dataId)->update([
  598. 'member_id' => $this->member_id,
  599. 'supplier_id' => $this->supplier_id,
  600. 'payment_method_id' => $this->payment_method_id,
  601. 'commercial' => $this->commercial,
  602. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  603. 'date' => date("Y-m-d", strtotime($this->date)),
  604. 'type' => $this->type,
  605. 'financial_movement' => $this->financial_movement,
  606. 'deleted' => $this->deleted,
  607. ]);
  608. $no_receipt_causal = false;
  609. $tot = 0;
  610. $vat = 0;
  611. // Elimino le righe
  612. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  613. // Inserisco le righe
  614. foreach($this->rows as $row)
  615. {
  616. foreach($row["when"] as $x => $y)
  617. {
  618. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  619. }
  620. \App\Models\RecordRow::create([
  621. 'record_id' => $this->dataId,
  622. 'causal_id' => $row["causal_id"],
  623. 'note' => $row["note"],
  624. 'vat_id' => $row["vat_id"],
  625. 'amount' => $this->currencyToDouble($row["amount"]),
  626. 'commercial' => $this->commercial,
  627. 'when' => json_encode($row["when"])
  628. ]);
  629. $tot += $this->currencyToDouble($row["amount"]);
  630. $vat += getVatValue($this->currencyToDouble($row["amount"]), $row["vat_id"]);
  631. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  632. if ($cau->no_receipt)
  633. $no_receipt_causal = true;
  634. }
  635. $rec = \App\Models\Record::findOrFail($this->dataId);
  636. $rec->amount = $tot;
  637. $rec->save();
  638. if (!$this->financial_movement)
  639. {
  640. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  641. if (!$payment_method->money)
  642. {
  643. if ($generate && !$no_receipt_causal)
  644. $this->createReceipt();
  645. }
  646. }
  647. session()->flash('success','Movimento aggiornato');
  648. $this->resetFields();
  649. $this->update = false;
  650. $this->isDuplicate = false;
  651. $this->emit('setEdit', false);
  652. } catch (\Exception $ex) {
  653. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  654. }
  655. }
  656. public function cancel()
  657. {
  658. // Se arrivo da duplica elimino
  659. if ($this->isDuplicate)
  660. {
  661. try{
  662. \App\Models\Record::find($this->dataId)->delete();
  663. session()->flash('success',"Movimento eliminato");
  664. }catch(\Exception $e){
  665. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  666. }
  667. }
  668. $this->isDuplicate = false;
  669. $this->add = false;
  670. $this->update = false;
  671. $this->resetFields();
  672. $this->emit('setEdit', false);
  673. }
  674. public function delete($id)
  675. {
  676. try{
  677. $r = \App\Models\Record::find($id);
  678. // Annullo la ricevuta
  679. $receipt = \App\Models\Receipt::where('record_id', $r->id)->first();
  680. if($receipt)
  681. {
  682. $receipt->status = 99;
  683. sendReceiptDeleteEmail($receipt);
  684. $receipt->save();
  685. }
  686. if ($r->member_course_id > 0)
  687. {
  688. $months = json_decode($r->months);
  689. $c = \App\Models\MemberCourse::findOrFail($r->member_course_id);
  690. $xxx = json_decode($c->months);
  691. foreach($xxx as $idx => $mm)
  692. {
  693. if (in_array($mm->m, $months))
  694. {
  695. $xxx[$idx]->status = "";
  696. }
  697. }
  698. $c->months = json_encode($xxx);
  699. $c->save();
  700. }
  701. $r->deleted = true;
  702. $r->save();
  703. session()->flash('success','Movimento aggiornato');
  704. $this->resetFields();
  705. $this->update = false;
  706. $this->isDuplicate = false;
  707. $this->emit('setEdit', false);
  708. $this->emit('reload');
  709. //$this->emit('load-data-table');
  710. }catch(\Exception $ex){
  711. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  712. }
  713. }
  714. public function multipleDelete()
  715. {
  716. try{
  717. foreach($this->multipleIds as $id)
  718. {
  719. \App\Models\Record::find($id)->delete();
  720. }
  721. }catch(\Exception $e){
  722. session()->flash('error','Errore (' . $ex->getMessage() . ')');
  723. }
  724. $this->multipleAction = '';
  725. }
  726. public function createMember()
  727. {
  728. $this->newMemberFiscalCodeExist = false;
  729. $this->validate([
  730. // 'newMemberFiscalCode'=>'required|max:16',
  731. 'newMemberFirstName'=>'required',
  732. 'newMemberLastName'=>'required',
  733. 'newMemberEmail'=>'required',
  734. ]);
  735. // Check fiscal code exist
  736. $exist = false;
  737. if ($this->newMemberFiscalCode != '')
  738. {
  739. $check = \App\Models\Member::where('fiscal_code', $this->newMemberFiscalCode)->get();
  740. $exist = $check->count() > 0;
  741. }
  742. if (!$exist)
  743. {
  744. $member = \App\Models\Member::create([
  745. 'first_name' => strtoupper($this->newMemberFirstName),
  746. 'last_name' => strtoupper($this->newMemberLastName),
  747. 'email' => strtoupper($this->newMemberEmail),
  748. 'to_complete' => $this->newMemberToComplete,
  749. 'fiscal_code' => $this->newMemberFiscalCode,
  750. 'status' => true
  751. ]);
  752. $this->member_id = $member->id;
  753. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->get();
  754. // $this->emit('reloadMembers');
  755. $this->emit('refresh');
  756. $this->newMemberFirstName = '';
  757. $this->newMemberLastName = '';
  758. $this->newMemberEmail = '';
  759. $this->newMemberToComplete = false;
  760. $this->newMemberFiscalCode = '';
  761. $this->emit('saved');
  762. //$this->validate();
  763. $this->selectId++;
  764. }
  765. else
  766. {
  767. $this->newMemberFiscalCodeExist = true;
  768. }
  769. }
  770. public function createReceipt()
  771. {
  772. // Ulteriore controllo commerciale/non commerciale
  773. if (!$this->commercial)
  774. {
  775. $create = false;
  776. $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->orderBy('id', 'DESC')->first();
  777. if ($receipt != null)
  778. {
  779. // Controllo lo stato, se 99 ne genero una nuova
  780. if ($receipt->status == 99)
  781. {
  782. $create = true;
  783. }
  784. }
  785. else
  786. {
  787. $create = true;
  788. }
  789. if ($create)
  790. {
  791. $number = 1;
  792. $exist = \App\Models\Receipt::where('year', date("Y"))->orderBy('number', 'DESC')->first();
  793. if ($exist != null)
  794. $number = $exist->number + 1;
  795. $receipt = \App\Models\Receipt::create([
  796. 'record_id' => $this->dataId,
  797. 'member_id' => $this->member_id,
  798. 'supplier_id' => $this->supplier_id,
  799. 'payment_method_id' => $this->payment_method_id,
  800. 'number' => $number,
  801. 'date' => $this->date,
  802. 'year' => date("Y"),
  803. 'type' => $this->type,
  804. 'parent' => $this->parent,
  805. 'status' => 1,
  806. ]);
  807. foreach($this->rows as $row)
  808. {
  809. \App\Models\ReceiptRow::create([
  810. 'receip_id' => $receipt->id,
  811. 'causal_id' => $row["causal_id"],
  812. 'note' => $row["note"],
  813. 'vat_id' => $row["vat_id"],
  814. 'amount' => $this->currencyToDouble($row["amount"]),
  815. 'commercial' => $row["commercial"],
  816. 'when' => json_encode($row["when"])
  817. ]);
  818. }
  819. $this->currentReceip = $receipt;
  820. sendReceiptEmail($receipt);
  821. /*
  822. // Invio mail
  823. $pdf = PDF::loadView('receipt', array('receipt' => $receipt));
  824. $pdfName = "ricevuta_" . $receipt->number . "_" . $receipt->year . ".pdf";
  825. Storage::put('public/pdf/' . $pdfName, $pdf->output());
  826. $email = \App\Models\Member::findOrFail($receipt->member_id)->email;
  827. if ($email != '')
  828. {
  829. Mail::to($email)->send(new \App\Mail\ReceipEmail([
  830. 'pdf' => 'public/pdf/' . $pdfName,
  831. 'number' => $receipt->number . "/" . $receipt->year
  832. ]));
  833. }
  834. */
  835. session()->flash('receipt',"Ricevuta " . $number . "/" . date("Y") . " creata correttamente");
  836. // Apro la ricevuta
  837. $this->emit('showReceipt', $this->currentReceip->id);
  838. }
  839. }
  840. }
  841. public function removeReceipt()
  842. {
  843. $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
  844. $receipt->status = 99;
  845. $receipt->save();
  846. sendReceiptDeleteEmail($receipt);
  847. $this->currentReceip = $receipt;
  848. }
  849. function currencyToDouble($val)
  850. {
  851. $x = str_replace("€", "", $val);
  852. $x = str_replace(".", "", $x);
  853. $x = str_replace(",", ".", $x);
  854. return floatval(trim($x));
  855. }
  856. public function addRow()
  857. {
  858. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  859. $this->emit('load-select');
  860. }
  861. public function delRow($idx)
  862. {
  863. unset($this->rows[$idx]);
  864. // $this->emit('load-select');
  865. }
  866. public function addPeriod($idx)
  867. {
  868. $x = sizeof($this->rows[$idx]['when']) - 1;
  869. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  870. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  871. }
  872. public function delPeriod($idx, $xxx)
  873. {
  874. array_splice($this->rows[$idx]['when'], $xxx, $xxx);
  875. //unset($this->rows[$idx]['when'][$xxx]);
  876. // $this->emit('load-select');
  877. }
  878. public function getTotal()
  879. {
  880. $total = 0.00;
  881. foreach($this->rows as $r)
  882. {
  883. if ($r["amount"] != null && $r["amount"] != "")
  884. {
  885. $total += $this->currencyToDouble($r["amount"]);
  886. if ($r["vat_id"] > 0)
  887. $total += getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  888. }
  889. }
  890. return formatPrice($total);
  891. // $this->emit('load-select');
  892. }
  893. public function getTotalCorrispettivo()
  894. {
  895. $total = 0.00;
  896. foreach($this->corrispettivo as $r)
  897. {
  898. $total += $this->currencyToDouble($r);
  899. }
  900. return formatPrice($total);
  901. // $this->emit('load-select');
  902. }
  903. public function getPrice()
  904. {
  905. $total = 0.00;
  906. foreach($this->rows as $r)
  907. {
  908. if ($r["amount"] != null && $r["amount"] != "")
  909. $total += $this->currencyToDouble($r["amount"]);
  910. }
  911. return formatPrice($total);
  912. // $this->emit('load-select');
  913. }
  914. public function getVat()
  915. {
  916. $total = 0.00;
  917. foreach($this->rows as $r)
  918. {
  919. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
  920. $total += getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  921. }
  922. return formatPrice($total);
  923. // $this->emit('load-select');
  924. }
  925. public function getVats()
  926. {
  927. $vats = array();
  928. foreach($this->rows as $r)
  929. {
  930. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
  931. {
  932. $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  933. $vatName = "";
  934. foreach($this->vats as $v)
  935. {
  936. if ($v->id == $r["vat_id"])
  937. $vatName = $v->name;
  938. }
  939. if (isset($vats[$vatName]))
  940. $vats[$vatName] += $vat;
  941. else
  942. $vats[$vatName] = $vat;
  943. }
  944. }
  945. return $vats;
  946. // $this->emit('load-select');
  947. }
  948. public function setCausal($id, $idx)
  949. {
  950. $this->rows[$idx]["causal_id"] = $id;
  951. }
  952. public function printReceipt()
  953. {
  954. //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
  955. $pdf = PDF::loadView('receipt', array('receipt' => $this->currentReceip));//->output();
  956. $pdfName = "Ricevuta_" . $this->currentReceip->member->last_name . "_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf";
  957. return $pdf->stream();
  958. /*return response()->streamDownload(
  959. fn () => print($pdf),
  960. "ricevuta_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf"
  961. );*/
  962. /*return response()->streamDownload(function () {
  963. echo $pdf->stream();
  964. }, 'test.pdf');*/
  965. }
  966. public function multiPeriod()
  967. {
  968. $this->multiP = true;
  969. }
  970. public function multiPeriodCreate($idx)
  971. {
  972. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  973. foreach ($period as $dt) {
  974. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  975. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  976. }
  977. $this->multiP = false;
  978. }
  979. public function multiPeriodCancel()
  980. {
  981. $this->multiP = false;
  982. }
  983. public function getMonth($m)
  984. {
  985. $ret = '';
  986. switch ($m) {
  987. case 1:
  988. $ret = 'Gennaio';
  989. break;
  990. case 2:
  991. $ret = 'Febbraio';
  992. break;
  993. case 3:
  994. $ret = 'Marzo';
  995. break;
  996. case 4:
  997. $ret = 'Aprile';
  998. break;
  999. case 5:
  1000. $ret = 'Maggio';
  1001. break;
  1002. case 6:
  1003. $ret = 'Giugno';
  1004. break;
  1005. case 7:
  1006. $ret = 'Luglio';
  1007. break;
  1008. case 8:
  1009. $ret = 'Agosto';
  1010. break;
  1011. case 9:
  1012. $ret = 'Settembre';
  1013. break;
  1014. case 10:
  1015. $ret = 'Ottobre';
  1016. break;
  1017. case 11:
  1018. $ret = 'Novembre';
  1019. break;
  1020. case 12:
  1021. $ret = 'Dicembre';
  1022. break;
  1023. default:
  1024. $ret = '';
  1025. break;
  1026. }
  1027. return $ret;
  1028. }
  1029. public function setYear($idx, $xxx)
  1030. {
  1031. $m = $this->rows[$idx]["when"][$xxx]["month"];
  1032. $this->rows[$idx]["when"][$xxx]["year"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
  1033. }
  1034. }