RecordIN.php 40 KB

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