Files
Verde-Web/app/Http/Controllers/Api/V1/Me/MySalesController.php

80 lines
2.3 KiB
PHP

<?php
namespace App\Http\Controllers\Api\V1\Me;
use App\Http\Controllers\Api\V1\ApiController;
use App\Models\Household;
use App\Models\StoreSale;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class MySalesController extends ApiController
{
/**
* Get the household associated with the authenticated user.
*/
private function getHousehold(): ?Household
{
return Household::where('head_user_id', auth()->id())
->orWhereHas('members', function ($q) {
$q->where('user_id', auth()->id());
})
->first();
}
/**
* List sales history for the user's household.
*/
public function index(): JsonResponse
{
$household = $this->getHousehold();
if (!$household) {
return $this->ok([], 'No household associated with this account.');
}
$sales = StoreSale::where('household_id', $household->id)
->with('store')
->latest('sold_at')
->paginate(15);
return $this->ok(
$sales->map(fn($s) => [
'id' => $s->id,
'store_name' => $s->store?->business_name ?? 'Verde Partner Store',
'quantity' => $s->quantity,
'retail_price_pesos' => number_format($s->retail_price_centavos / 100, 2),
'sold_at' => $s->sold_at?->toIso8601String() ?? $s->created_at->toIso8601String(),
'receipt_url' => route('api.v1.me.sales.receipt', $s->id),
]),
null,
[
'page' => $sales->currentPage(),
'per_page' => $sales->perPage(),
'total' => $sales->total(),
]
);
}
/**
* Download a PDF receipt for a specific sale.
*/
public function downloadReceipt(StoreSale $sale): Response
{
$household = $this->getHousehold();
if (!$household || $sale->household_id !== $household->id) {
abort(403, 'Unauthorized access to this receipt.');
}
$sale->load(['store', 'household.head', 'household.barangay']);
$pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('pdfs.receipt', [
'sale' => $sale
]);
return $pdf->download("receipt-{$sale->id}.pdf");
}
}