From 6f5414a86a6961c6fdb93bf6a1225e3a1c19ade4 Mon Sep 17 00:00:00 2001 From: QS5ELkMu Date: Thu, 26 Jul 2018 13:15:29 +0200 Subject: [PATCH] [WIP][MIG][11.0] Hotel Calendar & Hotel Channel Connector --- hotel_calendar/__init__.py | 5 + hotel_calendar/__manifest__.py | 45 + hotel_calendar/controllers/__init__.py | 3 + hotel_calendar/controllers/bus.py | 21 + hotel_calendar/data/menus.xml | 27 + hotel_calendar/data/records.xml | 81 + hotel_calendar/data/views.xml | 27 + hotel_calendar/i18n/es.po | 1227 +++++++ hotel_calendar/models/__init__.py | 16 + hotel_calendar/models/bus_hotel_calendar.py | 145 + .../models/hotel_calendar_management.py | 328 ++ .../models/inherited_hotel_folio.py | 17 + .../models/inherited_hotel_reservation.py | 384 +++ hotel_calendar/models/inherited_hotel_room.py | 9 + .../models/inherited_hotel_virtual_room.py | 21 + ...herited_hotel_virtual_room_availability.py | 51 + ...ted_hotel_virtual_room_restriction_item.py | 93 + .../inherited_ir_actions_act_window_view.py | 8 + hotel_calendar/models/inherited_ir_default.py | 36 + hotel_calendar/models/inherited_ir_ui_view.py | 8 + .../models/inherited_product_pricelist.py | 33 + .../inherited_product_pricelist_item.py | 155 + hotel_calendar/models/inherited_res_users.py | 82 + hotel_calendar/models/res_config.py | 166 + .../models/virtual_room_pricelist_cached.py | 17 + hotel_calendar/readme/CONTRIBUTORS.rst | 1 + hotel_calendar/readme/DESCRIPTION.rst | 8 + hotel_calendar/readme/ROADMAP.rst | 2 + hotel_calendar/readme/USAGE.rst | 5 + hotel_calendar/security/ir.model.access.csv | 5 + .../static/description/eiqui_logo.png | Bin 0 -> 6240 bytes .../static/description/icon_calendar.png | Bin 0 -> 4155 bytes .../icon_calendar_configurator.png | Bin 0 -> 5221 bytes hotel_calendar/static/description/index.html | 22 + hotel_calendar/static/src/css/view.css | 96 + ...open_reservation_wizard_listview_button.js | 28 + .../calendar/hotel_calendar_controller.js | 304 ++ .../js/views/calendar/hotel_calendar_model.js | 119 + .../views/calendar/hotel_calendar_renderer.js | 840 +++++ .../js/views/calendar/hotel_calendar_view.js | 211 ++ .../hotel_calendar_management_controller.js | 174 + .../hotel_calendar_management_model.js | 68 + .../hotel_calendar_management_renderer.js | 526 +++ .../hotel_calendar_management_v.js | 661 ++++ .../hotel_calendar_management_view.js | 93 + .../static/src/js/views/constants.js | 20 + hotel_calendar/static/src/lib/bootbox.js | 985 ++++++ .../src/lib/hcalendar/css/hcalendar.css | 499 +++ .../hcalendar/css/hcalendar_management.css | 177 + .../static/src/lib/hcalendar/js/hcalendar.js | 2844 +++++++++++++++++ .../lib/hcalendar/js/hcalendar_management.js | 1088 +++++++ hotel_calendar/static/src/lib/moment.js | 551 ++++ .../xml/hotel_calendar_management_view.xml | 94 + .../src/xml/hotel_calendar_templates.xml | 168 + .../static/src/xml/hotel_calendar_view.xml | 101 + hotel_calendar/tests/__init__.py | 5 + hotel_calendar/tests/common.py | 41 + .../tests/test_management_calendar.py | 425 +++ .../tests/test_product_pricelist.py | 66 + .../tests/test_reservations_calendar.py | 289 ++ hotel_calendar/views/actions.xml | 27 + hotel_calendar/views/general.xml | 32 + .../views/inherited_hotel_room_views.xml | 14 + .../inherited_hotel_virtual_room_views.xml | 14 + .../views/inherited_res_users_views.xml | 43 + hotel_calendar/views/res_config_views.xml | 35 + .../virtual_room_pricelist_cached_views.xml | 35 + hotel_calendar/wizard/__init__.py | 1 + hotel_calendar/wizard/wizard_reservation.py | 584 ++++ hotel_calendar/wizard/wizard_reservation.xml | 101 + hotel_calendar_channel_connector/README.rst | 15 + hotel_calendar_channel_connector/__init__.py | 22 + .../__manifest__.py | 53 + hotel_calendar_channel_connector/i18n/es.po | 111 + .../models/__init__.py | 25 + .../models/inherited_bus_hotel_calendar.py | 63 + .../inherited_hotel_calendar_management.py | 45 + .../models/inherited_hotel_reservation.py | 122 + .../models/inherited_wubook_issue.py | 37 + .../static/description/eiqui_logo.png | Bin 0 -> 6240 bytes .../static/description/index.html | 22 + .../static/sfx/book_cancelled.mp3 | Bin 0 -> 10152 bytes .../static/sfx/book_new.mp3 | Bin 0 -> 10176 bytes .../static/src/css/view.css | 50 + .../src/js/views/hotel_calendar_controller.js | 87 + .../src/js/views/hotel_calendar_model.js | 119 + .../src/js/views/hotel_calendar_renderer.js | 60 + .../src/xml/hotel_calendar_templates.xml | 14 + .../static/src/xml/hotel_calendar_view.xml | 29 + .../tests/__init__.py | 23 + .../tests/test_folio.py | 31 + .../views/actions.xml | 23 + .../views/general.xml | 12 + .../views/hotel_reservation.xml | 85 + hotel_channel_connector/README.rst | 18 + hotel_channel_connector/__init__.py | 25 + hotel_channel_connector/__manifest__.py | 68 + .../controllers/__init__.py | 22 + hotel_channel_connector/controllers/main.py | 121 + hotel_channel_connector/data/cron_jobs.xml | 26 + hotel_channel_connector/data/menus.xml | 42 + hotel_channel_connector/data/sequences.xml | 13 + hotel_channel_connector/i18n/es.po | 1121 +++++++ hotel_channel_connector/models/__init__.py | 33 + .../models/hotel_channel_connector_issue.py | 71 + .../models/inherited_hotel_folio.py | 108 + .../models/inherited_hotel_reservation.py | 263 ++ .../models/inherited_hotel_virtual_room.py | 128 + .../models/inherited_product_pricelist.py | 153 + .../inherited_product_pricelist_item.py | 73 + .../models/inherited_res_partner.py | 71 + .../inherited_reservation_restriction.py | 144 + .../inherited_reservation_restriction_item.py | 46 + .../inherited_virtual_room_availability.py | 132 + hotel_channel_connector/models/res_config.py | 234 ++ .../models/wubook_channel_info.py | 34 + .../security/ir.model.access.csv | 6 + .../security/wubook_security.xml | 21 + .../static/description/eiqui_logo.png | Bin 0 -> 6240 bytes .../static/description/index.html | 22 + .../src/js/wubook_listview_import_buttons.js | 189 ++ hotel_channel_connector/tests/__init__.py | 35 + hotel_channel_connector/tests/common.py | 310 ++ .../test_hotel_calendar_management_model.py | 152 + .../tests/test_hotel_folio_model.py | 125 + .../tests/test_hotel_reservation_model.py | 181 ++ .../tests/test_hotel_virtual_room_model.py | 73 + .../test_product_pricelist_item_model.py | 75 + .../tests/test_product_pricelist_model.py | 70 + .../tests/test_res_partner_model.py | 84 + ...test_reservation_restriction_item_model.py | 45 + .../test_reservation_restriction_model.py | 99 + .../test_virtual_room_availability_model.py | 43 + hotel_channel_connector/tests/test_wubook.py | 608 ++++ .../tests/test_wubook_channel_info_model.py | 38 + .../tests/test_wubook_issue_model.py | 57 + hotel_channel_connector/views/general.xml | 11 + .../views/inherited_hotel_folio_views.xml | 42 + .../inherited_hotel_reservation_views.xml | 112 + ..._hotel_virtual_room_availability_views.xml | 26 + .../inherited_hotel_virtual_room_views.xml | 16 + ...inherited_product_pricelist_item_views.xml | 19 + .../inherited_product_pricelist_views.xml | 31 + .../views/inherited_res_partner_views.xml | 18 + ...ted_reservation_restriction_item_views.xml | 14 + ...nherited_reservation_restriction_views.xml | 20 + .../views/res_config_views.xml | 43 + .../views/wubook_channel_info_views.xml | 33 + .../views/wubook_issue_views.xml | 71 + hotel_channel_connector/wizard/__init__.py | 28 + .../wizard/inherited_duplicate_reservation.py | 35 + .../wizard/inherited_massive_changes.py | 43 + ...nherited_massive_price_reservation_days.py | 41 + .../wizard/wubook_import_availability.py | 45 + .../wizard/wubook_import_availability.xml | 40 + .../wizard/wubook_import_plan_prices.py | 49 + .../wizard/wubook_import_plan_prices.xml | 37 + .../wizard/wubook_import_plan_restrictions.py | 54 + .../wubook_import_plan_restrictions.xml | 38 + .../wizard/wubook_installer.py | 156 + .../wizard/wubook_installer.xml | 90 + hotel_channel_connector/wubook.py | 1760 ++++++++++ 162 files changed, 23506 insertions(+) create mode 100644 hotel_calendar/__init__.py create mode 100644 hotel_calendar/__manifest__.py create mode 100644 hotel_calendar/controllers/__init__.py create mode 100644 hotel_calendar/controllers/bus.py create mode 100644 hotel_calendar/data/menus.xml create mode 100644 hotel_calendar/data/records.xml create mode 100644 hotel_calendar/data/views.xml create mode 100644 hotel_calendar/i18n/es.po create mode 100644 hotel_calendar/models/__init__.py create mode 100644 hotel_calendar/models/bus_hotel_calendar.py create mode 100644 hotel_calendar/models/hotel_calendar_management.py create mode 100644 hotel_calendar/models/inherited_hotel_folio.py create mode 100644 hotel_calendar/models/inherited_hotel_reservation.py create mode 100644 hotel_calendar/models/inherited_hotel_room.py create mode 100644 hotel_calendar/models/inherited_hotel_virtual_room.py create mode 100644 hotel_calendar/models/inherited_hotel_virtual_room_availability.py create mode 100644 hotel_calendar/models/inherited_hotel_virtual_room_restriction_item.py create mode 100644 hotel_calendar/models/inherited_ir_actions_act_window_view.py create mode 100644 hotel_calendar/models/inherited_ir_default.py create mode 100644 hotel_calendar/models/inherited_ir_ui_view.py create mode 100644 hotel_calendar/models/inherited_product_pricelist.py create mode 100644 hotel_calendar/models/inherited_product_pricelist_item.py create mode 100644 hotel_calendar/models/inherited_res_users.py create mode 100644 hotel_calendar/models/res_config.py create mode 100644 hotel_calendar/models/virtual_room_pricelist_cached.py create mode 100644 hotel_calendar/readme/CONTRIBUTORS.rst create mode 100644 hotel_calendar/readme/DESCRIPTION.rst create mode 100644 hotel_calendar/readme/ROADMAP.rst create mode 100644 hotel_calendar/readme/USAGE.rst create mode 100644 hotel_calendar/security/ir.model.access.csv create mode 100644 hotel_calendar/static/description/eiqui_logo.png create mode 100644 hotel_calendar/static/description/icon_calendar.png create mode 100644 hotel_calendar/static/description/icon_calendar_configurator.png create mode 100644 hotel_calendar/static/description/index.html create mode 100644 hotel_calendar/static/src/css/view.css create mode 100644 hotel_calendar/static/src/js/open_reservation_wizard_listview_button.js create mode 100644 hotel_calendar/static/src/js/views/calendar/hotel_calendar_controller.js create mode 100644 hotel_calendar/static/src/js/views/calendar/hotel_calendar_model.js create mode 100644 hotel_calendar/static/src/js/views/calendar/hotel_calendar_renderer.js create mode 100644 hotel_calendar/static/src/js/views/calendar/hotel_calendar_view.js create mode 100644 hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_controller.js create mode 100644 hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_model.js create mode 100644 hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_renderer.js create mode 100644 hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_v.js create mode 100644 hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_view.js create mode 100644 hotel_calendar/static/src/js/views/constants.js create mode 100644 hotel_calendar/static/src/lib/bootbox.js create mode 100644 hotel_calendar/static/src/lib/hcalendar/css/hcalendar.css create mode 100644 hotel_calendar/static/src/lib/hcalendar/css/hcalendar_management.css create mode 100644 hotel_calendar/static/src/lib/hcalendar/js/hcalendar.js create mode 100644 hotel_calendar/static/src/lib/hcalendar/js/hcalendar_management.js create mode 100644 hotel_calendar/static/src/lib/moment.js create mode 100644 hotel_calendar/static/src/xml/hotel_calendar_management_view.xml create mode 100644 hotel_calendar/static/src/xml/hotel_calendar_templates.xml create mode 100644 hotel_calendar/static/src/xml/hotel_calendar_view.xml create mode 100644 hotel_calendar/tests/__init__.py create mode 100644 hotel_calendar/tests/common.py create mode 100644 hotel_calendar/tests/test_management_calendar.py create mode 100644 hotel_calendar/tests/test_product_pricelist.py create mode 100644 hotel_calendar/tests/test_reservations_calendar.py create mode 100644 hotel_calendar/views/actions.xml create mode 100644 hotel_calendar/views/general.xml create mode 100644 hotel_calendar/views/inherited_hotel_room_views.xml create mode 100644 hotel_calendar/views/inherited_hotel_virtual_room_views.xml create mode 100644 hotel_calendar/views/inherited_res_users_views.xml create mode 100644 hotel_calendar/views/res_config_views.xml create mode 100644 hotel_calendar/views/virtual_room_pricelist_cached_views.xml create mode 100644 hotel_calendar/wizard/__init__.py create mode 100644 hotel_calendar/wizard/wizard_reservation.py create mode 100644 hotel_calendar/wizard/wizard_reservation.xml create mode 100644 hotel_calendar_channel_connector/README.rst create mode 100644 hotel_calendar_channel_connector/__init__.py create mode 100644 hotel_calendar_channel_connector/__manifest__.py create mode 100644 hotel_calendar_channel_connector/i18n/es.po create mode 100644 hotel_calendar_channel_connector/models/__init__.py create mode 100644 hotel_calendar_channel_connector/models/inherited_bus_hotel_calendar.py create mode 100644 hotel_calendar_channel_connector/models/inherited_hotel_calendar_management.py create mode 100644 hotel_calendar_channel_connector/models/inherited_hotel_reservation.py create mode 100644 hotel_calendar_channel_connector/models/inherited_wubook_issue.py create mode 100644 hotel_calendar_channel_connector/static/description/eiqui_logo.png create mode 100644 hotel_calendar_channel_connector/static/description/index.html create mode 100644 hotel_calendar_channel_connector/static/sfx/book_cancelled.mp3 create mode 100644 hotel_calendar_channel_connector/static/sfx/book_new.mp3 create mode 100644 hotel_calendar_channel_connector/static/src/css/view.css create mode 100644 hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_controller.js create mode 100644 hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_model.js create mode 100644 hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_renderer.js create mode 100644 hotel_calendar_channel_connector/static/src/xml/hotel_calendar_templates.xml create mode 100644 hotel_calendar_channel_connector/static/src/xml/hotel_calendar_view.xml create mode 100644 hotel_calendar_channel_connector/tests/__init__.py create mode 100644 hotel_calendar_channel_connector/tests/test_folio.py create mode 100644 hotel_calendar_channel_connector/views/actions.xml create mode 100644 hotel_calendar_channel_connector/views/general.xml create mode 100644 hotel_calendar_channel_connector/views/hotel_reservation.xml create mode 100644 hotel_channel_connector/README.rst create mode 100644 hotel_channel_connector/__init__.py create mode 100644 hotel_channel_connector/__manifest__.py create mode 100644 hotel_channel_connector/controllers/__init__.py create mode 100644 hotel_channel_connector/controllers/main.py create mode 100644 hotel_channel_connector/data/cron_jobs.xml create mode 100644 hotel_channel_connector/data/menus.xml create mode 100644 hotel_channel_connector/data/sequences.xml create mode 100644 hotel_channel_connector/i18n/es.po create mode 100644 hotel_channel_connector/models/__init__.py create mode 100644 hotel_channel_connector/models/hotel_channel_connector_issue.py create mode 100644 hotel_channel_connector/models/inherited_hotel_folio.py create mode 100644 hotel_channel_connector/models/inherited_hotel_reservation.py create mode 100644 hotel_channel_connector/models/inherited_hotel_virtual_room.py create mode 100644 hotel_channel_connector/models/inherited_product_pricelist.py create mode 100644 hotel_channel_connector/models/inherited_product_pricelist_item.py create mode 100644 hotel_channel_connector/models/inherited_res_partner.py create mode 100644 hotel_channel_connector/models/inherited_reservation_restriction.py create mode 100644 hotel_channel_connector/models/inherited_reservation_restriction_item.py create mode 100644 hotel_channel_connector/models/inherited_virtual_room_availability.py create mode 100644 hotel_channel_connector/models/res_config.py create mode 100644 hotel_channel_connector/models/wubook_channel_info.py create mode 100644 hotel_channel_connector/security/ir.model.access.csv create mode 100644 hotel_channel_connector/security/wubook_security.xml create mode 100644 hotel_channel_connector/static/description/eiqui_logo.png create mode 100644 hotel_channel_connector/static/description/index.html create mode 100644 hotel_channel_connector/static/src/js/wubook_listview_import_buttons.js create mode 100644 hotel_channel_connector/tests/__init__.py create mode 100644 hotel_channel_connector/tests/common.py create mode 100644 hotel_channel_connector/tests/test_hotel_calendar_management_model.py create mode 100644 hotel_channel_connector/tests/test_hotel_folio_model.py create mode 100644 hotel_channel_connector/tests/test_hotel_reservation_model.py create mode 100644 hotel_channel_connector/tests/test_hotel_virtual_room_model.py create mode 100644 hotel_channel_connector/tests/test_product_pricelist_item_model.py create mode 100644 hotel_channel_connector/tests/test_product_pricelist_model.py create mode 100644 hotel_channel_connector/tests/test_res_partner_model.py create mode 100644 hotel_channel_connector/tests/test_reservation_restriction_item_model.py create mode 100644 hotel_channel_connector/tests/test_reservation_restriction_model.py create mode 100644 hotel_channel_connector/tests/test_virtual_room_availability_model.py create mode 100644 hotel_channel_connector/tests/test_wubook.py create mode 100644 hotel_channel_connector/tests/test_wubook_channel_info_model.py create mode 100644 hotel_channel_connector/tests/test_wubook_issue_model.py create mode 100644 hotel_channel_connector/views/general.xml create mode 100644 hotel_channel_connector/views/inherited_hotel_folio_views.xml create mode 100644 hotel_channel_connector/views/inherited_hotel_reservation_views.xml create mode 100644 hotel_channel_connector/views/inherited_hotel_virtual_room_availability_views.xml create mode 100644 hotel_channel_connector/views/inherited_hotel_virtual_room_views.xml create mode 100644 hotel_channel_connector/views/inherited_product_pricelist_item_views.xml create mode 100644 hotel_channel_connector/views/inherited_product_pricelist_views.xml create mode 100644 hotel_channel_connector/views/inherited_res_partner_views.xml create mode 100644 hotel_channel_connector/views/inherited_reservation_restriction_item_views.xml create mode 100644 hotel_channel_connector/views/inherited_reservation_restriction_views.xml create mode 100644 hotel_channel_connector/views/res_config_views.xml create mode 100644 hotel_channel_connector/views/wubook_channel_info_views.xml create mode 100644 hotel_channel_connector/views/wubook_issue_views.xml create mode 100644 hotel_channel_connector/wizard/__init__.py create mode 100644 hotel_channel_connector/wizard/inherited_duplicate_reservation.py create mode 100644 hotel_channel_connector/wizard/inherited_massive_changes.py create mode 100644 hotel_channel_connector/wizard/inherited_massive_price_reservation_days.py create mode 100644 hotel_channel_connector/wizard/wubook_import_availability.py create mode 100644 hotel_channel_connector/wizard/wubook_import_availability.xml create mode 100644 hotel_channel_connector/wizard/wubook_import_plan_prices.py create mode 100644 hotel_channel_connector/wizard/wubook_import_plan_prices.xml create mode 100644 hotel_channel_connector/wizard/wubook_import_plan_restrictions.py create mode 100644 hotel_channel_connector/wizard/wubook_import_plan_restrictions.xml create mode 100644 hotel_channel_connector/wizard/wubook_installer.py create mode 100644 hotel_channel_connector/wizard/wubook_installer.xml create mode 100644 hotel_channel_connector/wubook.py diff --git a/hotel_calendar/__init__.py b/hotel_calendar/__init__.py new file mode 100644 index 000000000..b3576e732 --- /dev/null +++ b/hotel_calendar/__init__.py @@ -0,0 +1,5 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from . import models +from . import controllers +from . import wizard diff --git a/hotel_calendar/__manifest__.py b/hotel_calendar/__manifest__.py new file mode 100644 index 000000000..15e0b71cf --- /dev/null +++ b/hotel_calendar/__manifest__.py @@ -0,0 +1,45 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +{ + 'name': 'Hotel Calendar', + 'version': '11.0.2.0', + 'author': "Alexandre Díaz ", + 'website': 'https://www.eiqui.com', + 'category': 'hotel/calendar', + 'summary': "Hotel Calendar", + 'description': "Hotel Calendar", + 'depends': [ + 'bus', + 'web', + 'calendar', + 'hotel', + 'web_widget_color', + ], + 'external_dependencies': { + 'python': [] + }, + 'data': [ + 'views/general.xml', + 'views/actions.xml', + 'views/res_config_views.xml', + 'views/inherited_res_users_views.xml', + 'views/inherited_hotel_virtual_room_views.xml', + 'views/inherited_hotel_room_views.xml', + 'views/virtual_room_pricelist_cached_views.xml', + 'data/views.xml', + 'data/menus.xml', + 'data/records.xml', + 'security/ir.model.access.csv', + 'wizard/wizard_reservation.xml' + ], + 'qweb': [ + 'static/src/xml/*.xml', + ], + 'test': [ + ], + + 'installable': True, + 'auto_install': False, + 'license': 'AGPL-3', +} diff --git a/hotel_calendar/controllers/__init__.py b/hotel_calendar/controllers/__init__.py new file mode 100644 index 000000000..de7342fae --- /dev/null +++ b/hotel_calendar/controllers/__init__.py @@ -0,0 +1,3 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from . import bus diff --git a/hotel_calendar/controllers/bus.py b/hotel_calendar/controllers/bus.py new file mode 100644 index 000000000..ebb36b2e8 --- /dev/null +++ b/hotel_calendar/controllers/bus.py @@ -0,0 +1,21 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo.http import request +from odoo.addons.bus.controllers.main import BusController + +HOTEL_BUS_CHANNEL_ID = 'hpublic' + + +# More info... +# https://github.com/odoo/odoo/commit/092cf33f93830daf5e704b964724bdf8586da8d9 +class Controller(BusController): + def _poll(self, dbname, channels, last, options): + if request.session.uid: + # registry, cr, uid, context = request.registry, request.cr, \ + # request.session.uid, request.context + channels = channels + [( + request.db, + 'hotel.reservation', + HOTEL_BUS_CHANNEL_ID + )] + return super(Controller, self)._poll(dbname, channels, last, options) diff --git a/hotel_calendar/data/menus.xml b/hotel_calendar/data/menus.xml new file mode 100644 index 000000000..9a8ac6ed1 --- /dev/null +++ b/hotel_calendar/data/menus.xml @@ -0,0 +1,27 @@ + + + + + Hotel Calendar + hotel.reservation + pms + + + + Hotel Calendar Management + hotel.calendar.management + mpms + + + + + + + + + diff --git a/hotel_calendar/data/records.xml b/hotel_calendar/data/records.xml new file mode 100644 index 000000000..0958ac134 --- /dev/null +++ b/hotel_calendar/data/records.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hotel_calendar/data/views.xml b/hotel_calendar/data/views.xml new file mode 100644 index 000000000..78f51aac4 --- /dev/null +++ b/hotel_calendar/data/views.xml @@ -0,0 +1,27 @@ + + + + + + Hotel Calendar + hotel.reservation + + form + + +
+
+
+
+ + + Hotel Calendar Management + hotel.calendar.management + form + +
+
+
+ +
diff --git a/hotel_calendar/i18n/es.po b/hotel_calendar/i18n/es.po new file mode 100644 index 000000000..07485b17f --- /dev/null +++ b/hotel_calendar/i18n/es.po @@ -0,0 +1,1227 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * hotel_calendar +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 10.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2018-04-15 07:33+0000\n" +"PO-Revision-Date: 2018-04-15 09:41+0200\n" +"Last-Translator: <>\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: \n" +"Language: es\n" +"X-Generator: Poedit 1.8.7.1\n" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:13 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:73 +#, python-format +msgid " " +msgstr " " + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "0 Days" +msgstr "0 Días" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "1 Days" +msgstr "1 Día" + +#. module: hotel_calendar +#: selection:res.users,npms_default_num_days:0 +#: selection:res.users,pms_default_num_days:0 +msgid "1 Month" +msgstr "1 Mes" + +#. module: hotel_calendar +#: selection:res.users,npms_default_num_days:0 +#: selection:res.users,pms_default_num_days:0 +msgid "1 Week" +msgstr "1 Semana" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "2 Days" +msgstr "2 Días" + +#. module: hotel_calendar +#: selection:res.users,npms_default_num_days:0 +#: selection:res.users,pms_default_num_days:0 +msgid "2 Weeks" +msgstr "2 Semanas" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "3 Days" +msgstr "3 Días" + +#. module: hotel_calendar +#: selection:res.users,npms_default_num_days:0 +#: selection:res.users,pms_default_num_days:0 +msgid "3 Weeks" +msgstr "3 Semanas" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "4 Days" +msgstr "4 Días" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "5 Days" +msgstr "5 Días" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week_offset:0 +#: selection:res.users,pms_end_day_week_offset:0 +msgid "6 Days" +msgstr "6 Días" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:67 +#, python-format +msgid "AMENITIES:" +msgstr "CARACTERISTICAS:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_adults +msgid "Adults" +msgstr "Adultos" + +#. module: hotel_calendar +#: selection:res.users,pms_type_move:0 +msgid "Allow Invalid" +msgstr "Permitir Inválidas" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_npms_end_day_week_offset +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_end_day_week_offset +msgid "Also illuminate the previous" +msgstr "Sombrear también los previos" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:47 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:56 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:64 +#, python-format +msgid "Are you sure you want to make this changes?" +msgstr "¿Estás seguo de que quieres confirmar estos cambios?" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:72 +#, python-format +msgid "Arrival Hour:" +msgstr "Hora de Llegada:" + +#. module: hotel_calendar +#: selection:res.users,pms_type_move:0 +msgid "Assisted" +msgstr "Asistido" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Back" +msgstr "Volver" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:85 +#, python-format +msgid "Belongs to the Virtual Rooms:" +msgstr "Incluida en las Habitaciones Virtuales:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:27 +#, python-format +msgid "CHARGES" +msgstr "CARGOS" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:23 +#, python-format +msgid "CHECK-IN" +msgstr "CHECK-IN" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:19 +#, python-format +msgid "CHECK-OUT" +msgstr "CHECK-OUT" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:986 +#, python-format +msgid "CONTINUE" +msgstr "CONTINUAR" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.view_users_form +msgid "Calendar (PMS)" +msgstr "Calendario (PMS)" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.view_users_form +msgid "Calendar Management (Revenue PMS)" +msgstr "Calendario de Gestión (Revenue PMS)" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_room_hcal_sequence +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_virtual_room_hcal_sequence +msgid "Calendar Sequence" +msgstr "Orden Calendario" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:140 +#, python-format +msgid "Calendar Settings" +msgstr "Configuración Calendario" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.view_hotel_config_settings +msgid "Calendar colors" +msgstr "Colores del Calendario" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_checkin +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_checkin +msgid "Check In" +msgstr "Check In" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_checkout +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_checkout +msgid "Check Out" +msgstr "Check Out" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:125 +#, python-format +msgid "Check-In:" +msgstr "Entrada:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:126 +#, python-format +msgid "Check-Out:" +msgstr "Salida:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_stay +msgid "Checkin" +msgstr "Entrada" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:12 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:31 +#, python-format +msgid "Checkin:" +msgstr "Entrada:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_checkout +msgid "Checkout" +msgstr "Salida" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:15 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:34 +#, python-format +msgid "Checkout:" +msgstr "Salida" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_children +msgid "Children" +msgstr "Niños" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:110 +#, python-format +msgid "Closed Arrival:" +msgstr "Cerrar Llegada:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:111 +#, python-format +msgid "Closed Departure:" +msgstr "Cerrar Salida:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:109 +#, python-format +msgid "Closed:" +msgstr "Cerrado:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:566 +#, python-format +msgid "Confirm Folio" +msgstr "Confirmar Ficha" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:261 +#, python-format +msgid "Confirm Price Change" +msgstr "Confirmar Cambio de Precio" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:401 +#, python-format +msgid "Confirm Reservation Changes" +msgstr "Confirmar Reserva Cambios" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:322 +#, python-format +msgid "Confirm Reservation Swap" +msgstr "Confirm Reservation Swap" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_confirm +msgid "Confirm Reservations" +msgstr "Confirmar Reservas" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_reservation +msgid "Confirmed Reservation " +msgstr "Reserva Confirmada" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Create Reservations" +msgstr "Crear Reservas" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:541 +#, python-format +msgid "Create: " +msgstr "Creado: " + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar_create_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management_create_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_create_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_create_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_create_uid +msgid "Created by" +msgstr "Creado por" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar_create_date +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management_create_date +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_create_date +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_create_date +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_create_date +msgid "Created on" +msgstr "Creado en" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:54 +#, python-format +msgid "Current Price:" +msgstr "Precio Actual:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_partner_id +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_partner_id +msgid "Customer" +msgstr "Cliente" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_date +msgid "Date" +msgstr "Fecha" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_npms_default_num_days +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_default_num_days +msgid "Default number of days" +msgstr "Num. por defecto de días" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar_display_name +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management_display_name +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_display_name +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_display_name +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_display_name +msgid "Display Name" +msgstr "Mostrar Nombre" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_divide_rooms_by_capacity +msgid "Divide rooms by capacity" +msgstr "Dividir las filas por capacidad" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:117 +#, python-format +msgid "Do you want to confirm this folio?" +msgstr "Deseas confirmar la ficha?" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:134 +#, python-format +msgid "Do you want to save these changes?" +msgstr "Deseas confirmar la ficha?" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_dontsell +msgid "Dont Sell" +msgstr "No vender" + +#. module: hotel_calendar +#: selection:hotel.folio.wizard,channel_type:0 +msgid "Door" +msgstr "Puerta" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:993 +#, python-format +msgid "END" +msgstr "END" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_npms_end_day_week +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_end_day_week +msgid "End day of week" +msgstr "Último día de Semana" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:39 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:96 +#, python-format +msgid "FROM" +msgstr "DE" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_folio_wizard_id +msgid "Folio wizard id" +msgstr "Folio wizard id" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Friday" +msgstr "Viernes" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:133 +#, python-format +msgid "Have unsaved changes!" +msgstr "Tienes cambios sin guardar!" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:159 +#: model:ir.actions.act_window,name:hotel_calendar.action_hotel_calendar +#: model:ir.ui.menu,name:hotel_calendar.hotel_calendar_menu +#, python-format +msgid "Hotel Calendar" +msgstr "Calendario del Hotel" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_management_view.js:61 +#: model:ir.actions.act_window,name:hotel_calendar.action_hotel_calendar_management +#: model:ir.ui.menu,name:hotel_calendar.hotel_calendar_management_menu +#, python-format +msgid "Hotel Calendar Management" +msgstr "Calendario de Configuración del Hotel" + +#. module: hotel_calendar +#: model:ir.actions.act_window,name:hotel_calendar.open_wizard_reservations +msgid "Hotel Reservation Wizard" +msgstr "Wizard Hotel Reservas" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_room +msgid "Hotel Room" +msgstr "Habitaciones" + +#. module: hotel_calendar +#: model:ir.actions.act_window,name:hotel_calendar.hotel_reservation_action_checkin +msgid "Hotel folio checkin" +msgstr "Hotel Ficha Checkin" + +#. module: hotel_calendar +#: model:ir.actions.act_window,name:hotel_calendar.hotel_reservation_action_checkout +msgid "Hotel folio checkout" +msgstr "Hotel Ficha Checkout" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar_id +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management_id +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_id +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_id +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_id +msgid "ID" +msgstr "ID" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/hotel_calendar_management.py:253 +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:246 +#, python-format +msgid "Input Error: No dates defined!" +msgstr "Error de entrada: ¡no hay fechas definidas!" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:308 +#, python-format +msgid "Invalid swap parameters" +msgstr "Valores incorrectos para el swap" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:57 +#, python-format +msgid "LOCATION:" +msgstr "UBICACIÓN:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar___last_update +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management___last_update +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard___last_update +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard___last_update +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached___last_update +msgid "Last Modified on" +msgstr "Última modificación en" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar_write_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management_write_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_write_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_write_uid +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_write_uid +msgid "Last Updated by" +msgstr "Última actualización por" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_bus_hotel_calendar_write_date +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_calendar_management_write_date +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_write_date +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_write_date +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_write_date +msgid "Last Updated on" +msgstr "Última actualización en" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:72 +#, python-format +msgid "Launch Massive Changes" +msgstr "Guardar Cambios Masivos" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_reservation +msgid "Letter Confirmed Reservation " +msgstr "Texto Reserva Confirmada" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_pre_reservation +msgid "Letter Pre-reservation" +msgstr "Texto Pre-reserva" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_stay +msgid "Letter Checkin" +msgstr "Texto Checkin" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_checkout +msgid "Letter Checkout" +msgstr "Texto Checkout" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_dontsell +msgid "Letter Dont Sell" +msgstr "Texto Fuera de Servicio" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_to_assign +msgid "Letter Ota to Assign" +msgstr "Texto OTA por Asignar" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_reservation_pay +msgid "Letter Paid Reservation" +msgstr "Texto Reserva Pagada" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_payment_pending +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_payment_pending +msgid "Letter Payment Pending" +msgstr "Texto Pagos Pendientes" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_staff +msgid "Letter Staff" +msgstr "Texto Staff" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_letter_stay_pay +msgid "Letter Stay Pay" +msgstr "Texto Checkin Pagado" + +#. module: hotel_calendar +#: model:ir.model.fields,help:hotel_calendar.field_hotel_reservation_wizard_adults +msgid "List of adults there in guest list. " +msgstr "Adultos en la lista de huéspedes" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:137 +#, python-format +msgid "Loading Calendar..." +msgstr "Cargando Calendario" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:127 +#, python-format +msgid "Made by:" +msgstr "Hecho por:" + +#. module: hotel_calendar +#: selection:hotel.folio.wizard,channel_type:0 +msgid "Mail" +msgstr "Mail" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_max_rooms +msgid "Max" +msgstr "Max" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Max(" +msgstr "Max(" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:108 +#, python-format +msgid "Max. Stay Arrival:" +msgstr "Max. Est. Llegada:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:107 +#, python-format +msgid "Max. Stay:" +msgstr "Max. Estancia:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:106 +#, python-format +msgid "Min. Stay:" +msgstr "Min. Estancia:" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Monday" +msgstr "Lunes" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:123 +#, python-format +msgid "Name:" +msgstr "Nombre:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:55 +#, python-format +msgid "New Price:" +msgstr "Nuevo Precio:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_nights +msgid "Nights" +msgstr "Noches" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:101 +#, python-format +msgid "Nights:" +msgstr "Noches" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_management_view.js:545 +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:275 +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:361 +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:433 +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:581 +#, python-format +msgid "No" +msgstr "No" + +#. module: hotel_calendar +#: selection:res.users,pms_type_move:0 +msgid "Normal" +msgstr "Normal" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_rooms_num +msgid "Number of Rooms" +msgstr "Núm. de Habitaciones" + +#. module: hotel_calendar +#: model:ir.model.fields,help:hotel_calendar.field_hotel_reservation_wizard_children +msgid "Number of children there in guest list." +msgstr "Núm. de niños en la lista de huéspedes" + +#. module: hotel_calendar +#: selection:hotel.folio.wizard,channel_type:0 +msgid "OTA" +msgstr "OTA" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_to_assign +msgid "Ota Reservation to Assign" +msgstr "Reservas de OTA a Asignar" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:96 +#, python-format +msgid "Overbooking Management" +msgstr "Gestión de Overbooking" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:19 +#, python-format +msgid "PRICELIST:" +msgstr "Tarifas:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_stay_pay +msgid "Paid Checkin" +msgstr "Checkin Pagado:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_reservation_pay +msgid "Paid Reservation" +msgstr "Pagar Reserva" + +#. module: hotel_calendar +#: model:ir.actions.server,name:hotel_calendar.hotel_reservation_action_paydue +msgid "Paydue" +msgstr "Pago Pendiente" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_account_payment +msgid "Payments" +msgstr "Pagos" + +#. module: hotel_calendar +#: selection:hotel.folio.wizard,channel_type:0 +msgid "Phone" +msgstr "Teléfono" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:71 +#, python-format +msgid "Phone:" +msgstr "Teléfono:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_pre_reservation +msgid "Pre-reservation" +msgstr "Pre-reserva" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_price +msgid "Price" +msgstr "Precio" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:83 +#, python-format +msgid "Price From:" +msgstr "Precio desde:" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_product_pricelist +msgid "Pricelist" +msgstr "Tarifas" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_product_pricelist_item +msgid "Pricelist item" +msgstr "Elemento Tarifa" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:27 +#, python-format +msgid "RESTRICTIONS:" +msgstr "Restricciones" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:541 +#, python-format +msgid "Reservation" +msgstr "Reserva" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:349 +#, python-format +msgid "Reservation Cancelled" +msgstr "Reserva Cancelada" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:349 +#, python-format +msgid "Reservation Changed" +msgstr "Reserva Cambiada" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:333 +#, python-format +msgid "Reservation Created" +msgstr "Reserva Creada" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:359 +#, python-format +msgid "Reservation Deleted" +msgstr "Reserva Eliminada" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Reservation Wizard" +msgstr "Wizard Reservas" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_type_move +msgid "Reservation move mode" +msgstr "Modo de Movimiento de Reservas" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:28 +#, python-format +msgid "Reserve changed:" +msgstr "Reserva modificada:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:9 +#, python-format +msgid "Reserve unchanged:" +msgstr "Reserva no modificada:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_reservation_wizard_ids +msgid "Resevations" +msgstr "Resevas" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Room Line" +msgstr "Habitaciones Rerservadas" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Room Lines" +msgstr "Líneas de Habitaciones" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.hotel_folio_wizard +msgid "Room No" +msgstr "Habitación Nº" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:18 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:37 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:124 +#, python-format +msgid "Room:" +msgstr "Habitación:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:49 +#, python-format +msgid "SEGMENTATION:" +msgstr "SEGMENTACIÓN:" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:369 +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:1000 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:35 +#, python-format +msgid "START SWAP" +msgstr "INTERCAMBIO" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_channel_type +msgid "Sales Channel" +msgstr "Sales Channel" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Saturday" +msgstr "Sábado" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:12 +#, python-format +msgid "Save Changes" +msgstr "Guardar Cambios" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:511 +#, python-format +msgid "Select Partner" +msgstr "Seleccionar Huésped" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:153 +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_show_availability +#, python-format +msgid "Show Availability" +msgstr "Mostrar Disponibilidad" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:151 +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_show_notifications +#, python-format +msgid "Show Notifications" +msgstr "Mostrar Notificaciones" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_show_num_rooms +msgid "Show Num. Rooms" +msgstr "Num. Habitaciones a mostrar" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:152 +#: model:ir.model.fields,field_description:hotel_calendar.field_res_users_pms_show_pricelist +#, python-format +msgid "Show Pricelist" +msgstr "Mostrar Tarifas" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:74 +#, python-format +msgid "Splitted:" +msgstr "Dividida:" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_config_settings_color_staff +msgid "Staff" +msgstr "Staff" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Sunday" +msgstr "Domingo" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:63 +#, python-format +msgid "Swap Reservations" +msgstr "Intercambio reservas" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml:48 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:105 +#, python-format +msgid "TO" +msgstr "A" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:5 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:53 +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:62 +#, python-format +msgid "The following changes will be made..." +msgstr "Los próximos cambios serán realizados..." + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:6 +#, python-format +msgid "This reservation belongs to a folio with more reservations!" +msgstr "Esta reserva pertenece a un folio con más reservas!" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/wizard/wizard_reservation.py:305 +#, python-format +msgid "This room is occupied!, please, choice other room or change the reservation date" +msgstr "Esta habitación está ocupada!, elige otra habitación o cambia las fechas de reserva" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Thursday" +msgstr "Jueves" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:149 +#, python-format +msgid "Toggle Advance Controls" +msgstr "Mostrar Controles Avanzados (Alt+x)" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/wizard/wizard_reservation.py:169 +#, python-format +msgid "Too many rooms!" +msgstr "Demasiadas Habitaciones!" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_total +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_amount_reservation +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_price +msgid "Total" +msgstr "Total" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_templates.xml:77 +#, python-format +msgid "Total Amount:" +msgstr "Cantidad Total:" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Tuesday" +msgstr "Martes" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:72 +#: code:addons/hotel_calendar/models/inherited_hotel_reservation.py:296 +#, python-format +msgid "Undefined" +msgstr "Indefinido" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_management_view.js:533 +#, python-format +msgid "Unsaved Changes!" +msgstr "Cambios sin Guardar!" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_res_users +msgid "Users" +msgstr "Usuarios" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:75 +#, python-format +msgid "VIRTUAL TYPE:" +msgstr "TIPO VIRTUAL:" + +#. module: hotel_calendar +#: model:ir.ui.menu,name:hotel_calendar.hotel_virtual_room_pricelist_cached +msgid "VRoom Pricelist Cached" +msgstr "VRoom Pricelist Cached" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_virtual_room_pricelist_cached_virtual_room_id +msgid "Virtual Room" +msgstr "Habitación Virtual" + +#. module: hotel_calendar +#: model:ir.actions.act_window,name:hotel_calendar.hotel_virtual_room_pricelist_cached_action_form_tree +#: model:ir.ui.view,arch_db:hotel_calendar.view_hotel_virtual_room_pricelist_cached_form +#: model:ir.ui.view,arch_db:hotel_calendar.view_hotel_virtual_room_pricelist_cached_tree +msgid "Virtual Room Pricelist Cached" +msgstr "Lista de precios de la habitación virtual en caché" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_virtual_room_id +msgid "Virtual Room Type" +msgstr "Tipos de Habitaciones Virtuales" + +#. module: hotel_calendar +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_folio_wizard_virtual_room_id +#: model:ir.model.fields,field_description:hotel_calendar.field_hotel_reservation_wizard_product_id +msgid "Virtual Rooms" +msgstr "Habitaciones Virtuales" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/xml/hotel_calendar_view.xml:30 +#, python-format +msgid "WIZARD" +msgstr "WIZARD" + +#. module: hotel_calendar +#: code:addons/hotel_calendar/wizard/wizard_reservation.py:241 +#, python-format +msgid "We need know the customer!" +msgstr "Necesitamos conocer al cliente!" + +#. module: hotel_calendar +#: selection:hotel.folio.wizard,channel_type:0 +msgid "Web" +msgstr "Web" + +#. module: hotel_calendar +#: selection:res.users,npms_end_day_week:0 +#: selection:res.users,pms_end_day_week:0 +msgid "Wednesday" +msgstr "Miércoles" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:264 +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:404 +#, python-format +msgid "Yes, change it" +msgstr "Confirmar cambio" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:569 +#, python-format +msgid "Yes, confirm it" +msgstr "Confirmar" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_management_view.js:536 +#, python-format +msgid "Yes, save it" +msgstr "Confirmar" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:325 +#, python-format +msgid "Yes, swap it" +msgstr "Sí, Intercambiarlas" + +#. module: hotel_calendar +#. openerp-web +#: code:addons/hotel_calendar/static/src/js/hotel_calendar_view.js:576 +#, python-format +msgid "" +"[Hotel Calendar]\n" +"ERROR: Can't confirm folio!" +msgstr "" +"[Hotel Calendario]\n" +"ERROR: La ficha no puede ser confirmada!" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_bus_hotel_calendar +msgid "bus.hotel.calendar" +msgstr "bus.hotel.calendar" + +#. module: hotel_calendar +#: model:ir.ui.view,arch_db:hotel_calendar.view_hotel_config_settings +msgid "calendar" +msgstr "calendario" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_reservation +msgid "hotel reservation" +msgstr "Reserva" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_calendar_management +msgid "hotel.calendar.management" +msgstr "hotel.calendar.management" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_config_settings +msgid "hotel.config.settings" +msgstr "hotel.config.settings" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_folio_wizard +msgid "hotel.folio.wizard" +msgstr "hotel.folio.wizard" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_reservation_wizard +msgid "hotel.reservation.wizard" +msgstr "hotel.reservation.wizard" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_virtual_room +msgid "hotel.virtual.room" +msgstr "hotel.virtual.room" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_virtual_room_availability +msgid "hotel.virtual.room.availability" +msgstr "hotel.virtual.room.availability" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_hotel_virtual_room_restriction_item +msgid "hotel.virtual.room.restriction.item" +msgstr "hotel.virtual.room.restriction.item" + +#. module: hotel_calendar +#: model:ir.model,name:hotel_calendar.model_virtual_room_pricelist_cached +msgid "virtual.room.pricelist.cached" +msgstr "virtual.room.pricelist.cached" diff --git a/hotel_calendar/models/__init__.py b/hotel_calendar/models/__init__.py new file mode 100644 index 000000000..162b5fde3 --- /dev/null +++ b/hotel_calendar/models/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from . import inherited_hotel_reservation +from . import inherited_product_pricelist_item +from . import inherited_res_users +from . import bus_hotel_calendar +from . import virtual_room_pricelist_cached +from . import hotel_calendar_management +from . import res_config +from . import inherited_hotel_virtual_room +from . import inherited_hotel_room +from . import inherited_hotel_virtual_room_restriction_item +from . import inherited_hotel_virtual_room_availability +from . import inherited_product_pricelist +from . import inherited_hotel_folio +from . import inherited_ir_default diff --git a/hotel_calendar/models/bus_hotel_calendar.py b/hotel_calendar/models/bus_hotel_calendar.py new file mode 100644 index 000000000..96f296231 --- /dev/null +++ b/hotel_calendar/models/bus_hotel_calendar.py @@ -0,0 +1,145 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from datetime import datetime +from odoo.tools import DEFAULT_SERVER_DATE_FORMAT +from odoo import models, api +from odoo.addons.hotel_calendar.controllers.bus import HOTEL_BUS_CHANNEL_ID + + +class BusHotelCalendar(models.TransientModel): + _name = 'bus.hotel.calendar' + + ''' + action: + - create + - write + - unlink + - cancelled + ntype: + - notif : Show a normal notification + - warn : Show a warning notification + - noshow : Don't show any notification + ''' + @api.model + def _generate_reservation_notif(self, vals): + user_id = self.env['res.users'].browse(self.env.uid) + master_reserv = vals['parent_reservation'] or vals['reserv_id'] + num_split = self.env['hotel.reservation'].search_count([ + ('folio_id', '=', vals['folio_id']), + '|', ('parent_reservation', '=', master_reserv), + ('id', '=', master_reserv), + ('splitted', '=', True), + ]) + + return { + 'type': 'reservation', + 'action': vals['action'], + 'subtype': vals['type'], + 'title': vals['title'], + 'username': user_id.partner_id.name, + 'userid': user_id.id, + 'reservation': { + 'product_id': vals['product_id'], + 'reserv_id': vals['reserv_id'], + 'partner_name': vals['partner_name'], + 'adults': vals['adults'], + 'childer': vals['children'], + 'checkin': vals['checkin'], + 'checkout': vals['checkout'], + 'folio_id': vals['folio_id'], + 'reserve_color': vals['reserve_color'], + 'reserve_color_text': vals['reserve_color_text'], + 'splitted': vals['splitted'], + 'parent_reservation': vals['parent_reservation'], + 'room_name': vals['room_name'], + 'state': vals['state'], + 'only_read': False, + 'fix_days': vals['fix_days'], + 'fix_rooms': False, + 'overbooking': vals['overbooking'], + }, + 'tooltip': [ + vals['partner_name'], + vals['partner_phone'], + vals['checkin'], + num_split, + vals['price'], + ] + } + + @api.model + def _generate_pricelist_notification(self, vals): + date_dt = datetime.strptime(vals['date'], DEFAULT_SERVER_DATE_FORMAT) + return { + 'type': 'pricelist', + 'price': { + vals['pricelist_id']: [{ + 'days': { + date_dt.strftime("%d/%m/%Y"): vals['price'], + }, + 'room': vals['virtual_room_id'], + 'id': vals['id'], + }], + }, + } + + @api.model + def _generate_restriction_notification(self, vals): + date_dt = datetime.strptime(vals['date'], DEFAULT_SERVER_DATE_FORMAT) + return { + 'type': 'restriction', + 'restriction': { + vals['virtual_room_id']: { + date_dt.strftime("%d/%m/%Y"): [ + vals['min_stay'], + vals['min_stay_arrival'], + vals['max_stay'], + vals['max_stay_arrival'], + vals['closed'], + vals['closed_arrival'], + vals['closed_departure'], + vals['id'], + ], + }, + }, + } + + @api.model + def _generate_availability_notification(self, vals): + date_dt = datetime.strptime(vals['date'], DEFAULT_SERVER_DATE_FORMAT) + return { + 'type': 'availability', + 'availability': { + vals['virtual_room_id']: { + date_dt.strftime("%d/%m/%Y"): [ + vals['avail'], + vals['no_ota'], + vals['id'], + ], + }, + }, + } + + @api.model + def send_reservation_notification(self, vals): + notif = self._generate_reservation_notif(vals) + self.env['bus.bus'].sendone((self._cr.dbname, 'hotel.reservation', + HOTEL_BUS_CHANNEL_ID), notif) + + @api.model + def send_pricelist_notification(self, vals): + notif = self._generate_pricelist_notification(vals) + self.env['bus.bus'].sendone((self._cr.dbname, 'hotel.reservation', + HOTEL_BUS_CHANNEL_ID), notif) + + @api.model + def send_restriction_notification(self, vals): + notif = self._generate_restriction_notification(vals) + self.env['bus.bus'].sendone((self._cr.dbname, 'hotel.reservation', + HOTEL_BUS_CHANNEL_ID), notif) + + @api.model + def send_availability_notification(self, vals): + notif = self._generate_availability_notification(vals) + self.env['bus.bus'].sendone((self._cr.dbname, 'hotel.reservation', + HOTEL_BUS_CHANNEL_ID), notif) diff --git a/hotel_calendar/models/hotel_calendar_management.py b/hotel_calendar/models/hotel_calendar_management.py new file mode 100644 index 000000000..4727c428e --- /dev/null +++ b/hotel_calendar/models/hotel_calendar_management.py @@ -0,0 +1,328 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import logging +from datetime import datetime, timedelta +from odoo.tools import ( + DEFAULT_SERVER_DATE_FORMAT, + DEFAULT_SERVER_DATETIME_FORMAT) +from odoo import models, api, _ +from odoo.exceptions import ValidationError +from odoo.addons.hotel import date_utils +_logger = logging.getLogger(__name__) + + +class HotelCalendarManagement(models.TransientModel): + _name = 'hotel.calendar.management' + + @api.model + def _get_prices_values(self, price): + vals = { + 'fixed_price': price['price'], + } + return vals + + @api.model + def _get_restrictions_values(self, restriction): + vals = { + 'min_stay': restriction['min_stay'], + 'min_stay_arrival': restriction['min_stay_arrival'], + 'max_stay': restriction['max_stay'], + 'max_stay_arrival': restriction['max_stay_arrival'], + 'closed': restriction['closed'], + 'closed_arrival': restriction['closed_arrival'], + 'closed_departure': restriction['closed_departure'], + } + return vals + + @api.model + def _get_availability_values(self, avail, vroom): + vroom_obj = self.env['hotel.virtual.room'] + cavail = len(vroom_obj.check_availability_virtual_room( + avail['date'], avail['date'], virtual_room_id=vroom.id)) + ravail = min(cavail, vroom.total_rooms_count, int(avail['avail'])) + vals = { + 'no_ota': avail['no_ota'], + 'avail': ravail, + } + return vals + + @api.multi + def save_changes(self, pricelist_id, restriction_id, pricelist, + restrictions, availability): + vroom_obj = self.env['hotel.virtual.room'] + product_pricelist_item_obj = self.env['product.pricelist.item'] + vroom_rest_item_obj = self.env['hotel.virtual.room.restriction.item'] + vroom_avail_obj = self.env['hotel.virtual.room.availability'] + + # Save Pricelist + for k_price in pricelist.keys(): + vroom_id = vroom_obj.browse([int(k_price)]) + vroom_prod_tmpl_id = vroom_id.product_id.product_tmpl_id + for price in pricelist[k_price]: + price_id = product_pricelist_item_obj.search([ + ('date_start', '>=', price['date']), + ('date_end', '<=', price['date']), + ('pricelist_id', '=', int(pricelist_id)), + ('applied_on', '=', '1_product'), + ('compute_price', '=', 'fixed'), + ('product_tmpl_id', '=', vroom_prod_tmpl_id.id), + ], limit=1) + vals = self._get_prices_values(price) + if not price_id: + vals.update({ + 'date_start': price['date'], + 'date_end': price['date'], + 'pricelist_id': int(pricelist_id), + 'applied_on': '1_product', + 'compute_price': 'fixed', + 'product_tmpl_id': vroom_prod_tmpl_id.id, + }) + price_id = product_pricelist_item_obj.create(vals) + else: + price_id.write(vals) + + # Save Restrictions + for k_res in restrictions.keys(): + for restriction in restrictions[k_res]: + res_id = vroom_rest_item_obj.search([ + ('date_start', '>=', restriction['date']), + ('date_end', '<=', restriction['date']), + ('restriction_id', '=', int(restriction_id)), + ('applied_on', '=', '0_virtual_room'), + ('virtual_room_id', '=', int(k_res)), + ], limit=1) + vals = self._get_restrictions_values(restriction) + if not res_id: + vals.update({ + 'date_start': restriction['date'], + 'date_end': restriction['date'], + 'restriction_id': int(restriction_id), + 'applied_on': '0_virtual_room', + 'virtual_room_id': int(k_res), + }) + res_id = vroom_rest_item_obj.create(vals) + else: + res_id.write(vals) + + # Save Availability + for k_avail in availability.keys(): + vroom_id = vroom_obj.browse(int(k_avail)) + for avail in availability[k_avail]: + vals = self._get_availability_values(avail, vroom_id) + avail_id = vroom_avail_obj.search([ + ('date', '=', avail['date']), + ('virtual_room_id', '=', vroom_id.id), + ], limit=1) + if not avail_id: + vals.update({ + 'date': avail['date'], + 'virtual_room_id': vroom_id.id, + }) + avail_id = vroom_avail_obj.with_context({ + 'mail_create_nosubscribe': True, + }).create(vals) + else: + avail_id.write(vals) + + @api.model + def _hcalendar_room_json_data(self, rooms): + json_data = [] + for room in rooms: + json_data.append(( + room.id, + room.name, + room.get_capacity(), + room.list_price, + room.max_real_rooms, + )) + return json_data + + @api.model + def _hcalendar_pricelist_json_data(self, prices): + json_data = {} + vroom_obj = self.env['hotel.virtual.room'] + for rec in prices: + virtual_room_id = vroom_obj.search([ + ('product_id.product_tmpl_id', '=', rec.product_tmpl_id.id) + ], limit=1) + if not virtual_room_id: + continue + + # TODO: date_end - date_start loop + json_data.setdefault(virtual_room_id.id, []).append({ + 'id': rec.id, + 'price': rec.fixed_price, + 'date': rec.date_start, + }) + return json_data + + @api.model + def _hcalendar_restriction_json_data(self, restrictions): + json_data = {} + for rec in restrictions: + # TODO: date_end - date_start loop + json_data.setdefault(rec.virtual_room_id.id, []).append({ + 'id': rec.id, + 'date': rec.date_start, + 'min_stay': rec.min_stay, + 'min_stay_arrival': rec.min_stay_arrival, + 'max_stay': rec.max_stay, + 'max_stay_arrival': rec.max_stay_arrival, + 'closed': rec.closed, + 'closed_departure': rec.closed_departure, + 'closed_arrival': rec.closed_arrival, + }) + return json_data + + @api.model + def _hcalendar_availability_json_data(self, dfrom, dto): + date_start = date_utils.get_datetime(dfrom, hours=False) + date_diff = date_utils.date_diff(dfrom, dto, hours=False) + 1 + vrooms = self.env['hotel.virtual.room'].search([]) + json_data = {} + + for vroom in vrooms: + json_data[vroom.id] = [] + for i in range(0, date_diff): + cur_date = date_start + timedelta(days=i) + cur_date_str = cur_date.strftime(DEFAULT_SERVER_DATE_FORMAT) + avail = self.env['hotel.virtual.room.availability'].search([ + ('date', '=', cur_date_str), + ('virtual_room_id', '=', vroom.id) + ]) + if avail: + json_data[vroom.id].append({ + 'id': avail.id, + 'date': avail.date, + 'avail': avail.avail, + 'no_ota': avail.no_ota, + }) + else: + json_data[vroom.id].append({ + 'id': False, + 'date': cur_date_str, + 'avail': vroom.max_real_rooms, + 'no_ota': False, + }) + return json_data + + @api.model + def _hcalendar_events_json_data(self, dfrom, dto): + date_start = date_utils.get_datetime(dfrom, hours=False) - timedelta(days=1) + date_start_str = date_start.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + user_id = self.env['res.users'].browse(self.env.uid) + domain = [] + if user_id.pms_allowed_events_tags: + domain.append(('categ_ids', 'in', user_id.pms_allowed_events_tags)) + if user_id.pms_denied_events_tags: + domain.append( + ('categ_ids', 'not in', user_id.pms_denied_events_tags)) + events_raw = self.env['calendar.event'].search(domain) + events_ll = self.env['calendar.event'].search([ + ('start', '<=', dto), + ('stop', '>=', date_start_str) + ]) + events_lr = self.env['calendar.event'].search([ + ('start', '>=', date_start_str), + ('stop', '<=', dto) + ]) + events = (events_ll | events_lr) & events_raw + json_data = [] + for event in events: + json_data.append([ + event.id, + event.name, + event.start, + event.location, + ]) + return json_data + + @api.model + def _hcalendar_get_count_reservations_json_data(self, dfrom, dto): + vrooms = self.env['hotel.virtual.room'].search([]) + date_start = date_utils.get_datetime(dfrom, hours=False) + date_diff = date_utils.date_diff(dfrom, dto, hours=False) + 1 + hotel_vroom_obj = self.env['hotel.virtual.room'] + vrooms = hotel_vroom_obj.search([]) + json_data = {} + + for vroom in vrooms: + for i in range(0, date_diff): + cur_date = date_start + timedelta(days=i) + cur_date_str = cur_date.strftime(DEFAULT_SERVER_DATE_FORMAT) + + json_data.setdefault(vroom.id, []).append({ + 'date': cur_date_str, + 'num': len( + hotel_vroom_obj.check_availability_virtual_room( + cur_date_str, + cur_date_str, + virtual_room_id=vroom.id)), + }) + + return json_data + + @api.model + def get_hcalendar_all_data(self, dfrom, dto, pricelist_id, restriction_id, + withRooms): + if not dfrom or not dto: + raise ValidationError(_('Input Error: No dates defined!')) + vals = {} + if not pricelist_id: + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if not restriction_id: + restriction_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_restrictions_id') + + pricelist_id = int(pricelist_id) + vals.update({'pricelist_id': pricelist_id}) + restriction_id = int(restriction_id) + vals.update({'restriction_id': restriction_id}) + + vroom_rest_it_obj = self.env['hotel.virtual.room.restriction.item'] + restriction_item_ids = vroom_rest_it_obj.search([ + ('date_start', '>=', dfrom), ('date_end', '<=', dto), + ('restriction_id', '=', restriction_id), + ('applied_on', '=', '0_virtual_room'), + ]) + + pricelist_item_ids = self.env['product.pricelist.item'].search([ + ('date_start', '>=', dfrom), ('date_end', '<=', dto), + ('pricelist_id', '=', pricelist_id), + ('applied_on', '=', '1_product'), + ('compute_price', '=', 'fixed'), + ]) + + json_prices = self._hcalendar_pricelist_json_data(pricelist_item_ids) + json_rest = self._hcalendar_restriction_json_data(restriction_item_ids) + json_avails = self._hcalendar_availability_json_data(dfrom, dto) + json_rc = self._hcalendar_get_count_reservations_json_data(dfrom, dto) + json_events = self._hcalendar_events_json_data(dfrom, dto) + vals.update({ + 'prices': json_prices or [], + 'restrictions': json_rest or [], + 'availability': json_avails or [], + 'count_reservations': json_rc or [], + 'events': json_events or [], + }) + + if withRooms: + room_ids = self.env['hotel.virtual.room'].search( + [], + order='hcal_sequence ASC') + json_rooms = self._hcalendar_room_json_data(room_ids) + vals.update({'rooms': json_rooms or []}) + + return vals + + @api.multi + def get_hcalendar_settings(self): + user_id = self.env['res.users'].browse(self.env.uid) + return { + 'eday_week': user_id.npms_end_day_week, + 'eday_week_offset': user_id.npms_end_day_week_offset, + 'days': user_id.npms_default_num_days, + 'show_notifications': user_id.pms_show_notifications, + 'show_num_rooms': user_id.pms_show_num_rooms, + } diff --git a/hotel_calendar/models/inherited_hotel_folio.py b/hotel_calendar/models/inherited_hotel_folio.py new file mode 100644 index 000000000..744f6b22c --- /dev/null +++ b/hotel_calendar/models/inherited_hotel_folio.py @@ -0,0 +1,17 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import logging +from odoo import models, fields, api, _ +_logger = logging.getLogger(__name__) + + +class HotelFolio(models.Model): + _inherit = 'hotel.folio' + + @api.multi + def write(self, vals): + ret = super(HotelFolio, self).write(vals) + if vals.get('room_lines') or vals.get('service_lines'): + for record in self: + record.room_lines.send_bus_notification('write', 'noshow') + return ret diff --git a/hotel_calendar/models/inherited_hotel_reservation.py b/hotel_calendar/models/inherited_hotel_reservation.py new file mode 100644 index 000000000..8e654df19 --- /dev/null +++ b/hotel_calendar/models/inherited_hotel_reservation.py @@ -0,0 +1,384 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import logging +from datetime import datetime, timedelta +from odoo import models, fields, api, _ +from odoo.exceptions import ValidationError +from odoo.tools import ( + DEFAULT_SERVER_DATE_FORMAT, + DEFAULT_SERVER_DATETIME_FORMAT) +from odoo.addons.hotel import date_utils +_logger = logging.getLogger(__name__) + + +class HotelReservation(models.Model): + _inherit = 'hotel.reservation' + + @api.model + def _hcalendar_reservation_data(self, reservations): + json_reservations = [] + json_reservation_tooltips = {} + for reserv in reservations: + json_reservations.append([ + reserv.product_id.id, + reserv.id, + reserv.folio_id.partner_id.name, + reserv.adults, + reserv.children, + reserv.checkin, + reserv.checkout, + reserv.folio_id.id, + reserv.reserve_color, + reserv.reserve_color_text, + reserv.splitted, + reserv.parent_reservation and reserv.parent_reservation.id + or False, + False, # Read-Only + reserv.splitted, # Fix Days + False, # Fix Rooms + reserv.overbooking]) + num_split = 0 + if reserv.splitted: + master_reserv = reserv.parent_reservation or reserv + num_split = self.search_count([ + ('folio_id', '=', reserv.folio_id.id), + '|', ('parent_reservation', '=', master_reserv.id), + ('id', '=', master_reserv.id), + ('splitted', '=', True), + ]) + json_reservation_tooltips.update({ + reserv.id: [ + reserv.folio_id.partner_id.name, + reserv.folio_id.partner_id.mobile or + reserv.folio_id.partner_id.phone or _('Undefined'), + reserv.checkin, + num_split, + reserv.folio_id.amount_total] + }) + return (json_reservations, json_reservation_tooltips) + + @api.model + def _hcalendar_room_data(self, rooms): + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_id: + pricelist_id = int(pricelist_id) + json_rooms = [] + room_type_obj = self.env['hotel.room.type'] + vroom_obj = self.env['hotel.virtual.room'] + for room in rooms: + room_type = room_type_obj.search([ + ('cat_id', '=', room.categ_id.id) + ], limit=1) + vrooms = vroom_obj.search([ + '|', ('room_ids', 'in', room.id), + ('room_type_ids.id', '=', room.categ_id.id)], + order='hcal_sequence ASC') + json_rooms.append(( + room.product_id.id, + room.name, + room.capacity, + room.categ_id.id, + room_type.code_type, + room.shared_room, + room.sale_price_type == 'vroom' + and ['pricelist', room.price_virtual_room.id, pricelist_id, + room.price_virtual_room.name] + or ['fixed', room.list_price], + vrooms.mapped('name'), + vrooms.ids, + room.floor_id.id, + room.room_amenities.ids)) + return json_rooms + + @api.model + def _hcalendar_event_data(self, events): + json_events = [] + for event in events: + json_events.append([ + event.id, + event.name, + event.start, + event.location, + ]) + return json_events + + @api.model + def get_hcalendar_reservations_data(self, dfrom, dto, rooms): + date_start = date_utils.get_datetime(dfrom, hours=False) \ + - timedelta(days=1) + date_start_str = date_start.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + room_product_ids = rooms.mapped('product_id.id') + reservations_raw = self.env['hotel.reservation'].search( + [ + ('product_id', 'in', room_product_ids), + ('state', 'in', + ['draft', 'confirm', 'booking', 'done', False]), + ], + order="checkin DESC, checkout ASC, adults DESC, children DESC") + reservations_ll = self.env['hotel.reservation'].search([ + ('checkin', '<=', dto), + ('checkout', '>=', date_start_str) + ]) + reservations_lr = self.env['hotel.reservation'].search([ + ('checkin', '>=', date_start_str), + ('checkout', '<=', dto) + ]) + reservations = (reservations_ll | reservations_lr) & reservations_raw + return self._hcalendar_reservation_data(reservations) + + @api.model + def get_hcalendar_pricelist_data(self, dfrom, dto): + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_id: + pricelist_id = int(pricelist_id) + date_start = date_utils.get_datetime(dfrom, hours=False) \ + - timedelta(days=1) + date_diff = date_utils.date_diff(date_start, dto, hours=False) + 1 + # Get Prices + json_rooms_prices = {pricelist_id: []} + vrooms = self.env['hotel.virtual.room'].search( + [], + order='hcal_sequence ASC') + vroom_pr_cached_obj = self.env['virtual.room.pricelist.cached'] + + for vroom in vrooms: + days = {} + for i in range(0, date_diff): + ndate = date_start + timedelta(days=i) + ndate_str = ndate.strftime(DEFAULT_SERVER_DATE_FORMAT) + prod_price_id = vroom_pr_cached_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date', '=', ndate_str) + ], limit=1) + days.update({ + ndate.strftime("%d/%m/%Y"): prod_price_id and + prod_price_id.price or + vroom.product_id.with_context( + quantity=1, + date=ndate_str, + pricelist=pricelist_id).price + }) + json_rooms_prices[pricelist_id].append({ + 'room': vroom.id, + 'days': days, + 'title': vroom.name, + }) + return json_rooms_prices + + @api.model + def get_hcalendar_restrictions_data(self, dfrom, dto): + restriction_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_restrictions_id') + if restriction_id: + restriction_id = int(restriction_id) + date_start = date_utils.get_datetime(dfrom, hours=False) \ + - timedelta(days=1) + date_diff = date_utils.date_diff(dfrom, dto, hours=False) + 1 + # Get Prices + json_rooms_rests = {} + vrooms = self.env['hotel.virtual.room'].search( + [], + order='hcal_sequence ASC') + vroom_rest_obj = self.env['hotel.virtual.room.restriction.item'] + for vroom in vrooms: + days = {} + for i in range(0, date_diff): + ndate = date_start + timedelta(days=i) + ndate_str = ndate.strftime(DEFAULT_SERVER_DATE_FORMAT) + rest_id = vroom_rest_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date_start', '>=', ndate_str), + ('date_end', '<=', ndate_str), + ('applied_on', '=', '0_virtual_room'), + ('restriction_id', '=', restriction_id) + ], limit=1) + if rest_id and (rest_id.min_stay or rest_id.min_stay_arrival or + rest_id.max_stay or rest_id.max_stay_arrival or + rest_id.closed or rest_id.closed_arrival or + rest_id.closed_departure): + days.update({ + ndate.strftime("%d/%m/%Y"): ( + rest_id.min_stay, + rest_id.min_stay_arrival, + rest_id.max_stay, + rest_id.max_stay_arrival, + rest_id.closed, + rest_id.closed_arrival, + rest_id.closed_departure) + }) + json_rooms_rests.update({vroom.id: days}) + return json_rooms_rests + + @api.model + def get_hcalendar_events_data(self, dfrom, dto): + date_start = date_utils.get_datetime(dfrom, hours=False) \ + - timedelta(days=1) + date_start_str = date_start.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + user_id = self.env['res.users'].browse(self.env.uid) + domain = [] + if user_id.pms_allowed_events_tags: + domain.append(('categ_ids', 'in', user_id.pms_allowed_events_tags)) + if user_id.pms_denied_events_tags: + domain.append( + ('categ_ids', 'not in', user_id.pms_denied_events_tags)) + events_raw = self.env['calendar.event'].search(domain) + events_ll = self.env['calendar.event'].search([ + ('start', '<=', dto), + ('stop', '>=', date_start_str) + ]) + events_lr = self.env['calendar.event'].search([ + ('start', '>=', date_start_str), + ('stop', '<=', dto) + ]) + events = (events_ll | events_lr) & events_raw + return self._hcalendar_event_data(events) + + @api.model + def get_hcalendar_settings(self): + user_id = self.env['res.users'].browse(self.env.uid) + type_move = user_id.pms_type_move + return { + 'divide_rooms_by_capacity': user_id.pms_divide_rooms_by_capacity, + 'eday_week': user_id.pms_end_day_week, + 'eday_week_offset': user_id.pms_end_day_week_offset, + 'days': user_id.pms_default_num_days, + 'allow_invalid_actions': type_move == 'allow_invalid', + 'assisted_movement': type_move == 'assisted', + 'default_arrival_hour': self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_arrival_hour'), + 'default_departure_hour': self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_departure_hour'), + 'show_notifications': user_id.pms_show_notifications, + 'show_pricelist': user_id.pms_show_pricelist, + 'show_availability': user_id.pms_show_availability, + 'show_num_rooms': user_id.pms_show_num_rooms, + } + + @api.model + def get_hcalendar_all_data(self, dfrom, dto, withRooms=True): + if not dfrom or not dto: + raise ValidationError(_('Input Error: No dates defined!')) + + rooms = self.env['hotel.room'].search([], order='hcal_sequence ASC') + json_res, json_res_tooltips = self.get_hcalendar_reservations_data( + dfrom, dto, rooms) + + vals = { + 'rooms': withRooms and self._hcalendar_room_data(rooms) or [], + 'reservations': json_res, + 'tooltips': json_res_tooltips, + 'pricelist': self.get_hcalendar_pricelist_data(dfrom, dto), + 'restrictions': self.get_hcalendar_restrictions_data(dfrom, dto), + 'events': self.get_hcalendar_events_data(dfrom, dto), + } + + return vals + + @api.multi + def send_bus_notification(self, naction, ntype, ntitle=''): + hotel_cal_obj = self.env['bus.hotel.calendar'] + for record in self: + hotel_cal_obj.send_reservation_notification({ + 'action': naction, + 'type': ntype, + 'title': ntitle, + 'product_id': record.product_id.id, + 'reserv_id': record.id, + 'partner_name': record.partner_id.name, + 'adults': record.adults, + 'children': record.children, + 'checkin': record.checkin, + 'checkout': record.checkout, + 'folio_id': record.folio_id.id, + 'reserve_color': record.reserve_color, + 'reserve_color_text': record.reserve_color_text, + 'splitted': record.splitted, + 'parent_reservation': record.parent_reservation and + record.parent_reservation.id or 0, + 'room_name': record.product_id.name, + 'partner_phone': record.partner_id.mobile + or record.partner_id.phone or _('Undefined'), + 'state': record.state, + 'fix_days': record.splitted, + 'overbooking': record.overbooking, + 'price': record.folio_id.amount_total, + }) + + @api.model + def swap_reservations(self, fromReservsIds, toReservsIds): + from_reservs = self.env['hotel.reservation'].browse(fromReservsIds) + to_reservs = self.env['hotel.reservation'].browse(toReservsIds) + + if not any(from_reservs) or not any(toReservs): + raise ValidationError(_("Invalid swap parameters")) + + max_from_persons = max( + from_reservs.mapped(lambda x: x.adults + x.children)) + max_to_persons = max( + to_reservs.mapped(lambda x: x.adults + x.children)) + + from_room_product = from_reservs[0].product_id + to_room_product = to_reservs[0].product_id + from_overbooking = from_reservs[0].overbooking + to_overbooking = to_reservs[0].overbooking + + hotel_room_obj = self.env['hotel.room'] + from_room = hotel_room_obj.search([ + ('product_id', '=', from_room_product.id)]) + to_room = hotel_room_obj.search([ + ('product_id', '=', from_room_product.id)]) + + if max_from_persons > to_room.capacity or \ + max_to_persons > from_room.capacity: + raise ValidationError("Invalid swap operation: wrong capacity") + + for record in from_reservs: + record.with_context({'ignore_avail_restrictions': True}).write({ + 'product_id': to_room_product.id, + 'overbooking': to_overbooking, + }) + for record in to_reservs: + record.with_context({'ignore_avail_restrictions': True}).write({ + 'product_id': from_room_product.id, + 'overbooking': from_overbooking, + }) + + return True + + @api.model + def create(self, vals): + reservation_id = super(HotelReservation, self).create(vals) + reservation_id.send_bus_notification('create', + 'notify', + _("Reservation Created")) + return reservation_id + + @api.multi + def write(self, vals): + ret = super(HotelReservation, self).write(vals) + if 'partner_id' in vals or 'checkin' in vals or \ + 'checkout' in vals or 'product_id' in vals or \ + 'adults' in vals or 'children' in vals or \ + 'state' in vals or 'splitted' in vals or \ + 'reserve_color' in vals or \ + 'reserve_color_text' in vals or 'product_id' in vals or \ + 'parent_reservation' in vals or 'overbooking' in vals: + for record in self: + record.send_bus_notification( + 'write', + (record.state == 'cancelled') and 'warn' or 'notify', + (record.state == 'cancelled') and + _("Reservation Cancelled") or _("Reservation Changed") + ) + elif not any(vals) or 'to_read' in vals or 'to_assign' in vals: + self.send_bus_notification('write', 'noshow') + return ret + + @api.multi + def unlink(self): + self.send_bus_notification('unlink', + 'warn', + _("Reservation Deleted")) + return super(HotelReservation, self).unlink() diff --git a/hotel_calendar/models/inherited_hotel_room.py b/hotel_calendar/models/inherited_hotel_room.py new file mode 100644 index 000000000..a87c7400f --- /dev/null +++ b/hotel_calendar/models/inherited_hotel_room.py @@ -0,0 +1,9 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields + + +class HotelRoom(models.Model): + _inherit = 'hotel.room' + + hcal_sequence = fields.Integer('Calendar Sequence', default=0) diff --git a/hotel_calendar/models/inherited_hotel_virtual_room.py b/hotel_calendar/models/inherited_hotel_virtual_room.py new file mode 100644 index 000000000..59508b000 --- /dev/null +++ b/hotel_calendar/models/inherited_hotel_virtual_room.py @@ -0,0 +1,21 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api + + +class HotelVirtualRoom(models.Model): + _inherit = 'hotel.virtual.room' + + hcal_sequence = fields.Integer('Calendar Sequence', default=0) + + @api.multi + def unlink(self): + vroom_pr_cached_obj = self.env['virtual.room.pricelist.cached'] + for record in self: + pr_chached = vroom_pr_cached_obj.search([ + ('virtual_room_id', '=', record.id) + ]) + # Because 'pricelist.cached' is an isolated model, + # doesn't trigger 'ondelete'. Need call 'unlink' instead. + pr_chached.unlink() + return super(HotelVirtualRoom, self).unlink() diff --git a/hotel_calendar/models/inherited_hotel_virtual_room_availability.py b/hotel_calendar/models/inherited_hotel_virtual_room_availability.py new file mode 100644 index 000000000..2d76784cc --- /dev/null +++ b/hotel_calendar/models/inherited_hotel_virtual_room_availability.py @@ -0,0 +1,51 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api + + +class HotelVirtualRoomAvailability(models.Model): + _inherit = 'hotel.virtual.room.availability' + + @api.model + def create(self, vals): + res = super(HotelVirtualRoomAvailability, self).create(vals) + self.env['bus.hotel.calendar'].send_availability_notification({ + 'date': res.date, + 'avail': res.avail, + 'no_ota': res.no_ota, + 'virtual_room_id': res.virtual_room_id.id, + 'id': res.id, + }) + return res + + @api.multi + def write(self, vals): + ret_vals = super(HotelVirtualRoomAvailability, self).write(vals) + bus_hotel_calendar_obj = self.env['bus.hotel.calendar'] + for record in self: + bus_hotel_calendar_obj.send_availability_notification({ + 'date': record.date, + 'avail': record.avail, + 'no_ota': record.no_ota, + 'virtual_room_id': record.virtual_room_id.id, + 'id': record.id, + }) + return ret_vals + + @api.multi + def unlink(self): + # Construct dictionary with relevant info of removed records + unlink_vals = [] + for record in self: + unlink_vals.append({ + 'date': record.date, + 'avail': record.virtual_room_id.max_real_rooms, + 'virtual_room_id': record.virtual_room_id.id, + 'no_ota': False, + 'id': record.id, + }) + res = super(HotelVirtualRoomAvailability, self).unlink() + bus_hotel_calendar_obj = self.env['bus.hotel.calendar'] + for uval in unlink_vals: + bus_hotel_calendar_obj.send_availability_notification(uval) + return res diff --git a/hotel_calendar/models/inherited_hotel_virtual_room_restriction_item.py b/hotel_calendar/models/inherited_hotel_virtual_room_restriction_item.py new file mode 100644 index 000000000..2059905fb --- /dev/null +++ b/hotel_calendar/models/inherited_hotel_virtual_room_restriction_item.py @@ -0,0 +1,93 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import logging +from odoo import models, fields, api +_logger = logging.getLogger(__name__) + + +class HotelVirtualRoomResrtrictionItem(models.Model): + _inherit = 'hotel.virtual.room.restriction.item' + + @api.model + def create(self, vals): + res = super(HotelVirtualRoomResrtrictionItem, self).create(vals) + restrictions_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_restrictions_id') + if restrictions_parity_id: + restrictions_parity_id = int(restrictions_parity_id) + restriction_id = res.restriction_id.id + if restriction_id == restrictions_parity_id and \ + self.applied_on == '0_virtual_room': + self.env['bus.hotel.calendar'].send_restriction_notification({ + 'restriction_id': self.restriction_id.id, + 'date': self.date_start, + 'min_stay': self.min_stay, + 'min_stay_arrival': self.min_stay_arrival, + 'max_stay': self.max_stay, + 'max_stay_arrival': self.max_stay_arrival, + 'closed': self.closed, + 'closed_departure': self.closed_departure, + 'closed_arrival': self.closed_arrival, + 'virtual_room_id': self.virtual_room_id.id, + 'id': self.id, + }) + return res + + @api.multi + def write(self, vals): + restrictions_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_restrictions_id') + if restrictions_parity_id: + restrictions_parity_id = int(restrictions_parity_id) + ret_vals = super(HotelVirtualRoomResrtrictionItem, self).write(vals) + + bus_hotel_calendar_obj = self.env['bus.hotel.calendar'] + for record in self: + if record.restriction_id.id != restrictions_parity_id or \ + record.applied_on != '0_virtual_room': + continue + bus_hotel_calendar_obj.send_restriction_notification({ + 'restriction_id': record.restriction_id.id, + 'date': record.date_start, + 'min_stay': record.min_stay, + 'min_stay_arrival': record.min_stay_arrival, + 'max_stay': record.max_stay, + 'max_stay_arrival': record.max_stay_arrival, + 'closed': record.closed, + 'closed_departure': record.closed_departure, + 'closed_arrival': record.closed_arrival, + 'virtual_room_id': record.virtual_room_id.id, + 'id': record.id, + }) + return ret_vals + + @api.multi + def unlink(self): + restrictions_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_restrictions_id') + if restrictions_parity_id: + restrictions_parity_id = int(restrictions_parity_id) + # Construct dictionary with relevant info of removed records + unlink_vals = [] + for record in self: + if record.restriction_id.id != restrictions_parity_id or \ + record.applied_on != '0_virtual_room': + continue + unlink_vals.append({ + 'restriction_id': record.restriction_id.id, + 'date': record.date_start, + 'min_stay': 0, + 'min_stay_arrival': 0, + 'max_stay': 0, + 'max_stay_arrival': 0, + 'closed': False, + 'closed_departure': False, + 'closed_arrival': False, + 'virtual_room_id': record.virtual_room_id.id, + 'id': record.id, + }) + res = super(HotelVirtualRoomResrtrictionItem, self).unlink() + bus_hotel_calendar_obj = self.env['bus.hotel.calendar'] + for uval in unlink_vals: + bus_hotel_calendar_obj.send_restriction_notification(uval) + return res diff --git a/hotel_calendar/models/inherited_ir_actions_act_window_view.py b/hotel_calendar/models/inherited_ir_actions_act_window_view.py new file mode 100644 index 000000000..e416d6664 --- /dev/null +++ b/hotel_calendar/models/inherited_ir_actions_act_window_view.py @@ -0,0 +1,8 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields + +class ActWindowView(models.Model): + _inherit = 'ir.actions.act_window.view' + + view_mode = fields.Selection(selection_add=[('pms', "PMS")]) diff --git a/hotel_calendar/models/inherited_ir_default.py b/hotel_calendar/models/inherited_ir_default.py new file mode 100644 index 000000000..9ae372b97 --- /dev/null +++ b/hotel_calendar/models/inherited_ir_default.py @@ -0,0 +1,36 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api +from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT +from odoo.addons.hotel import date_utils + + +class IrDefault(models.Model): + _inherit = 'ir.default' + + @api.model + def set(self, model_name, field_name, value, user_id=False, company_id=False, condition=False): + super(IrDefault, self).set(model_name, field_name, value, user_id, company_id, condition) + if model_name == 'res.config.settings' and field_name == 'parity_pricelist_id': + pricelist_id = int(value) + self.env['virtual.room.pricelist.cached'].search([]).unlink() + + pricelist_items = self.env['product.pricelist.item'].search([ + ('pricelist_id', '=', pricelist_id) + ]) + vroom_obj = self.env['hotel.virtual.room'] + vroom_pr_cached_obj = self.env['virtual.room.pricelist.cached'] + for pitem in pricelist_items: + date_start = pitem.date_start + product_tmpl_id = pitem.product_tmpl_id.id + fixed_price = pitem.fixed_price + vroom = vroom_obj.search([ + ('product_id.product_tmpl_id', '=', product_tmpl_id), + ('date_start', '>=', date_utils.now().strftime( + DEFAULT_SERVER_DATETIME_FORMAT)) + ], limit=1) + vroom_pr_cached_obj.create({ + 'virtual_room_id': vroom.id, + 'date': date_start, + 'price': fixed_price, + }) diff --git a/hotel_calendar/models/inherited_ir_ui_view.py b/hotel_calendar/models/inherited_ir_ui_view.py new file mode 100644 index 000000000..2491feda5 --- /dev/null +++ b/hotel_calendar/models/inherited_ir_ui_view.py @@ -0,0 +1,8 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields + +class View(models.Model): + _inherit = 'ir.ui.view' + + type = fields.Selection(selection_add=[('pms', "PMS")]) diff --git a/hotel_calendar/models/inherited_product_pricelist.py b/hotel_calendar/models/inherited_product_pricelist.py new file mode 100644 index 000000000..2a321cdb7 --- /dev/null +++ b/hotel_calendar/models/inherited_product_pricelist.py @@ -0,0 +1,33 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api + + +class ProductPricelist(models.Model): + _inherit = 'product.pricelist' + + @api.multi + def update_price(self, virtual_room_id, date, price): + vroom = self.env['hotel.virtual.room'].browse(virtual_room_id) + pritem_obj = self.env['product.pricelist.item'] + for record in self: + plitem = pritem_obj.search([ + ('pricelist_id', '=', record.id), + ('product_tmpl_id', '=', vroom.product_id.product_tmpl_id.id), + ('date_start', '=', date), + ('date_end', '=', date), + ('applied_on', '=', '1_product'), + ('compute_price', '=', 'fixed') + ]) + if plitem: + plitem.fixed_price = price + else: + pritem_obj.create({ + 'pricelist_id': record.id, + 'product_tmpl_id': vroom.product_id.product_tmpl_id.id, + 'date_start': date, + 'date_end': date, + 'applied_on': '1_product', + 'compute_price': 'fixed', + 'fixed_price': price + }) diff --git a/hotel_calendar/models/inherited_product_pricelist_item.py b/hotel_calendar/models/inherited_product_pricelist_item.py new file mode 100644 index 000000000..81f567b7d --- /dev/null +++ b/hotel_calendar/models/inherited_product_pricelist_item.py @@ -0,0 +1,155 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api + + +class ProductPricelistItem(models.Model): + _inherit = 'product.pricelist.item' + + @api.model + def create(self, vals): + res = super(ProductPricelistItem, self).create(vals) + pricelist_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_parity_id: + pricelist_parity_id = int(pricelist_parity_id) + pricelist_id = res.pricelist_id.id + product_tmpl_id = res.product_tmpl_id.id + date_start = res.date_start + vroom = self.env['hotel.virtual.room'].search([ + ('product_id.product_tmpl_id', '=', product_tmpl_id) + ], limit=1) + if pricelist_id == pricelist_parity_id and vroom: + prod = vroom.product_id.with_context( + quantity=1, + date=date_start, + pricelist=pricelist_id) + prod_price = prod.price + + self.env['bus.hotel.calendar'].send_pricelist_notification({ + 'pricelist_id': pricelist_id, + 'date': date_start, + 'virtual_room_id': vroom.id, + 'price': prod_price, + 'id': self.id, + }) + + vroom_pr_cached_obj = self.env['virtual.room.pricelist.cached'] + vroom_pr_cached_id = vroom_pr_cached_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date', '=', date_start), + ], limit=1) + if vroom_pr_cached_id: + vroom_pr_cached_id.write({'price': prod_price}) + else: + vroom_pr_cached_obj.create({ + 'virtual_room_id': vroom.id, + 'date': date_start, + 'price': prod_price, + }) + return res + + @api.multi + def write(self, vals): + pricelist_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_parity_id: + pricelist_parity_id = int(pricelist_parity_id) + ret_vals = super(ProductPricelistItem, self).write(vals) + + vroom_pr_cached_obj = self.env['virtual.room.pricelist.cached'] + bus_calendar_obj = self.env['bus.hotel.calendar'] + vroom_obj = self.env['hotel.virtual.room'] + if vals.get('fixed_price'): + for record in self: + pricelist_id = vals.get('pricelist_id') or \ + record.pricelist_id.id + if pricelist_id != pricelist_parity_id: + continue + date_start = vals.get('date_start') or record.date_start + product_tmpl_id = vals.get('product_tmpl_id') or \ + record.product_tmpl_id.id + vroom = vroom_obj.search([ + ('product_id.product_tmpl_id', '=', product_tmpl_id) + ], limit=1) + + if vroom and date_start: + prod = vroom.product_id.with_context( + quantity=1, + date=date_start, + pricelist=pricelist_id) + prod_price = prod.price + + bus_calendar_obj.send_pricelist_notification({ + 'pricelist_id': pricelist_id, + 'date': date_start, + 'virtual_room_id': vroom.id, + 'price': prod_price, + 'id': record.id, + }) + + vroom_pr_cached_id = vroom_pr_cached_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date', '=', date_start), + ], limit=1) + if vroom_pr_cached_id: + vroom_pr_cached_id.write({'price': prod_price}) + else: + vroom_pr_cached_obj.create({ + 'virtual_room_id': vroom.id, + 'date': date_start, + 'price': prod_price, + }) + return ret_vals + + @api.multi + def unlink(self): + pricelist_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_parity_id: + pricelist_parity_id = int(pricelist_parity_id) + # Construct dictionary with relevant info of removed records + unlink_vals = [] + for record in self: + if record.pricelist_id.id != pricelist_parity_id: + continue + vroom = self.env['hotel.virtual.room'].search([ + ('product_id.product_tmpl_id', '=', record.product_tmpl_id.id) + ], limit=1) + unlink_vals.append({ + 'pricelist_id': record.pricelist_id.id, + 'date': record.date_start, + 'vroom': vroom, + 'id': record.id, + }) + # Do Normal Stuff + res = super(ProductPricelistItem, self).unlink() + # Do extra operations + vroom_pr_cached_obj = self.env['virtual.room.pricelist.cached'] + bus_calendar_obj = self.env['bus.hotel.calendar'] + for vals in unlink_vals: + pricelist_id = vals['pricelist_id'] + date_start = vals['date'] + vroom = vals['vroom'] + prod = vroom.product_id.with_context( + quantity=1, + date=date_start, + pricelist=pricelist_id) + + # Send Notification to update calendar pricelist + bus_calendar_obj.send_pricelist_notification({ + 'pricelist_id': pricelist_id, + 'date': date_start, + 'virtual_room_id': vroom.id, + 'price': prod.price, + 'id': vals['id'], + }) + + # Remove records from cache model + vroom_pr_cached_id = vroom_pr_cached_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date', '=', date_start), + ], limit=1) + if vroom_pr_cached_id: + vroom_pr_cached_id.unlink() + return res diff --git a/hotel_calendar/models/inherited_res_users.py b/hotel_calendar/models/inherited_res_users.py new file mode 100644 index 000000000..63d7d98d2 --- /dev/null +++ b/hotel_calendar/models/inherited_res_users.py @@ -0,0 +1,82 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields + + +class ResUsers(models.Model): + _inherit = 'res.users' + + pms_divide_rooms_by_capacity = fields.Boolean('Divide rooms by capacity') + pms_end_day_week = fields.Selection([ + ('1', 'Monday'), + ('2', 'Tuesday'), + ('3', 'Wednesday'), + ('4', 'Thursday'), + ('5', 'Friday'), + ('6', 'Saturday'), + ('7', 'Sunday') + ], string='End day of week', default='6') + pms_end_day_week_offset = fields.Selection([ + ('0', '0 Days'), + ('1', '1 Days'), + ('2', '2 Days'), + ('3', '3 Days'), + ('4', '4 Days'), + ('5', '5 Days'), + ('6', '6 Days') + ], string='Also illuminate the previous', default='0') + pms_type_move = fields.Selection([ + ('normal', 'Normal'), + ('assisted', 'Assisted'), + ('allow_invalid', 'Allow Invalid') + ], string='Reservation move mode', default='normal') + pms_default_num_days = fields.Selection([ + ('month', '1 Month'), + ('21', '3 Weeks'), + ('14', '2 Weeks'), + ('7', '1 Week') + ], string='Default number of days', default='month') + + pms_show_notifications = fields.Boolean('Show Notifications', default=True) + pms_show_pricelist = fields.Boolean('Show Pricelist', default=True) + pms_show_availability = fields.Boolean('Show Availability', default=True) + pms_show_num_rooms = fields.Integer('Show Num. Rooms', default=0) + + pms_allowed_events_tags = fields.Many2many( + 'calendar.event.type', + string="Allow Calander Event Tags") + pms_denied_events_tags = fields.Many2many( + 'calendar.event.type', + string="Deny Calander Event Tags") + + npms_end_day_week = fields.Selection([ + ('1', 'Monday'), + ('2', 'Tuesday'), + ('3', 'Wednesday'), + ('4', 'Thursday'), + ('5', 'Friday'), + ('6', 'Saturday'), + ('7', 'Sunday') + ], string='End day of week', default='6') + npms_end_day_week_offset = fields.Selection([ + ('0', '0 Days'), + ('1', '1 Days'), + ('2', '2 Days'), + ('3', '3 Days'), + ('4', '4 Days'), + ('5', '5 Days'), + ('6', '6 Days') + ], string='Also illuminate the previous', default='0') + npms_default_num_days = fields.Selection([ + ('month', '1 Month'), + ('21', '3 Weeks'), + ('14', '2 Weeks'), + ('7', '1 Week') + ], string='Default number of days', default='month') + + npms_allowed_events_tags = fields.Many2many( + 'calendar.event.type', + string="Allow Calander Event Tags") + npms_denied_events_tags = fields.Many2many( + 'calendar.event.type', + string="Deny Calander Event Tags") diff --git a/hotel_calendar/models/res_config.py b/hotel_calendar/models/res_config.py new file mode 100644 index 000000000..e1e6e96e3 --- /dev/null +++ b/hotel_calendar/models/res_config.py @@ -0,0 +1,166 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api +from odoo.addons.hotel import date_utils + + +class HotelConfiguration(models.TransientModel): + _inherit = 'res.config.settings' + + color_pre_reservation = fields.Char('Pre-reservation') + color_reservation = fields.Char('Confirmed Reservation') + color_reservation_pay = fields.Char('Paid Reservation') + color_stay = fields.Char('Checkin') + color_stay_pay = fields.Char('Paid Checkin') + color_checkout = fields.Char('Checkout') + color_dontsell = fields.Char('Dont Sell') + color_staff = fields.Char('Staff') + color_to_assign = fields.Char('Ota Reservation to Assign') + color_payment_pending = fields.Char('Letter Payment Pending') + color_letter_pre_reservation = fields.Char('Letter Pre-reservation') + color_letter_reservation = fields.Char('Letter Confirmed Reservation') + color_letter_reservation_pay = fields.Char('Letter Paid Reservation') + color_letter_stay = fields.Char('Letter Checkin') + color_letter_stay_pay = fields.Char('Letter Stay Pay') + color_letter_checkout = fields.Char('Letter Checkout') + color_letter_dontsell = fields.Char('Letter Dont Sell') + color_letter_staff = fields.Char('Letter Staff') + color_letter_to_assign = fields.Char('Letter Ota to Assign') + color_letter_payment_pending = fields.Char('Letter Payment Pending') + + @api.multi + def set_values(self): + super(HotelConfiguration, self).set_values() + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_pre_reservation', self.color_pre_reservation) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_reservation', self.color_reservation) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_reservation_pay', self.color_reservation_pay) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_stay', self.color_stay) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_stay_pay', self.color_stay_pay) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_checkout', self.color_checkout) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_dontsell', self.color_dontsell) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_staff', self.color_staff) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_to_assign', self.color_to_assign) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_payment_pending', self.color_payment_pending) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_letter_pre_reservation', self.color_letter_pre_reservation) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_letter_reservation', self.color_letter_reservation) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_letter_reservation_pay', self.color_letter_reservation_pay) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_letter_stay', self.color_letter_stay) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_letter_stay_pay', self.color_letter_stay_pay) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_letter_checkout', self.color_letter_checkout) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_letter_dontsell', self.color_letter_dontsell) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_letter_staff', self.color_letter_staff) + self.env['ir.default'].sudo().set( + 'res.config.settings', 'color_letter_to_assign', self.color_letter_to_assign) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'color_letter_payment_pending', self.color_letter_payment_pending) + self.env['ir.default'].sudo().set( + 'res.config.settings', + 'default_arrival_hour', self.default_arrival_hour) + + @api.model + def get_values(self): + res = super(HotelConfiguration, self).get_values() + + # ONLY FOR v11. DO NOT FORWARD-PORT + color_pre_reservation = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_pre_reservation', self.color_pre_reservation) + color_reservation = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_reservation', self.color_reservation) + color_reservation_pay = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_reservation_pay', self.color_reservation_pay) + color_stay = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_stay', self.color_stay) + color_stay_pay = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_stay_pay', self.color_stay_pay) + color_checkout = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_checkout', self.color_checkout) + color_dontsell = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_dontsell', self.color_dontsell) + color_staff = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_staff', self.color_staff) + color_to_assign = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_to_assign', self.color_to_assign) + color_payment_pending = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_payment_pending', self.color_payment_pending) + color_letter_pre_reservation = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_letter_pre_reservation', self.color_letter_pre_reservation) + color_letter_reservation = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_letter_reservation', self.color_letter_reservation) + color_letter_reservation_pay = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_letter_reservation_pay', self.color_letter_reservation_pay) + color_letter_stay = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_letter_stay', self.color_letter_stay) + color_letter_stay_pay = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_letter_stay_pay', + self.color_letter_stay_pay) + color_letter_checkout = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_letter_checkout', + self.color_letter_checkout) + color_letter_dontsell = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_letter_dontsell', + self.color_letter_dontsell) + color_letter_staff = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_letter_staff', + self.color_letter_staff) + color_letter_to_assign = self.env['ir.default'].sudo().get( + 'res.config.settings', 'color_letter_to_assign', + self.color_letter_to_assign) + color_letter_payment_pending = self.env['ir.default'].sudo().get( + 'res.config.settings', + 'color_letter_payment_pending', self.color_letter_payment_pending) + res.update( + color_pre_reservation=color_pre_reservation, + color_reservation=color_reservation, + color_reservation_pay=color_reservation_pay, + color_stay=color_stay, + color_stay_pay=color_stay_pay, + color_checkout=color_checkout, + color_dontsell=color_dontsell, + color_staff=color_staff, + color_to_assign=color_to_assign, + color_payment_pending=color_payment_pending, + color_letter_pre_reservation=color_letter_pre_reservation, + color_letter_reservation=color_letter_reservation, + color_letter_reservation_pay=color_letter_reservation_pay, + color_letter_stay=color_letter_stay, + color_letter_stay_pay=color_letter_stay_pay, + color_letter_checkout=color_letter_checkout, + color_letter_dontsell=color_letter_dontsell, + color_letter_staff=color_letter_staff, + color_letter_to_assign=color_letter_to_assign, + color_letter_payment_pending=color_letter_payment_pending, + ) + return res diff --git a/hotel_calendar/models/virtual_room_pricelist_cached.py b/hotel_calendar/models/virtual_room_pricelist_cached.py new file mode 100644 index 000000000..5d1395fd7 --- /dev/null +++ b/hotel_calendar/models/virtual_room_pricelist_cached.py @@ -0,0 +1,17 @@ +# Copyright 2018 Alexandre Díaz +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +from odoo import models, fields, api +from odoo.exceptions import ValidationError + + +class VirtualRoomPricelistCached(models.Model): + ''' + Cached Pricelist. Used only for Calendar Values + ''' + + _name = 'virtual.room.pricelist.cached' + + virtual_room_id = fields.Many2one('hotel.virtual.room', 'Virtual Room', + required=True, track_visibility='always') + price = fields.Float('Price', default=0.0) + date = fields.Date('Date', required=True, track_visibility='always') diff --git a/hotel_calendar/readme/CONTRIBUTORS.rst b/hotel_calendar/readme/CONTRIBUTORS.rst new file mode 100644 index 000000000..55873688c --- /dev/null +++ b/hotel_calendar/readme/CONTRIBUTORS.rst @@ -0,0 +1 @@ +* Alexandre Díaz diff --git a/hotel_calendar/readme/DESCRIPTION.rst b/hotel_calendar/readme/DESCRIPTION.rst new file mode 100644 index 000000000..a7d8b5ff5 --- /dev/null +++ b/hotel_calendar/readme/DESCRIPTION.rst @@ -0,0 +1,8 @@ +This module adds new view type "pms" + +Features: + + * Responsive & Interactive PMS + * Revenue Management + * Long-Polling Communication + diff --git a/hotel_calendar/readme/ROADMAP.rst b/hotel_calendar/readme/ROADMAP.rst new file mode 100644 index 000000000..ed40c796a --- /dev/null +++ b/hotel_calendar/readme/ROADMAP.rst @@ -0,0 +1,2 @@ +* Improve paginator speed +* Improve theme diff --git a/hotel_calendar/readme/USAGE.rst b/hotel_calendar/readme/USAGE.rst new file mode 100644 index 000000000..21364b658 --- /dev/null +++ b/hotel_calendar/readme/USAGE.rst @@ -0,0 +1,5 @@ +The following keyboard shortcuts are implemented: + +* Toggle Advance Search - ALT Key + X Key +* SWAP MODE - CTRL Key + LEFT MOUSE CLICK +* ``ESC`` to cancel active action (ex. Swap) diff --git a/hotel_calendar/security/ir.model.access.csv b/hotel_calendar/security/ir.model.access.csv new file mode 100644 index 000000000..eb1e32c43 --- /dev/null +++ b/hotel_calendar/security/ir.model.access.csv @@ -0,0 +1,5 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_virtual_price_cache_user,hotel_calendar.model_virtual_room_pricelist_cached_user,hotel_calendar.model_virtual_room_pricelist_cached,hotel.group_hotel_user,1,1,1,1 +access_virtual_price_cache_call,hotel_calendar.model_virtual_room_pricelist_cached_call,hotel_calendar.model_virtual_room_pricelist_cached,hotel.group_hotel_call,1,1,1,1 +access_hotel_product_pricelist_item_call,hotel_calendar.pricelist_item_call,hotel_calendar.model_product_pricelist_item,hotel.group_hotel_call,1,1,1,1 +access_hotel_product_pricelist_item_user,hotel_calendar.pricelist_item_use,hotel_calendar.model_product_pricelist_item,hotel.group_hotel_user,1,1,1,1 diff --git a/hotel_calendar/static/description/eiqui_logo.png b/hotel_calendar/static/description/eiqui_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..ca3bd8c1321a85719347fea0ba79a2320b29eb69 GIT binary patch literal 6240 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 DYa-VG literal 0 HcmV?d00001 diff --git a/hotel_calendar/static/description/icon_calendar.png b/hotel_calendar/static/description/icon_calendar.png new file mode 100644 index 0000000000000000000000000000000000000000..45ab4dc2931dc4e4d40244268a9a071e73a08778 GIT binary patch literal 4155 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 literal 0 HcmV?d00001 diff --git a/hotel_calendar/static/description/icon_calendar_configurator.png b/hotel_calendar/static/description/icon_calendar_configurator.png new file mode 100644 index 0000000000000000000000000000000000000000..bce8eb8f191c8de2cbf5b05a070194e7079edbde GIT binary patch literal 5221 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 g`D^Hx{JOih +
+
+
+

HOTEL CALENDAR

+

Hotel Calendar

+
+
+

Hotel Calendar

+
+ +
+ +
+
+ + + +
+
+
+ diff --git a/hotel_calendar/static/src/css/view.css b/hotel_calendar/static/src/css/view.css new file mode 100644 index 000000000..4fa4e944c --- /dev/null +++ b/hotel_calendar/static/src/css/view.css @@ -0,0 +1,96 @@ +/* + * Hotel Calendar JS v0.0.1a - 2017 + * GNU Public License + * Aloxa Solucions S.L. + * Alexandre Díaz + */ + + +/* .openerp .oe-view-manager { + overflow: initial !important; +} + */ +.nopadding { + padding: 0 !important; + margin: 0 !important; +} + +#pms-menu { + padding: 0 0.2em !important; +} +#pms-menu button { + min-height: 45px; + margin: 0.2em 0; +} + +#pms-search { + padding: 0.5em !important; + background-color: white; + box-shadow: 10px 1px 12px #333; +} +#pms-search fieldset { + display: inline-block; +} +#pms-search fieldset legend { + font-size: initial !important; + margin: initial !important; +} +#pms-search .list { + overflow-y: auto; + text-align: left; +} +#pms-search label { + font-size: 12px; +} + +#pms-search-table > tbody > tr > td { + background-color: white; + padding: 0.1em; + border: 1px solid #efefef; + border-width: 0 2px; + vertical-align: middle; + text-align: center; +} +#pms-search-table > tbody > tr > td:first-child { + border-width: 0 2px 0 0; +} +#pms-search-table > tbody > tr > td:last-child { + border-width: 0 0 0 2px; +} + +#pms-search-cal-pag .btn { + background-color: transparent; + padding: 0.1em; +} + +.input-group { + padding: 0.1em; +} + +/** SELECT 2 **/ +#pms-search .select2-search-choice { + padding-top: 1px !important; + padding-bottom: 1px !important; + font-size: 10px !important; +} +#pms-search .select2-search-choice-close { + top: 1px !important; +} + +/** BOOTSTRAP **/ +.badge-danger { + background-color: #d34f2a !important; +} + +/** FONT AWESOME **/ +.cloud-text { + margin-top: .12em; + font-size: 26px; + font-family: sans-serif; + font-weight: bold; +} + +/** ODOO **/ +.o_chat_window { + z-index: 8 !important; +} diff --git a/hotel_calendar/static/src/js/open_reservation_wizard_listview_button.js b/hotel_calendar/static/src/js/open_reservation_wizard_listview_button.js new file mode 100644 index 000000000..974594a59 --- /dev/null +++ b/hotel_calendar/static/src/js/open_reservation_wizard_listview_button.js @@ -0,0 +1,28 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.listview_button_open_reservation_wizard', function(require) { +'use strict'; + +var ListView = require('web.ListView'), + Core = require('web.core'), + + _t = Core._t; + + +ListView.include({ + render_buttons: function () { + var self = this; + this._super.apply(this, arguments); // Sets this.$buttons + + if (this.dataset.model == 'hotel.reservation') { + this.$buttons.append(""); + this.$buttons.find('.oe_open_reservation_wizard').on('click', function(){ + self.do_action('hotel_calendar.open_wizard_reservations'); + }); + } + } +}); + +return ListView; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar/hotel_calendar_controller.js b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_controller.js new file mode 100644 index 000000000..91b28c8d4 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_controller.js @@ -0,0 +1,304 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.PMSCalendarController', function (require) { +"use strict"; + +var AbstractController = require('web.AbstractController'), + Core = require('web.core'), + Bus = require('bus.bus').bus, + HotelConstants = require('hotel_calendar.Constants'), + + _t = Core._t, + QWeb = Core.qweb; + +var PMSCalendarController = AbstractController.extend({ + custom_events: _.extend({}, AbstractController.prototype.custom_events, { + onLoadCalendar: '_onLoadCalendar', + onLoadCalendarSettings: '_onLoadCalendarSettings', + onLoadViewFilters: '_onLoadViewFilters', + onUpdateButtonsCounter: '_onUpdateButtonsCounter', + onReloadCalendar: '_onReloadCalendar', + }), + + init: function (parent, model, renderer, params) { + this._super.apply(this, arguments); + this.displayName = params.displayName; + this.formViewId = params.formViewId; + this.context = params.context; + + Bus.on("notification", this, this._onBusNotification); + }, + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + + //-------------------------------------------------------------------------- + // Private + //-------------------------------------------------------------------------- + + _updateRecord: function (record) { + return this.model.updateRecord(record).then(this.reload.bind(this)); + }, + + //-------------------------------------------------------------------------- + // Handlers + //-------------------------------------------------------------------------- + _onLoadCalendarSettings: function (ev) { + var self = this; + return this.model.get_hcalendar_settings().then(function(options){ + self.renderer.load_hcalendar_options(options); + }); + }, + + _onLoadCalendar: function (ev) { + var self = this; + + /** DO MAGIC **/ + var hcal_dates = this.renderer.get_view_filter_dates(); + var oparams = [ + hcal_dates[0].format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + hcal_dates[1].format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT) + ]; + this.model.get_calendar_data(oparams).then(function(results){ + + self.renderer._days_tooltips = results['events']; + self.renderer._reserv_tooltips = results['tooltips']; + var rooms = []; + for (var r of results['rooms']) { + var nroom = new HRoom( + r[0], // Id + r[1], // Name + r[2], // Capacity + r[4], // Category + r[5], // Shared Room + r[6] // Price + ); + nroom.addUserData({ + 'categ_id': r[3], + 'price_from': r[6][0] === 'fixed'?`${r[6][1]}${HotelConstants.CURRENCY_SYMBOL} (${_t('Fixed Price')})`:r[6][3], + 'inside_rooms': r[7], + 'inside_rooms_ids': r[8], + 'floor_id': r[9], + 'amenities': r[10] + }); + rooms.push(nroom); + } + + self.renderer.create_calendar('#hcal_widget', rooms, results['pricelist'], results['restrictions']); + + // TODO: Not read this... do the change!! + var reservs = []; + for (var r of results['reservations']) { + var room = self._hcalendar.getRoom(r[0], r[15], r[1]); + // need create a overbooking row? + if (!room && r[15]) { + room = self.renderer._hcalendar.createOBRoom(self._hcalendar.getRoom(r[0]), r[1]); + self.renderer._hcalendar.createOBRoomRow(room); + } + if (!room) { + console.warn(`Can't found a room for the reservation '${r[0]}'!`); + continue; + } + + var nreserv = new HReservation({ + 'id': r[1], + 'room': room, + 'title': r[2], + 'adults': r[3], + 'childrens': r[4], + 'startDate': HotelCalendar.toMomentUTC(r[5], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'endDate': HotelCalendar.toMomentUTC(r[6], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'color': r[8], + 'colorText': r[9], + 'splitted': r[10], + 'readOnly': r[12], + 'fixDays': r[13], + 'fixRooms': r[14], + 'unusedZone': false, + 'linkedId': false, + 'overbooking': r[15], + }); + nreserv.addUserData({'folio_id': r[7]}); + nreserv.addUserData({'parent_reservation': r[11]}); + reservs.push(nreserv); + } + self.renderer.load_reservations(reservs); + }); + }, + + _onReloadCalendar: function (ev) { + this.model.get_calendar_data(ev.data.oparams).then(function(results){ + this.renderer._merge_days_tooltips(results['events']); + this.renderer._reserv_tooltips = _.extend(this.renderer._reserv_tooltips, results['tooltips']); + var reservs = []; + for (var r of results['reservations']) { + var room = this.renderer._hcalendar.getRoom(r[0], r[15], r[1]); + // need create a overbooking row? + if (!room && r[15]) { + room = this.renderer._hcalendar.createOBRoom(this.renderer._hcalendar.getRoom(r[0]), r[1]); + this.renderer._hcalendar.createOBRoomRow(room); + } + if (!room) { + console.warn(`Can't found a room for the reservation '${r[0]}'!`); + continue; + } + var nreserv = new HReservation({ + 'id': r[1], + 'room': room, + 'title': r[2], + 'adults': r[3], + 'childrens': r[4], + 'startDate': HotelCalendar.toMomentUTC(r[5], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'endDate': HotelCalendar.toMomentUTC(r[6], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'color': r[8], + 'colorText': r[9], + 'splitted': r[10], + 'readOnly': r[12] || false, + 'fixDays': r[13] || false, + 'fixRooms': r[14] || false, + 'unusedZone': false, + 'linkedId': false, + 'overbooking': r[15], + }); + nreserv.addUserData({'folio_id': r[7]}); + nreserv.addUserData({'parent_reservation': r[11]}); + reservs.push(nreserv); + } + + this.renderer._hcalendar.addPricelist(results['pricelist']); + this.renderer._hcalendar.addRestrictions(results['restrictions']); + if (ev.data.clearReservations) { + this.renderer._hcalendar.setReservations(reservs); + } else { + this.renderer._hcalendar.addReservations(reservs); + } + + this.renderer._assign_extra_info(); + }.bind(this)); + }, + + _onUpdateButtonsCounter: function (ev) { + var self = this; + var domain_checkouts = [['is_checkout', '=', true]]; + var domain_checkins = [['is_checkin', '=', true]]; + var domain_overbookings = [['overbooking', '=', true], ['state', 'not in', ['cancelled']]]; + $.when( + this.model.search_count(domain_checkouts), + this.model.search_count(domain_checkins), + this.model.search_count(domain_overbookings), + ).then(function(a1, a2, a3){ + self.renderer.update_buttons_counter(a1, a2, a3); + }); + }, + + _onLoadViewFilters: function (ev) { + var self = this; + $.when( + this.model.get_room_types(), + this.model.get_floors(), + this.model.get_amenities(), + this.model.get_vrooms() + ).then(function(a1, a2, a3, a4){ + self.renderer.loadViewFilters(a1, a2, a3, a4); + }); + }, + + _onBusNotification: function(notifications) { + if (!this.renderer._hcalendar) { + return; + } + var need_reload_pricelists = false; + var need_update_counters = false; + var nreservs = [] + for (var notif of notifications) { + if (notif[0][1] === 'hotel.reservation') { + switch (notif[1]['type']) { + case 'reservation': + var reserv = notif[1]['reservation']; + // Only show notifications of other users + // if (notif[1]['subtype'] !== 'noshow' && this._view_options['show_notifications'] && notif[1]['userid'] != this.dataset.context.uid) { + // var qdict = _.clone(reserv); + // qdict = _.extend(qdict, { + // 'checkin': HotelCalendar.toMomentUTC(qdict['checkin'], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT).clone().local().format(HotelConstants.L10N_DATETIME_MOMENT_FORMAT), // UTC -> Local + // 'checkout': HotelCalendar.toMomentUTC(qdict['checkout'], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT).clone().local().format(HotelConstants.L10N_DATETIME_MOMENT_FORMAT), // UTC -> Local + // 'username': notif[1]['username'], + // 'userid': notif[1]['userid'] + // }); + // var msg = QWeb.render('HotelCalendar.Notification', qdict); + // if (notif[1]['subtype'] === "notify") { + // this.do_notify(notif[1]['title'], msg, true); + // } else if (notif[1]['subtype'] === "warn") { + // this.do_warn(notif[1]['title'], msg, true); + // } + // } + + // Create/Update/Delete reservation + if (notif[1]['action'] === 'unlink' || reserv['state'] === 'cancelled') { + this.renderer._hcalendar.removeReservation(reserv['reserv_id'], true); + this.renderer._reserv_tooltips = _.pick(this.renderer._reserv_tooltips, function(value, key, obj){ return key != reserv['reserv_id']; }); + nreservs = _.reject(nreservs, function(item){ return item.id == reserv['reserv_id']; }); + } else { + nreservs = _.reject(nreservs, {'id': reserv['reserv_id']}); // Only like last changes + var room = this.renderer._hcalendar.getRoom(reserv['product_id'], reserv['overbooking'], reserv['reserv_id']); + // need create a overbooking row? + if (!room && reserv['overbooking']) { + room = this.renderer._hcalendar.createOBRoom(this.renderer._hcalendar.getRoom(reserv['product_id']), reserv['reserv_id']); + this.renderer._hcalendar.createOBRoomRow(room); + } + if (!room) { + console.warn(`Can't found a room for the reservation '${reserv['reserv_id']}'!`); + continue; + } + if (room) { + var nreserv = new HReservation({ + 'id': reserv['reserv_id'], + 'room': room, + 'title': reserv['partner_name'], + 'adults': reserv['adults'], + 'childrens': reserv['children'], + 'startDate': HotelCalendar.toMomentUTC(reserv['checkin'], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'endDate': HotelCalendar.toMomentUTC(reserv['checkout'], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'color': reserv['reserve_color'], + 'colorText': reserv['reserve_color_text'], + 'splitted': reserv['splitted'], + 'readOnly': reserv['read_only'], + 'fixDays': reserv['fix_days'], + 'fixRooms': reserv['fix_rooms'], + 'unusedZone': false, + 'linkedId': false, + 'overbooking': reserv['overbooking'], + }); + nreserv.addUserData({'folio_id': reserv['folio_id']}); + nreserv.addUserData({'parent_reservation': reserv['parent_reservation']}); + this.renderer._reserv_tooltips[reserv['reserv_id']] = notif[1]['tooltip']; + nreservs.push(nreserv); + } + } + need_update_counters = true; + break; + case 'pricelist': + this.renderer._hcalendar.addPricelist(notif[1]['price']); + break; + case 'restriction': + this.renderer._hcalendar.addRestrictions(notif[1]['restriction']); + break; + default: + // Do Nothing + } + } + } + if (nreservs.length > 0) { + this.renderer._hcalendar.addReservations(nreservs); + } + if (need_update_counters) { + this._onUpdateButtonsCounter(); + } + }, + +}); + +return PMSCalendarController; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar/hotel_calendar_model.js b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_model.js new file mode 100644 index 000000000..b1542c5e3 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_model.js @@ -0,0 +1,119 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.PMSCalendarModel', function (require) { +"use strict"; + +var AbstractModel = require('web.AbstractModel'), + Context = require('web.Context'), + Core = require('web.core'), + FieldUtils = require('web.field_utils'), + Session = require('web.session'); + + +return AbstractModel.extend({ + init: function () { + this._super.apply(this, arguments); + this.end_date = null; + }, + + load: function (params) { + this.modelName = params.modelName; + this.modelManagementName = 'hotel.calendar.management' + }, + + save_pricelist: function(params) { + return this._rpc({ + model: this.modelManagementName, + method: 'save_changes', + args: params, + context: Session.user_context, + }); + }, + + swap_reservations: function(fromIds, toIds) { + return this._rpc({ + model: this.modelName, + method: 'swap_reservations', + args: [fromIds, toIds], + context: Session.user_context, + }); + }, + + get_calendar_data: function(oparams) { + return this._rpc({ + model: this.modelName, + method: 'get_hcalendar_all_data', + args: oparams, + context: Session.user_context, + }); + }, + + get_hcalendar_settings: function() { + return this._rpc({ + model: this.modelName, + method: 'get_hcalendar_settings', + args: [false], + }); + }, + + get_room_types: function() { + return this._rpc({ + model: 'hotel.room.type', + method: 'search_read', + args: [false, ['cat_id','name']], + context: Session.user_context, + }); + }, + get_floors: function() { + return this._rpc({ + model: 'hotel.floor', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + get_amenities: function() { + return this._rpc({ + model: 'hotel.room.amenities', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + get_vrooms: function() { + return this._rpc({ + model: 'hotel.virtual.room', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + + search_count: function(domain) { + return this._rpc({ + model: this.modelName, + method: 'search_count', + args: [domain], + context: Session.user_context, + }); + }, + + update_records: function(ids, vals) { + return this._rpc({ + model: this.modelName, + method: 'write', + args: [ids, write_values], + context: Session.user_context, + }); + }, + + folio_search_count: function(domain) { + return this._rpc({ + model: 'hotel.folio', + method: 'search_count', + args: [domain], + context: Session.user_context, + }); + }, +}); +}); diff --git a/hotel_calendar/static/src/js/views/calendar/hotel_calendar_renderer.js b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_renderer.js new file mode 100644 index 000000000..d8a4fa235 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_renderer.js @@ -0,0 +1,840 @@ +/* global $, odoo, _, HotelCalendar, moment */ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.PMSCalendarRenderer', function (require) { +"use strict"; + +var Core = require('web.core'), + ViewDialogs = require('web.view_dialogs'), + Dialog = require('web.Dialog'), + Session = require('web.session'), + AbstractRenderer = require('web.AbstractRenderer'), + HotelConstants = require('hotel_calendar.Constants'), + //Formats = require('web.formats'), + + _t = Core._t, + _lt = Core._lt, + QWeb = Core.qweb; + +var HotelCalendarView = AbstractRenderer.extend({ + /** VIEW OPTIONS **/ + template: "hotel_calendar.HotelCalendarView", + display_name: _lt('Hotel Calendar'), + icon: 'fa fa-map-marker', + searchable: false, + searchview_hidden: true, + + // Custom Options + _view_options: {}, + _hcalendar: null, + _reserv_tooltips: {}, + _days_tooltips: [], + _last_dates: [false, false], + + + /** VIEW METHODS **/ + init: function(parent, state, params) { + this._super.apply(this, arguments); + this.model = params.model; + }, + + start: function () { + return this._super().then(function() { + this.init_calendar_view(); + }.bind(this)); + }, + + on_attach_callback: function() { + this._super(); + + if (this._hcalendar && !this._is_visible) { + // FIXME: Workaround for restore "lost" reservations (Drawn when the view is hidden) + setTimeout(function(){ + for (var reserv of this._hcalendar._reservations) { + var style = window.getComputedStyle(reserv._html, null); + if (parseInt(style.width, 10) < 15 || parseInt(style.height, 10) < 15 || parseInt(style.top, 10) === 0) { + this._hcalendar._updateReservation(reserv); + } + } + }.bind(this), 300); + } + }, + + /** CUSTOM METHODS **/ + _generate_reservation_tooltip_dict: function(tp) { + return { + 'name': tp[0], + 'phone': tp[1], + 'arrival_hour': HotelCalendar.toMomentUTC(tp[2], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT).local().format('HH:mm'), + 'num_split': tp[3], + 'amount_total': Number(tp[4]).toLocaleString() + }; + }, + + load_reservations: function(reservs) { + this._hcalendar.setReservations(reservs); + this._assign_extra_info(); + }, + + get_view_filter_dates: function () { + var $dateTimePickerBegin = this.$el.find('#pms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#pms-search #date_end'); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().set({'hour': 0, 'minute': 0, 'second': 0}).clone().utc(); + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().set({'hour': 23, 'minute': 59, 'second': 59}).clone().utc(); + + return [date_begin, date_end]; + }, + + load_hcalendar_options: function(options) { + // View Options + this._view_options = options; + var date_begin = moment().startOf('day'); + if (['xs', 'md'].indexOf(this._find_bootstrap_environment()) >= 0) { + this._view_options['days'] = 7; + } else { + this._view_options['days'] = (this._view_options['days'] !== 'month')?parseInt(this._view_options['days']):date_begin.daysInMonth(); + } + var date_end = date_begin.clone().add(this._view_options['days'], 'd').endOf('day'); + var $dateTimePickerBegin = this.$el.find('#pms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#pms-search #date_end'); + //$dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + //$dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + this._last_dates = this.get_view_filter_dates(); + }, + + destroy_calendar: function() { + if (this._hcalendar) { + this._hcalendar.$base.empty(); + delete this._hcalendar; + } + }, + + create_calendar: function(containerSelector, rooms, pricelist, restrictions) { + this.destroy_calendar(); + + var options = { + startDate: HotelCalendar.toMomentUTC(this._last_dates[0], HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + days: this._view_options['days'] + 1, + rooms: rooms, + endOfWeek: parseInt(this._view_options['eday_week']) || 6, + divideRoomsByCapacity: this._view_options['divide_rooms_by_capacity'] || false, + allowInvalidActions: this._view_options['allow_invalid_actions'] || false, + assistedMovement: this._view_options['assisted_movement'] || false, + showPricelist: this._view_options['show_pricelist'] || false, + showAvailability: this._view_options['show_availability'] || false, + showNumRooms: this._view_options['show_num_rooms'] || 0, + endOfWeekOffset: this._view_options['eday_week_offset'] || 0 + }; + + this._hcalendar = new HotelCalendar(containerSelector, options, pricelist, restrictions, this.$el[0]); + this._assign_hcalendar_events(); + }, + + _assign_hcalendar_events: function() { + var self = this; + this._hcalendar.addEventListener('hcalOnSavePricelist', function(ev){ + var pricelist = self._hcalendar.getPricelist(); + var oparams = [false, self._hcalendar._pricelist_id, false, pricelist, {}, {}]; + self._rpc({ + model: 'hotel.calendar.management', + method: 'save_changes', + args: oparams, + context: Session.user_context, + }).then(function(results){ + $(self._hcalendar.btnSaveChanges).removeClass('need-save'); + $('.hcal-input-changed').removeClass('hcal-input-changed'); + }); + }); + this._hcalendar.addEventListener('hcalOnMouseEnterReservation', function(ev){ + if (ev.detail.reservationObj) { + var tp = self._reserv_tooltips[ev.detail.reservationObj.id]; + var qdict = self._generate_reservation_tooltip_dict(tp); + $(ev.detail.reservationDiv).tooltip('destroy').tooltip({ + animation: false, + html: true, + placement: 'bottom', + title: QWeb.render('HotelCalendar.TooltipReservation', qdict) + }).tooltip('show'); + } + }); + this._hcalendar.addEventListener('hcalOnClickReservation', function(ev){ + //var res_id = ev.detail.reservationObj.getUserData('folio_id'); + $(ev.detail.reservationDiv).tooltip('hide'); + self.do_action({ + type: 'ir.actions.act_window', + res_model: 'hotel.reservation', + res_id: ev.detail.reservationObj.id, + views: [[false, 'form']] + }); + // self._model.call('get_formview_id', [res_id, Session.user_context]).then(function(view_id){ + // var pop = new ViewDialogs.FormViewDialog(self, { + // res_model: 'hotel.folio', + // res_id: res_id, + // title: _t("Open: ") + ev.detail.reservationObj.title, + // view_id: view_id + // //readonly: false + // }).open(); + // pop.on('write_completed', self, function(){ + // self.trigger('changed_value'); + // }); + // }); + }); + this._hcalendar.addEventListener('hcalOnSwapReservations', function(ev){ + var qdict = {}; + var dialog = new Dialog(self, { + title: _t("Confirm Reservation Swap"), + buttons: [ + { + text: _t("Yes, swap it"), + classes: 'btn-primary', + close: true, + click: function () { + if (self._hcalendar.swapReservations(ev.detail.inReservs, ev.detail.outReservs)) { + var fromIds = _.pluck(ev.detail.inReservs, 'id'); + var toIds = _.pluck(ev.detail.outReservs, 'id'); + var refFromReservDiv = ev.detail.inReservs[0]._html; + var refToReservDiv = ev.detail.outReservs[0]._html; + + // Animate Movement + for (var nreserv of ev.detail.inReservs) { + $(nreserv._html).animate({'top': refToReservDiv.style.top}); + } + for (var nreserv of ev.detail.outReservs) { + $(nreserv._html).animate({'top': refFromReservDiv.style.top}); + } + self.model.swapReservations(fromIds, toIds).then(function(results){ + var allReservs = ev.detail.inReservs.concat(ev.detail.outReservs); + for (nreserv of allReservs) { + $(nreserv._html).stop(true); + } + }).fail(function(err, errev){ + for (var nreserv of ev.detail.inReservs) { + $(nreserv._html).animate({'top': refFromReservDiv.style.top}, 'fast'); + } + for (var nreserv of ev.detail.outReservs) { + $(nreserv._html).animate({'top': refToReservDiv.style.top}, 'fast'); + } + + self._hcalendar.swapReservations(ev.detail.outReservs, ev.detail.inReservs); + }); + } else { + var qdict = {}; + var dialog = new Dialog(self, { + title: _t("Invalid Reservation Swap"), + buttons: [ + { + text: _t("Oops, Ok!"), + classes: 'btn-primary', + close: true + } + ], + $content: QWeb.render('HotelCalendar.InvalidSwapOperation', qdict) + }).open(); + } + } + }, + { + text: _t("No"), + close: true + } + ], + $content: QWeb.render('HotelCalendar.ConfirmSwapOperation', qdict) + }).open(); + }); + this._hcalendar.addEventListener('hcalOnCancelSwapReservations', function(ev){ + $("#btn_swap span.ntext").html(_t("START SWAP")); + $("#btn_swap").css({ + 'backgroundColor': '', + 'fontWeight': 'normal' + }); + }); + this._hcalendar.addEventListener('hcalOnChangeReservation', function(ev){ + var newReservation = ev.detail.newReserv; + var oldReservation = ev.detail.oldReserv; + var oldPrice = ev.detail.oldPrice; + var newPrice = ev.detail.newPrice; + var folio_id = newReservation.getUserData('folio_id'); + + var linkedReservs = _.find(self._hcalendar._reservations, function(item){ + return item.id !== newReservation.id && !item.unusedZone && item.getUserData('folio_id') === folio_id; + }); + + var hasChanged = false; + + var qdict = { + ncheckin: newReservation.startDate.clone().local().format(HotelConstants.L10N_DATETIME_MOMENT_FORMAT), + ncheckout: newReservation.endDate.clone().local().format(HotelConstants.L10N_DATETIME_MOMENT_FORMAT), + nroom: newReservation.room.number, + nprice: newPrice, + ocheckin: oldReservation.startDate.clone().local().format(HotelConstants.L10N_DATETIME_MOMENT_FORMAT), + ocheckout: oldReservation.endDate.clone().local().format(HotelConstants.L10N_DATETIME_MOMENT_FORMAT), + oroom: oldReservation.room.number, + oprice: oldPrice, + hasReservsLinked: (linkedReservs && linkedReservs.length !== 0)?true:false + }; + var dialog = new Dialog(self, { + title: _t("Confirm Reservation Changes"), + buttons: [ + { + text: _t("Yes, change it"), + classes: 'btn-primary', + close: true, + disabled: !newReservation.id, + click: function () { + var roomId = newReservation.room.id; + if (newReservation.room.overbooking) { + roomId = +newReservation.room.id.substr(newReservation.room.id.indexOf('@')+1); + } + var write_values = { + 'checkin': newReservation.startDate.format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'checkout': newReservation.endDate.format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'product_id': roomId, + 'overbooking': newReservation.room.overbooking + }; + self.model.update_records([newReservation.id], write_values).then(function(result){ + // Remove OB Room Row? + if (oldReservation.room.overbooking) { + self._hcalendar.removeOBRoomRow(oldReservation); + } + }).fail(function(err, errev){ + self._hcalendar.replaceReservation(newReservation, oldReservation); + }); + // Workarround for dispatch room lines regeneration + // new Model('hotel.reservation').call('on_change_checkin_checkout_product_id', [[newReservation.id], false]); + hasChanged = true; + } + }, + { + text: _t("No"), + close: true, + } + ], + $content: QWeb.render('HotelCalendar.ConfirmReservationChanges', qdict) + }).open(); + dialog.$modal.on('hide.bs.modal', function(e){ + if (!hasChanged) { + self._hcalendar.replaceReservation(newReservation, oldReservation); + } + }); + }); + this._hcalendar.addEventListener('hcalOnUpdateSelection', function(ev){ + for (var td of ev.detail.old_cells) { + $(td).tooltip('destroy'); + } + if (ev.detail.cells.length > 1) { + var last_cell = ev.detail.cells[ev.detail.cells.length-1]; + var date_cell_start = HotelCalendar.toMoment(self._hcalendar.etable.querySelector(`#${ev.detail.cells[0].dataset.hcalParentCell}`).dataset.hcalDate); + var date_cell_end = HotelCalendar.toMoment(self._hcalendar.etable.querySelector(`#${last_cell.dataset.hcalParentCell}`).dataset.hcalDate); + var parentRow = document.querySelector(`#${ev.detail.cells[0].dataset.hcalParentRow}`); + var room = self._hcalendar.getRoom(parentRow.dataset.hcalRoomObjId); + if (room.overbooking) { + return; + } + var nights = date_cell_end.diff(date_cell_start, 'days'); + var qdict = { + 'total_price': Number(ev.detail.totalPrice).toLocaleString(), + 'nights': nights + }; + $(last_cell).tooltip({ + animation: false, + html: true, + placement: 'top', + title: QWeb.render('HotelCalendar.TooltipSelection', qdict) + }).tooltip('show'); + } + }); + this._hcalendar.addEventListener('hcalOnChangeSelection', function(ev){ + var parentRow = document.querySelector(`#${ev.detail.cellStart.dataset.hcalParentRow}`); + var parentCellStart = document.querySelector(`#${ev.detail.cellStart.dataset.hcalParentCell}`); + var parentCellEnd = document.querySelector(`#${ev.detail.cellEnd.dataset.hcalParentCell}`); + var startDate = HotelCalendar.toMoment(parentCellStart.dataset.hcalDate); + var endDate = HotelCalendar.toMoment(parentCellEnd.dataset.hcalDate); + var room = self._hcalendar.getRoom(parentRow.dataset.hcalRoomObjId); + if (room.overbooking) { + return; + } + var numBeds = (room.shared || self._hcalendar.getOptions('divideRoomsByCapacity'))?(ev.detail.cellEnd.dataset.hcalBedNum - ev.detail.cellStart.dataset.hcalBedNum)+1:room.capacity; + if (numBeds <= 0) { + return; + } + + // Normalize Dates + if (startDate.isAfter(endDate)) { + var tt = endDate; + endDate = startDate; + startDate = tt; + } + + var def_arrival_hour = self._view_options['default_arrival_hour'].split(':'); + var def_departure_hour = self._view_options['default_departure_hour'].split(':'); + startDate.set({'hour': def_arrival_hour[0], 'minute': def_arrival_hour[1], 'second': 0}); + endDate.set({'hour': def_departure_hour[0], 'minute': def_departure_hour[1], 'second': 0}); + + var popCreate = new ViewDialogs.FormViewDialog(self, { + res_model: 'hotel.reservation', + context: { + 'default_checkin': startDate.utc().format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'default_checkout': endDate.utc().format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + 'default_adults': numBeds, + 'default_children': 0, + 'default_product_id': room.id, + }, + title: _t("Create: ") + _t("Reservation"), + initial_view: "form", + disable_multiple_selection: true, + }).open(); + }); + + this._hcalendar.addEventListener('hcalOnDateChanged', function(ev){ + var $dateTimePickerBegin = this.$el.find('#pms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#pms-search #date_end'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").minDate(false); + $dateTimePickerEnd.data("DateTimePicker").maxDate(false); + $dateTimePickerBegin.data("DateTimePicker").date(ev.detail.date_begin.local().add(1, 'd')); + $dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").date(ev.detail.date_end.local()); + this.reload_hcalendar_reservations(false); + }.bind(this)); + }, + + _assign_extra_info: function() { + var self = this; + $(this._hcalendar.etable).find('.hcal-cell-room-type-group-item.btn-hcal-3d').on("mouseenter", function(){ + var $this = $(this); + var room = self._hcalendar.getRoom($this.parent().data("hcalRoomObjId")); + if (room.overbooking) { + $this.tooltip({ + animation: true, + html: true, + placement: 'right', + title: QWeb.render('HotelCalendar.TooltipRoomOverbooking', {'name': room.number}) + }).tooltip('show'); + return; + } else { + var qdict = { + 'price_from': room.getUserData('price_from'), + 'inside_rooms': room.getUserData('inside_rooms'), + 'num_inside_rooms': room.getUserData('inside_rooms').length, + 'name': room.number + }; + $this.tooltip({ + animation: true, + html: true, + placement: 'right', + title: QWeb.render('HotelCalendar.TooltipRoom', qdict) + }).tooltip('show'); + } + }); + + $(this._hcalendar.etableHeader).find('.hcal-cell-header-day').each(function(index, elm){ + var $elm = $(elm); + var cdate = HotelCalendar.toMoment($elm.data('hcalDate'), HotelConstants.L10N_DATE_MOMENT_FORMAT); + var data = _.filter(self._days_tooltips, function(item) { + var ndate = HotelCalendar.toMoment(item[2], HotelConstants.ODOO_DATE_MOMENT_FORMAT); + return ndate.isSame(cdate, 'd'); + }); + if (data.length > 0) { + $elm.addClass('hcal-event-day'); + $elm.prepend(""); + $elm.on("mouseenter", function(data){ + var $this = $(this); + if (data.length > 0) { + var qdict = { + 'date': $this.data('hcalDate'), + 'events': _.map(data, function(item){ + return { + 'name': item[1], + 'date': item[2], + 'location': item[3] + }; + }) + }; + $this.attr('title', ''); + $this.tooltip({ + animation: true, + html: true, + placement: 'bottom', + title: QWeb.render('HotelCalendar.TooltipEvent', qdict) + }).tooltip('show'); + } + }.bind(elm, data)); + } + }); + }, + + update_buttons_counter: function(ncheckouts, ncheckins, noverbookings) { + var self = this; + // Checkouts Button + var $ninfo = self.$el.find('#pms-menu #btn_action_checkout div.ninfo'); + var $badge_checkout = $ninfo.find('.badge'); + if (ncheckouts > 0) { + $badge_checkout.text(ncheckouts); + $badge_checkout.parent().show(); + $ninfo.show(); + } else { + $ninfo.hide(); + } + + // Checkins Button + $ninfo = self.$el.find('#pms-menu #btn_action_checkin div.ninfo'); + var $badge_checkin = $ninfo.find('.badge'); + if (ncheckins > 0) { + $badge_checkin.text(ncheckins); + $badge_checkin.parent().show(); + $ninfo.show(); + } else { + $ninfo.hide(); + } + + // OverBookings + $ninfo = self.$el.find('#pms-menu #btn_swap div.ninfo'); + var $badge_swap = $ninfo.find('.badge'); + if (noverbookings > 0) { + $badge_swap.text(noverbookings); + $badge_swap.parent().show(); + $ninfo.show(); + } else { + $ninfo.hide(); + } + }, + + init_calendar_view: function(){ + var self = this; + + /** VIEW CONTROLS INITIALIZATION **/ + // DATE TIME PICKERS + var DTPickerOptions = { + viewMode: 'months', + icons : { + time: 'fa fa-clock-o', + date: 'fa fa-calendar', + up: 'fa fa-chevron-up', + down: 'fa fa-chevron-down' + }, + //language : moment.locale(), + locale : moment.locale(), + format : HotelConstants.L10N_DATE_MOMENT_FORMAT, + }; + var $dateTimePickerBegin = this.$el.find('#pms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#pms-search #date_end'); + $dateTimePickerBegin.datetimepicker(DTPickerOptions); + $dateTimePickerEnd.datetimepicker($.extend({}, DTPickerOptions, { 'useCurrent': false })); + $dateTimePickerBegin.on("dp.change", function (e) { + $dateTimePickerEnd.data("DateTimePicker").minDate(e.date.clone().add(3,'d')); + $dateTimePickerEnd.data("DateTimePicker").maxDate(e.date.clone().add(2,'M')); + $dateTimePickerBegin.data("DateTimePicker").hide(); + self.on_change_filter_date(true); + }); + $dateTimePickerEnd.on("dp.change", function (e) { + $dateTimePickerEnd.data("DateTimePicker").hide(); + self.on_change_filter_date(false); + }); + + var date_begin = moment().startOf('day'); + var days = date_begin.daysInMonth(); + var date_end = date_begin.clone().add(days, 'd').endOf('day'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + this._last_dates = this.get_view_filter_dates(); + + // Initial State + var $pms_search = this.$el.find('#pms-search'); + $pms_search.css({ + 'top': `-100%`, + 'opacity': 0.0, + }); + // Show search (Alt+S) + $(document).keydown(function(ev){ + if (ev.altKey){ + if (ev.key == 'x' || ev.key == 'X'){ + self.toggle_pms_search(); + } + } + }); + + /* TOUCH EVENTS */ + this.$el.on('touchstart', function(ev){ + var orgEvent = ev.originalEvent; + this._mouseEventStartPos = [orgEvent.touches[0].screenX, orgEvent.touches[0].screenY]; + }); + this.$el.on('touchend', function(ev){ + var orgEvent = ev.originalEvent; + if (orgEvent.changedTouches.length > 2) { + var mousePos = [orgEvent.changedTouches[0].screenX, orgEvent.changedTouches[0].screenY]; + var mouseDiffX = mousePos[0] - this._mouseEventStartPos[0]; + var moveLength = 40; + var date_begin = false; + var days = orgEvent.changedTouches.length == 3 && 7 || 1; + if (mouseDiffX < -moveLength) { + date_begin = $dateTimePickerBegin.data("DateTimePicker").date().set({'hour': 0, 'minute': 0, 'second': 0}).clone().add(days, 'd'); + } + else if (mouseDiffX > moveLength) { + date_begin = $dateTimePickerBegin.data("DateTimePicker").date().set({'hour': 0, 'minute': 0, 'second': 0}).clone().subtract(days, 'd'); + } + if (date_begin) { + var date_end = date_begin.clone().add(self._view_options['days'], 'd').endOf('day'); + $dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + } + } + }); + + /* BUTTONS */ + var $button = this.$el.find('#pms-menu #btn_action_bookings'); + $button.on('click', function(ev){ self._open_bookings_tree(); }); + var $btnInput = this.$el.find('#pms-menu #bookings_search'); + $btnInput.on('keypress', function(ev){ + if (ev.keyCode === 13) { + self._open_bookings_tree(); + } + }); + + this.$el.find("button[data-action]").on('click', function(ev){ + self.do_action(this.dataset.action); + }); + + this.$el.find("#btn_swap").on('click', function(ev){ + var hcalSwapMode = self._hcalendar.getSwapMode(); + if (hcalSwapMode === HotelCalendar.MODE.NONE) { + self._hcalendar.setSwapMode(HotelCalendar.MODE.SWAP_FROM); + $("#btn_swap span.ntext").html(_t("CONTINUE")); + $("#btn_swap").css({ + 'backgroundColor': 'rgb(145, 255, 0)', + 'fontWeight': 'bold' + }); + } else if (self._hcalendar.getReservationAction().inReservations.length > 0 && hcalSwapMode === HotelCalendar.MODE.SWAP_FROM) { + self._hcalendar.setSwapMode(HotelCalendar.MODE.SWAP_TO); + $("#btn_swap span.ntext").html(_t("END")); + $("#btn_swap").css({ + 'backgroundColor': 'orange', + 'fontWeight': 'bold' + }); + } else { + self._hcalendar.setSwapMode(HotelCalendar.MODE.NONE); + $("#btn_swap span.ntext").html(_t("START SWAP")); + $("#btn_swap").css({ + 'backgroundColor': '', + 'fontWeight': '' + }); + } + }); + + return $.when( + this.trigger_up('onLoadCalendarSettings'), + this.trigger_up('onUpdateButtonsCounter'), + this.trigger_up('onLoadCalendar'), + this.trigger_up('onLoadViewFilters'), + ); + }, + + loadViewFilters: function(resultsHotelRoomType, resultsHotelFloor, resultsHotelRoomAmenities, resultsHotelVirtualRooms) { + var $list = this.$el.find('#pms-search #type_list'); + $list.html(''); + resultsHotelRoomType.forEach(function(item, index){ + $list.append(``); + }); + $list.select2({ + theme: "classic" + }); + $list.on('change', function(ev){ + this._apply_filters(); + }.bind(this)); + + // Get Floors + $list = this.$el.find('#pms-search #floor_list'); + $list.html(''); + resultsHotelFloor.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + this._apply_filters(); + }.bind(this)); + + // Get Amenities + $list = this.$el.find('#pms-search #amenities_list'); + $list.html(''); + resultsHotelRoomAmenities.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + this._apply_filters(); + }.bind(this)); + + // Get Virtual Rooms + $list = this.$el.find('#pms-search #virtual_list'); + $list.html(''); + resultsHotelVirtualRooms.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + this._apply_filters(); + }.bind(this)); + }, + + toggle_pms_search: function() { + var $pms_search = this.$el.find('#pms-search'); + if ($pms_search.position().top < 0) + { + var $navbar = $('.navbar'); + var toPos = $navbar.height() + parseInt($navbar.css('border-top-width'), 10) + parseInt($navbar.css('border-bottom-width'), 10); + $pms_search.animate({ + 'top': `${toPos}px`, + 'opacity': 1.0, + }, 'fast'); + } else { + $pms_search.animate({ + 'top': `-${$pms_search.height()}px`, + 'opacity': 0.0, + }, 'slow'); + } + }, + + _generate_bookings_domain: function(tsearch) { + var domain = []; + domain.push('|', '|', '|', '|', + ['partner_id.name', 'ilike', tsearch], + ['partner_id.mobile', 'ilike', tsearch], + ['partner_id.vat', 'ilike', tsearch], + ['partner_id.email', 'ilike', tsearch], + ['partner_id.phone', 'ilike', tsearch]); + return domain; + }, + + _open_bookings_tree: function() { + var $elm = this.$el.find('#pms-menu #bookings_search'); + var searchQuery = $elm.val(); + var domain = false; + if (searchQuery) { + domain = this._generate_bookings_domain(searchQuery); + } + + this.do_action({ + type: 'ir.actions.act_window', + view_mode: 'form', + view_type: 'tree,form', + res_model: 'hotel.reservation', + views: [[false, 'list'], [false, 'form']], + domain: domain, + name: searchQuery?'Reservations for ' + searchQuery:'All Reservations' + }); + + $elm.val(''); + }, + + on_change_filter_date: function(isStartDate) { + isStartDate = isStartDate || false; + var $dateTimePickerBegin = this.$el.find('#pms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#pms-search #date_end'); + + // FIXME: Hackish onchange ignore (Used when change dates from code) + if ($dateTimePickerBegin.data("ignore_onchange") || $dateTimePickerEnd.data("ignore_onchange")) { + $dateTimePickerBegin.data("ignore_onchange", false); + $dateTimePickerEnd.data("ignore_onchange", false) + return true; + } + + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().set({'hour': 0, 'minute': 0, 'second': 0}).clone().utc(); + + if (this._hcalendar && date_begin) { + if (isStartDate) { + var ndate_end = date_begin.clone().add(this._view_options['days'], 'd'); + $dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").date(ndate_end.local()); + } + + if (!date_begin.isSame(this._last_dates[0].clone().utc(), 'd') || !date_end.isSame(this._last_dates[1].clone().utc(), 'd')) { + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().set({'hour': 23, 'minute': 59, 'second': 59}).clone().utc(); + this._hcalendar.setStartDate(date_begin, this._hcalendar.getDateDiffDays(date_begin, date_end), false, function(){ + this.reload_hcalendar_reservations(false); + }.bind(this)); + } + } + }, + + reload_hcalendar_reservations: function(clearReservations) { + var filterDates = this.get_view_filter_dates(); + // Clip dates + var dfrom = filterDates[0].clone(), + dto = filterDates[1].clone(); + if (filterDates[0].isBetween(this._last_dates[0], this._last_dates[1], 'days') && filterDates[1].isAfter(this._last_dates[1], 'day')) { + dfrom = this._last_dates[1].clone().local().startOf('day').utc(); + } else if (this._last_dates[0].isBetween(filterDates[0], filterDates[1], 'days') && this._last_dates[1].isAfter(filterDates[0], 'day')) { + dto = this._last_dates[0].clone().local().endOf('day').utc(); + } else { + clearReservations = true; + } + + return $.when(this.trigger_up('onReloadCalendar', { + oparams: [ + dfrom.format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + dto.format(HotelConstants.ODOO_DATETIME_MOMENT_FORMAT), + false, + ], + clearReservations: clearReservations, + })).then(function(){ + this._last_dates = filterDates; + }); + }, + + _apply_filters: function() { + var category = _.map(this.$el.find('#pms-search #type_list').val(), function(item){ return +item; }); + var floor = _.map(this.$el.find('#pms-search #floor_list').val(), function(item){ return +item; }); + var amenities = _.map(this.$el.find('#pms-search #amenities_list').val(), function(item){ return +item; }); + var virtual = _.map(this.$el.find('#pms-search #virtual_list').val(), function(item){ return +item; }); + var domain = []; + if (category && category.length > 0) { + domain.push(['categ_id', 'in', category]); + } + if (floor && floor.length > 0) { + domain.push(['floor_id', 'in', floor]); + } + if (amenities && amenities.length > 0) { + domain.push(['amenities', 'in', amenities]); + } + if (virtual && virtual.length > 0) { + domain.push(['inside_rooms_ids', 'some', virtual]); + } + + this._hcalendar.setDomain(HotelCalendar.DOMAIN.ROOMS, domain); + }, + + _merge_days_tooltips: function(new_tooltips) { + for (var nt of new_tooltips) { + var fnt = _.find(this._days_tooltips, function(item) { return item[0] === nt[0]}); + if (fnt) { + fnt = nt; + } else { + this._days_tooltips.push(nt); + } + } + }, + + _find_bootstrap_environment: function() { + var envs = ['xs', 'sm', 'md', 'lg']; + + var $el = $('
'); + $el.appendTo($('body')); + + for (var i = envs.length - 1; i >= 0; i--) { + var env = envs[i]; + + $el.addClass('hidden-'+env); + if ($el.is(':hidden')) { + $el.remove(); + return env; + } + } + } +}); + +return HotelCalendarView; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar/hotel_calendar_view.js b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_view.js new file mode 100644 index 000000000..cc863f29f --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar/hotel_calendar_view.js @@ -0,0 +1,211 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.PMSCalendarView', function (require) { +"use strict"; + +var AbstractView = require('web.AbstractView'), + PMSCalendarModel = require('hotel_calendar.PMSCalendarModel'), + PMSCalendarController = require('hotel_calendar.PMSCalendarController'), + PMSCalendarRenderer = require('hotel_calendar.PMSCalendarRenderer'), + ViewRegistry = require('web.view_registry'), + SystrayMenu = require('web.SystrayMenu'), + ControlPanel = require('web.ControlPanel'), + Widget = require('web.Widget'), + Session = require('web.session'), + Core = require('web.core'), + + _lt = Core._lt, + QWeb = Core.qweb; + +/* HIDE CONTROL PANEL */ +/* FIXME: Look's like a hackish solution */ +ControlPanel.include({ + update: function(status, options) { + if (typeof options === 'undefined') { + options = {}; + } + if (typeof options.toHide === 'undefined') + options.toHide = false; + var action_stack = this.getParent().action_stack; + if (action_stack && action_stack.length) { + var active_action = action_stack[action_stack.length-1]; + if (active_action.widget && active_action.widget.active_view && + active_action.widget.active_view.type === 'pms'){ + options.toHide = true; + } + } + this._super(status, options); + this._toggle_visibility(!options.toHide); + } +}); + +/** SYSTRAY **/ +var CalendarMenu = Widget.extend({ + template: 'HotelCalendar.SettingsMenu', + events: { + "click a[data-action]": "perform_callback", + }, + + start: function(){ + this.$dropdown = this.$(".o_calendar_settings_dropdown"); + return $.when( + this._rpc({ + model: 'res.users', + method: 'read', + args: [[Session.uid], ["pms_show_notifications", "pms_show_pricelist", "pms_show_availability", "pms_divide_rooms_by_capacity"]], + context: Session.user_context, + }) + ).then(function(result) { + this._show_notifications = result[0]['pms_show_notifications']; + this._show_pricelist = result[0]['pms_show_pricelist']; + this._show_availability = result[0]['pms_show_availability']; + this._show_divide_rooms_by_capacity = result[0]['pms_divide_rooms_by_capacity']; + return this.update(); + }.bind(this)); + }, + + perform_callback: function (evt) { + evt.preventDefault(); + var params = $(evt.target).data(); + var callback = params.action; + + if (callback && this[callback]) { + this[callback](params, evt); + } else { + console.warn("No handler for ", callback); + } + }, + + update: function() { + // var view_type = this.getParent().getParent()._current_state.view_type; + // if (view_type === 'pms') { + // this.do_show(); + this.$dropdown + .empty() + .append(QWeb.render('HotelCalendar.SettingsMenu.Global', { + manager: this, + })); + // } + // else { + // this.do_hide(); + // } + return $.when(); + }, + + toggle_show_adv_controls: function() { + var $pms_search = $(document).find('#pms-search'); + if ($pms_search.position().top < 0) + { + var $navbar = $('.navbar'); + var toPos = $navbar.height() + parseInt($navbar.css('border-top-width'), 10) + parseInt($navbar.css('border-bottom-width'), 10); + $pms_search.animate({ + 'top': `${toPos}px`, + 'opacity': 1.0, + }, 'fast'); + } else { + $pms_search.animate({ + 'top': `-${$pms_search.height()}px`, + 'opacity': 0.0, + }, 'slow'); + } + }, + + toggle_show_notification: function() { + this._show_notifications = !this._show_notifications; + this._rpc({ + model: 'res.users', + method: 'write', + args: [[Session.uid], {pms_show_notifications: this._show_notifications}], + context: Session.user_context, + }).then(function () { + window.location.reload(); + }); + }, + + toggle_show_pricelist: function() { + this._show_pricelist = !this._show_pricelist; + this._rpc({ + model: 'res.users', + method: 'write', + args: [[Session.uid], {pms_show_pricelist: this._show_pricelist}], + context: Session.user_context, + }).then(function () { + window.location.reload(); + }); + }, + + toggle_show_availability: function() { + this._show_availability = !this._show_availability; + this._rpc({ + model: 'res.users', + method: 'write', + args: [[Session.uid], {pms_show_availability: this._show_availability}], + context: Session.user_context, + }).then(function () { + window.location.reload(); + }); + }, + + toggle_show_divide_rooms_by_capacity: function() { + this._show_divide_rooms_by_capacity = !this._show_divide_rooms_by_capacity; + this._rpc({ + model: 'res.users', + method: 'write', + args: [[Session.uid], {pms_divide_rooms_by_capacity: this._show_divide_rooms_by_capacity}], + context: Session.user_context, + }).then(function () { + window.location.reload(); + }); + } +}); + +var PMSCalendarView = AbstractView.extend({ + display_name: _lt('Calendar PMS'), + icon: 'fa-calendar', + jsLibs: ['/hotel_calendar/static/src/lib/hcalendar/js/hcalendar.js'], + cssLibs: ['/hotel_calendar/static/src/lib/hcalendar/css/hcalendar.css'], + config: { + Model: PMSCalendarModel, + Controller: PMSCalendarController, + Renderer: PMSCalendarRenderer, + }, + + init: function (viewInfo, params) { + this._super.apply(this, arguments); + var arch = viewInfo.arch; + var fields = viewInfo.fields; + var attrs = arch.attrs; + + // If form_view_id is set, then the calendar view will open a form view + // with this id, when it needs to edit or create an event. + this.controllerParams.formViewId = + attrs.form_view_id ? parseInt(attrs.form_view_id, 10) : false; + if (!this.controllerParams.formViewId && params.action) { + var formViewDescr = _.find(params.action.views, function (v) { + return v[1] === 'form'; + }); + if (formViewDescr) { + this.controllerParams.formViewId = formViewDescr[0]; + } + } + + this.controllerParams.readonlyFormViewId = !attrs.readonly_form_view_id || !utils.toBoolElse(attrs.readonly_form_view_id, true) ? false : attrs.readonly_form_view_id; + this.controllerParams.context = params.context || {}; + this.controllerParams.displayName = params.action && params.action.name; + + this.rendererParams.model = viewInfo.model; + + this.loadParams.fields = fields; + this.loadParams.fieldsInfo = viewInfo.fieldsInfo; + this.loadParams.creatable = false; + + this.loadParams.mode = attrs.mode; + }, +}); + +SystrayMenu.Items.push(CalendarMenu); +ViewRegistry.add('pms', PMSCalendarView); + +return PMSCalendarView; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_controller.js b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_controller.js new file mode 100644 index 000000000..6ed969790 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_controller.js @@ -0,0 +1,174 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.MPMSCalendarController', function (require) { +"use strict"; + +var AbstractController = require('web.AbstractController'), + Core = require('web.core'), + Bus = require('bus.bus').bus, + HotelConstants = require('hotel_calendar.Constants'), + + _t = Core._t, + QWeb = Core.qweb; + +var MPMSCalendarController = AbstractController.extend({ + custom_events: _.extend({}, AbstractController.prototype.custom_events, { + viewUpdated: '_onViewUpdated', + onSaveChanges: '_onSaveChanges', + onLoadCalendar: '_onLoadCalendar', + onLoadCalendarSettings: '_onLoadCalendarSettings', + }), + /** + * @override + * @param {Widget} parent + * @param {AbstractModel} model + * @param {AbstractRenderer} renderer + * @param {Object} params + */ + init: function (parent, model, renderer, params) { + this._super.apply(this, arguments); + this.displayName = params.displayName; + this.formViewId = params.formViewId; + this.context = params.context; + + Bus.on("notification", this, this._onBusNotification); + }, + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + + //-------------------------------------------------------------------------- + // Private + //-------------------------------------------------------------------------- + + /** + * @param {Object} record + * @param {integer} record.id + * @returns {Deferred} + */ + _updateRecord: function (record) { + return this.model.updateRecord(record).then(this.reload.bind(this)); + }, + + //-------------------------------------------------------------------------- + // Handlers + //-------------------------------------------------------------------------- + _onSaveChanges: function (ev) { + this.model.save_changes(ev.data).then(function(results){ + this.renderer.resetSaveState(); + }); + }, + + _onLoadCalendar: function (ev) { + var self = this; + + /** DO MAGIC **/ + var params = this.renderer.generate_params(); + var oparams = [params['dates'][0], params['dates'][1], false, false, true]; + this.model.get_hcalendar_data(oparams).then(function(results){ + self.renderer._days_tooltips = results['events']; + var rooms = []; + for (var r of results['rooms']) { + var nroom = new HVRoom( + r[0], // Id + r[1], // Name + r[2], // Capacity + r[3], // Price + ); + rooms.push(nroom); + } + + // Get Pricelists + self.renderer._pricelist_id = results['pricelist_id']; + self.renderer._restriction_id = results['restriction_id']; + $.when( + self.model.get_pricelists(), + self.model.get_restrictions(), + ).then(function(a1, a2){ + self.renderer.loadViewFilters(a1, a2); + }) + + self.renderer.create_calendar(rooms); + console.log(results); + self.renderer.setCalendarData(results['prices'], results['restrictions'], results['availability'], results['count_reservations']); + }); + }, + + _onLoadCalendarSettings: function (ev) { + var self = this; + this.model.get_hcalendar_settings().then(function(results){ + self.renderer.setHCalendarSettings(results); + }); + }, + + _onBusNotification: function () { + if (!this.renderer._hcalendar) { + return; + } + for (var notif of notifications) { + if (notif[0][1] === 'hotel.reservation') { + switch (notif[1]['type']) { + case 'availability': + var avail = notif[1]['availability']; + var vroom = Object.keys(avail)[0]; + var day = Object.keys(avail[vroom])[0]; + var dt = HotelCalendarManagement.toMoment(day); + var availability = {}; + availability[vroom] = [{ + 'date': dt.format(ODOO_DATE_MOMENT_FORMAT), + 'avail': avail[vroom][day][0], + 'no_ota': avail[vroom][day][1], + 'id': avail[vroom][day][2] + }]; + this.renderer._hcalendar.addAvailability(availability); + break; + case 'pricelist': + var prices = notif[1]['price']; + var pricelist_id = Object.keys(prices)[0]; + var pr = {}; + for (var price of prices[pricelist_id]) { + pr[price['room']] = []; + var days = Object.keys(price['days']); + for (var day of days) { + var dt = HotelCalendarManagement.toMoment(day); + pr[price['room']].push({ + 'date': dt.format(ODOO_DATE_MOMENT_FORMAT), + 'price': price['days'][day], + 'id': price['id'] + }); + } + } + this.renderer._hcalendar.addPricelist(pr); + break; + case 'restriction': + // FIXME: Expected one day and one vroom + var restriction = notif[1]['restriction']; + var vroom = Object.keys(restriction)[0]; + var day = Object.keys(restriction[vroom])[0]; + var dt = HotelCalendarManagement.toMoment(day); + var rest = {}; + rest[vroom] = [{ + 'date': dt.format(ODOO_DATE_MOMENT_FORMAT), + 'min_stay': restriction[vroom][day][0], + 'min_stay_arrival': restriction[vroom][day][1], + 'max_stay': restriction[vroom][day][2], + 'max_stay_arrival': restriction[vroom][day][3], + 'closed': restriction[vroom][day][4], + 'closed_arrival': restriction[vroom][day][5], + 'closed_departure': restriction[vroom][day][6], + 'id': restriction[vroom][day][7] + }]; + this.renderer._hcalendar.addRestrictions(rest); + break; + } + } + } + }, + +}); + +return MPMSCalendarController; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_model.js b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_model.js new file mode 100644 index 000000000..523b8819e --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_model.js @@ -0,0 +1,68 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.MPMSCalendarModel', function (require) { +"use strict"; + +var AbstractModel = require('web.AbstractModel'), + Context = require('web.Context'), + Core = require('web.core'), + FieldUtils = require('web.field_utils'), + Session = require('web.session'); + + +return AbstractModel.extend({ + init: function () { + this._super.apply(this, arguments); + this.end_date = null; + }, + + load: function (params) { + this.modelName = params.modelName; + }, + + save_changes: function (params) { + return this._rpc({ + model: this.modelName, + method: 'save_changes', + args: params, + context: Session.user_context, + }); + }, + + get_hcalendar_data: function (params) { + return this._rpc({ + model: this.modelName, + method: 'get_hcalendar_all_data', + args: params, + context: Session.user_context, + }); + }, + + get_pricelists: function () { + return this._rpc({ + model: 'product.pricelist', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + + get_restrictions: function () { + return this._rpc({ + model: 'hotel.virtual.room.restriction', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + + get_hcalendar_settings: function () { + return this._rpc({ + model: this.modelName, + method: 'search_read', + args: [false], + context: Session.user_context, + }); + }, +}); +}); diff --git a/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_renderer.js b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_renderer.js new file mode 100644 index 000000000..d3782fa15 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_renderer.js @@ -0,0 +1,526 @@ +/* global $, odoo, _, HotelCalendar, moment */ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.MPMSCalendarRenderer', function (require) { +"use strict"; + +var Core = require('web.core'), + ViewDialogs = require('web.view_dialogs'), + Dialog = require('web.Dialog'), + Session = require('web.session'), + AbstractRenderer = require('web.AbstractRenderer'), + HotelConstants = require('hotel_calendar.Constants'), + //Formats = require('web.formats'), + + _t = Core._t, + _lt = Core._lt, + QWeb = Core.qweb; + +var HotelCalendarManagementView = AbstractRenderer.extend({ + /** VIEW OPTIONS **/ + template: "hotel_calendar.HotelCalendarManagementView", + display_name: _lt('Hotel Calendar Management'), + icon: 'fa fa-map-marker', + searchable: false, + searchview_hidden: true, + + // Custom Options + _view_options: {}, + _hcalendar: null, + _last_dates: [false, false], + _pricelist_id: null, + _restriction_id: null, + _days_tooltips: [], + + + /** VIEW METHODS **/ + init: function(parent, state, params) { + this._super.apply(this, arguments); + + this.model = params.model; + }, + + start: function () { + var self = this; + return this._super().then(function() { + self.init_calendar_view(); + $(window).trigger('resize'); + }); + }, + + do_show: function() { + if (this.$ehcal) { + this.$ehcal.show(); + $('.o_content').css('overflow', 'hidden'); + } + this.do_push_state({}); + return this._super(); + }, + do_hide: function () { + if (this.$ehcal) { + this.$ehcal.hide(); + $('.o_content').css('overflow', ''); + } + return this._super(); + }, + + destroy: function () { + return this._super.apply(this, arguments); + }, + + /** CUSTOM METHODS **/ + save_changes: function() { + var self = this; + var btn_save = this.$el.find('#btn_save_changes'); + if (!btn_save.hasClass('need-save')) { + return; + } + + var pricelist = this._hcalendar.getPricelist(true); + var restrictions = this._hcalendar.getRestrictions(true); + var availability = this._hcalendar.getAvailability(true); + + var params = this.generate_params(); + var oparams = [false, params['prices'], params['restrictions'], pricelist, restrictions, availability]; + this.trigger_up('onSaveChanges', oparams); + }, + + resetSaveState: function() { + this.$el.find('#btn_save_changes').removeClass('need-save'); + $('.hcal-management-record-changed').removeClass('hcal-management-record-changed'); + $('.hcal-management-input-changed').removeClass('hcal-management-input-changed'); + }, + + create_calendar: function(rooms) { + var self = this; + // CALENDAR + if (this._hcalendar) { + delete this._hcalendar; + } + this.$ehcal.empty(); + + var options = { + rooms: rooms, + days: self._view_options['days'], + endOfWeek: parseInt(self._view_options['eday_week']) || 6, + endOfWeekOffset: self._view_options['eday_week_offset'] || 0, + dateFormatLong: HotelConstants.ODOO_DATETIME_MOMENT_FORMAT, + dateFormatShort: HotelConstants.ODOO_DATE_MOMENT_FORMAT, + translations: { + 'Open': _t('Open'), + 'Closed': _t('Closed'), + 'C. Departure': _t('C. Departure'), + 'C. Arrival': _t('C. Arrival'), + 'Price': _t('Price'), + 'Availability': _t('Availability'), + 'Min. Stay': _t('Min. Stay'), + 'Max. Stay': _t('Max. Stay'), + 'Min. Stay Arrival': _t('Min. Stay Arrival'), + 'Max. Stay Arrival': _t('Max. Stay Arrival'), + 'Clousure': _t('Clousure'), + 'Free Rooms': _t('Free Rooms'), + 'No OTA': _t('No OTA'), + 'Options': _t('Options'), + 'Reset': _t('Reset'), + 'Copy': _t('Copy'), + 'Paste': _t('Paste'), + 'Clone': _t('Clone'), + 'Cancel': _t('Cancel') + } + }; + + this._hcalendar = new HotelCalendarManagement('#hcal_management_widget', options, this.$el[0]); + this._assignHCalendarEvents(); + + this.$CalendarHeaderDays = this.$el.find("div.table-vroom-data-header"); + + // Sticky Header Days + this.$ehcal.scroll(this._on_scroll.bind(this)); + }, + + setCalendarData: function (prices, restrictions, availability, count_reservations) { + this._hcalendar.setData(prices, restrictions, availability, count_reservations); + this._assign_extra_info(); + }, + + _assignHCalendarEvents: function () { + var self = this; + this._hcalendar.addEventListener('hcOnChangeDate', function(ev){ + var date_begin = moment(ev.detail.newDate); + var days = self._hcalendar.getOptions('days')-1; + var date_end = date_begin.clone().add(days, 'd'); + + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + + self.reload_hcalendar_management(); + }); + this._hcalendar.addEventListener('hcmOnInputChanged', function(ev){ + var btn_save = self.$el.find('#btn_save_changes'); + if (self._hcalendar.hasChangesToSave()) { + btn_save.addClass('need-save'); + } else { + btn_save.removeClass('need-save'); + } + }); + }, + + _on_scroll: function() { + var curScrollPos = this.$ehcal.scrollTop(); + if (curScrollPos > 0) { + this.$CalendarHeaderDays.css({ + top: `${curScrollPos}px`, + position: 'sticky' + }); + } else { + this.$CalendarHeaderDays.css({ + top: '0px', + position: 'initial' + }); + } + }, + + loadViewFilters: function (resultsPricelist, resultsRestrictions) { + var self = this; + + var $list = self.$el.find('#mpms-search #price_list'); + $list.html(''); + resultsPricelist.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + self._check_unsaved_changes(function(){ + self.reload_hcalendar_management(); + }); + }); + + $list = self.$el.find('#mpms-search #restriction_list'); + $list.html(''); + resultsRestrictions.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + self._check_unsaved_changes(function(){ + self.reload_hcalendar_management(); + }); + }); + + $list = self.$el.find('#mpms-search #mode_list'); + $list.select2({ + minimumResultsForSearch: -1 + }); + $list.on('change', function(ev){ + var mode = HotelCalendarManagement.MODE.ALL; + if (this.value === 'low') { + mode = HotelCalendarManagement.MODE.LOW; + } else if (this.value === 'medium') { + mode = HotelCalendarManagement.MODE.MEDIUM; + } + self._hcalendar.setMode(mode); + }); + }, + + call_action: function(action) { + this.do_action(action); + }, + + init_calendar_view: function(){ + var self = this; + + this.$ehcal = this.$el.find("div#hcal_management_widget"); + + /** VIEW CONTROLS INITIALIZATION **/ + // DATE TIME PICKERS + var l10nn = _t.database.parameters + var DTPickerOptions = { + viewMode: 'months', + icons : { + time: 'fa fa-clock-o', + date: 'fa fa-calendar', + up: 'fa fa-chevron-up', + down: 'fa fa-chevron-down' + }, + format : HotelConstants.L10N_DATE_MOMENT_FORMAT, + disabledHours: [0, 1, 2, 3, 4, 5, 6, 7, 8, 18, 19, 20, 21, 22, 23] + }; + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + $dateTimePickerBegin.datetimepicker(DTPickerOptions); + $dateTimePickerEnd.datetimepicker($.extend({}, DTPickerOptions, { 'useCurrent': false })); + $dateTimePickerBegin.on("dp.change", function (e) { + $dateTimePickerEnd.data("DateTimePicker").minDate(e.date.clone().add(3,'d')); + $dateTimePickerEnd.data("DateTimePicker").maxDate(e.date.clone().add(2,'M')); + $dateTimePickerBegin.data("DateTimePicker").hide(); // TODO: Odoo uses old datetimepicker version + self.on_change_filter_date(e, true); + }); + $dateTimePickerEnd.on("dp.change", function (e) { + self.on_change_filter_date(e, false); + $dateTimePickerEnd.data("DateTimePicker").hide(); // TODO: Odoo uses old datetimepicker version + }); + + // var date_begin = moment().startOf('day'); + // var date_end = date_begin.clone().add(this._view_options['days'], 'd').endOf('day'); + // $dateTimePickerBegin.data("ignore_onchange", true); + // $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + // $dateTimePickerEnd.data("DateTimePicker").date(date_end); + // this._last_dates = this.generate_params()['dates']; + + // View Events + this.$el.find("#mpms-search #cal-pag-prev-plus").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + //var days = moment($dateTimePickerBegin.data("DateTimePicker").date()).clone().local().daysInMonth(); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().subtract(14, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().subtract(14, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-prev").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().subtract(7, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().subtract(7, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-next-plus").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + //var days = moment($dateTimePickerBegin.data("DateTimePicker").date()).clone().local().daysInMonth(); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().add(14, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().add(14, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-next").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().add(7, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().add(7, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-selector").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + var date_begin = moment().startOf('day'); + var date_end = date_begin.clone().add(self._view_options['days'], 'd').endOf('day'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + + ev.preventDefault(); + }); + + // Save Button + this.$el.find("#btn_save_changes").on('click', function(ev){ + self.save_changes(); + }); + + // Launch Massive Changes + this.$el.find("#btn_massive_changes").on('click', function(ev){ + self.call_action("hotel.action_hotel_massive_change"); + }); + + /** RENDER CALENDAR **/ + this.trigger_up('onLoadCalendarSettings'); + }, + + setHCalendarSettings: function (results) { + this._view_options = results; + var date_begin = moment().startOf('day'); + if (['xs', 'md'].indexOf(this._findBootstrapEnvironment()) >= 0) { + this._view_options['days'] = 7; + } else { + this._view_options['days'] = (this._view_options['days'] !== 'month')?parseInt(this._view_options['days']):date_begin.daysInMonth(); + } + var date_end = date_begin.clone().add(this._view_options['days'], 'd').endOf('day'); + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + //$dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").date(date_begin); + //$dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").date(date_end); + this._last_dates = this.generate_params()['dates']; + + this.trigger_up('onLoadCalendar'); + }, + + on_change_filter_date: function(ev, isStartDate) { + var self = this; + isStartDate = isStartDate || false; + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + + // FIXME: Hackish onchange ignore (Used when change dates from code) + if ($dateTimePickerBegin.data("ignore_onchange") || $dateTimePickerEnd.data("ignore_onchange")) { + $dateTimePickerBegin.data("ignore_onchange", false); + $dateTimePickerEnd.data("ignore_onchange", false) + return true; + } + + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().set({'hour': 0, 'minute': 0, 'second': 0}).clone(); + + if (this._hcalendar && date_begin) { + if (isStartDate) { + var ndate_end = date_begin.clone().add(this._view_options['days'], 'd'); + $dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").date(ndate_end.local()); + } + + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().set({'hour': 23, 'minute': 59, 'second': 59}).clone(); + + this._check_unsaved_changes(function(){ + self._hcalendar.setStartDate(date_begin, self._hcalendar.getDateDiffDays(date_begin, date_end)); + self.reload_hcalendar_management(); + }); + } + }, + + reload_hcalendar_management: function() { + var self = this; + var params = this.generate_params(); + var oparams = [params['dates'][0], params['dates'][1], params['prices'], params['restrictions'], false]; + this._model.call('get_hcalendar_all_data', oparams).then(function(results){ + self._days_tooltips = results['events']; + self._hcalendar.setData(results['prices'], results['restrictions'], results['availability'], results['count_reservations']); + self._assign_extra_info(); + }); + this._last_dates = params['dates']; + this.$CalendarHeaderDays = this.$el.find("div.table-vroom-data-header"); + this._on_scroll(); // FIXME: Workaround for update sticky header + }, + + generate_params: function() { + var fullDomain = []; + var prices = this.$el.find('#mpms-search #price_list').val(); + var restrictions = this.$el.find('#mpms-search #restriction_list').val(); + + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + + var date_begin = $dateTimePickerBegin.data("DateTimePicker").date().set({'hour': 0, 'minute': 0, 'second': 0}).clone().utc().format(HotelConstants.ODOO_DATE_MOMENT_FORMAT); + var date_end = $dateTimePickerEnd.data("DateTimePicker").date().set({'hour': 23, 'minute': 59, 'second': 59}).clone().utc().format(HotelConstants.ODOO_DATE_MOMENT_FORMAT); + + return { + 'dates': [date_begin, date_end], + 'prices': prices, + 'restrictions': restrictions + }; + }, + + _check_unsaved_changes: function(fnCallback) { + var self = this; + var btn_save = this.$el.find("#btn_save_changes"); + if (!btn_save.hasClass('need-save')) { + btn_save.removeClass('need-save'); + fnCallback(); + return; + } + + new Dialog(self, { + title: _t("Unsaved Changes!"), + buttons: [ + { + text: _t("Yes, save it"), + classes: 'btn-primary', + close: true, + click: function() { + self.save_changes(); + fnCallback(); + } + }, + { + text: _t("No"), + close: true, + click: function() { + btn_save.removeClass('need-save'); + fnCallback(); + } + } + ], + $content: QWeb.render('HotelCalendarManagement.UnsavedChanges', {}) + }).open(); + }, + + _findBootstrapEnvironment: function() { + var envs = ['xs', 'sm', 'md', 'lg']; + + var $el = $('
'); + $el.appendTo($('body')); + + for (var i = envs.length - 1; i >= 0; i--) { + var env = envs[i]; + + $el.addClass('hidden-'+env); + if ($el.is(':hidden')) { + $el.remove(); + return env; + } + } + }, + + _assign_extra_info: function() { + var self = this; + + $(this._hcalendar.etableHeader).find('.hcal-cell-header-day').each(function(index, elm){ + var $elm = $(elm); + var cdate = HotelCalendarManagement.toMoment($elm.data('hcalDate'), HotelConstants.L10N_DATE_MOMENT_FORMAT); + var data = _.filter(self._days_tooltips, function(item) { + var ndate = HotelCalendarManagement.toMoment(item[2], HotelConstants.ODOO_DATE_MOMENT_FORMAT); + return ndate.isSame(cdate, 'd'); + }); + if (data.length > 0) { + $elm.addClass('hcal-event-day'); + $elm.on("mouseenter", function(data){ + var $this = $(this); + if (data.length > 0) { + var qdict = { + 'date': $this.data('hcalDate'), + 'events': _.map(data, function(item){ + return { + 'name': item[1], + 'date': item[2], + 'location': item[3] + }; + }) + }; + $this.attr('title', ''); + $this.tooltip({ + animation: true, + html: true, + placement: 'bottom', + title: QWeb.render('HotelCalendar.TooltipEvent', qdict) + }).tooltip('show'); + } + }.bind(elm, data)); + } + }); + }, +}); + +return HotelCalendarManagementView; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_v.js b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_v.js new file mode 100644 index 000000000..4cc966931 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_v.js @@ -0,0 +1,661 @@ +/* global $, odoo, _, HotelCalendarManagement, moment */ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.HotelCalendarManagementView', function (require) { +"use strict"; + +var Core = require('web.core'), + Bus = require('bus.bus').bus, + //Data = require('web.data'), + Time = require('web.time'), + Model = require('web.DataModel'), + View = require('web.View'), + Widgets = require('web_calendar.widgets'), + //Common = require('web.form_common'), + //Pyeval = require('web.pyeval'), + ActionManager = require('web.ActionManager'), + Utils = require('web.utils'), + Dialog = require('web.Dialog'), + //Ajax = require('web.ajax'), + ControlPanel = require('web.ControlPanel'), + //Session = require('web.session'), + formats = require('web.formats'), + + _t = Core._t, + _lt = Core._lt, + QWeb = Core.qweb, + l10n = _t.database.parameters, + + ODOO_DATETIME_MOMENT_FORMAT = "YYYY-MM-DD HH:mm:ss", + ODOO_DATE_MOMENT_FORMAT = "YYYY-MM-DD", + L10N_DATE_MOMENT_FORMAT = "DD/MM/YYYY", //FIXME: Time.strftime_to_moment_format(l10n.date_format); + L10N_DATETIME_MOMENT_FORMAT = L10N_DATE_MOMENT_FORMAT + ' ' + Time.strftime_to_moment_format(l10n.time_format); + + +/* HIDE CONTROL PANEL */ +/* FIXME: Look's like a hackish solution */ +ControlPanel.include({ + update: function(status, options) { + if (typeof options.toHide === 'undefined') + options.toHide = false; + var action_stack = this.getParent().action_stack; + if (action_stack && action_stack.length) { + var active_action = action_stack[action_stack.length-1]; + if (active_action.widget && active_action.widget.active_view && + active_action.widget.active_view.type === 'mpms'){ + options.toHide = true; + } + } + this._super(status, options); + this._toggle_visibility(!options.toHide); + } +}); + +var HotelCalendarManagementView = View.extend({ + /** VIEW OPTIONS **/ + template: "hotel_calendar.HotelCalendarManagementView", + display_name: _lt('Hotel Calendar Management'), + icon: 'fa fa-map-marker', + //view_type: "mpms", + searchable: false, + searchview_hidden: true, + quick_create_instance: Widgets.QuickCreate, + defaults: _.extend({}, View.prototype.defaults, { + confirm_on_delete: true, + }), + + // Custom Options + _model: null, + _hcalendar: null, + _action_manager: null, + _last_dates: [false, false], + _pricelist_id: null, + _restriction_id: null, + _days_tooltips: [], + + /** VIEW METHODS **/ + init: function(parent, dataset, fields_view, options) { + this._super.apply(this, arguments); + this.shown = $.Deferred(); + this.dataset = dataset; + this.model = dataset.model; + this.view_type = 'mpms'; + this.selected_filters = []; + this.mutex = new Utils.Mutex(); + this._model = new Model(this.dataset.model); + this._action_manager = this.findAncestor(function(ancestor){ return ancestor instanceof ActionManager; }); + + Bus.on("notification", this, this._on_bus_signal); + }, + + start: function () { + this.shown.done(this._do_show_init.bind(this)); + return this._super(); + }, + + _do_show_init: function () { + this.init_calendar_view().then(function() { + $(window).trigger('resize'); + }); + }, + + do_show: function() { + if (this.$ehcal) { + this.$ehcal.show(); + $('.o_content').css('overflow', 'hidden'); + } + this.do_push_state({}); + this.shown.resolve(); + return this._super(); + }, + do_hide: function () { + if (this.$ehcal) { + this.$ehcal.hide(); + $('.o_content').css('overflow', ''); + } + return this._super(); + }, + + destroy: function () { + return this._super.apply(this, arguments); + }, + + /** CUSTOM METHODS **/ + save_changes: function() { + var self = this; + var btn_save = this.$el.find('#btn_save_changes'); + if (!btn_save.hasClass('need-save')) { + return; + } + + var pricelist = this._hcalendar.getPricelist(true); + var restrictions = this._hcalendar.getRestrictions(true); + var availability = this._hcalendar.getAvailability(true); + + var params = this.generate_params(); + var oparams = [false, params['prices'], params['restrictions'], pricelist, restrictions, availability]; + this._model.call('save_changes', oparams).then(function(results){ + btn_save.removeClass('need-save'); + $('.hcal-management-record-changed').removeClass('hcal-management-record-changed'); + $('.hcal-management-input-changed').removeClass('hcal-management-input-changed'); + }); + }, + + create_calendar: function(options) { + var self = this; + // CALENDAR + if (this._hcalendar) { + delete this._hcalendar; + } + + this.$ehcal.empty(); + + this._hcalendar = new HotelCalendarManagement('#hcal_management_widget', options, this.$el[0]); + this._hcalendar.addEventListener('hcOnChangeDate', function(ev){ + var date_begin = moment(ev.detail.newDate); + var days = self._hcalendar.getOptions('days')-1; + var date_end = date_begin.clone().add(days, 'd'); + + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + + self.reload_hcalendar_management(); + }); + this._hcalendar.addEventListener('hcmOnInputChanged', function(ev){ + var btn_save = self.$el.find('#btn_save_changes'); + if (self._hcalendar.hasChangesToSave()) { + btn_save.addClass('need-save'); + } else { + btn_save.removeClass('need-save'); + } + }); + + this.$CalendarHeaderDays = this.$el.find("div.table-vroom-data-header"); + + // Sticky Header Days + this.$ehcal.scroll(this._on_scroll.bind(this)); + }, + + _on_scroll: function() { + var curScrollPos = this.$ehcal.scrollTop(); + if (curScrollPos > 0) { + this.$CalendarHeaderDays.css({ + top: `${curScrollPos}px`, + position: 'sticky' + }); + } else { + this.$CalendarHeaderDays.css({ + top: '0px', + position: 'initial' + }); + } + }, + + generate_hotel_calendar: function(){ + var self = this; + + /** DO MAGIC **/ + var params = this.generate_params(); + var oparams = [params['dates'][0], params['dates'][1], false, false, true]; + this._model.call('get_hcalendar_all_data', oparams).then(function(results){ + self._days_tooltips = results['events']; + var rooms = []; + for (var r of results['rooms']) { + var nroom = new HVRoom( + r[0], // Id + r[1], // Name + r[2], // Capacity + r[3], // Price + ); + rooms.push(nroom); + } + + // Get Pricelists + self._pricelist_id = results['pricelist_id']; + new Model('product.pricelist').query(['id','name']).all().then(function(resultsPricelist){ + var $list = self.$el.find('#mpms-search #price_list'); + $list.html(''); + resultsPricelist.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + self._check_unsaved_changes(function(){ + self.reload_hcalendar_management(); + }); + }); + }); + + // Get Restrictions + self._restriction_id = results['restriction_id']; + new Model('hotel.virtual.room.restriction').query(['id','name']).all().then(function(resultsRestrictions){ + var $list = self.$el.find('#mpms-search #restriction_list'); + $list.html(''); + resultsRestrictions.forEach(function(item, index){ + $list.append(``); + }); + $list.select2(); + $list.on('change', function(ev){ + self._check_unsaved_changes(function(){ + self.reload_hcalendar_management(); + }); + }); + }); + + // Calendar Mode + var $list = self.$el.find('#mpms-search #mode_list'); + $list.select2({ + minimumResultsForSearch: -1 + }); + $list.on('change', function(ev){ + var mode = HotelCalendarManagement.MODE.ALL; + if (this.value === 'low') { + mode = HotelCalendarManagement.MODE.LOW; + } else if (this.value === 'medium') { + mode = HotelCalendarManagement.MODE.MEDIUM; + } + self._hcalendar.setMode(mode); + }); + + self.create_calendar({ + rooms: rooms, + days: self._view_options['days'], + endOfWeek: parseInt(self._view_options['eday_week']) || 6, + endOfWeekOffset: self._view_options['eday_week_offset'] || 0, + dateFormatLong: ODOO_DATETIME_MOMENT_FORMAT, + dateFormatShort: ODOO_DATE_MOMENT_FORMAT, + translations: { + 'Open': _t('Open'), + 'Closed': _t('Closed'), + 'C. Departure': _t('C. Departure'), + 'C. Arrival': _t('C. Arrival'), + 'Price': _t('Price'), + 'Availability': _t('Availability'), + 'Min. Stay': _t('Min. Stay'), + 'Max. Stay': _t('Max. Stay'), + 'Min. Stay Arrival': _t('Min. Stay Arrival'), + 'Max. Stay Arrival': _t('Max. Stay Arrival'), + 'Clousure': _t('Clousure'), + 'Free Rooms': _t('Free Rooms'), + 'No OTA': _t('No OTA'), + 'Options': _t('Options'), + 'Reset': _t('Reset'), + 'Copy': _t('Copy'), + 'Paste': _t('Paste'), + 'Clone': _t('Clone'), + 'Cancel': _t('Cancel') + } + }); + self._hcalendar.setData(results['prices'], results['restrictions'], results['availability'], results['count_reservations']); + self._assign_extra_info(); + }); + }, + + call_action: function(action) { + this._action_manager.do_action(action); + }, + + init_calendar_view: function(){ + var self = this; + + this.$ehcal = this.$el.find("div#hcal_management_widget"); + + /** VIEW CONTROLS INITIALIZATION **/ + // DATE TIME PICKERS + var l10nn = _t.database.parameters + var DTPickerOptions = { + viewMode: 'months', + icons : { + time: 'fa fa-clock-o', + date: 'fa fa-calendar', + up: 'fa fa-chevron-up', + down: 'fa fa-chevron-down' + }, + language : moment.locale(), + format : L10N_DATE_MOMENT_FORMAT, + disabledHours: true // TODO: Odoo uses old datetimepicker version + }; + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + $dateTimePickerBegin.datetimepicker(DTPickerOptions); + $dateTimePickerEnd.datetimepicker($.extend({}, DTPickerOptions, { 'useCurrent': false })); + $dateTimePickerBegin.on("dp.change", function (e) { + $dateTimePickerEnd.data("DateTimePicker").setMinDate(e.date.add(3,'d')); + $dateTimePickerEnd.data("DateTimePicker").setMaxDate(e.date.add(2,'M')); + $dateTimePickerBegin.data("DateTimePicker").hide(); // TODO: Odoo uses old datetimepicker version + self.on_change_filter_date(e, true); + }); + $dateTimePickerEnd.on("dp.change", function (e) { + self.on_change_filter_date(e, false); + $dateTimePickerEnd.data("DateTimePicker").hide(); // TODO: Odoo uses old datetimepicker version + }); + + // var date_begin = moment().startOf('day'); + // var date_end = date_begin.clone().add(this._view_options['days'], 'd').endOf('day'); + // $dateTimePickerBegin.data("ignore_onchange", true); + // $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + // $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + // this._last_dates = this.generate_params()['dates']; + + // View Events + this.$el.find("#mpms-search #cal-pag-prev-plus").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + //var days = moment($dateTimePickerBegin.data("DateTimePicker").getDate()).clone().local().daysInMonth(); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").getDate().subtract(14, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").getDate().subtract(14, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-prev").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").getDate().subtract(7, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").getDate().subtract(7, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-next-plus").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + //var days = moment($dateTimePickerBegin.data("DateTimePicker").getDate()).clone().local().daysInMonth(); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").getDate().add(14, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").getDate().add(14, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-next").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + var date_begin = $dateTimePickerBegin.data("DateTimePicker").getDate().add(7, 'd'); + var date_end = $dateTimePickerEnd.data("DateTimePicker").getDate().add(7, 'd'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + + ev.preventDefault(); + }); + this.$el.find("#mpms-search #cal-pag-selector").on('click', function(ev){ + // FIXME: Ugly repeated code. Change place. + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + var date_begin = moment().startOf('day'); + var date_end = date_begin.clone().add(self._view_options['days'], 'd').endOf('day'); + $dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + + ev.preventDefault(); + }); + + // Save Button + this.$el.find("#btn_save_changes").on('click', function(ev){ + self.save_changes(); + }); + + // Launch Massive Changes + this.$el.find("#btn_massive_changes").on('click', function(ev){ + self.call_action("hotel.action_hotel_massive_change"); + }); + + /** RENDER CALENDAR **/ + this._model.call('get_hcalendar_settings', [false]).then(function(results){ + self._view_options = results; + var date_begin = moment().startOf('day'); + if (['xs', 'md'].indexOf(self._findBootstrapEnvironment()) >= 0) { + self._view_options['days'] = 7; + } else { + self._view_options['days'] = (self._view_options['days'] !== 'month')?parseInt(self._view_options['days']):date_begin.daysInMonth(); + } + var date_end = date_begin.clone().add(self._view_options['days'], 'd').endOf('day'); + var $dateTimePickerBegin = self.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = self.$el.find('#mpms-search #date_end'); + //$dateTimePickerBegin.data("ignore_onchange", true); + $dateTimePickerBegin.data("DateTimePicker").setDate(date_begin); + //$dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").setDate(date_end); + self._last_dates = self.generate_params()['dates']; + + self.generate_hotel_calendar(); + }); + + return $.when(); + }, + + on_change_filter_date: function(ev, isStartDate) { + var self = this; + isStartDate = isStartDate || false; + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + + // FIXME: Hackish onchange ignore (Used when change dates from code) + if ($dateTimePickerBegin.data("ignore_onchange") || $dateTimePickerEnd.data("ignore_onchange")) { + $dateTimePickerBegin.data("ignore_onchange", false); + $dateTimePickerEnd.data("ignore_onchange", false) + return true; + } + + var date_begin = $dateTimePickerBegin.data("DateTimePicker").getDate().set({'hour': 0, 'minute': 0, 'second': 0}).clone(); + + if (this._hcalendar && date_begin) { + if (isStartDate) { + var ndate_end = date_begin.clone().add(this._view_options['days'], 'd'); + $dateTimePickerEnd.data("ignore_onchange", true); + $dateTimePickerEnd.data("DateTimePicker").setDate(ndate_end.local()); + } + + var date_end = $dateTimePickerEnd.data("DateTimePicker").getDate().set({'hour': 23, 'minute': 59, 'second': 59}).clone(); + + this._check_unsaved_changes(function(){ + self._hcalendar.setStartDate(date_begin, self._hcalendar.getDateDiffDays(date_begin, date_end)); + self.reload_hcalendar_management(); + }); + } + }, + + _on_bus_signal: function(notifications) { + if (!this._hcalendar) { + return; + } + for (var notif of notifications) { + if (notif[0][1] === 'hotel.reservation') { + switch (notif[1]['type']) { + case 'availability': + var avail = notif[1]['availability']; + var vroom = Object.keys(avail)[0]; + var day = Object.keys(avail[vroom])[0]; + var dt = HotelCalendarManagement.toMoment(day); + var availability = {}; + availability[vroom] = [{ + 'date': dt.format(ODOO_DATE_MOMENT_FORMAT), + 'avail': avail[vroom][day][0], + 'no_ota': avail[vroom][day][1], + 'id': avail[vroom][day][2] + }]; + this._hcalendar.addAvailability(availability); + break; + case 'pricelist': + var prices = notif[1]['price']; + var pricelist_id = Object.keys(prices)[0]; + var pr = {}; + for (var price of prices[pricelist_id]) { + pr[price['room']] = []; + var days = Object.keys(price['days']); + for (var day of days) { + var dt = HotelCalendarManagement.toMoment(day); + pr[price['room']].push({ + 'date': dt.format(ODOO_DATE_MOMENT_FORMAT), + 'price': price['days'][day], + 'id': price['id'] + }); + } + } + this._hcalendar.addPricelist(pr); + break; + case 'restriction': + // FIXME: Expected one day and one vroom + var restriction = notif[1]['restriction']; + var vroom = Object.keys(restriction)[0]; + var day = Object.keys(restriction[vroom])[0]; + var dt = HotelCalendarManagement.toMoment(day); + var rest = {}; + rest[vroom] = [{ + 'date': dt.format(ODOO_DATE_MOMENT_FORMAT), + 'min_stay': restriction[vroom][day][0], + 'min_stay_arrival': restriction[vroom][day][1], + 'max_stay': restriction[vroom][day][2], + 'max_stay_arrival': restriction[vroom][day][3], + 'closed': restriction[vroom][day][4], + 'closed_arrival': restriction[vroom][day][5], + 'closed_departure': restriction[vroom][day][6], + 'id': restriction[vroom][day][7] + }]; + this._hcalendar.addRestrictions(rest); + break; + } + } + } + }, + + reload_hcalendar_management: function() { + var self = this; + var params = this.generate_params(); + var oparams = [params['dates'][0], params['dates'][1], params['prices'], params['restrictions'], false]; + this._model.call('get_hcalendar_all_data', oparams).then(function(results){ + self._days_tooltips = results['events']; + self._hcalendar.setData(results['prices'], results['restrictions'], results['availability'], results['count_reservations']); + self._assign_extra_info(); + }); + this._last_dates = params['dates']; + this.$CalendarHeaderDays = this.$el.find("div.table-vroom-data-header"); + this._on_scroll(); // FIXME: Workaround for update sticky header + }, + + generate_params: function() { + var fullDomain = []; + var prices = this.$el.find('#mpms-search #price_list').val(); + var restrictions = this.$el.find('#mpms-search #restriction_list').val(); + + var $dateTimePickerBegin = this.$el.find('#mpms-search #date_begin'); + var $dateTimePickerEnd = this.$el.find('#mpms-search #date_end'); + + var date_begin = $dateTimePickerBegin.data("DateTimePicker").getDate().set({'hour': 0, 'minute': 0, 'second': 0}).clone().utc().format(ODOO_DATE_MOMENT_FORMAT); + var date_end = $dateTimePickerEnd.data("DateTimePicker").getDate().set({'hour': 23, 'minute': 59, 'second': 59}).clone().utc().format(ODOO_DATE_MOMENT_FORMAT); + + return { + 'dates': [date_begin, date_end], + 'prices': prices, + 'restrictions': restrictions + }; + }, + + _check_unsaved_changes: function(fnCallback) { + var self = this; + var btn_save = this.$el.find("#btn_save_changes"); + if (!btn_save.hasClass('need-save')) { + btn_save.removeClass('need-save'); + fnCallback(); + return; + } + + new Dialog(self, { + title: _t("Unsaved Changes!"), + buttons: [ + { + text: _t("Yes, save it"), + classes: 'btn-primary', + close: true, + click: function() { + self.save_changes(); + fnCallback(); + } + }, + { + text: _t("No"), + close: true, + click: function() { + btn_save.removeClass('need-save'); + fnCallback(); + } + } + ], + $content: QWeb.render('HotelCalendarManagement.UnsavedChanges', {}) + }).open(); + }, + + _findBootstrapEnvironment: function() { + var envs = ['xs', 'sm', 'md', 'lg']; + + var $el = $('
'); + $el.appendTo($('body')); + + for (var i = envs.length - 1; i >= 0; i--) { + var env = envs[i]; + + $el.addClass('hidden-'+env); + if ($el.is(':hidden')) { + $el.remove(); + return env; + } + } + }, + + _assign_extra_info: function() { + var self = this; + + $(this._hcalendar.etableHeader).find('.hcal-cell-header-day').each(function(index, elm){ + var $elm = $(elm); + var cdate = HotelCalendar.toMoment($elm.data('hcalDate'), L10N_DATE_MOMENT_FORMAT); + var data = _.filter(self._days_tooltips, function(item) { + var ndate = HotelCalendar.toMoment(item[2], ODOO_DATE_MOMENT_FORMAT); + return ndate.isSame(cdate, 'd'); + }); + if (data.length > 0) { + $elm.addClass('hcal-event-day'); + $elm.on("mouseenter", function(data){ + var $this = $(this); + if (data.length > 0) { + var qdict = { + 'date': $this.data('hcalDate'), + 'events': _.map(data, function(item){ + return { + 'name': item[1], + 'date': item[2], + 'location': item[3] + }; + }) + }; + $this.attr('title', ''); + $this.tooltip({ + animation: true, + html: true, + placement: 'bottom', + title: QWeb.render('HotelCalendar.TooltipEvent', qdict) + }).tooltip('show'); + } + }.bind(elm, data)); + } + }); + }, +}); + +Core.view_registry.add('mpms', HotelCalendarManagementView); +return HotelCalendarManagementView; + +}); diff --git a/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_view.js b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_view.js new file mode 100644 index 000000000..9e3af7d12 --- /dev/null +++ b/hotel_calendar/static/src/js/views/calendar_management/hotel_calendar_management_view.js @@ -0,0 +1,93 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.MPMSCalendarView', function (require) { +"use strict"; + +var AbstractView = require('web.AbstractView'), + MPMSCalendarModel = require('hotel_calendar.MPMSCalendarModel'), + MPMSCalendarController = require('hotel_calendar.MPMSCalendarController'), + MPMSCalendarRenderer = require('hotel_calendar.MPMSCalendarRenderer'), + ViewRegistry = require('web.view_registry'), + SystrayMenu = require('web.SystrayMenu'), + ControlPanel = require('web.ControlPanel'), + Widget = require('web.Widget'), + Session = require('web.session'), + Core = require('web.core'), + + _lt = Core._lt, + QWeb = Core.qweb; + +/* HIDE CONTROL PANEL */ +/* FIXME: Look's like a hackish solution */ +ControlPanel.include({ + update: function(status, options) { + if (typeof options === 'undefined') { + options = {}; + } + if (typeof options.toHide === 'undefined') + options.toHide = false; + var action_stack = this.getParent().action_stack; + if (action_stack && action_stack.length) { + var active_action = action_stack[action_stack.length-1]; + if (active_action.widget && active_action.widget.active_view && + active_action.widget.active_view.type === 'mpms'){ + options.toHide = true; + } + } + this._super(status, options); + this._toggle_visibility(!options.toHide); + } +}); + +var MPMSCalendarView = AbstractView.extend({ + display_name: _lt('Calendar MPMS'), + icon: 'fa-calendar', + jsLibs: ['/hotel_calendar/static/src/lib/hcalendar/js/hcalendar_management.js'], + cssLibs: [ + '/hotel_calendar/static/src/lib/hcalendar/css/hcalendar.css', + '/hotel_calendar/static/src/lib/hcalendar/css/hcalendar_management.css' + ], + config: { + Model: MPMSCalendarModel, + Controller: MPMSCalendarController, + Renderer: MPMSCalendarRenderer, + }, + + init: function (viewInfo, params) { + this._super.apply(this, arguments); + var arch = viewInfo.arch; + var fields = viewInfo.fields; + var attrs = arch.attrs; + + // If form_view_id is set, then the calendar view will open a form view + // with this id, when it needs to edit or create an event. + this.controllerParams.formViewId = + attrs.form_view_id ? parseInt(attrs.form_view_id, 10) : false; + if (!this.controllerParams.formViewId && params.action) { + var formViewDescr = _.find(params.action.views, function (v) { + return v[1] === 'form'; + }); + if (formViewDescr) { + this.controllerParams.formViewId = formViewDescr[0]; + } + } + + this.controllerParams.readonlyFormViewId = !attrs.readonly_form_view_id || !utils.toBoolElse(attrs.readonly_form_view_id, true) ? false : attrs.readonly_form_view_id; + this.controllerParams.context = params.context || {}; + this.controllerParams.displayName = params.action && params.action.name; + + this.rendererParams.model = viewInfo.model; + + this.loadParams.fields = fields; + this.loadParams.fieldsInfo = viewInfo.fieldsInfo; + this.loadParams.creatable = false; + + this.loadParams.mode = attrs.mode; + }, +}); + +ViewRegistry.add('mpms', MPMSCalendarView); + +return MPMSCalendarView; + +}); diff --git a/hotel_calendar/static/src/js/views/constants.js b/hotel_calendar/static/src/js/views/constants.js new file mode 100644 index 000000000..f52526b83 --- /dev/null +++ b/hotel_calendar/static/src/js/views/constants.js @@ -0,0 +1,20 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.Constants', function (require) { +"use strict"; + + var Core = require('web.core'), + Time = require('web.time'), + + l10n = Core._t.database.parameters; + + return { + ODOO_DATE_MOMENT_FORMAT: 'YYYY-MM-DD', + ODOO_DATETIME_MOMENT_FORMAT: 'YYYY-MM-DD HH:mm:ss', + L10N_DATE_MOMENT_FORMAT: "DD/MM/YYYY", //FIXME: Time.strftime_to_moment_format(l10n.date_format), + L10N_DATETIME_MOMENT_FORMAT: 'DD/MM/YYYY ' + Time.strftime_to_moment_format(l10n.time_format), + + CURRENCY_SYMBOL: "€", + }; + +}); diff --git a/hotel_calendar/static/src/lib/bootbox.js b/hotel_calendar/static/src/lib/bootbox.js new file mode 100644 index 000000000..3e8312a85 --- /dev/null +++ b/hotel_calendar/static/src/lib/bootbox.js @@ -0,0 +1,985 @@ +/** + * bootbox.js [v4.4.0] + * + * http://bootboxjs.com/license.txt + */ + +// @see https://github.com/makeusabrew/bootbox/issues/180 +// @see https://github.com/makeusabrew/bootbox/issues/186 +(function (root, factory) { + + "use strict"; + if (typeof define === "function" && define.amd) { + // AMD. Register as an anonymous module. + define(["jquery"], factory); + } else if (typeof exports === "object") { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(require("jquery")); + } else { + // Browser globals (root is window) + root.bootbox = factory(root.jQuery); + } + +}(this, function init($, undefined) { + + "use strict"; + + // the base DOM structure needed to create a modal + var templates = { + dialog: + "", + header: + "", + footer: + "", + closeButton: + "", + form: + "
", + inputs: { + text: + "", + textarea: + "", + email: + "", + select: + "", + checkbox: + "
", + date: + "", + time: + "", + number: + "", + password: + "" + } + }; + + var defaults = { + // default language + locale: "en", + // show backdrop or not. Default to static so user has to interact with dialog + backdrop: "static", + // animate the modal in/out + animate: true, + // additional class string applied to the top level dialog + className: null, + // whether or not to include a close button + closeButton: true, + // show the dialog immediately by default + show: true, + // dialog container + container: "body" + }; + + // our public object; augmented after our private API + var exports = {}; + + /** + * @private + */ + function _t(key) { + var locale = locales[defaults.locale]; + return locale ? locale[key] : locales.en[key]; + } + + function processCallback(e, dialog, callback) { + e.stopPropagation(); + e.preventDefault(); + + // by default we assume a callback will get rid of the dialog, + // although it is given the opportunity to override this + + // so, if the callback can be invoked and it *explicitly returns false* + // then we'll set a flag to keep the dialog active... + var preserveDialog = $.isFunction(callback) && callback.call(dialog, e) === false; + + // ... otherwise we'll bin it + if (!preserveDialog) { + dialog.modal("hide"); + } + } + + function getKeyLength(obj) { + // @TODO defer to Object.keys(x).length if available? + var k, t = 0; + for (k in obj) { + t ++; + } + return t; + } + + function each(collection, iterator) { + var index = 0; + $.each(collection, function(key, value) { + iterator(key, value, index++); + }); + } + + function sanitize(options) { + var buttons; + var total; + + if (typeof options !== "object") { + throw new Error("Please supply an object of options"); + } + + if (!options.message) { + throw new Error("Please specify a message"); + } + + // make sure any supplied options take precedence over defaults + options = $.extend({}, defaults, options); + + if (!options.buttons) { + options.buttons = {}; + } + + buttons = options.buttons; + + total = getKeyLength(buttons); + + each(buttons, function(key, button, index) { + + if ($.isFunction(button)) { + // short form, assume value is our callback. Since button + // isn't an object it isn't a reference either so re-assign it + button = buttons[key] = { + callback: button + }; + } + + // before any further checks make sure by now button is the correct type + if ($.type(button) !== "object") { + throw new Error("button with key " + key + " must be an object"); + } + + if (!button.label) { + // the lack of an explicit label means we'll assume the key is good enough + button.label = key; + } + + if (!button.className) { + if (total <= 2 && index === total-1) { + // always add a primary to the main option in a two-button dialog + button.className = "btn-primary"; + } else { + button.className = "btn-default"; + } + } + }); + + return options; + } + + /** + * map a flexible set of arguments into a single returned object + * if args.length is already one just return it, otherwise + * use the properties argument to map the unnamed args to + * object properties + * so in the latter case: + * mapArguments(["foo", $.noop], ["message", "callback"]) + * -> { message: "foo", callback: $.noop } + */ + function mapArguments(args, properties) { + var argn = args.length; + var options = {}; + + if (argn < 1 || argn > 2) { + throw new Error("Invalid argument length"); + } + + if (argn === 2 || typeof args[0] === "string") { + options[properties[0]] = args[0]; + options[properties[1]] = args[1]; + } else { + options = args[0]; + } + + return options; + } + + /** + * merge a set of default dialog options with user supplied arguments + */ + function mergeArguments(defaults, args, properties) { + return $.extend( + // deep merge + true, + // ensure the target is an empty, unreferenced object + {}, + // the base options object for this type of dialog (often just buttons) + defaults, + // args could be an object or array; if it's an array properties will + // map it to a proper options object + mapArguments( + args, + properties + ) + ); + } + + /** + * this entry-level method makes heavy use of composition to take a simple + * range of inputs and return valid options suitable for passing to bootbox.dialog + */ + function mergeDialogOptions(className, labels, properties, args) { + // build up a base set of dialog properties + var baseOptions = { + className: "bootbox-" + className, + buttons: createLabels.apply(null, labels) + }; + + // ensure the buttons properties generated, *after* merging + // with user args are still valid against the supplied labels + return validateButtons( + // merge the generated base properties with user supplied arguments + mergeArguments( + baseOptions, + args, + // if args.length > 1, properties specify how each arg maps to an object key + properties + ), + labels + ); + } + + /** + * from a given list of arguments return a suitable object of button labels + * all this does is normalise the given labels and translate them where possible + * e.g. "ok", "confirm" -> { ok: "OK, cancel: "Annuleren" } + */ + function createLabels() { + var buttons = {}; + + for (var i = 0, j = arguments.length; i < j; i++) { + var argument = arguments[i]; + var key = argument.toLowerCase(); + var value = argument.toUpperCase(); + + buttons[key] = { + label: _t(value) + }; + } + + return buttons; + } + + function validateButtons(options, buttons) { + var allowedButtons = {}; + each(buttons, function(key, value) { + allowedButtons[value] = true; + }); + + each(options.buttons, function(key) { + if (allowedButtons[key] === undefined) { + throw new Error("button key " + key + " is not allowed (options are " + buttons.join("\n") + ")"); + } + }); + + return options; + } + + exports.alert = function() { + var options; + + options = mergeDialogOptions("alert", ["ok"], ["message", "callback"], arguments); + + if (options.callback && !$.isFunction(options.callback)) { + throw new Error("alert requires callback property to be a function when provided"); + } + + /** + * overrides + */ + options.buttons.ok.callback = options.onEscape = function() { + if ($.isFunction(options.callback)) { + return options.callback.call(this); + } + return true; + }; + + return exports.dialog(options); + }; + + exports.confirm = function() { + var options; + + options = mergeDialogOptions("confirm", ["cancel", "confirm"], ["message", "callback"], arguments); + + /** + * overrides; undo anything the user tried to set they shouldn't have + */ + options.buttons.cancel.callback = options.onEscape = function() { + return options.callback.call(this, false); + }; + + options.buttons.confirm.callback = function() { + return options.callback.call(this, true); + }; + + // confirm specific validation + if (!$.isFunction(options.callback)) { + throw new Error("confirm requires a callback"); + } + + return exports.dialog(options); + }; + + exports.prompt = function() { + var options; + var defaults; + var dialog; + var form; + var input; + var shouldShow; + var inputOptions; + + // we have to create our form first otherwise + // its value is undefined when gearing up our options + // @TODO this could be solved by allowing message to + // be a function instead... + form = $(templates.form); + + // prompt defaults are more complex than others in that + // users can override more defaults + // @TODO I don't like that prompt has to do a lot of heavy + // lifting which mergeDialogOptions can *almost* support already + // just because of 'value' and 'inputType' - can we refactor? + defaults = { + className: "bootbox-prompt", + buttons: createLabels("cancel", "confirm"), + value: "", + inputType: "text" + }; + + options = validateButtons( + mergeArguments(defaults, arguments, ["title", "callback"]), + ["cancel", "confirm"] + ); + + // capture the user's show value; we always set this to false before + // spawning the dialog to give us a chance to attach some handlers to + // it, but we need to make sure we respect a preference not to show it + shouldShow = (options.show === undefined) ? true : options.show; + + /** + * overrides; undo anything the user tried to set they shouldn't have + */ + options.message = form; + + options.buttons.cancel.callback = options.onEscape = function() { + return options.callback.call(this, null); + }; + + options.buttons.confirm.callback = function() { + var value; + + switch (options.inputType) { + case "text": + case "textarea": + case "email": + case "select": + case "date": + case "time": + case "number": + case "password": + value = input.val(); + break; + + case "checkbox": + var checkedItems = input.find("input:checked"); + + // we assume that checkboxes are always multiple, + // hence we default to an empty array + value = []; + + each(checkedItems, function(_, item) { + value.push($(item).val()); + }); + break; + } + + return options.callback.call(this, value); + }; + + options.show = false; + + // prompt specific validation + if (!options.title) { + throw new Error("prompt requires a title"); + } + + if (!$.isFunction(options.callback)) { + throw new Error("prompt requires a callback"); + } + + if (!templates.inputs[options.inputType]) { + throw new Error("invalid prompt type"); + } + + // create the input based on the supplied type + input = $(templates.inputs[options.inputType]); + + switch (options.inputType) { + case "text": + case "textarea": + case "email": + case "date": + case "time": + case "number": + case "password": + input.val(options.value); + break; + + case "select": + var groups = {}; + inputOptions = options.inputOptions || []; + + if (!$.isArray(inputOptions)) { + throw new Error("Please pass an array of input options"); + } + + if (!inputOptions.length) { + throw new Error("prompt with select requires options"); + } + + each(inputOptions, function(_, option) { + + // assume the element to attach to is the input... + var elem = input; + + if (option.value === undefined || option.text === undefined) { + throw new Error("given options in wrong format"); + } + + // ... but override that element if this option sits in a group + + if (option.group) { + // initialise group if necessary + if (!groups[option.group]) { + groups[option.group] = $("").attr("label", option.group); + } + + elem = groups[option.group]; + } + + elem.append(""); + }); + + each(groups, function(_, group) { + input.append(group); + }); + + // safe to set a select's value as per a normal input + input.val(options.value); + break; + + case "checkbox": + var values = $.isArray(options.value) ? options.value : [options.value]; + inputOptions = options.inputOptions || []; + + if (!inputOptions.length) { + throw new Error("prompt with checkbox requires options"); + } + + if (!inputOptions[0].value || !inputOptions[0].text) { + throw new Error("given options in wrong format"); + } + + // checkboxes have to nest within a containing element, so + // they break the rules a bit and we end up re-assigning + // our 'input' element to this container instead + input = $("
"); + + each(inputOptions, function(_, option) { + var checkbox = $(templates.inputs[options.inputType]); + + checkbox.find("input").attr("value", option.value); + checkbox.find("label").append(option.text); + + // we've ensured values is an array so we can always iterate over it + each(values, function(_, value) { + if (value === option.value) { + checkbox.find("input").prop("checked", true); + } + }); + + input.append(checkbox); + }); + break; + } + + // @TODO provide an attributes option instead + // and simply map that as keys: vals + if (options.placeholder) { + input.attr("placeholder", options.placeholder); + } + + if (options.pattern) { + input.attr("pattern", options.pattern); + } + + if (options.maxlength) { + input.attr("maxlength", options.maxlength); + } + + // now place it in our form + form.append(input); + + form.on("submit", function(e) { + e.preventDefault(); + // Fix for SammyJS (or similar JS routing library) hijacking the form post. + e.stopPropagation(); + // @TODO can we actually click *the* button object instead? + // e.g. buttons.confirm.click() or similar + dialog.find(".btn-primary").click(); + }); + + dialog = exports.dialog(options); + + // clear the existing handler focusing the submit button... + dialog.off("shown.bs.modal"); + + // ...and replace it with one focusing our input, if possible + dialog.on("shown.bs.modal", function() { + // need the closure here since input isn't + // an object otherwise + input.focus(); + }); + + if (shouldShow === true) { + dialog.modal("show"); + } + + return dialog; + }; + + exports.dialog = function(options) { + options = sanitize(options); + + var dialog = $(templates.dialog); + var innerDialog = dialog.find(".modal-dialog"); + var body = dialog.find(".modal-body"); + var buttons = options.buttons; + var buttonStr = ""; + var callbacks = { + onEscape: options.onEscape + }; + + if ($.fn.modal === undefined) { + throw new Error( + "$.fn.modal is not defined; please double check you have included " + + "the Bootstrap JavaScript library. See http://getbootstrap.com/javascript/ " + + "for more details." + ); + } + + each(buttons, function(key, button) { + + // @TODO I don't like this string appending to itself; bit dirty. Needs reworking + // can we just build up button elements instead? slower but neater. Then button + // can just become a template too + buttonStr += ""; + callbacks[key] = button.callback; + }); + + body.find(".bootbox-body").html(options.message); + + if (options.animate === true) { + dialog.addClass("fade"); + } + + if (options.className) { + dialog.addClass(options.className); + } + + if (options.size === "large") { + innerDialog.addClass("modal-lg"); + } else if (options.size === "small") { + innerDialog.addClass("modal-sm"); + } + + if (options.title) { + body.before(templates.header); + } + + if (options.closeButton) { + var closeButton = $(templates.closeButton); + + if (options.title) { + dialog.find(".modal-header").prepend(closeButton); + } else { + closeButton.css("margin-top", "-10px").prependTo(body); + } + } + + if (options.title) { + dialog.find(".modal-title").html(options.title); + } + + if (buttonStr.length) { + body.after(templates.footer); + dialog.find(".modal-footer").html(buttonStr); + } + + + /** + * Bootstrap event listeners; used handle extra + * setup & teardown required after the underlying + * modal has performed certain actions + */ + + dialog.on("hidden.bs.modal", function(e) { + // ensure we don't accidentally intercept hidden events triggered + // by children of the current dialog. We shouldn't anymore now BS + // namespaces its events; but still worth doing + if (e.target === this) { + dialog.remove(); + } + }); + + /* + dialog.on("show.bs.modal", function() { + // sadly this doesn't work; show is called *just* before + // the backdrop is added so we'd need a setTimeout hack or + // otherwise... leaving in as would be nice + if (options.backdrop) { + dialog.next(".modal-backdrop").addClass("bootbox-backdrop"); + } + }); + */ + + dialog.on("shown.bs.modal", function() { + dialog.find(".btn-primary:first").focus(); + }); + + /** + * Bootbox event listeners; experimental and may not last + * just an attempt to decouple some behaviours from their + * respective triggers + */ + + if (options.backdrop !== "static") { + // A boolean true/false according to the Bootstrap docs + // should show a dialog the user can dismiss by clicking on + // the background. + // We always only ever pass static/false to the actual + // $.modal function because with `true` we can't trap + // this event (the .modal-backdrop swallows it) + // However, we still want to sort of respect true + // and invoke the escape mechanism instead + dialog.on("click.dismiss.bs.modal", function(e) { + // @NOTE: the target varies in >= 3.3.x releases since the modal backdrop + // moved *inside* the outer dialog rather than *alongside* it + if (dialog.children(".modal-backdrop").length) { + e.currentTarget = dialog.children(".modal-backdrop").get(0); + } + + if (e.target !== e.currentTarget) { + return; + } + + dialog.trigger("escape.close.bb"); + }); + } + + dialog.on("escape.close.bb", function(e) { + if (callbacks.onEscape) { + processCallback(e, dialog, callbacks.onEscape); + } + }); + + /** + * Standard jQuery event listeners; used to handle user + * interaction with our dialog + */ + + dialog.on("click", ".modal-footer button", function(e) { + var callbackKey = $(this).data("bb-handler"); + + processCallback(e, dialog, callbacks[callbackKey]); + }); + + dialog.on("click", ".bootbox-close-button", function(e) { + // onEscape might be falsy but that's fine; the fact is + // if the user has managed to click the close button we + // have to close the dialog, callback or not + processCallback(e, dialog, callbacks.onEscape); + }); + + dialog.on("keyup", function(e) { + if (e.which === 27) { + dialog.trigger("escape.close.bb"); + } + }); + + // the remainder of this method simply deals with adding our + // dialogent to the DOM, augmenting it with Bootstrap's modal + // functionality and then giving the resulting object back + // to our caller + + $(options.container).append(dialog); + + dialog.modal({ + backdrop: options.backdrop ? "static": false, + keyboard: false, + show: false + }); + + if (options.show) { + dialog.modal("show"); + } + + // @TODO should we return the raw element here or should + // we wrap it in an object on which we can expose some neater + // methods, e.g. var d = bootbox.alert(); d.hide(); instead + // of d.modal("hide"); + + /* + function BBDialog(elem) { + this.elem = elem; + } + + BBDialog.prototype = { + hide: function() { + return this.elem.modal("hide"); + }, + show: function() { + return this.elem.modal("show"); + } + }; + */ + + return dialog; + + }; + + exports.setDefaults = function() { + var values = {}; + + if (arguments.length === 2) { + // allow passing of single key/value... + values[arguments[0]] = arguments[1]; + } else { + // ... and as an object too + values = arguments[0]; + } + + $.extend(defaults, values); + }; + + exports.hideAll = function() { + $(".bootbox").modal("hide"); + + return exports; + }; + + + /** + * standard locales. Please add more according to ISO 639-1 standard. Multiple language variants are + * unlikely to be required. If this gets too large it can be split out into separate JS files. + */ + var locales = { + bg_BG : { + OK : "Ок", + CANCEL : "Отказ", + CONFIRM : "Потвърждавам" + }, + br : { + OK : "OK", + CANCEL : "Cancelar", + CONFIRM : "Sim" + }, + cs : { + OK : "OK", + CANCEL : "Zrušit", + CONFIRM : "Potvrdit" + }, + da : { + OK : "OK", + CANCEL : "Annuller", + CONFIRM : "Accepter" + }, + de : { + OK : "OK", + CANCEL : "Abbrechen", + CONFIRM : "Akzeptieren" + }, + el : { + OK : "Εντάξει", + CANCEL : "Ακύρωση", + CONFIRM : "Επιβεβαίωση" + }, + en : { + OK : "OK", + CANCEL : "Cancel", + CONFIRM : "OK" + }, + es : { + OK : "OK", + CANCEL : "Cancelar", + CONFIRM : "Aceptar" + }, + et : { + OK : "OK", + CANCEL : "Katkesta", + CONFIRM : "OK" + }, + fa : { + OK : "قبول", + CANCEL : "لغو", + CONFIRM : "تایید" + }, + fi : { + OK : "OK", + CANCEL : "Peruuta", + CONFIRM : "OK" + }, + fr : { + OK : "OK", + CANCEL : "Annuler", + CONFIRM : "D'accord" + }, + he : { + OK : "אישור", + CANCEL : "ביטול", + CONFIRM : "אישור" + }, + hu : { + OK : "OK", + CANCEL : "Mégsem", + CONFIRM : "Megerősít" + }, + hr : { + OK : "OK", + CANCEL : "Odustani", + CONFIRM : "Potvrdi" + }, + id : { + OK : "OK", + CANCEL : "Batal", + CONFIRM : "OK" + }, + it : { + OK : "OK", + CANCEL : "Annulla", + CONFIRM : "Conferma" + }, + ja : { + OK : "OK", + CANCEL : "キャンセル", + CONFIRM : "確認" + }, + lt : { + OK : "Gerai", + CANCEL : "Atšaukti", + CONFIRM : "Patvirtinti" + }, + lv : { + OK : "Labi", + CANCEL : "Atcelt", + CONFIRM : "Apstiprināt" + }, + nl : { + OK : "OK", + CANCEL : "Annuleren", + CONFIRM : "Accepteren" + }, + no : { + OK : "OK", + CANCEL : "Avbryt", + CONFIRM : "OK" + }, + pl : { + OK : "OK", + CANCEL : "Anuluj", + CONFIRM : "Potwierdź" + }, + pt : { + OK : "OK", + CANCEL : "Cancelar", + CONFIRM : "Confirmar" + }, + ru : { + OK : "OK", + CANCEL : "Отмена", + CONFIRM : "Применить" + }, + sq : { + OK : "OK", + CANCEL : "Anulo", + CONFIRM : "Prano" + }, + sv : { + OK : "OK", + CANCEL : "Avbryt", + CONFIRM : "OK" + }, + th : { + OK : "ตกลง", + CANCEL : "ยกเลิก", + CONFIRM : "ยืนยัน" + }, + tr : { + OK : "Tamam", + CANCEL : "İptal", + CONFIRM : "Onayla" + }, + zh_CN : { + OK : "OK", + CANCEL : "取消", + CONFIRM : "确认" + }, + zh_TW : { + OK : "OK", + CANCEL : "取消", + CONFIRM : "確認" + } + }; + + exports.addLocale = function(name, values) { + $.each(["OK", "CANCEL", "CONFIRM"], function(_, v) { + if (!values[v]) { + throw new Error("Please supply a translation for '" + v + "'"); + } + }); + + locales[name] = { + OK: values.OK, + CANCEL: values.CANCEL, + CONFIRM: values.CONFIRM + }; + + return exports; + }; + + exports.removeLocale = function(name) { + delete locales[name]; + + return exports; + }; + + exports.setLocale = function(name) { + return exports.setDefaults("locale", name); + }; + + exports.init = function(_$) { + return init(_$ || $); + }; + + return exports; +})); diff --git a/hotel_calendar/static/src/lib/hcalendar/css/hcalendar.css b/hotel_calendar/static/src/lib/hcalendar/css/hcalendar.css new file mode 100644 index 000000000..5379c2791 --- /dev/null +++ b/hotel_calendar/static/src/lib/hcalendar/css/hcalendar.css @@ -0,0 +1,499 @@ +/* + * Hotel Calendar JS v0.0.1a - 2017-2018 + * GNU Public License + * Aloxa Solucions S.L. + * Alexandre Díaz + */ + + +/** ANIMATIONS **/ +@keyframes cell-invalid { + 0% { + background: #ff0000; + background: repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 40%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + background: -webkit-repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 40%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + background: -moz-repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 40%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + } + 50% { + background: #ff0000; + background: repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 40%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + background: -webkit-repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 35%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + background: -moz-repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 40%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + } + 100% { + background: #ff0000; + background: repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 30%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + background: -webkit-repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 30%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + background: -moz-repeating-linear-gradient(141deg,#ff0000 10%, #ff0000 30%, rgba(255,0,0,0.51) 30%, rgba(255,0,0,0.51) 50%); + } +} + +#hcal_load { + width: 100%; + height: 90vh; + text-align: center; + line-height: 90vh; + color: darkgray; +} +#hcal_load > span { + line-height: 24px; + display: inline-block; + vertical-align: middle; +} + +#pms-search { + position: fixed; + z-index: 9; +} + +#pms-menu { + background-color: white; + height: 100%; +} + +#hcal_widget { + max-height: 100%; +} + +#cal-pag-prev-plus, #cal-pag-prev, #cal-pag-selector, #cal-pag-next, #cal-pag-next-plus { + min-height: 0px; +} + +.table-reservations-header { + order: 1; + flex-grow: 1; + overflow-y: scroll; + overflow-x: hidden; +} +.table-reservations { + order: 2; + flex-grow: 2; + overflow-y: scroll; + overflow-x: hidden; + position: relative; + max-height: 57vh; +} +.table-calcs-header { + order: 3; + flex-grow: 1; + overflow-y: scroll; + overflow-x: hidden; +} +.table-calcs { + order: 4; + flex-grow: 2; + overflow-y: scroll; + overflow-x: hidden; + max-height: 20vh; +} +.table-calcs input, .table-reservations-header input { + border-radius: 0; + border: 1px solid lightgray; + width: 100%; +} +.table-calcs input { + text-align: center; +} + +.hcal-event-day { + background-color: #6ebcff !important; +} + +.btn-hcal { } +.btn-hcal.hcal-cell-current-day { + background-color: #7c7bad66; + color: #654a37; +} +.btn-hcal.hcal-cell-end-week { + background-color: #0D5A8F; +} +.btn-hcal-3d { + color: white; + background-color: #7c7bad; + border: 1px solid #cfcfdd; + /*border-color: white black black white !important;*/ +} +.btn-hcal-flat { + background-color: #cfcfdd; + border: 1px solid #cfcfdd; +} + +.hcal-warn-ob-indicator { + position: absolute; + background-color: red; + color: yellow; + border: 1px solid black; + z-index: 9; + width: 25px; + height: 20px; + text-align: center; +} + +.table-calcs-header .hcal-table, .table-reservations-header .hcal-table { + height: 46px; +} + +.hcal-table, .hcal-table-day { + border-collapse: initial !important; + width: 100%; + table-layout: fixed; +} +.hcal-table > tbody { + max-height: 50vh; + overflow: scroll; +} +.hcal-table td { + text-align: center; + min-width: 100px; + white-space: nowrap; + overflow: hidden; +} +.hcal-table a { + text-decoration: none; +} +.hcal-table tr:hover td:not(.hcal-unused-zone):not(.hcal-cell-highlight):not(.hcal-cell-current-day):not(.hcal-cell-end-week):not(.btn-hcal):not(.hcal-cell-invalid) { + /*background-color: #F6F6F6; + border: 5px solid red;*/ +} + +.hcal-table tr:hover td.hcal-cell-room-type-group-item { + background-color: #7c7bad80; + color: white; +} + +.hcal-restriction-room-day { + background-color: #b3218366 !important; +} + +.hcal-table-day { + height: 100%; + border-collapse: collapse !important; + border: 0 dotted #cfcfcf; + border-width: 2px 0; +} +/*.hcal-table-day tr:first-child td{ + border: 1px solid #727272 !important; + border-width: 0 1px 0 0 !important; +} +.hcal-table tr:not(:last-child) .hcal-table-day tr:last-child td { + border-style: solid; + border-color: #727272 !important; + border-bottom-width: 1px !important; +} +.hcal-table-day tr:not(:last-child):not(:first-child) td { + border-width: 0; +}*/ +.hcal-table-day td { + padding: 2px; + height: 2.3em; + font-size: 7px; + vertical-align: middle; + font-weight: bold; + border: 1px solid #cecece !important; +} +.hcal-table-day td:hover:not(.hcal-cell-highlight):not(.hcal-cell-invalid) { + background-color: #FCFEE1 !important; +} + +.hcal-cell-current-day { + background-color: #E0F8B0; +} +.hcal-cell-end-week { + background-color: #E2EAF9; +} + +.hcal-cell-day-selector { + text-align: center; + vertical-align: center; + max-width: 140px; +} +.hcal-cell-day-selector a { + font-size: 22px; + padding: 0 0.5em; +} +.hcal-cell-day-selector span { + cursor: pointer; +} +.hcal-cell-day-selector input { + border: 1px solid lightgray; + width: 120px; + font-size: large; + text-align: center; +} + +.hcal-cell-month { + overflow: hidden; + max-width: 0; + text-align: center !important; + vertical-align: middle; + white-space: nowrap; +} +.hcal-cell-month:nth-child(n+3) { + border-left-width: 2px !important; +} + +.hcal-cell-start-month { + border-left-width: 2px !important; +} + +.hcal-room-type:hover { + cursor:pointer; +} + +.hcal-cell-highlight { + background-color: #F8FD9C; +} + +.hcal-cell-invalid { + background-color: #e58e92; +} + + +.hcal-cell-room-type-group-item-day { + padding: 0 !important; + height: 100%; +} + +.hcal-input-changed { + background-color: rgb(237,110,110); + border: 1px solid gray; +} + +.hcal-cell-room-type-group-item-day-occupied { + /*background-color: #227eaf;*/ +} +.hcal-cell-room-type-group-item-day-occupied[data-hcal-reservation-cell-type=soft-start] { + background-color: #729fcf; + /*border: 2px solid #3465a4;*/ +} + +.hcal-cell-pagination button { + padding: 0.1em; + border-radius: 0; + background-color: initial; +} + +#btn_save_changes.need-save { + color: yellow; + background: orange; +} + +.hcal-hidden { + display: none; +} + +.hcal-reservation-unselect { + opacity: 0.3; + pointer-events: none; +} + +.hcal-reservation { + position: absolute; + text-align: center; + /*background-color: #729fcf;*/ + /*transform: skewX(-25deg);*/ + border-radius: 5px; + border: 1px solid #3465a4; + color: white; + white-space: nowrap; + overflow: hidden; + z-index:8; +} +.hcal-reservation:hover { + background-color: #4e97bf; +} +.hcal-reservation span { + position: relative; +} + +.hcal-reservation-splitted { + border-width: 1px 6px; +} + +.hcal-reservation-invalid { + background-color: #c8543b !important; + border-color: #6c3624 !important; +} +.hcal-reservation-invalid:hover { + background-color: #f5b595 !important; + border-color: #c8543b !important; +} + +.hcal-reservation-foreground { + pointer-events: none; + opacity: 0.9; + color: transparent !important; + background: repeating-linear-gradient( + 45deg, + #606dbc, + #606dbc 10px, + #465298 10px, + #465298 20px + ); +} + +.hcal-reservation-invalid-swap { + pointer-events: none; + opacity: 0.9; + color: transparent !important; + background: repeating-linear-gradient( + 45deg, + #BA6359, + #BA6359 10px, + #dfe066 10px, + #dfe066 20px + ); +} + +.hcal-reservation-action { + border: 2px dashed #3465a4; + opacity: 0.9; + pointer-events: none; + z-index:10; +} + +.hcal-reservation-readonly:not(.hcal-unused-zone) { + border: 2px solid #99995b; + color: white !important; + font-weight: bold; + background: #ffee00; + background: repeating-radial-gradient(circle farthest-corner at right center, #ffee00 0%, #2c2c2c 5%, #ffff00 10%, #2c2c2c 20%, #2c2c2c 100%); + background: -webkit-repeating-radial-gradient(circle farthest-corner at right center, #ffee00 0%, #2c2c2c 5%, #ffff00 10%, #2c2c2c 20%, #2c2c2c 100%); + background: -moz-repeating-radial-gradient(circle farthest-corner at right center, #ffee00 0%, #2c2c2c 5%, #ffff00 10%, #2c2c2c 20%, #2c2c2c 100%); +} + +.hcal-reservation-swap-in-selected { + background-color: #005B96 !important; + border-color: #99bdd5 !important; +} + +.hcal-reservation-swap-out-selected { + border-color: #005B96 !important; + background-color: #99bdd5 !important; +} + +.hcal-row-room-type-group-item { + text-align: center; +} + +tr.hcal-row-room-type-group-overbooking-item td { + background-color: #c78585; +} + +.hcal-cell-month-day { + text-align: center !important; +} + +.hcal-cell-room-type-group-day { + text-align: center !important; +} + +.hcal-table-type-group-day { + border-collapse: collapse; + width:100%; +} +.hcal-table-type-group-day td { + border-width: 0; +} +.hcal-table-type-group-day tr:not(:last-child) td { + border-bottom-width: 1px; +} + +.hcal-cell-room-type { + cursor: pointer; +} +td.hcal-cell-room-type { + border-right-width: 2px; +} + +td.hcal-cell-room-type-group-day, td.hcal-cell-room-type { + border-top-width: 2px; +} +td.hcal-cell-room-type-group-day { + padding: 0; +} + +td.hcal-cell-room-type-group-item { + text-align: center !important; + vertical-align: middle; + font-size: x-small; + white-space: nowrap; +} +td.hcal-cell-room-type-group-item:last-child { + border-right-width: 2px; +} + +.hcal-cell-type-group-day-free { + text-align: center; + font-weight: bold; + padding: 0 !important; +} +.hcal-cell-type-group-day-price { + text-align: center; +} + +td.hcal-cell-header-day { + padding: 0; + vertical-align: middle; +} + +td.hcal-cell-month-day-occupied { + padding: 0; + text-align: center; +} + +.hcal-cell-detail-room-free-type-group-item-day, +.hcal-cell-detail-room-free-total-group-item-day, +.hcal-cell-detail-room-perc-occup-group-item-day, +.hcal-cell-detail-room-price-type-group-item-day, +.hcal-cell-detail-room-min-stay-group-item-day { + border: 1px solid lightgray; +} +.hcal-cell-detail-room-min-stay-group-item-day { + border-color: #307CB0 lightgray lightgray lightgray; + border-width: 2px 1px 1px 1px; +} + +.hcal-cell-detail-room-group-item { + white-space: nowrap; + text-align: right !important; + text-overflow: '...'; +} + +/* FIXME: Workaround for work with other currencies */ +.hcal-cell-detail-room-group-item[data-currency-symbol='€'] { + text-overflow: '... €'; +} + +.hcal-unused-zone { + border: 1px solid #444; + border-radius: 0px; +} + +.input-price { + width: 100%; + border-style: none !important; + border-radius: 0 !important; + text-align: center; +} + +button#btn_action_bookings { + margin-bottom: -1px !important; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} +input#bookings_search { + border-top-left-radius: 0; + border-top-right-radius: 0; + margin-bottom: 0.2em; +} + +.noselect { + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; /* Non-prefixed version, currently + supported by Chrome and Opera */ +} diff --git a/hotel_calendar/static/src/lib/hcalendar/css/hcalendar_management.css b/hotel_calendar/static/src/lib/hcalendar/css/hcalendar_management.css new file mode 100644 index 000000000..5ff23e8a0 --- /dev/null +++ b/hotel_calendar/static/src/lib/hcalendar/css/hcalendar_management.css @@ -0,0 +1,177 @@ +/* + * Hotel Calendar Management JS v0.0.1a - 2017 + * GNU Public License + * Aloxa Solucions S.L. + * Alexandre Díaz + */ + +.hcal-management-table, .hcal-management-table-day { + border-collapse: collapse !important; + table-layout: fixed; +} +.hcal-management-table > tbody { + max-height: 50vh; + overflow: scroll; +} +.hcal-management-table > thead > tr > td { + /*text-align: center !important;*/ + width: 110px !important; + vertical-align: center; + min-width: 110px; + height: 1.5em; + min-height: 1.5em; + white-space: nowrap; + /*overflow: hidden;*/ + border: 1px solid black !important; +} +.hcal-management-table > tbody > tr > td { + /*text-align: center !important;*/ + width: 110px !important; + vertical-align: center; + min-width: 110px; + height: 115px; + min-height: 100px; + white-space: nowrap; + /*overflow: hidden;*/ + padding: 5px !important; + border: 1px solid black; +} +.hcal-management-table thead td { + text-align: center !important; +} +.hcal-management-table a { + text-decoration: none; +} +.hcal-management-table tr:hover td:not(.hcal-cell-highlight):not(.hcal-cell-current-day):not(.hcal-cell-end-week):not(.btn-hcal):not(.hcal-cell-invalid) { + background-color: #F6F6F6; +} + +.hcal-management-table tr:hover td.hcal-cell-room-type-group-item { + background-color: #9bcd9b; + color: black; +} + +.hcal-management-table input[type='edit'] { + width: 100%; + font-size: 10px; + text-align: center; +} +.hcal-management-table select { + font-size: 9px; +} + +.hcal-management-table-day { + height: 100%; + border-collapse: collapse !important; +} +.hcal-management-table-day td { + padding: 2px; + height: 2.3em; + font-size: 7px; + vertical-align: middle; + font-weight: bold; + border: 0; +} +.hcal-management-table-day td:hover:not(.hcal-cell-highlight):not(.hcal-cell-invalid) { + background-color: #FCFEE1 !important; +} + +.hcal-management-low > tbody > tr > td, .hcal-management-low > table > tbody > tr > td { + height: 35px !important; +} + +.hcal-management-medium > tbody > tr > td, .hcal-management-medium > table > tbody > tr > td { + height: 60px !important; +} + +.hcal-management-medium tr[name='rest_b'], .hcal-management-medium tr[name='rest_c'], + .hcal-management-low tr[name='rest_a'], .hcal-management-low tr[name='rest_b'], .hcal-management-low tr[name='rest_c'] { + display: none; + visibility: hidden; +} + +.table-vrooms { + float: left; + margin-top: 1.6em; +} + +#hcal_management_widget { + overflow: auto; + height: 84vh; +} + +#hcal-management-container-dd { + overflow: auto; + position: relative; +} + +#btn_save_changes, #btn_massive_changes { + height: 56px; +} +#btn_save_changes i, #btn_massive_changes i { + top: 22%; +} + +.hcal-management-input-changed { + background-color: rgb(237,110,110); + border: 1px solid gray; +} + +.hcal-management-record-changed { + background-color: #FFFF66 !important; +} + +table.hcal-management-table input { + border: 1px solid lightgray; +} + +.hcal-border-radius-right { + border-top-right-radius: 25px; + border-bottom-right-radius: 25px; +} + +.hcal-border-radius-left { + border-top-left-radius: 25px; + border-bottom-left-radius: 25px; +} + +.hcal-management-record-options { + padding: 0.5em; +} + +button.hcal-management-input { + font-size: 9px; + border: 1px solid gray; + padding: 0.5em 2em 0.2em 2em; + border-radius: 3px; + margin: 0.2em; + + background: rgba(255,255,255,1); + background: -moz-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(227,227,227,1) 47%, rgba(194,194,194,1) 100%); + background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(255,255,255,1)), color-stop(47%, rgba(227,227,227,1)), color-stop(100%, rgba(194,194,194,1))); + background: -webkit-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(227,227,227,1) 47%, rgba(194,194,194,1) 100%); + background: -o-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(227,227,227,1) 47%, rgba(194,194,194,1) 100%); + background: -ms-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(227,227,227,1) 47%, rgba(194,194,194,1) 100%); + background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(227,227,227,1) 47%, rgba(194,194,194,1) 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#c2c2c2', GradientType=0 ); +} +button.hcal-management-input:hover { + background: rgba(255,255,255,1); + background: -moz-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(246,246,246,1) 47%, rgba(237,237,237,1) 100%); + background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(255,255,255,1)), color-stop(47%, rgba(246,246,246,1)), color-stop(100%, rgba(237,237,237,1))); + background: -webkit-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(246,246,246,1) 47%, rgba(237,237,237,1) 100%); + background: -o-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(246,246,246,1) 47%, rgba(237,237,237,1) 100%); + background: -ms-linear-gradient(top, rgba(255,255,255,1) 0%, rgba(246,246,246,1) 47%, rgba(237,237,237,1) 100%); + background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(246,246,246,1) 47%, rgba(237,237,237,1) 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#ededed', GradientType=0 ); +} +button.hcal-management-input-active { + background: rgba(245,215,93,1) !important; + background: -moz-linear-gradient(top, rgba(245,215,93,1) 0%, rgba(245,165,44,1) 47%, rgba(255,153,0,1) 100%) !important; + background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(245,215,93,1)), color-stop(47%, rgba(245,165,44,1)), color-stop(100%, rgba(255,153,0,1))) !important; + background: -webkit-linear-gradient(top, rgba(245,215,93,1) 0%, rgba(245,165,44,1) 47%, rgba(255,153,0,1) 100%) !important; + background: -o-linear-gradient(top, rgba(245,215,93,1) 0%, rgba(245,165,44,1) 47%, rgba(255,153,0,1) 100%) !important; + background: -ms-linear-gradient(top, rgba(245,215,93,1) 0%, rgba(245,165,44,1) 47%, rgba(255,153,0,1) 100%) !important; + background: linear-gradient(to bottom, rgba(245,215,93,1) 0%, rgba(245,165,44,1) 47%, rgba(255,153,0,1) 100%) !important; + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f5d75d', endColorstr='#ff9900', GradientType=0 ) !important; +} diff --git a/hotel_calendar/static/src/lib/hcalendar/js/hcalendar.js b/hotel_calendar/static/src/lib/hcalendar/js/hcalendar.js new file mode 100644 index 000000000..4432ec0ab --- /dev/null +++ b/hotel_calendar/static/src/lib/hcalendar/js/hcalendar.js @@ -0,0 +1,2844 @@ +/* global _, moment */ +'use strict'; +/* + * Hotel Calendar JS - 2017-2018 + * GNU Public License + * Alexandre Díaz + * + * Dependencies: + * - moment + * - underscore + * - awesomeicons !shit + * - bootstrap !shit + */ + +function HotelCalendar(/*String*/querySelector, /*Dictionary*/options, /*List*/pricelist, /*restrictions*/restrictions, /*HTMLObject?*/_base) { + if (window === this) { + return new HotelCalendar(querySelector, options, pricelist, _base); + } + + this.$base = (_base === 'undefined') ? document : _base; + + if (typeof querySelector === 'string') { + this.e = this.$base.querySelector(querySelector); + if (!this.e) { + return false; + } + } else if (typeof querySelector === 'object') { + this.e = querySelector; + } else { + return { + Version: '0.5', + Author: "Alexandre Díaz", + Created: "20/04/2017", + Updated: "19/07/2018" + }; + } + + /** Strings **/ + this._strings = { + 'Save Changes': 'Save Changes' + }; + + /** Options **/ + options = options || {}; + this.options = { + startDate: ((options.startDate && HotelCalendar.toMomentUTC(options.startDate)) || moment(new Date()).utc()).subtract('1', 'd'), + days: (options.days || ((options.startDate && HotelCalendar.toMomentUTC(options.startDate)) || moment(new Date())).clone().local().daysInMonth()), + rooms: options.rooms || [], + allowInvalidActions: options.allowInvalidActions || false, + assistedMovement: options.assistedMovement || false, + endOfWeek: options.endOfWeek || 6, + endOfWeekOffset: options.endOfWeekOffset || 0, + divideRoomsByCapacity: options.divideRoomsByCapacity || false, + currencySymbol: options.currencySymbol || '€', + showPricelist: options.showPricelist || false, + showAvailability: options.showAvailability || false, + showNumRooms: options.showNumRooms || 0, + paginatorStepsMin: options.paginatorAdv || 1, + paginatorStepsMax: options.paginatorAdv || 15, + }; + + // Check correct values + if (this.options.rooms.length > 0 && !(this.options.rooms[0] instanceof HRoom)) { + this.options.rooms = []; + console.warn("[Hotel Calendar][init] Invalid Room definiton!"); + } + + /** Internal Values **/ + this._pricelist = pricelist || []; // Store Prices + this._pricelist_id = -1; // Store Price Plan ID (Because can be edited) + this._restrictions = restrictions || {}; // Store Restrictions + this._reservations = []; // Store Reservations + this._reservationsMap = {}; // Store Reservations Mapped by Room for Search Purposes + this._modeSwap = HotelCalendar.MODE.NONE; // Store Swap Mode + this._endDate = this.options.startDate.clone().add(this.options.days, 'd'); // Store End Calendar Day + this._tableCreated = false; // Store Flag to Know Calendar Creation + this._cellSelection = {start:false, end:false, current:false}; // Store Info About Selected Cells + this._lazyModeReservationsSelection = false; // Store Info About Timer for Selection Action + this._domains = {}; // Store domains for filter rooms & reservations + + /***/ + this._reset_action_reservation(); + if (!this._create()) { + return false; + } + + + /** Main Events **/ + document.addEventListener('mouseup', this.onMainMouseUp.bind(this), false); + document.addEventListener('touchend', this.onMainMouseUp.bind(this), false); + document.addEventListener('keyup', this.onMainKeyUp.bind(this), false); + document.addEventListener('keydown', this.onMainKeyDown.bind(this), false); + window.addEventListener('resize', _.debounce(this.onMainResize.bind(this), 300), false); + + return this; +} + +HotelCalendar.prototype = { + /** PUBLIC MEMBERS **/ + addEventListener: function(/*String*/event, /*Function*/callback) { + this.e.addEventListener(event, callback); + }, + + //==== CALENDAR + setStartDate: function(/*String,MomentObject*/date, /*Int?*/days, /*Bool*/fullUpdate, /*Functions*/callback) { + if (moment.isMoment(date)) { + this.options.startDate = date.subtract('1','d'); + } else if (typeof date === 'string'){ + this.options.startDate = HotelCalendar.toMomentUTC(date).subtract('1','d'); + } else { + console.warn("[Hotel Calendar][setStartDate] Invalid date format!"); + return; + } + + if (typeof days !== 'undefined') { + this.options.days = days; + } + + this._endDate = this.options.startDate.clone().add(this.options.days, 'd'); + + /*this.e.dispatchEvent(new CustomEvent( + 'hcOnChangeDate', + {'detail': {'prevDate':curDate, 'newDate': $this.options.startDate}}));*/ + this._updateView(!fullUpdate, callback); + }, + + getOptions: function(/*String?*/key) { + if (typeof key !== 'undefined') { + return this.options[key]; + } + return this.options; + }, + + setSwapMode: function(/*Int*/mode) { + if (mode !== this._modeSwap) { + this._modeSwap = mode; + if (this._modeSwap === HotelCalendar.MODE.NONE) { + this._dispatchSwapReservations(); + this._reset_action_reservation(); + } + + this._updateHighlightSwapReservations(); + } + }, + + getSwapMode: function() { + return this._modeSwap; + }, + + //==== DOMAINS + setDomain: function(/*Int*/section, /*Array*/domain) { + if (this._domains[section] !== domain) { + this._domains[section] = domain; + if (section === HotelCalendar.DOMAIN.RESERVATIONS) { + this._filterReservations(); + } else if (section === HotelCalendar.DOMAIN.ROOMS) { + this._filterRooms(); + } + } + }, + + getDomain: function(/*Int*/section) { + return this._domains[section]; + }, + + //==== RESERVATIONS + _filterReservations: function() { + for (var r of this._reservations) { + r._active = this._in_domain(r, this._domains[HotelCalendar.DOMAIN.RESERVATIONS]); + this._updateReservation(r, true); + } + + //_.defer(function(){ this._updateReservationOccupation() }.bind(this)); + }, + + getReservationAction: function() { + return this.reservationAction; + }, + + getReservation: function(/*Int,String*/id) { + return _.find(this._reservations, function(item){ return item.id == id; }); + }, + + // getReservationDiv: function(/*HReservationObject*/reservationObj) { + // var reservDiv = this.e.querySelector(`div.hcal-reservation[data-hcal-reservation-obj-id='${reservationObj.id}']`); + // return reservDiv; + // }, + + setReservations: function(/*List*/reservations) { + for (var reservation of this._reservations) { + this.removeReservation(reservation); + } + + this._reservations = []; + this.addReservations(reservations); + }, + + addReservations: function(/*List*/reservations, /*Bool*/forced) { + if (!reservations) { + return; + } + + if (reservations.length > 0 && !(reservations[0] instanceof HReservation)) { + console.warn("[HotelCalendar][addReservations] Invalid Reservation definition!"); + } else { + // Merge + var uzr = []; + for (var r of reservations) { + var rindex = !forced?_.findKey(this._reservations, {'id': r.id}):false; + if (rindex) { + r._html = this._reservations[rindex]._html; + if (this._reservations[rindex].overbooking && !r.overbooking) { + if (this.getReservationsByRoom(this._reservations[rindex].room).length === 1) { + this.removeOBRoomRow(this._reservations[rindex]); + } + } + this._reservations[rindex] = r; + this._cleanUnusedZones(r); + } else { + this._reservations.push(r); + } + } + + // Create & Render New Reservations + _.defer(function(reservs){ + var unusedZones = this._createUnusedZones(reservs); + // Add Unused Zones + this._reservations = this._reservations.concat(unusedZones); + // Create Map + this._updateReservationsMap(); + + reservs = reservs.concat(unusedZones); + for (var r of reservs) { + r._active = this._in_domain(r, this._domains[HotelCalendar.DOMAIN.RESERVATIONS]); + this._calcReservationCellLimits(r); + if (r._html) { + r._html.innerText = r.title; + } else { + if (r._limits.isValid()) { + r._html = document.createElement('div'); + r._html.dataset.hcalReservationObjId = r.id; + r._html.classList.add('hcal-reservation'); + r._html.classList.add('noselect'); + r._html.innerText = r.title; + this.edivr.appendChild(r._html); + + if (r.unusedZone) { + r._html.classList.add('hcal-unused-zone'); + } else { + this._assignReservationsEvents([r._html]); + } + } + } + this._updateReservation(r); + } + }.bind(this), reservations); + + _.defer(function(){ this._updateReservationOccupation(); }.bind(this)); + } + }, + + removeReservation: function(/*Int/HReservationObject*/reservation) { + var reserv = reservation; + if (!(reserv instanceof HReservation)) { + reserv = this.getReservation(reservation); + } + + if (reserv) { + // Remove all related content... + var elms = [reserv._html, this.e.querySelector(`.hcal-warn-ob-indicator[data-hcal-reservation-obj-id='${reserv.id}']`)]; + for (var elm of elms) { + if (elm && elm.parentNode) { + elm.parentNode.removeChild(elm); + } + } + // Remove OB Row + if (reserv.overbooking) { + if (this.getReservationsByRoom(reserv.room).length === 1) { + this.removeOBRoomRow(reserv); + } + } + // Remove Unused Zones + this._cleanUnusedZones(reserv); + + this._reservations = _.without(this._reservations, reserv); + this._updateReservationsMap(); + } else { + console.warn(`[HotelCalendar][removeReservation] Can't remove '${reservation.id}' reservation!`); + } + }, + + getReservationsByDay: function(/*MomentObject*/day, /*Bool?*/noCheckouts, /*Bool?*/includeUnusedZones, /*Int?*/nroom, /*Int?*/nbed, /*HReservation?*/ignoreThis) { + var inclusivity = noCheckouts?'[)':'[]'; + + if (typeof nroom !== 'undefined') { + return _.filter(this._reservationsMap[nroom], function(item){ + return day.isBetween(item.startDate, item.endDate, 'day', inclusivity) && + (typeof nbed === 'undefined' || item._beds.includes(nbed)) && + ((includeUnusedZones && item.unusedZone) || !item.unusedZone) && + item !== ignoreThis; + }); + } else { + return _.filter(this._reservations, function(item){ + return day.isBetween(item.startDate, item.endDate, 'day', inclusivity) && + (typeof nbed === 'undefined' || item._beds.includes(nbed)) && + ((includeUnusedZones && item.unusedZone) || !item.unusedZone) && + item !== ignoreThis; + }); + } + }, + + getReservationsByRoom: function(/*Int,HRoomObject*/room, /*Boolean*/includeUnusedZones) { + if (!(room instanceof HRoom)) { room = this.getRoom(room); } + if (room) { + return _.filter(this._reservationsMap[room.id], function(item){ + return (includeUnusedZones || (!includeUnusedZones && !item.unusedZone)); + }); + } + + return []; + }, + + _updateReservationsMap: function() { + this._reservationsMap = {}; + this._reservations.map(function(current){ + if (!(current.room.id in this._reservationsMap)) { + this._reservationsMap[current.room.id] = []; + } + this._reservationsMap[current.room.id].push(current); + }.bind(this)); + }, + + _calcReservationCellLimits: function(/*HReservationObject*/reservation, /*Int?*/nbed, /*Bool?*/notCheck) { + var limits = new HLimit(); + if (!reservation.startDate || !reservation.endDate) { + return limits; + } + + var notFound; + do { + notFound = false; + + // Num of beds + var bedNum; + if (typeof nbed === 'undefined') { + if (reservation._beds && reservation._beds.length) { + bedNum = reservation._beds[0]; + } else { + bedNum = (reservation.unusedZone)?1:0; + } + } else { + bedNum = nbed; + } + + // Search Initial Cell + if (reservation.startDate.clone().local().isSameOrAfter(this.options.startDate, 'd')) { + reservation._drawModes[0] = 'hard-start'; + limits.left = this.getCell(reservation.startDate.clone().local(), + reservation.room, + bedNum); + } + else { + reservation._drawModes[0] = 'soft-start'; + limits.left = this.getCell(this.options.startDate.clone().local(), + reservation.room, + bedNum); + } + + // More Beds? + var rpersons = (reservation.room.shared || this.options.divideRoomsByCapacity)?reservation.room.capacity:1; + var reservPersons = reservation.getTotalPersons(false); + if ((reservation.room.shared || this.options.divideRoomsByCapacity) && reservPersons > 1 && bedNum+reservPersons <= rpersons) { + bedNum += reservPersons-1; + } + + // Search End Cell + if (reservation.endDate.clone().local().isSameOrBefore(this._endDate, 'd')) { + reservation._drawModes[1] = 'hard-end'; + limits.right = this.getCell(reservation.endDate.clone().local(), + reservation.room, + bedNum); + } + else { + reservation._drawModes[1] = 'soft-end'; + limits.right = this.getCell(this._endDate.clone().local(), + reservation.room, + bedNum); + } + + // Exists other reservation in the same place? + if (!notCheck && limits.isValid()) { + var diff_date = this.getDateDiffDays(reservation.startDate, reservation.endDate); + var numBeds = +limits.right.dataset.hcalBedNum - +limits.left.dataset.hcalBedNum; + var ndate = reservation.startDate.clone().local(); + for (var i=0; i= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + + // Update Reservations Position + var bounds = row.getBoundingClientRect(); + var cheight = bounds.bottom-bounds.top; + var start_index = _.indexOf(this.options.rooms, ob_room) + 1; + for (var i=start_index; i 0) + humantext += `Min. Stay: ${restr[0]}\n`; + if (restr[1] > 0) + humantext += `Min. Stay Arrival: ${restr[1]}\n`; + if (restr[2] > 0) + humantext += `Max. Stay: ${restr[2]}\n`; + if (restr[3] > 0) + humantext += `Max. Stay Arrival: ${restr[3]}\n`; + if (restr[4]) + humantext += `Closed: ${restr[4]}\n`; + if (restr[5]) + humantext += `Closed Arrival: ${restr[5]}\n`; + if (restr[6]) + humantext += `Closed Departure: ${restr[6]}`; + cell.title = humantext; + } + else { + cell.classList.remove('hcal-restriction-room-day'); + cell.title = ''; + } + } + } + } + } + } + } + } + }, + + //==== DETAIL CALCS + calcDayRoomTypeReservations: function(/*String,MomentObject*/day, /*String*/room_type) { + var day = HotelCalendar.toMoment(day); + if (!day) { + return false; + } + + var reservs = this.getDayRoomTypeReservations(day, room_type); + var num_rooms = this.getRoomsCapacityByType(room_type); + for (var r of reservs) { + if (r.unusedZone || r.overbooking) { + continue; + } + num_rooms -= (r.room && r.room.shared)?r.getTotalPersons(false):1; + } + + return num_rooms; + }, + + calcDayRoomTotalReservations: function(/*String,MomentObject*/day) { + var day = HotelCalendar.toMoment(day); + if (!day) { + return false; + } + + var reservs = this.getReservationsByDay(day, true); + var num_rooms = this.getRoomsCapacityTotal(); + for (var r of reservs) { + if (r.unusedZone || r.overbooking) { + continue; + } + num_rooms -= (r.room && r.room.shared)?r.getTotalPersons(false):1; + } + + return num_rooms; + }, + + calcReservationOccupation: function(/*String,MomentObject*/day, /*String*/room_type) { + var day = HotelCalendar.toMoment(day); + if (!day) { + return false; + } + + var reservs = this.getReservationsByDay(day, true); + return Math.round(reservs.length/_.filter(this.options.rooms, function(item){ return !item.overbooking; }).length*100.0); + }, + + + + /** PRIVATE MEMBERS **/ + //==== MAIN FUNCTIONS + _reset_action_reservation: function() { + if (this._lazyModeReservationsSelection) { + clearTimeout(this._lazyModeReservationsSelection); + this._lazyModeReservationsSelection = false; + } + + this.reservationAction = { + action: HotelCalendar.ACTION.NONE, + reservation: null, + oldReservationObj: null, + newReservationObj: null, + mousePos: false, + inReservations: [], + outReservations: [], + }; + }, + + get_normalized_rooms_: function() { + var rooms = {}; + if (this.options.rooms) { + var keys = Object.keys(this.options.rooms); + + for (var r of this.options.rooms) { + rooms[r.number] = [r.type, r.capacity]; + } + } + return rooms; + }, + + //==== RENDER FUNCTIONS + _create: function() { + var $this = this; + while (this.e.hasChildNodes()) { + this.e.removeChild(this.e.lastChild); + } + + if (this._tableCreated) { + console.warn("[Hotel Calendar][_create] Already created!"); + return false; + } + + var scrollThrottle = _.throttle(this._updateOBIndicators.bind(this), 100); + + // Reservations Table + this.edivrh = document.createElement("div"); + this.edivrh.classList.add('table-reservations-header'); + this.e.appendChild(this.edivrh); + this.etableHeader = document.createElement("table"); + this.etableHeader.classList.add('hcal-table'); + this.etableHeader.classList.add('noselect'); + this.edivrh.appendChild(this.etableHeader); + this.edivr = document.createElement("div"); + this.edivr.classList.add('table-reservations'); + this.e.appendChild(this.edivr); + this.etable = document.createElement("table"); + this.etable.classList.add('hcal-table'); + this.etable.classList.add('noselect'); + this.edivr.appendChild(this.etable); + this.edivr.addEventListener("scroll", scrollThrottle, false); + // Detail Calcs Table + this.edivch = document.createElement("div"); + this.edivch.classList.add('table-calcs-header'); + this.e.appendChild(this.edivch); + this.edtableHeader = document.createElement("table"); + this.edtableHeader.classList.add('hcal-table'); + this.edtableHeader.classList.add('noselect'); + this.edivch.appendChild(this.edtableHeader); + this.edivc = document.createElement("div"); + this.edivc.classList.add('table-calcs'); + this.e.appendChild(this.edivc); + this.edtable = document.createElement("table"); + this.edtable.classList.add('hcal-table'); + this.edtable.classList.add('noselect'); + this.edivc.appendChild(this.edtable); + + var observer = new MutationObserver(function(mutationsList){ + $this._updateOBIndicators(); + }); + observer.observe(this.edivr, { childList: true }); + + this._updateView(); + this._tableCreated = true; + + return true; + }, + + _generateTableDay: function(/*HTMLObject*/parentCell, /*HRoomObject*/room) { + var $this = this; + var table = document.createElement("table"); + table.classList.add('hcal-table-day'); + table.classList.add('noselect'); + var row = false; + var cell = false; + var num = ((room.shared || this.options.divideRoomsByCapacity)?room.capacity:1); + for (var i=0; i${dd_local.format('ddd')}`; + cell.setAttribute('title', dd_local.format('dddd')) + var day = +dd_local.format('D'); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + cur_month = dd_local.format('MMMM'); + months[cur_month] = {}; + months[cur_month].year = dd_local.format('YYYY'); + months[cur_month].colspan = 0; + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + ++months[cur_month].colspan; + } + // Render Months + var month_keys = Object.keys(months); + for (var m of month_keys) { + var cell_month = row_init.insertCell(); + cell_month.setAttribute('colspan', months[m].colspan); + cell_month.innerText = m+' '+months[m].year; + cell_month.classList.add('hcal-cell-month'); + cell_month.classList.add('btn-hcal'); + cell_month.classList.add('btn-hcal-3d'); + } + + /** ROOM LINES **/ + var tbody = document.createElement("tbody"); + this.etable.appendChild(tbody); + for (var itemRoom of this.options.rooms) { + // Room Number + row = tbody.insertRow(); + row.dataset.hcalRoomObjId = itemRoom.id; + row.classList.add('hcal-row-room-type-group-item'); + if (itemRoom.overbooking) { + var reservId = this.parseOBRoomId(itemRoom.id)[0]; + var cnumber = itemRoom.number; + var isf = cnumber.search('OB-'); + var isfb = cnumber.search('/#'); + if (isf != -1 && isfb != -1) { cnumber = cnumber.substr(isf+3, isfb-(isf+3)); } + row.setAttribute('id', this._sanitizeId(`ROW_${cnumber}_${itemRoom.type}_OVER${reservId}`)); + row.classList.add('hcal-row-room-type-group-overbooking-item'); + } else { + row.setAttribute('id', $this._sanitizeId(`ROW_${itemRoom.number}_${itemRoom.type}`)); + } + cell = row.insertCell(); + cell.textContent = itemRoom.number; + cell.classList.add('hcal-cell-room-type-group-item'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-3d'); + cell.setAttribute('colspan', '2'); + cell = row.insertCell(); + cell.textContent = itemRoom.type; + cell.classList.add('hcal-cell-room-type-group-item'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-flat'); + for (var i=0; i<=$this.options.days; i++) { + var dd = $this.options.startDate.clone().local().startOf('day').add(i,'d').utc(); + var dd_local = dd.clone().local(); + cell = row.insertCell(); + cell.setAttribute('id', $this._sanitizeId(`${itemRoom.type}_${itemRoom.number}_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)); + cell.classList.add('hcal-cell-room-type-group-item-day'); + cell.dataset.hcalParentRow = row.getAttribute('id'); + cell.dataset.hcalDate = dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_); + cell.dataset.hcalRoomObjId = itemRoom.id; + // Generate Interactive Table + cell.appendChild($this._generateTableDay(cell, itemRoom)); + //cell.innerHTML = dd.format("DD"); + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + + itemRoom._html = row; + } + + this._filterRooms(); + this._calcViewHeight(); + }, + + _calcViewHeight: function() { + if (this.options.showNumRooms > 0) { + var rows = this.edivr.querySelectorAll('tr.hcal-row-room-type-group-item'); + var cheight = 0.0; + for (var i=0; i${dd_local.format('ddd')}`; + cell.setAttribute('title', dd_local.format("dddd")) + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + + /** DETAIL LINES **/ + var tbody = document.createElement("tbody"); + this.edtable.appendChild(tbody); + if (this.options.showAvailability) { + // Rooms Free Types + if (this.options.rooms) { + var room_types = this.getRoomTypes(); + for (var rt of room_types) { + if (rt || room_types.length > 1) { + row = tbody.insertRow(); + row.setAttribute('id', this._sanitizeId(`ROW_DETAIL_FREE_TYPE_${rt}`)); + row.dataset.hcalRoomType = rt; + row.classList.add('hcal-row-detail-room-free-type-group-item'); + cell = row.insertCell(); + cell.textContent = rt; + cell.classList.add('hcal-cell-detail-room-free-type-group-item'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-flat'); + cell.setAttribute("colspan", "3"); + for (var i=0; i<=this.options.days; i++) { + var dd = this.options.startDate.clone().local().startOf('day').add(i,'d').utc(); + var dd_local = dd.clone().local(); + cell = row.insertCell(); + cell.setAttribute('id', this._sanitizeId(`CELL_FREE_${rt}_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)); + cell.classList.add('hcal-cell-detail-room-free-type-group-item-day'); + cell.dataset.hcalParentRow = row.getAttribute('id'); + cell.dataset.hcalDate = dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_); + cell.textContent = '0'; + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + } + } + } + // Total Free + row = tbody.insertRow(); + row.setAttribute('id', "ROW_DETAIL_TOTAL_FREE"); + row.classList.add('hcal-row-detail-room-free-total-group-item'); + cell = row.insertCell(); + cell.textContent = 'FREE TOTAL'; + cell.classList.add('hcal-cell-detail-room-free-total-group-item'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-flat'); + cell.setAttribute("colspan", "3"); + for (var i=0; i<=this.options.days; i++) { + var dd = this.options.startDate.clone().local().startOf('day').add(i,'d').utc(); + var dd_local = dd.clone().local(); + cell = row.insertCell(); + cell.setAttribute('id', this._sanitizeId(`CELL_DETAIL_TOTAL_FREE_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)); + cell.classList.add('hcal-cell-detail-room-free-total-group-item-day'); + cell.dataset.hcalParentRow = row.getAttribute('id'); + cell.dataset.hcalDate = dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_); + cell.textContent = '0'; + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + // Percentage Occupied + row = tbody.insertRow(); + row.setAttribute('id', "ROW_DETAIL_PERC_OCCUP"); + row.classList.add('hcal-row-detail-room-perc-occup-group-item'); + cell = row.insertCell(); + cell.textContent = '% OCCUP.'; + cell.classList.add('hcal-cell-detail-room-perc-occup-group-item'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-flat'); + cell.setAttribute("colspan", "3"); + for (var i=0; i<=this.options.days; i++) { + var dd = this.options.startDate.clone().local().startOf('day').add(i,'d').utc(); + var dd_local = dd.clone().local(); + cell = row.insertCell(); + cell.setAttribute('id', this._sanitizeId(`CELL_DETAIL_PERC_OCCUP_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)); + cell.classList.add('hcal-cell-detail-room-perc-occup-group-item-day'); + cell.dataset.hcalParentRow = row.getAttribute('id'); + cell.dataset.hcalDate = dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_); + cell.textContent = '0'; + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + } + // Rooms Pricelist + this._pricelist_id = _.keys(this._pricelist)[0]; + if (this.options.showPricelist && this._pricelist) { + //var pricelists_keys = _.keys(this._pricelist) + //for (var key of pricelists_keys) { + var key = this._pricelist_id; + var pricelist = this._pricelist[key]; + for (var listitem of pricelist) { + row = tbody.insertRow(); + row.setAttribute('id', this._sanitizeId(`ROW_DETAIL_PRICE_ROOM_${key}_${listitem.room}`)); + row.dataset.hcalPricelist = key; + row.dataset.hcalVRoomId = listitem.room + row.classList.add('hcal-row-detail-room-price-group-item'); + cell = row.insertCell(); + var span = document.createElement('span'); + cell.title = cell.textContent = listitem.title + ' ' + this.options.currencySymbol; + cell.classList.add('hcal-cell-detail-room-group-item', 'btn-hcal', 'btn-hcal-flat'); + cell.dataset.currencySymbol = this.options.currencySymbol; + cell.setAttribute("colspan", "3"); + for (var i=0; i<=$this.options.days; i++) { + var dd = this.options.startDate.clone().local().startOf('day').add(i,'d').utc(); + var dd_local = dd.clone().local(); + cell = row.insertCell(); + cell.setAttribute('id', this._sanitizeId(`CELL_PRICE_${key}_${listitem.room}_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)); + cell.classList.add('hcal-cell-detail-room-price-group-item-day'); + cell.dataset.hcalParentRow = row.getAttribute('id'); + cell.dataset.hcalDate = dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_); + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + + var input = document.createElement('input'); + input.setAttribute('id', this._sanitizeId(`INPUT_PRICE_${key}_${listitem.room}_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)); + input.setAttribute('type', 'edit'); + input.setAttribute('title', 'Price'); + input.setAttribute('name', 'vroom_price_day'); + input.dataset.hcalParentCell = cell.getAttribute('id'); + var dd_fmrt = dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_); + input.dataset.orgValue = input.value = _.has(listitem['days'], dd_fmrt)?Number(listitem['days'][dd_fmrt]).toLocaleString():'...'; + input.addEventListener('change', function(ev){ $this._onInputChange(ev, this); }, false); + cell.appendChild(input); + } + } + //} + } + }, + + //==== PRICELISTS + getPricelist: function(onlyNew) { + var data = {}; + + var key = this._pricelist_id; + var pricelist = this._pricelist[key]; + for (var listitem of pricelist) { + for (var i=0; i<=this.options.days; ++i) { + var dd = this.options.startDate.clone().local().startOf('day').add(i,'d').utc(); + var dd_local = dd.clone().local(); + + var input = this.edtable.querySelector(`#${this._sanitizeId(`INPUT_PRICE_${key}_${listitem.room}_${dd_local.format(HotelCalendar.DATE_FORMAT_SHORT_)}`)}`); + if (input.value !== input.dataset.orgValue) { + var value = input.value; + var orgValue = input.dataset.orgValue; + var parentCell = this.edtable.querySelector(`#${input.dataset.hcalParentCell}`); + var parentRow = this.edtable.querySelector(`#${parentCell.dataset.hcalParentRow}`); + if (!(parentRow.dataset.hcalVRoomId in data)) { data[parentRow.dataset.hcalVRoomId] = []; } + data[parentRow.dataset.hcalVRoomId].push({ + 'date': HotelCalendar.toMoment(parentCell.dataset.hcalDate).format('YYYY-MM-DD'), + 'price': value + }); + } + } + } + + return data; + }, + + //==== UPDATE FUNCTIONS + _updateView: function(/*Bool*/notData, /*function*/callback) { + this._createTableReservationDays(); + if (typeof callback !== 'undefined') { + callback(); + } + this._updateCellSelection(); + this._createTableDetailDays(); + + _.defer(function(){ + this._updateReservations(true); + }.bind(this)); + if (!notData) { + _.defer(function(){ + this._updateRestrictions(); + this._updatePriceList(); + this._updateReservationOccupation(); + }.bind(this)); + } + }, + + _updateOBIndicators: function() { + var mainBounds = this.edivr.getBoundingClientRect(); + for (var reserv of this._reservations) { + if (reserv.overbooking && reserv._html) { + var eOffset = this.e.getBoundingClientRect(); + var bounds = reserv._html.getBoundingClientRect(); + if (bounds.top > mainBounds.bottom) { + var warnDiv = this.e.querySelector(`div.hcal-warn-ob-indicator[data-hcal-reservation-obj-id='${reserv.id}']`); + if (!warnDiv) { + var warnDiv = document.createElement("DIV"); + warnDiv.innerHTML = ""; + warnDiv.classList.add('hcal-warn-ob-indicator'); + warnDiv.style.borderTopLeftRadius = warnDiv.style.borderTopRightRadius = "50px"; + warnDiv.dataset.hcalReservationObjId = reserv.id; + this.e.appendChild(warnDiv); + var warnComputedStyle = window.getComputedStyle(warnDiv, null); + warnDiv.style.top = `${mainBounds.bottom - eOffset.top - parseInt(warnComputedStyle.getPropertyValue("height"), 10)}px`; + warnDiv.style.left = `${(bounds.left + (bounds.right - bounds.left)/2.0 - parseInt(warnComputedStyle.getPropertyValue("width"), 10)/2.0) - mainBounds.left}px`; + } + } else if (bounds.bottom < mainBounds.top) { + var warnDiv = this.e.querySelector(`div.hcal-warn-ob-indicator[data-hcal-reservation-obj-id='${reserv.id}']`); + if (!warnDiv) { + var warnDiv = document.createElement("DIV"); + warnDiv.innerHTML = ""; + warnDiv.classList.add('hcal-warn-ob-indicator'); + warnDiv.style.borderBottomLeftRadius = warnDiv.style.borderBottomRightRadius = "50px"; + warnDiv.style.top = `${mainBounds.top - eOffset.top}px`; + warnDiv.dataset.hcalReservationObjId = reserv.id; + this.e.appendChild(warnDiv); + var warnComputedStyle = window.getComputedStyle(warnDiv, null); + warnDiv.style.left = `${(bounds.left + (bounds.right - bounds.left)/2.0 - parseInt(warnComputedStyle.getPropertyValue("width"), 10)/2.0) - mainBounds.left}px`; + } + } else { + var warnDiv = this.e.querySelector(`div.hcal-warn-ob-indicator[data-hcal-reservation-obj-id='${reserv.id}']`); + if (warnDiv) { + warnDiv.parentNode.removeChild(warnDiv); + } + } + } + } + }, + + _updateHighlightSwapReservations: function() { + var $this = this; + if (this.reservationAction.inReservations.length === 0 && this.reservationAction.outReservations.length === 0) { + var elms = this.e.querySelectorAll("div.hcal-reservation-invalid-swap"); + for (var elm of elms) { elm.classList.remove('hcal-reservation-invalid-swap'); } + elms = this.e.querySelectorAll("div.hcal-reservation-swap-in-selected"); + for (var elm of elms) { elm.classList.remove('hcal-reservation-swap-in-selected'); } + elms = this.e.querySelectorAll("div.hcal-reservation-swap-out-selected"); + for (var elm of elms) { elm.classList.remove('hcal-reservation-swap-out-selected'); } + } + else { + var dateLimits = this.getDateLimits(this.reservationAction.inReservations); + var refInReservation = this.reservationAction.inReservations[0]; + var refOutReservation = this.reservationAction.outReservations[0]; + var inCapacity = refInReservation?refInReservation.room.capacity:false; + var outCapacity = refOutReservation?refOutReservation.room.capacity:false; + var realDateLimits = this.getFreeDatesByRoom(dateLimits[0], dateLimits[1], refInReservation?refInReservation.room.id:refOutReservation.room.id); + for (var nreserv of this._reservations) { + if (nreserv._html.classList.contains('hcal-reservation-swap-in-selected') || nreserv._html.classList.contains('hcal-reservation-swap-out-selected')) { + continue; + } + + // Invalid capacity + var totalReservPerson = nreserv.getTotalPersons(false); + if (totalReservPerson > inCapacity || (outCapacity && totalReservPerson > outCapacity) || nreserv.room.capacity < refInReservation.getTotalPersons(false)) + { + nreserv._html.classList.add('hcal-reservation-invalid-swap'); + } + else if (this._modeSwap === HotelCalendar.MODE.SWAP_FROM && this.reservationAction.inReservations.length !== 0 && refInReservation.room.id !== nreserv.room.id) { + if (!_.find(this.reservationAction.outReservations, {'id': nreserv.linkedId})) { + nreserv._html.classList.add('hcal-reservation-invalid-swap'); + } + } else if (this._modeSwap === HotelCalendar.MODE.SWAP_TO && this.reservationAction.outReservations.length !== 0 && refOutReservation.room.id !== nreserv.room.id) { + if (!_.find(this.reservationAction.inReservations, {'id': nreserv.linkedId})) { + nreserv._html.classList.add('hcal-reservation-invalid-swap'); + } + } + // Invalid reservations out of dates + else if (nreserv.startDate.isBefore(realDateLimits[0], 'day') || nreserv.endDate.isAfter(realDateLimits[1], 'day')) { + if (nreserv.room.id !== refInReservation.room.id) { + nreserv._html.classList.add('hcal-reservation-invalid-swap'); + } + } + else { + // var reservs = this.getReservationsByRoom(nreserv.room, false); + // var hasInvalidReservs = false; + // for (var r of reservs) { + // if (r._html.classList.contains('hcal-reservation-invalid-swap') && nreserv.startDate.isSameOrAfter(realDateLimits[0], 'day') && nreserv.endDate.isSameOrBefore(realDateLimits[1], 'day')) { + // hasInvalidReservs = true; + // break; + // } + // } + // var nrealDateLimits = this.getFreeDatesByRoom(nreserv.startDate, nreserv.endDate, nreserv.room.number); + // if (hasInvalidReservs && (nrealDateLimits[0].isAfter(realDateLimits[0], 'day') || nrealDateLimits[1].isBefore(realDateLimits[1], 'day'))) { + // if (nreserv.room.id !== refInReservation.room.id) { + // nreserv._html.classList.add('hcal-reservation-invalid-swap'); + // } + // } + // // Is a valid reservation + // else + // { + nreserv._html.classList.remove('hcal-reservation-invalid-swap'); + // } + } + } + } + }, + + _updateHighlightInvalidZones: function(/*HReservation*/reserv) { + if (typeof reserv === 'undefined') { + var elms = this.etable.querySelectorAll("td[data-hcal-date] table td"); + for (var tdCell of elms) { + tdCell.classList.remove('hcal-cell-invalid'); + } + return; + } + + if (reserv.readOnly) { + var elms = this.etable.querySelectorAll("td[data-hcal-date] table td"); + for (var tdCell of elms) { + tdCell.classList.add('hcal-cell-invalid'); + } + } else if (reserv.fixDays) { + var limitLeftDate = this.etable.querySelector(`#${reserv._limits.left.dataset.hcalParentCell}`).dataset.hcalDate; + var limitRightDate = this.etable.querySelector(`#${reserv._limits.right.dataset.hcalParentCell}`).dataset.hcalDate; + var limitLeftDateMoment = HotelCalendar.toMoment(limitLeftDate); + var limitRightDateMoment = HotelCalendar.toMoment(limitRightDate); + var diff_date = this.getDateDiffDays(limitLeftDateMoment, limitRightDateMoment); + var date = limitLeftDateMoment.clone().startOf('day'); + var selector = []; + for (var i=0; i<=diff_date; i++) { + selector.push("not([data-hcal-date='"+date.format(HotelCalendar.DATE_FORMAT_SHORT_)+"'])"); + date.add(1, 'd'); + } + if (selector.length) { + var elms = this.etable.querySelectorAll(`td:${selector.join(':')}`+ ' table td'); + for (var tdCell of elms) { + tdCell.classList.add('hcal-cell-invalid'); + } + } + } else if (reserv.fixRooms) { + var parentCell = this.etable.querySelector(`#${reserv._limits.left.dataset.hcalParentCell}`); + var parent_row = parentCell.dataset.hcalParentRow; + var elms = this.etable.querySelectorAll("td:not([data-hcal-parent-row='"+parent_row+"']) table td"); + for (var tdCell of elms) { + tdCell.classList.add('hcal-cell-invalid'); + } + } else { + var limitLeftDate = this.etable.querySelector(`#${reserv._limits.left.dataset.hcalParentCell}`).dataset.hcalDate; + var limitRightDate = this.etable.querySelector(`#${reserv._limits.right.dataset.hcalParentCell}`).dataset.hcalDate; + var limitLeftDateMoment = HotelCalendar.toMoment(limitLeftDate); + var limitRightDateMoment = HotelCalendar.toMoment(limitRightDate); + var diff_date = this.getDateDiffDays(limitLeftDateMoment, limitRightDateMoment); + var date = limitLeftDateMoment.clone().startOf('day'); + var selector = []; + for (var i=0; i<=diff_date; i++) { + selector.push("td[data-hcal-date='"+date.format(HotelCalendar.DATE_FORMAT_SHORT_)+"'] table td"); + date.add(1, 'd'); + } + if (selector.length) { + var elms = this.etable.querySelectorAll(`${selector.join(', ')}`); + for (var tdCell of elms) { + tdCell.classList.add('hcal-cell-highlight'); + } + } + } + }, + + _updateScroll: function(/*HTMLObject*/reservationDiv) { + var reservBounds = reservationDiv.getBoundingClientRect(); + var mainBounds = this.edivr.getBoundingClientRect(); + var eOffset = this.e.getBoundingClientRect(); + var bottom = mainBounds.bottom - eOffset.top; + var top = mainBounds.top + eOffset.top; + var offset = 10.0; + var scrollDisp = 10.0; + if (reservBounds.bottom >= bottom-offset) { + this.edivr.scrollBy(0, scrollDisp); + } + else if (reservBounds.top <= top+offset) { + this.edivr.scrollBy(0, -scrollDisp); + } + }, + + //==== SELECTION + _updateCellSelection: function() { + // Clear all + var highlighted_td = this.etable.querySelectorAll('td.hcal-cell-highlight'); + for (var td of highlighted_td) { + td.classList.remove('hcal-cell-highlight'); + td.textContent = ''; + } + + // Highlight Selected + if (this._cellSelection.current) { + this._cellSelection.current.classList.add('hcal-cell-highlight'); + } + // Highlight Range Cells + var cells = false; + var total_price = 0.0; + var limits = new HLimit(this._cellSelection.start, + this._cellSelection.end?this._cellSelection.end:this._cellSelection.current); + if (limits.isValid()) { + // Normalize + // TODO: Multi-Directional Selection. Now only support normal or inverse. + var limitLeftDate = HotelCalendar.toMoment(this.etable.querySelector(`#${limits.left.dataset.hcalParentCell}`).dataset.hcalDate); + var limitRightDate = HotelCalendar.toMoment(this.etable.querySelector(`#${limits.right.dataset.hcalParentCell}`).dataset.hcalDate); + if (limitLeftDate.isAfter(limitRightDate)) { + limits.swap(); + } + cells = this.getCells(limits); + for (var c of cells) { + var parentRow = this.$base.querySelector(`#${c.dataset.hcalParentRow}`); + var room = this.getRoom(parentRow.dataset.hcalRoomObjId); + if (room.overbooking) { + continue; + } + c.classList.add('hcal-cell-highlight'); + if (this._pricelist) { + // FIXME: Normalize data calendar (gmt) vs extra info (utc) + var date_cell = HotelCalendar.toMoment(this.etable.querySelector(`#${c.dataset.hcalParentCell}`).dataset.hcalDate); + var room_price = this.getRoomPrice(parentRow.dataset.hcalRoomObjId, date_cell); + if (c === cells[0] || !date_cell.isSame(limitRightDate, 'day')) { + c.textContent = room_price + ' ' + this.options.currencySymbol; + if (!room.shared && c.dataset.hcalBedNum > limits.left.dataset.hcalBedNum) { + c.style.color = 'lightgray'; + } + else { + c.style.color = 'black'; + total_price += room_price; + } + } + } + } + } + + this._dispatchEvent( + 'hcalOnUpdateSelection', + { + 'limits': limits, + 'cells': cells, + 'old_cells': highlighted_td, + 'totalPrice': total_price + }); + }, + + _resetCellSelection: function() { + this._cellSelection = { current: false, end: false, start: false }; + }, + + //==== RESERVATIONS + _updateDivReservation: function(/*HReservationObject*/reserv, /*Bool?*/noRefresh) { + if (!reserv._limits.isValid() || !reserv._html) { + return; + } + + if (reserv.readOnly) { + reserv._html.classList.add('hcal-reservation-readonly'); + } else { + reserv._html.classList.remove('hcal-reservation-readonly'); + } + + if (reserv.room._active) { + reserv._html.classList.remove('hcal-hidden'); + } else { + reserv._html.classList.add('hcal-hidden'); + } + + if (reserv._active) { + reserv._html.classList.remove('hcal-reservation-unselect'); + } else { + reserv._html.classList.add('hcal-reservation-unselect'); + } + + if (!noRefresh) { + var numBeds = (+reserv._limits.right.dataset.hcalBedNum)-(+reserv._limits.left.dataset.hcalBedNum); + reserv._beds = []; + for (var i=0; i<=numBeds; reserv._beds.push(+reserv._limits.left.dataset.hcalBedNum+i++)); + + var boundsInit = reserv._limits.left.getBoundingClientRect(); + var boundsEnd = reserv._limits.right.getBoundingClientRect(); + + reserv._html.removeAttribute('style'); + + if (reserv.splitted) { + reserv._html.classList.add('hcal-reservation-splitted'); + var magicNumber = Math.floor(Math.abs(Math.sin((reserv.getUserData('parent_reservation') || reserv.id))) * 100000); + var bbColor = this._intToRgb(magicNumber); + reserv._html.style.borderColor = `rgb(${bbColor[0]},${bbColor[1]},${bbColor[2]})`; + } else { + reserv._html.classList.remove('hcal-reservation-splitted'); + } + reserv._html.style.backgroundColor = reserv.color; + reserv._html.style.color = reserv.colorText; + + var etableOffset = this.etable.getBoundingClientRect(); + + reserv._html.style.top = `${boundsInit.top-etableOffset.top}px`; + var divHeight = (boundsEnd.bottom-etableOffset.top)-(boundsInit.top-etableOffset.top); + reserv._html.style.height = `${divHeight}px`; + reserv._html.style.lineHeight = `${divHeight}px`; + var fontHeight = divHeight/1.3; + if (fontHeight > 16) { + fontHeight = 16; + } + reserv._html.style.fontSize = `${fontHeight}px`; + + var clearBorderLeft = function(/*HTMLObject*/elm) { + elm.style.borderLeftWidth = '0'; + elm.style.borderTopLeftRadius = '0'; + elm.style.borderBottomLeftRadius = '0'; + }; + var clearBorderRight = function(/*HTMLObject*/elm) { + elm.style.borderRightWidth = '0'; + elm.style.borderTopRightRadius = '0'; + elm.style.borderBottomRightRadius = '0'; + }; + + if (reserv._drawModes[0] === 'soft-start' && reserv._drawModes[1] === 'soft-end') { + clearBorderLeft(reserv._html); + clearBorderRight(reserv._html); + reserv._html.style.left = `${boundsInit.left-etableOffset.left}px`; + reserv._html.style.width = `${(boundsEnd.left-boundsInit.left)+boundsEnd.width}px`; + } else if (reserv._drawModes[0] === 'soft-start') { + clearBorderLeft(reserv._html); + reserv._html.style.left = `${boundsInit.left-etableOffset.left}px`; + reserv._html.style.width = `${(boundsEnd.left-boundsInit.left)+boundsEnd.width/2.0}px`; + } else if (reserv._drawModes[1] === 'soft-end') { + clearBorderRight(reserv._html); + reserv._html.style.left = `${boundsInit.left-etableOffset.left+boundsInit.width/2.0}px`; + reserv._html.style.width = `${(boundsEnd.left-boundsInit.left)+boundsEnd.width}px`; + } else { + reserv._html.style.left = `${(boundsInit.left-etableOffset.left)+boundsEnd.width/2.0}px`; + reserv._html.style.width = `${(boundsEnd.left-boundsInit.left)}px`; + } + } + }, + + swapReservations: function(/*List HReservationObject*/fromReservations, /*List HReservationObject*/toReservations) { + if (fromReservations.length === 0 || toReservations.length === 0) { + console.warn("[HotelCalendar][swapReservations] Invalid Swap Operation!"); + return false; + } + var fromDateLimits = this.getDateLimits(fromReservations); + var fromRealDateLimits = this.getFreeDatesByRoom(fromDateLimits[0], fromDateLimits[1], fromReservations[0].room.id); + var toDateLimits = this.getDateLimits(toReservations); + var toRealDateLimits = this.getFreeDatesByRoom(toDateLimits[0], toDateLimits[1], toReservations[0].room.id); + + if (fromDateLimits[0].clone().local().isSameOrAfter(toRealDateLimits[0].clone().local(), 'd') && fromDateLimits[1].clone().local().isSameOrBefore(toRealDateLimits[1].clone().local(), 'd') && + toDateLimits[0].clone().local().isSameOrAfter(fromRealDateLimits[0].clone().local(), 'd') && toDateLimits[1].clone().local().isSameOrBefore(fromRealDateLimits[1].clone().local(), 'd')) + { + // Change some critical values + var refFromReservs = fromReservations[0]; + var refToReservs = toReservations[0]; + var refFromRoom = refFromReservs.room; + var refToRoom = refToReservs.room; + var fromRoomRow = this.getOBRoomRow(refFromReservs); + var toRoomRow = this.getOBRoomRow(refToReservs); + var refFromRoomNewId = refFromRoom.overbooking?this.parseOBRoomId(refFromRoom.id)[1]:refFromRoom.id; + refFromRoomNewId = `${refToReservs.id}@${refFromRoomNewId}`; + var refToRoomNewId = refToRoom.overbooking?this.parseOBRoomId(refToRoom.id)[1]:refToRoom.id; + refToRoomNewId = `${refFromReservs.id}@${refToRoomNewId}`; + + if (refFromRoom.overbooking) { + // Obtain real id + var isf = refFromReservs.room.number.search('OB-'); + var isfb = refFromReservs.room.number.search('/#'); + var cnumber = refFromReservs.room.number; + if (isf != -1 && isfb != -1) { cnumber = cnumber.substr(isf+3, isfb-(isf+3)); } + + refFromRoom.id = refFromRoomNewId; + var newRowId = `${this._sanitizeId(`ROW_${cnumber}_${refToRoom.type}_OVER${refToReservs.id}`)}`; + var elms = fromRoomRow.querySelectorAll(`td[data-hcal-parent-row='${fromRoomRow.id}']`); + for (var elm of elms) { elm.dataset.hcalParentRow = newRowId; } + fromRoomRow.setAttribute('id', `${newRowId}`); + fromRoomRow.dataset.hcalRoomObjId = refFromRoom.id; + } + if (refToRoom.overbooking) { + // Obtain real id + var isf = refToReservs.room.number.search('OB-'); + var isfb = refToReservs.room.number.search('/#'); + var cnumber = refToReservs.room.number; + if (isf != -1 && isfb != -1) { cnumber = cnumber.substr(isf+3, isfb-(isf+3)); } + + refToRoom.id = refToRoomNewId; + var newRowId = `${this._sanitizeId(`ROW_${cnumber}_${refFromRoom.type}_OVER${refFromReservs.id}`)}`; + var elms = toRoomRow.querySelectorAll(`td[data-hcal-parent-row='${toRoomRow.id}']`); + for (var elm of elms) { elm.dataset.hcalParentRow = newRowId; } + toRoomRow.setAttribute('id', `${newRowId}`); + toRoomRow.dataset.hcalRoomObjId = refToRoom.id; + } + + for (var nreserv of fromReservations) { + nreserv.overbooking = refToRoom.overbooking; + nreserv.room = refToRoom; + } + for (var nreserv of toReservations) { + nreserv.overbooking = refToRoom.overbooking; + nreserv.room = refFromRoom; + } + + if (this.options.divideRoomsByCapacity) { + var allReservs = toReservations.concat(fromReservations); + for (var nreserv of allReservs) { this._updateUnusedZones(nreserv); } + } + } else { + console.warn("[HotelCalendar][swapReservations] Invalid Swap Operation!"); + return false; + } + + return true; + }, + + _dispatchSwapReservations: function() { + if (this.reservationAction.inReservations.length > 0 && this.reservationAction.outReservations.length > 0) { + this._dispatchEvent( + 'hcalOnSwapReservations', + { + 'inReservs': this.reservationAction.inReservations || [], + 'outReservs': this.reservationAction.outReservations || [], + } + ); + } + }, + + replaceReservation: function(/*HReservationObject*/reservationObj, /*HReservationObject*/newReservationObj) { + if (!reservationObj._html) { + console.warn("[Hotel Calendar][updateReservation_] Invalid Reservation Object"); + return; + } + + var index = _.findKey(this._reservations, {'id': reservationObj.id}); + delete this._reservations[index]; + this._reservations[index] = newReservationObj; + reservationObj._html.dataset.hcalReservationObjId = newReservationObj.id; + this._updateReservationsMap(); + this._updateDivReservation(newReservationObj); + + var linkedReservations = this.getLinkedReservations(newReservationObj); + for (var lr of linkedReservations) { + lr.startDate = newReservationObj.startDate.clone(); + lr.endDate = newReservationObj.endDate.clone(); + + if (lr._html) { + this._calcReservationCellLimits(lr); + this._updateDivReservation(lr); + } + } + _.defer(function(){ this._updateReservationOccupation(); }.bind(this)); + }, + + getLinkedReservations: function(/*HReservationObject*/reservationObj) { + return _.reject(this._reservations, function(item){ return item === reservationObj || item.linkedId !== reservationObj.id; }); + }, + + _updateReservation: function(/*HReservationObject*/reservationObj, /*Bool?*/noRefresh) { + // Fill + if (reservationObj._limits.isValid()) { + this._updateDivReservation(reservationObj, noRefresh); + } else { + console.warn(`[Hotel Calendar][_updateReservation] Can't place reservation ID@${reservationObj.id} [${reservationObj.startDate.format(HotelCalendar.DATE_FORMAT_LONG_)} --> ${reservationObj.endDate.format(HotelCalendar.DATE_FORMAT_LONG_)}]`); + this.removeReservation(reservationObj); + } + }, + + _updateReservations: function(/*Bool*/updateLimits) { + for (var reservation of this._reservations){ + if (updateLimits) { + this._calcReservationCellLimits(reservation); + } + this._updateReservation(reservation); + } + //this._assignReservationsEvents(); + //this._updateReservationOccupation(); + this._updateOBIndicators(); + }, + + _assignReservationsEvents: function(reservDivs) { + var $this = this; + reservDivs = reservDivs || this.e.querySelectorAll('div.hcal-reservation'); + for (var rdiv of reservDivs) { + var bounds = rdiv.getBoundingClientRect(); + rdiv.addEventListener('mousemove', function(ev){ + var posAction = $this._getRerservationPositionAction(this, ev.layerX, ev.layerY); + this.style.cursor = (posAction == HotelCalendar.ACTION.MOVE_LEFT || posAction == HotelCalendar.ACTION.MOVE_RIGHT)?'col-resize':'pointer'; + }, false); + var _funcEvent = function(ev){ + if ($this._isLeftButtonPressed(ev)) { + if (ev.ctrlKey || $this._modeSwap === HotelCalendar.MODE.SWAP_FROM) { + $this.reservationAction.action = HotelCalendar.ACTION.SWAP; + $this.setSwapMode(HotelCalendar.MODE.SWAP_FROM); + } + // MODE SWAP RESERVATIONS + if ($this.reservationAction.action === HotelCalendar.ACTION.SWAP) { + var reserv = $this.getReservation(this.dataset.hcalReservationObjId); + var refFromReserv = ($this.reservationAction.inReservations.length > 0)?$this.reservationAction.inReservations[0]:false; + var refToReserv = ($this.reservationAction.outReservations.length > 0)?$this.reservationAction.outReservations[0]:false; + + if (ev.ctrlKey || $this._modeSwap === HotelCalendar.MODE.SWAP_FROM) { + var canAdd = !((!refFromReserv && refToReserv && reserv.room.id === refToReserv.room.id) || (refFromReserv && reserv.room.id !== refFromReserv.room.id)); + // Can unselect + if ($this.reservationAction.inReservations.indexOf(reserv) != -1 && (($this.reservationAction.outReservations.length > 0 && $this.reservationAction.inReservations.length > 1) || $this.reservationAction.outReservations.length === 0)) { + $this.reservationAction.inReservations = _.reject($this.reservationAction.inReservations, function(item){ return item === reserv}); + this.classList.remove('hcal-reservation-swap-in-selected'); + } + // Can't add a 'out' reservation in 'in' list + else if ($this.reservationAction.outReservations.indexOf(reserv) == -1 && canAdd) { + $this.reservationAction.inReservations.push(reserv); + this.classList.add('hcal-reservation-swap-in-selected'); + } + } else if (!ev.ctrlKey || $this._modeSwap === HotelCalendar.MODE.SWAP_TO) { + $this.setSwapMode(HotelCalendar.MODE.SWAP_TO); + var canAdd = !((!refToReserv && refFromReserv && reserv.room.id === refFromReserv.room.id) || (refToReserv && reserv.room.id !== refToReserv.room.id)); + // Can unselect + if ($this.reservationAction.outReservations.indexOf(reserv) != -1) { + $this.reservationAction.outReservations = _.reject($this.reservationAction.outReservations, function(item){ return item === reserv; }); + this.classList.remove('hcal-reservation-swap-out-selected'); + } + // Can't add a 'in' reservation in 'out' list + else if ($this.reservationAction.inReservations.indexOf(reserv) == -1 && canAdd) { + $this.reservationAction.outReservations.push(reserv); + this.classList.add('hcal-reservation-swap-out-selected'); + } + } + $this._updateHighlightSwapReservations(); + } + // MODE RESIZE/MOVE RESERVATION + else if (!$this.reservationAction.reservation) { + $this.reservationAction = { + reservation: this, + mousePos: [ev.x, ev.y], + action: $this._getRerservationPositionAction(this, ev.layerX, ev.layerY), + inReservations: [], + outReservations: [], + }; + + // FIXME: Workaround for lazy selection operation + if ($this._lazyModeReservationsSelection) { + clearTimeout($this._lazyModeReservationsSelection); + $this._lazyModeReservationsSelection = false; + } + + $this._lazyModeReservationsSelection = setTimeout(function($this){ + var reserv = $this.getReservation(this.dataset.hcalReservationObjId); + $this._updateHighlightInvalidZones(reserv); + if (reserv.readOnly || (reserv.fixDays && ($this.reservationAction.action == HotelCalendar.ACTION.MOVE_LEFT || + $this.reservationAction.action == HotelCalendar.ACTION.MOVE_RIGHT))) { + $this.reservationAction.action = HotelCalendar.ACTION.NONE; + return false; + } + var affectedReservations = [reserv].concat($this.getLinkedReservations(reserv)); + for (var areserv of affectedReservations) { + if (areserv._html) { + areserv._html.classList.add('hcal-reservation-action'); + } + } + + var otherReservs = _.difference($this._reservations, affectedReservations); + for (var oreserv of otherReservs) { + if (oreserv._html) { + oreserv._html.classList.add('hcal-reservation-foreground'); + } + } + + $this._lazyModeReservationsSelection = false; + }.bind(this, $this), 100); + } + } + }; + rdiv.addEventListener('mousedown', _funcEvent, false); + rdiv.addEventListener('touchstart', _funcEvent, false); + rdiv.addEventListener('mouseenter', function(ev){ + $this._dispatchEvent( + 'hcalOnMouseEnterReservation', + { + 'event': ev, + 'reservationDiv': this, + 'reservationObj': $this.getReservation(this.dataset.hcalReservationObjId) + }); + }, false); + rdiv.addEventListener('mouseleave', function(ev){ + $this._dispatchEvent( + 'hcalOnMouseLeaveReservation', + { + 'event': ev, + 'reservationDiv': this, + 'reservationObj': $this.getReservation(this.dataset.hcalReservationObjId) + }); + }, false); + } + }, + + _getRerservationPositionAction: function(/*HTMLObject*/elm, /*Int*/posX, /*Int*/posY) { + var bounds = elm.getBoundingClientRect(); + if (posX <= 5) { return HotelCalendar.ACTION.MOVE_LEFT; } + else if (posX >= bounds.width-10) { return HotelCalendar.ACTION.MOVE_RIGHT; } + return HotelCalendar.ACTION.MOVE_ALL; + }, + + // _getRerservationPositionAction: function(/*HTMLObject*/elm, /*Int*/posX, /*Int*/posY) { + // var bounds = elm.getBoundingClientRect(); + // var mouseActMargin = 10*bounds.width*0.01; + // console.log("------- Esta aiki"); + // console.log(posX); + // var ppOsX = posX - posX*(1.0-window.devicePixelRatio); + // posX -= ppOsX; + // console.log(posX); + // var mouseActMarginV = (10*bounds.width)/100; + // //debugger; + // if (posX <= mouseActMargin) { return HotelCalendar.ACTION.MOVE_LEFT; } + // else if (posX >= bounds.width-mouseActMargin) { return HotelCalendar.ACTION.MOVE_RIGHT; } + // return HotelCalendar.ACTION.MOVE_ALL; + // }, + + _cleanUnusedZones: function(/*HReservationObject*/reserv) { + var reservs = _.filter(this._reservations, function(item){ return item.unusedZone && item.linkedId === reserv.id; }); + for (var creserv of reservs) { this.removeReservation(creserv); } + }, + + _createUnusedZones: function(/*Array*/reservs) { + var nreservs = []; + for (var reserv of reservs) { + if (!reserv.unusedZone) { + var unused_id = 0; + var numBeds = reserv.getTotalPersons(false); + for (var e=numBeds; e reservationObj.room.capacity)) { + return false; + } + + if (reservationObj.room.id in this._reservationsMap) { + for (var r of this._reservationsMap[reservationObj.room.id]) { + if (!r.unusedZone && r !== reservationObj && reservationObj.room.number == r.room.number && + (_.difference(reservationObj._beds, r._beds).length != reservationObj._beds.length || this.options.divideRoomsByCapacity) && + (r.startDate.isBetween(reservationObj.startDate, reservationObj.endDate, 'day', '[)') || + r.endDate.isBetween(reservationObj.startDate, reservationObj.endDate, 'day', '(]') || + (reservationObj.startDate.isSameOrAfter(r.startDate, 'day') && reservationObj.endDate.isSameOrBefore(r.endDate, 'day')))) { + return false; + } + } + } + + return true; + }, + + //==== EVENT FUNCTIONS + _onInputChange: function(/*EventObject*/ev, /*HTMLObject*/elm) { + //var parentCell = this.edtable.querySelector(`#${elm.dataset.hcalParentCell}`); + //var parentRow = this.edtable.querySelector(`#${parentCell.dataset.hcalParentRow}`); + var value = elm.value; + var orgValue = elm.dataset.orgValue; + var name = elm.getAttribute('name'); + + if (name === 'vroom_price_day') { + if (!this._isNumeric(value)) { + elm.style.backgroundColor = 'red'; + } else if (orgValue !== value) { + elm.classList.add('hcal-input-changed'); + elm.style.backgroundColor = ''; + } else { + elm.classList.remove('hcal-input-changed'); + if (value == 0) { + elm.style.backgroundColor = 'rgb(255, 174, 174)'; + } + } + } + + var parentCell = this.edtable.querySelector(`#${elm.dataset.hcalParentCell}`); + var parentRow = this.edtable.querySelector(`#${parentCell.dataset.hcalParentRow}`); + var vals = { + 'vroom_id': +parentRow.dataset.hcalVRoomId, + 'date': HotelCalendar.toMoment(parentCell.dataset.hcalDate), + 'price': value, + 'old_price': orgValue, + 'pricelist_id': +parentRow.dataset.hcalPricelist + }; + //this.updateVRoomPrice(vals['pricelist_id'], vals['vroom_id'], vals['date'], vals['price']); + this._dispatchEvent('hcalOnPricelistChanged', vals); + + if (this.edivc.querySelector('.hcal-input-changed') !== null) + { + this.btnSaveChanges.classList.add('need-save'); + } else { + this.btnSaveChanges.classList.remove('need-save'); + } + }, + + _onCellMouseUp: function(ev) { + if (this._cellSelection.start && + this._cellSelection.start != ev.target && + this._cellSelection.start.dataset.hcalParentRow === ev.target.dataset.hcalParentRow) { + this._cellSelection.end = ev.target; + + this._dispatchEvent( + 'hcalOnChangeSelection', + { + 'cellStart': this._cellSelection.start, + 'cellEnd': this._cellSelection.end + }); + } + }, + + _onCellMouseDown: function(ev) { + this._cellSelection.start = this._cellSelection.current = ev.target; + this._cellSelection.end = false; + this._updateCellSelection(); + }, + + _onCellMouseEnter: function(ev) { + var date_cell = HotelCalendar.toMoment(this.etable.querySelector(`#${ev.target.dataset.hcalParentCell}`).dataset.hcalDate); + var reserv; + if (this.reservationAction.reservation) { + var reserv = this.getReservation(this.reservationAction.reservation.dataset.hcalReservationObjId); + if (!this.reservationAction.oldReservationObj) { + this.reservationAction.oldReservationObj = reserv.clone(); + this.reservationAction.daysOffset = this.getDateDiffDays(reserv.startDate.clone().local(), date_cell); + if (this.reservationAction.daysOffset < 0 ) { + this.reservationAction.daysOffset = 0; + } + } + } + if (this._isLeftButtonPressed(ev)) { + var toRoom = undefined; + var needUpdate = false; + if (!this.reservationAction.reservation) { + if (this._cellSelection.start && this._cellSelection.start.dataset.hcalParentRow === ev.target.dataset.hcalParentRow) { + this._cellSelection.current = ev.target; + } + this._updateCellSelection(); + } else if (this.reservationAction.mousePos) { + // workarround for not trigger reservation change + var a = this.reservationAction.mousePos[0] - ev.x; + var b = this.reservationAction.mousePos[1] - ev.y; + //var dist = Math.sqrt(a*a + b*b); + if (this.reservationAction.action == HotelCalendar.ACTION.MOVE_RIGHT) { + if (reserv.fixDays) { + this._reset_action_reservation(); + return true; + } + if (!date_cell.isAfter(reserv.startDate, 'd')) { + date_cell = reserv.startDate.clone().startOf('day').add(1, 'd'); + } + if (!this.reservationAction.oldReservationObj) { + this.reservationAction.oldReservationObj = reserv.clone(); + } + reserv.endDate.set({'date': date_cell.date(), 'month': date_cell.month(), 'year': date_cell.year()}); + this.reservationAction.newReservationObj = reserv; + needUpdate = true; + } else if (this.reservationAction.action == HotelCalendar.ACTION.MOVE_LEFT) { + if (reserv.fixDays) { + this._reset_action_reservation(); + return true; + } + var ndate = reserv.endDate.clone().endOf('day').subtract(1, 'd'); + if (!date_cell.isBefore(ndate, 'd')) { + date_cell = ndate; + } + if (!this.reservationAction.oldReservationObj) { + this.reservationAction.oldReservationObj = reserv.clone(); + } + reserv.startDate.set({'date': date_cell.date(), 'month': date_cell.month(), 'year': date_cell.year()}); + this.reservationAction.newReservationObj = reserv; + needUpdate = true; + } else if (this.reservationAction.action == HotelCalendar.ACTION.MOVE_ALL) { + // Relative Movement + date_cell.subtract(this.reservationAction.daysOffset, 'd'); + + var parentRow = ev.target.parentNode.parentNode.parentNode.parentNode; + var room = this.getRoom(parentRow.dataset.hcalRoomObjId); + reserv.room = room; + var diff_date = this.getDateDiffDays(reserv.startDate, reserv.endDate); + reserv.startDate.set({'date': date_cell.date(), 'month': date_cell.month(), 'year': date_cell.year()}); + var date_end = reserv.startDate.clone().add(diff_date, 'd'); + reserv.endDate.set({'date': date_end.date(), 'month': date_end.month(), 'year': date_end.year()}); + this.reservationAction.newReservationObj = reserv; + toRoom = +ev.target.dataset.hcalBedNum; + needUpdate = true; + } + } + + if (needUpdate && reserv) { + _.defer(function(r){ this._updateScroll(r._html); }.bind(this), reserv) + + var affectedReservations = [reserv].concat(this.getLinkedReservations(this.reservationAction.newReservationObj)); + for (var areserv of affectedReservations) { + if (areserv !== reserv) { + areserv.startDate = reserv.startDate.clone(); + areserv.endDate = reserv.endDate.clone(); + } + + if (areserv._html) { + if (areserv.unusedZone) { + areserv._html.style.visibility = 'hidden'; + continue; + } + _.defer(function(ro, r, tro){ + this._calcReservationCellLimits( + r, + r===ro?tro:undefined, + !this.options.assistedMovement); + this._updateDivReservation(r); + + if (!r._limits.isValid() || !this.checkReservationPlace(r) || + (r.fixRooms && this.reservationAction.oldReservationObj.room.id != r.room.id) || + (r.fixDays && !this.reservationAction.oldReservationObj.startDate.isSame(r.startDate, 'day'))) { + r._html.classList.add('hcal-reservation-invalid'); + } + else { + r._html.classList.remove('hcal-reservation-invalid'); + } + }.bind(this), reserv, areserv, toRoom); + } + } + } + } + }, + + onMainKeyUp: function(/*EventObject*/ev) { + if (this.reservationAction.action === HotelCalendar.ACTION.SWAP || this.getSwapMode() !== HotelCalendar.MODE.NONE) { + var needReset = false; + if (ev.keyCode === 27) { + this._dispatchEvent('hcalOnCancelSwapReservations'); + needReset = true; + } + else if (ev.keyCode === 13) { + this._dispatchSwapReservations(); + needReset = true; + } + else if (ev.keyCode === 17 && this.getSwapMode() === HotelCalendar.MODE.SWAP_FROM) { + this.setSwapMode(HotelCalendar.MODE.SWAP_TO); + } + + if (needReset) { + this._reset_action_reservation(); + this._updateHighlightSwapReservations(); + this._modeSwap = HotelCalendar.MODE.NONE; + } + } + }, + + onMainKeyDown: function(/*EventObject*/ev) { + if (this.reservationAction.action === HotelCalendar.ACTION.SWAP || this.getSwapMode() !== HotelCalendar.MODE.NONE) { + if (ev.keyCode === 17 && this.getSwapMode() === HotelCalendar.MODE.SWAP_TO) { + this.setSwapMode(HotelCalendar.MODE.SWAP_FROM); + } + } + }, + + onMainMouseUp: function(/*EventObject*/ev) { + if (this._lazyModeReservationsSelection) { + clearTimeout(this._lazyModeReservationsSelection); + this._lazyModeReservationsSelection = false; + } + _.defer(function(ev){ + if (this.reservationAction.reservation) { + var reservDiv = this.reservationAction.reservation; + reservDiv.classList.remove('hcal-reservation-action'); + this._updateHighlightInvalidZones(); + + var rdivs = this.e.querySelectorAll('div.hcal-reservation.hcal-reservation-foreground'); + for (var rd of rdivs) { rd.classList.remove('hcal-reservation-foreground'); } + + var reserv = this.getReservation(reservDiv.dataset.hcalReservationObjId); + var linkedReservations = this.getLinkedReservations(reserv); + var hasInvalidLink = false; + for (var r of linkedReservations) { + if (r._html) { + hasInvalidLink = !hasInvalidLink && r._html.classList.contains('hcal-reservation-invalid'); + r._html.classList.remove('hcal-reservation-action'); + r._html.classList.remove('hcal-reservation-invalid'); + } + } + + if (this.reservationAction.oldReservationObj && this.reservationAction.newReservationObj) { + if (!this.options.allowInvalidActions && (reservDiv.classList.contains('hcal-reservation-invalid') || hasInvalidLink)) { + this.replaceReservation(this.reservationAction.newReservationObj, this.reservationAction.oldReservationObj); + } else { + var oldReservation = this.reservationAction.oldReservationObj; + var newReservation = this.reservationAction.newReservationObj; + // Calc Old Reservation Price + var oldDiff = this.getDateDiffDays(oldReservation.startDate, oldReservation.endDate); + var oldPrice = 0.0 + for (var e=0; e> 16) & 255, (RGBint >> 8) & 255, RGBint & 255]; + }, + + _hueToRgb: function(/*Int*/v1, /*Int*/v2, /*Int*/h) { + if (h<0.0) { h+=1; } + if (h>1.0) { h-=1; } + if ((6.0*h) < 1.0) { return v1+(v2-v1)*6.0*h; } + if ((2.0*h) < 1.0) { return v2; } + if ((3.0*h) < 2.0) { return v1+(v2-v1)*((2.0/3.0)-h)*6.0; } + return v1; + }, + + _hslToRgb: function(/*Int*/h, /*Int*/s, /*Int*/l) { + if (s == 0.0) { + return [l,l,l]; + } + var v2 = l<0.5?l*(1.0+s):(l+s)-(s*l); + var v1 = 2.0*l-v2; + return [ + this._hueToRgb(v1,v2,h+(1.0/3.0)), + this._hueToRgb(v1,v2,h), + this._hueToRgb(v1,v2,h-(1.0/3.0))]; + }, + + _RGBToHex: function(/*Int*/r, /*Int*/g, /*Int*/b){ + var bin = r << 16 | g << 8 | b; + return (function(h){ + return new Array(7-h.length).join("0")+h; + })(bin.toString(16).toUpperCase()); + }, + + _hexToRGB: function(/*Int*/hex){ + var r = hex >> 16; + var g = hex >> 8 & 0xFF; + var b = hex & 0xFF; + return [r,g,b]; + }, + + _generateColor: function(/*Int*/value, /*Int*/max, /*Int*/offset, /*Bool*/reverse, /*Bool*/strmode) { + var rgb = [offset,1.0,0.5]; + if (value > max) { + if (!strmode) { + return rgb; + } + return "rgb("+Math.floor(rgb[0]*255)+","+Math.floor(rgb[1]*255)+","+Math.floor(rgb[2]*255)+")"; + } + if (reverse) { + value = max-value; + } + rgb = this._hslToRgb(((max-value)*offset)/max, 1.0, 0.5); + if (!strmode) { + return rgb; + } + return "rgb("+Math.floor(rgb[0]*255)+","+Math.floor(rgb[1]*255)+","+Math.floor(rgb[2]*255)+")"; + } +}; + +/** CONSTANTS **/ +HotelCalendar.DOMAIN = { NONE: -1, RESERVATIONS: 0, ROOMS: 1 }; +HotelCalendar.ACTION = { NONE: -1, MOVE_ALL: 0, MOVE_LEFT: 1, MOVE_RIGHT: 2, SWAP: 3 }; +HotelCalendar.MODE = { NONE: -1, SWAP_FROM: 0, SWAP_TO: 1 }; +HotelCalendar.DATE_FORMAT_SHORT_ = 'DD/MM/YYYY'; +HotelCalendar.DATE_FORMAT_LONG_ = HotelCalendar.DATE_FORMAT_SHORT_ + ' HH:mm:ss'; +/** STATIC METHODS **/ +HotelCalendar.toMoment = function(/*String,MomentObject*/ndate, /*String*/format) { + if (moment.isMoment(ndate)) { + return ndate; + } else if (typeof ndate === 'string' || ndate instanceof Date) { + ndate = moment(ndate, typeof format==='undefined'?HotelCalendar.DATE_FORMAT_LONG_:format); + if (moment.isMoment(ndate)) { + return ndate; + } + } + + //debugger; + console.warn('[Hotel Calendar][toMoment] Invalid date format!'); + return false; +} +HotelCalendar.toMomentUTC = function(/*String,MomentObject*/ndate, /*String*/format) { + if (moment.isMoment(ndate)) { + return ndate; + } else if (typeof ndate === 'string' || ndate instanceof Date) { + ndate = moment.utc(ndate, (typeof format==='undefined'?HotelCalendar.DATE_FORMAT_LONG_:format)); + if (moment.isMoment(ndate)) { + return ndate; + } + } + + //debugger; + console.warn('[Hotel Calendar][toMomentUTC] Invalid date format!'); + return false; +} + + +/** ROOM OBJECT **/ +function HRoom(/*Int*/id, /*String*/number, /*Int*/capacity, /*String*/type, /*Bool*/shared, /*List*/price) { + this.id = id || -1; + this.number = number || -1; + this.capacity = capacity || 1; + this.type = type || ''; + this.shared = shared; + this.price = price || false; + this.overbooking = false; + + this._html = false; + this._active = true; + this._userData = {}; +} +HRoom.prototype = { + clearUserData: function() { this._userData = {}; }, + getUserData: function(/*String?*/key) { + if (typeof key === 'undefined') { + return this._userData; + } + return key in this._userData && this._userData[key] || null; + }, + addUserData: function(/*Dictionary*/data) { + if (!_.isObject(data)) { + console.warn("[Hotel Calendar][HRoom][setUserData] Invalid Data! Need be a object!"); + } else { + this._userData = _.extend(this._userData, data); + } + }, + clone: function() { + var nroom = new HRoom( + this.id, + this.number, // Name + this.capacity, // Capacity + this.type, // Category + this.shared, // Shared Room + this.price // Price + ); + nroom.overbooking = this.overbooking; + nroom._html = this._html; + nroom._active = this._active; + nroom.addUserData(this.getUserData()); + return nroom; + } +}; + +/** RESERVATION OBJECT **/ +function HReservation(/*Dictionary*/rValues) { + if (typeof rValues.room === 'undefined') { + delete this; + console.warn("[Hotel Calendar][HReservation] room can't be empty!"); + return; + } + + this.id = rValues.id; + this.room = rValues.room; + this.adults = rValues.adults || 1; + this.childrens = rValues.childrens || 0; + this.title = rValues.title || ''; + this.startDate = rValues.startDate || null; + this.endDate = rValues.endDate || null; + this.color = rValues.color || '#000'; + this.colorText = rValues.colorText || '#FFF'; + this.readOnly = rValues.readOnly || false; + this.fixRooms = rValues.fixRooms || false; + this.fixDays = rValues.fixDays || false; + this.unusedZone = rValues.unusedZone || false; + this.linkedId = rValues.linkedId || -1; + this.splitted = rValues.splitted || false; + this.overbooking = rValues.overbooking || false; + + this._drawModes = ['hard-start', 'hard-end']; + this._html = false; + this._limits = new HLimit(); + this._beds = []; + this._active = true; + this._userData = {}; +} +HReservation.prototype = { + setRoom: function(/*HRoomObject*/room) { this.room = room; }, + setStartDate: function(/*String,MomentObject*/date) { this.startDate = HotelCalendar.toMomentUTC(date); }, + setEndDate: function(/*String,MomentObject*/date) { this.endDate = HotelCalendar.toMomentUTC(date); }, + + clearUserData: function() { this._userData = {}; }, + getUserData: function(/*String?*/key) { + if (typeof key === 'undefined') { + return this._userData; + } + return key in this._userData && this._userData[key] || null; + }, + addUserData: function(/*Dictionary*/data) { + if (!_.isObject(data)) { + console.warn("[Hotel Calendar][HReservation][setUserData] Invalid Data! Need be a object!"); + } else { + this._userData = _.extend(this._userData, data); + } + }, + getTotalPersons: function(/*Boolean*/countChildrens) { + var persons = this.adults; + if (countChildrens) { + persons += this.childrens; + } + return persons; + }, + clone: function() { + var nreserv = new HReservation({ + 'id': this.id, + 'room': this.room, + 'adults': this.adults, + 'childrens': this.childrens, + 'title': this.title, + 'startDate': this.startDate.clone(), + 'endDate': this.endDate.clone(), + 'color': this.color, + 'colorText': this.colorText, + 'readOnly': this.readOnly, + 'fixRooms': this.fixRooms, + 'fixDays': this.fixDays, + 'unusedZone': this.unusedZone, + 'linkedId': this.linkedId, + 'splitted': this.splitted, + 'overbooking': this.overbooking + }); + nreserv._beds = _.clone(this._beds); + nreserv._html = this._html; + nreserv._drawModes = _.clone(this._drawModes); + nreserv._limits = this._limits.clone(); + nreserv._active = this._active; + nreserv.addUserData(this.getUserData()); + return nreserv; + } +}; + +/** LIMIT OBJECT **/ +function HLimit(/*HTMLObject*/left, /*HMTLObject*/right) { + this.left = left; + this.right = right; +} +HLimit.prototype = { + isSame: function() { + return this.left == this.right; + }, + isValid: function() { + return this.left && this.right; + }, + swap: function() { + var tt = this.left; + this.left = this.right; + this.right = tt; + }, + clone: function() { + return new HLimit(this.left, this.right); + } +}; diff --git a/hotel_calendar/static/src/lib/hcalendar/js/hcalendar_management.js b/hotel_calendar/static/src/lib/hcalendar/js/hcalendar_management.js new file mode 100644 index 000000000..cd6dcd1e4 --- /dev/null +++ b/hotel_calendar/static/src/lib/hcalendar/js/hcalendar_management.js @@ -0,0 +1,1088 @@ +/* global _, moment */ +'use strict'; +/* + * Hotel Calendar Management JS v0.0.1a - 2017-2018 + * GNU Public License + * Alexandre Díaz + * + * Dependencies: + * - moment + * - underscore + * - jquery !shit + * - bootbox !shit + * - bootstrap !shit + */ + +function HotelCalendarManagement(/*String*/querySelector, /*Dictionary*/options, /*HTMLObject?*/_base) { + if (window === this) { + return new HotelCalendarManagement(querySelector, options, _base); + } + + this.$base = (_base === 'undefined') ? document : _base; + + if (typeof querySelector === 'string') { + this.e = this.$base.querySelector(querySelector); + if (!this.e) { + return false; + } + } else if (typeof querySelector === 'object') { + this.e = querySelector; + } else { + return { + Version: '0.0.1a', + Author: "Alexandre Díaz", + Created: "24/09/2017", + Updated: "21/04/2018" + }; + } + + /** Strings **/ + this._strings = { + 'Open': 'Open', + 'Closed': 'Closed', + 'C. Departure': 'C. Departure', + 'C. Arrival': 'C. Arrival', + 'Price': 'Price', + 'Availability': 'Availability', + 'Min. Stay': 'Min. Stay', + 'Max. Stay': 'Max. Stay', + 'Min. Stay Arrival': 'Min. Stay Arrival', + 'Max. Stay Arrival': 'Max. Stay Arrival', + 'Clousure': 'Clousure', + 'Free Rooms': 'Free Rooms', + 'No OTA': 'No OTA', + 'Options': 'Options', + 'Reset': 'Reset', + 'Copy': 'Copy', + 'Paste': 'Paste', + 'Clone': 'Clone', + 'Cancel': 'Cancel' + }; + + /** Options **/ + if (!options) { options = {}; } + this.options = { + startDate: moment(options.startDate || new Date()), + days: options.days || moment(options.startDate || new Date()).daysInMonth(), + rooms: options.rooms || [], + endOfWeek: options.endOfWeek || 6, + endOfWeekOffset: options.endOfWeekOffset || 0, + currencySymbol: options.currencySymbol || '€', + dateFormatLong: options.dateFormat || 'YYYY-MM-DD HH:mm:ss', + dateFormatShort: options.dateFormat || 'YYYY-MM-DD', + translations: options.translations || [] + }; + + // Check correct values + if (this.options.rooms.length > 0 && !(this.options.rooms[0] instanceof HVRoom)) { + this.options.rooms = []; + console.warn("[Hotel Calendar Management][init] Invalid Room definiton!"); + } + + // Merge Transalations + for (var key in this.options.translations) { + this._strings[key] = this.options.translations[key]; + } + + /** Internal Values **/ + this.tableCreated = false; + this._pricelist = {}; + this._restrictions = {}; + this._availability = {}; + this._copy_values = {}; + this._mode = HotelCalendarManagement.MODE.ALL; + + /***/ + if (!this._create()) { + return false; + } + + return this; +} + +HotelCalendarManagement.prototype = { + /** PUBLIC MEMBERS **/ + addEventListener: function(/*String*/event, /*Function*/callback) { + this.e.addEventListener(event, callback); + }, + + hasChangesToSave: function() { + return this.e.querySelector('.hcal-management-record-changed') !== null; + }, + + //==== CALENDAR + setStartDate: function(/*String,MomentObject*/date, /*Int?*/days) { + var curDate = this.options.startDate; + if (moment.isMoment(date)) { + this.options.startDate = date; + } else if (typeof date === 'string'){ + this.options.startDate = moment(date); + } else { + console.warn("[Hotel Calendar Management][setStartDate] Invalid date format!"); + return; + } + + if (typeof days !== 'undefined') { + this.options.days = days; + } + + /*this.e.dispatchEvent(new CustomEvent( + 'hcOnChangeDate', + {'detail': {'prevDate':curDate, 'newDate': $this.options.startDate}}));*/ + this._updateView(); + }, + + getOptions: function(/*String?*/key) { + if (typeof key !== 'undefined') { + return this.options[key]; + } + return this.options; + }, + + setMode: function(/*Int*/mode) { + if (typeof mode === 'undefined') { + mode = this._mode; + } + if (mode === HotelCalendarManagement.MODE.LOW) { + this.etable.classList.remove('hcal-management-medium'); + this.etable.classList.add('hcal-management-low'); + this.edivrhl.classList.remove('hcal-management-medium'); + this.edivrhl.classList.add('hcal-management-low'); + this._mode = HotelCalendarManagement.MODE.LOW; + } else if (mode === HotelCalendarManagement.MODE.MEDIUM) { + this.etable.classList.remove('hcal-management-low'); + this.etable.classList.add('hcal-management-medium'); + this.edivrhl.classList.remove('hcal-management-low'); + this.edivrhl.classList.add('hcal-management-medium'); + this._mode = HotelCalendarManagement.MODE.MEDIUM; + } else { + this.etable.classList.remove('hcal-management-low'); + this.etable.classList.remove('hcal-management-medium'); + this.edivrhl.classList.remove('hcal-management-low'); + this.edivrhl.classList.remove('hcal-management-medium'); + this._mode = HotelCalendarManagement.MODE.ALL; + } + }, + + + /** PRIVATE MEMBERS **/ + //==== MAIN FUNCTIONS + _create: function() { + this.e.innerHTML = ""; + if (this.tableCreated) { + console.warn("[Hotel Calendar Management] Already created!"); + return false; + } + + /** Main Table **/ + this.etable = document.createElement("table"); + this.etable.classList.add('hcal-management-table'); + this.etable.classList.add('noselect'); + this.e.appendChild(this.etable); + this._updateView(); + this.tableCreated = true; + + return true; + }, + + _generateTableDay: function(/*HTMLObject*/parentCell) { + var $this = this; + var table = document.createElement("table"); + table.classList.add('hcal-management-table-day'); + table.classList.add('noselect'); + var row = false; + var cell = false; + var telm = false; + var roomId = $this.$base.querySelector(`#${parentCell.dataset.hcalParentRow}`).dataset.hcalRoomObjId; + var room = $this.getRoom(roomId); + var dateCell = HotelCalendarManagement.toMoment(parentCell.dataset.hcalDate); + var dateShortStr = dateCell.format(HotelCalendarManagement._DATE_FORMAT_SHORT); + + row = table.insertRow(); + row.setAttribute('name', 'price'); + cell = row.insertCell(); + cell.setAttribute('colspan', '3'); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`PRICE_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'price'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Price')); + telm.value = room.price; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + cell = row.insertCell(); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`AVAIL_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'avail'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Availability')); + telm.value = 0; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + + row = table.insertRow(); + row.setAttribute('name', 'rest_a'); + cell = row.insertCell(); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`MIN_STAY_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'min_stay'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Min. Stay')); + telm.dataset.orgValue = telm.value = 0; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input'); + telm.classList.add('hcal-border-radius-left'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + cell = row.insertCell(); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`MAX_STAY_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'max_stay'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Max. Stay')); + telm.dataset.orgValue = telm.value = 0; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input'); + telm.classList.add('hcal-border-radius-right'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + cell = row.insertCell(); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`MIN_STAY_ARRIVAL_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'min_stay_arrival'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Min. Stay Arrival')); + telm.dataset.orgValue = telm.value = 0; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input'); + telm.classList.add('hcal-border-radius-left'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + cell = row.insertCell(); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`MAX_STAY_ARRIVAL_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'max_stay_arrival'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Max. Stay Arrival')); + telm.dataset.orgValue = telm.value = 0; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input'); + telm.classList.add('hcal-border-radius-right'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + + row = table.insertRow(); + row.setAttribute('name', 'rest_b'); + cell = row.insertCell(); + cell.setAttribute('colspan', '3'); + telm = document.createElement("select"); + telm.classList.add('hcal-management-input'); + telm.addEventListener('change', function(ev){ $this.onInputChange(ev, this); }, false); + telm.setAttribute('id', this._sanitizeId(`CLOUSURE_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'clousure'); + telm.setAttribute('title', this._t('Closure')); + telm.dataset.orgValue = 'open'; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + var selectOpt = document.createElement("option"); + selectOpt.value = "open"; + selectOpt.textContent = this._t("Open"); + telm.appendChild(selectOpt); + selectOpt = document.createElement("option"); + selectOpt.value = "closed"; + selectOpt.textContent = this._t("Closed"); + telm.appendChild(selectOpt); + selectOpt = document.createElement("option"); + selectOpt.value = "closed_departure"; + selectOpt.textContent = this._t("C. Departure"); + telm.appendChild(selectOpt); + selectOpt = document.createElement("option"); + selectOpt.value = "closed_arrival"; + selectOpt.textContent = this._t("C. Arrival"); + telm.appendChild(selectOpt); + cell.appendChild(telm); + cell = row.insertCell(); + telm = document.createElement("input"); + telm.setAttribute('id', this._sanitizeId(`FREE_ROOMS_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'free_rooms'); + telm.setAttribute('type', 'edit'); + telm.setAttribute('title', this._t('Free Rooms')); + telm.setAttribute('readonly', 'readonly'); + telm.setAttribute('disabled', 'disabled'); + telm.style.backgroundColor = 'lightgray'; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + cell.appendChild(telm); + + row = table.insertRow(); + row.setAttribute('name', 'rest_c'); + cell = row.insertCell(); + cell.style.textAlign = 'center'; + cell.setAttribute('colspan', '4'); + telm = document.createElement("button"); + telm.setAttribute('id', this._sanitizeId(`NO_OTA_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'no_ota'); + telm.setAttribute('title', this._t('No OTA')); + telm.innerHTML = "No OTA"; + telm.dataset.orgValue = telm.dataset.state = 'false'; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + telm.classList.add('hcal-management-input', 'pull-left'); + telm.addEventListener('click', function(ev){ $this.onInputChange(ev, this); }, false); + cell.appendChild(telm); + + telm = document.createElement("span"); + telm.setAttribute('id', this._sanitizeId(`OPTIONS_${roomId}_${dateShortStr}`)); + telm.setAttribute('name', 'options'); + telm.setAttribute('title', this._t('Options')); + telm.classList.add('dropdown', 'pull-right', 'hcal-management-record-options'); + telm.innerHTML = ` + + `; + telm.dataset.hcalParentCell = parentCell.getAttribute('id'); + cell.appendChild(telm); + + cell.querySelector('.hcal-record-option-clone').addEventListener('click', function(ev){ $this.onOptionsRecord(ev, this); }, false); + cell.querySelector('.hcal-record-option-reset').addEventListener('click', function(ev){ $this.onOptionsRecord(ev, this); }, false); + cell.querySelector('.hcal-record-option-copy').addEventListener('click', function(ev){ $this.onOptionsRecord(ev, this); }, false); + cell.querySelector('.hcal-record-option-paste').addEventListener('click', function(ev){ $this.onOptionsRecord(ev, this); }, false); + + + parentCell.appendChild(table); + + return table; + }, + + _getCell: function(/*HRoomObject*/room, /*DateTimeObject*/sdate) { + return this.e.querySelector(`#${this._sanitizeId(`${room.name}_${room.id}_${sdate.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`)}`); + }, + + setData: function(prices, restrictions, avail, count_free_rooms) { + //this._updateView(); + if (typeof prices !== 'undefined' && prices) { + this._pricelist = prices; + this._updatePriceList(); + } + if (typeof restrictions !== 'undefined' && restrictions) { + this._restrictions = restrictions; + this._updateRestrictions(); + } + if (typeof avail !== 'undefined' && avail) { + this._availability = avail; + this._updateAvailability(); + } + if (typeof count_free_rooms !== 'undefined' && count_free_rooms) { + this._free_rooms = count_free_rooms; + this._updateNumFreeRooms(); + } + }, + + //==== ROOMS + getRoom: function(/*String*/id) { + return _.find(this.options.rooms, function(item){ return item.id == id; }); + }, + + //==== RENDER FUNCTIONS + _create_table_data_days: function() { + var $this = this; + while (this.e.hasChildNodes()) { + this.e.removeChild(this.e.lastChild); + } + + // VRoom Names + this.edivrhl = document.createElement("div"); + this.edivrhl.classList.add('table-vrooms'); + this.e.appendChild(this.edivrhl); + this.etableRooms = document.createElement("table"); + this.etableRooms.classList.add('hcal-management-table'); + this.etableRooms.classList.add('noselect'); + this.edivrhl.appendChild(this.etableRooms); + + // Container: Days + Data + this.edivm = document.createElement("div"); + this.edivm.setAttribute('id', 'hcal-management-container-dd'); + this.e.appendChild(this.edivm); + // Days + this.edivrh = document.createElement("div"); + this.edivrh.classList.add('table-vroom-data-header'); + this.edivm.appendChild(this.edivrh); + this.etableHeader = document.createElement("table"); + this.etableHeader.classList.add('hcal-management-table'); + this.etableHeader.classList.add('noselect'); + this.edivrh.appendChild(this.etableHeader); + // Data + this.edivr = document.createElement("div"); + this.edivr.classList.add('table-vroom-data'); + this.edivm.appendChild(this.edivr); + this.etable = document.createElement("table"); + this.etable.classList.add('hcal-management-table'); + this.etable.classList.add('noselect'); + this.edivr.appendChild(this.etable); + + /** TABLE HEADER **/ + var thead = this.etableHeader.createTHead(); + + // Render Next Days + var row = thead.insertRow(); + var now = moment().local(); + for (var i=0; i<=this.options.days; i++) { + var dd = this.options.startDate.clone().add(i,'d'); + var dd_local = dd.clone().local(); + var cell = row.insertCell(); + cell.setAttribute('id', this._sanitizeId(`hday_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`)); + cell.classList.add('hcal-cell-header-day'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-3d'); + cell.dataset.hcalDate = dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT); + cell.textContent = dd.format('D') + ' ' + dd.format('ddd') + ' (' + dd.format('MMM') + "'" + dd.format('YY') + ')'; + cell.setAttribute('title', dd.format('dddd')) + var day = +dd_local.format('D'); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= this.options.endOfWeek-this.options.endOfWeekOffset && dd_local.format('e') <= this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + + /** ROOM LINES **/ + var tbody = document.createElement("tbody"); + this.etableRooms.appendChild(tbody); + this.options.rooms.forEach(function(itemRoom, indexRoom){ + row = tbody.insertRow(); + cell = row.insertCell(); + cell.textContent = itemRoom.name; + cell.setAttribute('colspan', 2); + cell.classList.add('hcal-cell-room-type-group-item'); + cell.classList.add('btn-hcal'); + cell.classList.add('btn-hcal-3d'); + }); + + /** ROOM DATA LINES **/ + var tbody = document.createElement("tbody"); + this.etable.appendChild(tbody); + this.options.rooms.forEach(function(itemRoom, indexRoom){ + // Room Number + row = tbody.insertRow(); + row.setAttribute('id', $this._sanitizeId(`ROW_${itemRoom.name}_${itemRoom.id}`)); + row.dataset.hcalRoomObjId = itemRoom.id; + row.classList.add('hcal-row-room-type-group-item'); + for (var i=0; i<=$this.options.days; i++) { + var dd = $this.options.startDate.clone().add(i,'d'); + var dd_local = dd.clone().local(); + cell = row.insertCell(); + cell.setAttribute('id', $this._sanitizeId(`${itemRoom.name}_${itemRoom.id}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`)); + cell.classList.add('hcal-cell-room-type-group-item-day'); + cell.dataset.hcalParentRow = row.getAttribute('id'); + cell.dataset.hcalDate = dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT); + // Generate Interactive Table + cell.appendChild($this._generateTableDay(cell)); + //cell.innerHTML = dd.format("DD"); + var day = +dd_local.format("D"); + if (day == 1) { + cell.classList.add('hcal-cell-start-month'); + } + if (dd_local.isSame(now, 'day')) { + cell.classList.add('hcal-cell-current-day'); + } else if (dd_local.format('e') >= $this.options.endOfWeek-$this.options.endOfWeekOffset && dd_local.format('e') <= $this.options.endOfWeek) { + cell.classList.add('hcal-cell-end-week'); + } + } + }); + }, + + //==== PRICELIST + addPricelist: function(/*Object*/pricelist) { + var vroom_ids = Object.keys(pricelist); + for (var vid of vroom_ids) { + if (vid in this._pricelist) { + for (var price of pricelist[vid]) { + var index = _.findIndex(this._pricelist[vid], {date: price['date']}); + if (index >= 0) { + this._pricelist[vid][index] = price; + } else { + this._pricelist[vid].push(price); + } + } + } + else { + this._pricelist[vid] = pricelist[vid]; + } + } + this._updatePriceList(); + }, + + _updatePriceList: function() { + var keys = Object.keys(this._pricelist); + for (var vroomId of keys) { + for (var price of this._pricelist[vroomId]) { + var dd = HotelCalendarManagement.toMoment(price.date, this.options.dateFormatShort); + var inputId = this._sanitizeId(`PRICE_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`); + var input = this.etable.querySelector(`#${inputId}`); + if (input && !input.classList.contains('hcal-management-input-changed')) { + input.dataset.orgValue = price.price; + input.value = price.price; + } + } + } + }, + + getPricelist: function(onlyNew) { + var data = {}; + for (var room of this.options.rooms) { + for (var i=0; i<=this.options.days; i++) { + var ndate = this.options.startDate.clone().add(i, 'd'); + var ndateStr = ndate.format(HotelCalendarManagement._DATE_FORMAT_SHORT); + var inputId = this._sanitizeId(`PRICE_${room.id}_${ndateStr}`); + var input = this.etable.querySelector(`#${inputId}`); + if (!onlyNew || (onlyNew && input.value !== input.dataset.orgValue)) { + if (!(room.id in data)) { data[room.id] = []; } + data[room.id].push({ + 'date': ndate.format('YYYY-MM-DD'), + 'price': input.value + }); + } + } + } + return data; + }, + + //==== RESTRICTIONS + addRestrictions: function(/*Object*/restrictions) { + var vroom_ids = Object.keys(restrictions); + for (var vid of vroom_ids) { + if (vid in this._restrictions) { + for (var rest of restrictions[vid]) { + var index = _.findIndex(this._restrictions[vid], {date: rest['date']}); + if (index >= 0) { + this._restrictions[vid][index] = rest; + } else { + this._restrictions[vid].push(rest); + } + } + } + else { + this._restrictions[vid] = restrictions[vid]; + } + } + this._updateRestrictions(); + }, + + _updateRestrictions: function() { + var keys = Object.keys(this._restrictions); + for (var vroomId of keys) { + var room = this.getRoom(vroomId); + for (var restriction of this._restrictions[vroomId]) { + var dd = HotelCalendarManagement.toMoment(restriction.date, this.options.dateFormatShort); + var inputIds = [ + this._sanitizeId(`MIN_STAY_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`), restriction.min_stay, + this._sanitizeId(`MIN_STAY_ARRIVAL_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`), restriction.min_stay_arrival, + this._sanitizeId(`MAX_STAY_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`), restriction.max_stay, + this._sanitizeId(`MAX_STAY_ARRIVAL_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`), restriction.max_stay_arrival, + ]; + for (var i=0; i= 0) { + this._availability[vid][index] = avail; + } else { + this._availability[vid].push(avail); + } + } + } + else { + this._availability[vid] = availability[vid]; + } + } + this._updateAvailability(); + }, + + _updateAvailability: function() { + var keys = Object.keys(this._availability); + for (var vroomId of keys) { + for (var avail of this._availability[vroomId]) { + var dd = HotelCalendarManagement.toMoment(avail.date, this.options.dateFormatShort); + var inputIds = [ + `AVAIL_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`, avail.avail, + `NO_OTA_${vroomId}_${dd.format(HotelCalendarManagement._DATE_FORMAT_SHORT)}`, avail.no_ota + ]; + + for (var i=0; i + + + +
+ Price: ${copy_values['price']}
+ Availability: ${copy_values['avail']}
+ Min. Stay: ${copy_values['min_stay']}
+ Max. Stay: ${copy_values['max_stay']}
+ Min. Stay Arrival: ${copy_values['min_stay_arrival']}
+ Max. Stay Arrival: ${copy_values['max_stay_arrival']}
+ Clousure: ${copy_values['clousure']}
+ No OTA: ${copy_values['no_ota']}
+
+ + + + + FROM
+
+ + + + +
+ + + TO
+
+ + + + +
+ + + + + + + + + + `, + buttons: { + confirm : { + label: $this._t('Clone'), + className: "btn-success", + callback: function() { + var date_begin = $('table#hcal-management-clone-dates #date_begin').data("DateTimePicker").getDate().set({'hour': 0, 'minute': 0, 'second': 0}).clone(); + var date_end = $('table#hcal-management-clone-dates #date_end').data("DateTimePicker").getDate().set({'hour': 0, 'minute': 0, 'second': 0}).clone(); + var diff_days = $this.getDateDiffDays(date_begin, date_end) + 1; + var same_day = $('table#hcal-management-clone-dates #same_day').is(':checked'); + var cell_date = HotelCalendarManagement.toMoment(parentCell.dataset.hcalDate); + + var ndate = date_begin.clone(); + for (var i=0; i0)for(c in rd)d=rd[c],e=b[d],p(e)||(a[d]=e);return a} +// Moment prototype object +function r(b){q(this,b),this._d=new Date(null!=b._d?b._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)), +// Prevent infinite loop in case updateOffset creates new moment +// objects. +sd===!1&&(sd=!0,a.updateOffset(this),sd=!1)}function s(a){return a instanceof r||null!=a&&null!=a._isAMomentObject}function t(a){return a<0?Math.ceil(a)||0:Math.floor(a)}function u(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=t(b)),c} +// compare two arrays, return the number of differences +function v(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;d0?"future":"past"];return z(c)?c(b):c.replace(/%s/i,b)}function J(a,b){var c=a.toLowerCase();Dd[c]=Dd[c+"s"]=Dd[b]=a}function K(a){return"string"==typeof a?Dd[a]||Dd[a.toLowerCase()]:void 0}function L(a){var b,c,d={};for(c in a)i(a,c)&&(b=K(c),b&&(d[b]=a[c]));return d}function M(a,b){Ed[a]=b}function N(a){var b=[];for(var c in a)b.push({unit:c,priority:Ed[c]});return b.sort(function(a,b){return a.priority-b.priority}),b}function O(b,c){return function(d){return null!=d?(Q(this,b,d),a.updateOffset(this,c),this):P(this,b)}}function P(a,b){return a.isValid()?a._d["get"+(a._isUTC?"UTC":"")+b]():NaN}function Q(a,b,c){a.isValid()&&a._d["set"+(a._isUTC?"UTC":"")+b](c)} +// MOMENTS +function R(a){return a=K(a),z(this[a])?this[a]():this}function S(a,b){if("object"==typeof a){a=L(a);for(var c=N(a),d=0;d=0;return(f?c?"+":"":"-")+Math.pow(10,Math.max(0,e)).toString().substr(1)+d} +// token: 'M' +// padded: ['MM', 2] +// ordinal: 'Mo' +// callback: function () { this.month() + 1 } +function U(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(Id[a]=e),b&&(Id[b[0]]=function(){return T(e.apply(this,arguments),b[1],b[2])}),c&&(Id[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function V(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function W(a){var b,c,d=a.match(Fd);for(b=0,c=d.length;b=0&&Gd.test(a);)a=a.replace(Gd,c),Gd.lastIndex=0,d-=1;return a}function Z(a,b,c){$d[a]=z(b)?b:function(a,d){return a&&c?c:b}}function $(a,b){return i($d,a)?$d[a](b._strict,b._locale):new RegExp(_(a))} +// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript +function _(a){return aa(a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}))}function aa(a){return a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function ba(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),f(b)&&(d=function(a,c){c[b]=u(a)}),c=0;c=0&&isFinite(h.getFullYear())&&h.setFullYear(a),h}function ta(a){var b=new Date(Date.UTC.apply(null,arguments)); +//the Date.UTC function remaps years 0-99 to 1900-1999 +return a<100&&a>=0&&isFinite(b.getUTCFullYear())&&b.setUTCFullYear(a),b} +// start-of-first-week - start-of-year +function ua(a,b,c){var// first-week day -- which january is always in the first week (4 for iso, 1 for other) +d=7+b-c, +// first-week day local weekday -- which local weekday is fwd +e=(7+ta(a,0,d).getUTCDay()-b)%7;return-e+d-1} +//http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday +function va(a,b,c,d,e){var f,g,h=(7+c-d)%7,i=ua(a,d,e),j=1+7*(b-1)+h+i;return j<=0?(f=a-1,g=pa(f)+j):j>pa(a)?(f=a+1,g=j-pa(a)):(f=a,g=j),{year:f,dayOfYear:g}}function wa(a,b,c){var d,e,f=ua(a.year(),b,c),g=Math.floor((a.dayOfYear()-f-1)/7)+1;return g<1?(e=a.year()-1,d=g+xa(e,b,c)):g>xa(a.year(),b,c)?(d=g-xa(a.year(),b,c),e=a.year()+1):(e=a.year(),d=g),{week:d,year:e}}function xa(a,b,c){var d=ua(a,b,c),e=ua(a+1,b,c);return(pa(a)-d+e)/7} +// HELPERS +// LOCALES +function ya(a){return wa(a,this._week.dow,this._week.doy).week}function za(){return this._week.dow}function Aa(){return this._week.doy} +// MOMENTS +function Ba(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function Ca(a){var b=wa(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")} +// HELPERS +function Da(a,b){return"string"!=typeof a?a:isNaN(a)?(a=b.weekdaysParse(a),"number"==typeof a?a:null):parseInt(a,10)}function Ea(a,b){return"string"==typeof a?b.weekdaysParse(a)%7||7:isNaN(a)?null:a}function Fa(a,b){return a?c(this._weekdays)?this._weekdays[a.day()]:this._weekdays[this._weekdays.isFormat.test(b)?"format":"standalone"][a.day()]:this._weekdays}function Ga(a){return a?this._weekdaysShort[a.day()]:this._weekdaysShort}function Ha(a){return a?this._weekdaysMin[a.day()]:this._weekdaysMin}function Ia(a,b,c){var d,e,f,g=a.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],d=0;d<7;++d)f=k([2e3,1]).day(d),this._minWeekdaysParse[d]=this.weekdaysMin(f,"").toLocaleLowerCase(),this._shortWeekdaysParse[d]=this.weekdaysShort(f,"").toLocaleLowerCase(),this._weekdaysParse[d]=this.weekdays(f,"").toLocaleLowerCase();return c?"dddd"===b?(e=je.call(this._weekdaysParse,g),e!==-1?e:null):"ddd"===b?(e=je.call(this._shortWeekdaysParse,g),e!==-1?e:null):(e=je.call(this._minWeekdaysParse,g),e!==-1?e:null):"dddd"===b?(e=je.call(this._weekdaysParse,g),e!==-1?e:(e=je.call(this._shortWeekdaysParse,g),e!==-1?e:(e=je.call(this._minWeekdaysParse,g),e!==-1?e:null))):"ddd"===b?(e=je.call(this._shortWeekdaysParse,g),e!==-1?e:(e=je.call(this._weekdaysParse,g),e!==-1?e:(e=je.call(this._minWeekdaysParse,g),e!==-1?e:null))):(e=je.call(this._minWeekdaysParse,g),e!==-1?e:(e=je.call(this._weekdaysParse,g),e!==-1?e:(e=je.call(this._shortWeekdaysParse,g),e!==-1?e:null)))}function Ja(a,b,c){var d,e,f;if(this._weekdaysParseExact)return Ia.call(this,a,b,c);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),d=0;d<7;d++){ +// test the regex +if( +// make the regex if we don't have it already +e=k([2e3,1]).day(d),c&&!this._fullWeekdaysParse[d]&&(this._fullWeekdaysParse[d]=new RegExp("^"+this.weekdays(e,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[d]=new RegExp("^"+this.weekdaysShort(e,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[d]=new RegExp("^"+this.weekdaysMin(e,"").replace(".",".?")+"$","i")),this._weekdaysParse[d]||(f="^"+this.weekdays(e,"")+"|^"+this.weekdaysShort(e,"")+"|^"+this.weekdaysMin(e,""),this._weekdaysParse[d]=new RegExp(f.replace(".",""),"i")),c&&"dddd"===b&&this._fullWeekdaysParse[d].test(a))return d;if(c&&"ddd"===b&&this._shortWeekdaysParse[d].test(a))return d;if(c&&"dd"===b&&this._minWeekdaysParse[d].test(a))return d;if(!c&&this._weekdaysParse[d].test(a))return d}} +// MOMENTS +function Ka(a){if(!this.isValid())return null!=a?this:NaN;var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Da(a,this.localeData()),this.add(a-b,"d")):b}function La(a){if(!this.isValid())return null!=a?this:NaN;var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Ma(a){if(!this.isValid())return null!=a?this:NaN; +// behaves the same as moment#day except +// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) +// as a setter, sunday should belong to the previous week. +if(null!=a){var b=Ea(a,this.localeData());return this.day(this.day()%7?b:b-7)}return this.day()||7}function Na(a){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Qa.call(this),a?this._weekdaysStrictRegex:this._weekdaysRegex):(i(this,"_weekdaysRegex")||(this._weekdaysRegex=ue),this._weekdaysStrictRegex&&a?this._weekdaysStrictRegex:this._weekdaysRegex)}function Oa(a){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Qa.call(this),a?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(i(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=ve),this._weekdaysShortStrictRegex&&a?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function Pa(a){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Qa.call(this),a?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(i(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=we),this._weekdaysMinStrictRegex&&a?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Qa(){function a(a,b){return b.length-a.length}var b,c,d,e,f,g=[],h=[],i=[],j=[];for(b=0;b<7;b++) +// make the regex if we don't have it already +c=k([2e3,1]).day(b),d=this.weekdaysMin(c,""),e=this.weekdaysShort(c,""),f=this.weekdays(c,""),g.push(d),h.push(e),i.push(f),j.push(d),j.push(e),j.push(f);for( +// Sorting makes sure if one weekday (or abbr) is a prefix of another it +// will match the longer piece. +g.sort(a),h.sort(a),i.sort(a),j.sort(a),b=0;b<7;b++)h[b]=aa(h[b]),i[b]=aa(i[b]),j[b]=aa(j[b]);this._weekdaysRegex=new RegExp("^("+j.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+h.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+g.join("|")+")","i")} +// FORMATTING +function Ra(){return this.hours()%12||12}function Sa(){return this.hours()||24}function Ta(a,b){U(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})} +// PARSING +function Ua(a,b){return b._meridiemParse} +// LOCALES +function Va(a){ +// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays +// Using charAt should be more compatible. +return"p"===(a+"").toLowerCase().charAt(0)}function Wa(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Xa(a){return a?a.toLowerCase().replace("_","-"):a} +// pick the locale from the array +// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each +// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root +function Ya(a){for(var b,c,d,e,f=0;f0;){if(d=Za(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&v(e,c,!0)>=b-1) +//the next array item is better than a shallower substring of this one +break;b--}f++}return null}function Za(a){var b=null; +// TODO: Find a better way to register and load all the locales in Node +if(!Be[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=xe._abbr,require("./locale/"+a), +// because defineLocale currently also sets the global locale, we +// want to undo that for lazy loaded locales +$a(b)}catch(a){}return Be[a]} +// This function will load locale and then set the global locale. If +// no arguments are passed in, it will simply return the current global +// locale key. +function $a(a,b){var c; +// moment.duration._locale = moment._locale = data; +return a&&(c=p(b)?bb(a):_a(a,b),c&&(xe=c)),xe._abbr}function _a(a,b){if(null!==b){var c=Ae;if(b.abbr=a,null!=Be[a])y("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),c=Be[a]._config;else if(null!=b.parentLocale){if(null==Be[b.parentLocale])return Ce[b.parentLocale]||(Ce[b.parentLocale]=[]),Ce[b.parentLocale].push({name:a,config:b}),null;c=Be[b.parentLocale]._config} +// backwards compat for now: also set the locale +// make sure we set the locale AFTER all child locales have been +// created, so we won't end up with the child locale set. +return Be[a]=new C(B(c,b)),Ce[a]&&Ce[a].forEach(function(a){_a(a.name,a.config)}),$a(a),Be[a]} +// useful for testing +return delete Be[a],null}function ab(a,b){if(null!=b){var c,d=Ae; +// MERGE +null!=Be[a]&&(d=Be[a]._config),b=B(d,b),c=new C(b),c.parentLocale=Be[a],Be[a]=c, +// backwards compat for now: also set the locale +$a(a)}else +// pass null for config to unupdate, useful for tests +null!=Be[a]&&(null!=Be[a].parentLocale?Be[a]=Be[a].parentLocale:null!=Be[a]&&delete Be[a]);return Be[a]} +// returns locale data +function bb(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return xe;if(!c(a)){if( +//short-circuit everything else +b=Za(a))return b;a=[a]}return Ya(a)}function cb(){return wd(Be)}function db(a){var b,c=a._a;return c&&m(a).overflow===-2&&(b=c[be]<0||c[be]>11?be:c[ce]<1||c[ce]>ea(c[ae],c[be])?ce:c[de]<0||c[de]>24||24===c[de]&&(0!==c[ee]||0!==c[fe]||0!==c[ge])?de:c[ee]<0||c[ee]>59?ee:c[fe]<0||c[fe]>59?fe:c[ge]<0||c[ge]>999?ge:-1,m(a)._overflowDayOfYear&&(bce)&&(b=ce),m(a)._overflowWeeks&&b===-1&&(b=he),m(a)._overflowWeekday&&b===-1&&(b=ie),m(a).overflow=b),a} +// date from iso format +function eb(a){var b,c,d,e,f,g,h=a._i,i=De.exec(h)||Ee.exec(h);if(i){for(m(a).iso=!0,b=0,c=Ge.length;bpa(e)&&(m(a)._overflowDayOfYear=!0),c=ta(e,0,a._dayOfYear),a._a[be]=c.getUTCMonth(),a._a[ce]=c.getUTCDate()),b=0;b<3&&null==a._a[b];++b)a._a[b]=f[b]=d[b]; +// Zero out whatever was not defaulted, including time +for(;b<7;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b]; +// Check for 24:00:00.000 +24===a._a[de]&&0===a._a[ee]&&0===a._a[fe]&&0===a._a[ge]&&(a._nextDay=!0,a._a[de]=0),a._d=(a._useUTC?ta:sa).apply(null,f), +// Apply timezone offset from input. The actual utcOffset can be changed +// with parseZone. +null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[de]=24)}}function jb(a){var b,c,d,e,f,g,h,i;if(b=a._w,null!=b.GG||null!=b.W||null!=b.E)f=1,g=4, +// TODO: We need to take the current isoWeekYear, but that depends on +// how we interpret now (local, utc, fixed offset). So create +// a now version of current config (take local/utc/offset flags, and +// create now). +c=gb(b.GG,a._a[ae],wa(sb(),1,4).year),d=gb(b.W,1),e=gb(b.E,1),(e<1||e>7)&&(i=!0);else{f=a._locale._week.dow,g=a._locale._week.doy;var j=wa(sb(),f,g);c=gb(b.gg,a._a[ae],j.year), +// Default to current week. +d=gb(b.w,j.week),null!=b.d?( +// weekday -- low day numbers are considered next week +e=b.d,(e<0||e>6)&&(i=!0)):null!=b.e?( +// local weekday -- counting starts from begining of week +e=b.e+f,(b.e<0||b.e>6)&&(i=!0)): +// default to begining of week +e=f}d<1||d>xa(c,f,g)?m(a)._overflowWeeks=!0:null!=i?m(a)._overflowWeekday=!0:(h=va(c,d,e,f,g),a._a[ae]=h.year,a._dayOfYear=h.dayOfYear)} +// date from string and format string +function kb(b){ +// TODO: Move this to another part of the creation flow to prevent circular deps +if(b._f===a.ISO_8601)return void eb(b);b._a=[],m(b).empty=!0; +// This array is used to make a Date, either with `new Date` or `Date.UTC` +var c,d,e,f,g,h=""+b._i,i=h.length,j=0;for(e=Y(b._f,b._locale).match(Fd)||[],c=0;c0&&m(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),j+=d.length), +// don't parse if it's not a known token +Id[f]?(d?m(b).empty=!1:m(b).unusedTokens.push(f),da(f,d,b)):b._strict&&!d&&m(b).unusedTokens.push(f); +// add remaining unparsed input length to the string +m(b).charsLeftOver=i-j,h.length>0&&m(b).unusedInput.push(h), +// clear _12h flag if hour is <= 12 +b._a[de]<=12&&m(b).bigHour===!0&&b._a[de]>0&&(m(b).bigHour=void 0),m(b).parsedDateParts=b._a.slice(0),m(b).meridiem=b._meridiem, +// handle meridiem +b._a[de]=lb(b._locale,b._a[de],b._meridiem),ib(b),db(b)}function lb(a,b,c){var d; +// Fallback +return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&b<12&&(b+=12),d||12!==b||(b=0),b):b} +// date from string and array of format strings +function mb(a){var b,c,d,e,f;if(0===a._f.length)return m(a).invalidFormat=!0,void(a._d=new Date(NaN));for(e=0;e +// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset +// +0200, so we adjust the time as needed, to be valid. +// +// Keeping the time actually adds/subtracts (one hour) +// from the actual represented time. That is why we call updateOffset +// a second time. In case it wants us to change the offset again +// _changeInProgress == true case, then we have to adjust, because +// there is no such time in the given timezone. +function Db(b,c){var d,e=this._offset||0;if(!this.isValid())return null!=b?this:NaN;if(null!=b){if("string"==typeof b){if(b=Ab(Xd,b),null===b)return this}else Math.abs(b)<16&&(b=60*b);return!this._isUTC&&c&&(d=Cb(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?Tb(this,Ob(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?e:Cb(this)}function Eb(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Fb(a){return this.utcOffset(0,a)}function Gb(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Cb(this),"m")),this}function Hb(){if(null!=this._tzm)this.utcOffset(this._tzm);else if("string"==typeof this._i){var a=Ab(Wd,this._i);null!=a?this.utcOffset(a):this.utcOffset(0,!0)}return this}function Ib(a){return!!this.isValid()&&(a=a?sb(a).utcOffset():0,(this.utcOffset()-a)%60===0)}function Jb(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Kb(){if(!p(this._isDSTShifted))return this._isDSTShifted;var a={};if(q(a,this),a=pb(a),a._a){var b=a._isUTC?k(a._a):sb(a._a);this._isDSTShifted=this.isValid()&&v(a._a,b.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function Lb(){return!!this.isValid()&&!this._isUTC}function Mb(){return!!this.isValid()&&this._isUTC}function Nb(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}function Ob(a,b){var c,d,e,g=a, +// matching against regexp is expensive, do it on demand +h=null;// checks for null or undefined +return xb(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:f(a)?(g={},b?g[b]=a:g.milliseconds=a):(h=Ne.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:u(h[ce])*c,h:u(h[de])*c,m:u(h[ee])*c,s:u(h[fe])*c,ms:u(yb(1e3*h[ge]))*c}):(h=Oe.exec(a))?(c="-"===h[1]?-1:1,g={y:Pb(h[2],c),M:Pb(h[3],c),w:Pb(h[4],c),d:Pb(h[5],c),h:Pb(h[6],c),m:Pb(h[7],c),s:Pb(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=Rb(sb(g.from),sb(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new wb(g),xb(a)&&i(a,"_locale")&&(d._locale=a._locale),d}function Pb(a,b){ +// We'd normally use ~~inp for this, but unfortunately it also +// converts floats to ints. +// inp may be undefined, so careful calling replace on it. +var c=a&&parseFloat(a.replace(",",".")); +// apply sign while we're at it +return(isNaN(c)?0:c)*b}function Qb(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Rb(a,b){var c;return a.isValid()&&b.isValid()?(b=Bb(b,a),a.isBefore(b)?c=Qb(a,b):(c=Qb(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c):{milliseconds:0,months:0}} +// TODO: remove 'name' arg after deprecation is removed +function Sb(a,b){return function(c,d){var e,f; +//invert the arguments, but complain about it +return null===d||isNaN(+d)||(y(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Ob(c,d),Tb(this,e,a),this}}function Tb(b,c,d,e){var f=c._milliseconds,g=yb(c._days),h=yb(c._months);b.isValid()&&(e=null==e||e,f&&b._d.setTime(b._d.valueOf()+f*d),g&&Q(b,"Date",P(b,"Date")+g*d),h&&ja(b,P(b,"Month")+h*d),e&&a.updateOffset(b,g||h))}function Ub(a,b){var c=a.diff(b,"days",!0);return c<-6?"sameElse":c<-1?"lastWeek":c<0?"lastDay":c<1?"sameDay":c<2?"nextDay":c<7?"nextWeek":"sameElse"}function Vb(b,c){ +// We want to compare the start of today, vs this. +// Getting start-of-today depends on whether we're local/utc/offset or not. +var d=b||sb(),e=Bb(d,this).startOf("day"),f=a.calendarFormat(this,e)||"sameElse",g=c&&(z(c[f])?c[f].call(this,d):c[f]);return this.format(g||this.localeData().calendar(f,this,sb(d)))}function Wb(){return new r(this)}function Xb(a,b){var c=s(a)?a:sb(a);return!(!this.isValid()||!c.isValid())&&(b=K(p(b)?"millisecond":b),"millisecond"===b?this.valueOf()>c.valueOf():c.valueOf()f&&(b=f),Fc.call(this,a,b,c,d,e))}function Fc(a,b,c,d,e){var f=va(a,b,c,d,e),g=ta(f.year,0,f.dayOfYear);return this.year(g.getUTCFullYear()),this.month(g.getUTCMonth()),this.date(g.getUTCDate()),this} +// MOMENTS +function Gc(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)} +// HELPERS +// MOMENTS +function Hc(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function Ic(a,b){b[ge]=u(1e3*("0."+a))} +// MOMENTS +function Jc(){return this._isUTC?"UTC":""}function Kc(){return this._isUTC?"Coordinated Universal Time":""}function Lc(a){return sb(1e3*a)}function Mc(){return sb.apply(null,arguments).parseZone()}function Nc(a){return a}function Oc(a,b,c,d){var e=bb(),f=k().set(d,b);return e[c](f,a)}function Pc(a,b,c){if(f(a)&&(b=a,a=void 0),a=a||"",null!=b)return Oc(a,b,c,"month");var d,e=[];for(d=0;d<12;d++)e[d]=Oc(a,d,c,"month");return e} +// () +// (5) +// (fmt, 5) +// (fmt) +// (true) +// (true, 5) +// (true, fmt, 5) +// (true, fmt) +function Qc(a,b,c,d){"boolean"==typeof a?(f(b)&&(c=b,b=void 0),b=b||""):(b=a,c=b,a=!1,f(b)&&(c=b,b=void 0),b=b||"");var e=bb(),g=a?e._week.dow:0;if(null!=c)return Oc(b,(c+g)%7,d,"day");var h,i=[];for(h=0;h<7;h++)i[h]=Oc(b,(h+g)%7,d,"day");return i}function Rc(a,b){return Pc(a,b,"months")}function Sc(a,b){return Pc(a,b,"monthsShort")}function Tc(a,b,c){return Qc(a,b,c,"weekdays")}function Uc(a,b,c){return Qc(a,b,c,"weekdaysShort")}function Vc(a,b,c){return Qc(a,b,c,"weekdaysMin")}function Wc(){var a=this._data;return this._milliseconds=Ze(this._milliseconds),this._days=Ze(this._days),this._months=Ze(this._months),a.milliseconds=Ze(a.milliseconds),a.seconds=Ze(a.seconds),a.minutes=Ze(a.minutes),a.hours=Ze(a.hours),a.months=Ze(a.months),a.years=Ze(a.years),this}function Xc(a,b,c,d){var e=Ob(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()} +// supports only 2.0-style add(1, 's') or add(duration) +function Yc(a,b){return Xc(this,a,b,1)} +// supports only 2.0-style subtract(1, 's') or subtract(duration) +function Zc(a,b){return Xc(this,a,b,-1)}function $c(a){return a<0?Math.floor(a):Math.ceil(a)}function _c(){var a,b,c,d,e,f=this._milliseconds,g=this._days,h=this._months,i=this._data; +// if we have a mix of positive and negative values, bubble down first +// check: https://github.com/moment/moment/issues/2166 +// The following code bubbles up values, see the tests for +// examples of what that means. +// convert days to months +// 12 months -> 1 year +return f>=0&&g>=0&&h>=0||f<=0&&g<=0&&h<=0||(f+=864e5*$c(bd(h)+g),g=0,h=0),i.milliseconds=f%1e3,a=t(f/1e3),i.seconds=a%60,b=t(a/60),i.minutes=b%60,c=t(b/60),i.hours=c%24,g+=t(c/24),e=t(ad(g)),h+=e,g-=$c(bd(e)),d=t(h/12),h%=12,i.days=g,i.months=h,i.years=d,this}function ad(a){ +// 400 years have 146097 days (taking into account leap year rules) +// 400 years have 12 months === 4800 +return 4800*a/146097}function bd(a){ +// the reverse of daysToMonths +return 146097*a/4800}function cd(a){var b,c,d=this._milliseconds;if(a=K(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+ad(b),"month"===a?c:c/12;switch( +// handle milliseconds separately because of floating point math errors (issue #1867) +b=this._days+Math.round(bd(this._months)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3; +// Math.floor prevents floating point math errors here +case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}} +// TODO: Use this.as('ms')? +function dd(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*u(this._months/12)}function ed(a){return function(){return this.as(a)}}function fd(a){return a=K(a),this[a+"s"]()}function gd(a){return function(){return this._data[a]}}function hd(){return t(this.days()/7)} +// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize +function id(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function jd(a,b,c){var d=Ob(a).abs(),e=of(d.as("s")),f=of(d.as("m")),g=of(d.as("h")),h=of(d.as("d")),i=of(d.as("M")),j=of(d.as("y")),k=e0,k[4]=c,id.apply(null,k)} +// This function allows you to set the rounding function for relative time strings +function kd(a){return void 0===a?of:"function"==typeof a&&(of=a,!0)} +// This function allows you to set a threshold for relative time strings +function ld(a,b){return void 0!==pf[a]&&(void 0===b?pf[a]:(pf[a]=b,!0))}function md(a){var b=this.localeData(),c=jd(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function nd(){ +// for ISO strings we do not use the normal bubbling rules: +// * milliseconds bubble up until they become hours +// * days do not bubble at all +// * months bubble up until they become years +// This is because there is no context-free conversion between hours and days +// (think of clock changes) +// and also not between days and months (28-31 days per month) +var a,b,c,d=qf(this._milliseconds)/1e3,e=qf(this._days),f=qf(this._months); +// 3600 seconds -> 60 minutes -> 1 hour +a=t(d/60),b=t(a/60),d%=60,a%=60, +// 12 months -> 1 year +c=t(f/12),f%=12; +// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js +var g=c,h=f,i=e,j=b,k=a,l=d,m=this.asSeconds();return m?(m<0?"-":"")+"P"+(g?g+"Y":"")+(h?h+"M":"")+(i?i+"D":"")+(j||k||l?"T":"")+(j?j+"H":"")+(k?k+"M":"")+(l?l+"S":""):"P0D"}var od,pd;pd=Array.prototype.some?Array.prototype.some:function(a){for(var b=Object(this),c=b.length>>>0,d=0;d68?1900:2e3)}; +// MOMENTS +var pe=O("FullYear",!0); +// FORMATTING +U("w",["ww",2],"wo","week"),U("W",["WW",2],"Wo","isoWeek"), +// ALIASES +J("week","w"),J("isoWeek","W"), +// PRIORITIES +M("week",5),M("isoWeek",5), +// PARSING +Z("w",Od),Z("ww",Od,Kd),Z("W",Od),Z("WW",Od,Kd),ca(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=u(a)});var qe={dow:0,// Sunday is the first day of the week. +doy:6}; +// FORMATTING +U("d",0,"do","day"),U("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),U("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),U("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),U("e",0,0,"weekday"),U("E",0,0,"isoWeekday"), +// ALIASES +J("day","d"),J("weekday","e"),J("isoWeekday","E"), +// PRIORITY +M("day",11),M("weekday",11),M("isoWeekday",11), +// PARSING +Z("d",Od),Z("e",Od),Z("E",Od),Z("dd",function(a,b){return b.weekdaysMinRegex(a)}),Z("ddd",function(a,b){return b.weekdaysShortRegex(a)}),Z("dddd",function(a,b){return b.weekdaysRegex(a)}),ca(["dd","ddd","dddd"],function(a,b,c,d){var e=c._locale.weekdaysParse(a,d,c._strict); +// if we didn't get a weekday name, mark the date as invalid +null!=e?b.d=e:m(c).invalidWeekday=a}),ca(["d","e","E"],function(a,b,c,d){b[d]=u(a)}); +// LOCALES +var re="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),se="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),te="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),ue=Zd,ve=Zd,we=Zd;U("H",["HH",2],0,"hour"),U("h",["hh",2],0,Ra),U("k",["kk",2],0,Sa),U("hmm",0,0,function(){return""+Ra.apply(this)+T(this.minutes(),2)}),U("hmmss",0,0,function(){return""+Ra.apply(this)+T(this.minutes(),2)+T(this.seconds(),2)}),U("Hmm",0,0,function(){return""+this.hours()+T(this.minutes(),2)}),U("Hmmss",0,0,function(){return""+this.hours()+T(this.minutes(),2)+T(this.seconds(),2)}),Ta("a",!0),Ta("A",!1), +// ALIASES +J("hour","h"), +// PRIORITY +M("hour",13),Z("a",Ua),Z("A",Ua),Z("H",Od),Z("h",Od),Z("HH",Od,Kd),Z("hh",Od,Kd),Z("hmm",Pd),Z("hmmss",Qd),Z("Hmm",Pd),Z("Hmmss",Qd),ba(["H","HH"],de),ba(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),ba(["h","hh"],function(a,b,c){b[de]=u(a),m(c).bigHour=!0}),ba("hmm",function(a,b,c){var d=a.length-2;b[de]=u(a.substr(0,d)),b[ee]=u(a.substr(d)),m(c).bigHour=!0}),ba("hmmss",function(a,b,c){var d=a.length-4,e=a.length-2;b[de]=u(a.substr(0,d)),b[ee]=u(a.substr(d,2)),b[fe]=u(a.substr(e)),m(c).bigHour=!0}),ba("Hmm",function(a,b,c){var d=a.length-2;b[de]=u(a.substr(0,d)),b[ee]=u(a.substr(d))}),ba("Hmmss",function(a,b,c){var d=a.length-4,e=a.length-2;b[de]=u(a.substr(0,d)),b[ee]=u(a.substr(d,2)),b[fe]=u(a.substr(e))});var xe,ye=/[ap]\.?m?\.?/i,ze=O("Hours",!0),Ae={calendar:xd,longDateFormat:yd,invalidDate:zd,ordinal:Ad,ordinalParse:Bd,relativeTime:Cd,months:le,monthsShort:me,week:qe,weekdays:re,weekdaysMin:te,weekdaysShort:se,meridiemParse:ye},Be={},Ce={},De=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Ee=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Fe=/Z|[+-]\d\d(?::?\d\d)?/,Ge=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/], +// YYYYMM is NOT allowed by the standard +["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],He=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],Ie=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=x("value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}), +// constant that refers to the ISO standard +a.ISO_8601=function(){};var Je=x("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var a=sb.apply(null,arguments);return this.isValid()&&a.isValid()?athis?this:a:o()}),Le=function(){return Date.now?Date.now():+new Date};zb("Z",":"),zb("ZZ",""), +// PARSING +Z("Z",Xd),Z("ZZ",Xd),ba(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ab(Xd,a)}); +// HELPERS +// timezone chunker +// '+10:00' > ['10', '00'] +// '-1530' > ['-15', '30'] +var Me=/([\+\-]|\d\d)/gi; +// HOOKS +// This function will be called whenever a moment is mutated. +// It is intended to keep the offset in sync with the timezone. +a.updateOffset=function(){}; +// ASP.NET json date format regex +var Ne=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,Oe=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;Ob.fn=wb.prototype;var Pe=Sb(1,"add"),Qe=Sb(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",a.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Re=x("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)}); +// FORMATTING +U(0,["gg",2],0,function(){return this.weekYear()%100}),U(0,["GG",2],0,function(){return this.isoWeekYear()%100}),zc("gggg","weekYear"),zc("ggggg","weekYear"),zc("GGGG","isoWeekYear"),zc("GGGGG","isoWeekYear"), +// ALIASES +J("weekYear","gg"),J("isoWeekYear","GG"), +// PRIORITY +M("weekYear",1),M("isoWeekYear",1), +// PARSING +Z("G",Vd),Z("g",Vd),Z("GG",Od,Kd),Z("gg",Od,Kd),Z("GGGG",Sd,Md),Z("gggg",Sd,Md),Z("GGGGG",Td,Nd),Z("ggggg",Td,Nd),ca(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=u(a)}),ca(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}), +// FORMATTING +U("Q",0,"Qo","quarter"), +// ALIASES +J("quarter","Q"), +// PRIORITY +M("quarter",7), +// PARSING +Z("Q",Jd),ba("Q",function(a,b){b[be]=3*(u(a)-1)}), +// FORMATTING +U("D",["DD",2],"Do","date"), +// ALIASES +J("date","D"), +// PRIOROITY +M("date",9), +// PARSING +Z("D",Od),Z("DD",Od,Kd),Z("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),ba(["D","DD"],ce),ba("Do",function(a,b){b[ce]=u(a.match(Od)[0],10)}); +// MOMENTS +var Se=O("Date",!0); +// FORMATTING +U("DDD",["DDDD",3],"DDDo","dayOfYear"), +// ALIASES +J("dayOfYear","DDD"), +// PRIORITY +M("dayOfYear",4), +// PARSING +Z("DDD",Rd),Z("DDDD",Ld),ba(["DDD","DDDD"],function(a,b,c){c._dayOfYear=u(a)}), +// FORMATTING +U("m",["mm",2],0,"minute"), +// ALIASES +J("minute","m"), +// PRIORITY +M("minute",14), +// PARSING +Z("m",Od),Z("mm",Od,Kd),ba(["m","mm"],ee); +// MOMENTS +var Te=O("Minutes",!1); +// FORMATTING +U("s",["ss",2],0,"second"), +// ALIASES +J("second","s"), +// PRIORITY +M("second",15), +// PARSING +Z("s",Od),Z("ss",Od,Kd),ba(["s","ss"],fe); +// MOMENTS +var Ue=O("Seconds",!1); +// FORMATTING +U("S",0,0,function(){return~~(this.millisecond()/100)}),U(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),U(0,["SSS",3],0,"millisecond"),U(0,["SSSS",4],0,function(){return 10*this.millisecond()}),U(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),U(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),U(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),U(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),U(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}), +// ALIASES +J("millisecond","ms"), +// PRIORITY +M("millisecond",16), +// PARSING +Z("S",Rd,Jd),Z("SS",Rd,Kd),Z("SSS",Rd,Ld);var Ve;for(Ve="SSSS";Ve.length<=9;Ve+="S")Z(Ve,Ud);for(Ve="S";Ve.length<=9;Ve+="S")ba(Ve,Ic); +// MOMENTS +var We=O("Milliseconds",!1); +// FORMATTING +U("z",0,0,"zoneAbbr"),U("zz",0,0,"zoneName");var Xe=r.prototype;Xe.add=Pe,Xe.calendar=Vb,Xe.clone=Wb,Xe.diff=bc,Xe.endOf=oc,Xe.format=gc,Xe.from=hc,Xe.fromNow=ic,Xe.to=jc,Xe.toNow=kc,Xe.get=R,Xe.invalidAt=xc,Xe.isAfter=Xb,Xe.isBefore=Yb,Xe.isBetween=Zb,Xe.isSame=$b,Xe.isSameOrAfter=_b,Xe.isSameOrBefore=ac,Xe.isValid=vc,Xe.lang=Re,Xe.locale=lc,Xe.localeData=mc,Xe.max=Ke,Xe.min=Je,Xe.parsingFlags=wc,Xe.set=S,Xe.startOf=nc,Xe.subtract=Qe,Xe.toArray=sc,Xe.toObject=tc,Xe.toDate=rc,Xe.toISOString=ec,Xe.inspect=fc,Xe.toJSON=uc,Xe.toString=dc,Xe.unix=qc,Xe.valueOf=pc,Xe.creationData=yc, +// Year +Xe.year=pe,Xe.isLeapYear=ra, +// Week Year +Xe.weekYear=Ac,Xe.isoWeekYear=Bc, +// Quarter +Xe.quarter=Xe.quarters=Gc, +// Month +Xe.month=ka,Xe.daysInMonth=la, +// Week +Xe.week=Xe.weeks=Ba,Xe.isoWeek=Xe.isoWeeks=Ca,Xe.weeksInYear=Dc,Xe.isoWeeksInYear=Cc, +// Day +Xe.date=Se,Xe.day=Xe.days=Ka,Xe.weekday=La,Xe.isoWeekday=Ma,Xe.dayOfYear=Hc, +// Hour +Xe.hour=Xe.hours=ze, +// Minute +Xe.minute=Xe.minutes=Te, +// Second +Xe.second=Xe.seconds=Ue, +// Millisecond +Xe.millisecond=Xe.milliseconds=We, +// Offset +Xe.utcOffset=Db,Xe.utc=Fb,Xe.local=Gb,Xe.parseZone=Hb,Xe.hasAlignedHourOffset=Ib,Xe.isDST=Jb,Xe.isLocal=Lb,Xe.isUtcOffset=Mb,Xe.isUtc=Nb,Xe.isUTC=Nb, +// Timezone +Xe.zoneAbbr=Jc,Xe.zoneName=Kc, +// Deprecations +Xe.dates=x("dates accessor is deprecated. Use date instead.",Se),Xe.months=x("months accessor is deprecated. Use month instead",ka),Xe.years=x("years accessor is deprecated. Use year instead",pe),Xe.zone=x("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",Eb),Xe.isDSTShifted=x("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",Kb);var Ye=C.prototype;Ye.calendar=D,Ye.longDateFormat=E,Ye.invalidDate=F,Ye.ordinal=G,Ye.preparse=Nc,Ye.postformat=Nc,Ye.relativeTime=H,Ye.pastFuture=I,Ye.set=A, +// Month +Ye.months=fa,Ye.monthsShort=ga,Ye.monthsParse=ia,Ye.monthsRegex=na,Ye.monthsShortRegex=ma, +// Week +Ye.week=ya,Ye.firstDayOfYear=Aa,Ye.firstDayOfWeek=za, +// Day of Week +Ye.weekdays=Fa,Ye.weekdaysMin=Ha,Ye.weekdaysShort=Ga,Ye.weekdaysParse=Ja,Ye.weekdaysRegex=Na,Ye.weekdaysShortRegex=Oa,Ye.weekdaysMinRegex=Pa, +// Hours +Ye.isPM=Va,Ye.meridiem=Wa,$a("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===u(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}), +// Side effect imports +a.lang=x("moment.lang is deprecated. Use moment.locale instead.",$a),a.langData=x("moment.langData is deprecated. Use moment.localeData instead.",bb);var Ze=Math.abs,$e=ed("ms"),_e=ed("s"),af=ed("m"),bf=ed("h"),cf=ed("d"),df=ed("w"),ef=ed("M"),ff=ed("y"),gf=gd("milliseconds"),hf=gd("seconds"),jf=gd("minutes"),kf=gd("hours"),lf=gd("days"),mf=gd("months"),nf=gd("years"),of=Math.round,pf={s:45,// seconds to minute +m:45,// minutes to hour +h:22,// hours to day +d:26,// days to month +M:11},qf=Math.abs,rf=wb.prototype; +// Deprecations +// Side effect imports +// FORMATTING +// PARSING +// Side effect imports +return rf.abs=Wc,rf.add=Yc,rf.subtract=Zc,rf.as=cd,rf.asMilliseconds=$e,rf.asSeconds=_e,rf.asMinutes=af,rf.asHours=bf,rf.asDays=cf,rf.asWeeks=df,rf.asMonths=ef,rf.asYears=ff,rf.valueOf=dd,rf._bubble=_c,rf.get=fd,rf.milliseconds=gf,rf.seconds=hf,rf.minutes=jf,rf.hours=kf,rf.days=lf,rf.weeks=hd,rf.months=mf,rf.years=nf,rf.humanize=md,rf.toISOString=nd,rf.toString=nd,rf.toJSON=nd,rf.locale=lc,rf.localeData=mc,rf.toIsoString=x("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",nd),rf.lang=Re,U("X",0,0,"unix"),U("x",0,0,"valueOf"),Z("x",Vd),Z("X",Yd),ba("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),ba("x",function(a,b,c){c._d=new Date(u(a))}),a.version="2.17.1",b(sb),a.fn=Xe,a.min=ub,a.max=vb,a.now=Le,a.utc=k,a.unix=Lc,a.months=Rc,a.isDate=g,a.locale=$a,a.invalid=o,a.duration=Ob,a.isMoment=s,a.weekdays=Tc,a.parseZone=Mc,a.localeData=bb,a.isDuration=xb,a.monthsShort=Sc,a.weekdaysMin=Vc,a.defineLocale=_a,a.updateLocale=ab,a.locales=cb,a.weekdaysShort=Uc,a.normalizeUnits=K,a.relativeTimeRounding=kd,a.relativeTimeThreshold=ld,a.calendarFormat=Ub,a.prototype=Xe,a}); \ No newline at end of file diff --git a/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml b/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml new file mode 100644 index 000000000..630ff1ace --- /dev/null +++ b/hotel_calendar/static/src/xml/hotel_calendar_management_view.xml @@ -0,0 +1,94 @@ + + + + +
+
+ +
+
+
+
+ + + diff --git a/hotel_calendar/static/src/xml/hotel_calendar_templates.xml b/hotel_calendar/static/src/xml/hotel_calendar_templates.xml new file mode 100644 index 000000000..736f677bf --- /dev/null +++ b/hotel_calendar/static/src/xml/hotel_calendar_templates.xml @@ -0,0 +1,168 @@ + diff --git a/hotel_calendar/static/src/xml/hotel_calendar_view.xml b/hotel_calendar/static/src/xml/hotel_calendar_view.xml new file mode 100644 index 000000000..ed12414fc --- /dev/null +++ b/hotel_calendar/static/src/xml/hotel_calendar_view.xml @@ -0,0 +1,101 @@ + + + + +
+ +
+ +
+
+ +
+

Loading Calendar...

+
+
+
+
+
+
+ + + diff --git a/hotel_calendar/tests/__init__.py b/hotel_calendar/tests/__init__.py new file mode 100644 index 000000000..d770a5fe1 --- /dev/null +++ b/hotel_calendar/tests/__init__.py @@ -0,0 +1,5 @@ +# -*- coding: utf-8 -*- + +from . import test_reservations_calendar +from . import test_management_calendar +from . import test_product_pricelist diff --git a/hotel_calendar/tests/common.py b/hotel_calendar/tests/common.py new file mode 100644 index 000000000..7b3f0cccd --- /dev/null +++ b/hotel_calendar/tests/common.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from odoo.addons.hotel.tests.common import TestHotel + + +class TestHotelCalendar(TestHotel): + + @classmethod + def setUpClass(cls): + super(TestHotelCalendar, cls).setUpClass() + + # Minimal Hotel Calendar Configuration + cls.tz_hotel = 'Europe/Madrid' + cls.parity_pricelist_id = cls.pricelist_1.id + cls.parity_restrictions_id = cls.restriction_1.id + cls.env['ir.default'].sudo().set_default('res.config.settings', + 'default_arrival_hour', + '14:00') + cls.env['ir.default'].sudo().set_default('res.config.settings', + 'default_departure_hour', + '12:00') diff --git a/hotel_calendar/tests/test_management_calendar.py b/hotel_calendar/tests/test_management_calendar.py new file mode 100644 index 000000000..f959b0f80 --- /dev/null +++ b/hotel_calendar/tests/test_management_calendar.py @@ -0,0 +1,425 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from openerp.exceptions import ValidationError +from .common import TestHotelCalendar +from odoo.addons.hotel import date_utils +import logging +_logger = logging.getLogger(__name__) + + +class TestManagementCalendar(TestHotelCalendar): + + def test_calendar_prices(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=15) + + vrooms = (self.hotel_vroom_budget, self.hotel_vroom_special) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['prices'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + if k_info >= len(self.prices_tmp[vroom.id]): + break + self.assertEqual(v_info['price'], + self.prices_tmp[vroom.id][k_info], + "Hotel Calendar Management Prices \ + doesn't match!") + + # REMOVE PRICES + prices_obj = self.env['product.pricelist.item'].sudo( + self.user_hotel_manager) + prod_tmpl_ids = ( + self.hotel_vroom_budget.product_id.product_tmpl_id.id, + self.hotel_vroom_special.product_id.product_tmpl_id.id + ) + pr_ids = prices_obj.search([ + ('pricelist_id', '=', self.parity_pricelist_id), + ('product_tmpl_id', 'in', prod_tmpl_ids), + ]) + pr_ids.sudo(self.user_hotel_manager).unlink() + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + self.assertFalse(any(hcal_data['prices']), "Hotel Calendar Management \ + Prices doesn't match after remove!") + + def test_calendar_restrictions(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=15) + vrooms = (self.hotel_vroom_budget, self.hotel_vroom_special) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['restrictions'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + rest_items = self.restrictions_min_stay_tmp[vroom.id] + if k_info >= len(rest_items): + break + self.assertEqual( + v_info['min_stay'], + self.restrictions_min_stay_tmp[vroom.id][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + + # REMOVE RESTRICTIONS + rest_it_obj = self.env['hotel.virtual.room.restriction.item'].sudo( + self.user_hotel_manager) + rest_ids = rest_it_obj.search([ + ('applied_on', '=', '0_virtual_room'), + ('restriction_id', '=', self.parity_restrictions_id), + ('virtual_room_id', 'in', (self.hotel_vroom_budget.id, + self.hotel_vroom_special.id)), + ]) + rest_ids.sudo(self.user_hotel_manager).unlink() + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + self.assertFalse( + any(hcal_data['restrictions']), + "Hotel Calendar Management Restrictions doesn't match \ + after remove!") + + def test_calendar_availability(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=6) + vrooms = (self.hotel_vroom_budget, self.hotel_vroom_special) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + vroom_avail_obj = self.env['hotel.virtual.room.availability'].sudo( + self.user_hotel_manager) + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['availability'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + if k_info >= len(self.avails_tmp[vroom.id]): + break + self.assertEqual( + v_info['avail'], + self.avails_tmp[vroom.id][k_info], + "Hotel Calendar Management Availability \ + doesn't match!") + + # CHANGE AVAIL + avail_ids = vroom_avail_obj.search([ + ('virtual_room_id', 'in', (self.hotel_vroom_budget.id, + self.hotel_vroom_special.id)), + ]) + for avail_id in avail_ids: + avail_id.sudo(self.user_hotel_manager).write({'avail': 1}) + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['availability'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual( + v_info['avail'], + 1, + "Hotel Calendar Management Availability \ + doesn't match!") + + # REMOVE AVAIL + avail_ids = vroom_avail_obj.search([ + ('virtual_room_id', 'in', (self.hotel_vroom_budget.id, + self.hotel_vroom_special.id)), + ]) + avail_ids.sudo(self.user_hotel_manager).unlink() + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['availability'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual( + v_info['avail'], + vroom.max_real_rooms, + "Hotel Calendar Management Availability \ + doesn't match!") + + def test_save_changes(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=3) + vrooms = (self.hotel_vroom_budget,) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + + # Generate new prices + prices = (144.0, 170.0, 30.0, 50.0) + cprices = {} + for k_item, v_item in enumerate(prices): + ndate_utc_dt = now_utc_dt + timedelta(days=k_item) + cprices.setdefault(self.hotel_vroom_budget.id, []).append({ + 'date': ndate_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'price': v_item + }) + + # Generate new restrictions + restrictions = { + 'min_stay': (3, 2, 4, 1), + 'max_stay': (5, 8, 9, 3), + 'min_stay_arrival': (2, 3, 6, 2), + 'max_stay_arrival': (4, 7, 7, 4), + 'closed_departure': (False, True, False, True), + 'closed_arrival': (True, False, False, False), + 'closed': (False, False, True, True), + } + crestrictions = {} + for i in range(0, 4): + ndate_utc_dt = now_utc_dt + timedelta(days=i) + crestrictions.setdefault(self.hotel_vroom_budget.id, []).append({ + 'date': ndate_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'closed_arrival': restrictions['closed_arrival'][i], + 'max_stay': restrictions['max_stay'][i], + 'min_stay': restrictions['min_stay'][i], + 'closed_departure': restrictions['closed_departure'][i], + 'closed': restrictions['closed'][i], + 'min_stay_arrival': restrictions['min_stay_arrival'][i], + 'max_stay_arrival': restrictions['max_stay_arrival'][i], + }) + + # Generate new availability + avails = (1, 2, 2, 1) + cavails = {} + for k_item, v_item in enumerate(avails): + ndate_utc_dt = now_utc_dt + timedelta(days=k_item) + ndate_dt = date_utils.dt_as_timezone(ndate_utc_dt, self.tz_hotel) + cavails.setdefault(self.hotel_vroom_budget.id, []).append({ + 'date': ndate_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + 'avail': v_item, + 'no_ota': False, + }) + + # Save new values + hotel_cal_mngt_obj.save_changes( + self.parity_pricelist_id, + self.parity_restrictions_id, + cprices, + crestrictions, + cavails) + + # Check data integrity + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + + for vroom in vrooms: + for k_pr, v_pr in hcal_data['availability'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual(v_info['avail'], + avails[k_info], + "Hotel Calendar Management \ + Availability doesn't match!") + for k_pr, v_pr in hcal_data['restrictions'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual(v_info['min_stay'], + restrictions['min_stay'][k_info], + "Hotel Calendar Management \ + Restrictions doesn't match!") + self.assertEqual(v_info['max_stay'], + restrictions['max_stay'][k_info], + "Hotel Calendar Management \ + Restrictions doesn't match!") + self.assertEqual( + v_info['min_stay_arrival'], + restrictions['min_stay_arrival'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['max_stay_arrival'], + restrictions['max_stay_arrival'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['closed_departure'], + restrictions['closed_departure'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['closed_arrival'], + restrictions['closed_arrival'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['closed'], + restrictions['closed'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + for k_pr, v_pr in hcal_data['prices'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual(v_info['price'], + prices[k_info], "Hotel Calendar \ + Management Prices doesn't match!") + + def test_calendar_reservations(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=15) + vrooms = (self.hotel_vroom_budget,) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + + reserv_start_utc_dt = now_utc_dt + timedelta(days=3) + reserv_end_utc_dt = reserv_start_utc_dt + timedelta(days=3) + folio = self.create_folio(self.user_hotel_manager, self.partner_2) + reservation = self.create_reservation( + self.user_hotel_manager, + folio, + reserv_start_utc_dt, + reserv_end_utc_dt, + self.hotel_room_simple_100, + "Reservation Test #1") + + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + + avail_end_utc_dt = reserv_end_utc_dt - timedelta(days=1) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['count_reservations'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + ndate = date_utils.get_datetime(v_info['date']) + if date_utils.date_in(ndate, + reserv_start_utc_dt, + avail_end_utc_dt) == 0: + self.assertEqual(v_info['num'], + 1, + "Hotel Calendar Management \ + Availability doesn't match!") + + def test_invalid_input_calendar_data(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=15) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + + with self.assertRaises(ValidationError): + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + False, + adv_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + with self.assertRaises(ValidationError): + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + False, + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + with self.assertRaises(ValidationError): + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + False, + False, + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + False, + False, + True) + self.assertTrue(any(hcal_data), "Hotel Calendar invalid default \ + management parity models!") + + def test_calendar_settings(self): + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + settings = hotel_cal_mngt_obj.get_hcalendar_settings() + self.assertTrue(settings, "Hotel Calendar invalid settings") + + self.assertEqual(settings['eday_week'], + self.user_hotel_manager.npms_end_day_week, + "Hotel Calendar invalid settings") + self.assertEqual(settings['eday_week_offset'], + self.user_hotel_manager.npms_end_day_week_offset, + "Hotel Calendar invalid settings") + self.assertEqual(settings['days'], + self.user_hotel_manager.npms_default_num_days, + "Hotel Calendar invalid settings") + self.assertEqual(settings['show_notifications'], + self.user_hotel_manager.pms_show_notifications, + "Hotel Calendar invalid settings") + self.assertEqual(settings['show_num_rooms'], + self.user_hotel_manager.pms_show_num_rooms, + "Hotel Calendar invalid settings") diff --git a/hotel_calendar/tests/test_product_pricelist.py b/hotel_calendar/tests/test_product_pricelist.py new file mode 100644 index 000000000..333442732 --- /dev/null +++ b/hotel_calendar/tests/test_product_pricelist.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2018 Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.tools import DEFAULT_SERVER_DATE_FORMAT +from .common import TestHotelCalendar +from odoo.addons.hotel import date_utils + + +class TestProductPricelist(TestHotelCalendar): + + def test_update_price(self): + now_utc_dt = date_utils.now() + now_utc_str = now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT) + + vroom_tmpl_id = self.hotel_vroom_special.product_id.product_tmpl_id + + pritem_obj = self.env['product.pricelist.item'] + plitem = pritem_obj.search([ + ('pricelist_id', '=', self.parity_pricelist_id), + ('product_tmpl_id', '=', vroom_tmpl_id.id), + ('date_start', '=', now_utc_str), + ('date_end', '=', now_utc_str), + ('applied_on', '=', '1_product'), + ('compute_price', '=', 'fixed') + ]) + old_price = plitem.fixed_price + + self.pricelist_1.update_price( + self.hotel_vroom_special.id, + now_utc_str, + 999.9) + + plitem = pritem_obj.search([ + ('pricelist_id', '=', self.parity_pricelist_id), + ('product_tmpl_id', '=', vroom_tmpl_id.id), + ('date_start', '=', now_utc_str), + ('date_end', '=', now_utc_str), + ('applied_on', '=', '1_product'), + ('compute_price', '=', 'fixed') + ]) + new_price = plitem.fixed_price + + self.assertNotEqual(old_price, + new_price, + "Hotel Calendar can't change price") + self.assertEqual(new_price, + 999.9, + "Hotel Calendar can't change price") diff --git a/hotel_calendar/tests/test_reservations_calendar.py b/hotel_calendar/tests/test_reservations_calendar.py new file mode 100644 index 000000000..1cbc497ad --- /dev/null +++ b/hotel_calendar/tests/test_reservations_calendar.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +import datetime +from datetime import timedelta +from odoo import fields +from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT +from openerp.exceptions import ValidationError +from .common import TestHotelCalendar +from odoo.addons.hotel import date_utils +import pytz + + +class TestReservationsCalendar(TestHotelCalendar): + + def test_calendar_pricelist(self): + now_utc_dt = date_utils.now() + real_start_utc_dt = (now_utc_dt - timedelta(days=1)) + adv_utc_dt = now_utc_dt + timedelta(days=15) + + hotel_reserv_obj = self.env['hotel.reservation'].sudo( + self.user_hotel_manager) + + hcal_data = hotel_reserv_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) + + # Check Pricelist Integrity + for k_pr, v_pr in hcal_data['pricelist'].iteritems(): + for vroom_pr in v_pr: + # Only Check Test Cases + if vroom_pr['room'] in self.prices_tmp.keys(): + sorted_dates = sorted( + vroom_pr['days'].keys(), + key=lambda x: datetime.datetime.strptime(x, '%d/%m/%Y') + ) + init_date_dt = datetime.datetime.strptime( + sorted_dates[0], + '%d/%m/%Y').replace(tzinfo=pytz.utc) + end_date_dt = datetime.datetime.strptime( + sorted_dates[-1], + '%d/%m/%Y').replace(tzinfo=pytz.utc) + + self.assertEqual(real_start_utc_dt, init_date_dt, + "Hotel Calendar don't start in \ + the correct date!") + self.assertEqual(adv_utc_dt, end_date_dt, + "Hotel Calendar don't end in \ + the correct date!") + + vroom_prices = self.prices_tmp[vroom_pr['room']] + for k_price, v_price in enumerate(vroom_prices): + self.assertEqual( + v_price, + vroom_pr['days'][sorted_dates[k_price+1]], + "Hotel Calendar Pricelist doesn't match!") + + # Check Pricelist Integrity after unlink + pricelist_item_obj = self.env['product.pricelist.item'].sudo( + self.user_hotel_manager) + pr_ids = pricelist_item_obj.search([ + ('pricelist_id', '=', self.parity_pricelist_id), + ('product_tmpl_id', 'in', ( + self.hotel_vroom_budget.product_id.product_tmpl_id.id, + self.hotel_vroom_special.product_id.product_tmpl_id.id)), + ]) + pr_ids.sudo(self.user_hotel_manager).unlink() + reserv_obj = self.env['hotel.reservation'].sudo( + self.user_hotel_manager) + hcal_data = reserv_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) + vrooms = (self.hotel_vroom_budget, self.hotel_vroom_special) + for vroom in vrooms: + for k_pr, v_pr in hcal_data['pricelist'].iteritems(): + for vroom_pr in v_pr: + if vroom_pr['room'] == vroom.id: # Only Check Test Cases + self.assertEqual( + vroom.list_price, + vroom_pr['days'][sorted_dates[k_price+1]], + "Hotel Calendar Pricelist doesn't \ + match after remove!") + + def test_calendar_reservations(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=15) + + hotel_reserv_obj = self.env['hotel.reservation'].sudo( + self.user_hotel_manager) + + def is_reservation_listed(reservation_id): + hcal_data = hotel_reserv_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) + # TODO: Perhaps not the best way to do this test... :/ + hasReservationTest = False + for reserv in hcal_data['reservations']: + if reserv[1] == reservation_id: + hasReservationTest = True + break + return hasReservationTest + + # CREATE COMPLETE RESERVATION (3 Nigths) + reserv_start_utc_dt = now_utc_dt + timedelta(days=3) + reserv_end_utc_dt = reserv_start_utc_dt + timedelta(days=3) + folio = self.create_folio(self.user_hotel_manager, self.partner_2) + reservation = self.create_reservation( + self.user_hotel_manager, + folio, + reserv_start_utc_dt, + reserv_end_utc_dt, + self.hotel_room_double_200, + "Reservation Test #1") + + # CHECK SUCCESSFULL CREATION + self.assertTrue(is_reservation_listed(reservation.id), + "Hotel Calendar can't found test reservation!") + + # CONFIRM FOLIO + folio.sudo(self.user_hotel_manager).action_confirm() + self.assertTrue(is_reservation_listed(reservation.id), + "Hotel Calendar can't found test reservation!") + + # CALENDAR LIMITS + now_utc_dt_tmp = now_utc_dt + adv_utc_dt_tmp = adv_utc_dt + # Start after reservation end + now_utc_dt = reserv_end_utc_dt + timedelta(days=2) + adv_utc_dt = now_utc_dt + timedelta(days=15) + self.assertFalse( + is_reservation_listed(reservation.id), + "Hotel Calendar found test reservation but expected not found it!") + + # Ends before reservation start + adv_utc_dt = reserv_start_utc_dt - timedelta(days=1) + now_utc_dt = adv_utc_dt - timedelta(days=15) + self.assertFalse( + is_reservation_listed(reservation.id), + "Hotel Calendar found test reservation but expected not found it!") + now_utc_dt = now_utc_dt_tmp + adv_utc_dt = adv_utc_dt_tmp + + # Start in the middle of the reservation days + now_utc_dt = reserv_end_utc_dt - timedelta(days=1) + adv_utc_dt = now_utc_dt + timedelta(days=15) + self.assertTrue( + is_reservation_listed(reservation.id), + "Hotel Calendar can't found test reservation!") + now_utc_dt = now_utc_dt_tmp + adv_utc_dt = adv_utc_dt_tmp + + # CANCEL FOLIO + folio.sudo(self.user_hotel_manager).action_cancel() + self.assertFalse( + is_reservation_listed(reservation.id), + "Hotel Calendar can't found test reservation!") + + # REMOVE FOLIO + folio.sudo().unlink() # FIXME: Can't use: self.user_hotel_manager + self.assertFalse( + is_reservation_listed(reservation.id), + "Hotel Calendar can't found test reservation!") + + def test_invalid_input_calendar_data(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=15) + + hotel_reserv_obj = self.env['hotel.reservation'].sudo( + self.user_hotel_manager) + + with self.assertRaises(ValidationError): + hcal_data = hotel_reserv_obj.get_hcalendar_all_data( + False, + adv_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) + with self.assertRaises(ValidationError): + hcal_data = hotel_reserv_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + False) + with self.assertRaises(ValidationError): + hcal_data = hotel_reserv_obj.get_hcalendar_all_data( + False, + False) + + def test_calendar_settings(self): + hcal_options = self.env['hotel.reservation'].sudo( + self.user_hotel_manager).get_hcalendar_settings() + + self.assertEqual(hcal_options['divide_rooms_by_capacity'], + self.user_hotel_manager.pms_divide_rooms_by_capacity, + "Hotel Calendar Invalid Options!") + self.assertEqual(hcal_options['eday_week'], + self.user_hotel_manager.pms_end_day_week, + "Hotel Calendar Invalid Options!") + self.assertEqual(hcal_options['days'], + self.user_hotel_manager.pms_default_num_days, + "Hotel Calendar Invalid Options!") + self.assertEqual( + hcal_options['allow_invalid_actions'], + self.user_hotel_manager.pms_type_move == 'allow_invalid', + "Hotel Calendar Invalid Options!") + self.assertEqual( + hcal_options['assisted_movement'], + self.user_hotel_manager.pms_type_move == 'assisted', + "Hotel Calendar Invalid Options!") + default_arrival_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_arrival_hour') + self.assertEqual(hcal_options['default_arrival_hour'], + default_arrival_hour, + "Hotel Calendar Invalid Options!") + default_departure_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_departure_hour') + self.assertEqual(hcal_options['default_departure_hour'], + default_departure_hour, + "Hotel Calendar Invalid Options!") + self.assertEqual(hcal_options['show_notifications'], + self.user_hotel_manager.pms_show_notifications, + "Hotel Calendar Invalid Options!") + self.assertEqual(hcal_options['show_num_rooms'], + self.user_hotel_manager.pms_show_num_rooms, + "Hotel Calendar Invalid Options!") + self.assertEqual(hcal_options['show_pricelist'], + self.user_hotel_manager.pms_show_pricelist, + "Hotel Calendar Invalid Options!") + self.assertEqual(hcal_options['show_availability'], + self.user_hotel_manager.pms_show_availability, + "Hotel Calendar Invalid Options!") + + def test_swap_reservation(self): + hcal_reserv_obj = self.env['hotel.reservation'].sudo( + self.user_hotel_manager) + now_utc_dt = date_utils.now() + + # CREATE RESERVATIONS + reserv_start_utc_dt = now_utc_dt + timedelta(days=3) + reserv_end_utc_dt = reserv_start_utc_dt + timedelta(days=3) + folio_a = self.create_folio(self.user_hotel_manager, self.partner_2) + reservation_a = self.create_reservation( + self.user_hotel_manager, + folio_a, + reserv_start_utc_dt, + reserv_end_utc_dt, + self.hotel_room_double_200, + "Reservation Test #1") + self.assertTrue(reservation_a, + "Hotel Calendar create test reservation!") + folio_a.sudo(self.user_hotel_manager).action_confirm() + + folio_b = self.create_folio(self.user_hotel_manager, self.partner_2) + reservation_b = self.create_reservation( + self.user_hotel_manager, + folio_b, + reserv_start_utc_dt, + reserv_end_utc_dt, + self.hotel_room_simple_101, + "Reservation Test #2") + self.assertTrue(reservation_b, + "Hotel Calendar can't create test reservation!") + folio_b.sudo(self.user_hotel_manager).action_confirm() + + self.assertTrue( + hcal_reserv_obj.swap_reservations(reservation_a.ids, + reservation_b.ids), + "Hotel Calendar invalid swap operation" + ) + self.assertEqual(reservation_a.product_id.id, + self.hotel_room_simple_101.product_id.id, + "Hotel Calendar wrong swap operation") + self.assertEqual(reservation_b.product_id.id, + self.hotel_room_double_200.product_id.id, + "Hotel Calendar wrong swap operation") diff --git a/hotel_calendar/views/actions.xml b/hotel_calendar/views/actions.xml new file mode 100644 index 000000000..ea479919c --- /dev/null +++ b/hotel_calendar/views/actions.xml @@ -0,0 +1,27 @@ + + + + + Hotel folio checkin + hotel.reservation + form + tree,form + [('is_checkin','=', True)] + + + + Hotel folio checkout + hotel.reservation + form + tree,form + [('is_checkout','=', True)] + + + + Virtual Room Pricelist Cached + virtual.room.pricelist.cached + form + tree,form + + + diff --git a/hotel_calendar/views/general.xml b/hotel_calendar/views/general.xml new file mode 100644 index 000000000..5b3ab3d38 --- /dev/null +++ b/hotel_calendar/views/general.xml @@ -0,0 +1,32 @@ + + + + + + + + + + diff --git a/hotel_calendar/views/inherited_hotel_room_views.xml b/hotel_calendar/views/inherited_hotel_room_views.xml new file mode 100644 index 000000000..b5e45a354 --- /dev/null +++ b/hotel_calendar/views/inherited_hotel_room_views.xml @@ -0,0 +1,14 @@ + + + + + hotel.room + + + + + + + + + diff --git a/hotel_calendar/views/inherited_hotel_virtual_room_views.xml b/hotel_calendar/views/inherited_hotel_virtual_room_views.xml new file mode 100644 index 000000000..57505f6a0 --- /dev/null +++ b/hotel_calendar/views/inherited_hotel_virtual_room_views.xml @@ -0,0 +1,14 @@ + + + + + hotel.virtual.room + + + + + + + + + diff --git a/hotel_calendar/views/inherited_res_users_views.xml b/hotel_calendar/views/inherited_res_users_views.xml new file mode 100644 index 000000000..3d3c18772 --- /dev/null +++ b/hotel_calendar/views/inherited_res_users_views.xml @@ -0,0 +1,43 @@ + + + + + res.users + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hotel_calendar/views/res_config_views.xml b/hotel_calendar/views/res_config_views.xml new file mode 100644 index 000000000..a3549f08b --- /dev/null +++ b/hotel_calendar/views/res_config_views.xml @@ -0,0 +1,35 @@ + + + + + + res.config.settings.view.form.inherit.hotel + res.config.settings + + + + +
+

Calendar colors

+
+
+ + + + + +
+
+ + + + + +
+
+
+
+
+
+ +
diff --git a/hotel_calendar/views/virtual_room_pricelist_cached_views.xml b/hotel_calendar/views/virtual_room_pricelist_cached_views.xml new file mode 100644 index 000000000..18e79643b --- /dev/null +++ b/hotel_calendar/views/virtual_room_pricelist_cached_views.xml @@ -0,0 +1,35 @@ + + + + + + + hotel.virtual.room.pricelist.cached.form + virtual.room.pricelist.cached + +
+ + + + + + + +
+
+
+ + + + hotel.virtual.room.pricelist.cached.tree + virtual.room.pricelist.cached + + + + + + + + + +
diff --git a/hotel_calendar/wizard/__init__.py b/hotel_calendar/wizard/__init__.py new file mode 100644 index 000000000..cc636fed6 --- /dev/null +++ b/hotel_calendar/wizard/__init__.py @@ -0,0 +1 @@ +from . import wizard_reservation \ No newline at end of file diff --git a/hotel_calendar/wizard/wizard_reservation.py b/hotel_calendar/wizard/wizard_reservation.py new file mode 100644 index 000000000..35c0ca159 --- /dev/null +++ b/hotel_calendar/wizard/wizard_reservation.py @@ -0,0 +1,584 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +import pytz +import time +import logging +from decimal import Decimal +from dateutil.relativedelta import relativedelta +from datetime import datetime, timedelta, date +from openerp.exceptions import except_orm, UserError, ValidationError +from openerp.tools import ( + misc, + DEFAULT_SERVER_DATE_FORMAT, + DEFAULT_SERVER_DATETIME_FORMAT) +from openerp import models, fields, api, _ +from odoo.addons.hotel import date_utils +import odoo.addons.decimal_precision as dp +_logger = logging.getLogger(__name__) + + +class FolioWizard(models.TransientModel): + _name = 'hotel.folio.wizard' + + @api.model + def _get_default_center_user(self): + user = self.env['res.users'].browse(self.env.uid) + return user.has_group('hotel.group_hotel_call') + + @api.model + def _get_default_checkin(self): + folio = False + default_arrival_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_arrival_hour') + if 'folio_id' in self._context: + folio = self.env['hotel.folio'].search([ + ('id', '=', self._context['folio_id']) + ]) + if folio and folio.room_lines: + return folio.room_lines[0].checkin + else: + tz_hotel = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'tz_hotel') + now_utc_dt = date_utils.now() + ndate = "%s %s:00" % \ + (now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + default_arrival_hour) + ndate_dt = date_utils.get_datetime(ndate, stz=tz_hotel) + ndate_dt = date_utils.dt_as_timezone(ndate_dt, 'UTC') + return ndate_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + + @api.model + def _get_default_checkout(self): + folio = False + default_departure_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_departure_hour') + if 'folio_id' in self._context: + folio = self.env['hotel.folio'].search([ + ('id', '=', self._context['folio_id']) + ]) + if folio and folio.room_lines: + return folio.room_lines[0].checkout + else: + tz_hotel = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'tz_hotel') + now_utc_dt = date_utils.now() + timedelta(days=1) + ndate = "%s %s:00" % \ + (now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + default_departure_hour) + ndate_dt = date_utils.get_datetime(ndate, stz=tz_hotel) + ndate_dt = date_utils.dt_as_timezone(ndate_dt, 'UTC') + return ndate_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + + @api.model + def _get_default_channel_type(self): + user = self.env['res.users'].browse(self.env.uid) + if user.has_group('hotel.group_hotel_call'): + return 'phone' + + partner_id = fields.Many2one('res.partner',string="Customer") + checkin = fields.Datetime('Check In', required=True, + default=_get_default_checkin) + checkout = fields.Datetime('Check Out', required=True, + default=_get_default_checkout) + reservation_wizard_ids = fields.One2many('hotel.reservation.wizard', + 'folio_wizard_id', + string="Resevations") + service_wizard_ids = fields.One2many('hotel.service.wizard', + 'folio_wizard_id', + string='Services') + total = fields.Float('Total', compute='_computed_total') + confirm = fields.Boolean('Confirm Reservations', default="1") + autoassign = fields.Boolean('Autoassign', default="1") + channel_type = fields.Selection([ + ('door', 'Door'), + ('mail', 'Mail'), + ('phone', 'Phone') + ], string='Sales Channel', default=_get_default_channel_type) + virtual_room_wizard_ids = fields.Many2many('hotel.virtual.room.wizard', + string="Virtual Rooms") + call_center = fields.Boolean(default=_get_default_center_user) + + def assign_rooms(self): + self.assign=True + + @api.onchange('autoassign') + def create_reservations(self): + self.ensure_one() + total = 0 + cmds = [] + for line in self.virtual_room_wizard_ids: + if line.rooms_num == 0: + continue + if line.rooms_num > line.max_rooms: + raise ValidationError(_("Too many rooms!")) + elif line.virtual_room_id: + checkout_dt = date_utils.get_datetime(line.checkout) + occupied = self.env['hotel.reservation'].occupied( + line.checkin, + checkout_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)) + rooms_occupied = occupied.mapped('product_id.id') + free_rooms = self.env['hotel.room'].search([ + ('product_id.id', 'not in', rooms_occupied), + ('price_virtual_room.id', '=', line.virtual_room_id.id)], + order='sequence', limit=line.rooms_num) + room_ids = free_rooms.mapped('product_id.id') + product_list = self.env['product.product'].search([ + ('id', 'in', room_ids) + ]) + nights = days_diff = date_utils.date_diff(line.checkin, + line.checkout, + hours=False) + hotel_tz = self.env['ir.default'].sudo().get( + 'hotel.config.settings', + 'hotel_tz') + start_date_utc_dt = date_utils.get_datetime(self.checkin) + start_date_dt = date_utils.dt_as_timezone(start_date_utc_dt, + hotel_tz) + for room in product_list: + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_id: + pricelist_id = int(pricelist_id) + res_price = 0 + res_partner = self.partner_id or self.env['res.partner'].browse('1') + for i in range(0, nights): + ndate = start_date_dt + timedelta(days=i) + ndate_str = ndate.strftime(DEFAULT_SERVER_DATE_FORMAT) + prod = line.virtual_room_id.product_id.with_context( + lang=self.partner_id.lang, + partner=self.partner_id.id, + quantity=1, + date=ndate_str, + pricelist=pricelist_id, + uom=room.uom_id.id) + res_price += prod.price + adults = self.env['hotel.room'].search([ + ('product_id.id', '=', room.id) + ]).capacity + res_price = res_price - (res_price * line.discount)/100 + total += res_price + cmds.append((0, False, { + 'checkin': line.checkin, + 'checkout': line.checkout, + 'discount': line.discount, + 'product_id': room.id, + 'nights': nights, + 'adults': adults, + 'children': 0, + 'virtual_room_id': line.virtual_room_id, + 'price': res_price, + 'amount_reservation': res_price + })) + self.reservation_wizard_ids = cmds + self.total = total + + @api.multi + @api.onchange('checkin', 'checkout') + def onchange_checks(self): + ''' + When you change checkin or checkout it will checked it + and update the qty of hotel folio line + ----------------------------------------------------------------- + @param self: object pointer + ''' + self.ensure_one() + now_utc_dt = date_utils.now() + if not self.checkin: + self.checkin = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + if not self.checkout: + self.checkout = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + + # UTC -> Hotel tz + tz = self.env['ir.default'].sudo().get('hotel.config.settings', + 'tz_hotel') + chkin_utc_dt = date_utils.get_datetime(self.checkin) + chkout_utc_dt = date_utils.get_datetime(self.checkout) + + if chkin_utc_dt >= chkout_utc_dt: + dpt_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_departure_hour') + checkout_str = (chkin_utc_dt + timedelta(days=1)).strftime( + DEFAULT_SERVER_DATE_FORMAT) + checkout_str = "%s %s:00" % (checkout_str, dpt_hour) + checkout_dt = date_utils.get_datetime(checkout_str, stz=tz) + checkout_utc_dt = date_utils.dt_as_timezone(checkout_dt, 'UTC') + self.checkout = checkout_utc_dt.strftime( + DEFAULT_SERVER_DATETIME_FORMAT) + checkout_dt = date_utils.get_datetime(self.checkout, stz=tz) + # Reservation end day count as free day. Not check it + checkout_dt -= timedelta(days=1) + virtual_room_ids = self.env['hotel.virtual.room'].search([]) + virtual_rooms = [] + + for virtual in virtual_room_ids: + virtual_rooms.append((0, False, { + 'virtual_room_id': virtual.id, + 'checkin': self.checkin, + 'checkout': self.checkout, + 'folio_wizard_id': self.id, + })) + self.virtual_room_wizard_ids = virtual_rooms + for virtual in self.virtual_room_wizard_ids: + virtual.update_price() + + @api.depends('virtual_room_wizard_ids','reservation_wizard_ids','service_wizard_ids') + def _computed_total(self): + total = 0 + for line in self.service_wizard_ids: + total += line.price_total + if not self.reservation_wizard_ids: + for line in self.virtual_room_wizard_ids: + total += line.total_price + self.total = total + else: + for line in self.reservation_wizard_ids: + total += line.price + self.total = total + + @api.multi + def create_folio(self): + self.ensure_one() + if not self.partner_id: + raise ValidationError(_("We need know the customer!")) + reservations = [(5, False, False)] + services = [(5, False, False)] + if self.autoassign == True: + self.create_reservations() + for line in self.reservation_wizard_ids: + reservations.append((0, False, { + 'product_id': line.product_id.id, + 'adults': line.adults, + 'children': line.children, + 'checkin': line.checkin, + 'checkout': line.checkout, + 'discount': line.discount, + 'virtual_room_id': line.virtual_room_id.id, + 'to_read': line.to_read, #REFACT: wubook module + 'to_assign': line.to_assign, + })) + for line in self.service_wizard_ids: + services.append((0, False, { + 'product_id': line.product_id.id, + 'discount': line.discount, + 'price_unit': line.price_unit, + 'product_uom_qty': line.product_uom_qty, + })) + vals = { + 'partner_id': self.partner_id.id, + 'channel_type': self.channel_type, + 'room_lines': reservations, + 'service_lines': services, + } + newfol = self.env['hotel.folio'].create(vals) + for room in newfol.room_lines: + room.on_change_checkin_checkout_product_id() + newfol.compute_invoices_amount() + if self.confirm: + newfol.room_lines.confirm() + action = self.env.ref('hotel.open_hotel_folio1_form_tree_all').read()[0] + if newfol: + action['views'] = [(self.env.ref('hotel.view_hotel_folio1_form').id, 'form')] + action['res_id'] = newfol.id + else: + action = {'type': 'ir.actions.act_window_close'} + return action + +class VirtualRoomWizars(models.TransientModel): + _name = 'hotel.virtual.room.wizard' + + @api.multi + def _get_default_checkin(self): + return self.folio_wizard_id.checkin + + @api.model + def _get_default_checkout(self): + return self.folio_wizard_id.checkout + + virtual_room_id = fields.Many2one('hotel.virtual.room', + string="Virtual Rooms") + rooms_num = fields.Integer('Number of Rooms') + max_rooms = fields.Integer('Max', compute="_compute_max") + price = fields.Float(string='Price by Room') + total_price = fields.Float(string='Total Price') + folio_wizard_id = fields.Many2one('hotel.folio.wizard') + amount_reservation = fields.Float(string='Total', readonly=True) + discount = fields.Float('discount') + min_stay = fields.Integer('Min. Days', compute="_compute_max") + checkin = fields.Datetime('Check In', required=True, + default=_get_default_checkin) + checkout = fields.Datetime('Check Out', required=True, + default=_get_default_checkout) + can_confirm = fields.Boolean(compute="_can_confirm") + + def _can_confirm(self): + for vroom in self: + date_start = date_utils.get_datetime(vroom.checkin) + date_end = date_utils.get_datetime(vroom.checkout) + date_diff = date_utils.date_diff(date_start, date_end, hours=False) + if vroom.max_rooms > 0 and vroom.min_stay <= date_diff: + vroom.can_confirm = True + else: + vroom.can_confirm = False + + def _compute_max(self): + for res in self: + user = self.env['res.users'].browse(self.env.uid) + date_start = date_utils.get_datetime(res.checkin) + date_end = date_utils.get_datetime(res.checkout) + date_diff = date_utils.date_diff(date_start, date_end, hours=False) + minstay_restrictions = self.env['hotel.virtual.room.restriction.item'].search([ + ('virtual_room_id','=',res.virtual_room_id.id), + ]) + avail_restrictions = self.env['hotel.virtual.room.availability'].search([ + ('virtual_room_id','=',res.virtual_room_id.id) + ]) + real_max = len(res.virtual_room_id.check_availability_virtual_room( + res.checkin, + res.checkout, + res.virtual_room_id.id)) + avail = 100000 + min_stay = 0 + dates = [] + for i in range(0, date_diff): + ndate_dt = date_start + timedelta(days=i) + ndate_str = ndate_dt.strftime(DEFAULT_SERVER_DATE_FORMAT) + dates.append(ndate_str) + if minstay_restrictions: + date_min_days = minstay_restrictions.filtered( + lambda r: r.date_start <= ndate_str and \ + r.date_end >= ndate_str).min_stay + if date_min_days > min_stay: + min_stay = date_min_days + if user.has_group('hotel.group_hotel_call'): + if avail_restrictions: + max_avail = avail_restrictions.filtered( + lambda r: r.date == ndate_str).wmax_avail + if max_avail < avail: + avail = min(max_avail, real_max) + else: + avail = real_max + + + if avail < 100000 and avail > 0: + res.max_rooms = avail + else: + res.max_rooms = 0 + if min_stay > 0: + res.min_stay = min_stay + + @api.onchange('rooms_num', 'discount', 'price','virtual_room_id', + 'checkin','checkout') + def update_price(self): + for line in self: + now_utc_dt = date_utils.now() + if not self.checkin: + self.checkin = self.folio_wizard_id.checkin + if not self.checkout: + self.checkout = self.folio_wizard_id.checkout + if self.rooms_num > self.max_rooms: + raise ValidationError(_("There are not enough rooms!")) + # UTC -> Hotel tz + tz = self.env['ir.default'].sudo().get('hotel.config.settings', + 'tz_hotel') + chkin_utc_dt = date_utils.get_datetime(self.checkin) + chkout_utc_dt = date_utils.get_datetime(self.checkout) + + if chkin_utc_dt >= chkout_utc_dt: + dpt_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_departure_hour') + checkout_str = (chkin_utc_dt + timedelta(days=1)).strftime( + DEFAULT_SERVER_DATE_FORMAT) + checkout_str = "%s %s:00" % (checkout_str, dpt_hour) + checkout_dt = date_utils.get_datetime(checkout_str, stz=tz) + checkout_utc_dt = date_utils.dt_as_timezone(checkout_dt, 'UTC') + self.checkout = checkout_utc_dt.strftime( + DEFAULT_SERVER_DATETIME_FORMAT) + checkout_dt = date_utils.get_datetime(self.checkout, stz=tz) + # Reservation end day count as free day. Not check it + checkout_dt -= timedelta(days=1) + nights = days_diff = date_utils.date_diff(self.checkin, + self.checkout, + hours=False) + start_date_dt = date_utils.dt_as_timezone(chkin_utc_dt, + tz) + # Reservation end day count as free day. Not check it + checkout_dt -= timedelta(days=1) + + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_id: + pricelist_id = int(pricelist_id) + + res_price = 0 + for i in range(0, nights): + ndate = start_date_dt + timedelta(days=i) + ndate_str = ndate.strftime(DEFAULT_SERVER_DATE_FORMAT) + prod = self.virtual_room_id.product_id.with_context( + lang=self.folio_wizard_id.partner_id.lang, + partner=self.folio_wizard_id.partner_id.id, + quantity=1, + date=ndate_str, + pricelist=pricelist_id, + uom=self.virtual_room_id.product_id.uom_id.id) + res_price += prod.price + self.price = res_price - (res_price * self.discount)/100 + self.total_price = self.rooms_num * self.price + self.amount_reservation = self.total_price + + +class ReservationWizard(models.TransientModel): + _name = 'hotel.reservation.wizard' + + product_id = fields.Many2one('product.product', + string="Virtual Rooms") + + folio_wizard_id = fields.Many2one('hotel.folio.wizard') + + adults = fields.Integer('Adults', + help='List of adults there in guest list. ') + children = fields.Integer('Children', + help='Number of children there in guest list.') + checkin = fields.Datetime('Check In', required=True) + checkout = fields.Datetime('Check Out', required=True) + virtual_room_id = fields.Many2one('hotel.virtual.room', + string='Virtual Room Type', + required=True) + nights = fields.Integer('Nights', readonly=True) + price = fields.Float(string='Total') + amount_reservation = fields.Float(string='Total', readonly=True) + partner_id = fields.Many2one(related='folio_wizard_id.partner_id') + discount = fields.Float('discount') + to_read = fields.Boolean(compute="_compute_to_read_assign") + to_assign = fields.Boolean(compute="_compute_to_read_assign") + + @api.multi + def _compute_to_read_assign(self): + for rec in self: + user = self.env['res.users'].browse(self.env.uid) + if user.has_group('hotel.group_hotel_call'): + rec.to_read = rec.to_assign = True + + @api.multi + @api.onchange('product_id') + def onchange_product_id(self): + for line in self: + if line.checkin and line.checkout: + room = self.env['hotel.room'].search([ + ('product_id.id','=',line.product_id.id) + ]) + if line.adults == 0: + line.adults = room.capacity + line.virtual_room_id = room.price_virtual_room.id + checkout_dt = date_utils.get_datetime(line.checkout) + checkout_dt -= timedelta(days=1) + occupied = self.env['hotel.reservation'].occupied( + line.checkin, + checkout_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)) + rooms_occupied = occupied.mapped('product_id.id') + if line.product_id.id in rooms_occupied: + raise ValidationError(_("This room is occupied!, please, choice other room or change the reservation date")) + + @api.multi + @api.onchange('checkin', 'checkout', 'virtual_room_id', 'discount') + def onchange_dates(self): + for line in self: + if not self.checkin: + self.checkin = self.folio_wizard_id.checkin + if not self.checkout: + self.checkout = self.folio_wizard_id.checkout + + hotel_tz = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'hotel_tz') + start_date_utc_dt = date_utils.get_datetime(line.checkin) + start_date_dt = date_utils.dt_as_timezone(start_date_utc_dt, + hotel_tz) + + if line.virtual_room_id: + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + if pricelist_id: + pricelist_id = int(pricelist_id) + nights = days_diff = date_utils.date_diff(line.checkin, + line.checkout, + hours=False) + res_price = 0 + res_partner = self.partner_id or self.env['res.partner'].browse('1') + for i in range(0, nights): + ndate = start_date_dt + timedelta(days=i) + ndate_str = ndate.strftime(DEFAULT_SERVER_DATE_FORMAT) + prod = line.virtual_room_id.product_id.with_context( + lang=self.partner_id.lang, + partner=self.partner_id.id, + quantity=1, + date=ndate_str, + pricelist=pricelist_id, + uom=line.product_id.uom_id.id) + res_price += prod.price + adults = self.env['hotel.room'].search([ + ('product_id.id', '=', line.product_id.id) + ]).capacity + res_price = res_price - (res_price * self.discount)/100 + line.amount_reservation = res_price + line.price = res_price + checkout_dt = date_utils.get_datetime(self.checkout) + checkout_dt -= timedelta(days=1) + occupied = self.env['hotel.reservation'].occupied( + self.checkin, + checkout_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)) + rooms_occupied = occupied.mapped('product_id.id') + domain_rooms = [ + ('isroom', '=', True), + ('id', 'not in', rooms_occupied) + ] + return {'domain': {'product_id': domain_rooms}} + +class ServiceWizard(models.TransientModel): + _name = 'hotel.service.wizard' + + product_id = fields.Many2one('product.product', + string="Service") + folio_wizard_id = fields.Many2one('hotel.folio.wizard') + discount = fields.Float('discount') + price_unit = fields.Float('Unit Price', required=True, digits=dp.get_precision('Product Price'), default=0.0) + price_total = fields.Float(compute='_compute_amount', string='Subtotal', readonly=True, store=True) + product_uom_qty = fields.Float(string='Quantity', digits=dp.get_precision('Product Unit of Measure'), required=True, default=1.0) + + @api.onchange('product_id') + def onchange_product_id(self): + if self.product_id: + #TODO change pricelist for partner + pricelist_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_pricelist_id') + prod = self.product_id.with_context( + lang=self.folio_wizard_id.partner_id.lang, + partner=self.folio_wizard_id.partner_id.id, + quantity=1, + date=fields.Datetime.now(), + pricelist=pricelist_id, + uom=self.product_id.uom_id.id) + self.price_unit = prod.price + + @api.depends('price_unit', 'product_uom_qty', 'discount') + def _compute_amount(self): + for ser in self: + total = (ser.price_unit * ser.product_uom_qty) + ser.price_total = total - (total * ser.discount) / 100 diff --git a/hotel_calendar/wizard/wizard_reservation.xml b/hotel_calendar/wizard/wizard_reservation.xml new file mode 100644 index 000000000..5d880e580 --- /dev/null +++ b/hotel_calendar/wizard/wizard_reservation.xml @@ -0,0 +1,101 @@ + + + + + hotel.folio.wizard + hotel.folio.wizard + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + + Hotel Reservation Wizard + ir.actions.act_window + hotel.folio.wizard + + form + form + new + + +
diff --git a/hotel_calendar_channel_connector/README.rst b/hotel_calendar_channel_connector/README.rst new file mode 100644 index 000000000..b855c9f79 --- /dev/null +++ b/hotel_calendar_channel_connector/README.rst @@ -0,0 +1,15 @@ +HOTEL CALENDAR WUBOOK +============= +- Show button for see reservations from wubook in hotel calendar view +- Mark as read-only reservations from wubook + +** UNDER DEVELOPMENT: NOT USE IN PRODUCTION ** + + +Credits +======= + +Creator +------------ + +* Alexandre Díaz \ No newline at end of file diff --git a/hotel_calendar_channel_connector/__init__.py b/hotel_calendar_channel_connector/__init__.py new file mode 100644 index 000000000..8f10572dd --- /dev/null +++ b/hotel_calendar_channel_connector/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from . import models diff --git a/hotel_calendar_channel_connector/__manifest__.py b/hotel_calendar_channel_connector/__manifest__.py new file mode 100644 index 000000000..ac888bdc5 --- /dev/null +++ b/hotel_calendar_channel_connector/__manifest__.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## + +{ + 'name': 'Hotel Calendar WuBook', + 'version': '1.0', + 'author': "Alexandre Díaz (Aloxa Solucións S.L.) ", + 'website': 'https://www.eiqui.com', + 'category': 'eiqui/hotel', + 'summary': "Hotel Calendar", + 'description': "Hotel Calendar WuBook", + 'depends': [ + 'hotel_calendar', + 'hotel_wubook_proto', + ], + 'external_dependencies': { + 'python': [] + }, + 'data': [ + 'views/hotel_reservation.xml', + 'views/general.xml', + 'views/actions.xml', + ], + 'qweb': [ + 'static/src/xml/*.xml', + ], + 'test': [ + ], + + 'installable': True, + 'auto_install': True, + 'application': False, + 'license': 'AGPL-3', +} diff --git a/hotel_calendar_channel_connector/i18n/es.po b/hotel_calendar_channel_connector/i18n/es.po new file mode 100644 index 000000000..7f6d06e2d --- /dev/null +++ b/hotel_calendar_channel_connector/i18n/es.po @@ -0,0 +1,111 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * hotel_calendar_wubook +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 10.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2018-05-22 06:41+0000\n" +"PO-Revision-Date: 2018-05-22 06:41+0000\n" +"Last-Translator: <>\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: \n" + +#. module: hotel_calendar_wubook +#. openerp-web +#: code:addons/hotel_calendar_wubook/static/src/xml/hotel_calendar_templates.xml:10 +#: code:addons/hotel_calendar_wubook/static/src/xml/hotel_calendar_view.xml:24 +#, python-format +msgid "Channel:" +msgstr "Canal:" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Final Price" +msgstr "Precio Final" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Folio Pending Amount" +msgstr "Pendiente en Ficha" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Hotel Reservation" +msgstr "Reserva" + +#. module: hotel_calendar_wubook +#. openerp-web +#: code:addons/hotel_calendar_wubook/static/src/xml/hotel_calendar_view.xml:15 +#, python-format +msgid "ISSUES" +msgstr "AVISOS" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.hotel_reservation_view_form +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Mark as Read" +msgstr "Marcar como leídp" + +#. module: hotel_calendar_wubook +#: code:addons/hotel_calendar_wubook/models/inherited_wubook_issue.py:33 +#, python-format +msgid "Oops! Issue Reported!!" +msgstr "Oops! ¡Aviso generado!" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Persons" +msgstr "Personas" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Reservation Price" +msgstr "Precio de Reserva" + +#. module: hotel_calendar_wubook +#: model:ir.actions.act_window,name:hotel_calendar_wubook.hotel_reservation_action_manager_request +msgid "Reservations to Assign from WuBook" +msgstr "Reservas por Asignar desde WuBook" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Reserved Room Type" +msgstr "Tipo Habitación Reservada" + +#. module: hotel_calendar_wubook +#: model:ir.ui.view,arch_db:hotel_calendar_wubook.view_hotel_toassign_reservation_tree +msgid "Room" +msgstr "Habitación" + +#. module: hotel_calendar_wubook +#. openerp-web +#: code:addons/hotel_calendar_wubook/static/src/xml/hotel_calendar_templates.xml:4 +#, python-format +msgid "Section:" +msgstr "Sección" + +#. module: hotel_calendar_wubook +#: model:ir.actions.act_window,name:hotel_calendar_wubook.calendar_wubook_issues_action +msgid "WuBook Issues" +msgstr "Problemas de WuBook" + +#. module: hotel_calendar_wubook +#: model:ir.model,name:hotel_calendar_wubook.model_bus_hotel_calendar +msgid "bus.hotel.calendar" +msgstr "bus.hotel.calendar" + +#. module: hotel_calendar_wubook +#: model:ir.model,name:hotel_calendar_wubook.model_hotel_reservation +msgid "hotel reservation" +msgstr "Reserva" + +#. module: hotel_calendar_wubook +#: model:ir.model,name:hotel_calendar_wubook.model_wubook_issue +msgid "wubook.issue" +msgstr "wubook.issue" + diff --git a/hotel_calendar_channel_connector/models/__init__.py b/hotel_calendar_channel_connector/models/__init__.py new file mode 100644 index 000000000..32e496b97 --- /dev/null +++ b/hotel_calendar_channel_connector/models/__init__.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from . import inherited_hotel_reservation +from . import inherited_bus_hotel_calendar +from . import inherited_wubook_issue +from . import inherited_hotel_calendar_management diff --git a/hotel_calendar_channel_connector/models/inherited_bus_hotel_calendar.py b/hotel_calendar_channel_connector/models/inherited_bus_hotel_calendar.py new file mode 100644 index 000000000..1897d5ca2 --- /dev/null +++ b/hotel_calendar_channel_connector/models/inherited_bus_hotel_calendar.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import datetime +from openerp.tools import DEFAULT_SERVER_DATE_FORMAT +from openerp import models, api +from odoo.addons.hotel_calendar.controllers.bus import HOTEL_BUS_CHANNEL_ID + + +class BusHotelCalendar(models.TransientModel): + _inherit = 'bus.hotel.calendar' + + @api.model + def _generate_issue_notification(self, ntype, title, issue_id, section, + message): + user_id = self.env['res.users'].browse(self.env.uid) + return { + 'type': 'issue', + 'subtype': ntype, + 'title': title, + 'username': user_id.partner_id.name, + 'userid': user_id.id, + 'issue': { + 'issue_id': issue_id, + 'section': section.upper(), + 'message': message, + }, + } + + @api.model + def _generate_reservation_notif(self, vals): + json = super(BusHotelCalendar, self)._generate_reservation_notif(vals) + json['reservation'].update({ + 'wrid': vals['wrid'], + }) + return json + + @api.model + def send_issue_notification(self, ntype, title, issue_id, section, + message): + notif = self._generate_issue_notification(ntype, title, issue_id, + section, message) + self.env['bus.bus'].sendone( + (self._cr.dbname, 'hotel.reservation', + HOTEL_BUS_CHANNEL_ID), notif) diff --git a/hotel_calendar_channel_connector/models/inherited_hotel_calendar_management.py b/hotel_calendar_channel_connector/models/inherited_hotel_calendar_management.py new file mode 100644 index 000000000..6b576872f --- /dev/null +++ b/hotel_calendar_channel_connector/models/inherited_hotel_calendar_management.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp import models, api + + +class HotelCalendarManagement(models.TransientModel): + _inherit = 'hotel.calendar.management' + + @api.model + def _get_availability_values(self, avail, vroom): + vals = super(HotelCalendarManagement, self)._get_availability_values( + avail, vroom) + vals.update({'wmax_avail': vals['avail']}) + return vals + + @api.multi + def save_changes(self, pricelist_id, restriction_id, pricelist, + restrictions, availability): + res = super(HotelCalendarManagement, self).save_changes( + pricelist_id, + restriction_id, + pricelist, + restrictions, + availability) + self.env['wubook'].push_changes() + return res diff --git a/hotel_calendar_channel_connector/models/inherited_hotel_reservation.py b/hotel_calendar_channel_connector/models/inherited_hotel_reservation.py new file mode 100644 index 000000000..0ae6e46dd --- /dev/null +++ b/hotel_calendar_channel_connector/models/inherited_hotel_reservation.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +import logging +from datetime import datetime, timedelta +from openerp import models, fields, api, _ +from openerp.tools import ( + DEFAULT_SERVER_DATE_FORMAT, + DEFAULT_SERVER_DATETIME_FORMAT) +_logger = logging.getLogger(__name__) + + +class HotelReservation(models.Model): + _inherit = "hotel.reservation" + + @api.model + def _generate_reservation_notif(self, action, ntype, title, + product_id, reserv_id, partner_name, + adults, children, checkin, checkout, + folio_id, color, color_text, splitted, + parent_reservation, room_name, + partner_phone, state, fix_days): + vals = super(HotelReservation, self)._generate_reservation_notif( + action, ntype, title, product_id, + reserv_id, partner_name, adults, + children, checkin, checkout, + folio_id, color, color_text, splitted, parent_reservation, + room_name, partner_phone, state, fix_days) + reserv = self.env['hotel.reservation'].browse(vals['reserv_id']) + vals['reservation'].update({ + 'fix_days': (reserv.wrid and reserv.wrid != '') or fix_days, + 'wchannel': (reserv.wchannel_id and reserv.wchannel_id.name), + }) + return vals + + @api.multi + def _hcalendar_reservation_data(self, reservations): + vals = super(HotelReservation, self)._hcalendar_reservation_data( + reservations) + hotel_reservation_obj = self.env['hotel.reservation'] + json_reservations = [] + for v_rval in vals[0]: + reserv = hotel_reservation_obj.browse(v_rval[1]) + json_reservations.append(( + reserv.product_id.id, + reserv.id, + reserv.folio_id.partner_id.name, + reserv.adults, + reserv.children, + reserv.checkin, + reserv.checkout, + reserv.folio_id.id, + reserv.reserve_color, + reserv.reserve_color_text, + reserv.splitted, + reserv.parent_reservation.id, + # Read-Only + False, + # Fix Days + (reserv.wrid and reserv.wrid != '') or reserv.splitted, + # Fix Rooms + False, + reserv.overbooking)) + # Update tooltips + vals[1][reserv.id].append(reserv.wchannel_id.name) + return (json_reservations, vals[1]) + + @api.multi + def send_bus_notification(self, naction, ntype, ntitle=''): + hotel_cal_obj = self.env['bus.hotel.calendar'] + for record in self: + hotel_cal_obj.send_reservation_notification({ + 'action': naction, + 'type': ntype, + 'title': ntitle, + 'product_id': record.product_id.id, + 'reserv_id': record.id, + 'partner_name': record.partner_id.name, + 'adults': record.adults, + 'children': record.children, + 'checkin': record.checkin, + 'checkout': record.checkout, + 'folio_id': record.folio_id.id, + 'reserve_color': record.reserve_color, + 'reserve_color_text': record.reserve_color_text, + 'splitted': record.splitted, + 'parent_reservation': record.parent_reservation and + record.parent_reservation.id or 0, + 'room_name': record.product_id.name, + 'partner_phone': record.partner_id.mobile + or record.partner_id.phone or _('Undefined'), + 'state': record.state, + 'fix_days': record.splitted or record.wis_from_channel, + 'overbooking': record.overbooking, + 'price': record.folio_id.amount_total, + 'wrid': record.wrid, + }) + + @api.multi + def confirm(self): + for record in self: + if record.to_assign == True: + record.write({'to_read': False, 'to_assign': False}) + return super(HotelReservation, self).confirm() diff --git a/hotel_calendar_channel_connector/models/inherited_wubook_issue.py b/hotel_calendar_channel_connector/models/inherited_wubook_issue.py new file mode 100644 index 000000000..a897e3ac0 --- /dev/null +++ b/hotel_calendar_channel_connector/models/inherited_wubook_issue.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp import models, fields, api, _ + + +class WuBookIssue(models.Model): + _inherit = 'wubook.issue' + + @api.model + def create(self, vals): + issue_id = super(WuBookIssue, self).create(vals) + self.env['bus.hotel.calendar'].send_issue_notification( + 'warn', + _("Oops! Issue Reported!!"), + issue_id.id, + issue_id.section, + issue_id.message) + return issue_id diff --git a/hotel_calendar_channel_connector/static/description/eiqui_logo.png b/hotel_calendar_channel_connector/static/description/eiqui_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..ca3bd8c1321a85719347fea0ba79a2320b29eb69 GIT binary patch literal 6240 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 DYa-VG literal 0 HcmV?d00001 diff --git a/hotel_calendar_channel_connector/static/description/index.html b/hotel_calendar_channel_connector/static/description/index.html new file mode 100644 index 000000000..9022331a1 --- /dev/null +++ b/hotel_calendar_channel_connector/static/description/index.html @@ -0,0 +1,22 @@ +
+
+
+
+

HOTEL CALENDAR WUBOOK

+

Hotel Calendar WuBook

+
+
+

Hotel Calendar WuBook

+
+ +
+ +
+
+ + + +
+
+
+
diff --git a/hotel_calendar_channel_connector/static/sfx/book_cancelled.mp3 b/hotel_calendar_channel_connector/static/sfx/book_cancelled.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..10ffab8e7833cc8875b8d2c9950e52d74b395ed2 GIT binary patch literal 10152 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 + * Alexandre Díaz + */ + + /** ANIMATIONS **/ + @keyframes channel-manager-changes { + 0% { + color: red; + } + 5% { + transform: rotate(10deg); + } + 10% { + transform: rotate(0deg); + } + 15% { + transform: rotate(-10deg); + } + 20% { + transform: rotate(0deg); + } + 100% { + color: yellow; + } +} +@keyframes channel-manager-changes-text { + from { + color: white; + } + to { + color: black; + } +} + + +#pms-menu #btn_channel_manager_request.incoming i { + animation-name: channel-manager-changes; + animation-duration: 2s; + animation-iteration-count: infinite; + animation-direction: alternate; +} +#pms-menu #btn_channel_manager_request.incoming span { + animation-name: channel-manager-changes-text; + animation-duration: 2s; + animation-iteration-count: infinite; + animation-direction: alternate; +} \ No newline at end of file diff --git a/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_controller.js b/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_controller.js new file mode 100644 index 000000000..d242eec9f --- /dev/null +++ b/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_controller.js @@ -0,0 +1,87 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.PMSHotelCalendarControllerChannelConnector', function (require) { +"use strict"; + +var PMSCalendarController = require('hotel_calendar.PMSCalendarController'); +var Core = require('web.core'); + +var QWeb = Core.qweb; + +var PMSHotelCalendarControllerChannelConnector = PMSCalendarController.include({ + _sounds: [], + SOUNDS: { NONE: 0, BOOK_NEW:1, BOOK_CANCELLED:2 }, + + init: function (parent, model, renderer, params) { + this._super.apply(this, arguments); + + this._sounds[this.SOUNDS.BOOK_NEW] = new Audio('hotel_calendar_channel_connector/static/sfx/book_new.mp3'); + this._sounds[this.SOUNDS.BOOK_CANCELLED] = new Audio('hotel_calendar_channel_connector/static/sfx/book_cancelled.mp3'); + }, + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + + //-------------------------------------------------------------------------- + // Private + //-------------------------------------------------------------------------- + _play_sound: function(/*int*/SoundID) { + this._sounds[SoundID].play(); + }, + + //-------------------------------------------------------------------------- + // Handlers + //-------------------------------------------------------------------------- + _onUpdateButtonsCounter: function (ev) { + this._super(ev); + var self = this; + var domain_reservations = [['to_assign', '=', true], ['to_read', '=', true]]; + var domain_issues = [['to_read', '=', true]]; + $.when( + this.model.search_count(domain_reservations), + this.model.search_count(domain_issues), + ).then(function(a1, a2){ + self.renderer.update_buttons_counter_channel_connector(a1, a2); + }); + }, + + _onBusNotification: function(notifications) { + for (var notif of notifications) { + if (notif[0][1] === 'hotel.reservation') { + if (notif[1]['type'] === 'issue') { + if (notif[1]['userid'] === this.dataset.context.uid) { + continue; + } + + var issue = notif[1]['issue']; + var qdict = issue; + var msg = QWeb.render('HotelCalendarChannelConnector.NotificationIssue', qdict); + if (notif[1]['subtype'] === 'notify') { + this.do_notify(notif[1]['title'], msg, true); + } else if (notif[1]['subtype'] === 'warn') { + this.do_warn(notif[1]['title'], msg, true); + } + } + else if (notif[1]['type'] === 'reservation') { + var reserv = notif[1]['reservation']; + if (reserv['wrid']) { + if (notif[1]['action'] === 'create') { + this._play_sound(this.SOUNDS.BOOK_NEW); + } else if (notif[1]['action'] !== 'unlink' && reserv['state'] === 'cancelled') { + this._play_sound(this.SOUNDS.BOOK_CANCELLED); + } + } + } + } + } + + this._super(notifications); + }, + +}); + +return PMSHotelCalendarControllerChannelConnector; + +}); diff --git a/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_model.js b/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_model.js new file mode 100644 index 000000000..b1542c5e3 --- /dev/null +++ b/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_model.js @@ -0,0 +1,119 @@ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar.PMSCalendarModel', function (require) { +"use strict"; + +var AbstractModel = require('web.AbstractModel'), + Context = require('web.Context'), + Core = require('web.core'), + FieldUtils = require('web.field_utils'), + Session = require('web.session'); + + +return AbstractModel.extend({ + init: function () { + this._super.apply(this, arguments); + this.end_date = null; + }, + + load: function (params) { + this.modelName = params.modelName; + this.modelManagementName = 'hotel.calendar.management' + }, + + save_pricelist: function(params) { + return this._rpc({ + model: this.modelManagementName, + method: 'save_changes', + args: params, + context: Session.user_context, + }); + }, + + swap_reservations: function(fromIds, toIds) { + return this._rpc({ + model: this.modelName, + method: 'swap_reservations', + args: [fromIds, toIds], + context: Session.user_context, + }); + }, + + get_calendar_data: function(oparams) { + return this._rpc({ + model: this.modelName, + method: 'get_hcalendar_all_data', + args: oparams, + context: Session.user_context, + }); + }, + + get_hcalendar_settings: function() { + return this._rpc({ + model: this.modelName, + method: 'get_hcalendar_settings', + args: [false], + }); + }, + + get_room_types: function() { + return this._rpc({ + model: 'hotel.room.type', + method: 'search_read', + args: [false, ['cat_id','name']], + context: Session.user_context, + }); + }, + get_floors: function() { + return this._rpc({ + model: 'hotel.floor', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + get_amenities: function() { + return this._rpc({ + model: 'hotel.room.amenities', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + get_vrooms: function() { + return this._rpc({ + model: 'hotel.virtual.room', + method: 'search_read', + args: [false, ['id','name']], + context: Session.user_context, + }); + }, + + search_count: function(domain) { + return this._rpc({ + model: this.modelName, + method: 'search_count', + args: [domain], + context: Session.user_context, + }); + }, + + update_records: function(ids, vals) { + return this._rpc({ + model: this.modelName, + method: 'write', + args: [ids, write_values], + context: Session.user_context, + }); + }, + + folio_search_count: function(domain) { + return this._rpc({ + model: 'hotel.folio', + method: 'search_count', + args: [domain], + context: Session.user_context, + }); + }, +}); +}); diff --git a/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_renderer.js b/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_renderer.js new file mode 100644 index 000000000..a0c12dd1b --- /dev/null +++ b/hotel_calendar_channel_connector/static/src/js/views/hotel_calendar_renderer.js @@ -0,0 +1,60 @@ +/* global odoo, $ */ +// Copyright 2018 Alexandre Díaz +// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +odoo.define('hotel_calendar_channel_connector.PMSHotelCalendarRendererChannelConnector', function (require) { + 'use strict'; + + var PMSCalendarRenderer = require('hotel_calendar.PMSCalendarRenderer'); + + var PMSHotelCalendarRendererChannelConnector = PMSCalendarRenderer.include({ + + update_buttons_counter_channel_connector: function (nreservations, nissues) { + // Cloud Reservations + var $button = this.$el.find('#btn_channel_manager_request'); + var $text = this.$el.find('#btn_channel_manager_request .cloud-text'); + if (nreservations > 0) { + $button.addClass('incoming'); + $text.text(nreservations); + $text.show(); + } else { + $button.removeClass('incoming'); + $text.hide(); + } + + // Issues + var $ninfo = this.$el.find('#pms-menu #btn_action_issues div.ninfo'); + var $badge_issues = $ninfo.find('.badge'); + if (nissues > 0) { + $badge_issues.text(nissues); + $badge_issues.parent().show(); + $ninfo.show(); + } else { + $ninfo.hide(); + } + }, + + init_calendar_view: function () { + var self = this; + return this._super().then(function () { + self.$el.find('#btn_channel_manager_request').on('click', function (ev) { + self.do_action("hotel_calendar_wubook.hotel_reservation_action_manager_request"); + }); + }); + }, + + _generate_reservation_tooltip_dict: function(tp) { + var qdict = this._super(tp); + qdict['channel_name'] = tp[5]; + return qdict; + }, + + _generate_bookings_domain: function(tsearch) { + var domain = this._super(tsearch); + domain.splice(0, 0, '|'); + domain.push(['wrid', 'ilike', tsearch]); + return domain; + } + }); + + return PMSHotelCalendarRendererChannelConnector; +}); diff --git a/hotel_calendar_channel_connector/static/src/xml/hotel_calendar_templates.xml b/hotel_calendar_channel_connector/static/src/xml/hotel_calendar_templates.xml new file mode 100644 index 000000000..f03900f73 --- /dev/null +++ b/hotel_calendar_channel_connector/static/src/xml/hotel_calendar_templates.xml @@ -0,0 +1,14 @@ + diff --git a/hotel_calendar_channel_connector/static/src/xml/hotel_calendar_view.xml b/hotel_calendar_channel_connector/static/src/xml/hotel_calendar_view.xml new file mode 100644 index 000000000..b395cbf06 --- /dev/null +++ b/hotel_calendar_channel_connector/static/src/xml/hotel_calendar_view.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + +
  • Channel:
  • +
    +
    +
    + +
    diff --git a/hotel_calendar_channel_connector/tests/__init__.py b/hotel_calendar_channel_connector/tests/__init__.py new file mode 100644 index 000000000..327f7e426 --- /dev/null +++ b/hotel_calendar_channel_connector/tests/__init__.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from . import test_folio diff --git a/hotel_calendar_channel_connector/tests/test_folio.py b/hotel_calendar_channel_connector/tests/test_folio.py new file mode 100644 index 000000000..718141d45 --- /dev/null +++ b/hotel_calendar_channel_connector/tests/test_folio.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from odoo.addons.hotel_calendar.tests.common import TestHotelCalendar +from odoo.addons.hotel import date_utils + + +class TestHotelReservations(TestHotelCalendar): + + def test_cancel_folio(self): + now_utc_dt = date_utils.now() diff --git a/hotel_calendar_channel_connector/views/actions.xml b/hotel_calendar_channel_connector/views/actions.xml new file mode 100644 index 000000000..fb0f0eb07 --- /dev/null +++ b/hotel_calendar_channel_connector/views/actions.xml @@ -0,0 +1,23 @@ + + + + + + Reservations to Assign from WuBook + hotel.reservation + tree,form + + [('to_assign','=',True),('to_read','=',True)] + + + + + + Channel Connector Issues + hotel.channel.connector.issue + tree,form + [('to_read','=',True)] + + + + diff --git a/hotel_calendar_channel_connector/views/general.xml b/hotel_calendar_channel_connector/views/general.xml new file mode 100644 index 000000000..e336595db --- /dev/null +++ b/hotel_calendar_channel_connector/views/general.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/hotel_calendar_channel_connector/views/hotel_reservation.xml b/hotel_calendar_channel_connector/views/hotel_reservation.xml new file mode 100644 index 000000000..8a91f3934 --- /dev/null +++ b/hotel_calendar_channel_connector/views/hotel_reservation.xml @@ -0,0 +1,85 @@ + + + + + + + hotel.toassign.reservation.tree + hotel.reservation + + + "); + this.$buttons.find('.oe_wubook_import_rooms').on('click', import_rooms.bind(this)); + } else if (this.dataset.model === 'hotel.folio') { + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_import_reservations').on('click', import_reservations.bind(this)); + } else if (this.dataset.model === 'product.pricelist') { + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_import_price_plans').on('click', import_price_plans.bind(this)); + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_push_price_plans').on('click', push_price_plans.bind(this)); + } else if (this.dataset.model === 'wubook.channel.info') { + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_import_channels_info').on('click', import_channels_info.bind(this)); + } else if (this.dataset.model === 'hotel.virtual.room.restriction') { + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_import_restriction_plans').on('click', import_restriction_plans.bind(this)); + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_push_restriction_plans').on('click', push_restriction_plans.bind(this)); + } else if (this.dataset.model === 'hotel.virtual.room.availability') { + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_import_availability').on('click', import_availability.bind(this)); + this.$buttons.append(""); + this.$buttons.find('.oe_wubook_push_availability').on('click', push_availability.bind(this)); + } + } +}); + +}); diff --git a/hotel_channel_connector/tests/__init__.py b/hotel_channel_connector/tests/__init__.py new file mode 100644 index 000000000..cde75d095 --- /dev/null +++ b/hotel_channel_connector/tests/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from . import test_wubook +from . import test_virtual_room_availability_model +from . import test_wubook_issue_model +from . import test_reservation_restriction_item_model +from . import test_reservation_restriction_model +from . import test_res_partner_model +from . import test_product_pricelist_item_model +from . import test_wubook_channel_info_model +from . import test_product_pricelist_model +from . import test_hotel_calendar_management_model +from . import test_hotel_folio_model +from . import test_hotel_virtual_room_model +from . import test_hotel_reservation_model diff --git a/hotel_channel_connector/tests/common.py b/hotel_channel_connector/tests/common.py new file mode 100644 index 000000000..00859b10d --- /dev/null +++ b/hotel_channel_connector/tests/common.py @@ -0,0 +1,310 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from odoo import api +from odoo.addons.hotel import date_utils +from odoo.addons.hotel.tests.common import TestHotel +from odoo.addons.hotel_wubook_proto.wubook import ( + DEFAULT_WUBOOK_DATE_FORMAT, + DEFAULT_WUBOOK_TIME_FORMAT, + WUBOOK_STATUS_CONFIRMED, + WUBOOK_STATUS_CANCELLED) +from random import randint +import logging +_logger = logging.getLogger(__name__) + + +class TestHotelWubook(TestHotel): + + @classmethod + def _init_mock_hotel(cls): + super(TestHotelWubook, cls)._init_mock_hotel() + + @api.multi + def wubook_ommit(self, *args, **kwargs): + return True + + @api.model + def wubook_create_wubook_issue(self, section, message, wmessage, + wid=False, dfrom=False, dto=False): + _logger.info("ISSUE CREATED:\n\t- %s\n\t--- %s", section, message) + + cls.env['wubook']._patch_method('create_wubook_issue', + wubook_create_wubook_issue) + cls.env['wubook']._patch_method('is_valid_account', wubook_ommit) + cls.env['wubook']._patch_method('initialize', wubook_ommit) + cls.env['wubook']._patch_method('push_activation', wubook_ommit) + cls.env['wubook']._patch_method('init_connection', wubook_ommit) + cls.env['wubook']._patch_method('close_connection', wubook_ommit) + cls.env['wubook']._patch_method('create_room', wubook_ommit) + cls.env['wubook']._patch_method('modify_room', wubook_ommit) + cls.env['wubook']._patch_method('delete_room', wubook_ommit) + cls.env['wubook']._patch_method('import_rooms', wubook_ommit) + cls.env['wubook']._patch_method('fetch_rooms_values', wubook_ommit) + cls.env['wubook']._patch_method('update_availability', wubook_ommit) + cls.env['wubook']._patch_method('corporate_fetch', wubook_ommit) + cls.env['wubook']._patch_method('create_reservation', wubook_ommit) + cls.env['wubook']._patch_method('cancel_reservation', wubook_ommit) + cls.env['wubook']._patch_method('fetch_new_bookings', wubook_ommit) + cls.env['wubook']._patch_method('fetch_booking', wubook_ommit) + cls.env['wubook']._patch_method('mark_bookings', wubook_ommit) + cls.env['wubook']._patch_method('create_plan', wubook_ommit) + cls.env['wubook']._patch_method('delete_plan', wubook_ommit) + cls.env['wubook']._patch_method('update_plan_name', wubook_ommit) + cls.env['wubook']._patch_method('update_plan_prices', wubook_ommit) + cls.env['wubook']._patch_method('update_plan_periods', wubook_ommit) + cls.env['wubook']._patch_method('import_pricing_plans', wubook_ommit) + cls.env['wubook']._patch_method('fetch_plan_prices', wubook_ommit) + cls.env['wubook']._patch_method('fetch_all_plan_prices', wubook_ommit) + cls.env['wubook']._patch_method('import_restriction_plans', + wubook_ommit) + cls.env['wubook']._patch_method('fetch_rplan_restrictions', + wubook_ommit) + cls.env['wubook']._patch_method('update_rplan_values', wubook_ommit) + cls.env['wubook']._patch_method('create_rplan', wubook_ommit) + cls.env['wubook']._patch_method('rename_rplan', wubook_ommit) + cls.env['wubook']._patch_method('delete_rplan', wubook_ommit) + cls.env['wubook']._patch_method('import_channels_info', wubook_ommit) + cls.env['wubook']._patch_method('push_changes', wubook_ommit) + cls.env['wubook']._patch_method('push_availability', wubook_ommit) + cls.env['wubook']._patch_method('push_priceplans', wubook_ommit) + cls.env['wubook']._patch_method('push_restrictions', wubook_ommit) + + def create_wubook_booking(self, creator, checkin, partner, rinfo, + channel=0, notes=''): + rcode = randint(100000, 999999) + crcode = randint(100000, 999999) + brate = randint(100000, 999999) + id_woodoo = randint(100000, 999999) + + if not partner.email or partner.email == '': + self.raiseException("Partner doesn't have a mail") + + now_utc_dt = date_utils.now() + now_dt = date_utils.dt_as_timezone(now_utc_dt, self.tz_hotel) + checkin_utc_dt = date_utils.get_datetime(checkin) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, self.tz_hotel) + numdays = 0 + for k_room, v_room in rinfo.iteritems(): + numdays = max(len(v_room['dayprices']), numdays) + checkout_utc_dt = checkin_utc_dt + timedelta(days=numdays) + checkout_dt = date_utils.dt_as_timezone(checkout_utc_dt, self.tz_hotel) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + + # Generate Day Prices + dayprices = {} + total_amount = 0.0 + for k_room, v_room in rinfo.iteritems(): + for price in v_room['dayprices']: + dayprices.setdefault(k_room, []).append(price) + total_amount += price + # Generate Values + rooms = [] + rooms_occu = [] + booked_rooms = [] + vroom_obj = self.env['hotel.virtual.room'] + max_persons = 0 + for k_room, v_room in rinfo.iteritems(): + vroom = vroom_obj.search([ + ('wrid', '=', k_room) + ], limit=1) + # Generate Rooms + for price in range(0, len(v_room['occupancy'])): + rooms.append(k_room) + # Generate Rooms Occupancies + for val in v_room['occupancy']: + # Generate Rooms Occupancies + rooms_occu.append({ + 'id': k_room, + 'occupancy': val, + }) + # Generate Booked Rooms + roomdays = [] + for k_price, v_price in enumerate(v_room['dayprices']): + ndate = checkin_dt + timedelta(days=k_price) + roomdays.append({ + 'ancillary': {}, + 'rate_id': 3, + 'price': v_price, + 'day': ndate.strftime(DEFAULT_WUBOOK_DATE_FORMAT) + }) + booked_rooms.append({ + 'ancillary': { + 'channel_room_id': 1, + 'channel_room_name': vroom.name, + 'addons': [], + 'guests': val + }, + 'room_id': k_room, + 'roomdays': roomdays + }) + if val > max_persons: + max_persons = val + + return { + 'id_channel': channel, + 'special_offer': '', + 'reservation_code': rcode, + 'dayprices': dayprices, + 'arrival_hour': checkin_dt.strftime(DEFAULT_WUBOOK_TIME_FORMAT), + 'booked_rate': brate, + 'rooms': ','.join(map(str, rooms)), + 'customer_mail': partner.email, + 'customer_country': 'ES', + 'children': 0, + 'payment_gateway_fee': '', + 'modified_reservations': [], + 'customer_surname': ' '.join(partner.name.split(' ')[1:]), + 'date_departure': checkout_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + 'amount_reason': '', + 'customer_city': partner.city, + 'opportunities': 0, + 'date_received': now_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + 'rooms_occupancies': rooms_occu, + 'sessionSeed': '', + 'booked_rooms': booked_rooms, + 'customer_name': partner.name.split(' ')[0], + 'date_arrival': checkin_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + 'status': WUBOOK_STATUS_CONFIRMED, + 'was_modified': 0, + 'channel_reservation_code': crcode, + 'men': max_persons, + 'orig_amount': total_amount, + 'customer_phone': partner.mobile or partner.phone or '', + 'customer_notes': notes, + 'customer_address': partner.street, + 'device': -1, + 'addons_list': [], + 'status_reason': '', + 'roomnight': date_diff-1, + 'boards': '', + 'customer_language': 32, + 'fount': '', + 'channel_data': {}, + 'room_opportunities': 0, + 'customer_zip': partner.zip, + 'amount': total_amount, + 'id_woodoo': id_woodoo, + 'cc_info': 1, + 'customer_language_iso': 'es' + } + + def create_wubook_rooms_values(self, rooms, values): + json_data = {} + _logger.info("=== PASA AAA") + _logger.info(values) + for room in rooms: + for cvalue in values: + json_data.setdefault(room.wrid, []).append({ + 'closed_arrival': cvalue['closed_arrival'], + 'booked': cvalue['booked'], + 'max_stay_arrival': cvalue['max_stay_arrival'], + 'max_stay': cvalue['max_stay'], + 'price': cvalue['price'], + 'min_stay': cvalue['min_stay'], + 'closed_departure': cvalue['closed_departure'], + 'avail': cvalue['avail'], + 'closed': cvalue['closed'], + 'min_stay_arrival': cvalue['min_stay_arrival'], + 'no_ota': cvalue['no_ota'], + }) + return json_data + + def cancel_booking(self, wbooking): + wbooking['status'] = WUBOOK_STATUS_CANCELLED + return wbooking + + @classmethod + def setUpClass(cls): + super(TestHotelWubook, cls).setUpClass() + + # Update Test Virtual Rooms + cls.hotel_vroom_budget.write({ + 'wcapacity': 1, + 'wrid': 3000, + 'wscode': 'T001', + }) + cls.hotel_vroom_special.write({ + 'wcapacity': 2, + 'wrid': 3001, + 'wscode': 'T002', + }) + + # Update Restriction + vroom_restr_obj = cls.env['hotel.virtual.room.restriction'] + default_restriction = vroom_restr_obj.search([ + ('wpid', '=', '0') + ], limit=1) + if default_restriction: + cls.restriction_default_id = default_restriction.id + else: + cls.restriction_1.write({ + 'wpid': '0' + }) + cls.restriction_default_id = cls.restriction_1.id + + # Create Some Wubook Info + cls.wubook_channel_test = cls.env['wubook.channel.info'].create({ + 'wid': 1, + 'name': 'Channel Test' + }) + + @classmethod + def tearDownClass(cls): + # Remove mocks + cls.env['wubook']._revert_method('create_wubook_issue') + cls.env['wubook']._revert_method('is_valid_account') + cls.env['wubook']._revert_method('initialize') + cls.env['wubook']._revert_method('push_activation') + cls.env['wubook']._revert_method('init_connection') + cls.env['wubook']._revert_method('close_connection') + cls.env['wubook']._revert_method('create_room') + cls.env['wubook']._revert_method('modify_room') + cls.env['wubook']._revert_method('delete_room') + cls.env['wubook']._revert_method('import_rooms') + cls.env['wubook']._revert_method('fetch_rooms_values') + cls.env['wubook']._revert_method('update_availability') + cls.env['wubook']._revert_method('corporate_fetch') + cls.env['wubook']._revert_method('create_reservation') + cls.env['wubook']._revert_method('cancel_reservation') + cls.env['wubook']._revert_method('fetch_new_bookings') + cls.env['wubook']._revert_method('fetch_booking') + cls.env['wubook']._revert_method('mark_bookings') + cls.env['wubook']._revert_method('create_plan') + cls.env['wubook']._revert_method('delete_plan') + cls.env['wubook']._revert_method('update_plan_name') + cls.env['wubook']._revert_method('update_plan_prices') + cls.env['wubook']._revert_method('update_plan_periods') + cls.env['wubook']._revert_method('import_pricing_plans') + cls.env['wubook']._revert_method('fetch_plan_prices') + cls.env['wubook']._revert_method('fetch_all_plan_prices') + cls.env['wubook']._revert_method('import_restriction_plans') + cls.env['wubook']._revert_method('fetch_rplan_restrictions') + cls.env['wubook']._revert_method('update_rplan_values') + cls.env['wubook']._revert_method('create_rplan') + cls.env['wubook']._revert_method('rename_rplan') + cls.env['wubook']._revert_method('delete_rplan') + cls.env['wubook']._revert_method('import_channels_info') + + super(TestHotelWubook, cls).tearDownClass() diff --git a/hotel_channel_connector/tests/test_hotel_calendar_management_model.py b/hotel_channel_connector/tests/test_hotel_calendar_management_model.py new file mode 100644 index 000000000..b1c4652d2 --- /dev/null +++ b/hotel_channel_connector/tests/test_hotel_calendar_management_model.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook + + +class TestHotelCalendarManagement(TestHotelWubook): + + def test_save_changes(self): + now_utc_dt = date_utils.now() + adv_utc_dt = now_utc_dt + timedelta(days=3) + vrooms = (self.hotel_vroom_budget,) + + hotel_cal_mngt_obj = self.env['hotel.calendar.management'].sudo( + self.user_hotel_manager) + + # Generate new prices + prices = (144.0, 170.0, 30.0, 50.0) + cprices = {} + for k_item, v_item in enumerate(prices): + ndate_utc_dt = now_utc_dt + timedelta(days=k_item) + cprices.setdefault(self.hotel_vroom_budget.id, []).append({ + 'date': ndate_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'price': v_item + }) + + # Generate new restrictions + restrictions = { + 'min_stay': (3, 2, 4, 1), + 'max_stay': (5, 8, 9, 3), + 'min_stay_arrival': (2, 3, 6, 2), + 'max_stay_arrival': (4, 7, 7, 4), + 'closed_departure': (False, True, False, True), + 'closed_arrival': (True, False, False, False), + 'closed': (False, False, True, True), + } + crestrictions = {} + for i in range(0, 4): + ndate_utc_dt = now_utc_dt + timedelta(days=i) + crestrictions.setdefault(self.hotel_vroom_budget.id, []).append({ + 'date': ndate_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'closed_arrival': restrictions['closed_arrival'][i], + 'max_stay': restrictions['max_stay'][i], + 'min_stay': restrictions['min_stay'][i], + 'closed_departure': restrictions['closed_departure'][i], + 'closed': restrictions['closed'][i], + 'min_stay_arrival': restrictions['min_stay_arrival'][i], + 'max_stay_arrival': restrictions['max_stay_arrival'][i], + }) + + # Generate new availability + avails = (1, 2, 2, 1) + cavails = {} + for k_item, v_item in enumerate(avails): + ndate_utc_dt = now_utc_dt + timedelta(days=k_item) + ndate_dt = date_utils.dt_as_timezone(ndate_utc_dt, self.tz_hotel) + cavails.setdefault(self.hotel_vroom_budget.id, []).append({ + 'date': ndate_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + 'avail': v_item, + 'no_ota': False, + }) + + # Save new values + hotel_cal_mngt_obj.save_changes( + self.parity_pricelist_id, + self.parity_restrictions_id, + cprices, + crestrictions, + cavails) + + # Check data integrity + hcal_data = hotel_cal_mngt_obj.get_hcalendar_all_data( + now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + adv_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + self.parity_pricelist_id, + self.parity_restrictions_id, + True) + + for vroom in vrooms: + for k_pr, v_pr in hcal_data['availability'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual(v_info['avail'], + avails[k_info], + "Hotel Calendar Management \ + Availability doesn't match!") + for k_pr, v_pr in hcal_data['restrictions'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual(v_info['min_stay'], + restrictions['min_stay'][k_info], + "Hotel Calendar Management \ + Restrictions doesn't match!") + self.assertEqual(v_info['max_stay'], + restrictions['max_stay'][k_info], + "Hotel Calendar Management \ + Restrictions doesn't match!") + self.assertEqual( + v_info['min_stay_arrival'], + restrictions['min_stay_arrival'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['max_stay_arrival'], + restrictions['max_stay_arrival'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['closed_departure'], + restrictions['closed_departure'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['closed_arrival'], + restrictions['closed_arrival'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + self.assertEqual( + v_info['closed'], + restrictions['closed'][k_info], + "Hotel Calendar Management Restrictions \ + doesn't match!") + for k_pr, v_pr in hcal_data['prices'].iteritems(): + if k_pr == vroom.id: # Only Check Test Cases + for k_info, v_info in enumerate(v_pr): + self.assertEqual(v_info['price'], + prices[k_info], "Hotel Calendar \ + Management Prices doesn't match!") diff --git a/hotel_channel_connector/tests/test_hotel_folio_model.py b/hotel_channel_connector/tests/test_hotel_folio_model.py new file mode 100644 index 000000000..ef0987b65 --- /dev/null +++ b/hotel_channel_connector/tests/test_hotel_folio_model.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook + + +class TestHotelFolio(TestHotelWubook): + + def test_has_wubook_reservations(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + nreserv = self.env['hotel.reservation'].search([ + ('wrid', '=', processed_rids[0]) + ], order='id ASC', limit=1) + self.assertTrue(nreserv, "Can't found reservation") + self.assertTrue(nreserv.folio_id.whas_wubook_reservations, + "Can't found reservations from wubook") + + def test_import_reservations(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + nreserv = self.env['hotel.reservation'].search([ + ('wrid', '=', processed_rids[0]) + ], order='id ASC', limit=1) + self.assertTrue(nreserv, "Can't found reservation") + nreserv.folio_id.import_reservations() + + def test_action_confirm(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + nreserv = self.env['hotel.reservation'].search([ + ('wrid', '=', processed_rids[0]) + ], order='id ASC', limit=1) + self.assertTrue(nreserv, "Can't found reservation") + nreserv.folio_id.action_confirm() + self.assertEqual(nreserv.folio_id.state, + 'sale', + "Reservation not confirmed") diff --git a/hotel_channel_connector/tests/test_hotel_reservation_model.py b/hotel_channel_connector/tests/test_hotel_reservation_model.py new file mode 100644 index 000000000..c305c36d1 --- /dev/null +++ b/hotel_channel_connector/tests/test_hotel_reservation_model.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.exceptions import UserError +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook + + +class TestHotelReservation(TestHotelWubook): + + def test_is_from_channel(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], # 1 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + }, + channel=self.wubook_channel_test.wid, + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + + # Check Creation + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + hotel_reserv_obj = self.env['hotel.reservation'] + nreserv = hotel_reserv_obj.sudo(self.user_hotel_manager).search([ + ('wrid', 'in', processed_rids) + ]) + self.assertTrue(nreserv, "Reservation not found") + self.assertTrue(nreserv.wis_from_channel) + nreserv.wrid = '' + self.assertFalse(nreserv.wis_from_channel) + + def test_write(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], # 1 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + + # Check Creation + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + hotel_reserv_obj = self.env['hotel.reservation'] + nreserv = hotel_reserv_obj.sudo(self.user_hotel_manager).search([ + ('wrid', 'in', processed_rids) + ]) + self.assertTrue(nreserv, "Reservation not found") + checkin_utc_dt = now_utc_dt + timedelta(days=6) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + nreserv.write({ + 'checkin': checkin_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + 'checkout': checkout_utc_dt.strftime( + DEFAULT_SERVER_DATETIME_FORMAT), + }) + + def test_unlink(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], # 1 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + + # Check Creation + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + hotel_reserv_obj = self.env['hotel.reservation'] + nreserv = hotel_reserv_obj.sudo(self.user_hotel_manager).search([ + ('wrid', 'in', processed_rids) + ]) + self.assertTrue(nreserv, "Reservation not found") + + with self.assertRaises(UserError): + nreserv.sudo(self.user_hotel_manager).unlink() + + def test_action_cancel(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], # 1 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + + # Check Creation + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + hotel_reserv_obj = self.env['hotel.reservation'] + nreserv = hotel_reserv_obj.sudo(self.user_hotel_manager).search([ + ('wrid', 'in', processed_rids) + ]) + self.assertTrue(nreserv, "Reservation not found") + nreserv.sudo(self.user_hotel_manager).action_cancel() + self.assertEqual(nreserv.state, 'cancelled', + "Rervation don't cancelled") diff --git a/hotel_channel_connector/tests/test_hotel_virtual_room_model.py b/hotel_channel_connector/tests/test_hotel_virtual_room_model.py new file mode 100644 index 000000000..91eb66363 --- /dev/null +++ b/hotel_channel_connector/tests/test_hotel_virtual_room_model.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from openerp.exceptions import ValidationError +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook + + +class TestHotelVirtualRoom(TestHotelWubook): + + def test_get_capacity(self): + self.assertEqual(self.hotel_vroom_budget.wcapacity, + 1, + "Invalid wcapacity") + + def test_check_wcapacity(self): + with self.assertRaises(ValidationError): + self.hotel_vroom_budget.sudo(self.user_hotel_manager).write({ + 'wcapacity': 0 + }) + + def test_check_wscode(self): + with self.assertRaises(ValidationError): + self.hotel_vroom_budget.sudo(self.user_hotel_manager).write({ + 'wscode': 'abcdefg' + }) + + def test_get_restrictions(self): + now_utc_dt = date_utils.now() + rests = self.hotel_vroom_budget.sudo( + self.user_hotel_manager).get_restrictions( + now_utc_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT)) + self.assertTrue(any(rests), "Restrictions not found") + + def test_import_rooms(self): + self.hotel_vroom_budget.sudo(self.user_hotel_manager).import_rooms() + + def test_create(self): + vroom_obj = self.env['hotel.virtual.room'] + vroom = vroom_obj.sudo(self.user_hotel_manager).create({ + 'name': 'Budget Room', + 'virtual_code': '001', + 'list_price': 50, + 'wrid': 1234 + }) + vroom.unlink() + + def test_unlink(self): + self.hotel_vroom_budget.sudo(self.user_hotel_manager).unlink() diff --git a/hotel_channel_connector/tests/test_product_pricelist_item_model.py b/hotel_channel_connector/tests/test_product_pricelist_item_model.py new file mode 100644 index 000000000..92803f47f --- /dev/null +++ b/hotel_channel_connector/tests/test_product_pricelist_item_model.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import DEFAULT_SERVER_DATE_FORMAT +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook +import logging +_logger = logging.getLogger(__name__) + + +class TestProductPricelistItem(TestHotelWubook): + + def test_create(self): + now_utc_dt = date_utils.now() + day_utc_dt = now_utc_dt + timedelta(days=20) + budget_product_id = self.hotel_vroom_budget.product_id + pr_item_obj = self.env['product.pricelist.item'] + + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + parity_pricelist.write({'wpid': 1234}) + pricelist_item = pr_item_obj.sudo(self.user_hotel_manager).create({ + 'pricelist_id': self.parity_pricelist_id, + 'date_start': day_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + 'date_end': day_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + 'compute_price': 'fixed', + 'applied_on': '1_product', + 'product_tmpl_id': budget_product_id.product_tmpl_id.id, + 'fixed_price': 99.0, + }) + self.assertTrue(pricelist_item, "Can't create test pricelist") + self.assertFalse(pricelist_item.wpushed, "Invalid pushed status") + + def test_write(self): + now_utc_dt = date_utils.now() + day_utc_dt = now_utc_dt + timedelta(days=20) + budget_product_id = self.hotel_vroom_budget.product_id + pr_item_obj = self.env['product.pricelist.item'] + + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + parity_pricelist.write({'wpid': 1234}) + pricelist_item = pr_item_obj.sudo(self.user_hotel_manager).create({ + 'pricelist_id': self.parity_pricelist_id, + 'date_start': day_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + 'date_end': day_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + 'compute_price': 'fixed', + 'applied_on': '1_product', + 'product_tmpl_id': budget_product_id.product_tmpl_id.id, + 'fixed_price': 99.0, + }) + self.assertTrue(pricelist_item, "Can't create test pricelist") + + pricelist_item.write({'fixed_price': 30.0}) + self.assertEqual(pricelist_item.fixed_price, 30.0, "Invalid price") diff --git a/hotel_channel_connector/tests/test_product_pricelist_model.py b/hotel_channel_connector/tests/test_product_pricelist_model.py new file mode 100644 index 000000000..63abc6438 --- /dev/null +++ b/hotel_channel_connector/tests/test_product_pricelist_model.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from .common import TestHotelWubook + + +class TestProductPricelist(TestHotelWubook): + + def test_get_wubook_prices(self): + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + wprices = parity_pricelist.sudo( + self.user_hotel_manager).get_wubook_prices() + self.assertTrue(any(wprices), "Can't get any price for wubook") + + def test_create(self): + npricelist = self.env['product.pricelist'].sudo( + self.user_hotel_manager).create({ + 'name': 'Pricelist Test #1' + }) + self.assertTrue(npricelist, "Can't create test pricelist") + + def test_write(self): + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + parity_pricelist.sudo(self.user_hotel_manager).write({ + 'name': 'Pricelist Test New Name #1' + }) + self.assertEqual( + parity_pricelist.name, + 'Pricelist Test New Name #1', + 'Invalid pricelist name') + + def test_unlink(self): + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + parity_pricelist.sudo(self.user_hotel_manager).unlink() + + def test_import_price_plans(self): + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + parity_pricelist.import_price_plans() + + def test_name_get(self): + parity_pricelist = self.env['product.pricelist'].browse([ + self.parity_pricelist_id]) + rest_name = parity_pricelist.sudo(self.user_hotel_manager).name_get() + self.assertTrue('WuBook' in rest_name[0][1], 'Invalid Name') + parity_pricelist.sudo(self.user_hotel_manager).write({'wpid': ''}) + rest_name = parity_pricelist.sudo(self.user_hotel_manager).name_get() + self.assertFalse('WuBook' in rest_name[0][1], 'Invalid Name') diff --git a/hotel_channel_connector/tests/test_res_partner_model.py b/hotel_channel_connector/tests/test_res_partner_model.py new file mode 100644 index 000000000..5296ce3b2 --- /dev/null +++ b/hotel_channel_connector/tests/test_res_partner_model.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook +import logging +_logger = logging.getLogger(__name__) + + +class TestResPartner(TestHotelWubook): + + def test_write(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [ + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_1, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + ) + ] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + self.partner_2.sudo(self.user_hotel_manager).write({ + 'vat': 'ES00000000T' + }) + self.partner_1.sudo(self.user_hotel_manager).write({ + 'vat': 'ES00000000T', + 'unconfirmed': True, + }) + reservation = self.env['hotel.reservation'].search([ + ('wrid', '=', processed_rids[1]) + ], order='id ASC', limit=1) + self.assertTrue(reservation, "Can't found reservation") + self.assertFalse(self.partner_1.active, "Uncofirmed user still active") + self.assertEqual(reservation.partner_id.id, + self.partner_2.id, + "Old Partner not changed") diff --git a/hotel_channel_connector/tests/test_reservation_restriction_item_model.py b/hotel_channel_connector/tests/test_reservation_restriction_item_model.py new file mode 100644 index 000000000..85da887be --- /dev/null +++ b/hotel_channel_connector/tests/test_reservation_restriction_item_model.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook + + +class TestReservationRestrictionItem(TestHotelWubook): + + def test_write(self): + now_utc_dt = date_utils.now() + day_utc_dt = now_utc_dt + timedelta(days=20) + day_utc_str = day_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT) + rest_item_obj = self.env['hotel.virtual.room.restriction.item'] + restriction = rest_item_obj.search([], limit=1) + self.assertTrue(restriction, "Can't found restriction for test") + restriction.write({ + 'min_stay': 3, + 'date_start': day_utc_str + }) + self.assertEqual(restriction.min_stay, 3, "Invalid Max Avail") + self.assertEqual(restriction.date_start, day_utc_str, "Invalid Date") diff --git a/hotel_channel_connector/tests/test_reservation_restriction_model.py b/hotel_channel_connector/tests/test_reservation_restriction_model.py new file mode 100644 index 000000000..0355bb837 --- /dev/null +++ b/hotel_channel_connector/tests/test_reservation_restriction_model.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from .common import TestHotelWubook +import logging +_logger = logging.getLogger(__name__) + + +class TestReservationRestriction(TestHotelWubook): + + def test_get_wubook_restrictions(self): + wrests = self.restriction_1.sudo(self.user_hotel_manager).\ + get_wubook_restrictions() + self.assertTrue(any(wrests), "Any restriction found") + + def test_create(self): + vroo_restriction_obj = self.env['hotel.virtual.room.restriction'] + # Restriction Plan + restriction = vroo_restriction_obj.sudo(self.user_hotel_manager).\ + create({ + 'name': 'Restriction Test #1', + 'active': True + }) + self.assertTrue(restriction, "Can't create new restriction") + + def test_write(self): + vroo_restriction_obj = self.env['hotel.virtual.room.restriction'] + # Restriction Plan + restriction = vroo_restriction_obj.sudo(self.user_hotel_manager).\ + create({ + 'name': 'Restriction Test #1', + 'active': True + }) + self.assertTrue(restriction, "Can't create new restriction") + restriction.sudo(self.user_hotel_manager).write({ + 'name': 'Restriction Test Modif #1' + }) + self.assertEqual( + restriction.name, + 'Restriction Test Modif #1', + "Can't modif restriction") + + def test_unlink(self): + vroo_restriction_obj = self.env['hotel.virtual.room.restriction'] + # Restriction Plan + restriction = vroo_restriction_obj.sudo(self.user_hotel_manager).\ + create({ + 'name': 'Restriction Test #1', + 'active': True, + 'wpid': 1234, + }) + self.assertTrue(restriction, "Can't create new restriction") + restriction.sudo(self.user_hotel_manager).unlink() + + def test_import_restriction_plans(self): + vroo_restriction_obj = self.env['hotel.virtual.room.restriction'] + # Restriction Plan + restriction = vroo_restriction_obj.sudo(self.user_hotel_manager).\ + create({ + 'name': 'Restriction Test #1', + 'active': True, + 'wpid': 1234, + }) + self.assertTrue(restriction, "Can't create new restriction") + restriction.sudo(self.user_hotel_manager).import_restriction_plans() + + def test_name_get(self): + vroo_restriction_obj = self.env['hotel.virtual.room.restriction'] + # Restriction Plan + restriction = vroo_restriction_obj.sudo(self.user_hotel_manager).\ + create({ + 'name': 'Restriction Test #1', + 'active': True, + }) + self.assertTrue(restriction, "Can't create new restriction") + rest_name = restriction.sudo(self.user_hotel_manager).name_get() + self.assertTrue('WuBook' in rest_name[0][1], 'Invalid Name') + restriction.sudo(self.user_hotel_manager).write({'wpid': ''}) + rest_name = restriction.sudo(self.user_hotel_manager).name_get() + self.assertFalse('WuBook' in rest_name[0][1], 'Invalid Name') diff --git a/hotel_channel_connector/tests/test_virtual_room_availability_model.py b/hotel_channel_connector/tests/test_virtual_room_availability_model.py new file mode 100644 index 000000000..47e48690f --- /dev/null +++ b/hotel_channel_connector/tests/test_virtual_room_availability_model.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from .common import TestHotelWubook +from openerp.exceptions import ValidationError +from odoo.addons.hotel import date_utils +from openerp.tools import DEFAULT_SERVER_DATE_FORMAT + + +class TestVirtualRoomAvailability(TestHotelWubook): + + def test_write(self): + now_utc_dt = date_utils.now() + day_utc_dt = now_utc_dt + timedelta(days=1) + vroom_avail_obj = self.env['hotel.virtual.room.availability'] + avail = vroom_avail_obj.search([ + ('virtual_room_id', '=', self.hotel_vroom_budget.id), + ('date', '=', now_utc_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)) + ], limit=1) + avail.write({ + 'avail': 1, + }) + self.assertEqual(avail.avail, 1, "Invalid avail") diff --git a/hotel_channel_connector/tests/test_wubook.py b/hotel_channel_connector/tests/test_wubook.py new file mode 100644 index 000000000..f7b48c77e --- /dev/null +++ b/hotel_channel_connector/tests/test_wubook.py @@ -0,0 +1,608 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import datetime, timedelta +from openerp.tools import ( + DEFAULT_SERVER_DATETIME_FORMAT, + DEFAULT_SERVER_DATE_FORMAT) +from odoo.addons.hotel_wubook_proto.wubook import DEFAULT_WUBOOK_DATE_FORMAT +from openerp.exceptions import ValidationError +from .common import TestHotelWubook +from odoo.addons.hotel import date_utils +import pytz +import logging +_logger = logging.getLogger(__name__) + + +class TestWubook(TestHotelWubook): + + def test_simple_booking(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], # 1 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + + # Check Creation + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + nreserv = self.env['hotel.reservation'].search([ + ('wrid', 'in', processed_rids) + ], order='id ASC') + self.assertTrue(nreserv, "Reservation not found") + self.assertEqual(nreserv.state, 'draft', "Invalid reservation state") + nfolio = self.env['hotel.folio'].search([ + ('id', '=', nreserv.folio_id.id) + ], limit=1) + self.assertTrue(nfolio, "Folio not found") + self.assertEqual(nfolio.state, 'draft', "Invalid folio state") + + # Check Dates + self.assertEqual( + nreserv.checkin, + checkin_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + "Invalid Checkin Reservation Date") + self.assertEqual( + nreserv.checkout, + checkout_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + "Invalid Checkout Reservation Date") + # Check Price + self.assertEqual(nreserv.price_unit, 30.0, "Invalid Reservation Price") + # Check Reservation Lines + self.assertTrue(any(nreserv.reservation_line_ids), + "Reservation lines snot found") + dates_arr = date_utils.generate_dates_list(checkin_dt, date_diff-1) + for k_line, v_line in enumerate(nreserv.reservation_line_ids): + self.assertEqual(dates_arr[k_line], v_line['date'], + "Invalid Reservation Lines Dates") + + def test_complex_booking(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1, 1], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + + # Check Creation + self.assertTrue(any(processed_rids), "Reservation not found") + self.assertFalse(errors, "Reservation errors") + nreservs = self.env['hotel.reservation'].search([ + ('wrid', 'in', processed_rids) + ], order='id ASC') + self.assertEqual(len(nreservs), 2, "Reservations not found") + + for nreserv in nreservs: + # Check State + self.assertEqual(nreserv.state, 'draft', + "Invalid reservation state") + + # Check Dates + self.assertEqual( + nreserv.checkin, + checkin_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + "Invalid Checkin Reservation Date") + self.assertEqual( + nreserv.checkout, + checkout_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + "Invalid Checkout Reservation Date") + # Check Price + self.assertEqual(nreserv.price_unit, 30.0, + "Invalid Reservation Price") + # Check Reservation Lines + self.assertTrue(any(nreserv.reservation_line_ids), + "Reservation lines snot found") + dates_arr = date_utils.generate_dates_list(checkin_dt, date_diff-1) + for k_line, v_line in enumerate(nreserv.reservation_line_ids): + self.assertEqual(dates_arr[k_line], v_line['date'], + "Invalid Reservation Lines Dates") + + def test_complex_bookings(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + wbooks = [ + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + (checkin_dt - timedelta(days=3)).strftime( + DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + (checkin_dt + timedelta(days=3)).strftime( + DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + ) + ] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 3, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + def test_cancel_booking(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + def check_state(wrids, state): + reservs = self.env['hotel.reservation'].sudo().search([ + ('wrid', 'in', wrids) + ]) + self.assertTrue(any(reservs), "Reservations not found") + for reserv in reservs: + self.assertEqual( + reserv.state, state, "Reservation state invalid") + + # Create Reservation + nbook = self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + }, channel=self.wubook_channel_test.wid) + wbooks = [nbook] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 1, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + # Cancel It + wbooks = [self.cancel_booking(nbook)] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 1, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + check_state(processed_rids, 'cancelled') + # Can't confirm cancelled bookings + reserv = self.env['hotel.reservation'].sudo().search([ + ('wrid', 'in', processed_rids) + ], limit=1) + with self.assertRaises(ValidationError): + reserv.confirm() + + # Create Reservation and Cancel It + nbook = self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + }) + cbook = self.cancel_booking(nbook) + wbooks = [nbook, cbook] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 2, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + check_state(processed_rids, 'cancelled') + + def test_splitted_booking(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + book_a = self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + ) + book_b = self.create_wubook_booking( + self.user_hotel_manager, + (checkin_dt + timedelta(days=2)).strftime( + DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + ) + wbooks = [book_a, book_b] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 2, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + reserv = self.env['hotel.reservation'].search([ + ('wrid', '=', book_b['reservation_code']) + ], order='id ASC', limit=1) + self.assertTrue(reserv, "Rervation doesn't exists") + self.assertEqual( + reserv.product_id.id, + self.hotel_room_simple_100.product_id.id, + "Unexpected room assigned") + reserv.product_id = \ + self.hotel_room_simple_101.product_id.id + + wbooks = [ + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0, 20.0, 17.0] + } + } + ) + ] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 1, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + + # Check Splitted Integrity + nreservs = self.env['hotel.reservation'].search([ + ('wrid', 'in', processed_rids) + ], order="id ASC") + _logger.info(nreservs) + self.assertEqual(len(nreservs), 2, "Reservations not found") + date_dt = date_utils.get_datetime(nreservs[0].checkin) + self.assertEqual(nreservs[0].reservation_line_ids[0].date, + date_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + "Invalid split") + date_dt = date_utils.get_datetime(nreservs[1].checkin) + self.assertEqual(nreservs[1].reservation_line_ids[0].date, + date_dt.strftime(DEFAULT_SERVER_DATE_FORMAT), + "Invalid split") + self.assertEqual(nreservs[0].price_unit, + 30.0, + "Invalid split price") + self.assertEqual(nreservs[1].price_unit, + 37.0, + "Invalid split price") + self.assertEqual(nreservs[1].parent_reservation.id, + nreservs[0].id, + "Invalid split parent reservation") + self.assertEqual(nreservs[0].product_id.id, + self.hotel_room_simple_101.product_id.id, + "Invalid room assigned") + self.assertEqual(nreservs[1].product_id.id, + self.hotel_room_simple_100.product_id.id, + "Invalid room assigned") + + def test_invalid_booking(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=2) + date_diff = date_utils.date_diff(checkin_utc_dt, checkout_utc_dt, + hours=False) + 1 + + # Invalid Occupancy + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [3], + 'dayprices': [15.0, 15.0] + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertTrue(errors, "Invalid reservation created") + self.assertFalse(any(processed_rids), "Invalid reservation created") + + # No Real Rooms Avail + wbooks = [self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2, 1], + 'dayprices': [15.0, 15.0] + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertFalse(errors, "Invalid reservation created") + self.assertTrue(any(processed_rids), "Invalid reservation created") + + nreservs = self.env['hotel.reservation'].search([ + ('wrid', 'in', processed_rids) + ], order='id ASC') + + self.assertEqual(nreservs[0].state, + 'draft', + "Overbooking don't handled") + self.assertTrue(nreservs[1].overbooking, + "Overbooking don't handled") + + # No Real Rooms Avail + wbooks = [ + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + (checkin_dt - timedelta(days=1)).strftime( + DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + (checkin_dt + timedelta(days=1)).strftime( + DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + } + ), + ] + + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 3, "Invalid Reservation created") + self.assertFalse(errors, "Invalid Reservation created") + nreservs = self.env['hotel.reservation'].search([ + ('wrid', 'in', processed_rids) + ], order='id ASC') + for nreserv in nreservs: + self.assertTrue(nreserv.overbooking, "Overbooking don't handled") + + def text_invalid_booking_amount(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + + # Create Reservation + num_issues = self.env['wubook.issue'].search_count([]) + nbook = self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_special.wrid: { + 'occupancy': [2], # 2 Reservation Line + 'dayprices': [15.0, 15.0] # 2 Days + } + }, channel=self.wubook_channel_test.wid) + nbook['amount'] = 30.75 + wbooks = [nbook] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertEqual(len(processed_rids), 1, "Reservation not found") + self.assertFalse(errors, "Reservation errors") + self.assertNotEqual(self.env['wubook.issue'].search_count([]), num_issues) + + def test_overbooking(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, self.tz_hotel) + + # Invalid Occupancy + wbooks = [ + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + ), + self.create_wubook_booking( + self.user_hotel_manager, + checkin_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT), + self.partner_2, + { + self.hotel_vroom_budget.wrid: { + 'occupancy': [1], + 'dayprices': [15.0, 15.0] + } + } + )] + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.env['wubook'].sudo().generate_reservations(wbooks) + self.assertFalse(errors, "Overbooking don't handled") + self.assertTrue(any(processed_rids), "Overbooking don't handled") + nreservs = self.env['hotel.reservation'].search([ + ('wrid', 'in', processed_rids) + ], order="id ASC") + self.assertFalse(nreservs[0].overbooking, + "Overbooking don't handled") + self.assertFalse(nreservs[1].overbooking, + "Overbooking don't handled") + self.assertTrue(nreservs[2].overbooking, + "Overbooking don't handled") + + def test_generate_room_values(self): + now_utc_dt = date_utils.now() + checkin_utc_dt = now_utc_dt + timedelta(days=3) + checkin_dt = date_utils.dt_as_timezone(checkin_utc_dt, + self.tz_hotel) + checkout_utc_dt = checkin_utc_dt + timedelta(days=1) + checkout_dt = date_utils.dt_as_timezone(checkout_utc_dt, + self.tz_hotel) + vroom_restr_item_obj = self.env['hotel.virtual.room.restriction.item'] + + vrooms = [self.hotel_vroom_budget, self.hotel_vroom_special] + values = self.create_wubook_rooms_values( + vrooms, + [{ + 'closed_arrival': 0, + 'booked': 0, + 'max_stay_arrival': 9, + 'max_stay': 0, + 'price': 150.0, + 'min_stay': 0, + 'closed_departure': '1', + 'avail': 0, + 'closed': 0, + 'min_stay_arrival': 0, + 'no_ota': 0, + }, { + 'closed_arrival': 0, + 'booked': 0, + 'max_stay_arrival': 9, + 'max_stay': 0, + 'price': 50.0, + 'min_stay': 0, + 'closed_departure': '1', + 'avail': 0, + 'closed': 0, + 'min_stay_arrival': 0, + 'no_ota': 0, + }]) + self.env['wubook'].sudo().generate_room_values( + checkin_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + checkout_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + values) + + for vroom in vrooms: + items = vroom_restr_item_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date_start', + '>=', checkin_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)), + ('date_end', + '<=', checkout_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)), + ('restriction_id', '=', self.restriction_default_id) + ]) + self.assertTrue(any(items), + "Hotel Wubook Invalid fetch room values") + for item in items: + self.assertTrue( + item.closed_departure, + "Hotel Wubook Invalid fetch room values") + self.assertEqual( + item.max_stay_arrival, + 9, + "Hotel Wubook Invalid fetch room values") diff --git a/hotel_channel_connector/tests/test_wubook_channel_info_model.py b/hotel_channel_connector/tests/test_wubook_channel_info_model.py new file mode 100644 index 000000000..890ef516a --- /dev/null +++ b/hotel_channel_connector/tests/test_wubook_channel_info_model.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import timedelta +from odoo.addons.hotel import date_utils +from .common import TestHotelWubook + + +class TestWubookChannelInfo(TestHotelWubook): + + def test_import_channels_info(self): + now_utc_dt = date_utils.now() + day_utc_dt = now_utc_dt + timedelta(days=20) + info_channel = self.env['wubook.channel.info'].create({ + 'wid': 1234, + 'name': 'Test Channel', + }) + self.assertTrue(info_channel, "Can't create test channel info") + info_channel.import_channels_info() diff --git a/hotel_channel_connector/tests/test_wubook_issue_model.py b/hotel_channel_connector/tests/test_wubook_issue_model.py new file mode 100644 index 000000000..da2ac6e86 --- /dev/null +++ b/hotel_channel_connector/tests/test_wubook_issue_model.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.exceptions import ValidationError +from .common import TestHotelWubook + + +class TestWubookIssue(TestHotelWubook): + + def test_mark_readed(self): + wubook_issue_obj = self.env['wubook.issue'] + issue_a = wubook_issue_obj.create({ + 'section': 'wubook', + 'message': 'Testing #1', + }) + self.assertTrue(issue_a, "Can't create issues") + issue_a.sudo(self.user_hotel_manager).mark_readed() + self.assertFalse(issue_a.to_read, "Can't mark issue as readed") + + def test_toggle_to_read(self): + wubook_issue_obj = self.env['wubook.issue'] + issue_a = wubook_issue_obj.create({ + 'section': 'wubook', + 'message': 'Testing #1', + }) + self.assertTrue(issue_a, "Can't create issues") + issue_a.sudo(self.user_hotel_manager).toggle_to_read() + self.assertFalse(issue_a.to_read, "Can't toggle read status") + + def test_mark_as_read(self): + wubook_issue_obj = self.env['wubook.issue'] + issue_a = wubook_issue_obj.create({ + 'section': 'reservation', + 'message': 'Testing #1', + 'wid': 'test', + }) + self.assertTrue(issue_a, "Can't create issues") + issue_a.sudo(self.user_hotel_manager).mark_as_read() diff --git a/hotel_channel_connector/views/general.xml b/hotel_channel_connector/views/general.xml new file mode 100644 index 000000000..1fe1dcae3 --- /dev/null +++ b/hotel_channel_connector/views/general.xml @@ -0,0 +1,11 @@ + + + + + + + \ No newline at end of file diff --git a/hotel_channel_connector/views/inherited_hotel_folio_views.xml b/hotel_channel_connector/views/inherited_hotel_folio_views.xml new file mode 100644 index 000000000..f50517e74 --- /dev/null +++ b/hotel_channel_connector/views/inherited_hotel_folio_views.xml @@ -0,0 +1,42 @@ + + + + + hotel.folio + + + + + + + + + + + hotel.folio + + + + + + + + {'readonly': [('wis_from_channel', '!=', False)]} + + + {'readonly': [('wis_from_channel', '!=', False)]} + + + + + + + {'readonly': [('wis_from_channel', '!=', False)]} + + + {'readonly': [('wis_from_channel', '!=', False)]} + + + + + diff --git a/hotel_channel_connector/views/inherited_hotel_reservation_views.xml b/hotel_channel_connector/views/inherited_hotel_reservation_views.xml new file mode 100644 index 000000000..cf58536e5 --- /dev/null +++ b/hotel_channel_connector/views/inherited_hotel_reservation_views.xml @@ -0,0 +1,112 @@ + + + + + hotel.reservation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {'readonly': [('wis_from_channel','=',True),('able_to_modify_wubook','=',False)]} + + + {'readonly': [('wrid','!=',False),('able_to_modify_wubook','=',False)]} + + + {'readonly': [('wis_from_channel','=',True),('able_to_modify_wubook','=',False)]} + + + {'readonly': [('wis_from_channel','=',True),('able_to_modify_wubook','=',False)]} + + + {'readonly': [('wis_from_channel','=',True),('able_to_modify_wubook','=',False)]} + + + {'readonly': [('wis_from_channel','=',True),('able_to_modify_wubook','=',False)]} + + + + + + + + hotel.reservation + + + + + + + + + + + hotel.reservation + + + + + + + + + + + + + + view.hotel.reservation.graph + hotel.reservation + + + + + + + + + + + view.hotel.pivot.graph + hotel.reservation + + + + + + + + + + diff --git a/hotel_channel_connector/views/inherited_hotel_virtual_room_availability_views.xml b/hotel_channel_connector/views/inherited_hotel_virtual_room_availability_views.xml new file mode 100644 index 000000000..4cf867141 --- /dev/null +++ b/hotel_channel_connector/views/inherited_hotel_virtual_room_availability_views.xml @@ -0,0 +1,26 @@ + + + + + + hotel.virtual.room.availability + + + + + + + + + + + hotel.virtual.room.availability + + tree + + + + + + + diff --git a/hotel_channel_connector/views/inherited_hotel_virtual_room_views.xml b/hotel_channel_connector/views/inherited_hotel_virtual_room_views.xml new file mode 100644 index 000000000..64a54b3f0 --- /dev/null +++ b/hotel_channel_connector/views/inherited_hotel_virtual_room_views.xml @@ -0,0 +1,16 @@ + + + + + hotel.virtual.room + + + + + + + + + + + \ No newline at end of file diff --git a/hotel_channel_connector/views/inherited_product_pricelist_item_views.xml b/hotel_channel_connector/views/inherited_product_pricelist_item_views.xml new file mode 100644 index 000000000..6ce838576 --- /dev/null +++ b/hotel_channel_connector/views/inherited_product_pricelist_item_views.xml @@ -0,0 +1,19 @@ + + + + + product.pricelist.item + + + + + + + + {'readonly': [('wdaily', '=', True)]} + + + + + + diff --git a/hotel_channel_connector/views/inherited_product_pricelist_views.xml b/hotel_channel_connector/views/inherited_product_pricelist_views.xml new file mode 100644 index 000000000..2e7fca25f --- /dev/null +++ b/hotel_channel_connector/views/inherited_product_pricelist_views.xml @@ -0,0 +1,31 @@ + + + + + product.pricelist + + + +
    +
    +
    + + + + + +
    +
    + + + product.pricelist + + + + + + + + +
    \ No newline at end of file diff --git a/hotel_channel_connector/views/inherited_res_partner_views.xml b/hotel_channel_connector/views/inherited_res_partner_views.xml new file mode 100644 index 000000000..e61e40a31 --- /dev/null +++ b/hotel_channel_connector/views/inherited_res_partner_views.xml @@ -0,0 +1,18 @@ + + + + + + res.partner + + + + + + + + + + + + diff --git a/hotel_channel_connector/views/inherited_reservation_restriction_item_views.xml b/hotel_channel_connector/views/inherited_reservation_restriction_item_views.xml new file mode 100644 index 000000000..ec38b02ee --- /dev/null +++ b/hotel_channel_connector/views/inherited_reservation_restriction_item_views.xml @@ -0,0 +1,14 @@ + + + + + hotel.virtual.room.restriction.item + + + + True + + + + + diff --git a/hotel_channel_connector/views/inherited_reservation_restriction_views.xml b/hotel_channel_connector/views/inherited_reservation_restriction_views.xml new file mode 100644 index 000000000..fb6407352 --- /dev/null +++ b/hotel_channel_connector/views/inherited_reservation_restriction_views.xml @@ -0,0 +1,20 @@ + + + + + hotel.virtual.room.restriction + + + +
    +
    +
    + + + + +
    +
    + +
    diff --git a/hotel_channel_connector/views/res_config_views.xml b/hotel_channel_connector/views/res_config_views.xml new file mode 100644 index 000000000..f2147694c --- /dev/null +++ b/hotel_channel_connector/views/res_config_views.xml @@ -0,0 +1,43 @@ + + + + + + WuBook Settings + wubook.config.settings + +
    +
    +
    + +
    + +
    +
    + + + + + + + + + + + +
    +
    +
    +
    +
    + +
    diff --git a/hotel_channel_connector/views/wubook_channel_info_views.xml b/hotel_channel_connector/views/wubook_channel_info_views.xml new file mode 100644 index 000000000..fcfa1de86 --- /dev/null +++ b/hotel_channel_connector/views/wubook_channel_info_views.xml @@ -0,0 +1,33 @@ + + + + + + wubook.channel.info.form + wubook.channel.info + +
    + + + + + + + +
    +
    +
    + + + + wubook.channel.info.tree + wubook.channel.info + + + + + + + + +
    diff --git a/hotel_channel_connector/views/wubook_issue_views.xml b/hotel_channel_connector/views/wubook_issue_views.xml new file mode 100644 index 000000000..bd4425dc4 --- /dev/null +++ b/hotel_channel_connector/views/wubook_issue_views.xml @@ -0,0 +1,71 @@ + + + + + + wubook.issue.form + wubook.issue + +
    + +
    + +
    + + + + + + + + + + + + +
    +
    +
    +
    + + + + wubook.issue.tree + wubook.issue + tree + + + + + + + + + + + + + + + wubook.issue.search + wubook.issue + + + + + + + + + + + + +
    diff --git a/hotel_channel_connector/wizard/__init__.py b/hotel_channel_connector/wizard/__init__.py new file mode 100644 index 000000000..689ca52b8 --- /dev/null +++ b/hotel_channel_connector/wizard/__init__.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from . import wubook_installer +from . import wubook_import_plan_prices +from . import wubook_import_plan_restrictions +from . import wubook_import_availability +from . import inherited_massive_changes +from . import inherited_duplicate_reservation +from . import inherited_massive_price_reservation_days diff --git a/hotel_channel_connector/wizard/inherited_duplicate_reservation.py b/hotel_channel_connector/wizard/inherited_duplicate_reservation.py new file mode 100644 index 000000000..3e104d3a1 --- /dev/null +++ b/hotel_channel_connector/wizard/inherited_duplicate_reservation.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.exceptions import ValidationError +from openerp import models, api, _ + + +class MassiveChangesWizard(models.TransientModel): + _inherit = 'hotel.wizard.duplicate.reservation' + + @api.multi + def duplicate_reservation(self): + reservation_id = self.env['hotel.reservation'].browse( + self.env.context.get('active_id')) + if reservation_id and reservation_id.wis_from_channel: + raise ValidationError(_("Can't duplicate a reservation from channel")) + return super(MassiveChangesWizard, self).duplicate_reservation() diff --git a/hotel_channel_connector/wizard/inherited_massive_changes.py b/hotel_channel_connector/wizard/inherited_massive_changes.py new file mode 100644 index 000000000..7c381d2e5 --- /dev/null +++ b/hotel_channel_connector/wizard/inherited_massive_changes.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from datetime import datetime, timedelta +from openerp.exceptions import ValidationError +from openerp import models, api + + +class MassiveChangesWizard(models.TransientModel): + _inherit = 'hotel.wizard.massive.changes' + + @api.model + def _get_availability_values(self, ndate, vroom, record): + vals = super(MassiveChangesWizard, self)._get_availability_values( + ndate, vroom, record) + vals.update({ + 'wmax_avail': vals['avail'] + }) + return vals + + @api.multi + def massive_change(self): + res = super(MassiveChangesWizard, self).massive_change() + self.env['wubook'].push_changes() + return res diff --git a/hotel_channel_connector/wizard/inherited_massive_price_reservation_days.py b/hotel_channel_connector/wizard/inherited_massive_price_reservation_days.py new file mode 100644 index 000000000..46445a927 --- /dev/null +++ b/hotel_channel_connector/wizard/inherited_massive_price_reservation_days.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2018 Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.exceptions import ValidationError +from openerp import models, api, _ + + +class MassivePriceChangeWizard(models.TransientModel): + _inherit = 'hotel.wizard.massive.price.reservation.days' + + @api.multi + def massive_price_change_days(self): + self.ensure_one() + hotel_reservation_obj = self.env['hotel.reservation'] + reservation_id = hotel_reservation_obj.browse( + self.env.context.get('active_id')) + if not reservation_id: + return False + + if reservation_id.wis_from_channel: + raise ValidationError( + _("Can't change prices of reservations from OTA's")) + + return super(MassivePriceChangeWizard, self).massive_price_change_days() diff --git a/hotel_channel_connector/wizard/wubook_import_availability.py b/hotel_channel_connector/wizard/wubook_import_availability.py new file mode 100644 index 000000000..ce2b748cd --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_import_availability.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.exceptions import ValidationError +from openerp import models, fields, api, _ +from ..wubook import DEFAULT_WUBOOK_DATE_FORMAT + + +class ImportAvailabilityWizard(models.TransientModel): + _name = 'wubook.wizard.availability' + + date_start = fields.Datetime('Start Date', required=True) + date_end = fields.Datetime('End Date', required=True) + set_wmax_avail = fields.Boolean('Set wmax_avail?', default=True) + + @api.multi + def import_availability(self): + for record in self: + date_start_dt = fields.Datetime.from_string(record.date_start) + date_end_dt = fields.Datetime.from_string(record.date_end) + wres = self.env['wubook'].fetch_rooms_values( + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + set_wmax_avail=record.set_wmax_avail) + if not wres: + raise ValidationError(_("Can't fetch availability from WuBook")) + return True diff --git a/hotel_channel_connector/wizard/wubook_import_availability.xml b/hotel_channel_connector/wizard/wubook_import_availability.xml new file mode 100644 index 000000000..24f35482e --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_import_availability.xml @@ -0,0 +1,40 @@ + + + + + wubook.wizard.availability + wubook.wizard.availability + +
    + + + + + + + + + + + +
    +
    +
    +
    +
    + + + Import Availability + ir.actions.act_window + wubook.wizard.availability + + form + form + new + + +
    diff --git a/hotel_channel_connector/wizard/wubook_import_plan_prices.py b/hotel_channel_connector/wizard/wubook_import_plan_prices.py new file mode 100644 index 000000000..42463e8f8 --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_import_plan_prices.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.exceptions import ValidationError +from openerp import models, fields, api, _ +from odoo.addons.hotel import date_utils +from ..wubook import DEFAULT_WUBOOK_DATE_FORMAT + + +class ImportPlanPricesWizard(models.TransientModel): + _name = 'wubook.wizard.plan.prices' + + date_start = fields.Datetime('Start Date', required=True) + date_end = fields.Datetime('End Date', required=True) + + @api.multi + def import_plan_prices(self): + pricelist_id = self.env['product.pricelist'].browse( + self.env.context.get('active_id')) + if pricelist_id: + for record in self: + date_start_dt = date_utils.get_datetime(record.date_start) + date_end_dt = date_utils.get_datetime(record.date_end) + wres = self.env['wubook'].fetch_plan_prices( + pricelist_id.wpid, + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT)) + if not wres: + raise ValidationError(_("Can't fetch plan prices \ + from WuBook")) + return True diff --git a/hotel_channel_connector/wizard/wubook_import_plan_prices.xml b/hotel_channel_connector/wizard/wubook_import_plan_prices.xml new file mode 100644 index 000000000..72af6ce06 --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_import_plan_prices.xml @@ -0,0 +1,37 @@ + + + + + wubook.wizard.plan.prices + wubook.wizard.plan.prices + +
    + + + + + + + + +
    +
    +
    +
    +
    + + + Import Plan Prices + ir.actions.act_window + wubook.wizard.plan.prices + + form + form + new + + +
    diff --git a/hotel_channel_connector/wizard/wubook_import_plan_restrictions.py b/hotel_channel_connector/wizard/wubook_import_plan_restrictions.py new file mode 100644 index 000000000..e46c5e813 --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_import_plan_restrictions.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +from openerp.exceptions import ValidationError +from openerp import models, fields, api, _ +from odoo.addons.hotel import date_utils +from ..wubook import DEFAULT_WUBOOK_DATE_FORMAT + + +class ImportPlanRestrictionsWizard(models.TransientModel): + _name = 'wubook.wizard.plan.restrictions' + + date_start = fields.Datetime('Start Date', required=True) + date_end = fields.Datetime('End Date', required=True) + + @api.multi + def import_plan_restrictions(self): + restriction_id = self.env['hotel.virtual.room.restriction'].browse( + self.env.context.get('active_id')) + if restriction_id: + for record in self: + date_start_dt = date_utils.get_datetime(record.date_start) + date_end_dt = date_utils.get_datetime(record.date_end) + if int(restriction_id.wpid) == 0: + wres = self.env['wubook'].fetch_rooms_values( + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT)) + else: + wres = self.env['wubook'].fetch_rplan_restrictions( + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + restriction_id.wpid) + if not wres: + raise ValidationError(_("Can't fetch restrictions \ + from WuBook")) + return True diff --git a/hotel_channel_connector/wizard/wubook_import_plan_restrictions.xml b/hotel_channel_connector/wizard/wubook_import_plan_restrictions.xml new file mode 100644 index 000000000..f182739d2 --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_import_plan_restrictions.xml @@ -0,0 +1,38 @@ + + + + + wubook.wizard.plan.prices + wubook.wizard.plan.prices + +
    + + + + + + + + +
    +
    +
    +
    +
    + + + Import Plan Restrictions + ir.actions.act_window + wubook.wizard.plan.restrictions + + form + form + new + {'restriction_id': [active_id]} + + +
    diff --git a/hotel_channel_connector/wizard/wubook_installer.py b/hotel_channel_connector/wizard/wubook_installer.py new file mode 100644 index 000000000..ff745d68d --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_installer.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +import os +import binascii +from openerp import models, fields, api, _ +from openerp.exceptions import ValidationError +from ..wubook import DEFAULT_WUBOOK_DATE_FORMAT +from odoo.addons.hotel import date_utils + + +class WuBookInstaller(models.TransientModel): + _name = 'wubook.installer' + _inherit = 'res.config.installer' + + wubook_user = fields.Char('User', required=True) + wubook_passwd = fields.Char('Password', required=True) + wubook_lcode = fields.Char('LCode', required=True) + wubook_server = fields.Char(string='Server', + default='https://wired.wubook.net/xrws/', + required=True) + wubook_pkey = fields.Char('PKey', required=True) + activate_push = fields.Boolean('Active Push Notifications', default=True) + + @api.multi + def execute(self): + super(WuBookInstaller, self).execute() + return self.execute_simple() + + @api.multi + def execute_simple(self): + activate_push = True + for rec in self: + self.env['ir.default'].sudo().set('wubook.config.settings', + 'wubook_user', + rec.wubook_user) + self.env['ir.default'].sudo().set('wubook.config.settings', + 'wubook_passwd', + rec.wubook_passwd) + self.env['ir.default'].sudo().set('wubook.config.settings', + 'wubook_lcode', + rec.wubook_lcode) + self.env['ir.default'].sudo().set('wubook.config.settings', + 'wubook_server', + rec.wubook_server) + self.env['ir.default'].sudo().set('wubook.config.settings', + 'wubook_pkey', + rec.wubook_pkey) + activate_push = rec.activate_push + self.env['ir.default'].sudo().set( + 'wubook.config.settings', + 'wubook_push_security_token', + binascii.hexlify(os.urandom(16)).decode()) + self.env.cr.commit() # FIXME: Need do this + + # Create Wubook Base Restrictions + restr_obj = self.env['hotel.virtual.room.restriction'].with_context({ + 'wubook_action': False + }) + base_rest = restr_obj.search([('wpid', '=', '0')], limit=1) + if not base_rest: + nrest = restr_obj.create({ + 'name': 'Base WuBook Restrictions', + 'wpid': '0', + }) + if not nrest: + raise ValidationError(_("Can't create base wubook restrictions")) + + # Initialize WuBook + wres = self.env['wubook'].initialize(activate_push) + if not wres: + raise ValidationError("Can't finish installation!") + + # Open Next Step + v_id = 'hotel_wubook_proto.view_wubook_configuration_installer_parity' + return { + 'name': _("Configure Hotel Parity"), + 'type': 'ir.actions.act_window', + 'res_model': 'wubook.installer.parity', + 'view_id': self.env.ref(v_id).id, + 'view_type': 'form', + 'view_mode': 'form', + 'target': 'new' + } + + +class WuBookInstallerParity(models.TransientModel): + _name = 'wubook.installer.parity' + _inherit = 'res.config.installer' + + parity_pricelist_id = fields.Many2one('product.pricelist', + 'Product Pricelist') + parity_restrictions_id = fields.Many2one('hotel.virtual.room.restriction', + 'Restrictions') + import_data = fields.Boolean('Import Data From WuBook', default=False) + date_start = fields.Date('Date Start') + date_end = fields.Date('Date End') + + @api.multi + def execute(self): + self.execute_simple() + return super(WuBookInstallerParity, self).execute() + + @api.multi + def execute_simple(self): + wubookObj = self.env['wubook'] + irValuesObj = self.env['ir.values'] + for rec in self: + irValuesObj.sudo().set_default('hotel.config.settings', + 'parity_pricelist_id', + rec.parity_pricelist_id.id) + irValuesObj.sudo().set_default('hotel.config.settings', + 'parity_restrictions_id', + rec.parity_restrictions_id.id) + import_data = rec.import_data + if rec.import_data: + date_start_dt = date_utils.get_datetime(rec.date_start) + date_end_dt = date_utils.get_datetime(rec.date_end) + # Availability + wresAvail = wubookObj.fetch_rooms_values( + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT)) + # Pricelist + wresPrices = wubookObj.fetch_plan_prices( + rec.parity_pricelist_id.wpid, + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT)) + # Restrictions + wresRestr = wubookObj.fetch_rplan_restrictions( + date_start_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + date_end_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + rec.parity_restrictions_id.wpid) + + if not wresAvail or not wresPrices or not wresRestr: + raise ValidationError(_("Errors importing data from WuBook")) + + # Reservations + wubookObj.fetch_new_bookings() diff --git a/hotel_channel_connector/wizard/wubook_installer.xml b/hotel_channel_connector/wizard/wubook_installer.xml new file mode 100644 index 000000000..3d767615f --- /dev/null +++ b/hotel_channel_connector/wizard/wubook_installer.xml @@ -0,0 +1,90 @@ + + + + wubook.installer.form + wubook.installer + + + + WuBook Configuration + + +
    +
    +
    + +

    + WuBook API Configuration. This wizard will activate push request and synchronize rooms & reservations with Odoo. +

    + + + + + + + + + + + + + + +
    +
    +
    + + + wubook.installer.parity.form + wubook.installer.parity + + + + WuBook Configuration Parity + + +
    +
    +
    + +

    + These models are used as masters +

    + + + + + + + + + + + + + + + +
    +
    +
    + + + Configure WuBook Data + ir.actions.act_window + wubook.installer + + form + form + new + + + + + 3 + automatic + + +
    diff --git a/hotel_channel_connector/wubook.py b/hotel_channel_connector/wubook.py new file mode 100644 index 000000000..ba7d97ec5 --- /dev/null +++ b/hotel_channel_connector/wubook.py @@ -0,0 +1,1760 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2017 Solucións Aloxa S.L. +# Alexandre Díaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +############################################################################## +import logging +import xmlrpc +import socket +import pytz +import json +from datetime import timedelta +from urllib.parse import urljoin +from odoo import models, api +from odoo.exceptions import UserError, ValidationError +from odoo.tools import ( + DEFAULT_SERVER_DATE_FORMAT, + DEFAULT_SERVER_DATETIME_FORMAT) +from odoo.addons.payment.models.payment_acquirer import _partner_split_name +from odoo.addons.hotel import date_utils +_logger = logging.getLogger(__name__) + +# GLOBAL VARS +DEFAULT_WUBOOK_DATE_FORMAT = "%d/%m/%Y" +DEFAULT_WUBOOK_TIME_FORMAT = "%H:%M" +DEFAULT_WUBOOK_DATETIME_FORMAT = "%s %s" % (DEFAULT_WUBOOK_DATE_FORMAT, + DEFAULT_WUBOOK_TIME_FORMAT) +WUBOOK_STATUS_CONFIRMED = 1 +WUBOOK_STATUS_WAITING = 2 +WUBOOK_STATUS_REFUSED = 3 +WUBOOK_STATUS_ACCEPTED = 4 +WUBOOK_STATUS_CANCELLED = 5 +WUBOOK_STATUS_CANCELLED_PENALTY = 6 + +WUBOOK_STATUS_GOOD = ( + WUBOOK_STATUS_CONFIRMED, + WUBOOK_STATUS_WAITING, + WUBOOK_STATUS_ACCEPTED, +) +WUBOOK_STATUS_BAD = ( + WUBOOK_STATUS_REFUSED, + WUBOOK_STATUS_CANCELLED, + WUBOOK_STATUS_CANCELLED_PENALTY, +) + +# class TimeoutTransport(xmlrpclib.Transport): +# """ +# Custom XML-RPC transport class for HTTP connections, allowing a timeout in +# the base connection. +# """ +# +# def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, use_datetime=0): +# xmlrpclib.Transport.__init__(self, use_datetime) +# self._timeout = timeout +# +# def make_connection(self, host): +# # If using python 2.6, since that implementation normally returns the +# # HTTP compatibility class, which doesn't have a timeout feature. +# #import httplib +# #host, extra_headers, x509 = self.get_host_info(host) +# #return httplib.HTTPConnection(host, timeout=self._timeout) +# +# conn = xmlrpclib.Transport.make_connection(self, host) +# conn.timeout = self._timeout +# return conn + + +# WUBOOK +class WuBook(models.AbstractModel): + _name = 'wubook' + + # === INITALIZATION + def __init__(self, pool, cr): + super(WuBook, self).__init__(pool, cr) + self.SERVER = False + self.LCODE = False + self.TOKEN = False + + @api.model + def initialize(self, activate): + self_context = self.with_context({'init_connection': False}) + if not self_context.init_connection(): + return False + if activate: + if not self_context.push_activation(): + return False + + res = (self_context.import_rooms()[0] + and self_context.import_channels_info()[0] + and self_context.import_pricing_plans()[0] + and self_context.import_restriction_plans()[0]) + + self_context.close_connection() + return res + + @api.model + def push_activation(self): + base_url = self.env['ir.config_parameter'].get_param('web.base.url') + base_url = base_url.replace("http://", "https://") + hotel_security_token = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_push_security_token') + + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode_a, results_a = self.SERVER.push_activation( + self.TOKEN, + self.LCODE, + urljoin(base_url, + "/wubook/push/reservations/%s" % hotel_security_token), + 1) + rcode_ua, results_ua = self.SERVER.push_update_activation( + self.TOKEN, + self.LCODE, + urljoin(base_url, "/wubook/push/rooms/%s" % hotel_security_token)) + if init_connection: + self.close_connection() + + if rcode_a != 0: + self.create_wubook_issue('wubook', + "Can't activate push reservations", + results_a) + if rcode_ua != 0: + self.create_wubook_issue('wubook', "Can't activate push rooms", + results_ua) + + return rcode_a == 0 and rcode_ua == 0 + + def is_valid_account(self): + user = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_user') + passwd = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_passwd') + lcode = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_lcode') + pkey = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_pkey') + server_addr = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_server') + return bool(user and passwd and pkey and server_addr and lcode) + + # === NETWORK + def init_connection(self): + user = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_user') + passwd = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_passwd') + self.LCODE = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_lcode') + pkey = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_pkey') + server_addr = self.env['ir.default'].sudo().get( + 'wubook.config.settings', 'wubook_server') + + if not user or not passwd or not pkey or not server_addr or \ + not self.LCODE: + self.create_wubook_issue( + 'wubook', + "Can't connect with WuBook! Perhaps account not configured...", + "") + return False + + try: + # t = TimeoutTransport(timeout=3) + # self.SERVER = xmlrpclib.Server(server_addr, transport=t) + self.SERVER = xmlrpclib.Server(server_addr) + res, tok = self.SERVER.acquire_token(user, passwd, pkey) + self.TOKEN = tok + if res != 0: + self.create_wubook_issue( + 'wubook', + "Can't connect with WuBook! Perhaps the account haven't \ + a good configuration...", + tok) + except Exception: + self.create_wubook_issue( + 'wubook', + "Can't connect with WuBook! Please, check internet \ + connection.", + "") + res = -1 + + return res == 0 + + def close_connection(self): + self.SERVER.release_token(self.TOKEN) + self.TOKEN = False + self.SERVER = False + + # === HELPER FUNCTIONS + @api.model + def create_wubook_issue(self, section, message, wmessage, wid=False, + dfrom=False, dto=False): + self.env['wubook.issue'].sudo().create({ + 'section': section, + 'message': message, + 'wid': wid, + 'wmessage': wmessage, + 'date_start': dfrom and date_utils.get_datetime( + dfrom, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT).strftime( + DEFAULT_SERVER_DATE_FORMAT), + 'date_end': dto and date_utils.get_datetime( + dto, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT).strftime( + DEFAULT_SERVER_DATE_FORMAT), + }) + + def set_clousure_today(self, status): + hotel_tz = self.env['ir.default'].sudo().get('hotel.config.settings', + 'tz_hotel') + now_utc_dt = date_utils.now() + now_dt = date_utils.dt_as_timezone(now_utc_dt, hotel_tz) + now_str = now_dt.strftime(DEFAULT_SERVER_DATE_FORMAT) + vrooms = self.env['hotel.virtual.room'].search([]) + + restriction_parity_id = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'parity_restrictions_id') + if restriction_parity_id: + restriction_parity_id = int(restriction_parity_id) + + vroom_restr_obj = self.env['hotel.virtual.room.restriction.item'] + vroom_obj = self.env['hotel.virtual.room'] + + vrooms = vroom_obj.search([('wrid', '!=', False), ('wrid', '!=', '')]) + for vroom in vrooms: + restr = vroom_restr_obj.search([ + ('restriction_id', '=', restriction_parity_id), + ('virtual_room_id', '=', vroom.id), + ('date_start', '>=', now_str), + ('date_end', '<=', now_str), + ('applied_on', '=', '0_virtual_room'), + ], limit=1) + if restr: + restr.write({'closed': status}) + else: + restr = vroom_restr_obj.create({ + 'date_start': now_str, + 'date_end': now_str, + 'virtual_room_id': vroom.id, + 'applied_on': '0_virtual_room', + 'restriction_id': restriction_parity_id, + 'min_stay': 0, + 'min_stay_arrival': 0, + 'max_stay': 0, + 'max_stay_arrival': 0, + 'closed': status, + 'closed_departure': False, + 'closed_arrival': False, + 'wpushed': False, + }) + if not restr: + raise ValidationError("Can't close rooms!") + return self.push_restrictions() + + # === ROOMS + @api.model + def create_room(self, shortcode, name, capacity, price, availability): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.new_room( + self.TOKEN, + self.LCODE, + 0, + name, + capacity, + price, + availability, + shortcode[:4], + 'nb' # TODO: Complete this part + # rtype=('name' in vals and vals['name'] and 3) or 1 + ) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'room', "Can't create room in WuBook", results) + return False + + return results + + @api.model + def modify_room(self, wrid, name, capacity, price, availability, scode): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.mod_room( + self.TOKEN, + self.LCODE, + wrid, + name, + capacity, + price, + availability, + scode, + 'nb' + # rtype=('name' in vals and vals['name'] and 3) or 1 + ) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('room', "Can't modify room in WuBook", + results, wid=wrid) + + return rcode == 0 + + @api.model + def delete_room(self, wrid): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.del_room( + self.TOKEN, + self.LCODE, + wrid + ) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('room', "Can't delete room in WuBook", + results, wid=wrid) + + return rcode == 0 + + @api.model + def import_rooms(self): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return (False, 0) + rcode, results = self.SERVER.fetch_rooms( + self.TOKEN, + self.LCODE, + 0 + ) + if init_connection: + self.close_connection() + + vroom_obj = self.env['hotel.virtual.room'] + count = 0 + if rcode == 0: + count = len(results) + for room in results: + vroom = vroom_obj.search([('wrid', '=', room['id'])], limit=1) + vals = { + 'name': room['name'], + 'wrid': room['id'], + 'wscode': room['shortname'], + 'list_price': room['price'], + 'wcapacity': room['occupancy'], + # 'max_real_rooms': room['availability'], + } + if vroom: + vroom.with_context({'wubook_action': False}).write(vals) + else: + vroom_obj.with_context({'wubook_action': False}).create( + vals) + else: + self.create_wubook_issue( + 'room', "Can't import rooms from WuBook", results) + + return (rcode == 0, count) + + @api.model + def fetch_rooms_values(self, dfrom, dto, rooms=False, + set_wmax_avail=False): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + # Sanitize Dates + now_dt = date_utils.now() + now = now_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT) + dfrom_dt = date_utils.get_datetime(dfrom, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT) + dto_dt = date_utils.get_datetime(dto, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT) + if dto_dt < now_dt: + return True + if dfrom_dt < now_dt: + dfrom = now + if dfrom_dt > dto_dt: + dtemp = dfrom + dfrom = dto + dto = dtemp + rcode, results = self.SERVER.fetch_rooms_values(self.TOKEN, + self.LCODE, + dfrom, + dto, + rooms) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('room', + "Can't fetch rooms values from WuBook", + results, dfrom=dfrom, dto=dto) + else: + self.generate_room_values(dfrom, dto, results, + set_wmax_avail=set_wmax_avail) + + return rcode == 0 + + @api.model + def update_availability(self, rooms_avail): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.update_sparse_avail(self.TOKEN, + self.LCODE, + rooms_avail) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'room', + "Can't update rooms availability in WuBook", + results) + + return rcode == 0 + + @api.model + def corporate_fetch(self): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.corporate_fetchable_properties(self.TOKEN) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'wubook', + "Can't call 'corporate_fetch' from WuBook", + results) + + return rcode == 0 + + # === RESERVATIONS + @api.model + def create_reservation(self, reserv): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + vroom = self.env['hotel.virtual.room'].search([ + ('product_id', '=', reserv.product_id.id) + ], limit=1) + customer = { + 'lname': _partner_split_name(reserv.partner_id.name)[0], + 'fname': _partner_split_name(reserv.partner_id.name)[1], + 'email': reserv.partner_id.email, + 'city': reserv.partner_id.city, + 'phone': reserv.partner_id.phone, + 'street': reserv.partner_id.street, + 'country': reserv.partner_id.country_id.code, + 'arrival_hour': date_utils.get_datetime(reserv.checkin, + dtformar="%H:%M:%S"), + 'notes': '' # TODO: + } + rcode, results = self.SERVER.new_reservation( + self.TOKEN, + self.LCODE, + reserv.checkin, + reserv.checkout, + {vroom.wrid: [reserv.adults+reserv.children, 'nb']}, + customer, + reserv.adults+reserv.children) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('reservation', + "Can't create reservations in wubook", + results, + dfrom=reserv.checkin, dto=reserv.checkout) + else: + reserv.write({'wrid': results}) + + return rcode == 0 + + @api.model + def cancel_reservation(self, wrid, reason=""): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.cancel_reservation(self.TOKEN, + self.LCODE, + wrid, + reason) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('reservation', + "Can't cancel reservation in WuBook", + results, wid=wrid) + + return rcode == 0 + + @api.model + def fetch_new_bookings(self): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return (False, 0) + rcode, results = self.SERVER.fetch_new_bookings(self.TOKEN, + self.LCODE, + 1, + 0) + errors = False + processed_rids = [] + if rcode == 0: + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.generate_reservations(results) + if any(processed_rids): + uniq_rids = list(set(processed_rids)) + rcodeb, resultsb = self.SERVER.mark_bookings(self.TOKEN, + self.LCODE, + uniq_rids) + + if rcodeb != 0: + self.create_wubook_issue( + 'wubook', + "Problem trying mark bookings (%s)" % + str(processed_rids), + '') + if init_connection: + self.close_connection() + + # Update Odoo availability (don't wait for wubook) + if rcode == 0 and checkin_utc_dt and checkout_utc_dt: + self.fetch_rooms_values( + checkin_utc_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + checkout_utc_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT)) + + if rcode != 0: + self.create_wubook_issue('reservation', + "Can't process reservations from wubook", + results) + + return ((rcode == 0 and not errors), len(processed_rids)) + + @api.model + def fetch_booking(self, lcode, wrid): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return (False, 0) + rcode, results = self.SERVER.fetch_booking(self.TOKEN, + lcode, + wrid) + errors = False + processed_rids = [] + if rcode == 0: + processed_rids, errors, checkin_utc_dt, checkout_utc_dt = \ + self.generate_reservations(results) + if any(processed_rids): + uniq_rids = list(set(processed_rids)) + rcode, results = self.SERVER.mark_bookings(self.TOKEN, + self.LCODE, + uniq_rids) + + if rcode != 0: + self.create_wubook_issue( + 'wubook', + "Problem trying mark bookings (%s)" % + str(processed_rids), + '') + + if init_connection: + self.close_connection() + + # Update Odoo availability (don't wait for wubook) + if rcode == 0 and checkin_utc_dt and checkout_utc_dt: + self.fetch_rooms_values( + checkin_utc_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + checkout_utc_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT)) + + if rcode != 0: + self.create_wubook_issue('reservation', + "Can't process reservations from wubook", + results, wid=wrid) + + return ((rcode == 0 and not errors), len(processed_rids)) + + @api.model + def mark_bookings(self, wrids): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.mark_bookings(self.TOKEN, + self.LCODE, + wrids) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'reservation', + "Can't mark as readed a reservation in wubook", + results, wid=str(wrids)) + + return rcode == 0 + + # === PRICE PLANS + @api.model + def create_plan(self, name, daily=1): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.add_pricing_plan(self.TOKEN, + self.LCODE, + name, + daily) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'plan', "Can't add pricing plan to wubook", results) + return False + + return results + + @api.model + def delete_plan(self, pid): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.del_plan(self.TOKEN, + self.LCODE, + pid) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('plan', + "Can't delete pricing plan from wubook", + results, + wid=pid) + + return rcode == 0 + + @api.model + def update_plan_name(self, pid, name): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.update_plan_name(self.TOKEN, + self.LCODE, + pid, + name) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'plan', + "Can't update pricing plan name in wubook", + results, wid=pid) + + return rcode == 0 + + @api.model + def update_plan_prices(self, pid, dfrom, prices): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.update_plan_prices(self.TOKEN, + self.LCODE, + pid, + dfrom, + prices) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'plan', + "Can't update pricing plan in wubook", + results, wid=pid, dfrom=dfrom) + + return rcode == 0 + + @api.model + def update_plan_periods(self, pid, periods): + _logger.info("[WuBook] Updating Plan Periods...") + _logger.info(periods) + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.update_plan_periods(self.TOKEN, + self.LCODE, + pid, + periods) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'plan', + "Can't update pricing plan period in wubook", + results, wid=pid) + + return rcode == 0 + + @api.model + def import_pricing_plans(self): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return (False, 0) + rcode, results = self.SERVER.get_pricing_plans(self.TOKEN, + self.LCODE) + if init_connection: + self.close_connection() + + count = 0 + if rcode != 0: + self.create_wubook_issue( + 'plan', + "Can't get pricing plans from wubook", + results) + else: + count = self.generate_pricelists(results) + + return (rcode == 0, count) + + @api.model + def fetch_plan_prices(self, pid, dfrom, dto, rooms=None): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.fetch_plan_prices(self.TOKEN, + self.LCODE, + pid, + dfrom, + dto, + rooms or []) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'plan', + "Can't fetch plan prices from wubook", + results, wid=pid, dfrom=dfrom, dto=dto) + else: + self.generate_pricelist_items(pid, dfrom, dto, results) + + return rcode == 0 + + @api.model + def fetch_all_plan_prices(self, dfrom, dto, rooms=None): + no_errors = True + plan_wpids = self.env['product.pricelist'].search([ + ('wpid', '!=', False), ('wpid', '!=', '') + ]).mapped('wpid') + if any(plan_wpids): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + for wpid in plan_wpids: + rcode, results = self.SERVER.fetch_plan_prices(self.TOKEN, + self.LCODE, + wpid, + dfrom, + dto, + rooms or []) + if rcode != 0: + self.create_wubook_issue( + 'plan', + "Can't fetch all plan prices from wubook!", + results, wid=wpid, dfrom=dfrom, dto=dto) + no_errors = False + else: + self.generate_pricelist_items(wpid, dfrom, dto, results) + if init_connection: + self.close_connection() + + return no_errors + + # === RESTRICTION PLANS + @api.model + def import_restriction_plans(self): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return (False, 0) + rcode, results = self.SERVER.rplan_rplans(self.TOKEN, + self.LCODE) + if init_connection: + self.close_connection() + + count = 0 + if rcode != 0: + self.create_wubook_issue( + 'rplan', + "Can't fetch restriction plans from wubook", + results) + else: + count = self.generate_restrictions(results) + + return (rcode == 0, count) + + @api.model + def fetch_rplan_restrictions(self, dfrom, dto, rpid=False): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.wired_rplan_get_rplan_values(self.TOKEN, + self.LCODE, + dfrom, + dto, + int(rpid)) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'rplan', + "Can't fetch plan restrictions from wubook", + results, wid=rpid, dfrom=dfrom, dto=dto) + elif any(results): + self.generate_restriction_items(dfrom, dto, results) + + return rcode == 0 + + @api.model + def update_rplan_values(self, rpid, dfrom, values): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.rplan_update_rplan_values(self.TOKEN, + self.LCODE, + rpid, + dfrom, + values) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue( + 'rplan', + "Can't update plan restrictions on wubook", + results, wid=rpid, dfrom=dfrom) + + return rcode == 0 + + @api.model + def create_rplan(self, name, compact=False): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.rplan_add_rplan(self.TOKEN, + self.LCODE, + name, + compact and 1 or 0) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('rplan', + "Can't create plan restriction in wubook", + results) + return False + + return results + + @api.model + def rename_rplan(self, rpid, name): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.rplan_rename_rplan(self.TOKEN, + self.LCODE, + rpid, + name) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('rplan', + "Can't rename plan restriction in wubook", + results, wid=rpid) + + return rcode == 0 + + @api.model + def delete_rplan(self, rpid): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return False + rcode, results = self.SERVER.rplan_del_rplan(self.TOKEN, + self.LCODE, + rpid) + if init_connection: + self.close_connection() + + if rcode != 0: + self.create_wubook_issue('rplan', + "Can't delete plan restriction on wubook", + results, wid=rpid) + + return rcode == 0 + + # === WUBOOK INFO + @api.model + def import_channels_info(self): + init_connection = self._context.get('init_connection', True) + if init_connection: + if not self.init_connection(): + return (False, 0) + results = self.SERVER.get_channels_info(self.TOKEN) + if init_connection: + self.close_connection() + + count = self.generate_wubook_channel_info(results) + + return (True, count) + + # === WUBOOK -> ODOO + @api.model + def generate_room_values(self, dfrom, dto, values, set_wmax_avail=False): + virtual_room_avail_obj = self.env['hotel.virtual.room.availability'] + virtual_room_restr_obj = self.env['hotel.virtual.room.restriction'] + vroom_restr_item_obj = self.env['hotel.virtual.room.restriction.item'] + hotel_virtual_room_obj = self.env['hotel.virtual.room'] + def_wubook_restr = virtual_room_restr_obj.search([('wpid', '=', '0')]) + _logger.info("==== ROOM VALUES (%s -- %s)", dfrom, dto) + _logger.info(values) + for k_rid, v_rid in values.iteritems(): + vroom = hotel_virtual_room_obj.search([ + ('wrid', '=', k_rid) + ], limit=1) + if vroom: + date_dt = date_utils.get_datetime( + dfrom, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT) + for day_vals in v_rid: + date_str = date_dt.strftime(DEFAULT_SERVER_DATE_FORMAT) + # Get Availability + vroom_avail = virtual_room_avail_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('date', '=', date_str) + ], limit=1) + vals = { + 'no_ota': day_vals.get('no_ota'), + 'booked': day_vals.get('booked'), + 'avail': day_vals.get('avail', 0), + 'wpushed': True, + } + if set_wmax_avail: + vals.update({'wmax_avail': day_vals.get('avail', 0)}) + if vroom_avail: + vroom_avail.with_context({ + 'wubook_action': False, + }).write(vals) + else: + vals.update({ + 'virtual_room_id': vroom.id, + 'date': date_str, + }) + virtual_room_avail_obj.with_context({ + 'wubook_action': False, + 'mail_create_nosubscribe': True, + }).create(vals) + + # Get Restrictions + if def_wubook_restr: + vroom_restr = vroom_restr_item_obj.search([ + ('virtual_room_id', '=', vroom.id), + ('applied_on', '=', '0_virtual_room'), + ('date_start', '=', date_str), + ('date_end', '=', date_str), + ('restriction_id', '=', def_wubook_restr.id), + ]) + vals = { + 'min_stay': int(day_vals.get('min_stay', 0)), + 'min_stay_arrival': int(day_vals.get( + 'min_stay_arrival', + 0)), + 'max_stay': int(day_vals.get('max_stay', 0)), + 'max_stay_arrival': int(day_vals.get( + 'max_stay_arrival', + 0)), + 'closed': int(day_vals.get('closed', False)), + 'closed_departure': int(day_vals.get( + 'closed_departure', + False)), + 'closed_arrival': int(day_vals.get( + 'closed_arrival', + False)), + 'wpushed': True, + } + if vroom_restr: + vroom_restr.with_context({ + 'wubook_action': False, + }).write(vals) + else: + vals.update({ + 'restriction_id': def_wubook_restr.id, + 'virtual_room_id': vroom.id, + 'date_start': date_str, + 'date_end': date_str, + 'applied_on': '0_virtual_room', + }) + vroom_restr_item_obj.with_context({ + 'wubook_action': False, + }).create(vals) + date_dt = date_dt + timedelta(days=1) + return True + + @api.model + def generate_restrictions(self, restriction_plans): + restriction_obj = self.env['hotel.virtual.room.restriction'] + count = 0 + for plan in restriction_plans: + vals = { + 'name': plan['name'], + } + plan_id = restriction_obj.search([ + ('wpid', '=', str(plan['id'])) + ], limit=1) + if not plan_id: + vals.update({ + 'wpid': str(plan['id']), + }) + restriction_obj.with_context({ + 'wubook_action': False, + 'rules': plan.get('rules'), + }).create(vals) + else: + plan_id.with_context({'wubook_action': False}).write(vals) + count = count + 1 + return count + + @api.model + def generate_restriction_items(self, dfrom, dto, plan_restrictions): + hotel_virtual_room_obj = self.env['hotel.virtual.room'] + reserv_restriction_obj = self.env['hotel.virtual.room.restriction'] + restriction_item_obj = self.env['hotel.virtual.room.restriction.item'] + _logger.info("===== RESTRICTIONS") + _logger.info(plan_restrictions) + for k_rpid, v_rpid in plan_restrictions.iteritems(): + restriction_id = reserv_restriction_obj.search([ + ('wpid', '=', k_rpid) + ], limit=1) + if restriction_id: + for k_rid, v_rid in v_rpid.iteritems(): + vroom = hotel_virtual_room_obj.search([ + ('wrid', '=', k_rid) + ], limit=1) + if vroom: + for item in v_rid: + date_dt = date_utils.get_datetime( + item['date'], + dtformat=DEFAULT_WUBOOK_DATE_FORMAT) + restriction_item = restriction_item_obj.search([ + ('restriction_id', '=', restriction_id.id), + ('date_start', '=', date_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT)), + ('date_end', '=', date_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT)), + ('applied_on', '=', '0_virtual_room'), + ('virtual_room_id', '=', vroom.id) + ], limit=1) + vals = { + 'closed_arrival': item['closed_arrival'], + 'closed': item['closed'], + 'min_stay': item['min_stay'], + 'closed_departure': item['closed_departure'], + 'max_stay': item['max_stay'], + 'max_stay_arrival': item['max_stay_arrival'], + 'min_stay_arrival': item['min_stay_arrival'], + 'wpushed': True, + } + if restriction_item: + restriction_item.with_context({ + 'wubook_action': False}).write(vals) + else: + vals.update({ + 'restriction_id': restriction_id.id, + 'date_start': date_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT), + 'date_end': date_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT), + 'applied_on': '0_virtual_room', + 'virtual_room_id': vroom.id + }) + restriction_item_obj.with_context({ + 'wubook_action': False}).create(vals) + + return True + + @api.model + def generate_pricelist_items(self, pid, dfrom, dto, plan_prices): + hotel_virtual_room_obj = self.env['hotel.virtual.room'] + pricelist = self.env['product.pricelist'].search([ + ('wpid', '=', pid) + ], limit=1) + if pricelist: + pricelist_item_obj = self.env['product.pricelist.item'] + dfrom_dt = date_utils.get_datetime( + dfrom, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT) + dto_dt = date_utils.get_datetime( + dto, + dtformat=DEFAULT_WUBOOK_DATE_FORMAT) + days_diff = date_utils.date_diff(dfrom_dt, dto_dt, hours=False) + 1 + for i in range(0, days_diff): + ndate_dt = dfrom_dt + timedelta(days=i) + for k_rid, v_rid in plan_prices.iteritems(): + vroom = hotel_virtual_room_obj.search([ + ('wrid', '=', k_rid) + ], limit=1) + if vroom: + pricelist_item = pricelist_item_obj.search([ + ('pricelist_id', '=', pricelist.id), + ('date_start', '=', ndate_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT)), + ('date_end', '=', ndate_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT)), + ('compute_price', '=', 'fixed'), + ('applied_on', '=', '1_product'), + ('product_tmpl_id', '=', vroom.product_id.product_tmpl_id.id) + ], limit=1) + vals = { + 'fixed_price': plan_prices[k_rid][i], + 'wpushed': True, + } + if pricelist_item: + pricelist_item.with_context({ + 'wubook_action': False}).write(vals) + else: + vals.update({ + 'pricelist_id': pricelist.id, + 'date_start': ndate_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT), + 'date_end': ndate_dt.strftime( + DEFAULT_SERVER_DATE_FORMAT), + 'compute_price': 'fixed', + 'applied_on': '1_product', + 'product_tmpl_id': vroom.product_id.product_tmpl_id.id + }) + pricelist_item_obj.with_context({ + 'wubook_action': False}).create(vals) + return True + + @api.model + def generate_pricelists(self, price_plans): + product_listprice_obj = self.env['product.pricelist'] + count = 0 + for plan in price_plans: + if 'vpid' in plan: + continue # Ignore Virtual Plans + + vals = { + 'name': plan['name'], + 'wdaily': plan['daily'] == 1, + } + plan_id = product_listprice_obj.search([ + ('wpid', '=', str(plan['id'])) + ], limit=1) + if not plan_id: + vals.update({ + 'wpid': str(plan['id']), + }) + product_listprice_obj.with_context({ + 'wubook_action': False}).create(vals) + else: + plan_id.with_context({'wubook_action': False}).write(vals) + count = count + 1 + return count + + @api.model + def _generate_booking_vals(self, broom, checkin_str, checkout_str, + is_cancellation, wchannel_info, wstatus, crcode, + rcode, vroom, split_booking, dates_checkin, + dates_checkout, book): + # Generate Reservation Day Lines + reservation_line_ids = [] + tprice = 0.0 + for brday in broom['roomdays']: + wndate = date_utils.get_datetime( + brday['day'], + dtformat=DEFAULT_WUBOOK_DATE_FORMAT + ).replace(tzinfo=pytz.utc) + if date_utils.date_in(wndate, + dates_checkin[0], + dates_checkout[0] - timedelta(days=1), + hours=False) == 0: + reservation_line_ids.append((0, False, { + 'date': wndate.strftime( + DEFAULT_SERVER_DATE_FORMAT), + 'price': brday['price'] + })) + tprice += brday['price'] + persons = vroom.wcapacity + if 'ancillary' in broom and 'guests' in broom['ancillary']: + persons = broom['ancillary']['guests'] + vals = { + 'checkin': checkin_str, + 'checkout': checkout_str, + 'adults': persons, + 'children': book['children'], + 'reservation_line_ids': reservation_line_ids, + 'price_unit': tprice, + 'to_assign': True, + 'wrid': rcode, + 'wchannel_id': wchannel_info and wchannel_info.id, + 'wchannel_reservation_code': crcode, + 'wstatus': wstatus, + 'to_read': True, + 'state': is_cancellation and 'cancelled' or 'draft', + 'virtual_room_id': vroom.id, + 'splitted': split_booking, + 'wbook_json': json.dumps(book), + 'wmodified': book['was_modified'] + } + _logger.info("===== CONTRUCT RESERV") + _logger.info(vals) + return vals + + @api.model + def _generate_partner_vals(self, book): + country_id = self.env['res.country'].search([ + ('code', '=', str(book['customer_country'])) + ], limit=1) + # lang = self.env['res.lang'].search([('code', '=', book['customer_language_iso'])], limit=1) + return { + 'name': "%s, %s" % + (book['customer_surname'], book['customer_name']), + 'country_id': country_id and country_id.id, + 'city': book['customer_city'], + 'phone': book['customer_phone'], + 'zip': book['customer_zip'], + 'street': book['customer_address'], + 'email': book['customer_mail'], + 'unconfirmed': True, + # 'lang': lang and lang.id, + } + + # FIXME: Super big method!!! O_o + @api.model + def generate_reservations(self, bookings): + _logger.info("=== BOOKINGS FROM WUBOOK") + _logger.info(bookings) + default_arrival_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_arrival_hour') + default_departure_hour = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'default_departure_hour') + + # Get user timezone + tz_hotel = self.env['ir.default'].sudo().get( + 'hotel.config.settings', 'tz_hotel') + res_partner_obj = self.env['res.partner'] + hotel_reserv_obj = self.env['hotel.reservation'] + hotel_folio_obj = self.env['hotel.folio'] + hotel_vroom_obj = self.env['hotel.virtual.room'] + # Space for store some data for construct folios + processed_rids = [] + failed_reservations = [] + checkin_utc_dt = False + checkout_utc_dt = False + split_booking = False + for book in bookings: # This create a new folio + splitted_map = {} + is_cancellation = book['status'] in WUBOOK_STATUS_BAD + bstatus = str(book['status']) + rcode = str(book['reservation_code']) + crcode = str(book['channel_reservation_code']) \ + if book['channel_reservation_code'] else 'undefined' + + # Can't process failed reservations + # (for example set a invalid new reservation and receive in + # the same transaction an cancellation) + if crcode in failed_reservations: + self.create_wubook_issue( + 'reservation', + "Can't process a reservation that previusly failed!", + '', wid=book['reservation_code']) + continue + + # Get dates for the reservation (GMT->UTC) + arr_hour = default_arrival_hour if book['arrival_hour'] == "--" \ + else book['arrival_hour'] + checkin = "%s %s" % (book['date_arrival'], arr_hour) + checkin_dt = date_utils.get_datetime( + checkin, + dtformat=DEFAULT_WUBOOK_DATETIME_FORMAT, + stz=tz_hotel) + checkin_utc_dt = date_utils.dt_as_timezone(checkin_dt, 'UTC') + checkin = checkin_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + + checkout = "%s %s" % (book['date_departure'], + default_departure_hour) + checkout_dt = date_utils.get_datetime( + checkout, + dtformat=DEFAULT_WUBOOK_DATETIME_FORMAT, + stz=tz_hotel) + checkout_utc_dt = date_utils.dt_as_timezone(checkout_dt, 'UTC') + checkout = checkout_utc_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT) + + # Search Folio. If exists. + folio_id = False + if crcode != 'undefined': + reserv_folio = hotel_reserv_obj.search([ + ('wchannel_reservation_code', '=', crcode) + ], limit=1) + if reserv_folio: + folio_id = reserv_folio.folio_id + else: + reserv_folio = hotel_reserv_obj.search([ + ('wrid', '=', rcode) + ], limit=1) + if reserv_folio: + folio_id = reserv_folio.folio_id + + # Need update reservations? + sreservs = hotel_reserv_obj.search([('wrid', '=', rcode)]) + reservs = folio_id.room_lines if folio_id else sreservs + reservs_processed = False + if any(reservs): + folio_id = reservs[0].folio_id + for reserv in reservs: + if reserv.wrid == rcode: + reserv.with_context({'wubook_action': False}).write({ + 'wstatus': str(book['status']), + 'wstatus_reason': book.get('status_reason', ''), + 'to_read': True, + 'to_assign': True, + 'price_unit': book['amount'], + 'wcustomer_notes': book['customer_notes'], + 'wbook_json': json.dumps(book), + }) + if reserv.partner_id.unconfirmed: + reserv.partner_id.write( + self._generate_partner_vals(book) + ) + reservs_processed = True + if is_cancellation: + reserv.with_context({ + 'wubook_action': False}).action_cancel() + elif reserv.state == 'cancelled': + reserv.with_context({ + 'wubook_action': False, + }).write({ + 'discount': 0.0, + 'state': 'confirm', + }) + + # Do Nothing if already processed 'wrid' + if reservs_processed: + processed_rids.append(rcode) + continue + + # Search Customer + customer_mail = book.get('customer_mail', False) + partner_id = False + if customer_mail: + partner_id = res_partner_obj.search([ + ('email', '=', customer_mail) + ], limit=1) + if not partner_id: + partner_id = res_partner_obj.create(self._generate_partner_vals(book)) + + # Search Wubook Channel Info + wchannel_info = self.env['wubook.channel.info'].search( + [('wid', '=', str(book['id_channel']))], limit=1) + + reservations = [] + used_rooms = [] + # Iterate booked rooms + for broom in book['booked_rooms']: + vroom = hotel_vroom_obj.search([ + ('wrid', '=', broom['room_id']) + ], limit=1) + if not vroom: + self.create_wubook_issue( + 'reservation', + "Can't found any virtual room associated to '%s' \ + in this hotel" % book['rooms'], + '', wid=book['reservation_code']) + failed_reservations.append(crcode) + continue + + dates_checkin = [checkin_utc_dt, False] + dates_checkout = [checkout_utc_dt, False] + split_booking = False + split_booking_parent = False + # This perhaps create splitted reservation + while dates_checkin[0]: + checkin_str = dates_checkin[0].strftime( + DEFAULT_SERVER_DATETIME_FORMAT) + checkout_str = dates_checkout[0].strftime( + DEFAULT_SERVER_DATETIME_FORMAT) + vals = self._generate_booking_vals( + broom, + checkin_str, + checkout_str, + is_cancellation, + wchannel_info, + bstatus, + crcode, + rcode, + vroom, + split_booking, + dates_checkin, + dates_checkout, + book, + ) + if vals['price_unit'] != book['amount']: + self.create_wubook_issue( + 'reservation', + "Invalid reservation total price! %.2f != %.2f" % (vals['price_unit'], book['amount']), + '', wid=book['reservation_code']) + + free_rooms = hotel_vroom_obj.check_availability_virtual_room( + checkin_str, + checkout_str, + virtual_room_id=vroom.id, + notthis=used_rooms) + if any(free_rooms): + vals.update({ + 'product_id': free_rooms[0].product_id.id, + 'name': free_rooms[0].name, + }) + reservations.append((0, False, vals)) + used_rooms.append(free_rooms[0].id) + + if split_booking: + if not split_booking_parent: + split_booking_parent = len(reservations) + else: + splitted_map.setdefault( + split_booking_parent, + []).append(len(reservations)) + dates_checkin = [dates_checkin[1], False] + dates_checkout = [dates_checkout[1], False] + else: + date_diff = (dates_checkout[0].replace( + hour=0, minute=0, second=0, + microsecond=0) - + dates_checkin[0].replace( + hour=0, minute=0, second=0, + microsecond=0)).days + if date_diff <= 0: + if split_booking: + if split_booking_parent: + del reservations[split_booking_parent-1:] + if split_booking_parent in splitted_map: + del splitted_map[split_booking_parent] + # Can't found space for reservation + vals = self._generate_booking_vals( + broom, + checkin_utc_dt, + checkout_utc_dt, + is_cancellation, + wchannel_info, + bstatus, + crcode, + rcode, + vroom, + False, + (checkin_utc_dt, False), + (checkout_utc_dt, False), + book, + ) + vals.update({ + 'product_id': + vroom.room_ids[0].product_id.id, + 'name': vroom.name, + 'overbooking': True, + }) + reservations.append((0, False, vals)) + self.create_wubook_issue( + 'reservation', + "Reservation imported with overbooking state", + '', wid=rcode) + dates_checkin = [False, False] + dates_checkout = [False, False] + split_booking = False + else: + split_booking = True + dates_checkin = [ + dates_checkin[0], + dates_checkin[0] + timedelta(days=date_diff-1) + ] + dates_checkout = [ + dates_checkout[0] - timedelta(days=1), + checkout_utc_dt + ] + + if split_booking: + self.create_wubook_issue( + 'reservation', + "Reservation Splitted", + '', wid=rcode) + + # Create Folio + if not any(failed_reservations) and any(reservations): + try: + # TODO: Improve 'addons_list' & discounts + addons = str(book['addons_list']) if any(book['addons_list']) else '' + discounts = book.get('discount', '') + vals = { + 'room_lines': reservations, + 'wcustomer_notes': "%s\nADDONS:\n%s\nDISCOUNT:\n%s" % ( + book['customer_notes'], addons, discounts), + 'channel_type': 'web', + } + _logger.info("=== FOLIO CREATE") + _logger.info(reservations) + if folio_id: + folio_id.with_context({ + 'wubook_action': False}).write(vals) + else: + vals.update({ + 'partner_id': partner_id.id, + 'wseed': book['sessionSeed'] + }) + folio_id = hotel_folio_obj.with_context({ + 'wubook_action': False}).create(vals) + + # Update Reservation Spitted Parents + sorted_rlines = folio_id.room_lines.sorted(key='id') + for k_pid, v_pid in splitted_map.iteritems(): + preserv = sorted_rlines[k_pid-1] + for pid in v_pid: + creserv = sorted_rlines[pid-1] + creserv.parent_reservation = preserv.id + + processed_rids.append(rcode) + except Exception as e_msg: + self.create_wubook_issue( + 'reservation', + e_msg[0], + '', wid=rcode) + failed_reservations.append(crcode) + return (processed_rids, any(failed_reservations), + checkin_utc_dt, checkout_utc_dt) + + @api.model + def generate_wubook_channel_info(self, channels): + channel_info_obj = self.env['wubook.channel.info'] + count = 0 + for k_cid, v_cid in channels.iteritems(): + vals = { + 'name': v_cid['name'], + 'ical': v_cid['ical'] == 1, + } + channel_info = channel_info_obj.search([ + ('wid', '=', k_cid) + ], limit=1) + if channel_info: + channel_info.write(vals) + else: + vals.update({ + 'wid': k_cid + }) + channel_info_obj.create(vals) + count = count + 1 + return count + + # === ODOO -> WUBOOK + @api.model + def push_changes(self): + return self.push_availability() and self.push_priceplans() and \ + self.push_restrictions() + + @api.model + def push_availability(self): + vroom_avail_ids = self.env['hotel.virtual.room.availability'].search([ + ('wpushed', '=', False), + ('date', '>=', date_utils.now(hours=False).strftime( + DEFAULT_SERVER_DATE_FORMAT)) + ]) + + vrooms = vroom_avail_ids.mapped('virtual_room_id') + avails = [] + for vroom in vrooms: + vroom_avails = vroom_avail_ids.filtered( + lambda x: x.virtual_room_id.id == vroom.id) + days = [] + for vroom_avail in vroom_avails: + vroom_avail.with_context({ + 'wubook_action': False}).write({'wpushed': True}) + wavail = vroom_avail.avail + if wavail > vroom_avail.wmax_avail: + wavail = vroom_avail.wmax_avail + date_dt = date_utils.get_datetime( + vroom_avail.date, + dtformat=DEFAULT_SERVER_DATE_FORMAT) + days.append({ + 'date': date_dt.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + 'avail': wavail, + 'no_ota': vroom_avail.no_ota and 1 or 0, + # 'booked': vroom_avail.booked and 1 or 0, + }) + avails.append({'id': vroom.wrid, 'days': days}) + _logger.info("UPDATING AVAILABILITY IN WUBOOK...") + _logger.info(avails) + if any(avails): + self.update_availability(avails) + return True + + @api.model + def push_priceplans(self): + unpushed = self.env['product.pricelist.item'].search([ + ('wpushed', '=', False), + ('date_start', '>=', date_utils.now(hours=False).strftime( + DEFAULT_SERVER_DATE_FORMAT)) + ], order="date_start ASC") + if any(unpushed): + date_start = date_utils.get_datetime( + unpushed[0].date_start, + dtformat=DEFAULT_SERVER_DATE_FORMAT) + date_end = date_utils.get_datetime( + unpushed[-1].date_start, + dtformat=DEFAULT_SERVER_DATE_FORMAT) + days_diff = date_utils.date_diff(date_start, date_end, hours=False) + 1 + + prices = {} + pricelist_ids = self.env['product.pricelist'].search([ + ('wpid', '!=', False), + ('active', '=', True) + ]) + for pr in pricelist_ids: + prices.update({pr.wpid: {}}) + unpushed_pl = self.env['product.pricelist.item'].search( + [('wpushed', '=', False), ('pricelist_id', '=', pr.id)]) + product_tmpl_ids = unpushed_pl.mapped('product_tmpl_id') + for pt_id in product_tmpl_ids: + vroom = self.env['hotel.virtual.room'].search([ + ('product_id.product_tmpl_id', '=', pt_id.id) + ], limit=1) + if vroom: + prices[pr.wpid].update({vroom.wrid: []}) + for i in range(0, days_diff): + prod = vroom.product_id.with_context({ + 'quantity': 1, + 'pricelist': pr.id, + 'date': (date_start + timedelta(days=i)). + strftime(DEFAULT_SERVER_DATE_FORMAT), + }) + prices[pr.wpid][vroom.wrid].append(prod.price) + _logger.info("UPDATING PRICES IN WUBOOK...") + _logger.info(prices) + for k_pk, v_pk in prices.iteritems(): + if any(v_pk): + self.update_plan_prices(k_pk, date_start.strftime( + DEFAULT_WUBOOK_DATE_FORMAT), v_pk) + + unpushed.with_context({ + 'wubook_action': False}).write({'wpushed': True}) + return True + + @api.model + def push_restrictions(self): + vroom_rest_obj = self.env['hotel.virtual.room.restriction'] + rest_item_obj = self.env['hotel.virtual.room.restriction.item'] + unpushed = rest_item_obj.search([ + ('wpushed', '=', False), + ('date_start', '>=', date_utils.now(hours=False).strftime( + DEFAULT_SERVER_DATE_FORMAT)) + ], order="date_start ASC") + if any(unpushed): + date_start = date_utils.get_datetime( + unpushed[0].date_start, + dtformat=DEFAULT_SERVER_DATE_FORMAT) + date_end = date_utils.get_datetime( + unpushed[-1].date_start, + dtformat=DEFAULT_SERVER_DATE_FORMAT) + days_diff = date_utils.date_diff( + date_start, + date_end, + hours=False) + 1 + restrictions = {} + restriction_plan_ids = vroom_rest_obj.search([ + ('wpid', '!=', False), + ('active', '=', True) + ]) + for rp in restriction_plan_ids: + restrictions.update({rp.wpid: {}}) + unpushed_rp = rest_item_obj.search([ + ('wpushed', '=', False), + ('restriction_id', '=', rp.id) + ]) + virtual_room_ids = unpushed_rp.mapped('virtual_room_id') + for vroom in virtual_room_ids: + restrictions[rp.wpid].update({vroom.wrid: []}) + for i in range(0, days_diff): + ndate_dt = date_start + timedelta(days=i) + restr = vroom.get_restrictions( + ndate_dt.strftime(DEFAULT_SERVER_DATE_FORMAT)) + if restr: + restrictions[rp.wpid][vroom.wrid].append({ + 'min_stay': restr.min_stay or 0, + 'min_stay_arrival': restr.min_stay_arrival or 0, + 'max_stay': restr.max_stay or 0, + 'max_stay_arrival': restr.max_stay_arrival or 0, + 'closed': restr.closed and 1 or 0, + 'closed_arrival': restr.closed_arrival and 1 or 0, + 'closed_departure': restr.closed_departure and 1 or 0, + }) + else: + restrictions[rp.wpid][vroom.wrid].append({}) + _logger.info("UPDATING RESTRICTIONS IN WUBOOK...") + _logger.info(restrictions) + for k_res, v_res in restrictions.iteritems(): + if any(v_res): + self.update_rplan_values( + int(k_res), + date_start.strftime(DEFAULT_WUBOOK_DATE_FORMAT), + v_res) + unpushed.with_context({ + 'wubook_action': False}).write({'wpushed': True}) + return True