diff options
Diffstat (limited to 'addons/website/static/src/js')
3 files changed, 295 insertions, 5 deletions
diff --git a/addons/website/static/src/js/content/website_root.js b/addons/website/static/src/js/content/website_root.js index dedf5c94359..fa2a01eecd2 100644 --- a/addons/website/static/src/js/content/website_root.js +++ b/addons/website/static/src/js/content/website_root.js @@ -1,15 +1,14 @@ odoo.define('website.root', function (require) { 'use strict'; -var core = require('web.core'); +const ajax = require('web.ajax'); +const {_t} = require('web.core'); var Dialog = require('web.Dialog'); const KeyboardNavigationMixin = require('web.KeyboardNavigationMixin'); const session = require('web.session'); var publicRootData = require('web.public.root'); require("web.zoomodoo"); -var _t = core._t; - var websiteRootRegistry = publicRootData.publicRootRegistry; var WebsiteRoot = publicRootData.PublicRoot.extend(KeyboardNavigationMixin, { @@ -20,8 +19,10 @@ var WebsiteRoot = publicRootData.PublicRoot.extend(KeyboardNavigationMixin, { 'shown.bs.modal': '_onModalShown', }), custom_events: _.extend({}, publicRootData.PublicRoot.prototype.custom_events || {}, { + 'gmap_api_request': '_onGMapAPIRequest', + 'gmap_api_key_request': '_onGMapAPIKeyRequest', 'ready_to_clean_for_save': '_onWidgetsStopRequest', - seo_object_request: '_onSeoObjectRequest', + 'seo_object_request': '_onSeoObjectRequest', }), /** @@ -91,6 +92,21 @@ var WebsiteRoot = publicRootData.PublicRoot.extend(KeyboardNavigationMixin, { }, this._super.apply(this, arguments)); }, /** + * @private + * @param {boolean} [refetch=false] + */ + async _getGMapAPIKey(refetch) { + if (refetch || !this._gmapAPIKeyProm) { + this._gmapAPIKeyProm = new Promise(async resolve => { + const data = await this._rpc({ + route: '/website/google_maps_api_key', + }); + resolve(JSON.parse(data).google_maps_api_key || ''); + }); + } + return this._gmapAPIKeyProm; + }, + /** * @override */ _getPublicWidgetsRegistry: function (options) { @@ -103,6 +119,50 @@ var WebsiteRoot = publicRootData.PublicRoot.extend(KeyboardNavigationMixin, { return registry; }, /** + * @private + * @param {boolean} [editableMode=false] + * @param {boolean} [refetch=false] + */ + async _loadGMapAPI(editableMode, refetch) { + // Note: only need refetch to reload a configured key and load the + // library. If the library was loaded with a correct key and that the + // key changes meanwhile... it will not work but we can agree the user + // can bother to reload the page at that moment. + if (refetch || !this._gmapAPILoading) { + this._gmapAPILoading = new Promise(async resolve => { + const key = await this._getGMapAPIKey(refetch); + + window.odoo_gmap_api_post_load = (async function odoo_gmap_api_post_load() { + await this._startWidgets(undefined, {editableMode: editableMode}); + resolve(key); + }).bind(this); + + if (!key) { + if (!editableMode && session.is_admin) { + this.displayNotification({ + type: 'warning', + sticky: true, + message: + $('<div/>').append( + $('<span/>', {text: _t("Cannot load google map.")}), + $('<br/>'), + $('<a/>', { + href: "/web#action=website.action_website_configuration", + text: _t("Check your configuration."), + }), + )[0].outerHTML, + }); + } + resolve(false); + this._gmapAPILoading = false; + return; + } + await ajax.loadJS(`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&callback=odoo_gmap_api_post_load&key=${key}`); + }); + } + return this._gmapAPILoading; + }, + /** * Toggles the fullscreen mode. * * @private @@ -164,6 +224,24 @@ var WebsiteRoot = publicRootData.PublicRoot.extend(KeyboardNavigationMixin, { window.location.href = _.str.sprintf("/website/lang/%(lang)s?r=%(url)s%(hash)s", redirect); }, /** + * @private + * @param {OdooEvent} ev + */ + async _onGMapAPIRequest(ev) { + ev.stopPropagation(); + const apiKey = await this._loadGMapAPI(ev.data.editableMode, ev.data.refetch); + ev.data.onSuccess(apiKey); + }, + /** + * @private + * @param {OdooEvent} ev + */ + async _onGMapAPIKeyRequest(ev) { + ev.stopPropagation(); + const apiKey = await this._getGMapAPIKey(ev.data.refetch); + ev.data.onSuccess(apiKey); + }, + /** /** * Checks information about the page SEO object. * diff --git a/addons/website/static/src/js/editor/snippets.editor.js b/addons/website/static/src/js/editor/snippets.editor.js index ca231278fd1..8e48424b853 100644 --- a/addons/website/static/src/js/editor/snippets.editor.js +++ b/addons/website/static/src/js/editor/snippets.editor.js @@ -1,16 +1,23 @@ odoo.define('website.snippet.editor', function (require) { 'use strict'; -const {_t} = require('web.core'); +const {qweb, _t} = require('web.core'); +const Dialog = require('web.Dialog'); const weSnippetEditor = require('web_editor.snippet.editor'); const wSnippetOptions = require('website.editor.snippets.options'); const FontFamilyPickerUserValueWidget = wSnippetOptions.FontFamilyPickerUserValueWidget; weSnippetEditor.Class.include({ + xmlDependencies: (weSnippetEditor.Class.prototype.xmlDependencies || []) + .concat(['/website/static/src/xml/website.editor.xml']), events: _.extend({}, weSnippetEditor.Class.prototype.events, { 'click .o_we_customize_theme_btn': '_onThemeTabClick', }), + custom_events: Object.assign({}, weSnippetEditor.Class.prototype.custom_events, { + 'gmap_api_request': '_onGMapAPIRequest', + 'gmap_api_key_request': '_onGMapAPIKeyRequest', + }), tabs: _.extend({}, weSnippetEditor.Class.prototype.tabs, { THEME: 'theme', }), @@ -32,6 +39,55 @@ weSnippetEditor.Class.include({ return this._super(...arguments); }, /** + * Depending of the demand, reconfigure they gmap key or configure it + * if not already defined. + * + * @private + * @param {boolean} [reconfigure=false] + * @param {boolean} [onlyIfUndefined=false] + */ + async _configureGMapAPI({reconfigure, onlyIfUndefined}) { + const apiKey = await new Promise(resolve => { + this.getParent().trigger_up('gmap_api_key_request', { + onSuccess: key => resolve(key), + }); + }); + if (!reconfigure && (apiKey || !onlyIfUndefined)) { + return false; + } + let websiteId; + this.trigger_up('context_get', { + callback: ctx => websiteId = ctx['website_id'], + }); + return new Promise(resolve => { + let invalidated = false; + const dialog = new Dialog(this, { + size: 'medium', + title: _t("Google Map API Key"), + buttons: [ + {text: _t("Save"), classes: 'btn-primary', close: true, click: async () => { + const newAPIKey = dialog.$('#api_key_input').val() || false; + await this._rpc({ + model: 'website', + method: 'write', + args: [ + [websiteId], + {google_maps_api_key: newAPIKey}, + ], + }); + invalidated = true; + }}, + {text: _t("Cancel"), close: true} + ], + $content: $(qweb.render('website.s_google_map_modal', { + apiKey: apiKey, + })), + }); + dialog.on('closed', this, () => resolve(invalidated)); + dialog.open(); + }); + }, + /** * @override */ _getScrollOptions(options = {}) { @@ -45,6 +101,23 @@ weSnippetEditor.Class.include({ return finalOptions; }, /** + * @private + * @param {OdooEvent} ev + * @param {string} gmapRequestEventName + */ + async _handleGMapRequest(ev, gmapRequestEventName) { + ev.stopPropagation(); + const reconfigured = await this._configureGMapAPI({ + reconfigure: ev.data.reconfigure, + onlyIfUndefined: ev.data.configureIfNecessary, + }); + this.getParent().trigger_up(gmapRequestEventName, { + refetch: reconfigured, + editableMode: true, + onSuccess: key => ev.data.onSuccess(key), + }); + }, + /** * @override */ _updateLeftPanelContent: function ({content, tab}) { @@ -58,6 +131,20 @@ weSnippetEditor.Class.include({ /** * @private + * @param {OdooEvent} ev + */ + _onGMapAPIRequest(ev) { + this._handleGMapRequest(ev, 'gmap_api_request'); + }, + /** + * @private + * @param {OdooEvent} ev + */ + _onGMapAPIKeyRequest(ev) { + this._handleGMapRequest(ev, 'gmap_api_key_request'); + }, + /** + * @private */ _onThemeTabClick: async function (ev) { this._addTabLoading(this.tabs.THEME); diff --git a/addons/website/static/src/js/editor/snippets.options.js b/addons/website/static/src/js/editor/snippets.options.js index 981ca05e387..db2d33585f4 100644 --- a/addons/website/static/src/js/editor/snippets.options.js +++ b/addons/website/static/src/js/editor/snippets.options.js @@ -211,8 +211,133 @@ const FontFamilyPickerUserValueWidget = SelectUserValueWidget.extend({ }, }); +const GPSPicker = InputUserValueWidget.extend({ + events: { // Explicitely not consider all InputUserValueWidget events + 'blur input': '_onInputBlur', + }, + + /** + * @constructor + */ + init() { + this._super(...arguments); + this._gmapCacheGPSToPlace = {}; + }, + /** + * @override + */ + async willStart() { + await this._super(...arguments); + this._gmapLoaded = await new Promise(resolve => { + this.trigger_up('gmap_api_request', { + editableMode: true, + configureIfNecessary: true, + onSuccess: key => resolve(!!key), + }); + }); + if (!this._gmapLoaded) { + this.trigger_up('user_value_widget_critical'); + return; + } + }, + /** + * @override + */ + async start() { + await this._super(...arguments); + this.el.classList.add('o_we_large_input'); + if (!this._gmapLoaded) { + return; + } + + this._gmapAutocomplete = new google.maps.places.Autocomplete(this.inputEl, {types: ['geocode']}); + google.maps.event.addListener(this._gmapAutocomplete, 'place_changed', this._onPlaceChanged.bind(this)); + }, + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + /** + * @override + */ + getMethodsParams: function (methodName) { + return Object.assign({gmapPlace: this._gmapPlace || {}}, this._super(...arguments)); + }, + + //-------------------------------------------------------------------------- + // Private + //-------------------------------------------------------------------------- + + /** + * @override + */ + _updateUI: async function () { + await this._super(...arguments); + + await new Promise(resolve => { + const gps = this._value; + if (this._gmapCacheGPSToPlace[gps]) { + this._gmapPlace = this._gmapCacheGPSToPlace[gps]; + resolve(); + return; + } + const service = new google.maps.places.PlacesService(document.createElement('div')); + const p = gps.substring(1).slice(0, -1).split(','); + const location = new google.maps.LatLng(p[0] || 0, p[1] || 0); + service.nearbySearch({ + // Do a 'nearbySearch' followed by 'getDetails' to avoid using + // GMap Geocoder which the user may not have enabled... but + // ideally Geocoder should be used to get the exact location at + // those coordinates and to limit billing query count. + location: location, + radius: 1, + }, (results, status) => { + const GMAP_CRITICAL_ERRORS = [google.maps.places.PlacesServiceStatus.REQUEST_DENIED, google.maps.places.PlacesServiceStatus.UNKNOWN_ERROR]; + if (status === google.maps.places.PlacesServiceStatus.OK) { + service.getDetails({ + placeId: results[0].place_id, + fields: ['geometry', 'formatted_address'], + }, (place, status) => { + resolve(); + if (status === google.maps.places.PlacesServiceStatus.OK) { + this._gmapCacheGPSToPlace[gps] = place; + this._gmapPlace = place; + } else if (GMAP_CRITICAL_ERRORS.includes(status)) { + this.trigger_up('user_value_widget_critical'); + } + }); + } else if (GMAP_CRITICAL_ERRORS.includes(status)) { + resolve(); + this.trigger_up('user_value_widget_critical'); + } + }); + }); + this.inputEl.value = this._gmapPlace.formatted_address; + }, + //-------------------------------------------------------------------------- + // Handlers + //-------------------------------------------------------------------------- + + /** + * @private + * @param {Event} ev + */ + _onPlaceChanged(ev) { + const gmapPlace = this._gmapAutocomplete.getPlace(); + if (gmapPlace && gmapPlace.geometry) { + this._gmapPlace = gmapPlace; + const location = this._gmapPlace.geometry.location; + this._value = `(${location.lat()},${location.lng()})`; + this._gmapCacheGPSToPlace[this._value] = gmapPlace; + this._onUserValueChange(ev); + } + }, +}); + options.userValueWidgetsRegistry['we-urlpicker'] = UrlPickerUserValueWidget; options.userValueWidgetsRegistry['we-fontfamilypicker'] = FontFamilyPickerUserValueWidget; +options.userValueWidgetsRegistry['we-gpspicker'] = GPSPicker; //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
