RecordIN.php 45 KB

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