RecordIN.php 41 KB

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