RecordIN.php 61 KB

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