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,304 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class Athena
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->reservationPushUrl = [
546 => 'http://46.175.134.18:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
541 => 'http://94.43.46.153:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
545 => 'http://92.51.70.35:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
//538 => 'http://92.51.72.105:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
538 => 'http://146.255.233.146:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
548 => 'http://92.51.72.105:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
549 => 'http://92.51.72.105:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking',
550 => 'http://146.255.239.106:6161/HotelEx/api/v1/hotel/ors/extranetwork/booking'
];
$this->typeMapping = [
'Booking' => 'Book',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
$this->channelManagerId = 5;
$this->channelManagerName = 'Athena';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
}
public function requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$type = $this->typeMapping[$type];
$bookingDetail = $param['booking_detail'];
$jsonResponse = [];
$jsonResponse['hotel_id'] = $propertyId;
$jsonResponse['reservation']['code'] = $bookingDetail['booking_code'];
$jsonResponse['reservation']['status'] = $type;
$jsonResponse['reservation']['time'] = Carbon::createFromTimestamp($param['booking_detail']['created_at'])->toDateTimeString();
$jsonResponse['reservation']['checkin_date'] = $bookingDetail['checkin_date'];
$jsonResponse['reservation']['checkout_date'] = $bookingDetail['checkout_date'];
$jsonResponse['reservation']['currency'] = $bookingDetail['currency_code'];
$jsonResponse['reservation']['total'] = $bookingDetail['total'];
$jsonResponse['reservation']['contact'] = [
'name' => $bookingDetail['booking_contact']['name'],
'surname' => $bookingDetail['booking_contact']['surname'],
'email' => $bookingDetail['booking_contact']['email'],
'phone' => $bookingDetail['booking_contact']['phoneFormatted'],
'note' => $bookingDetail['booking_contact']['note'],
];
$jsonResponse['reservation']['rooms'] = [];
$roomKey = 0;
foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {
if($roomDetail['status'] != 1) {
continue;
}
$occupancy = occupancyCodeParser($roomDetail['occupancy_code']);
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
//Additional Fee
$additionalFees = null;
if (!empty($roomDetail['rate_detail'])) {
$rateDetail = json_decode($roomDetail['rate_detail'], 1);
if(isset($rateDetail['taxes']) && $bookingDetail['channel_manager_id'] == 2) {
$additionalFees = $rateDetail['taxes'];
}
}
$additionalFeeTotal = null;
if(!empty($additionalFees)) {
foreach ($additionalFees as $additionalFee) {
if(!$additionalFee['is_inclusive']) {
$additionalFeeTotal+=$additionalFee['total_price'];
}
}
}
$additionalFeePerDay = 0;
if(!empty($additionalFeeTotal)) {
$additionalFeePerDay = moneyDoubleFormatDecimal($additionalFeeTotal / $diffInDays);
}
//Additional Fee
$roomDailyAmount = [];
if (!empty($roomDetail['daily_amount'])) {
$roomDetailDailyAmount = json_decode($roomDetail['daily_amount'], 1);
if (!empty($roomDetailDailyAmount) && isset($roomDetailDailyAmount)) {
foreach ($roomDetailDailyAmount as $roomRateAmount) {
$calculatedAmount = $roomRateAmount['amount'] + $additionalFeePerDay;
$roomDailyAmount[] = [
'date' => $roomRateAmount['date'],
'amount' => moneyDoubleFormatDecimal($calculatedAmount),
'currency_code' => $roomRateAmount['currency_code'],
];
}
}
$totalFromRoomDaily = collect($roomDailyAmount)->sum('amount');
if($totalFromRoomDaily != $roomDetail['total']) {
$totalFromDifference = moneyDoubleFormatDecimal($roomDetail['total'] - $totalFromRoomDaily);
$roomDailyAmount[count($roomDailyAmount)-1]['amount']+= $totalFromDifference;
}
}
$baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
if (empty($roomDailyAmount)) {
$currentDate = $roomDetail['checkin_date'];
for ($i = 0; $i < $diffInDays; $i++) {
$roomDailyAmount[] = [
'date' => $currentDate,
'amount' => $baseRateDaily,
'currency_code' => $roomDetail['currency_code'],
];
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
}
$roomPax = [];
foreach ($roomDetail['room_pax'] as $pax) {
$roomPax[] = [
'type' => $pax['type'],
'name' => $pax['name'],
'surname' => $pax['surname'],
'gender' => $pax['gender'],
'citizen' => $pax['citizen'],
'birth_date' => $pax['birth_date'],
];
}
$jsonResponse['reservation']['rooms'][$roomKey] = [
'id' => $roomDetail['id'],
'room_id' => $roomDetail['room_id'],
'room_name' => $roomDetail['room_name'],
'rate_id' => $roomDetail['room_rate_mapping_id'],
'rate_name' => $roomDetail['room_rate_name'],
'occupancy' => [
'adults' => $occupancy['ADT'],
'children' => $occupancy['CHD'],
'age' => $occupancy['AGE'],
],
'total' => $roomDetail['total'],
//'totalFromDaily' => collect($roomDailyAmount)->sum('amount'),
'daily' => $roomDailyAmount,
'pax' => $roomPax
];
}
$jsonResponse['reservation']['channel'] = [
'id' => $bookingDetail['booking_channel']['id'],
'name' => $bookingDetail['booking_channel']['id'] == 1 ? 'Extranetwork' : $bookingDetail['booking_channel']['name'],
'booking_code' => !empty($bookingDetail['channel_booking_code']) ? $bookingDetail['channel_booking_code'] : $bookingDetail['booking_code']
];
$jsonResponse['reservation']['payment'] = [
'code' => $bookingDetail['booking_payment_type']['code'],
'name' => $bookingDetail['booking_payment_type']['name'],
];
//CHN - For Offline Agency Booking Engine
if($bookingDetail['booking_channel']['channel_category_id'] == 2) {
if($bookingDetail['booking_payment']['payment_type_code'] == 'HTL') {
$jsonResponse['reservation']['payment'] = [
'code' => 'CHN',
'name' => 'Channel Manager',
];
}
}
if($bookingDetail['booking_payment']['payment_type_code'] == 'CRD' && $bookingDetail['booking_payment']['payment_source_code'] == 'GST') {
$jsonResponse['reservation']['payment'] = [
'code' => 'HTL',
'name' => 'Pay at Hotel',
];
}
//Expedia Net Commission
if($jsonResponse['reservation']['total'] != $bookingDetail['booking_payment']['total']) {
if($jsonResponse['reservation']['total'] == 0) {
$netRate = 0;
} else {
$netRate = $bookingDetail['booking_payment']['total'] / $jsonResponse['reservation']['total'];
}
foreach ($jsonResponse['reservation']['rooms'] as $roomKey => $roomDetail) {
foreach ($roomDetail['daily'] as $roomDailyKey => $roomDaily) {
$jsonResponse['reservation']['rooms'][$roomKey]['daily'][$roomDailyKey]['amount'] = $roomDaily['amount'] * $netRate;
}
$jsonResponse['reservation']['rooms'][$roomKey]['total'] = collect($jsonResponse['reservation']['rooms'][$roomKey]['daily'])->sum('amount');
$jsonResponse['reservation']['rooms'][$roomKey]['total'] = moneyDoubleFormatDecimal($jsonResponse['reservation']['rooms'][$roomKey]['total']);
}
$jsonResponse['reservation']['total'] = collect($jsonResponse['reservation']['rooms'])->sum('total');
$jsonResponse['reservation']['total'] = moneyDoubleFormatDecimal($jsonResponse['reservation']['total']);
}
return json_encode($jsonResponse);
}
public function requestPostReservationPush($jsonPayload)
{
$response = ['status' => false, 'message' => ''];
$jsonData = json_decode($jsonPayload,1);
try {
if(!isset($this->reservationPushUrl[$jsonData['hotel_id']])) {
throw new ApiErrorException('Athena live reservation no push url');
}
$this->restClient = new Client(['http_errors' => false, 'timeout' => 30]);
$res = $this->restClient->post($this->reservationPushUrl[$jsonData['hotel_id']],
[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
$getResponseBody = $res->getBody();
$getResponseJsonBase = $getResponseBody->getContents();
$getResponse = json_decode($getResponseJsonBase, 1);
if (!$getResponse['success']) {
throw new ApiErrorException($getResponse['errorReason']);
}
$response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];
} catch (ApiErrorException $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,226 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class ElektraWeb
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->reservationPushUrl = 'https://channelmanager.elektraweb.com/extranetwork?action=push';
$this->typeMapping = [
'Booking' => 'Book',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
$this->channelManagerId = 4;
$this->channelManagerName = 'ElektraWeb';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
}
public function requestPost($method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$res = $this->restClient->post($this->url . $method,
[
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
'Accept' => 'text/xml'
],
'body' => $xmlPayload,
]
);
$getResponseBody = $res->getBody();
$getResponse = $getResponseBody->getContents();
$getResponseXml = new \SimpleXMLElement($getResponse, LIBXML_NOCDATA);
$getResponse = json_decode(json_encode($getResponseXml), 1);
$response = ["status" => true, 'message' => '', "data" => $getResponse];
} 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 requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$type = $this->typeMapping[$type];
$bookingDetail = $param['booking_detail'];
$jsonResponse = [];
$jsonResponse['hotel_id'] = $propertyId;
$jsonResponse['reservation']['code'] = $bookingDetail['booking_code'];
$jsonResponse['reservation']['status'] = $type;
$jsonResponse['reservation']['time'] = Carbon::createFromTimestamp($param['booking_detail']['created_at'])->toDateTimeString();
$jsonResponse['reservation']['checkin_date'] = $bookingDetail['checkin_date'];
$jsonResponse['reservation']['checkout_date'] = $bookingDetail['checkout_date'];
$jsonResponse['reservation']['currency'] = $bookingDetail['currency_code'];
$jsonResponse['reservation']['total'] = ($bookingDetail['total'] - $bookingDetail['addon_amount']);
$jsonResponse['reservation']['contact'] = [
'name' => $bookingDetail['booking_contact']['name'],
'surname' => $bookingDetail['booking_contact']['surname'],
'email' => $bookingDetail['booking_contact']['email'],
'phone' => $bookingDetail['booking_contact']['phoneFormatted'],
'note' => $bookingDetail['booking_contact']['note'],
];
$jsonResponse['reservation']['rooms'] = [];
$roomKey = 0;
foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {
$occupancy = occupancyCodeParser($roomDetail['occupancy_code']);
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
$baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
$dailyPrices = [];
$currentDate = $roomDetail['checkin_date'];
for ($i = 0; $i < $diffInDays; $i++) {
$dailyPrices[] = [
'date' => $currentDate,
'amount' => $baseRateDaily
];
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
$roomPax = [];
foreach ($roomDetail['room_pax'] as $pax) {
$roomPax[] = [
'type' => $pax['type'],
'name' => $pax['name'],
'surname' => $pax['surname'],
'gender' => $pax['gender'],
'citizen' => $pax['citizen'],
'birth_date' => $pax['birth_date'],
];
}
$jsonResponse['reservation']['rooms'][$roomKey] = [
'room_id' => $roomDetail['room_id'],
'room_name' => $roomDetail['room_name'],
'rate_id' => $roomDetail['room_rate_mapping_id'],
'rate_name' => $roomDetail['room_rate_name'],
'occupancy' => [
'adults' => $occupancy['ADT'],
'children' => $occupancy['CHD'],
'age' => $occupancy['AGE'],
],
'daily' => $dailyPrices,
'pax' => $roomPax
];
}
$jsonResponse['reservation']['channel'] = [
'id' => $bookingDetail['booking_channel']['id'],
'name' => $bookingDetail['booking_channel']['id'] == 1 ? 'Extranetwork' : $bookingDetail['booking_channel']['name'],
];
$jsonResponse['reservation']['payment'] = [
'code' => $bookingDetail['booking_payment_type']['code'],
'name' => $bookingDetail['booking_payment_type']['name'],
];
return json_encode($jsonResponse);
}
public function requestPostReservationPush($jsonPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$res = $this->restClient->post($this->reservationPushUrl,
[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
$getResponseBody = $res->getBody();
$getResponseJsonBase = $getResponseBody->getContents();
$getResponse = json_decode($getResponseJsonBase, 1);
if (!$getResponse['Success']) {
throw new ApiErrorException($getResponse['Message']);
}
$response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];
} catch (ApiErrorException $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
}

View File

@@ -0,0 +1,255 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class Fina
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->reservationPushUrl = [
790 => 'http://92.51.115.18/api/hotel/saveReservation'
];
$this->typeMapping = [
'Booking' => 'Book',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
$this->channelManagerId = 8;
$this->channelManagerName = 'Fina';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
}
public function requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$type = $this->typeMapping[$type];
$bookingDetail = $param['booking_detail'];
$jsonResponse = [];
$jsonResponse['hotel_id'] = $propertyId;
$jsonResponse['reservation']['code'] = $bookingDetail['booking_code'];
$jsonResponse['reservation']['status'] = $type;
$jsonResponse['reservation']['time'] = Carbon::createFromTimestamp($param['booking_detail']['created_at'])->toDateTimeString();
$jsonResponse['reservation']['checkin_date'] = $bookingDetail['checkin_date'];
$jsonResponse['reservation']['checkout_date'] = $bookingDetail['checkout_date'];
$jsonResponse['reservation']['currency'] = $bookingDetail['currency_code'];
$jsonResponse['reservation']['total'] = $bookingDetail['total'];
$jsonResponse['reservation']['contact'] = [
'name' => $bookingDetail['booking_contact']['name'],
'surname' => $bookingDetail['booking_contact']['surname'],
'email' => $bookingDetail['booking_contact']['email'],
'phone' => $bookingDetail['booking_contact']['phoneFormatted'],
'note' => $bookingDetail['booking_contact']['note'],
];
$jsonResponse['reservation']['rooms'] = [];
$roomKey = 0;
foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {
if ($roomDetail['status'] != 1) {
continue;
}
$occupancy = occupancyCodeParser($roomDetail['occupancy_code']);
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
//Additional Fee
$additionalFees = null;
if (!empty($roomDetail['rate_detail'])) {
$rateDetail = json_decode($roomDetail['rate_detail'], 1);
if (isset($rateDetail['taxes']) && $bookingDetail['channel_manager_id'] == 2) {
$additionalFees = $rateDetail['taxes'];
}
}
$additionalFeeTotal = null;
if (!empty($additionalFees)) {
foreach ($additionalFees as $additionalFee) {
if (!$additionalFee['is_inclusive']) {
$additionalFeeTotal += $additionalFee['total_price'];
}
}
}
$additionalFeePerDay = 0;
if (!empty($additionalFeeTotal)) {
$additionalFeePerDay = moneyDoubleFormatDecimal($additionalFeeTotal / $diffInDays);
}
//Additional Fee
$roomDailyAmount = [];
if (!empty($roomDetail['daily_amount'])) {
$roomDetailDailyAmount = json_decode($roomDetail['daily_amount'], 1);
if (!empty($roomDetailDailyAmount) && isset($roomDetailDailyAmount)) {
foreach ($roomDetailDailyAmount as $roomRateAmount) {
$calculatedAmount = $roomRateAmount['amount'] + $additionalFeePerDay;
$roomDailyAmount[] = [
'date' => $roomRateAmount['date'],
'amount' => moneyDoubleFormatDecimal($calculatedAmount),
'currency_code' => $roomRateAmount['currency_code'],
];
}
}
$totalFromRoomDaily = collect($roomDailyAmount)->sum('amount');
if ($totalFromRoomDaily != $roomDetail['total']) {
$totalFromDifference = moneyDoubleFormatDecimal($roomDetail['total'] - $totalFromRoomDaily);
$roomDailyAmount[count($roomDailyAmount) - 1]['amount'] += $totalFromDifference;
}
}
$baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
if (empty($roomDailyAmount)) {
$currentDate = $roomDetail['checkin_date'];
for ($i = 0; $i < $diffInDays; $i++) {
$roomDailyAmount[] = [
'date' => $currentDate,
'amount' => $baseRateDaily,
'currency_code' => $roomDetail['currency_code'],
];
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
}
$roomPax = [];
foreach ($roomDetail['room_pax'] as $pax) {
$roomPax[] = [
'type' => $pax['type'],
'name' => $pax['name'],
'surname' => $pax['surname'],
'gender' => $pax['gender'],
'citizen' => $pax['citizen'],
'birth_date' => $pax['birth_date'],
];
}
$jsonResponse['reservation']['rooms'][$roomKey] = [
'id' => $roomDetail['id'],
'room_id' => $roomDetail['room_id'],
'room_name' => $roomDetail['room_name'],
'rate_id' => $roomDetail['room_rate_mapping_id'],
'rate_name' => $roomDetail['room_rate_name'],
'occupancy' => [
'adults' => $occupancy['ADT'],
'children' => $occupancy['CHD'],
'age' => $occupancy['AGE'],
],
'total' => $roomDetail['total'],
//'totalFromDaily' => collect($roomDailyAmount)->sum('amount'),
'daily' => $roomDailyAmount,
'pax' => $roomPax
];
}
$jsonResponse['reservation']['channel'] = [
'id' => $bookingDetail['booking_channel']['id'],
'name' => $bookingDetail['booking_channel']['id'] == 1 ? 'Extranetwork' : $bookingDetail['booking_channel']['name'],
'booking_code' => !empty($bookingDetail['channel_booking_code']) ? $bookingDetail['channel_booking_code'] : $bookingDetail['booking_code']
];
$jsonResponse['reservation']['payment'] = [
'code' => $bookingDetail['booking_payment_type']['code'],
'source' => $bookingDetail['booking_payment']['payment_source_code'],
'name' => $bookingDetail['booking_payment_type']['name'],
];
return json_encode($jsonResponse);
}
public function requestPostReservationPush($jsonPayload)
{
$response = ['status' => false, 'message' => ''];
$jsonData = json_decode($jsonPayload, 1);
$getResponse = [];
try {
/*if(!isset($this->reservationPushUrl[$jsonData['hotel_id']])) {
throw new ApiErrorException('Fina live reservation no push url');
}
$this->restClient = new Client(['http_errors' => false, 'timeout' => 30]);
$res = $this->restClient->post($this->reservationPushUrl[$jsonData['hotel_id']],
[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
$getResponseBody = $res->getBody();
$getResponseJsonBase = $getResponseBody->getContents();
$getResponse = json_decode($getResponseJsonBase, 1);
if (!$getResponse['success']) {
throw new ApiErrorException($getResponse['errorReason']);
}*/
$response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
}

View File

@@ -0,0 +1,284 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class HotelRunner
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
//$this->reservationPushUrl = 'https://cm-staging.hotelrunner.com/api/push/reservation/28fb9e7b18903126e9d71a10ced00db0edec8710';
$this->reservationPushUrl = 'https://cm.hotelrunner.com/api/push/reservation/da120fb30eae007e41034f5ab7824608ab8250de';
$this->typeMapping = [
'Booking' => 'Confirm',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
$this->roomStatusTypeMapping = [
1 => 'Confirm',
0 => 'Cancel'
];
$this->channelManagerId = 3;
$this->channelManagerName = 'HotelRunner';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
}
public function requestPost($method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$res = $this->restClient->post($this->url . $method,
[
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
'Accept' => 'text/xml'
],
'body' => $xmlPayload,
]
);
$getResponseBody = $res->getBody();
$getResponse = $getResponseBody->getContents();
$getResponseXml = new \SimpleXMLElement($getResponse, LIBXML_NOCDATA);
$getResponse = json_decode(json_encode($getResponseXml), 1);
$response = ["status" => true, 'message' => '', "data" => $getResponse];
} 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 requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$type = $this->typeMapping[$type];
$bookingDetail = $param['booking_detail'];
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><reservation></reservation>');
$xmlResponse->addChild('status', $type);
$xmlResponse->addChild('code', $bookingDetail['booking_code']);
$xmlResponse->addChild('time_zone', 'UTC');
if (in_array($type, ['Modify', 'Cancel'])) {
$xmlResponse->addChild('date', Carbon::createFromTimestamp($param['booking_detail']['updated_at'], 'UTC')->toDateTimeString());
} else {
$xmlResponse->addChild('date', Carbon::createFromTimestamp($param['booking_detail']['created_at'], 'UTC')->toDateTimeString());
}
//$xmlResponse->addChild('name', $bookingDetail['booking_contact']['nameSurname']);
$xmlResponse->addChild('name', '<![CDATA[' . htmlentities($bookingDetail['booking_contact']['nameSurname']) . ']]>');
$xmlResponse->addChild('mail', $bookingDetail['booking_contact']['email']);
$xmlResponse->addChild('address');
$xmlResponse->addChild('city');
$firstRoom = reset($bookingDetail['booking_room']);
$firstPax = reset($firstRoom['room_pax']);
$xmlResponse->addChild('country', $firstPax['pax_country']['name']);
$xmlResponse->addChild('telephone', $bookingDetail['booking_contact']['phoneFormatted']);
$xmlResponse->addChild('property_id', $bookingDetail['property_id']);
$totalAdultCount = 0;
$totalChildrenCount = 0;
$roomSearchOccupancy = json_decode($bookingDetail['rooms'], 1);
foreach ($roomSearchOccupancy as $roomOccupancy) {
$totalAdultCount += $roomOccupancy['adults'];
$totalChildrenCount += $roomOccupancy['children'];
}
$xmlResponse->addChild('adult_count', $totalAdultCount);
$xmlResponse->addChild('child_count', $totalChildrenCount);
$xmlResponse->addChild('total_cost', $bookingDetail['total']);
$xmlResponse->addChild('currency', $bookingDetail['currency_code']);
if (!empty($bookingDetail['booking_contact']['note'])) {
$xmlResponse->addChild('remark', '<![CDATA[' . htmlentities($bookingDetail['booking_contact']['note']) . ']]>');
} else {
$xmlResponse->addChild('remark', $bookingDetail['booking_contact']['note']);
}
$xmlResponse->addChild('arrival_date', $bookingDetail['checkin_date']);
$xmlResponse->addChild('departure_date', $bookingDetail['checkout_date']);
$xmlResponse->addChild('card');//Credit Card
$rooms = $xmlResponse->addChild('rooms');
foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {
$room = $rooms->addChild('room');
$roomStatusType = isset($this->roomStatusTypeMapping[$roomDetail['status']]) ? $this->roomStatusTypeMapping[$roomDetail['status']] : 1;
if (in_array($type, ['Modify']) && $roomDetail['status'] == 1) {
$roomStatusType = $type;
}
if (in_array($type, ['Cancel'])) {
$roomStatusType = $type;
}
$room->addChild('room_id', $roomDetail['room_id']);
$room->addChild('rate_id', $roomDetail['room_rate_mapping_id']);
$room->addChild('code', $roomDetail['room_id'] . ':' . $roomDetail['room_rate_mapping_id']);
$isNonRefundable = false;
$cancellationPolicy = json_decode($roomDetail['cancellation_policy'], 1);
if (!empty($cancellationPolicy)) {
if (isset($cancellationPolicy['isNonRefundable']) && $cancellationPolicy['isNonRefundable'] == 1) {
$isNonRefundable = true;
}
}
if ($isNonRefundable) {
$roomName = $roomDetail['room_name'] . ' - ' . $roomDetail['room_rate_name'].' - NonRefundable';
} else {
$roomName = $roomDetail['room_name'] . ' - ' . $roomDetail['room_rate_name'];
}
$room->addChild('name', '<![CDATA[' . htmlentities($roomName) . ']]>');
$roomPaxCollect = collect($roomDetail['room_pax']);
$room->addChild('adult_count', $roomPaxCollect->where('type', 'ADT')->count());
$room->addChild('child_count', $roomPaxCollect->where('type', 'CHD')->count());
$childAges = isset($roomSearchOccupancy[$roomKey]) && $roomSearchOccupancy[$roomKey]['children'] > 0 ? '[' . implode(',', $roomSearchOccupancy[$roomKey]['age']) . ']' : null;
$room->addChild('child_ages', $childAges);
$room->addChild('arrival_date', $roomDetail['checkin_date']);
$room->addChild('departure_date', $roomDetail['checkout_date']);
$room->addChild('total_cost', $roomDetail['total']);
$room->addChild('status', $roomStatusType);
$room->addChild('non_refundable', $isNonRefundable);
$dailyPrices = $room->addChild('daily_prices');
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
$baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
$currentDate = $roomDetail['checkin_date'];
for ($i = 0; $i < $diffInDays; $i++) {
$dailyPrice = $dailyPrices->addChild('daily_price');
$dailyPrice->addChild('date', $currentDate);
$dailyPrice->addChild('price', $baseRateDaily);
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
}
//Log::debug($xmlResponse->asXML());
//dd(html_entity_decode($xmlResponse->asXML()));
return html_entity_decode($xmlResponse->asXML());
}
public function requestPostReservationPush($xmlPayload)
{
$response = ['status' => false, 'message' => ''];
$propertyId = null;
$xmlPayloadData = simplexml_load_string($xmlPayload);
$xmlPayloadData = json_decode(json_encode($xmlPayloadData), 1);
try {
$this->restClient = new Client(['http_errors' => false]);
$res = $this->restClient->post($this->reservationPushUrl . '/' . $xmlPayloadData['property_id'],
[
'headers' => [
'Content-Type' => 'text/xml; charset=UTF8',
//'Authorization' => 'Basic dUV4dHJhbmV0V29yazpFeHRybnRXcmsyMSEqMjI=',
'Accept' => 'text/xml'
],
'body' => $xmlPayload,
]
);
$getResponseBody = $res->getBody();
$getResponseXmlBase = $getResponseBody->getContents();
$getResponseXml = new \SimpleXMLElement($getResponseXmlBase, LIBXML_NOCDATA);
$getResponse = json_decode(json_encode($getResponseXml), 1);
//Log::debug($xmlPayload);
//Log::debug($getResponse);
if ($getResponse['status'] != 0) {
throw new ApiErrorException($getResponse['message']);
}
$response = ['status' => true, 'message' => '', 'response' => $getResponseXmlBase];
} 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;
}
}

View File

@@ -0,0 +1,416 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class HyperGuest
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->reservationPushUrl = 'https://book-api.hyperguest.com';
$this->bearerToken = '63d51938dc3749788ac3e88ea6d58950';
$this->channelManagerId = 10;
$this->channelManagerName = 'HyperGuest';
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->paymentTypeMapping = [
'CRD' => 'bank_transfer',
'HTL' => 'external'
];
}
public function requestPost($method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$parameter = [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->bearerToken
]
];
if (!empty($jsonPayload)) {
$parameter['body'] = $jsonPayload;
}
$request = $this->restClient->request('POST', $this->url . $method, $parameter);
$getResponseBody = $request->getBody();
$getResponse = $getResponseBody->getContents();
$getResponse = json_decode($getResponse, 1);
if ($request->getStatusCode() != 200) {
$errors = singleElementArray($getResponse['errors']);
$firstError = reset($errors);
throw new ApiErrorException($firstError['code'] . ': ' . $firstError['title']);
}
$response = ["status" => true, 'message' => '', "data" => fillOnUndefined($getResponse, '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 requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$jsonResponse = null;
try {
$bookingDetail = $param['booking_detail'];
$requestParam = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping'],
'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'];
$jsonResponse = [];
$jsonResponse['dates']['from'] = $bookingDetail['checkin_date'];
$jsonResponse['dates']['to'] = $bookingDetail['checkout_date'];
$jsonResponse['propertyId'] = $channelManagerPropertyMapping['channel_manager_property_id'];
//$jsonResponse['reservation']['code'] = $bookingDetail['booking_code'];
//$jsonResponse['reservation']['status'] = $type;
//$jsonResponse['reservation']['time'] = Carbon::createFromTimestamp($param['booking_detail']['created_at'])->toDateTimeString();
$jsonResponse['leadGuest']['birthDate'] = '1980-01-01';
$jsonResponse['leadGuest']['contact']['address'] = 'N/A';
$jsonResponse['leadGuest']['contact']['city'] = 'N/A';
$jsonResponse['leadGuest']['contact']['country'] = !empty($bookingDetail['booking_contact']['country_code']) ? $bookingDetail['booking_contact']['country_code'] : 'TR';
$jsonResponse['leadGuest']['contact']['email'] = $bookingDetail['booking_contact']['email'];
$jsonResponse['leadGuest']['contact']['phone'] = $bookingDetail['booking_contact']['phoneFormatted'];
$jsonResponse['leadGuest']['contact']['state'] = 'N/A';
$jsonResponse['leadGuest']['contact']['zip'] = 'N/A';
$jsonResponse['leadGuest']['name']['first'] = $bookingDetail['booking_contact']['name'];
$jsonResponse['leadGuest']['name']['last'] = $bookingDetail['booking_contact']['surname'];
$jsonResponse['leadGuest']['title'] = 'Mr';
$jsonResponse['reference']['agency'] = $bookingDetail['booking_code'];//'Extranetwork';
$jsonResponse['paymentDetails']['type'] = isset($this->paymentTypeMapping[$bookingDetail['payment_type_code']]) ? $this->paymentTypeMapping[$bookingDetail['payment_type_code']] : $this->paymentTypeMapping['HTL'];
//$jsonResponse['paymentDetails']['details']['number'] = null;
//$jsonResponse['paymentDetails']['details']['cvv'] = null;
//$jsonResponse['paymentDetails']['details']['expiry']['month'] = null;
//$jsonResponse['paymentDetails']['details']['name']['first'] = null;
//$jsonResponse['paymentDetails']['details']['name']['last'] = null;
$jsonResponse['rooms'] = [];
$roomKey = 0;
foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {
/*$occupancy = occupancyCodeParser($roomDetail['occupancy_code']);
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
*/
$roomPax = [];
foreach ($roomDetail['room_pax'] as $pax) {
$roomPax[] = [
'birthDate' => $pax['birth_date'],
/*'contact' => [
'address' => null,
'city' => null,
'country' => $pax['citizen'],
'email' => null,
'phone' => null,
'state' => null,
'zip' => null,
],*/
'name' => [
'first' => $pax['name'],
'last' => $pax['surname'],
],
//'title' => null
];
}
$channelRoom = collect($channelManagerPropertyMapping['channel_manager_room_rate'])->where('property_room_rate_mapping.room_id', $roomDetail['room_id'])->first();
$channelRoomRate = collect($channelManagerPropertyMapping['channel_manager_room_rate'])->where('property_room_rate_mapping_id', $roomDetail['room_rate_mapping_id'])->first();
$jsonResponse['rooms'][$roomKey] = [
'roomCode' => $channelRoom['channel_manager_room_id'],
'rateCode' => $channelRoomRate['channel_manager_room_rate_id'],
'expectedPrice' => [
'amount' => $roomDetail['total'],
'currency' => $roomDetail['currency_code'],
],
'guests' => $roomPax,
'specialRequests' => [
$roomDetail['room_name'], $roomDetail['room_rate_name'],
]
];
}
$metaNotes = [];
$metaNotes[] = [
'key' => 'Source',
'value' => 'Extranetwork',
];
$metaNotes[] = [
'key' => 'BookingId',
'value' => $bookingDetail['id'],
];
$metaNotes[] = [
'key' => 'BookingCode',
'value' => $bookingDetail['booking_code'],
];
$metaNotes[] = [
'key' => 'ChannelBookingCode',
'value' => !empty($bookingDetail['channel_booking_code']) ? $bookingDetail['channel_booking_code'] : false,
];
$metaNotes[] = [
'key' => 'Channel',
'value' => $bookingDetail['booking_channel']['name'],
];
$metaNotes[] = [
'key' => 'Payment',
'value' => $bookingDetail['booking_payment_type']['code'] . ': ' . $bookingDetail['booking_payment_type']['name'],
];
$metaNotes[] = [
'key' => 'Status',
'value' => $bookingDetail['booking_status']['name'],
];
if (!empty($bookingDetail['booking_contact']['note'])) {
$metaNotes[] = [
'key' => 'Note',
'value' => $bookingDetail['booking_contact']['note'],
];
}
$jsonResponse['meta'] = $metaNotes;
$jsonResponse['isTest'] = (App::environment() == 'production') ? false : true;
$jsonResponse['groupBooking'] = false;
return json_encode($jsonResponse);
} catch (ApiErrorException | Exception $e) {
$jsonResponse = null;
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
}
return $jsonResponse;
}
public function requestPostReservationPush($jsonPayload)
{
$response = ['status' => false, 'message' => ''];
$jsonPayloadArray = json_decode($jsonPayload, 1);
$status = collect($jsonPayloadArray['meta'])->where('key', 'Status')->pluck('value')->first();
$bookingId = collect($jsonPayloadArray['meta'])->where('key', 'BookingId')->pluck('value')->first();
$bookingCode = collect($jsonPayloadArray['meta'])->where('key', 'BookingCode')->pluck('value')->first();
$channelBookingCode = collect($jsonPayloadArray['meta'])->where('key', 'ChannelBookingCode')->pluck('value')->first();
if ($status == 'Booking') {
$method = '/2.0/booking/create';
} elseif ($status == 'Cancel/Refund') {
$method = '/2.0/booking/cancel';
}
if ($status == 'Cancel/Refund') {
$jsonResponse = [
'bookingId' => $channelBookingCode,
'reason' => 'N/A',
'simulation' => false,
];
$jsonPayload = json_encode($jsonResponse);
}
try {
$this->restClient = new Client(['http_errors' => false]);
$parameter = [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->bearerToken
]
];
//$jsonPayload = '{"dates":{"from":"2024-08-30","to":"2024-08-31"},"propertyId":"90365","leadGuest":{"birthDate":"1980-01-01","contact":{"address":false,"city":false,"country":"TR","email":"cem@test.com","phone":"+4932121321","state":false,"zip":false},"name":{"first":"cem","last":"test"},"title":"Mr"},"reference":{"agency":"BKG240730-5VI02ISW"},"paymentDetails":{"type":"external"},"rooms":[{"roomCode":"DBL","rateCode":"BB","expectedPrice":{"amount":200.75,"currency":"EUR"},"guests":[{"birthDate":"1988-07-20","name":{"first":"dsada","last":"sadsa"}},{"birthDate":"1988-07-24","name":{"first":"sad","last":"sadfds"}}],"specialRequests":["Standart Room With Sea View","Bed and Breakfast"]}],"meta":[{"key":"Source","value":"Extranetwork"},{"key":"BookingId","value":46502},{"key":"BookingCode","value":"BKG240730-5VI02ISW"},{"key":"ChannelBookingCode","value":false},{"key":"Channel","value":"Web Booking Engine"},{"key":"Payment","value":"HTL: Pay at Hotel"},{"key":"Status","value":"Booking"},{"key":"Note","value":"asdasd"}],"isTest":true,"groupBooking":false}';
if (!empty($jsonPayload)) {
$parameter['body'] = $jsonPayload;
}
$request = $this->restClient->request('POST', $this->reservationPushUrl . $method, $parameter);
$getResponseBody = $request->getBody();
$getResponse = $getResponseBody->getContents();
$getResponse = json_decode($getResponse, 1);
//dd(json_encode($getResponse));
//Log::debug($method);
//Log::debug($parameter);
//Log::debug(json_encode($getResponse));
//Log::debug($request->getStatusCode());
if ($request->getStatusCode() != 200) {
if (isset($getResponse['error'])) {
if (is_array($getResponse['errorDetails']) && !empty($getResponse['errorDetails'])) {
$errors = $getResponse['errorDetails'];
$firstError = reset($errors);
throw new ApiErrorException($firstError['message']);
} elseif (!empty($getResponse['errorDetails'])) {
throw new ApiErrorException($getResponse['errorDetails']);
} else {
throw new ApiErrorException($getResponse['error']);
}
} else {
$errors = singleElementArray($getResponse);
$firstError = reset($errors);
throw new ApiErrorException($firstError['errorCode'] . ': ' . $firstError['errorDetails']);
}
}
if ($status == 'Booking') {
$channelBookingCodeUpdate = $this->bookingService->update($bookingId, ['channel_booking_code' => $getResponse['content']['bookingId']]);
}
$response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];
} 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 reservationListParam($propertyId)
{
$response = ['status' => false, 'message' => null];
return $response;
}
public function reservationList($propertyId)
{
$response = ['status' => false, 'message' => null];
return $response;
}
public function roomAvailabilityPush($propertyId)
{
$response = ['status' => false, 'message' => null];
return $response;
}
}

