82 lines
2.3 KiB
PHP
82 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 Barryvdh\DomPDF\Facade\Pdf;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Response;
|
|
|
|
use Illuminate\Support\Facades\URL;
|
|
|
|
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();
|
|
|
|
$sales = StoreSale::where(function ($q) use ($household) {
|
|
if ($household) {
|
|
$q->where('household_id', $household->id);
|
|
}
|
|
$q->orWhere('user_id', auth()->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' => URL::temporarySignedRoute(
|
|
'api.v1.me.sales.receipt',
|
|
now()->addHours(24),
|
|
['sale' => $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
|
|
{
|
|
|
|
$sale->load(['store', 'household.head', 'household.barangay']);
|
|
|
|
$pdf = Pdf::loadView('pdfs.receipt', [
|
|
'sale' => $sale,
|
|
]);
|
|
|
|
return $pdf->download("receipt-{$sale->id}.pdf");
|
|
}
|
|
}
|