RecordIN.php 41 KB

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