View File

@@ -0,0 +1,685 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class Mirai
{
private $channelManagerId;
private $channelManagerName;
private $mailer;
private $login;
private $password;
private $url;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
/*if (App::environment() == 'production') {
$this->login = 'extranetwork-xml-100378788';
$this->password = 'Burhan21';
} else {
$this->login = 'ExtranetWorktest-xml-100378347';
$this->password = 'ifXHs3EJc-$>';
}*/
$this->login = null;
$this->password = null;
$this->url = 'https://api.mirai.com/XMLIntegrationx/';
$this->channelManagerId = 7;
$this->channelManagerName = 'Mirai';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
}
public function setupUser($login, $password)
{
$this->login = $login;
$this->password = $password;
}
public function request($type, $method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$formAuthParam = [
'login' => $this->login,
'password' => $this->password,
];
if(empty($this->login)) {
throw new ApiErrorException('Login data not set!');
}
$parameter = [
'headers' => [],
'query' => $formAuthParam,
];
if (!empty($xmlPayload)) {
$parameter['body'] = $xmlPayload;
}
//Log::debug($xmlPayload);
$request = $this->restClient->request($type, $this->url . $method, $parameter);
$getResponseBody = $request->getBody();
$getResponse = $getResponseBody->getContents();
$getResponseXml = new \SimpleXMLElement($getResponse);
$getResponse = json_decode(json_encode($getResponseXml), 1);
if (isset($getResponse['message']['error'])) {
$errorMessage = is_array($getResponse['message']['error']['comment']) ? implode(',', $getResponse['message']['error']['comment']) : $getResponse['message']['error']['comment'];
throw new ApiErrorException($errorMessage);
}
if ($request->getStatusCode() != 200) {
if($request->getReasonPhrase()) {
$firstError = $request->getReasonPhrase();
} else {
$firstError = is_array($getResponse['message']['error']['comment']) ? implode(',', $getResponse['message']['error']['comment']) : $getResponse['message']['error']['comment'];
}
/*Log::debug('__REQ__');
Log::debug($this->url);
Log::debug($type);
Log::debug($method);
Log::debug($xmlPayload);
Log::debug('__RES__');
Log::debug($getResponse);
Log::debug(PHP_EOL); */
throw new ApiErrorException($firstError);
}
$response = ["status" => true, 'message' => '', "data" => fillOnUndefined($getResponse, 'data', [])];
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function inventoryRoomRateUpdate($method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$request = $this->request('POST', $method, $xmlPayload);
if (!$request['status']) {
throw new ApiErrorException($request['message']);
}
$response = [
'status' => true,
'data' => null
];
} 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;
}
/** Pattern Functions */
/*
public function availabilityUpdateRequestMultiParam($propertyId, $propertyRoomRateMapping, $params)
{
$idList = [];
$requestParam['values'] = [];
ksort($params);
$dataByRoomDate = [];
$propertyRoomRateMappingCollect = collect($propertyRoomRateMapping);
foreach ($params as $currentDate => $rooms) {
foreach ($rooms as $roomId => $value) {
$uniqueKey = $value['availability'];
$roomIdManipulate = $roomId;
$roomIdManipulateCheck = $propertyRoomRateMappingCollect->where('channel_manager_room_id', $roomId)->where('property_room_rate_mapping.status', 1)->first();
if (!empty($roomIdManipulateCheck)) {
$roomIdManipulate = $roomIdManipulateCheck['channel_manager_room_rate_id'];
}
$dataByRoomDate[$roomIdManipulate][$uniqueKey][$currentDate] = $value;
}
}
$requestParam = [];
$valueKey = 0;
foreach ($dataByRoomDate as $roomId => $rooms) {
foreach ($rooms as $uniqueKey => $uniqueValues) {
$uniqueValueDate = array_keys($uniqueValues);
$dateKey = 0;
$dateGroup = [];
for ($i = 0; $i < count($uniqueValueDate); $i++) {
$dateGroup[$dateKey][] = $uniqueValueDate[$i];
if ($i + 1 < count($uniqueValueDate)) {
if (Carbon::parse($uniqueValueDate[$i])->diffInDays(Carbon::parse($uniqueValueDate[$i + 1])) > 1) {
$dateKey++;
}
}
}
foreach ($uniqueValues as $uniqueValue) {
$idList = array_merge($idList, $uniqueValue['idList']);
}
$currentValue = reset($uniqueValues);
foreach ($dateGroup as $dates) {
if (count($dates) > 1) {
$requestParam[$roomId]['data'][$valueKey] = [
'property_id' => $propertyId,
'room_type_id' => $roomId,
'date_from' => reset($dates),
'date_to' => last($dates),
'availability' => $currentValue['availability']
];
} else {
$requestParam[$roomId]['data'][$valueKey] = [
'property_id' => $propertyId,
'room_type_id' => $roomId,
'date_from' => reset($dates),
'date_to' => reset($dates),
'availability' => $currentValue['availability']
];
}
$valueKey++;
}
}
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventoryUpdate></inventoryUpdate>');
$xmlResponse->addAttribute('hotelId', $propertyId);
foreach ($requestParam as $roomId => $roomData) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $roomId);
$roomInventory = $room->addChild('inventory');
foreach ($roomData['data'] as $roomRate) {
$roomInventoryAvailability = $roomInventory->addChild('availability');
$roomInventoryAvailability->addAttribute('from', $roomRate['date_from']);
$roomInventoryAvailability->addAttribute('to', $roomRate['date_to']);
$roomInventoryAvailability->addAttribute('quantity', $roomRate['availability']);
}
}
return [
'idList' => $idList,
'payload' => $xmlResponse->asXML()
];
}
public function roomAvailabilityPush($propertyId, $bulkQueueData)
{
$response = ['status' => false, 'message' => ''];
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping'],
'firstRow' => true,
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
$channelManagerPushedIds = [];
$channelManagerNoneMappingIds = [];
$channelManagerPushConfirmCode = [];
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
$channelManagerPropertyRoomRateMappingCollect = collect($channelManagerPropertyMapping['channel_manager_room_rate']);
$roomAvailabilityQueueForUpdate = [];
$roomAvailabilityQueueForUpdateIdList = [];
$roomAvailabilityQueue = $bulkQueueData;
try {
foreach ($roomAvailabilityQueue as $roomAvailability) {
//Dates less than today cannot be updated.
if (Carbon::parse($roomAvailability['date'])->lessThan(Carbon::now()->toDateString())) {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - Previous Date Problem',
'logMessage' => '<pre>' . print_r($roomAvailability, true) . '</pre>'
];
//$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$channelManagerPushedIds[] = $roomAvailability['id'];
continue;
}
$channelManagerRoomRate = $channelManagerPropertyRoomRateMappingCollect->where('property_room_rate_mapping.room_id', $roomAvailability['property_room_id'])->first();
if (empty($channelManagerRoomRate)) {
//None Mapping!
//$channelManagerPushedIds[] = $roomAvailability['id'];
$channelManagerNoneMappingIds[] = $roomAvailability['id'];
continue;
}
$roomAvailabilityQueueForUpdateIdList[$roomAvailability['date']][] = $roomAvailability['id'];
$roomAvailabilityQueueForUpdate[$roomAvailability['date']]
[$channelManagerRoomRate['channel_manager_room_id']] = [
'id' => $roomAvailability['id'],
'idList' => $roomAvailabilityQueueForUpdateIdList[$roomAvailability['date']],
'date' => $roomAvailability['date'],
'availability' => $roomAvailability['stop_sell'] == 1 ? 0 : $roomAvailability['availability']
];
}
$roomAvailabilityUpdateRequestMultiParam = $this->availabilityUpdateRequestMultiParam($channelManagerPropertyMapping['channel_manager_property_id'], $channelManagerPropertyMapping['channel_manager_room_rate'], $roomAvailabilityQueueForUpdate);
$request = $this->inventoryRoomRateUpdate('webservice_updater.apro', $roomAvailabilityUpdateRequestMultiParam['payload']);
if ($request['status']) {
$channelManagerPushedIds = array_merge($channelManagerPushedIds, $roomAvailabilityUpdateRequestMultiParam['idList']);
$channelManagerPushConfirmCode[] = $request['data']['confirmId'];
} else {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - InventoryRoomRateAvailabilityUpdate Error',
'logMessage' => '<pre>' . print_r(array_merge($request, $roomAvailabilityUpdateRequestMultiParam), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
throw new ApiErrorException($request['message']);
}
} catch (ApiErrorException $e) {
$message = $this->channelManagerName . ' - ' . $e->getFile() . " " . $e->getLine() . " " . implode(', ', $e->getMessageArr());
Log::error($message);
//$response['message'] = $this->channelManagerName . ' - ' . implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $this->channelManagerName . ' - ' . $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
//$response['message'] = $e->getMessage();
}
} else {
$channelManagerNoneMappingIds = collect($bulkQueueData)->pluck('id')->toArray();
}
$channelManagerPushedIds = array_unique($channelManagerPushedIds);
asort($channelManagerPushedIds);
$channelManagerPushedIds = array_values($channelManagerPushedIds);
$response = [
'status' => true,
'data' => [
'confirmCode' => $channelManagerPushConfirmCode,
'channelManagerPushedIds' => $channelManagerPushedIds,
'channelManagerNoneMappingIds' => $channelManagerNoneMappingIds
]
];
return $response;
}
public function roomRateUpdateRequestMultiParam($propertyId, $params)
{
$idList = [];
ksort($params);
$dataByRoomRate = [];
foreach ($params as $currentDate => $rooms) {
foreach ($rooms as $roomId => $rates) {
foreach ($rates as $rateId => $value) {
$uniqueKey = $value['amount'] . '|' . $value['stop_sell'] . '|' . $value['min_stay'];
$dataByRoomRate[$rateId][$uniqueKey][$currentDate] = $value;
}
}
}
//Log::debug(json_encode($dataByRoomRate));
$requestParam = [];
$valueKey = 0;
foreach ($dataByRoomRate as $rateId => $rates) {
$valueKey = 0;
foreach ($rates as $uniqueKey => $uniqueValues) {
$uniqueValueDate = array_keys($uniqueValues);
$dateKey = 0;
$dateGroup = [];
for ($i = 0; $i < count($uniqueValueDate); $i++) {
$dateGroup[$dateKey][] = $uniqueValueDate[$i];
if ($i + 1 < count($uniqueValueDate)) {
if (Carbon::parse($uniqueValueDate[$i])->diffInDays(Carbon::parse($uniqueValueDate[$i + 1])) > 1) {
$dateKey++;
}
}
}
foreach ($uniqueValues as $uniqueValue) {
$idList = array_merge($idList, $uniqueValue['idList']);
}
$currentValue = reset($uniqueValues);
foreach ($dateGroup as $dates) {
$requestParam[$rateId][$valueKey] = [
'property_id' => $propertyId,
'rate_plan_id' => $rateId,
'date_from' => reset($dates),
'date_to' => last($dates),
'amount' => moneyDoubleFormatDecimal($currentValue['amount']),
'stop_sell' => fillOnUndefined($currentValue, 'stop_sell', 0),
'min_stay' => fillOnUndefined($currentValue, 'min_stay', 1) != 0 ? $currentValue['min_stay'] : 1,
'currency' => $currentValue['currency'],
];
if ($requestParam[$rateId][$valueKey]['amount'] == 0) {
$requestParam[$rateId][$valueKey]['stop_sell'] = 1;
}
$valueKey++;
}
}
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventoryUpdate></inventoryUpdate>');
$xmlResponse->addAttribute('hotelId', $propertyId);
foreach ($requestParam as $roomId => $roomData) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $roomId);
$currencyCode = reset($roomData)['currency'];
$roomRate = $room->addChild('rate');
$roomRate->addAttribute('currency', $currencyCode);
foreach ($roomData as $roomRateData) {
$roomRatePlaning = $roomRate->addChild('planning');
$roomRatePlaning->addAttribute('from', $roomRateData['date_from']);
$roomRatePlaning->addAttribute('to', $roomRateData['date_to']);
$roomRatePlaning->addAttribute('unitPrice', $roomRateData['stop_sell'] == 1 ? 0 : $roomRateData['amount']);
$roomRatePlaning->addAttribute('minimumStay', $roomRateData['min_stay']);
}
}
return [
'idList' => $idList,
'payload' => $xmlResponse->asXML()
];
}
public function roomRatePricePush($propertyId, $bulkQueueData)
{
$response = ['status' => false, 'message' => ''];
try {
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping'],
'firstRow' => true,
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
$channelManagerPushedIds = [];
$channelManagerNoneMappingIds = [];
$channelManagerPushConfirmCode = null;
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
$channelManagerPropertyRoomRateMappingCollect = collect($channelManagerPropertyMapping['channel_manager_room_rate']);
$roomRatePriceQueueForUpdate = [];
$roomRatePriceQueueForUpdateIdList = [];
$roomRatePriceQueue = $bulkQueueData;
foreach ($roomRatePriceQueue as $roomRatePrice) {
//Dates less than today cannot be updated.
if (Carbon::parse($roomRatePrice['date'])->lessThan(Carbon::now()->toDateString())) {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - Previous Date Problem',
'logMessage' => '<pre>' . print_r($roomRatePrice, true) . '</pre>'
];
//$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$channelManagerPushedIds[] = $roomRatePrice['id'];
continue;
}
$channelManagerRoomRate = $channelManagerPropertyRoomRateMappingCollect->where('property_room_rate_mapping_id', $roomRatePrice['room_rate_mapping_id'])->first();
if (empty($channelManagerRoomRate)) {
//None Mapping!
//$channelManagerPushedIds[] = $roomAvailability['id'];
$channelManagerNoneMappingIds[] = $roomRatePrice['id'];
//TODO: Burada oda eşleşmiyorsa süreç devam ediyor ama uyarı maili atılabilir.
continue;
}
$roomRatePriceQueueForUpdateIdList
[$channelManagerPropertyMapping['channel_manager_property_id']]
[$roomRatePrice['date']][$channelManagerRoomRate['channel_manager_room_id']]
[$channelManagerRoomRate['channel_manager_room_rate_id']][] = $roomRatePrice['id'];
$roomRatePriceQueueForUpdate
[$channelManagerPropertyMapping['channel_manager_property_id']]
[$roomRatePrice['date']]
[$channelManagerRoomRate['channel_manager_room_id']]
[$channelManagerRoomRate['channel_manager_room_rate_id']] = [
'id' => $roomRatePrice['id'],
'idList' => $roomRatePriceQueueForUpdateIdList[$channelManagerPropertyMapping['channel_manager_property_id']][$roomRatePrice['date']][$channelManagerRoomRate['channel_manager_room_id']][$channelManagerRoomRate['channel_manager_room_rate_id']],
'date' => $roomRatePrice['date'],
'amount' => $roomRatePrice['amount'],
'currency' => $roomRatePrice['currency'],
'stop_sell' => $roomRatePrice['stop_sell'],
'min_stay' => $roomRatePrice['min_stay'],
];
}
foreach ($roomRatePriceQueueForUpdate as $channelManagerPropertyId => $channelManagerProperty) {
if (empty($channelManagerProperty)) {
throw new ApiErrorException('$channelManagerProperty is Empty!');
}
$roomRateUpdateRequestMultiParam = $this->roomRateUpdateRequestMultiParam($channelManagerPropertyId, $channelManagerProperty);
$request = $this->inventoryRoomRateUpdate('webservice_updater.apro', $roomRateUpdateRequestMultiParam['payload']);
if ($request['status']) {
$channelManagerPushedIds = array_merge($channelManagerPushedIds, $roomRateUpdateRequestMultiParam['idList']);
$channelManagerPushConfirmCode = $request['data']['confirmId'];
} else {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - InventoryRoomRateUpdate Error',
'logMessage' => '<pre>' . print_r($request, true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
throw new ApiErrorException($request['message']);
}
}
}
$channelManagerPushedIds = array_unique($channelManagerPushedIds);
asort($channelManagerPushedIds);
$channelManagerPushedIds = array_values($channelManagerPushedIds);
$response = [
'status' => true,
'data' => [
'confirmCode' => $channelManagerPushConfirmCode,
'channelManagerPushedIds' => $channelManagerPushedIds,
'channelManagerNoneMappingIds' => $channelManagerNoneMappingIds
]
];
} catch (ApiErrorException $e) {
$response['message'] = $this->channelManagerName . ' - ' . implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $this->channelManagerName . ' - ' . $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
*/
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,252 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerBookingService;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class SistemOtel
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService,
ChannelManagerBookingService $channelManagerBookingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->reservationPushUrl = 'https://cm.istbooking.com/push/extranetwork';
$this->typeMapping = [
'Booking' => 'Book',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
$this->channelManagerId = 6;
$this->channelManagerName = 'SistemOtel';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
$this->channelManagerBookingService = $channelManagerBookingService;
}
public function requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$type = $this->typeMapping[$type];
$bookingDetail = $param['booking_detail'];
$jsonResponse = [];
$jsonResponse['hotel_id'] = $propertyId;
$jsonResponse['reservation']['code'] = $bookingDetail['booking_code'];
$jsonResponse['reservation']['status'] = $type;
$jsonResponse['reservation']['time'] = Carbon::createFromTimestamp($param['booking_detail']['created_at'])->toDateTimeString();
$jsonResponse['reservation']['checkin_date'] = $bookingDetail['checkin_date'];
$jsonResponse['reservation']['checkout_date'] = $bookingDetail['checkout_date'];
$jsonResponse['reservation']['currency'] = $bookingDetail['currency_code'];
$jsonResponse['reservation']['total'] = $bookingDetail['total'];
$jsonResponse['reservation']['contact'] = [
'name' => $bookingDetail['booking_contact']['name'],
'surname' => $bookingDetail['booking_contact']['surname'],
'email' => $bookingDetail['booking_contact']['email'],
'phone' => $bookingDetail['booking_contact']['phoneFormatted'],
'note' => $bookingDetail['booking_contact']['note'],
];
$jsonResponse['reservation']['rooms'] = [];
$roomKey = 0;
$additionalNoteText = [];
foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {
if ($roomDetail['status'] != 1) {
continue;
}
$occupancy = occupancyCodeParser($roomDetail['occupancy_code']);
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
$baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
$dailyPrices = [];
$currentDate = $roomDetail['checkin_date'];
for ($i = 0; $i < $diffInDays; $i++) {
$dailyPrices[] = [
'date' => $currentDate,
'amount' => $baseRateDaily
];
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
$roomPax = [];
foreach ($roomDetail['room_pax'] as $pax) {
$roomPax[] = [
'type' => $pax['type'],
'name' => $pax['name'],
'surname' => $pax['surname'],
'gender' => $pax['gender'],
'citizen' => $pax['citizen'],
'birth_date' => $pax['birth_date'],
];
}
$cancellationPolicy = [];
$cancellationPolicyRoom = json_decode($roomDetail['cancellation_policy'], 1);
if ($cancellationPolicyRoom) {
$cancellationPolicy = [
'is_nonrefundable' => fillOnUndefined($cancellationPolicyRoom, 'isNonRefundable') == 1 ? true : false,
'is_freecancellation' => fillOnUndefined($cancellationPolicyRoom, 'isFreeCancellation') == 1 ? true : false,
'before_arrival_day' => fillOnUndefined($cancellationPolicyRoom, 'isFreeCancellation') == 1 ? fillOnUndefined($cancellationPolicyRoom, 'beforeArrivalDay') : null,
'type' => fillOnUndefined($cancellationPolicyRoom, 'type') == 1 ? fillOnUndefined($cancellationPolicyRoom, 'type') : null,
'value' => fillOnUndefined($cancellationPolicyRoom, 'value') == 1 ? fillOnUndefined($cancellationPolicyRoom, 'value') : null,
'text' => null,
];
$cancellationPolicyTextFormatted = cancellationPolicyTextFormatted(
fillOnUndefined($cancellationPolicyRoom, 'isNonRefundable'),
fillOnUndefined($cancellationPolicyRoom, 'isFreeCancellation'),
fillOnUndefined($cancellationPolicyRoom, 'beforeArrivalDay'),
fillOnUndefined($cancellationPolicyRoom, 'type'),
fillOnUndefined($cancellationPolicyRoom, 'value'),
$bookingDetail['currency_code'],
'en'
);
if($cancellationPolicyTextFormatted) {
$cancellationPolicy['text'] = $cancellationPolicyTextFormatted;
}
}
$jsonResponse['reservation']['rooms'][$roomKey] = [
'id' => $roomDetail['id'],
'room_id' => $roomDetail['room_id'],
'room_name' => $roomDetail['room_name'],
'rate_id' => $roomDetail['room_rate_mapping_id'],
'rate_name' => $roomDetail['room_rate_name'],
'cancellation_policy' => $cancellationPolicy,
'occupancy' => [
'adults' => $occupancy['ADT'],
'children' => $occupancy['CHD'],
'age' => $occupancy['AGE'],
],
'daily' => $dailyPrices,
'pax' => $roomPax,
];
if(isset($jsonResponse['reservation']['rooms'][$roomKey]['cancellation_policy']['text'])) {
$additionalNoteText[] = ($roomKey + 1).'. '.$jsonResponse['reservation']['rooms'][$roomKey]['room_name'].' - '.$jsonResponse['reservation']['rooms'][$roomKey]['rate_name']. ' ('.$jsonResponse['reservation']['rooms'][$roomKey]['cancellation_policy']['text'].')';
}
}
$additionalNoteText[] = 'Payment: '.$bookingDetail['booking_payment_type']['code'].' - '.$bookingDetail['booking_payment_type']['name'];
$jsonResponse['reservation']['contact']['note'].=implode(', ',$additionalNoteText);
$jsonResponse['reservation']['channel'] = [
'id' => $bookingDetail['booking_channel']['id'],
'name' => $bookingDetail['booking_channel']['id'] == 1 ? 'Extranetwork' : $bookingDetail['booking_channel']['name'],
];
$jsonResponse['reservation']['payment'] = [
'code' => $bookingDetail['booking_payment_type']['code'],
'name' => $bookingDetail['booking_payment_type']['name'],
];
return json_encode($jsonResponse);
}
public function requestPostReservationPush($jsonPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$res = $this->restClient->post($this->reservationPushUrl,
[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
$getResponseBody = $res->getBody();
$getResponseJsonBase = $getResponseBody->getContents();
$getResponse = json_decode($getResponseJsonBase, 1);
if (!$getResponse['status']) {
if($getResponse['message'] == 'HOTEL_TANIMLI_DEGIL') {
$jsonPayloadArray = json_decode($jsonPayload,1);
$bookingCriteria = [
'criteria' =>
[
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'type', 'condition' => '=', 'value' => array_search($jsonPayloadArray['reservation']['status'], $this->typeMapping)],
['field' => 'request', 'condition' => 'LIKE', 'value' => '%'.$jsonPayloadArray['reservation']['code'].'%'],
],
'firstRow' => true
];
$channelManagerBookingDetail = $this->channelManagerBookingService->select($bookingCriteria);
if($channelManagerBookingDetail['status'] == 'success' && !empty($channelManagerBookingDetail['status'])) {
$channelManagerBookingDetail = $channelManagerBookingDetail['data'];
$this->channelManagerBookingService->update($channelManagerBookingDetail['id'], ['status' => 2]);
}
}
throw new ApiErrorException($getResponse['message']);
}
$response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
}

View File

@@ -0,0 +1,208 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class Trivago
{
private $statusMapping;
private $paymentTypeMapping;
private $channelManagerId;
private $channelManagerName;
private $mailer;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService,
BookingService $bookingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->reservationPushUrl = 'https://secde.trivago.com/tracking/booking';
$this->typeMapping = [
'Booking' => 'Booking',
'Modify' => 'Modify',
'Cancel' => 'Cancel'
];
$this->channelManagerId = 11;
$this->channelManagerName = 'Trivago';
$this->xTrvAnaKey = '1fe8a527-cbcb-4e01-9a3c-31444d47c422';
$this->advertiserId = 3698;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
$this->bookingService = $bookingService;
}
public function requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
{
$type = $this->typeMapping[$type];
$bookingDetail = $param['booking_detail'];
$jsonResponse = [];
$extraParam = json_decode($bookingDetail['extra_param'], 1);
if (!isset($extraParam['trv_reference'])) {
return $jsonResponse;
}
$locale = 'TR';
if(isset($extraParam['locale'])) {
$locale = $extraParam['locale'];
}
if($bookingDetail['total'] > 0) {
$bookingDetail['total'] = $bookingDetail['total'];
} else {
$bookingDetail['total'] = $bookingDetail['booking_payment']['total'];
}
$jsonResponse['trv_reference'] = $extraParam['trv_reference'];
$jsonResponse['advertiser_id'] = $this->advertiserId;
$jsonResponse['hotel'] = $bookingDetail['property_id'];
$jsonResponse['arrival'] = Carbon::parse($bookingDetail['checkin_date'])->format('Ymd');
$jsonResponse['departure'] = Carbon::parse($bookingDetail['checkout_date'])->format('Ymd');
$jsonResponse['date_format'] = 'Ymd';
$jsonResponse['volume'] = $bookingDetail['total'];
$jsonResponse['currency'] = $bookingDetail['currency_code'];
$jsonResponse['locale'] = mb_strtoupper($locale);
$jsonResponse['booking_id'] = $bookingDetail['booking_code'];
//$jsonResponse['margin'] = $bookingDetail['booking_code'];
$jsonResponse['booking_date'] = Carbon::createFromTimestamp($bookingDetail['created_at'])->subHours(3)->format('YmdHisP');
$jsonResponse['booking_date_format'] = 'YmdHisP';
$jsonResponse['number_of_rooms'] = count($bookingDetail['booking_room']);
if ($type == 'Modify') {
$jsonResponse['update_date'] = Carbon::createFromTimestamp($param['created_at'])->subHours(3)->format('YmdHisP');
$jsonResponse['update_date_format'] = 'YmdHisP';
$jsonResponse['update_origin'] = 'user';
}
if ($type == 'Cancel') {
$jsonResponse['refund_amount'] = $bookingDetail['total'];
$jsonResponse['cancellation_date'] = Carbon::createFromTimestamp($param['created_at'])->subHours(3)->format('YmdHisP');
$jsonResponse['cancellation_date_format'] = 'YmdHisP';
}
$jsonResponse['params']['type'] = $type;
return json_encode($jsonResponse);
}
public function requestPostReservationPush($jsonPayload)
{
$response = ['status' => false, 'message' => ''];
$getResponse = [];
$this->restClient = new Client(['http_errors' => false]);
try {
$jsonData = json_decode($jsonPayload, 1);
$jsonDataParams = $jsonData['params'];
unset($jsonData['params']);
$jsonPayload = json_encode($jsonData);
switch ($jsonDataParams['type']) {
case 'Booking':
$request = $this->restClient->post($this->reservationPushUrl,
[
'headers' => [
'X-Trv-Ana-Key' => $this->xTrvAnaKey,
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
break;
case 'Modify':
$request = $this->restClient->put($this->reservationPushUrl,
[
'headers' => [
'X-Trv-Ana-Key' => $this->xTrvAnaKey,
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
break;
case 'Cancel':
$request = $this->restClient->delete($this->reservationPushUrl,
[
'headers' => [
'X-Trv-Ana-Key' => $this->xTrvAnaKey,
'Content-Type' => 'application/json'
],
'body' => $jsonPayload,
]
);
break;
case 'default':
throw new ApiErrorException('Reservation push type not found.');
break;
}
$getResponseBody = $request->getBody();
$getResponseJsonBase = $getResponseBody->getContents();
$getResponse = json_decode($getResponseJsonBase, 1);
Log::debug($jsonPayload);
Log::debug(json_encode($getResponse));
//dd($getResponse);
if ($getResponse['state'] != 'OK') {
throw new ApiErrorException($getResponse['errorMessage']);
}
$response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
}

View File

@@ -0,0 +1,667 @@
<?php
namespace App\Core\Service\ChannelManager;
use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;
class _Mirai
{
private $channelManagerId;
private $channelManagerName;
private $mailer;
private $login;
private $password;
private $url;
public function __construct(
Client $restClient,
Mailer $mailer,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerMappingService $channelManagerMappingService
)
{
$this->restClient = $restClient;
$this->mailer = $mailer;
if (App::environment() == 'production') {
$this->login = 'ExtranetWorktest-xml-100378347';
$this->password = 'ifXHs3EJc-$>';
$this->url = 'https://api.mirai.com/XMLIntegrationx/';
} else {
$this->login = 'ExtranetWorktest-xml-100378347';
$this->password = 'ifXHs3EJc-$>';
$this->url = 'https://api.mirai.com/XMLIntegrationx/';
}
$this->channelManagerId = 7;
$this->channelManagerName = 'Mirai';
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerMappingService = $channelManagerMappingService;
}
public function request($type, $method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
$formAuthParam = [
'login' => $this->login,
'password' => $this->password,
];
$parameter = [
'headers' => [],
'query' => $formAuthParam,
];
if (!empty($xmlPayload)) {
$parameter['body'] = $xmlPayload;
}
$request = $this->restClient->request($type, $this->url . $method, $parameter);
$getResponseBody = $request->getBody();
$getResponse = $getResponseBody->getContents();
$getResponseXml = new \SimpleXMLElement($getResponse);
$getResponse = json_decode(json_encode($getResponseXml), 1);
if (isset($getResponse['error'])) {
$errorMessage = is_array($getResponse['error']['comment']) ? implode(',', $getResponse['error']['comment']) : $getResponse['error']['comment'];
throw new ApiErrorException($errorMessage);
}
if ($request->getStatusCode() != 200) {
$firstError = is_array($getResponse['error']['comment']) ? implode(',', $getResponse['error']['comment']) : $getResponse['error']['comment'];
Log::debug('__REQ__');
Log::debug($this->url);
Log::debug($type);
Log::debug($method);
Log::debug($xmlPayload);
Log::debug('__RES__');
Log::debug($getResponse);
Log::debug(PHP_EOL);
throw new ApiErrorException($firstError);
}
$response = ["status" => true, 'message' => '', "data" => fillOnUndefined($getResponse, 'data', [])];
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function inventoryRoomRateUpdate($method, $xmlPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$request = $this->request('POST', $method, $xmlPayload);
if (!$request['status']) {
throw new ApiErrorException($request['message']);
}
$response = [
'status' => true,
'data' => null
];
} 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;
}
/** Pattern Functions */
public function availabilityUpdateRequestMultiParam($propertyId, $propertyRoomRateMapping, $params)
{
$idList = [];
$requestParam['values'] = [];
ksort($params);
$dataByRoomDate = [];
$propertyRoomRateMappingCollect = collect($propertyRoomRateMapping);
foreach ($params as $currentDate => $rooms) {
foreach ($rooms as $roomId => $value) {
$uniqueKey = $value['availability'];
$roomIdManipulate = $roomId;
$roomIdManipulateCheck = $propertyRoomRateMappingCollect->where('channel_manager_room_id', $roomId)->where('property_room_rate_mapping.status', 1)->first();
if (!empty($roomIdManipulateCheck)) {
$roomIdManipulate = $roomIdManipulateCheck['channel_manager_room_rate_id'];
}
$dataByRoomDate[$roomIdManipulate][$uniqueKey][$currentDate] = $value;
}
}
$requestParam = [];
$valueKey = 0;
foreach ($dataByRoomDate as $roomId => $rooms) {
foreach ($rooms as $uniqueKey => $uniqueValues) {
$uniqueValueDate = array_keys($uniqueValues);
$dateKey = 0;
$dateGroup = [];
for ($i = 0; $i < count($uniqueValueDate); $i++) {
$dateGroup[$dateKey][] = $uniqueValueDate[$i];
if ($i + 1 < count($uniqueValueDate)) {
if (Carbon::parse($uniqueValueDate[$i])->diffInDays(Carbon::parse($uniqueValueDate[$i + 1])) > 1) {
$dateKey++;
}
}
}
foreach ($uniqueValues as $uniqueValue) {
$idList = array_merge($idList, $uniqueValue['idList']);
}
$currentValue = reset($uniqueValues);
foreach ($dateGroup as $dates) {
if (count($dates) > 1) {
$requestParam[$roomId]['data'][$valueKey] = [
'property_id' => $propertyId,
'room_type_id' => $roomId,
'date_from' => reset($dates),
'date_to' => last($dates),
'availability' => $currentValue['availability']
];
} else {
$requestParam[$roomId]['data'][$valueKey] = [
'property_id' => $propertyId,
'room_type_id' => $roomId,
'date_from' => reset($dates),
'date_to' => reset($dates),
'availability' => $currentValue['availability']
];
}
$valueKey++;
}
}
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventoryUpdate></inventoryUpdate>');
$xmlResponse->addAttribute('hotelId', $propertyId);
foreach ($requestParam as $roomId => $roomData) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $roomId);
$roomInventory = $room->addChild('inventory');
foreach ($roomData['data'] as $roomRate) {
$roomInventoryAvailability = $roomInventory->addChild('availability');
$roomInventoryAvailability->addAttribute('from', $roomRate['date_from']);
$roomInventoryAvailability->addAttribute('to', $roomRate['date_to']);
$roomInventoryAvailability->addAttribute('quantity', $roomRate['availability']);
}
}
return [
'idList' => $idList,
'payload' => $xmlResponse->asXML()
];
}
public function roomAvailabilityPush($propertyId, $bulkQueueData)
{
$response = ['status' => false, 'message' => ''];
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping'],
'firstRow' => true,
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
$channelManagerPushedIds = [];
$channelManagerNoneMappingIds = [];
$channelManagerPushConfirmCode = [];
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
$channelManagerPropertyRoomRateMappingCollect = collect($channelManagerPropertyMapping['channel_manager_room_rate']);
$roomAvailabilityQueueForUpdate = [];
$roomAvailabilityQueueForUpdateIdList = [];
$roomAvailabilityQueue = $bulkQueueData;
try {
foreach ($roomAvailabilityQueue as $roomAvailability) {
//Dates less than today cannot be updated.
if (Carbon::parse($roomAvailability['date'])->lessThan(Carbon::now()->toDateString())) {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - Previous Date Problem',
'logMessage' => '<pre>' . print_r($roomAvailability, true) . '</pre>'
];
//$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$channelManagerPushedIds[] = $roomAvailability['id'];
continue;
}
$channelManagerRoomRate = $channelManagerPropertyRoomRateMappingCollect->where('property_room_rate_mapping.room_id', $roomAvailability['property_room_id'])->first();
if (empty($channelManagerRoomRate)) {
//None Mapping!
//$channelManagerPushedIds[] = $roomAvailability['id'];
$channelManagerNoneMappingIds[] = $roomAvailability['id'];
continue;
}
$roomAvailabilityQueueForUpdateIdList[$roomAvailability['date']][] = $roomAvailability['id'];
$roomAvailabilityQueueForUpdate[$roomAvailability['date']]
[$channelManagerRoomRate['channel_manager_room_id']] = [
'id' => $roomAvailability['id'],
'idList' => $roomAvailabilityQueueForUpdateIdList[$roomAvailability['date']],
'date' => $roomAvailability['date'],
'availability' => $roomAvailability['stop_sell'] == 1 ? 0 : $roomAvailability['availability']
];
}
$roomAvailabilityUpdateRequestMultiParam = $this->availabilityUpdateRequestMultiParam($channelManagerPropertyMapping['channel_manager_property_id'], $channelManagerPropertyMapping['channel_manager_room_rate'], $roomAvailabilityQueueForUpdate);
$request = $this->inventoryRoomRateUpdate('webservice_updater.apro', $roomAvailabilityUpdateRequestMultiParam['payload']);
if ($request['status']) {
$channelManagerPushedIds = array_merge($channelManagerPushedIds, $roomAvailabilityUpdateRequestMultiParam['idList']);
$channelManagerPushConfirmCode[] = $request['data']['confirmId'];
} else {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - InventoryRoomRateAvailabilityUpdate Error',
'logMessage' => '<pre>' . print_r(array_merge($request, $roomAvailabilityUpdateRequestMultiParam), true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
throw new ApiErrorException($request['message']);
}
} catch (ApiErrorException $e) {
$message = $this->channelManagerName . ' - ' . $e->getFile() . " " . $e->getLine() . " " . implode(', ', $e->getMessageArr());
Log::error($message);
//$response['message'] = $this->channelManagerName . ' - ' . implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $this->channelManagerName . ' - ' . $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
//$response['message'] = $e->getMessage();
}
} else {
$channelManagerNoneMappingIds = collect($bulkQueueData)->pluck('id')->toArray();
}
$channelManagerPushedIds = array_unique($channelManagerPushedIds);
asort($channelManagerPushedIds);
$channelManagerPushedIds = array_values($channelManagerPushedIds);
$response = [
'status' => true,
'data' => [
'confirmCode' => $channelManagerPushConfirmCode,
'channelManagerPushedIds' => $channelManagerPushedIds,
'channelManagerNoneMappingIds' => $channelManagerNoneMappingIds
]
];
return $response;
}
public function roomRateUpdateRequestMultiParam($propertyId, $params)
{
$idList = [];
ksort($params);
$dataByRoomRate = [];
foreach ($params as $currentDate => $rooms) {
foreach ($rooms as $roomId => $rates) {
foreach ($rates as $rateId => $value) {
$uniqueKey = $value['amount'] . '|' . $value['stop_sell'] . '|' . $value['min_stay'];
$dataByRoomRate[$rateId][$uniqueKey][$currentDate] = $value;
}
}
}
//Log::debug(json_encode($dataByRoomRate));
$requestParam = [];
$valueKey = 0;
foreach ($dataByRoomRate as $rateId => $rates) {
$valueKey = 0;
foreach ($rates as $uniqueKey => $uniqueValues) {
$uniqueValueDate = array_keys($uniqueValues);
$dateKey = 0;
$dateGroup = [];
for ($i = 0; $i < count($uniqueValueDate); $i++) {
$dateGroup[$dateKey][] = $uniqueValueDate[$i];
if ($i + 1 < count($uniqueValueDate)) {
if (Carbon::parse($uniqueValueDate[$i])->diffInDays(Carbon::parse($uniqueValueDate[$i + 1])) > 1) {
$dateKey++;
}
}
}
foreach ($uniqueValues as $uniqueValue) {
$idList = array_merge($idList, $uniqueValue['idList']);
}
$currentValue = reset($uniqueValues);
foreach ($dateGroup as $dates) {
$requestParam[$rateId][$valueKey] = [
'property_id' => $propertyId,
'rate_plan_id' => $rateId,
'date_from' => reset($dates),
'date_to' => last($dates),
'amount' => moneyDoubleFormatDecimal($currentValue['amount']),
'stop_sell' => fillOnUndefined($currentValue, 'stop_sell', 0),
'min_stay' => fillOnUndefined($currentValue, 'min_stay', 1) != 0 ? $currentValue['min_stay'] : 1,
'currency' => $currentValue['currency'],
];
if ($requestParam[$rateId][$valueKey]['amount'] == 0) {
$requestParam[$rateId][$valueKey]['stop_sell'] = 1;
}
$valueKey++;
}
}
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventoryUpdate></inventoryUpdate>');
$xmlResponse->addAttribute('hotelId', $propertyId);
foreach ($requestParam as $roomId => $roomData) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $roomId);
$currencyCode = reset($roomData)['currency'];
$roomRate = $room->addChild('rate');
$roomRate->addAttribute('currency', $currencyCode);
foreach ($roomData as $roomRateData) {
$roomRatePlaning = $roomRate->addChild('planning');
$roomRatePlaning->addAttribute('from', $roomRateData['date_from']);
$roomRatePlaning->addAttribute('to', $roomRateData['date_to']);
$roomRatePlaning->addAttribute('unitPrice', $roomRateData['stop_sell'] == 1 ? 0 : $roomRateData['amount']);
$roomRatePlaning->addAttribute('minimumStay', $roomRateData['min_stay']);
}
}
return [
'idList' => $idList,
'payload' => $xmlResponse->asXML()
];
}
public function roomRatePricePush($propertyId, $bulkQueueData)
{
$response = ['status' => false, 'message' => ''];
try {
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '!=', 'value' => null],
],
'with' => ['channelManagerRoomRate.propertyRoomRateMapping'],
'firstRow' => true,
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
$channelManagerPushedIds = [];
$channelManagerNoneMappingIds = [];
$channelManagerPushConfirmCode = null;
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
$channelManagerPropertyRoomRateMappingCollect = collect($channelManagerPropertyMapping['channel_manager_room_rate']);
$roomRatePriceQueueForUpdate = [];
$roomRatePriceQueueForUpdateIdList = [];
$roomRatePriceQueue = $bulkQueueData;
foreach ($roomRatePriceQueue as $roomRatePrice) {
//Dates less than today cannot be updated.
if (Carbon::parse($roomRatePrice['date'])->lessThan(Carbon::now()->toDateString())) {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - Previous Date Problem',
'logMessage' => '<pre>' . print_r($roomRatePrice, true) . '</pre>'
];
//$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
$channelManagerPushedIds[] = $roomRatePrice['id'];
continue;
}
$channelManagerRoomRate = $channelManagerPropertyRoomRateMappingCollect->where('property_room_rate_mapping_id', $roomRatePrice['room_rate_mapping_id'])->first();
if (empty($channelManagerRoomRate)) {
//None Mapping!
//$channelManagerPushedIds[] = $roomAvailability['id'];
$channelManagerNoneMappingIds[] = $roomRatePrice['id'];
//TODO: Burada oda eşleşmiyorsa süreç devam ediyor ama uyarı maili atılabilir.
continue;
}
$roomRatePriceQueueForUpdateIdList
[$channelManagerPropertyMapping['channel_manager_property_id']]
[$roomRatePrice['date']][$channelManagerRoomRate['channel_manager_room_id']]
[$channelManagerRoomRate['channel_manager_room_rate_id']][] = $roomRatePrice['id'];
$roomRatePriceQueueForUpdate
[$channelManagerPropertyMapping['channel_manager_property_id']]
[$roomRatePrice['date']]
[$channelManagerRoomRate['channel_manager_room_id']]
[$channelManagerRoomRate['channel_manager_room_rate_id']] = [
'id' => $roomRatePrice['id'],
'idList' => $roomRatePriceQueueForUpdateIdList[$channelManagerPropertyMapping['channel_manager_property_id']][$roomRatePrice['date']][$channelManagerRoomRate['channel_manager_room_id']][$channelManagerRoomRate['channel_manager_room_rate_id']],
'date' => $roomRatePrice['date'],
'amount' => $roomRatePrice['amount'],
'currency' => $roomRatePrice['currency'],
'stop_sell' => $roomRatePrice['stop_sell'],
'min_stay' => $roomRatePrice['min_stay'],
];
}
foreach ($roomRatePriceQueueForUpdate as $channelManagerPropertyId => $channelManagerProperty) {
if (empty($channelManagerProperty)) {
throw new ApiErrorException('$channelManagerProperty is Empty!');
}
$roomRateUpdateRequestMultiParam = $this->roomRateUpdateRequestMultiParam($channelManagerPropertyId, $channelManagerProperty);
$request = $this->inventoryRoomRateUpdate('webservice_updater.apro', $roomRateUpdateRequestMultiParam['payload']);
if ($request['status']) {
$channelManagerPushedIds = array_merge($channelManagerPushedIds, $roomRateUpdateRequestMultiParam['idList']);
$channelManagerPushConfirmCode = $request['data']['confirmId'];
} else {
//$logMessage
$mailParams = [
'title' => $this->channelManagerName . ' - RoomAvailabilityPushService Error - InventoryRoomRateUpdate Error',
'logMessage' => '<pre>' . print_r($request, true) . '</pre>'
];
$this->mailer->onQueue('logMail', new LogMail($mailParams));
//$logMessage
throw new ApiErrorException($request['message']);
}
}
}
$channelManagerPushedIds = array_unique($channelManagerPushedIds);
asort($channelManagerPushedIds);
$channelManagerPushedIds = array_values($channelManagerPushedIds);
$response = [
'status' => true,
'data' => [
'confirmCode' => $channelManagerPushConfirmCode,
'channelManagerPushedIds' => $channelManagerPushedIds,
'channelManagerNoneMappingIds' => $channelManagerNoneMappingIds
]
];
} catch (ApiErrorException $e) {
$response['message'] = $this->channelManagerName . ' - ' . implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $this->channelManagerName . ' - ' . $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
}