RecordIN.php 59 KB

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