Record.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use DateInterval;
  5. use DatePeriod;
  6. use DateTime;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  9. use Illuminate\Support\Facades\Storage;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Mail;
  12. use App\Mail\ExportNotification;
  13. use App\Jobs\ExportPrimaNota;
  14. class Record extends Component
  15. {
  16. public $records, $dataId, $totals;
  17. public $in;
  18. public $out;
  19. public $payments = [];
  20. public $fromDate;
  21. public $toDate;
  22. public $appliedFromDate;
  23. public $appliedToDate;
  24. public $exportFromDate;
  25. public $exportToDate;
  26. public $isExporting = false;
  27. public $selectedPeriod = 'OGGI';
  28. public $filterCausals = null;
  29. public $filterMember = null;
  30. public $isFiltering = false;
  31. public array $recordDatas = [];
  32. public array $labels = [];
  33. public array $causals = [];
  34. public $members = array();
  35. public $sendViaEmail = false;
  36. public $exportEmailAddress = '';
  37. public $exportEmailSubject = 'Prima Nota - Export';
  38. protected $rules = [
  39. 'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
  40. 'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
  41. ];
  42. protected $messages = [
  43. 'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
  44. 'exportEmailAddress.email' => 'Inserisci un indirizzo email valido.',
  45. 'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
  46. 'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
  47. ];
  48. public function hydrate()
  49. {
  50. $this->emit('load-select');
  51. }
  52. public function mount()
  53. {
  54. $this->fromDate = date("Y-m-d");
  55. $this->toDate = date("Y-m-d");
  56. $this->appliedFromDate = date("Y-m-d");
  57. $this->appliedToDate = date("Y-m-d");
  58. $this->exportFromDate = date("Y-m-d");
  59. $this->exportToDate = date("Y-m-d");
  60. $this->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
  61. $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
  62. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
  63. $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
  64. }
  65. private function generateExportData($fromDate, $toDate)
  66. {
  67. $exportRecords = array();
  68. $exportTotals = array();
  69. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  70. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  71. ->select(
  72. 'records.*',
  73. 'records_rows.id as row_id',
  74. 'records_rows.record_id',
  75. 'records_rows.causal_id',
  76. 'records_rows.amount',
  77. 'records_rows.note',
  78. 'records_rows.when',
  79. 'records_rows.vat_id',
  80. 'records_rows.imponibile',
  81. 'records_rows.aliquota_iva',
  82. 'records_rows.imposta',
  83. 'records_rows.divisa',
  84. 'records_rows.numero_linea',
  85. 'records_rows.prezzo_unitario',
  86. 'records_rows.quantita',
  87. 'records_rows.created_at as row_created_at',
  88. 'records_rows.updated_at as row_updated_at'
  89. )
  90. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  91. ->whereBetween('date', [$fromDate, $toDate])
  92. ->where(function ($query) {
  93. $query->where('type', 'OUT')
  94. ->orWhere(function ($query) {
  95. $query->where('records.corrispettivo_fiscale', true)
  96. ->orWhere('records.commercial', false);
  97. });
  98. })
  99. ->where(function ($query) use ($exclude_from_records) {
  100. $query->where('type', 'OUT')
  101. ->orWhere(function ($subquery) use ($exclude_from_records) {
  102. $subquery->whereNotIn('member_id', $exclude_from_records);
  103. });
  104. });
  105. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  106. $causals = array();
  107. foreach ($this->filterCausals as $z) {
  108. $causals[] = $z;
  109. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  110. foreach ($childs as $c) {
  111. $causals[] = $c->id;
  112. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  113. foreach ($childsX as $cX) {
  114. $causals[] = $cX->id;
  115. }
  116. }
  117. }
  118. $datas->whereIn('causal_id', $causals);
  119. }
  120. if ($this->filterMember != null && $this->filterMember > 0) {
  121. $datas->where('member_id', $this->filterMember);
  122. }
  123. $datas = $datas->orderBy('date', 'ASC')
  124. ->orderBy('records.created_at', 'ASC')
  125. ->orderBy('records_rows.id', 'ASC')
  126. ->get();
  127. $groupedData = [];
  128. $causalsCount = [];
  129. foreach ($datas as $idx => $data) {
  130. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  131. $paymentCheck = $data->payment_method->money;
  132. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  133. if (!$data->deleted) {
  134. $amount = $data->amount;
  135. $amount += getVatValue($amount, $data->vat_id);
  136. } else {
  137. $amount = $data->amount;
  138. }
  139. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  140. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  141. $nominativo = '';
  142. if ($data->type == "IN") {
  143. if ($data->member) {
  144. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  145. }
  146. } else {
  147. if ($data->supplier) {
  148. $nominativo = $data->supplier->name;
  149. }
  150. }
  151. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  152. if (!isset($groupedData[$groupKey])) {
  153. $groupedData[$groupKey] = [
  154. 'date' => $data->date,
  155. 'type_label' => $typeLabel,
  156. 'payment_method' => $data->payment_method->name,
  157. 'transaction_type' => $data->type,
  158. 'nominativo' => $nominativo,
  159. 'amount' => 0,
  160. 'deleted' => false,
  161. 'causals' => [],
  162. 'notes' => []
  163. ];
  164. $causalsCount[$groupKey] = [];
  165. }
  166. $groupedData[$groupKey]['amount'] += $amount;
  167. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  168. if (!empty($data->note)) {
  169. $groupedData[$groupKey]['notes'][] = $data->note;
  170. }
  171. if ($data->deleted) {
  172. $groupedData[$groupKey]['deleted'] = true;
  173. }
  174. }
  175. }
  176. foreach ($groupedData as $groupKey => $group) {
  177. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  178. $causalDisplay = $group['type_label'];
  179. if (count($causalsInGroup) > 1) {
  180. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
  181. } else {
  182. $detailDisplay = $causalsInGroup[0];
  183. }
  184. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  185. if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  186. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  187. }
  188. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  189. if (!isset($exportTotals[$group['payment_method']])) {
  190. $exportTotals[$group['payment_method']]["IN"] = 0;
  191. $exportTotals[$group['payment_method']]["OUT"] = 0;
  192. }
  193. if (!$group['deleted'])
  194. $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  195. }
  196. return $exportRecords;
  197. }
  198. private function generateExportTotals($fromDate, $toDate)
  199. {
  200. $exportTotals = array();
  201. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  202. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  203. ->select(
  204. 'records.*',
  205. 'records_rows.id as row_id',
  206. 'records_rows.record_id',
  207. 'records_rows.causal_id',
  208. 'records_rows.amount',
  209. 'records_rows.note',
  210. 'records_rows.when',
  211. 'records_rows.vat_id',
  212. 'records_rows.imponibile',
  213. 'records_rows.aliquota_iva',
  214. 'records_rows.imposta'
  215. )
  216. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  217. ->whereBetween('date', [$fromDate, $toDate])
  218. ->where(function ($query) {
  219. $query->where('type', 'OUT')
  220. ->orWhere(function ($query) {
  221. $query->where('records.corrispettivo_fiscale', true)
  222. ->orWhere('records.commercial', false);
  223. });
  224. })
  225. ->where(function ($query) use ($exclude_from_records) {
  226. $query->where('type', 'OUT')
  227. ->orWhere(function ($subquery) use ($exclude_from_records) {
  228. $subquery->whereNotIn('member_id', $exclude_from_records);
  229. });
  230. });
  231. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  232. $causals = array();
  233. foreach ($this->filterCausals as $z) {
  234. $causals[] = $z;
  235. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  236. foreach ($childs as $c) {
  237. $causals[] = $c->id;
  238. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  239. foreach ($childsX as $cX) {
  240. $causals[] = $cX->id;
  241. }
  242. }
  243. }
  244. $datas->whereIn('causal_id', $causals);
  245. }
  246. if ($this->filterMember != null && $this->filterMember > 0) {
  247. $datas->where('member_id', $this->filterMember);
  248. }
  249. $datas = $datas->orderBy('date', 'ASC')
  250. ->orderBy('records.created_at', 'ASC')
  251. ->orderBy('records_rows.id', 'ASC')
  252. ->get();
  253. foreach ($datas as $data) {
  254. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  255. $paymentCheck = $data->payment_method->money;
  256. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  257. if (!$data->deleted) {
  258. $amount = $data->amount;
  259. $amount += getVatValue($amount, $data->vat_id);
  260. } else {
  261. $amount = $data->amount;
  262. }
  263. if (!isset($exportTotals[$data->payment_method->name])) {
  264. $exportTotals[$data->payment_method->name]["IN"] = 0;
  265. $exportTotals[$data->payment_method->name]["OUT"] = 0;
  266. }
  267. if (!$data->deleted)
  268. $exportTotals[$data->payment_method->name][$data->type] += $amount;
  269. }
  270. }
  271. return $exportTotals;
  272. }
  273. public function resetFilters()
  274. {
  275. $this->selectedPeriod = 'OGGI';
  276. $this->filterCausals = [];
  277. $this->filterMember = null;
  278. $today = date("Y-m-d");
  279. $this->fromDate = $today;
  280. $this->toDate = $today;
  281. $this->appliedFromDate = $today;
  282. $this->appliedToDate = $today;
  283. $this->emit('filters-reset');
  284. }
  285. public function applyFilters()
  286. {
  287. $this->isFiltering = true;
  288. $this->setPeriodDates();
  289. $this->appliedFromDate = $this->fromDate;
  290. $this->appliedToDate = $this->toDate;
  291. $this->render();
  292. $this->isFiltering = false;
  293. $this->emit('filters-applied');
  294. }
  295. private function setPeriodDates()
  296. {
  297. $today = now();
  298. switch ($this->selectedPeriod) {
  299. case 'OGGI':
  300. $this->fromDate = $today->format('Y-m-d');
  301. $this->toDate = $today->format('Y-m-d');
  302. break;
  303. case 'IERI':
  304. $yesterday = $today->copy()->subDay();
  305. $this->fromDate = $yesterday->format('Y-m-d');
  306. $this->toDate = $yesterday->format('Y-m-d');
  307. break;
  308. case 'MESE CORRENTE':
  309. $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
  310. $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
  311. break;
  312. case 'MESE PRECEDENTE':
  313. $lastMonth = $today->copy()->subMonth();
  314. $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
  315. $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
  316. break;
  317. case 'ULTIMO TRIMESTRE':
  318. $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
  319. $this->toDate = $today->format('Y-m-d');
  320. break;
  321. case 'ULTIMO QUADRIMESTRE':
  322. $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
  323. $this->toDate = $today->format('Y-m-d');
  324. break;
  325. }
  326. }
  327. public function getCausals($records, $indentation)
  328. {
  329. foreach ($records as $record) {
  330. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  331. if (count($record->childs))
  332. $this->getCausals($record->childs, $indentation + 1);
  333. }
  334. }
  335. public function getMonth($m)
  336. {
  337. $ret = '';
  338. switch ($m) {
  339. case 1:
  340. $ret = 'Gennaio';
  341. break;
  342. case 2:
  343. $ret = 'Febbraio';
  344. break;
  345. case 3:
  346. $ret = 'Marzo';
  347. break;
  348. case 4:
  349. $ret = 'Aprile';
  350. break;
  351. case 5:
  352. $ret = 'Maggio';
  353. break;
  354. case 6:
  355. $ret = 'Giugno';
  356. break;
  357. case 7:
  358. $ret = 'Luglio';
  359. break;
  360. case 8:
  361. $ret = 'Agosto';
  362. break;
  363. case 9:
  364. $ret = 'Settembre';
  365. break;
  366. case 10:
  367. $ret = 'Ottobre';
  368. break;
  369. case 11:
  370. $ret = 'Novembre';
  371. break;
  372. case 12:
  373. $ret = 'Dicembre';
  374. break;
  375. default:
  376. $ret = '';
  377. break;
  378. }
  379. return $ret;
  380. }
  381. public function render()
  382. {
  383. $month = 0;
  384. $year = 0;
  385. $this->records = array();
  386. $this->totals = array();
  387. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  388. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  389. ->select(
  390. 'records.*',
  391. 'records_rows.id as row_id',
  392. 'records_rows.record_id',
  393. 'records_rows.causal_id',
  394. 'records_rows.amount',
  395. 'records_rows.note',
  396. 'records_rows.when',
  397. 'records_rows.vat_id',
  398. 'records_rows.imponibile',
  399. 'records_rows.aliquota_iva',
  400. 'records_rows.imposta'
  401. )
  402. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  403. ->whereBetween('date', [$this->appliedFromDate, $this->appliedToDate])
  404. ->where(function ($query) {
  405. $query->where('type', 'OUT')
  406. ->orWhere(function ($query) {
  407. $query->where('records.corrispettivo_fiscale', true)
  408. ->orWhere('records.commercial', false);
  409. });
  410. })
  411. ->where(function ($query) use ($exclude_from_records) {
  412. $query->where('type', 'OUT')
  413. ->orWhere(function ($subquery) use ($exclude_from_records) {
  414. $subquery->whereNotIn('member_id', $exclude_from_records);
  415. });
  416. });
  417. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  418. $causals = array();
  419. foreach ($this->filterCausals as $z) {
  420. $causals[] = $z;
  421. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  422. foreach ($childs as $c) {
  423. $causals[] = $c->id;
  424. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  425. foreach ($childsX as $cX) {
  426. $causals[] = $cX->id;
  427. }
  428. }
  429. }
  430. $datas->whereIn('causal_id', $causals);
  431. }
  432. if ($this->filterMember != null && $this->filterMember > 0) {
  433. $datas->where('member_id', $this->filterMember);
  434. }
  435. $datas = $datas->orderBy('date', 'ASC')
  436. ->orderBy('records.created_at', 'ASC')
  437. ->orderBy('records_rows.id', 'ASC')
  438. ->get();
  439. $groupedData = [];
  440. $causalsCount = [];
  441. $nominativi = [];
  442. foreach ($datas as $idx => $data) {
  443. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  444. $paymentCheck = $data->payment_method->money;
  445. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  446. if (!$data->deleted) {
  447. $amount = $data->amount;
  448. $amount += getVatValue($amount, $data->vat_id);
  449. } else {
  450. $amount = $data->amount;
  451. }
  452. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  453. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  454. $nominativo = '';
  455. if ($data->type == "IN") {
  456. if ($data->member) {
  457. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  458. }
  459. } else {
  460. if ($data->supplier) {
  461. $nominativo = $data->supplier->name;
  462. }
  463. }
  464. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  465. if (!isset($groupedData[$groupKey])) {
  466. $groupedData[$groupKey] = [
  467. 'date' => $data->date,
  468. 'type_label' => $typeLabel,
  469. 'payment_method' => $data->payment_method->name,
  470. 'transaction_type' => $data->type,
  471. 'nominativo' => $nominativo,
  472. 'amount' => 0,
  473. 'deleted' => false,
  474. 'causals' => [],
  475. 'notes' => []
  476. ];
  477. $causalsCount[$groupKey] = [];
  478. $nominativi[$groupKey] = $nominativo;
  479. }
  480. $groupedData[$groupKey]['amount'] += $amount;
  481. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  482. if (!empty($data->note)) {
  483. $groupedData[$groupKey]['notes'][] = $data->note;
  484. }
  485. if ($data->deleted) {
  486. $groupedData[$groupKey]['deleted'] = true;
  487. }
  488. }
  489. }
  490. foreach ($groupedData as $groupKey => $group) {
  491. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  492. $causalDisplay = $group['type_label'];
  493. if (count($causalsInGroup) > 1) {
  494. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
  495. } else {
  496. $detailDisplay = $causalsInGroup[0];
  497. }
  498. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  499. if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  500. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  501. }
  502. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  503. if (!isset($this->totals[$group['payment_method']])) {
  504. $this->totals[$group['payment_method']]["IN"] = 0;
  505. $this->totals[$group['payment_method']]["OUT"] = 0;
  506. }
  507. if (!$group['deleted'])
  508. $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  509. }
  510. return view('livewire.records');
  511. }
  512. private function getLabels($fromDate, $toDate)
  513. {
  514. $begin = new DateTime($fromDate);
  515. $end = new DateTime($toDate);
  516. $interval = DateInterval::createFromDateString('1 day');
  517. $date_range = new DatePeriod($begin, $interval, $end);
  518. foreach ($date_range as $date) {
  519. $labels[] = $date->format('d/M');
  520. }
  521. return $labels;
  522. }
  523. private function getRecordData($type, $fromDate, $toDate)
  524. {
  525. $data = [];
  526. $begin = new DateTime($fromDate);
  527. $end = new DateTime($toDate);
  528. $interval = DateInterval::createFromDateString('1 day');
  529. $date_range = new DatePeriod($begin, $interval, $end);
  530. foreach ($date_range as $date) {
  531. if ($type == 'IN') {
  532. $found = false;
  533. foreach ($this->in as $in) {
  534. if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
  535. $data[] = number_format($in->total, 0, "", "");
  536. $found = true;
  537. }
  538. }
  539. if (!$found)
  540. $data[] = 0;
  541. }
  542. if ($type == 'OUT') {
  543. $found = false;
  544. foreach ($this->out as $out) {
  545. if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
  546. $data[] = number_format($out->total, 0, "", "");
  547. $found = true;
  548. }
  549. }
  550. if (!$found)
  551. $data[] = 0;
  552. }
  553. }
  554. return $data;
  555. }
  556. public function openExportModal()
  557. {
  558. $this->exportFromDate = $this->appliedFromDate;
  559. $this->exportToDate = $this->appliedToDate;
  560. // Reset email options
  561. $this->sendViaEmail = false;
  562. $this->exportEmailAddress = $this->getPreferredEmail();
  563. $this->updateEmailSubject();
  564. $this->emit('show-export-modal');
  565. }
  566. public function exportWithDateRange()
  567. {
  568. $this->isExporting = true;
  569. $this->emit('$refresh'); // This forces Livewire to re-render
  570. // Add a small delay to allow the view to update
  571. usleep(100000);
  572. if ($this->sendViaEmail) {
  573. $this->validate([
  574. 'exportEmailAddress' => 'required|email',
  575. 'exportEmailSubject' => 'required|string|max:255',
  576. ]);
  577. }
  578. $this->isExporting = true;
  579. try {
  580. $exportRecords = $this->generateExportData($this->exportFromDate, $this->exportToDate);
  581. $exportTotals = $this->generateExportTotals($this->exportFromDate, $this->exportToDate);
  582. if ($this->sendViaEmail) {
  583. // Dispatch job to background queue
  584. $this->dispatchExportJob($exportRecords, $exportTotals);
  585. } else {
  586. // Direct download (synchronous)
  587. return $this->exportWithData($exportRecords, $exportTotals);
  588. }
  589. } catch (\Illuminate\Validation\ValidationException $e) {
  590. $this->isExporting = false;
  591. throw $e;
  592. } catch (\Exception $e) {
  593. $this->isExporting = false;
  594. Log::error('Export error: ' . $e->getMessage());
  595. if ($this->sendViaEmail) {
  596. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  597. } else {
  598. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  599. }
  600. } finally {
  601. $this->isExporting = false;
  602. $this->emit('export-complete');
  603. $this->emit('hide-export-modal');
  604. }
  605. }
  606. private function getMemberName($memberId)
  607. {
  608. $member = \App\Models\Member::find($memberId);
  609. return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
  610. }
  611. private function getCausalsNames($causalIds)
  612. {
  613. if (!is_array($causalIds)) {
  614. return null;
  615. }
  616. $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
  617. return implode(', ', $causals);
  618. }
  619. public function updatedExportFromDate()
  620. {
  621. $this->updateEmailSubject();
  622. }
  623. public function updatedExportToDate()
  624. {
  625. $this->updateEmailSubject();
  626. }
  627. public function updatedSendViaEmail($value)
  628. {
  629. if ($value && empty($this->exportEmailAddress)) {
  630. $this->exportEmailAddress = $this->getPreferredEmail();
  631. }
  632. }
  633. public function resetEmailForm()
  634. {
  635. $this->sendViaEmail = false;
  636. $this->exportEmailAddress = $this->getPreferredEmail();
  637. $this->updateEmailSubject();
  638. }
  639. private function updateEmailSubject()
  640. {
  641. if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
  642. $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
  643. $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
  644. if ($this->exportFromDate === $this->exportToDate) {
  645. $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
  646. } else {
  647. $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
  648. }
  649. }
  650. }
  651. /**
  652. * Dispatch export job to queue
  653. */
  654. private function dispatchExportJob($exportRecords, $exportTotals)
  655. {
  656. try {
  657. // Prepare filter descriptions for the job
  658. $filterDescriptions = [
  659. 'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
  660. 'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
  661. ];
  662. $paymentsArray = $this->payments->map(function ($payment) {
  663. return [
  664. 'id' => $payment->id,
  665. 'name' => $payment->name,
  666. 'type' => $payment->type
  667. ];
  668. })->toArray();
  669. // Dispatch job to background queue
  670. ExportPrimaNota::dispatch(
  671. $exportRecords,
  672. $exportTotals,
  673. $this->exportEmailAddress,
  674. $this->exportEmailSubject,
  675. [
  676. 'from' => date('d/m/Y', strtotime($this->exportFromDate)),
  677. 'to' => date('d/m/Y', strtotime($this->exportToDate))
  678. ],
  679. auth()->id(),
  680. $paymentsArray,
  681. $filterDescriptions
  682. );
  683. $this->emit('export-email-queued');
  684. session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
  685. Log::info('Export job dispatched', [
  686. 'user_id' => auth()->id(),
  687. 'email' => $this->exportEmailAddress,
  688. 'date_range' => [$this->exportFromDate, $this->exportToDate],
  689. 'total_records' => count($exportRecords)
  690. ]);
  691. } catch (\Exception $e) {
  692. Log::error('Failed to dispatch export job', [
  693. 'user_id' => auth()->id(),
  694. 'email' => $this->exportEmailAddress,
  695. 'error' => $e->getMessage()
  696. ]);
  697. throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
  698. }
  699. }
  700. function export()
  701. {
  702. $exportRecords = $this->generateExportData($this->appliedFromDate, $this->appliedToDate);
  703. $exportTotals = $this->generateExportTotals($this->appliedFromDate, $this->appliedToDate);
  704. return $this->exportWithData($exportRecords, $exportTotals);
  705. }
  706. private function exportWithData($exportRecords, $exportTotals)
  707. {
  708. ini_set('memory_limit', '512M');
  709. gc_enable();
  710. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  711. $spreadsheet = new Spreadsheet();
  712. $activeWorksheet = $spreadsheet->getActiveSheet();
  713. $activeWorksheet->setCellValue('A1', "Data");
  714. $activeWorksheet->setCellValue('B1', "Causale");
  715. $activeWorksheet->setCellValue('C1', "Dettaglio");
  716. $activeWorksheet->setCellValue('D1', "Nominativo");
  717. $activeWorksheet->setCellValue('E1', "Stato");
  718. $idx = 0;
  719. foreach ($this->payments as $p) {
  720. if ($idx >= count($letters)) {
  721. break;
  722. }
  723. $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
  724. $idx++;
  725. if ($idx >= count($letters)) {
  726. break;
  727. }
  728. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
  729. $idx++;
  730. }
  731. $idx = 0;
  732. $activeWorksheet->setCellValue('A2', "");
  733. $activeWorksheet->setCellValue('B2', "");
  734. $activeWorksheet->setCellValue('C2', "");
  735. $activeWorksheet->setCellValue('D2', "");
  736. $activeWorksheet->setCellValue('E2', "");
  737. foreach ($this->payments as $p) {
  738. if ($p->type == 'ALL') {
  739. if ($idx >= count($letters)) {
  740. break;
  741. }
  742. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  743. $idx++;
  744. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  745. $idx++;
  746. } elseif ($p->type == 'IN') {
  747. if ($idx >= count($letters)) {
  748. break;
  749. }
  750. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  751. $idx++;
  752. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  753. $idx++;
  754. } elseif ($p->type == 'OUT') {
  755. if ($idx >= count($letters)) {
  756. break;
  757. }
  758. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  759. $idx++;
  760. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  761. $idx++;
  762. }
  763. }
  764. $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
  765. $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
  766. $count = 3;
  767. $batchSize = 1000;
  768. $recordsProcessed = 0;
  769. $totalRecords = count($exportRecords);
  770. $recordsArray = array_chunk($exportRecords, $batchSize, true);
  771. foreach ($recordsArray as $recordsBatch) {
  772. foreach ($recordsBatch as $causal => $record) {
  773. $check = $causal;
  774. $parts = explode("§", $check);
  775. $d = $parts[0] ?? '';
  776. $c = $parts[1] ?? '';
  777. $j = $parts[2] ?? '';
  778. $det = $parts[3] ?? '';
  779. $deleted = $parts[4] ?? '';
  780. $detailParts = explode('|', $det);
  781. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  782. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  783. $activeWorksheet->setCellValue('B' . $count, $c);
  784. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  785. $activeWorksheet->setCellValue('D' . $count, $j);
  786. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  787. $activeWorksheet->setCellValue('E' . $count, $stato);
  788. if ($stato === 'ANNULLATA') {
  789. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  790. }
  791. $idx = 0;
  792. foreach ($this->payments as $p) {
  793. if ($idx >= count($letters) - 1) {
  794. break;
  795. }
  796. if (isset($record[$p->name])) {
  797. $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
  798. $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
  799. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  800. $idx++;
  801. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  802. $idx++;
  803. } else {
  804. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  805. $idx++;
  806. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  807. $idx++;
  808. }
  809. }
  810. $count++;
  811. $recordsProcessed++;
  812. if ($recordsProcessed % 500 === 0) {
  813. gc_collect_cycles();
  814. }
  815. }
  816. unset($recordsBatch);
  817. gc_collect_cycles();
  818. }
  819. $count++;
  820. $idx = 0;
  821. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  822. $activeWorksheet->setCellValue('B' . $count, '');
  823. $activeWorksheet->setCellValue('C' . $count, '');
  824. $activeWorksheet->setCellValue('D' . $count, '');
  825. $activeWorksheet->setCellValue('E' . $count, '');
  826. foreach ($this->payments as $p) {
  827. if ($idx >= count($letters) - 1) {
  828. break;
  829. }
  830. if (isset($exportTotals[$p->name])) {
  831. if ($p->type == 'ALL') {
  832. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  833. $idx++;
  834. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  835. $idx++;
  836. } elseif ($p->type == 'IN') {
  837. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  838. $idx++;
  839. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  840. $idx++;
  841. } elseif ($p->type == 'OUT') {
  842. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  843. $idx++;
  844. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  845. $idx++;
  846. }
  847. } else {
  848. if ($p->type == 'ALL') {
  849. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  850. $idx++;
  851. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  852. $idx++;
  853. } elseif ($p->type == 'IN') {
  854. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  855. $idx++;
  856. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  857. $idx++;
  858. } elseif ($p->type == 'OUT') {
  859. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  860. $idx++;
  861. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  862. $idx++;
  863. }
  864. }
  865. }
  866. $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
  867. $activeWorksheet->getColumnDimension('A')->setWidth(20);
  868. $activeWorksheet->getColumnDimension('B')->setWidth(40);
  869. $activeWorksheet->getColumnDimension('C')->setWidth(40);
  870. $activeWorksheet->getColumnDimension('D')->setWidth(40);
  871. $activeWorksheet->getColumnDimension('E')->setWidth(20);
  872. foreach ($letters as $l) {
  873. $activeWorksheet->getColumnDimension($l)->setWidth(20);
  874. }
  875. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  876. try {
  877. $currentClient = session('currentClient', 'default');
  878. $tempPath = sys_get_temp_dir() . '/' . $filename;
  879. $writer = new Xlsx($spreadsheet);
  880. $writer->save($tempPath);
  881. unset($spreadsheet, $activeWorksheet, $writer);
  882. gc_collect_cycles();
  883. $disk = Storage::disk('s3');
  884. $s3Path = $currentClient . '/prima_nota/' . $filename;
  885. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  886. if (!$disk->exists($primaNotaFolderPath)) {
  887. $disk->put($primaNotaFolderPath, '');
  888. Log::info("Created prima_nota folder for client: {$currentClient}");
  889. }
  890. $fileContent = file_get_contents($tempPath);
  891. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  892. if (!$uploaded) {
  893. throw new \Exception('Failed to upload file to Wasabi S3');
  894. }
  895. Log::info("Prima Nota exported to Wasabi", [
  896. 'client' => $currentClient,
  897. 'path' => $s3Path,
  898. 'size' => filesize($tempPath),
  899. 'records_processed' => $recordsProcessed
  900. ]);
  901. if (file_exists($tempPath)) {
  902. unlink($tempPath);
  903. }
  904. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  905. return redirect($downloadUrl);
  906. } catch (\Exception $e) {
  907. Log::error('Error exporting Prima Nota to Wasabi S3', [
  908. 'error' => $e->getMessage(),
  909. 'client' => session('currentClient', 'unknown'),
  910. 'filename' => $filename,
  911. 'records_processed' => $recordsProcessed ?? 0
  912. ]);
  913. $currentClient = session('currentClient', 'default');
  914. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  915. if (!is_dir($clientFolder)) {
  916. mkdir($clientFolder, 0755, true);
  917. Log::info("Created local client prima_nota folder: {$clientFolder}");
  918. }
  919. $localPath = $clientFolder . '/' . $filename;
  920. if (isset($tempPath) && file_exists($tempPath)) {
  921. rename($tempPath, $localPath);
  922. } else {
  923. $writer = new Xlsx($spreadsheet);
  924. $writer->save($localPath);
  925. unset($spreadsheet, $activeWorksheet, $writer);
  926. }
  927. gc_collect_cycles();
  928. Log::warning("Prima Nota saved locally due to S3 error", [
  929. 'client' => $currentClient,
  930. 'local_path' => $localPath,
  931. 'error' => $e->getMessage()
  932. ]);
  933. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  934. return response()->download($localPath)->deleteFileAfterSend();
  935. }
  936. }
  937. private function getPreferredEmail()
  938. {
  939. // Try multiple sources in order of preference
  940. $email = auth()->user()->email ?? null;
  941. if (empty($email)) {
  942. $email = session('user_email', null);
  943. }
  944. if (empty($email)) {
  945. $member = \App\Models\Member::where('user_id', auth()->id())->first();
  946. $email = $member ? $member->email : null;
  947. }
  948. if (empty($email)) {
  949. // Get from user input or company default
  950. $email = config('mail.default_recipient', '');
  951. }
  952. return $email;
  953. }
  954. }