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,328 @@
<?php
namespace App\Http\Controllers;
use App\Core\Service\ApiAccessTokenService;
use App\Core\Service\UserPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Auth;
use App\Core\Validator\User\UserLoginValidator;
use App\Models\User;
use App\Core\Service\JwtService;
use Illuminate\Http\Request;
use Firebase\JWT\ExpiredException;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Config;
use App\Core\Service\PermissionService;
use Illuminate\Support\Facades\Log;
use Laravel\Lumen\Routing\Controller as BaseController;
class AuthController extends BaseController
{
private $request;
private $apiAccessTokenService;
private $jwtService;
private $userLoginValidator;
private $userPropertyMappingService;
private $permissionService;
public function __construct(
Request $request,
UserPropertyMappingService $userPropertyMappingService,
UserLoginValidator $userLoginValidator,
PermissionService $permissionService,
ApiAccessTokenService $apiAccessTokenService,
JwtService $jwtService
)
{
$this->request = $request;
$this->userLoginValidator = $userLoginValidator;
$this->jwtService = $jwtService;
$this->userPropertyMappingService = $userPropertyMappingService;
$this->permissionService = $permissionService;
$this->apiAccessTokenService = $apiAccessTokenService;
}
public function authenticate(User $user)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$return = [];
$validationData = [
'email' => $this->request->input('email'),
'password' => $this->request->input('password')
];
$locale = $this->request->input('locale');
$rememberMe = $this->request->input('remember_me') ;
$validationResult = $this->userLoginValidator->validate($validationData);
if ($validationResult->errors()->first()) {
$errors = $validationResult->errors()->all();
throw new ApiErrorException($errors);
}
$user = User::where('email', $this->request->input('email'))->where('status', 1)->first();
if (!$user) {
throw new ApiErrorException(lang('Email or password is wrong.'));
}
if (Hash::check($this->request->input('password'), $user->password)) {
$jwtToken = $this->jwtService->jwtCreate(['user_id' => $user['id'], 'remember_me' => $rememberMe, 'day_counter' => 5]);
if ($jwtToken['status'] != 'success') {
throw new ApiErrorException(lang('An unknown error occurred.'));
}
$jwtToken = $jwtToken['data'];
$return = [
'token' => $jwtToken['token']
];
} else {
throw new ApiErrorException(lang('Email or password is wrong.'));
}
$saveToken = [
"token" => md5(fillOnUndefined($jwtToken, "token")),
"expire_date" => fillOnUndefined($jwtToken, "exp"),
"user_id" => fillOnUndefined($user, "id"),
"invalidate" => fillOnUndefined($jwtToken, "invalidate", 0),
];
$saveTokenTo = $this->apiAccessTokenService->create($saveToken);
if ($saveTokenTo['status'] != 'success') {
throw new ApiErrorException(lang('General error'));
}
$return = [
'token' => $jwtToken['token'],
'expire_time' => $saveTokenTo['data']['expire_time'],
'locale' => $user['locale']
];
$onesignalKey = $this->request->input('onesignal_key');
if(isset($onesignalKey) && $onesignalKey){
if(strlen($onesignalKey) > 36){
throw new ApiErrorException(lang('Onesignal Key Size error'));
}
$userUpdateStatus = User::where('id', $user['id'])->where('status', 1)
->update(['onesignal_key' => $onesignalKey]);
if ($userUpdateStatus !== 1) {
throw new ApiErrorException(lang('Onesignal Key Update Error'));
}
}
$mappingPropertiesCriteria = [
'criteria' => [
['field' => 'user_id', 'condition' => '=', 'value' => $user['id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['property.defaultPropertyPhoto'],
];
$mappingProperties = $this->userPropertyMappingService->select($mappingPropertiesCriteria);
if (!$mappingProperties['data']) {
throw new ApiErrorException(lang('User Property mapping not found'));
}
$propertyList = collect($mappingProperties['data'])->map(function ($value) use ($user, $locale) {
$menuParams = [
'user_id' => $user['id'],
'property_id' => $value['property']['id'],
'status' => $value['property']['status'],
'locale' => $locale
] ;
if (is_array($value['property'])) {
$defaultPhoto = isset($value['property']['default_property_photo']) ? $value['property']['default_property_photo'] : null ;
$photoUrlThumbFilePath = '/assets/img/placeholder.png';
if(isset($defaultPhoto['photo_name'])){
$photoUrlThumbFilePath = Config::get('app.fileSystemDriver') . "/property-photos/{$value['property']['id']}" . "/{$defaultPhoto['photo_name']}_200x200.{$defaultPhoto['file_ext']}";
if (File::exists($photoUrlThumbFilePath)) {
$photoUrlThumbFilePath = Config::get('app.imageUrl') . "/property-photos/{$value['property']['id']}" . "/{$defaultPhoto['photo_name']}_200x200.{$defaultPhoto['file_ext']}";
}else {
$photoUrlThumbFilePath = Config::get('app.imageUrl') . "/property-photos/{$value['property']['id']}" . "/{$defaultPhoto['photo_name']}_thumbnail.{$defaultPhoto['file_ext']}";
}
}
return $value['property'] = [
'id' => $value['property']['id'],
'name' => $value['property']['name'],
'status' => $value['property']['status'],
'default_photo' => $photoUrlThumbFilePath ,
// 'property_menu' => $this->permissionService->getMenuTreeForUser($menuParams)
];
}
})->where('status' , '=', 1);
$propertyList = $propertyList->map(function ($value) {
return [
'id' => $value['id'],
'name' => $value['name'],
'default_photo' => $value['default_photo'],
];
})->toArray();
$return['property_list'] = $propertyList;
$return['user'] = [
'name' => $user['name'],
'surname' => $user['surname'],
'language' => $user['language']
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function refreshToken(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$token = $request->header('authToken');
$credentials = JWT::decode($token, Config::get('app.jwt.secret'), ['HS256']);
$rememberMe = $credentials->remember_me ;
$userId = $request->credentials->user_id;
$findTokenCriteria = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => md5($token) ],
['field' => 'expire_date', 'condition' => '>', 'value' => time() ],
['field' => 'user_id', 'condition' => '=', 'value' => $userId ],
['field' => 'invalidate', 'condition' => '=', 'value' => 0 ],
],
'firstRow' => 1
];
$getTokenData = $this->apiAccessTokenService->select($findTokenCriteria);
if(!$getTokenData['data']){
throw new ApiErrorException(lang('Token data not found'));
}
$getTokenData = $getTokenData['data'];
$jwtToken = $this->jwtService->jwtCreate(['user_id' => $userId, 'remember_me' => $rememberMe, 'day_counter' => 0.5]);
if ($jwtToken['status'] != 'success') {
throw new ApiErrorException(lang('An unknown error occurred.'));
}
$jwtToken = $jwtToken['data'];
$updateToken = [
"token" => md5(fillOnUndefined($jwtToken, "token")),
"expire_date" => fillOnUndefined($jwtToken, "exp"),
"updated_at" => time(),
];
$updateTokenTo = $this->apiAccessTokenService->update($getTokenData['id'], $updateToken);
if ($updateTokenTo['status'] != 'success') {
throw new ApiErrorException(lang('General error'));
}
$return = [
'token' => $jwtToken['token'],
'expire_time' => $updateTokenTo['data']['expire_time']
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function logOut(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$token = $request->header('authToken');
$userId = $request->credentials->user_id;
$findTokenCriteria = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => md5($token)],
['field' => 'expire_date', 'condition' => '>', 'value' => time()],
['field' => 'user_id', 'condition' => '=', 'value' => $userId],
['field' => 'invalidate', 'condition' => '=', 'value' => 0 ],
],
'firstRow' => 1
];
$getTokenData = $this->apiAccessTokenService->select($findTokenCriteria);
if(!$getTokenData['data']){
throw new ApiErrorException(lang('Token data not found.'));
}
$getTokenData = $getTokenData['data'];
$updateToken = [
"updated_at" => time(),
"invalidate" => 1 ,
];
$updateTokenTo = $this->apiAccessTokenService->update($getTokenData['id'], $updateToken);
if ($updateTokenTo['status'] != 'success') {
throw new ApiErrorException(lang('An unknown error occurred.'));
}
/*$userUpdateStatus = User::where('id', $userId)->where('status', 1)
->update(['onesignal_key' => null]);
if ($userUpdateStatus !== 1) {
throw new ApiErrorException(lang('Onesignal Key Update Error'));
}*/
$response = ['status' => 1, 'statusCode' => 200, 'message' => 'Logged out.', 'data' => []];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,109 @@
<?php
namespace App\Http\Controllers\BookingEngine\V1;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
Abstract class BookingEngineBaseController
{
protected $cachePrefix = 'enwAPISearch:';
protected $cacheExpireTime = 30;
public function __construct()
{
}
public function setCacheDataWithSearchKey($searchKey, $dataArray)
{
$searchKeyPrefix = $this->cachePrefix . $searchKey;
Cache::put($searchKeyPrefix, $dataArray, $this->cacheExpireTime * 60);//5 min, 300 ttl, 600 10 dk
if (Cache::has($searchKeyPrefix)) {
return true;
} else {
return false;
}
}
public function getCacheDataWithSearchKey($searchKey)
{
$cacheData = [];
$searchKeyPrefix = $this->cachePrefix . $searchKey;
if (Cache::has($searchKeyPrefix)) {
$cacheData = Cache::get($searchKeyPrefix);
}
return $cacheData;
}
public function rateKeyCodeDecode($rateKeyCode)
{
$rateKeyCodeExplode = explode('-', $rateKeyCode);
$data = [
'propertyId' => $rateKeyCodeExplode[0],
'channelId' => $rateKeyCodeExplode[1],
'availabilityTypeId' => $rateKeyCodeExplode[2],
'roomId' => $rateKeyCodeExplode[3],
'rateMappingId' => $rateKeyCodeExplode[4],
'roomOccupancyCode' => $rateKeyCodeExplode[5],
'checkInDate' => Carbon::parse($rateKeyCodeExplode[6])->format('Y-m-d'),
'checkOutDate' => Carbon::parse($rateKeyCodeExplode[7])->format('Y-m-d'),
'cancellationPolicyId' => $rateKeyCodeExplode[8],
'paymentTypeId' => $rateKeyCodeExplode[9],
];
return $data;
}
public function getDateByDay($dates = [])
{
$dateByDay = [];
$diffInDays = Carbon::parse($dates['checkIn'])->floatDiffInDays(Carbon::parse($dates['checkOut']));
for ($i = 0; $i < $diffInDays; $i++) {
$dateByDay[] = Carbon::parse($dates['checkIn'])->addDay($i)->format('Y-m-d');
}
return $dateByDay;
}
public function getRoomsByOccupancies($rooms = [])
{
$roomsByOccupancies = [];
foreach ($rooms as $roomOrder => $room) {
$roomKey = [];
$roomKey[] = str_repeat('A', $room['adults']);
if ($room['children'] > 0) {
foreach ($room['age'] as $childAge) {
$roomKey[] = 'C' . $childAge;
}
}
$roomKey = implode($roomKey, '');
$roomsByOccupancies[$roomKey]['rooms'][] = $roomOrder;
$roomsByOccupancies[$roomKey]['roomCount'] = count($roomsByOccupancies[$roomKey]['rooms']);
$roomsByOccupancies[$roomKey]['occupancy'] = intval($room['adults'] + $room['children']);
$roomsByOccupancies[$roomKey]['adultCount'] = $room['adults'];
$roomsByOccupancies[$roomKey]['childCount'] = $room['children'];
$roomsByOccupancies[$roomKey]['childAges'] = fillOnUndefined($room, 'age', []);
$roomsByOccupancies[$roomKey]['occupancyCode'] = str_repeat('A', $room['adults']) . str_repeat('C', $room['children']);
}
return $roomsByOccupancies;
}
}

View File

@@ -0,0 +1,489 @@
<?php
namespace App\Http\Controllers\BookingEngine\V1;
use App\Core\Service\BookingService;
use App\Core\Service\BookingRoomService;
use App\Core\Service\BookingRoomPaxService;
use App\Core\Service\BookingContactService;
use App\Core\Service\BookingPaymentService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyPaymentService;
use App\Core\Service\NewBookingMailService;
use App\Core\Service\PropertyService;
use App\Core\Service\LanguageService;
use App\Core\Service\ManualPaymentMailService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use phpDocumentor\Reflection\Types\Collection;
class PaymentLinkController extends BookingEngineBaseController
{
private $request;
private $newBookingMailService;
private $propertyPaymentService;
private $propertyService;
private $languageService;
private $manualPaymentMailService;
public function __construct(
Request $request,
PropertyPaymentService $propertyPaymentService,
PropertyService $propertyService,
LanguageService $languageService,
ManualPaymentMailService $manualPaymentMailService,
PropertyChannelMappingService $propertyChannelMappingService
)
{
$this->request = $request;
$this->propertyPaymentService = $propertyPaymentService;
$this->propertyService = $propertyService;
$this->languageService = $languageService;
$this->manualPaymentMailService = $manualPaymentMailService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
}
public function paymentLinkDetail(Request $request, $orderCode)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$paymentDetailParam = [
'criteria' => [
['field' => 'order_id', 'condition' => '=', 'value' => $orderCode],
['field' => 'transaction_type', 'condition' => '=', 'value' => 'LNK'],
['field' => 'status', 'condition' => '=', 'value' => 5],
],
'with' => ['relatedTransactions', 'paymentTypeMapping.paymentType'],
'firstRow' => true
];
$paymentDetail = $this->propertyPaymentService->selectPaymentTransaction($paymentDetailParam);
if ($paymentDetail['status'] != 'success' || empty($paymentDetail['data'])) {
throw new ApiErrorException(lang('Payment not found'));
}
$paymentDetail = $paymentDetail['data'];
if ($paymentDetail['status'] != 5) {
throw new ApiErrorException(lang('Payment not link status'));
}
$paymentDetail['is_payed'] = false;
if (!empty($paymentDetail['related_transactions'])) {
$relatedTransactions = collect($paymentDetail['related_transactions']);
if ($relatedTransactions->where('status', 1)->count() > 0) {
$paymentDetail['is_payed'] = true;
}
}
$propertyId = $paymentDetail['property_id'];
$propertyParam = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $propertyId],
],
'with' => ['propertyBrand', 'propertyContact'],
'firstRow' => true
];
$getProperty = $this->propertyService->select($propertyParam);
if ($getProperty['status'] != "success") {
throw new ApiErrorException($getProperty['message']);
}
$property = $getProperty['data'];
$property['property_brand']['logo_url'] = $property['property_brand'] ? Config::get('app.imageUrl') . '/property-photos/' . $property['id'] . "/logo/" . $property['property_brand']['logo_name'] . '_250x250.' . $property['property_brand']['logo_file_ext'] : null;
$property['property_contact']['social_media_addresses'] = json_decode($property['property_contact']['social_media_addresses'], 1);
$availableLanguageRequest = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'is_application', 'condition' => '=', 'value' => 1],
['field' => 'is_published', 'condition' => '=', 'value' => 1]
],
];
$availableLanguages = $this->languageService->select($availableLanguageRequest, ['code', 'name', 'language_key']);
$availableLanguages = Collect($availableLanguages['data'])->keyBy('code')->all();
//contract_file
$property['contract_file'] = null;
$channelMappingRequest = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $property['id']],
['field' => 'channel_id', 'condition' => '=', 'value' => 1],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$channelMapping = $this->propertyChannelMappingService->select($channelMappingRequest, ['id', 'contract_file', 'currency_code']);
if ($channelMapping['status'] == 'success' && !empty($channelMapping['data'])) {
$property['contract_file'] = Config::get('app.propertyFilesUrl') . $channelMapping['data']['contract_file'];
}
//contract_file
$responseData = [
'payment_detail' => $paymentDetail,
'property_detail' => $property,
'available_languages' => $availableLanguages,
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function paymentLinkInitialize(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(), 1);
$orderCode = $params['orderCode'];
$paymentDetailParam = [
'criteria' => [
['field' => 'order_id', 'condition' => '=', 'value' => $orderCode],
['field' => 'transaction_type', 'condition' => '=', 'value' => 'LNK'],
['field' => 'status', 'condition' => '=', 'value' => 5],
],
'firstRow' => true
];
$paymentDetail = $this->propertyPaymentService->selectPaymentTransaction($paymentDetailParam);
if ($paymentDetail['status'] != 'success' || empty($paymentDetail['data'])) {
throw new ApiErrorException(lang('Payment not found'));
}
$paymentDetail = $paymentDetail['data'];
if ($paymentDetail['status'] != 5) {
throw new ApiErrorException(lang('Payment not link status'));
}
$paymentStatusCheckParam = [
'criteria' => [
['field' => 'order_id', 'condition' => '=', 'value' => $orderCode],
['field' => 'transaction_type', 'condition' => '=', 'value' => 'LNK'],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$paymentStatusCheck = $this->propertyPaymentService->selectPaymentTransaction($paymentStatusCheckParam);
if ($paymentStatusCheck['status'] == 'success' && !empty($paymentStatusCheck['data'])) {
throw new ApiErrorException(lang('Previously paid transaction'));
}
DB::beginTransaction();
$initializePaymentParam = [
'propertyId' => $paymentDetail['property_id'],
'orderId' => $paymentDetail['order_id'],
'installment' => 0,
'amount' => (double)$paymentDetail['amount'],
'currency' => $paymentDetail['currency'],
'type' => 'LNK',
'preferredPaymentTypeId' => $paymentDetail['payment_type_mapping_id'],
'responseUrl' => $params['responseUrl'],
'creditCard' => [
'name' => $params['creditCard']['cardHolder'],
'number' => $params['creditCard']['cardNumber'],
'month' => $params['creditCard']['cardExpireMonth'],
'year' => $params['creditCard']['cardExpireYear'],
'cvv' => $params['creditCard']['cardCvv'],
]
];
$initializePayment = $this->propertyPaymentService->initializePayment($initializePaymentParam);
if (!$initializePayment['status']) {
throw new ApiErrorException(lang($initializePayment['message']));
}
$responseData = [
'orderCode' => $paymentDetail['order_id'],
'paymentCode' => $initializePayment['data']['paymentCode'],
];
if (isset($initializePayment['data']['redirectUrl'])) {
$responseData['redirectUrl'] = $initializePayment['data']['redirectUrl'];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function paymentLinkConfirm(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(), 1);
$orderCode = $params['orderCode'];
$paymentCode = $params['paymentCode'];
$paymentDetailParam = [
'criteria' => [
['field' => 'order_id', 'condition' => '=', 'value' => $orderCode],
['field' => 'code', 'condition' => '=', 'value' => $paymentCode],
['field' => 'transaction_type', 'condition' => '=', 'value' => 'LNK'],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$paymentDetail = $this->propertyPaymentService->selectPaymentTransaction($paymentDetailParam);
if ($paymentDetail['status'] != 'success' || empty($paymentDetail['data'])) {
throw new ApiErrorException(lang('Payment not confirmed'));
}
$paymentDetailParam = [
'orderCode' => $orderCode,
'language_code' => isset($params['language_code']) ? $params['language_code'] : 'en'
];
$this->manualPaymentMailService->process($paymentDetailParam);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => []];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createManualPaymentForm(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$createPaymentLink = $this->propertyPaymentService->createManualPaymentForm($params);
if ($createPaymentLink['status'] != "success") {
throw new ApiErrorException($createPaymentLink['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createPaymentLink['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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createManualPayment(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
$createPaymentLink = $this->propertyPaymentService->createManualPayment($params);
if ($createPaymentLink['status'] != "success") {
throw new ApiErrorException($createPaymentLink['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createPaymentLink['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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function editManualPaymentForm(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$createPaymentLink = $this->propertyPaymentService->editManualPaymentForm($params);
if ($createPaymentLink['status'] != "success") {
throw new ApiErrorException($createPaymentLink['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createPaymentLink['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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateManualPayment(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$createPaymentLink = $this->propertyPaymentService->updateManualPayment($params);
if ($createPaymentLink['status'] != "success") {
throw new ApiErrorException($createPaymentLink['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createPaymentLink['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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getManualPayment(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$createPaymentLink = $this->propertyPaymentService->getManualPayment($params);
if ($createPaymentLink['status'] != "success") {
throw new ApiErrorException($createPaymentLink['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createPaymentLink['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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,357 @@
<?php
namespace App\Http\Controllers\BookingEngine\V1;
use App\Core\Service\CurrencyService;
use App\Core\Service\FindCountryCodeService;
use App\Core\Service\GeneralTimezoneService;
use App\Core\Service\LanguageService;
use App\Core\Service\PropertyBookingEngineService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyGroupService;
use App\Exceptions\ApiErrorException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class PropertyBookingEngineController extends Controller
{
private $propertyBookingEngineService;
private $propertyChannelMappingService;
private $languageService;
public function __construct(
PropertyBookingEngineService $propertyBookingEngineService,
LanguageService $languageService,
PropertyChannelMappingService $propertyChannelMappingService,
CurrencyService $currencyService,
PropertyGroupService $propertyGroupService,
FindCountryCodeService $findCountryCodeService,
GeneralTimezoneService $generalTimezoneService
)
{
$this->propertyBookingEngineService = $propertyBookingEngineService;
$this->languageService = $languageService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->currencyService = $currencyService;
$this->propertyGroupService = $propertyGroupService;
$this->findCountryCodeService = $findCountryCodeService;
$this->generalTimezoneService = $generalTimezoneService;
}
public function checkProperty(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $request->params;
$propertyRequest = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => $params['token']],
],
'with' => ['channel',
'property.propertyBookingEngineGroupMapping.propertyGroup.propertyGroupMapping.property.propertyBookingEngineToken',
'property.propertyBookingEngineGroupMapping.propertyGroup.propertyGroupMapping.property.propertyWeb',
'propertyWeb', 'propertyChannelMapping.channelTax', 'propertyWebComponent',
'property.propertyAdditionalInfos'
],
'firstRow' => 1
];
$propertyBookingEngine = $this->propertyBookingEngineService->select($propertyRequest, ['id', 'property_id', 'channel_id', 'token', 'parameters']);
if ($propertyBookingEngine['status'] != 'success') {
throw new ApiErrorException($propertyBookingEngine['message']);
}
if (!$propertyBookingEngine['data']) {
throw new ApiErrorException('General error ...');
}
$propertyBookingEngine = $propertyBookingEngine['data'];
$availableLanguageRequest = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'is_application', 'condition' => '=', 'value' => 1],
['field' => 'is_published', 'condition' => '=', 'value' => 1]
]
];
$availableLanguages = $this->languageService->select($availableLanguageRequest, ['code', 'name', 'language_key']);
$languageCodes = [];
foreach ($availableLanguages['data'] as $language) {
$languageCodes[$language['code']] = $language;
}
$properBookingEngineMapping = [];
if (isset($propertyBookingEngine['parametersArray']['property_group_id'])) {
$propertyGroupRequest = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'type', 'condition' => '=', 'value' => 'BEN'],
['field' => 'id', 'condition' => '=', 'value' => $propertyBookingEngine['parametersArray']['property_group_id']]
],
'with' => ['propertyGroupMapping'],
'firstRow' => true,
];
$propertyGroup = $this->propertyGroupService->select($propertyGroupRequest);
$propertyGroup = $propertyGroup['status'] == 'success' && !empty($propertyGroup['data']) ? $propertyGroup['data']['property_group_mapping'] : [];
$propertyGroupPropertyIds = collect($propertyGroup)->pluck('property_id')->toArray();
$propertyGroupBookingEngineRequest = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'channel_id', 'condition' => '=', 'value' => $propertyBookingEngine['channel_id']],
],
'with' => ['property.propertyBookingEngineGroupMapping.propertyGroup.propertyGroupMapping.property.propertyBookingEngineToken'],
'whereIn' => [
['field' => 'property_id', 'value' => $propertyGroupPropertyIds]
]
];
$propertyGroupBookingEngine = $this->propertyBookingEngineService->select($propertyGroupBookingEngineRequest);
if ($propertyGroupBookingEngine['status'] == 'success') {
foreach ($propertyGroupBookingEngine['data'] as $bookingEngine) {
$properBookingEngineMapping[] = [
'property_id' => $bookingEngine['property_id'],
'name' => $bookingEngine['property']['name'],
'token' => $bookingEngine['token'],
'order_number' => count($properBookingEngineMapping)
];
}
}
}
if ($propertyBookingEngine['channel_id'] == 1) {
$propertyBookingEngineGroupMapping = $propertyBookingEngine['property']['property_booking_engine_group_mapping'];
foreach ($propertyBookingEngineGroupMapping as $beGroupMapping) {
$group = $beGroupMapping['property_group'];
if ($group['type'] == 'MYW') {
$groupProperties = $group['property_group_mapping'];
foreach ($groupProperties as $groupProperty) {
if (isset($groupProperty['property']['property_booking_engine_token'])) {
$arrayItem = [
'property_id' => $groupProperty['property_id'],
'name' => $groupProperty['property']['name'],
'token' => $groupProperty['property']['property_booking_engine_token']['token'],
'order_number' => $groupProperty['order_number']
];
$arrayItem['web'] = null;
if (!empty($groupProperty['property']['property_web'])) {
if ($groupProperty['property']['property_web']['status'] && $groupProperty['property']['property_web']['is_published']) {
$arrayItem['web'] = $groupProperty['property']['property_web']['webProtocolUrl'];
}
}
$properBookingEngineMapping[] = $arrayItem;
}
}
}
}
}
if (count($properBookingEngineMapping) > 1) {
array_multisort(array_column($properBookingEngineMapping, 'order_number'), SORT_ASC, $properBookingEngineMapping);
}
$channelMappingRequest = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyBookingEngine['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $propertyBookingEngine['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$channelMapping = $this->propertyChannelMappingService->select($channelMappingRequest, ['id', 'contract_file', 'currency_code']);
if ($channelMapping['status'] != 'success') {
throw new ApiErrorException($channelMapping['message']);
}
$channelDefaultCurrencyCode = $channelMapping['data']['currency_code'];
//IP Bases Pricing Channel Manipulation
if (isset($params['ipAddress']) && !empty($params['ipAddress']) && fillOnUndefined($params, 'referrer') != 'google') {
// Find Country Code with IP
$ipResponse = $this->findCountryCodeService->findCountryWithIpAddress($params['ipAddress']);
if ($ipResponse['status'] == 'success') {
$propertyChannelMappingParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyBookingEngine['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel'],
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingParam);
$ipCountryCode = isset($ipResponse['data']['code']) ? $ipResponse['data']['code'] : 'tr';
if ($propertyChannelMapping['status'] == 'success') {
$propertyChannelMappingCollect = collect($propertyChannelMapping['data']);
$countryChannel = $propertyChannelMappingCollect
->where('channel.channel_category_id', 3)
->where('channel.country_code', $ipCountryCode)
->where('channel.parent_id', 1)
->first();
if (!empty($countryChannel)) {
$channelDefaultCurrencyCode = $countryChannel['currency_code'];
}
//countryCodeGroup
if (empty($countryChannel)) {
$countryChannelGroup = $propertyChannelMappingCollect
->where('channel.channel_category_id', 3)
->where('channel.country_code', 'group')
->where('channel.parent_id', 1)
->toArray();
if (!empty($countryChannelGroup)) {
foreach ($countryChannelGroup as $country) {
if (!empty($country['channel']['country_code_group'])) {
if (in_array($ipCountryCode, $country['channel']['countryCodeGroupArray'])) {
$channelDefaultCurrencyCode = $country['currency_code'];
break;
}
}
}
}
}
//countryCodeGroup
}
}
//channelToken Manipulation
}
$exchangeCurrencyRates = $this->currencyService->exchangeCurrencyRates($channelDefaultCurrencyCode);
$exchangeCurrencyRateList = [];
$exchangeCurrencyAvailable = ['EUR', 'USD', 'TRY', 'GBP', 'GEL', 'MAD', 'AZN'];
if ($exchangeCurrencyRates['status'] == 'success') {
foreach ($exchangeCurrencyRates['data'] as $currencyRate) {
if (!in_array($currencyRate['exc_currency_code'], $exchangeCurrencyAvailable)) {
continue;
}
$currencyKey = $currencyRate['currency_code'] . '-' . $currencyRate['exc_currency_code'];
$exchangeCurrencyRateList[$currencyKey] = [
'currency_code' => $currencyRate['currency_code'],
'exc_currency_code' => $currencyRate['exc_currency_code'],
'rate' => moneyFourFormatDecimal($currencyRate['rate']),
];
}
}
$contractFileUrl = NULL;
if (!empty($channelMapping['data']['contract_file'])) {
$contractFileUrl = Config::get('app.propertyFilesUrl') . $channelMapping['data']['contract_file'];
}
$channelTax = null;
$taxOptions = Config::get('app.taxOptions');
if (!empty($propertyBookingEngine['property_channel_mapping']['channel_tax_id'])) {
$channelTax = [
'id' => $propertyBookingEngine['property_channel_mapping']['channel_tax']['id'],
'code' => $propertyBookingEngine['property_channel_mapping']['channel_tax']['code'],
'name' => $propertyBookingEngine['property_channel_mapping']['channel_tax']['name'],
'language_key' => $propertyBookingEngine['property_channel_mapping']['channel_tax']['language_key'],
'tax' => isset($taxOptions[$propertyBookingEngine['property']['country']]) ? $taxOptions[$propertyBookingEngine['property']['country']] : null
];
}
//PropertyWebComponent
$propertyWebComponent = null;
if ($propertyBookingEngine['property_web_component']) {
$propertyWebComponentSojernBookingEngine = collect($propertyBookingEngine['property_web_component'])
->where('component_id', 10)
->first();
if ($propertyWebComponentSojernBookingEngine) {
$propertyWebComponent['sojernbookingengine'] = $propertyWebComponentSojernBookingEngine['parameterArray'];
}
$propertyWebComponentClarityBookingEngine = collect($propertyBookingEngine['property_web_component'])
->where('component_id', 14)
->first();
if ($propertyWebComponentClarityBookingEngine) {
$propertyWebComponent['claritybookingengine'] = $propertyWebComponentClarityBookingEngine['parameterArray'];
}
}
$propertyTimeZoneDetail = null;
$timeZoneValue = collect($propertyBookingEngine['property']['property_additional_infos'])->where('additional_info_key_id', '13')->first();
if ($timeZoneValue) {
$generalTimezoneRepositoryCriteria = ['criteria' => [['field' => 'id', 'condition' => '=', 'value' => $timeZoneValue['value']],], 'firstRow' => true];
$propertyTimeZoneDetail = $this->generalTimezoneService->select($generalTimezoneRepositoryCriteria, ['location', 'action_type', 'hour', 'minute']);
if ($propertyTimeZoneDetail['status'] == 'success') {
$propertyTimeZoneDetail = $propertyTimeZoneDetail['data'];
}
}
$responseData = [
'property_id' => $propertyBookingEngine['property_id'],
'property_name' => $propertyBookingEngine['property']['name'],
'channel_id' => $propertyBookingEngine['channel_id'],
'channel_name' => $propertyBookingEngine['channel']['name'],
'channel_category_id' => $propertyBookingEngine['channel']['channel_category_id'],
'booking_engine_token' => $propertyBookingEngine['token'],
'channel_token' => $propertyBookingEngine['channel']['token'],
'channel_contact' => $propertyBookingEngine['channel']['contact'],
'default_language' => isset($propertyBookingEngine['property_web']['default_language']) ? $propertyBookingEngine['property_web']['default_language'] : null,
'default_currency' => $channelDefaultCurrencyCode,
'available_language_codes' => $languageCodes,
'property_booking_engine_mapping' => count($properBookingEngineMapping) > 0 ? $properBookingEngineMapping : null,
'contract_file_url' => $contractFileUrl,
'exchange_currency_rate' => $exchangeCurrencyRateList,
'booking_engine_parameters' => $propertyBookingEngine['parametersArray'],
'channel_tax' => $channelTax,
'property_web_component' => $propertyWebComponent,
'property_timezone' => $propertyTimeZoneDetail
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,488 @@
<?php
namespace App\Http\Controllers\ChannelManager\Athena\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class AthenaController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = 'athena';
$this->password = 'AU3EUmA9LChTzAzv';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadJson = json_decode($payload, 1);
$this->param = $payloadJson;
$this->channelId = 1;
$this->channelManagerId = 5; //Athena
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['update-room-availability', 'update-room-rate'];
$this->channelManagerLogId = null;
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($payloadJson),
'response' => null,
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
//['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$response = [];
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
if($roomRate['status'] == 0) {
continue;
}
if(empty($roomRate['property_room_rate_mapping'])) {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'capacity' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'capacity_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
];
}
$roomKey = 0;
$response['rooms'] = [];
foreach ($roomRates as $roomId => $roomRate) {
$response['rooms'][$roomKey] = [
'id' => $roomId,
'room_name' => $roomRate['room']['name'],
];
$roomRateKey = 0;
$response['rooms'][$roomKey]['rates'] = [];
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$response['rooms'][$roomKey]['rates'][$roomRateKey] = [
'id' => $roomRateMappingId,
'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
'board_id' => $rateData['accommodationId'],
'board_name' => $rateData['name'],
];
$roomRateKey++;
}
$roomKey++;
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function channel(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$propertyChannelCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['parentChannel','propertyChannelCategory'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
];
$propertyChannel = $this->propertyChannelService->select($propertyChannelCriteria);
if (!$propertyChannel['status']) {
throw new ApiErrorException($propertyChannel['message']);
}
$propertyChannel = $propertyChannel['data'];
$response = [];
$response['channels'] = [];
foreach ($propertyChannel as $channel) {
$response['channels'][] = [
'id' => $channel['id'],
'name' => $channel['name'],
'category_id' => $channel['property_channel_category']['id'],
'category_name' => $channel['property_channel_category']['name'],
];
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

View File

@@ -0,0 +1,228 @@
<?php
namespace App\Http\Controllers\ChannelManager\Channex\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Core\Mail\ChannelManagerNotificationMail;
use App\Core\Service\ChannelManager\Channex;
use App;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class ChannexController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
Channex $channexService,
Mailer $mailer
)
{
$this->username = 'channex';
$this->password = 'AU3EUmA9LChTzAzv';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->mailer = $mailer;
$this->channexService = $channexService;
$payloadJson = $this->request->all();
$this->param = $payloadJson;
Log::debug($payloadJson);
$this->channelManagerId = 2; //Channex
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function channelManagerProperty($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'with' => ['property'],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property mapping not found');
}
$response = [
'status' => true,
'data' => $channelManagerPropertyMapping['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 notification(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['property_id'];
$propertyChannelMapping = $this->channelManagerProperty($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$channelDetails = $this->channexService->getChannelDetails($this->param['payload']['channel_id']);
if (!$channelDetails['status']) {
throw new ApiErrorException($channelDetails['message']);
}
$channelDetails = $channelDetails['data'];
$mailParams = [
'propertyId' => $propertyChannelMapping['property']['id'],
'propertyName' => $propertyChannelMapping['property']['name'],
'channelName' => $channelDetails['attributes']['channel']
];
$this->mailer->onQueue('channelManagerNotificationMail', new ChannelManagerNotificationMail($mailParams));
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

View File

@@ -0,0 +1,893 @@
<?php
namespace App\Http\Controllers\ChannelManager\ElektraWeb\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class ElektraWebController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
private $channelManagerRequestTime;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = 'elektraweb';
$this->password = 'XGgK2BSYCERDaVAx';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadJson = json_decode($payload, 1);
$this->param = $payloadJson;
$this->channelId = 1;
$this->channelManagerId = 4; //ElektraWeb
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['update-room-availability', 'update-room-rate'];
$this->channelManagerLogId = null;
$this->channelManagerRequestTime = microtime(true);
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($payloadJson),
'ip_address' => $this->request->ip(),
'response' => null,
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$getChannelPropertyRoomRate['data'] = collect($getChannelPropertyRoomRate['data'])->where('property_room_rate_mapping.property_room.status',1)->toArray();
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
//TODO: burada otelinde kendisine bakmak lazım status
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$response = [];
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'max_adult' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'max_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
'max_occupancy' => $roomRate['property_room_rate_mapping']['property_room']['max_occupancy'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
'included_occupancy' => $roomRate['property_room_rate_mapping']['included_occupancy'],
];
}
$roomKey = 0;
$response['rooms'] = [];
foreach ($roomRates as $roomId => $roomRate) {
$response['rooms'][$roomKey] = [
'id' => $roomId,
'room_name' => $roomRate['room']['name'],
'max_adult' => $roomRate['room']['max_adult'],
'max_child' => $roomRate['room']['max_child'],
'max_occupancy' => $roomRate['room']['max_occupancy'],
];
$roomRateKey = 0;
$response['rooms'][$roomKey]['rates'] = [];
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$response['rooms'][$roomKey]['rates'][$roomRateKey] = [
'id' => $roomRateMappingId,
'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
'board_id' => $rateData['accommodationId'],
'board_name' => $rateData['name'],
'included_occupancy' => floor($rateData['included_occupancy']),
];
$roomRateKey++;
}
$roomKey++;
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomAvailability(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomAvailabilities = $this->param['rooms'];
// Merge consecutive dates with same availability and stop_sell
usort($roomAvailabilities, function ($a, $b) {
if ($a['room_id'] === $b['room_id']) {
return strcmp($a['start_date'], $b['start_date']);
}
return $a['room_id'] <=> $b['room_id'];
});
$mergedAvailabilities = [];
$currentAvailability = null;
foreach ($roomAvailabilities as $availability) {
if ($currentAvailability === null) {
$currentAvailability = $availability;
continue;
}
$currentEnd = Carbon::parse($currentAvailability['end_date']);
$nextStart = Carbon::parse($availability['start_date']);
$isConsecutive = $currentEnd->addDay()->toDateString() === $nextStart->toDateString();
$sameRoomId = ($currentAvailability['room_id'] === $availability['room_id']);
$sameAvailability = (isset($currentAvailability['availability']) && isset($availability['availability']) && $currentAvailability['availability'] === $availability['availability']) || (!isset($currentAvailability['availability']) && !isset($availability['availability']));
$sameStopSell = (isset($currentAvailability['stop_sell']) && isset($availability['stop_sell']) && $currentAvailability['stop_sell'] === $availability['stop_sell']) || (!isset($currentAvailability['stop_sell']) && !isset($availability['stop_sell']));
if ($isConsecutive && $sameRoomId && $sameAvailability && $sameStopSell) {
$currentAvailability['end_date'] = $availability['end_date'];
} else {
$mergedAvailabilities[] = $currentAvailability;
$currentAvailability = $availability;
}
}
if ($currentAvailability !== null) {
$mergedAvailabilities[] = $currentAvailability;
}
$roomAvailabilities = $mergedAvailabilities;
$roomAvailabilitiesCollect = collect($roomAvailabilities);
DB::beginTransaction();
$startDate = $roomAvailabilitiesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomAvailabilitiesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($roomAvailabilities as $availability) {
$roomId = $availability['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$totalInventoryAvailable = null;
if (isset($availability['availability'])) {
$totalInventoryAvailable = $availability['availability'];
}
$startDate = Carbon::parse($availability['start_date'])->toDateString();
$endDate = Carbon::parse($availability['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
if (isset($availability['stop_sell']) && !is_null($availability['stop_sell'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'room_stop_sell';
$requestParams['value'] = $availability['stop_sell'];
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomRates = $this->param['rooms'];
$roomRatesCollect = collect($roomRates);
$paramsListChannel = [];
$paramsListChannel[] = $this->channelId;
//CONNECTED CHANNEL RATE UPDATE
/*$propertyChannelMappingConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'channel_id', 'condition' => '=', 'value' => 5],//JUST CM
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel']
];
$propertyChannelMappingConnected = $this->propertyChannelMappingService->select($propertyChannelMappingConnectedCriteria);
if ($propertyChannelMappingConnected['status'] == 'success') {
foreach ($propertyChannelMappingConnected['data'] as $channel) {
if (!is_null($channel['channel']['parent_id'])) {
continue;
}
$paramsListChannel[] = $channel['channel_id'];
}
}*/
//CONNECTED CHANNEL RATE UPDATE
DB::beginTransaction();
foreach ($roomRates as $roomRate) {
$roomId = $roomRate['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
//throw new ApiErrorException('Undefined or inactive room accommodation');
continue;
}
$rates = $roomRate['rates'];
if (empty($rates)) {
continue;
}
// Sort by rate_id and then start_date to ensure we process them in order for each rate_id
usort($rates, function ($a, $b) {
if ($a['rate_id'] === $b['rate_id']) {
return strcmp($a['start_date'], $b['start_date']);
}
return strcmp($a['rate_id'], $b['rate_id']);
});
$mergedRates = [];
$currentRate = null;
foreach ($rates as $rate) {
if ($currentRate === null) {
$currentRate = $rate;
continue;
}
$currentEnd = Carbon::parse($currentRate['end_date']);
$nextStart = Carbon::parse($rate['start_date']);
$isConsecutive = $currentEnd->addDay()->toDateString() === $nextStart->toDateString();
$sameRateId = ($currentRate['rate_id'] === $rate['rate_id']);
$sameAmount = (isset($currentRate['amount']) && isset($rate['amount']) && (float)$currentRate['amount'] === (float)$rate['amount']) || (!isset($currentRate['amount']) && !isset($rate['amount']));
$sameStopSell = (isset($currentRate['stop_sell']) && isset($rate['stop_sell']) && $currentRate['stop_sell'] === $rate['stop_sell']) || (!isset($currentRate['stop_sell']) && !isset($rate['stop_sell']));
$sameMinStay = (isset($currentRate['min_stay']) && isset($rate['min_stay']) && $currentRate['min_stay'] === $rate['min_stay']) || (!isset($currentRate['min_stay']) && !isset($rate['min_stay']));
if ($isConsecutive && $sameRateId && $sameAmount && $sameStopSell && $sameMinStay) {
$currentRate['end_date'] = $rate['end_date'];
} else {
$mergedRates[] = $currentRate;
$currentRate = $rate;
}
}
if ($currentRate !== null) {
$mergedRates[] = $currentRate;
}
$roomRatesCollect = collect($mergedRates);
$startDate = $roomRatesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomRatesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($mergedRates as $rate) {
$startDate = Carbon::parse($rate['start_date'])->toDateString();
$endDate = Carbon::parse($rate['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
$roomRateMappingId = $rate['rate_id'];
$isCloseRoomRateMappingSale = null;
if (isset($rate['stop_sell'])) {
$isCloseRoomRateMappingSale = $rate['stop_sell'] == 1 ? true : false;
}
$channelRoomRateMappingCheck = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->isEmpty();
if ($channelRoomRateMappingCheck) {
//throw new ApiErrorException('Undefined or inactive room accommodation');
continue;
}
$roomRates = [];
$roomRates[] = [
'room_id' => $roomId,
'room_rate_mapping_id' => [
$roomRateMappingId
]
];
foreach ($paramsListChannel as $paramChannelId) {
//Eğer Rate var ise currency check yapılmalı ve PerDay var mı check edilmeli, burada sonra günceleme yaptırılabilri
if (isset($rate['amount'])) {
$currency = $this->param['currency'];
$currencyCheck = ($currency == $propertyChannelMapping['currency_code']) ? true : false;
if (!$currencyCheck) {
throw new ApiErrorException('Exchange rate that does not match the channel exchange rate, channel exchange rate: ' . $propertyChannelMapping['currency_code']);
}
$channelRoomRateMapping = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->first();
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate';
$requestParams['value'] = $rate['amount'];
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$requestParams['ip_address'] = $this->request->ip();
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Room Rate Stop Sale
if (!is_null($isCloseRoomRateMappingSale)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate_stop_sell';
$requestParams['value'] = $isCloseRoomRateMappingSale ? 1 : 0;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$requestParams['ip_address'] = $this->request->ip();
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Kısıtlamalar var ise min los
if (isset($rate['min_stay'])) {
//Minimum Konaklama Gün Sayısı
if (isset($rate['min_stay'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'min_stay';
$requestParams['value'] = $rate['min_stay'];
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$requestParams['ip_address'] = $this->request->ip();
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

View File

@@ -0,0 +1,809 @@
<?php
namespace App\Http\Controllers\ChannelManager\ElektraWeb\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class ElektraWebController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
private $channelManagerRequestTime;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = 'elektraweb';
$this->password = 'XGgK2BSYCERDaVAx';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadJson = json_decode($payload, 1);
$this->param = $payloadJson;
$this->channelId = 1;
$this->channelManagerId = 4; //ElektraWeb
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['update-room-availability', 'update-room-rate'];
$this->channelManagerLogId = null;
$this->channelManagerRequestTime = microtime(true);
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($payloadJson),
'ip_address' => $this->request->ip(),
'response' => null,
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$getChannelPropertyRoomRate['data'] = collect($getChannelPropertyRoomRate['data'])->where('property_room_rate_mapping.property_room.status',1)->toArray();
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
//TODO: burada otelinde kendisine bakmak lazım status
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$response = [];
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'max_adult' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'max_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
'max_occupancy' => $roomRate['property_room_rate_mapping']['property_room']['max_occupancy'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
'included_occupancy' => $roomRate['property_room_rate_mapping']['included_occupancy'],
];
}
$roomKey = 0;
$response['rooms'] = [];
foreach ($roomRates as $roomId => $roomRate) {
$response['rooms'][$roomKey] = [
'id' => $roomId,
'room_name' => $roomRate['room']['name'],
'max_adult' => $roomRate['room']['max_adult'],
'max_child' => $roomRate['room']['max_child'],
'max_occupancy' => $roomRate['room']['max_occupancy'],
];
$roomRateKey = 0;
$response['rooms'][$roomKey]['rates'] = [];
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$response['rooms'][$roomKey]['rates'][$roomRateKey] = [
'id' => $roomRateMappingId,
'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
'board_id' => $rateData['accommodationId'],
'board_name' => $rateData['name'],
'included_occupancy' => floor($rateData['included_occupancy']),
];
$roomRateKey++;
}
$roomKey++;
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomAvailability(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomAvailabilities = $this->param['rooms'];
$roomAvailabilitiesCollect = collect($roomAvailabilities);
DB::beginTransaction();
$startDate = $roomAvailabilitiesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomAvailabilitiesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($roomAvailabilities as $availability) {
$roomId = $availability['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$totalInventoryAvailable = null;
if (isset($availability['availability'])) {
$totalInventoryAvailable = $availability['availability'];
}
$startDate = Carbon::parse($availability['start_date'])->toDateString();
$endDate = Carbon::parse($availability['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
if (isset($availability['stop_sell']) && !is_null($availability['stop_sell'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'room_stop_sell';
$requestParams['value'] = $availability['stop_sell'];
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomRates = $this->param['rooms'];
$roomRatesCollect = collect($roomRates);
$paramsListChannel = [];
$paramsListChannel[] = $this->channelId;
//CONNECTED CHANNEL RATE UPDATE
/*$propertyChannelMappingConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'channel_id', 'condition' => '=', 'value' => 5],//JUST CM
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel']
];
$propertyChannelMappingConnected = $this->propertyChannelMappingService->select($propertyChannelMappingConnectedCriteria);
if ($propertyChannelMappingConnected['status'] == 'success') {
foreach ($propertyChannelMappingConnected['data'] as $channel) {
if (!is_null($channel['channel']['parent_id'])) {
continue;
}
$paramsListChannel[] = $channel['channel_id'];
}
}*/
//CONNECTED CHANNEL RATE UPDATE
DB::beginTransaction();
foreach ($roomRates as $roomRate) {
$roomId = $roomRate['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
//throw new ApiErrorException('Undefined or inactive room accommodation');
continue;
}
$roomRatesCollect = collect($roomRate['rates']);
$startDate = $roomRatesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomRatesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($roomRate['rates'] as $rate) {
$startDate = Carbon::parse($rate['start_date'])->toDateString();
$endDate = Carbon::parse($rate['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
$roomRateMappingId = $rate['rate_id'];
$isCloseRoomRateMappingSale = null;
if (isset($rate['stop_sell'])) {
$isCloseRoomRateMappingSale = $rate['stop_sell'] == 1 ? true : false;
}
$channelRoomRateMappingCheck = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->isEmpty();
if ($channelRoomRateMappingCheck) {
//throw new ApiErrorException('Undefined or inactive room accommodation');
continue;
}
$roomRates = [];
$roomRates[] = [
'room_id' => $roomId,
'room_rate_mapping_id' => [
$roomRateMappingId
]
];
foreach ($paramsListChannel as $paramChannelId) {
//Eğer Rate var ise currency check yapılmalı ve PerDay var mı check edilmeli, burada sonra günceleme yaptırılabilri
if (isset($rate['amount'])) {
$currency = $this->param['currency'];
$currencyCheck = ($currency == $propertyChannelMapping['currency_code']) ? true : false;
if (!$currencyCheck) {
throw new ApiErrorException('Exchange rate that does not match the channel exchange rate, channel exchange rate: ' . $propertyChannelMapping['currency_code']);
}
$channelRoomRateMapping = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->first();
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate';
$requestParams['value'] = $rate['amount'];
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$requestParams['ip_address'] = $this->request->ip();
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Room Rate Stop Sale
if (!is_null($isCloseRoomRateMappingSale)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate_stop_sell';
$requestParams['value'] = $isCloseRoomRateMappingSale ? 1 : 0;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$requestParams['ip_address'] = $this->request->ip();
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Kısıtlamalar var ise min los
if (isset($rate['min_stay'])) {
//Minimum Konaklama Gün Sayısı
if (isset($rate['min_stay'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'min_stay';
$requestParams['value'] = $rate['min_stay'];
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$requestParams['ip_address'] = $this->request->ip();
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

View File

@@ -0,0 +1,488 @@
<?php
namespace App\Http\Controllers\ChannelManager\Fina\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class FinaController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = 'fina';
$this->password = '6T3VpfsNvLwWFY2gtXjz8y';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadJson = json_decode($payload, 1);
$this->param = $payloadJson;
$this->channelId = 1;
$this->channelManagerId = 8; //Fina
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['update-room-availability', 'update-room-rate'];
$this->channelManagerLogId = null;
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($payloadJson),
'response' => null,
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
//['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$response = [];
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
if($roomRate['status'] == 0) {
continue;
}
if(empty($roomRate['property_room_rate_mapping'])) {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'capacity' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'capacity_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
];
}
$roomKey = 0;
$response['rooms'] = [];
foreach ($roomRates as $roomId => $roomRate) {
$response['rooms'][$roomKey] = [
'id' => $roomId,
'room_name' => $roomRate['room']['name'],
];
$roomRateKey = 0;
$response['rooms'][$roomKey]['rates'] = [];
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$response['rooms'][$roomKey]['rates'][$roomRateKey] = [
'id' => $roomRateMappingId,
'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
'board_id' => $rateData['accommodationId'],
'board_name' => $rateData['name'],
];
$roomRateKey++;
}
$roomKey++;
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function channel(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$propertyChannelCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['parentChannel','propertyChannelCategory'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
];
$propertyChannel = $this->propertyChannelService->select($propertyChannelCriteria);
if (!$propertyChannel['status']) {
throw new ApiErrorException($propertyChannel['message']);
}
$propertyChannel = $propertyChannel['data'];
$response = [];
$response['channels'] = [];
foreach ($propertyChannel as $channel) {
$response['channels'][] = [
'id' => $channel['id'],
'name' => $channel['name'],
'category_id' => $channel['property_channel_category']['id'],
'category_name' => $channel['property_channel_category']['name'],
];
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

View File

@@ -0,0 +1,825 @@
<?php
namespace App\Http\Controllers\ChannelManager\HotelRunner\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class HotelRunnerController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = 'hotelrunner';
$this->password = '2otNDLCgJz9Tgdga';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadXML = simplexml_load_string($payload);
$payloadParam = json_decode(json_encode($payloadXML), 1);
$this->param = $payloadParam;
$this->channelId = 1;
$this->channelManagerId = 3; //HotelRunner
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['room-inventory-update'];
$this->channelManagerLogId = null;
$this->channelManagerRequestTime = microtime(true);
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => $payload,
'response' => null,
'ip_address' => $this->request->ip(),
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
//Authentication
$errors = [];
if ($this->username != $payloadParam['username'] || $this->password != $payloadParam['password']) {
$errors[] = [
//'code' => 100,
'message' => 'Your username or password is incorrect.'
];
}
if (!empty($errors)) {
$this->responseError($errors);
}
}
public function responseError($errors)
{
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response></response>');
$xmlResponse->addChild('status', -1);
foreach ($errors as $error) {
$xmlResponseError = $xmlResponse->addChild('message', $error['message']);
if (isset($error['code'])) {
$xmlResponseError->addAttribute('code', $error['code']);
}
}
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => $xmlResponse->asXML(),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
header('Content-type: text/xml');
echo $xmlResponse->asXML();
die();
}
public function responseSuccess($xmlPayload)
{
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => $xmlPayload->asXML(),
'status' => 1
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
header('Content-type: text/xml');
//echo $xmlPayload->asXML();
echo html_entity_decode($xmlPayload->asXML());
die();
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$getChannelPropertyRoomRate['data'] = collect($getChannelPropertyRoomRate['data'])->where('property_room_rate_mapping.property_room.status',1)->toArray();
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><rooms></rooms>');
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'capacity' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'capacity_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
'included_occupancy' => $roomRate['property_room_rate_mapping']['included_occupancy'],
];
}
foreach ($roomRates as $roomId => $roomRate) {
$room = $xmlResponse->addChild('room');
$room->addAttribute('id', $roomId);
$room->addAttribute('room_name', $roomRate['room']['name']);
$rates = $room->addChild('rates');
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$rate = $rates->addChild('rate');
$rate->addAttribute('id', $roomRateMappingId);
$rate->addAttribute('board_id', $rateData['accommodationId']);
$rate->addAttribute('rate_name', $rateData['name'] . ' - ' . $rateData['rate'].' - '. $rateData['included_occupancy'].' Person');
$rate->addAttribute('allocation_group', $roomId);
$rate->addAttribute('stop_sale_group', $roomId . ':' . $roomRateMappingId);
$rate->addAttribute('min_stay_group', $roomId . ':' . $roomRateMappingId);
$rate->addAttribute('included_occupancy', $rateData['included_occupancy']);
}
}
$this->responseSuccess($xmlResponse);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
$errors[] = [
'message' => $response['message']
];
$this->responseError($errors);
}
}
public function availabilityRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$startDate = $this->param['start_date'];
$finishDate = $this->param['end_date'];
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$requestParams = [
'property_id' => $propertyId,
'room_id' => null,
'room_rate_mapping_id' => null,
'channel_id' => $this->channelId,
'start_date' => $startDate,
'end_date' => $finishDate,
];
$propertyRoomType = $this->propertyRoomService->getPropertyRoomInventory($requestParams);
if ($propertyRoomType['status'] != 'success') {
throw new ApiErrorException($propertyRoomType['message']);
}
$propertyRoomType = $propertyRoomType['data'];
$propertyRoomRateAvailability = collect($propertyRoomType);
$roomRates = [];
foreach ($propertyRoomRateAvailability as $room) {
foreach ($room['property_room_rate_mapping'] as $roomRateMapping) {
foreach ($room['room_availability'] as $date => $roomAvailability) {
$roomRates[$room['id']]['availability'][$date] = $roomAvailability['value'];
}
$roomRates[$room['id']]['rate'][$roomRateMapping['id']] = [
'roomName' => $room['name'],
'roomRateName' => $roomRateMapping['name'],
//'minStay' => $roomRateMapping['min_stay'],
//'maxStay' => $roomRateMapping['max_stay'],
'currencyCode' => $roomRateMapping['currency_code'],
];
$roomRatePrices = reset($roomRateMapping['prices']);
foreach ($roomRatePrices['price'] as $date => $roomRatePrice) {
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['price'][$date] = $roomRatePrice['value'];
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['stopSell'][$date] = $roomRatePrice['stop_sell'];
}
foreach ($roomRatePrices['stop_sell'] as $date => $stopSell) {
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['stopSell'][$date] = $stopSell['value'];
}
foreach ($roomRatePrices['min_stay'] as $date => $minStay) {
$roomRates[$room['id']]['rate'][$roomRateMapping['id']]['minstay'][$date] = $minStay['value'];
}
}
}
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><inventories></inventories>');
$diffInDays = Carbon::parse($startDate)->diffInDays(Carbon::parse($finishDate));
if ($diffInDays > 180) {
throw new ApiErrorException('A maximum of 180 days of data can be retrieved.');
}
$currentDate = $startDate;
for ($i = 0; $i <= $diffInDays; $i++) {
foreach ($roomRates as $roomId => $roomRateMapping) {
foreach ($roomRateMapping['rate'] as $roomRateMappingId => $roomRate) {
$inventory = $xmlResponse->addChild('inventory');
$inventory->addAttribute('room_id', $roomId);
$inventory->addAttribute('rate_id', $roomRateMappingId);
$inventory->addAttribute('date', $currentDate);
$inventory->addAttribute('price', $roomRate['price'][$currentDate]);
$inventory->addAttribute('allocation', $roomRateMapping['availability'][$currentDate]);
$inventory->addAttribute('stop_sale', $roomRate['stopSell'][$currentDate] == 1 ? 1 : 0);
$inventory->addAttribute('min_stay', $roomRate['minstay'][$currentDate]);
}
}
$currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
}
$this->responseSuccess($xmlResponse);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
$errors[] = [
'message' => $response['message']
];
$this->responseError($errors);
}
}
public function availabilityRateUpdate(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$availRateUpdates = singleElementXMLArray($this->param['inventories']['inventory']);
DB::beginTransaction();
$dateRange = [];
$dateRange['startDate'] = $this->param['start_date'];
$dateRange['finishDate'] = $this->param['end_date'];
if (Carbon::parse($dateRange['startDate'])->isBefore(Carbon::now()->toDateString()) || Carbon::parse($dateRange['finishDate'])->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($availRateUpdates as $availRateUpdate) {
$roomId = $availRateUpdate['@attributes']['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$totalInventoryAvailable = null;
if (isset($availRateUpdate['@attributes']['allocation'])) {
$totalInventoryAvailable = $availRateUpdate['@attributes']['allocation'];
}
$currentDate = Carbon::parse($availRateUpdate['@attributes']['date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $currentDate,
'end_date' => $currentDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
$roomRateMappingId = $availRateUpdate['@attributes']['rate_id'];
$isCloseRoomRateMappingSale = null;
if (isset($availRateUpdate['@attributes']['stop_sale'])) {
$isCloseRoomRateMappingSale = $availRateUpdate['@attributes']['stop_sale'] == 1 ? true : false;
}
$channelRoomRateMappingCheck = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->isEmpty();
if ($channelRoomRateMappingCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$roomRates = [];
$roomRates[] = [
'room_id' => $roomId,
'room_rate_mapping_id' => [
$roomRateMappingId
]
];
$paramsListChannel = [];
$paramsListChannel[] = $this->channelId;
//CONNECTED CHANNEL RATE UPDATE
$propertyChannelMappingConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $requestParamBase['property_id']],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $requestParamBase['channel_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => 5],//JUST CM
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel']
];
$propertyChannelMappingConnected = $this->propertyChannelMappingService->select($propertyChannelMappingConnectedCriteria);
if ($propertyChannelMappingConnected['status'] == 'success') {
foreach ($propertyChannelMappingConnected['data'] as $channel) {
if (!is_null($channel['channel']['parent_id'])) {
continue;
}
$paramsListChannel[] = $channel['channel_id'];
}
}
//CONNECTED CHANNEL RATE UPDATE
foreach ($paramsListChannel as $paramChannelId) {
//Eğer Rate var ise currency check yapılmalı ve PerDay var mı check edilmeli, burada sonra günceleme yaptırılabilri
if (isset($availRateUpdate['@attributes']['price'])) {
$currency = $this->param['currency'];
$currencyCheck = ($currency == $propertyChannelMapping['currency_code']) ? true : false;
if (!$currencyCheck) {
throw new ApiErrorException('Exchange rate that does not match the channel exchange rate, channel exchange rate: ' . $propertyChannelMapping['currency_code']);
}
$channelRoomRateMapping = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->first();
$amountPerDay = $availRateUpdate['@attributes']['price'];
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate';
$requestParams['value'] = $amountPerDay;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Room Rate Stop Sale
if (!is_null($isCloseRoomRateMappingSale)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate_stop_sell';
$requestParams['value'] = $isCloseRoomRateMappingSale ? 1 : 0;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Kısıtlamalar var ise min los
if (isset($availRateUpdate['@attributes']['min_stay'])) {
//Minimum Konaklama Gün Sayısı
if (isset($availRateUpdate['@attributes']['min_stay'])) {
$minStay = $availRateUpdate['@attributes']['min_stay'];
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'min_stay';
$requestParams['value'] = $minStay;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
}
}
DB::commit();
$xmlResponse = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response></response>');
$xmlResponse->addChild('status', 0);
$xmlResponse->addChild('message', 'success');
$xmlResponse->addChild('ConfirmCode', $this->channelManagerLogId);
$this->responseSuccess($xmlResponse);
} 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();
}
DB::rollBack();
if (!$response['status']) {
$errors[] = [
'message' => $response['message']
];
$this->responseError($errors);
}
}
}

View File

@@ -0,0 +1,635 @@
<?php
namespace App\Http\Controllers\ChannelManager\HyperGuest\v1;
use App\Core\Mail\LogMail;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
class HyperGuestController
{
private $channelManagerId;
private $channelManagerName;
private $mailer;
private $userApiKey;
public function __construct(
Request $request,
Client $restClient,
Mailer $mailer,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
$this->request = $request;
$this->restClient = $restClient;
$this->mailer = $mailer;
$this->param = $this->request->all();
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
if (App::environment() == 'production') {
$this->url = 'https://pdm.hyperguest.io/api/';
$this->urlstatic = 'https://hg-static.hyperguest.com/';
$this->bearerToken = '63d51938dc3749788ac3e88ea6d58950';
} else {
$this->url = 'https://pdm.hyperguest.com/api/';
$this->urlstatic = 'https://hg-static.hyperguest.com/';
$this->bearerToken = '63d51938dc3749788ac3e88ea6d58950';
}
$this->channelId = 1;
$this->channelManagerId = 10;
$this->channelManagerName = 'HyperGuest';
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['room-inventory-update'];
$this->channelManagerLogId = null;
$this->channelManagerRequestTime = microtime(true);
if (in_array($serviceRequestName, $logArray)) {
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($this->param['propertyId']);
if ($channelManagerPropertyCheck['status']) {
$insertDataLog = [
'property_id' => $channelManagerPropertyCheck['data']['property_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($this->param),
'response' => null,
'ip_address' => $this->request->ip(),
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
}
//channelManagerLogService
}
public function request($type, $method, $jsonPayload)
{
$response = ['status' => false, 'message' => ''];
try {
$this->restClient = new Client(['http_errors' => false]);
if ($type == 'POST') {
$parameter = [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->bearerToken
]
];
if (!empty($jsonPayload)) {
$parameter['body'] = $jsonPayload;
}
$res = $this->restClient->request('POST', $this->url . $method, $parameter);
$getResponseBody = $res->getBody();
$getResponse = $getResponseBody->getContents();
$getResponse = json_decode($getResponse, 1);
} else if ($type == 'GET') {
$res = $this->restClient->request('GET', $this->url . $method,
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->bearerToken
],
'query' => $jsonPayload
]
);
$getResponseBody = $res->getBody();
$getResponse = $getResponseBody->getContents();
$getResponse = json_decode($getResponse, 1);
}
if ($res->getStatusCode() != 200) {
$errors = singleElementArray($getResponse['errors']);
$firstError = reset($errors);
throw new Exception($firstError['code'] . ': ' . $firstError['title']);
}
$response = ["status" => true, 'message' => '', "data" => fillOnUndefined($getResponse, 'data', [])];
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function responseError($errors)
{
$response = ['success' => false, 'message' => null];
$response['message'] = implode(',', $errors);
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($data = [])
{
$response = ['success' => true, 'message' => null];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'channel_manager_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'];
$response = [
'status' => true,
'data' => $channelManagerPropertyMapping
];
} 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 availabilityRateUpdate(Request $request)
{
$errors = [];
$response = ['status' => false, 'message' => ''];
try {
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($this->param['propertyId']);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelManagerPropertyCheck = $channelManagerPropertyCheck['data'];
$channelManagerPropertyRoomRateCollect = collect($channelManagerPropertyCheck['channel_manager_room_rate']);
$propertyId = $channelManagerPropertyCheck['property_id'];
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$availRateUpdates = $this->param['ARIUpdate'];
DB::beginTransaction();
/*$dateRange = [];
$dateRange['startDate'] = $this->param['start_date'];
$dateRange['finishDate'] = $this->param['end_date'];
if (Carbon::parse($dateRange['startDate'])->isBefore(Carbon::now()->toDateString()) || Carbon::parse($dateRange['finishDate'])->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}*/
foreach ($availRateUpdates as $availRateUpdate) {
$roomIdCheck = $channelManagerPropertyRoomRateCollect->where('channel_manager_room_id', $availRateUpdate['roomTypeCode'])->first();
if (empty($roomIdCheck)) {
continue;
}
$roomId = $roomIdCheck['property_room_rate_mapping']['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
continue;
}
$totalInventoryAvailable = null;
if (isset($availRateUpdate['numberOfAvailableRooms'])) {
$totalInventoryAvailable = $availRateUpdate['numberOfAvailableRooms'];
}
$currentDate = Carbon::parse($availRateUpdate['date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $currentDate,
'end_date' => $currentDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
foreach ($availRateUpdate['ratePlans'] as $ratePlan) {
$roomRateMappingIdCheck = $channelManagerPropertyRoomRateCollect->where('channel_manager_room_id', $availRateUpdate['roomTypeCode'])->where('channel_manager_room_rate_id', $ratePlan['ratePlanCode'])->first();
if (empty($roomRateMappingIdCheck)) {
continue;
}
$roomRateMappingId = $roomRateMappingIdCheck['property_room_rate_mapping_id'];
$channelRoomRateMappingCheck = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->isEmpty();
if ($channelRoomRateMappingCheck) {
continue;
}
$includedOccupancy = (int)$roomRateMappingIdCheck['included_occupancy'];
$ratePlanPrice = collect($ratePlan['prices'])->where('numberOfGuests.adults', $includedOccupancy)
->where('numberOfGuests.adults', $includedOccupancy)
->where('numberOfGuests.children', 0)
->where('numberOfGuests.infants', 0)
->first();
if (empty($ratePlanPrice)) {
continue;
}
$ratePlanPrice = $ratePlanPrice['price'];
$roomRates = [];
$roomRates[] = [
'room_id' => $roomId,
'room_rate_mapping_id' => [
$roomRateMappingId
]
];
$paramsListChannel = [];
$paramsListChannel[] = $this->channelId;
//CONNECTED CHANNEL RATE UPDATE
$propertyChannelMappingConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $requestParamBase['property_id']],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $requestParamBase['channel_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => 5],//JUST CM
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel']
];
$propertyChannelMappingConnected = $this->propertyChannelMappingService->select($propertyChannelMappingConnectedCriteria);
if ($propertyChannelMappingConnected['status'] == 'success') {
foreach ($propertyChannelMappingConnected['data'] as $channel) {
if (!is_null($channel['channel']['parent_id'])) {
continue;
}
$paramsListChannel[] = $channel['channel_id'];
}
}
//CONNECTED CHANNEL RATE UPDATE
foreach ($paramsListChannel as $paramChannelId) {
//Eğer Rate var ise currency check yapılmalı ve PerDay var mı check edilmeli, burada sonra günceleme yaptırılabilri
if (isset($ratePlanPrice)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate';
$requestParams['value'] = $ratePlanPrice;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Room Rate Stop Sale
$isCloseRoomRateMappingSale = null;
if (isset($ratePlan['isOpen'])) {
$isCloseRoomRateMappingSale = $ratePlan['isOpen'] == 1 ? false : true;
}
if (!is_null($isCloseRoomRateMappingSale)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate_stop_sell';
$requestParams['value'] = $isCloseRoomRateMappingSale ? 1 : 0;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Minimum Konaklama Gün Sayısı
if (isset($ratePlan['minLOS'])) {
$minStay = $ratePlan['minLOS'];
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'min_stay';
$requestParams['value'] = $minStay;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
}
}
DB::commit();
//$this->channelManagerLogId
return $this->responseSuccess();
} 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();
}
DB::rollBack();
if (!$response['status']) {
$errors[] = $response['message'];
return $this->responseError($errors);
}
}
}

View File

@@ -0,0 +1,640 @@
<?php
namespace App\Http\Controllers\ChannelManager\OneC\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Validator;
class OneCController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = '1CHotel';
$this->password = 'w2Dffb9EGXPZfiUDxWKZqB';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadJson = json_decode($payload, 1);
$this->param = $payloadJson;
$this->channelId = 1;
$this->channelManagerId = 9; //1C Hotels
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['update-room-availability', 'update-room-rate'];
$this->channelManagerLogId = null;
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($payloadJson),
'response' => null,
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
//['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$response = [];
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
if($roomRate['status'] == 0) {
continue;
}
if(empty($roomRate['property_room_rate_mapping'])) {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'capacity' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'capacity_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
];
}
$roomKey = 0;
$response['rooms'] = [];
foreach ($roomRates as $roomId => $roomRate) {
$response['rooms'][$roomKey] = [
'id' => $roomId,
'room_name' => $roomRate['room']['name'],
];
$roomRateKey = 0;
$response['rooms'][$roomKey]['rates'] = [];
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$response['rooms'][$roomKey]['rates'][$roomRateKey] = [
'id' => $roomRateMappingId,
'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
'board_id' => $rateData['accommodationId'],
'board_name' => $rateData['name'],
];
$roomRateKey++;
}
$roomKey++;
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function channel(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$propertyChannelCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['parentChannel','propertyChannelCategory'],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
],
];
$propertyChannel = $this->propertyChannelService->select($propertyChannelCriteria);
if (!$propertyChannel['status']) {
throw new ApiErrorException($propertyChannel['message']);
}
$propertyChannel = $propertyChannel['data'];
$response = [];
$response['channels'] = [];
foreach ($propertyChannel as $channel) {
$response['channels'][] = [
'id' => $channel['id'],
'name' => $channel['name'],
'category_id' => $channel['property_channel_category']['id'],
'category_name' => $channel['property_channel_category']['name'],
];
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomAvailability(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomAvailabilities = $this->param['rooms'];
$roomAvailabilitiesCollect = collect($roomAvailabilities);
DB::beginTransaction();
$startDate = $roomAvailabilitiesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomAvailabilitiesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($roomAvailabilities as $availability) {
$roomId = $availability['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$totalInventoryAvailable = null;
if (isset($availability['availability'])) {
$totalInventoryAvailable = $availability['availability'];
}
$startDate = Carbon::parse($availability['start_date'])->toDateString();
$endDate = Carbon::parse($availability['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
//Days Filter
if (isset($availability['days']) && !empty($availability['days']) && is_array($availability['days']) && count($availability['days']) <= 7) {
$requestParams = [
'days' => $availability['days']
];
$validator = Validator::make($requestParams, ['days' => 'required|array|in:Mon,Tue,Wed,Thu,Fri,Sat,Sun']);//Mon,Tue,Wed,Thu,Fri,Sat,Sun
if (empty($validator->errors()->messages())) {
$requestParamBase['include_days'] = $availability['days'];
}
}
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
if (isset($availability['stop_sell']) && !is_null($availability['stop_sell'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'room_stop_sell';
$requestParams['value'] = $availability['stop_sell'];
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,827 @@
<?php
namespace App\Http\Controllers\ChannelManager\SistemOtel\v1;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\BookingService;
use App\Core\Service\ChannelManagerLogService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Validator;
class SistemOtelController extends Controller
{
private $username;
private $password;
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
private $param;
private $channelId;
private $channelManagerLogId;
private $channelManagerRequestTime;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
PropertyRoomService $propertyRoomService,
BookingService $bookingService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerLogService $channelManagerLogService
)
{
//Note: channel_manager_property_mapping tablosunda channel_manager_property_id alanı NULL ise, bu ENW nin CHANNEL tarafından yönetiliyor olması demek.
//Eğer channel_manager_property_id alanında bir otel id var ise, bu CHANNEL ın ENW tarafından güncelleniyor olması demek.
$this->username = 'sistemotel';
$this->password = 'ys6paYBmEWa5q7Mt';
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->propertyRoomService = $propertyRoomService;
$this->bookingService = $bookingService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerLogService = $channelManagerLogService;
$payload = $this->request->getContent();
$payloadJson = json_decode($payload, 1);
$this->param = $payloadJson;
$this->channelId = 1;
$this->channelManagerId = 6; //SistemOtel
$getRequestUri = $request->getRequestUri();
$getRequestUriExplode = explode('/', $getRequestUri);
$serviceRequestName = last($getRequestUriExplode);
//channelManagerLogService
$logArray = ['update-room-availability', 'update-room-rate'];
$this->channelManagerLogId = null;
$this->channelManagerRequestTime = microtime(true);
if (in_array($serviceRequestName, $logArray)) {
$insertDataLog = [
'property_id' => $this->param['hotel_id'],
'channel_manager_id' => $this->channelManagerId,
'type' => 'C2E',
'service' => $serviceRequestName,
'request' => json_encode($payloadJson),
'response' => null,
'ip_address' => $this->request->ip(),
'status' => null
];
$channelManagerLog = $this->channelManagerLogService->create($insertDataLog);
if ($channelManagerLog['status'] == 'success') {
$this->channelManagerLogId = $channelManagerLog['data']['id'];
}
}
//channelManagerLogService
}
public function checkAuthentication($username, $password)
{
$response = ['status' => false, 'message' => ''];
if ($this->username != $username || $this->password != $password) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function responseSuccess($responseData = null)
{
$response = [
'status' => true,
'message' => null,
'data' => $responseData,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 1
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function propertyChannelMapping($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = [
'status' => true,
'data' => $propertyChannelMapping['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelPropertyRoomRate($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam = [
'criteria' => [
['field' => 'channel_id', 'condition' => '=', 'value' => $this->channelId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => [
'propertyRoomRateMapping.propertyRoomRate.propertyRoomRateAccommodation',
'propertyRoomRateMapping.propertyRoom.propertyRoomType',
]
];
$getChannelPropertyRoomRate = $this->propertyRoomRateChannelMappingService->select($requestParam);
if ($getChannelPropertyRoomRate['status'] != 'success' || empty($getChannelPropertyRoomRate['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$getChannelPropertyRoomRate['data'] = collect($getChannelPropertyRoomRate['data'])->where('property_room_rate_mapping.property_room.status',1)->toArray();
$response = [
'status' => true,
'data' => $getChannelPropertyRoomRate['data']
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function channelManagerPropertyCheck($propertyId)
{
$response = ['status' => false, 'message' => ''];
try {
$requestParam =
[
'criteria' =>
[
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
],
'firstRow' => true
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($requestParam);
if ($channelManagerPropertyMapping['status'] != 'success' || empty($channelManagerPropertyMapping['data'])) {
throw new ApiErrorException('Property Room Rate not found');
}
$channelManagerPropertyMapping = $channelManagerPropertyMapping['data'];
if (!is_null($channelManagerPropertyMapping['channel_manager_property_id'])) {
throw new ApiErrorException('This hotel can only be updated by ENW');
}
$response = [
'status' => true
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
return $response;
}
public function roomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
try {
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$response = [];
$roomRates = [];
foreach ($channelPropertyRoomRate as $roomRate) {
if($roomRate['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]['room'] = [
'id' => $roomRate['property_room_rate_mapping']['property_room']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room']['name'],
'status' => 'Active',
'capacity' => $roomRate['property_room_rate_mapping']['property_room']['max_adult'],
'capacity_child' => $roomRate['property_room_rate_mapping']['property_room']['max_child'],
];
$roomRates[$roomRate['property_room_rate_mapping']['room_id']]
['rate'][$roomRate['property_room_rate_mapping']['id']] = [
'id' => $roomRate['property_room_rate_mapping']['id'],
'name' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['name'],
'rate' => $roomRate['property_room_rate_mapping']['property_room_rate']['name'],
'accommodationId' => $roomRate['property_room_rate_mapping']['property_room_rate']['property_room_rate_accommodation']['id'],
];
}
$roomKey = 0;
$response['rooms'] = [];
foreach ($roomRates as $roomId => $roomRate) {
$response['rooms'][$roomKey] = [
'id' => $roomId,
'room_name' => $roomRate['room']['name'],
];
$roomRateKey = 0;
$response['rooms'][$roomKey]['rates'] = [];
foreach ($roomRate['rate'] as $roomRateMappingId => $rateData) {
$response['rooms'][$roomKey]['rates'][$roomRateKey] = [
'id' => $roomRateMappingId,
'rate_name' => $rateData['name'] . ' - ' . $rateData['rate'],
'board_id' => $rateData['accommodationId'],
'board_name' => $rateData['name'],
];
$roomRateKey++;
}
$roomKey++;
}
return $this->responseSuccess($response);
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomAvailability(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomAvailabilities = $this->param['rooms'];
$roomAvailabilitiesCollect = collect($roomAvailabilities);
DB::beginTransaction();
$startDate = $roomAvailabilitiesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomAvailabilitiesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($roomAvailabilities as $availability) {
$roomId = $availability['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$totalInventoryAvailable = null;
if (isset($availability['availability'])) {
$totalInventoryAvailable = $availability['availability'];
}
$startDate = Carbon::parse($availability['start_date'])->toDateString();
$endDate = Carbon::parse($availability['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
//Days Filter
if (isset($availability['days']) && !empty($availability['days']) && is_array($availability['days']) && count($availability['days']) <= 7) {
$requestParams = [
'days' => $availability['days']
];
$validator = Validator::make($requestParams, ['days' => 'required|array|in:Mon,Tue,Wed,Thu,Fri,Sat,Sun']);//Mon,Tue,Wed,Thu,Fri,Sat,Sun
if (empty($validator->errors()->messages())) {
$requestParamBase['include_days'] = $availability['days'];
}
}
if (!is_null($totalInventoryAvailable)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'availability';
$requestParams['value'] = $totalInventoryAvailable;
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
if (isset($availability['stop_sell']) && !is_null($availability['stop_sell'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'room_stop_sell';
$requestParams['value'] = $availability['stop_sell'];
$requestParams['room_rates'] = [
['room_id' => $roomId]
];
$propertyRoomRateMapping = $this->propertyRoomAvailabilityService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
public function updateRoomRate(Request $request)
{
$response = ['status' => false, 'message' => ''];
try {
//checkAuthentication
$checkAuthentication = $this->checkAuthentication($this->param['username'], $this->param['password']);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$propertyId = $this->param['hotel_id'];
$channelManagerPropertyCheck = $this->channelManagerPropertyCheck($propertyId);
if (!$channelManagerPropertyCheck['status']) {
throw new ApiErrorException($channelManagerPropertyCheck['message']);
}
$channelPropertyRoomRate = $this->channelPropertyRoomRate($propertyId);
if (!$channelPropertyRoomRate['status']) {
throw new ApiErrorException($channelPropertyRoomRate['message']);
}
$channelPropertyRoomRate = $channelPropertyRoomRate['data'];
$channelPropertyRoomRateCollect = collect($channelPropertyRoomRate);
$propertyChannelMapping = $this->propertyChannelMapping($propertyId);
if (!$propertyChannelMapping['status']) {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
$roomRates = $this->param['rooms'];
$roomRatesCollect = collect($roomRates);
DB::beginTransaction();
foreach ($roomRates as $roomRate) {
$roomId = $roomRate['room_id'];
$roomCheck = $channelPropertyRoomRateCollect->where('property_room_rate_mapping.room_id', $roomId)->isEmpty();
if ($roomCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$roomRatesCollect = collect($roomRate['rates']);
$startDate = $roomRatesCollect->sortBy('start_date')->first();
$startDate = $startDate['start_date'];
$endDate = $roomRatesCollect->sortByDesc('end_date')->first();
$endDate = $endDate['end_date'];
if (Carbon::parse($startDate)->isBefore(Carbon::now()->toDateString()) || Carbon::parse($endDate)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Dates to be updated cannot be earlier than today');
}
foreach ($roomRate['rates'] as $rate) {
$startDate = Carbon::parse($rate['start_date'])->toDateString();
$endDate = Carbon::parse($rate['end_date'])->toDateString();
$requestParamBase = [
'property_id' => fillOnUndefined($propertyChannelMapping, 'property_id'),
'channel_id' => fillOnUndefined($propertyChannelMapping, 'channel_id'),
'availability_type_id' => fillOnUndefined($propertyChannelMapping, 'property_availability_type_id', 1),
'start_date' => $startDate,
'end_date' => $endDate,
'include_days' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
];
//Days Filter
if (isset($rate['days']) && !empty($rate['days']) && is_array($rate['days']) && count($rate['days']) <= 7) {
$requestParams = [
'days' => $rate['days']
];
$validator = Validator::make($requestParams, ['days' => 'required|array|in:Mon,Tue,Wed,Thu,Fri,Sat,Sun']);
if (empty($validator->errors()->messages())) {
$requestParamBase['include_days'] = $rate['days'];
}
}
$roomRateMappingId = $rate['rate_id'];
$isCloseRoomRateMappingSale = null;
if (isset($rate['stop_sell'])) {
$isCloseRoomRateMappingSale = $rate['stop_sell'] == 1 ? true : false;
}
$channelRoomRateMappingCheck = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->isEmpty();
if ($channelRoomRateMappingCheck) {
throw new ApiErrorException('Undefined or inactive room accommodation');
}
$roomRates = [];
$roomRates[] = [
'room_id' => $roomId,
'room_rate_mapping_id' => [
$roomRateMappingId
]
];
$paramsListChannel = [];
$paramsListChannel[] = $this->channelId;
//CONNECTED CHANNEL RATE UPDATE
$propertyChannelMappingConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $requestParamBase['property_id']],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $requestParamBase['channel_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => 5],//JUST CM
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel']
];
$propertyChannelMappingConnected = $this->propertyChannelMappingService->select($propertyChannelMappingConnectedCriteria);
if ($propertyChannelMappingConnected['status'] == 'success') {
foreach ($propertyChannelMappingConnected['data'] as $channel) {
if (!is_null($channel['channel']['parent_id'])) {
continue;
}
$paramsListChannel[] = $channel['channel_id'];
}
}
//CONNECTED CHANNEL RATE UPDATE
foreach ($paramsListChannel as $paramChannelId) {
//Eğer Rate var ise currency check yapılmalı ve PerDay var mı check edilmeli, burada sonra günceleme yaptırılabilri
if (isset($rate['amount'])) {
$currency = $this->param['currency'];
$currencyCheck = ($currency == $propertyChannelMapping['currency_code']) ? true : false;
if (!$currencyCheck) {
throw new ApiErrorException('Exchange rate that does not match the channel exchange rate, channel exchange rate: ' . $propertyChannelMapping['currency_code']);
}
$channelRoomRateMapping = $channelPropertyRoomRateCollect->where('room_rate_mapping_id', $roomRateMappingId)->first();
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate';
$requestParams['value'] = $rate['amount'];
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Room Rate Stop Sale
if (!is_null($isCloseRoomRateMappingSale)) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'rate_stop_sell';
$requestParams['value'] = $isCloseRoomRateMappingSale ? 1 : 0;
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
//Kısıtlamalar var ise min los
if (isset($rate['min_stay'])) {
//Minimum Konaklama Gün Sayısı
if (isset($rate['min_stay'])) {
$requestParams = [];
$requestParams = $requestParamBase;
$requestParams['update_type'] = 'min_stay';
$requestParams['value'] = $rate['min_stay'];
$requestParams['room_rates'] = $roomRates;
$requestParams['channel_id'] = $paramChannelId;
$propertyRoomRateMapping = $this->propertyRoomRatePriceService->bulkUpdate($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
}
}
}
DB::commit();
return $this->responseSuccess(['confirmCode' => $this->channelManagerLogId]);
} 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();
}
DB::rollBack();
if (!$response['status']) {
return $this->responseError($response['message']);
}
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
}

View File

@@ -0,0 +1,372 @@
<?php
namespace App\Http\Controllers\MetaSearch\Google\v1;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyChannelCouponService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use App\Models\PropertyChannel;
use App\Models\PropertyContact;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Exception;
class GoogleController extends Controller
{
private $username;
private $password;
private $authorization;
private $channelManagerId;
private $channelManagerLogId;
private $mealCodeMapping;
private $paymentTypeMapping;
private $countryCodeCampaign;
public function __construct(
Request $request,
CurrencyService $currencyService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
PropertyChannelCouponService $propertyChannelCouponService
)
{
$this->username = 'google';
$this->password = 'P8MUQtNP6TkKMz3E';
$this->channelManagerId = 14;//Google
$this->request = $request;
$this->currencyService = $currencyService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->propertyChannelCouponService = $propertyChannelCouponService;
$payload = $this->request->getContent();
parse_str(urldecode($payload), $payloadDecode);
$this->param = $payloadDecode;
$this->authorization = $request->header('authorization');
$this->tax = 10;
$this->mealCodeMapping = [
10 => 'AI',
11 => 'BB',
13 => 'RO',
14 => 'FB',
15 => 'HB',
];
$this->paymentTypeMapping = [
'CRD' => 'prepaid',
'HTL' => 'postpaid'
];
}
public function checkAuthentication($authorization)
{
$response = ['status' => false, 'message' => ''];
$basicAuth = 'Basic ' . base64_encode($this->username . ':' . $this->password);
if ($authorization != $basicAuth) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function requestParamConverter($requestParam = [])
{
$searchRequestJson = [];
$searchRequestJson['date']['checkIn'] = Carbon::parse($requestParam['Checkin'])->toDateString();
$searchRequestJson['date']['checkOut'] = Carbon::parse($requestParam['Checkin'])->addDays($requestParam['Nights'])->toDateString();
$rooms = [];
$rooms[0]['adults'] = (integer)$requestParam['Context']['OccupancyDetails']['NumAdults'];
$rooms[0]['children'] = (integer)($requestParam['Context']['Occupancy'] - $requestParam['Context']['OccupancyDetails']['NumAdults']);
$rooms[0]['age'] = [];
if (isset($requestParam['Context']['OccupancyDetails']['Children']['Child'])) {
$requestParam['Context']['OccupancyDetails']['Children']['Child'] = singleElementXMLArray($requestParam['Context']['OccupancyDetails']['Children']['Child']);
} else {
$requestParam['Context']['OccupancyDetails']['Children']['Child'] = [];
}
foreach ($requestParam['Context']['OccupancyDetails']['Children']['Child'] as $child) {
$rooms[0]['age'][] = $child['@attributes']['age'];
}
$searchRequestJson['rooms'] = $rooms;
if (isset($requestParam['PropertyList']['Property'])) {
$requestParam['PropertyList']['Property'] = singleElementXMLArray($requestParam['PropertyList']['Property']);
} else {
$requestParam['PropertyList']['Property'] = [];
}
$searchRequestJson['property'] = $requestParam['PropertyList']['Property'];
return $searchRequestJson;
}
public function deepLinkGenerator($token, $requestParam = [])
{
$deepLink = 'https://be.extranetwork.com/' . $token . '/' . fillOnUndefined($requestParam, 'locale', 'en') . '/search/';
$deepLink .= Carbon::parse($requestParam['date']['checkIn'])->format('Ymd') . '/';
$deepLink .= Carbon::parse($requestParam['date']['checkOut'])->format('Ymd') . '/';
$roomOccupancy = $this->roomOccupancy($requestParam['rooms']);
$deepLink .= implode(',', $roomOccupancy);;
$deepLink .= '?utm_source=google';
return $deepLink;
}
public function hotel(Request $request)
{
$response = ['status' => true, 'message' => ''];
$listings = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><listings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.gstatic.com/localfeed/local_feed.xsd"></listings>');
$listings->addChild('language', 'en');
try {
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMappingCriteria['with'] = [
'property.propertyType', 'property.propertyContact', 'property.propertyWeb', 'property.country',
'property.propertyRooms', 'property.propertyPhotos', 'property.propertyAdditionalInfos', 'property.propertyBrand'
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
if ($propertyMapping['status'] != 1) {
continue;
}
$metaAddress = json_decode($propertyMapping['property']['property_contact']['meta'], 1);
$listing = $listings->addChild('listing');
$listing->addChild('id', $propertyMapping['property']['id']);
$listing->addChild('name', htmlspecialchars($propertyMapping['property']['name'], ENT_XML1, 'UTF-8'));
$address = $listing->addChild('address');
$address->addAttribute('format', 'simple');
$component = $address->addChild('component', htmlspecialchars(fillOnUndefined($metaAddress, 'street'), ENT_XML1, 'UTF-8'));
$component->addAttribute('name', 'addr1');
//$component = $address->addChild('component');
//$component->addAttribute('name', 'addr2');
$component = $address->addChild('component', fillOnUndefined($metaAddress, 'city'));
$component->addAttribute('name', 'city');
//$component = $address->addChild('component', $propertyMapping['property']['country']['name']);
//$component->addAttribute('name','region');
$component = $address->addChild('component', fillOnUndefined($metaAddress, 'zip_code'));
$component->addAttribute('name', 'postal_code');
$listing->addChild('country', $propertyMapping['property']['country']['country_code']);
$listing->addChild('latitude', $propertyMapping['property']['property_contact']['latitude']);
$listing->addChild('longitude', $propertyMapping['property']['property_contact']['longitude']);
if (!empty($propertyMapping['property']['property_contact']['view_full_phone'])) {
$phone = $listing->addChild('phone');
$phone->addAttribute('number', $propertyMapping['property']['property_contact']['view_full_phone']);
}
$listing->addChild('category', 'hotel');
if (!empty($propertyMapping['property']['property_brand']['name'])) {
$listing->addChild('brand', htmlspecialchars($propertyMapping['property']['property_brand']['name'], ENT_XML1, 'UTF-8'));
}
if (!empty($propertyMapping['property']['property_web']['webProtocolUrl'])) {
$listing->addChild('website', $propertyMapping['property']['property_web']['webProtocolUrl']);
}
$content = $listing->addChild('content');
$text = $content->addChild('text');
$text->addAttribute('type', 'description');
$text->addChild('body', htmlspecialchars($propertyMapping['property']['name'], ENT_XML1, 'UTF-8'));
$attributes = $content->addChild('attributes');
$clientAttrCountry = $attributes->addChild('client_attr', $propertyMapping['property']['country']['country_code']);
$clientAttrCountry->addAttribute('name', 'country');
$clientAttrMaxNightStay = $attributes->addChild('client_attr', '0');
$clientAttrMaxNightStay->addAttribute('name', 'max_night_stay');
$clientAttrMinNightStay = $attributes->addChild('client_attr', '1');
$clientAttrMinNightStay->addAttribute('name', 'minimum_night_stay');
$roomCountTotal = 0;
if (!empty($propertyMapping['property']['property_additional_infos'])) {
foreach ($propertyMapping['property']['property_additional_infos'] as $info) {
if ($info['additional_info_key_id'] == 3) {
$roomCountTotal = $info['value'];
break;
}
}
}
$clientAttrRooms = $attributes->addChild('client_attr', $roomCountTotal);
$clientAttrRooms->addAttribute('name', 'number_of_rooms');
$clientAttrLatLong = $attributes->addChild('client_attr', $propertyMapping['property']['property_contact']['latitude'] . ', ' . $propertyMapping['property']['property_contact']['longitude']);
$clientAttrLatLong->addAttribute('name', 'latlong');
if (!empty($propertyMapping['property']['property_photos'])) {
$photos = $propertyMapping['property']['property_photos'];
// Filter photos with status 1
$photos = array_filter($photos, function ($p) {
return isset($p['status']) && $p['status'] == 1;
});
// Sort photos by is_default (desc), photo_order (asc), and created_at (desc)
usort($photos, function ($a, $b) {
return ($b['is_default'] ?? 0) <=> ($a['is_default'] ?? 0)
?: ($a['photo_order'] ?? 0) <=> ($b['photo_order'] ?? 0)
?: ($b['created_at'] ?? 0) <=> ($a['created_at'] ?? 0);
});
// Limit to first 10 photos
$photos = array_slice($photos, 0, 10);
foreach ($photos as $photo) {
$imageUrl = $photo['photoUrl']['default'] ?? $photo['photo_url']['default'] ?? null;
if ($imageUrl) {
$image = $content->addChild('image');
$image->addAttribute('type', 'ad');
$image->addAttribute('url', $imageUrl);
$width = '1440';
$height = '959';
if (!empty($photo['photo_resolution'])) {
$resolution = explode('x', $photo['photo_resolution']);
if (count($resolution) == 2) {
$width = trim($resolution[0]);
$height = trim($resolution[1]);
}
}
$image->addAttribute('width', $width);
$image->addAttribute('height', $height);
$image->addChild('link', $imageUrl);
$image->addChild('title', 'Unknown title');
$date = $image->addChild('date');
if (!empty($photo['created_at'])) {
$photoCreatedAt = Carbon::createFromTimestamp($photo['created_at']);
} else {
$photoCreatedAt = Carbon::now();
}
$date->addAttribute('day', $photoCreatedAt->day);
$date->addAttribute('month', $photoCreatedAt->month);
$date->addAttribute('year', $photoCreatedAt->year);
}
}
}
}
}
} 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();
}
header('Content-Type: application/xml; charset=UTF-8');
echo $listings->asXML();
exit;
}
}

View File

@@ -0,0 +1,872 @@
<?php
namespace App\Http\Controllers\MetaSearch\Trivago\v1;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyChannelCouponService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use App\Models\PropertyChannel;
use App\Models\PropertyContact;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Exception;
class TrivagoController extends Controller
{
private $username;
private $password;
private $authorization;
private $channelManagerId;
private $channelManagerLogId;
private $mealCodeMapping;
private $paymentTypeMapping;
private $countryCodeCampaign;
public function __construct(
Request $request,
CurrencyService $currencyService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
PropertyChannelCouponService $propertyChannelCouponService
)
{
$this->username = 'trivago';
$this->password = 'P8MUQtNP6TkKMz3E';
$this->channelManagerId = 11;//Trivago
$this->request = $request;
$this->currencyService = $currencyService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->propertyChannelCouponService = $propertyChannelCouponService;
$payload = $this->request->getContent();
parse_str(urldecode($payload), $payloadDecode);
$this->param = $payloadDecode;
$this->authorization = $request->header('authorization');
$this->tax = 10;
$this->cityTax = 2;
$this->mealCodeMapping = [
10 => 'AI',
11 => 'BB',
13 => 'RO',
14 => 'FB',
15 => 'HB',
];
$this->paymentTypeMapping = [
'CRD' => 'prepaid',
'HTL' => 'postpaid'
];
$this->CPA['TR'] = ["1" => 9.60, "2" => 10.80, "3" => 11.00, "4" => 11.20, "5" => 11.40, "6" => 11.60, "7" => 11.80, "8" => 12.00];
$this->CPA['DE'] = ["1" => 10.80, "2" => 11.00, "3" => 11.20, "4" => 11.40, "5" => 11.60, "6" => 11.80, "7" => 12.00, "8" => 12.20];
$this->CPA['UK'] = ["1" => 10.80, "2" => 11.00, "3" => 11.20, "4" => 11.40, "5" => 11.60, "6" => 11.80, "7" => 12.00, "8" => 12.20];
$this->CPA['US'] = ["1" => 10.80, "2" => 11.00, "3" => 11.20, "4" => 11.40, "5" => 11.60, "6" => 11.80, "7" => 12.00, "8" => 12.20];
$this->countryCodeCampaign = [
'DE' => [
'code' => 'DE',
'campaignCode' => 7
],
'TR' => [
'code' => 'TR',
'campaignCode' => 8
],
'US' => [
'code' => 'US',
'campaignCode' => 7
],
'UK' => [
'code' => 'UK',
'campaignCode' => 7
]
];
}
public function checkAuthentication($authorization)
{
$response = ['status' => false, 'message' => ''];
$basicAuth = 'Basic ' . base64_encode($this->username . ':' . $this->password);
if ($authorization != $basicAuth) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function requestParamConverter($requestParam = [])
{
$searchRequestJson = [];
$searchRequestJson['date']['checkIn'] = Carbon::parse($requestParam['start_date'])->toDateString();
$searchRequestJson['date']['checkOut'] = Carbon::parse($requestParam['end_date'])->toDateString();
$rooms = [];
for ($i = 0; $i < $requestParam['num_rooms']; $i++) {
$roomCounter = ($i + 1);
if (isset($requestParam['room_adults_' . $roomCounter])) {
$rooms[$i]['adults'] = $requestParam['room_adults_' . $roomCounter];
}
$rooms[$i]['children'] = 0;
$rooms[$i]['age'] = null;
if (isset($requestParam['room_childs_' . $roomCounter])) {
$childAges = json_decode($requestParam['room_childs_' . $roomCounter]);
$rooms[$i]['children'] = count($childAges);
$rooms[$i]['age'] = $childAges;
}
}
$searchRequestJson['rooms'] = $rooms;
$searchRequestJson['property'] = json_decode($requestParam['hotels']);
return $searchRequestJson;
}
public function roomOccupancy($requestParam)
{
$roomOccupancy = [];
foreach ($requestParam as $room) {
$adults = str_repeat('A', $room['adults']);
$children = [];
if ($room['children'] > 0 && !empty($room['age'])) {
foreach ($room['age'] as $child) {
$children[] = 'C' . $child;
}
}
$roomOccupancy[] = $adults . implode('', $children);
}
return $roomOccupancy;
}
public function deepLinkGenerator($token, $requestParam = [])
{
$deepLink = 'https://be.extranetwork.com/' . $token . '/en/search/';
$deepLink .= Carbon::parse($requestParam['date']['checkIn'])->format('Ymd') . '/';
$deepLink .= Carbon::parse($requestParam['date']['checkOut'])->format('Ymd') . '/';
$roomOccupancy = $this->roomOccupancy($requestParam['rooms']);
$deepLink .= implode(',', $roomOccupancy);;
$deepLink .= '?utm_medium=trivago&utm_source=trivago&locale=' . $requestParam['locale'];
return $deepLink;
}
public function couponCodeCheck($propertyId, $checkIn, $checkOut)
{
//$propertyChannelCoupon
$propertyChannelCouponsCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_id', 'condition' => '=', 'value' => 1],
['field' => 'start_date', 'condition' => '<=', 'value' => Carbon::now()->toDateString()],
['field' => 'end_date', 'condition' => '>=', 'value' => Carbon::now()->toDateString()],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'orderBy' => [
['field' => 'id', 'value' => 'DESC']
],
];
$propertyChannelCoupons = $this->propertyChannelCouponService->select($propertyChannelCouponsCriteria);
if ($propertyChannelCoupons['status'] == 'success') {
$propertyChannelCoupons = $propertyChannelCoupons['data'];
foreach ($propertyChannelCoupons as $propertyChannelCouponKey => $propertyChannelCouponData) {
//Reservation Date Check
if (!is_null($propertyChannelCouponData['reservation_start_date']) && !is_null($propertyChannelCouponData['reservation_end_date'])) {
$reservationDateCheck = Carbon::parse($propertyChannelCouponData['reservation_start_date'])->lessThanOrEqualTo(Carbon::parse($checkIn))
&& Carbon::parse($propertyChannelCouponData['reservation_end_date'])->greaterThanOrEqualTo(Carbon::parse($checkOut));
if (!$reservationDateCheck) {
unset($propertyChannelCoupons[$propertyChannelCouponKey]);
}
}
}
} else {
$propertyChannelCoupons = [];
}
$propertyChannelCoupon = !empty($propertyChannelCoupons) ? reset($propertyChannelCoupons) : null;
return $propertyChannelCoupon;
}
public function availability(Request $request)
{
$response = ['status' => true, 'message' => ''];
$checkAuthentication = $this->checkAuthentication($this->authorization);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$searchController = App::make("App\Http\Controllers\BookingEngine\V1\SearchController");
$requestTime = microtime(true);
$hotelList['root'] = $this->param;
unset($hotelList['root']['hotels']);
$hotelList['root']['hotel_ids'] = json_decode($this->param['hotels']);
$hotelList['root']['hotels'] = [];
$hotelList['root']['api_version'] = (integer)$hotelList['root']['api_version'];
$hotelList['root']['num_rooms'] = (integer)$hotelList['root']['num_rooms'];
for ($i = 0; $i < $hotelList['root']['num_rooms']; $i++) {
$roomCounter = ($i + 1);
if (isset($hotelList['root']['room_adults_' . $roomCounter])) {
$hotelList['root']['room_adults_' . $roomCounter] = (integer)$hotelList['root']['room_adults_' . $roomCounter];
}
}
$requestCurrency = $this->param['currency'];
try {
//Hotels Check
$channelManagerPropertyList = [];
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyList = pickItemFromArray('property_id', $channelManagerPropertyMapping['data']);
}
$availableHotelIds = array_intersect($hotelList['root']['hotel_ids'], $channelManagerPropertyList);
if (empty($availableHotelIds)) {
throw new ApiErrorException('Hotel not found');
}
$this->param['hotels'] = json_encode($availableHotelIds);
//Hotels Check
$searchRequestJson = $this->requestParamConverter($this->param);
$searchRequestJson['ipAddress'] = $request->getClientIp();
$searchRequestJson['isMobile'] = null;
$searchRequestJson['noneCacheSearch'] = true;
$searchRequestJson['ipAddress'] = $request->getClientIp();
$searchRequestJson['justPriceValues'] = true;
$cacheKeyParam = $this->param;
unset($cacheKeyParam['currency']);
unset($cacheKeyParam['rate_model']);
unset($cacheKeyParam['lang']);
$cacheKey = 'TRV:' . md5(implode(',', $cacheKeyParam));
//Cache::forget($cacheKey);
if (Cache::has($cacheKey)) {
$search = Cache::get($cacheKey);
} else {
$requestCreate = Request::create(null, null, [], [], [], [], json_encode($searchRequestJson));
$requestCreate->headers->set('channelId', '1');
//$requestCreate->headers->set('bookingEnginePropertyId', null);
$requestCreate->headers->set('channelToken', 'ece3ef02-42e7-92b7-f379-08226ed7a0f3');//TODO: from DB
$requestCreate->headers->set('bookingEngineToken', null);
$search = $searchController->search($requestCreate);
Cache::put($cacheKey, $search, 60 * 60);//1 Day 24 * 60 * 60
}
$search = json_decode(json_encode($search), 1);
if ($search['original']['status'] != 200) {
throw new ApiErrorException('Hotel not found');
}
$properties = $search['original']['data']['properties'];
if (empty($properties)) {
throw new ApiErrorException('Hotel not found');
}
$hotelCounter = 0;
$numberOfStay = Carbon::parse($searchRequestJson['date']['checkIn'])->diffInDays(Carbon::parse($searchRequestJson['date']['checkOut']));
foreach ($properties as $propertyId => $property) {
if (!isset($property['currency'])) {
continue;
}
$currencyExchangeRate = 1;
if ($requestCurrency != $property['currency']) {
$currencyExchangeRate = $this->currencyService->lastExchangeRate($property['currency'], $requestCurrency);
if ($currencyExchangeRate['status'] == 'success') {
$currencyExchangeRate = $currencyExchangeRate['data'];
}
}
$languageLocale = explode('_', $this->param['lang'], 2);
$searchRequestJson['locale'] = $languageLocale[1];
$token = $property['booking_engine_token'];
$deepLinkGenerator = $this->deepLinkGenerator($token, $searchRequestJson);
$property = reset($property['availabilities']);
$propertyRooms = $property['rooms'];
//Standard Room Room Only FreeCancellation - Pay at Hotel
$requestedRoomPriceGroup = [];
foreach ($propertyRooms as $propertyRoomId => $propertyRoom) {
foreach ($propertyRoom['rates'] as $propertyRoomRateId => $propertyRoomRate) {
foreach ($propertyRoomRate['requestedRoomPrice'] as $occupancyCode => $requestedRoomPrices) {
foreach ($requestedRoomPrices['prices'] as $requestedRoomPriceKey => $requestedRoomPrice) {
$roomRateKeyName = $occupancyCode . ' ' . $requestedRoomPrice['room']['name'] . ' ' . $requestedRoomPrice['rate']['boardName'] . ' ' . $requestedRoomPrice['name'];
$roomRateKeycode = $requestedRoomPrice['rate']['accommodationCode'] . '|' . (isset($requestedRoomPrice['cancellationPolicy']['id']) ? $requestedRoomPrice['cancellationPolicy']['id'] : 0) . '|' . $requestedRoomPrice['bookingPaymentType']['code'];
//$requestedRoomPriceGroup[$roomRateKeycode][$occupancyCode][] = $roomRateKeyName . '-' . $requestedRoomPrice['rateKeyCode'];
$requestedRoomPrice['dailyAverageDiscount'] = $requestedRoomPrices['dailyAverageDiscount'];
$requestedRoomPriceGroup[$roomRateKeycode][$occupancyCode][] = $requestedRoomPrice;
}
}
}
}
$roomOccupancy = $this->roomOccupancy($searchRequestJson['rooms']);
$roomRateBoardGroup = [];
foreach ($requestedRoomPriceGroup as $groupKey => $groupValue) {
$counter = 0;
foreach ($groupValue as $groupValueOccupancyCode => $groupValueOccupancy) {
foreach ($groupValueOccupancy as $groupValueOccupancyCodeX => $groupValueOccupancyVal) {
foreach ($roomOccupancy as $occupancyOrder => $occupancy) {
$occupancyCheckKey = $occupancy . '-' . $occupancyOrder;
if ($groupValueOccupancyCode == $occupancy && !isset($roomRateBoardGroup[$groupKey][$counter][$occupancyCheckKey])) {
$roomRateBoardGroup[$groupKey][$counter][$occupancyCheckKey] = $groupValueOccupancyVal;
if (count($roomRateBoardGroup[$groupKey][$counter]) == count($roomOccupancy)) {
$counter++;
}
}
}
}
}
}
$roomRateTypes = [];
foreach ($roomRateBoardGroup as $boardGroups) {
foreach ($boardGroups as $boardGroups) {
$roomRateTypesGroup = [];
foreach ($boardGroups as $requestedRoomPrice) {
$roomRateKeyName = $requestedRoomPrice['room']['name'] . ' ' . $requestedRoomPrice['rate']['boardName'] . ' ' . $requestedRoomPrice['name'];
$total = $requestedRoomPrice['total'];
$totalBeforeDiscount = $requestedRoomPrice['total'];
$totalBeforeDiscountDailyAverage = ($totalBeforeDiscount / $numberOfStay);
$discounts = [];
if ($requestedRoomPrice['dailyAverageDiscount'] > 0) {
$totalBeforeDiscount = ($total / (100 - (double)$requestedRoomPrice['dailyAverageDiscount'])) * 100;
$totalBeforeDiscountDailyAverage = ($totalBeforeDiscount / $numberOfStay);
$totalDiscount = $totalBeforeDiscount - $total;
$dailyDiscountAverage = ($totalDiscount / $numberOfStay);
$netRate = $dailyDiscountAverage / (1 + ($this->tax / 100) + ($this->cityTax / 100));
$vat = $netRate * ($this->tax / 100);
$localTax = $netRate * ($this->cityTax / 100);
$finalRateDiscount = moneyDoubleFormatDecimal($localTax * $currencyExchangeRate) + moneyDoubleFormatDecimal($netRate * $currencyExchangeRate) + moneyDoubleFormatDecimal($vat * $currencyExchangeRate);
$discounts[] = [
'booking_fee' => 0,
'final_rate' => moneyDoubleFormatDecimal($finalRateDiscount), //moneyDoubleFormatDecimal($dailyDiscountAverage * $currencyExchangeRate),
'hotel_fee' => 0,
'local_tax' => moneyDoubleFormatDecimal($localTax * $currencyExchangeRate),
'marketing_text' => $requestedRoomPrice['dailyAverageDiscount'] . '% Special Discount',
'net_rate' => moneyDoubleFormatDecimal($netRate * $currencyExchangeRate),
'resort_fee' => 0,
'service_charge' => 0,
'vat' => moneyDoubleFormatDecimal($vat * $currencyExchangeRate),
];
}
$netRate = $totalBeforeDiscountDailyAverage / (1 + ($this->tax / 100) + ($this->cityTax / 100));
$vat = $netRate * ($this->tax / 100);
$localTax = $netRate * ($this->cityTax / 100);
$finalRate = moneyDoubleFormatDecimal($localTax * $currencyExchangeRate) + moneyDoubleFormatDecimal($netRate * $currencyExchangeRate) + moneyDoubleFormatDecimal($vat * $currencyExchangeRate);
$roomRateTypesGroup[][$roomRateKeyName] = [
'booking_fee' => 0,
'breakfast_included' => in_array($requestedRoomPrice['rate']['accommodationCode'], [10, 11, 14, 15]) ? true : false,
'currency' => $requestCurrency,
'discounts' => $discounts,
'final_rate' => moneyDoubleFormatDecimal($finalRate),//moneyDoubleFormatDecimal($totalBeforeDiscountDailyAverage * $currencyExchangeRate),
'free_cancellation' => $requestedRoomPrice['cancellationPolicy']['isFreeCancellation'] ? true : false,
//'free_cancellation_deadline' => '2018-04-25T16:00:00+00:00',
'hotel_fee' => 0,
'local_tax' => moneyDoubleFormatDecimal($localTax * $currencyExchangeRate),
'meal_code' => isset($this->mealCodeMapping[$requestedRoomPrice['rate']['accommodationCode']]) ? $this->mealCodeMapping[$requestedRoomPrice['rate']['accommodationCode']] : 'RO',
'net_rate' => moneyDoubleFormatDecimal($netRate * $currencyExchangeRate),
'payment_type' => isset($this->paymentTypeMapping[$requestedRoomPrice['bookingPaymentType']['code']]) ? $this->paymentTypeMapping[$requestedRoomPrice['bookingPaymentType']['code']] : 'postpaid',
'resort_fee' => 0,
'room_code' => $requestedRoomPrice['room']['name'],
'service_charge' => 0,
'url' => $deepLinkGenerator,
//'mobileURL' => null',
'vat' => moneyDoubleFormatDecimal($vat * $currencyExchangeRate),
'rate_type' => 'DEFAULT',
//'rateKeyCode' => $requestedRoomPrice['rateKeyCode'],
//'dailyAverageDiscount' => $requestedRoomPrice['dailyAverageDiscount'],
];
}
$roomRateTypes[] = $roomRateTypesGroup;
}
}
if (!empty($roomRateTypes)) {
//if (in_array($propertyId, [1275,1325])) {
$propertyCouponCodeCheck = $this->couponCodeCheck($propertyId, $searchRequestJson['date']['checkIn'], $searchRequestJson['date']['checkOut']);
if (!empty($propertyCouponCodeCheck)) {
$roomRateTypesWithCoupon = [];
foreach ($roomRateTypes as $roomRateTypeKey => $roomRateType) {
foreach ($roomRateType as $roomRateTypeDetailKey => $roomRateTypeDetails) {
//dd($roomRateTypeKey, $roomRateTypeDetailKey, $propertyCouponCodeCheck, $roomRateTypeDetail, key($roomRateTypeDetail));
$roomRateTypeDetail = reset($roomRateTypeDetails);
$couponPercentageValue = (100 - $propertyCouponCodeCheck['value']) / 100;
$finalRateDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('final_rate');
$localTaxDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('local_tax');
$netRateDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('net_rate');
$vatDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('vat');
$finalRateDiscountReward = ($roomRateTypeDetail['final_rate'] - $finalRateDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$localTaxDiscountReward = ($roomRateTypeDetail['local_tax'] - $localTaxDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$netRateDiscountReward = ($roomRateTypeDetail['net_rate'] - $netRateDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$vatDiscountReward = ($roomRateTypeDetail['vat'] - $vatDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$discountReward = [
'booking_fee' => 0,
'final_rate' => moneyDoubleFormatDecimal($finalRateDiscountBeforeReward + $finalRateDiscountReward),
'hotel_fee' => 0,
'local_tax' => moneyDoubleFormatDecimal($localTaxDiscountBeforeReward + $localTaxDiscountReward),
'marketing_text' => 'Special REWARD Discount',
'net_rate' => moneyDoubleFormatDecimal($netRateDiscountBeforeReward + $netRateDiscountReward),
'resort_fee' => 0,
'service_charge' => 0,
'vat' => moneyDoubleFormatDecimal($vatDiscountBeforeReward + $vatDiscountReward),
];
$discountReward['marketing_text'] = number_format($discountReward['final_rate'] / $roomRateTypeDetail['final_rate'] * 100) . '% Special Popup Discount';
unset($roomRateTypeDetail['discounts']);
$roomRateTypeDetail['discounts'][] = $discountReward;
//$roomRateTypeDetail['rate_type'] = 'REWARD';
$roomRateTypeDetail['rate_type'] = 'DEFAULT';
$roomRateTypesWithCoupon[$roomRateTypeKey][$roomRateTypeDetailKey][key($roomRateTypeDetails)] = $roomRateTypeDetail;
}
unset($roomRateTypes[$roomRateTypeKey]);
}
$roomRateTypes = array_merge($roomRateTypes, $roomRateTypesWithCoupon);
}
//}
$hotelList['root']['hotels'][$hotelCounter] = [
'hotel_id' => $propertyId,
'room_types' => $roomRateTypes
];
$hotelCounter++;
}
}
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
$hotelList['root']['hotels'] = [];
}
$responseTime = microtime(true) - $requestTime;
//Log::debug(json_encode($this->param) . ' - Response Time: ' . number_format($responseTime, 2) . ' - Status: ' . count($hotelList['root']['hotels']));
return response()->json($hotelList);
}
public function hotel(Request $request)
{
$response = ['status' => true, 'message' => ''];
$hotelList = [];
$hotelList['api_version'] = 4;
$hotelList['lang'] = 'en_GB';
$hotelList['hotels'] = [];
try {
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMappingCriteria['with'] = [
'property.propertyType', 'property.propertyContact', 'property.propertyWeb', 'property.country'
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
if ($propertyMapping['status'] != 1) {
continue;
}
$metaAddress = json_decode($propertyMapping['property']['property_contact']['meta'], 1);
$hotelList['hotels'][] = [
'partner_reference' => $propertyMapping['property']['id'],
'name' => $propertyMapping['property']['name'],
'street' => fillOnUndefined($metaAddress, 'street'),
'city' => fillOnUndefined($metaAddress, 'city'),
'postal_code' => fillOnUndefined($metaAddress, 'zip_code'),
//'state' => null,
'country' => $propertyMapping['property']['country']['name'],
'latitude' => $propertyMapping['property']['property_contact']['latitude'],
'longitude' => $propertyMapping['property']['property_contact']['longitude'],
'desc' => $propertyMapping['property']['name'],
'amenities' => null,//['Beauty Center', 'Business Center', 'Café/ Bistro', 'Sauna'],
'url' => $propertyMapping['property']['property_web']['webProtocolUrl'],
'email' => $propertyMapping['property']['property_contact']['email'],
'phone' => $propertyMapping['property']['property_contact']['phone'],
'fax' => $propertyMapping['property']['property_contact']['fax']
];
//dd(json_decode($propertyMapping['property']['property_contact']['meta'],1));
$addressExplode = explode('/', $propertyMapping['property']['property_contact']['address'], 2);
$street = isset($addressExplode[0]) ? $addressExplode[0] : $propertyMapping['property']['property_contact']['address'];
$cityExplode = isset($addressExplode[1]) ? explode(',', $addressExplode[1]) : (isset($addressExplode[0]) ? explode(',', $addressExplode[0]) : null);
$city = isset($cityExplode[0]) ? $cityExplode[0] : null;
$streetExplode = explode(', ', $street);
unset($streetExplode[count($streetExplode) - 1]);
$street = implode(', ', $streetExplode);
$metaUpdate = [
'street' => $street,
'city' => $city,
'zip_code' => $propertyMapping['property']['property_contact']['zip_code'],
];
if (empty($propertyMapping['property']['property_contact']['meta'])) {
PropertyContact::where('id', $propertyMapping['property']['property_contact']['id'])->update(['meta' => json_encode($metaUpdate)]);
}
//dd($propertyMapping['property']['property_contact']['id'],$metaUpdate);
}
}
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
$hotelList['root']['hotels'] = [];
}
return response()->json($hotelList);
}
public function campaign(Request $request)
{
$hotelList = [];
$hotelExcludeList = [];
$hotelExcludeList['TR'] = [721, 729];
try {
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMappingCriteria['with'] = [
'property.propertyType', 'property.propertyContact', 'property.propertyWeb', 'property.country'
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$hotelList[] = [
'partner_reference' => 'partner_reference',
'locale' => 'locale',
'campaign' => 'campaign'
];
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
foreach ($this->CPA as $countryCode => $countryValue) {
foreach ($countryValue as $campaignId => $campaignValue) {
if (isset($this->countryCodeCampaign[$countryCode]) && $this->countryCodeCampaign[$countryCode]['campaignCode'] == $campaignId) {
if (isset($hotelExcludeList[$countryCode])) {
if (in_array($propertyMapping['property_id'], $hotelExcludeList[$countryCode])) {
continue;
}
}
$hotelList[] = [
'partner_reference' => $propertyMapping['property']['id'],
'locale' => $countryCode,
'campaign' => $campaignId
];
}
}
}
}
}
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
}
$out = "";
foreach ($hotelList as $hotel) {
$out .= implode(",", $hotel) . PHP_EOL;
}
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=Extranetwork-Campaign.csv");
header('Pragma: no-cache');
header("Expires: 0");
echo $out;
die();
//return response()->json($hotelList);
}
public function cpa(Request $request)
{
$cpaList[] = [
'locale' => 'locale',
'campaign' => 'campaign',
'cpa_value' => 'cpa_value'
];
try {
foreach ($this->CPA as $countryCode => $countryValue) {
foreach ($countryValue as $campaignId => $campaignValue) {
$cpaList[] = [
'locale' => $countryCode,
'campaign' => $campaignId,
'cpa_value' => $campaignValue
];
}
}
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
}
$out = "";
foreach ($cpaList as $cpa) {
$out .= implode(",", $cpa) . PHP_EOL;
}
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=Extranetwork-CPA.csv");
header('Pragma: no-cache');
header("Expires: 0");
echo $out;
die();
//return response()->json($hotelList);
}
}

View File

@@ -0,0 +1,884 @@
<?php
namespace App\Http\Controllers\MetaSearch\Trivago\v1;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyChannelCouponService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use App\Models\PropertyChannel;
use App\Models\PropertyContact;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Exception;
class TrivagoController extends Controller
{
private $username;
private $password;
private $authorization;
private $channelManagerId;
private $channelManagerLogId;
private $mealCodeMapping;
private $paymentTypeMapping;
private $countryCodeCampaign;
public function __construct(
Request $request,
CurrencyService $currencyService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
PropertyChannelCouponService $propertyChannelCouponService
)
{
$this->username = 'trivago';
$this->password = 'P8MUQtNP6TkKMz3E';
$this->channelManagerId = 11;//Trivago
$this->request = $request;
$this->currencyService = $currencyService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->propertyChannelCouponService = $propertyChannelCouponService;
$payload = $this->request->getContent();
parse_str(urldecode($payload), $payloadDecode);
$this->param = $payloadDecode;
$this->authorization = $request->header('authorization');
$this->tax = 10;
$this->cityTax = 2;
$this->mealCodeMapping = [
10 => 'AI',
11 => 'BB',
13 => 'RO',
14 => 'FB',
15 => 'HB',
];
$this->paymentTypeMapping = [
'CRD' => 'prepaid',
'HTL' => 'postpaid'
];
$this->CPA['TR'] = ["1" => 9.60, "2" => 10.80, "3" => 11.00, "4" => 11.20, "5" => 11.40, "6" => 11.60, "7" => 11.80, "8" => 12.00];
$this->CPA['DE'] = ["1" => 10.80, "2" => 11.00, "3" => 11.20, "4" => 11.40, "5" => 11.60, "6" => 11.80, "7" => 12.00, "8" => 12.20];
$this->CPA['UK'] = ["1" => 10.80, "2" => 11.00, "3" => 11.20, "4" => 11.40, "5" => 11.60, "6" => 11.80, "7" => 12.00, "8" => 12.20];
$this->CPA['US'] = ["1" => 10.80, "2" => 11.00, "3" => 11.20, "4" => 11.40, "5" => 11.60, "6" => 11.80, "7" => 12.00, "8" => 12.20];
$this->countryCodeCampaign = [
'DE' => [
'code' => 'DE',
'campaignCode' => 7
],
'TR' => [
'code' => 'TR',
'campaignCode' => 8
],
'US' => [
'code' => 'US',
'campaignCode' => 7
],
'UK' => [
'code' => 'UK',
'campaignCode' => 7
]
];
}
public function checkAuthentication($authorization)
{
$response = ['status' => false, 'message' => ''];
$basicAuth = 'Basic ' . base64_encode($this->username . ':' . $this->password);
if ($authorization != $basicAuth) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function requestParamConverter($requestParam = [])
{
$searchRequestJson = [];
$searchRequestJson['date']['checkIn'] = Carbon::parse($requestParam['start_date'])->toDateString();
$searchRequestJson['date']['checkOut'] = Carbon::parse($requestParam['end_date'])->toDateString();
$rooms = [];
for ($i = 0; $i < $requestParam['num_rooms']; $i++) {
$roomCounter = ($i + 1);
if (isset($requestParam['room_adults_' . $roomCounter])) {
$rooms[$i]['adults'] = $requestParam['room_adults_' . $roomCounter];
}
$rooms[$i]['children'] = 0;
$rooms[$i]['age'] = null;
if (isset($requestParam['room_childs_' . $roomCounter])) {
$childAges = json_decode($requestParam['room_childs_' . $roomCounter]);
$rooms[$i]['children'] = count($childAges);
$rooms[$i]['age'] = $childAges;
}
}
$searchRequestJson['rooms'] = $rooms;
$searchRequestJson['property'] = json_decode($requestParam['hotels']);
return $searchRequestJson;
}
public function roomOccupancy($requestParam)
{
$roomOccupancy = [];
foreach ($requestParam as $room) {
$adults = str_repeat('A', $room['adults']);
$children = [];
if ($room['children'] > 0 && !empty($room['age'])) {
foreach ($room['age'] as $child) {
$children[] = 'C' . $child;
}
}
$roomOccupancy[] = $adults . implode('', $children);
}
return $roomOccupancy;
}
public function deepLinkGenerator($token, $requestParam = [])
{
$deepLink = 'https://be.extranetwork.com/' . $token . '/en/search/';
$deepLink .= Carbon::parse($requestParam['date']['checkIn'])->format('Ymd') . '/';
$deepLink .= Carbon::parse($requestParam['date']['checkOut'])->format('Ymd') . '/';
$roomOccupancy = $this->roomOccupancy($requestParam['rooms']);
$deepLink .= implode(',', $roomOccupancy);;
$deepLink .= '?utm_medium=trivago&utm_source=trivago&locale=' . $requestParam['locale'];
return $deepLink;
}
public function couponCodeCheck($propertyId, $checkIn, $checkOut)
{
//$propertyChannelCoupon
$propertyChannelCouponsCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_id', 'condition' => '=', 'value' => 1],
['field' => 'start_date', 'condition' => '<=', 'value' => Carbon::now()->toDateString()],
['field' => 'end_date', 'condition' => '>=', 'value' => Carbon::now()->toDateString()],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'orderBy' => [
['field' => 'id', 'value' => 'DESC']
],
];
$propertyChannelCoupons = $this->propertyChannelCouponService->select($propertyChannelCouponsCriteria);
if ($propertyChannelCoupons['status'] == 'success') {
$propertyChannelCoupons = $propertyChannelCoupons['data'];
foreach ($propertyChannelCoupons as $propertyChannelCouponKey => $propertyChannelCouponData) {
//Reservation Date Check
if (!is_null($propertyChannelCouponData['reservation_start_date']) && !is_null($propertyChannelCouponData['reservation_end_date'])) {
$reservationDateCheck = Carbon::parse($propertyChannelCouponData['reservation_start_date'])->lessThanOrEqualTo(Carbon::parse($checkIn))
&& Carbon::parse($propertyChannelCouponData['reservation_end_date'])->greaterThanOrEqualTo(Carbon::parse($checkOut));
if (!$reservationDateCheck) {
unset($propertyChannelCoupons[$propertyChannelCouponKey]);
}
}
}
} else {
$propertyChannelCoupons = [];
}
$propertyChannelCoupon = !empty($propertyChannelCoupons) ? reset($propertyChannelCoupons) : null;
return $propertyChannelCoupon;
}
public function availability(Request $request)
{
$response = ['status' => true, 'message' => ''];
$checkAuthentication = $this->checkAuthentication($this->authorization);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$searchController = App::make("App\Http\Controllers\BookingEngine\V1\SearchController");
$requestTime = microtime(true);
$hotelList['root'] = $this->param;
unset($hotelList['root']['hotels']);
$hotelList['root']['hotel_ids'] = json_decode($this->param['hotels']);
$hotelList['root']['hotels'] = [];
$hotelList['root']['api_version'] = (integer)$hotelList['root']['api_version'];
$hotelList['root']['num_rooms'] = (integer)$hotelList['root']['num_rooms'];
for ($i = 0; $i < $hotelList['root']['num_rooms']; $i++) {
$roomCounter = ($i + 1);
if (isset($hotelList['root']['room_adults_' . $roomCounter])) {
$hotelList['root']['room_adults_' . $roomCounter] = (integer)$hotelList['root']['room_adults_' . $roomCounter];
}
}
$requestCurrency = $this->param['currency'];
try {
//Hotels Check
$channelManagerPropertyList = [];
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyList = pickItemFromArray('property_id', $channelManagerPropertyMapping['data']);
}
$availableHotelIds = array_intersect($hotelList['root']['hotel_ids'], $channelManagerPropertyList);
if (empty($availableHotelIds)) {
throw new ApiErrorException('Hotel not found');
}
$this->param['hotels'] = json_encode($availableHotelIds);
//Hotels Check
$searchRequestJson = $this->requestParamConverter($this->param);
$searchRequestJson['ipAddress'] = $request->getClientIp();
$searchRequestJson['isMobile'] = null;
$searchRequestJson['noneCacheSearch'] = true;
$searchRequestJson['ipAddress'] = $request->getClientIp();
$searchRequestJson['justPriceValues'] = true;
$cacheKeyParam = $this->param;
unset($cacheKeyParam['currency']);
unset($cacheKeyParam['rate_model']);
unset($cacheKeyParam['lang']);
$cacheKey = 'TRV:' . md5(implode(',', $cacheKeyParam));
//Cache::forget($cacheKey);
if (Cache::has($cacheKey)) {
$search = Cache::get($cacheKey);
} else {
$requestCreate = Request::create(null, null, [], [], [], [], json_encode($searchRequestJson));
$requestCreate->headers->set('channelId', '1');
//$requestCreate->headers->set('bookingEnginePropertyId', null);
$requestCreate->headers->set('channelToken', 'ece3ef02-42e7-92b7-f379-08226ed7a0f3');//TODO: from DB
$requestCreate->headers->set('bookingEngineToken', null);
$search = $searchController->search($requestCreate);
Cache::put($cacheKey, $search, 60 * 60);//1 Day 24 * 60 * 60
}
$search = json_decode(json_encode($search), 1);
if ($search['original']['status'] != 200) {
throw new ApiErrorException('Hotel not found');
}
$properties = $search['original']['data']['properties'];
if (empty($properties)) {
throw new ApiErrorException('Hotel not found');
}
$hotelCounter = 0;
$numberOfStay = Carbon::parse($searchRequestJson['date']['checkIn'])->diffInDays(Carbon::parse($searchRequestJson['date']['checkOut']));
foreach ($properties as $propertyId => $property) {
if (!isset($property['currency'])) {
continue;
}
$currencyExchangeRate = 1;
if ($requestCurrency != $property['currency']) {
$currencyExchangeRate = $this->currencyService->lastExchangeRate($property['currency'], $requestCurrency);
if ($currencyExchangeRate['status'] == 'success') {
$currencyExchangeRate = $currencyExchangeRate['data'];
}
}
$languageLocale = explode('_', $this->param['lang'], 2);
$searchRequestJson['locale'] = $languageLocale[1];
$token = $property['booking_engine_token'];
$deepLinkGenerator = $this->deepLinkGenerator($token, $searchRequestJson);
$property = reset($property['availabilities']);
$propertyRooms = $property['rooms'];
//Standard Room Room Only FreeCancellation - Pay at Hotel
$requestedRoomPriceGroup = [];
foreach ($propertyRooms as $propertyRoomId => $propertyRoom) {
foreach ($propertyRoom['rates'] as $propertyRoomRateId => $propertyRoomRate) {
foreach ($propertyRoomRate['requestedRoomPrice'] as $occupancyCode => $requestedRoomPrices) {
foreach ($requestedRoomPrices['prices'] as $requestedRoomPriceKey => $requestedRoomPrice) {
$roomRateKeyName = $occupancyCode . ' ' . $requestedRoomPrice['room']['name'] . ' ' . $requestedRoomPrice['rate']['boardName'] . ' ' . $requestedRoomPrice['name'];
$roomRateKeycode = $requestedRoomPrice['rate']['accommodationCode'] . '|' . (isset($requestedRoomPrice['cancellationPolicy']['id']) ? $requestedRoomPrice['cancellationPolicy']['id'] : 0) . '|' . $requestedRoomPrice['bookingPaymentType']['code'];
//$requestedRoomPriceGroup[$roomRateKeycode][$occupancyCode][] = $roomRateKeyName . '-' . $requestedRoomPrice['rateKeyCode'];
$requestedRoomPrice['dailyAverageDiscount'] = $requestedRoomPrices['dailyAverageDiscount'];
$requestedRoomPriceGroup[$roomRateKeycode][$occupancyCode][] = $requestedRoomPrice;
}
}
}
}
$roomOccupancy = $this->roomOccupancy($searchRequestJson['rooms']);
$roomRateBoardGroup = [];
foreach ($requestedRoomPriceGroup as $groupKey => $groupValue) {
$counter = 0;
foreach ($groupValue as $groupValueOccupancyCode => $groupValueOccupancy) {
foreach ($groupValueOccupancy as $groupValueOccupancyCodeX => $groupValueOccupancyVal) {
foreach ($roomOccupancy as $occupancyOrder => $occupancy) {
$occupancyCheckKey = $occupancy . '-' . $occupancyOrder;
if ($groupValueOccupancyCode == $occupancy && !isset($roomRateBoardGroup[$groupKey][$counter][$occupancyCheckKey])) {
$roomRateBoardGroup[$groupKey][$counter][$occupancyCheckKey] = $groupValueOccupancyVal;
if (count($roomRateBoardGroup[$groupKey][$counter]) == count($roomOccupancy)) {
$counter++;
}
}
}
}
}
}
$roomRateTypes = [];
foreach ($roomRateBoardGroup as $boardGroups) {
foreach ($boardGroups as $boardGroups) {
$roomRateTypesGroup = [];
foreach ($boardGroups as $requestedRoomPrice) {
$roomRateKeyName = $requestedRoomPrice['room']['name'] . ' ' . $requestedRoomPrice['rate']['boardName'] . ' ' . $requestedRoomPrice['name'];
$total = $requestedRoomPrice['total'];
$totalBeforeDiscount = $requestedRoomPrice['total'];
$totalBeforeDiscountDailyAverage = ($totalBeforeDiscount / $numberOfStay);
$discounts = [];
if ($requestedRoomPrice['dailyAverageDiscount'] > 0) {
$totalBeforeDiscount = ($total / (100 - (double)$requestedRoomPrice['dailyAverageDiscount'])) * 100;
$totalBeforeDiscountDailyAverage = ($totalBeforeDiscount / $numberOfStay);
$totalDiscount = $totalBeforeDiscount - $total;
$dailyDiscountAverage = ($totalDiscount / $numberOfStay);
$netRate = $dailyDiscountAverage / (1 + ($this->tax / 100) + ($this->cityTax / 100));
$vat = $netRate * ($this->tax / 100);
$localTax = $netRate * ($this->cityTax / 100);
$finalRateDiscount = moneyDoubleFormatDecimal($localTax * $currencyExchangeRate) + moneyDoubleFormatDecimal($netRate * $currencyExchangeRate) + moneyDoubleFormatDecimal($vat * $currencyExchangeRate);
$discounts[] = [
'booking_fee' => 0,
'final_rate' => moneyDoubleFormatDecimal($finalRateDiscount), //moneyDoubleFormatDecimal($dailyDiscountAverage * $currencyExchangeRate),
'hotel_fee' => 0,
'local_tax' => moneyDoubleFormatDecimal($localTax * $currencyExchangeRate),
'marketing_text' => $requestedRoomPrice['dailyAverageDiscount'] . '% Special Discount',
'net_rate' => moneyDoubleFormatDecimal($netRate * $currencyExchangeRate),
'resort_fee' => 0,
'service_charge' => 0,
'vat' => moneyDoubleFormatDecimal($vat * $currencyExchangeRate),
];
}
$netRate = $totalBeforeDiscountDailyAverage / (1 + ($this->tax / 100) + ($this->cityTax / 100));
$vat = $netRate * ($this->tax / 100);
$localTax = $netRate * ($this->cityTax / 100);
$finalRate = moneyDoubleFormatDecimal($localTax * $currencyExchangeRate) + moneyDoubleFormatDecimal($netRate * $currencyExchangeRate) + moneyDoubleFormatDecimal($vat * $currencyExchangeRate);
$roomRateTypesGroup[][$roomRateKeyName] = [
'booking_fee' => 0,
'breakfast_included' => in_array($requestedRoomPrice['rate']['accommodationCode'], [10, 11, 14, 15]) ? true : false,
'currency' => $requestCurrency,
'discounts' => $discounts,
'final_rate' => moneyDoubleFormatDecimal($finalRate),//moneyDoubleFormatDecimal($totalBeforeDiscountDailyAverage * $currencyExchangeRate),
'free_cancellation' => $requestedRoomPrice['cancellationPolicy']['isFreeCancellation'] ? true : false,
//'free_cancellation_deadline' => '2018-04-25T16:00:00+00:00',
'hotel_fee' => 0,
'local_tax' => moneyDoubleFormatDecimal($localTax * $currencyExchangeRate),
'meal_code' => isset($this->mealCodeMapping[$requestedRoomPrice['rate']['accommodationCode']]) ? $this->mealCodeMapping[$requestedRoomPrice['rate']['accommodationCode']] : 'RO',
'net_rate' => moneyDoubleFormatDecimal($netRate * $currencyExchangeRate),
'payment_type' => isset($this->paymentTypeMapping[$requestedRoomPrice['bookingPaymentType']['code']]) ? $this->paymentTypeMapping[$requestedRoomPrice['bookingPaymentType']['code']] : 'postpaid',
'resort_fee' => 0,
'room_code' => $requestedRoomPrice['room']['name'],
'service_charge' => 0,
'url' => $deepLinkGenerator,
//'mobileURL' => null',
'vat' => moneyDoubleFormatDecimal($vat * $currencyExchangeRate),
'rate_type' => 'DEFAULT',
//'rateKeyCode' => $requestedRoomPrice['rateKeyCode'],
//'dailyAverageDiscount' => $requestedRoomPrice['dailyAverageDiscount'],
];
}
$roomRateTypes[] = $roomRateTypesGroup;
}
}
if (!empty($roomRateTypes)) {
//if (in_array($propertyId, [1275,1325])) {
$propertyCouponCodeCheck = $this->couponCodeCheck($propertyId, $searchRequestJson['date']['checkIn'], $searchRequestJson['date']['checkOut']);
if (!empty($propertyCouponCodeCheck)) {
$roomRateTypesWithCoupon = [];
foreach ($roomRateTypes as $roomRateTypeKey => $roomRateType) {
foreach ($roomRateType as $roomRateTypeDetailKey => $roomRateTypeDetails) {
//dd($roomRateTypeKey, $roomRateTypeDetailKey, $propertyCouponCodeCheck, $roomRateTypeDetail, key($roomRateTypeDetail));
$roomRateTypeDetail = reset($roomRateTypeDetails);
$couponPercentageValue = (100 - $propertyCouponCodeCheck['value']) / 100;
$finalRateDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('final_rate');
$localTaxDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('local_tax');
$netRateDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('net_rate');
$vatDiscountBeforeReward = collect($roomRateTypeDetail['discounts'])->sum('vat');
$finalRateDiscountReward = ($roomRateTypeDetail['final_rate'] - $finalRateDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$localTaxDiscountReward = ($roomRateTypeDetail['local_tax'] - $localTaxDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$netRateDiscountReward = ($roomRateTypeDetail['net_rate'] - $netRateDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$vatDiscountReward = ($roomRateTypeDetail['vat'] - $vatDiscountBeforeReward) * $propertyCouponCodeCheck['value'] / 100;
$discountReward = [
'booking_fee' => 0,
'final_rate' => moneyDoubleFormatDecimal($finalRateDiscountBeforeReward + $finalRateDiscountReward),
'hotel_fee' => 0,
'local_tax' => moneyDoubleFormatDecimal($localTaxDiscountBeforeReward + $localTaxDiscountReward),
'marketing_text' => 'Special REWARD Discount',
'net_rate' => moneyDoubleFormatDecimal($netRateDiscountBeforeReward + $netRateDiscountReward),
'resort_fee' => 0,
'service_charge' => 0,
'vat' => moneyDoubleFormatDecimal($vatDiscountBeforeReward + $vatDiscountReward),
];
/*foreach ($roomRateTypeDetail['discounts'] as $discountKey => $discount) {
$discount['vat'] = moneyDoubleFormatDecimal($discount['vat'] * $couponPercentageValue);
$discount['net_rate'] = moneyDoubleFormatDecimal($discount['net_rate'] * $couponPercentageValue);
$discount['local_tax'] = moneyDoubleFormatDecimal($discount['local_tax'] * $couponPercentageValue);
$discount['final_rate'] = moneyDoubleFormatDecimal($discount['net_rate'] + $discount['vat'] + $discount['local_tax']);
$roomRateTypeDetail['discounts'][$discountKey] = $discount;
}
$roomRateTypeDetail['vat'] = moneyDoubleFormatDecimal($roomRateTypeDetail['vat'] * $couponPercentageValue);
$roomRateTypeDetail['net_rate'] = moneyDoubleFormatDecimal($roomRateTypeDetail['net_rate'] * $couponPercentageValue);
$roomRateTypeDetail['local_tax'] = moneyDoubleFormatDecimal($roomRateTypeDetail['local_tax'] * $couponPercentageValue);
$roomRateTypeDetail['final_rate'] = moneyDoubleFormatDecimal($roomRateTypeDetail['net_rate'] + $roomRateTypeDetail['vat'] + $roomRateTypeDetail['local_tax']);*/
unset($roomRateTypeDetail['discounts']);
$roomRateTypeDetail['discounts'][] = $discountReward;
$roomRateTypeDetail['rate_type'] = 'REWARD';
$roomRateTypesWithCoupon[$roomRateTypeKey][$roomRateTypeDetailKey][key($roomRateTypeDetails)] = $roomRateTypeDetail;
}
}
$roomRateTypes = array_merge($roomRateTypes, $roomRateTypesWithCoupon);
}
//}
$hotelList['root']['hotels'][$hotelCounter] = [
'hotel_id' => $propertyId,
'room_types' => $roomRateTypes
];
$hotelCounter++;
}
}
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
$hotelList['root']['hotels'] = [];
}
$responseTime = microtime(true) - $requestTime;
//Log::debug(json_encode($this->param) . ' - Response Time: ' . number_format($responseTime, 2) . ' - Status: ' . count($hotelList['root']['hotels']));
return response()->json($hotelList);
}
public function hotel(Request $request)
{
$response = ['status' => true, 'message' => ''];
$hotelList = [];
$hotelList['api_version'] = 4;
$hotelList['lang'] = 'en_GB';
$hotelList['hotels'] = [];
try {
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMappingCriteria['with'] = [
'property.propertyType', 'property.propertyContact', 'property.propertyWeb', 'property.country'
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
if ($propertyMapping['status'] != 1) {
continue;
}
$metaAddress = json_decode($propertyMapping['property']['property_contact']['meta'], 1);
$hotelList['hotels'][] = [
'partner_reference' => $propertyMapping['property']['id'],
'name' => $propertyMapping['property']['name'],
'street' => fillOnUndefined($metaAddress, 'street'),
'city' => fillOnUndefined($metaAddress, 'city'),
'postal_code' => fillOnUndefined($metaAddress, 'zip_code'),
//'state' => null,
'country' => $propertyMapping['property']['country']['name'],
'latitude' => $propertyMapping['property']['property_contact']['latitude'],
'longitude' => $propertyMapping['property']['property_contact']['longitude'],
'desc' => $propertyMapping['property']['name'],
'amenities' => null,//['Beauty Center', 'Business Center', 'Café/ Bistro', 'Sauna'],
'url' => $propertyMapping['property']['property_web']['webProtocolUrl'],
'email' => $propertyMapping['property']['property_contact']['email'],
'phone' => $propertyMapping['property']['property_contact']['phone'],
'fax' => $propertyMapping['property']['property_contact']['fax']
];
//dd(json_decode($propertyMapping['property']['property_contact']['meta'],1));
$addressExplode = explode('/', $propertyMapping['property']['property_contact']['address'], 2);
$street = isset($addressExplode[0]) ? $addressExplode[0] : $propertyMapping['property']['property_contact']['address'];
$cityExplode = isset($addressExplode[1]) ? explode(',', $addressExplode[1]) : (isset($addressExplode[0]) ? explode(',', $addressExplode[0]) : null);
$city = isset($cityExplode[0]) ? $cityExplode[0] : null;
$streetExplode = explode(', ', $street);
unset($streetExplode[count($streetExplode) - 1]);
$street = implode(', ', $streetExplode);
$metaUpdate = [
'street' => $street,
'city' => $city,
'zip_code' => $propertyMapping['property']['property_contact']['zip_code'],
];
if (empty($propertyMapping['property']['property_contact']['meta'])) {
PropertyContact::where('id', $propertyMapping['property']['property_contact']['id'])->update(['meta' => json_encode($metaUpdate)]);
}
//dd($propertyMapping['property']['property_contact']['id'],$metaUpdate);
}
}
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
if (!$response['status']) {
$hotelList['root']['hotels'] = [];
}
return response()->json($hotelList);
}
public function campaign(Request $request)
{
$hotelList = [];
$hotelExcludeList = [];
$hotelExcludeList['TR'] = [721, 729];
try {
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMappingCriteria['with'] = [
'property.propertyType', 'property.propertyContact', 'property.propertyWeb', 'property.country'
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$hotelList[] = [
'partner_reference' => 'partner_reference',
'locale' => 'locale',
'campaign' => 'campaign'
];
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
foreach ($this->CPA as $countryCode => $countryValue) {
foreach ($countryValue as $campaignId => $campaignValue) {
if (isset($this->countryCodeCampaign[$countryCode]) && $this->countryCodeCampaign[$countryCode]['campaignCode'] == $campaignId) {
if (isset($hotelExcludeList[$countryCode])) {
if (in_array($propertyMapping['property_id'], $hotelExcludeList[$countryCode])) {
continue;
}
}
$hotelList[] = [
'partner_reference' => $propertyMapping['property']['id'],
'locale' => $countryCode,
'campaign' => $campaignId
];
}
}
}
}
}
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
}
$out = "";
foreach ($hotelList as $hotel) {
$out .= implode(",", $hotel) . PHP_EOL;
}
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=Extranetwork-Campaign.csv");
header('Pragma: no-cache');
header("Expires: 0");
echo $out;
die();
//return response()->json($hotelList);
}
public function cpa(Request $request)
{
$cpaList[] = [
'locale' => 'locale',
'campaign' => 'campaign',
'cpa_value' => 'cpa_value'
];
try {
foreach ($this->CPA as $countryCode => $countryValue) {
foreach ($countryValue as $campaignId => $campaignValue) {
$cpaList[] = [
'locale' => $countryCode,
'campaign' => $campaignId,
'cpa_value' => $campaignValue
];
}
}
} catch (ApiErrorException | Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
}
$out = "";
foreach ($cpaList as $cpa) {
$out .= implode(",", $cpa) . PHP_EOL;
}
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=Extranetwork-CPA.csv");
header('Pragma: no-cache');
header("Expires: 0");
echo $out;
die();
//return response()->json($hotelList);
}
}

View File

@@ -0,0 +1,541 @@
<?php
namespace App\Http\Controllers\MetaSearch\Yandex\v1;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyChannelCouponService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use App\Models\PropertyChannel;
use App\Models\PropertyContact;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Exception;
class YandexController extends Controller
{
private $username;
private $password;
private $authorization;
private $channelManagerId;
private $channelManagerLogId;
private $mealCodeMapping;
private $paymentTypeMapping;
private $countryCodeCampaign;
public function __construct(
Request $request,
CurrencyService $currencyService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
PropertyChannelCouponService $propertyChannelCouponService
)
{
$this->username = 'yandex';
$this->password = 'P8MUQtNP6TkKMz3E';
$this->channelManagerId = 13;//Yandex
$this->request = $request;
$this->currencyService = $currencyService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->propertyChannelCouponService = $propertyChannelCouponService;
$payload = $this->request->getContent();
parse_str(urldecode($payload), $payloadDecode);
$this->param = $payloadDecode;
$this->authorization = $request->header('authorization');
$this->tax = 10;
$this->mealCodeMapping = [
10 => 'AI',
11 => 'BB',
13 => 'RO',
14 => 'FB',
15 => 'HB',
];
$this->paymentTypeMapping = [
'CRD' => 'prepaid',
'HTL' => 'postpaid'
];
}
public function checkAuthentication($authorization)
{
$response = ['status' => false, 'message' => ''];
$basicAuth = 'Basic ' . base64_encode($this->username . ':' . $this->password);
if ($authorization != $basicAuth) {
$response['message'] = 'Your username or password is incorrect.';
} else {
$response['status'] = true;
}
return $response;
}
public function responseError($errorMessage)
{
$response = [
'status' => false,
'message' => $errorMessage,
];
//channelManagerLogService
if (!is_null($this->channelManagerLogId)) {
$updateDataLog = [
'response' => json_encode($response),
'status' => 0
];
if (!is_null($this->channelManagerRequestTime)) {
$updateDataLog['response_time'] = microtime(true) - $this->channelManagerRequestTime;
}
$channelManagerLog = $this->channelManagerLogService->update($this->channelManagerLogId, $updateDataLog);
}
//channelManagerLogService
return response()->json($response);
}
public function requestParamConverter($requestParam = [])
{
$searchRequestJson = [];
$searchRequestJson['date']['checkIn'] = Carbon::parse($requestParam['Checkin'])->toDateString();
$searchRequestJson['date']['checkOut'] = Carbon::parse($requestParam['Checkin'])->addDays($requestParam['Nights'])->toDateString();
$rooms = [];
$rooms[0]['adults'] = (integer)$requestParam['Context']['OccupancyDetails']['NumAdults'];
$rooms[0]['children'] = (integer)($requestParam['Context']['Occupancy'] - $requestParam['Context']['OccupancyDetails']['NumAdults']);
$rooms[0]['age'] = [];
if (isset($requestParam['Context']['OccupancyDetails']['Children']['Child'])) {
$requestParam['Context']['OccupancyDetails']['Children']['Child'] = singleElementXMLArray($requestParam['Context']['OccupancyDetails']['Children']['Child']);
} else {
$requestParam['Context']['OccupancyDetails']['Children']['Child'] = [];
}
foreach ($requestParam['Context']['OccupancyDetails']['Children']['Child'] as $child) {
$rooms[0]['age'][] = $child['@attributes']['age'];
}
$searchRequestJson['rooms'] = $rooms;
if (isset($requestParam['PropertyList']['Property'])) {
$requestParam['PropertyList']['Property'] = singleElementXMLArray($requestParam['PropertyList']['Property']);
} else {
$requestParam['PropertyList']['Property'] = [];
}
$searchRequestJson['property'] = $requestParam['PropertyList']['Property'];
return $searchRequestJson;
}
public function roomOccupancy($requestParam)
{
$roomOccupancy = [];
foreach ($requestParam as $room) {
$adults = str_repeat('A', $room['adults']);
$children = [];
if ($room['children'] > 0 && !empty($room['age'])) {
foreach ($room['age'] as $child) {
$children[] = 'C' . $child;
}
}
$roomOccupancy[] = $adults . implode('', $children);
}
return $roomOccupancy;
}
public function deepLinkGenerator($token, $requestParam = [])
{
$deepLink = 'https://be.extranetwork.com/' . $token . '/' . fillOnUndefined($requestParam, 'locale', 'en') . '/search/';
$deepLink .= Carbon::parse($requestParam['date']['checkIn'])->format('Ymd') . '/';
$deepLink .= Carbon::parse($requestParam['date']['checkOut'])->format('Ymd') . '/';
$roomOccupancy = $this->roomOccupancy($requestParam['rooms']);
$deepLink .= implode(',', $roomOccupancy);;
$deepLink .= '?utm_source=yandex';
return $deepLink;
}
public function couponCodeCheck($propertyId, $checkIn, $checkOut)
{
//$propertyChannelCoupon
$propertyChannelCouponsCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_id', 'condition' => '=', 'value' => 1],
['field' => 'start_date', 'condition' => '<=', 'value' => Carbon::now()->toDateString()],
['field' => 'end_date', 'condition' => '>=', 'value' => Carbon::now()->toDateString()],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'orderBy' => [
['field' => 'id', 'value' => 'DESC']
],
];
$propertyChannelCoupons = $this->propertyChannelCouponService->select($propertyChannelCouponsCriteria);
if ($propertyChannelCoupons['status'] == 'success') {
$propertyChannelCoupons = $propertyChannelCoupons['data'];
foreach ($propertyChannelCoupons as $propertyChannelCouponKey => $propertyChannelCouponData) {
//Reservation Date Check
if (!is_null($propertyChannelCouponData['reservation_start_date']) && !is_null($propertyChannelCouponData['reservation_end_date'])) {
$reservationDateCheck = Carbon::parse($propertyChannelCouponData['reservation_start_date'])->lessThanOrEqualTo(Carbon::parse($checkIn))
&& Carbon::parse($propertyChannelCouponData['reservation_end_date'])->greaterThanOrEqualTo(Carbon::parse($checkOut));
if (!$reservationDateCheck) {
unset($propertyChannelCoupons[$propertyChannelCouponKey]);
}
}
}
} else {
$propertyChannelCoupons = [];
}
$propertyChannelCoupon = !empty($propertyChannelCoupons) ? reset($propertyChannelCoupons) : null;
return $propertyChannelCoupon;
}
public function hotel(Request $request)
{
$response = ['status' => true, 'message' => ''];
$listings = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><listings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.gstatic.com/localfeed/local_feed.xsd"></listings>');
$listings->addChild('language', 'tr');
try {
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMappingCriteria['with'] = [
'property.propertyType', 'property.propertyContact', 'property.propertyWeb', 'property.country'
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $propertyMapping) {
if ($propertyMapping['status'] != 1) {
continue;
}
$metaAddress = json_decode($propertyMapping['property']['property_contact']['meta'], 1);
$listing = $listings->addChild('listing');
$listing->addChild('id', $propertyMapping['property']['id']);
$listing->addChild('name', htmlspecialchars($propertyMapping['property']['name'], ENT_XML1, 'UTF-8'));
$address = $listing->addChild('address');
$address->addAttribute('format', 'simple');
$component = $address->addChild('component', htmlspecialchars(fillOnUndefined($metaAddress, 'street'), ENT_XML1, 'UTF-8'));
$component->addAttribute('name', 'addr1');
//$component = $address->addChild('component');
//$component->addAttribute('name', 'addr2');
$component = $address->addChild('component', fillOnUndefined($metaAddress, 'city'));
$component->addAttribute('name', 'city');
//$component = $address->addChild('component', $propertyMapping['property']['country']['name']);
//$component->addAttribute('name','region');
$component = $address->addChild('component', fillOnUndefined($metaAddress, 'zip_code'));
$component->addAttribute('name', 'postal_code');
$listing->addChild('country', $propertyMapping['property']['country']['country_code']);
$listing->addChild('latitude', $propertyMapping['property']['property_contact']['latitude']);
$listing->addChild('longitude', $propertyMapping['property']['property_contact']['longitude']);
$listing->addChild('category', 'hotel');
}
}
} 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();
}
header('Content-Type: application/xml; charset=UTF-8');
echo $listings->asXML();
exit;
}
public function availability(Request $request)
{
$response = ['status' => true, 'message' => ''];
$checkAuthentication = $this->checkAuthentication($this->authorization);
if (!$checkAuthentication['status']) {
return $this->responseError($checkAuthentication['message']);
}
$searchController = App::make("App\Http\Controllers\BookingEngine\V1\SearchController");
$requestTime = microtime(true);
$param = $this->request->getContent();
$paramXML = simplexml_load_string($param);
$requestParam = json_decode(json_encode($paramXML), 1);
$hotelIdList = collect($requestParam['PropertyList']['Property'])->values();
$hotelIdList = $hotelIdList ? $hotelIdList->toArray() : [];
$transaction = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Transaction></Transaction>');
try {
//Hotels Check
$channelManagerPropertyList = [];
$channelManagerPropertyMappingCriteria['criteria'] = [
['field' => 'channel_manager_id', 'condition' => '=', 'value' => $this->channelManagerId],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
$channelManagerPropertyList = pickItemFromArray('property_id', $channelManagerPropertyMapping['data']);
}
$availableHotelIds = array_intersect($hotelIdList, $channelManagerPropertyList);
if (empty($availableHotelIds)) {
throw new ApiErrorException('Hotel not found');
}
//Hotels Check
$searchRequestJson = $this->requestParamConverter($requestParam);
$searchRequestJson['isMobile'] = null;
$searchRequestJson['noneCacheSearch'] = true;
$searchRequestJson['ipAddress'] = $request->getClientIp();
$searchRequestJson['justPriceValues'] = true;
$searchRequestJson['locale'] = fillOnUndefined($requestParam, 'Locale') ?? 'tr';
$roomOccupancy = $this->roomOccupancy($searchRequestJson['rooms']);
$roomOccupancy = implode(',', $roomOccupancy);
$requestCurrency = fillOnUndefined($requestParam, 'Currency') ?? 'TRY';
$cacheKeyParam = $requestCurrency . ':' . $searchRequestJson['date']['checkIn'] . ':' . $searchRequestJson['date']['checkOut'] . ':' . implode(',', $searchRequestJson['property']) . ':' . $roomOccupancy;
$cacheKey = 'YND:' . md5($cacheKeyParam);
//Cache::forget($cacheKey);
if (Cache::has($cacheKey)) {
$search = Cache::get($cacheKey);
} else {
$requestCreate = Request::create(null, null, [], [], [], [], json_encode($searchRequestJson));
$requestCreate->headers->set('channelId', '1');
//$requestCreate->headers->set('bookingEnginePropertyId', null);
$requestCreate->headers->set('channelToken', 'ece3ef02-42e7-92b7-f379-08226ed7a0f3');//TODO: from DB
$requestCreate->headers->set('bookingEngineToken', null);
$search = $searchController->search($requestCreate);
Cache::put($cacheKey, $search, 60 * 60);//1 Day 24 * 60 * 60
}
$search = json_decode(json_encode($search), 1);
if ($search['original']['status'] != 200) {
throw new ApiErrorException('Hotel not found');
}
$properties = $search['original']['data']['properties'];
if (empty($properties)) {
throw new ApiErrorException('Hotel not found');
}
$hotelCounter = 0;
$numberOfStay = Carbon::parse($searchRequestJson['date']['checkIn'])->diffInDays(Carbon::parse($searchRequestJson['date']['checkOut']));
foreach ($properties as $propertyId => $property) {
$propertyName = $property['name'];
if (!isset($property['currency'])) {
continue;
}
$currencyExchangeRate = 1;
if ($requestCurrency != $property['currency']) {
$currencyExchangeRate = $this->currencyService->lastExchangeRate($property['currency'], $requestCurrency);
if ($currencyExchangeRate['status'] == 'success') {
$currencyExchangeRate = $currencyExchangeRate['data'];
}
}
$token = $property['booking_engine_token'];
$deepLinkGenerator = $this->deepLinkGenerator($token, $searchRequestJson);
$property = reset($property['availabilities']);
$propertyRooms = $property['rooms'];
//Standard Room Room Only FreeCancellation - Pay at Hotel
$requestedRoomPriceGroup = [];
foreach ($propertyRooms as $propertyRoomId => $propertyRoom) {
foreach ($propertyRoom['rates'] as $propertyRoomRateId => $propertyRoomRate) {
foreach ($propertyRoomRate['requestedRoomPrice'] as $occupancyCode => $requestedRoomPrices) {
foreach ($requestedRoomPrices['prices'] as $requestedRoomPriceKey => $requestedRoomPrice) {
$roomRateKeyName = $occupancyCode . ' ' . $requestedRoomPrice['room']['name'] . ' ' . $requestedRoomPrice['rate']['boardName'] . ' ' . $requestedRoomPrice['name'];
$roomRateKeycode = $requestedRoomPrice['rate']['accommodationCode'] . '|' . (isset($requestedRoomPrice['cancellationPolicy']['id']) ? $requestedRoomPrice['cancellationPolicy']['id'] : 0) . '|' . $requestedRoomPrice['bookingPaymentType']['code'];
//$requestedRoomPriceGroup[$roomRateKeycode][$occupancyCode][] = $roomRateKeyName . '-' . $requestedRoomPrice['rateKeyCode'];
$requestedRoomPrice['dailyAverageDiscount'] = $requestedRoomPrices['dailyAverageDiscount'];
$requestedRoomPriceGroup[] = $requestedRoomPrice;
}
}
}
}
if (!empty($requestedRoomPriceGroup)) {
$requestedRoomPriceGroup = collect($requestedRoomPriceGroup)->sortBy('total')->toArray();
}
$requestedRoomPrice = reset($requestedRoomPriceGroup);
$propertyCouponCodeCheck = $this->couponCodeCheck($propertyId, $searchRequestJson['date']['checkIn'], $searchRequestJson['date']['checkOut']);
if ($propertyCouponCodeCheck) {
$requestedRoomPrice['totalWithoutPopup'] = $requestedRoomPrice['total'];
$couponPercentageValue = (100 - $propertyCouponCodeCheck['value']) / 100;
$requestedRoomPrice['total'] = moneyDoubleFormatDecimal($requestedRoomPrice['total'] * $couponPercentageValue);
}
$transactionResult = $transaction->addChild('Result');
$transactionResult->addChild('Property', $propertyId);
$transactionResult->addChild('Checkin', $searchRequestJson['date']['checkIn']);
$transactionResult->addChild('Nights', $numberOfStay);
$taxValue = $requestedRoomPrice['total'] * ($this->tax / 100);
$baseTotalValue = $requestedRoomPrice['total'] - $taxValue;
$netTotalValue = ($taxValue + $baseTotalValue);
$baseRate = $transactionResult->addChild('Baserate', moneyDoubleFormatDecimal($baseTotalValue * $currencyExchangeRate));
$baseRate->addAttribute('currency', $requestCurrency);
$tax = $transactionResult->addChild('Tax', moneyDoubleFormatDecimal($taxValue * $currencyExchangeRate));
$tax->addAttribute('currency', $requestCurrency);
$otherFees = $transactionResult->addChild('OtherFees', 0);
$otherFees->addAttribute('currency', $requestCurrency);
$transactionResult->addChild('Custom1', htmlspecialchars($propertyName, ENT_XML1, 'UTF-8'));
$allowablePointsOfSale = $transactionResult->addChild('AllowablePointsOfSale');
$pointOfSale = $allowablePointsOfSale->addChild('PointOfSale');
$pointOfSale->addAttribute('id', 'default');
$pointOfSale->addChild('URL', htmlspecialchars($deepLinkGenerator, ENT_XML1, 'UTF-8'));
}
} 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();
}
header('Content-Type: application/xml; charset=UTF-8');
echo $transaction->asXML();
exit;
}
}

View File

@@ -0,0 +1,257 @@
<?php
namespace App\Http\Controllers;
use App\Core\Mail\LogMail;
use App\Core\Service\PropertyPaymentService;
use App\Exceptions\ApiErrorException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Mail\Mailer;
use Mews\Pos\Pos;
class PaymentController
{
public function __construct(
PropertyPaymentService $propertyPaymentService,
Mailer $mailer
)
{
$this->propertyPaymentService = $propertyPaymentService;
$this->mailer = $mailer;
}
public function initializePayment(Request $request)
{
/*
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(), 1);
dd($params);
$responseData = [
'bookingCode' => $bookingCode,
'total' => $totalRoomsPrice,
'currency' => $currencyCode
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
*/
}
public function paymentRedirect(Request $request, $paymentCode)
{
$response = ['status' => false, 'message' => ''];
try {
$paymentTransaction = $this->propertyPaymentService->getPaymentTransactionDetail($paymentCode);
if (!$paymentTransaction['status']) {
throw new ApiErrorException($paymentTransaction['message']);
}
$paymentTransaction = $paymentTransaction['data'];
if ($paymentTransaction['status'] == 1) {
return redirect()->to($paymentTransaction['paramsArray']['responseUrl']);
}
//Set Redirect Status
$this->propertyPaymentService->updatePaymentTransaction($paymentTransaction['id'], ['status' => 3]);
if ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'POS') {
//TODO: Burada PAN replace edilecek
//$this->propertyPaymentService->updatePaymentTransaction($paymentTransaction['id'], ['status' => 3]);
$formData = $paymentTransaction['extraParamsArray'];
return view('threeDSecureForm', compact('formData'));
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'STR') {
if (isset($paymentTransaction['extraParamsArray']['redirect']['url'])) {
return redirect()->to($paymentTransaction['extraParamsArray']['redirect']['url']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'ENW') {
if (isset($paymentTransaction['extraParamsArray']['redirect']['url'])) {
return redirect()->to($paymentTransaction['extraParamsArray']['redirect']['url']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'SPY') {
$formData = $paymentTransaction['extraParamsArray'];
return view('threeDSecureForm', compact('formData'));
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'MOK') {
if (isset($paymentTransaction['extraParamsArray'])) {
return redirect()->to($paymentTransaction['extraParamsArray']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'BOG') {
$redirectUrl = collect($paymentTransaction['extraParamsArray']['links'])->where('method', 'REDIRECT')->first();
if (isset($redirectUrl['href'])) {
return redirect()->to($redirectUrl['href']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'TBC') {
$redirectUrl = collect($paymentTransaction['extraParamsArray']['links'])->where('method', 'REDIRECT')->first();
if (isset($redirectUrl['uri'])) {
return redirect()->to($redirectUrl['uri']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'QNB') {
$formData = $paymentTransaction['extraParamsArray'];
return view('threeDSecureForm', compact('formData'));
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'WEE') {
if (isset($paymentTransaction['extraParamsArray']['threeDSecureUrl'])) {
return redirect()->to($paymentTransaction['extraParamsArray']['threeDSecureUrl']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'HLK') {
$formData = $paymentTransaction['extraParamsArray'];
return view('threeDSecureForm', compact('formData'));
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'ESN') {
if (isset($paymentTransaction['extraParamsArray']['URL_3DS'])) {
return redirect()->to($paymentTransaction['extraParamsArray']['URL_3DS']);
}
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'KVY') {
$formData = $paymentTransaction['extra_params'];
echo $formData; die();
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'RTL') {
$extraParams = json_decode($paymentTransaction['extra_params'],1);
echo $extraParams['form3d_html']; die();
} elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'PYR') {
$redirectUrl = $paymentTransaction['extraParamsArray']['payload'];
if (isset($redirectUrl['paymentUrl'])) {
return redirect()->to($redirectUrl['paymentUrl']);
}
}
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
}
//TODO: Burada bir yere yönlendirilmeli
dd($response);
}
public function paymentCheck(Request $request, $paymentCode)
{
$responseData = ['status' => false];
try {
$checkPayment = $this->propertyPaymentService->checkPayment($paymentCode, $request->all());
$responseData['paymentCode'] = $checkPayment['data']['paymentCode'];
if ($checkPayment['status']) {
$responseData['status'] = true;
$responseData['bankOrderId'] = $checkPayment['data']['bankOrderId'];
} else {
$responseData['message'] = $checkPayment['message'];
}
if (isset($checkPayment['data']['paymentTransactionDetail']['property'])) {
$responseData['paymentTransactionDetail']['amount'] = $checkPayment['data']['paymentTransactionDetail']['amount'];
$responseData['paymentTransactionDetail']['currency'] = $checkPayment['data']['paymentTransactionDetail']['currency'];
$responseData['paymentTransactionDetail']['message'] = $checkPayment['data']['paymentTransactionDetail']['message'];
$responseData['property'] = $checkPayment['data']['paymentTransactionDetail']['property'];
}
//$logMessage
$mailParams = [
'title' => 'PaymentCheck',
'logMessage' => '<pre>' . print_r($responseData, true) . '</pre>'
];
$this->mailer->onQueue(
'logMail',
new LogMail($mailParams)
);
//$logMessage
} catch (ApiErrorException $e) {
$responseData['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$responseData['message'] = $e->getMessage();
}
return redirect()->to($checkPayment['data']['responseUrl']);
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,845 @@
<?php
namespace App\Http\Controllers;
use App\Core\Service\PropertyService;
use App\Core\Service\TempPropertyService;
use App\Core\Service\UserPropertyMappingService;
use App\Core\Service\UserService;
use App\Notifications\NewUserNotification;
use Illuminate\Http\Request;
use App\Core\Service\JwtService;
use App\Core\Service\ApplicationCacheService;
use App\Core\Mail\UserCreateMail;
use App\Core\Mail\UserForgotPassword;
use Illuminate\Mail\Mailer;
use App\Core\Service\ApiAccessTokenService;
use App\Core\Service\LanguageService;
use App\Core\Service\ProductService;
use App\Core\Service\ThirdPartyServices\MondayService;
use App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Notification;
class UserController extends Controller
{
private $request;
private $userService;
private $tempPropertyService;
private $propertyService;
private $userPropertyMappingService;
private $jwtService;
private $applicationCacheService;
private $mailer;
private $apiAccessTokenService;
private $languageService;
private $productService;
public function __construct(
Request $request,
Mailer $mailer,
ApplicationCacheService $applicationCacheService,
TempPropertyService $tempPropertyService,
PropertyService $propertyService,
JwtService $jwtService,
UserPropertyMappingService $userPropertyMappingService,
ApiAccessTokenService $apiAccessTokenService,
UserService $userService,
LanguageService $languageService,
ProductService $productService,
MondayService $mondayService
)
{
$this->request = $request;
$this->userService = $userService;
$this->tempPropertyService = $tempPropertyService;
$this->propertyService = $propertyService;
$this->userPropertyMappingService = $userPropertyMappingService;
$this->jwtService = $jwtService;
$this->applicationCacheService = $applicationCacheService;
$this->mailer = $mailer;
$this->apiAccessTokenService = $apiAccessTokenService;
$this->languageService = $languageService;
$this->productService = $productService;
$this->mondayService = $mondayService;
}
public function getUserList()
{
/*$userListCriteria['criteria'] = [];
$userListCriteria['criteria'][] = ['field' => 'idate', 'condition' => '=', 'value' => 0];
//$userListCriteria['firstRow'] = true;
$userListCriteria['skip'] = 0; //take *2
$userListCriteria['take'] = 3;
$userListCriteria['orderBy'][] = ['field' => 'id', 'value' => 'DESC'];*/
if (is_null($this->request->params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userListCriteria = $this->request->params;
$userList = $this->userService->select($userListCriteria, fillOnUndefined($userListCriteria, 'select', ['*']));
if ($userList['status'] == 'success') {
return apiResponse(1, null, $userList['data'], 200);
} else {
return apiResponse(0, $userList['message'], null, 400);
}
}
public function userCreate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userCreateParams = $params;
$userCreateParams['user_id'] = $userId;
$return = [];
$userCreate = $this->userService->create($userCreateParams);
if ($userCreate['status'] != 'success') {
throw new ApiErrorException($userCreate['message']);
}
$return['user'] = $userCreate['data'];
$mailParams = [
'name_surname' => $return['user']['name'] . ' ' . $return['user']['surname'],
'email' => $return['user']['email'],
'hash_key' => $return['user']['hash_key'],
'activation_link' => Config::get('app.client_server') . '/activate-user?email=' . $return['user']['email'] . '&key=' . $return['user']['hash_key'],
];
$this->mailer->onQueue(
'userCreateMail',
new UserCreateMail($mailParams)
);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function checkUserKey(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$checkUserParams = $params;
$return = [];
$checkUserKey = $this->userService->checkUserKey($checkUserParams);
if ($checkUserKey['status'] != 'success') {
throw new ApiErrorException($checkUserKey['message']);
}
$return['user'] = $checkUserKey['data'];
unset($return['user']['id']);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function newPassword(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$checkUserParams = $params;
$return = [];
$checkUserKey = $this->userService->checkUserKey($checkUserParams);
if ($checkUserKey['status'] != 'success') {
throw new Exception($checkUserKey['message']);
}
$checkUserKey = $checkUserKey['data'];
$newPasswordParams = [
'email' => fillOnUndefined($params, 'email'),
'hash_key' => fillOnUndefined($params, 'key'),
'password' => fillOnUndefined($params, 'password'),
'password_confirmation' => fillOnUndefined($params, 'password_confirmation'),
'user_id' => $checkUserKey['id'],
];
$newPassword = $this->userService->newPassword($newPasswordParams);
if ($newPassword['status'] != 'success') {
throw new Exception($newPassword['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function changePassword(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$return = [];
$changePasswordParams = [
'user_id' => $userId,
'old_password' => fillOnUndefined($params, 'old_password'),
'password' => fillOnUndefined($params, 'password'),
'password_confirmation' => fillOnUndefined($params, 'password_confirmation'),
];
$changePassword = $this->userService->changePassword($changePasswordParams);
if ($changePassword['status'] != 'success') {
throw new Exception($changePassword['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function forgotPassword(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$language = "en";
if ($request->headers->get('language')) {
$language = $request->headers->get('language');
}
$userUpdateParams = [
'email' => fillOnUndefined($params, 'email'),
];
$return = [];
$userUpdate = $this->userService->forgotPassword($userUpdateParams);
if ($userUpdate['status'] != 'success') {
throw new Exception($userUpdate['message']);
}
$userUpdate = $userUpdate['data'];
$mailParams = [
'name_surname' => $userUpdate['name'] . ' ' . $userUpdate['surname'],
'email' => $userUpdate['email'],
'hash_key' => $userUpdate['hash_key'],
'activation_link' => Config::get('app.client_server') . '/reset-password?email=' . $userUpdate['email'] . '&key=' . $userUpdate['hash_key'],
'language' => $language,
];
$this->mailer->onQueue(
'UserForgotPassword',
new UserForgotPassword($mailParams)
);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function resetPassword(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userUpdateParams = [
'email' => fillOnUndefined($params, 'email'),
'hash_key' => fillOnUndefined($params, 'key'),
'password' => fillOnUndefined($params, 'password'),
'password_confirmation' => fillOnUndefined($params, 'password_confirmation'),
];
$return = [];
$userUpdate = $this->userService->resetPassword($userUpdateParams);
if ($userUpdate['status'] != 'success') {
throw new Exception($userUpdate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => 'Your password updated successfuly', 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function userUpdate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userUpdateParams = [
'user_update_data' => fillOnUndefined($params, 'user_update_data'),
'update_user_id' => fillOnUndefined($params, 'update_user_id'),
'user_id' => $userId
];
$return = [];
$userCreate = $this->userService->update($userUpdateParams);
if ($userCreate['status'] != 'success') {
throw new Exception($userCreate['message']);
}
$return['user'] = $userCreate['data'];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addUserProperty(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userPropertyParams = [
'add_user_id' => fillOnUndefined($params, 'add_user_id'),
'add_property_id' => fillOnUndefined($params, 'add_property_id'),
'user_id' => $userId
];
$return = [];
$addUserProperty = $this->userPropertyMappingService->addUserProperty($userPropertyParams);
if ($addUserProperty['status'] != 'success') {
throw new Exception($addUserProperty['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function removeUserProperty(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userPropertyParams = [
'remove_user_id' => fillOnUndefined($params, 'remove_user_id'),
'remove_property_id' => fillOnUndefined($params, 'remove_property_id'),
'user_id' => $userId
];
$return = [];
$addUserProperty = $this->userPropertyMappingService->removeUserProperty($userPropertyParams);
if ($addUserProperty['status'] != 'success') {
throw new Exception($addUserProperty['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function userRegister()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$params = $this->request->params;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$userCreateParams = $params;
$return = [];
$userCreate = $this->userService->create($userCreateParams);
if ($userCreate['status'] != 'success') {
throw new Exception($userCreate['message']);
}
$return['user'] = $userCreate['data'];
$jwtData = $this->jwtService->jwtCreate(['user_id' => $return['user']['id']]);
if ($jwtData['status'] != 'success') {
throw new Exception($userCreate['message']);
}
$return['token'] = $jwtData['data'];
if ($params['temp_hotel_id']) {
$propertySearchCriteria = [
'criteria' => [
["field" => "id", "condition" => "=", "value" => $params['temp_hotel_id']]
],
'firstRow' => true
];
$tempPropertyData = $this->tempPropertyService->select($propertySearchCriteria, ['id', 'name', 'giata_id', 'destination_id']);
if ($tempPropertyData['status'] == 'success') {
$tempProperty = $tempPropertyData['data'];
$propertyInsertData = [
'name' => $tempProperty['name'],
'destination_id' => $tempProperty['destination_id'],
'giata_id' => $tempProperty['destination_id'],
'currency_type' => 'TRY',
'created_at' => time(),
'updated_at' => time(),
];
$propertyCreate = $this->propertyService->create($propertyInsertData);
if ($propertyCreate['status'] == 'success') {
$return['property'] = $propertyCreate['data'];
$userPropertyMappingData = [
'user_id' => $userCreate['data']['id'],
'property_id' => $propertyCreate['data']['id'],
];
$userPropertyMappingCreate = $this->userPropertyMappingService->create($userPropertyMappingData);
if ($userPropertyMappingCreate['status'] == 'success') {
// $return['user_property_mapping'] = $userPropertyMappingCreate['data'] ;
}
}
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function setProperty()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
$request = $this->request->params;
$checkUserPropertyCriteria = [
'criteria' => [
['field' => 'user_id', 'condition' => '=', 'value' => $this->request->credentials->user_id],
['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($request, 'property_id')],
],
'with' => ['property'],
'firstRow' => true,
];
$checkUserProperty = $this->userPropertyMappingService->select($checkUserPropertyCriteria);
if ($checkUserProperty['status'] != 'success') {
throw new Exception(lang('An unknown error occurred'));
}
if (!$checkUserProperty['data']) {
throw new ApiErrorException(lang('Mapping data not found'));
}
$cacheParams = [
'token' => $this->request->header('authToken'),
'property_id' => $checkUserProperty['data']['property_id']
];
$applicationCache = $this->applicationCacheService->applicationCacheCreate($cacheParams);
$return['hotel_user_mapping'] = $checkUserProperty['data'];
$return['application_cache'] = $applicationCache['data'];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function userRegisterWithProperty()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
try {
DB::beginTransaction();
$params = $this->request->params;
if (is_null($params)) {
return apiResponse(0, 'Parameter Error.', null, 400);
}
$language = "en";
if ($this->request->headers->get('language')) {
$language = $this->request->headers->get('language');
}
$userCreateParams = $params;
$return = [];
$userCreateParams['status'] = 1;
$userCreateParams['user_type'] = 1;
$userCreate = $this->userService->create($userCreateParams);
if ($userCreate['status'] != 'success') {
throw new ApiErrorException($userCreate['message']);
}
$return['user'] = $userCreate['data'];
$propertyInsertData = [
'name' => $userCreateParams['property_name'],
'status' => 1,
'created_by' => $return['user']['id'],
'updated_by' => $return['user']['id'],
'created_at' => time(),
'updated_at' => time(),
];
$propertyCreate = $this->propertyService->create($propertyInsertData);
if ($propertyCreate['status'] != 'success') {
throw new ApiErrorException($propertyCreate['message']);
}
$return['property_list'] = [
[
'id' => $propertyCreate['data']['id'],
'name' => $propertyCreate['data']['name'],
'default_photo' => "/assets/img/placeholder.png",
]
];
$userPropertyMappingData = [
'user_id' => $userCreate['data']['id'],
'status' => 1,
'property_id' => $propertyCreate['data']['id'],
'created_by' => $return['user']['id'],
'updated_by' => $return['user']['id'],
'created_at' => time(),
'updated_at' => time(),
];
$userPropertyMappingCreate = $this->userPropertyMappingService->create($userPropertyMappingData);
if ($userPropertyMappingCreate['status'] != 'success') {
throw new ApiErrorException($userPropertyMappingCreate['message']);
}
$propertyProducts = $this->productService->setDefaultPropertyProducts($userPropertyMappingData);
if ($propertyProducts['status'] != 'success') {
throw new ApiErrorException($propertyProducts['message']);
}
$jwtToken = $this->jwtService->jwtCreate(['user_id' => $return['user']['id']]);
if ($jwtToken['status'] != 'success') {
throw new ApiErrorException(lang('An unknown error occurred.'));
}
$jwtToken = $jwtToken['data'];
$saveToken = [
"token" => md5(fillOnUndefined($jwtToken, "token")),
"expire_date" => fillOnUndefined($jwtToken, "exp"),
"user_id" => fillOnUndefined($return['user'], "id"),
"invalidate" => fillOnUndefined($jwtToken, "invalidate", 0),
];
$saveTokenTo = $this->apiAccessTokenService->create($saveToken);
if ($saveTokenTo['status'] != 'success') {
throw new ApiErrorException(lang('General error'));
}
$return['token'] = $jwtToken['token'];
$return['expire_time'] = $saveTokenTo['data']['expire_time'];
$return['locale'] = null;
$mailParams = [
'name_surname' => $return['user']['name'] . ' ' . $return['user']['surname'],
'email' => $return['user']['email'],
"password" => $return['user']['userPassword'],
'language' => $language,
];
$this->mailer->onQueue(
'userCreateMail',
new UserCreateMail($mailParams)
);
$return['user'] = [
'name' => $userCreate['data']['name'],
'surname' => $userCreate['data']['surname'],
];
$notificationParam = $userCreateParams;
Notification::route('mail', ['sales@extranetwork.com' => 'Extranetwork Sales'])->notify(new NewUserNotification($notificationParam));
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
DB::commit();
//Monday.com contact items
//$createBoardItems = $this->mondayService->createBoardItems($userCreateParams);
//Kommo integration
$kommoPropertyParam = [
'name_surname' => $notificationParam['name'] . ' ' . $notificationParam['surname'],
'phone_number' => $notificationParam['phone'],
'email' => $notificationParam['email'],
'property' => $notificationParam['property_name'],
'web' => fillOnUndefined($notificationParam, 'web', 'www.extranetwork.com')
];
$this->propertyService->kommoCreateLead($kommoPropertyParam);
} catch (ApiErrorException $e) {
DB::rollBack();
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
DB::rollBack();
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 400;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getProfile(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$return = [];
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$requestParams = [
'user_id' => $request->credentials->user_id,
'status' => 1
];
$profileFields = ['id', 'email', 'name', 'surname', 'gender', 'language', 'phone'];
$profile = $this->userService->getProfile($requestParams, $profileFields);
if ($profile['status'] != 'success') {
throw new Exception($profile['message']);
}
$return['profile'] = $profile['data'];
$languageCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'is_application', 'condition' => '=', 'value' => 1],
['field' => 'is_published', 'condition' => '=', 'value' => 1]
],
"orderBy" => [
["field" => "name", "value" => "ASC"]
]
];
$languages = $this->languageService->getAllLanguages($languageCriteria, ['id', 'code', 'name', 'status', 'language_key']);
if ($languages['status'] != 'success') {
throw new Exception($languages['message']);
}
$return['languages'] = $languages['data'];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateProfile(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $request->params;
$requestParams = [
'name' => fillOnUndefined($params, 'name'),
'surname' => fillOnUndefined($params, 'surname'),
'gender' => fillOnUndefined($params, 'gender'),
'language' => fillOnUndefined($params, 'language'),
'phone' => fillOnUndefined($params, 'phone'),
'user_id' => $request->credentials->user_id,
];
$profile = $this->userService->profileUpdate($requestParams);
if ($profile['status'] != 'success') {
throw new ApiErrorException($profile['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $profile['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\CurrencyService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class AIController extends Controller
{
private $currencyService;
public function __construct()
{
}
public function request(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $request->params;
$client = new \GuzzleHttp\Client([
'max' => 5,
'strict' => false,
'referer' => false,
'protocols' => ['https'],
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . config('app.openAISecretKey'),
'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
'Accept-Encoding' => 'gzip'
]
]
);
$result = $client->post('https://api.openai.com/v1/chat/completions', [
'body' => json_encode($params['query'])
]);
$result = $result->getBody()->getContents();
$result = json_decode($result, 1);
$choiceMessage = reset($result['choices']);
if (isset($choiceMessage['message']['content'])) {
$choiceMessage = json_decode($choiceMessage['message']['content'], 1);
$data = $choiceMessage;
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $data];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,49 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\CurrencyService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
class CurrencyController extends Controller
{
private $currencyService;
public function __construct(
CurrencyService $currencyService
){
$this->currencyService = $currencyService;
}
public function getListCurrency(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$currencyList = $this->currencyService->getCurrencyList();
if($currencyList['status'] != 'success'){
throw new Exception($currencyList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $currencyList['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\DestinationService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class DestinationController
{
private $request;
private $destinationService;
public function __construct(
Request $request,
DestinationService $destinationService
)
{
$this->request = $request;
$this->destinationService = $destinationService;
}
public function searchDestination(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'search_term' => fillOnUndefined($params, 'search_term'),
'user_id' => $request->credentials->user_id,
];
$destinationSearch = $this->destinationService->searchDestination($requestParams);
if($destinationSearch['status'] != 'success'){
throw new ApiErrorException($destinationSearch['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $destinationSearch['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\EnwContactFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class EnwContactFormController extends Controller
{
private $enwContactFormService;
public function __construct(
EnwContactFormService $enwContactFormService
)
{
$this->enwContactFormService = $enwContactFormService;
}
public function sendEmail(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$language = "en";
if($request->headers->get('language')){
$language = $request->headers->get('language');
app('translator')->setLocale($language);
}
$params = $request->params;
$requestParams = [
'language' => $language,
'name' => fillOnUndefined($params, 'name'),
'surname' => fillOnUndefined($params, 'surname'),
'email' => fillOnUndefined($params, 'email'),
'subject' => fillOnUndefined($params, 'subject')
];
$contactForm = $this->enwContactFormService->sendEmail($requestParams);
if ($contactForm['status'] != 'success') {
throw new ApiErrorException($contactForm['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $contactForm['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,741 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Mail\PropertyProductOfferMail;
use App\Core\Service\PdfContentService;
use App\Core\Service\PropertyRoomService;
use App\Exceptions\ApiErrorException;
use App\Jobs\PropertyCatalogServiceJob;
use App\Jobs\RunPropertyCatalogService;
use App\Models\PropertyProductOffer;
use App\Models\User;
use Carbon\Carbon;
use Exception;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\App;
use Barryvdh\DomPDF\PDF;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
class ExportPdfController
{
private $pdf;
private $pdfContentService;
private $propertyRoomService;
public function __construct(
PDF $pdf,
PdfContentService $pdfContentService,
PropertyRoomService $propertyRoomService,
Mailer $mailer
)
{
$this->pdf = $pdf;
$this->pdfContentService = $pdfContentService;
$this->propertyRoomService = $propertyRoomService;
$this->mailer = $mailer;
}
public function pdf(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(), 1);
$params = current($params);
if (isset($params['dataExport']) && $params['dataExport'] == 'json') {
$pdfDataRequest = [
'property_id' => fillOnUndefined($params, 'property_id', null),
'locale' => app('translator')->getLocale()
];
$factSheetDataResponse = $this->pdfContentService->factSheetData($pdfDataRequest);
if ($factSheetDataResponse['status'] != 'success') {
throw new Exception($factSheetDataResponse['message']);
}
$factSheetData = $factSheetDataResponse['data'];
return apiResponse(1, null, $factSheetData, 200);
}
if (isset($params['dataExport']) && $params['dataExport'] == 'catalog') {
/*$pdfDataRequest = [
'property_id' => fillOnUndefined($params, 'property_id', null),
'locale' => fillOnUndefined($params, 'language', 'en'),
];
$factSheetDataResponse = $this->pdfContentService->factSheetData($pdfDataRequest);
if ($factSheetDataResponse['status'] != 'success') {
throw new Exception($factSheetDataResponse['message']);
}
$pageContent = $factSheetDataResponse['data'];
$pdfLanguage = $pdfDataRequest['locale'];
app('translator')->setLocale($pdfLanguage);
$pdfService = $this->pdf->loadView('pdf.propertyCatalog', compact('pageContent'), [], 'UTF8');
//$pdfService->setOptions(['dpi' => 100, 'isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]);
$hotelName = Str::slug($pageContent['name'], '_', 'en') . '_' . $pdfLanguage;
return $pdfService->download($hotelName . '.pdf');*/
dispatch(new PropertyCatalogServiceJob(
fillOnUndefined($params, 'property_id', null),
fillOnUndefined($params, 'language', app('translator')->getLocale()),
fillOnUndefined($params, 'email', null)
));
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
$pdfDataRequest = [
'property_id' => fillOnUndefined($params, 'property_id', null),
'locale' => app('translator')->getLocale()
];
$pdfDataResponse = $this->pdfContentService->pdfData($pdfDataRequest);
if ($pdfDataResponse['status'] != 'success') {
throw new Exception($pdfDataResponse['message']);
}
$pdfData = $pdfDataResponse['data'];
$pdfLanguage = upperCase(app('translator')->getLocale());
$logoBase64 = null;
if ($pdfData['property_brand']) {
if ($pdfData['property_brand']['logo_name']) {
$logoFile = Config::get('app.imageUrl') . '/property-photos/' . $pdfData['property_brand']['property_id'] . '/logo/' . $pdfData['property_brand']['logo_name'] . '_250x250.' . $pdfData['property_brand']['logo_file_ext'];
$logoBase64 = 'data:image/' . $pdfData['property_brand']['logo_file_ext'] . ';base64,' . base64_encode(file_get_contents($logoFile));
}
}
$ip = $request->ip();
$pdf = $this->pdf->loadView('pdf.hotelContent', compact('pdfData', 'logoBase64', 'ip'), [], 'UTF8');
$hotelName = Str::slug($pdfData['name'], '_', 'en') . '_' . $pdfLanguage;
return $pdf->download($hotelName . '.pdf');
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (\Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
// return $pdf->stream();
}
public function getPropertyPdfInventory(Request $request, $token)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$requestParams = [
'token' => $token
];
$params = $this->propertyRoomService->getParamsForPdfInvenyory($requestParams);
$params = $params['data'];
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
'start_date' => fillOnUndefined($params, 'start_date'),
'end_date' => fillOnUndefined($params, 'end_date'),
];
$inventoryData = $this->propertyRoomService->getPropertyRoomInventory($requestParams);
if ($inventoryData['status'] != 'success') {
throw new ApiErrorException($inventoryData['message']);
}
$data = $inventoryData['data'];
foreach ($data as $dataKey => $dataVal) {
//room_availability
$i = 0;
$monthKey = null;
foreach ($dataVal['room_availability'] as $key => $val) {
$keyArr = explode('-', $key);
if ($monthKey != $keyArr[1]) {
$monthKey = $keyArr[1];
$i++;
}
if ($i > 6) {
continue;
}
$data[$dataKey]['monthly_room_availability'][$i][$key] = $val;
}
//room_stop_sell
$i = 0;
$monthKey = null;
foreach ($dataVal['room_stop_sell'] as $key => $val) {
$keyArr = explode('-', $key);
if ($monthKey != $keyArr[1]) {
$monthKey = $keyArr[1];
$i++;
}
if ($i > 6) {
continue;
}
$data[$dataKey]['monthly_room_stop_sell'][$i][$key] = $val;
}
foreach ($dataVal['property_room_rate_mapping'] as $propertyRoomRateMappingKey => $propertyRoomRateMappingVal) {
foreach ($propertyRoomRateMappingVal['prices'] as $pricesKey => $pricesVal) {
//price
$i = 0;
$monthKey = null;
foreach ($pricesVal['price'] as $key => $val) {
$keyArr = explode('-', $key);
if ($monthKey != $keyArr[1]) {
$monthKey = $keyArr[1];
$i++;
}
if ($i > 6) {
continue;
}
$data[$dataKey]['property_room_rate_mapping'][$propertyRoomRateMappingKey]['prices'][$pricesKey]['monthly_price'][$i][$key] = $val;
}
//stop_sell
$i = 0;
$monthKey = null;
foreach ($pricesVal['stop_sell'] as $key => $val) {
$keyArr = explode('-', $key);
if ($monthKey != $keyArr[1]) {
$monthKey = $keyArr[1];
$i++;
}
if ($i > 6) {
continue;
}
$data[$dataKey]['property_room_rate_mapping'][$propertyRoomRateMappingKey]['prices'][$pricesKey]['monthly_stop_sell'][$i][$key] = $val;
}
//min_stay
$i = 0;
$monthKey = null;
foreach ($pricesVal['min_stay'] as $key => $val) {
$keyArr = explode('-', $key);
if ($monthKey != $keyArr[1]) {
$monthKey = $keyArr[1];
$i++;
}
if ($i > 6) {
continue;
}
$data[$dataKey]['property_room_rate_mapping'][$propertyRoomRateMappingKey]['prices'][$pricesKey]['monthly_min_stay'][$i][$key] = $val;
}
}
}
}
$propertyDataRequest = [
'property_id' => fillOnUndefined($params, 'property_id', null)
];
$propertyDataResponse = $this->pdfContentService->propertyBaseData($propertyDataRequest);
if ($propertyDataResponse['status'] != 'success') {
throw new Exception($propertyDataResponse['message']);
}
$propertyData = $propertyDataResponse['data'];
$logoBase64 = null;
if ($propertyData['property_brand']) {
if ($propertyData['property_brand']['logo_name']) {
$logoFile = Config::get('app.imageUrl') . '/property-photos/' . $propertyData['property_brand']['property_id'] . '/logo/' . $propertyData['property_brand']['logo_name'] . '_250x250.' . $propertyData['property_brand']['logo_file_ext'];
$logoBase64 = 'data:image/' . $propertyData['property_brand']['logo_file_ext'] . ';base64,' . base64_encode(file_get_contents($logoFile));
}
}
/*$pdf = $this->pdf->loadView('pdf.inventory', compact('data','propertyData','logoFile','logoBase64'), [], 'UTF8' )->setPaper('a4', 'landscape');
$pdfLanguage = upperCase(app('translator')->getLocale());
$fileName = Str::slug('inventory', '_','en').'_'.$pdfLanguage;*/
return view('pdf.inventory', compact('data', 'propertyData', 'logoFile', 'logoBase64'));
/*return $pdf->download($fileName.'.pdf');*/
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function propertyProductOffer(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(), 1);
$params = current($params);
if (fillOnUndefined($params, 'version') == 'v2') {
$offerKey = [];
$offerKey[] = $params['propertyName'];
$offerKey[] = $params['executiveName'];
$offerKey[] = $params['executiveEmail'];
$offerKey[] = $params['executivePhone'];
$offerKey[] = $params['accountManager'];
$offerKey[] = hash('sha256', json_encode($params['detail'], JSON_UNESCAPED_UNICODE));
$offerKey = md5(implode('-', $offerKey));
} else {
$offerKey = md5($params['propertyName'] . '-' . $params['executiveName'] . '-' . $params['package'] . '-' . $params['numberOfRooms'] . '-' . $params['promotionCode']);
if ($offerKey != fillOnUndefined($params, 'hashKey')) {
throw new ApiErrorException('HASH verification error!');
}
}
$createParam = [
'offer_key' => $offerKey,
'property_name' => $params['propertyName'],
'executive_name' => $params['executiveName'],
'executive_email' => $params['executiveEmail'],
'executive_phone' => $params['executivePhone'],
'account_manager_name' => fillOnUndefined($params, 'accountManagerName'),
'account_manager_email' => fillOnUndefined($params, 'accountManagerEmail'),
'confirm' => fillOnUndefined($params, 'confirm'),
'offer_date' => Carbon::now()->toDateTimeString(),
'offer_expire_date' => Carbon::now()->addDays(2)->toDateTimeString(),
'package' => $params['package'],
'promotion_code' => $params['promotionCode'],
'detail' => fillOnUndefined($params, 'detail') ? json_encode($params['detail']) : json_encode($params),
'version' => fillOnUndefined($params, 'version', 'v1'),
'ip_address' => $params['ipAddress'],
'status' => 1,
'created_at' => time(),
'updated_at' => time()
];
$propertyProductOfferCheck = PropertyProductOffer::where('offer_key', $offerKey)->first();
if ($propertyProductOfferCheck) {
$propertyProductOfferSync = PropertyProductOffer::where('offer_key', $offerKey)->update($createParam);
} else {
$propertyProductOfferSync = PropertyProductOffer::insert($createParam);
}
if (!$propertyProductOfferSync) {
throw new ApiErrorException('Your offer could not be generated. Please try again.');
}
if(fillOnUndefined($params, 'sendEmail')) {
$propertyProductOfferMail = ['offerKey' => $offerKey];
$this->mailer->onQueue('propertyProductOfferMail', new PropertyProductOfferMail($propertyProductOfferMail));
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['offer_key' => $offerKey]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
//$response['message'] = $e->getMessage();
$response['message'] = 'Your offer could not be generated. Please try again.';
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function propertyProductOfferExport(Request $request, $offerKey)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
$package = [
'LRG' => [
'commission' => 15,
'minFee' => 2,
'name' => 'Paket A',
'creditRange' => [
'25-50' => [
'min' => 25,
'max' => 50,
'monthly' => 250,
'annually' => 3000,
],
'51-75' => [
'min' => 51,
'max' => 75,
'monthly' => 500,
'annually' => 6000,
],
'76-100' => [
'min' => 76,
'max' => 100,
'monthly' => 750,
'annually' => 9000,
],
'101-150' => [
'min' => 101,
'max' => 150,
'monthly' => 1000,
'annually' => 12000,
],
'151-200' => [
'min' => 151,
'max' => 200,
'monthly' => 1500,
'annually' => 18000,
],
'201-250' => [
'min' => 201,
'max' => 250,
'monthly' => 2000,
'annually' => 24000,
],
'250+' => [
'min' => 251,
'max' => null,
'monthly' => 2500,
'annually' => 30000,
],
]
],
'MED' => [
'commission' => 10,
'minFee' => 3,
'name' => 'Paket B',
'creditRange' => [
'25-50' => [
'min' => 25,
'max' => 50,
'monthly' => 375,
'annually' => 4500,
],
'51-75' => [
'min' => 51,
'max' => 75,
'monthly' => 750,
'annually' => 9000,
],
'76-100' => [
'min' => 76,
'max' => 100,
'monthly' => 1125,
'annually' => 13500,
],
'101-150' => [
'min' => 101,
'max' => 150,
'monthly' => 1500,
'annually' => 18000,
],
'151-200' => [
'min' => 151,
'max' => 200,
'monthly' => 2250,
'annually' => 27000,
],
'201-250' => [
'min' => 201,
'max' => 250,
'monthly' => 3000,
'annually' => 36000,
],
'250+' => [
'min' => 251,
'max' => null,
'monthly' => 3750,
'annually' => 45000,
],
]
],
'SML' => [
'commission' => 5,
'minFee' => 4,
'name' => 'Paket C',
'creditRange' => [
'25-50' => [
'min' => 25,
'max' => 50,
'monthly' => 750,
'annually' => 9000,
],
'51-75' => [
'min' => 51,
'max' => 75,
'monthly' => 1500,
'annually' => 18000,
],
'76-100' => [
'min' => 76,
'max' => 100,
'monthly' => 2250,
'annually' => 27000,
],
'101-150' => [
'min' => 101,
'max' => 150,
'monthly' => 3000,
'annually' => 36000,
],
'151-200' => [
'min' => 151,
'max' => 200,
'monthly' => 4500,
'annually' => 54000,
],
'201-250' => [
'min' => 201,
'max' => 250,
'monthly' => 6000,
'annually' => 72000,
],
'250+' => [
'min' => 251,
'max' => null,
'monthly' => 7500,
'annually' => 90000,
],
],
]
];
$campaign = [
'promotion' => [
'code' => [/*'ITF2025','ATF2025','TTI2025'*/],
'percentage' => 50
],
'oneYearAnnually' => [
'percentage' => 10
],
'twoYearAnnually' => [
'percentage' => 20
]
];
$userListIds = [904, 941, 1485];//22-41
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$userList = User::whereIn('id', $userListIds)->get()->toArray();
$offerDetail = PropertyProductOffer::where('offer_key', $offerKey)->first();
$offerDetail = $offerDetail ? $offerDetail->toArray() : null;
if (empty($offerDetail)) {
return redirect()->to(config('app.url'));
}
$pageContent = [
'name' => $offerDetail['property_name'],
'executiveName' => $offerDetail['executive_name'],
'executiveEmail' => $offerDetail['executive_email'],
'executivePhone' => $offerDetail['detailArray']['executivePhone'],
'offerTime' => $offerDetail['offer_date'],
'offerExpireTime' => $offerDetail['offer_expire_date'],
'offerTimeFormatted' => $offerDetail['offerTimeFormatted'],
'offerExpireTimeFormatted' => $offerDetail['offerExpireTimeFormatted'],
'numberOfRooms' => $offerDetail['detailArray']['numberOfRooms'],
'package' => $offerDetail['package'],
'promotionCode' => $offerDetail['promotion_code'],
];
$pageContent['package'] = !empty($request->get('package')) ? $request->get('package') : $pageContent['package'];
$pageContent['numberOfRooms'] = !empty($request->get('numberOfRooms')) ? $request->get('numberOfRooms') : $pageContent['numberOfRooms'];
$creditPackage = [];
if ((int)$pageContent['numberOfRooms'] < 25) {
$creditPackage = $package[$pageContent['package']]['creditRange']['25-50'];
} elseif ((int)$pageContent['numberOfRooms'] > 250) {
$creditPackage = $package[$pageContent['package']]['creditRange']['250+'];
} else {
$creditPackage = collect($package[$pageContent['package']]['creditRange'])
->where('min', '<=', (int)$pageContent['numberOfRooms'])
->where('max', '>=', (int)$pageContent['numberOfRooms'])
->first();
}
$pricing = [];
$pricing['minFee'] = $package[$pageContent['package']]['minFee'];
$pricing['minFeeBeforeDiscount'] = $package[$pageContent['package']]['minFee'];
if (in_array($pageContent['promotionCode'], $campaign['promotion']['code'])) {
$pricing['minFee'] = (int)($pricing['minFee'] * (1 - ($campaign['promotion']['percentage'] / 100)));
}
$pricing['commission'] = $package[$pageContent['package']]['commission'];
$pricing['minFee'] = $pricing['minFee'];
$pricing['minFeeBeforeDiscount'] = $pricing['minFeeBeforeDiscount'];
$pricing['monthly']['minFee'] = (int)$pricing['minFee'] * (int)$pageContent['numberOfRooms'];
$pricing['monthly']['minFeeBeforePromotion'] = (int)$pricing['minFeeBeforeDiscount'] * (int)$pageContent['numberOfRooms'];
$pricing['monthly']['commission'] = $package[$pageContent['package']]['commission'];
//$pricing['monthly']['minReservationTotal'] = number_format(((int)$pricing['monthly']['minFee'] * 100) / $package[$pageContent['package']]['commission'], 0, '', '.');
$pricing['monthly']['minReservationTotal'] = number_format(fillOnUndefined($creditPackage, 'monthly', 0), 0, '', '.');
$pricing['annually']['minFee'] = (int)$pricing['monthly']['minFee'] * 12;
$pricing['annually']['minFeeBeforePromotion'] = (int)$pricing['monthly']['minFeeBeforePromotion'] * 12;
$pricing['annually']['commission'] = $package[$pageContent['package']]['commission'];
$pricing['annually']['minFeeDiscount'] = (int)$pricing['annually']['minFee'] * (1 - ($campaign['oneYearAnnually']['percentage'] / 100));//%10
//$pricing['annually']['minReservationTotal'] = number_format(((int)$pricing['annually']['minFeeDiscount'] * 100) / $package[$pageContent['package']]['commission'], 0, '', '.');
$pricing['annually']['minReservationTotal'] = number_format(fillOnUndefined($creditPackage, 'annually', 0), 0, '', '.');
if ($pricing['minFee'] == $pricing['minFeeBeforeDiscount']) {
$pricing['monthly']['minFeeBeforePromotion'] = null;
$pricing['annually']['minFeeBeforePromotion'] = null;
}
$pageContent['packageName'] = $package[$pageContent['package']]['name'];
$pageContent['pricing'] = $pricing;
$accountUserDetail = collect($userList)->where('email', $offerDetail['detailArray']['accountManager'])->first();
$pageContent['accountManagerName'] = fillOnUndefined($accountUserDetail, 'nameSurname');
$pageContent['accountManagerEmail'] = fillOnUndefined($accountUserDetail, 'email');
$pageContent['accountManagerPhone'] = fillOnUndefined($accountUserDetail, 'phone');
$pdfService = $this->pdf->loadView('pdf.propertyProductOffer', compact('pageContent'), [], 'UTF8');
$pdfService->setOptions(['dpi' => 100, 'isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]);
$hotelName = Str::slug($pageContent['name'], '_', 'en');
return $pdfService->stream($hotelName . '.pdf');
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function propertyProductOfferData(Request $request, $offerKey)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
$userListIds = [904, 941, 1485];//22-41
try {
if (is_null($request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$userList = User::whereIn('id', $userListIds)->get()->toArray();
$offerDetail = PropertyProductOffer::where('offer_key', $offerKey)->first();
$offerDetail = $offerDetail ? $offerDetail->toArray() : null;
if (empty($offerDetail)) {
return redirect()->to(config('app.url'));
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $offerDetail];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,138 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\LanguageService;
use App\Http\Controllers\Controller;
use App\Core\Service\LanguageBaseService ;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class LanguageController extends Controller
{
private $languageService;
private $languageBaseService ;
public function __construct(
LanguageService $languageService,
LanguageBaseService $languageBaseService
)
{
$this->languageService = $languageService;
$this->languageBaseService = $languageBaseService ;
}
public function getAllLanguages($param)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500 ];
try {
if($param === "all"){
$languageCriteria = [
'criteria' => [
['field' => 'status' , 'condition' => '=', 'value' => 1 ]
] ,
"orderBy" => [
["field" => "name", "value" => "ASC"]
]
];
}elseif ($param === "app"){
$languageCriteria = [
'criteria' => [
['field' => 'status' , 'condition' => '=', 'value' => 1 ],
['field' => 'is_application' , 'condition' => '=', 'value' => 1 ],
['field' => 'is_published' , 'condition' => '=', 'value' => 1 ]
] ,
"orderBy" => [
["field" => "name", "value" => "ASC"]
]
];
}else{
throw new ApiErrorException(lang('Parameter Error.'));
}
$languages = $this->languageService->getAllLanguages($languageCriteria, ['id','code','name','status', 'language_key']);
if ($languages['status'] != 'success') {
throw new ApiErrorException($languages['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null,'data' => $languages['data'] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createApplicationLanguageFiles()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500 ];
try {
$languageBaseResponse = $this->languageBaseService->createApplicationLanguageFiles() ;
if ($languageBaseResponse['status'] != 'success') {
throw new ApiErrorException($languageBaseResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null,'data' => null ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getNullDescriptions()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500 ];
try {
$applicationLanguages = $this->languageService->getApplicationLanguages();
$applicationLanguages = $applicationLanguages['data'];
$responseLangTitle = [] ;
foreach ($applicationLanguages as $applicationLanguage) {
$langKey = $applicationLanguage['code'];
$responseLangTitle[] = [
'language_code' => $langKey,
'description' => isset($titleLangContents[$langKey]) ? $titleLangContents[$langKey] : null
];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null,'data' => $responseLangTitle ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,368 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\BookingPaymentService;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyPaymentService;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Http\Request ;
use Exception ;
use phpDocumentor\Reflection\Types\Collection;
class PaymentController
{
private $request ;
private $propertyPaymentService;
private $currencyService ;
private $bookingPaymentService;
public function __construct(
Request $request,
PropertyPaymentService $propertyPaymentService,
BookingPaymentService $bookingPaymentService,
CurrencyService $currencyService
)
{
$this->propertyPaymentService = $propertyPaymentService ;
$this->request = $request ;
$this->currencyService = $currencyService ;
$this->bookingPaymentService = $bookingPaymentService ;
}
public function getPaymentTypeList(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$paymentList = $this->propertyPaymentService->getPaymentTypeList($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$currencyList = $this->currencyService->getCurrencyList();
if($currencyList['status'] != 'success'){
throw new Exception($currencyList['message']);
}
$currencyList = collect($currencyList['data'])->map(function ($value){
return [
'code' => $value['code'],
'name' => $value['name'],
'language_key' => $value['language_key'],
];
}) ;
$responseData['payment_types'] = $paymentList['data'] ;
$responseData['currencies'] = $currencyList ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPaymentType(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$paymentList = $this->propertyPaymentService->getPaymentType($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $paymentList['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPaymentMappingList(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$paymentList = $this->propertyPaymentService->getPaymentMappingList($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPaymentMapping(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$paymentList = $this->propertyPaymentService->createPaymentMapping($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePaymentMappingStatus(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$paymentList = $this->propertyPaymentService->updatePaymentMappingStatus($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function setPaymentMappingDefault(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$paymentList = $this->propertyPaymentService->setPaymentMappingDefault($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePaymentMapping(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$paymentList = $this->propertyPaymentService->updatePaymentMapping($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePaymentInstallments(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$paymentList = $this->propertyPaymentService->updateInstallments($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePaymentInstallmentStatus(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$paymentList = $this->propertyPaymentService->updatePaymentInstallmentStatus($params);
if($paymentList['status'] != 'success'){
throw new Exception($paymentList['message']);
}
$responseData = $paymentList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function paymentDashboard(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$paymentDashboard = $this->bookingPaymentService->getPaymentDashboard($params);
if($paymentDashboard['status'] != "success"){
throw new ApiErrorException($paymentDashboard['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $paymentDashboard['data']];
} catch (ApiErrorException $e) {
$responseData['message'] = implode(', ', $e->getMessageArr());
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$responseData['message'] = $e->getMessage();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\ProductService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class ProductController
{
private $request;
private $productService;
public function __construct(
Request $request,
ProductService $productService
)
{
$this->request = $request;
$this->productService = $productService;
}
public function getPropertyProducts(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyProducts = $this->productService->getPropertyProducts($requestParams);
if($propertyProducts['status'] != 'success'){
throw new ApiErrorException($propertyProducts['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyProducts['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function propertyProductActivate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'product_id' => fillOnUndefined($params, 'product_id'),
];
$propertyProducts = $this->productService->propertyProductActivate($requestParams);
if($propertyProducts['status'] != 'success'){
throw new ApiErrorException($propertyProducts['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyProducts['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyAdditionalInfo\PropertyAdditionalInfoService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyAdditionalInfoController extends Controller
{
private $request;
private $propertyAdditionalInfoService;
public function __construct
(
Request $request,
PropertyAdditionalInfoService $propertyAdditionalInfoService
)
{
$this->request = $request;
$this->propertyAdditionalInfoService = $propertyAdditionalInfoService;
}
public function getPropertyAdditionalInfo()
{
$response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
//TODO : Validataion eklenecek. Eklendikten sonra if kaldırılması gerekiyor
if (!isset($params['locale']) || empty($params['locale'])) {
throw new ApiErrorException(lang('Location is a required field'));
}
$getPropertyAdditionalInfo = $this->propertyAdditionalInfoService->getPropertyAdditionalInfo($params);
$getPropertyAdditionalInfo = $getPropertyAdditionalInfo ? $getPropertyAdditionalInfo : null;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getPropertyAdditionalInfo];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function insertPropertyAdditionalInfo()
{
$response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
//TODO : Validataion eklenecek ( benzersiz alanları unutma!!!). Eklendikten sonra if'in kaldırılması gerekiyor.
if (!isset($params['data'][0]['additional_info_key_id']) || empty($params['data'][0]['additional_info_key_id'])) {
throw new ApiErrorException(lang('Location is a required field'));
}
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyAdditionalInfo()
{
$response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
//TODO : Validataion eklenecek ( benzersiz alanları unutma!!!). Eklendikten sonra if'in kaldırılması gerekiyor.
if (!isset(current($params['data'])['additional_info_key_id']) || empty(current($params['data'])['additional_info_key_id'])) {
throw new ApiErrorException(lang('Location is a required field'));
}
$response = $this->propertyAdditionalInfoService->updatePropertyAdditionalInfo($params);
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,349 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\LanguageService;
use App\Core\Service\PropertyAddonService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Validator\PropertyAddon\PropertyAddonValidator;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Exception;
class PropertyAddonController extends Controller
{
private $params;
private $propertyAddonService;
private $propertyChannelMappingService;
private $propertyAddonValidator;
private $languageService;
public function __construct(
PropertyAddonService $propertyAddonService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyAddonValidator $propertyAddonValidator,
LanguageService $languageService
)
{
$this->params = Input::all();
$this->params = $this->params['params'];
$this->propertyAddonService = $propertyAddonService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyAddonValidator = $propertyAddonValidator;
$this->languageService = $languageService;
}
protected function propertyChannelMappingCheck($propertyId, $channelId)
{
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_id', 'condition' => '=', 'value' => $channelId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] == 'success') {
if (empty($propertyChannelMapping['data'])) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public function getPropertyAddon(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
//TODO: Validator
$propertyChannelMappingCheck = $this->propertyChannelMappingCheck($this->params['property_id'], $this->params['channel_id']);
if (!$propertyChannelMappingCheck) {
throw new ApiErrorException('Transactions cannot be made through a unconnected channel.');
}
$requestSelectCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['channel_id']],
['field' => 'status', 'condition' => '!=', 'value' => 3],
],
//'with' => ['propertyAddon']
];
$columns = ['id', 'property_id', 'channel_id', 'property_addon_id', 'title', 'description', 'amount', 'type', 'min_stay','status'];
$requestSelectResult = $this->propertyAddonService->selectPropertyChannelAddon($requestSelectCriteria, $columns);
$propertyChannelAddon = [];
if ($requestSelectResult['status'] == 'success') {
$propertyChannelAddon = $requestSelectResult['data'];
}
$propertyChannelAddonCollect = collect($propertyChannelAddon);
$requestSelectCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['fact'],
'orderBy' => [
['field' => 'order_number', 'value' => 'ASC']
],
];
$columns = ['id', 'fact_id', 'title', 'attribute', 'order_number'];
$propertyAddonResult = $this->propertyAddonService->selectPropertyAddon($requestSelectCriteria, $columns);
$propertyAddon = [];
if ($requestSelectResult['status'] == 'success') {
$propertyAddon = $propertyAddonResult['data'];
}
$getApplicationLanguages = $this->languageService->getApplicationLanguages();
if ($getApplicationLanguages['status'] != 'success') {
throw new ApiErrorException($getApplicationLanguages['message']);
}
$applicationLanguages = $getApplicationLanguages['data'];
$propertyAddonList = [];
foreach ($propertyAddon as $addon) {
$channelAddon = [];
$channelAddons = $propertyChannelAddonCollect->where('property_addon_id', $addon['id'])->toArray();
$isSelected = false;
if ($channelAddons) {
$channelAddons = array_values($channelAddons);
foreach ($channelAddons as $channelAddonItem) {
$responseLangDescription = [];
$descriptionLangContents = json_decode($channelAddonItem['description'], 1);
foreach ($applicationLanguages as $applicationLanguage) {
$langKey = $applicationLanguage['code'];
$responseLangDescription[] = [
'language_code' => $langKey,
'description' => isset($descriptionLangContents[$langKey]) ? $descriptionLangContents[$langKey] : null
];
}
$channelAddonItem['description'] = $responseLangDescription;
$channelAddon[] = $channelAddonItem;
}
$isSelected = true;
} else {
$responseLangDescription = [];
foreach ($applicationLanguages as $applicationLanguage) {
$langKey = $applicationLanguage['code'];
$responseLangDescription[] = [
'language_code' => $langKey,
'description' => null
];
}
$channelAddon[] = [
'property_id' => $this->params['property_id'],
'channel_id' => $this->params['channel_id'],
'property_addon_id' => $addon['id'],
'title' => '',
'description' => $responseLangDescription,
'amount' => '',
'type' => '',
'min_stay' => null,
'status' => 1
];
}
$propertyAddonList[] = [
'id' => $addon['id'],
'fact_id' => $addon['fact_id'],
'name' => $addon['fact']['name'],
'language_key' => $addon['fact']['language_key'],
'icon' => $addon['fact']['icon'],
'attributeArray' => $addon['attributeArray'],
'is_selected' => $isSelected,
'channelAddon' => $channelAddon
];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyAddonList];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncPropertyAddon(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
/*$validationResult = $this->propertyAddonValidator->validate($this->params);
if ($validationResult->errors()->first()) {
$errors = $validationResult->errors()->all();
throw new ApiErrorException($errors);
}*/
$propertyChannelMappingCheck = $this->propertyChannelMappingCheck($this->params['property_id'], $this->params['channel_id']);
if (!$propertyChannelMappingCheck) {
throw new ApiErrorException('Transactions cannot be made through a unconnected channel.');
}
$requestSelectCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['channel_id']],
['field' => 'property_addon_id', 'condition' => '=', 'value' => $this->params['property_addon_id']],
]
];
$columns = ['id', 'property_id', 'channel_id', 'property_addon_id', 'amount', 'type'];
$requestSelectResult = $this->propertyAddonService->selectPropertyChannelAddon($requestSelectCriteria, $columns);
$propertyChannelAddon = [];
if ($requestSelectResult['status'] == 'success') {
$propertyChannelAddon = $requestSelectResult['data'];
}
$currentPropertyChannelAddon = $propertyChannelAddon;
$propertyChannelAddon = collect($propertyChannelAddon);
DB::beginTransaction();
//Status Delete All ChannelAddon
foreach ($currentPropertyChannelAddon as $channelAddon) {
$updateParam = [
'property_id' => $channelAddon['property_id'],
'channel_id' => $channelAddon['channel_id'],
'property_addon_id' => $channelAddon['property_addon_id'],
'status' => 3,
'updated_by' => $request->auth->id,
];
$this->propertyAddonService->updatePropertyChannelAddon($channelAddon['id'], $updateParam);
}
//Status Delete All ChannelAddon
$channelAddonProcessed = [];
foreach ($this->params['channelAddon'] as $channelAddon) {
$description = [];
foreach (fillOnUndefined($channelAddon, "description", []) as $title) {
$description[$title['language_code']] = $title['description'];
}
if (!isset($channelAddon['id'])) {
$createParam = [
'property_id' => $this->params['property_id'],
'channel_id' => $this->params['channel_id'],
'property_addon_id' => $this->params['property_addon_id'],
'title' => fillOnUndefined($channelAddon, 'title'),
'description' => json_encode($description),
'amount' => $channelAddon['amount'],
'type' => $channelAddon['type'],
'min_stay' => fillOnUndefined($channelAddon,'min_stay'),
'status' => fillOnUndefined($channelAddon, 'status', 1) == 1 ? 1 : 0,
'created_by' => $request->auth->id,
'updated_by' => $request->auth->id,
];
$syncPropertyAddon = $this->propertyAddonService->createPropertyChannelAddon($createParam);
if ($syncPropertyAddon['status'] != 'success') {
throw new ApiErrorException($syncPropertyAddon['message']);
}
$channelAddonProcessed[] = $syncPropertyAddon['data'];
} elseif (isset($channelAddon['id']) && $propertyChannelAddon->where('id', $channelAddon['id'])->isNotEmpty()) {
$updateParam = [
'property_id' => $this->params['property_id'],
'channel_id' => $this->params['channel_id'],
'property_addon_id' => $this->params['property_addon_id'],
'title' => fillOnUndefined($channelAddon, 'title'),
'description' => json_encode($description),
'amount' => $channelAddon['amount'],
'type' => $channelAddon['type'],
'min_stay' => fillOnUndefined($channelAddon,'min_stay'),
'status' => fillOnUndefined($channelAddon, 'status', 1) == 1 ? 1 : 0,
'updated_by' => $request->auth->id,
];
$syncPropertyAddon = $this->propertyAddonService->updatePropertyChannelAddon($channelAddon['id'], $updateParam);
if ($syncPropertyAddon['status'] != 'success') {
throw new ApiErrorException($syncPropertyAddon['message']);
}
$channelAddonProcessed[] = $syncPropertyAddon['data'];
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelAddonProcessed];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,256 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\PropertyAwardsCertificateService;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Http\Request ;
use Exception ;
class PropertyAwardCertificatesController
{
private $request ;
private $propertyAwardsCertificateService;
public function __construct(
Request $request,
PropertyAwardsCertificateService $propertyAwardsCertificateService
)
{
$this->request = $request ;
$this->propertyAwardsCertificateService = $propertyAwardsCertificateService ;
}
public function getAwardCertificateCategories( ){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyAwardsCertificateList = $this->propertyAwardsCertificateService->getCategoryList($params);
if($getPropertyAwardsCertificateList['status'] != 'success'){
throw new Exception($getPropertyAwardsCertificateList['message']);
}
$responseData['award_certificate_categories'] = $getPropertyAwardsCertificateList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createAwardsCertificates(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params =
[
"property_id" => $request->input('property_id'),
"category_id" => $request->input('category_id'),
"language_code" => $request->input('language_code'),
"name" => $request->input('name'),
"date" => $request->input('date'),
"url" => $request->input('url'),
"file" => $request->file('file'),
];
$requestParams = $params;
$requestParams['user_id'] = $this->request->auth->id;
$storeAwardsCertificate = $this->propertyAwardsCertificateService->create($requestParams);
if ($storeAwardsCertificate['status'] != 'success') {
throw new ApiErrorException($storeAwardsCertificate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeAwardsCertificate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function listAwardsCertificates(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$storeAwardsCertificate = $this->propertyAwardsCertificateService->listAwardsCertificates($params);
if ($storeAwardsCertificate['status'] != 'success') {
throw new ApiErrorException($storeAwardsCertificate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeAwardsCertificate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateAwardsCertificates(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params =
[
"award_certificate_id" => $request->input('award_certificate_id'),
"property_id" => $request->input('property_id'),
"category_id" => $request->input('category_id'),
"language_code" => $request->input('language_code'),
"name" => $request->input('name'),
"date" => $request->input('date'),
"url" => $request->input('url'),
"file" => $request->file('file'),
];
$requestParams = $params;
$requestParams['user_id'] = $this->request->auth->id;
$storeAwardsCertificate = $this->propertyAwardsCertificateService->update($requestParams);
if ($storeAwardsCertificate['status'] != 'success') {
throw new ApiErrorException($storeAwardsCertificate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeAwardsCertificate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePhotoAwardsCertificates(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$storeAwardsCertificate = $this->propertyAwardsCertificateService->deletePhotoAwardsCertificates($params);
if ($storeAwardsCertificate['status'] != 'success') {
throw new ApiErrorException($storeAwardsCertificate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeAwardsCertificate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateStatusAwardsCertificates(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$storeAwardsCertificate = $this->propertyAwardsCertificateService->updateStatus($params);
if ($storeAwardsCertificate['status'] != 'success') {
throw new ApiErrorException($storeAwardsCertificate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $storeAwardsCertificate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,888 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Mail\CancelBookingMail;
use App\Http\Controllers\Controller;
use App\Core\Service\BookingService;
use App\Core\Service\PropertyBookingEngineService;
use App\Core\Service\BookingTicketService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Core\Service\ChannelManagerBookingService;
use App\Core\Service\BookingRoomService;
use App\Core\Service\PropertyRoomAvailabilityService;
use App\Core\Validator\Booking\BookingUpdateValidator;
use App\Export\PropertyBookingListExport;
use App\Core\Service\NewBookingMailService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Config;
use Maatwebsite\Excel\Facades\Excel;
class PropertyBookingController extends Controller
{
private $request;
private $bookingService;
private $propertyBookingEngineService;
private $bookingTicketService;
private $bookingUpdateValidator;
public function __construct(
Request $request,
Mailer $mailer,
BookingService $bookingService,
BookingRoomService $bookingRoomService,
PropertyBookingEngineService $propertyBookingEngineService,
BookingTicketService $bookingTicketService,
ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
ChannelManagerBookingService $channelManagerBookingService,
PropertyRoomAvailabilityService $propertyRoomAvailabilityService,
BookingUpdateValidator $bookingUpdateValidator,
NewBookingMailService $newBookingMailService
)
{
$this->request = $request;
$this->mailer = $mailer;
$this->bookingService = $bookingService;
$this->bookingRoomService = $bookingRoomService;
$this->propertyBookingEngineService = $propertyBookingEngineService;
$this->bookingTicketService = $bookingTicketService;
$this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
$this->channelManagerBookingService = $channelManagerBookingService;
$this->propertyRoomAvailabilityService = $propertyRoomAvailabilityService;
$this->bookingUpdateValidator = $bookingUpdateValidator;
$this->newBookingMailService = $newBookingMailService;
}
public function getPropertyBookingList(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyBooking = $this->bookingService->getBookingList($params);
if ($getPropertyBooking['status'] != "success") {
throw new ApiErrorException($getPropertyBooking['message']);
}
if (isset($params['excelExport']) && $params['excelExport']) {
foreach ($getPropertyBooking['data'] as $bookingKey => $booking) {
$dataTableData[$bookingKey]['booking_channel'] = $booking['booking_channel']['name'];
$dataTableData[$bookingKey]['booking_code'] = $booking['booking_code'];
$dataTableData[$bookingKey]['name_surname'] = $booking['booking_contact']['nameSurname'];
$dataTableData[$bookingKey]['checkin_date'] = $booking['checkin_date'];
$dataTableData[$bookingKey]['checkout_date'] = $booking['checkout_date'];
$dataTableData[$bookingKey]['payment_type'] = $booking['booking_payment_type']['name'];
$dataTableData[$bookingKey]['total'] = $booking['total'];
$dataTableData[$bookingKey]['currency_code'] = $booking['currency_code'];
$dataTableData[$bookingKey]['status'] = $booking['booking_status']['name'];
$dataTableData[$bookingKey]['reservation_time'] = Carbon::createFromTimestamp($booking['reservation_time'])->toDateTimeString();
}
$fileNameHash = [
'property_id' => $params['property_id'],
'channel_id' => fillOnUndefined($params['filter'], 'channel_id'),
'booking_code' => fillOnUndefined($params['filter'], 'booking_code'),
'payment_type_code' => fillOnUndefined($params['filter'], 'payment_type_code'),
'status' => fillOnUndefined($params['filter'], 'status'),
'date_type' => fillOnUndefined($params['filter'], 'date_type'),
'date_range' => fillOnUndefined($params['filter'], 'date_range'),
];
$fileName = 'PropertyBookingList-' . md5(implode('-', $fileNameHash)) . '.xlsx';
$fileNamePath = 'excel/' . $fileName;
$fileNamePublic = config('app.url') . '/' . $fileNamePath;
$excelStore = Excel::store(new PropertyBookingListExport($dataTableData), $fileNamePath, 'public');
if (!$excelStore) {
throw new ApiErrorException(lang('Mapping data not found'));
}
$data = [
'url' => $fileNamePublic
];
//Delete files older than 1 hours
$excelFileDir = public_path('excel');
foreach (glob($excelFileDir . '/' . "*") as $file) {
if (filemtime($file) < time() - 3600) { // 6 hours 21600
unlink($file);
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $data];
} else {
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['booking' => $getPropertyBooking['data']]];
}
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyBookingListFilter(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyBookingFilter = $this->bookingService->getPropertyBookingListFilter($params);
if ($getPropertyBookingFilter['status'] != "success") {
throw new ApiErrorException($getPropertyBookingFilter['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getPropertyBookingFilter['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyBookingDetail(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$bookingDetail = $this->bookingService->getBookingDetail($params);
if ($bookingDetail['status'] != "success") {
throw new ApiErrorException($bookingDetail['message']);
}
//BOOKING ADDON
$bookingAddons = $bookingDetail['data']['booking_addon'];
unset($bookingDetail['data']['booking_addon']);
$bookingAddonList = [];
foreach ($bookingAddons as $bookingAddon) {
$bookingAddonAttributeList = [];
$isHasAttribute = false;
$attributeArray = [];
if (!empty($bookingAddon['property_channel_addon']['property_addon']['attributeArray'])) {
$isHasAttribute = true;
$attributeArray = $bookingAddon['property_channel_addon']['property_addon']['attributeArray'];
$bookingAddonAttributes = json_decode($bookingAddon['attribute'], 1);
if (!is_null($bookingAddonAttributes)) {
foreach ($bookingAddonAttributes as $key => $bookingAddonAttribute) {
foreach ($bookingAddonAttribute as $bookingAddonAttributeKey => $bookingAddonAttributeValue) {
if (isset($bookingAddon['property_channel_addon']['property_addon']['attributeArray'][$bookingAddonAttributeKey])) {
$bookingAddonAttributeList[] = [
'key' => $bookingAddonAttributeKey,
'name' => $bookingAddon['property_channel_addon']['property_addon']['attributeArray'][$bookingAddonAttributeKey]['name'],
'language_key' => $bookingAddon['property_channel_addon']['property_addon']['attributeArray'][$bookingAddonAttributeKey]['language_key'],
'value' => $bookingAddonAttributeValue,
];
}
}
}
}
}
$bookingAddonList[] = [
'id' => $bookingAddon['id'],
'booking_id' => $bookingAddon['booking_id'],
'property_channel_addon_id' => $bookingAddon['property_channel_addon_id'],
'count' => $bookingAddon['count'],
'amount' => $bookingAddon['amount'],
'total' => $bookingAddon['total'],
'min_stay' => $bookingAddon['property_channel_addon']['min_stay'],
'currency_code' => $bookingAddon['currency_code'],
'name' => $bookingAddon['property_channel_addon']['property_addon']['fact']['name'],
'title' => $bookingAddon['property_channel_addon']['title'],
'language_key' => $bookingAddon['property_channel_addon']['property_addon']['fact']['language_key'],
'icon' => $bookingAddon['property_channel_addon']['property_addon']['fact']['icon'],
'isHasAttribute' => $isHasAttribute,
'attributeArray' => $attributeArray,
'attribute' => $bookingAddonAttributeList
];
}
$bookingDetail['data']['booking_addon'] = $bookingAddonList;
//BOOKING ADDON
//DAILY AMOUNT BY ROOM
foreach ($bookingDetail['data']['booking_room'] as $roomKey => $roomDetail) {
if (!empty($roomDetail['room_rate_mapping']['property_room'])) {
$bookingDetail['data']['booking_room'][$roomKey]['room_name'] = $roomDetail['room_rate_mapping']['property_room']['name'];
}
if (!empty($roomDetail['room_rate_mapping']['property_room_rate'])) {
$bookingDetail['data']['booking_room'][$roomKey]['room_rate_name'] = $roomDetail['room_rate_mapping']['property_room_rate']['name'];
}
$diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
$baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
$roomDailyAmount = [];
if (!empty($roomDetail['daily_amount'])) {
$roomDetailDailyAmount = json_decode($roomDetail['daily_amount'], 1);
if (!empty($roomDetailDailyAmount) && isset($roomDetailDailyAmount)) {
foreach ($roomDetailDailyAmount as $roomRateAmount) {
$roomDailyAmount[] = [
'date' => $roomRateAmount['date'],
'amount' => $roomRateAmount['amount'],
'currency_code' => $roomRateAmount['currency_code'],
];
}
}
}
if (empty($roomDailyAmount)) {
$roomRateDetail = is_array($roomDetail['rate_detail']) ? $roomDetail['rate_detail'] : json_decode($roomDetail['rate_detail'], 1);
if (!empty($roomRateDetail) && isset($roomRateDetail['days'])) {
foreach ($roomRateDetail['days'] as $roomRateDay => $roomRateAmount) {
$roomDailyAmount[] = [
'date' => Carbon::parse($roomRateDay)->toDateString(),
'amount' => $roomRateAmount,
'currency_code' => $roomDetail['currency_code'],
];
}
}
}
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();
}
}
$bookingDetail['data']['booking_room'][$roomKey]['daily_amount'] = $roomDailyAmount;
$extraParam = null;
if (!empty($roomDetail['extra_param'])) {
$extraParamDecode = json_decode($roomDetail['extra_param'], 1);
foreach ($extraParamDecode as $extraParamKey => $extraParamValue) {
$extraParamTitle = explode('_', $extraParamKey);
foreach ($extraParamTitle as $extraParamTitleKey => $extraParamTitleValue) {
$extraParamTitle[$extraParamTitleKey] = ucwords($extraParamTitleValue);
}
$extraParamTitle = implode(' ', $extraParamTitle);
$extraParam[$extraParamKey] = [
'title' => $extraParamTitle,
'value' => $extraParamValue,
];
}
}
$bookingDetail['data']['booking_room'][$roomKey]['extra_param'] = $extraParam;
$bookingDetail['data']['booking_room'][$roomKey]['occupancyFormatted'] = occupancyCodeFormatted($roomDetail['occupancy_code']);
}
//DAILY AMOUNT BY ROOM
if (empty($bookingDetail['data']['is_viewed'])) {
$this->bookingService->update($params['booking_id'], ['is_viewed' => 1]);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['booking_detail' => $bookingDetail['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function sendBookingEmail(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$bookingDetail = $this->bookingService->getBookingDetail($params);
if ($bookingDetail['status'] != "success") {
throw new ApiErrorException($bookingDetail['message']);
}
if (!in_array($bookingDetail['data']['status'], [0,1])) {
throw new ApiErrorException('Only active and canceled reservation emails can be sent');
}
if (in_array($bookingDetail['data']['status'], [0])) {
$mailParams = ['booking_id' => $params['booking_id']];
$this->mailer->onQueue('cancelBookingMail', new CancelBookingMail($mailParams));
}
if (in_array($bookingDetail['data']['status'], [1])) {
$mailParams = ['booking_id' => $params['booking_id']];
$this->newBookingMailService->process($mailParams);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => []];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function bookEngineDashboard(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyBookingEngine = $this->propertyBookingEngineService->bookEngineDashboard($params);
if ($getPropertyBookingEngine['status'] != "success") {
throw new ApiErrorException($getPropertyBookingEngine['message']);
}
$responseData['booking_engine'] = $getPropertyBookingEngine['data'];
//Cache
$getBookingDetailedListCacheKey = md5('getBookingDetailedList-' . $params['property_id']);
if (Cache::has($getBookingDetailedListCacheKey)) {
$responseDataCache = Cache::get($getBookingDetailedListCacheKey);
$responseData['all_booking_count'] = $responseDataCache['all_booking_count'];
$responseData['success_booking_count'] = $responseDataCache['success_booking_count'];
$responseData['pre_booking_count'] = $responseDataCache['pre_booking_count'];
$responseData['conversion_rate'] = $responseDataCache['conversion_rate'];
$responseData['total_pax_count'] = $responseDataCache['total_pax_count'];
} else {
$getPropertyBooking = $this->bookingService->getBookingDetailedList($params);
if ($getPropertyBooking['status'] != "success") {
throw new ApiErrorException($getPropertyBooking['message']);
}
$bookings = collect($getPropertyBooking['data']);
$channelBookings = $bookings->where('channel_id', '=', 1);
$getBookingEngineBookings = $channelBookings->all();
$paxCountArray = $channelBookings->where('status', '=', 1)->map(function ($booking) {
$roomPaxCount = collect($booking['booking_room'])->map(function ($room) {
return collect($room['room_pax'])->count();
})->values()->first();
return [
'booking_id' => $booking['id'],
'room_pax_count' => $roomPaxCount,
];
})->values()->all();
$totalPaxCount = collect($paxCountArray)->sum('room_pax_count');
$allBookingCount = $channelBookings->count();
$preBookingCount = $channelBookings->where('status', '=', 2)->count();
$successBookingCount = $channelBookings->where('status', '=', 1)->count();
$conversionRate = $allBookingCount > 0 ? ($successBookingCount * 100) / $allBookingCount : 0;
$responseData['all_booking_count'] = $allBookingCount;
$responseData['success_booking_count'] = $successBookingCount;
$responseData['pre_booking_count'] = $preBookingCount;
$responseData['conversion_rate'] = number_format($conversionRate, 2);
$responseData['total_pax_count'] = $totalPaxCount;
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function bookingEngineContractUpload(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params =
[
"property_id" => $request->input('property_id'),
"contract_file" => $request->file('contract_file'),
"user_id" => $this->request->auth->id
];
$uploadResponse = $this->propertyBookingEngineService->contractFileUpload($params);
if ($uploadResponse['status'] != "success") {
throw new ApiErrorException($uploadResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $uploadResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyTransactionList(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyTransaction = $this->bookingService->getTransactionList($params);
if ($getPropertyTransaction['status'] != "success") {
throw new ApiErrorException($getPropertyTransaction['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['transactions' => $getPropertyTransaction['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateBooking(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
DB::beginTransaction();
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
if (!isset($params['property_id'])) {
$params = $this->request->requestParams;
}
$validationResult = $this->bookingUpdateValidator->validate($params);
if ($validationResult->errors()->first()) {
$errors = $validationResult->errors()->all();
throw new ApiErrorException($errors);
}
$bookingstatusList = $this->bookingService->getBookingstatusList();
$bookingstatusListCollect = collect($bookingstatusList['data']);
if ($bookingstatusListCollect->where('id', $params['status'])->count() <= 0) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$bookingRequest = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['booking_id']],
],
'with' => ['bookingRoom','propertyBookingEngineSearch'],
'firstRow' => true
];
$booking = $this->bookingService->select($bookingRequest);
if ($booking['status'] != 'success') {
throw new ApiErrorException($booking['message']);
}
if (empty($booking['data'])) {
throw new ApiErrorException('Booking not found.');
}
$booking = $booking['data'];
$isNonRefundable = false;
if($params['status'] == 0) {
foreach ($booking['booking_room'] as $roomDetail) {
$cancellationPolicy = json_decode($roomDetail['cancellation_policy'],1);
if(!empty($cancellationPolicy) && is_array($cancellationPolicy)) {
if(isset($cancellationPolicy['isNonRefundable']) && $cancellationPolicy['isNonRefundable']) {
$isNonRefundable = true;
break;
}
}
}
}
//Trivago Check
/*if(isset($booking['property_booking_engine_search']['referrer']) && $booking['property_booking_engine_search']['referrer'] == 'trivago:trivago') {
if($isNonRefundable) {
throw new ApiErrorException('Refunds are not permitted for non-refundable transactions received through Trivago.');
}
}*/
$bookingUpdateParam = [];
$bookingUpdateAvailableColumns = ['total', 'status', 'currency_code'];
foreach ($params as $param => $value) {
if (in_array($param, $bookingUpdateAvailableColumns)) {
$bookingUpdateParam[$param] = $value;
}
}
$action = null;
$percentage = 1;
if ($booking['status'] == 0) {
$percentage = 0;
} elseif ($bookingUpdateParam['total'] > $booking['total']) {
$action = 'INC';
$percentage = ($bookingUpdateParam['total'] - $booking['total']) / $booking['total'] * 100;
} else {
$action = 'DEC';
$percentage = ($booking['total'] - $bookingUpdateParam['total']) / $booking['total'] * 100;
}
$bookingUpdate = $this->bookingService->update($booking['id'], $bookingUpdateParam);
if ($bookingUpdate['status'] != 'success') {
throw new ApiErrorException($booking['message']);
}
foreach ($booking['booking_room'] as $room) {
if (!is_null($action)) {
$totalAmount = $room['total'];
$affectedAmount = ($room['total'] * $percentage) / 100;
if ($action == 'INC') {
$totalAmount = $totalAmount + $affectedAmount;
}
if ($action == 'DEC') {
$totalAmount = $totalAmount - $affectedAmount;
}
$bookingRoomUpdate = $this->bookingRoomService->update($room['id'], ['total' => $totalAmount]);
if ($bookingUpdate['status'] != 'success') {
throw new ApiErrorException($bookingRoomUpdate['message']);
}
}
//Availability Decrease
if (in_array($params['status'], [0, 3]) && $booking['status'] == 1) {
$dateByDay = [];
$diffInDays = Carbon::parse($room['checkin_date'])->floatDiffInDays(Carbon::parse($room['checkout_date']));
for ($i = 0; $i < $diffInDays; $i++) {
$dateByDay[] = Carbon::parse($room['checkin_date'])->addDay($i)->format('Y-m-d');
}
foreach ($dateByDay as $day) {
$requestParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $booking['property_id']],
['field' => 'property_room_id', 'condition' => '=', 'value' => $room['room_id']],
['field' => 'availability_type_id', 'condition' => '=', 'value' => 1],
['field' => 'date', 'condition' => '=', 'value' => $day]
],
'firstRow' => true,
];
$dateAvailability = $this->propertyRoomAvailabilityService->select($requestParam);
if ($dateAvailability['status'] == 'success') {
$currentAvailability = $dateAvailability['data']['availability'];
$currentAvailability = $currentAvailability + 1;
$this->propertyRoomAvailabilityService->update($dateAvailability['data']['id'], ['availability' => $currentAvailability]);
}
}
}
}
//PUSH CHANNEL MANAGER QUEUE
//if ($booking['channel_id'] == 1) {
$type = 'Modify';
if (in_array($params['status'], [1, 2, 3])) {
$type = 'Modify';
}
if (in_array($params['status'], [0])) {
$type = 'Cancel';
}
$channelManagerPropertyMappingCriteria = [
'criteria' =>
[
['field' => 'property_id', 'condition' => '=', 'value' => $booking['property_id']],
['field' => 'channel_manager_property_id', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$channelManagerPropertyMapping = $this->channelManagerPropertyMappingService->select($channelManagerPropertyMappingCriteria);
if ($channelManagerPropertyMapping['status'] == 'success' && !empty($channelManagerPropertyMapping['data'])) {
foreach ($channelManagerPropertyMapping['data'] as $channelPropertyData) {
$extraParamDecode = json_decode($booking['extra_param'], 1);
if($channelPropertyData['channel_manager_id'] == 11 && !isset($extraParamDecode['trv_reference'])) {
continue;
}
//Yandex
if(in_array($channelPropertyData['channel_manager_id'],[13])) {
continue;
}
$channelManagerBookingCreateParam = [
'property_id' => $booking['property_id'],
'booking_id' => $booking['id'],
'channel_manager_id' => $channelPropertyData['channel_manager_id'],
'type' => $type,
];
$channelManagerBookingCreate = $this->channelManagerBookingService->create($channelManagerBookingCreateParam);
}
}
//}
//PUSH CHANNEL MANAGER QUEUE
//Booking Ticket Log
$bookingTicketRequest = [
'criteria' => [
['field' => 'booking_id', 'condition' => '=', 'value' => $booking['id']],
],
'firstRow' => true
];
$bookingTicket = $this->bookingTicketService->select($bookingTicketRequest, ['id']);
$userId = isset($this->request->auth->id) ? $this->request->auth->id : 1;
$createBookingTicketParams = [];
if (empty($bookingTicket['data'])) {
$createBookingTicketParams = [
'booking_id' => $booking['id'],
'code' => getTicketCodeGenerate('TCK'),
'user_id' => $userId,
'is_log' => true,
'log' => json_encode($booking),
'status' => 1
];
} else {
$createBookingTicketParams = [
'parent_id' => $bookingTicket['data']['id'],
'booking_id' => $booking['id'],
'user_id' => $userId,
'is_log' => true,
'log' => json_encode($booking),
'status' => 1
];
}
$bookingTicketCreate = $this->bookingTicketService->create($createBookingTicketParams);
//Booking Ticket Log
if ($type == 'Cancel') {
$notificationCancelToPropertyUser = [
'booking_id' => $booking['id'],
];
$this->mailer->onQueue('cancelBookingMail', new CancelBookingMail($notificationCancelToPropertyUser));
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['transactions' => $bookingUpdate['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getBookingPayment(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$getBookingPayment = $this->bookingService->getBookingPayment($params);
if ($getBookingPayment['status'] != "success") {
throw new ApiErrorException($getBookingPayment['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getBookingPayment['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,293 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Mail\BookingTicketMail;
use App\Core\Service\BookingService;
use App\Core\Service\BookingTicketService;
use App\Core\Service\NotificationService;
use App\Core\Validator\PropertyBookingTicket\PropertyTicketCreateValidator;
use App\Core\Validator\PropertyBookingTicket\PropertyTicketGetValidator;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
class PropertyBookingTicketController extends Controller
{
private $currencyService;
public function __construct(
Request $request,
BookingService $bookingService,
BookingTicketService $bookingTicketService,
PropertyTicketGetValidator $propertyTicketGetValidator,
PropertyTicketCreateValidator $propertyTicketCreateValidator,
Mailer $mailer,
NotificationService $notificationService
)
{
$this->bookingService = $bookingService;
$this->bookingTicketService = $bookingTicketService;
$this->propertyTicketGetValidator = $propertyTicketGetValidator;
$this->propertyTicketCreateValidator = $propertyTicketCreateValidator;
$this->mailer = $mailer;
$this->notificationService = $notificationService;
$this->params = json_decode($request->getContent(), 1);
$this->params = $this->params['params'];
}
public function createTicket(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
DB::beginTransaction();
$params = $this->params;
if(is_null($params)) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params['ip_address'] = fillOnUndefined($params,'ip_address') ? $params['ip_address'] : $request->ip();
$validationResult = $this->propertyTicketCreateValidator->validate($params);
if ($validationResult->errors()->first()) {
$errors = $validationResult->errors()->all();
throw new ApiErrorException($errors);
}
$bookingRequest = [
'criteria' => [
['field' => 'booking_code', 'condition' => '=', 'value' => $params['booking_code']],
],
'firstRow' => true
];
$booking = $this->bookingService->select($bookingRequest);
if ($booking['status'] != 'success') {
throw new ApiErrorException($booking['message']);
}
if (empty($booking['data'])) {
throw new ApiErrorException('Booking not found.');
}
$booking = $booking['data'];
$bookingTicketRequest = [
'criteria' => [
['field' => 'booking_id', 'condition' => '=', 'value' => $booking['id']],
],
'firstRow' => true
];
$bookingTicket = $this->bookingTicketService->select($bookingTicketRequest, ['id']);
if ($bookingTicket['status'] != 'success') {
throw new ApiErrorException($bookingTicket['message']);
}
$createParams = [];
if (empty($bookingTicket['data'])) {
$createParams = [
'booking_id' => $booking['id'],
'code' => getTicketCodeGenerate('TCK'),
'user_id' => $params['user_id'],
'message' => $params['message'],
'is_note' => fillOnUndefined($params, 'is_note') == false ? null : $params['is_note'],
'is_log' => fillOnUndefined($params, 'is_log'),
'ip_address' => fillOnUndefined($params,'ip_address'),
'status' => 1
];
} else {
$createParams = [
'parent_id' => $bookingTicket['data']['id'],
'booking_id' => $booking['id'],
'user_id' => $params['user_id'],
'message' => $params['message'],
'is_note' => fillOnUndefined($params, 'is_note') == false ? null : $params['is_note'],
'is_log' => fillOnUndefined($params, 'is_log'),
'ip_address' => fillOnUndefined($params,'ip_address'),
'status' => 1
];
}
$bookingTicketCreate = $this->bookingTicketService->create($createParams);
if ($bookingTicketCreate['status'] != 'success') {
throw new ApiErrorException($bookingTicketCreate['message']);
}
//BookingTicketMail
if(is_null($createParams['is_note'])) {
$mailParams = [
'user' => $params['user_id'],
'booking_id' => $booking['id'],
//'locale' => 'en'
];
$this->mailer->onQueue('bookingTicketMail', new BookingTicketMail($mailParams));
}
//BookingTicketMail
//PUSH NOTIFICATION
if(empty($params['user_id'])) {
$notificationParam = ['booking_id' => $booking['id']];
$this->notificationService->sendTicketNotification($notificationParam);
}
//PUSH NOTIFICATION
if(empty($params['user_id'])) {
$this->bookingService->update($booking['id'], ['is_viewed' => null]);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $bookingTicketCreate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if($response['status']) {
DB::commit();
}else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getTicketList()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->params;
if(is_null($params)) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$validationResult = $this->propertyTicketGetValidator->validate($params);
if ($validationResult->errors()->first()) {
$errors = $validationResult->errors()->all();
throw new ApiErrorException($errors);
}
$bookingRequest = [
'criteria' => [
['field' => 'booking_code', 'condition' => '=', 'value' => $params['booking_code']],
],
'with' => ['bookingContact'],
'firstRow' => true
];
$booking = $this->bookingService->select($bookingRequest);
if ($booking['status'] != 'success') {
throw new ApiErrorException($booking['message']);
}
$booking = $booking['data'];
$bookingTicketRequest = [
'criteria' => [
['field' => 'booking_id', 'condition' => '=', 'value' => $booking['id']],
['field' => 'is_log', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['user'],
'orderBy' => [
['field' => 'created_at', 'value' => 'ASC']
]
];
if (!isset($params['user_id']) || is_null($params['user_id'])) {
$bookingTicketRequest['criteria'][] = ['field' => 'is_note', 'condition' => '=', 'value' => null];
}
$column = ['id', 'user_id', 'message', 'is_note', 'is_viewed', 'created_at'];
$bookingTicket = $this->bookingTicketService->select($bookingTicketRequest, $column);
if ($bookingTicket['status'] != 'success') {
throw new ApiErrorException($bookingTicket['message']);
}
foreach ($bookingTicket['data'] as $key => $row) {
if(is_null($row['user_id'])) {
$bookingTicket['data'][$key]['nameSurname'] = $booking['booking_contact']['nameSurname'];
} else {
$bookingTicket['data'][$key]['nameSurname'] = $row['user']['nameSurname'];
}
unset($bookingTicket['data'][$key]['user']);
}
$updateCriteria = [
'criteria' => [
['field' => 'booking_id', 'condition' => '=', 'value' => $booking['id']],
['field' => 'is_log', 'condition' => '=', 'value' => null],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
if (!isset($params['user_id']) || is_null($params['user_id'])) {
$updateCriteria['criteria'][] = ['field' => 'user_id', 'condition' => '!=', 'value' => null];
$updateCriteria['criteria'][] = ['field' => 'is_viewed', 'condition' => '=', 'value' => null];
} else {
$updateCriteria['criteria'][] = ['field' => 'user_id', 'condition' => '=', 'value' => null];
$updateCriteria['criteria'][] = ['field' => 'is_viewed', 'condition' => '=', 'value' => null];
}
$updateParam = [
'is_viewed' => 1
];
$this->bookingTicketService->updateWhere($updateCriteria, $updateParam);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $bookingTicket['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,158 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyBrandService;
use App\Core\Service\PropertyConfigService ;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Config;
class PropertyBrandController extends Controller
{
private $request;
private $propertyBrandService;
private $propertyConfigService;
public function __construct(
Request $request,
PropertyBrandService $propertyBrandService,
PropertyConfigService $propertyConfigService
)
{
$this->request = $request;
$this->propertyBrandService = $propertyBrandService;
$this->propertyConfigService = $propertyConfigService ;
}
public function updatePropertyBrand(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params =
[
"property_id" => $request->input('property_id'),
"title" => $request->input("title"),
"color_codes" => $request->input("colors"),
"logo_path" => $request->input( "logo_path"),
"logo_name" => $request->input( "logo_name"),
"photo" => $request->file('photo'),
"user_id" => $this->request->auth->id
];
$updateResponse = $this->propertyBrandService->updatePropertyBrand($params);
if($updateResponse['status'] != 'success'){
throw new ApiErrorException($updateResponse['message']);
}
$rateParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => fillOnUndefined($params, 'user_id'),
'property_rate_for' => 'Property.Brand.Update',
];
$this->propertyConfigService->rateProperty(array_merge($params, $rateParams));
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['get_property_brand' => $updateResponse['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyBrand(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyBrand = $this->propertyBrandService->getPropertyBrand($params);
if($getPropertyBrand['status'] != "success"){
throw new ApiErrorException($getPropertyBrand['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['get_property_brand' => $getPropertyBrand['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function clearBrandLogo(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->credentials->user_id;
$getPropertyBrand = $this->propertyBrandService->clearBrandLogo($params);
if($getPropertyBrand['status'] != "success"){
throw new ApiErrorException($getPropertyBrand['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ''];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyCancellationPolicyService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyCancellationPolicyController extends Controller
{
private $request;
private $propertyCancellationPolicyService;
public function __construct(
Request $request,
PropertyCancellationPolicyService $propertyCancellationPolicyService
)
{
$this->request = $request;
$this->propertyCancellationPolicyService = $propertyCancellationPolicyService;
}
public function getPropertyCancellationPolicyList(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyCancellationList = $this->propertyCancellationPolicyService->getPropertyCancellationPolicyList($params);
if ($getPropertyCancellationList['status'] != "success") {
throw new ApiErrorException($getPropertyCancellationList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['cancellation_policies' => $getPropertyCancellationList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyCancellationPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
if (!isset($params['is_date_range']) || (isset($params['is_date_range']) && $params['is_date_range'] == 0)) {
$params['is_date_range'] = 0;
unset($params['start_date']);
unset($params['finish_date']);
}
$createResponse = $this->propertyCancellationPolicyService->createPropertyCancellationPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyCancellationPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
if (!isset($params['is_date_range']) || (isset($params['is_date_range']) && $params['is_date_range'] == 0)) {
$params['is_date_range'] = 0;
unset($params['start_date']);
unset($params['finish_date']);
}
$updateResponse = $this->propertyCancellationPolicyService->updatePropertyCancellationPolicy($params);
if ($updateResponse['status'] != 'success') {
throw new ApiErrorException($updateResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $updateResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getRoomRateChannelCancellationPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyCancellationList = $this->propertyCancellationPolicyService->getRoomRateChannelCancellationPolicy($params);
if ($getPropertyCancellationList['status'] != "success") {
throw new ApiErrorException($getPropertyCancellationList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['rooms' => $getPropertyCancellationList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateRoomRateChannelCancellationPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$getPropertyCancellationList = $this->propertyCancellationPolicyService->updateRoomRateChannelCancellationPolicy($params);
if ($getPropertyCancellationList['status'] != "success") {
throw new ApiErrorException($getPropertyCancellationList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChainService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyChainController
{
private $request;
private $propertyChainService;
public function __construct(
Request $request,
PropertyChainService $propertyChainService
)
{
$this->request = $request;
$this->propertyChainService = $propertyChainService;
}
public function getPropertyChains(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
];
$propertyChains = $this->propertyChainService->getPropertyChains($requestParams);
if($propertyChains['status'] != 'success'){
throw new ApiErrorException($propertyChains['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChains['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,111 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChannelBookingPaymentSetupService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyChannelBookingPaymentSetupController
{
private $request;
private $propertyChannelBookingPaymentSetupService;
public function __construct(
Request $request,
PropertyChannelBookingPaymentSetupService $propertyChannelBookingPaymentSetupService
)
{
$this->request = $request;
$this->propertyChannelBookingPaymentSetupService = $propertyChannelBookingPaymentSetupService;
}
public function getPropertyChannelBookingPaymentSetup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$propertyChannelBookingPaymentSetup = $this->propertyChannelBookingPaymentSetupService->getChannelBookingPaymentSetup($requestParams);
if($propertyChannelBookingPaymentSetup['status'] != 'success'){
throw new ApiErrorException($propertyChannelBookingPaymentSetup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelBookingPaymentSetup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyChannelBookingPaymentSetup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = $params ;
$requestParams['user_id'] = $this->request->auth->id;
$propertyChannelBookingPaymentSetup = $this->propertyChannelBookingPaymentSetupService->addChannelBookingPaymentSetup($requestParams);
if($propertyChannelBookingPaymentSetup['status'] != 'success'){
throw new ApiErrorException($propertyChannelBookingPaymentSetup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelBookingPaymentSetup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChannelCategoryService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyChannelCategoryController
{
private $request;
private $propertyChannelCategoryService;
public function __construct(
Request $request,
PropertyChannelCategoryService $propertyChannelCategoryService
)
{
$this->request = $request;
$this->propertyChannelCategoryService = $propertyChannelCategoryService;
}
public function getPropertyChannelCategories(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
];
$propertyChannelCategory = $this->propertyChannelCategoryService->getPropertyChannelCategories($requestParams);
if($propertyChannelCategory['status'] != 'success'){
throw new ApiErrorException($propertyChannelCategory['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelCategory['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,262 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyChannelContactService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class PropertyChannelContactController extends Controller
{
private $request;
private $propertyChannelService;
private $propertyChannelMappingService;
private $propertyChannelContactService;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyChannelContactService $propertyChannelContactService
)
{
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyChannelContactService = $propertyChannelContactService;
}
public function getPropertyChannelContact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$channelMappingRequest = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$channelMapping = $this->propertyChannelMappingService->getOnlyPropertyChannelMapping($channelMappingRequest);
if($channelMapping['status'] != 'success'){
throw new ApiErrorException($channelMapping['message']);
}
if(!count($channelMapping['data'])){
throw new ApiErrorException("This channel is not connected with this property");
}
$channelContactRequest = [
'property_channel_mapping_id' => $channelMapping["data"]["id"],
];
if(isset($request->params['id'])){
$channelContactRequest = [
'id' => fillOnUndefined($params, 'id'),
'property_channel_mapping_id' => $channelMapping["data"]["id"],
];
}
$channelContact = $this->propertyChannelContactService->getContact($channelContactRequest);
if($channelContact['status'] != 'success'){
throw new ApiErrorException($channelContact['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelContact['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyChannelContact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$channelMappingRequest = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$channelMapping = $this->propertyChannelMappingService->getOnlyPropertyChannelMapping($channelMappingRequest);
if($channelMapping['status'] != 'success'){
throw new ApiErrorException($channelMapping['message']);
}
if(!count($channelMapping['data'])){
throw new ApiErrorException("This channel is not connected with this property");
}
$requestParams = [
'property_channel_mapping_id' => $channelMapping["data"]["id"],
'name' => fillOnUndefined($params, 'name', null),
'email' => fillOnUndefined($params, 'email', null),
'user_id' => $this->request->auth->id,
];
$channelContact = $this->propertyChannelContactService->add($requestParams);
if($channelContact['status'] != 'success'){
throw new ApiErrorException($channelContact['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelContact['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyChannelContact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$channelMappingRequest = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$channelMapping = $this->propertyChannelMappingService->getOnlyPropertyChannelMapping($channelMappingRequest);
if($channelMapping['status'] != 'success'){
throw new ApiErrorException($channelMapping['message']);
}
if(!count($channelMapping['data']) || $channelMapping['data']['id'] != $params['property_channel_mapping_id']){
throw new ApiErrorException("This channel is not connected with this property");
}
$requestParams = [
'name' => fillOnUndefined($params, 'name', null),
'email' => fillOnUndefined($params, 'email', null),
'updated_by' => $this->request->auth->id,
'updated_at' => time()
];
$channelContact = $this->propertyChannelContactService->update($params['id'],$requestParams);
if($channelContact['status'] != 'success'){
throw new ApiErrorException($channelContact['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelContact['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyChannelContact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$channelMappingRequest = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$channelMapping = $this->propertyChannelMappingService->getOnlyPropertyChannelMapping($channelMappingRequest);
if($channelMapping['status'] != 'success'){
throw new ApiErrorException($channelMapping['message']);
}
if(!count($channelMapping['data']) || $channelMapping['data']['id'] != $params['property_channel_mapping_id']){
throw new ApiErrorException("This channel is not connected with this property");
}
$requestParams = [
'id' => $params["id"],
'property_channel_mapping_id' => $params['property_channel_mapping_id']
];
$channelContact = $this->propertyChannelContactService->delete($requestParams);
if($channelContact['status'] != 'success'){
throw new ApiErrorException($channelContact['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelContact['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChannelService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyChannelController
{
private $request;
private $propertyChannelService;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService
)
{
$this->request = $request;
$this->propertyChannelService = $propertyChannelService;
}
public function getPropertyChannel(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'parent_id' => fillOnUndefined($params, 'parent_id'),
'type' => fillOnUndefined($params, 'type'),
'channel_category_id' => fillOnUndefined($params, 'channel_category_id'),
'country_code' => fillOnUndefined($params, 'country_code'),
];
$propertyChannel = $this->propertyChannelService->getPropertyChannels($requestParams);
if($propertyChannel['status'] != 'success'){
throw new ApiErrorException($propertyChannel['message']);
}
//CHANNEL RESTRICTION PROPERTIES
foreach ($propertyChannel['data'] as $channelId => $channel) {
if(!empty($channel['restriction'])) {
$channelRestriction = json_decode($channel['restriction'],1);
if(!in_array($params['property_id'],$channelRestriction)) {
unset($propertyChannel['data'][$channelId]);
}
}
}
//dd($propertyChannel['data'], $params['property_id']);
//TODO: Channell sıralaması için bir alan seçilip kurgulanacak
//$propertyChannelCollect = collect($propertyChannel['data']);
//$propertyChannel['data'] = $propertyChannelCollect->sortByDesc('fax', SORT_NUMERIC )->toArray();
//$propertyChannel['data'] = array_values($propertyChannel['data']);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannel['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyChannel(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'parent_id' => fillOnUndefined($params, 'parent_id'),
'name' => fillOnUndefined($params, 'name'),
'official_name' => fillOnUndefined($params, 'official_name'),
'description' => fillOnUndefined($params, 'description'),
'channel_category_id' => fillOnUndefined($params, 'channel_category_id'),
'country_code' => fillOnUndefined($params, 'country_code'),
'currency_code' => fillOnUndefined($params, 'currency_code', []),
'logo' => fillOnUndefined($params, 'logo'),
'address' => fillOnUndefined($params, 'address'),
'zip_code' => fillOnUndefined($params, 'zip_code'),
'email' => fillOnUndefined($params, 'email'),
'phone' => fillOnUndefined($params, 'phone'),
'phone2' => fillOnUndefined($params, 'phone2'),
'fax' => fillOnUndefined($params, 'fax'),
'score' => fillOnUndefined($params, 'score'),
'user_id' => $this->request->auth->id,
];
$propertyChannel = $this->propertyChannelService->addPropertyChannel($requestParams);
if($propertyChannel['status'] != 'success'){
throw new ApiErrorException($propertyChannel['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannel['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyChannel(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'parent_id' => fillOnUndefined($params, 'parent_id'),
'name' => fillOnUndefined($params, 'name'),
'official_name' => fillOnUndefined($params, 'official_name'),
'description' => fillOnUndefined($params, 'description'),
'channel_category_id' => fillOnUndefined($params, 'channel_category_id'),
'country_code' => fillOnUndefined($params, 'country_code'),
'currency_code' => fillOnUndefined($params, 'currency_code', []),
'logo' => fillOnUndefined($params, 'logo'),
'address' => fillOnUndefined($params, 'address'),
'zip_code' => fillOnUndefined($params, 'zip_code'),
'email' => fillOnUndefined($params, 'email'),
'phone' => fillOnUndefined($params, 'phone'),
'phone2' => fillOnUndefined($params, 'phone2'),
'fax' => fillOnUndefined($params, 'fax'),
'score' => fillOnUndefined($params, 'score'),
'user_id' => $this->request->auth->id,
];
$propertyChannel = $this->propertyChannelService->updatePropertyChannel($requestParams);
if($propertyChannel['status'] != 'success'){
throw new ApiErrorException($propertyChannel['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannel['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,497 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChannelGroupService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyRoomService;
use App\Core\Repository\PropertyChannelGroup\PropertyChannelGroupChannelMappingRepository;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class PropertyChannelGroupController extends Controller
{
private $request;
private $propertyChannelGroupService;
private $propertyChannelMappingService;
private $propertyRoomService;
private $propertyChannelGroupChannelMappingRepository;
public function __construct(
Request $request,
PropertyChannelGroupService $propertyChannelGroupService,
PropertyChannelGroupChannelMappingRepository $propertyChannelGroupChannelMappingRepository,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomService $propertyRoomService
)
{
$this->request = $request;
$this->propertyChannelGroupService = $propertyChannelGroupService;
$this->propertyChannelGroupChannelMappingRepository = $propertyChannelGroupChannelMappingRepository;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomService = $propertyRoomService;
}
public function getPropertyChannelGroup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
];
if(isset($request->params['group_id'])){
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'id' => fillOnUndefined($params, 'group_id'),
];
}
$propertyChannelGroup = $this->propertyChannelGroupService->getPropertyChannelGroup($requestParams);
if($propertyChannelGroup['status'] != 'success'){
throw new ApiErrorException($propertyChannelGroup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelGroup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyChannelGroup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
DB::beginTransaction();
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id', null),
'name' => fillOnUndefined($params, 'name', null),
'created_by' => $this->request->auth->id,
'updated_by' => $this->request->auth->id,
];
$propertyChannelGroup = $this->propertyChannelGroupService->create($requestParams);
if($propertyChannelGroup['status'] != 'success'){
throw new ApiErrorException($propertyChannelGroup['message']);
}
$channels = fillOnUndefined($params, 'channels',[]);
$insertData = [];
foreach ($channels as $channel){
$insertData[] = [
'channel_group_id' => $propertyChannelGroup['data']['id'],
'channel_id' => $channel,
'status' => 1,
'created_by' => $this->request->auth->id,
'updated_by' => $this->request->auth->id,
'created_at' => time(),
'updated_at' => time()
];
}
$propertyChannelGroupChannels = $this->propertyChannelGroupChannelMappingRepository->insert($insertData);
if($propertyChannelGroupChannels['status'] != 'success'){
throw new ApiErrorException($propertyChannelGroupChannels['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelGroup['data']];
DB::commit();
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
DB::rollBack();
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyChannelGroup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
DB::beginTransaction();
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'name' => fillOnUndefined($params, 'name', null),
'updated_by' => $this->request->auth->id,
'updated_at' => time()
];
$propertyChannelGroup = $this->propertyChannelGroupService->update($params['group_id'], $requestParams);
if($propertyChannelGroup['status'] != 'success'){
throw new ApiErrorException($propertyChannelGroup['message']);
}
$channels = fillOnUndefined($params, 'channels',[]);
$channelRequest = [
'criteria' => [
['field' => 'channel_group_id', 'condition' => '=', 'value' => $params['group_id']],
]
];
$propertyChannelGroupChannelDelete = $this->propertyChannelGroupChannelMappingRepository->delete($channelRequest);
$insertData = [];
foreach ($channels as $channel){
$insertData[] = [
'channel_group_id' => $params['group_id'],
'channel_id' => $channel,
'status' => 1,
'created_by' => $this->request->auth->id,
'updated_by' => $this->request->auth->id,
'created_at' => time(),
'updated_at' => time()
];
}
$propertyChannelGroupChannels = $this->propertyChannelGroupChannelMappingRepository->insert($insertData);
if($propertyChannelGroupChannels['status'] != 'success'){
throw new ApiErrorException($propertyChannelGroupChannels['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelGroup['data']];
DB::commit();
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
DB::rollBack();
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyGroupInventory(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$startDate = fillOnUndefinedAndEmpty($params, 'start_date', date('Y-m-d')) ;
$endDate = fillOnUndefinedAndEmpty($params, 'end_date', Carbon::parse($startDate)->addDay(15)->format('Y-m-d')) ;
if($endDate < $startDate){
throw new ApiErrorException('date error') ;
}
$diffInDays = Carbon::parse($startDate)->diffInDays($endDate);
if($diffInDays > 15){
throw new ApiErrorException('date error') ;
}
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_group_id' => fillOnUndefined($params, 'channel_group_id'),
'start_date' => fillOnUndefined($params, 'start_date'),
'end_date' => fillOnUndefined($params, 'end_date'),
];
$groupActiveChannels = $this->propertyChannelGroupService->getPropertyChannelGroupActiveChannels($requestParams);
if($groupActiveChannels['status'] != 'success'){
throw new ApiErrorException($groupActiveChannels['message']);
}
$inventoryData = $groupActiveChannels["data"];
$inventoryData['channel_ids'] = [];
$inventoryData['currencies'] = [];
foreach ($groupActiveChannels['data']['channel_group_active_channels'] as $groupActiveChannel){
$channelId = $groupActiveChannel['channel_id'];
$checkPropertyChannelMappingRequestParams = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $channelId],
['field' => 'status', 'condition' => '=', 'value' => 1]
]
];
$checkPropertyChannelMapping = $this->propertyChannelMappingService->select($checkPropertyChannelMappingRequestParams,['id', 'property_id', 'status']) ;
if($checkPropertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($checkPropertyChannelMapping['message']);
}
if(!empty($checkPropertyChannelMapping['data'])){
$inventoryData['channels'][$channelId] = $groupActiveChannel['channel'];
$inventoryData['channel_ids'][$channelId] = $channelId;
}
}
if(!count($inventoryData['channel_ids'])){
throw new ApiErrorException("There isn't any active channel in this channel group");
}
$channelMappingRequestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => $params['property_id'],
'channel_ids' => $inventoryData['channel_ids'],
];
$getChannelMappingResponse = $this->propertyChannelMappingService->getPropertyChannelMappingForChannelGroup($channelMappingRequestParams) ;
if($getChannelMappingResponse['status'] != 'success'){
throw new ApiErrorException($getChannelMappingResponse['message']);
}
foreach ($getChannelMappingResponse["data"] as $channelMapping){
$channelId = $channelMapping['channel_id'];
$inventoryData['channels'][$channelId]['currency_code'] = $channelMapping['currency_code'];
$inventoryData['channels'][$channelId]['property_availability_type_id'] = $channelMapping['property_availability_type_id'];
$inventoryData['currencies'][$channelMapping['currency_code']] = $channelMapping['currency_code'];
}
foreach ($inventoryData['channel_ids'] as $channelId){
$getGroupInventoryRequestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => $params['property_id'],
'channel_id' => $channelId,
];
$inventoryData['channels'][$channelId]['rooms_temp'] = $this->propertyRoomService->inventoryRoomList($getGroupInventoryRequestParams);
}
foreach ($inventoryData['channels'] as $channel){
$channelId = $channel['id'];
$currency = $channel['currency_code'];
foreach ($channel['rooms_temp'] as $roomTemp){
$roomId = $roomTemp['id'];
$dateKey = Carbon::parse($params['start_date']);
for ($i = 0; $i <= $diffInDays; $i++) {
$responseAVAKey = 'AVA_1_'.$roomId.'_'. '0' .'_'.$dateKey->format('Ymd') ;
$responseSTSKey = 'STS_1_'.$roomId.'_'. '0' .'_'.$dateKey->format('Ymd') ;
$roomAvailability[$dateKey->format('Y-m-d')] = [
'key' => $responseAVAKey,
'value' => null,
'stop_sell' => 0
];
$roomStopSell[$dateKey->format('Y-m-d')] = [
'key' => $responseSTSKey,
'value' => 0,
];
$dateKey = $dateKey->addDay();
}
foreach ($roomTemp['property_room_rate_mapping'] as $roomRateMapping ){
$roomRate = $roomRateMapping['property_room_rate'];
$roomRateId = $roomRate['id'];
$roomRateChannel = $roomRateMapping['property_room_rate_channel'];
foreach ($roomRateChannel as $roomRateChan){
if($roomRateChan['channel_id'] == $channelId && $roomRateChan['status'] == 1){
$inventoryData['rooms'][$roomId]['id'] = $roomTemp['id'];
$inventoryData['rooms'][$roomId]['name'] = $roomTemp['name'];
$inventoryData['rooms'][$roomId]['room_selected'] = false;
$inventoryData['rooms'][$roomId]['availability'] = $roomAvailability;
$inventoryData['rooms'][$roomId]['room_stop_sell'] = $roomStopSell;
$rate['id'] = $roomRateId;
$rate['name'] = $roomRate['name'];
$rate['currency'] = $currency;
$rate['rate_selected'] = false;
$rate['room_rate_mapping_id'] = $roomRateChan['room_rate_mapping_id'];
$dateKey = Carbon::parse($params['start_date']);
for ($i = 0; $i <= $diffInDays; $i++) {
$responsePRCKey = 'PRC_1'.'_'.$roomRateMapping['room_id'].'_'. $roomRateMapping['id'].'_'.$dateKey->format('Ymd').'_'.$currency ;
$responseSTSKey = 'STS_1'.'_'.$roomRateMapping['room_id'].'_'. $roomRateMapping['id'].'_'.$dateKey->format('Ymd');
$responseMNSKey = 'MNS_1'.'_'.$roomRateMapping['room_id'].'_'. $roomRateMapping['id'].'_'.$dateKey->format('Ymd');
$price[$dateKey->format('Y-m-d')] = [
'key' => $responsePRCKey,
'value' => null,
'stop_sell' => 0
];
$stopSell[$dateKey->format('Y-m-d')] = [
'key' => $responseSTSKey,
'value' => 0,
];
$minStay[$dateKey->format('Y-m-d')] = [
'key' => $responseMNSKey,
'value' => 1,
];
$dateKey = $dateKey->addDay();
}
$rate['price'] = $price;
$rate['stop_sell'] = $stopSell;
$rate['min_stay'] = $minStay;
$inventoryData['rooms'][$roomId]['rates'][$roomRateId][$currency] = $rate;
}
}
}
}
}
if(isset($inventoryData['channel_group_active_channels'])){
unset($inventoryData['channel_group_active_channels']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $inventoryData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyChannelGroup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$mappedChannelCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel'],
];
$propertyChannelsForGroup = $this->propertyChannelMappingService->select($mappedChannelCriteria);
if($propertyChannelsForGroup['status'] != 'success'){
throw new ApiErrorException($propertyChannelsForGroup['message']);
}
$channels = [];
foreach ($propertyChannelsForGroup['data'] as $data){
if($data['property_availability_type_id'] == 1 && $data['channel']['parent_id'] == null){
$channels[$data['id']] = $data['channel'];
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channels];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,447 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyChannelService ;
use App\Core\Service\PropertyBookingEngineService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyChannelMappingController
{
private $request;
private $propertyChannelMappingService;
private $propertyChannelService;
private $propertyBookingEngineService;
const CHANNEL_MANAGER = 4;
const PARENT_ID = 5;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyBookingEngineService $propertyBookingEngineService
)
{
$this->request = $request;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyChannelService = $propertyChannelService ;
$this->propertyBookingEngineService = $propertyBookingEngineService;
}
public function getPropertyChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $this->request->auth->id,
];
$propertyChannelMapping = $this->propertyChannelMappingService->getPropertyChannelMapping($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channels' => fillOnUndefined($params, 'channels', []),
'user_id' => $this->request->auth->id,
];
$propertyChannelMapping = $this->propertyChannelMappingService->addPropertyChannelMapping($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function removePropertyChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'channels' => fillOnUndefined($params, 'channels', []),
'user_id' => $this->request->auth->id,
];
$propertyChannelMapping = $this->propertyChannelMappingService->removePropertyChannelMapping($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$propertyChannelMapping = $this->propertyChannelMappingService->updatePropertyChannelMapping($params);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyChannelSetup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params =
[
"property_id" => $request->input('property_id'),
"channel_id" => $request->input('channel_id'),
"booking_type_id" => $request->input('booking_type_id') != 'null' ? $request->input('booking_type_id') : null,
"availability_type_id" => $request->input('availability_type_id') != 'null' ? $request->input('availability_type_id') : null,
"room_pricing_type_id" => $request->input('room_pricing_type_id') != 'null' ? $request->input('room_pricing_type_id') : null,
"currency_code" => $request->input('currency_code') != 'null' ? $request->input('currency_code') : null,
"connected_channel_id" => $request->input('connected_channel_id') != 'null' ? $request->input('connected_channel_id') : null,
"connected_channel_action" => $request->input('connected_channel_action') != 'null' ? $request->input('connected_channel_action') : null,
"contract_file" => $request->file('contract_file')
];
$requestParams = $params ;
$requestParams['user_id'] = $this->request->auth->id;
$getChannelRequest = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$getChannelResponse = $this->propertyChannelService->select($getChannelRequest, ['id', 'parent_id', 'channel_category_id']) ;
if($getChannelResponse['status'] != 'success' && !empty($getChannelResponse['data'])){
throw new ApiErrorException($getChannelResponse['message']);
}
if($getChannelResponse['data']['channel_category_id'] === self::CHANNEL_MANAGER && $getChannelResponse['data']['parent_id'] === self::PARENT_ID
&& !$requestParams['booking_type_id'] && !$requestParams['availability_type_id'] && !$requestParams['room_pricing_type_id'] ){
$propertyChannelMapping = $this->propertyChannelMappingService->addPropertyChannelSetupWithMissingParameters($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelMapping['data']];
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
$propertyChannelMapping = $this->propertyChannelMappingService->addPropertyChannelSetup($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$getChannelRequest = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['parentChannel', 'propertyChannelCategory'],
'firstRow' => 1
];
$getChannelResponse = $this->propertyChannelService->select($getChannelRequest, ['id', 'parent_id', 'name', 'official_name', 'description', 'channel_category_id', 'default_currency', 'country_code', 'currency_code', 'logo', 'address', 'zip_code', 'email', 'phone', 'phone2', 'fax', 'score', 'status']) ;
if($getChannelResponse['status'] != 'success'){
throw new ApiErrorException($getChannelResponse['message']);
}
$channelData['channel'] = $getChannelResponse['data'] ;
$getChannelMappingRequest = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$getChannelMappingResponse = $this->propertyChannelMappingService->select($getChannelMappingRequest) ;
if($getChannelMappingResponse['status'] != 'success'){
throw new ApiErrorException($getChannelMappingResponse['message']);
}
$channelData['channel']['currency_list'] = json_decode($channelData['channel']['currency_code'] , 1);
$channelData['channel']['currency'] = isset($getChannelMappingResponse['data']['currency_code']) ? $getChannelMappingResponse['data']['currency_code'] : $channelData['channel']['default_currency'] ;
$channelData['channel']['is_connected'] = $getChannelMappingResponse['data'] ? true : false ;
$propertyChannelMapping = $this->propertyChannelMappingService->getPropertyChannelSetup($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$channelData = array_merge($channelData, $propertyChannelMapping['data']) ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyChannelSetup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = $params ;
$requestParams['user_id'] = $this->request->auth->id;
$getChannelRequest = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['parentChannel', 'propertyChannelCategory'],
'firstRow' => 1
];
$getChannelResponse = $this->propertyChannelService->select($getChannelRequest, ['id', 'parent_id', 'name', 'official_name', 'default_currency', 'description', 'channel_category_id', 'country_code', 'currency_code', 'logo', 'address', 'zip_code', 'email', 'phone', 'phone2', 'fax', 'score', 'status']) ;
if($getChannelResponse['status'] != 'success'){
throw new ApiErrorException($getChannelResponse['message']);
}
$channelData['channel'] = $getChannelResponse['data'] ;
$childChannels = [];
if(!empty($channelData['channel']) && $channelData['channel']['parent_id'] === NULL
&& $channelData['channel']['property_channel_category']['id'] == 4 ){
$childChannels = $this->propertyChannelMappingService->getPropertyChildChannel(['property_id' => $params['property_id']]);
$childChannels = $childChannels['data'];
}
$getChannelMappingRequest = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $params['channel_id']],
],
'with' => ['channelBookingType', 'channelAvailabilityType', 'channelRoomPricingType'] ,
'firstRow' => 1
];
$getChannelMappingResponse = $this->propertyChannelMappingService->select($getChannelMappingRequest);
if($getChannelMappingResponse['status'] != 'success'){
throw new ApiErrorException($getChannelMappingResponse['message']);
}
$getChannelMappingRequestData = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $params['channel_id']],
],
'firstRow' => 1
];
$getChannelMappingResponseData = $this->propertyChannelMappingService->select($getChannelMappingRequestData) ;
if($getChannelMappingResponseData['status'] != 'success'){
throw new ApiErrorException($getChannelMappingResponseData['message']);
}
$isPending = false;
if(isset($getChannelMappingResponse['data']['status'])){
$isPending = $getChannelMappingResponse['data']['status'] === 2 ? true : false ;
}
$isConnected = false ;
if(isset($getChannelMappingResponse['data']['status'])){
$isConnected = $getChannelMappingResponse['data']['status'] ? true : false ;
}
$channelData['channel']['is_connected'] = $isConnected ;
$channelData['channel']['is_pending'] = $isPending ;
$channelData['channel']['currency_list'] = json_decode($channelData['channel']['currency_code'] , 1);
$channelData['channel']['currency'] = isset($getChannelMappingResponse['data']['currency_code']) ? $getChannelMappingResponse['data']['currency_code'] : $channelData['channel']['default_currency'] ;
$channelData['channel']['channel_booking_type'] = isset($getChannelMappingResponse['data']['channel_booking_type']) ? $getChannelMappingResponse['data']['channel_booking_type'] : null;
$channelData['channel']['channel_availability_type'] = isset($getChannelMappingResponse['data']['channel_availability_type']) ? $getChannelMappingResponse['data']['channel_availability_type'] : null ;
$channelData['channel']['channel_room_pricing_type'] = isset($getChannelMappingResponse['data']['channel_room_pricing_type'] ) ? $getChannelMappingResponse['data']['channel_room_pricing_type'] : null;
$channelData['channel']['connected_channel_id'] = isset($getChannelMappingResponse['data']['connected_channel_id'] ) ? $getChannelMappingResponse['data']['connected_channel_id'] : null;
$channelData['channel']['connected_channel_action'] = isset($getChannelMappingResponse['data']['connected_channel_action'] ) ? $getChannelMappingResponse['data']['connected_channel_action'] : null;
$propertyChannelMapping = $this->propertyChannelMappingService->getPropertyChannelSetup($requestParams);
if($propertyChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyChannelMapping['message']);
}
$channelData = array_merge($channelData, $propertyChannelMapping['data']) ;
$channelData['mapping_child_channels'] = $childChannels;
$channelData['channel']['bookingEngineUrl'] = null;
$channelData['channel']['bookingEngineToken'] = null;
$propertyBookingEngineRequest = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$propertyBookingEngine = $this->propertyBookingEngineService->select($propertyBookingEngineRequest);
$bookingEngineUrl = null;
$bookingEngineToken = null;
if($propertyBookingEngine['status'] == 'success' && !empty($propertyBookingEngine['data'])) {
$bookingEngineToken = $propertyBookingEngine['data']['token'];
$bookingEngineUrl = Config::get('app.bookingEngineUrl').'/'.$propertyBookingEngine['data']['token'];
}
$channelData['channel']['bookingEngineUrl'] = $bookingEngineUrl;
$channelData['channel']['bookingEngineToken'] = $bookingEngineToken;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $channelData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\PropertyCompetitorGroupService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
class PropertyCompetitorGroupController extends Controller
{
private $params;
private $request;
private $propertyCompetitorGroupService;
public function __construct(
Request $request,
PropertyCompetitorGroupService $propertyCompetitorGroupService
)
{
$this->propertyCompetitorGroupService = $propertyCompetitorGroupService;
$this->request = $request;
$this->params = $request->all();
}
public function getPropertyCompetitorGroup(Request $request)
{
$params = $this->params;
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$requestSelectCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['params']['property_id']],
]
];
// created_by, updated_by, created_at, updated_at alanları get cevaplarında gizlenir
$columns = ['id', 'property_id', 'name', 'status'];
$requestSelectResult = $this->propertyCompetitorGroupService->selectPropertyCompetitorGroup($requestSelectCriteria, $columns);
if ($requestSelectResult['status'] != 'success') {
throw new ApiErrorException($requestSelectResult['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $requestSelectResult['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncPropertyCompetitorGroup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
DB::beginTransaction();
try {
$requestParams = [
'id' => $this->params['params']['id'] ?? null,
'property_id' => $this->params['params']['property_id'] ?? null,
'name' => $this->params['params']['name'] ?? null,
'status' => $this->params['params']['status'] ?? 1,
// Öncelik: auth üzerinden gelen kullanıcı
'user_id' => ($this->request->auth->id ?? null) ?: ($this->params['params']['user_id'] ?? null),
];
$requestResult = $this->propertyCompetitorGroupService->syncPropertyCompetitorGroup($requestParams);
if ($requestResult['status'] != 'success') {
throw new ApiErrorException($requestResult['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $requestResult['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyCompetitorGroupMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$requestParams = [
'property_id' => $this->params['params']['property_id'] ?? null,
'competitor_group_id' => $this->params['params']['competitor_group_id'] ?? null,
];
$result = $this->propertyCompetitorGroupService->getPropertyCompetitorGroupMapping($requestParams);
if (($result['status'] ?? false) !== true && ($result['status'] ?? '') !== 'success') {
throw new ApiErrorException($result['message'] ?? 'unknown_error');
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $result['data'] ?? null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncPropertyCompetitorGroupMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
DB::beginTransaction();
try {
$requestParams = [
'property_id' => $this->params['params']['property_id'] ?? null,
'competitor_group_id' => $this->params['params']['competitor_group_id'] ?? null,
'competitor' => $this->params['params']['competitor'] ?? [],
// Öncelik: auth üzerinden gelen kullanıcı
'user_id' => ($this->request->auth->id ?? null) ?: ($this->params['params']['user_id'] ?? null),
];
$result = $this->propertyCompetitorGroupService->syncPropertyCompetitorGroupMapping($requestParams);
if (($result['status'] ?? false) !== true && ($result['status'] ?? '') !== 'success') {
throw new ApiErrorException($result['message'] ?? 'unknown_error');
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $result['data'] ?? null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyConfigService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyConfigController extends Controller
{
private $request;
private $propertyConfigService;
public function __construct(
Request $request,
PropertyConfigService $propertyConfigService
)
{
$this->request = $request;
$this->propertyConfigService = $propertyConfigService;
}
public function getPropertyConfig()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'config_keys' => fillOnUndefined($params, 'config_keys'),
];
$propertyConfig = $this->propertyConfigService->getPropertyConfig($requestParams);
if($propertyConfig['status'] != 'success'){
throw new ApiErrorException($propertyConfig['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyConfig['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyConfig(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'config_keys' => fillOnUndefined($params, 'config_keys'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyConfig = $this->propertyConfigService->propertyConfigUpdate($requestParams);
if($propertyConfig['status'] != 'success'){
throw new ApiErrorException($propertyConfig['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyConfig['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyConfig(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'executive_type' => fillOnUndefined($params, 'executive_type'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyConfig = $this->propertyConfigService->propertyConfigDelete($requestParams);
if($propertyConfig['status'] != 'success'){
throw new ApiErrorException($propertyConfig['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyConfig['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,175 @@
<?php
namespace App\Http\Controllers\V1;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyContactService;
use App\Core\Service\PropertyService;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyContactController extends Controller
{
private $request;
private $propertyContactService;
private $propertyService;
public function __construct(
Request $request,
PropertyService $propertyService,
PropertyContactService $propertyContactService
)
{
$this->request = $request;
$this->propertyService = $propertyService ;
$this->propertyContactService = $propertyContactService;
}
/**
* @return \Illuminate\Http\JsonResponse
*/
public function getPropertyContact()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyContact = $this->propertyContactService->propertyContact($requestParams);
if ($propertyContact['status'] != 'success'){
throw new Exception($propertyContact['message']);
}
$requestParams = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],
],
'firstRow' => 1
];
$property = $this->propertyService->select($requestParams, ['country']);
if($property['status'] != 'success'){
throw new Exception($property['message']);
}
$propertyContact['data']['country_code'] = strtolower($property['data']['country']) ;
$responseData = $propertyContact['data'];
$propertyRequest = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['property_id']],
],
'firstRow' => true
];
$getPropertyFields = ['id', 'name', 'official_name','tax_office', 'tax_number'];
$property = $this->propertyService->select($propertyRequest, $getPropertyFields);
if($property['status'] != 'success'){
throw new Exception($property['message']);
}
$responseData['get_property'] = $property['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
/**
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function updateOrCreatePropertyContact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'contact' => fillOnUndefined($params, 'contact'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyContact = $this->propertyContactService->propertyContactUpdateOrCreate($requestParams);
if($propertyContact['status'] != 'success'){
throw new ApiErrorException($propertyContact['message']);
}
$propertyData = fillOnUndefined($params, 'property_info');
if($propertyData){
$updateData = [];
$validateKeys = ['official_name', 'tax_office', 'tax_number'];
foreach ($propertyData as $key => $value) {
if (!in_array($key, $validateKeys)) {
throw new ApiErrorException(lang('Error Columns'));
}
$updateData[$key] = $value;
}
if ($updateData) {
$updateData['updated_by'] = $requestParams['user_id'];
$updateData['updated_at'] = time();
}
$propertyUpdateResult = $this->propertyService->update($params['property_id'], $updateData);
if ($propertyUpdateResult['status'] != 'success') {
throw new ApiErrorException($propertyUpdateResult['message']);
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContact['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyContentService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyContentController extends Controller
{
private $request;
private $propertyContentService;
public function __construct(
Request $request,
PropertyContentService $propertyContentService
)
{
$this->request = $request;
$this->propertyContentService = $propertyContentService;
}
public function getPropertyContent()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'language_code' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'category_id' => fillOnUndefined($params, 'category_id'),
];
$propertyContent = $this->propertyContentService->propertyContent($requestParams);
if($propertyContent['status'] != 'success'){
throw new Exception($propertyContent['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyContent(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'active_user' => $this->request->credentials->user_id,
'locale' => fillOnUndefined($params, 'locale'),
'contents' => fillOnUndefined($params, 'contents'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyContent = $this->propertyContentService->propertyContentUpdate($requestParams);
if($propertyContent['status'] != 'success'){
throw new ApiErrorException($propertyContent['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,204 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\PropertyChannelCouponService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Validator\PropertyChannelCoupon\PropertyChannelCouponValidator;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Exception;
class PropertyCouponController extends Controller
{
private $params;
private $propertyChannelCouponService;
private $propertyChannelMappingService;
private $propertyChannelCouponValidator;
public function __construct(
PropertyChannelCouponService $propertyChannelCouponService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyChannelCouponValidator $propertyChannelCouponValidator
)
{
$this->params = Input::all();
$this->params = $this->params['params'];
$this->propertyChannelCouponService = $propertyChannelCouponService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyChannelCouponValidator = $propertyChannelCouponValidator;
}
protected function propertyChannelMappingCheck($propertyId, $channelId)
{
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'channel_id', 'condition' => '=', 'value' => $channelId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] == 'success') {
if (empty($propertyChannelMapping['data'])) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public function getPropertyChannelCoupon(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$propertyChannelMappingCheck = $this->propertyChannelMappingCheck($this->params['property_id'], $this->params['channel_id']);
if (!$propertyChannelMappingCheck) {
throw new ApiErrorException('Transactions cannot be made through a unconnected channel.');
}
$requestSelectCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['channel_id']],
],
];
$columns = ['id', 'title', 'property_id', 'channel_id', 'code', 'start_date', 'end_date', 'reservation_start_date', 'reservation_end_date', 'type', 'value', 'is_notify', 'email', 'status'];
$requestSelectResult = $this->propertyChannelCouponService->select($requestSelectCriteria, $columns);
$propertyChannelCoupon = [];
if ($requestSelectResult['status'] == 'success') {
$propertyChannelCoupon = $requestSelectResult['data'];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyChannelCoupon];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncPropertyChannelCoupon(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$validationResult = $this->propertyChannelCouponValidator->validate($this->params);
if ($validationResult->errors()->first()) {
$errors = $validationResult->errors()->all();
throw new ApiErrorException($errors);
}
$propertyChannelMappingCheck = $this->propertyChannelMappingCheck($this->params['property_id'], $this->params['channel_id']);
if (!$propertyChannelMappingCheck) {
throw new ApiErrorException('Transactions cannot be made through a unconnected channel.');
}
$propertyChannelCoupon = [];
if (isset($this->params['id'])) {
$requestSelectCriteria = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $this->params['id']],
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['channel_id']],
],
'firstRow' => true
];
$columns = ['id', 'property_id', 'channel_id', 'code', 'start_date', 'end_date', 'type', 'value', 'status'];
$requestSelectResult = $this->propertyChannelCouponService->select($requestSelectCriteria, $columns);
if ($requestSelectResult['status'] == 'success') {
$propertyChannelCoupon = $requestSelectResult['data'];
}
}
DB::beginTransaction();
if (empty($propertyChannelCoupon)) {
$createParam = [
'title' => fillOnUndefined($this->params, 'title'),
'property_id' => $this->params['property_id'],
'channel_id' => $this->params['channel_id'],
'code' => $this->params['code'],
'start_date' => $this->params['start_date'],
'end_date' => $this->params['end_date'],
'reservation_start_date' => fillOnUndefined($this->params, 'reservation_start_date'),
'reservation_end_date' => fillOnUndefined($this->params, 'reservation_end_date'),
'type' => $this->params['type'],
'value' => $this->params['value'],
'is_notify' => fillOnUndefined($this->params, 'is_notify'),
'email' => fillOnUndefined($this->params, 'email'),
'status' => fillOnUndefined($this->params, 'status', 1),
'created_by' => $request->auth->id,
'updated_by' => $request->auth->id,
];
$syncPropertyChannelCoupon = $this->propertyChannelCouponService->create($createParam);
} else {
$this->params['updated_by'] = $request->auth->id;
$syncPropertyChannelCoupon = $this->propertyChannelCouponService->update($propertyChannelCoupon['id'], $this->params);
}
if ($syncPropertyChannelCoupon['status'] != 'success') {
throw new ApiErrorException($syncPropertyChannelCoupon['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $syncPropertyChannelCoupon['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,271 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyExecutiveService;
use Illuminate\Http\Request;
use App\Core\Service\PropertyService;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyExecutiveController extends Controller
{
private $request;
private $propertyExecutiveService;
private $propertyService;
public function __construct(
Request $request,
PropertyService $propertyService,
PropertyExecutiveService $propertyExecutiveService
)
{
$this->request = $request;
$this->propertyExecutiveService = $propertyExecutiveService;
$this->propertyService = $propertyService;
}
public function getPropertyExecutive()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyExecutive = $this->propertyExecutiveService->getPropertyExecutive($requestParams);
if($propertyExecutive['status'] != 'success'){
throw new Exception($propertyExecutive['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function listPropertyExecutive()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyExecutive = $this->propertyExecutiveService->listPropertyExecutive($requestParams);
if($propertyExecutive['status'] != 'success'){
throw new Exception($propertyExecutive['message']);
}
$requestParams = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],
],
'firstRow' => 1
];
$property = $this->propertyService->select($requestParams, ['country']);
if($property['status'] != 'success'){
throw new Exception($property['message']);
}
$propertyExecutive['data']['country_code'] = strtolower($property['data']['country']) ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyExecutive(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'executive_type' => fillOnUndefined($params, 'executive_type'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyExecutive = $this->propertyExecutiveService->propertyExecutiveAdd($requestParams);
if($propertyExecutive['status'] != 'success'){
throw new ApiErrorException($propertyExecutive['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyExecutive(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'executive_type' => fillOnUndefined($params, 'executive_type'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$oldPropertyExecutive = $this->propertyExecutiveService->listPropertyExecutive($requestParams);
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'executive_type' => fillOnUndefined($params, 'executive_type'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyExecutive = $this->propertyExecutiveService->propertyExecutiveUpdate($requestParams);
if($propertyExecutive['status'] != 'success'){
throw new ApiErrorException($propertyExecutive['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['data']];
} catch (ApiErrorException $e) {
$response['data'] = $oldPropertyExecutive['data'] ;
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['data'] = $oldPropertyExecutive['data'] ;
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyExecutive(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_executive_id' => fillOnUndefined($params, 'property_executive_id'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$propertyExecutive = $this->propertyExecutiveService->propertyExecutivePassive($requestParams);
if($propertyExecutive['status'] != 'success'){
throw new ApiErrorException($propertyExecutive['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,183 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyFactService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyFactController
{
private $request;
private $propertyFactService;
public function __construct(
Request $request,
PropertyFactService $propertyFactService
)
{
$this->request = $request;
$this->propertyFactService = $propertyFactService;
}
public function getPropertyFact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestFact = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$getPropertyFact = $this->propertyFactService->getPropertyFact($requestFact);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['get_facts' => $getPropertyFact['data']] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function searchPropertyFact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestFact = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'search_term' => fillOnUndefined($params, 'search_term'),
];
$getPropertyFact = $this->propertyFactService->searchPropertyFact($requestFact);
if($getPropertyFact['status'] != 'success'){
throw new ApiErrorException($getPropertyFact['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['get_facts' => $getPropertyFact['data']] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getSubCategoryFacts(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestFact = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'sub_category_id' => fillOnUndefined($params, 'sub_category_id'),
];
$factRequestData = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['sub_category_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'type', 'condition' => '=', 'value' => 0],
],
'with' => ['propertyFactParent'],
'firstRow' => 1
];
$thisFact = $this->propertyFactService->select($factRequestData, ['id', 'parent_id', 'name', 'language_key', 'title_language_key']);
if($thisFact['status'] != 'success' || !$thisFact['data']){
throw new ApiErrorException('Fact data not found') ;
}
$subCategoryFacts = $this->propertyFactService->getSubCategoryFacts($requestFact);
if($subCategoryFacts['status'] != 'success'){
throw new ApiErrorException($subCategoryFacts['message']) ;
}
$requestFact['parent_id'] = $thisFact['data']['parent_id'] ;
$thisMenus = $this->propertyFactService->getSubCategoryMenus($requestFact);
if($thisMenus['status'] != 'success'){
throw new ApiErrorException($thisMenus['message']) ;
}
$thisSubCategory = $thisFact['data'] ;
$thisMainCategory = $thisSubCategory['property_fact_parent'] ;
unset($thisSubCategory['property_fact_parent']) ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' =>
[
'get_facts' => $subCategoryFacts['data'],
'get_menus' => $thisMenus['data'],
'this_sub_category' => $thisSubCategory,
'this_main_category' => $thisMainCategory,
]
];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyFactMappingService;
use Predis\Replication\RoleException;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyFactMappingController extends Controller
{
private $request;
private $propertyFactMappingService;
public function __construct(
Request $request,
PropertyFactMappingService $propertyFactMappingService
)
{
$this->request = $request;
$this->propertyFactMappingService = $propertyFactMappingService;
}
public function getPropertyFactMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $params];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function removePropertyFactMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = $params['property_fact_mapping_remove'] ;
$requestParams = [
'active_user' => $this->request->credentials->user_id,
'facts' => fillOnUndefined($params, 'facts'),
];
$removeResponse = $this->propertyFactMappingService->removePropertyFactMapping($requestParams);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $removeResponse];
//$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyFactMapping()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try
{
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(),1);
$params = current($params);
$params['user_id'] = $this->request->auth->id;
$response = $this->propertyFactMappingService->addPropertyFactMapping($params);
}catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyFactMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try
{
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(),1);
$params = current($params);
$params['user_id'] = $this->request->auth->id;
$response = $this->propertyFactMappingService->updatePropertyFactMapping($params);
}catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyNonrefundableService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyNonrefundableController extends Controller
{
private $request;
private $propertyNonrefundableService;
public function __construct(
Request $request,
PropertyNonrefundableService $propertyNonrefundableService
)
{
$this->request = $request;
$this->propertyNonrefundableService = $propertyNonrefundableService;
}
public function createPropertyChannelNonrefundable(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyNonrefundable = $this->propertyNonrefundableService->createForm($params);
if($getPropertyNonrefundable['status'] != "success"){
throw new ApiErrorException($getPropertyNonrefundable['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getPropertyNonrefundable['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function storePropertyChannelNonrefundable(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
$updateResponse = $this->propertyNonrefundableService->storePropertyNonrefundable($params);
if($updateResponse['status'] != 'success'){
throw new ApiErrorException($updateResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $updateResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyChannelNonrefundable(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyNonrefundable = $this->propertyNonrefundableService->getNonrefundableData($params);
if($getPropertyNonrefundable['status'] != "success"){
throw new ApiErrorException($getPropertyNonrefundable['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['channel_list' => $getPropertyNonrefundable['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,431 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyPersonPricingPolicyService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyPersonPricingPolicyController extends Controller
{
private $request;
private $propertyPersonPricingPolicyService;
public function __construct(
Request $request,
PropertyPersonPricingPolicyService $propertyPersonPricingPolicyService
)
{
$this->request = $request;
$this->propertyPersonPricingPolicyService = $propertyPersonPricingPolicyService;
}
public function getPropertyPersonPricingPolicyList(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyPersonPricingList = $this->propertyPersonPricingPolicyService->getPropertyPersonPricingPolicyList($params);
if ($getPropertyPersonPricingList['status'] != "success") {
throw new ApiErrorException($getPropertyPersonPricingList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['pricing_policies' => $getPropertyPersonPricingList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyPersonPricingAdultPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
$params =
[
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => fillOnUndefined($params, 'name'),
'adult_action_type' => fillOnUndefined($params, 'adult_action_type'),
'adult' => fillOnUndefined($params, 'adult'),
'action_type' => fillOnUndefined($params, 'action_type'),
'type' => fillOnUndefined($params, 'type'),
'value' => fillOnUndefined($params, 'value'),
'reservation_start_date' => fillOnUndefined($params, 'reservation_start_date'),
'reservation_end_date' => fillOnUndefined($params, 'reservation_end_date'),
'user_id' => $userId,
];
$createResponse = $this->propertyPersonPricingPolicyService->createPropertyPersonPricingAdultPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyPersonPricingChildPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
$params =
[
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => fillOnUndefined($params, 'name'),
'adult' => fillOnUndefined($params, 'adult'),
'child_order' => fillOnUndefined($params, 'child_order'),
'child_age_start' => fillOnUndefined($params, 'child_age_start'),
'child_age_end' => fillOnUndefined($params, 'child_age_end'),
'type' => fillOnUndefined($params, 'type'),
'value' => fillOnUndefined($params, 'value'),
'reservation_start_date' => fillOnUndefined($params, 'reservation_start_date'),
'reservation_end_date' => fillOnUndefined($params, 'reservation_end_date'),
'user_id' => $userId,
];
$createResponse = $this->propertyPersonPricingPolicyService->createPropertyPersonPricingChildPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyPersonPricingAdultPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
$params =
[
'property_id' => fillOnUndefined($params, 'property_id'),
'pricing_policy_id' => fillOnUndefined($params, 'pricing_policy_id'),
'name' => fillOnUndefined($params, 'name'),
'adult_action_type' => fillOnUndefined($params, 'adult_action_type'),
'adult' => fillOnUndefined($params, 'adult'),
'action_type' => fillOnUndefined($params, 'action_type'),
'type' => fillOnUndefined($params, 'type'),
'value' => fillOnUndefined($params, 'value'),
'reservation_start_date' => fillOnUndefined($params, 'reservation_start_date'),
'reservation_end_date' => fillOnUndefined($params, 'reservation_end_date'),
'user_id' => $userId,
];
$createResponse = $this->propertyPersonPricingPolicyService->updatePropertyPersonPricingAdultPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyPersonPricingChildPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
$params =
[
'property_id' => fillOnUndefined($params, 'property_id'),
'pricing_policy_id' => fillOnUndefined($params, 'pricing_policy_id'),
'name' => fillOnUndefined($params, 'name'),
'adult' => fillOnUndefined($params, 'adult'),
'child_order' => fillOnUndefined($params, 'child_order'),
'child_age_start' => fillOnUndefined($params, 'child_age_start'),
'child_age_end' => fillOnUndefined($params, 'child_age_end'),
'type' => fillOnUndefined($params, 'type'),
'value' => fillOnUndefined($params, 'value'),
'reservation_start_date' => fillOnUndefined($params, 'reservation_start_date'),
'reservation_end_date' => fillOnUndefined($params, 'reservation_end_date'),
'room_rate_channel_mapping_id' => fillOnUndefined($params, 'room_rate_channel_mapping_id'),
'user_id' => $userId,
];
$createResponse = $this->propertyPersonPricingPolicyService->updatePropertyPersonPricingChildPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyPersonPricingAdultPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
$params = [
'property_id' => fillOnUndefined($params, 'property_id'),
'pricing_policy_id' => fillOnUndefined($params, 'pricing_policy_id'),
'user_id' => $userId,
];
$createResponse = $this->propertyPersonPricingPolicyService->deletePropertyPersonPricingAdultPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyPersonPricingChildPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$userId = $request->credentials->user_id;
$params = [
'property_id' => fillOnUndefined($params, 'property_id'),
'pricing_policy_id' => fillOnUndefined($params, 'pricing_policy_id'),
'user_id' => $userId,
];
$createResponse = $this->propertyPersonPricingPolicyService->deletePropertyPersonPricingChildPolicy($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateRoomRatePricingAdultPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$checkChannelRoomPricingType = $this->propertyPersonPricingPolicyService->checkChannelRoomPricingType($params);
if ($checkChannelRoomPricingType['status'] != 'success') {
throw new ApiErrorException($checkChannelRoomPricingType['message']);
}
$getPropertyPersonPricingList = $this->propertyPersonPricingPolicyService->updateRoomRatePricingAdultPolicy($params);
if ($getPropertyPersonPricingList['status'] != "success") {
throw new ApiErrorException($getPropertyPersonPricingList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateRoomRatePricingChildPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$checkChannelRoomPricingType = $this->propertyPersonPricingPolicyService->checkChannelRoomPricingType($params);
if ($checkChannelRoomPricingType['status'] != 'success') {
throw new ApiErrorException($checkChannelRoomPricingType['message']);
}
$getPropertyPersonPricingList = $this->propertyPersonPricingPolicyService->updateRoomRatePricingChildPolicy($params);
if ($getPropertyPersonPricingList['status'] != "success") {
throw new ApiErrorException($getPropertyPersonPricingList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getRoomRateChannelPersonPricingPolicy(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$checkChannelRoomPricingType = $this->propertyPersonPricingPolicyService->checkChannelRoomPricingType($params);
if ($checkChannelRoomPricingType['status'] != 'success') {
throw new ApiErrorException($checkChannelRoomPricingType['message']);
}
$getPropertyPersonPricingList = $this->propertyPersonPricingPolicyService->getRoomRateChannelPersonPricingPolicy($params);
if ($getPropertyPersonPricingList['status'] != "success") {
throw new ApiErrorException($getPropertyPersonPricingList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['rooms' => $getPropertyPersonPricingList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyPhotoService\PropertyPhotoCategoryService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyPhotoCategoryController
{
private $request;
private $propertyPhotoCategoryService;
public function __construct(
Request $request,
PropertyPhotoCategoryService $propertyPhotoCategoryService
)
{
$this->request = $request;
$this->propertyPhotoCategoryService = $propertyPhotoCategoryService;
}
public function propertyPhotoCategoryList()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyPhotoCategory = $this->propertyPhotoCategoryService->getPropertyPhotoCategoryList($requestParams);
if($propertyPhotoCategory['status'] != 'success'){
throw new Exception($propertyPhotoCategory['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyPhotoCategory['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,381 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\PropertyService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Core\Service\PropertyPhotoService\PropertyPhotoService;
use App\Core\Service\Google\GoogleVisionLabelService;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use App\Core\Service\PropertyConfigService;
use Illuminate\Support\Str;
use ZipArchive ;
class PropertyPhotoController extends Controller
{
private $request;
private $propertyPhotoService;
private $googleVisionLabelService;
private $propertyConfigService;
private $propertyService;
public function __construct
(
PropertyPhotoService $propertyPhotoService,
PropertyService $propertyService,
GoogleVisionLabelService $googleVisionLabelService,
PropertyConfigService $propertyConfigService
)
{
$this->propertyPhotoService = $propertyPhotoService;
$this->googleVisionLabelService = $googleVisionLabelService;
$this->propertyConfigService = $propertyConfigService;
$this->propertyService = $propertyService ;
}
public function getPropertyPhotos(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if ( is_null( $request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = current($params);
//TODO : Validation Yapılması gerekiyor.
$response = $this->propertyPhotoService->getPropertyPhotos($params);
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function uploadPropertyPhoto(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if(!$request->hasFile('image'))
{
throw new ApiErrorException(lang('Photos not found'));
}
$propertyId = $request->input('property_id');
$photo = $request->file('image');
$param =
[
"property_id" => $propertyId,
"photo" => $photo,
];
$response = $this->propertyPhotoService->propertyPhotoUploadFilter($param);
$rateParams = [
'property_id' => $propertyId,
'user_id' => 1,
'property_rate_for' => 'Property.Photo.Upload',
];
$this->propertyConfigService->rateProperty($rateParams);
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function setDefaultPhoto(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if ( is_null( $request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = current($params);
//TODO : Validation Yapılması gerekiyor.
$response = $this->propertyPhotoService->setDefaultPhoto($params);
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
$response['message'] = $e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function setPropertyPhotoOrder(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if ( is_null( $request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = current($params);
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'set_photo_order' => fillOnUndefined($params, 'set_photo_order'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
//TODO : Validation Yapılması gerekiyor.
$response = $this->propertyPhotoService->setPhotoOrder($requestParams);
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function publishPhotos(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if ( is_null( $request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = current($params);
//TODO : Validation Yapılması gerekiyor.
$response = $this->propertyPhotoService->publishPhotos($params);
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyPhotos(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if ( is_null( $request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = current($params);
//TODO : Validation Yapılması gerekiyor.
$deletePhoto = $this->propertyPhotoService->deletePhotos($params);
if ($deletePhoto['status'] == false) {
throw new ApiErrorException($deletePhoto['message']);
}
$defaultPhotoCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
['field' => 'is_default', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$propertyPhotoData = $this->propertyPhotoService->select($defaultPhotoCriteria, ['id']);
if ($propertyPhotoData['status'] == false) {
throw new ApiErrorException($propertyPhotoData['message']);
}
$defaultPhoto = isset($propertyPhotoData['data']['id']) ? $propertyPhotoData['data']['id'] : null ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['default_photo' => $defaultPhoto] ];
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function setPropertyPhotoCategory(Request $request)
{
$response = ['status' => false, 'statusCode' => 500 ,'message' => '', 'data' => null];
try
{
if ( is_null( $request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($request->getContent(),1);
$params = current($params);
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
'set_photo_category' => fillOnUndefined($params, 'set_photo_category'),
];
//TODO : Validation Yapılması gerekiyor.
$response = $this->propertyPhotoService->setPhotoCategory($requestParams);
}catch (ApiErrorException $e)
{
$response['message'] = $e->getMessage();
}catch (Exception $e)
{
$message = $e->getFile().' '.$e->getLine().' '.$e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function downloadPropertyPhotos(Request $request)
{
$response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
try {
if (is_null($request->getContent())) {
throw new Exception('api-unknown_error');
}
$params = json_decode($request->getContent(), 1);
$params = current($params);
$responseData = null ;
$propertyId = $params['property_id'];
$getPhotosRequest = [
'property_id' => $propertyId
];
if(isset($params['custom']) && !empty($params['custom'])) {
$getPhotosRequest['custom'] = $params['custom'];
}
$response = $this->propertyPhotoService->getPropertyPhotos($getPhotosRequest);
if ($response['status'] != 'success') {
throw new Exception('api-unknown_error');
}
if (!$response['data']) {
throw new Exception('api-unknown_error');
}
$photos = $response['data'];
if ($photos) {
$public_dir = public_path();
$zipFileStoragePath = $public_dir . '/property-zip-files';
$propertyRequest = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $propertyId],
],
'firstRow' => true
];
$thisProperty = $this->propertyService->select($propertyRequest);
if ($thisProperty['status'] != 'success') {
throw new Exception('api-unknown_error');
}
$hotelName = Str::slug($thisProperty['data']['name'], '_', 'en');
if (!File::exists($zipFileStoragePath)) {
File::makeDirectory($zipFileStoragePath, 0777, true);
}
$zipFileName = $hotelName . '_photos.zip';
$zip = new ZipArchive;
if(file_exists($zipFileStoragePath . '/' . $zipFileName)) {
unlink($zipFileStoragePath . '/' . $zipFileName);
}
if ($zip->open($zipFileStoragePath . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {
foreach ($photos as $photo) {
$photoUrlFilePath = Config::get('app.fileSystemDriver') . "/property-photos/{$photo['property_id']}" . "/{$photo['photo_name']}_medium.{$photo['file_ext']}";
$fileName = "{$photo['photo_name']}_medium.{$photo['file_ext']}";
if (file_exists($photoUrlFilePath)) {
$zip->addFile($photoUrlFilePath, $fileName);
}
}
$zip->close();
}
$responseData = Config::get('app.zipFilesUrl').$zipFileName;
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['zipFile' => $responseData]];
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,520 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\PropertyPhotoService\PropertyPhotoService;
use App\Core\Service\PropertyPlaceService;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request ;
use Exception ;
class PropertyPlaceController
{
private $request ;
private $propertyPlaceService;
private $propertyPhotoService;
public function __construct(
Request $request,
PropertyPhotoService $propertyPhotoService,
PropertyPlaceService $propertyPlaceService
)
{
$this->request = $request ;
$this->propertyPlaceService = $propertyPlaceService ;
$this->propertyPhotoService = $propertyPhotoService ;
}
public function getPlaceCategories(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$placeCategories = $this->propertyPlaceService->getPropertyPlaceCategories($params);
if($placeCategories['status'] != 'success'){
throw new Exception($placeCategories['message']);
}
$responseData['place_categories'] = $placeCategories['data'] ;
$placeWorkingHours = $this->propertyPlaceService->getPropertyWorkingHours($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$responseData['place_working_hours'] = $placeWorkingHours['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPlaceCategoriesSingle(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$placeCategories = $this->propertyPlaceService->getPropertyPlaceCategoriesSingle($params);
if($placeCategories['status'] != 'success'){
throw new Exception($placeCategories['message']);
}
$responseData['place_categories'] = $placeCategories['data'] ;
$placeWorkingHours = $this->propertyPlaceService->getPropertyWorkingHours($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$responseData['place_working_hours'] = $placeWorkingHours['data'] ;
$placeIncludes = $this->propertyPlaceService->getPlaceIncludes($params);
if($placeIncludes['status'] != 'success'){
throw new Exception($placeIncludes['message']);
}
$responseData['place_includes'] = $placeIncludes['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPlacePlaceWorkingHours(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$placeWorkingHours = $this->propertyPlaceService->getPropertyWorkingHours($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$responseData['place_working_hours'] = $placeWorkingHours['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPlace(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$placeWorkingHours = $this->propertyPlaceService->create($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$responseData['property_place'] = $placeWorkingHours['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function listPlace(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$listPlaces = $this->propertyPlaceService->listPlaces($params);
if($listPlaces['status'] != 'success'){
throw new Exception($listPlaces['message']);
}
$responseData['places'] = $listPlaces['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyPlacePhoto(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestFact = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'place_id' => fillOnUndefined($params, 'place_id'),
];
$getPropertyPhoto = $this->propertyPhotoService->getPropertyPlacePhoto($requestFact);
if ($getPropertyPhoto['status'] != 'success') {
throw new ApiErrorException($getPropertyPhoto['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getPropertyPhoto['data'] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyPlacePhotoMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try
{
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(),1);
$params = current($params);
$params['user_id'] = $this->request->auth->id;
$response = $this->propertyPlaceService->updatePropertyPlacePhotoMapping($params);
}catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePlace(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$placeWorkingHours = $this->propertyPlaceService->update($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $placeWorkingHours['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePlaceStatus(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$placeWorkingHours = $this->propertyPlaceService->updateStatus($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $placeWorkingHours['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePlace(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$placeWorkingHours = $this->propertyPlaceService->deletePlace($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $placeWorkingHours['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function editPlace(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$listPlaces = $this->propertyPlaceService->editPlaces($params);
if($listPlaces['status'] != 'success'){
throw new Exception($listPlaces['message']);
}
$responseData = $listPlaces['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function listPlaceFacilities(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$listPlaces = $this->propertyPlaceService->listPlaceFacilities($params);
if($listPlaces['status'] != 'success'){
throw new Exception($listPlaces['message']);
}
$responseData['place_facilities'] = $listPlaces['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePlaceFacilities(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$placeWorkingHours = $this->propertyPlaceService->updatePlaceFacilities($params);
if($placeWorkingHours['status'] != 'success'){
throw new Exception($placeWorkingHours['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $placeWorkingHours['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPlaceCategoryFields(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$responseData = null ;
$placeCategoryFields = $this->propertyPlaceService->getPlaceCategoryFields($params);
if($placeCategoryFields['status'] != 'success'){
throw new Exception($placeCategoryFields['message']);
}
$responseData['place_category_fields'] = $placeCategoryFields['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function insertNewFieldMapping(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$responseData = null ;
$placeCategoryFields = $this->propertyPlaceService->insertNewFieldMapping($params);
if($placeCategoryFields['status'] != 'success'){
throw new Exception($placeCategoryFields['message']);
}
$responseData['place_category_fields'] = $placeCategoryFields['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,264 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyPromotionService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyPromotionController extends Controller
{
private $request;
private $propertyPromotionService;
public function __construct(
Request $request,
PropertyPromotionService $propertyPromotionService
)
{
$this->request = $request;
$this->propertyPromotionService = $propertyPromotionService;
}
public function getPromotionTypeList(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPromotionTypeList = $this->propertyPromotionService->getPromotionTypeList($params);
if ($getPromotionTypeList['status'] != "success") {
throw new ApiErrorException($getPromotionTypeList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['promotion_type' => $getPromotionTypeList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyPromotionList(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyPromotionList = $this->propertyPromotionService->getPropertyPromotionList($params);
if ($getPropertyPromotionList['status'] != "success") {
throw new ApiErrorException($getPropertyPromotionList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['property_promotions' => $getPropertyPromotionList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyPromotion(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
$createResponse = $this->propertyPromotionService->createPropertyPromotion($params);
if ($createResponse['status'] != 'success') {
throw new ApiErrorException($createResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $createResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getRoomRateChannelPromotion(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$getPropertyPromotionList = $this->propertyPromotionService->getRoomRateChannelPromotion($params);
if ($getPropertyPromotionList['status'] != "success") {
throw new ApiErrorException($getPropertyPromotionList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['rooms' => $getPropertyPromotionList['data']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyPromotion(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
$updateResponse = $this->propertyPromotionService->updatePropertyPromotion($params);
if ($updateResponse['status'] != 'success') {
throw new ApiErrorException($updateResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $updateResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updateRoomRateChannelPromotion(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$params['user_id'] = $this->request->auth->id;
$getPropertyPromotionList = $this->propertyPromotionService->updateRoomRateChannelPromotion($params);
if ($getPropertyPromotionList['status'] != "success") {
throw new ApiErrorException($getPropertyPromotionList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyPromotion(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$params = $this->request->params;
$params['user_id'] = $request->credentials->user_id;
$updateResponse = $this->propertyPromotionService->deletePropertyPromotion($params);
if ($updateResponse['status'] != 'success') {
throw new ApiErrorException($updateResponse['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $updateResponse['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,490 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Repository\PropertyRoomRateChannelMapping\PropertyRoomRateChannelMappingRepository;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyQuickPricingService;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyRoomRatePriceService;
use App\Exceptions\ApiErrorException;
use App\Export\PropertyCompetitorExport;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Exception;
use Maatwebsite\Excel\Facades\Excel;
class PropertyQuickPricingController extends Controller
{
private $params;
private $propertyQuickPricingService;
private $propertyRoomRateChannelMappingService;
private $propertyChannelMappingService;
private $propertyRoomRatePriceService;
public function __construct(
PropertyQuickPricingService $propertyQuickPricingService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomRatePriceService $propertyRoomRatePriceService
)
{
$this->params = Input::all();
$this->propertyQuickPricingService = $propertyQuickPricingService;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
}
public function syncPropertyQuickPricing(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
//TODO Param validator
$propertyRoomRateChannelIds = [];
$channelRoomRateCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$propertyRoomRateChannels = $this->propertyRoomRateChannelMappingService->select($channelRoomRateCriteria);
if ($propertyRoomRateChannels['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateChannels['message']);
}
$propertyRoomRateChannelIds = pickItemFromArray('id', $propertyRoomRateChannels['data']);
if (empty($propertyRoomRateChannelIds)) {
throw new ApiErrorException('Not mapping room rate this channel.');
}
DB::beginTransaction();
$quickPricingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
]
];
$quickPricingResult = $this->propertyQuickPricingService->selectPropertyQuickPricingMapping($quickPricingCriteria);
if ($quickPricingResult['status'] != 'success') {
throw new ApiErrorException($quickPricingResult['message']);
}
if (!empty($quickPricingResult['data'])) {
$deleteIds = pickItemFromArray('id', $quickPricingResult['data']);
$deletePropertyQuickPricingMapping = $this->propertyQuickPricingService->deletePropertyQuickPricingMapping($deleteIds);
if ($deletePropertyQuickPricingMapping['status'] != 'success') {
throw new ApiErrorException($deletePropertyQuickPricingMapping['message']);
}
}
$roomRateChannelMappingIdCollect = collect($this->params['params']['room_rates'])->groupBy('room_rate_channel_mapping_id')->toArray();
foreach ($roomRateChannelMappingIdCollect as $roomRateChannelMapping) {
if (count($roomRateChannelMapping) > 1) {
throw new ApiErrorException('The same room rate channel id can not be processed.');
}
}
$requestResultData = [];
foreach ($this->params['params']['room_rates'] as $roomRate) {
if (!in_array($roomRate['room_rate_channel_mapping_id'], $propertyRoomRateChannelIds)) {
continue;
}
$requestParam = [
'property_id' => $this->params['params']['property_id'],
'channel_id' => $this->params['params']['channel_id'],
'room_rate_channel_mapping_id' => $roomRate['room_rate_channel_mapping_id'],
'action_type' => fillOnUndefined($roomRate, 'action_type'),
'price_type' => fillOnUndefined($roomRate, 'price_type'),
'price_value' => fillOnUndefined($roomRate, 'price_value'),
'created_by' => $request->auth->id,
'updated_by' => $request->auth->id,
];
$requestResult = $this->propertyQuickPricingService->createPropertyQuickPricingMapping($requestParam);
if ($requestResult['status'] != 'success') {
throw new ApiErrorException($requestResult['message']);
}
$requestResultData[] = $requestResult['data'];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $requestResultData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyQuickPricing(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$requestSelectCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
],
'with' => ['propertyRoomRateChannelMapping.propertyRoomRateMapping']
];
$columns = ['id', 'property_id', 'channel_id', 'room_rate_channel_mapping_id', 'action_type', 'price_type', 'price_value'];
$requestSelectResult = $this->propertyQuickPricingService->selectPropertyQuickPricingMapping($requestSelectCriteria, $columns);
if ($requestSelectResult['status'] != 'success') {
throw new ApiErrorException($requestSelectResult['message']);
}
$requestSelectResultData = [];
foreach ($requestSelectResult['data'] as $key => $value) {
$requestSelectResultData[$value['room_rate_channel_mapping_id']] = [
'property_id' => $value['property_id'],
'channel_id' => $value['channel_id'],
'room_id' => $value['property_room_rate_channel_mapping']['property_room_rate_mapping']['room_id'],
'room_rate_id' => $value['property_room_rate_channel_mapping']['property_room_rate_mapping']['room_rate_id'],
'room_rate_mapping_id' => $value['property_room_rate_channel_mapping']['room_rate_mapping_id'],
'room_rate_channel_mapping_id' => $value['room_rate_channel_mapping_id'],
'action_type' => $value['action_type'],
'price_type' => $value['price_type'],
'price_value' => $value['price_value'],
];
}
$channelRoomRateCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['propertyRoomRateMapping.propertyRoom', 'propertyRoomRateMapping.propertyRoomRate']
];
$propertyRoomRateChannels = $this->propertyRoomRateChannelMappingService->select($channelRoomRateCriteria);
if ($propertyRoomRateChannels['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateChannels['message']);
}
$propertyRoomRateChannelQp = [];
foreach ($propertyRoomRateChannels['data'] as $propertyRoomRateChannel) {
//Best Available Rate Manipulate
if($propertyRoomRateChannel['property_room_rate_mapping']['property_room_rate']['name'] == 'Best Available Rate') {
continue;
}
$roomId = $propertyRoomRateChannel['property_room_rate_mapping']['room_id'];
//dd($propertyRoomRateChannel['property_room_rate_mapping']['property_room']['name']);
$propertyRoomRateChannelQp['rooms'][$roomId]['name'] = $propertyRoomRateChannel['property_room_rate_mapping']['property_room']['name'];
$propertyRoomRateChannelQp['rooms'][$roomId]['property_room_rate_mapping'][$propertyRoomRateChannel['room_rate_mapping_id']] = [
'name' => $propertyRoomRateChannel['property_room_rate_mapping']['property_room_rate']['name'],
'room_rate_channel_mapping_id' => $propertyRoomRateChannel['id'],
'action_type' => null,
'price_type' => null,
'price_value' => null
];
if (isset($requestSelectResultData[$propertyRoomRateChannel['id']])) {
$propertyRoomRateChannelQp['rooms'][$roomId]['property_room_rate_mapping'][$propertyRoomRateChannel['room_rate_mapping_id']] = [
'name' => $propertyRoomRateChannel['property_room_rate_mapping']['property_room_rate']['name'],
'room_rate_channel_mapping_id' => $propertyRoomRateChannel['id'],
'action_type' => $requestSelectResultData[$propertyRoomRateChannel['id']]['action_type'],
'price_type' => $requestSelectResultData[$propertyRoomRateChannel['id']]['price_type'],
'price_value' => $requestSelectResultData[$propertyRoomRateChannel['id']]['price_value'],
];
}
}
//array_values
foreach ($propertyRoomRateChannelQp['rooms'] as $roomId => $rooms) {
$propertyRoomRateChannelQp['rooms'][$roomId]['property_room_rate_mapping'] = array_values($rooms['property_room_rate_mapping']);
}
$propertyRoomRateChannelQp['rooms'] = array_values($propertyRoomRateChannelQp['rooms']);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateChannelQp];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function propertyQuickPricingRate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
//Burada kanal ve proeprty ile kanal maping detaylatı çekilmeli property_channel_mapping tablosundan
$propertyChannelMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingCriteria);
if ($propertyChannelMapping['status'] != 'success') {
throw new ApiErrorException($propertyChannelMapping['message']);
}
$propertyChannelMapping = $propertyChannelMapping['data'];
//CONNECTED CHANNEL RATE CHECK
$propertyChannelConnectedList = [];
$propertyChannelConnectedCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'connected_channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$propertyChannelConnected = $this->propertyChannelMappingService->select($propertyChannelConnectedCriteria);
if ($propertyChannelConnected['status'] == 'success') {
$propertyChannelConnectedList = $propertyChannelConnected['data'];
}
//CONNECTED CHANNEL RATE CHECK
/*
"property_id" => 1
"channel_id" => 1
"currency_code" => "EUR"
"property_booking_type_id" => 1
"property_availability_type_id" => 1
* */
//Property ve Kanala ait mapping yapılan room rate ler
$propertyRoomRateChannelIds = [];
$channelRoomRateCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$propertyRoomRateChannels = $this->propertyRoomRateChannelMappingService->select($channelRoomRateCriteria);
if ($propertyRoomRateChannels['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateChannels['message']);
}
$propertyRoomRateChannelIds = pickItemFromArray('id', $propertyRoomRateChannels['data']);
if (empty($propertyRoomRateChannelIds)) {
throw new ApiErrorException('Not mapping room rate this channel.');
}
$propertyQuickPricingMapping = [];
$requestSelectCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['params']['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['params']['channel_id']],
],
'with' => ['propertyRoomRateChannelMapping.propertyRoomRateMapping', 'propertyRoomRateChannelMapping.propertyRoomRateMapping']
];
$columns = ['id', 'property_id', 'channel_id', 'room_rate_channel_mapping_id', 'action_type', 'price_type', 'price_value'];
$requestSelectResult = $this->propertyQuickPricingService->selectPropertyQuickPricingMapping($requestSelectCriteria, $columns);
if ($requestSelectResult['status'] != 'success') {
throw new ApiErrorException($requestSelectResult['message']);
}
$propertyQuickPricingMapping = $requestSelectResult['data'];
DB::beginTransaction();
foreach ($propertyQuickPricingMapping as $quickPricing) {
//Eğer kanalda kapalı bir room rate var ise onun fiyatı güncellenmez
if (!in_array($quickPricing['room_rate_channel_mapping_id'], $propertyRoomRateChannelIds)) {
continue;
}
//dd($quickPricing,$propertyChannelMapping,$this->params);
$requestParams = [
'property_id' => $quickPricing['property_id'],
'channel_id' => $quickPricing['channel_id'],
'user_id' => $request->auth->id,
'availability' => []
];
$requestParams['rates'] = [];
foreach ($this->params['params']['data'] as $date => $amount) {
$dateForSql = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2);
if (!Carbon::parse($dateForSql)) {
throw new ApiErrorException('Invalid date format.');
}
if (Carbon::parse($dateForSql)->isBefore(Carbon::now()->toDateString())) {
throw new ApiErrorException('Date to be updated cannot be earlier than today');
}
$dateKeyParam = [];
$dateKeyParam[] = $propertyChannelMapping['property_availability_type_id'];
$dateKeyParam[] = $quickPricing['property_room_rate_channel_mapping']['property_room_rate_mapping']['room_id'];
$dateKeyParam[] = $quickPricing['property_room_rate_channel_mapping']['room_rate_mapping_id'];
$dateKeyParam[] = $dateForSql;
$dateKey = implode('|', $dateKeyParam);
$amountCalculated = $amount;
$amountAffected = 0;
if ($quickPricing['price_type'] == 'PER') {
$amountAffected = ($amount * $quickPricing['price_value']) / 100;
} elseif ($quickPricing['price_type'] == 'FIX') {
$amountAffected = $quickPricing['price_value'];
}
if ($quickPricing['action_type'] == 'INC') {
$amountCalculated = $amountCalculated + $amountAffected;
}
if ($quickPricing['action_type'] == 'DEC') {
$amountCalculated = $amountCalculated - $amountAffected;
}
if ($amountCalculated <= 0) {
throw new ApiErrorException('Calculated amount cannot be 0 or less.');
}
$requestParams['rates'][$dateKey] = [
"setup_type_id" => $propertyChannelMapping['property_availability_type_id'],
"room_id" => $quickPricing['property_room_rate_channel_mapping']['property_room_rate_mapping']['room_id'],
"room_rate_mapping_id" => $quickPricing['property_room_rate_channel_mapping']['room_rate_mapping_id'],
"date" => $dateForSql,
"amount" => $amountCalculated
];
}
$requestParams['quickPricing'] = true;
$roomRateUpdate = $this->propertyRoomRatePriceService->roomRateUpdate($requestParams);
if ($roomRateUpdate['status'] != 'success') {
throw new ApiErrorException($roomRateUpdate['message']);
}
//CONNECTED CHANNEL RATE UPDATE
foreach ($propertyChannelConnectedList as $propertyChannelConnected) {
$requestParams['channel_id'] = $propertyChannelConnected['channel_id'];
$roomRateUpdate = $this->propertyRoomRatePriceService->roomRateUpdate($requestParams);
if ($roomRateUpdate['status'] != 'success') {
throw new ApiErrorException($roomRateUpdate['message']);
}
}
//CONNECTED CHANNEL RATE UPDATE
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => []];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomBedService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomBedController extends Controller
{
private $request;
private $propertyRoomBedService;
public function __construct(
Request $request,
PropertyRoomBedService $propertyRoomBedService
)
{
$this->request = $request;
$this->propertyRoomBedService = $propertyRoomBedService;
}
public function getPropertyRoomBed(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
];
$propertyRoomBedType = $this->propertyRoomBedService->getPropertyRoomBeds($requestParams);
if($propertyRoomBedType['status'] != 'success'){
throw new ApiErrorException($propertyRoomBedType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomBedType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomBed(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id', null),
'room_id' => fillOnUndefined($params, 'room_id', null),
'room_bed_group' => fillOnUndefined($params, 'room_bed_group', []),
'user_id' => $this->request->auth->id,
];
$propertyRoomBedType = $this->propertyRoomBedService->addPropertyRoomBed($requestParams);
if($propertyRoomBedType['status'] != 'success'){
throw new ApiErrorException($propertyRoomBedType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomBedType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomBedTypeService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomBedTypeController
{
private $request;
private $propertyRoomBedTypeService;
public function __construct(
Request $request,
PropertyRoomBedTypeService $propertyRoomBedTypeService
)
{
$this->request = $request;
$this->propertyRoomBedTypeService = $propertyRoomBedTypeService;
}
public function getPropertyRoomBedTypes(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
];
$propertyRoomBedType = $this->propertyRoomBedTypeService->getPropertyRoomBedTypes($requestParams);
if($propertyRoomBedType['status'] != 'success'){
throw new ApiErrorException($propertyRoomBedType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomBedType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,665 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomService;
use App\Core\Service\PropertyRoomTypeService;
use Illuminate\Http\Request;
use App\Core\Service\PropertyRoomBedTypeService;
use App\Core\Service\PropertyRoomViewTypeService;
use App\Core\Service\PropertyChannelMappingService ;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomController
{
private $request;
private $propertyRoomService;
private $propertyRoomTypeService;
private $propertyRoomBedTypeService;
private $propertyRoomViewTypeService;
private $propertyChannelMappingService;
public function __construct(
Request $request,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyRoomService $propertyRoomService,
PropertyRoomTypeService $propertyRoomTypeService,
PropertyRoomBedTypeService $propertyRoomBedTypeService,
PropertyRoomViewTypeService $propertyRoomViewTypeService
)
{
$this->request = $request;
$this->propertyRoomService = $propertyRoomService;
$this->propertyRoomTypeService = $propertyRoomTypeService;
$this->propertyRoomBedTypeService = $propertyRoomBedTypeService;
$this->propertyRoomViewTypeService = $propertyRoomViewTypeService;
$this->propertyChannelMappingService = $propertyChannelMappingService ;
}
public function getPropertyRoom(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyRoomType = $this->propertyRoomService->getPropertyRooms($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoom(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => fillOnUndefined($params, 'name'),
'room_type_id' => fillOnUndefined($params, 'room_type_id'),
'max_occupancy' => fillOnUndefined($params, 'max_occupancy'),
'max_adult' => fillOnUndefined($params, 'max_adult'),
'max_child' => fillOnUndefined($params, 'max_child'),
'occupancy_lock' => fillOnUndefined($params, 'occupancy_lock'),
'room_size' => fillOnUndefined($params, 'room_size'),
'room_size_type' => fillOnUndefined($params, 'room_size_type'),
'room_type_count' => fillOnUndefined($params, 'room_type_count',1),
'room_count' => fillOnUndefined($params, 'room_count'),
'bathroom_count' => fillOnUndefined($params, 'bathroom_count'),
'toilet_count' => fillOnUndefined($params, 'toilet_count'),
'lounge_count' => fillOnUndefined($params, 'lounge_count'),
'max_child_number' => fillOnUndefined($params, 'max_child_number'),
'description' => fillOnUndefined($params, 'description'),
'user_id' => $this->request->auth->id,
];
$propertyRoomType = $this->propertyRoomService->addPropertyRoom($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomAndBed(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => trim(fillOnUndefined($params, 'name')),
'room_type_id' => fillOnUndefined($params, 'room_type_id'),
'max_occupancy' => fillOnUndefined($params, 'max_occupancy'),
'max_adult' => fillOnUndefined($params, 'max_adult'),
'max_child' => fillOnUndefined($params, 'max_child'),
'occupancy_lock' => fillOnUndefined($params, 'occupancy_lock'),
'exclude_occupancy' => fillOnUndefined($params, 'exclude_occupancy'),
'room_size' => fillOnUndefined($params, 'room_size', null),
'room_size_type' => fillOnUndefined($params, 'room_size_type', null),
'room_type_count' => fillOnUndefined($params, 'room_type_count', 1),
'room_count' => fillOnUndefined($params, 'room_count', null),
'bathroom_count' => fillOnUndefined($params, 'bathroom_count', null),
'toilet_count' => fillOnUndefined($params, 'toilet_count', null),
'lounge_count' => fillOnUndefined($params, 'lounge_count', null),
'max_child_number' => fillOnUndefined($params, 'max_child_number', null),
'description' => fillOnUndefined($params, 'description', []),
'room_bed_group' => fillOnUndefined($params, 'room_bed_group'),
'room_view_type' => fillOnUndefined($params, 'room_view_type'),
'is_connected_room' => fillOnUndefined($params, 'is_connected_room', null),
'is_connected_room_price' => fillOnUndefined($params, 'is_connected_room_price', null),
'is_connected_room_availability' => fillOnUndefined($params, 'is_connected_room_availability', null),
'connected_rooms' => fillOnUndefined($params, 'connected_rooms', []),
'user_id' => $this->request->auth->id,
];
$propertyRoomType = $this->propertyRoomService->addPropertyRoomAndBed($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyRoomAndBed(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'name' => trim(fillOnUndefined($params, 'name')),
'room_type_id' => fillOnUndefined($params, 'room_type_id'),
'max_occupancy' => fillOnUndefined($params, 'max_occupancy'),
'max_adult' => fillOnUndefined($params, 'max_adult'),
'max_child' => fillOnUndefined($params, 'max_child'),
'occupancy_lock' => fillOnUndefined($params, 'occupancy_lock'),
'exclude_occupancy' => fillOnUndefined($params, 'exclude_occupancy'),
'room_size' => fillOnUndefined($params, 'room_size', null),
'room_size_type' => fillOnUndefined($params, 'room_size_type', null),
'room_type_count' => fillOnUndefined($params, 'room_type_count', 1),
'room_count' => fillOnUndefined($params, 'room_count', null),
'bathroom_count' => fillOnUndefined($params, 'bathroom_count', null),
'toilet_count' => fillOnUndefined($params, 'toilet_count', null),
'lounge_count' => fillOnUndefined($params, 'lounge_count', null),
'max_child_number' => fillOnUndefined($params, 'max_child_number', null),
'description' => fillOnUndefined($params, 'description', []),
'room_bed_group' => fillOnUndefined($params, 'room_bed_group'),
'room_view_type' => fillOnUndefined($params, 'room_view_type'),
'is_connected_room' => fillOnUndefined($params, 'is_connected_room', null),
'is_connected_room_price' => fillOnUndefined($params, 'is_connected_room_price', null),
'is_connected_room_availability' => fillOnUndefined($params, 'is_connected_room_availability', null),
'connected_rooms' => fillOnUndefined($params, 'connected_rooms', []),
"status" => fillOnUndefined($params, "status", 1),
'user_id' => $this->request->auth->id,
];
$propertyRoomType = $this->propertyRoomService->updatePropertyRoomAndBed($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyRoom(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => trim(fillOnUndefined($params, 'name')),
'room_type_id' => fillOnUndefined($params, 'room_type_id'),
'max_occupancy' => fillOnUndefined($params, 'max_occupancy'),
'max_adult' => fillOnUndefined($params, 'max_adult'),
'max_child' => fillOnUndefined($params, 'max_child'),
'occupancy_lock' => fillOnUndefined($params, 'occupancy_lock'),
'exclude_occupancy' => fillOnUndefined($params, 'exclude_occupancy'),
'room_size' => fillOnUndefined($params, 'room_size', null),
'room_size_type' => fillOnUndefined($params, 'room_size_type', null),
'room_type_count' => fillOnUndefined($params, 'room_type_count', 1),
'room_count' => fillOnUndefined($params, 'room_count', null),
'bathroom_count' => fillOnUndefined($params, 'bathroom_count', null),
'toilet_count' => fillOnUndefined($params, 'toilet_count', null),
'lounge_count' => fillOnUndefined($params, 'lounge_count', null),
'max_child_number' => fillOnUndefined($params, 'max_child_number', null),
'description' => fillOnUndefined($params, 'description', []),
'user_id' => $this->request->auth->id,
];
$propertyRoomType = $this->propertyRoomService->updatePropertyRoom($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$propertyRoomType['data']['exclude_occupancy'] = json_decode($propertyRoomType['data']['exclude_occupancy'], true);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyRoomAndBed(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'room_id' => fillOnUndefined($params, 'room_id'),
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $this->request->auth->id,
];
$propertyRoom = $this->propertyRoomService->getPropertyRoomAndBed($requestParams);
if($propertyRoom['status'] != 'success'){
throw new ApiErrorException($propertyRoom['message']);
}
$responseData['property_room'] = $propertyRoom['data'] ;
$propertyRoomType = $this->propertyRoomTypeService->getPropertyRoomTypes($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$responseData['property_room_types'] = $propertyRoomType['data'] ;
$propertyRoomBedType = $this->propertyRoomBedTypeService->getPropertyRoomBedTypes($requestParams);
if($propertyRoomBedType['status'] != 'success'){
throw new ApiErrorException($propertyRoomBedType['message']);
}
$responseData['property_room_bed_types'] = $propertyRoomBedType['data'] ;
$propertyRoomViewTypeCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1]
],
"orderBy" => [
["field" => "name", "value" => "ASC"]
]
];
$propertyRoomViewTypeList = $this->propertyRoomViewTypeService->getPropertyRoomViewTypes($propertyRoomViewTypeCriteria);
if($propertyRoomViewTypeList['status'] != 'success'){
throw new ApiErrorException($propertyRoomViewTypeList['message']);
}
$responseData['property_room_view_types'] = $propertyRoomViewTypeList['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyRoom(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'user_id' => $this->request->auth->id,
];
$propertyRoomType = $this->propertyRoomService->deletePropertyRoom($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyRoomRateChannel(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyRoomType = $this->propertyRoomService->getPropertyRoomRateChannel($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyRoomInventory(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_mapping_id' => fillOnUndefined($params, 'room_rate_mapping_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
'start_date' => fillOnUndefined($params, 'start_date'),
'end_date' => fillOnUndefined($params, 'end_date'),
];
$propertyRoomType = $this->propertyRoomService->getPropertyRoomInventory($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
//Best Available Rate Manipulate
foreach ($propertyRoomType['data'] as $roomKey => $room) {
foreach ($room['property_room_rate_mapping'] as $roomRateMappingKey => $roomRateMapping) {
if($roomRateMapping['name'] == 'Best Available Rate') {
unset($room['property_room_rate_mapping'][$roomRateMappingKey]);
}
}
$propertyRoomType['data'][$roomKey]['property_room_rate_mapping'] = array_values($room['property_room_rate_mapping']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getChannelRoomRateMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$propertyRoomType = $this->propertyRoomService->getChannelRoomRateMapping($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getChannelBulkUpdateParams(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$propertyRooms = $this->propertyRoomService->getChannelRoomRateMapping($requestParams);
if($propertyRooms['status'] != 'success'){
throw new ApiErrorException($propertyRooms['message']);
}
$propertyRooms = $propertyRooms['data'] ;
$rooms = [] ;
foreach ($propertyRooms as $propertyRoom) {
$room = [
'id' => $propertyRoom['id'],
'name' => $propertyRoom['name'],
'room_selected' => false,
] ;
$rates = [] ;
foreach ($propertyRoom['property_room_rate_mapping'] as $roomRate) {
//Best Available Rate Manipulate
if($roomRate['name'] == 'Best Available Rate') {
continue;
}
if($roomRate['is_selected'] === true){
$rate = [
'id' => $roomRate['room_rate_id'],
'room_rate_mapping_id' => $roomRate['id'],
'name' => $roomRate['name'],
'rate_selected' => false,
] ;
$rates[] = $rate ;
}
}
if($rates){
$room['room_rate_mapping'] = $rates;
$rooms[] = $room;
}
}
$bulkUpdateOptionParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
'user_id' => $this->request->auth->id,
];
$channelMapping = $this->propertyChannelMappingService->getPropertyChannelSetup($bulkUpdateOptionParams);
if($channelMapping['status'] != 'success'){
throw new ApiErrorException($channelMapping['message']);
}
$channelMapping = $channelMapping['data'] ;
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['room_rates' => $rooms, 'bulk_update_options' => $channelMapping['bulk_update_options']]];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomFactMappingService;
use App\Core\Service\PropertyFactService;
use Predis\Replication\RoleException;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomFactMappingController extends Controller
{
private $request;
private $propertyRoomFactMappingService;
private $propertyFactService;
public function __construct(
Request $request,
PropertyRoomFactMappingService $propertyRoomFactMappingService,
PropertyFactService $propertyFactService
)
{
$this->request = $request;
$this->propertyRoomFactMappingService = $propertyRoomFactMappingService;
$this->propertyFactService = $propertyFactService;
}
public function updatePropertyRoomFactMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try
{
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(),1);
$params = current($params);
$params['user_id'] = $this->request->auth->id;
$response = $this->propertyRoomFactMappingService->updatePropertyRoomFactMapping($params);
}catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyRoomFact(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestFact = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
];
$getPropertyFact = $this->propertyFactService->getPropertyRoomFact($requestFact);
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getPropertyFact['data'] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyRoomFactIsFeature(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try
{
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(),1);
$params = current($params);
$params['user_id'] = $this->request->auth->id;
$response = $this->propertyRoomFactMappingService->updatePropertyRoomFactIsFeature($params);
}catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomPhotoMappingService;
use App\Core\Service\PropertyPhotoService\PropertyPhotoService;
use Predis\Replication\RoleException;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomPhotoMappingController extends Controller
{
private $request;
private $propertyRoomPhotoMappingService;
private $propertyPhotoService;
public function __construct(
Request $request,
PropertyRoomPhotoMappingService $propertyRoomPhotoMappingService,
PropertyPhotoService $propertyPhotoService
)
{
$this->request = $request;
$this->propertyRoomPhotoMappingService = $propertyRoomPhotoMappingService;
$this->propertyPhotoService = $propertyPhotoService;
}
public function updatePropertyRoomPhotoMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try
{
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = json_decode($this->request->getContent(),1);
$params = current($params);
$params['user_id'] = $this->request->auth->id;
$response = $this->propertyRoomPhotoMappingService->updatePropertyRoomPhotoMapping($params);
}catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyRoomPhoto(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestFact = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
];
$getPropertyPhoto = $this->propertyPhotoService->getPropertyRoomPhoto($requestFact);
if ($getPropertyPhoto['status'] != 'success') {
throw new ApiErrorException($getPropertyPhoto['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $getPropertyPhoto['data'] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,177 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomRateChannelMappingService;
use App\Core\Service\PropertyChannelService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomRateChannelMappingController
{
private $request;
private $propertyRoomRateChannelMappingService;
private $propertyChannelService ;
public function __construct(
Request $request,
PropertyChannelService $propertyChannelService,
PropertyRoomRateChannelMappingService $propertyRoomRateChannelMappingService
)
{
$this->request = $request;
$this->propertyRoomRateChannelMappingService = $propertyRoomRateChannelMappingService;
$this->propertyChannelService = $propertyChannelService ;
}
public function getPropertyRoomRateChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
];
$propertyChannel = $this->propertyChannelService->getPropertyChannels($requestParams);
if($propertyChannel['status'] != 'success'){
throw new ApiErrorException($propertyChannel['message']);
}
$propertyChannels = collect($propertyChannel['data'])->where('is_selected', '=', true);
if($requestParams['channel_id']){
$propertyChannels = $propertyChannels->whereIn('id', $requestParams['channel_id']) ;
}
$propertyChannels = $propertyChannels->values()->toArray() ;
$requestParams['channels'] = $propertyChannels ;
$propertyRoomRateChannelMapping = $this->propertyRoomRateChannelMappingService->getPropertyRoomRateChannelMapping($requestParams);
if($propertyRoomRateChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomRateChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_mapping_id' => fillOnUndefined($params, 'room_rate_mapping_id'),
'channels' => fillOnUndefined($params, 'channels'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRateChannelMapping = $this->propertyRoomRateChannelMappingService->addPropertyRoomRateChannelMapping($requestParams);
if($propertyRoomRateChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyRoomRateChannelMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_channel_mapping' => fillOnUndefined($params, 'room_rate_channel_mapping'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRateChannelMapping = $this->propertyRoomRateChannelMappingService->updatePropertyRoomRateChannelMapping($requestParams);
if($propertyRoomRateChannelMapping['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateChannelMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateChannelMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,527 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomRateService;
use App\Core\Service\PropertyRoomRateMappingService;
use App\Core\Service\PropertyRoomService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomRateController
{
private $request;
private $propertyRoomRateService;
private $propertyRoomRateMappingService;
private $propertyRoomService;
public function __construct(
Request $request,
PropertyRoomRateService $propertyRoomRateService,
PropertyRoomRateMappingService $propertyRoomRateMappingService,
PropertyRoomService $propertyRoomService
)
{
$this->request = $request;
$this->propertyRoomRateService = $propertyRoomRateService;
$this->propertyRoomRateMappingService = $propertyRoomRateMappingService;
$this->propertyRoomService = $propertyRoomService;
}
public function getPropertyRoomRate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyRoomRate = $this->propertyRoomRateService->getPropertyRoomRates($requestParams);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyRoomRateConnected(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
];
$propertyRoomRateConnected = $this->propertyRoomRateMappingService->getPropertyRoomRateMappingConnected($requestParams);
if($propertyRoomRateConnected['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateConnected['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateConnected['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncPropertyRoomRateConnected(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
'connected_room_rate' => fillOnUndefined($params, 'connected_room_rate'),
];
$propertyRoomRateConnected = $this->propertyRoomRateMappingService->syncPropertyRoomRateMappingConnected($requestParams);
if($propertyRoomRateConnected['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateConnected['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateConnected['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomRate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => fillOnUndefined($params, 'name'),
'description' => fillOnUndefined($params, 'description'),
'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
'min_stay' => fillOnUndefined($params, 'min_stay'),
'max_stay' => fillOnUndefined($params, 'max_stay'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRate = $this->propertyRoomRateService->addPropertyRoomRate($requestParams);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomRateWithInclusion(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => fillOnUndefined($params, 'name'),
'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
'description' => fillOnUndefined($params, 'description'),
/* 'min_stay' => fillOnUndefined($params, 'min_stay'),
'max_stay' => fillOnUndefined($params, 'max_stay'),*/
'facts' => fillOnUndefined($params, 'facts'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRate = $this->propertyRoomRateService->addPropertyRoomRateWithInclusion($requestParams);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
foreach ($params['rooms'] as $room){
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => [$room['room_id']],
'room_rate_id' => $propertyRoomRate['data']['id'],
'rack_rate' => fillOnUndefined($params, 'rack_rate'),
'included_occupancy' => $room['value'],
'room_rate_mapping_setup' => [
[
'setup_type' => 'EXT_ADULT',
'value_type' => fillOnUndefined($params, 'ext_adult_type'),
'value' => fillOnUndefined($params, 'ext_adult_rate'),
],
[
'setup_type' => 'EXT_CHILD',
'value_type' => fillOnUndefined($params, 'ext_child_type'),
'value' => fillOnUndefined($params, 'ext_child_rate'),
],
[
'setup_type' => 'DIS_GUEST',
'value_type' => fillOnUndefined($params, 'dis_guest_type'),
'value' => fillOnUndefined($params, 'dis_guest_rate'),
],
],
'user_id' => $this->request->auth->id,
];
$propertyRoomRateMapping = $this->propertyRoomRateMappingService->addPropertyRoomRateMappingWithSetup($requestParams);
if ($propertyRoomRateMapping['status'] != 'success') {
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyRoomRate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
DB::beginTransaction();
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => trim(fillOnUndefined($params, 'name')),
'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
'min_stay' => fillOnUndefined($params, 'min_stay'),
'facts' => fillOnUndefined($params, 'facts', []),
'description' => fillOnUndefined($params, 'description'),
'user_id' => $this->request->auth->id,
];
if(isset($params['status'])){
$requestParams['status'] = fillOnUndefined($params, "status", 0);
}
$propertyRoomRate = $this->propertyRoomRateService->updatePropertyRoomRate($requestParams);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
if(isset($params['rooms'])){
foreach ($params['rooms'] as $room){
$criteria = [
['field' => 'room_id', 'condition' => '=', 'value' => $room['room_id']],
['field' => 'room_rate_id', 'condition' => '=', 'value' => $params['id']]
];
$data = [
'room_id' => fillOnUndefined($room, 'room_id'),
'room_rate_id' => fillOnUndefined($params, 'id'),
'included_occupancy' => fillOnUndefined($room, 'value'),
'status' => 1,
'created_by' => $this->request->auth->id,
'updated_by' => $this->request->auth->id,
'created_at' => time(),
'updated_at' => time(),
];
$propertyRoomRateMapping = $this->propertyRoomRateMappingService->updateOrCreate($criteria,$data);
if($propertyRoomRateMapping['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateMapping['message']);
}
}
}
DB::commit();
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
DB::rollBack();
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
DB::rollBack();
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyRoomRate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRate = $this->propertyRoomRateService->deletePropertyRoomRate($requestParams);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyAccommodationTypes(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRate = $this->propertyRoomRateService->getPropertyAccommodationTypes($requestParams);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function editPropertyRoomRate(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$criteria = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $params['room_rate_id']],
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
],
'firstRow' => 1
];
$propertyRoomRate = $this->propertyRoomRateService->select($criteria);
if($propertyRoomRate['status'] != 'success'){
throw new ApiErrorException($propertyRoomRate['message']);
}
$criteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1]
],
'with' => ['propertyRoomRateMapping']
];
$propertyRoom = $this->propertyRoomService->select($criteria);
if($propertyRoom['status'] != 'success'){
throw new ApiErrorException($propertyRoom['message']);
}
$propertyRoomRate['data']['rooms'] = $propertyRoom['data'];
foreach ($propertyRoomRate['data']['rooms'] as $roomKey => $roomVal){
$propertyRoomRate['data']['rooms'][$roomKey]['is_selected'] = false;
$propertyRoomRate['data']['rooms'][$roomKey]['is_selected_lock'] = false;
$propertyRoomRate['data']['rooms'][$roomKey]['included_occupancy'] = null;
foreach ($roomVal['property_room_rate_mapping'] as $rate){
if($rate['room_rate_id'] == $params['room_rate_id']){
$propertyRoomRate['data']['rooms'][$roomKey]['is_selected'] = true;
$propertyRoomRate['data']['rooms'][$roomKey]['is_selected_lock'] = true;
$propertyRoomRate['data']['rooms'][$roomKey]['included_occupancy'] = $rate['included_occupancy'];
break;
}
}
unset($propertyRoomRate['data']['rooms'][$roomKey]['property_room_rate_mapping']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRate['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomRateInclusionMappingService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomRateInclusionMappingController
{
private $request;
private $propertyRoomRateInclusionMappingService;
public function __construct(
Request $request,
PropertyRoomRateInclusionMappingService $propertyRoomRateInclusionMappingService
)
{
$this->request = $request;
$this->propertyRoomRateInclusionMappingService = $propertyRoomRateInclusionMappingService;
}
public function getPropertyRoomRateInclusionMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRateInclusionMapping = $this->propertyRoomRateInclusionMappingService->getPropertyRoomRateInclusionMapping($requestParams);
if($propertyRoomRateInclusionMapping['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateInclusionMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateInclusionMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomRateInclusionMapping(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
'facts' => fillOnUndefined($params, 'facts'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRateInclusionMapping = $this->propertyRoomRateInclusionMappingService->addPropertyRoomRateInclusionMapping($requestParams);
if($propertyRoomRateInclusionMapping['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateInclusionMapping['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateInclusionMapping['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,124 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomRateMappingSetupService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomRateMappingSetupController
{
private $request;
private $propertyRoomRateMappingSetupService;
public function __construct(
Request $request,
PropertyRoomRateMappingSetupService $propertyRoomRateMappingSetupService
)
{
$this->request = $request;
$this->propertyRoomRateMappingSetupService = $propertyRoomRateMappingSetupService;
}
public function getPropertyRoomRateMappingSetup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_mapping_id' => fillOnUndefined($params, 'room_rate_mapping_id'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRateMappingSetup = $this->propertyRoomRateMappingSetupService->getPropertyRoomRateMappingSetup($requestParams);
if($propertyRoomRateMappingSetup['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateMappingSetup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateMappingSetup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomRateMappingSetup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'room_id' => fillOnUndefined($params, 'room_id'),
'room_rate_mapping_id' => fillOnUndefined($params, 'room_rate_mapping_id'),
'setup' => fillOnUndefined($params, 'setup'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRateMappingSetup = $this->propertyRoomRateMappingSetupService->addPropertyRoomRateMappingSetup($requestParams);
if($propertyRoomRateMappingSetup['status'] != 'success'){
throw new ApiErrorException($propertyRoomRateMappingSetup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRateMappingSetup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,217 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomRatePriceService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomRatePriceController
{
private $request;
private $propertyRoomRatePriceService;
public function __construct(
Request $request,
PropertyRoomRatePriceService $propertyRoomRatePriceService
)
{
$this->request = $request;
$this->propertyRoomRatePriceService = $propertyRoomRatePriceService;
}
public function getPropertyRoomRatePrice(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyRoomRatePrice = $this->propertyRoomRatePriceService->getPropertyRoomRatePrices($requestParams);
if($propertyRoomRatePrice['status'] != 'success'){
throw new ApiErrorException($propertyRoomRatePrice['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRatePrice['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function addPropertyRoomRatePrice(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
'property_room_id' => fillOnUndefined($params, 'property_room_id'),
'room_rate_mapping_id' => fillOnUndefined($params, 'room_rate_mapping_id'),
'offer_id' => fillOnUndefined($params, 'offer_id'),
'channel_id' => fillOnUndefined($params, 'channel_id'),
'min_stay' => fillOnUndefined($params, 'min_stay'),
'max_stay' => fillOnUndefined($params, 'max_stay'),
'stop_sell' => fillOnUndefined($params, 'stop_sell'),
'booking_on_request' => fillOnUndefined($params, 'booking_on_request'),
'start_date' => fillOnUndefined($params, 'start_date'),
'end_date' => fillOnUndefined($params, 'end_date'),
'amount' => fillOnUndefined($params, 'amount'),
'currency' => fillOnUndefined($params, 'currency'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRatePrice = $this->propertyRoomRatePriceService->addPropertyRoomRatePrice($requestParams);
if($propertyRoomRatePrice['status'] != 'success'){
throw new ApiErrorException($propertyRoomRatePrice['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRatePrice['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyRoomRatePrice(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'property_id' => fillOnUndefined($params, 'property_id'),
'name' => fillOnUndefined($params, 'name'),
'description' => fillOnUndefined($params, 'description'),
'min_stay' => fillOnUndefined($params, 'min_stay'),
'user_id' => $this->request->auth->id,
];
if(isset($params['status'])){
$requestParams['status'] = fillOnUndefined($params, "status", 0);
}
$propertyRoomRatePrice = $this->propertyRoomRatePriceService->updatePropertyRoomRatePrice($requestParams);
if($propertyRoomRatePrice['status'] != 'success'){
throw new ApiErrorException($propertyRoomRatePrice['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRatePrice['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyRoomRatePrice(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => fillOnUndefined($params, 'id'),
'user_id' => $this->request->auth->id,
];
$propertyRoomRatePrice = $this->propertyRoomRatePriceService->deletePropertyRoomRatePrice($requestParams);
if($propertyRoomRatePrice['status'] != 'success'){
throw new ApiErrorException($propertyRoomRatePrice['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomRatePrice['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\PropertyRoomSizeTypeService;
use App\Exceptions\ApiErrorException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class PropertyRoomSizeTypeController
{
private $propertyRoomSizeTypeService;
public function __construct(PropertyRoomSizeTypeService $propertyRoomSizeTypeService)
{
$this->propertyRoomSizeTypeService = $propertyRoomSizeTypeService;
}
public function getPropertyRoomSizeTypes(){
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$propertyRoomSizeTypeCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
],
"orderBy" => [
["field" => "name", "value" => "ASC"]
]
];
$propertyRoomSizeTypes = $this->propertyRoomSizeTypeService->select($propertyRoomSizeTypeCriteria, ['id', 'name', 'code', 'language_key']);
if($propertyRoomSizeTypes['status'] != 'success'){
throw new Exception($propertyRoomSizeTypes['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomSizeTypes['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomTypeService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomTypeController
{
private $request;
private $propertyRoomTypeService;
public function __construct(
Request $request,
PropertyRoomTypeService $propertyRoomTypeService
)
{
$this->request = $request;
$this->propertyRoomTypeService = $propertyRoomTypeService;
}
public function getPropertyRoomTypes(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
];
$propertyRoomType = $this->propertyRoomTypeService->getPropertyRoomTypes($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyMappedRoomTypes(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
'property_id' => fillOnUndefined($params, 'property_id'),
];
$propertyRoomType = $this->propertyRoomTypeService->getPropertyMappedRoomTypes($requestParams);
if($propertyRoomType['status'] != 'success'){
throw new ApiErrorException($propertyRoomType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyRoomViewTypeService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyRoomViewTypeController
{
private $propertyRoomViewTypeService;
public function __construct(
PropertyRoomViewTypeService $propertyRoomViewTypeService
)
{
$this->propertyRoomViewTypeService = $propertyRoomViewTypeService;
}
public function getPropertyRoomViewTypeList()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$propertyRoomViewTypeCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1]
],
"orderBy" => [
["field" => "name", "value" => "ASC"]
]
];
$propertyRoomViewTypeList = $this->propertyRoomViewTypeService->getPropertyRoomViewTypes($propertyRoomViewTypeCriteria);
if($propertyRoomViewTypeList['status'] != 'success'){
throw new ApiErrorException($propertyRoomViewTypeList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyRoomViewTypeList['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyTypeService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyTypeController
{
private $request;
private $propertyTypeService;
public function __construct(
Request $request,
PropertyTypeService $propertyTypeService
)
{
$this->request = $request;
$this->propertyTypeService = $propertyTypeService;
}
public function getPropertyTypes(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'locale' => fillOnUndefined($params, 'locale'),
];
$propertyType = $this->propertyTypeService->getPropertyTypes($requestParams);
if($propertyType['status'] != 'success'){
throw new ApiErrorException($propertyType['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyType['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,250 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\LanguageService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyWebService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Exception;
class PropertyWebComponentController extends Controller
{
private $params;
private $propertyChannelMappingService;
private $languageService;
public function __construct(
PropertyWebService $propertyWebService,
PropertyChannelMappingService $propertyChannelMappingService,
LanguageService $languageService
)
{
$this->params = Input::all();
$this->params = $this->params['params'];
$this->propertyWebService = $propertyWebService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->languageService = $languageService;
}
public function getPropertyWebComponent(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
//TODO: Validator
$propertyWebComponentCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$propertyWebComponent = $this->propertyWebService->selectPropertyWebComponent($propertyWebComponentCriteria);
$propertyWebComponent = $propertyWebComponent['status'] == 'success' && !empty($propertyWebComponent['data']) ? $propertyWebComponent['data'] : [];
$propertyWebComponentMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$propertyWebComponentMapping = $this->propertyWebService->selectPropertyWebComponentMapping($propertyWebComponentMappingCriteria);
$propertyWebComponentMapping = $propertyWebComponentMapping['status'] == 'success' && !empty($propertyWebComponentMapping['data']) ? $propertyWebComponentMapping['data'] : [];
$propertyChannelAddonCollect = collect($propertyWebComponentMapping);
$propertyWebComponentList = [];
foreach ($propertyWebComponent as $webComponentKey => $webComponent) {
$webComponentMapping = $propertyChannelAddonCollect->where('component_id', $webComponent['id'])->first();
$webComponentDetail = null;
$isSelected = $webComponentMapping ? true : false;
if ($webComponentMapping) {
$webComponentDetail = [
'component_id' => $webComponentMapping['component_id'],
'parameterArray' => $webComponentMapping['parameterArray'],
'language' => $webComponentMapping['language'],
'languageArray' => $webComponentMapping['languageArray'],
];
}
$propertyWebComponentList[] = [
//'code' => $webComponent['code'],
'id' => $webComponent['id'],
'name' => $webComponent['name'],
'component' => $webComponent['component'],
'icon' => $webComponent['icon'],
'iconUrl' => $webComponent['iconUrl'],
'parameterArray' => $webComponent['parameterArray'],
'is_selected' => $isSelected,
'componentDetail' => $webComponentDetail
];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebComponentList];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncPropertyWebComponent(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$propertyWebComponentCriteria = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'component_id')],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyWebComponent = $this->propertyWebService->selectPropertyWebComponent($propertyWebComponentCriteria);
$propertyWebComponent = $propertyWebComponent['status'] == 'success' && !empty($propertyWebComponent['data']) ? $propertyWebComponent['data'] : [];
if(empty($propertyWebComponent)){
throw new ApiErrorException(lang('Component data not found'));
}
//Parameter Check
if (!empty($this->params['componentDetail'])) {
$parameterCheck = array_diff(array_keys($propertyWebComponent['parameterArray']),array_keys($this->params['componentDetail']['parameter']));
if(!empty($parameterCheck)) {
throw new ApiErrorException(lang('Missing or incorrect parameter'));
}
}
$propertyWebComponentMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'property_id')],
['field' => 'channel_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'channel_id')],
['field' => 'component_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'component_id')],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$propertyWebComponentMapping = $this->propertyWebService->selectPropertyWebComponentMapping($propertyWebComponentMappingCriteria);
$propertyWebComponentMapping = $propertyWebComponentMapping['status'] == 'success' && !empty($propertyWebComponentMapping['data']) ? $propertyWebComponentMapping['data'] : [];
//Parameter Check
DB::beginTransaction();
if ($propertyWebComponentMapping) {
//Remove
if (empty($this->params['componentDetail'])) {
$syncPropertyWebComponent = $this->propertyWebService->deletePropertyWebComponentMapping($propertyWebComponentMapping['id']) ;
if($syncPropertyWebComponent['status'] != 'success'){
throw new Exception('api-unknown_error');
}
} else {
//Update
$updateParam = [
'property_id' => fillOnUndefined($this->params, 'property_id'),
'channel_id' => fillOnUndefined($this->params, 'channel_id'),
'component_id' => fillOnUndefined($this->params, 'component_id'),
'parameter' => fillOnUndefined($this->params['componentDetail'], 'parameter') ? json_encode($this->params['componentDetail']['parameter']) : null,
'language' => fillOnUndefined($this->params['componentDetail'], 'language') ? json_encode($this->params['componentDetail']['language']) : null,
'updated_by' => $request->auth->id,
];
$syncPropertyWebComponent = $this->propertyWebService->updatePropertyWebComponentMapping($propertyWebComponentMapping['id'], $updateParam);
if ($syncPropertyWebComponent['status'] != 'success') {
throw new ApiErrorException($syncPropertyWebComponent['message']);
}
}
} else {
$createParam = [
'property_id' => fillOnUndefined($this->params, 'property_id'),
'channel_id' => fillOnUndefined($this->params, 'channel_id'),
'component_id' => fillOnUndefined($this->params, 'component_id'),
'parameter' => fillOnUndefined($this->params['componentDetail'], 'parameter') ? json_encode($this->params['componentDetail']['parameter']) : null,
'language' => fillOnUndefined($this->params['componentDetail'], 'language') ? json_encode($this->params['componentDetail']['language']) : null,
'status' => 1,
'created_by' => $request->auth->id,
];
$syncPropertyWebComponent = $this->propertyWebService->createPropertyWebComponentMapping($createParam);
if ($syncPropertyWebComponent['status'] != 'success') {
throw new ApiErrorException($syncPropertyWebComponent['message']);
}
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,296 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyWebContentService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyWebContentController extends Controller
{
private $request;
private $propertyWebContentService;
public function __construct(
Request $request,
PropertyWebContentService $propertyWebContentService
)
{
$this->request = $request;
$this->propertyWebContentService = $propertyWebContentService;
}
public function getPropertyWebContent(Request $request, $id = null)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$columns = ['id', 'property_id', 'content_category_id', 'title', 'slug', 'image', 'language_code', 'status', 'created_at'];
$propertyWebContentCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']]
],
'with' => ['ContentCategory'],
'orderBy' => [
['field' => 'id', 'value' => 'DESC']
]
];
$availableFilterArray = ['title', 'content_category_id', 'language_code'];
if (!empty($params['filter'])) {
foreach ($params['filter'] as $filterKey => $filterValue) {
if (in_array($filterKey, $availableFilterArray)) {
if (in_array($filterKey, ['content_category_id', 'language_code', 'status'])) {
$propertyWebContentCriteria['criteria'][] = ['field' => $filterKey, 'condition' => '=', 'value' => $filterValue];
}
if (in_array($filterKey, ['title'])) {
$propertyWebContentCriteria['criteria'][] = ['field' => $filterKey, 'condition' => 'LIKE', 'value' => '%' . $filterValue . '%'];
}
}
}
}
if (!empty($id)) {
$propertyWebContentCriteria['criteria'][] = ['field' => 'id', 'condition' => '=', 'value' => $id];
$propertyWebContentCriteria['firstRow'] = true;
$columns[] = 'content';
}
$propertyWebContent = $this->propertyWebContentService->select($propertyWebContentCriteria, $columns);
if ($propertyWebContent['status'] != 'success') {
throw new Exception($propertyWebContent['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getPropertyWebContentCategory(Request $request, $id = null)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$columns = ['id', 'name', 'language_key'];
$propertyWebContentCategoryCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1]
],
'orderBy' => [
['field' => 'id', 'value' => 'ASC']
]
];
$propertyWebContentCategory = $this->propertyWebContentService->selectWebContentCategory($propertyWebContentCategoryCriteria, $columns);
if ($propertyWebContentCategory['status'] != 'success') {
throw new Exception($propertyWebContentCategory['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebContentCategory['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyWebContent(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'content_category_id' => fillOnUndefined($params, 'content_category_id'),
'title' => fillOnUndefined($params, 'title'),
'language_code' => fillOnUndefined($params, 'language_code'),
'image' => fillOnUndefined($params, 'image'),
'content' => fillOnUndefined($params, 'content'),
'user_id' => $this->request->credentials->user_id
];
$propertyContent = $this->propertyWebContentService->create($requestParams);
if ($propertyContent['status'] != 'success') {
throw new ApiErrorException($propertyContent['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyWebContent(Request $request, $id)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'content_category_id' => fillOnUndefined($params, 'content_category_id'),
'title' => fillOnUndefined($params, 'title'),
'language_code' => fillOnUndefined($params, 'language_code'),
'image' => fillOnUndefined($params, 'image'),
'content' => fillOnUndefined($params, 'content'),
'updated_by' => $this->request->credentials->user_id
];
$propertyContent = $this->propertyWebContentService->update($id, $requestParams);
if ($propertyContent['status'] != 'success') {
throw new ApiErrorException($propertyContent['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyWebContent(Request $request, $id)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => $id,
'property_id' => fillOnUndefined($params, 'property_id')
];
$propertyContent = $this->propertyWebContentService->delete($id, $requestParams);
if ($propertyContent['status'] != 'success') {
throw new ApiErrorException($propertyContent['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyContent['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function uploadPropertyWebContentImage(Request $request)
{
$response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
try {
if (!$request->hasFile('image')) {
throw new ApiErrorException(lang('Photos not found'));
}
$param = [
"property_id" => $request->input('property_id'),
"photo" => $request->file('image'),
];
$response = $this->propertyWebContentService->uploadPhoto($param);
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,255 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\PropertyWebPopupService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class PropertyWebPopupController extends Controller
{
private $request;
private $propertyWebContentService;
public function __construct(
Request $request,
PropertyWebPopupService $propertyWebPopupService
)
{
$this->request = $request;
$this->propertyWebPopupService = $propertyWebPopupService;
}
public function getPropertyWebPopup(Request $request, $id = null)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$columns = ['id', 'property_id', 'title', 'language_code', 'start_date', 'end_date', 'url', 'image', 'status', 'created_at'];
$criteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
],
'orderBy' => [
['field' => 'id', 'value' => 'DESC']
]
];
$availableFilterArray = ['title', 'language_code'];
if (!empty($params['filter'])) {
foreach ($params['filter'] as $filterKey => $filterValue) {
if (in_array($filterKey, $availableFilterArray)) {
if (in_array($filterKey, ['language_code', 'status'])) {
$criteria['criteria'][] = ['field' => $filterKey, 'condition' => '=', 'value' => $filterValue];
}
if (in_array($filterKey, ['title'])) {
$criteria['criteria'][] = ['field' => $filterKey, 'condition' => 'LIKE', 'value' => '%' . $filterValue . '%'];
}
}
}
}
if (!empty($id)) {
$criteria['criteria'][] = ['field' => 'id', 'condition' => '=', 'value' => $id];
$criteria['firstRow'] = true;
}
$propertyWebPopup = $this->propertyWebPopupService->select($criteria, $columns);
if ($propertyWebPopup['status'] != 'success') {
throw new Exception($propertyWebPopup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebPopup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function createPropertyWebPopup(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'title' => fillOnUndefined($params, 'title'),
'language_code' => fillOnUndefined($params, 'language_code'),
'image' => fillOnUndefined($params, 'image'),
'start_date' => fillOnUndefined($params, 'start_date'),
'end_date' => fillOnUndefined($params, 'end_date'),
'url' => fillOnUndefined($params, 'url'),
'user_id' => $this->request->credentials->user_id
];
$propertyWebPopup = $this->propertyWebPopupService->create($requestParams);
if ($propertyWebPopup['status'] != 'success') {
throw new ApiErrorException($propertyWebPopup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebPopup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function updatePropertyWebPopup(Request $request, $id)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'title' => fillOnUndefined($params, 'title'),
'language_code' => fillOnUndefined($params, 'language_code'),
'image' => fillOnUndefined($params, 'image'),
'start_date' => fillOnUndefined($params, 'start_date'),
'end_date' => fillOnUndefined($params, 'end_date'),
'url' => fillOnUndefined($params, 'url'),
'updated_by' => $this->request->credentials->user_id
];
$propertyWebPopup = $this->propertyWebPopupService->update($id, $requestParams);
if ($propertyWebPopup['status'] != 'success') {
throw new ApiErrorException($propertyWebPopup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebPopup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function deletePropertyWebPopup(Request $request, $id)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
if (is_null($this->request->getContent())) {
throw new ApiErrorException(lang('Parameter Error.'));
}
$params = $this->request->params;
$requestParams = [
'id' => $id,
'property_id' => fillOnUndefined($params, 'property_id')
];
$propertyWebPopup = $this->propertyWebPopupService->delete($id, $requestParams);
if ($propertyWebPopup['status'] != 'success') {
throw new ApiErrorException($propertyWebPopup['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyWebPopup['data']];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function uploadPropertyWebPopupImage(Request $request)
{
$response = ['status' => false, 'statusCode' => 500, 'message' => '', 'data' => null];
try {
if (!$request->hasFile('image')) {
throw new ApiErrorException(lang('Photos not found'));
}
$param = [
"property_id" => $request->input('property_id'),
"photo" => $request->file('image'),
];
$response = $this->propertyWebPopupService->uploadPhoto($param);
} catch (ApiErrorException $e) {
$response['message'] = $e->getMessage();
} catch (Exception $e) {
$message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
Log::error($message);
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,570 @@
<?php
namespace App\Http\Controllers\V1;
use App\Core\Service\ReputationManagementService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use App\Jobs\PropertyReviewServiceJob;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Exception;
class ReputationManagementController extends Controller
{
private $params;
private $reputationManagementService;
public function __construct(
ReputationManagementService $reputationManagementService
)
{
$this->params = Input::all();
$this->params = $this->params['params'];
$this->reputationManagementService = $reputationManagementService;
}
public function getChannel(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$criteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$reputationManagementChannel = $this->reputationManagementService->selectChannel($criteria, ['id', 'name', 'logo', 'parameter', 'logo']);
$reputationManagementChannel = $reputationManagementChannel['status'] == 'success' && !empty($reputationManagementChannel['data']) ? $reputationManagementChannel['data'] : [];
$reputationManagementMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['fetchStatus'],
];
$reputationManagementMapping = $this->reputationManagementService->selectChannelMapping($reputationManagementMappingCriteria);
$reputationManagementMapping = $reputationManagementMapping['status'] == 'success' && !empty($reputationManagementMapping['data']) ? $reputationManagementMapping['data'] : [];
$reputationManagementMappingCollect = collect($reputationManagementMapping);
$reputationManagementList = [];
foreach ($reputationManagementChannel as $reputationManagementChannelKey => $reputationManagementChannel) {
$reputationManagementMapping = $reputationManagementMappingCollect->where('channel_id', $reputationManagementChannel['id'])->first();
$reputationManagementDetail = null;
$isSelected = $reputationManagementMapping ? true : false;
if ($reputationManagementMapping) {
$reputationManagementDetail = [
'fetchStatus' => $reputationManagementMapping['fetch_status'],
'parameterArray' => $reputationManagementMapping['parameterArray']
];
}
$reputationManagementList[] = [
//'code' => $webComponent['code'],
'id' => $reputationManagementChannel['id'],
'name' => $reputationManagementChannel['name'],
'logo' => $reputationManagementChannel['logo'],
'logoUrl' => $reputationManagementChannel['logoUrl'],
'parameterArray' => $reputationManagementChannel['parameterArray'],
'is_selected' => $isSelected,
'channelDetail' => $reputationManagementDetail
];
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $reputationManagementList];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function syncChannel(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$criteria = [
'criteria' => [
['field' => 'id', 'condition' => '=', 'value' => $this->params['channel_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$reputationManagementChannel = $this->reputationManagementService->selectChannel($criteria, ['id', 'name', 'logo', 'parameter', 'logo']);
$reputationManagementChannel = $reputationManagementChannel['status'] == 'success' && !empty($reputationManagementChannel['data']) ? $reputationManagementChannel['data'] : [];
if (empty($reputationManagementChannel)) {
throw new ApiErrorException(lang('Channel data not found'));
}
//Parameter Check
if (!empty($this->params['channelDetail'])) {
$parameterCheck = array_diff(array_keys($reputationManagementChannel['parameterArray']), array_keys($this->params['channelDetail']['parameter']));
if (!empty($parameterCheck)) {
throw new ApiErrorException(lang('Missing or incorrect parameter'));
}
}
$reputationManagementChannelMappingCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'property_id')],
['field' => 'channel_id', 'condition' => '=', 'value' => fillOnUndefined($this->params, 'channel_id')],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => true
];
$reputationManagementChannelMapping = $this->reputationManagementService->selectChannelMapping($reputationManagementChannelMappingCriteria);
$reputationManagementChannelMapping = $reputationManagementChannelMapping['status'] == 'success' && !empty($reputationManagementChannelMapping['data']) ? $reputationManagementChannelMapping['data'] : [];
//Parameter Check
DB::beginTransaction();
if ($reputationManagementChannelMapping) {
//Remove
if (empty($this->params['channelDetail'])) {
$syncReputationManagementChannelMapping = $this->reputationManagementService->deleteChannelMapping($reputationManagementChannelMapping['id']);
if ($syncReputationManagementChannelMapping['status'] != 'success') {
throw new Exception('api-unknown_error');
}
} else {
//Update
$updateParam = [
'property_id' => fillOnUndefined($this->params, 'property_id'),
'channel_id' => fillOnUndefined($this->params, 'channel_id'),
'parameter' => fillOnUndefined($this->params['channelDetail'], 'parameter') ? json_encode($this->params['channelDetail']['parameter']) : null,
'fetch_status' => fillOnUndefined($reputationManagementChannelMapping, 'fetch_status'),
'updated_by' => $request->auth->id,
];
$syncReputationManagementChannelMapping = $this->reputationManagementService->updateChannelMapping($reputationManagementChannelMapping['id'], $updateParam);
if ($syncReputationManagementChannelMapping['status'] != 'success') {
throw new ApiErrorException($syncReputationManagementChannelMapping['message']);
}
}
} else {
$createParam = [
'property_id' => fillOnUndefined($this->params, 'property_id'),
'channel_id' => fillOnUndefined($this->params, 'channel_id'),
'parameter' => fillOnUndefined($this->params['channelDetail'], 'parameter') ? json_encode($this->params['channelDetail']['parameter']) : null,
'fetch_status' => 3,
'status' => 1,
'created_by' => $request->auth->id,
];
$syncReputationManagementChannelMapping = $this->reputationManagementService->createChannelMapping($createParam);
if ($syncReputationManagementChannelMapping['status'] != 'success') {
throw new ApiErrorException($syncReputationManagementChannelMapping['message']);
}
//First Fetch Review
dispatch(new PropertyReviewServiceJob($createParam['property_id'], $createParam['channel_id']));
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => null];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
if ($response['status']) {
DB::commit();
} else {
DB::rollBack();
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getReview(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$propertyReviewCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel', 'channel', 'categoryMapping.category'],
'orderBy' => [
['field' => 'review_date', 'value' => 'DESC']
],
];
if (isset($this->params['filter']) && !empty(isset($this->params['filter']))) {
if (isset($this->params['filter']['channel_id'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['filter']['channel_id']];
}
if (isset($this->params['filter']['start_date'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'review_date', 'condition' => '>', 'value' => $this->params['filter']['start_date']];
}
if (isset($this->params['filter']['end_date'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'review_date', 'condition' => '<=', 'value' => $this->params['filter']['end_date']];
}
if (isset($this->params['filter']['sentiment'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'sentiment', 'condition' => '=', 'value' => $this->params['filter']['sentiment']];
}
if (isset($this->params['filter']['keyword'])) {
$propertyReviewCriteria['whereOr'][] = ['field' => 'author', 'condition' => 'LIKE', 'value' => '%' . $this->params['filter']['keyword'] . '%'];
$propertyReviewCriteria['whereOr'][] = ['field' => 'title', 'condition' => 'LIKE', 'value' => '%' . $this->params['filter']['keyword'] . '%'];
$propertyReviewCriteria['whereOr'][] = ['field' => 'review', 'condition' => 'LIKE', 'value' => '%' . $this->params['filter']['keyword'] . '%'];
}
}
//Just Last 1 Year
$propertyReviewCriteria['criteria'][] = ['field' => 'review_date', 'condition' => '>', 'value' => Carbon::now()->subYear()->toDateString()];
$propertyReviewCriteriaCount = $propertyReviewCriteria;
$propertyReviewCriteriaCount['count'] = true;
$propertyReviewCount = $this->reputationManagementService->select($propertyReviewCriteriaCount, ['id']);
$propertyReviewCriteria['skip'] = fillOnUndefined($this->params, 'page', 0) ? ($this->params['page'] - 1) : 0;
$propertyReviewCriteria['take'] = fillOnUndefined($this->params, 'per_page', 20);
$propertyReviewCriteria['skip'] = $propertyReviewCriteria['skip'] * $propertyReviewCriteria['take'];
$column = ['id', 'property_id', 'channel_id', 'author', 'title', 'review', 'review_date', 'rating', 'top_rating', 'score', 'sentiment', 'language'];
$propertyReview = $this->reputationManagementService->select($propertyReviewCriteria, $column);
$propertyReview = $propertyReview['status'] == 'success' && !empty($propertyReview['data']) ? $propertyReview['data'] : [];
$propertyReviewList = [
'total' => $propertyReviewCount['data'],
'page' => $this->params['page'],
'count' => count($propertyReview),
'review' => $propertyReview
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyReviewList];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
public function getReviewStatistics(Request $request)
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
try {
$propertyReviewCriteria = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $this->params['property_id']],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel', 'channel', 'categoryMapping.category', 'keywordMapping'],
'orderBy' => [
['field' => 'review_date', 'value' => 'DESC']
],
];
if (isset($this->params['filter']) && !empty(isset($this->params['filter']))) {
if (isset($this->params['filter']['channel_id'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'channel_id', 'condition' => '=', 'value' => $this->params['filter']['channel_id']];
}
if (isset($this->params['filter']['start_date'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'review_date', 'condition' => '>', 'value' => $this->params['filter']['start_date']];
}
if (isset($this->params['filter']['end_date'])) {
$propertyReviewCriteria['criteria'][] = ['field' => 'review_date', 'condition' => '<=', 'value' => $this->params['filter']['end_date']];
}
}
//Just Last 1 Year
$propertyReviewCriteria['criteria'][] = ['field' => 'review_date', 'condition' => '>', 'value' => Carbon::now()->subYear()->toDateString()];
$column = ['id', 'property_id', 'channel_id', 'review_date', 'rating', 'top_rating', 'score', 'sentiment', 'language'];
$propertyReview = $this->reputationManagementService->select($propertyReviewCriteria, $column);
$propertyReview = $propertyReview['status'] == 'success' && !empty($propertyReview['data']) ? $propertyReview['data'] : [];
$propertyReviewStatistics['reviewScore'] = collect($propertyReview)->average('score');
$propertyReviewStatistics['reviewScore'] = (float)number_format($propertyReviewStatistics['reviewScore'], 2, '.', '');
$reviewSentimentGroup = collect($propertyReview)->groupBy('sentiment')->map->count();
$reviewSentimentGroup = $reviewSentimentGroup ? $reviewSentimentGroup->toArray() : null;
$reviewSentiment['positive'] = isset($reviewSentimentGroup[1]) ? $reviewSentimentGroup[1] : 0;
$reviewSentiment['negative'] = isset($reviewSentimentGroup[0]) ? $reviewSentimentGroup[0] : 0;
$propertyReviewStatistics['reviewScoreBySystem'] = null;
if (($reviewSentiment['positive'] + $reviewSentiment['negative']) > 0) {
$propertyReviewStatistics['reviewScoreBySystem'] = $reviewSentiment['positive'] / ($reviewSentiment['positive'] + $reviewSentiment['negative']) * 100;
$propertyReviewStatistics['reviewScoreBySystem'] = (float)number_format($propertyReviewStatistics['reviewScoreBySystem'], 2, '.', '');
}
//$reviewCategoryScoreBySystem
$reviewCategoryMapping = [];
$reviewCategoryScoreBySystem = [];
$reviewKeywordScoreBySystem = [];
foreach ($propertyReview as $review) {
foreach ($review['category_mapping'] as $reviewCategory) {
if (!isset($reviewCategoryScoreBySystem[$reviewCategory['category_id']])) {
$reviewCategoryScoreBySystem[$reviewCategory['category_id']][0] = 0;
$reviewCategoryScoreBySystem[$reviewCategory['category_id']][1] = 0;
}
$reviewCategoryScoreBySystem[$reviewCategory['category_id']][$reviewCategory['sentiment']]++;
$reviewCategoryMapping[$reviewCategory['category_id']]['name'] = $reviewCategory['category']['name'];
$reviewCategoryMapping[$reviewCategory['category_id']]['score'][$review['review_date']] = $review['score'];
if (!isset($reviewCategoryMapping[$reviewCategory['category_id']]['sentimentScore'][Carbon::parse($review['review_date'])->format('Y-m')])) {
$reviewCategoryMapping[$reviewCategory['category_id']]['sentimentScore'][Carbon::parse($review['review_date'])->format('Y-m')][0] = 0;
$reviewCategoryMapping[$reviewCategory['category_id']]['sentimentScore'][Carbon::parse($review['review_date'])->format('Y-m')][1] = 0;
}
$reviewCategoryMapping[$reviewCategory['category_id']]['sentimentScore'][Carbon::parse($review['review_date'])->format('Y-m')][$reviewCategory['sentiment']]++;
}
foreach ($review['keyword_mapping'] as $reviewKeyword) {
if (!isset($reviewKeywordScoreBySystem[md5($reviewKeyword['keyword'])])) {
$reviewKeywordScoreBySystem[md5($reviewKeyword['keyword'])]['positive'] = 0;
$reviewKeywordScoreBySystem[md5($reviewKeyword['keyword'])]['negative'] = 0;
$reviewKeywordScoreBySystem[md5($reviewKeyword['keyword'])]['keyword'] = $reviewKeyword['keyword'];
}
if ($reviewKeyword['sentiment'] == 1) {
$reviewKeywordScoreBySystem[md5($reviewKeyword['keyword'])]['positive']++;
} elseif ($reviewKeyword['sentiment'] == 0) {
$reviewKeywordScoreBySystem[md5($reviewKeyword['keyword'])]['negative']++;
}
}
}
$propertyReviewCategoryCriteria = [
'criteria' => [
['field' => 'status', 'condition' => '=', 'value' => 1],
]
];
$propertyReviewCategory = $this->reputationManagementService->selectCategory($propertyReviewCategoryCriteria);
$propertyReviewCategory = $propertyReviewCategory['status'] == 'success' ? $propertyReviewCategory['data'] : [];
$propertyReviewCategoryScore = [];
foreach ($propertyReviewCategory as $reviewCategory) {
if (empty($reviewCategoryScoreBySystem)) {
continue;
}
if (isset($reviewCategoryScoreBySystem[$reviewCategory['id']]) && array_sum($reviewCategoryScoreBySystem[$reviewCategory['id']]) < 5) {
continue;
}
$propertyReviewCategoryScore[$reviewCategory['id']] = [
'name' => $reviewCategory['name'],
'language_key' => $reviewCategory['language_key'],
];
$propertyReviewCategoryScore[$reviewCategory['id']]['score'] = null;
if (isset($reviewCategoryScoreBySystem[$reviewCategory['id']])) {
$propertyReviewCategoryScore[$reviewCategory['id']]['score'] = (float)number_format($reviewCategoryScoreBySystem[$reviewCategory['id']][1] / array_sum($reviewCategoryScoreBySystem[$reviewCategory['id']]) * 100, 2, '.', '');
$propertyReviewCategoryScore[$reviewCategory['id']]['positive'] = $reviewCategoryScoreBySystem[$reviewCategory['id']][1];
$propertyReviewCategoryScore[$reviewCategory['id']]['negative'] = $reviewCategoryScoreBySystem[$reviewCategory['id']][0];
$propertyReviewCategoryScore[$reviewCategory['id']]['total'] = array_sum($reviewCategoryScoreBySystem[$reviewCategory['id']]);
krsort($reviewCategoryMapping[$reviewCategory['id']]['score']);
$propertyReviewCategoryScore[$reviewCategory['id']]['scoreLastNumber'] = array_slice($reviewCategoryMapping[$reviewCategory['id']]['score'], 0, 10);
//Group By Month
/*$propertyReviewCategoryGroupScore = [];
foreach ($reviewCategoryMapping[$reviewCategory['id']]['score'] as $reviewDateTime => $reviewScore) {
$propertyReviewCategoryGroupScore[Carbon::parse($reviewDateTime)->format('m-Y')][] = $reviewScore;
}
$propertyReviewCategoryGroupScoreAverage = [];
foreach ($propertyReviewCategoryGroupScore as $reviewPeriod => $reviewPeriodScore) {
$propertyReviewCategoryGroupScoreAverage[$reviewPeriod] = round(collect($reviewPeriodScore)->avg());
}*/
//Group By Month
//Group By Month
ksort($reviewCategoryMapping[$reviewCategory['id']]['sentimentScore']);
$propertyReviewCategoryGroupScoreAverage = [];
foreach ($reviewCategoryMapping[$reviewCategory['id']]['sentimentScore'] as $reviewPeriod => $reviewPeriodScore) {
$categorySentimentScore = (float)number_format($reviewPeriodScore[1] / array_sum($reviewPeriodScore) * 100, 2, '.', '');
if ($categorySentimentScore <= 0) {
continue;
}
$propertyReviewCategoryGroupScoreAverage[$reviewPeriod] = round($categorySentimentScore);
}
//Group By Month
$propertyReviewCategoryScore[$reviewCategory['id']]['scoreMonthlyGroup'] = $propertyReviewCategoryGroupScoreAverage;
$propertyReviewCategoryScore[$reviewCategory['id']]['scoreMonthlyGroupAverage'] = (float)number_format(collect($propertyReviewCategoryGroupScoreAverage)->average(), 2, '.', '');
}
}
$propertyReviewStatistics['reviewCategoryScoreBySystem'] = array_values($propertyReviewCategoryScore);
//$reviewCategoryScoreBySystem
foreach ($reviewKeywordScoreBySystem as $reviewKeywordKey => $reviewKeyword) {
if (($reviewKeyword['positive'] + $reviewKeyword['negative']) < 3) {
unset($reviewKeywordScoreBySystem[$reviewKeywordKey]);
continue;
}
if (isset($reviewKeywordScoreBySystem[$reviewKeywordKey])) {
$reviewKeywordScoreBySystem[$reviewKeywordKey]['score'] = (float)number_format($reviewKeywordScoreBySystem[$reviewKeywordKey]['positive'] / array_sum($reviewKeywordScoreBySystem[$reviewKeywordKey]) * 100, 2, '.', '');
}
}
$propertyReviewStatistics['reviewKeywordScoreBySystem'] = array_values($reviewKeywordScoreBySystem);
//Dashboard Summary
$propertyReviewStatistics['dashboard'] = [];
$currentWeekStart = Carbon::now()->startOfWeek(Carbon::MONDAY)->toDateString();
$currentWeekFinish = Carbon::now()->addWeek()->startOfWeek(Carbon::MONDAY)->toDateString();
//TOTAL
$totalReview = count($propertyReview);
$extraReviewCount = collect($propertyReview)->where('review_date', '>', $currentWeekStart)->count();
$propertyReviewStatistics['dashboard'] ['total'] = [
'count' => $totalReview,
'extraReviewCount' => $extraReviewCount
];
//POSITIVE
$totalReviewPositive = collect($propertyReview)->where('sentiment', 1)->count();
$extraPositiveReviewCount = collect($propertyReview)->where('review_date', '>', $currentWeekStart)->where('sentiment', 1)->count();
$propertyReviewStatistics['dashboard'] ['positive'] = [
'count' => $totalReviewPositive,
'extraReviewCount' => $extraPositiveReviewCount
];
//NEGATIVE
$totalReviewNegative = collect($propertyReview)->where('sentiment', '!=', 1)->count();
$extraNegativeReviewCount = collect($propertyReview)->where('review_date', '>', $currentWeekStart)->where('sentiment', '!=', 1)->count();
$propertyReviewStatistics['dashboard'] ['negative'] = [
'count' => $totalReviewNegative,
'extraReviewCount' => $extraNegativeReviewCount
];
//BEST
$bestReview = collect($propertyReviewCategoryScore)->sortByDesc('positive')->first();
$propertyReviewStatistics['dashboard'] ['best'] = [
'name' => $bestReview['name'],
'language_key' => $bestReview['language_key'],
'score' => $bestReview['score'],
'positive' => $bestReview['positive'],
'negative' => $bestReview['negative'],
'total' => $bestReview['total'],
];
$response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyReviewStatistics];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Http\Controllers\V1;
use App\Http\Controllers\Controller;
use App\Core\Service\TempPropertyService;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
class TempPropertyController extends Controller
{
private $request;
private $tempPropertyService;
public function __construct(
Request $request,
TempPropertyService $tempPropertyService
)
{
$this->request = $request;
$this->tempPropertyService = $tempPropertyService ;
}
public function getTempPropertyList()
{
$response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400 ];
try {
if (is_null($this->request->getContent())) {
throw new Exception(lang('Parameter Error.')) ;
}
$tempPropertyListCriteria = $this->request->getContent();
$tempPropertyListCriteria = json_decode($tempPropertyListCriteria,1);
$tempPropertyListCriteria = $tempPropertyListCriteria['params'];
$temPropertyList = $this->tempPropertyService->search($tempPropertyListCriteria, fillOnUndefined($tempPropertyListCriteria, 'select', ['*']));
if ($temPropertyList['status'] != 'success') {
throw new Exception($temPropertyList['message']);
}
$response = ['status' => 1, 'statusCode' => 200, 'message' => null,'data' => $temPropertyList['data'] ];
} catch (ApiErrorException $e) {
$response['message'] = implode(', ', $e->getMessageArr());
$response['statusCode'] = 400;
} catch (Exception $e) {
$message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
Log::error($message);
$response['message'] = $e->getMessage();
$response['statusCode'] = 500;
}
return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);;
}
}

View File

@@ -0,0 +1,364 @@
<?php
namespace App\Http\Controllers;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class bulutController extends Controller
{
private function client()
{
return new Client(array(
'timeout' => 15,
'headers' => array(
'x-rapidapi-host' => env('BULUT_RAPIDAPI_HOST'),
'x-rapidapi-key' => env('BULUT_RAPIDAPI_KEY'),
),
));
}
/**
* ADIM 1: Otel adına göre ara → hotel_id al
* GET /bulut/search?name=Grand Yavuz Hotel Istanbul
*/
public function search(Request $request)
{
$name = $request->query('name', '');
if (!$name) {
return response()->json(array('status' => false, 'message' => 'name parametresi gerekli'), 422);
}
try {
$response = $this->client()->get(
'https://' . env('BULUT_RAPIDAPI_HOST') . '/locations/auto-complete',
array('query' => array('text' => $name, 'languagecode' => 'en-us'))
);
$data = json_decode($response->getBody()->getContents(), true);
return response()->json(array('status' => true, 'raw' => $data));
} catch (Exception $e) {
Log::error('search error: ' . $e->getMessage());
return response()->json(array('status' => false, 'message' => $e->getMessage()), 500);
}
}
/**
* ADIM 2: Otel detayları
* GET /bulut/hotel-data?hotel_id=1234567&checkin=2026-06-01&checkout=2026-06-02
*/
public function hotelData(Request $request)
{
$hotelId = $request->query('hotel_id');
$checkin = $request->query('checkin');
$checkout = $request->query('checkout');
if (!$hotelId) {
return response()->json(array('status' => false, 'message' => 'hotel_id gerekli'), 422);
}
try {
$response = $this->client()->get(
'https://' . env('BULUT_RAPIDAPI_HOST') . '/properties/detail',
array('query' => array(
'hotel_id' => $hotelId,
'arrival_date' => $checkin,
'departure_date' => $checkout,
'languagecode' => 'en-us',
'currency_code' => 'USD',
))
);
$data = json_decode($response->getBody()->getContents(), true);
return response()->json(array('status' => true, 'data' => $data));
} catch (Exception $e) {
Log::error('hotelData error: ' . $e->getMessage());
return response()->json(array('status' => false, 'message' => $e->getMessage()), 500);
}
}
public function hotelPhotos(Request $request)
{
$hotelIds = $request->query('hotel_ids');
$hotelName = $request->query('hotel_name', 'hotel');
$propertyId = $request->query('property_id', $hotelIds);
if (!$hotelIds) {
return response()->json(array(
'status' => false,
'message' => 'hotel_ids gerekli'
), 422);
}
try {
$response = $this->client()->get(
'https://' . env('BULUT_RAPIDAPI_HOST') . '/properties/get-hotel-photos',
array(
'query' => array(
'hotel_ids' => $hotelIds,
'languagecode' => 'en-us',
)
)
);
$data = json_decode($response->getBody()->getContents(), true);
$savedImages = $this->saveHotelPhotosFromResponse($data, $hotelName, $propertyId);
Log::info('BULUT RAW RESPONSE KEYS', array(
'main_keys' => array_keys($data),
'data_keys' => isset($data['data']) && is_array($data['data']) ? array_keys($data['data']) : array(),
));
return response()->json(array(
'status' => true,
'message' => 'Otel görselleri başarıyla indirildi ve gruplandı.',
'debug' => array(
'main_keys' => array_keys($data),
'data_keys' => isset($data['data']) && is_array($data['data']) ? array_keys($data['data']) : array(),
'data_data_keys' => isset($data['data']['data']) && is_array($data['data']['data']) ? array_keys($data['data']['data']) : array(),
),
'saved_images' => $savedImages
));
} catch (Exception $e) {
Log::error('hotelPhotos error: ' . $e->getMessage());
return response()->json(array(
'status' => false,
'message' => $e->getMessage()
), 500);
}
}
private function saveHotelPhotosFromResponse(array $responseData, string $hotelName, $propertyId)
{
$result = array();
$urlPrefix = 'https://cf.bstatic.com';
if (isset($responseData['url_prefix'])) {
$urlPrefix = $responseData['url_prefix'];
}
if (isset($responseData['data']['url_prefix'])) {
$urlPrefix = $responseData['data']['url_prefix'];
}
$hotels = $this->extractHotelsFromPhotoResponse($responseData);
Log::info('BULUT PHOTO HOTELS EXTRACTED', array(
'hotel_count' => count($hotels),
'hotel_keys' => array_keys($hotels),
'url_prefix' => $urlPrefix
));
$uploadRootPath = rtrim(Config::get('app.fileSystemDriver'), '/');
$propertyBasePath = $uploadRootPath . '/property-photos/' . $propertyId;
if (!File::exists($propertyBasePath)) {
File::makeDirectory($propertyBasePath, 0777, true);
}
foreach ($hotels as $hotelId => $photos) {
$hotelFolderName = Str::slug($hotelName) . '-' . $hotelId;
$basePath = $propertyBasePath . '/bulut/' . $hotelFolderName;
if (!File::exists($basePath)) {
File::makeDirectory($basePath, 0777, true);
}
$result[$hotelId] = array(
'hotel_name' => $hotelName,
'property_id' => $propertyId,
'folder' => '/property-photos/' . $propertyId . '/bulut/' . $hotelFolderName,
'physical_path' => $basePath,
'groups' => array()
);
foreach ($photos as $photo) {
$photoId = isset($photo[2]) ? $photo[2] : uniqid();
$tags = isset($photo[3]) ? $photo[3] : array();
$imagePath = isset($photo[4]) ? $photo[4] : null;
if (!$imagePath) {
continue;
}
$groupName = $this->detectPhotoGroup($tags);
$groupPath = $basePath . '/' . $groupName;
if (!File::exists($groupPath)) {
File::makeDirectory($groupPath, 0777, true);
}
$imageUrl = $urlPrefix . $imagePath;
$fileName = $photoId . '.jpg';
$savePath = $groupPath . '/' . $fileName;
try {
$this->downloadImage($imageUrl, $savePath);
$relativePath = '/property-photos/' . $propertyId . '/bulut/' . $hotelFolderName . '/' . $groupName . '/' . $fileName;
if (!isset($result[$hotelId]['groups'][$groupName])) {
$result[$hotelId]['groups'][$groupName] = array();
}
$result[$hotelId]['groups'][$groupName][] = array(
'photo_id' => $photoId,
'file_name' => $fileName,
'photo_path' => '/property-photos/' . $propertyId . '/bulut/' . $hotelFolderName . '/' . $groupName . '/',
'relative_path' => $relativePath,
'physical_path' => $savePath,
'source_url' => $imageUrl,
'tags' => $tags
);
} catch (Exception $e) {
Log::error('BULUT IMAGE DOWNLOAD ERROR: ' . $e->getMessage(), array(
'image_url' => $imageUrl,
'save_path' => $savePath
));
}
}
}
return $result;
}
private function detectPhotoGroup(array $tags)
{
$tagNames = array();
foreach ($tags as $tag) {
if (isset($tag['tag'])) {
$tagNames[] = strtolower($tag['tag']);
}
}
$tagText = implode(' ', $tagNames);
if (
strpos($tagText, 'room') !== false ||
strpos($tagText, 'bedroom') !== false ||
strpos($tagText, 'bed') !== false ||
strpos($tagText, 'living room') !== false
) {
return 'rooms';
}
if (
strpos($tagText, 'bathroom') !== false ||
strpos($tagText, 'shower') !== false ||
strpos($tagText, 'toilet') !== false
) {
return 'bathroom';
}
if (
strpos($tagText, 'breakfast') !== false ||
strpos($tagText, 'buffet') !== false
) {
return 'breakfast';
}
if (
strpos($tagText, 'restaurant') !== false ||
strpos($tagText, 'food') !== false ||
strpos($tagText, 'drinks') !== false ||
strpos($tagText, 'lunch') !== false ||
strpos($tagText, 'dinner') !== false
) {
return 'restaurant';
}
if (
strpos($tagText, 'lobby') !== false ||
strpos($tagText, 'reception') !== false ||
strpos($tagText, 'lounge') !== false ||
strpos($tagText, 'seating area') !== false
) {
return 'lobby';
}
if (
strpos($tagText, 'spa') !== false ||
strpos($tagText, 'wellness') !== false ||
strpos($tagText, 'public bath') !== false
) {
return 'spa';
}
if (
strpos($tagText, 'balcony') !== false ||
strpos($tagText, 'terrace') !== false ||
strpos($tagText, 'garden') !== false ||
strpos($tagText, 'sea view') !== false ||
strpos($tagText, 'city view') !== false
) {
return 'view-and-outdoor';
}
if (
strpos($tagText, 'property building') !== false ||
strpos($tagText, 'property') !== false
) {
return 'property';
}
return 'other';
}
private function downloadImage(string $imageUrl, string $savePath)
{
$client = new Client(array(
'timeout' => 30,
'verify' => false,
'headers' => array(
'User-Agent' => 'Mozilla/5.0'
)
));
$response = $client->get($imageUrl);
if ($response->getStatusCode() !== 200) {
throw new Exception('Image download failed: ' . $imageUrl);
}
File::put($savePath, $response->getBody()->getContents());
return true;
}
private function extractHotelsFromPhotoResponse(array $responseData)
{
if (isset($responseData['data']) && is_array($responseData['data'])) {
foreach ($responseData['data'] as $key => $value) {
if (is_numeric($key) && is_array($value)) {
return $responseData['data'];
}
}
}
if (isset($responseData['data']['data']) && is_array($responseData['data']['data'])) {
return $responseData['data']['data'];
}
if (isset($responseData['data']['data']['data']) && is_array($responseData['data']['data']['data'])) {
return $responseData['data']['data']['data'];
}
return array();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Authenticate
{
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace App\Http\Middleware;
use App\Core\Service\FindCountryCodeService;
use App\Core\Service\PropertyBookingEngineService;
use App\Core\Service\PropertyChannelMappingService;
use App\Core\Service\PropertyChannelService;
use App\Core\Service\PropertyWebService;
use App\Exceptions\ApiErrorException;
use Closure;
use Exception;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class BookingEngineTokenMiddleware
{
private $propertyWebService;
public function __construct(
PropertyWebService $propertyWebService,
PropertyChannelService $channelService,
PropertyChannelMappingService $propertyChannelMappingService,
PropertyBookingEngineService $propertyBookingEngineService,
FindCountryCodeService $findCountryCodeService
)
{
$this->propertyWebService = $propertyWebService;
$this->channelService = $channelService;
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->propertyBookingEngineService = $propertyBookingEngineService;
$this->findCountryCodeService = $findCountryCodeService;
}
public function handle($request, Closure $next, $guard = null)
{
$channelToken = $request->header('channelToken');
$bookingEngineToken = $request->header('bookingEngineToken');
if (!$channelToken) {
return apiResponse(0, 'Token not provided.', null, 401);
}
$channelRequest = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => $channelToken],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$channelCheck = $this->channelService->select($channelRequest);
if ($channelCheck['status'] != 'success' || empty($channelCheck['data'])) {
return apiResponse(0, 'Channel Token not found.', null, 401);
}
$bookingEnginePropertyId = null;
if (in_array($channelCheck['data']['channel_category_id'], [2, 3, 7])) {
if (is_null($bookingEngineToken)) {
if (!in_array($channelCheck['data']['channel_category_id'], [7])) {
return apiResponse(0, 'Booking Engine Token not found.', null, 401);
}
}
$bookingEngineRequest = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => $bookingEngineToken],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'firstRow' => 1
];
$bookingEngineCheck = $this->propertyBookingEngineService->select($bookingEngineRequest);
if ($bookingEngineCheck['status'] != 'success' || empty($bookingEngineCheck['data'])) {
if (!in_array($channelCheck['data']['channel_category_id'], [7])) {
return apiResponse(0, 'Booking Engine Token not found.', null, 401);
}
}
$bookingEnginePropertyId = isset($bookingEngineCheck['data']['property_id']) ? $bookingEngineCheck['data']['property_id'] : null;
//channelToken Manipulation
$params = json_decode($request->getContent(), 1);
if (fillOnUndefined($params, 'ipAddress') && fillOnUndefined($params,'referrer') != 'google') {
// Find Country Code with IP
$ipResponse = $this->findCountryCodeService->findCountryWithIpAddress($params['ipAddress']);
if ($ipResponse['status'] == 'success') {
$propertyChannelMappingParam = [
'criteria' => [
['field' => 'property_id', 'condition' => '=', 'value' => $bookingEnginePropertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['channel'],
];
$propertyChannelMapping = $this->propertyChannelMappingService->select($propertyChannelMappingParam);
$ipCountryCode = isset($ipResponse['data']['code']) ? $ipResponse['data']['code'] : 'tr';
if ($propertyChannelMapping['status'] == 'success') {
$propertyChannelMappingCollect = collect($propertyChannelMapping['data']);
$countryChannel = $propertyChannelMappingCollect
->where('channel.channel_category_id', 3)
->where('channel.country_code', $ipCountryCode)
->where('channel.parent_id', 1)
->first();
if (!empty($countryChannel)) {
$channelToken = $countryChannel['channel']['token'];
$channelCheck['data']['id'] = $countryChannel['channel']['id'];
}
//countryCodeGroup
if (empty($countryChannel)) {
$countryChannelGroup = $propertyChannelMappingCollect
->where('channel.channel_category_id', 3)
->where('channel.country_code', 'group')
->where('channel.parent_id', 1)
->toArray();
if (!empty($countryChannelGroup)) {
foreach ($countryChannelGroup as $country) {
if (!empty($country['channel']['country_code_group'])) {
if (in_array($ipCountryCode, $country['channel']['countryCodeGroupArray'])) {
$channelToken = $country['channel']['token'];
$channelCheck['data']['id'] = $country['channel']['id'];
break;
}
}
}
}
}
//countryCodeGroup
}
}
//channelToken Manipulation
}
}
$request->channelId = $channelCheck['data']['id'];
$request->channelToken = $channelToken;
$request->bookingEngineToken = $bookingEngineToken;
$request->bookingEnginePropertyId = $bookingEnginePropertyId;
$request->bookingEngineChannelCategoryId = $channelCheck['data']['channel_category_id'];
return $next($request);
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace App\Http\Middleware;
use App\Core\Service\PropertyChannelMappingService;
use Closure;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class CheckPropertyChannelConnectionMiddleware
{
private $propertyChannelMappingService;
private $request;
private $response;
public function __construct(
Request $request,
Response $response,
PropertyChannelMappingService $propertyChannelMappingService
)
{
$this->propertyChannelMappingService = $propertyChannelMappingService;
$this->request = $request;
$this->response = $response;
}
public function handle($request, Closure $next, $guard = null)
{
//TODO: Buraya kanal (channel_id) ve kanal grupları (channel_group_id) için property için bir kontrol koyulacak
//dd($this->request->params['property_id']);
/*$response = $next($request);
$propertyId = $request->property_id ? $request->property_id : fillOnUndefined($request->params, 'property_id');
$channelId = fillOnUndefined($request->params, 'channel_id');
$checkParams = [
'property_id' => $propertyId,
'channel_id' => $channelId,
] ;
$checkMappingStatus =$this->propertyChannelMappingService->checkPropertyChannelMapping($checkParams);
if ($checkMappingStatus['status'] != 'success') {
return apiResponse(false, $checkMappingStatus['message'], null, 400);
}
return $response;*/
return $next($request);
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Http\Middleware;
use App\Core\Service\PropertyConfigService;
use Closure;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class ContentWizardMiddleware
{
private $propertyConfigService;
private $request;
private $response;
public function __construct(
Request $request,
Response $response,
PropertyConfigService $propertyConfigService
)
{
$this->propertyConfigService = $propertyConfigService;
$this->request = $request;
$this->response = $response;
}
public function handle($request, Closure $next, $guard = null)
{
$response = $next($request);
if ($response->getData()->status == 200) {
$params = $this->request->params;
$url = collect($this->request->route());
$getNameArray = $url->where('as', '!=', null)->first();
$routeAlias = fillOnUndefined($getNameArray, 'as');
if($routeAlias == 'Property.Contact.Update'){
if(isset($params['contact']['address']) && isset($params['contact']['latitude']) && isset($params['contact']['longitude'])){
$routeAlias = 'Property.Location.Update' ;
}
}
$rateParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $this->request->credentials->user_id,
'property_rate_for' => $routeAlias,
];
$this->propertyConfigService->rateProperty(array_merge($params, $rateParams));
}
return $response;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Exception ;
class CorsMiddleware
{
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, language, authToken'
];
$apiHeader = collect($request->headers)->toArray();
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
//$response->header($key, $value);
$response->headers->set($key, $value);
}
return $response;
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Closure;
class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace App\Http\Middleware;
use App\Core\Service\ApiAccessTokenService;
use App\Exceptions\ApiErrorException ;
use Closure;
use Exception;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Illuminate\Support\Facades\Config;
class JwtMiddleware
{
private $apiAccessTokenService;
public function __construct(
ApiAccessTokenService $apiAccessTokenService
)
{
$this->apiAccessTokenService = $apiAccessTokenService ;
}
public function handle($request, Closure $next, $guard = null)
{
$token = $request->header('authToken');
if (!$token) {
return apiResponse(0, 'Token not provided.', null, 401);
}
try {
$credentials = JWT::decode($token, Config::get('app.jwt.secret'), ['HS256']);
$findTokenCriteria = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => md5($token) ],
['field' => 'expire_date', 'condition' => '>', 'value' => time() ],
['field' => 'user_id', 'condition' => '=', 'value' => $credentials->user_id ],
['field' => 'invalidate', 'condition' => '=', 'value' => 0 ],
],
'firstRow' => 1
];
$getTokenData = $this->apiAccessTokenService->select($findTokenCriteria);
if(!$getTokenData['data']){
throw new ExpiredException();
}
} catch (ExpiredException $e) {
return apiResponse(0, lang('Token is expired.'), null, 401);
} catch (Exception $e) {
return apiResponse(0, lang('An error while decoding token.'), null, 500);
}
$inputs = json_decode($request->getContent(), true);
$inputs = is_array($inputs) ? $inputs : ["params" => []];
$user = User::find($credentials->user_id);
// Now let's put the user in the request class so that you can grab it from there
$request->credentials = $credentials;
$request->body = $inputs;
$request->auth = $user;
return $next($request);
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Http\Middleware;
use Closure;
use App\Core\Helper\LanguageService;
use Exception;
class LanguageSettingMiddleware
{
public function handle($request, Closure $next)
{
$apiHeader = collect($request->headers)->toArray();
if(!isset($apiHeader['language'])){
return apiResponse(0, 'Language field is null.', null, 400);
}
$apiRequest = collect($request->params)->toArray();
$apiRequest['locale'] = isset($apiRequest['locale']) ? $apiRequest['locale'] : reset($apiHeader['language']);
LanguageService::setCurrentLanguage(reset($apiHeader['language']));
$request->params = $apiRequest;
app('translator')->setLocale(reset($apiHeader['language']));
return $next($request);
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Http\Middleware;
use App\Core\Service\PropertyWebService;
use App\Exceptions\ApiErrorException ;
use Closure;
use Exception;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Illuminate\Support\Facades\Config;
class MyWebTokenMiddleware
{
private $propertyWebService;
public function __construct(
PropertyWebService $propertyWebService
)
{
$this->propertyWebService = $propertyWebService ;
}
public function handle($request, Closure $next, $guard = null)
{
$token = $request->header('authToken');
if (!$token) {
return apiResponse(0, 'Token not provided.', null, 401);
}
try {
$findTokenCriteria = [
'criteria' => [
['field' => 'token', 'condition' => '=', 'value' => $token],
],
'firstRow' => 1
];
$getTokenData = $this->propertyWebService->select($findTokenCriteria);
if(!$getTokenData['data']){
throw new ExpiredException();
}
} catch (ExpiredException $e) {
return apiResponse(0, lang('Token is expired.'), null, 400);
} catch (Exception $e) {
return apiResponse(0, lang('An error while decoding token.'), null, 500);
}
$inputs = json_decode($request->getContent(), true);
$inputs = is_array($inputs) ? $inputs : ["params" => []];
$inputs['params']['property_id'] = $getTokenData['data']['property_id'];
$inputs['params']['property_web_id'] = $getTokenData['data']['id'];
$inputs['params']['domain'] = $getTokenData['data']['domain'];
$inputs['params']['default_language'] = $getTokenData['data']['default_language'];
$inputs['params']['template_id'] = $getTokenData['data']['template_id'];
$request->body = $inputs;
return $next($request);
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace App\Http\Middleware;
use App\Core\Service\ServiceLogService;
use Closure;
use Exception;
use App\Models\User;
use App\Core\Repository\UserPropertyMapping\UserPropertyMappingRepository;
use Illuminate\Support\Facades\Route;
class PropertyMiddleware
{
private $userPropertyMappingRepository;
public function __construct(
UserPropertyMappingRepository $userPropertyMappingRepository,
ServiceLogService $serviceLogService
)
{
$this->userPropertyMappingRepository = $userPropertyMappingRepository;
$this->serviceLogService = $serviceLogService;
}
public function handle($request, Closure $next, $guard = null)
{
$userId = $request->credentials->user_id;
$propertyId = $request->property_id ? $request->property_id : fillOnUndefined($request->params, 'property_id');
if (!$propertyId) {
return apiResponse(0, 'Property_id required.', null, 401);
}
$checkPropertyUserRequest = [
'criteria' => [
['field' => 'user_id', 'condition' => '=', 'value' => $userId],
['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
['field' => 'status', 'condition' => '=', 'value' => 1],
],
'with' => ['property'],
'firstRow' => 1
];
$checkPropertyUser = $this->userPropertyMappingRepository->findByCriteria($checkPropertyUserRequest);
if (!$checkPropertyUser) {
return apiResponse(0, 'User not matched this property.', null, 400);
}
if (!$checkPropertyUser['property']['status']) {
return apiResponse(0, 'User not matched this property.', null, 400);
}
/** ServiceLog **/
$request->serviceLogId = null;
$request->serviceLogRequestTime = microtime(true);
$selectedRoute = [
//'Property.Dashboard',
'Property.RoomRateMapping.RoomRateAvailabilityUpdate',
'Property.RoomRateMapping.BulkUpdate',
'RoomRateChannelPromotion.Update',
'Property.Promotion.Update',
'PA.Property.Quick-Pricing.Sync'
];
$route = $request->route();
$routeName = isset($route[1]['as']) ? $route[1]['as'] : null;
$inputs = json_decode($request->getContent(), true);
if (in_array($routeName, $selectedRoute)) {
$serviceLogParam = [
'property_id' => $propertyId,
'user_id' => $userId,
'service' => $routeName,
'request' => json_encode($inputs),
'ip_address' => $request->ip(),
'status' => 2
];
$serviceLog = $this->serviceLogService->create($serviceLogParam);
if($serviceLog['status'] == 'success' && !empty($serviceLog['data'])) {
$request->serviceLogId = $serviceLog['data']['id'];
}
}
/** ServiceLog **/
return $next($request);
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Http\Middleware;
use App\Core\Permission\RoutePermissionAuthorize;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class UserRoutePermissionAuthorize
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
private $routePermissionAuthorize;
public function __construct ( RoutePermissionAuthorize $routePermissionAuthorize )
{
$this->routePermissionAuthorize =$routePermissionAuthorize;
}
public function handle($request, Closure $next, $guard = null)
{
$params = $request->params;
$requestParams = [
'property_id' => fillOnUndefined($params, 'property_id'),
'user_id' => $request->credentials->user_id,
];
$result = $this->routePermissionAuthorize->isUserAuthorizedForCurrentRoute($requestParams);
if ( !$result)
{
return apiResponse(0, "Your permission not authorised" , null, 400);
}
return $next($request);
}
}