first commit

This commit is contained in:
ExtraNetwork
2026-05-12 17:04:54 +03:00
commit e5c4b6aa13
1425 changed files with 284735 additions and 0 deletions

View File

@@ -0,0 +1,356 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\PropertyBookingEngineService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\BookingEngine\V1\SearchController;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class BestAvailableRateSyncService extends Command
{
protected $signature = 'cron:bar-sync-service {--property_id=}';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyBookingEngineService $propertyBookingEngineService,
PropertyRoomRatePriceService $propertyRoomRatePriceService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyBookingEngineService = $propertyBookingEngineService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => 2],//Channex
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'with' => ['property']
];
$howManyDays = 90;
if (!is_null($this->option('property_id'))) {
$requestParam['criteria'][] = ['field' => 'property_id', 'condition' => '=', 'value' => $this->option('property_id')];
$howManyDays = 6 * 30;
}
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
$channelManagerPropertyMapping = $channelManagerPropertyMapping['status'] == 'success' ? $channelManagerPropertyMapping['data'] : [];
foreach ($channelManagerPropertyMapping as $propertyMapping) {
if ($propertyMapping['property']['status'] != 1) {
$this->error(date('Y-m-d H:i:s') . ' : ' . $propertyMapping['property']['name']);
continue;
}
$response = ['status' => false, 'message' => ''];
try {
$propertyRoomRateChannelMappingParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => 5],//Kanal Yöentimi
['field' => 'property_id', 'condition' => '=', 'value' => $propertyMapping['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$propertyRoomRateChannelMapping = $this->propertyRoomRateChannelMappingService->select($propertyRoomRateChannelMappingParam);
$propertyRoomRateChannelMapping = $propertyRoomRateChannelMapping['status'] == 'success' ? $propertyRoomRateChannelMapping['data'] : [];
$propertyRoomRateChannelMappingCollect = collect($propertyRoomRateChannelMapping);
$propertyBookingEngineParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyMapping['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => 1],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel', 'property.propertyBookingEngineToken'],
'firstRow' => 1
];
$propertyBookingEngine = $this->propertyBookingEngineService->select($propertyBookingEngineParam, ['id', 'property_id', 'channel_id', 'token']);
$propertyBookingEngine = $propertyBookingEngine['status'] == 'success' ? $propertyBookingEngine['data'] : [];
if (empty($propertyBookingEngine)) {
$this->info(date('Y-m-d H:i:s') . ' : None Booking Engine!');
continue;
}
$searchController = App::make("App\Http\Controllers\BookingEngine\V1\SearchController");
$roomRateFormatted = [];
$today = Carbon::now()->startOfDay()->toDateTimeString();
if (!is_null($this->option('property_id'))) {
$today = Carbon::now()->startOfDay()->toDateTimeString();
} else {
//00:00 04:00 08:00 12:00 16:00 20:00
$processHour = (integer)Carbon::now()->format('H');
switch ($processHour) {
case ($processHour >= 0 && $processHour <= 2) :
case ($processHour > 8 && $processHour <= 10):
case ($processHour > 16 && $processHour <= 18):
$today = Carbon::now()->startOfDay()->toDateTimeString();
break;
case ($processHour > 2 && $processHour <= 4) :
case ($processHour > 10 && $processHour <= 12):
case ($processHour > 18 && $processHour <= 20) :
$today = Carbon::now()->startOfDay()->addDays($howManyDays)->toDateTimeString();
break;
case ($processHour > 4 && $processHour <= 6) :
case ($processHour > 12 && $processHour <= 14):
case ($processHour > 20 && $processHour <= 22) :
$today = Carbon::now()->startOfDay()->addDays($howManyDays * 2)->toDateTimeString();
break;
case ($processHour > 6 && $processHour <= 8) :
case ($processHour > 14 && $processHour <= 16):
case ($processHour > 22 && $processHour < 24) :
$today = Carbon::now()->startOfDay()->addDays($howManyDays * 3)->toDateTimeString();
break;
}
}
for ($i = 0; $i < $howManyDays; $i++) {
$checkIn = Carbon::parse($today)->addDays($i)->toDateString();
$checkOut = Carbon::parse($checkIn)->addDay()->toDateString();
$searchRequestJson = [
'date' => [
'checkIn' => $checkIn,
'checkOut' => $checkOut,
],
'rooms' => [
[
'adults' => 2,
'children' => 0,
'age' => [],
]
],
'property' => [],
'ipAddress' => '185.137.215.118',
'isMobile' => null,
'noneCacheSearch' => true,
'min_stay_disabled' => true
];
$requestCreate = Request::create(null, null, [], [], [], [], json_encode($searchRequestJson));
$requestCreate->headers->set('channelId', '1');
$requestCreate->headers->set('bookingEnginePropertyId', $propertyMapping['property_id']);
$requestCreate->headers->set('channelToken', $propertyBookingEngine['channel']['token']);
$requestCreate->headers->set('bookingEngineToken', $propertyBookingEngine['property']['property_booking_engine_token']['token']);
$search = $searchController->search($requestCreate);
$search = json_decode(json_encode($search), 1);
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn);
if ($search['original']['status'] == 200) {
if (empty($search['original']['data']['properties'])) {
//Rate Stop or Price 0 Case
foreach ($propertyRoomRateChannelMapping as $roomRateChannelMapping) {
$referenceRoomRateMapping = $propertyRoomRateChannelMappingCollect
->where('property_room_rate_mapping.room_id', $roomRateChannelMapping['property_room_rate_mapping']['room_id'])
->where('property_room_rate_mapping.property_room_rate.name', 'Best Available Rate')->first();
if (!empty($referenceRoomRateMapping)) {
$roomRateKey = '1|' . $referenceRoomRateMapping['property_room_rate_mapping']['room_id'] . '|' . $referenceRoomRateMapping['property_room_rate_mapping']['id'] . '|' . $checkIn;
$roomRateFormatted[$roomRateKey] = [
'setup_type_id' => '1',
'room_id' => $referenceRoomRateMapping['property_room_rate_mapping']['room_id'],
'room_rate_mapping_id' => $referenceRoomRateMapping['property_room_rate_mapping']['id'],
'date' => $checkIn,
'amount' => 0
];
}
}
//Rate Stop or Price 0 Case
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
$property = reset($search['original']['data']['properties']);
if (empty($property)) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
if (!isset($property['availabilities'])) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
$propertyAvailability = reset($property['availabilities']);
if (empty($propertyAvailability)) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
/*dd($propertyAvailability['rooms']);
$propertyAvailabilityRoom = reset($propertyAvailability['rooms']);
if (empty($propertyAvailability)) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
$propertyAvailabilityRoom['rates'] = collect($propertyAvailabilityRoom['rates'])->sortBy('total')->toArray();
*/
foreach ($propertyAvailability['rooms'] as $roomId => $room) {
foreach ($room['rates'] as $roomRateInnerKey => $roomRate) {
/*$propertyAvailabilityRoomRate = reset($propertyAvailabilityRoom['rates']);
if (empty($propertyAvailabilityRoomRate)) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}*/
$propertyAvailabilityRoomRatePrices = reset($roomRate['requestedRoomPrice']);
if (empty($propertyAvailabilityRoomRatePrices)) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
$propertyAvailabilityRoomRatePrice = reset($propertyAvailabilityRoomRatePrices['prices']);
if (empty($propertyAvailabilityRoomRatePrice)) {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
continue;
}
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['id'] . ' - ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - ' . $propertyAvailabilityRoomRatePrice['total']);
$referenceRoomRateMapping = $propertyRoomRateChannelMappingCollect
->where('property_room_rate_mapping.room_id', $roomId)
->where('property_room_rate_mapping.property_room_rate.name', 'Best Available Rate')->first();
if (empty($referenceRoomRateMapping)) {
$this->info(date('Y-m-d H:i:s') . ' : None Best Available Rate! PropertyId: ' . $propertyMapping['property_id'] . ' Room: ' . $room['name']);
continue;
}
/*if($referenceRoomRateMapping['property_room_rate_mapping']['id'] != 6003) {
continue;
}*/
$roomRateKey = '1|' . $referenceRoomRateMapping['property_room_rate_mapping']['room_id'] . '|' . $referenceRoomRateMapping['property_room_rate_mapping']['id'] . '|' . $checkIn;
if (!isset($roomRateFormatted[$roomRateKey])) {
$roomRateFormatted[$roomRateKey] = [
'setup_type_id' => '1',
'room_id' => $referenceRoomRateMapping['property_room_rate_mapping']['room_id'],
'room_rate_mapping_id' => $referenceRoomRateMapping['property_room_rate_mapping']['id'],
'date' => $checkIn,
'amount' => $propertyAvailabilityRoomRatePrice['total']
];
}
if ($propertyAvailabilityRoomRatePrice['total'] < $roomRateFormatted[$roomRateKey]['amount']) {
$roomRateFormatted[$roomRateKey]['amount'] = $propertyAvailabilityRoomRatePrice['total'];
}
}
}
} else {
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['name'] . ' - ' . $checkIn . ' - NONE');
}
}
$requestParams = [
'property_id' => $propertyMapping['property_id'],
'channel_id' => 5,
'availability' => [],
'user_id' => 1,
'rates' => $roomRateFormatted
];
$roomRateUpdate = $this->propertyRoomRatePriceService->roomRateUpdate($requestParams);
if ($roomRateUpdate['status'] != 'success') {
throw new ApiErrorException($roomRateUpdate['message']);
}
$response['status'] = true;
$this->info(date('Y-m-d H:i:s') . ' : ' . $propertyBookingEngine['property']['id'] . ' : ' . $propertyBookingEngine['property']['name'] . ' - Today: ' . $today . ' - OK');
Log::debug($propertyBookingEngine['property']['id'] . ' : ' . $propertyBookingEngine['property']['name'] . ' - Today: ' . $today . ' - OK');
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$this->error(date('Y-m-d H:i:s') . ' : ' . $response['message']);
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerBookingService;
use App\Exceptions\ApiErrorException;
use App\Models\Booking;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class MetaCancellationService extends Command
{
protected $signature = 'cron:meta-cancellation-service';
protected $description = '';
protected $channelService;
public function __construct(
Mailer $mailer,
ChannelManagerBookingService $channelManagerBookingService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelManagerBookingService = $channelManagerBookingService;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
$today = Carbon::now()->startOfDay()->toDateString();
if(!Carbon::parse($today)->isLastOfMonth()) {
$this->alert(date('Y-m-d H:i:s') . ' : Not Today!');
return false;
}
$fistDayOfMonth = Carbon::parse($today)->startOfMonth()->toDateString();
$lastDayOfMonth = Carbon::parse($today)->addMonth()->startOfMonth()->toDateString();
$cancellationBooking = Booking::where('channel_id', 1)
->where('status', 0)
->where('checkout_date', '>', $fistDayOfMonth)
->where('checkout_date', '<', $lastDayOfMonth)
//->where('id', 68690)
->with('channelManagerBooking')
->with('bookingRoom')
->get();
//11 - Trivago
$cancellationBooking = $cancellationBooking ? $cancellationBooking->toArray() : [];
foreach ($cancellationBooking as $booking) {
try {
if (empty($booking['channel_manager_booking'])) {
$this->line(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['id']);
continue;
}
$channelBookingCheck = collect($booking['channel_manager_booking'])
->where('channel_manager_id', 11)
->where('type', 'Booking')
->where('is_pushed', 1)
->isEmpty();
if ($channelBookingCheck) {
$this->line(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['id']);
continue;
}
$channelCancelCheck = collect($booking['channel_manager_booking'])
->where('channel_manager_id', 11)
->where('type', 'Cancel')
->where('is_pushed', 1)
->isEmpty();
if (!$channelCancelCheck) {
$this->line(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['id']);
continue;
}
$channelManagerBookingCreateParam = [
'property_id' => $booking['property_id'],
'booking_id' => $booking['id'],
'channel_manager_id' => 11,
'type' => 'Cancel',
];
$this->channelManagerBookingService->create($channelManagerBookingCreateParam);
$this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['id']);
} catch (ApiErrorException $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
class PropertyBookingSyncService extends Command
{
protected $signature = 'cron:propertybooking-sync-service';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer,
PropertyRoomService $propertyRoomService,
PropertyRoomRatePriceService $propertyRoomRatePriceService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->propertyRoomService = $propertyRoomService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
}
public function handle()
{
$sourcePath = 'C:\www\api.extranetwork.com\app\Console\Commands\ChannelManager\akgun.xlsx';
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load($sourcePath);
$sheet = $spreadsheet->getSheet($spreadsheet->getFirstSheetIndex());
$rows = $sheet->toArray();
$rowKey = 0;
foreach ($rows as $row) {
$rowKey++;
if($rowKey < 3) {
continue;
}
dd($row);
}
//dd(file_exists($sourcePath));
$this->info(date('Y-m-d H:i:s') . ' : Start');
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,222 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerService;
use App\Core\Service\PropertyRoomAvailabilityQueueService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PropertyChannelSyncService extends Command
{
protected $signature = 'cron:propertychannel-sync-service';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer,
PropertyRoomService $propertyRoomService,
PropertyRoomRatePriceService $propertyRoomRatePriceService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->propertyRoomService = $propertyRoomService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
}
public function handle()
{
$sourceChannelId = 1; //Booking Engine
$targetChannelId = 5; //Channel Manager
$propertyIdList = [1098];
$this->info(date('Y-m-d H:i:s') . ' : Start');
foreach ($propertyIdList as $propertyId) {
$this->info(date('Y-m-d H:i:s') . ' - AVAILABILITY START : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
$isPropertyRoomAvailabilityUpdate = false;
DB::beginTransaction();
try {
$propertyRoomAvailabilityUpdateQuery = <<<BUR
UPDATE property_room_availability SET status = 1 WHERE property_id = {$propertyId} AND date >= curdate() AND channel_id IS NULL AND status = 1;
BUR;
$propertyRoomAvailabilityUpdate = DB::select(DB::raw($propertyRoomAvailabilityUpdateQuery));
$isPropertyRoomAvailabilityUpdate = true;
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (\Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
if ($isPropertyRoomAvailabilityUpdate) {
DB::commit();
$this->info(date('Y-m-d H:i:s') . ' - AVAILABILITY SUCCESS : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
} else {
DB::rollBack();
$this->info(date('Y-m-d H:i:s') . ' - AVAILABILITY ERROR : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
}
$this->info(date('Y-m-d H:i:s') . ' - AVAILABILITY FINISHED : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
$this->info(date('Y-m-d H:i:s') . ' - RATE START : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
$requestParams = [
'property_id' => $propertyId,
'channel_id' => $sourceChannelId,
'start_date' => Carbon::now()->toDateString(),
'end_date' => Carbon::now()->addMonths(6)->subDay()->toDateString(),
//'start_date' => '2023-03-01',
//'end_date' => '2024-01-01',
];
$propertyRoomType = $this->propertyRoomService->getPropertyRoomInventory($requestParams);
if ($propertyRoomType['status'] != 'success') {
throw new ApiErrorException($propertyRoomType['message']);
}
$propertyRoomType = $propertyRoomType['data'];
$propertyRoomRateAvailability = collect($propertyRoomType);
$roomRates = [];
foreach ($propertyRoomRateAvailability as $room) {
foreach ($room['property_room_rate_mapping'] as $roomRateMapping) {
foreach ($room['room_availability'] as $date => $roomAvailability) {
$roomRates[$room['id']]['availability'][$date] = $roomAvailability['value'];
}
$roomRates[$room['id']]['rate'][$roomRateMapping['id']] = [
'roomName' => $room['name'],
'roomRateName' => $roomRateMapping['name'],
'currencyCode' => $roomRateMapping['currency_code'],
];
$roomRatePrices = reset($roomRateMapping['prices']);
foreach ($roomRatePrices['price'] as $date => $roomRatePrice) {
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['price'][$date] = $roomRatePrice['value'];
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['stopSell'][$date] = $roomRatePrice['stop_sell'];
}
foreach ($roomRatePrices['stop_sell'] as $date => $stopSell) {
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['stopSell'][$date] = $stopSell['value'];
}
foreach ($roomRatePrices['min_stay'] as $date => $minStay) {
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['minStay'][$date] = $minStay['value'];
}
}
}
$roomRateFormatted = [];
foreach ($roomRates as $roomId => $roomRateMapping) {
foreach ($roomRateMapping['rate'] as $roomRateMappingId => $roomRate) {
foreach ($roomRate['price'] as $date => $price) {
$roomRateKey = '1|' . $roomId . '|' . $roomRateMappingId . '|' . $date;
$roomRateFormatted[$roomRateKey] = [
'setup_type_id' => '1',
'room_id' => $roomId,
'room_rate_mapping_id' => $roomRateMappingId,
'date' => $date,
'amount' => is_null($price) ? 0 : $price,
'min_stay' => $roomRate['minStay'][$date],
'stop_sell' => $roomRate['stopSell'][$date],
];
}
}
}
$isPropertyRoomRateUpdate = false;
DB::beginTransaction();
try {
$roomRateFormattedChunked = array_chunk($roomRateFormatted, 1000);
foreach ($roomRateFormattedChunked as $roomRateFormattedParsed) {
$requestParams = [
'property_id' => $propertyId,
'channel_id' => $targetChannelId,
'rates' => $roomRateFormattedParsed
];
$roomRateUpdate = $this->propertyRoomRatePriceService->roomRateUpdate($requestParams);
if ($roomRateUpdate['status'] != 'success') {
throw new ApiErrorException($roomRateUpdate['message']);
}
}
$isPropertyRoomRateUpdate = true;
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (\Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
if ($isPropertyRoomRateUpdate) {
DB::commit();
$this->info(date('Y-m-d H:i:s') . ' - RATE SUCCESS : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
} else {
DB::rollBack();
$this->info(date('Y-m-d H:i:s') . ' - RATE ERROR : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
}
$this->info(date('Y-m-d H:i:s') . ' - RATE FINISHED : Property: ' . $propertyId . ' : SourceChannelId: ' . $sourceChannelId . ' : TargetChannelId: ' . $targetChannelId);
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,344 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Exceptions\ApiErrorException;
use App\Models\PropertyMeta;
use App\Models\PropertyMetaRoomRate;
use App\Models\PropertyMetaRoomRatePrice;
use App\Models\PropertyRoomRatePrice;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PropertyMetaRoomRatePriceService extends Command
{
protected $signature = 'cron:propertymeta-roomrateprice-service {--property_id=}';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer
)
{
parent::__construct();
$this->mailer = $mailer;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
if (!is_null($this->option('property_id'))) {
$propertyMeta = PropertyMeta::where('status', 1)->where('property_id', $this->option('property_id'))->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'cancellation_policy', 'adult_policy', 'child_policy', 'promotion', 'status'])->toArray();
} else {
$propertyMeta = PropertyMeta::where('status', 1)->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'cancellation_policy', 'adult_policy', 'child_policy', 'promotion', 'status'])->toArray();
}
foreach ($propertyMeta as $property) {
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Price Start: ' . $property['property']['name']);
$roomRateOccupancyPriceParam = [];
$propertyId = $property['property_id'];
$startDate = Carbon::now()->toDateString();
$finishDate = Carbon::parse($startDate)->addDays(360)->toDateString();
$propertyCancellationPolicy = json_decode($property['cancellation_policy'], 1);
$propertyAdultPolicy = json_decode($property['adult_policy'], 1);
$propertyChildPolicy = json_decode($property['child_policy'], 1);
$propertyPromotion = json_decode($property['promotion'], 1);
$propertyRoomRatePrice = PropertyRoomRatePrice::where('property_id', $propertyId)
->where('date', '>=', $startDate)
->where('date', '<=', $finishDate)
->where('channel_id', 1)
//->where('room_rate_mapping_id', 79)//TODO: Delete
//->where('date', '2024-09-01')//TODO: Delete
->where('availability_type_id', 1)
->where('status', 1)
->get(['id', 'property_id', 'property_room_id', 'room_rate_mapping_id', 'date', 'amount', 'currency', 'min_stay', 'stop_sell']);
$propertyRoomRatePrice = $propertyRoomRatePrice->toArray();
$roomRateOccupancy = PropertyMetaRoomRate::where('property_id', $propertyId)->get()->toArray();
//TODO: DEL
//$roomRateOccupancy = collect($roomRateOccupancy)->where('occupancy_code', 'A')->toArray();
$propertyAllPriceCounter = 0;
$roomRateOccupancyPrice = [];
foreach ($propertyRoomRatePrice as $perPropertyRoomRatePrice) {
$roomRateOccupancySelected = collect($roomRateOccupancy)->where('room_rate_mapping_id', $perPropertyRoomRatePrice['room_rate_mapping_id'])->toArray();
foreach ($roomRateOccupancySelected as $roomRateOccupancyKey => $perRoomRateOccupancy) {
$baseAmount = $perPropertyRoomRatePrice['amount'];
$roomRateOccupancyKey = $perRoomRateOccupancy['code'];
$affectedAmountArray = [];
$roomRateMappingId = $perPropertyRoomRatePrice['room_rate_mapping_id'];
$cancellationPolicy = isset($propertyCancellationPolicy[$roomRateMappingId]) ? $propertyCancellationPolicy[$roomRateMappingId] : [];
$adultPolicy = isset($propertyAdultPolicy[$roomRateMappingId]) ? $propertyAdultPolicy[$roomRateMappingId] : [];
$childPolicy = isset($propertyChildPolicy[$roomRateMappingId]) ? $propertyChildPolicy[$roomRateMappingId] : [];
$promotions = isset($propertyPromotion[$roomRateMappingId]) ? $propertyPromotion[$roomRateMappingId] : [];
//dd($promotions,$perPropertyRoomRatePrice,$baseAmount);
$perPersonAmount = $baseAmount / $perRoomRateOccupancy['included_occupancy'];
//Kişi bazlı fiyat hesaplamada baz fiyat dikkate alınır, daha sonra $perPersonAmount baz fiyat üzerinden alınıp çocuk hespaplanır.
//Adult Policy
$affectedAmount = 0;
if ($perRoomRateOccupancy['included_occupancy'] != strlen($perRoomRateOccupancy['occupancy_code'])) {
if (!empty($adultPolicy)) {
if ($perRoomRateOccupancy['included_occupancy'] > strlen($perRoomRateOccupancy['occupancy_code'])) {
$occupancyDifference = $perRoomRateOccupancy['included_occupancy'] - strlen($perRoomRateOccupancy['occupancy_code']);
$adultPolicySelected = collect($adultPolicy)
->where('adult', $occupancyDifference)
->where('adult_action_type', 'DEC')
->first();
if (!empty($adultPolicySelected)) {
if ($adultPolicySelected['type'] == 'PER') {
$affectedAmount = ($baseAmount * $adultPolicySelected['value'] / 100);
} elseif ($adultPolicySelected['type'] == 'FIX') {
$affectedAmount = $adultPolicySelected['value'];
}
$affectedAmountArray[] = $adultPolicySelected['action_type'] == 'DEC' ? ($affectedAmount * -1) : $affectedAmount;
}
}
if (strlen($perRoomRateOccupancy['occupancy_code']) > $perRoomRateOccupancy['included_occupancy']) {
$occupancyDifference = strlen($perRoomRateOccupancy['occupancy_code']) - $perRoomRateOccupancy['included_occupancy'];
$adultPolicySelected = collect($adultPolicy)
->where('adult', $occupancyDifference)
->where('adult_action_type', 'INC')
->first();
if (!empty($adultPolicySelected)) {
if ($adultPolicySelected['type'] == 'PER') {
$affectedAmount = ($baseAmount * $adultPolicySelected['value'] / 100);
} elseif ($adultPolicySelected['type'] == 'FIX') {
$affectedAmount = $adultPolicySelected['value'];
}
$affectedAmountArray[] = $adultPolicySelected['action_type'] == 'DEC' ? ($affectedAmount * -1) : $affectedAmount;
}
}
}
}
//Adult Policy
//Önce Oda Fiyatı Hesaplanır, Yetişkine Göre
$roomAmount = $baseAmount + array_sum($affectedAmountArray);
//Oluşan fiyata göre de iptal politikası uygulanır
//$cancellationPolicy
$affectedAmount = 0;
$isCancellationPolicyActive = false;
if (isset($cancellationPolicy[$perRoomRateOccupancy['cancellation_policy_id']])) {
$cancellationPolicySelected = $cancellationPolicy[$perRoomRateOccupancy['cancellation_policy_id']];
//dd($cancellationPolicy,$perRoomRateOccupancy,$cancellationPolicySelected,$perPropertyRoomRatePrice['date']);
//if ($cancellationPolicySelected['is_affected_price'] == 1) {
$isDateRange = $cancellationPolicySelected['is_date_range'];
$isDateRangeDate = Carbon::parse($perPropertyRoomRatePrice['date'])->between($cancellationPolicySelected['start_date'], $cancellationPolicySelected['finish_date']);
if (($isDateRange && $isDateRangeDate) || empty($isDateRange)) {
if ($cancellationPolicySelected['affect_price_type'] == 'PER') {
$affectedAmount = ($roomAmount * $cancellationPolicySelected['affect_price_value'] / 100);
} elseif ($cancellationPolicySelected['affect_price_type'] == 'FIX') {
$affectedAmount = $cancellationPolicySelected['affect_price_value'];
}
$affectedAmountArray[] = $cancellationPolicySelected['affect_price_action_type'] == 'DEC' ? ($affectedAmount * -1) : $affectedAmount;
$isCancellationPolicyActive = true;
}
//}
}
//$cancellationPolicy
//dd($perRoomRateOccupancy, $perPropertyRoomRatePrice, $cancellationPolicy);
$isCancellationPolicyActive = true;
if ($isCancellationPolicyActive) {
$calculatedAmount = $baseAmount + array_sum($affectedAmountArray);
$promotionsGrouped = collect($promotions)->groupBy('type')->toArray();
/**** PROMOTION START ****/
$totalPromotionDiscount = 0;
foreach ($promotionsGrouped as $promotionsGroupKey => $promotions) {
$promotions = collect($promotions)->sortByDesc('amount')->toArray();
foreach ($promotions as $promotion) {
if ($promotion['min_stay'] > 1) {
continue;
}
if ($promotion['is_mobile']) {
continue;
}
$daysArray = !empty($promotion['days']) ? json_decode($promotion['days'], 1) : [];
if (!in_array((Carbon::parse($perPropertyRoomRatePrice['date'])->dayOfWeek + 1), $daysArray)) {
continue;
}
if ($promotion['type'] == 'PRD') {
if (!Carbon::now()->startOfDay()->between(Carbon::parse($promotion['start_date'])->toDateString(), Carbon::parse($promotion['end_date'])->toDateString())) {
continue;
}
if (!Carbon::parse($perPropertyRoomRatePrice['date'])->startOfDay()->between(Carbon::parse($promotion['reservation_start_date'])->toDateString(), Carbon::parse($promotion['reservation_end_date'])->toDateString())) {
continue;
}
$totalPromotionDiscount += ($calculatedAmount * $promotion['amount']) / 100;
break;
}
if ($promotion['type'] == 'BFD') {
if (Carbon::parse($perPropertyRoomRatePrice['date'])->diffInDays(Carbon::now()->startOfDay()->toDateString()) < $promotion['day_before']) {
continue;
}
$totalPromotionDiscount += ($calculatedAmount * $promotion['amount']) / 100;
break;
}
if ($promotion['type'] == 'DSC') {
$totalPromotionDiscount += ($calculatedAmount * $promotion['amount']) / 100;
break;
}
}
}
$calculatedAmount = moneyDoubleFormatDecimal($calculatedAmount - $totalPromotionDiscount);
$calculatedAmount = $calculatedAmount > 0 ? $calculatedAmount : 0;
/**** PROMOTION FINISHED ****/
$roomRateOccupancyPriceParam[] = [
'property_id' => $property['property_id'],
'room_id' => $perRoomRateOccupancy['room_id'],
'room_rate_mapping_id' => $roomRateMappingId,
'date' => $perPropertyRoomRatePrice['date'],
'code' => $roomRateOccupancyKey,
//'title' => $perRoomRateOccupancy['title'],
//'baseAmount' => $perPropertyRoomRatePrice['amount'],
'amount' => $calculatedAmount,
'currency' => $perPropertyRoomRatePrice['currency'],
'status' => 1,
'created_by' => 1,
'updated_by' => 1,
'created_at' => Carbon::now()->unix(),
'updated_at' => Carbon::now()->unix(),
];
$propertyAllPriceCounter++;
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Price Finished: ' . $property['property']['name']);
//dd(collect($roomRateOccupancyPriceParam)->sortBy('room_id')->sortBy('amount')->toArray());
$insertRows = [];
$updateRows = [];
$rowChunk = 0;
foreach ($roomRateOccupancyPriceParam as $roomRateOccupancyPrice) {
$insertRows[$rowChunk][] = $roomRateOccupancyPrice;
if (count($insertRows[$rowChunk]) > 1000) {
$rowChunk++;
}
}
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Price to DB Start: ' . $property['property']['name']);
DB::beginTransaction();
PropertyMetaRoomRatePrice::where('property_id', $propertyId)->delete();
if (!empty($insertRows)) {
foreach ($insertRows as $insertRow) {
PropertyMetaRoomRatePrice::insert($insertRow);
}
}
DB::commit();
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Price to DB Finished: ' . $property['property']['name']);
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,309 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Mirai;
use App\Exceptions\ApiErrorException;
use App\Models\ChannelManagerPropertyMapping;
use App\Models\PropertyMeta;
use App\Models\PropertyMetaRoomRate;
use App\Models\PropertyMetaRoomRateMapping;
use App\Models\PropertyMetaRoomRatePrice;
use App\Models\PropertyRoomAvailability;
use App\Models\PropertyRoomRatePrice;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PropertyMetaRoomRatePushService extends Command
{
protected $signature = 'cron:propertymeta-roomratepush-service {--property_id=}';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer,
Mirai $miraiService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->miraiService = $miraiService;
}
function getMonthlyPeriod($endDate)
{
$diffInMonths = Carbon::parse()->floorMonth()->diffInMonths(Carbon::parse($endDate)->floorMonth());
$diffInMonths++;
$monthlyPeriod = [];
$startDate = null;
$finishDate = null;
for ($i = 0; $i < $diffInMonths; $i++) {
if (empty($startDate)) {
$startDate = Carbon::now()->toDateString();
$finishDate = Carbon::parse($startDate)->endOfMonth()->toDateString();
} else {
$startDate = Carbon::now()->addMonths($i)->startOfMonth()->toDateString();
$finishDate = Carbon::parse($startDate)->endOfMonth()->toDateString();
}
if ($finishDate > $endDate) {
$finishDate = $endDate;
}
$monthlyPeriod[] = [
'startDate' => $startDate,
'finishDate' => $finishDate,
];
}
return $monthlyPeriod;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
if (!is_null($this->option('property_id'))) {
$propertyMeta = PropertyMeta::where('status', 1)->where('property_id', $this->option('property_id'))->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'cancellation_policy', 'adult_policy', 'child_policy', 'param', 'status'])->toArray();
} else {
$propertyMeta = PropertyMeta::where('status', 1)->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'cancellation_policy', 'adult_policy', 'child_policy', 'param', 'status'])->toArray();
}
foreach ($propertyMeta as $property) {
$propertyId = $property['property_id'];
//Mirai User Setup
$this->miraiService->setupUser($property['paramsArray']['login'], $property['paramsArray']['password']);
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Push Start: ' . $property['property']['name']);
//$propertyRoomRatePriceEndDate = PropertyRoomRatePrice::where('property_id', $propertyId)->orderBy('date', 'DESC')->first();
//$propertyRoomRatePriceEndDate = $propertyRoomRatePriceEndDate->toArray() ? $propertyRoomRatePriceEndDate['date'] : null;
//$propertyRoomRatePriceEndDate = '2023-10-31';
//$getMonthlyPeriod = $this->getMonthlyPeriod($propertyRoomRatePriceEndDate);
$getMonthlyPeriod = [];
$getMonthlyPeriod[] = [
'startDate' => Carbon::now()->toDateString(),
//'finishDate' => Carbon::now()->addYear()->toDateString(),
'finishDate' => Carbon::now()->addDays(360)->toDateString(),
];
$propertyMetaRoomRateMapping = PropertyMetaRoomRateMapping::where('property_id', $propertyId)->with('propertyMetaRoomRate')->get()->toArray();
$propertyMetaRoomRateMappingCollect = collect($propertyMetaRoomRateMapping);
$channelManagerPropertyMapping = ChannelManagerPropertyMapping::where('property_id', $propertyId)->where('status', 1)->where('channel_manager_id', 7)->first()->toArray();
if (empty($channelManagerPropertyMapping)) {
continue;
}
$metaRoomRateMapping = [];
$propertyMetaRoomRateMappingGroup = $propertyMetaRoomRateMappingCollect->groupBy('property_meta_room_rate.room_id')->toArray();
foreach ($propertyMetaRoomRateMappingGroup as $roomGroup) {
$roomGroup = reset($roomGroup);
$metaRoomRateMapping[$roomGroup['property_meta_room_rate']['room_id']]['meta_code'] = $roomGroup['meta_code'];
}
foreach ($getMonthlyPeriod as $period) {
$this->info(date('Y-m-d H:i:s') . ' : Meta Availability Start: ' . $property['property']['name'] . ' - ' . $period['startDate'] . ' / ' . $period['finishDate']);
try {
$propertyRoomAvailability = PropertyRoomAvailability::where('property_id', $propertyId)
->where('status', 1)->where('channel_id', null)
->whereBetween('date', [$period['startDate'], $period['finishDate']])
->get(['property_room_id', 'date', 'stop_sell', 'availability'])
->toArray();
$propertyRoomAvailabilityCollect = collect($propertyRoomAvailability);
foreach ($metaRoomRateMapping as $roomId => $metaRoom) {
$metaRoomRateMapping[$roomId]['data'] = $propertyRoomAvailabilityCollect->where('property_room_id', $roomId)->sortBy('date')->toArray();
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventoryUpdate></inventoryUpdate>');
$xmlResponse->addAttribute('hotelId', $channelManagerPropertyMapping['channel_manager_property_id']);
foreach ($metaRoomRateMapping as $roomId => $metaRoom) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $metaRoom['meta_code']);
$roomInventory = $room->addChild('inventory');
foreach ($metaRoom['data'] as $roomRate) {
$roomInventoryAvailability = $roomInventory->addChild('availability');
$roomRate['availability'] = $roomRate['stop_sell'] == 1 ? 0 : $roomRate['availability'];
$roomInventoryAvailability->addAttribute('date', $roomRate['date']);
$roomInventoryAvailability->addAttribute('quantity', $roomRate['availability']);
}
}
$request = $this->miraiService->inventoryRoomRateUpdate('webservice_updater.apro', $xmlResponse->asXML());
if (!$request['status']) {
throw new ApiErrorException('webservice_updater AVAILABILITY Error: ' . $request['message']);
}
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
$this->info(date('Y-m-d H:i:s') . ' : Meta Price Start: ' . $property['property']['name'] . ' - ' . $period['startDate'] . ' / ' . $period['finishDate']);
try {
$propertyMetaRoomRatePrice = PropertyMetaRoomRatePrice::where('property_id', $propertyId)
->whereBetween('date', [$period['startDate'], $period['finishDate']])->where('status', 1)
->whereIn('code', pickItemFromArray('code', $propertyMetaRoomRateMapping))
->get(['date', 'code', 'amount', 'currency'])
->toArray();
$propertyMetaRoomRatePriceCollect = collect($propertyMetaRoomRatePrice);
if (empty($propertyMetaRoomRatePrice)) {
$this->error(date('Y-m-d H:i:s') . ' : ' . $property['property']['name'] . ' : Price not found!');
continue;
}
$metaRoomRatePrice = [];
$metaRoomPricesOrdered = [];
foreach ($propertyMetaRoomRateMapping as $metaRoom) {
$metaRoomPrices = $propertyMetaRoomRatePriceCollect->where('code', $metaRoom['code'])->sortBy('date')->toArray();
$metaRoomPricesCollect = collect($metaRoomPrices);
$metaRoomPricesGroup = [];
foreach ($metaRoomPrices as $metaRoomPrice) {
$metaRoomPricesGroup[md5($metaRoomPrice['amount'])][$metaRoomPrice['date']] = $metaRoomPrice;
ksort($metaRoomPricesGroup[md5($metaRoomPrice['amount'])]);
}
foreach ($metaRoomPricesGroup as $priceGroupKey => $priceGroup) {
$priceDateGroup = 0;
foreach ($priceGroup as $priceGroupDate => $price) {
if (!isset($metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['startDate'])) {
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['startDate'] = $price['date'];
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['finishDate'] = $price['date'];
} else {
if (Carbon::parse($metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['finishDate'])->addDay()->toDateString() != $price['date']) {
$priceDateGroup++;
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['startDate'] = $price['date'];
} else {
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['finishDate'] = $price['date'];
}
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['finishDate'] = $price['date'];
}
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['amount'] = $price['amount'];
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['currency'] = $price['currency'];
//$metaRoomPricesOrdered[$priceGroupKey][$priceDateGroup]['metaCode'] = $metaRoom['meta_code'];
$metaRoomPricesOrdered[$metaRoom['meta_code']][$priceGroupKey][$priceDateGroup]['title'] = $metaRoom['property_meta_room_rate']['title'];
}
}
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventoryUpdate></inventoryUpdate>');
$xmlResponse->addAttribute('hotelId', $channelManagerPropertyMapping['channel_manager_property_id']);
foreach ($metaRoomPricesOrdered as $roomRateMetaCode => $metaRoom) {
foreach ($metaRoom as $priceGroupKey => $metaRoomPriceGroup) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $roomRateMetaCode);
$currency = !empty($metaRoomPriceGroup) ? reset($metaRoomPriceGroup)['currency'] : 'EUR';
$rate = $room->addChild('rate');
$rate->addAttribute('currency', $currency);
foreach ($metaRoomPriceGroup as $metaRoomPrice) {
$planning = $rate->addChild('planning');
$planning->addAttribute('from', $metaRoomPrice['startDate']);
$planning->addAttribute('to', $metaRoomPrice['finishDate']);
$planning->addAttribute('unitPrice', $metaRoomPrice['amount']);
}
}
}
$request = $this->miraiService->inventoryRoomRateUpdate('webservice_updater.apro', $xmlResponse->asXML());
if (!$request['status']) {
throw new ApiErrorException('webservice_updater PRICE Error: ' . $request['message']);
}
//Remove all prices then push to meta
PropertyMetaRoomRatePrice::where('property_id', $propertyId)->delete();
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,288 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Exceptions\ApiErrorException;
use App\Models\PropertyMeta;
use App\Models\PropertyMetaRoomRate;
use App\Models\PropertyRoomRateChannelMapping;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PropertyMetaRoomRateService extends Command
{
protected $signature = 'cron:propertymeta-roomrate-service {--property_id=}';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer
)
{
parent::__construct();
$this->mailer = $mailer;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
if (!is_null($this->option('property_id'))) {
$propertyMeta = PropertyMeta::where('status', 1)->where('property_id', $this->option('property_id'))->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'status'])->toArray();
} else {
$propertyMeta = PropertyMeta::where('status', 1)->with('property')->orderBy('id', 'ASC')->get(['id', 'property_id', 'status'])->toArray();
}
foreach ($propertyMeta as $property) {
$this->info(date('Y-m-d H:i:s') . ' : Property Policy Start: ' . $property['property']['name']);
//Property All Room Rate Price Policy
$propertyRoomRateChannelMapping = PropertyRoomRateChannelMapping::with('propertyRoomRateMapping')
->with('propertyRoomRateMapping.propertyRoom')
->with('propertyRoomRateMapping.propertyRoomRate')
->with('propertyRoomRateChannelCancellationPolicy.propertyCancellationPolicy')
->with('propertyRoomRateChannelPricingAdultPolicy.propertyPricingPolicyAdult')
->with('propertyRoomRateChannelPricingChildPolicy.propertyPricingPolicyChild')
->with('propertyRoomRateChannelPromotion.propertyPromotion.promotionType')
->get()
->where('property_id', $property['property_id'])->where('channel_id', 1)
->where('status', 1);
$propertyRoomRateChannelMapping = $propertyRoomRateChannelMapping->where('propertyRoomRateMapping', '!=', null)->toArray();
//dd($propertyRoomRateChannelMapping);
$roomRateMappingPolicy = [];
foreach ($propertyRoomRateChannelMapping as $propertyRoom) {
$roomRateMappingPolicy['promotion'][$propertyRoom['room_rate_mapping_id']] = [];
foreach ($propertyRoom['property_room_rate_channel_promotion'] as $propertyRoomRateChannelPromotion) {
if($propertyRoomRateChannelPromotion['status'] != 1) {
continue;
}
$roomRateMappingPolicy['promotion'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateChannelPromotion['property_promotion_id']] = [
'type' => $propertyRoomRateChannelPromotion['property_promotion']['promotion_type']['type_code'],
'start_date' => $propertyRoomRateChannelPromotion['property_promotion']['start_date'],
'end_date' => $propertyRoomRateChannelPromotion['property_promotion']['end_date'],
'reservation_start_date' => $propertyRoomRateChannelPromotion['property_promotion']['reservation_start_date'],
'reservation_end_date' => $propertyRoomRateChannelPromotion['property_promotion']['reservation_end_date'],
'day_before' => $propertyRoomRateChannelPromotion['property_promotion']['day_before'],
'amount' => $propertyRoomRateChannelPromotion['property_promotion']['amount'],
'min_stay' => $propertyRoomRateChannelPromotion['property_promotion']['min_stay'],
'is_mobile' => $propertyRoomRateChannelPromotion['property_promotion']['is_mobile'],
'days' => $propertyRoomRateChannelPromotion['property_promotion']['days'],
];
}
$roomRateMappingPolicy['cancellation_policy'][$propertyRoom['room_rate_mapping_id']] = [];
foreach ($propertyRoom['property_room_rate_channel_cancellation_policy'] as $propertyRoomRateCancellationPolicy) {
$roomRateMappingPolicy['cancellation_policy'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateCancellationPolicy['cancellation_policy_id']] = [
'is_affected_price' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['is_affected_price'],
'affect_price_action_type' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['affect_price_action_type'],
'affect_price_type' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['affect_price_type'],
'affect_price_value' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['affect_price_value'],
'is_date_range' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['is_date_range'],
'start_date' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['start_date'],
'finish_date' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['finish_date'],
];
}
$roomRateMappingPolicy['adult_policy'][$propertyRoom['room_rate_mapping_id']] = [];
foreach ($propertyRoom['property_room_rate_channel_pricing_adult_policy'] as $propertyRoomRateAdultPolicy) {
$roomRateMappingPolicy['adult_policy'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateAdultPolicy['pricing_policy_adult_id']] = [
'adult_action_type' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['adult_action_type'],
'adult' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['adult'],
'action_type' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['action_type'],
'type' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['type'],
'value' => $propertyRoomRateAdultPolicy['property_pricing_policy_adult']['value'],
];
}
$roomRateMappingPolicy['child_policy'][$propertyRoom['room_rate_mapping_id']] = [];
foreach ($propertyRoom['property_room_rate_channel_pricing_child_policy'] as $propertyRoomRateChildPolicy) {
$roomRateMappingPolicy['child_policy'][$propertyRoom['room_rate_mapping_id']][$propertyRoomRateChildPolicy['pricing_policy_child_id']] = [
'adult' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['adult'],
'child_order' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['child_order'],
'child_age_start' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['child_age_start'],
'child_age_end' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['child_age_end'],
'type' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['type'],
'value' => $propertyRoomRateChildPolicy['property_pricing_policy_child']['value'],
];
}
}
//Property All Room Rate Price Policy
$propertyMetaPolicyUpdate = [
'cancellation_policy' => json_encode($roomRateMappingPolicy['cancellation_policy']),
'adult_policy' => json_encode($roomRateMappingPolicy['adult_policy']),
'child_policy' => json_encode($roomRateMappingPolicy['child_policy']),
'promotion' => json_encode($roomRateMappingPolicy['promotion']),
];
PropertyMeta::where('id', $property['id'])->update($propertyMetaPolicyUpdate);
$this->info(date('Y-m-d H:i:s') . ' : Property Policy Finished: ' . $property['property']['name']);
//$propertyMetaTemp
/*$propertyMetaTemp = PropertyMeta::where('property_id', $property['property_id'])->with('property')->get()->first();
$propertyMetaTemp = $propertyMetaTemp->toArray();
$propertyMetaPolicyUpdate = [
'cancellation_policy' => json_decode($propertyMetaTemp['cancellation_policy'], 1),
'adult_policy' => json_decode($propertyMetaTemp['adult_policy'], 1),
'child_policy' => json_decode($propertyMetaTemp['child_policy'], 1),
];*/
//$propertyMetaTemp
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Occupancy Start: ' . $property['property']['name']);
//Property All Price Combination
/*$propertyRoomRateChannelMapping = PropertyRoomRateChannelMapping::with('propertyRoomRateMapping')
->with('propertyRoomRateMapping.propertyRoom')
->with('propertyRoomRateMapping.propertyRoomRate')
->with('propertyRoomRateChannelCancellationPolicy.propertyCancellationPolicy')
->with('propertyRoomRateChannelPricingAdultPolicy')
->with('propertyRoomRateChannelPricingChildPolicy')
->get()
->where('property_id', $property['property_id'])->where('channel_id', 1)
->where('status', 1);
$propertyRoomRateChannelMapping = $propertyRoomRateChannelMapping->where('propertyRoomRateMapping', '!=', null)->toArray();*/
$roomRateOccupancy = [];
foreach ($propertyRoomRateChannelMapping as $propertyRoom) {
$roomId = $propertyRoom['property_room_rate_mapping']['room_id'];
$propertyRoomRateMappingId = $propertyRoom['property_room_rate_mapping']['id'];
$occupancyGroup = occupancyGroup(
$propertyRoom['property_room_rate_mapping']['property_room']['max_adult'],
$propertyRoom['property_room_rate_mapping']['property_room']['max_child'],
$propertyRoom['property_room_rate_mapping']['property_room']['max_occupancy']
);
//TODO: Burası incelenebilir, cancellation policy yok ise gelmiyor çünkü....
/*if(empty($propertyRoom['property_room_rate_channel_cancellation_policy'])) {
$propertyRoom['property_room_rate_channel_cancellation_policy'][] = [
'cancellation_policy_id' => 0,
'property_cancellation_policy' => [
'name' => 'Refundable',
'is_nonrefundable' => 0,
]
];
}*/
foreach ($propertyRoom['property_room_rate_channel_cancellation_policy'] as $propertyRoomRateCancellationPolicy) {
foreach ($occupancyGroup as $occupancyCode) {
$roomRateOccupancyKey = $roomId . '-' . $propertyRoomRateMappingId . '-' . $propertyRoomRateCancellationPolicy['cancellation_policy_id'] . '-' . $occupancyCode;
$roomRateOccupancyKey = md5($roomRateOccupancyKey);
$cancellationPolicyName = [];
$cancellationPolicyName[] = $propertyRoomRateCancellationPolicy['property_cancellation_policy']['is_nonrefundable'] ? 'NonRefundable' : 'Refundable';
$cancellationPolicyName[] = !empty($propertyRoomRateCancellationPolicy['property_cancellation_policy']['name']) ? '(' . $propertyRoomRateCancellationPolicy['property_cancellation_policy']['name'] . ')' : null;
$cancellationPolicyName = implode(' ', $cancellationPolicyName);
$roomRateOccupancyTitle = [];
$roomRateOccupancyTitle[] = $propertyRoom['property_room_rate_mapping']['property_room']['name'];
$roomRateOccupancyTitle[] = $propertyRoom['property_room_rate_mapping']['property_room_rate']['name'];
$roomRateOccupancyTitle[] = $cancellationPolicyName;
$roomRateOccupancyTitle[] = $occupancyCode;
$roomRateOccupancyTitle = implode(' - ', $roomRateOccupancyTitle);
$roomRateOccupancy[$roomRateOccupancyKey] = [
'propertyId' => $property['property_id'],
'roomId' => $roomId,
'roomName' => $propertyRoom['property_room_rate_mapping']['property_room']['name'],
'roomRateMappingId' => $propertyRoomRateMappingId,
'roomRateMappingName' => $propertyRoom['property_room_rate_mapping']['property_room_rate']['name'],
'cancellationPolicyId' => $propertyRoomRateCancellationPolicy['cancellation_policy_id'],
'cancellationPolicyName' => $propertyRoomRateCancellationPolicy['property_cancellation_policy']['name'],
'occupancyCode' => $occupancyCode,
'includedOccupancy' => $propertyRoom['property_room_rate_mapping']['included_occupancy'],
'title' => $roomRateOccupancyTitle
];
}
}
}
//Property All Price Combination
$propertyMetaRoomRateParam = [];
foreach ($roomRateOccupancy as $roomRateOccupancyKey => $roomRate) {
//$propertyMetaRoomRateCheck = PropertyMetaRoomRate::where('code', $roomRateOccupancyKey)->count();
$propertyMetaRoomRateParam[] = [
'code' => $roomRateOccupancyKey,
'title' => $roomRate['title'],
'property_id' => $roomRate['propertyId'],
'room_id' => $roomRate['roomId'],
'room_rate_mapping_id' => $roomRate['roomRateMappingId'],
'cancellation_policy_id' => $roomRate['cancellationPolicyId'],
'included_occupancy' => $roomRate['includedOccupancy'],
'occupancy_code' => $roomRate['occupancyCode'],
'status' => 1,
'created_by' => 1,
'updated_by' => 1,
'created_at' => Carbon::now()->unix(),
'updated_at' => Carbon::now()->unix(),
];
/*if ($propertyMetaRoomRateCheck) {
$propertyMetaRoomRateUpdate = PropertyMetaRoomRate::where('code', $roomRateOccupancyKey)->update($propertyMetaRoomRateParam);
} else {
$propertyMetaRoomRateCreate = PropertyMetaRoomRate::create($propertyMetaRoomRateParam);
}*/
//$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Occupancy: ' . $roomRate['title']);
}
//Delete all codes
if (!empty($propertyMetaRoomRateParam)) {
PropertyMetaRoomRate::where('property_id', $property['property_id'])->delete();
PropertyMetaRoomRate::insert($propertyMetaRoomRateParam);
}
$this->info(date('Y-m-d H:i:s') . ' : Property Room Rate Occupancy Finished: ' . $property['property']['name']);
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,116 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\BookingPaymentService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class RemovePaymentTokenService extends Command
{
protected $signature = 'cron:remove-payment-token-service';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer,
BookingPaymentService $bookingPaymentService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->bookingPaymentService = $bookingPaymentService;
}
public function handle()
{
try {
$this->info(date('Y-m-d H:i:s') . ' : Start');
$bookingPaymentDataCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 2],
['field' => 'type', 'condition' => '=', 'value' => 'ch'],
],
'with' => ['bookingDetail.channelManager'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$bookingPaymentData = $this->bookingPaymentService->selectPaymentData($bookingPaymentDataCriteria);
$bookingPaymentData = $bookingPaymentData['status'] == 'success' && !empty($bookingPaymentData['data']) ? $bookingPaymentData['data'] : [];
if (!empty($bookingPaymentData)) {
$bookingPaymentDataCollect = collect($bookingPaymentData);
$bookingPaymentData = $bookingPaymentDataCollect->where('booking_detail.checkout_date', '<', Carbon::now()->subDays(7))->toArray();
}
//$bookingPaymentData
foreach ($bookingPaymentData as $bookingPaymentKey => $bookingPayment) {
if (empty($bookingPayment['booking_detail']['channel_manager_id'])) {
continue;
}
$channelManagerId = $bookingPayment['booking_detail']['channel_manager_id'];
switch ($channelManagerId) {
case 2 :
$channelService = App::make("App\Core\Service\ChannelManager\\{$bookingPayment['booking_detail']['channel_manager']['name']}");
$removeCreditCardToken = $channelService->removeCreditCardToken($bookingPayment['data']);
if (!$removeCreditCardToken['status']) {
//Hata maili atılsın
$this->error(date('Y-m-d H:i:s') . ' : Channel: ' . $bookingPayment['booking_detail']['channel_manager']['name'] . ' Token: ' . $bookingPayment['data']);
} else {
$this->bookingPaymentService->updatePaymentData($bookingPayment['id'], ['status' => 1]);
$this->info(date('Y-m-d H:i:s') . ' : Channel: ' . $bookingPayment['booking_detail']['channel_manager']['name'] . ' Token: ' . $bookingPayment['data']);
}
break;
default;
break;
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}

View File

@@ -0,0 +1,957 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\CancelBookingMail;
use App\Core\Mail\LogMail;
use App\Core\Mail\ModifiedBookingMail;
use App\Core\Service\BookingContactService;
use App\Core\Service\BookingPaymentService;
use App\Core\Service\BookingRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerBookingService;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\ChannelManagerPropertyRateMappingService;
use App\Core\Service\ChannelManagerService;
use App\Core\Service\NewBookingMailService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ReservationPullService extends Command
{
protected $signature = 'cron:reservation-pull-service';
protected $description = '';
protected $mailer;
protected $channelService;
protected $channelManagerPropertyMappingService;
protected $bookingService;
protected $propertyRoomAvailabilityService;
protected $newBookingMailService;
public function __construct(
Mailer $mailer,
ChannelManagerMappingService $channelManagerMappingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
BookingService $bookingService,
BookingContactService $bookingContactService,
BookingRoomService $bookingRoomService,
BookingPaymentService $bookingPaymentService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
NewBookingMailService $newBookingMailService,
ChannelManagerService $channelManagerService,
ChannelManagerBookingService $channelManagerBookingService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelManagerMappingService = $channelManagerMappingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->bookingService = $bookingService;
$this->bookingContactService = $bookingContactService;
$this->bookingRoomService = $bookingRoomService;
$this->bookingPaymentService = $bookingPaymentService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->newBookingMailService = $newBookingMailService;
$this->channelManagerService = $channelManagerService;
$this->channelManagerBookingService = $channelManagerBookingService;
}
public function getDateByDay($dates = [])
{
$dateByDay = [];
$diffInDays = Carbon::parse($dates['checkIn'])->floatDiffInDays(Carbon::parse($dates['checkOut']));
for ($i = 0; $i < $diffInDays; $i++) {
$dateByDay[] = Carbon::parse($dates['checkIn'])->addDay($i)->format('Y-m-d');
}
return $dateByDay;
}
public function createBooking($channelCode, $param)
{
$response = ['status' => false, 'message' => ''];
DB::beginTransaction();
try {
$channelService = App::make("App\Core\Service\ChannelManager\\{$channelCode}");
$bookingCode = getCodeGenerate('BKG');
$param['booking']['booking_code'] = $bookingCode;
$param['booking']['extra_param'] = json_encode($param['channel_manager']);
$bookingCreate = $this->bookingService->create($param['booking']);
//$bookingCreate['status'] = 'success';//TODO: Delete
//$bookingCreate['data']['id'] = 1106;
if ($bookingCreate['status'] != 'success') {
throw new ApiErrorException('Booking could not be made, Reservation: ' . $param['booking']['search_key']);
}
$param['booking']['id'] = $bookingCreate['data']['id'];
//INSERT CONTACT DATA
$bookingContactCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'name' => $param['contact']['name'],
'surname' => $param['contact']['surname'],
'phone_code' => $param['contact']['phone_code'],
'phone_number' => $param['contact']['phone_number'],
'email' => $param['contact']['email'],
'country_code' => fillOnUndefined($param['contact'], 'country_code'),
'note' => !empty($param['contact']['note']) ? $param['contact']['note'] : null,
'language_code' => fillOnUndefined($param['contact'], 'language', 'en'),
'extra_param' => fillOnUndefined($param['contact'], 'extra_param'),
'status' => 1
];
$bookingContactCreate = $this->bookingContactService->create($bookingContactCreateParam);
//$bookingContactCreate['status'] = 'success';
if ($bookingContactCreate['status'] != 'success') {
throw new ApiErrorException('Booking Contact could not be made');
}
//INSERT ROOM DATA
foreach ($param['room'] as $roomOrder => $room) {
$bookingRoomCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'room_order_number' => ($roomOrder + 1),
'occupancy_code' => $room['occupancy_code'],
'checkin_date' => $room['checkin_date'], //$room['checkin'],
'checkout_date' => $room['checkout_date'],//$room['checkout'],
'rate_key' => fillOnUndefined($room, 'rate_key'),
'rate_key_code' => fillOnUndefined($room, 'rate_key_code'),
'availability_id' => 1,
'availability_code' => 'ROM',
'room_id' => $room['room_id'],
'room_name' => $room['room_name'],
'room_rate_mapping_id' => $room['room_rate_mapping_id'],
'room_rate_name' => $room['room_rate_name'],
'cancellation_policy' => fillOnUndefined($room, 'cancellation_policy'),
'payment_type_code' => fillOnUndefined($room, 'payment_type_code', 'CHN'),
'daily_amount' => fillOnUndefined($room, 'daily_amount'),
'extra_param' => fillOnUndefined($room, 'extra_param'),
'rate_detail' => fillOnUndefined($room, 'rate_detail'),
'total' => $room['total'],
'currency_code' => $room['currency_code'],
'status' => fillOnUndefined($room, 'status', 1),
];
$bookingRoomCreate = $this->bookingRoomService->create($bookingRoomCreateParam);
//$bookingRoomCreate['status'] = 'success';
if ($bookingRoomCreate['status'] != 'success') {
throw new ApiErrorException('Booking Room could not be made');
}
/* ROOM AVAILABILITY */
$dateByDay = [];
$dateByDay = $this->getDateByDay(['checkIn' => $room['checkin_date'], 'checkOut' => $room['checkout_date']]);
foreach ($dateByDay as $day) {
$requestParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['booking']['property_id']],
['field' => 'property_room_id', 'condition' => '=', 'value' => $room['room_id']],
['field' => 'availability_type_id', 'condition' => '=', 'value' => 1],
['field' => 'date', 'condition' => '=', 'value' => $day]
],
];
$getPropertyRoomAndRoomRateAvailability = $this->propertyRoomAvailabilityService->select($requestParam);
if ($getPropertyRoomAndRoomRateAvailability['status'] != 'success') {
throw new ApiErrorException('getPropertyRoomAndRoomRateAvailability Empty');
}
foreach ($getPropertyRoomAndRoomRateAvailability['data'] as $roomAvailability) {
$roomAvailabilityUpdated = $roomAvailability['availability'] <= 0 ? 0 : ($roomAvailability['availability'] - 1);
$this->propertyRoomAvailabilityService->update($roomAvailability['id'], ['availability' => $roomAvailabilityUpdated]);
}
}
/* ROOM AVAILABILITY */
}
//INSERT PAYMENT DATA
$bookingPaymentCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'payment_code' => fillOnUndefined($param['payment'], 'payment_code'),
'payment_type_code' => fillOnUndefined($param['payment'], 'payment_type_code'),//Type: CHN
'payment_source_code' => fillOnUndefined($param['payment'], 'payment_source_code'),
'extra_param' => fillOnUndefined($param['payment'], 'extra_param'),
'total' => fillOnUndefined($param['payment'], 'total'),
'currency_code' => fillOnUndefined($param['payment'], 'currency_code'),
'status' => fillOnUndefined($param['payment'], 'status'),//Type: 2
];
$bookingPaymentCreate = $this->bookingPaymentService->create($bookingPaymentCreateParam);
//$bookingPaymentCreate['status'] = 'success';
if ($bookingPaymentCreate['status'] != 'success') {
throw new ApiErrorException('Booking Payment could not be made');
}
//INSERT PAYMENT DATA
//INSERT CHANNEL PAYMENT DATA
if (isset($param['payment_channel']) && !empty($param['payment_channel'])) {
$bookingPaymentDataCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'type' => fillOnUndefined($param['payment_channel'], 'type'),
'data' => fillOnUndefined($param['payment_channel'], 'data'),
'status' => fillOnUndefined($param['payment_channel'], 'status', 1),
];
$bookingPaymentDataCreate = $this->bookingPaymentService->createPaymentData($bookingPaymentDataCreateParam);
if ($bookingPaymentDataCreate['status'] != 'success') {
throw new ApiErrorException('Booking Channel Payment could not be made');
}
}
//INSERT CHANNEL PAYMENT DATA
$reservationConfirmParam = $channelService->reservationConfirmParam($param['channel_manager']['property_id'], $param['channel_manager']['booking_id'], $bookingCode, $param);
$reservationConfirm = $channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
//PUSH CHANNEL MANAGER QUEUE
/*
538 Euphoria Hotel Batumi
541 Intourist Palace Hotel & SPA
545 Metro Sky Tower Hotel
546 Legend Hotel Batumi Convention Center & Spa
548 Legend Business Hotel Batumi
549 Euphoria Apartments
550 City Hotel Batumi
*/
/*if (in_array($bookingCreate['data']['property_id'], [546])) {
$channelManagerBookingParam = [
'property_id' => $bookingCreate['data']['property_id'],
'booking_id' => $bookingCreate['data']['id'],
'channel_manager_id' => $bookingCreate['data']['channel_manager_id'],
'type' => 'Booking',
];
$this->channelManagerBookingService->create($channelManagerBookingParam);
}*/
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'property_id', 'condition' => '=', 'value' => $bookingCreate['data']['property_id']],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $channelPropertyData) {
if(in_array($channelPropertyData['channel_manager_id'],[11,13])) {
continue;
}
$channelManagerBookingCreateParam = [
'property_id' => $bookingCreate['data']['property_id'],
'booking_id' => $bookingCreate['data']['id'],
'channel_manager_id' => $channelPropertyData['channel_manager_id'],
'type' => 'Booking',
];
$channelManagerBookingCreate = $this->channelManagerBookingService->create($channelManagerBookingCreateParam);
}
}
//PUSH CHANNEL MANAGER QUEUE
DB::commit();
$mailParams = ['booking_id' => $bookingCreate['data']['id']];
$this->newBookingMailService->process($mailParams);
$response['status'] = true;
$response['data'] = $param;
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
DB::rollBack();
}
return $response;
}
public function modifiedBooking($channelCode, $param)
{
$response = ['status' => false, 'message' => ''];
DB::beginTransaction();
try {
$channelService = App::make("App\Core\Service\ChannelManager\\{$channelCode}");
$bookingCode = null;
$bookingDetailParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['booking']['property_id']],
['field' => 'search_key', 'condition' => '=', 'value' => $param['booking']['search_key']],
//['field' => 'channel_manager_id', 'condition' => '=', 'value' => $param['booking']['channel_manager_id']],
],
'with' => ['bookingRoom', 'bookingContact', 'bookingChannel', 'bookingPayment'],
'firstRow' => true
];
$bookingDetail = $this->bookingService->select($bookingDetailParam);
if ($bookingDetail['status'] != 'success') {
throw new ApiErrorException(lang('Booking could not be found, Reservation: ' . $param['booking']['search_key']));
}
if (!empty($bookingDetail['data'])) {
$bookingCode = $bookingDetail['data']['booking_code'];
$param['booking']['id'] = $bookingDetail['data']['id'];
$param['booking']['booking_code'] = $bookingDetail['data']['booking_code'];
$bookingUpdateParam = [
'channel_booking_code' => fillOnUndefined($param['booking'], 'channel_booking_code'),
'search_key' => $param['booking']['search_key'],
'checkin_date' => $param['booking']['checkin_date'],
'checkout_date' => $param['booking']['checkout_date'],
'payment_type_code' => $param['booking']['payment_type_code'],
'total' => $param['booking']['total'],
'currency_code' => $param['booking']['currency_code'],
];
$bookingUpdate = $this->bookingService->update($bookingDetail['data']['id'], $bookingUpdateParam);
$bookingContactUpdateParam = [
'name' => $param['contact']['name'],
'surname' => $param['contact']['surname'],
'phone_code' => $param['contact']['phone_code'],
'phone_number' => $param['contact']['phone_number'],
'email' => $param['contact']['email'],
'country_code' => !empty($param['contact']['country_code']) ? $param['contact']['country_code'] : null,
'note' => !empty($param['contact']['note']) ? $param['contact']['note'] : null,
'language_code' => fillOnUndefined($param['contact'], 'language_code', 'en')
];
$bookingContactUpdate = $this->bookingContactService->update($bookingDetail['data']['booking_contact']['id'], $bookingContactUpdateParam);
foreach ($bookingDetail['data']['booking_room'] as $roomOrder => $room) {
foreach ($param['room'] as $roomOrderChannel => $roomChannel) {
if ($roomOrder == $roomOrderChannel) {
$bookingRoomUpdateParam = [
'occupancy_code' => $roomChannel['occupancy_code'],
'checkin_date' => $roomChannel['checkin_date'],
'checkout_date' => $roomChannel['checkout_date'],
'room_id' => $roomChannel['room_id'],
'room_name' => $roomChannel['room_name'],
'room_rate_mapping_id' => $roomChannel['room_rate_mapping_id'],
'room_rate_name' => $roomChannel['room_rate_name'],
'rate_detail' => json_encode($roomChannel),
'total' => $roomChannel['total'],
'currency_code' => $roomChannel['currency_code'],
'daily_amount' => fillOnUndefined($roomChannel, 'daily_amount'),
];
$bookingRoomUpdate = $this->bookingRoomService->update($room['id'], $bookingRoomUpdateParam);
/* ROOM AVAILABILITY */
//Eğer odaya ait tarihler farklı ise buraya gelecek.
if (($room['checkin_date'] != $roomChannel['checkin_date']) || ($room['checkout_date'] != $roomChannel['checkout_date'])) {
$dateByDay = [];
$dateByDay['update'] = [];
$dateByDay['current'] = $this->getDateByDay(['checkIn' => $room['checkin_date'], 'checkOut' => $room['checkout_date']]);
$dateByDay['modified'] = $this->getDateByDay(['checkIn' => $roomChannel['checkin_date'], 'checkOut' => $roomChannel['checkout_date']]);
foreach ($dateByDay['current'] as $date) {
$dateByDay['update'][$date] = !isset($dateByDay['update'][$date]) ? 0 : $dateByDay['update'][$date];
$dateByDay['update'][$date]++;
}
foreach ($dateByDay['modified'] as $date) {
$dateByDay['update'][$date] = !isset($dateByDay['update'][$date]) ? 0 : $dateByDay['update'][$date];
$dateByDay['update'][$date]--;
}
ksort($dateByDay['update']);
foreach ($dateByDay['update'] as $day => $availabilityModified) {
$requestParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['booking']['property_id']],
['field' => 'property_room_id', 'condition' => '=', 'value' => $room['room_id']],
['field' => 'availability_type_id', 'condition' => '=', 'value' => 1],
['field' => 'date', 'condition' => '=', 'value' => $day]
],
];
$getPropertyRoomAndRoomRateAvailability = $this->propertyRoomAvailabilityService->select($requestParam);
if ($getPropertyRoomAndRoomRateAvailability['status'] != 'success') {
throw new ApiErrorException('getPropertyRoomAndRoomRateAvailability Empty');
}
foreach ($getPropertyRoomAndRoomRateAvailability['data'] as $roomAvailability) {
$roomAvailabilityUpdated = 0;
$roomAvailabilityUpdated = $roomAvailability['availability'] + $availabilityModified;
if($roomAvailabilityUpdated < 0) {
$roomAvailabilityUpdated = 0;
}
$this->propertyRoomAvailabilityService->update($roomAvailability['id'], ['availability' => $roomAvailabilityUpdated]);
}
}
}
/* ROOM AVAILABILITY */
}
}
}
//Added New Room Case
if (count($bookingDetail['data']['booking_room']) != count($param['room']) && count($param['room']) > count($bookingDetail['data']['booking_room']) ) {
foreach ($param['room'] as $roomOrderChannel => $roomChannel) {
foreach ($bookingDetail['data']['booking_room'] as $roomOrder => $room) {
if ($roomOrder != $roomOrderChannel) {
$bookingRoomCreateParam = [
'booking_id' => $bookingDetail['data']['id'],
'room_order_number' => ($roomOrderChannel + 1),
'occupancy_code' => $roomChannel['occupancy_code'],
'checkin_date' => $roomChannel['checkin_date'], //$room['checkin'],
'checkout_date' => $roomChannel['checkout_date'],//$room['checkout'],
'rate_key' => fillOnUndefined($roomChannel, 'rate_key'),
'rate_key_code' => fillOnUndefined($roomChannel, 'rate_key_code'),
'availability_id' => 1,
'availability_code' => 'ROM',
'room_id' => $roomChannel['room_id'],
'room_name' => $roomChannel['room_name'],
'room_rate_mapping_id' => $roomChannel['room_rate_mapping_id'],
'room_rate_name' => $roomChannel['room_rate_name'],
'cancellation_policy' => fillOnUndefined($roomChannel, 'cancellation_policy'),
'payment_type_code' => fillOnUndefined($roomChannel, 'payment_type_code', 'CHN'),
'daily_amount' => fillOnUndefined($roomChannel, 'daily_amount'),
'extra_param' => fillOnUndefined($roomChannel, 'extra_param'),
'rate_detail' => fillOnUndefined($roomChannel, 'rate_detail'),
'total' => $roomChannel['total'],
'currency_code' => $roomChannel['currency_code'],
'status' => fillOnUndefined($roomChannel, 'status', 1),
];
$bookingRoomCreate = $this->bookingRoomService->create($bookingRoomCreateParam);
}
}
}
}
//UPDATE PAYMENT DATA
$bookingPaymentUpdateParam = [
'payment_type_code' => fillOnUndefined($param['payment'], 'payment_type_code'),
'payment_source_code' => fillOnUndefined($param['payment'], 'payment_source_code'),
'extra_param' => fillOnUndefined($param['payment'], 'extra_param'),
'total' => fillOnUndefined($param['payment'], 'total'),
'currency_code' => fillOnUndefined($param['payment'], 'currency_code')
];
$bookingPaymentUpdate = $this->bookingPaymentService->update($bookingDetail['data']['booking_payment']['id'], $bookingPaymentUpdateParam);
//UPDATE PAYMENT DATA
//INSERT CHANNEL PAYMENT DATA
if (isset($param['payment_channel']) && !empty($param['payment_channel'])) {
$bookingPaymentDataCreateParam = [
'booking_id' => $bookingDetail['data']['id'],
'type' => fillOnUndefined($param['payment_channel'], 'type'),
'data' => fillOnUndefined($param['payment_channel'], 'data'),
'status' => fillOnUndefined($param['payment_channel'], 'status', 1),
];
$bookingPaymentDataCreate = $this->bookingPaymentService->createPaymentData($bookingPaymentDataCreateParam);
if ($bookingPaymentDataCreate['status'] != 'success') {
throw new ApiErrorException('Booking Channel Payment could not be made');
}
}
//INSERT CHANNEL PAYMENT DATA
} else {
return $this->createBooking($channelCode, $param);
}
$bookingCode = is_null($bookingCode) ? 'ENW' . $param['booking']['search_key'] : $bookingCode;
$reservationConfirmParam = $channelService->reservationConfirmParam($param['channel_manager']['property_id'], $param['channel_manager']['booking_id'], $bookingCode, $param);
$reservationConfirm = $channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
$notificationModifiedToPropertyUser = [
'booking_id' => $param['booking']['id'],
];
$this->mailer->onQueue('modifiedBookingMail', new ModifiedBookingMail($notificationModifiedToPropertyUser));
$response['status'] = true;
$response['data'] = $param;
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if ($response['status']) {
//PUSH CHANNEL MANAGER QUEUE
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'property_id', 'condition' => '=', 'value' => $bookingDetail['data']['property_id']],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $channelPropertyData) {
if(in_array($channelPropertyData['channel_manager_id'],[11,13])) {
continue;
}
$channelManagerBookingCreateParam = [
'property_id' => $bookingDetail['data']['property_id'],
'booking_id' => $bookingDetail['data']['id'],
'channel_manager_id' => $channelPropertyData['channel_manager_id'],
'type' => 'Modify',
];
$channelManagerBookingCreate = $this->channelManagerBookingService->create($channelManagerBookingCreateParam);
}
}
//PUSH CHANNEL MANAGER QUEUE
DB::commit();
} else {
DB::rollBack();
}
return $response;
}
public function cancelBooking($channelCode, $param)
{
$response = ['status' => false, 'message' => ''];
DB::beginTransaction();
try {
$channelService = App::make("App\Core\Service\ChannelManager\\{$channelCode}");
$bookingCode = null;
$bookingDetailParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['booking']['property_id']],
['field' => 'search_key', 'condition' => '=', 'value' => $param['booking']['search_key']],
//['field' => 'channel_manager_id', 'condition' => '=', 'value' => $param['booking']['channel_manager_id']],
],
'with' => ['bookingRoom', 'bookingContact', 'bookingChannel'],
'firstRow' => true
];
$bookingDetail = $this->bookingService->select($bookingDetailParam);
if ($bookingDetail['status'] != 'success') {
throw new ApiErrorException(lang('Booking could not be found, Reservation: ' . $param['booking']['search_key']));
}
if (!empty($bookingDetail['data'])) {
$bookingCode = $bookingDetail['data']['booking_code'];
$param['booking']['id'] = $bookingDetail['data']['id'];
$param['booking']['booking_code'] = $bookingDetail['data']['booking_code'];
$this->bookingService->update($bookingDetail['data']['id'], ['status' => 0]);
foreach ($bookingDetail['data']['booking_room'] as $roomOrder => $room) {
$bookingRoomUpdate = $this->bookingRoomService->update($room['id'], ['status' => 0]);
/* ROOM AVAILABILITY */
$dateByDay = [];
$dateByDay = $this->getDateByDay(['checkIn' => $room['checkin_date'], 'checkOut' => $room['checkout_date']]);
foreach ($dateByDay as $day) {
$requestParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['booking']['property_id']],
['field' => 'property_room_id', 'condition' => '=', 'value' => $room['room_id']],
['field' => 'availability_type_id', 'condition' => '=', 'value' => 1],
['field' => 'date', 'condition' => '=', 'value' => $day]
],
];
$getPropertyRoomAndRoomRateAvailability = $this->propertyRoomAvailabilityService->select($requestParam);
if ($getPropertyRoomAndRoomRateAvailability['status'] != 'success') {
throw new ApiErrorException('getPropertyRoomAndRoomRateAvailability Empty');
}
foreach ($getPropertyRoomAndRoomRateAvailability['data'] as $roomAvailability) {
$roomAvailabilityUpdated = $roomAvailability['availability'] <= 0 ? 1 : ($roomAvailability['availability'] + 1);
$this->propertyRoomAvailabilityService->update($roomAvailability['id'], ['availability' => $roomAvailabilityUpdated]);
}
}
/* ROOM AVAILABILITY */
}
}
$bookingCode = is_null($bookingCode) ? 'ENW' . $param['booking']['search_key'] : $bookingCode;
$reservationConfirmParam = $channelService->reservationConfirmParam($param['channel_manager']['property_id'], $param['channel_manager']['booking_id'], $bookingCode, $param);
$reservationConfirm = $channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
$notificationCancelToPropertyUser = [
'booking_id' => $param['booking']['id'],
];
$this->mailer->onQueue('cancelBookingMail', new CancelBookingMail($notificationCancelToPropertyUser));
$response['status'] = true;
$response['data'] = $param;
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if ($response['status']) {
//PUSH CHANNEL MANAGER QUEUE
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'property_id', 'condition' => '=', 'value' => $bookingDetail['data']['property_id']],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $channelPropertyData) {
if(in_array($channelPropertyData['channel_manager_id'],[11,13])) {
continue;
}
$channelManagerBookingCreateParam = [
'property_id' => $bookingDetail['data']['property_id'],
'booking_id' => $bookingDetail['data']['id'],
'channel_manager_id' => $channelPropertyData['channel_manager_id'],
'type' => 'Cancel',
];
$channelManagerBookingCreate = $this->channelManagerBookingService->create($channelManagerBookingCreateParam);
}
}
//PUSH CHANNEL MANAGER QUEUE
DB::commit();
} else {
DB::rollBack();
}
return $response;
}
public function handle()
{
try {
$this->info(date('Y-m-d H:i:s') . ' : Start');
$channelManagerCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManager = $this->channelManagerService->select($channelManagerCriteria);
$channelManagerList = [];
if ($channelManager['status'] == 'success' && !empty($channelManager['data'])) {
$channelManagerList = $channelManager['data'];
}
//CHANNEL MANAGER
foreach ($channelManagerList as $channelKey => $channel) {
$this->info(date('Y-m-d H:i:s') . ' : Channel Start: ' . $channel['name']);
if (!class_exists("App\Core\Service\ChannelManager\\{$channel['name']}")) {
$this->error(date('Y-m-d H:i:s') . ' : Channel: ' . $channel['name'] . ' Class does not exist!');
continue;
}
$channelService = App::make("App\Core\Service\ChannelManager\\{$channel['name']}");
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $channel['id']],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping', 'property'],
'orderBy' => [
['field' => 'property_id', 'value' => 'ASC']
]
];
//TODO: Channex limited hotels
if ($channel['id'] == 2) {
$channexPullReservationPropertyIds = [71,313, /*538, 541, 545, 546, 548, 549, 550,*/ 672, 712, 785, 808, 790, 755, 901, 952, 912, 848, 1098, 1103, 1035];
$channelManagerPropertyMappingCriteria['whereIn'][] = ["field" => "property_id", "value" => $channexPullReservationPropertyIds];
}
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
//Eğer kanala ait bir otel yok ise devam et
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
continue;
}
if ($channelManagerPropertyMapping['status'] == 'success') {
//CHANNEL MANAGER PROPERTY
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
//Property
if (!in_array($propertyMapping['property']['id'],[623])) {
//continue;
}
$this->info(date('Y-m-d H:i:s') . ' : Property: ' . $propertyMapping['property']['id'] . ' - ' . $propertyMapping['property']['name']);
$reservationListParam = $channelService->reservationListParam($propertyMapping['channel_manager_property_id']);
$reservationList = $channelService->reservationList($reservationListParam);
//Eğer kanaldaki otele ait bir rezervasyon yok ise devam et
if (!$reservationList['status']) {
continue;
}
//CHANNEL MANAGER PROPERTY Reservation
foreach ($reservationList['data'] as $reservationKey => $reservation) {
$reservationPullFormatted = $channelService->reservationPullFormattedData($propertyMapping['property_id'], $propertyMapping['channel_manager_property_id'], $reservation);
if (!$reservationPullFormatted['status']) {
//Burada bi hata var demektir, mail atılsın ama sonraki işleme devam edilsin.
//$logMessage
$mailParams = [
'title' => $channel['name'] . ' - ReservationPullService Error - reservationPullFormatted',
'logMessage' => '<pre>' . print_r($reservationPullFormatted, true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->error(date('Y-m-d H:i:s') . ' : Property: ' . $propertyMapping['property']['id'] . ' - ' . $propertyMapping['property']['name'].' Error: reservationPullFormattedData');
continue;
}
//TODO: Eğer burada gelen kanal extranetwork ise alınmış gibi yapılıp diğer işleme geçilmeli
if (in_array($reservationPullFormatted['data']['channel_manager']['sub_channel'], ['ExtranetWork'])) {
$reservationConfirmParam = $channelService->reservationConfirmParam($reservationPullFormatted['data']['channel_manager']['property_id'], $reservationPullFormatted['data']['channel_manager']['booking_id'], 'ENW' . $reservationPullFormatted['data']['channel_manager']['booking_id'], $reservationPullFormatted['data']);
$reservationConfirm = $channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
continue;
}
$reservationPull = ['status' => false, 'message' => ''];
if ($reservationPullFormatted['type'] == 'createBooking') {
$reservationPull = $this->createBooking($channel['name'], $reservationPullFormatted['data']);
} elseif ($reservationPullFormatted['type'] == 'modifiedBooking') {
//If the modified reservation is not found, first create a reservation.
$bookingDetailParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $reservationPullFormatted['data']['booking']['property_id']],
['field' => 'search_key', 'condition' => '=', 'value' => $reservationPullFormatted['data']['booking']['search_key']],
],
'firstRow' => true
];
$bookingDetail = $this->bookingService->select($bookingDetailParam);
if (empty($bookingDetail['data'])) {
$reservationPull = $this->createBooking($channel['name'], $reservationPullFormatted['data']);
} else {
$reservationPull = $this->modifiedBooking($channel['name'], $reservationPullFormatted['data']);
}
} elseif ($reservationPullFormatted['type'] == 'cancelBooking') {
$reservationPull = $this->cancelBooking($channel['name'], $reservationPullFormatted['data']);
}
if ($reservationPull['status']) {
$this->info(date('Y-m-d H:i:s') . ' : Success ' . $reservationPullFormatted['type'] . ': ' . $reservationPull['data']['booking']['booking_code']);
} else {
//$logMessage
$mailParams = [
'title' => $channel['name'] . ' - ReservationPullService Error - Booking',
'logMessage' => '<pre>' . print_r(array_merge($reservationPullFormatted, $reservationPull), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $reservationPull['message']);
}
}
}
}
$this->info(PHP_EOL);
}
//dd($channelManagerList);
$this->info(date('Y-m-d H:i:s') . ' : Finished');
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}

