RecordIN.php 43 KB

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