RecordIN.php 50 KB

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