RecordIN.php 40 KB

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