View File

@@ -0,0 +1,150 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerBookingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class ReservationPushService extends Command
{
protected $signature = 'cron:reservation-push-service';
protected $description = '';
protected $channelService;
protected $channelManagerBookingService;
public function __construct(
Mailer $mailer,
Reseliva $channelService,
ChannelManagerBookingService $channelManagerBookingService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelService = $channelService;
$this->channelManagerBookingService = $channelManagerBookingService;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
$pendingBookingCriteria = [
'criteria' =>
[
//['field' => 'id', 'condition' => '=', 'value' => 22461],#21390
['field' => 'is_pushed', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'channelManager',
'bookingDetail.bookingContact', 'bookingDetail.bookingChannel',
'bookingDetail.bookingPayment', 'bookingDetail.bookingPaymentType',
'bookingDetail.bookingStatus', 'bookingDetail.bookingRoom.roomPax.paxCountry'
],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
'take' => 100
];
$pendingBooking = $this->channelManagerBookingService->select($pendingBookingCriteria);
if ($pendingBooking['status'] == 'success') {
$pendingBooking = $pendingBooking['data'];
foreach ($pendingBooking as $booking) {
try {
$this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id']);
$channelService = App::make("App\Core\Service\ChannelManager\\{$booking['channel_manager']['name']}");
$this->info(date('Y-m-d H:i:s') . ' : Channel: ' . $booking['channel_manager']['name']);
if ($booking['channel_manager_id'] == 10) {
//After 3 minutes, the faulty operation is set to status 2 for Hyperguest.
if (Carbon::createFromTimestamp($booking['created_at'])->diffInMinutes(Carbon::now()) > 3) {
$this->channelManagerBookingService->update($booking['id'], ['status' => 2]);
$this->error(date('Y-m-d H:i:s') . ' : Channel: ' . $booking['channel_manager']['name']);
continue;
}
}
//After 30 minutes, the faulty operation is set to status 2.
if (Carbon::createFromTimestamp($booking['created_at'])->diffInMinutes(Carbon::now()) > 30) {
$this->channelManagerBookingService->update($booking['id'], ['status' => 2]);
}
$requestPostReservationPushParam = $channelService->requestPostReservationPushParam($booking['property_id'], $booking['booking_id'], $booking['type'], $booking);
if (empty($requestPostReservationPushParam)) {
throw new ApiErrorException('requestPostReservationPushParam Error');
}
$this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id'] . ' Push');
$this->channelManagerBookingService->update($booking['id'], ['request' => $requestPostReservationPushParam]);
$requestPostReservationPush = $channelService->requestPostReservationPush($requestPostReservationPushParam);
if ($requestPostReservationPush['status']) {
$this->info(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id'] . ' Success');
$this->channelManagerBookingService->update($booking['id'], ['is_pushed' => 1, 'status' => 1, 'response' => $requestPostReservationPush['response']]);
} else {
//$logMessage
$mailParams = [
'title' => 'ReservationPushService Error - ChannelManagerName: ' . $booking['channel_manager']['name'],
'logMessage' => '<pre>' . print_r(array_merge($booking, $requestPostReservationPush), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->error(date('Y-m-d H:i:s') . ' : Booking ID: ' . $booking['booking_id'] . ' Failed');
$this->channelManagerBookingService->update($booking['id'], ['response' => $requestPostReservationPush['message']]);
}
} catch (ApiErrorException $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,262 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\ChannelManagerService;
use App\Core\Service\PropertyRoomAvailabilityQueueService;
use App\Exceptions\ApiErrorException;
use App\Models\PropertyRoomAvailabilityQueue;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class RoomAvailabilityPushService extends Command
{
protected $signature = 'cron:roomavailability-push-service';
protected $description = '';
protected $mailer;
protected $channelService;
protected $channelManagerService;
protected $propertyRoomAvailabilityQueueService;
public function __construct(
Mailer $mailer,
ChannelManagerService $channelManagerService,
PropertyRoomAvailabilityQueueService $propertyRoomAvailabilityQueueService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelManagerService = $channelManagerService;
$this->propertyRoomAvailabilityQueueService = $propertyRoomAvailabilityQueueService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
}
public function handle()
{
try {
$this->info(date('Y-m-d H:i:s') . ' : Start');
//Queue Check
$this->info(date('Y-m-d H:i:s') . ' : Queue Check');
$roomAvailabilityQueueCountCriteria = ['criteria' => [['field' => 'status', 'condition' => '=', 'value' => 1]], 'count' => true];
$roomAvailabilityQueueCount = $this->propertyRoomAvailabilityQueueService->select($roomAvailabilityQueueCountCriteria);
if ($roomAvailabilityQueueCount['status'] == 'success') {
$roomAvailabilityQueueCount = $roomAvailabilityQueueCount['data'];
if ($roomAvailabilityQueueCount > 2000) {
$roomAvailabilityQueueCountGroupByProperty = PropertyRoomAvailabilityQueue::selectRaw('property_id, COUNT(*) as total')
->groupBy('property_id')
->orderByDesc('total')
->first();
$roomAvailabilityQueueCountGroupByProperty = $roomAvailabilityQueueCountGroupByProperty ? $roomAvailabilityQueueCountGroupByProperty->toArray() : null;
if ($roomAvailabilityQueueCountGroupByProperty) {
if ($roomAvailabilityQueueCountGroupByProperty['total'] > 1000) {
PropertyRoomAvailabilityQueue::where('property_id', $roomAvailabilityQueueCountGroupByProperty['property_id'])->delete();
}
}
}
if ($roomAvailabilityQueueCount > 1000) {
$this->error(date('Y-m-d H:i:s') . ' : Queue Alarm: ' . $roomAvailabilityQueueCount);
//Clear Test Property Data
PropertyRoomAvailabilityQueue::where('property_id', 1)->delete();
//$logMessage
$mailParams = [
'title' => 'RoomAvailabilityPushService Error - Queue Error',
'logMessage' => 'Queue: ' . $roomAvailabilityQueueCount
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
}
}
//Queue Check
$channelManagerCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
],
/*'whereIn' =>
[
['field' => 'id', "value" => [7]]
],*/
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManager = $this->channelManagerService->select($channelManagerCriteria);
$channelManagerList = [];
if ($channelManager['status'] == 'success' && !empty($channelManager['data'])) {
$channelManagerList = $channelManager['data'];
}
$roomAvailabilityQueueCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['property'/*, 'propertyChannelManager.channelManagerRoomRate.propertyRoomRateMapping'*/],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
'take' => 500
];
$roomAvailabilityQueue = $this->propertyRoomAvailabilityQueueService->select($roomAvailabilityQueueCriteria);
if ($roomAvailabilityQueue['status'] == 'success' && !empty($roomAvailabilityQueue['data'])) {
foreach ($roomAvailabilityQueue['data'] as $data) {
$roomAvailabilityQueueData[$data['property_id']][] = $data;
}
$channelManagerPushedIdsList = [];
$channelManagerNoneMappingIdsList = [];
//PROPERTY
foreach ($roomAvailabilityQueueData as $roomAvailabilityQueuePropertyId => $roomAvailabilityQueueProperty) {
//CHANNEL MANAGER
$channelManagerCheckList = [];
foreach ($channelManagerList as $channelKey => $channel) {
if (in_array($channel['id'], [7, 10, 13])) {
continue;
}
$this->info(date('Y-m-d H:i:s') . ' : Channel Start: ' . $channel['name']);
if (!class_exists("App\Core\Service\ChannelManager\\{$channel['name']}")) {
$this->error(date('Y-m-d H:i:s') . ' : Channel: ' . $channel['name'] . ' Class does not exist!');
continue;
}
$channelService = App::make("App\Core\Service\ChannelManager\\{$channel['name']}");
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $roomAvailabilityQueuePropertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $channel['id']],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'firstRow' => true,
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] != 'success' || ($channelManagerPropertyMapping['status'] == 'success' && empty($channelManagerPropertyMapping['data']))) {
$this->info(date('Y-m-d H:i:s') . ' : Channel: ' . $channel['name'] . ' PropertyID: ' . $roomAvailabilityQueuePropertyId . ' : PASS');
continue;
}
$channelManagerCheckList[$channel['id']] = true;
$roomAvailabilityPush = $channelService->roomAvailabilityPush($roomAvailabilityQueuePropertyId, $roomAvailabilityQueueProperty);
if ($roomAvailabilityPush['status']) {
$channelManagerPushedIdsList[$channel['id']] = $roomAvailabilityPush['data']['channelManagerPushedIds'];
$channelManagerNoneMappingIdsList[$channel['id']] = $roomAvailabilityPush['data']['channelManagerNoneMappingIds'];
$this->info(date('Y-m-d H:i:s') . ' : Success: ' . $channel['name']);
} else {
$channelManagerCheckList[$channel['id']] = false;
//$logMessage
$mailParams = [
'title' => $channel['name'] . ' - RoomAvailabilityPushService Error - inventoryRoomRateUpdate Error',
'logMessage' => '<pre>' . print_r($roomAvailabilityPush, true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $channel['name'] . ' - ' . $roomAvailabilityPush['message']);
}
$this->info(date('Y-m-d H:i:s') . ' : Channel Finished: ' . $channel['name']);
}
if (in_array(false, $channelManagerCheckList)) {
$this->error(date('Y-m-d H:i:s') . ' : Error Break: ' . var_export($channelManagerCheckList));
continue;
}
if (count($channelManagerPushedIdsList) > 1) {
$channelManagerPushedIdIntersect = call_user_func_array('array_intersect', $channelManagerPushedIdsList);
if (!empty($channelManagerPushedIdIntersect)) {
$this->propertyRoomAvailabilityQueueService->delete($channelManagerPushedIdIntersect);
$this->info(date('Y-m-d H:i:s') . ' : channelManagerPushedIdsList Deleted: ' . var_dump($channelManagerPushedIdIntersect));
}
} elseif (!empty($channelManagerPushedIdsList)) {
$this->propertyRoomAvailabilityQueueService->delete(reset($channelManagerPushedIdsList));
$this->info(date('Y-m-d H:i:s') . ' : channelManagerPushedIdsList Deleted: ' . var_dump($channelManagerPushedIdsList));
}
if (empty($channelManagerNoneMappingIdsList)) {
$this->info(date('Y-m-d H:i:s') . ' : channelManagerNoneMappingIdsList Empty');
continue;
}
$channelManagerNoneMappingIdsListMerge = call_user_func_array('array_merge', $channelManagerNoneMappingIdsList);
if (!empty($channelManagerNoneMappingIdsListMerge)) {
$this->propertyRoomAvailabilityQueueService->delete($channelManagerNoneMappingIdsListMerge);
$this->info(date('Y-m-d H:i:s') . ' : channelManagerNoneMappingIdsListMerge Deleted: ' . var_dump($channelManagerNoneMappingIdsListMerge));
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}

View File

@@ -0,0 +1,255 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\ChannelManagerService;
use App\Core\Service\PropertyRoomAvailabilityQueueService;
use App\Core\Service\PropertyRoomRatePriceQueueService;
use App\Exceptions\ApiErrorException;
use App\Models\PropertyRoomRatePriceQueue;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class RoomRatePushService extends Command
{
protected $signature = 'cron:roomrate-push-service';
protected $description = '';
protected $mailer;
protected $channelService;
protected $propertyRoomRatePriceQueueService;
protected $channelManagerService;
protected $propertyRoomAvailabilityQueueService;
public function __construct(
Mailer $mailer,
PropertyRoomRatePriceQueueService $propertyRoomRatePriceQueueService,
ChannelManagerService $channelManagerService,
PropertyRoomAvailabilityQueueService $propertyRoomAvailabilityQueueService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->propertyRoomRatePriceQueueService = $propertyRoomRatePriceQueueService;
$this->channelManagerService = $channelManagerService;
$this->propertyRoomAvailabilityQueueService = $propertyRoomAvailabilityQueueService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
}
public function handle()
{
//$request = $this->channelService->productList(14480);
try {
$this->info(date('Y-m-d H:i:s') . ' : Start');
//Queue Check
$this->info(date('Y-m-d H:i:s') . ' : Queue Check');
$roomRatePriceQueueCountCriteria = ['criteria' => [['field' => 'status', 'condition' => '=', 'value' => 1]],'count' => true];
$roomRatePriceQueueCount = $this->propertyRoomRatePriceQueueService->select($roomRatePriceQueueCountCriteria);
if($roomRatePriceQueueCount['status'] == 'success') {
$roomRatePriceQueueCount = $roomRatePriceQueueCount['data'];
if($roomRatePriceQueueCount > 1000) {
$this->error(date('Y-m-d H:i:s') . ' : Queue Alarm: '. $roomRatePriceQueueCount);
//Clear Test Property Data
PropertyRoomRatePriceQueue::where('property_id',1)->delete();
//$logMessage
$mailParams = [
'title' => 'RoomRatePushService Error - Queue Error',
'logMessage' => 'Queue: '.$roomRatePriceQueueCount
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
}
}
//Queue Check
$channelManagerCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
],
/*'whereIn' =>
[
['field' => 'id', "value" => [7]]
],*/
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManager = $this->channelManagerService->select($channelManagerCriteria);
$channelManagerList = [];
if ($channelManager['status'] == 'success' && !empty($channelManager['data'])) {
$channelManagerList = $channelManager['data'];
}
$roomRatePriceQueueCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['property'/*, 'propertyChannelManager.channelManagerRoomRate'*/],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
'take' => 500
];
$roomRatePriceQueue = $this->propertyRoomRatePriceQueueService->select($roomRatePriceQueueCriteria);
if ($roomRatePriceQueue['status'] == 'success' && !empty($roomRatePriceQueue['data'])) {
foreach ($roomRatePriceQueue['data'] as $data) {
$roomRatePriceQueueData[$data['property_id']][] = $data;
}
$channelManagerPushedIdsList = [];
$channelManagerNoneMappingIdsList = [];
//PROPERTY
foreach ($roomRatePriceQueueData as $roomRatePriceQueuePropertyId => $roomRatePriceQueueProperty) {
//CHANNEL MANAGER
$channelManagerCheckList = [];
foreach ($channelManagerList as $channelKey => $channel) {
if(in_array($channel['id'],[7,10, 13])) {
continue;
}
$this->info(date('Y-m-d H:i:s') . ' : Channel Start: ' . $channel['name']);
if(!class_exists("App\Core\Service\ChannelManager\\{$channel['name']}")) {
$this->error(date('Y-m-d H:i:s') . ' : Channel: ' . $channel['name'].' Class does not exist!');
continue;
}
$channelService = App::make("App\Core\Service\ChannelManager\\{$channel['name']}");
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $roomRatePriceQueuePropertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $channel['id']],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'firstRow' => true,
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] != 'success' || ($channelManagerPropertyMapping['status'] == 'success' && empty($channelManagerPropertyMapping['data']))) {
$this->info(date('Y-m-d H:i:s') . ' : Channel: ' . $channel['name'] . ' PropertyID: ' . $roomRatePriceQueuePropertyId . ' : PASS');
continue;
}
$channelManagerCheckList[$channel['id']] = true;
$roomRatePricePush = $channelService->roomRatePricePush($roomRatePriceQueuePropertyId, $roomRatePriceQueueProperty);
if ($roomRatePricePush['status']) {
if (!empty($roomRatePricePush['data']['channelManagerPushedIds']) || !empty($roomRatePricePush['data']['channelManagerNoneMappingIds'])) {
$channelManagerPushedIdsList[$channel['id']] = $roomRatePricePush['data']['channelManagerPushedIds'];
$channelManagerNoneMappingIdsList[$channel['id']] = $roomRatePricePush['data']['channelManagerNoneMappingIds'];
}
$this->info(date('Y-m-d H:i:s') . ' : Channel Success: ' . $channel['name']);
} else {
$channelManagerCheckList[$channel['id']] = false;
//$logMessage
$mailParams = [
'title' => $channel['name'] . ' - RoomRatePushService Error - InventoryRoomRateUpdate Error',
'logMessage' => '<pre>' . print_r($roomRatePricePush, true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $channel['name'] . ' - ' . $roomRatePricePush['message']);
}
$this->info(date('Y-m-d H:i:s') . ' : Channel Finished: ' . $channel['name']);
}
/*foreach ($channelManagerPushedIdsList as $key => $channelManagerPushedIds) {
if(empty($channelManagerPushedIds)) {
unset($channelManagerPushedIdsList[$key]);
}
}*/
if (in_array(false, $channelManagerCheckList)) {
$this->error(date('Y-m-d H:i:s') . ' : Error Break: ' . var_export($channelManagerCheckList));
continue;
}
if (count($channelManagerPushedIdsList) > 1) {
$channelManagerPushedIdIntersect = call_user_func_array('array_intersect', $channelManagerPushedIdsList);
if (!empty($channelManagerPushedIdIntersect)) {
$this->propertyRoomRatePriceQueueService->delete($channelManagerPushedIdIntersect);
$this->info(date('Y-m-d H:i:s') . ' : $channelManagerPushedIdsList Deleted: ' . var_export($channelManagerPushedIdIntersect));
}
} elseif (!empty($channelManagerPushedIdsList)) {
$this->propertyRoomRatePriceQueueService->delete(reset($channelManagerPushedIdsList));
$this->info(date('Y-m-d H:i:s') . ' : $channelManagerPushedIdsList Deleted: ' . var_export($channelManagerPushedIdsList));
}
if (!empty($channelManagerNoneMappingIdsList)) {
$channelManagerNoneMappingIdsListMerge = call_user_func_array('array_merge', $channelManagerNoneMappingIdsList);
if (!empty($channelManagerNoneMappingIdsListMerge)) {
$this->propertyRoomRatePriceQueueService->delete($channelManagerNoneMappingIdsListMerge);
$this->info(date('Y-m-d H:i:s') . ' : $channelManagerNoneMappingIdsListMerge Deleted: ' . var_dump($channelManagerNoneMappingIdsListMerge));
}
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}

View File

@@ -0,0 +1,497 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\ChannelManagerService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomAvailabilityQueueService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ReselivaAvailRateUpdateService extends Command
{
protected $signature = 'cron:reseliva-availrateupdate-service';
protected $description = '';
protected $mailer;
public function __construct(
Mailer $mailer,
PropertyRoomService $propertyRoomService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
ChannelManagerLogService $channelManagerLogService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->propertyRoomService = $propertyRoomService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->channelManagerLogService = $channelManagerLogService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
}
public function propertyChannelMapping($propertyId, $channelId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId, $channelId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId, $channelId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $channelId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function handle()
{
$this->info(date('Y-m-d H:i:s') . ' : Start');
$channelId = 1;
$channelManagerId = 1;
$channelManagerLogCriteria = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => 32670],
['field' => 'service', 'condition' => '=', 'value' => 'AvailRateUpdate'],
['field' => 'status', 'condition' => '=', 'value' => null],
],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerLog = $this->channelManagerLogService->select($channelManagerLogCriteria);
if ($channelManagerLog['status'] && !empty($channelManagerLog['data'])) {
foreach ($channelManagerLog['data'] as $logData) {
$response = ['status' => false, 'message' => ''];
$payloadXML = simplexml_load_string($logData['request']);
$payloadParam = json_decode(json_encode($payloadXML), 1);
try {
$propertyId = $payloadParam['Hotel']['@attributes']['id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId, $channelId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId, $channelId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId, $channelId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$availRateUpdates = singleElementXMLArray($payloadParam['AvailRateUpdate']);
DB::beginTransaction();
foreach ($availRateUpdates as $availRateUpdate) {
$dateRange = [];
$dateRange['startDate'] = $availRateUpdate['DateRange']['@attributes']['from'];
$dateRange['finishDate'] = $availRateUpdate['DateRange']['@attributes']['to'];
if (Carbon::parse($dateRange['startDate'])->isBefore(Carbon::now()->toDateString()) || Carbon::parse($dateRange['finishDate'])->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
$roomTypes = singleElementXMLArray($availRateUpdate['RoomType']);
$this->info(date('Y-m-d H:i:s') . ' : ' . $dateRange['startDate'] . ' - ' . $dateRange['finishDate']);
foreach ($roomTypes as $roomType) {
$roomId = $roomType['@attributes']['id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Tanımlı ya da aktif olmayan oda');
}
$totalInventoryAvailable = null;
if (isset($roomType['Inventory']['@attributes']['totalInventoryAvailable'])) {
$totalInventoryAvailable = $roomType['Inventory']['@attributes']['totalInventoryAvailable'];
}
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $dateRange['startDate'],
'end_date' => $dateRange['finishDate'],
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
$this->info(date('Y-m-d H:i:s') . ' : Update Type: ' . $requestParams['update_type']);
}
if (isset($roomType['RatePlan'])) {
$ratePlans = singleElementXMLArray($roomType['RatePlan']);
foreach ($ratePlans as $ratePlan) {
$roomRateMappingId = $ratePlan['@attributes']['id'];
$isCloseRoomRateMappingSale = null;
if (isset($ratePlan['@attributes']['closed'])) {
$isCloseRoomRateMappingSale = $ratePlan['@attributes']['closed'] == 'true' ? true : false;
}
$channelRoomRateMappingCheck = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->isEmpty();
if ($channelRoomRateMappingCheck) {
throw new ApiErrorException('Tanımlı ya da aktif olmayan oda konaklama');
}
$roomRates = [
'room_id' => $roomId,
'room_rate_mapping_id' => [
$roomRateMappingId
]
];
$paramsListChannel = [];
$paramsListChannel[] = 1;
//CONNECTED CHANNEL RATE UPDATE
$propertyChannelMappingConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $requestParamBase['property_id']],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $requestParamBase['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel']
];
$propertyChannelMappingConnected = $this->propertyChannelMappingService->select($propertyChannelMappingConnectedCriteria);
if ($propertyChannelMappingConnected['status'] == 'success') {
foreach ($propertyChannelMappingConnected['data'] as $channel) {
if (!is_null($channel['channel']['parent_id'])) {
continue;
}
$paramsListChannel[] = $channel['channel_id'];
}
}
//CONNECTED CHANNEL RATE UPDATE
foreach ($paramsListChannel as $paramChannelId) {
//Eğer Rate var ise currency check yapılmalı ve PerDay var mı check edilmeli, burada sonra günceleme yaptırılabilri
if (isset($ratePlan['Rate'])) {
$currency = $ratePlan['Rate']['@attributes']['currency'];
$currencyCheck = ($currency == $propertyChannelMapping['currency_code']) ? true : false;
if (!$currencyCheck) {
throw new ApiErrorException('Kanal döviz kuru ile eşleşmeyen döviz kuru, kanal döviz kuru: ' . $propertyChannelMapping['currency_code']);
}
$channelRoomRateMapping = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->first();
$amountPerDay = $ratePlan['Rate']['PerDay']['@attributes']['rate'];
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate';
$requestParams['value'] = $amountPerDay;
$requestParams['room_rates'] = [$roomRates];
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
$this->info(date('Y-m-d H:i:s') .
' : Update Type: ' .$requestParams['update_type'].
' : Channel ID: '. $requestParams['channel_id'].
' : Room ID: '. $roomRates['room_id']
);
}
//Room Rate Stop Sale
if (!is_null($isCloseRoomRateMappingSale)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate_stop_sell';
$requestParams['value'] = $isCloseRoomRateMappingSale ? 1 : 0;
$requestParams['room_rates'] = [$roomRates];
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
$this->info(date('Y-m-d H:i:s') . ' : Update Type: ' . $requestParams['update_type']);
}
//Kısıtlamalar var ise min los
if (isset($ratePlan['Restrictions'])) {
//Minimum Konaklama Gün Sayısı
if (isset($ratePlan['Restrictions']['@attributes']['minLOS'])) {
$minStay = $ratePlan['Restrictions']['@attributes']['minLOS'];
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'min_stay';
$requestParams['value'] = $minStay;
$requestParams['room_rates'] = [$roomRates];
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
$this->info(date('Y-m-d H:i:s') . ' : Update Type: ' . $requestParams['update_type']);
}
}
}
}
}
}
}
$response['status'] = true;
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
$channelManagerLog = $this->channelManagerLogService->update($logData['id'], $updateDataLog);
DB::commit();
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
//TODO: mail
if (!$response['status']) {
DB::rollBack();
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
}
}

View File

@@ -0,0 +1,784 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\CancelBookingMail;
use App\Core\Mail\LogMail;
use App\Core\Mail\ModifiedBookingMail;
use App\Core\Service\BookingContactService;
use App\Core\Service\BookingPaymentService;
use App\Core\Service\BookingRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\ChannelManagerPropertyRateMappingService;
use App\Core\Service\NewBookingMailService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ReservationPullService extends Command
{
protected $signature = 'cron:reservation-pull-service';
protected $description = '';
protected $mailer;
protected $channelService;
protected $channelManagerPropertyMappingService;
protected $bookingService;
protected $propertyRoomAvailabilityService;
protected $newBookingMailService;
public function __construct(
Mailer $mailer,
Reseliva $channelService,
ChannelManagerMappingService $channelManagerMappingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
BookingService $bookingService,
BookingContactService $bookingContactService,
BookingRoomService $bookingRoomService,
BookingPaymentService $bookingPaymentService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
NewBookingMailService $newBookingMailService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelService = $channelService;
$this->channelManagerMappingService = $channelManagerMappingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->bookingService = $bookingService;
$this->bookingContactService = $bookingContactService;
$this->bookingRoomService = $bookingRoomService;
$this->bookingPaymentService = $bookingPaymentService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->newBookingMailService = $newBookingMailService;
}
public function reservationListParam($channelManagerPropertyId)
{
$userId = Config::get('app.channelManager.reseliva.userId');
$userPSW = Config::get('app.channelManager.reseliva.userPassword');
$requestParam = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><request></request>');
$Authentication = $requestParam->addChild('Authentication');
$Authentication->addChild('UserID', $userId);
$Authentication->addChild('UserPSW', $userPSW);
$Authentication->addChild('PropertyID', $channelManagerPropertyId);
return $requestParam->asXML();
}
public function reservationConfirmParam($propertyId, $channelManagerBookingId, $bookingCode)
{
$userId = Config::get('app.channelManager.reseliva.userId');
$userPSW = Config::get('app.channelManager.reseliva.userPassword');
$requestParam = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><request></request>');
$Authentication = $requestParam->addChild('Authentication');
$Authentication->addChild('UserID', $userId);
$Authentication->addChild('UserPSW', $userPSW);
$Authentication->addChild('PropertyID', $propertyId);
$reservations = $requestParam->addChild('reservations');
$reservation = $reservations->addChild('reservation');
$reservation->addAttribute('reseliva_id', $channelManagerBookingId);
$reservation->addAttribute('pms_id', $bookingCode);
return $requestParam->asXML();
}
public function getDateByDay($dates = [])
{
$dateByDay = [];
$diffInDays = Carbon::parse($dates['checkIn'])->floatDiffInDays(Carbon::parse($dates['checkOut']));
for ($i = 0; $i < $diffInDays; $i++) {
$dateByDay[] = Carbon::parse($dates['checkIn'])->addDay($i)->format('Y-m-d');
}
return $dateByDay;
}
public function createBooking($param)
{
$response = ['status' => false, 'message' => ''];
DB::beginTransaction();
try {
$bookingCode = getCodeGenerate('BKG');
$bookingStatus = 1;
$roomRequest = [];
foreach ($param['room'] as $room) {
$roomRequest[] = [
'adults' => $room['totalpax'],
'children' => $room['totalchd'],
'age' => []
];
}
if (empty(fillOnUndefined($param, 'reservno_ota'))) {
$param['reservno_ota'] = null;
}
$bookingCreateParam = [
'property_id' => $param['property']['id'],
'channel_id' => $param['property']['channel_id'],
'booking_code' => $bookingCode,
'channel_booking_code' => fillOnUndefined($param, 'reservno_ota'),
'search_key' => $param['reservno'],
'checkin_date' => $param['checkinFormatted'],
'checkout_date' => $param['checkoutFormatted'],
'rooms' => json_encode($roomRequest),
'payment_type_code' => 'CHN',
'room_amount' => $param['paymenttotal'],
'addon_amount' => 0,
'discount_amount' => 0,
'total' => $param['paymenttotal'],
'currency_code' => $param['paymentcurr'],
'channel_token' => null,
'booking_engine_token' => null,
'reservation_time' => $param['restimeUnixFormatted'],
'status' => $param['status'] == 'A' ? 1 : 0
];
$bookingCreate = $this->bookingService->create($bookingCreateParam);
//$bookingCreate['status'] = 'success';
//$bookingCreate['data']['id'] = 52;
if ($bookingCreate['status'] != 'success') {
throw new ApiErrorException(lang('Booking could not be made, Reservation: ' . $param['reservno']));
}
//INSERT CONTACT DATA
$bookingContactCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'name' => $param['firstname'],
'surname' => !empty($param['lastname']) ? $param['lastname'] : null,
'phone_code' => null,
'phone_number' => $param['tel'],
'email' => $param['email'],
'note' => !empty($param['note']) ? $param['note'] : null,
'language_code' => fillOnUndefined($param, 'language', 'en'),
'status' => 1
];
$bookingContactCreate = $this->bookingContactService->create($bookingContactCreateParam);
//$bookingContactCreate['status'] = 'success';
if ($bookingContactCreate['status'] != 'success') {
throw new ApiErrorException(lang('Booking Contact could not be made'));
}
//INSERT ROOM DATA
foreach ($param['room'] as $roomOrder => $room) {
$bookingRoomCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'room_order_number' => ($roomOrder + 1),
'occupancy_code' => str_repeat('A', $room['totalpax']) . str_repeat('C', $room['totalchd']),
'checkin_date' => $param['checkinFormatted'], //$room['checkin'],
'checkout_date' => $param['checkoutFormatted'],//$room['checkout'],
'rate_key' => null,
'rate_key_code' => null,
'availability_id' => 1,
'availability_code' => 'ROM',
'room_id' => $room['property']['room_id'],
'room_name' => $room['roomtype'],
'room_rate_mapping_id' => $room['property']['room_rate_mapping_id'],
'room_rate_name' => $room['ratename'],
'cancellation_policy' => null,
'payment_type_code' => 'CHN',
'rate_detail' => json_encode($room),
'total' => $room['total_amount'],
'currency_code' => $param['paymentcurr'],
'status' => $param['status'] == 'A' ? 1 : 0
];
$bookingRoomCreate = $this->bookingRoomService->create($bookingRoomCreateParam);
//$bookingRoomCreate['status'] = 'success';
if ($bookingRoomCreate['status'] != 'success') {
throw new ApiErrorException(lang('Booking Room could not be made'));
}
/* ROOM AVAILABILITY */
$dateByDay = [];
$dateByDay = $this->getDateByDay(['checkIn' => $room['checkin'], 'checkOut' => $room['checkout']]);
foreach ($dateByDay as $day) {
$requestParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['property']['id']],
['field' => 'property_room_id', 'condition' => '=', 'value' => $room['property']['room_id']],
['field' => 'availability_type_id', 'condition' => '=', 'value' => 1],
['field' => 'date', 'condition' => '=', 'value' => $day]
],
];
$getPropertyRoomAndRoomRateAvailability = $this->propertyRoomAvailabilityService->select($requestParam);
if ($getPropertyRoomAndRoomRateAvailability['status'] != 'success') {
throw new ApiErrorException('getPropertyRoomAndRoomRateAvailability Empty');
}
foreach ($getPropertyRoomAndRoomRateAvailability['data'] as $roomAvailability) {
$roomAvailabilityUpdated = $roomAvailability['availability'] <= 0 ? 0 : ($roomAvailability['availability'] - 1);
$this->propertyRoomAvailabilityService->update($roomAvailability['id'], ['availability' => $roomAvailabilityUpdated]);
}
}
/* ROOM AVAILABILITY */
}
//INSERT PAYMENT DATA
$bookingPaymentCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'payment_code' => (isset($param['cc_token']) && !empty($param['cc_token'])) ? fillOnUndefined($param, 'cc_token') : null,
'payment_type_code' => 'CHN',
'total' => $param['paymenttotal'],
'currency_code' => $param['paymentcurr'],
'status' => 2
];
$bookingPaymentCreate = $this->bookingPaymentService->create($bookingPaymentCreateParam);
//$bookingContactCreate['status'] = 'success';
if ($bookingPaymentCreate['status'] != 'success') {
throw new ApiErrorException(lang('Booking Payment could not be made'));
}
//INSERT PAYMENT DATA
//INSERT CHANNEL PAYMENT DATA
if (isset($param['cc_token']) && !empty($param['cc_token'])) {
$bookingPaymentDataCreateParam = [
'booking_id' => $bookingCreate['data']['id'],
'type' => 'ch',
'data' => md5($param['reservno'].$param['channelManagerPropertyId'].$param['cc_token'])
];
$bookingPaymentDataCreate = $this->bookingPaymentService->createPaymentData($bookingPaymentDataCreateParam);
if ($bookingPaymentDataCreate['status'] != 'success') {
throw new ApiErrorException(lang('Booking Payment could not be made'));
}
}
//INSERT CHANNEL PAYMENT DATA
//$param['reservno'] = '27145472222';
$reservationConfirmParam = $this->reservationConfirmParam($param['channelManagerPropertyId'], $param['reservno'], $bookingCode);
$reservationConfirm = $this->channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
DB::commit();
$mailParams = ['booking_id' => $bookingCreate['data']['id']];
$this->newBookingMailService->process($mailParams);
$response['status'] = true;
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
DB::rollBack();
}
return $response;
}
public function cancelBooking($param)
{
$response = ['status' => false, 'message' => ''];
DB::beginTransaction();
try {
$bookingCode = null;
$bookingDetailParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['property']['id']],
['field' => 'search_key', 'condition' => '=', 'value' => $param['reservno']]
],
'with' => ['bookingRoom'],
'firstRow' => true
];
$bookingDetail = $this->bookingService->select($bookingDetailParam);
if ($bookingDetail['status'] != 'success') {
throw new ApiErrorException(lang('Booking could not be found, Reservation: ' . $param['reservno']));
}
if (!empty($bookingDetail['data'])) {
$bookingCode = $bookingDetail['data']['booking_code'];
$this->bookingService->update($bookingDetail['data']['id'], ['status' => 0]);
foreach ($bookingDetail['data']['booking_room'] as $roomOrder => $room) {
$bookingRoomCreate = $this->bookingRoomService->update($room['id'], ['status' => 0]);
/* ROOM AVAILABILITY */
$dateByDay = [];
$dateByDay = $this->getDateByDay(['checkIn' => $room['checkin_date'], 'checkOut' => $room['checkout_date']]);
foreach ($dateByDay as $day) {
$requestParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['property']['id']],
['field' => 'property_room_id', 'condition' => '=', 'value' => $room['room_id']],
['field' => 'availability_type_id', 'condition' => '=', 'value' => 1],
['field' => 'date', 'condition' => '=', 'value' => $day]
],
];
$getPropertyRoomAndRoomRateAvailability = $this->propertyRoomAvailabilityService->select($requestParam);
if ($getPropertyRoomAndRoomRateAvailability['status'] != 'success') {
throw new ApiErrorException('getPropertyRoomAndRoomRateAvailability Empty');
}
foreach ($getPropertyRoomAndRoomRateAvailability['data'] as $roomAvailability) {
$roomAvailabilityUpdated = $roomAvailability['availability'] <= 0 ? 1 : ($roomAvailability['availability'] + 1);
$this->propertyRoomAvailabilityService->update($roomAvailability['id'], ['availability' => $roomAvailabilityUpdated]);
}
}
/* ROOM AVAILABILITY */
}
}
$response['status'] = true;
$bookingCode = is_null($bookingCode) ? 'ENW' . $param['reservno'] : $bookingCode;
$reservationConfirmParam = $this->reservationConfirmParam($param['channelManagerPropertyId'], $param['reservno'], $bookingCode);
$reservationConfirm = $this->channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
$notificationCancelToPropertyUser = [
'channel' => $param['otaname'],
'channelBookingCode' => $param['reservno_ota'],
'propertyChannelManager' => $param['otaname'],//$channelManagerMapping['property_channel_manager']['name'],
'nameSurname' => $param['firstname'] . ' ' . $param['lastname'],
'propertyId' => $param['property']['id'],
];
$this->mailer->onQueue('cancelBookingMail', new CancelBookingMail($notificationCancelToPropertyUser));
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return $response;
}
public function modifiedBooking($param)
{
$response = ['status' => false, 'message' => ''];
DB::beginTransaction();
try {
$bookingCode = null;
$bookingDetailParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $param['property']['id']],
['field' => 'search_key', 'condition' => '=', 'value' => $param['reservno']]
],
'with' => ['bookingRoom', 'bookingContact'],
'firstRow' => true
];
$bookingDetail = $this->bookingService->select($bookingDetailParam);
if ($bookingDetail['status'] != 'success') {
throw new ApiErrorException(lang('Booking could not be found, Reservation: ' . $param['reservno']));
}
if (!empty($bookingDetail['data'])) {
$bookingCode = $bookingDetail['data']['booking_code'];
$bookingUpdateParam = [
'channel_booking_code' => fillOnUndefined($param, 'reservno_ota'),
'search_key' => $param['reservno'],
'checkin_date' => $param['checkinFormatted'],
'checkout_date' => $param['checkoutFormatted'],
'payment_type_code' => 'CHN',
'total' => $param['paymenttotal'],
'currency_code' => $param['paymentcurr'],
];
$bookingUpdate = $this->bookingService->update($bookingDetail['data']['id'], $bookingUpdateParam);
$bookingContactUpdateParam = [
'name' => $param['firstname'],
'surname' => $param['lastname'],
'phone_code' => null,
'phone_number' => $param['tel'],
'email' => $param['email'],
'note' => !empty($param['note']) ? $param['note'] : null,
'language_code' => fillOnUndefined($param, 'language', 'en')
];
$bookingContactUpdate = $this->bookingContactService->update($bookingDetail['data']['booking_contact']['id'], $bookingContactUpdateParam);
foreach ($bookingDetail['data']['booking_room'] as $roomOrder => $room) {
foreach ($param['room'] as $roomOrderChannel => $roomChannel) {
if ($roomOrder == $roomOrderChannel) {
$bookingRoomUpdateParam = [
'occupancy_code' => str_repeat('A', $roomChannel['totalpax']) . str_repeat('C', $roomChannel['totalchd']),
'checkin_date' => $roomChannel['checkin'],
'checkout_date' => $roomChannel['checkout'],
'room_id' => $roomChannel['property']['room_id'],
'room_name' => $roomChannel['roomtype'],
'room_rate_mapping_id' => $roomChannel['property']['room_rate_mapping_id'],
'room_rate_name' => $roomChannel['ratename'],
'rate_detail' => json_encode($roomChannel),
'total' => $roomChannel['total_amount'],
'currency_code' => $param['paymentcurr'],
];
$bookingRoomUpdate = $this->bookingRoomService->update($room['id'], $bookingRoomUpdateParam);
}
}
}
}
$response['status'] = true;
$bookingCode = is_null($bookingCode) ? 'ENW' . $param['reservno'] : $bookingCode;
$reservationConfirmParam = $this->reservationConfirmParam($param['channelManagerPropertyId'], $param['reservno'], $bookingCode);
$reservationConfirm = $this->channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
$notificationModifiedToPropertyUser = [
'channel' => $param['otaname'],
'channelBookingCode' => $param['reservno_ota'],
'propertyChannelManager' => $param['otaname'],//$channelManagerMapping['property_channel_manager']['name'],
'nameSurname' => $param['firstname'] . ' ' . $param['lastname'],
'propertyId' => $param['property']['id'],
];
$this->mailer->onQueue('modifiedBookingMail', new ModifiedBookingMail($notificationModifiedToPropertyUser));
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return $response;
}
public function handle()
{
//$request = $this->channelService->productList(14480);
try {
/*
1. Reseliva mapping olan oteller çekilecek
2. Her otel için foreach ile reservaion servisi çağrılacak
3. Gelen bilgiler enw ye işlenecek, sonra da confirmcheck yapılacak
* */
$this->info(date('Y-m-d H:i:s') . ' : Start');
$channelManagerMappingCriteria =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['propertyChannelManager'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerMappingData = $this->channelManagerMappingService->select($channelManagerMappingCriteria);
$channelManagerMappingCollect = collect($channelManagerMappingData['data']);
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => 1],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
//['field' => 'property_id', 'condition' => '=', 'value' => 326],//TODO: Delete
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success') {
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
$channelManagerRoomRateCollect = collect($propertyMapping['channel_manager_room_rate']);
$reservationListParam = $this->reservationListParam($propertyMapping['channel_manager_property_id']);
$reservationList = $this->channelService->reservationList($reservationListParam);
if (!$reservationList['status']) {
//$logMessage
$mailParams = [
'title' => 'ReservationPullService Error - ReservationList Error',
'logMessage' => '<pre>' . $reservationListParam . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
throw new ApiErrorException('ReservationList Error: ' . $reservationList['message']);
}
foreach ($reservationList['data'] as $reservationKey => $reservation) {
//Check Channel Manager Mapping
$channelManagerMapping = $channelManagerMappingCollect->where('channel_manager_channel_id', $reservation['otaname'])->first();
//Eğer ExtranetWork ise içeri almadan onayla
if ($reservation['otaname'] == 'ExtranetWork') {
$reservationConfirmParam = $this->reservationConfirmParam($propertyMapping['channel_manager_property_id'], $reservation['reservno'], 'ENWRES' . $reservation['reservno']);
//$reservationConfirm = $this->channelService->reservationConfirm($reservationConfirmParam);
$reservationConfirm['status'] = true;
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
continue;
}
if (empty($channelManagerMapping)) {
//Eğer mapping yapılmış kanal bulunamamış ise rezervasyonu içeri alamazsın
//$logMessage
$mailParams = [
'title' => 'ReservationPullService Error - Channel Manager Mapping',
'logMessage' => '<pre>' . print_r(array_merge($propertyMapping, $reservation), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
unset($reservationList['data'][$reservationKey]);
continue;
}
$reservationList['data'][$reservationKey]['property']['id'] = $propertyMapping['property_id'];
$reservationList['data'][$reservationKey]['property']['channel_id'] = $channelManagerMapping['property_channel_id'];
foreach ($reservation['room'] as $roomKey => $room) {
//Check Room Rate Mapping
$channelManagerRoomRate = $channelManagerRoomRateCollect->where('channel_manager_room_id', $room['roomid'])->where('channel_manager_room_rate_id', $room['rateid'])->first();
if (empty($channelManagerRoomRate)) {
$channelManagerRoomRate = $channelManagerRoomRateCollect->where('channel_manager_room_id', $room['roomid'])->first();
}
$reservationList['data'][$reservationKey]['room'][$roomKey]['property']['room_id'] = null;
$reservationList['data'][$reservationKey]['room'][$roomKey]['property']['room_rate_id'] = null;
$reservationList['data'][$reservationKey]['room'][$roomKey]['property']['room_rate_mapping_id'] = null;
$reservationList['data'][$reservationKey]['channelManagerPropertyId'] = $propertyMapping['channel_manager_property_id'];
if (empty($channelManagerRoomRate)) {
//Eğer mapping yapılmış oda bulunamamış ise rezervasyonu içeri alamazsın
//$logMessage
$mailParams = [
'title' => 'ReservationPullService Error - Channel Manager Room Rate Mapping',
'logMessage' => '<pre>' . print_r(array_merge($propertyMapping, $reservation), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
unset($reservationList['data'][$reservationKey]);
$this->error(date('Y-m-d H:i:s') . ' : Error: RoomRate Mapping Reservation: ' . $reservation['reservno']);
//Eşleşmeyen ve iptal edilen işlemin otele bildirilmesi.
if ($reservation['status'] == 'C') {
$notificationCancelToPropertyUser = [
'channel' => $reservation['otaname'],
'channelBookingCode' => $reservation['reservno_ota'],
'propertyChannelManager' => $channelManagerMapping['property_channel_manager']['name'],
'nameSurname' => $reservation['firstname'] . ' ' . $reservation['lastname'],
'propertyId' => $propertyMapping['property_id'],
];
$this->mailer->onQueue('cancelBookingMail', new CancelBookingMail($notificationCancelToPropertyUser));
$reservationConfirmParam = $this->reservationConfirmParam($propertyMapping['channel_manager_property_id'], $reservation['reservno'], 'ENWRES' . $reservation['reservno']);
$reservationConfirm = $this->channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
}
} else {
$reservationList['data'][$reservationKey]['room'][$roomKey]['property']['room_id'] = $channelManagerRoomRate['property_room_rate_mapping']['room_id'];
$reservationList['data'][$reservationKey]['room'][$roomKey]['property']['room_rate_id'] = $channelManagerRoomRate['property_room_rate_mapping']['room_rate_id'];
$reservationList['data'][$reservationKey]['room'][$roomKey]['property']['room_rate_mapping_id'] = $channelManagerRoomRate['property_room_rate_mapping']['id'];
}
}
}
foreach ($reservationList['data'] as $reservationKey => $reservation) {
//Eğer ExtranetWork ise içeri almadan onayla
if ($reservation['otaname'] == 'ExtranetWork') {
$reservationConfirmParam = $this->reservationConfirmParam($propertyMapping['channel_manager_property_id'], $reservation['reservno'], 'ENWRES' . $reservation['reservno']);
$reservationConfirm = $this->channelService->reservationConfirm($reservationConfirmParam);
if (!$reservationConfirm['status']) {
throw new ApiErrorException($reservationConfirm['message']);
}
continue;
}
$booking = ['status' => false, 'message' => ''];
if ($reservation['status'] == 'A') {
$booking = $this->createBooking($reservation);
} elseif ($reservation['status'] == 'C') {
$booking = $this->cancelBooking($reservation);
} elseif ($reservation['status'] == 'M') {
$booking = $this->modifiedBooking($reservation);
}
//M Modified kayıt bul güncelle ve sonra mail atılacak cancel ile aynı mail yapısı kullanılacak
if ($booking['status']) {
$this->info(date('Y-m-d H:i:s') . ' : Success: ' . $reservation['reservno']);
} else {
//$logMessage
$mailParams = [
'title' => 'ReservationPullService Error - Booking',
'logMessage' => '<pre>' . print_r(array_merge($booking, $reservation), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $booking['message']);
}
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch
(Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}

View File

@@ -0,0 +1,281 @@
<?php
namespace App\Console\Commands\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManager\Reseliva;
use App\Core\Service\ChannelManagerBookingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class ReservationPushService extends Command
{
protected $signature = 'cron:reservation-push-service';
protected $description = '';
protected $channelService;
protected $channelManagerBookingService;
protected $typeMapping;
public function __construct(
Mailer $mailer,
Reseliva $channelService,
ChannelManagerBookingService $channelManagerBookingService
)
{
parent::__construct();
$this->mailer = $mailer;
$this->channelService = $channelService;
$this->channelManagerBookingService = $channelManagerBookingService;
$this->typeMapping = [
'Booking' => 'Book',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
}
public function handle()
{
try {
$this->info(date('Y-m-d H:i:s') . ' : Start');
$pendingBookingCriteria = [
'criteria' =>
[
['field' => 'channel_manager_id', 'condition' => '=', 'value' => 1],
['field' => 'is_pushed', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['bookingDetail.bookingContact', 'bookingDetail.bookingChannel', 'bookingDetail.bookingPayment', 'bookingDetail.bookingPaymentType', 'bookingDetail.bookingStatus', 'bookingDetail.bookingRoom.roomPax.paxCountry'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
'take' => 100
];
$pendingBooking = $this->channelManagerBookingService->select($pendingBookingCriteria);
if ($pendingBooking['status'] == 'success') {
$pendingBooking = $pendingBooking['data'];
foreach ($pendingBooking as $booking) {
$bookingDetail = $booking['booking_detail'];
$type = $this->typeMapping[$booking['type']];
$serviceRequestName = 'BookingRetrieval';
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><' . $serviceRequestName . 'RS></' . $serviceRequestName . 'RS>');
if (in_array($bookingDetail['status'], [0, 3])) {
$Bookings = $xmlResponse->addChild('Bookings');
$Booking = $Bookings->addChild('Booking');
if(Carbon::createFromTimestamp($booking['booking_detail']['created_at'])->lessThan(Carbon::parse('2022-04-01'))) {
$Booking->addAttribute('id', $bookingDetail['id']);
} else {
$Booking->addAttribute('id', $bookingDetail['booking_code']);
}
$Booking->addAttribute('type', 'Cancel');
$Booking->addAttribute('cancelDateTime', Carbon::createFromTimestamp($bookingDetail['updated_at'])->toISOString());
$Hotel = $Booking->addChild('Hotel');
$Hotel->addAttribute('id', $bookingDetail['property_id']);
foreach ($bookingDetail['booking_room'] as $room) {
$RoomStay = $Booking->addChild('RoomStay');
$RoomStay->addAttribute('roomTypeID', $room['room_id']);
$RoomStay->addAttribute('ratePlanID', $room['room_rate_mapping_id']);
$StayDate = $RoomStay->addChild('StayDate');
$StayDate->addAttribute('arrival', $room['checkin_date']);
$StayDate->addAttribute('departure', $room['checkout_date']);
}
} else {
$Bookings = $xmlResponse->addChild('Bookings');
$Booking = $Bookings->addChild('Booking');
if(Carbon::createFromTimestamp($booking['booking_detail']['created_at'])->lessThan(Carbon::parse('2022-04-01'))) {
$Booking->addAttribute('id', $bookingDetail['id']);
} else {
$Booking->addAttribute('id', $bookingDetail['booking_code']);
}
//Book ve Modify Aynı olacak, Cancel
if ($type == 'Book') {
$Booking->addAttribute('type', 'Book');
$Booking->addAttribute('createDateTime', Carbon::createFromTimestamp($bookingDetail['created_at'])->toISOString());
}
if ($type == 'Modify') {
$Booking->addAttribute('type', 'Modify');
$Booking->addAttribute('modifyDateTime', Carbon::createFromTimestamp($bookingDetail['updated_at'])->toISOString());
}
$Hotel = $Booking->addChild('Hotel');
$Hotel->addAttribute('id', $bookingDetail['property_id']);
foreach ($bookingDetail['booking_room'] as $room) {
$RoomStay = $Booking->addChild('RoomStay');
$RoomStay->addAttribute('roomTypeID', $room['room_id']);
$RoomStay->addAttribute('ratePlanID', $room['room_rate_mapping_id']);
$StayDate = $RoomStay->addChild('StayDate');
$StayDate->addAttribute('arrival', $room['checkin_date']);
$StayDate->addAttribute('departure', $room['checkout_date']);
$roomPaxCollect = collect($room['room_pax']);
$GuestCount = $RoomStay->addChild('GuestCount');
$GuestCount->addAttribute('adult', $roomPaxCollect->where('type', 'ADT')->count());
$diffInDays = Carbon::parse($room['checkin_date'])->diffInDays(Carbon::parse($room['checkout_date']));
//dd($room['total'], $diffInDays, $room);
$PerDayRates = $RoomStay->addChild('PerDayRates');
$PerDayRates->addAttribute('currency', $room['currency_code']);
$baseRateDaily = moneyDoubleFormatDecimal($room['total'] / $diffInDays);
$currentDate = $room['checkin_date'];
for ($i = 0; $i < $diffInDays; $i++) {
$PerDayRate = $PerDayRates->addChild('PerDayRate');
$PerDayRate->addAttribute('stayDate', $currentDate);
$PerDayRate->addAttribute('baseRate', $baseRateDaily);
$PerDayRate->addAttribute('hotelServiceFees', 0);
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
$Total = $RoomStay->addChild('Total');
$Total->addAttribute('amountAfterTaxes', $room['total']);
$Total->addAttribute('amountOfTaxes', 0);
$Total->addAttribute('currency', $room['currency_code']);
$roomNotes['cancellationPolicy'] = 'Cancellation Policy: Refundable';
$cancellationPolicy = json_decode($room['cancellation_policy'],1);
if(!empty($cancellationPolicy) && is_array($cancellationPolicy)) {
if(isset($cancellationPolicy['isNonRefundable']) && $cancellationPolicy['isNonRefundable']) {
$roomNotes['cancellationPolicy'] = 'Cancellation Policy: NonRefundable';
}
}
$roomNotes['payment'] = 'Payment: '.$bookingDetail['booking_payment_type']['name'];
$RoomStay->addChild('RoomNotes', implode('. ',$roomNotes));
}
$PrimaryGuest = $Booking->addChild('PrimaryGuest');
$Name = $PrimaryGuest->addChild('Name');
$Name->addAttribute('givenName', $bookingDetail['booking_contact']['name']);
$Name->addAttribute('surname', $bookingDetail['booking_contact']['surname']);
$Phone = $PrimaryGuest->addChild('Phone');
$Phone->addAttribute('countryCode', $bookingDetail['booking_contact']['phone_code']);
//$Phone->addAttribute('cityAreaCode');
$Phone->addAttribute('number', $bookingDetail['booking_contact']['phone_number']);
$PrimaryGuest->addChild('Email', $bookingDetail['booking_contact']['email']);
$Total = $Booking->addChild('Total');
$Total->addAttribute('amountAfterTaxes', $bookingDetail['total']);
$Total->addAttribute('amountOfTaxes', 0);
$Total->addAttribute('currency', $bookingDetail['currency_code']);
$Booking->addChild('SpecialRequest');
$Booking->addChild('BookingNotes', $bookingDetail['booking_contact']['note']);
}
$this->info(date('Y-m-d H:i:s') . ' : Booking Id: '. $booking['booking_id']. ' Push');
$xmlPayload = $xmlResponse->asXML();
$this->channelManagerBookingService->update($booking['id'], ['request' => $xmlPayload]);
$requestPostReservationPush = $this->channelService->requestPostReservationPush($xmlPayload);
$this->channelManagerBookingService->update($booking['id'], ['response' => $requestPostReservationPush['data']['xmlBase']]);
if ($requestPostReservationPush['status']) {
if($requestPostReservationPush['data']['Status'] == 'success') {
$this->info(date('Y-m-d H:i:s') . ' : Booking Id: '. $booking['booking_id']. ' Success');
$this->channelManagerBookingService->update($booking['id'], ['is_pushed' => 1]);
} else {
//$logMessage
$mailParams = [
'title' => 'ReservationPushService Error - requestPostReservationPush Error',
'logMessage' => '<pre>' . print_r(array_merge($booking, $requestPostReservationPush), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
}
} else {
//$logMessage
$mailParams = [
'title' => 'ReservationPushService Error - requestPostReservationPush Error',
'logMessage' => '<pre>' . print_r(array_merge($booking, $requestPostReservationPush), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$this->info(date('Y-m-d H:i:s') . ' : Booking Id: '. $booking['booking_id']. ' Failed');
}
}
}
$this->info(date('Y-m-d H:i:s') . ' : Finished');
} catch (ApiErrorException $e) {
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $e->getMessage());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$this->error(date('Y-m-d H:i:s') . ' : Error: ' . $message);
}
}
}

Binary file not shown.