RecordIN.php 38 KB

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