RecordIN.php.bak 50 KB

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