RecordIN.php 44 KB

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