RecordIN.php 42 KB

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