RecordIN.php 40 KB

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