RecordIN.php 41 KB

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