migrations and models
This commit is contained in:
81
app/Http/Controllers/InvoiceController.php
Normal file
81
app/Http/Controllers/InvoiceController.php
Normal file
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\RoomAvailability;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class InvoiceController extends Controller
|
||||
{
|
||||
|
||||
public function generate(Request $request, $bookingId)
|
||||
{
|
||||
$booking = Booking::findOrFail($bookingId);
|
||||
|
||||
if ($booking->status === 'cancelled') {
|
||||
return response()->json(['error' => 'Cannot generate invoice for cancelled booking'], 400);
|
||||
}
|
||||
|
||||
$totalAmount = 0;
|
||||
$currentDate = new \DateTime($booking->check_in);
|
||||
$endDate = new \DateTime($booking->check_out);
|
||||
|
||||
while ($currentDate < $endDate) {
|
||||
$date = $currentDate->format('Y-m-d');
|
||||
|
||||
$availability = RoomAvailability::where('room_type_id', $booking->room_type_id)
|
||||
->where('date', $date)
|
||||
->first();
|
||||
|
||||
$price = $availability && $availability->price_override !== null
|
||||
? $availability->price_override
|
||||
: $booking->roomType->base_price;
|
||||
|
||||
$totalAmount += $price;
|
||||
|
||||
$currentDate->modify('+1 day');
|
||||
}
|
||||
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$invoice = Invoice::create([
|
||||
'booking_id' => $booking->id,
|
||||
'total_amount' => $totalAmount,
|
||||
'status' => 'pending',
|
||||
]);
|
||||
|
||||
|
||||
$pdfPath = $this->generatePdf($invoice);
|
||||
|
||||
if ($pdfPath) {
|
||||
$invoice->update(['pdf_path' => $pdfPath]);
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return response()->json($invoice, 201);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private function generatePdf($invoice)
|
||||
{
|
||||
|
||||
$pdf = \PDF::loadView('invoices.show', compact('invoice'));
|
||||
|
||||
$fileName = "invoice_{$invoice->id}.pdf";
|
||||
$path = "invoices/{$fileName}";
|
||||
|
||||
Storage::put($path, $pdf->output());
|
||||
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user