RecordIN.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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. $money = new \App\Models\Money();
  514. $money->member_id = $this->member_id;
  515. $money->record_id = $this->dataId;
  516. $money->amount = env('EXTRA_MONEY', 10);
  517. $money->date = date("Y-m-d");
  518. $money->note = env('EXTRA_MONEY', 10) . ' in più per aver caricato ' . $rowNet;
  519. $money->save();
  520. }
  521. }
  522. }
  523. Log::info("Final amount saved to record: " . $totalNet);
  524. if (!$this->financial_movement) {
  525. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  526. if (!$payment_method->money) {
  527. if ($generate && !$no_receipt_causal)
  528. $this->createReceipt();
  529. }
  530. }
  531. if ($this->rateId > 0) {
  532. $rate = \App\Models\Rate::findOrFail($this->rateId);
  533. $rate->status = 1;
  534. $rate->record_id = $record->id;
  535. $rate->save();
  536. }
  537. session()->flash('success', 'Movimento creato');
  538. $this->resetFields();
  539. $this->add = false;
  540. $this->isDuplicate = false;
  541. $this->emit('setEdit', false);
  542. } catch (\Exception $ex) {
  543. Log::error("Error in store method: " . $ex->getMessage());
  544. Log::error("Stack trace: " . $ex->getTraceAsString());
  545. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  546. }
  547. }
  548. public function duplicate($id)
  549. {
  550. $record = \App\Models\Record::findOrFail($id);
  551. $newRecord = $record->replicate();
  552. $newRecord->save();
  553. $rows = \App\Models\RecordRow::where('record_id', $id)->get();
  554. foreach ($rows as $r) {
  555. $newRow = $r->replicate();
  556. $newRow->record_id = $newRecord->id;
  557. $newRow->save();
  558. }
  559. $this->edit($newRecord->id);
  560. $this->isDuplicate = true;
  561. }
  562. public function edit($id)
  563. {
  564. if (!isset($_GET["from"]) && $this->fromPage == '')
  565. $this->fromPage = 'in';
  566. $this->emit('setEdit', true);
  567. //if ($this->hasFilter)
  568. $this->emit('hide-search');
  569. $this->emit('load-select');
  570. try {
  571. $record = \App\Models\Record::findOrFail($id);
  572. if (!$record) {
  573. session()->flash('error', 'Movimento non trovato');
  574. } else {
  575. $this->member_id = $record->member_id;
  576. $this->supplier_id = $record->supplier_id;
  577. $this->payment_method_id = $record->payment_method_id;
  578. $this->amount = $record->amount; // This is the net amount in DB
  579. $this->commercial = $record->commercial;
  580. $this->corrispettivo_fiscale = $record->corrispettivo_fiscale;
  581. $this->date = date("Y-m-d", strtotime($record->date));
  582. $this->type = $record->type;
  583. $this->deleted = $record->deleted;
  584. $this->financial_movement = $record->financial_movement;
  585. $this->dataId = $record->id;
  586. $this->update = true;
  587. $this->add = false;
  588. $rows = \App\Models\RecordRow::where('record_id', $this->dataId)
  589. ->select('causal_id', 'note', 'commercial', 'when', 'amount', 'prediscount_amount', 'sconto', 'vat_id')
  590. ->get();
  591. $this->rows = [];
  592. foreach ($rows as $i => $r) {
  593. $grossAmount = $r->prediscount_amount ?? ($r->amount + $r->sconto);
  594. $this->rows[] = [
  595. 'causal_id' => $r->causal_id,
  596. 'note' => $r->note,
  597. 'commercial' => $r->commercial,
  598. 'when' => json_decode($r->when),
  599. 'amount' => formatPrice($grossAmount),
  600. 'sconto' => formatPrice($r->sconto),
  601. 'vat_id' => $r->vat_id
  602. ];
  603. }
  604. $exist = \App\Models\Receipt::where('record_id', $id)->orderBy('id', 'DESC')->first();
  605. if ($exist != null) {
  606. $this->currentReceip = $exist;
  607. $this->parent = $this->currentReceip->parent;
  608. }
  609. }
  610. } catch (\Exception $ex) {
  611. Log::error("Error in edit method: " . $ex->getMessage());
  612. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  613. }
  614. }
  615. public function update($generate = false)
  616. {
  617. Log::info("Starting update method");
  618. $this->emit('refresh');
  619. $rules = [
  620. 'payment_method_id' => 'required',
  621. 'rows.*.causal_id' => 'required',
  622. 'rows.*.amount' => 'required'
  623. ];
  624. if (!$this->commercial)
  625. $rules["member_id"] = 'required';
  626. $this->validate($rules);
  627. try {
  628. $totalGross = 0;
  629. $totalSconto = 0;
  630. $totalNet = 0;
  631. foreach ($this->rows as $row) {
  632. $rowAmount = $this->currencyToDouble($row["amount"]);
  633. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  634. $rowNet = max(0, $rowAmount - $rowSconto);
  635. $totalGross += $rowAmount;
  636. $totalSconto += $rowSconto;
  637. $totalNet += $rowNet;
  638. }
  639. Log::info("Total gross: " . $totalGross . ", Total sconto: " . $totalSconto . ", Total net: " . $totalNet);
  640. \App\Models\Record::whereId($this->dataId)->update([
  641. 'member_id' => $this->member_id,
  642. 'supplier_id' => $this->supplier_id,
  643. 'payment_method_id' => $this->payment_method_id,
  644. 'commercial' => $this->commercial,
  645. 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
  646. 'date' => date("Y-m-d", strtotime($this->date)),
  647. 'type' => $this->type,
  648. 'financial_movement' => $this->financial_movement,
  649. 'deleted' => $this->deleted,
  650. 'amount' => $totalNet,
  651. 'prediscount_amount' => $totalGross,
  652. ]);
  653. $no_receipt_causal = false;
  654. $vat = 0;
  655. \App\Models\RecordRow::where('record_id', $this->dataId)->delete();
  656. foreach ($this->rows as $row) {
  657. foreach ($row["when"] as $x => $y) {
  658. $row["when"][$x]['period'] = $row["when"][$x]['month'] . "-" . $row["when"][$x]['year'];
  659. }
  660. $rowAmount = $this->currencyToDouble($row["amount"]);
  661. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  662. $rowNet = max(0, $rowAmount - $rowSconto);
  663. Log::info("Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  664. \App\Models\RecordRow::create([
  665. 'record_id' => $this->dataId,
  666. 'causal_id' => $row["causal_id"],
  667. 'note' => $row["note"],
  668. 'vat_id' => $row["vat_id"],
  669. 'amount' => $rowNet,
  670. 'prediscount_amount' => $rowAmount,
  671. 'sconto' => $rowSconto,
  672. 'commercial' => $this->commercial,
  673. 'when' => json_encode($row["when"])
  674. ]);
  675. $vat += getVatValue($rowNet, $row["vat_id"]);
  676. $cau = \App\Models\Causal::findOrFail($row["causal_id"]);
  677. if ($cau->no_receipt)
  678. $no_receipt_causal = true;
  679. }
  680. Log::info("Final amount saved to record: " . $totalNet);
  681. if (!$this->financial_movement) {
  682. $payment_method = \App\Models\PaymentMethod::findOrFail($this->payment_method_id);
  683. if (!$payment_method->money) {
  684. if ($generate && !$no_receipt_causal)
  685. $this->createReceipt();
  686. }
  687. }
  688. session()->flash('success', 'Movimento aggiornato');
  689. $this->resetFields();
  690. $this->update = false;
  691. $this->isDuplicate = false;
  692. $this->emit('setEdit', false);
  693. } catch (\Exception $ex) {
  694. Log::error("Error in update method: " . $ex->getMessage());
  695. Log::error("Stack trace: " . $ex->getTraceAsString());
  696. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  697. }
  698. }
  699. public function rigenerate()
  700. {
  701. $this->emit('refresh');
  702. try {
  703. $record = \App\Models\Record::findOrFail($this->dataId);
  704. $newRecord = $record->replicate();
  705. $newRecord->date = date("Y-m-d");
  706. $newRecord->save();
  707. $recordRows = \App\Models\RecordRow::where('record_id', $this->dataId)->get();
  708. // Inserisco le righe
  709. foreach ($recordRows as $row) {
  710. $newRow = $row->replicate();
  711. $newRow->record_id = $newRecord->id;
  712. $newRow->save();
  713. }
  714. $this->dataId = $newRecord->id;
  715. $this->createReceipt();
  716. session()->flash('success', 'Movimento aggiornato');
  717. $this->resetFields();
  718. $this->update = false;
  719. $this->isDuplicate = false;
  720. $this->emit('setEdit', false);
  721. } catch (\Exception $ex) {
  722. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  723. }
  724. }
  725. public function cancel()
  726. {
  727. // Se arrivo da duplica elimino
  728. if ($this->isDuplicate) {
  729. try {
  730. \App\Models\Record::find($this->dataId)->delete();
  731. session()->flash('success', "Movimento eliminato");
  732. } catch (\Exception $e) {
  733. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  734. }
  735. }
  736. $this->isDuplicate = false;
  737. $this->add = false;
  738. $this->update = false;
  739. $this->resetFields();
  740. $this->emit('setEdit', false);
  741. return redirect()->to('/in');
  742. }
  743. public function delete($id)
  744. {
  745. try {
  746. $r = \App\Models\Record::find($id);
  747. // Annullo la ricevuta
  748. $receipt = \App\Models\Receipt::where('record_id', $r->id)->first();
  749. if ($receipt) {
  750. $receipt->status = 99;
  751. sendReceiptDeleteEmail($receipt);
  752. $receipt->save();
  753. }
  754. if ($r->member_course_id > 0) {
  755. $months = json_decode($r->months);
  756. $c = \App\Models\MemberCourse::findOrFail($r->member_course_id);
  757. $xxx = json_decode($c->months);
  758. foreach ($xxx as $idx => $mm) {
  759. if (in_array($mm->m, $months)) {
  760. $xxx[$idx]->status = "";
  761. }
  762. }
  763. $c->months = json_encode($xxx);
  764. $c->save();
  765. }
  766. $r->deleted = true;
  767. $r->save();
  768. session()->flash('success', 'Movimento aggiornato');
  769. $this->resetFields();
  770. $this->update = false;
  771. $this->isDuplicate = false;
  772. $this->emit('setEdit', false);
  773. $this->emit('reload');
  774. //$this->emit('load-data-table');
  775. } catch (\Exception $ex) {
  776. session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
  777. }
  778. }
  779. public function multipleDelete()
  780. {
  781. try {
  782. foreach ($this->multipleIds as $id) {
  783. \App\Models\Record::find($id)->delete();
  784. }
  785. } catch (\Exception $e) {
  786. session()->flash('error', 'Errore (' . $e->getMessage() . ')');
  787. }
  788. $this->multipleAction = '';
  789. }
  790. public function createMember()
  791. {
  792. $this->newMemberFiscalCodeExist = false;
  793. $this->validate([
  794. // 'newMemberFiscalCode'=>'required|max:16',
  795. 'newMemberFirstName' => 'required',
  796. 'newMemberLastName' => 'required',
  797. //'newMemberEmail'=>'required',
  798. ]);
  799. // Check fiscal code exist
  800. $exist = false;
  801. if ($this->newMemberFiscalCode != '') {
  802. $check = \App\Models\Member::where('fiscal_code', $this->newMemberFiscalCode)->get();
  803. $exist = $check->count() > 0;
  804. }
  805. if (!$exist) {
  806. $member = \App\Models\Member::create([
  807. 'first_name' => strtoupper($this->newMemberFirstName),
  808. 'last_name' => strtoupper($this->newMemberLastName),
  809. 'email' => strtoupper($this->newMemberEmail),
  810. 'to_complete' => $this->newMemberToComplete,
  811. 'fiscal_code' => $this->newMemberFiscalCode,
  812. 'status' => true
  813. ]);
  814. $this->member_id = $member->id;
  815. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->get();
  816. // $this->emit('reloadMembers');
  817. $this->emit('refresh');
  818. $this->newMemberFirstName = '';
  819. $this->newMemberLastName = '';
  820. $this->newMemberEmail = '';
  821. $this->newMemberToComplete = false;
  822. $this->newMemberFiscalCode = '';
  823. $this->emit('saved');
  824. //$this->validate();
  825. $this->selectId++;
  826. } else {
  827. $this->newMemberFiscalCodeExist = true;
  828. }
  829. }
  830. public function createReceipt()
  831. {
  832. // Ulteriore controllo commerciale/non commerciale
  833. if (!$this->commercial) {
  834. $create = false;
  835. $receipt = \App\Models\Receipt::where('record_id', $this->dataId)->orderBy('id', 'DESC')->first();
  836. if ($receipt != null) {
  837. // Controllo lo stato, se 99 ne genero una nuova
  838. if ($receipt->status == 99) {
  839. $create = true;
  840. }
  841. } else {
  842. $create = true;
  843. }
  844. if ($create) {
  845. $number = 1;
  846. $exist = \App\Models\Receipt::where('year', date("Y"))->orderBy('number', 'DESC')->first();
  847. if ($exist != null)
  848. $number = $exist->number + 1;
  849. // Calculate totals for the receipt
  850. $totalGross = 0;
  851. $totalNet = 0;
  852. foreach ($this->rows as $row) {
  853. $rowAmount = $this->currencyToDouble($row["amount"]);
  854. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  855. $rowNet = max(0, $rowAmount - $rowSconto);
  856. $totalGross += $rowAmount;
  857. $totalNet += $rowNet;
  858. }
  859. $receipt = \App\Models\Receipt::create([
  860. 'record_id' => $this->dataId,
  861. 'member_id' => $this->member_id,
  862. 'supplier_id' => $this->supplier_id,
  863. 'payment_method_id' => $this->payment_method_id,
  864. 'number' => $number,
  865. 'date' => $this->date,
  866. 'year' => date("Y"),
  867. 'type' => $this->type,
  868. 'parent' => $this->parent,
  869. 'status' => 1,
  870. ]);
  871. foreach ($this->rows as $row) {
  872. $rowAmount = $this->currencyToDouble($row["amount"]);
  873. $rowSconto = isset($row['sconto']) ? $this->currencyToDouble($row['sconto']) : 0;
  874. $rowNet = max(0, $rowAmount - $rowSconto);
  875. Log::info("Receipt Row - Gross: " . $rowAmount . ", Sconto: " . $rowSconto . ", Net: " . $rowNet);
  876. \App\Models\ReceiptRow::create([
  877. 'receip_id' => $receipt->id,
  878. 'causal_id' => $row["causal_id"],
  879. 'note' => $row["note"],
  880. 'vat_id' => $row["vat_id"],
  881. 'amount' => $rowNet,
  882. 'prediscount_amount' => $rowAmount,
  883. 'sconto' => $rowSconto,
  884. 'commercial' => $row["commercial"],
  885. 'when' => json_encode($row["when"])
  886. ]);
  887. }
  888. $this->currentReceip = $receipt;
  889. sendReceiptEmail($receipt);
  890. session()->flash('receipt', "Ricevuta " . $number . "/" . date("Y") . " creata correttamente");
  891. $this->emit('showReceipt', $this->currentReceip->id);
  892. }
  893. }
  894. }
  895. public function removeReceipt()
  896. {
  897. $receipt = \App\Models\Receipt::findOrFail($this->currentReceip->id);
  898. $receipt->status = 99;
  899. $receipt->save();
  900. sendReceiptDeleteEmail($receipt);
  901. $this->currentReceip = $receipt;
  902. }
  903. function currencyToDouble($val)
  904. {
  905. $x = str_replace("€", "", $val);
  906. $x = str_replace(".", "", $x);
  907. $x = str_replace(",", ".", $x);
  908. return floatval(trim($x));
  909. }
  910. public function addRow()
  911. {
  912. $this->rows[] = array('causal_id' => null, 'when' => array(array('month' => date("n"), 'year' => date("Y"), 'period' => '')), 'amount' => null, 'vat_id' => null, 'note' => '', 'commercial' => 0);
  913. $this->emit('load-select');
  914. }
  915. public function delRow($idx)
  916. {
  917. unset($this->rows[$idx]);
  918. // $this->emit('load-select');
  919. }
  920. public function addPeriod($idx)
  921. {
  922. $x = sizeof($this->rows[$idx]['when']) - 1;
  923. $newDate = \Carbon\Carbon::create($this->rows[$idx]['when'][$x]["year"] . "-" . $this->rows[$idx]['when'][$x]["month"] . '-01')->addMonth();
  924. $this->rows[$idx]['when'][] = array('month' => $newDate->format("n"), 'year' => $newDate->format("Y"), 'period' => '');
  925. }
  926. public function delPeriod($idx, $xxx)
  927. {
  928. array_splice($this->rows[$idx]['when'], $xxx, $xxx);
  929. //unset($this->rows[$idx]['when'][$xxx]);
  930. // $this->emit('load-select');
  931. }
  932. public function getTotal()
  933. {
  934. $total = 0.00;
  935. foreach ($this->rows as $r) {
  936. if ($r["amount"] != null && $r["amount"] != "") {
  937. $rowAmount = $this->currencyToDouble($r["amount"]);
  938. $rowSconto = isset($r['sconto']) ? $this->currencyToDouble($r['sconto']) : 0;
  939. $netAmount = max(0, $rowAmount - $rowSconto);
  940. $total += $netAmount;
  941. if ($r["vat_id"] > 0)
  942. $total += getVatValue($netAmount, $r["vat_id"]);
  943. }
  944. }
  945. return formatPrice($total);
  946. }
  947. public function getTotalCorrispettivo()
  948. {
  949. $total = 0.00;
  950. foreach ($this->corrispettivo as $r) {
  951. $total += $this->currencyToDouble($r);
  952. }
  953. return formatPrice($total);
  954. // $this->emit('load-select');
  955. }
  956. public function getPrice()
  957. {
  958. $total = 0.00;
  959. foreach ($this->rows as $r) {
  960. if ($r["amount"] != null && $r["amount"] != "")
  961. $total += $this->currencyToDouble($r["amount"]);
  962. }
  963. return formatPrice($total);
  964. // $this->emit('load-select');
  965. }
  966. public function getVat()
  967. {
  968. $total = 0.00;
  969. foreach ($this->rows as $r) {
  970. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0)
  971. $total += getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  972. }
  973. return formatPrice($total);
  974. // $this->emit('load-select');
  975. }
  976. public function getVats()
  977. {
  978. $vats = array();
  979. foreach ($this->rows as $r) {
  980. if ($r["amount"] != null && $r["amount"] != "" && $r["vat_id"] > 0) {
  981. $vat = getVatValue($this->currencyToDouble($r["amount"]), $r["vat_id"]);
  982. $vatName = "";
  983. foreach ($this->vats as $v) {
  984. if ($v->id == $r["vat_id"])
  985. $vatName = $v->name;
  986. }
  987. if (isset($vats[$vatName]))
  988. $vats[$vatName] += $vat;
  989. else
  990. $vats[$vatName] = $vat;
  991. }
  992. }
  993. return $vats;
  994. // $this->emit('load-select');
  995. }
  996. public function setCausal($id, $idx)
  997. {
  998. $this->rows[$idx]["causal_id"] = $id;
  999. }
  1000. public function printReceipt()
  1001. {
  1002. //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
  1003. $pdf = PDF::loadView('receipt', array('receipt' => $this->currentReceip)); //->output();
  1004. $pdfName = "Ricevuta_" . $this->currentReceip->member->last_name . "_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf";
  1005. return $pdf->stream();
  1006. /*return response()->streamDownload(
  1007. fn () => print($pdf),
  1008. "ricevuta_" . $this->currentReceip->number . "_" . $this->currentReceip->year . ".pdf"
  1009. );*/
  1010. /*return response()->streamDownload(function () {
  1011. echo $pdf->stream();
  1012. }, 'test.pdf');*/
  1013. }
  1014. public function multiPeriod()
  1015. {
  1016. $this->multiP = true;
  1017. }
  1018. public function multiPeriodCreate($idx)
  1019. {
  1020. $period = \Carbon\CarbonPeriod::create($this->multiYearFrom . '-' . $this->multiMonthFrom . '-01', '1 month', $this->multiYearTo . '-' . $this->multiMonthTo . '-01');
  1021. $this->rows[$idx]['when'] = [];
  1022. foreach ($period as $dt) {
  1023. if (!in_array(array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => ''), $this->rows[$idx]['when']))
  1024. $this->rows[$idx]['when'][] = array('month' => $dt->format("n"), 'year' => $dt->format("Y"), 'period' => '');
  1025. }
  1026. $this->multiP = false;
  1027. }
  1028. public function multiPeriodCancel()
  1029. {
  1030. $this->multiP = false;
  1031. }
  1032. public function getMonth($m)
  1033. {
  1034. $ret = '';
  1035. switch ($m) {
  1036. case 1:
  1037. $ret = 'Gennaio';
  1038. break;
  1039. case 2:
  1040. $ret = 'Febbraio';
  1041. break;
  1042. case 3:
  1043. $ret = 'Marzo';
  1044. break;
  1045. case 4:
  1046. $ret = 'Aprile';
  1047. break;
  1048. case 5:
  1049. $ret = 'Maggio';
  1050. break;
  1051. case 6:
  1052. $ret = 'Giugno';
  1053. break;
  1054. case 7:
  1055. $ret = 'Luglio';
  1056. break;
  1057. case 8:
  1058. $ret = 'Agosto';
  1059. break;
  1060. case 9:
  1061. $ret = 'Settembre';
  1062. break;
  1063. case 10:
  1064. $ret = 'Ottobre';
  1065. break;
  1066. case 11:
  1067. $ret = 'Novembre';
  1068. break;
  1069. case 12:
  1070. $ret = 'Dicembre';
  1071. break;
  1072. default:
  1073. $ret = '';
  1074. break;
  1075. }
  1076. return $ret;
  1077. }
  1078. public function setYear($idx, $xxx)
  1079. {
  1080. $m = $this->rows[$idx]["when"][$xxx]["month"];
  1081. $this->rows[$idx]["when"][$xxx]["year"] = $m < env('FISCAL_YEAR_MONTH_FROM', 1) ? (date("Y") + 1) : date("Y");
  1082. }
  1083. }