RecordIN.php 41 KB

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