RecordIN.php 42 KB

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