diff --git a/classes/Cart.php b/classes/Cart.php index 96fe2c68c..334292af4 100644 --- a/classes/Cart.php +++ b/classes/Cart.php @@ -3932,6 +3932,38 @@ class CartCore extends ObjectModel } } + $totalRoomsCount = 0; + if ($htlCartData = HotelCartBookingData::getHotelCartBookingData(0)) { + foreach ($htlCartData as $roomTypeCart) { + $totalRoomsCount += $roomTypeCart['total_num_rooms']; + } + } + $nbTotalProducts = 0; + $objServiceProductCartDetail = new ServiceProductCartDetail(); + foreach ($products as &$product) { + if (!$product['booking_product']) { + if (Product::SELLING_PREFERENCE_STANDALONE == $product['selling_preference_type']) { + $nbTotalProducts += (int) $product['cart_quantity']; + } elseif (Product::SELLING_PREFERENCE_HOTEL_STANDALONE == $product['selling_preference_type'] + || Product::SELLING_PREFERENCE_HOTEL_STANDALONE_AND_WITH_ROOM_TYPE == $product['selling_preference_type'] + ) { + if ($serviceProducts = $objServiceProductCartDetail->getServiceProductsInCart( + $this->id, + [Product::SELLING_PREFERENCE_HOTEL_STANDALONE, Product::SELLING_PREFERENCE_HOTEL_STANDALONE_AND_WITH_ROOM_TYPE], + null, + 0, + null, + $product['id_product'] + )) { + foreach ($serviceProducts as $serviceProduct) { + if ($serviceProduct['id_hotel'] && $serviceProduct['id_product'] == $product['id_product']) { + $nbTotalProducts += (int) $serviceProduct['quantity']; + } + } + } + } + } + } $objHotelAdvancedPayment = new HotelAdvancedPayment(); $total_rooms_with_services_without_discount_te = $total_rooms + $total_demands + $total_additional_services + $total_additional_services_auto_add + $total_standalone_service_products; $total_rooms_with_services_without_discount_ti = $total_rooms_wt + $total_demands_wt + $total_additional_services_wt + $total_additional_services_auto_add_wt + $total_standalone_service_products_wt; @@ -3988,7 +4020,8 @@ class CartCore extends ObjectModel 'total_rooms_with_services_without_discount_ti' => $total_rooms_with_services_without_discount_ti, 'cart_total_without_discount_te' => $cart_total_without_discount_te, 'cart_total_without_discount_ti' => $cart_total_without_discount_ti, - 'total_tax_without_discount' => $total_tax_without_discount + 'total_tax_without_discount' => $total_tax_without_discount, + 'total_products_in_cart' => $totalRoomsCount + $nbTotalProducts, ); $hook = Hook::exec('actionCartSummary', $summary, null, true); if (is_array($hook)) { diff --git a/controllers/front/CartController.php b/controllers/front/CartController.php index 76f2e5982..f646f1be3 100644 --- a/controllers/front/CartController.php +++ b/controllers/front/CartController.php @@ -155,8 +155,8 @@ class CartControllerCore extends FrontController $result = $this->context->cart->deleteProduct($this->id_product, $this->id_product_attribute, $this->customization_id, $this->id_address_delivery); // now get updated available rooms - $date_from = Tools::getValue('dateFrom'); - $date_to = Tools::getValue('dateTo'); + $date_from = Tools::getValue('date_from'); + $date_to = Tools::getValue('date_to'); $date_from = date("Y-m-d H:i:s", strtotime($date_from)); $date_to = date("Y-m-d H:i:s", strtotime($date_to)); $objRoomType = new HotelRoomType(); @@ -315,7 +315,7 @@ class CartControllerCore extends FrontController } if ($occupancyRequiredForBooking && $operator == 'up') { - if ($occupancy = json_decode(Tools::getValue('occupancy'), true)) { + if ($occupancy = Tools::getValue('occupancy')) { $this->qty = count($occupancy); } else { $this->errors[] = Tools::displayError('Invalid occupnacy.'); @@ -337,11 +337,21 @@ class CartControllerCore extends FrontController if (!$this->errors) { $objRoomType = new HotelRoomType(); if ($roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($this->id_product)) { - $date_from = Tools::getValue('dateFrom'); - $date_to = Tools::getValue('dateTo'); + $date_from = Tools::getValue('date_from'); + $date_to = Tools::getValue('date_to'); $date_from = date("Y-m-d H:i:s", strtotime($date_from)); $date_to = date("Y-m-d H:i:s", strtotime($date_to)); - $serviceProducts = json_decode(Tools::getValue('serviceProducts'),true); + + $rawServiceProducts = Tools::getValue('service_product'); + $serviceProducts = []; + if (is_array($rawServiceProducts) && !empty($rawServiceProducts)) { + foreach ($rawServiceProducts as $id_product => $data) { + $serviceProducts[] = [ + 'id_product' => (int) $id_product, + 'quantity' => isset($data['quantity']) ? (int) $data['quantity'] : 1, + ]; + } + } // valdiate occupancy if providede if ($operator == 'up' && $occupancyRequiredForBooking) { @@ -419,7 +429,11 @@ class CartControllerCore extends FrontController $total_available_rooms = $hotelRoomData['stats']['num_avail']; if (Tools::getValue('op', 'up') == 'up') { if ($total_available_rooms < $req_rm) { - die(json_encode(array('status' => 'unavailable_quantity', 'avail_rooms' => $total_available_rooms))); + if (Tools::getValue('ajax')) { + die(json_encode(array('status' => 'unavailable_quantity', 'avail_rooms' => $total_available_rooms))); + } else { + $this->errors[] = Tools::displayError('All rooms are sold out for the selected dates. Please try with different dates.'); + } } else { // validate service products if available if ($serviceProducts) { @@ -450,10 +464,18 @@ class CartControllerCore extends FrontController } } } else { - die(json_encode(array('status' => 'failed3'))); + if (Tools::getValue('ajax')) { + die(json_encode(array('status' => 'failed3'))); + } else { + $this->errors[] = Tools::displayError('An error occurred while processing your request.'); + } } } else { - die(json_encode(array('status' => 'failed4'))); + if (Tools::getValue('ajax')) { + die(json_encode(array('status' => 'failed4'))); + } else { + $this->errors[] = Tools::displayError('An error occurred while processing your request.'); + } } } } else { @@ -607,7 +629,7 @@ class CartControllerCore extends FrontController */ if ($product->booking_product) { $objHotelCartBookingData = new HotelCartBookingData(); - $roomDemand = json_decode(Tools::getValue('roomDemands'), true); + $roomDemand = json_decode(Tools::getValue('room_demands'), true); $roomDemand = json_encode($roomDemand); $availQty = $total_available_rooms; $update_quantity = $objHotelCartBookingData->updateCartBooking( diff --git a/controllers/front/CategoryController.php b/controllers/front/CategoryController.php index 6abb5d336..7be5770b7 100644 --- a/controllers/front/CategoryController.php +++ b/controllers/front/CategoryController.php @@ -59,6 +59,7 @@ class CategoryControllerCore extends FrontController $this->addCSS(_THEME_CSS_DIR_.'occupancy.css'); $this->addJS(_THEME_JS_DIR_.'occupancy.js'); + $this->addJS(_THEME_JS_DIR_.'room-type-service-products.js'); $scenes = Scene::getScenes($this->category->id, $this->context->language->id, true, false); if ($scenes && count($scenes)) { $this->addJS(_THEME_JS_DIR_.'scenes.js'); diff --git a/controllers/front/ContactController.php b/controllers/front/ContactController.php index acb21798d..4faa76dea 100644 --- a/controllers/front/ContactController.php +++ b/controllers/front/ContactController.php @@ -311,7 +311,7 @@ class ContactControllerCore extends FrontController ) ) { // by webkul to get media link. - $htlImgLink = $this->context->link->getMediaLink($objHotelImage->getImageLink($hotel['id_cover_img'], ImageType::getFormatedName('medium'))); + $htlImgLink = $this->context->link->getMediaLink($objHotelImage->getImageLink($hotel['id_cover_img'], ImageType::getFormatedName('large'))); if ((bool)Tools::file_get_contents($htlImgLink)) { $hotel['image_url'] = $htlImgLink; @@ -330,7 +330,6 @@ class ContactControllerCore extends FrontController $this->context->smarty->assign( array( 'hotelsInfo' => $hotelsInfo, - 'viewOnMap' => Configuration::get('WK_GOOGLE_ACTIVE_MAP'), 'displayHotels' => Configuration::get('WK_DISPLAY_CONTACT_PAGE_HOTEL_LIST'), 'gblHtlPhone' => $gblHtlPhone, 'gblHtlEmail' => $gblHtlEmail, diff --git a/controllers/front/GuestTrackingController.php b/controllers/front/GuestTrackingController.php index c685eb430..26b5ede23 100644 --- a/controllers/front/GuestTrackingController.php +++ b/controllers/front/GuestTrackingController.php @@ -110,6 +110,12 @@ class GuestTrackingControllerCore extends FrontController { $response = array('extra_demands' => false); + $order = new Order((int) Tools::getValue('id_order')); + + if (!Validate::isLoadedObject($order) || $order->secure_key != Tools::getValue('secure_key')) { + $this->ajaxDie(json_encode($response)); + } + if (($idProduct = Tools::getValue('id_product')) && ($idOrder = Tools::getValue('id_order')) && ($dateFrom = Tools::getValue('date_from')) diff --git a/controllers/front/OurPropertiesController.php b/controllers/front/OurPropertiesController.php index 06520f044..3df472859 100644 --- a/controllers/front/OurPropertiesController.php +++ b/controllers/front/OurPropertiesController.php @@ -49,7 +49,7 @@ class OurPropertiesControllerCore extends FrontController && $hotel['id_cover_img'] && Validate::isLoadedObject($objHotelImage = new HotelImage($hotel['id_cover_img'])) ) { - $htlImgLink = $this->context->link->getMediaLink($objHotelImage->getImageLink($hotel['id_cover_img'], ImageType::getFormatedName('medium'))); + $htlImgLink = $this->context->link->getMediaLink($objHotelImage->getImageLink($hotel['id_cover_img'], ImageType::getFormatedName('large'))); if ((bool)Tools::file_get_contents($htlImgLink)) { $hotelsInfo[$hotelKey]['image_url'] = $htlImgLink; } else { @@ -128,7 +128,6 @@ class OurPropertiesControllerCore extends FrontController array( 'hotelsInfo' => $hotelsInfo, 'hotelLocationArray' => $hotelLocationArray, - 'viewOnMap' => Configuration::get('WK_GOOGLE_ACTIVE_MAP'), 'displayHotelMap' => $displayHotelMap, 'WK_HTL_SHORT_DESC' => Configuration::get('WK_HTL_SHORT_DESC', $this->context->language->id), 'currentIndex' => $this->context->link->getPageLink('our-properties') diff --git a/controllers/front/ProductController.php b/controllers/front/ProductController.php index decd83c62..a5ec40f2d 100644 --- a/controllers/front/ProductController.php +++ b/controllers/front/ProductController.php @@ -49,6 +49,7 @@ class ProductControllerCore extends FrontController $this->addJS(array( _THEME_JS_DIR_.'tools.js', // retro compat themes 1.5 _THEME_JS_DIR_.'product.js', + _THEME_JS_DIR_.'room-type-service-products.js', )); } else { $this->addJqueryPlugin(array('scrollTo', 'serialScroll')); @@ -1443,8 +1444,8 @@ class ProductControllerCore extends FrontController $response = array('status' => false); $idProduct = (int) Tools::getValue('id_product'); if ($this->product->booking_product) { - $dateFrom = Tools::getValue('room_check_in'); - $dateTo = Tools::getValue('room_check_out'); + $dateFrom = Tools::getValue('date_from'); + $dateTo = Tools::getValue('date_to'); $occupancy = Tools::getValue('occupancy'); if (Configuration::get('PS_FRONT_ROOM_UNIT_SELECTION_TYPE') == HotelBookingDetail::PS_ROOM_UNIT_SELECTION_TYPE_OCCUPANCY) { if (!Validate::isOccupancy($occupancy)) { @@ -1468,9 +1469,9 @@ class ProductControllerCore extends FrontController )) { } } else { - $idHotel = Tools::getValue('service_id_hotel'); + $idHotel = Tools::getValue('id_hotel'); $id_product_option = Tools::getValue('id_product_option'); - $quantity = Tools::getValue('service_product_qty'); + $quantity = Tools::getValue('qty'); $this->assignServiceProductVars( $id_product_option, $quantity, @@ -1478,6 +1479,7 @@ class ProductControllerCore extends FrontController ); } + $this->context->smarty->assign('static_token', Tools::getToken(false)); $html = $this->context->smarty->fetch('_partials/booking-form.tpl'); $response['status'] = true; $response['html_booking_form'] = $html; diff --git a/modules/blockcart/ajax-cart.js b/modules/blockcart/ajax-cart.js index ca2ad2695..eaa8a6bd9 100644 --- a/modules/blockcart/ajax-cart.js +++ b/modules/blockcart/ajax-cart.js @@ -394,19 +394,29 @@ var ajaxCart = { if (parseInt(booking_product)) { // get the selected extra demands by customer if (typeof dateFrom != 'undefined') - req.append('dateFrom', dateFrom); + req.append('date_from', dateFrom); if (typeof dateTo != 'undefined') - req.append('dateTo', dateTo); + req.append('date_to', dateTo); - if (occupancy_required_for_booking) { - req.append('occupancy', JSON.stringify(occupancy)); + if (occupancy_required_for_booking) { + occupancy.forEach(function(room, i) { + req.append('occupancy['+i+'][adults]', room.adults); + req.append('occupancy['+i+'][children]', room.children || 0); + if (room.child_ages && room.child_ages.length) { + room.child_ages.forEach(function(age) { + req.append('occupancy['+i+'][child_ages][]', age); + }); + } + }); } else { req.append('qty', ((occupancy && occupancy != null) ? occupancy : '1')); } var roomDemands = getRoomsExtraDemands(); - req.append('roomDemands', JSON.stringify(roomDemands) ); - req.append('serviceProducts', JSON.stringify(getRoomsServiceProducts()) ); + req.append('room_demands', JSON.stringify(roomDemands) ); + getRoomsServiceProducts().forEach(function(product) { + req.append('service_product['+product.id_product+'][quantity]', product.quantity); + }); } else { req.append('qty', ((occupancy && occupancy != null) ? occupancy : '1')); } @@ -555,7 +565,7 @@ var ajaxCart = { async: true, cache: false, dataType: "json", - data: 'controller=cart&add=1&op=down&dateFrom=' + dateFrom + '&dateTo=' + dateTo + '&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ((parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination) : '' + '&id_customization=' + ((typeof customizationId !== 'undefined') ? customizationId : 0)), + data: 'controller=cart&add=1&op=down&date_from=' + dateFrom + '&date_to=' + dateTo + '&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ((parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination) : '' + '&id_customization=' + ((typeof customizationId !== 'undefined') ? customizationId : 0)), success: function(jsonData, textStatus, jqXHR) { /*by webkul checking and setting availability of rooms*/ /*for product page add to cart quantity management*/ @@ -629,7 +639,7 @@ var ajaxCart = { async: true, cache: false, dataType: "json", - data: 'controller=cart&delete=1&dateFrom=' + dateFrom + '&dateTo=' + dateTo + '&id_product=' + idProduct + '&id_hotel=' + idHotel + '&id_product_option=' + ((idCombination != null && parseInt(idCombination)) ? idCombination : '') + ((customizationId && customizationId != null) ? '&id_customization=' + customizationId : '') + '&id_address_delivery=' + idAddressDelivery + '&token=' + static_token + '&ajax=true', + data: 'controller=cart&delete=1&date_from=' + dateFrom + '&date_to=' + dateTo + '&id_product=' + idProduct + '&id_hotel=' + idHotel + '&id_product_option=' + ((idCombination != null && parseInt(idCombination)) ? idCombination : '') + ((customizationId && customizationId != null) ? '&id_customization=' + customizationId : '') + '&id_address_delivery=' + idAddressDelivery + '&token=' + static_token + '&ajax=true', success: function(jsonData) { if (pagename == 'product') { disableRoomTypeDemands(0); @@ -1387,112 +1397,3 @@ function crossselling_serialScroll() { pager: false }); } - -function resetRoomtypeServices(refresh = true) { - $('.room_demands_container').find('input.id_room_type_demand:checked').prop('checked', false).uniform(); - $('#additional_products').empty(); - $('#additional_products div') - $('.remove_roomtype_product').text(select_txt).removeClass('btn-danger remove_roomtype_product').addClass('btn-success add_roomtype_product'); - if (refresh) { - BookingForm.refresh(); - } -} - -function disableRoomTypeDemands(show) { - if (show) { - $('.room_demands_container_overlay').show(); - $('.room_demands_container').find('input:checkbox.id_room_type_demand').prop('checked', false); - $('.room_demand_block').find('.id_room_type_demand').prop('checked', false).parent().removeClass('checked'); - $('.room_demands_container').find('input:checkbox.id_room_type_demand').attr('disabled', 'disabled'); - } else { - $('.room_demands_container_overlay').hide(); - $('.room_demands_container').find('input:checkbox.id_room_type_demand').removeAttr('disabled'); - $('.room_demands_container').find('.checker').removeClass('disabled'); - } -} - -function disableRoomTypeServices(disable) { - if (disable) { - resetRoomtypeServices(false); - $('#service_products_cont').find('button.add_roomtype_product').attr('disabled', 'disabled'); - $('#service_products_cont').find('.qty_container .qty_direction a').attr('disabled', 'disabled'); - } else { - $('#service_products_cont').find('button.add_roomtype_product').removeAttr('disabled'); - $('#service_products_cont').find('.qty_container .qty_direction a').removeAttr('disabled'); - } -} - -function getRoomsExtraDemands() -{ - var roomDemands = []; - - $('input:checkbox.id_room_type_demand:checked').each(function () { - roomDemands.push({ - 'id_global_demand':$(this).val(), - 'id_option': $(this).closest('.room_demand_block').find('.id_option').val() - }); - }); - - return roomDemands; -} - -function getRoomsServiceProducts() -{ - var serviceProducts = []; - - $('#additional_products input.service_product').each(function () { - serviceProducts.push({ - 'id_product': $(this).data('id_product'), - 'quantity':$(this).val(), - }); - }); - - return serviceProducts; -} - -function getBookingOccupancyDetails(bookingform, booking_product) -{ - let occupancy; - if (booking_product) { - if (occupancy_required_for_booking) { - $('.booking_guest_occupancy_conatiner .dropdown').removeClass('open'); - let selected_occupancy = $(bookingform).find(".occupancy_info_block.selected") - if (selected_occupancy.length) { - occupancy = []; - $(selected_occupancy).each(function(ind, element) { - if (parseInt($(element).find('.num_adults').val())) { - let child_ages = []; - $(element).find('.guest_child_age').each(function(index) { - if ($(this).val() > -1) { - child_ages.push($(this).val()); - } - }); - if ($(element).find('.num_children').val()) { - if (child_ages.length != $(element).find('.num_children').val()) { - $(bookingform).find('.booking_occupancy_wrapper').parent().addClass('open') - occupancy = false; - } - } - occupancy.push({ - 'adults': $(element).find('.num_adults').val(), - 'children': $(element).find('.num_children').val(), - 'child_ages': child_ages - }); - } else { - $(bookingform).find('.booking_occupancy_wrapper').parent().addClass('open') - occupancy = false; - } - }); - } else { - $(bookingform).find('.booking_occupancy_wrapper').parent().addClass('open') - occupancy = false; - } - } else { - occupancy = parseInt($(bookingform).find(".quantity_wanted").val()); - } - } else { - occupancy = parseInt($('#service_product_qty').val()); - } - - return occupancy; -} diff --git a/modules/hotelreservationsystem/classes/HotelImage.php b/modules/hotelreservationsystem/classes/HotelImage.php index 1a94b8744..0fc87152f 100644 --- a/modules/hotelreservationsystem/classes/HotelImage.php +++ b/modules/hotelreservationsystem/classes/HotelImage.php @@ -25,6 +25,7 @@ class HotelImage extends ObjectModel { public $id; public $id_hotel; + public $id_htl_image_category; public $cover; public $source_index; public $image_dir; @@ -37,6 +38,7 @@ class HotelImage extends ObjectModel 'primary' => 'id', 'fields' => array( 'id_hotel' => array('type' => self::TYPE_INT, 'validate' => 'isInt'), + 'id_htl_image_category' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'allow_null' => true), 'cover' => array('type' => self::TYPE_BOOL,'validate' => 'isBool') ), ); @@ -99,7 +101,7 @@ class HotelImage extends ObjectModel * @param [int] $n [number of images per page for paginated images data] * @return [array|boolean] [if data found returns array containing information of the images of the hotel which id is passed] */ - public function getImagesByHotelId($id_hotel, $p = 1, $n = null) + public function getImagesByHotelId($id_hotel, $p = 1, $n = null, $idLang = null) { $p = (int) $p; $n = $n !== null ? (int) $n : $n; // n = null for no pagination @@ -107,9 +109,16 @@ class HotelImage extends ObjectModel $p = 1; } - $sql = 'SELECT * - FROM `'._DB_PREFIX_.'htl_image` - WHERE `id_hotel` = '.(int) $id_hotel. + if (!$idLang) { + $idLang = (int) Context::getContext()->language->id; + } + + $sql = 'SELECT hi.*, hicl.`name` AS `category_name` + FROM `'._DB_PREFIX_.'htl_image` hi + LEFT JOIN `'._DB_PREFIX_.'htl_image_category_lang` hicl + ON (hicl.`id_htl_image_category` = hi.`id_htl_image_category` + AND hicl.`id_lang` = '.(int) $idLang.') + WHERE hi.`id_hotel` = '.(int) $id_hotel. ($n ? ' LIMIT '.(int) (($p - 1) * $n).', '.(int) ($n) : ''); return Db::getInstance()->executeS($sql); @@ -174,107 +183,80 @@ class HotelImage extends ObjectModel ); } - public function uploadHotelImages($images, $idHotel) + public function uploadHotelImages($images, $idHotel, $idHtlImageCategory = 0, $objCategory = null) { - if (isset($images) && $idHotel) { - $objHotelHelper = new HotelHelper(); - $hotelImages = $images['tmp_name']; - if (is_array($images['tmp_name'])) { - foreach ($hotelImages as $image) { - $objHtlImage = new HotelImage(); - $objHtlImage->id_hotel = $idHotel; - if ($coverImgExist = HotelImage::getCover($idHotel)) { - $objHtlImage->cover = 0; - } else { - $objHtlImage->cover = 1; - } - if ($objHtlImage->save()) { - if ($path = $objHtlImage->getPathForCreation()) { - if (ImageManager::resize( - $image, - $path.$objHtlImage->id.'.'.$objHtlImage->image_format - )) { - // add hotel images in all required sizes - $imagesTypes = ImageType::getImagesTypes('hotels'); - $generate_hight_dpi_images = (bool)Configuration::get('PS_HIGHT_DPI'); + if (!isset($images['tmp_name']) || !$idHotel) { + return false; + } - foreach ($imagesTypes as $imageType) { - if (!ImageManager::resize( - $image, - $path.$objHtlImage->id.'-'.stripslashes($imageType['name']).'.'.$objHtlImage->image_format, - $imageType['width'], - $imageType['height'] - )) { - continue; - } + $isMultiple = is_array($images['tmp_name']); + $tmpFiles = $isMultiple ? $images['tmp_name'] : array($images['tmp_name']); - if ($generate_hight_dpi_images) { - if (!ImageManager::resize( - $image, - $path.$objHtlImage->id.'-'.stripslashes($imageType['name']).'.'.$objHtlImage->image_format, - (int)$imageType['width']*2, - (int)$imageType['height']*2 - )) { - continue; - } - } - } + $generateHighDpiImages = (bool) Configuration::get('PS_HIGHT_DPI'); + $imagesTypes = ImageType::getImagesTypes('hotels'); + $addedImage = false; + $allSucceeded = true; - } - } - } + foreach ($tmpFiles as $tmpFile) { + if (!is_string($tmpFile) || $tmpFile === '') { + $allSucceeded = false; + continue; + } + + $objHtlImage = new HotelImage(); + $objHtlImage->id_hotel = $idHotel; + $objHtlImage->id_htl_image_category = $idHtlImageCategory ?: null; + $objHtlImage->cover = self::getCover($idHotel) ? 0 : 1; + + if (!$objHtlImage->save() + || !($path = $objHtlImage->getPathForCreation()) + || !ImageManager::resize($tmpFile, $path.$objHtlImage->id.'.'.$objHtlImage->image_format) + ) { + $allSucceeded = false; + continue; + } + + foreach ($imagesTypes as $imageType) { + if (!ImageManager::resize( + $tmpFile, + $path.$objHtlImage->id.'-'.stripslashes($imageType['name']).'.'.$objHtlImage->image_format, + $imageType['width'], + $imageType['height'] + )) { + continue; } - } else { - $objHtlImage = new HotelImage(); - $objHtlImage->id_hotel = $idHotel; - if ($coverImgExist = HotelImage::getCover($idHotel)) { - $objHtlImage->cover = 0; - } else { - $objHtlImage->cover = 1; - } - if ($objHtlImage->save()) { - if ($path = $objHtlImage->getPathForCreation()) { - if (ImageManager::resize( - $hotelImages, - $path.$objHtlImage->id.'.'.$objHtlImage->image_format - )) { - $imagesTypes = ImageType::getImagesTypes('hotels'); - $generate_hight_dpi_images = (bool)Configuration::get('PS_HIGHT_DPI'); - foreach ($imagesTypes as $imageType) { - if (!ImageManager::resize( - $hotelImages, - $path.$objHtlImage->id.'-'.stripslashes($imageType['name']).'.'.$objHtlImage->image_format, - $imageType['width'], - $imageType['height'] - )) { - continue; - } - if ($generate_hight_dpi_images) { - if (!ImageManager::resize( - $hotelImages, - $path.$objHtlImage->id.'-'.stripslashes($imageType['name']).'.'.$objHtlImage->image_format, - (int)$imageType['width']*2, - (int)$imageType['height']*2 - )) { - continue; - } - } - } - $addedImage = array( - 'id' => $objHtlImage->id, - 'cover' => $objHtlImage->cover, - 'image_link' => Context::getContext()->link->getMediaLink($objHtlImage->getImageLink($objHtlImage->id)), - ); - return $addedImage; - } - } + if ($generateHighDpiImages) { + ImageManager::resize( + $tmpFile, + $path.$objHtlImage->id.'-'.stripslashes($imageType['name']).'.'.$objHtlImage->image_format, + (int) $imageType['width'] * 2, + (int) $imageType['height'] * 2 + ); } } - return true; + + if (!$isMultiple) { + if (!$objCategory || (int) $objCategory->id !== $idHtlImageCategory) { + $objCategory = new HotelImageCategory($idHtlImageCategory, Context::getContext()->language->id); + } + + $addedImage = array( + 'id' => $objHtlImage->id, + 'cover' => $objHtlImage->cover, + 'id_htl_image_category' => $idHtlImageCategory, + 'category_name' => (string) $objCategory->name, + 'image_link' => Context::getContext()->link->getMediaLink($objHtlImage->getImageLink($objHtlImage->id)), + ); + } } - return false; + + if ($isMultiple) { + return $allSucceeded; + } + + return $allSucceeded ? $addedImage : false; } public function getPathForCreation() diff --git a/modules/hotelreservationsystem/classes/HotelImageCategory.php b/modules/hotelreservationsystem/classes/HotelImageCategory.php new file mode 100644 index 000000000..863aadc5c --- /dev/null +++ b/modules/hotelreservationsystem/classes/HotelImageCategory.php @@ -0,0 +1,63 @@ + 'htl_image_category', + 'primary' => 'id_htl_image_category', + 'multilang' => true, + 'fields' => array( + 'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCatalogName', 'required' => true, 'size' => 128), + 'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false), + 'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false), + ), + ); + + public static function getImageCategories($idLang = null) + { + if (!$idLang) { + $idLang = (int) Context::getContext()->language->id; + } + + $defaultLangId = (int) Configuration::get('PS_LANG_DEFAULT'); + + return Db::getInstance()->executeS( + 'SELECT hic.`id_htl_image_category`, COALESCE(hicl.`name`, hiclDefault.`name`) AS `name` + FROM `'._DB_PREFIX_.'htl_image_category` hic + LEFT JOIN `'._DB_PREFIX_.'htl_image_category_lang` hicl + ON (hicl.`id_htl_image_category` = hic.`id_htl_image_category` + AND hicl.`id_lang` = '.(int) $idLang.') + LEFT JOIN `'._DB_PREFIX_.'htl_image_category_lang` hiclDefault + ON (hiclDefault.`id_htl_image_category` = hic.`id_htl_image_category` + AND hiclDefault.`id_lang` = '.(int) $defaultLangId.') + WHERE COALESCE(hicl.`name`, hiclDefault.`name`) IS NOT NULL + ORDER BY `name` ASC' + ); + } +} diff --git a/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php b/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php index e474ef68c..be397dc23 100644 --- a/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php +++ b/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php @@ -87,10 +87,27 @@ class HotelReservationSystemDb "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_image` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_hotel` int(10) unsigned NOT NULL, + `id_htl_image_category` int(10) unsigned DEFAULT NULL, `cover` tinyint(1) NOT NULL DEFAULT '0', + KEY `id_hotel` (`id_hotel`), + KEY `id_htl_image_category` (`id_htl_image_category`), PRIMARY KEY (`id`) ) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;", + "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_image_category` ( + `id_htl_image_category` int(10) unsigned NOT NULL AUTO_INCREMENT, + `date_add` datetime NOT NULL, + `date_upd` datetime NOT NULL, + PRIMARY KEY (`id_htl_image_category`) + ) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;", + + "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_image_category_lang` ( + `id_htl_image_category` int(10) unsigned NOT NULL, + `id_lang` int(10) unsigned NOT NULL, + `name` varchar(128) NOT NULL, + PRIMARY KEY (`id_htl_image_category`, `id_lang`) + ) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8;", + "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_amenity` ( `id_amenity` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_parent` int(10) unsigned NOT NULL, @@ -588,6 +605,8 @@ class HotelReservationSystemDb `'._DB_PREFIX_.'htl_branch_info`, `'._DB_PREFIX_.'htl_branch_info_lang`, `'._DB_PREFIX_.'htl_image`, + `'._DB_PREFIX_.'htl_image_category`, + `'._DB_PREFIX_.'htl_image_category_lang`, `'._DB_PREFIX_.'htl_branch_amenity`, `'._DB_PREFIX_.'htl_room_type_amenity`, `'._DB_PREFIX_.'htl_amenity`, diff --git a/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php b/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php index 9ebe57852..fcb976763 100644 --- a/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php +++ b/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php @@ -204,6 +204,9 @@ class AdminAddHotelController extends ModuleAdminController } else { $idCountry = Tools::getValue('hotel_country'); } + + $smartyVars['hotelImageCategories'] = HotelImageCategory::getImageCategories($this->context->language->id); + // manage state option $stateOptions = null; if ($idCountry) { @@ -412,6 +415,18 @@ class AdminAddHotelController extends ModuleAdminController } elseif (!Validate::isCityName($city)) { $this->errors[] = $this->l('Enter a valid city name.'); } + if (Tools::getValue('loclatitude') !== '' && (!is_numeric(Tools::getValue('loclatitude')) || !Validate::isCoordinate($latitude))) { + $this->errors[] = $this->l('Latitude is invalid.'); + } + if (Tools::getValue('loclongitude') !== '' && (!is_numeric(Tools::getValue('loclongitude')) || !Validate::isCoordinate($longitude))) { + $this->errors[] = $this->l('Longitude is invalid.'); + } + if ($map_formated_address && !Validate::isCleanHtml(html_entity_decode($map_formated_address))) { + $this->errors[] = $this->l('Map formatted address is invalid.'); + } + if ($map_input_text && !Validate::isString($map_input_text)) { + $this->errors[] = $this->l('Map location text is invalid.'); + } //Since the address for the hotel is saved in the address table. We are validating the hotel address here manually. $addressValidation = Address::getValidationRules('Address'); @@ -610,8 +625,8 @@ class AdminAddHotelController extends ModuleAdminController $objHotelBranch->check_in = $check_in; $objHotelBranch->check_out = $check_out; $objHotelBranch->rating = $rating; - $objHotelBranch->latitude = Validate::isCoordinate($latitude) ? Tools::ps_round($latitude, 8) : $latitude; - $objHotelBranch->longitude = Validate::isCoordinate($longitude) ? Tools::ps_round($longitude, 8) : $longitude; + $objHotelBranch->latitude = $latitude; + $objHotelBranch->longitude = $longitude; $objHotelBranch->map_formated_address = $map_formated_address; $objHotelBranch->map_input_text = $map_input_text; $objHotelBranch->save(); @@ -816,10 +831,12 @@ class AdminAddHotelController extends ModuleAdminController $conf = 4; } + $tabParam = Tools::getValue('htl_active_tab') ? '&htl_active_tab='.urlencode(Tools::getValue('htl_active_tab')) : ''; + if (Tools::isSubmit('submitAdd'.$this->table.'AndStay')) { - Tools::redirectAdmin(self::$currentIndex.'&id='.(int) $newIdHotel.'&update'.$this->table.'&conf='.$conf.'&token='.$this->token ); + Tools::redirectAdmin(self::$currentIndex.'&id='.(int) $newIdHotel.'&update'.$this->table.'&conf='.$conf.'&token='.$this->token.$tabParam); } else { - Tools::redirectAdmin(self::$currentIndex.'&conf='.$conf.'&token='.$this->token); + Tools::redirectAdmin(self::$currentIndex.'&conf='.$conf.'&token='.$this->token.$tabParam); } } @@ -867,38 +884,35 @@ class AdminAddHotelController extends ModuleAdminController $this->ajaxDie(json_encode($response)); } - public function ajaxProcessUploadHotelImages() + public function ajaxProcessUploadHotelImage() { - $response = array('success' => false); - $idHotel = Tools::getValue('id_hotel'); + $response = array('success' => false, 'errors' => array()); + $idHotel = (int) Tools::getValue('id_hotel'); + $idHtlImageCategory = (int) Tools::getValue('id_htl_image_category'); + $file = isset($_FILES['hotel_image']) ? $_FILES['hotel_image'] : null; + if ($idHotel) { - $invalidImg = ImageManager::validateUpload( - $_FILES['hotel_image'], - Tools::getMaxUploadSize() - ); - if (!$invalidImg) { - // Add Hotel images - $objHotelImage = new HotelImage(); - $imageDetail = $objHotelImage->uploadHotelImages($_FILES['hotel_image'], $idHotel); - if ($imageDetail) { - $response['success'] = true; - $imageDetail['image_link'] = $this->context->link->getMediaLink($objHotelImage->getImageLink($imageDetail['id'],ImageType::getFormatedName('large'))); - $imageDetail['image_link_small'] = $this->context->link->getMediaLink($objHotelImage->getImageLink($imageDetail['id'], ImageType::getFormatedName('small'))); - $response['data']['image_info'] = $imageDetail; - // get image row - $this->context->smarty->assign(array( - 'image' => $imageDetail, - 'hotel_info' => array('id' => $idHotel) - )); - $response['data']['image_row'] = $this->context->smarty->fetch( - _PS_MODULE_DIR_.$this->module->name. - '/views/templates/admin/add_hotel/_partials/htl-images-list-row.tpl' - ); + if ($file && $file['size']) { + $objCategory = $idHtlImageCategory ? new HotelImageCategory($idHtlImageCategory, $this->context->language->id) : null; + if ($idHtlImageCategory && !Validate::isLoadedObject($objCategory)) { + $response['errors'][] = $this->l('Selected image category is invalid.'); + } elseif ($error = ImageManager::validateUpload($file, Tools::getMaxUploadSize())) { + $response['errors'][] = $error; } else { - $response['errors'][] = $this->l('Unable to uploade image. Please try again'); + $objHotelImage = new HotelImage(); + $imageDetail = $objHotelImage->uploadHotelImages($file, $idHotel, $idHtlImageCategory, $objCategory); + if ($imageDetail) { + $imageDetail['image_link'] = $this->context->link->getMediaLink($objHotelImage->getImageLink($imageDetail['id'], ImageType::getFormatedName('large'))); + $imageDetail['image_link_small'] = $this->context->link->getMediaLink($objHotelImage->getImageLink($imageDetail['id'], ImageType::getFormatedName('small'))); + + $response['success'] = true; + $response['image_row'] = $this->renderHotelImageRow($imageDetail, $idHotel); + } else { + $response['errors'][] = $this->l('Unable to upload image. Please try again'); + } } } else { - $response['errors'][] = $_FILES['hotel_image']['name'].': '.$invalidImg; + $response['errors'][] = $this->l('No file received.'); } } else { $response['errors'][] = $this->l('Hotel info not found. Please try reloading the page'); @@ -908,38 +922,181 @@ class AdminAddHotelController extends ModuleAdminController public function ajaxProcessChangeCoverImage() { - $idImage = Tools::getValue('id_image'); + $idImage = (int) Tools::getValue('id_image'); + $idHotel = (int) Tools::getValue('id_hotel'); $response = array('status' => false); - if ($idImage) { - $idHotel = Tools::getValue('id_hotel'); + + if ($idImage && $idHotel && Validate::isLoadedObject($objHtlImage = new HotelImage($idImage)) && (int) $objHtlImage->id_hotel === $idHotel) { + $oldCoverId = null; + $affectedCoverImage = null; if ($coverImg = HotelImage::getCover($idHotel)) { - $objHtlImage = new HotelImage((int) $coverImg['id']); - $objHtlImage->cover = 0; - $objHtlImage->save(); + $oldCoverId = (int) $coverImg['id']; + $affectedCoverImage = new HotelImage($oldCoverId); + $affectedCoverImage->cover = 0; + $affectedCoverImage->save(); } - $objHtlImage = new HotelImage((int) $idImage); $objHtlImage->cover = 1; - if ($objHtlImage->update()) { - $response['status'] = true; + $objHtlImage->update(); + + $response['status'] = true; + $response['image_row'] = $this->renderHotelImageRow($this->getHotelImageRowData($objHtlImage), $idHotel); + + if ($oldCoverId) { + $response['old_cover_id'] = $oldCoverId; + $response['old_cover_row'] = $this->renderHotelImageRow( + $this->getHotelImageRowData($affectedCoverImage), + $idHotel + ); } } $this->ajaxDie(json_encode($response)); } + public function ajaxProcessEditHotelImage() + { + $response = array('status' => false); + $idImage = (int) Tools::getValue('id_image'); + $idHotel = (int) Tools::getValue('id_hotel'); + $idHtlImageCategory = (int) Tools::getValue('id_htl_image_category'); + $setCover = (bool) Tools::getValue('cover'); + + if ($idImage && $idHotel && Validate::isLoadedObject($objHtlImage = new HotelImage($idImage)) && (int) $objHtlImage->id_hotel === $idHotel) { + $objCategory = $idHtlImageCategory ? new HotelImageCategory($idHtlImageCategory, $this->context->language->id) : null; + if ($idHtlImageCategory && !Validate::isLoadedObject($objCategory)) { + $response['errors'][] = $this->l('Selected image category is invalid.'); + $this->ajaxDie(json_encode($response)); + } + + $otherImage = null; + if (!$setCover && $objHtlImage->cover) { + foreach ($objHtlImage->getImagesByHotelId($idHotel, 1, 2) as $image) { + if ((int) $image['id'] !== $idImage) { + $otherImage = $image; + break; + } + } + if (!$otherImage) { + $response['errors'][] = $this->l('At least one image must remain marked as cover.'); + $this->ajaxDie(json_encode($response)); + } + } + + $objHtlImage->id_htl_image_category = $idHtlImageCategory ?: null; + + $oldCoverId = null; + $affectedCoverImage = null; + if ($setCover && !$objHtlImage->cover) { + if ($coverImg = HotelImage::getCover($idHotel)) { + $oldCoverId = (int) $coverImg['id']; + $affectedCoverImage = new HotelImage($oldCoverId); + $affectedCoverImage->cover = 0; + $affectedCoverImage->save(); + } + + $objHtlImage->cover = 1; + } elseif ($otherImage) { + $objHtlImage->cover = 0; + + $affectedCoverImage = new HotelImage($otherImage['id']); + $affectedCoverImage->cover = 1; + $affectedCoverImage->save(); + $oldCoverId = (int) $affectedCoverImage->id; + } + + $objHtlImage->update(); + + $response['status'] = true; + $response['image_row'] = $this->renderHotelImageRow($this->getHotelImageRowData($objHtlImage, $objCategory), $idHotel); + + if ($oldCoverId) { + $response['old_cover_id'] = $oldCoverId; + $response['old_cover_row'] = $this->renderHotelImageRow( + $this->getHotelImageRowData($affectedCoverImage), + $idHotel + ); + } + } else { + $response['errors'][] = $this->l('Image not found.'); + } + + $this->ajaxDie(json_encode($response)); + } + + private function getHotelImageRowData($objHtlImage, ?HotelImageCategory $objCategory = null) + { + $idHtlImageCategory = (int) $objHtlImage->id_htl_image_category; + if (!$objCategory || (int) $objCategory->id !== $idHtlImageCategory) { + $objCategory = new HotelImageCategory($idHtlImageCategory, $this->context->language->id); + } + + return array( + 'id' => $objHtlImage->id, + 'cover' => $objHtlImage->cover, + 'id_htl_image_category' => $idHtlImageCategory, + 'category_name' => (string) $objCategory->name, + 'image_link' => $this->context->link->getMediaLink($objHtlImage->getImageLink($objHtlImage->id, ImageType::getFormatedName('large'))), + 'image_link_small' => $this->context->link->getMediaLink($objHtlImage->getImageLink($objHtlImage->id, ImageType::getFormatedName('small'))), + ); + } + + private function renderHotelImageRow($imageData, $idHotel) + { + $this->context->smarty->assign(array( + 'image' => $imageData, + 'hotel_info' => array('id' => $idHotel), + )); + + return $this->context->smarty->fetch(_PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/add_hotel/_partials/htl-images-list-row.tpl'); + } + + public function ajaxProcessBulkUpdateHotelImage() + { + $response = array('status' => false, 'errors' => array()); + $idHotel = (int) Tools::getValue('id_hotel'); + $idHtlImageCategory = (int) Tools::getValue('id_htl_image_category'); + $imageIds = array_filter(array_map('intval', (array) Tools::getValue('image_ids', array()))); + + if ($idHotel && $imageIds) { + $objCategory = $idHtlImageCategory ? new HotelImageCategory($idHtlImageCategory, $this->context->language->id) : null; + if ($idHtlImageCategory && !Validate::isLoadedObject($objCategory)) { + $response['errors'][] = $this->l('Selected image category is invalid.'); + } else { + foreach ($imageIds as $idImage) { + $objHtlImage = new HotelImage($idImage); + if (Validate::isLoadedObject($objHtlImage) && (int) $objHtlImage->id_hotel === $idHotel) { + $objHtlImage->id_htl_image_category = $idHtlImageCategory ?: null; + $objHtlImage->update(); + } + } + + $response['status'] = true; + $response['image_ids'] = $imageIds; + $response['category_name'] = $objCategory ? (string) $objCategory->name : ''; + } + } else { + $response['errors'][] = $this->l('No images selected.'); + } + + $this->ajaxDie(json_encode($response)); + } + public function ajaxProcessDeleteHotelImage() { $response = array('status' => false); if ($idImage = Tools::getValue('id_image')) { if ($idHotel = Tools::getValue('id_hotel')) { - if (Validate::isLoadedObject($objHtlImage = new HotelImage((int) $idImage))) { + if (Validate::isLoadedObject($objHtlImage = new HotelImage((int) $idImage)) && (int) $objHtlImage->id_hotel === (int) $idHotel) { if ($objHtlImage->delete()) { if (!HotelImage::getCover($idHotel)) { - $images = $objHtlImage->getImagesByHotelId($idHotel); + $images = $objHtlImage->getImagesByHotelId($idHotel, 1, 1); if ($images) { - $objHtlImage = new HotelImage($images[0]['id']); - $objHtlImage->cover = 1; - $objHtlImage->save(); + $objNewCover = new HotelImage($images[0]['id']); + $objNewCover->cover = 1; + $objNewCover->save(); + + $response['new_cover_id'] = (int) $objNewCover->id; + $response['new_cover_row'] = $this->renderHotelImageRow($this->getHotelImageRowData($objNewCover), $idHotel); } } $response['status'] = true; @@ -950,6 +1107,43 @@ class AdminAddHotelController extends ModuleAdminController $this->ajaxDie(json_encode($response)); } + public function ajaxProcessBulkDeleteHotelImage() + { + $response = array('status' => false, 'errors' => array()); + $idHotel = (int) Tools::getValue('id_hotel'); + $imageIds = array_filter(array_map('intval', (array) Tools::getValue('image_ids', array()))); + + if (!$idHotel || !$imageIds) { + $response['errors'][] = $this->l('No images selected.'); + $this->ajaxDie(json_encode($response)); + } + + $deletedIds = array(); + foreach ($imageIds as $idImage) { + $objHtlImage = new HotelImage($idImage); + if (Validate::isLoadedObject($objHtlImage) && (int) $objHtlImage->id_hotel === $idHotel && $objHtlImage->delete()) { + $deletedIds[] = $idImage; + } + } + + if (!HotelImage::getCover($idHotel)) { + $objHelper = new HotelImage(); + $images = $objHelper->getImagesByHotelId($idHotel, 1, 1); + if ($images) { + $objNewCover = new HotelImage($images[0]['id']); + $objNewCover->cover = 1; + $objNewCover->save(); + + $response['new_cover_id'] = (int) $objNewCover->id; + $response['new_cover_row'] = $this->renderHotelImageRow($this->getHotelImageRowData($objNewCover), $idHotel); + } + } + + $response['status'] = true; + $response['deleted_ids'] = $deletedIds; + $this->ajaxDie(json_encode($response)); + } + public function ajaxProcessUpdateSlidesPosition() { if (($slideIds = Tools::getValue('slides')) diff --git a/modules/hotelreservationsystem/controllers/admin/AdminHotelImageCategoryController.php b/modules/hotelreservationsystem/controllers/admin/AdminHotelImageCategoryController.php new file mode 100644 index 000000000..e0fdb8474 --- /dev/null +++ b/modules/hotelreservationsystem/controllers/admin/AdminHotelImageCategoryController.php @@ -0,0 +1,153 @@ +bootstrap = true; + $this->table = 'htl_image_category'; + $this->className = 'HotelImageCategory'; + $this->identifier = 'id_htl_image_category'; + $this->lang = true; + $this->context = Context::getContext(); + + parent::__construct(); + + $this->addRowAction('edit'); + $this->addRowAction('delete'); + + $this->fields_list = array( + 'id_htl_image_category' => array( + 'title' => $this->l('ID'), + 'align' => 'center', + 'class' => 'fixed-width-xs', + ), + 'name' => array( + 'title' => $this->l('Name'), + 'align' => 'center', + ), + 'date_add' => array( + 'title' => $this->l('Created On'), + 'type' => 'date', + 'align' => 'right' + ), + ); + + $this->bulk_actions = array( + 'delete' => array( + 'text' => $this->l('Delete selected'), + 'icon' => 'icon-trash', + 'confirm' => $this->l('Delete selected items?'), + ), + ); + } + + public function initToolbar() + { + parent::initToolbar(); + if (!$this->display || $this->display == 'list') { + $this->page_header_toolbar_btn['new'] = array( + 'href' => self::$currentIndex.'&add'.$this->table.'&token='.$this->token, + 'desc' => $this->l('Add new category'), + ); + } + } + + public function renderForm() + { + if (!$this->loadObject(true)) { + return; + } + + $this->fields_form = array( + 'legend' => array( + 'title' => $this->l('Hotel Image Category'), + 'icon' => 'icon-tags', + ), + 'input' => array( + array( + 'type' => 'text', + 'label' => $this->l('Name'), + 'name' => 'name', + 'required' => true, + 'lang' => true, + 'col' => 4, + 'hint' => $this->l('Enter the name of the hotel image category.'), + ), + ), + 'submit' => array( + 'title' => $this->l('Save'), + ), + 'buttons' => array( + 'save-and-stay' => array( + 'title' => $this->l('Save and stay'), + 'name' => 'submitAdd'.$this->table.'AndStay', + 'type' => 'submit', + 'class' => 'btn btn-default pull-right', + 'icon' => 'process-icon-save', + ), + ), + ); + + return parent::renderForm(); + } + + public function processSave() + { + if (!$this->loadObject(true)) { + return; + } + + $defaultLangId = (int) Configuration::get('PS_LANG_DEFAULT'); + $defaultLanguage = Language::getLanguage($defaultLangId); + $languages = Language::getLanguages(false); + + if (!trim(Tools::getValue('name_'.$defaultLangId))) { + $this->errors[] = $this->l('Category name is required at least in ').$defaultLanguage['name']; + } else { + foreach ($languages as $lang) { + $langName = trim(Tools::getValue('name_'.$lang['id_lang'])); + if ($langName && !Validate::isCatalogName($langName)) { + $this->errors[] = $this->l('Invalid category name in ').$lang['name']; + } + } + } + + return parent::processSave(); + } + + public function initPageHeaderToolbar() + { + if (!$this->display || $this->display == 'list') { + $back = $this->context->link->getAdminLink('AdminAddHotel'); + $this->page_header_toolbar_btn['back_to_list'] = array( + 'href' => $back, + 'desc' => $this->l('Back to hotel list'), + 'icon' => 'process-icon-back' + ); + } + parent::initPageHeaderToolbar(); + } + +} diff --git a/modules/hotelreservationsystem/define.php b/modules/hotelreservationsystem/define.php index 1f6809c2b..d17929877 100644 --- a/modules/hotelreservationsystem/define.php +++ b/modules/hotelreservationsystem/define.php @@ -26,6 +26,7 @@ require_once 'classes/HotelRoomType.php'; require_once 'classes/HotelRoomInformation.php'; require_once 'classes/HotelBranchInformation.php'; require_once 'classes/HotelImage.php'; +require_once 'classes/HotelImageCategory.php'; require_once 'classes/HotelAmenities.php'; require_once 'classes/HotelBranchAmenities.php'; require_once 'classes/HotelRoomTypeAmenities.php'; diff --git a/modules/hotelreservationsystem/hotelreservationsystem.php b/modules/hotelreservationsystem/hotelreservationsystem.php index 9b35b1b0d..6bd5443e3 100644 --- a/modules/hotelreservationsystem/hotelreservationsystem.php +++ b/modules/hotelreservationsystem/hotelreservationsystem.php @@ -529,6 +529,7 @@ class HotelReservationSystem extends Module $this->installTab('AdminHotelFeaturePricesSettings', 'Advanced Price Rules', 'AdminHotelConfigurationSetting', false); $this->installTab('AdminRoomTypeGlobalDemand', 'Additional Demand Configuration', 'AdminHotelConfigurationSetting', false); $this->installTab('AdminBookingDocument', 'Booking Documents', false, false); + $this->installTab('AdminHotelImageCategory', 'Hotel Image Category', false, false); return true; } diff --git a/modules/hotelreservationsystem/views/js/HotelReservationAdmin.js b/modules/hotelreservationsystem/views/js/HotelReservationAdmin.js index d90a1246a..7a7d09fe3 100644 --- a/modules/hotelreservationsystem/views/js/HotelReservationAdmin.js +++ b/modules/hotelreservationsystem/views/js/HotelReservationAdmin.js @@ -258,17 +258,34 @@ var GoogleMapsManager = { } }, setFormVars: function(params) { - $('#loclatitude').val(params.lat); - $('#loclongitude').val(params.lng); + $('#loclatitude').val(Number(params.lat).toFixed(8)); + $('#loclongitude').val(Number(params.lng).toFixed(8)); $('#locformatedAddr').val(params.formattedAddress); $('#googleInputField').val(params.inputText); }, + updateMarkerFromInputs: function() { + if (!this.map) { + return; + } + var latitude = Number($('#loclatitude').val()); + var longitude = Number($('#loclongitude').val()); + if (!latitude || !longitude) { + return; + } + var latLng = {lat: latitude, lng: longitude}; + this.map.setCenter(latLng); + this.addMarker(latLng, null, null, false); + }, } $(document).on('click', 'button.gm-ui-hover-effect', function () { GoogleMapsManager.clearAllMarkers(); }); +$(document).on('change', '#loclatitude, #loclongitude', function () { + GoogleMapsManager.updateMarkerFromInputs(); +}); + function initGoogleMaps() { if (typeof enabledDisplayMap != 'undefined' && $('#googleMapContainer').length diff --git a/modules/hotelreservationsystem/views/js/hotelImage.js b/modules/hotelreservationsystem/views/js/hotelImage.js index c1fd5f666..25df2800d 100644 --- a/modules/hotelreservationsystem/views/js/hotelImage.js +++ b/modules/hotelreservationsystem/views/js/hotelImage.js @@ -21,82 +21,126 @@ */ $(document).ready(function () { - $('.htl-img-preview').fancybox({ - width: 'auto', - height: 'auto', - autoSize : false, - maxWidth: 700, - 'hideOnContentClick': false, - }); - - $("#hotel_images").on("change", function(event) { - const files = Array.from(event.target.files); - uploadSelectedImages(files); - }); - - function uploadSelectedImages(files) + function initHotelImagePreview() { - if (files.length == 0) return; // all done - let file = files[0]; - files.splice(0, 1); - createImageUploadRequest(file).then((formData) => { - uploadHotelImages(formData).then(() => { - uploadSelectedImages(files) - }); - }) + $('.htl-img-preview').fancybox({ + width: 'auto', + height: 'auto', + autoSize : false, + maxWidth: 700, + 'hideOnContentClick': false, + }); } - function createImageUploadRequest(file) + initHotelImagePreview(); + + function initHotelImageModal(modalId) { - return new Promise((resolve, reject) => { - if (typeof file != 'undefined') { - if (file.size > maxSizeAllowed) { - reject(filesizeError + '[' + file.name + ']'); - } else { - var formData = new FormData(); - var idHotel = $("#id-hotel").val(); - formData.append('hotel_image', file); - formData.append('id_hotel', idHotel); - formData.append('ajax', true); - formData.append('action', 'uploadHotelImages'); - resolve(formData); - } + $('#page-loader').show(); + $(modalId).modal('show'); + setTimeout(function () { + $('#page-loader').hide(); + }, 0); + } + + function getCheckedImageIds() + { + return $('.hotel-image-checkbox:checked').map(function () { + return $(this).val(); + }).get(); + } + + function showEmptyRowIfNoImagesLeft() + { + if (!$('#hotel-image-table tbody tr[data-id-image]').length) { + $('.list-empty-tr').show(); + } + } + + $('#open-add-hotel-images-modal').on('click', function () { + var fileInput = document.getElementById('hotel-images-file-input'); + if (fileInput) { + fileInput.value = ''; + } + $('#hotel-images-file-name').val(''); + initHotelImageModal('#addHotelImagesModal'); + }); + + $('#hotel-images-file-add-btn').on('click', function () { + $('#hotel-images-file-input').trigger('click'); + }); + + $('#hotel-images-file-name').on('click', function () { + $('#hotel-images-file-input').trigger('click'); + }); + + $('#hotel-images-file-input').on('change', function () { + var fileNames = Array.prototype.map.call(this.files, function (file) { + return file.name; + }); + $('#hotel-images-file-name').val(fileNames.join(', ')); + }); + + $('#hotel-images-upload-btn').on('click', function () { + var fileInput = document.getElementById('hotel-images-file-input'); + var files = fileInput ? Array.prototype.slice.call(fileInput.files) : []; + if (!files.length) { + showErrorMessage(imgSelectErrorMsg); + return; + } + uploadHotelImagesSequentially(files); + }); + + function uploadHotelImagesSequentially(files) + { + var index = 0; + var idHotel = $('#id-hotel').val(); + var idHtlImageCategory = $('#id_htl_image_category').val(); + var $btn = $('#hotel-images-upload-btn').prop('disabled', true); + + $('#page-loader').show(); + + function next() { + if (index >= files.length) { + $btn.prop('disabled', false); + $('#page-loader').hide(); + $('#addHotelImagesModal').modal('hide'); + return; } - }); - } - function uploadHotelImages(formData) { - return new Promise((resolve, reject) => { + var file = files[index++]; + var formData = new FormData(); + formData.append('hotel_image', file); + formData.append('ajax', true); + formData.append('action', 'UploadHotelImage'); + formData.append('id_hotel', idHotel); + formData.append('id_htl_image_category', idHtlImageCategory); + $.ajax({ - type:'POST', - dataType:'JSON', + type: 'POST', url: adminHotelCtrlUrl, + dataType: 'json', data: formData, - cache:false, - contentType: false, processData: false, - success:function(response){ - if (response.success) { - $('.list-empty-tr').remove(); - $("#hotel-image-table tbody").append(response.data.image_row); + contentType: false, + success: function (resp) { + if (resp && resp.success) { + $('.list-empty-tr').hide(); + $('#hotel-image-table tbody').append(resp.image_row); + initHotelImagePreview(); showSuccessMessage(imgUploadSuccessMsg); - resolve(imgUploadSuccessMsg); } else { - if (typeof response.errors != 'undefined') { - showErrorMessage(response.errors); - reject(response.errors); - } else { - showErrorMessage(imgUploadErrorMsg); - reject(imgUploadErrorMsg); - } + showErrorMessage(file.name + ': ' + ((resp && resp.errors && resp.errors.join(', ')) || imgUploadErrorMsg)); } + next(); }, - error: function(data) { - showErrorMessage(imgUploadErrorMsg); - reject(imgUploadErrorMsg); + error: function () { + showErrorMessage(file.name + ': ' + imgUploadErrorMsg); + next(); } }); - }); + } + next(); } $('body').on('click', '.changer-cover-image', function(e){ @@ -104,8 +148,8 @@ $(document).ready(function () { var idHotel = $(this).attr('data-id-hotel'); var idImage = $(this).attr('data-id-image'); var isCover = $(this).attr('data-is-cover'); - var triggerElement = $(this); if (isCover == 0) { + $('#page-loader').show(); $.ajax({ type:'POST', url: adminHotelCtrlUrl, @@ -118,15 +162,11 @@ $(document).ready(function () { }, success: function(result) { if (result.status) { - // remover cover image identifier from old cover image - var oldCoverImageTr = $("#hotel-image-table tbody tr.cover-image-tr"); - oldCoverImageTr.removeClass("cover-image-tr").find("td.cover-image-td").removeClass("cover-image-td").find("a.changer-cover-image").removeClass("text-success").addClass("text-danger").attr("data-is-cover", "0").find("i.icon-check").removeClass("icon-check").addClass("icon-times"); - oldCoverImageTr.find("td button.delete-hotel-image").attr("data-is-cover", "0"); - - // Add classes in new covre image elements - triggerElement.removeClass("text-danger").addClass("text-success").find("i.icon-times").removeClass("icon-times").addClass("icon-check"); - triggerElement.parent().addClass("cover-image-td").parent().addClass("cover-image-tr").find("td button.delete-hotel-image").attr("data-is-cover", "1"); - + $('#hotel-image-table tr[data-id-image="' + idImage + '"]').replaceWith(result.image_row); + if (result.old_cover_row) { + $('#hotel-image-table tr[data-id-image="' + result.old_cover_id + '"]').replaceWith(result.old_cover_row); + } + initHotelImagePreview(); showSuccessMessage(coverImgSuccessMsg); } else { showErrorMessage(coverImgErrorMsg); @@ -135,18 +175,207 @@ $(document).ready(function () { error: function(data){ showErrorMessage(coverImgErrorMsg); } + }).always(function () { + $('#page-loader').hide(); }); } }); - $('body').on('click', '.delete-hotel-image', function(e){ + $('body').on('click', '.edit-hotel-image', function () { + var idImage = $(this).data('id-image'); + var idCategory = parseInt($(this).data('id-htl-image-category'), 10) || 0; + var isCover = parseInt($(this).attr('data-is-cover'), 10) === 1; + + var $categorySelect = $('#edit_id_htl_image_category'); + + $('#edit_hotel_image_id').val(idImage); + $categorySelect.val($categorySelect.find('option[value="' + idCategory + '"]').length ? idCategory : 0); + $('#edit_hotel_image_cover_on').prop('checked', isCover); + $('#edit_hotel_image_cover_off').prop('checked', !isCover); + + initHotelImageModal('#editHotelImageModal'); + }); + + $('#save-edit-hotel-image-btn').on('click', function () { + var idImage = $('#edit_hotel_image_id').val(); + var idHotel = $('#id-hotel').val(); + var $btn = $(this).prop('disabled', true); + + $('#page-loader').show(); + + $.ajax({ + type: 'POST', + url: adminHotelCtrlUrl, + dataType: 'json', + data: { + ajax: true, + action: 'EditHotelImage', + id_hotel: idHotel, + id_image: idImage, + id_htl_image_category: $('#edit_id_htl_image_category').val(), + cover: $('input[name="edit_hotel_image_cover"]:checked').val() + }, + success: function (resp) { + if (resp && resp.status) { + $('#hotel-image-table tr[data-id-image="' + idImage + '"]').replaceWith(resp.image_row); + if (resp.old_cover_row) { + $('#hotel-image-table tr[data-id-image="' + resp.old_cover_id + '"]').replaceWith(resp.old_cover_row); + } + initHotelImagePreview(); + showSuccessMessage(imgUpdateSuccessMsg); + $('#editHotelImageModal').modal('hide'); + } else { + showErrorMessage((resp && resp.errors && resp.errors.join('
')) || imgUploadErrorMsg); + } + }, + error: function () { + showErrorMessage(imgUploadErrorMsg); + } + }).always(function () { + $btn.prop('disabled', false); + $('#page-loader').hide(); + }); + }); + + $('#hotel-image-select-all').on('click', function (e) { e.preventDefault(); - var idHotel = $(this).attr('data-id-hotel'); - var idImage = $(this).attr('data-id-image'); - var isCover = $(this).attr('data-is-cover'); - var triggerElement = $(this); + $('.hotel-image-checkbox').prop('checked', true); + }); + + $('#hotel-image-unselect-all').on('click', function (e) { + e.preventDefault(); + $('.hotel-image-checkbox').prop('checked', false); + }); + + $('#hotel-image-bulk-update').on('click', function (e) { + e.preventDefault(); + if (!$('.hotel-image-checkbox:checked').length) { + showErrorMessage(bulkUpdateSelectErrorMsg); + return; + } + + $('#bulk_id_htl_image_category').val(0); + initHotelImageModal('#bulkUpdateHotelImageModal'); + }); + + var pendingBulkDeleteImageIds = null; + + $('#hotel-image-bulk-delete').on('click', function (e) { + e.preventDefault(); + var imageIds = getCheckedImageIds(); + if (!imageIds.length) { + showErrorMessage(bulkDeleteSelectErrorMsg); + return; + } + pendingBulkDeleteImageIds = imageIds; + $('#confirmDeleteHotelImageModal').modal('show'); + }); + + $('#save-bulk-hotel-image-btn').on('click', function () { + var idHotel = $('#id-hotel').val(); + var idHtlImageCategory = $('#bulk_id_htl_image_category').val(); + var imageIds = getCheckedImageIds(); + var $btn = $(this).prop('disabled', true); + + $('#page-loader').show(); + + $.ajax({ + type: 'POST', + url: adminHotelCtrlUrl, + dataType: 'json', + data: { + ajax: true, + action: 'BulkUpdateHotelImage', + id_hotel: idHotel, + id_htl_image_category: idHtlImageCategory, + image_ids: imageIds + }, + success: function (resp) { + if (resp && resp.status) { + $.each(resp.image_ids, function (i, idImage) { + var $row = $('#hotel-image-table tr[data-id-image="' + idImage + '"]'); + $row.find('.hotel-image-category-cell').text(resp.category_name || '—'); + $row.find('.edit-hotel-image').attr('data-id-htl-image-category', idHtlImageCategory); + }); + $('.hotel-image-checkbox').prop('checked', false); + showSuccessMessage(imgUpdateSuccessMsg); + $('#bulkUpdateHotelImageModal').modal('hide'); + } else { + showErrorMessage((resp && resp.errors && resp.errors.join('
')) || imgUploadErrorMsg); + } + }, + error: function () { + showErrorMessage(imgUploadErrorMsg); + } + }).always(function () { + $btn.prop('disabled', false); + $('#page-loader').hide(); + }); + }); + + var pendingDeleteHotelImage = null; + + $('body').on('click', '.delete-hotel-image', function (e) { + e.preventDefault(); + pendingDeleteHotelImage = $(this); + pendingBulkDeleteImageIds = null; + $('#confirmDeleteHotelImageModal').modal('show'); + }); + + $('#confirm-delete-hotel-image-btn').on('click', function () { + $('#confirmDeleteHotelImageModal').modal('hide'); + + if (pendingBulkDeleteImageIds && pendingBulkDeleteImageIds.length) { + var bulkImageIds = pendingBulkDeleteImageIds; + var bulkIdHotel = $('#id-hotel').val(); + pendingBulkDeleteImageIds = null; + + $('#page-loader').show(); + $.ajax({ + type: 'POST', + url: adminHotelCtrlUrl, + dataType: 'json', + data: { + ajax: true, + action: 'BulkDeleteHotelImage', + id_hotel: bulkIdHotel, + image_ids: bulkImageIds + }, + success: function (result) { + if (result.status) { + $.each(result.deleted_ids, function (i, idImage) { + $('#hotel-image-table tr[data-id-image="' + idImage + '"]').fadeOut().remove(); + }); + if (result.new_cover_row) { + $('#hotel-image-table tr[data-id-image="' + result.new_cover_id + '"]').replaceWith(result.new_cover_row); + initHotelImagePreview(); + } + showEmptyRowIfNoImagesLeft(); + $('.hotel-image-checkbox').prop('checked', false); + showSuccessMessage(deleteImgSuccessMsg); + } else { + showErrorMessage((result.errors && result.errors.join('
')) || deleteImgErrorMsg); + } + }, + error: function () { + showErrorMessage(deleteImgErrorMsg); + } + }).always(function () { + $('#page-loader').hide(); + }); + return; + } + + var triggerElement = pendingDeleteHotelImage; + if (!triggerElement) { + return; + } + + var idHotel = triggerElement.attr('data-id-hotel'); + var idImage = triggerElement.attr('data-id-image'); if (parseInt(idHotel) && parseInt(idImage)) { + $('#page-loader').show(); $.ajax({ type:'POST', url: adminHotelCtrlUrl, @@ -159,19 +388,16 @@ $(document).ready(function () { }, success: function(result) { if (result.status) { - if (parseInt(isCover)) { - location.reload(); - } else { - var currentPosition = parseInt(triggerElement.parents('tr').find('td.image-position').text()); - var nextAllSiblings = triggerElement.parents('tr').nextAll(); - triggerElement.parents('tr').fadeOut().remove(); + triggerElement.parents('tr').fadeOut().remove(); - // Correct Images Positions - $(nextAllSiblings).each(function(index, element) { - $(this).find('td.image-position').text(parseInt(currentPosition + parseInt(index))); - }); - showSuccessMessage(deleteImgSuccessMsg); + if (result.new_cover_row) { + $('#hotel-image-table tr[data-id-image="' + result.new_cover_id + '"]').replaceWith(result.new_cover_row); + initHotelImagePreview(); } + + showEmptyRowIfNoImagesLeft(); + + showSuccessMessage(deleteImgSuccessMsg); } else { showErrorMessage(deleteImgErrorMsg); } @@ -179,9 +405,11 @@ $(document).ready(function () { error: function(data){ showErrorMessage(deleteImgErrorMsg); } + }).always(function () { + $('#page-loader').hide(); }); } else { showErrorMessage(deleteImgErrorMsg); } }); -}); \ No newline at end of file +}); diff --git a/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list-row.tpl b/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list-row.tpl index 4a28112c7..700f21f24 100644 --- a/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list-row.tpl +++ b/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list-row.tpl @@ -20,16 +20,25 @@ * @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0 *} - +{assign var="isCoverImage" value=$image.cover == 1} + + {$image.id|escape:'html':'UTF-8'} - - - {if $image.cover == 1} + + {if isset($image.category_name) && $image.category_name} + {$image.category_name|escape:'html':'UTF-8'} + {else} + — + {/if} + + + + {if $isCoverImage} {else} @@ -37,6 +46,7 @@ - + + - \ No newline at end of file + diff --git a/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list.tpl b/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list.tpl index d03600bda..a5eadc833 100644 --- a/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list.tpl +++ b/modules/hotelreservationsystem/views/templates/admin/add_hotel/_partials/htl-images-list.tpl @@ -24,8 +24,10 @@ + + @@ -35,16 +37,183 @@ {foreach from=$hotelImages item=image name=hotelImage} {include file="./htl-images-list-row.tpl"} {/foreach} - {else} - - - {/if} + + +
  {l s='Image Id' mod='hotelreservationsystem'} {l s='Image' mod='hotelreservationsystem'}{l s='Category' mod='hotelreservationsystem'} {l s='Cover' mod='hotelreservationsystem'} {l s='Action' mod='hotelreservationsystem'}
-
- - {l s='No Image Found' mod='hotelreservationsystem'} -
-
+
+ + {l s='No Image Found' mod='hotelreservationsystem'} +
+
- \ No newline at end of file + +
+ + +
+ + + + + + + + diff --git a/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl b/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl index 244a174f2..fbbaf8fc1 100644 --- a/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl +++ b/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl @@ -30,6 +30,7 @@
+ {if isset($edit)} {assign var=hook_arg_id_hotel value=$hotel_info.id} {else} @@ -286,6 +287,18 @@ +
+ +
+ +
+
+
+ +
+ +
+