RecordIN.php 41 KB

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