| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904 |
- <?php
- namespace App\Http\Livewire;
- use Livewire\Component;
- use DateInterval;
- use DatePeriod;
- use DateTime;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Mail;
- use App\Mail\ExportNotification;
- use App\Jobs\ExportPrimaNota;
- class Record extends Component
- {
- public $records, $dataId, $totals;
- public $in;
- public $out;
- public $payments = [];
- public $origins = [];
- public $destinations = [];
- public $fromDate;
- public $toDate;
- public $appliedFromDate;
- public $appliedToDate;
- public $exportFromDate;
- public $exportToDate;
- public $isExporting = false;
- public $selectedPeriod = 'OGGI';
- public $filterCausals = null;
- public $filterPaymentMethods = null;
- public $filterOrigins = null;
- public $filterDestinations = null;
- public $filterMember = null;
- public $isFiltering = false;
- public array $recordDatas = [];
- public array $labels = [];
- public array $causals = [];
- public $members = array();
- public $sendViaEmail = false;
- public $exportEmailAddress = '';
- public $exportEmailSubject = 'Prima Nota - Export';
- private $causalAmounts = [];
- public $selectedMonth;
- public $showMonthPicker = false;
- public $selectedDay;
- public $showDayPicker = false;
- public $selectedYear;
- protected $rules = [
- 'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
- 'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
- ];
- public $total_in = 0;
- public $total_out = 0;
- protected $messages = [
- 'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
- 'exportEmailAddress.email' => 'Inserisci un indirizzo email valido.',
- 'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
- 'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
- ];
- public function hydrate()
- {
- $this->emit('load-select');
- }
- public function mount()
- {
- $this->fromDate = date("Y-m-d");
- $this->toDate = date("Y-m-d");
- $this->appliedFromDate = date("Y-m-d");
- $this->appliedToDate = date("Y-m-d");
- $this->exportFromDate = date("Y-m-d");
- $this->exportToDate = date("Y-m-d");
- $this->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
- $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
- $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
- ->where(function($query) {
- $query->where('is_archived', false)
- ->orWhereNull('is_archived');
- })
- ->where(function($query) {
- $query->where('is_deleted', false)
- ->orWhereNull('is_deleted');
- })->orderBy('last_name')->orderBy('first_name')->get();
- $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
- $this->origins = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', ['OUT', 'ALL'])->get();
- $this->destinations = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', ['IN', 'ALL'])->get();
- $this->selectedMonth = date('Y-m');
- $this->selectedDay = date('Y-m-d');
- $this->selectedYear = date('Y');
- }
- private function generateExportDataAndTotals($fromDate, $toDate)
- {
- Log::info('generateExportDataAndTotals: Start (combined method)', [
- 'from_date' => $fromDate,
- 'to_date' => $toDate,
- 'memory_before' => memory_get_usage(true)
- ]);
- $exportRecords = array();
- $exportTotals = array();
- Log::info('generateExportDataAndTotals: Getting excluded members');
- $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
- Log::info('generateExportDataAndTotals: Excluded members retrieved', ['count' => count($exclude_from_records)]);
- Log::info('generateExportDataAndTotals: Building main query');
- $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
- ->select(
- 'records.*',
- 'records_rows.id as row_id',
- 'records_rows.record_id',
- 'records_rows.causal_id',
- 'records_rows.amount',
- 'records_rows.note',
- 'records_rows.when',
- 'records_rows.vat_id',
- 'records_rows.created_at as row_created_at',
- 'records_rows.updated_at as row_updated_at'
- )
- ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
- //->where('records.deleted', false)
- ->where(function ($query) {
- $query->where('records.deleted', false)->orWhereNull('records.deleted');
- })
- ->whereBetween('date', [$fromDate, $toDate])
- ->where(function ($query) {
- $query->where('type', 'OUT')
- ->orWhere(function ($query) {
- $query->where('records.corrispettivo_fiscale', true)
- ->orWhere('records.commercial', false);
- });
- })
- ->where(function ($query) use ($exclude_from_records) {
- $query->where('type', 'OUT')
- ->orWhere(function ($subquery) use ($exclude_from_records) {
- $subquery->whereNotIn('member_id', $exclude_from_records);
- });
- });
- Log::info('generateExportDataAndTotals: Applying causal filters');
- if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
- $causals = array();
- foreach ($this->filterCausals as $z) {
- $causals[] = $z;
- $childs = \App\Models\Causal::where('parent_id', $z)->get();
- foreach ($childs as $c) {
- $causals[] = $c->id;
- $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
- foreach ($childsX as $cX) {
- $causals[] = $cX->id;
- }
- }
- }
- $datas->whereIn('causal_id', $causals);
- Log::info('generateExportDataAndTotals: Causal filters applied', ['causal_count' => count($causals)]);
- }
- if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
- $datas->whereIn('payment_method_id', $this->filterPaymentMethods);
- Log::info('generateExportDataAndTotals: Payment method filters applied', ['payment_method_count' => count($this->filterPaymentMethods)]);
- }
- if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
- $datas->whereIn('origin_id', $this->filterOrigins);
- Log::info('generateExportDataAndTotals: Origin filters applied', ['origins_count' => count($this->filterOrigins)]);
- }
- if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
- $datas->whereIn('destination_id', $this->filterDestinations);
- Log::info('generateExportDataAndTotals: Destination filters applied', ['destinations_count' => count($this->filterDestinations)]);
- }
- if ($this->filterMember != null && $this->filterMember > 0) {
- $datas->where('member_id', $this->filterMember);
- Log::info('generateExportDataAndTotals: Member filter applied', ['member_id' => $this->filterMember]);
- }
- Log::info('generateExportDataAndTotals: Executing query');
- $queryStart = microtime(true);
- $datas = $datas->orderBy('date', 'ASC')
- ->orderBy('records.created_at', 'ASC')
- ->orderBy('records_rows.id', 'ASC')
- ->get();
- $queryTime = microtime(true) - $queryStart;
- Log::info('generateExportDataAndTotals: Query executed', [
- 'record_count' => $datas->count(),
- 'query_time' => $queryTime,
- 'memory_after_query' => memory_get_usage(true)
- ]);
- $groupedData = [];
- $causalsCount = [];
- $processedCount = 0;
- // Initialize totals array
- foreach ($this->payments as $p) {
- $exportTotals[$p->name] = ["IN" => 0, "OUT" => 0];
- }
- Log::info('generateExportDataAndTotals: Starting combined data processing loop');
- $loopStart = microtime(true);
- foreach ($datas as $idx => $data) {
- if ($processedCount % 100 == 0) {
- Log::info('generateExportDataAndTotals: Processing progress', [
- 'processed' => $processedCount,
- 'total' => $datas->count(),
- 'memory_current' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true)
- ]);
- }
- try {
- $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
- $paymentCheck = $data->payment_method->money;
- if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
- if (!$data->deleted) {
- $amount = $data->amount;
- $amount += getVatValue($amount, $data->vat_id);
- } else {
- $amount = $data->amount;
- }
- // CALCULATE TOTALS HERE (in the same loop)
- /*if (!$data->deleted) {
- $exportTotals[$data->payment_method->name][$data->type] += $amount;
- }*/
- $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
- $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
- $nominativo = '';
- if ($data->type == "IN") {
- if ($data->member) {
- $nominativo = $data->member->last_name . " " . $data->member->first_name;
- }
- } else {
- if ($data->supplier) {
- $nominativo = $data->supplier->name;
- }
- }
- $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
- if (!isset($groupedData[$groupKey])) {
- $groupedData[$groupKey] = [
- 'date' => $data->date,
- 'type_label' => $typeLabel,
- 'payment_method' => $data->payment_method->name,
- 'transaction_type' => $data->type,
- 'nominativo' => $nominativo,
- 'amount' => 0,
- 'deleted' => false,
- 'causals' => [],
- 'notes' => []
- ];
- $causalsCount[$groupKey] = [];
- }
- $groupedData[$groupKey]['amount'] += $amount;
- $causalsCount[$groupKey][$causalCheck->getTree()] = true;
- if (!empty($data->note)) {
- $groupedData[$groupKey]['notes'][] = $data->note;
- }
- if ($data->deleted) {
- $groupedData[$groupKey]['deleted'] = true;
- }
- }
- $processedCount++;
- } catch (\Exception $e) {
- Log::error('generateExportDataAndTotals: Error processing individual record', [
- 'record_id' => $data->id ?? 'unknown',
- 'error' => $e->getMessage(),
- 'processed_so_far' => $processedCount
- ]);
- throw $e;
- }
- }
- $loopTime = microtime(true) - $loopStart;
- Log::info('generateExportDataAndTotals: Combined processing loop completed', [
- 'total_processed' => $processedCount,
- 'grouped_records' => count($groupedData),
- 'loop_time' => $loopTime,
- 'memory_after_loop' => memory_get_usage(true)
- ]);
- Log::info('generateExportDataAndTotals: Building final export records');
- $finalStart = microtime(true);
- $tot = 0;
- $count = 0;
- foreach ($groupedData as $groupKey => $group) {
- $causalsInGroup = array_keys($causalsCount[$groupKey]);
- $causalDisplay = $group['type_label'];
- if (count($causalsInGroup) > 1) {
- $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
- } else {
- $detailDisplay = $causalsInGroup[0];
- }
- $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
- if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
- $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
- }
- $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
- if (!$group['deleted'])
- $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
- }
- $finalTime = microtime(true) - $finalStart;
- Log::info('generateExportDataAndTotals: Final processing completed', [
- 'final_export_records' => count($exportRecords),
- 'final_export_totals' => count($exportTotals),
- 'final_time' => $finalTime,
- 'total_time' => microtime(true) - $loopStart + $queryTime,
- 'memory_final' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true)
- ]);
- // Cleanup
- unset($datas, $groupedData, $causalsCount);
- gc_collect_cycles();
- Log::info('generateExportDataAndTotals: Completed with cleanup', [
- 'memory_after_cleanup' => memory_get_usage(true)
- ]);
- return ['records' => $exportRecords, 'totals' => $exportTotals];
- }
- private function generateExportTotals($fromDate, $toDate)
- {
- $exportTotals = array();
- $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
- $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
- ->select(
- 'records.*',
- 'records_rows.id as row_id',
- 'records_rows.record_id',
- 'records_rows.causal_id',
- 'records_rows.amount',
- 'records_rows.note',
- 'records_rows.when',
- 'records_rows.vat_id',
- )
- ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
- //->where('records.deleted', false)
- ->where(function ($query) {
- $query->where('records.deleted', false)->orWhereNull('records.deleted');
- })
- ->whereBetween('date', [$fromDate, $toDate])
- ->where(function ($query) {
- $query->where('type', 'OUT')
- ->orWhere(function ($query) {
- $query->where('records.corrispettivo_fiscale', true)
- ->orWhere('records.commercial', false);
- });
- })
- ->where(function ($query) use ($exclude_from_records) {
- $query->where('type', 'OUT')
- ->orWhere(function ($subquery) use ($exclude_from_records) {
- $subquery->whereNotIn('member_id', $exclude_from_records);
- });
- });
- if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
- $causals = array();
- foreach ($this->filterCausals as $z) {
- $causals[] = $z;
- $childs = \App\Models\Causal::where('parent_id', $z)->get();
- foreach ($childs as $c) {
- $causals[] = $c->id;
- $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
- foreach ($childsX as $cX) {
- $causals[] = $cX->id;
- }
- }
- }
- $datas->whereIn('causal_id', $causals);
- }
- if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
- $datas->whereIn('payment_method_id', $this->filterPaymentMethods);
- }
- if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
- $datas->whereIn('origin_id', $this->filterOrigins);
- }
- if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
- $datas->whereIn('destination_id', $this->filterDestinations);
- }
- if ($this->filterMember != null && $this->filterMember > 0) {
- $datas->where('member_id', $this->filterMember);
- }
- $datas = $datas->orderBy('date', 'ASC')
- ->orderBy('records.created_at', 'ASC')
- ->orderBy('records_rows.id', 'ASC')
- ->get();
- foreach ($datas as $data) {
- $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
- $paymentCheck = $data->payment_method->money;
- if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
- if (!$data->deleted) {
- $amount = $data->amount;
- $amount += getVatValue($amount, $data->vat_id);
- } else {
- $amount = $data->amount;
- }
- if (!isset($exportTotals[$data->payment_method->name])) {
- $exportTotals[$data->payment_method->name]["IN"] = 0;
- $exportTotals[$data->payment_method->name]["OUT"] = 0;
- }
- if (!$data->deleted)
- $exportTotals[$data->payment_method->name][$data->type] += $amount;
- }
- }
- return $exportTotals;
- }
- public function resetFilters()
- {
- $this->selectedPeriod = 'OGGI';
- $this->selectedMonth = date('Y-m');
- $this->selectedDay = date('Y-m-d');
- $this->selectedYear = date('Y');
- $this->showMonthPicker = false;
- $this->showDayPicker = false;
- $this->filterCausals = [];
- $this->filterPaymentMethods = [];
- $this->filterOrigins = [];
- $this->filterDestinations = [];
- $this->filterMember = null;
- $today = date("Y-m-d");
- $this->fromDate = $today;
- $this->toDate = $today;
- $this->appliedFromDate = $today;
- $this->appliedToDate = $today;
- $this->emit('filters-reset');
- }
- public function applyFilters()
- {
- $this->isFiltering = true;
- $this->setPeriodDates();
- $this->appliedFromDate = $this->fromDate;
- $this->appliedToDate = $this->toDate;
- $this->render();
- $this->isFiltering = false;
- $this->emit('filters-applied');
- }
- private function setPeriodDates()
- {
- $today = now();
- switch ($this->selectedPeriod) {
- case 'OGGI':
- $this->fromDate = $today->format('Y-m-d');
- $this->toDate = $today->format('Y-m-d');
- break;
- case 'IERI':
- $yesterday = $today->copy()->subDay();
- $this->fromDate = $yesterday->format('Y-m-d');
- $this->toDate = $yesterday->format('Y-m-d');
- break;
- case 'MESE CORRENTE':
- $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
- $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
- break;
- case 'MESE PRECEDENTE':
- $lastMonth = $today->copy()->subMonth();
- $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
- $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
- break;
- case 'MESE_PERSONALIZZATO':
- if (!empty($this->selectedMonth)) {
- $firstDay = date('Y-m-01', strtotime($this->selectedMonth . '-01'));
- $lastDay = date('Y-m-t', strtotime($this->selectedMonth . '-01'));
- $this->fromDate = $firstDay;
- $this->toDate = $lastDay;
- }
- break;
- case 'GIORNO_PERSONALIZZATO':
- if (!empty($this->selectedDay)) {
- $this->fromDate = $this->selectedDay;
- $this->toDate = $this->selectedDay;
- }
- break;
- case 'ULTIMO TRIMESTRE':
- $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
- $this->toDate = $today->format('Y-m-d');
- break;
- case 'ULTIMO QUADRIMESTRE':
- $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
- $this->toDate = $today->format('Y-m-d');
- break;
- }
- }
- public function getCausals($records, $indentation)
- {
- foreach ($records as $record) {
- $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
- if (count($record->childs))
- $this->getCausals($record->childs, $indentation + 1);
- }
- }
- public function getMonth($m)
- {
- $ret = '';
- switch ($m) {
- case 1:
- $ret = 'Gennaio';
- break;
- case 2:
- $ret = 'Febbraio';
- break;
- case 3:
- $ret = 'Marzo';
- break;
- case 4:
- $ret = 'Aprile';
- break;
- case 5:
- $ret = 'Maggio';
- break;
- case 6:
- $ret = 'Giugno';
- break;
- case 7:
- $ret = 'Luglio';
- break;
- case 8:
- $ret = 'Agosto';
- break;
- case 9:
- $ret = 'Settembre';
- break;
- case 10:
- $ret = 'Ottobre';
- break;
- case 11:
- $ret = 'Novembre';
- break;
- case 12:
- $ret = 'Dicembre';
- break;
- default:
- $ret = '';
- break;
- }
- return $ret;
- }
- public function loadData($from, $to)
- {
- $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
- $f = $from != '' ? $from : $this->appliedFromDate;
- $t = $to != '' ? $to : $this->appliedToDate;
- $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
- ->select(
- 'records.*',
- 'records_rows.id as row_id',
- 'records_rows.record_id',
- 'records_rows.causal_id',
- 'records_rows.amount',
- 'records_rows.note',
- 'records_rows.when',
- 'records_rows.vat_id',
- //'causals.name as causal_name',
- 'd.name as destination',
- 'o.name as origin',
- )
- ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
- ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
- ->leftJoin('banks as d', 'records.destination_id', '=', 'd.id')
- ->leftJoin('banks as o', 'records.origin_id', '=', 'o.id')
- //->where('records.deleted', false)
- /*->where(function ($query) {
- $query->where('records.deleted', false)->orWhereNull('records.deleted');
- })*/
- ->whereBetween('date', [$f . " 00:00:00", $t . " 23:59:59"])
- ->where(function ($query) {
- $query->where('records.type', 'OUT')
- ->orWhere(function ($query) {
- $query->where('records.corrispettivo_fiscale', true)
- ->orWhere('records.commercial', false);
- });
- })
- ->where(function ($query) use ($exclude_from_records) {
- $query->where('records.type', 'OUT')
- ->orWhere(function ($subquery) use ($exclude_from_records) {
- $subquery->whereNotIn('member_id', $exclude_from_records);
- });
- });
- if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
- $causals = array();
- foreach ($this->filterCausals as $z) {
- $causals[] = $z;
- $childs = \App\Models\Causal::where('parent_id', $z)->get();
- foreach ($childs as $c) {
- $causals[] = $c->id;
- $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
- foreach ($childsX as $cX) {
- $causals[] = $cX->id;
- }
- }
- }
- $datas->whereIn('causal_id', $causals);
- }
- if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
- $datas->whereIn('payment_method_id', $this->filterPaymentMethods);
- }
- if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
- $datas->whereIn('origin_id', $this->filterOrigins);
- }
- if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
- $datas->whereIn('destination_id', $this->filterDestinations);
- }
- if ($this->filterMember != null && $this->filterMember > 0) {
- $datas->where('member_id', $this->filterMember);
- }
- $datas = $datas->orderBy('date', 'ASC')
- ->orderBy('records.created_at', 'ASC')
- ->orderBy('records_rows.id', 'ASC')
- ->get();
- $ret = array();
- $this->total_in = 0;
- $this->total_out = 0;
- foreach($datas as $data)
- {
- $causal = \App\Models\Causal::findOrFail($data->causal_id);
- $paymentCheck = $data->payment_method->money;
- if (!$paymentCheck && ($causal->no_first == null || !$causal->no_first))
- {
- $data->causal_name = $causal->getTree();
- $ret[] = $data;
- if ($data->type == 'IN')
- $this->total_in += $data->amount;
- if ($data->type == 'OUT')
- $this->total_out += $data->amount;
- }
- }
- if ($this->total_in > 0 || $this->total_out > 0)
- {
- $ret[] = (object) array("date" => "", "total_in" => $this->total_in, "total_out" => $this->total_out);
- }
- return $ret;
- }
- public function render()
- {
- $month = 0;
- $year = 0;
- $this->records = array();
- $this->totals = array();
- $this->causalAmounts = array();
- $this->records = $this->loadData('', '');
- /*
- foreach ($datas as $idx => $data) {
- $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
- $paymentCheck = $data->payment_method->money;
- if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
- if (!$data->deleted) {
- $amount = $data->amount;
- if ($data->vat_id > 0)
- $amount += getVatValue($amount, $data->vat_id);
- } else {
- $amount = $data->amount;
- }
- $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
- $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
- $nominativo = '';
- if ($data->type == "IN") {
- if ($data->member) {
- $nominativo = $data->member->last_name . " " . $data->member->first_name;
- }
- if ($data->payment_method_id == 7)
- $values[] = array('id' => $data->record_id, 'amount' => $amount);
- } else {
- if ($data->supplier) {
- $nominativo = $data->supplier->name;
- }
- }
- $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
- if (!isset($groupedData[$groupKey])) {
- $groupedData[$groupKey] = [
- 'date' => $data->date,
- 'type_label' => $typeLabel,
- 'payment_method' => $data->payment_method->name,
- 'transaction_type' => $data->type,
- 'nominativo' => $nominativo,
- 'amount' => 0,
- 'deleted' => false,
- 'causals' => [],
- 'notes' => []
- ];
- $causalsCount[$groupKey] = [];
- $causalsAmounts[$groupKey] = []; // Initialize causal amounts for this group
- $nominativi[$groupKey] = $nominativo;
- }
- $groupedData[$groupKey]['amount'] += $amount;
- $causalsCount[$groupKey][$causalCheck->getTree()] = true;
- $causalName = $causalCheck->getTree();
- if (!isset($causalsAmounts[$groupKey][$causalName])) {
- $causalsAmounts[$groupKey][$causalName] = 0;
- }
- $causalsAmounts[$groupKey][$causalName] += $amount;
- if (!empty($data->note)) {
- $groupedData[$groupKey]['notes'][] = $data->note;
- }
- if ($data->deleted) {
- $groupedData[$groupKey]['deleted'] = true;
- }
- }
- }
- Log::info('values', [$values]);
- foreach ($groupedData as $groupKey => $group) {
- $causalsInGroup = array_keys($causalsCount[$groupKey]);
- $causalDisplay = $group['type_label'];
- if (count($causalsInGroup) > 1) {
- $causalAmountsForJs = [];
- foreach ($causalsInGroup as $causalName) {
- $causalAmountsForJs[] = $causalName . ':::' . formatPrice($causalsAmounts[$groupKey][$causalName]);
- }
- $detailDisplay = 'Varie|' . implode('|', $causalAmountsForJs);
- } else {
- $detailDisplay = $causalsInGroup[0];
- }
- $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
- if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
- $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
- }
- $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
- if (!isset($this->totals[$group['payment_method']])) {
- $this->totals[$group['payment_method']]["IN"] = 0;
- $this->totals[$group['payment_method']]["OUT"] = 0;
- }
- if (!$group['deleted'])
- $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
- }
- */
- return view('livewire.records');
- }
- private function getLabels($fromDate, $toDate)
- {
- $begin = new DateTime($fromDate);
- $end = new DateTime($toDate);
- $interval = DateInterval::createFromDateString('1 day');
- $date_range = new DatePeriod($begin, $interval, $end);
- foreach ($date_range as $date) {
- $labels[] = $date->format('d/M');
- }
- return $labels;
- }
- private function getRecordData($type, $fromDate, $toDate)
- {
- $data = [];
- $begin = new DateTime($fromDate);
- $end = new DateTime($toDate);
- $interval = DateInterval::createFromDateString('1 day');
- $date_range = new DatePeriod($begin, $interval, $end);
- foreach ($date_range as $date) {
- if ($type == 'IN') {
- $found = false;
- foreach ($this->in as $in) {
- if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
- $data[] = number_format($in->total, 0, "", "");
- $found = true;
- }
- }
- if (!$found)
- $data[] = 0;
- }
- if ($type == 'OUT') {
- $found = false;
- foreach ($this->out as $out) {
- if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
- $data[] = number_format($out->total, 0, "", "");
- $found = true;
- }
- }
- if (!$found)
- $data[] = 0;
- }
- }
- return $data;
- }
- public function openExportModal()
- {
- $this->exportFromDate = $this->appliedFromDate;
- $this->exportToDate = $this->appliedToDate;
- // Reset email options
- $this->sendViaEmail = false;
- $this->exportEmailAddress = $this->getPreferredEmail();
- $this->updateEmailSubject();
- $this->emit('show-export-modal');
- }
- public function exportWithDateRange()
- {
- Log::info('=== EXPORT START ===', [
- 'user_id' => auth()->id(),
- 'from_date' => $this->exportFromDate,
- 'to_date' => $this->exportToDate,
- 'send_via_email' => $this->sendViaEmail,
- 'memory_usage' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true),
- 'time_limit' => ini_get('max_execution_time')
- ]);
- $this->isExporting = true;
- $this->emit('$refresh');
- usleep(100000);
- if ($this->sendViaEmail) {
- Log::info('Export: Validating email fields');
- $this->validate([
- 'exportEmailAddress' => 'required|email',
- 'exportEmailSubject' => 'required|string|max:255',
- ]);
- Log::info('Export: Email validation passed');
- }
- $this->isExporting = true;
- try {
- Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
- $startTime = microtime(true);
- // *** THIS IS THE KEY CHANGE - USE ONLY THE COMBINED METHOD ***
- $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
- $exportRecords = $result['records'];
- $exportTotals = $result['totals'];
- Log::info('TOTALS', [$exportTotals]);
- $dataGenTime = microtime(true) - $startTime;
- Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
- 'records_count' => count($exportRecords),
- 'totals_count' => count($exportTotals),
- 'generation_time' => $dataGenTime,
- 'memory_usage' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true)
- ]);
- if ($this->sendViaEmail) {
- Log::info('Export: Dispatching to background job');
- //$this->dispatchExportJob($exportRecords, $exportTotals);
- Log::info('Export: Job dispatched successfully');
- } else {
- Log::info('Export: Starting direct download export');
- $exportStartTime = microtime(true);
- $result = $this->exportWithData($exportRecords, $exportTotals);
- $exportTime = microtime(true) - $exportStartTime;
- Log::info('Export: Direct export completed', [
- 'export_time' => $exportTime,
- 'total_time' => microtime(true) - $startTime,
- 'memory_usage' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true)
- ]);
- return $result;
- }
- } catch (\Illuminate\Validation\ValidationException $e) {
- Log::error('Export: Validation error', [
- 'error' => $e->getMessage(),
- 'errors' => $e->errors()
- ]);
- $this->isExporting = false;
- throw $e;
- } catch (\Exception $e) {
- Log::error('Export: General error', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'memory_usage' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true),
- 'execution_time' => microtime(true) - ($startTime ?? 0)
- ]);
- $this->isExporting = false;
- if ($this->sendViaEmail) {
- $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
- } else {
- session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
- }
- } finally {
- Log::info('Export: Cleanup phase');
- $this->isExporting = false;
- $this->emit('export-complete');
- $this->emit('hide-export-modal');
- Log::info('=== EXPORT END ===');
- }
- }
- public function exportData()
- {
- $this->isExporting = true;
- $this->emit('$refresh');
- usleep(100000);
- if ($this->sendViaEmail) {
- Log::info('Export: Validating email fields');
- $this->validate([
- 'exportEmailAddress' => 'required|email',
- 'exportEmailSubject' => 'required|string|max:255',
- ]);
- Log::info('Export: Email validation passed');
- }
- $this->isExporting = true;
- try {
- Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
- $startTime = microtime(true);
- $records = $this->loadData($this->exportFromDate, $this->exportToDate);
-
- $dataGenTime = microtime(true) - $startTime;
-
- if ($this->sendViaEmail) {
- Log::info('Export: Dispatching to background job');
- // Invio mail
- $this->dispatchExportJob($records);
- Log::info('Export: Job dispatched successfully');
- } else {
- Log::info('Export: Starting direct download export');
- $exportStartTime = microtime(true);
- // Creo excel e scarico
- $result = $this->exportExcel($records);
- $exportTime = microtime(true) - $exportStartTime;
- return $result;
- }
- } catch (\Illuminate\Validation\ValidationException $e) {
- Log::error('Export: Validation error', [
- 'error' => $e->getMessage(),
- 'errors' => $e->errors()
- ]);
- $this->isExporting = false;
- throw $e;
- } catch (\Exception $e) {
- Log::error('Export: General error', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'memory_usage' => memory_get_usage(true),
- 'memory_peak' => memory_get_peak_usage(true),
- 'execution_time' => microtime(true) - ($startTime ?? 0)
- ]);
- $this->isExporting = false;
- if ($this->sendViaEmail) {
- $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
- } else {
- session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
- }
- } finally {
- Log::info('Export: Cleanup phase');
- $this->isExporting = false;
- $this->emit('export-complete');
- $this->emit('hide-export-modal');
- Log::info('=== EXPORT END ===');
- }
- }
- private function getEstimatedRecordCount($fromDate, $toDate)
- {
- $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
- $query = \App\Models\Record::join('records_rows', 'records.id', '=', 'records_rows.record_id')
- ->whereBetween('date', [$fromDate, $toDate])
- ->where(function ($query) {
- $query->where('type', 'OUT')
- ->orWhere(function ($query) {
- $query->where('records.corrispettivo_fiscale', true)
- ->orWhere('records.commercial', false);
- });
- })
- ->where(function ($query) use ($exclude_from_records) {
- $query->where('type', 'OUT')
- ->orWhere(function ($subquery) use ($exclude_from_records) {
- $subquery->whereNotIn('member_id', $exclude_from_records);
- });
- });
- if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
- $causals = array();
- foreach ($this->filterCausals as $z) {
- $causals[] = $z;
- $childs = \App\Models\Causal::where('parent_id', $z)->get();
- foreach ($childs as $c) {
- $causals[] = $c->id;
- $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
- foreach ($childsX as $cX) {
- $causals[] = $cX->id;
- }
- }
- }
- $query->whereIn('causal_id', $causals);
- }
- if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
- $query->whereIn('payment_method_id', $this->filterPaymentMethods);
- }
- if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
- $query->whereIn('origin_id', $this->filterOrigins);
- }
- if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
- $query->whereIn('destination_id', $this->filterDestinations);
- }
- if ($this->filterMember != null && $this->filterMember > 0) {
- $query->where('member_id', $this->filterMember);
- }
- return $query->count();
- }
- private function getMemberName($memberId)
- {
- $member = \App\Models\Member::find($memberId);
- return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
- }
- private function getCausalsNames($causalIds)
- {
- if (!is_array($causalIds)) {
- return null;
- }
- $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
- return implode(', ', $causals);
- }
- private function getPaymentMethodsNames($paymentMethodIds)
- {
- if (!is_array($paymentMethodIds)) {
- return null;
- }
- $payment_methods = \App\Models\PaymentMethod::whereIn('id', $paymentMethodIds)->pluck('name')->toArray();
- return implode(', ', $payment_methods);
- }
- private function getOriginsNames($originIds)
- {
- if (!is_array($originIds)) {
- return null;
- }
- $origins = \App\Models\Bank::whereIn('id', $originIds)->pluck('name')->toArray();
- return implode(', ', $origins);
- }
- private function getDestinationsNames($destinationIds)
- {
- if (!is_array($destinationIds)) {
- return null;
- }
- $destinations = \App\Models\Bank::whereIn('id', $destinationIds)->pluck('name')->toArray();
- return implode(', ', $destinations);
- }
- public function updatedExportFromDate()
- {
- $this->updateEmailSubject();
- }
- public function updatedExportToDate()
- {
- $this->updateEmailSubject();
- }
- public function updatedSendViaEmail($value)
- {
- if ($value && empty($this->exportEmailAddress)) {
- $this->exportEmailAddress = $this->getPreferredEmail();
- }
- }
- public function resetEmailForm()
- {
- $this->sendViaEmail = false;
- $this->exportEmailAddress = $this->getPreferredEmail();
- $this->updateEmailSubject();
- }
- private function updateEmailSubject()
- {
- if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
- $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
- $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
- if ($this->exportFromDate === $this->exportToDate) {
- $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
- } else {
- $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
- }
- }
- }
- /**
- * Dispatch export job to queue
- */
- //private function dispatchExportJob($exportRecords, $exportTotals)
- private function dispatchExportJob($records)
- {
- try {
- // Prepare filter descriptions for the job
- $filterDescriptions = [
- 'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
- 'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
- 'payment_methods' => $this->filterPaymentMethods ? $this->getPaymentMethodsNames($this->filterPaymentMethods) : null,
- 'origins' => $this->filterOrigins ? $this->getOriginsNames($this->filterOrigins) : null,
- 'destinations' => $this->filterDestinations ? $this->getDestinationsNames($this->filterDestinations) : null,
- ];
- $paymentsArray = $this->payments->map(function ($payment) {
- return [
- 'id' => $payment->id,
- 'name' => $payment->name,
- 'type' => $payment->type
- ];
- })->toArray();
- // Dispatch job to background queue
- ExportPrimaNota::dispatch(
- /*$exportRecords,
- $exportTotals,*/
- $records,
- $this->exportEmailAddress,
- $this->exportEmailSubject,
- [
- 'from' => date('d/m/Y', strtotime($this->exportFromDate)),
- 'to' => date('d/m/Y', strtotime($this->exportToDate))
- ],
- auth()->id(),
- $paymentsArray,
- $filterDescriptions
- );
- $this->emit('export-email-queued');
- session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
- Log::info('Export job dispatched', [
- 'user_id' => auth()->id(),
- 'email' => $this->exportEmailAddress,
- 'date_range' => [$this->exportFromDate, $this->exportToDate],
- 'total_records' => count($this->records)
- ]);
- } catch (\Exception $e) {
- Log::error('Failed to dispatch export job', [
- 'user_id' => auth()->id(),
- 'email' => $this->exportEmailAddress,
- 'error' => $e->getMessage()
- ]);
- throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
- }
- }
- function export()
- {
- $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
- $exportRecords = $result['records'];
- $exportTotals = $result['totals'];
- return $this->exportWithData($exportRecords, $exportTotals);
- }
- private function exportWithData($exportRecords, $exportTotals)
- {
- Log::info('exportWithData: Starting Excel generation', [
- 'records_count' => count($exportRecords),
- 'totals_count' => count($exportTotals),
- 'memory_before' => memory_get_usage(true)
- ]);
- $startTime = microtime(true);
- Log::info('exportWithData: Setting memory and GC');
- ini_set('memory_limit', '512M');
- gc_enable();
- Log::info('exportWithData: Preparing column letters');
- $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
- Log::info('exportWithData: Creating spreadsheet object');
- $spreadsheet = new Spreadsheet();
- $activeWorksheet = $spreadsheet->getActiveSheet();
- Log::info('exportWithData: Setting basic headers');
- $activeWorksheet->setCellValue('A1', "Data");
- $activeWorksheet->setCellValue('B1', "Tipologia");
- $activeWorksheet->setCellValue('C1', "Causale");
- $activeWorksheet->setCellValue('D1', "Nominativo");
- $activeWorksheet->setCellValue('E1', "Stato");
- $activeWorksheet->getStyle('A1:Q1')->getFill()
- ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
- ->getStartColor()->setARGB('FF0C6197');
- $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
- Log::info('exportWithData: Setting payment method headers');
- $idx = 0;
- foreach ($this->payments as $p) {
- if ($idx >= count($letters)) {
- Log::warning('exportWithData: Reached letter limit', ['payment_index' => $idx]);
- break;
- }
- Log::debug('exportWithData: Setting payment header', [
- 'payment_name' => $p->name,
- 'column_index' => $idx,
- 'column_letter' => $letters[$idx]
- ]);
- $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
- $idx++;
- if ($idx >= count($letters)) {
- break;
- }
- $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
- $idx++;
- }
- Log::info('exportWithData: Setting sub-headers');
- $idx = 0;
- $activeWorksheet->setCellValue('A2', "");
- $activeWorksheet->setCellValue('B2', "");
- $activeWorksheet->setCellValue('C2', "");
- $activeWorksheet->setCellValue('D2', "");
- $activeWorksheet->setCellValue('E2', "");
- foreach ($this->payments as $p) {
- if ($p->type == 'ALL') {
- if ($idx >= count($letters)) {
- break;
- }
- $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
- $idx++;
- } elseif ($p->type == 'IN') {
- if ($idx >= count($letters)) {
- break;
- }
- $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . '2', "");
- $idx++;
- } elseif ($p->type == 'OUT') {
- if ($idx >= count($letters)) {
- break;
- }
- $activeWorksheet->setCellValue($letters[$idx] . '2', "");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
- $idx++;
- }
- }
- Log::info('exportWithData: Applying header styles');
- $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
- $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
- Log::info('exportWithData: Starting data row processing');
- $count = 3;
- $batchSize = 1000;
- $recordsProcessed = 0;
- $totalRecords = count($exportRecords);
- Log::info('exportWithData: Processing records in batches', [
- 'total_records' => $totalRecords,
- 'batch_size' => $batchSize
- ]);
- $recordsArray = array_chunk($exportRecords, $batchSize, true);
- Log::info('exportWithData: Created batches', ['batch_count' => count($recordsArray)]);
- foreach ($recordsArray as $batchIndex => $recordsBatch) {
- Log::info('exportWithData: Processing batch', [
- 'batch_index' => $batchIndex,
- 'batch_size' => count($recordsBatch),
- 'memory_current' => memory_get_usage(true),
- 'time_elapsed' => microtime(true) - $startTime
- ]);
- foreach ($recordsBatch as $causal => $record) {
- if ($recordsProcessed % 250 == 0) {
- Log::info('exportWithData: Record processing progress', [
- 'processed' => $recordsProcessed,
- 'total' => $totalRecords,
- 'current_row' => $count,
- 'memory_usage' => memory_get_usage(true),
- 'time_elapsed' => microtime(true) - $startTime
- ]);
- }
- try {
- $check = $causal;
- $parts = explode("§", $check);
- $d = $parts[0] ?? '';
- $c = $parts[1] ?? '';
- $j = $parts[2] ?? '';
- $det = $parts[3] ?? '';
- $deleted = $parts[4] ?? '';
- $detailParts = explode('|', $det);
- $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
- Log::debug('exportWithData: Setting row cells', ['row' => $count]);
- $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
- $activeWorksheet->setCellValue('B' . $count, $c);
- $activeWorksheet->setCellValue('C' . $count, $exportDetail);
- $activeWorksheet->setCellValue('D' . $count, $j);
- $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
- $activeWorksheet->setCellValue('E' . $count, $stato);
- if ($stato === 'ANNULLATA') {
- $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
- }
- $idx = 0;
- foreach ($this->payments as $p) {
- if ($idx >= count($letters) - 1) {
- break;
- }
- if (isset($record[$p->name])) {
- $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
- $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
- $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
- $idx++;
- } else {
- $activeWorksheet->setCellValue($letters[$idx] . $count, "");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, "");
- $idx++;
- }
- }
- $count++;
- $recordsProcessed++;
- if ($recordsProcessed % 500 === 0) {
- Log::debug('exportWithData: Garbage collection');
- gc_collect_cycles();
- }
- } catch (\Exception $e) {
- Log::error('exportWithData: Error processing record row', [
- 'row' => $count,
- 'causal' => $causal,
- 'error' => $e->getMessage(),
- 'processed_so_far' => $recordsProcessed
- ]);
- throw $e;
- }
- }
- Log::info('exportWithData: Batch completed', [
- 'batch_index' => $batchIndex,
- 'records_in_batch' => count($recordsBatch),
- 'total_processed' => $recordsProcessed
- ]);
- unset($recordsBatch);
- gc_collect_cycles();
- }
- Log::info('exportWithData: Adding totals row');
- $count++;
- $idx = 0;
- $activeWorksheet->setCellValue('A' . $count, 'Totale');
- $activeWorksheet->setCellValue('B' . $count, '');
- $activeWorksheet->setCellValue('C' . $count, '');
- $activeWorksheet->setCellValue('D' . $count, '');
- $activeWorksheet->setCellValue('E' . $count, '');
- foreach ($this->payments as $p) {
- if ($idx >= count($letters) - 1) {
- break;
- }
- if (isset($exportTotals[$p->name])) {
- if ($p->type == 'ALL') {
- $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
- $idx++;
- } elseif ($p->type == 'IN') {
- $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, "");
- $idx++;
- } elseif ($p->type == 'OUT') {
- $activeWorksheet->setCellValue($letters[$idx] . $count, "");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
- $idx++;
- }
- } else {
- if ($p->type == 'ALL') {
- $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
- $idx++;
- } elseif ($p->type == 'IN') {
- $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, "");
- $idx++;
- } elseif ($p->type == 'OUT') {
- $activeWorksheet->setCellValue($letters[$idx] . $count, "");
- $idx++;
- $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
- $idx++;
- }
- }
- }
- Log::info('exportWithData: Applying final styles');
- $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
- Log::info('exportWithData: Setting column dimensions');
- $activeWorksheet->getColumnDimension('A')->setWidth(20);
- $activeWorksheet->getColumnDimension('B')->setWidth(40);
- $activeWorksheet->getColumnDimension('C')->setWidth(40);
- $activeWorksheet->getColumnDimension('D')->setWidth(40);
- $activeWorksheet->getColumnDimension('E')->setWidth(20);
- foreach ($letters as $l) {
- $activeWorksheet->getColumnDimension($l)->setWidth(20);
- }
- $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
- Log::info('exportWithData: Preparing to save file', [
- 'filename' => $filename,
- 'total_processing_time' => microtime(true) - $startTime,
- 'memory_before_save' => memory_get_usage(true)
- ]);
- try {
- $currentClient = session('currentClient', 'default');
- $tempPath = sys_get_temp_dir() . '/' . $filename;
- Log::info('exportWithData: Creating Excel writer');
- $writer = new Xlsx($spreadsheet);
- Log::info('exportWithData: Saving to temp path', ['temp_path' => $tempPath]);
- $writerStart = microtime(true);
- $writer->save($tempPath);
- $writerTime = microtime(true) - $writerStart;
- Log::info('exportWithData: File saved to temp', [
- 'writer_time' => $writerTime,
- 'file_size' => file_exists($tempPath) ? filesize($tempPath) : 'unknown',
- 'memory_after_save' => memory_get_usage(true)
- ]);
- unset($spreadsheet, $activeWorksheet, $writer);
- gc_collect_cycles();
- Log::info('exportWithData: Uploading to S3');
- $disk = Storage::disk('s3');
- $s3Path = $currentClient . '/prima_nota/' . $filename;
- $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
- if (!$disk->exists($primaNotaFolderPath)) {
- $disk->put($primaNotaFolderPath, '');
- Log::info("Created prima_nota folder for client: {$currentClient}");
- }
- $uploadStart = microtime(true);
- $fileContent = file_get_contents($tempPath);
- $uploaded = $disk->put($s3Path, $fileContent, 'private');
- $uploadTime = microtime(true) - $uploadStart;
- if (!$uploaded) {
- throw new \Exception('Failed to upload file to Wasabi S3');
- }
- Log::info("Export completed successfully", [
- 'client' => $currentClient,
- 'path' => $s3Path,
- 'file_size' => filesize($tempPath),
- 'records_processed' => $recordsProcessed,
- 'upload_time' => $uploadTime,
- 'total_time' => microtime(true) - $startTime,
- 'memory_peak' => memory_get_peak_usage(true)
- ]);
- if (file_exists($tempPath)) {
- unlink($tempPath);
- }
- $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
- return redirect($downloadUrl);
- } catch (\Exception $e) {
- Log::error('Export S3 error - falling back to local', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'client' => session('currentClient', 'unknown'),
- 'filename' => $filename,
- 'records_processed' => $recordsProcessed ?? 0,
- 'time_elapsed' => microtime(true) - $startTime
- ]);
- // Fallback logic remains the same...
- $currentClient = session('currentClient', 'default');
- $clientFolder = storage_path('app/prima_nota/' . $currentClient);
- if (!is_dir($clientFolder)) {
- mkdir($clientFolder, 0755, true);
- Log::info("Created local client prima_nota folder: {$clientFolder}");
- }
- $localPath = $clientFolder . '/' . $filename;
- if (isset($tempPath) && file_exists($tempPath)) {
- rename($tempPath, $localPath);
- } else {
- $writer = new Xlsx($spreadsheet);
- $writer->save($localPath);
- unset($spreadsheet, $activeWorksheet, $writer);
- }
- gc_collect_cycles();
- Log::warning("Export saved locally due to S3 error", [
- 'client' => $currentClient,
- 'local_path' => $localPath,
- 'error' => $e->getMessage()
- ]);
- session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
- return response()->download($localPath)->deleteFileAfterSend();
- }
- }
- private function getPreferredEmail()
- {
- $email = auth()->user()->email ?? null;
- if (empty($email)) {
- $email = session('user_email', null);
- }
- if (empty($email)) {
- $member = \App\Models\Member::where('user_id', auth()->id())->first();
- $email = $member ? $member->email : null;
- }
- if (empty($email)) {
- $email = config('mail.default_recipient', '');
- }
- return $email;
- }
- public function updatedSelectedPeriod($value) {
- $this->setPeriodDates();
- $this->applyFilters();
- }
- public function updatedSelectedDay($value)
- {
- if (!empty($value)) {
- $this->selectedPeriod = 'GIORNO_PERSONALIZZATO';
- $this->fromDate = $value;
- $this->toDate = $value;
- $this->applyFilters();
- }
- }
- public function selectDay($day)
- {
- $this->selectedDay = $day;
- $this->showDayPicker = false;
- $this->updatedSelectedDay($day);
- }
- public function toggleDayPicker()
- {
- $this->showDayPicker = !$this->showDayPicker;
- }
- public function selectToday()
- {
- $today = date('Y-m-d');
- $this->selectDay($today);
- }
- public function selectYesterday()
- {
- $yesterday = date('Y-m-d', strtotime('-1 day'));
- $this->selectDay($yesterday);
- }
- // Updated month methods to work with both custom month and day
- public function updatedSelectedMonth($value)
- {
- if (!empty($value)) {
- $this->selectedPeriod = 'MESE_PERSONALIZZATO';
- $firstDay = date('Y-m-01', strtotime($value . '-01'));
- $lastDay = date('Y-m-t', strtotime($value . '-01'));
- $this->fromDate = $firstDay;
- $this->toDate = $lastDay;
- $this->applyFilters();
- }
- }
- public function selectMonth($month)
- {
- $this->selectedMonth = $month;
- $this->showMonthPicker = false;
- $this->updatedSelectedMonth($month);
- }
- public function toggleMonthPicker()
- {
- $this->showMonthPicker = !$this->showMonthPicker;
- }
- private function exportExcel($records)
- {
-
- $startTime = microtime(true);
- $spreadsheet = new Spreadsheet();
- $activeWorksheet = $spreadsheet->getActiveSheet();
- $activeWorksheet->setCellValue('A1', "Data");
- $activeWorksheet->setCellValue('B1', "Tipologia");
- $activeWorksheet->setCellValue('C1', "Causale");
- $activeWorksheet->setCellValue('D1', "Nominativo");
- $activeWorksheet->setCellValue('E1', "Stato");
- $activeWorksheet->setCellValue('F1', "Entrata");
- $activeWorksheet->setCellValue('G1', "Uscita");
- $activeWorksheet->setCellValue('H1', "Origine");
- $activeWorksheet->setCellValue('I1', "Destinazione");
- $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
- $activeWorksheet->getStyle('A1:J1')->getFill()
- ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
- ->getStartColor()->setARGB('FF0C6197');
- $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
- $idx = 2;
- foreach($records as $record)
- {
- if ($record->date != '')
- {
- $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
- $activeWorksheet->setCellValue('B' . $idx, $record->commercial ? 'Commerciale' : 'Non commerciale');
- $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
- $activeWorksheet->setCellValue('D' . $idx, $record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name);
- $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
- $activeWorksheet->setCellValue('F' . $idx, $record->type == 'IN' ? formatPrice($record->amount) : '');
- $activeWorksheet->setCellValue('G' . $idx, $record->type == 'OUT' ? formatPrice($record->amount) : '');
- $activeWorksheet->setCellValue('H' . $idx, $record->type == 'OUT' ? $record->origin : '');
- $activeWorksheet->setCellValue('I' . $idx, $record->type == 'IN' ? $record->destination : '');
- $activeWorksheet->setCellValue('J' . $idx, $record->payment_method->name);
- }
- else
- {
- $activeWorksheet->setCellValue('A' . $idx, "Totali");
- $activeWorksheet->setCellValue('B' . $idx, "");
- $activeWorksheet->setCellValue('C' . $idx, "");
- $activeWorksheet->setCellValue('D' . $idx, "");
- $activeWorksheet->setCellValue('E' . $idx, "");
- $activeWorksheet->setCellValue('F' . $idx, formatPrice($record->total_in));
- $activeWorksheet->setCellValue('G' . $idx, formatPrice($record->total_out));
- $activeWorksheet->setCellValue('H' . $idx, "");
- $activeWorksheet->setCellValue('I' . $idx, "");
- $activeWorksheet->setCellValue('J' . $idx, "");
- }
- $idx++;
- }
- $activeWorksheet->getColumnDimension('A')->setWidth(10);
- $activeWorksheet->getColumnDimension('B')->setWidth(30);
- $activeWorksheet->getColumnDimension('C')->setWidth(30);
- $activeWorksheet->getColumnDimension('D')->setWidth(30);
- $activeWorksheet->getColumnDimension('E')->setWidth(10);
- $activeWorksheet->getColumnDimension('F')->setWidth(10);
- $activeWorksheet->getColumnDimension('G')->setWidth(10);
- $activeWorksheet->getColumnDimension('H')->setWidth(20);
- $activeWorksheet->getColumnDimension('I')->setWidth(20);
- $activeWorksheet->getColumnDimension('J')->setWidth(30);
- $activeWorksheet->getStyle('A' . ($idx - 1) . ':J' . ($idx - 1))->getFont()->setBold(true);
- $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
- Log::info('exportWithData: Preparing to save file', [
- 'filename' => $filename,
- //'total_processing_time' => microtime(true) - $startTime,
- 'memory_before_save' => memory_get_usage(true)
- ]);
- try {
- $currentClient = session('currentClient', 'default');
- $tempPath = sys_get_temp_dir() . '/' . $filename;
- $writer = new Xlsx($spreadsheet);
- $writer->save($tempPath);
-
- unset($spreadsheet, $activeWorksheet, $writer);
- gc_collect_cycles();
- Log::info('exportWithData: Uploading to S3');
- $disk = Storage::disk('s3');
- $s3Path = $currentClient . '/prima_nota/' . $filename;
- $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
- if (!$disk->exists($primaNotaFolderPath)) {
- $disk->put($primaNotaFolderPath, '');
- }
- $uploadStart = microtime(true);
- $fileContent = file_get_contents($tempPath);
- $uploaded = $disk->put($s3Path, $fileContent, 'private');
- $uploadTime = microtime(true) - $uploadStart;
- if (!$uploaded) {
- throw new \Exception('Failed to upload file to Wasabi S3');
- }
- Log::info("Export completed successfully", [
- 'client' => $currentClient,
- 'path' => $s3Path,
- 'file_size' => filesize($tempPath),
- 'records_processed' => $recordsProcessed,
- 'upload_time' => $uploadTime,
- 'total_time' => microtime(true) - $startTime,
- 'memory_peak' => memory_get_peak_usage(true)
- ]);
- if (file_exists($tempPath)) {
- unlink($tempPath);
- }
- $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
- return redirect($downloadUrl);
- } catch (\Exception $e) {
- Log::error('Export S3 error - falling back to local', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'client' => session('currentClient', 'unknown'),
- 'filename' => $filename,
- 'records_processed' => $recordsProcessed ?? 0,
- 'time_elapsed' => microtime(true) - $startTime
- ]);
- // Fallback logic remains the same...
- $currentClient = session('currentClient', 'default');
- $clientFolder = storage_path('app/prima_nota/' . $currentClient);
- if (!is_dir($clientFolder)) {
- mkdir($clientFolder, 0755, true);
- Log::info("Created local client prima_nota folder: {$clientFolder}");
- }
- $localPath = $clientFolder . '/' . $filename;
- if (isset($tempPath) && file_exists($tempPath)) {
- rename($tempPath, $localPath);
- } else {
- $writer = new Xlsx($spreadsheet);
- $writer->save($localPath);
- unset($spreadsheet, $activeWorksheet, $writer);
- }
- gc_collect_cycles();
- Log::warning("Export saved locally due to S3 error", [
- 'client' => $currentClient,
- 'local_path' => $localPath,
- 'error' => $e->getMessage()
- ]);
- session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
- return response()->download($localPath)->deleteFileAfterSend();
- }
- }
- }
|