RecordIN.php 59 KB

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