RecordIN.php 45 KB

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