RecordIN.php 43 KB

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