RecordIN.php 42 KB

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