Files
exchange-2.0/app/Classes/Modules/Bookings/ControllersLogic/DownloadBookingDocumentLogic.php
T
2022-03-02 03:22:47 +08:00

75 lines
2.2 KiB
PHP

<?php
namespace App\Classes\Modules\Bookings\ControllersLogic;
use ZipArchive;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\General\Abstracts\AbstractControllerLogic;
class DownloadBookingDocumentLogic
{
/**
* @return array
*/
protected function notification(): array
{
return [
'title' => 'Download Booking Document',
'message' => 'You have successfully retrieved a Booking Document'
];
}
/**
* DownloadBookingDocumentLogic constructor.
*/
public function __construct()
{
}
/**
* @param Request $request
* @return JsonResponse
* @throws MalformedRequestException
*/
public function execute(Request $request): JsonResponse
{
Auth::login(User::findOrFail(1));
$zip_file = $request->input('type').'.zip';
$attachment = storage_path('/documents/collections/'.$zip_file);
$zip = new ZipArchive();
if ($zip->open($attachment, ZIPARCHIVE::CREATE | ZipArchive::OVERWRITE)) {
$bookings = Booking::where('status', ApprovalStatus::COMPLETED)
->whereDate('updated_at', '>=', Carbon::parse($request->input('startDate')))
->whereDate('updated_at', '<=', Carbon::parse($request->input('endDate')))->get();
if (!count($bookings)) throw new MalformedRequestException('No available file to download');
foreach ($bookings as $booking) {
$file = $booking->documents()->where('document_type', $request->input('type'))->first()->files()->first();
$zip->addFile(Storage::disk('documents')->path($file->file->file_info->original->file), $booking->created_at->format('d_m_Y') . '_' . $booking->marking . '.pdf');
}
$zip->close();
return Storage::download('/documents/collections/'.$zip_file);
}
}
}