RecordIN.php 41 KB

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