Fix N+1 query problem and missing sales_payments data in Table 1 logic
This commit is contained in:
@@ -38,19 +38,50 @@ class DailySalePaymentReportModuleController extends Controller
|
|||||||
'sales.due_amount'
|
'sales.due_amount'
|
||||||
)->get();
|
)->get();
|
||||||
|
|
||||||
|
$saleIds = $sales->pluck('id')->all();
|
||||||
|
|
||||||
|
// 1. Get all payments for these sales (avoids N+1 query problem)
|
||||||
|
$paymentsTable = DB::table('payments')
|
||||||
|
->whereIn('sale_id', $saleIds)
|
||||||
|
->whereDate('created_at', $report_date)
|
||||||
|
->get(['id', 'sale_id', 'amount', 'payment_option_id']);
|
||||||
|
|
||||||
|
$usedPaymentIds = $paymentsTable->pluck('id')->all();
|
||||||
|
|
||||||
|
// 2. Get additional payments from sales_payments table
|
||||||
|
$salesPaymentsTable = DB::table('sales_payments')
|
||||||
|
->whereIn('sale_id', $saleIds)
|
||||||
|
->whereDate('created_at', $report_date)
|
||||||
|
->where(function ($q) use ($usedPaymentIds) {
|
||||||
|
$q->whereNull('payment_id');
|
||||||
|
if (!empty($usedPaymentIds)) {
|
||||||
|
$q->orWhereNotIn('payment_id', $usedPaymentIds);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
->get(['id', 'sale_id', 'amount', 'payment_id']);
|
||||||
|
|
||||||
|
$linkedPaymentIds = $salesPaymentsTable->whereNotNull('payment_id')->pluck('payment_id')->unique();
|
||||||
|
|
||||||
|
$linkedOptionMap = DB::table('payments')
|
||||||
|
->whereIn('id', $linkedPaymentIds)
|
||||||
|
->pluck('payment_option_id', 'id');
|
||||||
|
|
||||||
$sales_data = [];
|
$sales_data = [];
|
||||||
foreach ($sales as $sale) {
|
foreach ($sales as $sale) {
|
||||||
// Get payments ONLY made on the report_date
|
|
||||||
$payments = DB::table('payments')
|
|
||||||
->where('sale_id', $sale->id)
|
|
||||||
->whereDate('created_at', $report_date)
|
|
||||||
->select('payment_option_id', DB::raw('SUM(amount) as total_amount'))
|
|
||||||
->groupBy('payment_option_id')
|
|
||||||
->get();
|
|
||||||
|
|
||||||
$methodTotals = [];
|
$methodTotals = [];
|
||||||
foreach ($payments as $payment) {
|
|
||||||
$methodTotals[$payment->payment_option_id] = $payment->total_amount;
|
// Sum from payments table
|
||||||
|
foreach ($paymentsTable->where('sale_id', $sale->id) as $p) {
|
||||||
|
$optionId = $p->payment_option_id;
|
||||||
|
$methodTotals[$optionId] = ($methodTotals[$optionId] ?? 0) + $p->amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sum from sales_payments table
|
||||||
|
foreach ($salesPaymentsTable->where('sale_id', $sale->id) as $sp) {
|
||||||
|
$optionId = $sp->payment_id ? ($linkedOptionMap[$sp->payment_id] ?? null) : null;
|
||||||
|
if ($optionId) {
|
||||||
|
$methodTotals[$optionId] = ($methodTotals[$optionId] ?? 0) + $sp->amount;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$sales_data[] = (object) [
|
$sales_data[] = (object) [
|
||||||
|
|||||||
Reference in New Issue
Block a user