RecordIN.php 42 KB

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