RecordIN.php 41 KB

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