RecordIN.php 43 KB

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