RecordIN.php 63 KB

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