RecordIN.php 51 KB

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