RecordIN.php 36 KB

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