|
|
@@ -83,14 +83,22 @@ class Record extends Component
|
|
|
$this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
|
|
|
}
|
|
|
|
|
|
-
|
|
|
- private function generateExportData($fromDate, $toDate)
|
|
|
+ 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.*',
|
|
|
@@ -101,13 +109,6 @@ class Record extends Component
|
|
|
'records_rows.note',
|
|
|
'records_rows.when',
|
|
|
'records_rows.vat_id',
|
|
|
- 'records_rows.imponibile',
|
|
|
- 'records_rows.aliquota_iva',
|
|
|
- 'records_rows.imposta',
|
|
|
- 'records_rows.divisa',
|
|
|
- 'records_rows.numero_linea',
|
|
|
- 'records_rows.prezzo_unitario',
|
|
|
- 'records_rows.quantita',
|
|
|
'records_rows.created_at as row_created_at',
|
|
|
'records_rows.updated_at as row_updated_at'
|
|
|
)
|
|
|
@@ -127,6 +128,7 @@ class Record extends Component
|
|
|
});
|
|
|
});
|
|
|
|
|
|
+ Log::info('generateExportDataAndTotals: Applying causal filters');
|
|
|
if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
|
|
|
$causals = array();
|
|
|
foreach ($this->filterCausals as $z) {
|
|
|
@@ -141,74 +143,133 @@ class Record extends Component
|
|
|
}
|
|
|
}
|
|
|
$datas->whereIn('causal_id', $causals);
|
|
|
+ Log::info('generateExportDataAndTotals: Causal filters applied', ['causal_count' => count($causals)]);
|
|
|
}
|
|
|
+
|
|
|
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) {
|
|
|
- $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
|
|
|
- $paymentCheck = $data->payment_method->money;
|
|
|
+ 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)
|
|
|
+ ]);
|
|
|
+ }
|
|
|
|
|
|
- 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;
|
|
|
- }
|
|
|
+ try {
|
|
|
+ $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
|
|
|
+ $paymentCheck = $data->payment_method->money;
|
|
|
|
|
|
- $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
|
|
|
- $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
|
|
|
+ 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;
|
|
|
+ }
|
|
|
|
|
|
- $nominativo = '';
|
|
|
- if ($data->type == "IN") {
|
|
|
- if ($data->member) {
|
|
|
- $nominativo = $data->member->last_name . " " . $data->member->first_name;
|
|
|
+ // CALCULATE TOTALS HERE (in the same loop)
|
|
|
+ if (!$data->deleted) {
|
|
|
+ $exportTotals[$data->payment_method->name][$data->type] += $amount;
|
|
|
}
|
|
|
- } else {
|
|
|
- if ($data->supplier) {
|
|
|
- $nominativo = $data->supplier->name;
|
|
|
+
|
|
|
+ $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;
|
|
|
+ $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] = [];
|
|
|
+ }
|
|
|
|
|
|
- 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;
|
|
|
|
|
|
- $groupedData[$groupKey]['amount'] += $amount;
|
|
|
- $causalsCount[$groupKey][$causalCheck->getTree()] = true;
|
|
|
+ if (!empty($data->note)) {
|
|
|
+ $groupedData[$groupKey]['notes'][] = $data->note;
|
|
|
+ }
|
|
|
|
|
|
- if (!empty($data->note)) {
|
|
|
- $groupedData[$groupKey]['notes'][] = $data->note;
|
|
|
+ if ($data->deleted) {
|
|
|
+ $groupedData[$groupKey]['deleted'] = true;
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
- 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);
|
|
|
+
|
|
|
foreach ($groupedData as $groupKey => $group) {
|
|
|
$causalsInGroup = array_keys($causalsCount[$groupKey]);
|
|
|
|
|
|
@@ -227,17 +288,27 @@ class Record extends Component
|
|
|
}
|
|
|
|
|
|
$exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
|
|
|
-
|
|
|
- if (!isset($exportTotals[$group['payment_method']])) {
|
|
|
- $exportTotals[$group['payment_method']]["IN"] = 0;
|
|
|
- $exportTotals[$group['payment_method']]["OUT"] = 0;
|
|
|
- }
|
|
|
-
|
|
|
- if (!$group['deleted'])
|
|
|
- $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
|
|
|
}
|
|
|
|
|
|
- return $exportRecords;
|
|
|
+ $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)
|
|
|
@@ -256,9 +327,6 @@ class Record extends Component
|
|
|
'records_rows.note',
|
|
|
'records_rows.when',
|
|
|
'records_rows.vat_id',
|
|
|
- 'records_rows.imponibile',
|
|
|
- 'records_rows.aliquota_iva',
|
|
|
- 'records_rows.imposta'
|
|
|
)
|
|
|
->join('records_rows', 'records.id', '=', 'records_rows.record_id')
|
|
|
->whereBetween('date', [$fromDate, $toDate])
|
|
|
@@ -470,9 +538,6 @@ class Record extends Component
|
|
|
'records_rows.note',
|
|
|
'records_rows.when',
|
|
|
'records_rows.vat_id',
|
|
|
- 'records_rows.imponibile',
|
|
|
- 'records_rows.aliquota_iva',
|
|
|
- 'records_rows.imposta'
|
|
|
)
|
|
|
->join('records_rows', 'records.id', '=', 'records_rows.record_id')
|
|
|
->whereBetween('date', [$this->appliedFromDate, $this->appliedToDate])
|
|
|
@@ -672,37 +737,87 @@ class Record extends Component
|
|
|
public function exportWithDateRange()
|
|
|
{
|
|
|
|
|
|
- $this->isExporting = true;
|
|
|
- $this->emit('$refresh'); // This forces Livewire to re-render
|
|
|
+ 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')
|
|
|
+ ]);
|
|
|
|
|
|
- // Add a small delay to allow the view to update
|
|
|
+ $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 {
|
|
|
- $exportRecords = $this->generateExportData($this->exportFromDate, $this->exportToDate);
|
|
|
- $exportTotals = $this->generateExportTotals($this->exportFromDate, $this->exportToDate);
|
|
|
+ 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'];
|
|
|
+
|
|
|
+ $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) {
|
|
|
- // Dispatch job to background queue
|
|
|
+ Log::info('Export: Dispatching to background job');
|
|
|
$this->dispatchExportJob($exportRecords, $exportTotals);
|
|
|
+ Log::info('Export: Job dispatched successfully');
|
|
|
} else {
|
|
|
- // Direct download (synchronous)
|
|
|
- return $this->exportWithData($exportRecords, $exportTotals);
|
|
|
+ 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;
|
|
|
- Log::error('Export error: ' . $e->getMessage());
|
|
|
|
|
|
if ($this->sendViaEmail) {
|
|
|
$this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
|
|
|
@@ -710,11 +825,55 @@ class Record extends Component
|
|
|
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->filterMember != null && $this->filterMember > 0) {
|
|
|
+ $query->where('member_id', $this->filterMember);
|
|
|
+ }
|
|
|
+
|
|
|
+ return $query->count();
|
|
|
+ }
|
|
|
|
|
|
private function getMemberName($memberId)
|
|
|
{
|
|
|
@@ -829,33 +988,54 @@ class Record extends Component
|
|
|
|
|
|
function export()
|
|
|
{
|
|
|
- $exportRecords = $this->generateExportData($this->appliedFromDate, $this->appliedToDate);
|
|
|
- $exportTotals = $this->generateExportTotals($this->appliedFromDate, $this->appliedToDate);
|
|
|
+ $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', "Causale");
|
|
|
$activeWorksheet->setCellValue('C1', "Dettaglio");
|
|
|
$activeWorksheet->setCellValue('D1', "Nominativo");
|
|
|
$activeWorksheet->setCellValue('E1', "Stato");
|
|
|
|
|
|
+ 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)) {
|
|
|
@@ -865,6 +1045,7 @@ class Record extends Component
|
|
|
$idx++;
|
|
|
}
|
|
|
|
|
|
+ Log::info('exportWithData: Setting sub-headers');
|
|
|
$idx = 0;
|
|
|
$activeWorksheet->setCellValue('A2', "");
|
|
|
$activeWorksheet->setCellValue('B2', "");
|
|
|
@@ -900,75 +1081,119 @@ class Record extends Component
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ 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 ($recordsArray as $recordsBatch) {
|
|
|
foreach ($recordsBatch as $causal => $record) {
|
|
|
- $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;
|
|
|
-
|
|
|
- $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');
|
|
|
+ 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
|
|
|
+ ]);
|
|
|
}
|
|
|
|
|
|
- $idx = 0;
|
|
|
- foreach ($this->payments as $p) {
|
|
|
- if ($idx >= count($letters) - 1) {
|
|
|
- break;
|
|
|
+ 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');
|
|
|
}
|
|
|
|
|
|
- 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++;
|
|
|
+ $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++;
|
|
|
+ $count++;
|
|
|
+ $recordsProcessed++;
|
|
|
|
|
|
- if ($recordsProcessed % 500 === 0) {
|
|
|
- gc_collect_cycles();
|
|
|
+ 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;
|
|
|
|
|
|
@@ -1020,8 +1245,10 @@ class Record extends Component
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ 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);
|
|
|
@@ -1032,20 +1259,35 @@ class Record extends Component
|
|
|
}
|
|
|
|
|
|
$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';
|
|
|
@@ -1054,18 +1296,23 @@ class Record extends Component
|
|
|
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("Prima Nota exported to Wasabi", [
|
|
|
+ Log::info("Export completed successfully", [
|
|
|
'client' => $currentClient,
|
|
|
'path' => $s3Path,
|
|
|
- 'size' => filesize($tempPath),
|
|
|
- 'records_processed' => $recordsProcessed
|
|
|
+ '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)) {
|
|
|
@@ -1075,13 +1322,16 @@ class Record extends Component
|
|
|
$downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
|
|
|
return redirect($downloadUrl);
|
|
|
} catch (\Exception $e) {
|
|
|
- Log::error('Error exporting Prima Nota to Wasabi S3', [
|
|
|
+ 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
|
|
|
+ '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);
|
|
|
|
|
|
@@ -1102,14 +1352,13 @@ class Record extends Component
|
|
|
|
|
|
gc_collect_cycles();
|
|
|
|
|
|
- Log::warning("Prima Nota saved locally due to S3 error", [
|
|
|
+ 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();
|
|
|
}
|
|
|
}
|