RecordIN.php 44 KB

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