@php use App\Models\AccountingVoucherItem; // Step 1: Get IDs of sales and return vouchers $voucherIds = $vouchers->pluck('id'); $returnVoucherIds = $returnVouchers->pluck('id'); // Step 2: Fetch all voucher items for sales + returns in one go // Eager load stockItem and unit for related info $allItems = AccountingVoucherItem::with(['stockItem', 'unit']) ->whereIn('accounting_voucher_id', $voucherIds->merge($returnVoucherIds)) ->get() ->map(function ($item) use ($voucherIds) { // Step 3: Multiply by +1 if sales, -1 if return to subtract returns automatically $multiplier = $voucherIds->contains($item->accounting_voucher_id) ? 1 : -1; return (object) [ 'hsn_code' => $item->stockItem->hsn_code, 'uqc' => $item->unit->uqc, 'gst_per' => $item->gst_per, 'quantity' => $item->quantity * $multiplier, 'total' => $item->total * $multiplier, 'taxable_value' => $item->taxable_value * $multiplier, 'igst' => $item->igst * $multiplier, 'cgst' => $item->cgst * $multiplier, 'sgst' => $item->sgst * $multiplier, 'cess' => $item->cess * $multiplier, ]; }); // Step 4: Group by HSN code + UQC + GST percentage $groupedItems = $allItems->groupBy(function ($item) { return $item->hsn_code . '|' . $item->uqc . '|' . $item->gst_per; }); @endphp {{-- Step 5: Loop through each group and calculate totals --}} @foreach ($groupedItems as $groupKey => $items) @php [$hsn, $uqc, $gst] = explode('|', $groupKey); // Calculate sums after subtracting returns $quantity = $items->sum('quantity'); $totalValue = $items->sum('total'); $taxable = $items->sum('taxable_value'); $igst = $items->sum('igst'); $cgst = $items->sum('cgst'); $sgst = $items->sum('sgst'); $cess = $items->sum('cess'); $totalTax = $igst + $cgst + $sgst + $cess; // Skip rows with zero or negative quantity (optional) // if ($quantity <= 0) { // continue; // } @endphp @endforeach
HSN UQC Total Quantity Total Value Rate Taxable Value Integrated Tax Amount Central Tax Amount State/UT Tax Amount Cess Amount Total Tax
{{ $hsn }} {{ $uqc }} {{ round($quantity, 2) }} {{ round($totalValue, 2) }} {{ $gst ?? '0' }} {{ round($taxable, 2) }} {{ round($igst, 2) }} {{ round($cgst, 2) }} {{ round($sgst, 2) }} {{ round($cess, 2) }} {{ round($totalTax, 2) }}