RecordIN.php 61 KB

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