RecordIN.php 42 KB

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