RecordIN.php 39 KB

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