Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • coopdevs/comunitats-energetiques/odoo-ce
1 result
Show changes
Commits on Source (85)
Showing
with 934 additions and 343 deletions
class MapClientConfig:
# mapping between landings params and place params
MAPPING__INSTANCE_ID = 1
MAPPING__LANDING_ACTIVE_SERVICES__MAP_FILTER = {
"energy_communities.ce_tag_common_generation": "generacio-renovable-comunitaria",
"energy_communities.ce_tag_energy_efficiency": "eficiencia-energetica",
"energy_communities.ce_tag_sustainable_mobility": "mobilitat-sostenible",
"energy_communities.ce_tag_citizen_education": "formacio-ciutadana",
"energy_communities.ce_tag_thermal_energy": "energia-termica-i-climatitzacio",
"energy_communities.ce_tag_collective_purchases": "compres-col-lectives",
"energy_communities.ce_tag_renewable_energy": "subministrament-d-energia-100-renovable",
"energy_communities.ce_tag_aggregate_demand": "agregacio-i-flexibilitat-de-la-demanda",
}
MAPPING__MAP = "campanya"
MAPPING__LANDING_COMMUNITY_STATUS__MAP_FILTER = {"open": "oberta"}
MAPPING__LANDING_STATUS__MAP_PLACE_STATUS = {
"draft": "draft",
"publish": "published",
}
MAPPING__LANDING_COMMUNITY_TYPE__MAP_CATEGORY = {
"citizen": "ciutadania",
"industrial": "industrial",
}
MAPPING__LANDING_COMMUNITY_STATUS__MAP_PRESENTER = {"open": "CE Oberta"}
MAPPING__OPEN_PLACE_DESCRIPTION_META_KEY = "po2_description"
MAPPING__OPEN_PLACE_SOCIAL_HEADLINE_META_KEY = "po2_social_headline"
MAPPING__OPEN_PLACE_SOCIAL_HEADLINE_ORIGINAL = "<div class='flex justify-center align-center text-center'><p class='font-semibold text-white'>Comparteix i fem créixer la Comunitat Energètica</p></div>"
MAPPING__OPEN_PLACE_SOCIAL_HEADLINE_TRANSLATION = {
"es_ES": "<div class='flex justify-center align-center text-center'><p class='font-semibold text-white'>Comparte y hagamos crecer la Comunidad Energética</p></div>"
}
MAPPING__EXTERNAL_LINK__BECOME_COOPERATOR__LINK_LABEL = {
"ca_ES": "Fes-te'n soci/a",
"es_ES": "Hazte socio/a",
"eu_ES": "Bazkide bihurtu",
}
MAPPING__EXTERNAL_LINK__CONTACT__LINK_LABEL = {
"ca_ES": "Posa-t'hi en contacte",
"es_ES": "Ponte en contacto",
"eu_ES": "Jarri harremanetan",
}
MAPPING__EXTERNAL_LINK__LANDING__LINK_LABEL = {
"ca_ES": "Veure pàgina de la Comunitat",
"es_ES": "Ver página de la Comunidad",
"eu_ES": "Ikus Komunitatearen orria",
}
MAPPING__BUTTON_COLOR_CONFIG_NAME = {
"green": "Coorporate green dark button",
"yellow": "Coorporate yellow button",
}
from odoo import _
from odoo.exceptions import UserError
from ...pywordpress_client.resources.authenticate import Authenticate
from ...pywordpress_client.resources.landing_page import (
LandingPage as LandingPageResource,
)
from ..config import MapClientConfig
class LandingCmPlace:
_name = "landing_cmplace"
def __init__(self, landing):
self.landing = landing
self.wp_landing_data = self._get_wp_landing_data()
button_configs = self._get_button_color_configs()
if button_configs["errors"]:
raise UserError(error_msg)
else:
self.button_configs = button_configs["button_color_configs"]
def create(self):
"""
Creates a place from a landing instance.
"""
self._create_update_place("create")
def update(self):
"""
Updates a place from a landing instance.
"""
self._create_update_place("update")
def _create_update_place(self, mode):
validated_place_data = self._validate_and_prepare_place_data()
if validated_place_data["errors"]:
error_msg = ""
for error in validated_place_data["errors"]:
error_msg += error + "\n"
raise UserError(error_msg)
else:
if mode == "create":
place = self.landing.env["cm.place"].create(
validated_place_data["data"]
)
self.landing.write({"map_place_id": place.id})
if mode == "update":
place = self.landing.map_place_id
place.write(validated_place_data["data"])
self._place_extra_data_setup(place)
def _place_extra_data_setup(self, place):
place._get_slug_id()
place.build_presenter_metadata_ids()
# setup description
self._setup_place_description(place)
# setup external links
self._setup_external_links(place)
# apply translations
self._apply_place_metadatas_translations(place)
def _validate_and_prepare_place_data(self):
"""
Try to generate a place data dictionary and collect errors if they're
@returns: dictionary with 'data' key as the dict to be used for place creation or update and 'errors' key to collect errors if they're
"""
ret_dict = {
"data": {
"company_id": MapClientConfig.MAPPING__INSTANCE_ID,
"name": self.landing.name,
"type": "place",
"status": MapClientConfig.MAPPING__LANDING_STATUS__MAP_PLACE_STATUS[
self.landing.status
],
"interaction_method": "external_link",
"filter_mids": [(5, 0, 0)],
"address_txt": self._get_address_txt(),
},
"errors": [],
}
# Permissions
# TODO: Decide the permission level for this action
if self.landing.env.user.company_id.hierarchy_level not in [
"coordinator",
"instance",
]:
ret_dict["errors"].append(
_(
"Only users that belongs to the 'Coordinator' or 'Instance' company can create new Map Places."
)
)
# Map reference
map = self.landing.env["cm.map"].search(
[("slug_id", "=", MapClientConfig.MAPPING__MAP)]
)
if map:
ret_dict["data"]["map_id"] = map.id
else:
ret_dict["errors"].append(
_("Map not found slug_id: {}").format(self.MAPPING__MAP)
)
# Lat and Lng
if self.landing.lat:
ret_dict["data"]["lat"] = self.landing.lat
else:
ret_dict["errors"].append(
_("Landing lat param required for place creation")
)
if self.landing.lng:
ret_dict["data"]["lng"] = self.landing.lng
else:
ret_dict["errors"].append(
_("Landing lng param required for place creation")
)
# Place category
categories = self.landing.env["cm.place.category"].search([])
place_category_slug = (
MapClientConfig.MAPPING__LANDING_COMMUNITY_TYPE__MAP_CATEGORY[
self.landing.community_type
]
)
place_category = categories.filtered(lambda r: r.slug_id == place_category_slug)
if place_category:
ret_dict["data"]["place_category_id"] = place_category.id
else:
ret_dict["errors"].append(
_("Place category not found slug_id: {}").format(place_category_slug)
)
# Community status filter
filters = self.landing.env["cm.filter"].search([])
place_community_status_slug = (
MapClientConfig.MAPPING__LANDING_COMMUNITY_STATUS__MAP_FILTER[
self.landing.community_status
]
)
place_community_status = filters.filtered(
lambda r: r.slug_id == place_community_status_slug
)
if place_community_status:
ret_dict["data"]["marker_color"] = place_community_status.id
ret_dict["data"]["filter_mids"].append((4, place_community_status.id))
else:
ret_dict["errors"].append(
_("Place status filter not found slug_id: {}").format(
place_community_status_slug
)
)
# Community active services
for service in self.landing.community_active_services:
service_slug = MapClientConfig.MAPPING__LANDING_ACTIVE_SERVICES__MAP_FILTER[
service.tag_ext_id
]
place_service = filters.filtered(lambda r: r.slug_id == service_slug)
if place_service:
ret_dict["data"]["filter_mids"].append((4, place_service.id))
else:
ret_dict["errors"].append(
_("Place status filter not found slug_id: {}").format(service_slug)
)
# Presenter
presenter_name = (
MapClientConfig.MAPPING__LANDING_COMMUNITY_STATUS__MAP_PRESENTER[
self.landing.community_status
]
)
presenter = self.landing.env["cm.presenter.model"].search(
[("name", "=", presenter_name)]
)
if presenter:
ret_dict["data"]["presenter_model_id"] = presenter.id
else:
ret_dict["errors"].append(
_("Place presenter not found slug_id: {}").format(presenter_name)
)
return ret_dict
def _get_address_txt(self):
address_txt = ""
if self.landing.street:
address_txt = self.landing.street
if self.landing.postal_code:
if address_txt == "":
address_txt = self.landing.postal_code
else:
address_txt += ", " + self.landing.postal_code
if self.landing.city:
if address_txt == "":
address_txt = self.landing.city
else:
address_txt += ", " + self.landing.city
return address_txt
def _get_button_color_configs(self):
ret_dict = {"button_color_configs": {}, "errors": []}
button_color_configs = self.landing.env["cm.button.color.config"].search([])
ret_dict["button_color_configs"]["green"] = button_color_configs.filtered(
lambda r: r.name
== MapClientConfig.MAPPING__BUTTON_COLOR_CONFIG_NAME["green"]
)
ret_dict["button_color_configs"]["yellow"] = button_color_configs.filtered(
lambda r: r.name
== MapClientConfig.MAPPING__BUTTON_COLOR_CONFIG_NAME["yellow"]
)
if (
not ret_dict["button_color_configs"]["green"]
or not ret_dict["button_color_configs"]["yellow"]
):
ret_dict["errors"] = _("Button configs not found.")
return ret_dict
def _get_wp_landing_data(self):
instance_company = self.landing.env["res.company"].search(
[("hierarchy_level", "=", "instance")]
)
if instance_company:
baseurl = instance_company.wordpress_base_url
username = instance_company.wordpress_db_username
password = instance_company.wordpress_db_password
auth = Authenticate(baseurl, username, password).authenticate()
token = "Bearer %s" % auth["token"]
landing_page_wp_data = LandingPageResource(
token, baseurl, self.landing.wp_landing_page_id
).get()
return landing_page_wp_data
return False
def _setup_place_description(self, place):
desc_meta = self.landing.env["cm.place.presenter.metadata"].search(
[
("place_id", "=", place.id),
("key", "=", MapClientConfig.MAPPING__OPEN_PLACE_DESCRIPTION_META_KEY),
]
)
desc_meta.write({"value": self.landing.short_description})
def _setup_external_links(self, place):
new_external_links_ids = []
existing_external_links = self.landing.env["cm.place.external.link"].search(
[("place_id", "=", place.id)]
)
if self.landing.allow_new_members:
new_external_links_ids.append(
self._become_cooperator_external_link(place.id).id
)
else:
new_external_links_ids.append(self._contact_external_link(place.id).id)
new_external_links_ids.append(self._landing_external_link(place.id).id)
# remove old external_links if needed
for existing_external_link in existing_external_links:
if existing_external_link.id not in new_external_links_ids:
existing_external_link.unlink()
def _get_or_create_external_link(
self, place_id, name, url, target, button_color_config_id, sort_order
):
existing_external_links = self.landing.env["cm.place.external.link"].search(
[
("place_id", "=", place_id),
("name", "=", name),
("url", "=", url),
("target", "=", target),
("button_color_config_id", "=", button_color_config_id),
("sort_order", "=", sort_order),
]
)
if existing_external_links:
return existing_external_links[0]
else:
return self.landing.env["cm.place.external.link"].create(
{
"place_id": place_id,
"name": name,
"url": url,
"target": target,
"button_color_config_id": button_color_config_id,
"sort_order": sort_order,
}
)
def _become_cooperator_external_link(self, place_id):
external_link = self._get_or_create_external_link(
place_id,
MapClientConfig.MAPPING__EXTERNAL_LINK__BECOME_COOPERATOR__LINK_LABEL[
"ca_ES"
],
"{base_url}/become_cooperator?odoo_company_id={odoo_company_id}".format(
base_url=self.landing.env["ir.config_parameter"].get_param(
"web.base.url"
),
odoo_company_id=self.landing.company_id.id,
),
"_blank",
self.button_configs["yellow"].id,
0,
)
# es_ES Translation
self._update_translation(
"cm.place.external.link,name",
external_link.id,
MapClientConfig.MAPPING__EXTERNAL_LINK__BECOME_COOPERATOR__LINK_LABEL[
"ca_ES"
],
MapClientConfig.MAPPING__EXTERNAL_LINK__BECOME_COOPERATOR__LINK_LABEL[
"es_ES"
],
"es_ES",
)
self._update_translation(
"cm.place.external.link,url",
external_link.id,
"{base_url}/become_cooperator?odoo_company_id={odoo_company_id}".format(
base_url=self.landing.env["ir.config_parameter"].get_param(
"web.base.url"
),
odoo_company_id=self.landing.company_id.id,
),
"{base_url}/es/become_cooperator?odoo_company_id={odoo_company_id}".format(
base_url=self.landing.env["ir.config_parameter"].get_param(
"web.base.url"
),
odoo_company_id=self.landing.company_id.id,
),
"es_ES",
)
return external_link
def _contact_external_link(self, place_id):
external_link = self._get_or_create_external_link(
place_id,
MapClientConfig.MAPPING__EXTERNAL_LINK__CONTACT__LINK_LABEL["ca_ES"],
"{landing_link}/#contacte".format(
landing_link=self.wp_landing_data["link"]
),
"_top",
self.button_configs["yellow"].id,
0,
)
# es_ES Translation
self._update_translation(
"cm.place.external.link,name",
external_link.id,
MapClientConfig.MAPPING__EXTERNAL_LINK__CONTACT__LINK_LABEL["ca_ES"],
MapClientConfig.MAPPING__EXTERNAL_LINK__CONTACT__LINK_LABEL["es_ES"],
"es_ES",
)
if "es" in self.wp_landing_data["translations"].keys():
self._update_translation(
"cm.place.external.link,url",
external_link.id,
"{landing_link}/#contacte".format(
landing_link=self.wp_landing_data["link"]
),
"{landing_link}/#contacte".format(
landing_link=self.wp_landing_data["translations"]["es"]
),
"es_ES",
)
return external_link
def _landing_external_link(self, place_id):
external_link = self._get_or_create_external_link(
place_id,
MapClientConfig.MAPPING__EXTERNAL_LINK__LANDING__LINK_LABEL["ca_ES"],
self.wp_landing_data["link"],
"_top",
self.button_configs["green"].id,
1,
)
# es_ES Translation
self._update_translation(
"cm.place.external.link,name",
external_link.id,
MapClientConfig.MAPPING__EXTERNAL_LINK__LANDING__LINK_LABEL["ca_ES"],
MapClientConfig.MAPPING__EXTERNAL_LINK__LANDING__LINK_LABEL["es_ES"],
"es_ES",
)
if "es" in self.wp_landing_data["translations"].keys():
self._update_translation(
"cm.place.external.link,url",
external_link.id,
self.wp_landing_data["link"],
self.wp_landing_data["translations"]["es"],
"es_ES",
)
return external_link
def _apply_place_metadatas_translations(self, place):
for lang_code in self._get_active_languages():
# place description: applied from landing short_description already translated
landing_short_description_trans = self._get_translation(
"landing.page,short_description",
self.landing.id,
lang_code,
translated=True,
)
if landing_short_description_trans:
self._apply_place_metadata_translation(
place.id,
MapClientConfig.MAPPING__OPEN_PLACE_DESCRIPTION_META_KEY,
landing_short_description_trans.src,
landing_short_description_trans.value,
lang_code,
)
# place social headline: es_ES
self._apply_place_metadata_translation(
place.id,
MapClientConfig.MAPPING__OPEN_PLACE_SOCIAL_HEADLINE_META_KEY,
MapClientConfig.MAPPING__OPEN_PLACE_SOCIAL_HEADLINE_ORIGINAL,
MapClientConfig.MAPPING__OPEN_PLACE_SOCIAL_HEADLINE_TRANSLATION["es_ES"],
"es_ES",
)
def _apply_place_metadata_translation(
self, place_id, meta_key, original_value, trans_value, lang
):
related_meta = self.landing.env["cm.place.presenter.metadata"].search(
[("place_id", "=", place_id), ("key", "=", meta_key)]
)
if related_meta:
self._update_translation(
"cm.place.presenter.metadata,value",
related_meta.id,
original_value,
trans_value,
lang,
)
# TODO: Make all this translation block more compliant with ir.translation model
def _get_active_languages(self):
return self.landing.env["res.lang"].search([("active", "=", 1)]).mapped("code")
def _get_translation(self, translation_name, res_id, lang, translated=False):
query = [
("name", "=", translation_name),
("res_id", "=", res_id),
("lang", "=", lang),
]
if translated:
query.append(("state", "=", "translated"))
return self.landing.env["ir.translation"].search(query)
def _update_translation(
self, translation_name, res_id, original_value, trans_value, lang
):
translation = self._get_translation(translation_name, res_id, lang)
if translation:
translation.write(
{"src": original_value, "value": trans_value, "state": "translated"}
)
else:
self.landing.env["ir.translation"].create(
{
"name": translation_name,
"res_id": res_id,
"lang": lang,
"type": "model",
"src": original_value,
"value": trans_value,
"state": "translated",
}
)
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * energy_communities
......@@ -591,9 +592,9 @@ msgid "Allows new members"
msgstr "Autoritza nous membres"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__wp_lastupdate_datetime
msgid "Last wordpress update date"
msgstr "Data darrera actualització a wordpress"
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__publicdata_lastupdate_datetime
msgid "Last wordpress/map update date"
msgstr "Data darrera actualització a wordpress/mapa"
#. module: energy_communities
#: code:addons/energy_communities/models/res_company.py:0
......@@ -971,8 +972,8 @@ msgstr "Crear pàgina de Landing"
#. module: energy_communities
#: model_terms:ir.ui.view,arch_db:energy_communities.landing_page_form_view
msgid "Update wordpress data"
msgstr "Actualizar dades wordpress"
msgid "Update (wp landing / map place)"
msgstr "Actualizar dades wordpress/mapa"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_account_multicompany_easy_creation_wiz__create_user
......@@ -1195,11 +1196,6 @@ msgstr "General"
msgid "General Information"
msgstr "Informació general"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__group_image_link
msgid "Group image link"
msgstr "Enllaç d'imatge del grup"
#. module: energy_communities
#: model_terms:ir.ui.view,arch_db:energy_communities.voluntary_share_text_template
msgid "Hello,"
......@@ -1426,11 +1422,6 @@ msgstr "Descripció llarga"
msgid "Mandatory Shares"
msgstr "Aportacions obligatòries"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__map_geolocation
msgid "Map geolocation"
msgstr "Mapa de geolocalització"
#. module: energy_communities
#: model:crm.tag,name:energy_communities.ce_tag_sustainable_mobility
msgid "Mobilitat sostenible"
......@@ -2361,3 +2352,46 @@ msgid "€ by follow the steps you will receive by email."
msgstr ""
"€ seguint els passos que t'indicarem per correu electrònic un cop rebem la "
"teva petició."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Only users that belongs to the 'Coordinator' or 'Instance' company can create new Map Places."
msgstr "Només els usuaris coordinadors de Comunitat o d'instancia poden crear punts de mapa"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Map not found slug_id: {}"
msgstr "No s'ha trobat mapa per slug_id: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Landing lat param required for place creation"
msgstr "La latitud de la landing és requerit per la creació del punt de mapa"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Landing lng param required for place creation"
msgstr "La longitud de la landing és requerida per la creació del punt de mapa"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Place category not found slug_id: {}"
msgstr "No s'ha trobat categoria de mapa per slug_id: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Place status filter not found slug_id: {}"
msgstr "No s'ha trobat filtre de mapa per slug_id: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Button configs not found."
msgstr "No s'ha trobat configuració de botons"
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * energy_communities
......@@ -2191,3 +2192,4 @@ msgstr ""
#: model_terms:ir.ui.view,arch_db:energy_communities.becomecooperator_ccee
msgid "€ by follow the steps you will receive by email."
msgstr ""
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * energy_communities
......@@ -135,9 +136,9 @@ msgstr ""
"Una vez verificada la validez del pago realizado recibirás una nueva notificación confirmando la aportación realizada y detallando las condiciones particulares de tu aportación.\n"
" </p>\n"
" <p>\n"
"Agradecer tu implicación con la cooperativa y informarte que para cualquier duda o aclaración puedes consultar nuestra web \n"
"Agradecer tu implicación con la cooperativa y informarte que para cualquier duda o aclaración puedes consultar nuestra web \n"
" <a href=\"${object.company_id.website}\"> ${object.company_id.website}</a>\n"
" o enviarnos un correo electrónico \n"
" o enviarnos un correo electrónico \n"
" <a href=\"${object.company_id.email}\">${object.company_id.email}</a>\n"
" </p>\n"
" <p>\n"
......@@ -526,9 +527,9 @@ msgid "Allows new members"
msgstr ""
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__wp_lastupdate_datetime
msgid "Last wordpress update date"
msgstr "Fecha última actualización de wordpress"
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__publicdata_lastupdate_datetime
msgid "Last wordpress/map update date"
msgstr "Fecha última actualización de wordpress/mapa"
#. module: energy_communities
#: code:addons/energy_communities/models/res_company.py:0
......@@ -856,8 +857,8 @@ msgstr "Crear página de Landing"
#. module: energy_communities
#: model_terms:ir.ui.view,arch_db:energy_communities.landing_page_form_view
msgid "Update wordpress data"
msgstr "Actualizar datos wordpress"
msgid "Update (wp landing / map place)"
msgstr "Actualizar datos wordpress/mapa"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_account_multicompany_easy_creation_wiz__create_user
......@@ -1283,11 +1284,6 @@ msgstr ""
msgid "Mandatory Shares"
msgstr "Aportaciones obligatorias"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__map_geolocation
msgid "Map geolocation"
msgstr ""
#. module: energy_communities
#: model:crm.tag,name:energy_communities.ce_tag_sustainable_mobility
msgid "Mobilitat sostenible"
......@@ -2277,11 +2273,6 @@ msgstr "Coordinador Trabajador"
msgid "Energy Community Manager"
msgstr "Gerente de la Comunidad de Energía"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__group_image_link
msgid "Group image link"
msgstr "Enlace de imagen de grupo"
#. module: energy_communities
#: code:addons/energy_communities/models/landing_page.py:0
#: code:addons/energy_communities/models/landing_page.py:0
......@@ -2335,3 +2326,46 @@ msgstr "Enlace de Telegram"
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__twitter_link
msgid "Twitter link"
msgstr "Enlace de Twitter"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Only users that belongs to the 'Coordinator' or 'Instance' company can create new Map Places."
msgstr "Solo usuarios de tipo coordinador de Comunidad o de instancia pueden crear puntos de mapa."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Map not found slug_id: {}"
msgstr "No se ha encontrado mapa para slug_id: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Landing lat param required for place creation"
msgstr "La Latitud de la landing es requerida para la creación del punto de mapa."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Landing lng param required for place creation"
msgstr "La Longitud de la landing es requerida para la creación del punto de mapa."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Place category not found slug_id: {}"
msgstr "No se ha encontrado categoria de mapa para slug_id: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Place status filter not found slug_id: {}"
msgstr "No se ha encontrado filtro de mapa para slug_id: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Button configs not found."
msgstr "Configuración de botones no encontrada."
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * energy_communities
......@@ -598,9 +599,9 @@ msgid "Allows new members"
msgstr "Kide berriei baimena ematea"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__wp_lastupdate_datetime
msgid "Last wordpress update date"
msgstr "Wordpress eguneratzearen azken data"
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__publicdata_lastupdate_datetime
msgid "Last wordpress/map update date"
msgstr "Wordpress/Mapa eguneratzearen azken data"
#. module: energy_communities
#: code:addons/energy_communities/models/res_company.py:0
......@@ -984,8 +985,8 @@ msgstr "Sortu helmuga orria"
#. module: energy_communities
#: model_terms:ir.ui.view,arch_db:energy_communities.landing_page_form_view
msgid "Update wordpress data"
msgstr "Eguneratu wordpress datuak"
msgid "Update (wp landing / map place)"
msgstr "Eguneratu wordpress/mapa datuak"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_account_multicompany_easy_creation_wiz__create_user
......@@ -1208,11 +1209,6 @@ msgstr "Orokorra"
msgid "General Information"
msgstr "Informazio orokorra"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__group_image_link
msgid "Group image link"
msgstr "Taldeko irudiaren esteka"
#. module: energy_communities
#: model_terms:ir.ui.view,arch_db:energy_communities.voluntary_share_text_template
msgid "Hello,"
......@@ -1445,11 +1441,6 @@ msgstr "Deskribapen luzea"
msgid "Mandatory Shares"
msgstr "Nahitaezko akzioak"
#. module: energy_communities
#: model:ir.model.fields,field_description:energy_communities.field_landing_page__map_geolocation
msgid "Map geolocation"
msgstr "Maparen geokokapena"
#. module: energy_communities
#: model:crm.tag,name:energy_communities.ce_tag_sustainable_mobility
msgid "Mobilitat sostenible"
......@@ -2363,3 +2354,46 @@ msgstr " Borondatezko Ekarpenen."
#: model_terms:ir.ui.view,arch_db:energy_communities.becomecooperator_ccee
msgid "€ by follow the steps you will receive by email."
msgstr "€ posta elektronikoz jasoko dituzun urratsak jarraituz."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Only users that belongs to the 'Coordinator' or 'Instance' company can create new Map Places."
msgstr "Komunitate edo Instantzia Koordinatzaile motako erabiltzaileek soilik sor ditzakete mapa-puntuak."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Map not found slug_id: {}"
msgstr "Ez da maparik aurkitu slug_id-rako: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Landing lat param required for place creation"
msgstr "Lurreratzearen latitudea behar da mapa-puntua sortzeko."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Landing lng param required for place creation"
msgstr "Lurreratze-luzera beharrezkoa da mapa-puntua sortzeko."
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Place category not found slug_id: {}"
msgstr "Ez da aurkitu maparen kategoriarik slug_id-erako: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Place status filter not found slug_id: {}"
msgstr "Ez da aurkitu mapa-iragazkirik slug_id-rako: {}"
#. module: energy_communities
#: code:addons/energy_communities/client_map/resources/landing_cmplace.py:0
#, python-format
msgid "Button configs not found."
msgstr "Ez da aurkitu botoiaren konfigurazioa."
from . import cm_coordinates_mixin
from . import auth_oauth_provider
from . import account_chart_template
from . import landing_page
......
from odoo import fields, models
class CmCoordinatesMixin(models.AbstractModel):
_name = "cm.coordinates.mixin"
_description = "Add map coordinates to any model"
lat = fields.Char(string="Latitude")
lng = fields.Char(string="Longitude")
......@@ -7,18 +7,6 @@ from odoo.exceptions import UserError
class CrmLead(models.Model):
_inherit = "crm.lead"
# mapping between the xml_ids related to crm.lead.tag_ids and cm.filter xmlids
_XMLID_MAPPING_LEADTAGS_CMFILTERS = [
("ce_tag_common_generation", "ce_cm_filter_community_renewal_generation"),
("ce_tag_energy_efficiency", "ce_cm_filter_energetic_eficiency"),
("ce_tag_sustainable_mobility", "ce_cm_filter_sustainable_mobility"),
("ce_tag_citizen_education", "ce_cm_filter_citizen_education"),
("ce_tag_thermal_energy", "ce_cm_filter_thermical_energy"),
("ce_tag_collective_purchases", "ce_cm_filter_collective_purchase"),
("ce_tag_renewable_energy", "ce_cm_filter_renewal_energy_supply"),
("ce_tag_aggregate_demand", "ce_cm_filter_demand_flexibility_and_aggregation"),
]
lang = fields.Char(string="Language")
ce_tag_ids = fields.Many2many(
"crm.tag",
......@@ -28,14 +16,25 @@ class CrmLead(models.Model):
string="CE Tags",
help="CE Classify and analyze categories",
)
community_company_id = fields.Many2one(
string="Related Community",
comodel_name="res.company",
domain="[('coordinator','!=',True)]",
help="Community related to this Lead",
)
finished = fields.Boolean(
related="stage_id.is_won",
readonly=True,
)
company_hierarchy_level = fields.Selection(
related="company_id.hierarchy_level",
readonly=True,
)
can_be_assigned_to_coordinator = fields.Boolean(
string="Can be assigned to coordinator",
compute="_get_can_be_assigned_to_coordinator",
store=False,
)
is_instance_company = fields.Boolean(
string="Is instance company", compute="_is_instance_company"
)
......@@ -50,172 +49,6 @@ class CrmLead(models.Model):
else:
self.is_instance_company = False
def _create_map_place_proposal(self):
if not self.env.user.company_id.coordinator:
raise UserError(
_(
"Only users that belongs to the 'Coordinator' company can create new Map Places from Leads."
)
)
active_categ_id = self.env["ir.model.data"].get_object_reference(
"ce", "ce_cm_place_category_active"
)[1]
building_categ_id = self.env["ir.model.data"].get_object_reference(
"ce", "ce_cm_place_category_building"
)[1]
default_ce_map_id = self.env["ir.model.data"].get_object_reference(
"ce", "ce_default_cm_map"
)[1]
creation_ce_source_id = self.env["ir.model.data"].get_object_reference(
"ce", "ce_source_creation_ce_proposal"
)[1]
for lead in self:
if self.env["crm.team"].search(
[
("proposal_form_submission_id", "=", lead.id),
("map_id", "=", default_ce_map_id),
]
):
raise UserError(
_(
"There is an allready existing Map Place related to this Lead: {}."
).format(lead.name)
)
if not lead.source_id or lead.source_id.id != creation_ce_source_id:
raise UserError(
_(
"The Source {} of Lead {} do not allow the creation of Map Proposals"
).format(lead.source_id.name, lead.name)
)
place_creation_data = {
"name": lead.name,
"map_id": default_ce_map_id,
"team_type": "map_place_proposal",
"user_id": self.env.user.id,
"proposal_form_submission_id": lead.id,
"interaction_method": "external_link",
"external_link_target": "_top",
}
# read metadata key/value pairs
m_dict = {m.key: m.value for m in lead.form_submission_metadata_ids}
if (
m_dict.get("partner_legal_state", False)
and m_dict["partner_legal_state"]
):
if m_dict["partner_legal_state"] == "active":
place_creation_data["place_category_id"] = active_categ_id
else:
place_creation_data["place_category_id"] = building_categ_id
else:
raise UserError(
_(
"Unable to get the Category (mandatory map place field) from Lead: {}"
).format(lead.name)
)
if m_dict.get("partner_latitude", False) and m_dict["partner_latitude"]:
place_creation_data["lat"] = m_dict["partner_latitude"]
else:
raise UserError(
_(
"Unable to get the Latitude (mandatory map place field) from Lead: {}"
).format(lead.name)
)
if m_dict.get("partner_longitude", False) and m_dict["partner_longitude"]:
place_creation_data["lng"] = m_dict["partner_longitude"]
else:
raise UserError(
_(
"Unable to get the Longitude (mandatory map place field) from Lead: {}"
).format(lead.name)
)
if (
m_dict.get("partner_map_place_form_url", False)
and m_dict["partner_map_place_form_url"]
):
place_creation_data["external_link_url"] = m_dict[
"partner_map_place_form_url"
]
place_creation_data["address_txt"] = lead._get_address_txt() or None
place_creation_data["filter_mids"] = [(6, 0, lead._get_cmfilter_ids())]
place = self.env["crm.team"].create(place_creation_data)
# we need to do call those next 2 functions because the @api.onchange('map_id') defined on community_maps module
# is not being called on crm_team.create(). TODO: review why it happens and fix it.
place._get_slug_id()
place._get_config_relations_attrs()
place._build_presenter_metadata_ids()
place.place_category_id = place_creation_data["place_category_id"]
place.message_subscribe([self.env.user.partner_id.id])
pmnd_ids = [
m
for m in place.place_presenter_metadata_ids
if m.key == "p_description"
]
description_pmnd_id = pmnd_ids and pmnd_ids[0] or None
if description_pmnd_id and lead.description:
description_pmnd_id.value = "<p class='m-2'>{}</p>".format(
lead.description
)
# lead update
lead.write(
{
"team_id": place.id,
"submission_type": "place_proposal_submission",
}
)
def _get_cmfilter_ids(self):
self.ensure_one()
md = self.env["ir.model.data"]
id_pairs = {}
for pair in self._XMLID_MAPPING_LEADTAGS_CMFILTERS:
id_pairs[
md.get_object_reference("ce", pair[0])[1]
] = md.get_object_reference("ce", pair[1])[1]
return [id_pairs[t.id] for t in self.tag_ids if t.id in id_pairs]
def _get_address_txt(self):
self.ensure_one()
ret = ""
meta_address_txt = [
meta.value
for meta in self.form_submission_metadata_ids
if meta.key == "partner_full_address"
]
if self.street and (self.city or self.zip):
ret = "{}{}. {}{}".format(
self.street,
(self.street2 and " " + self.street2) or "",
self.zip or "",
(self.city and " " + self.city) or "",
)
if self.state_id:
ret += ", {}".format(self.state_id.name)
if self.country_id:
ret += ". {}".format(self.country_id.name)
elif meta_address_txt and meta_address_txt[0]:
ret = meta_address_txt[0]
return ret
def _build_community_company(self):
if not self.env.user.company_id.coordinator:
raise UserError(
......@@ -240,7 +73,7 @@ class CrmLead(models.Model):
if not lead.community_company_id:
# Create the new company using very basic starting Data
company = self.env["res.company"].create(
lead._get_company_create_vals()
lead._get_default_community_wizard()
)
# Update Lead & Map Place (if exist) fields accordingly
......@@ -258,20 +91,17 @@ class CrmLead(models.Model):
lead.community_company_id._create_keycloak_realm()
lead.community_company_id._community_post_keycloak_creation_tasks()
def _get_company_create_vals(self):
def _get_default_community_wizard(self):
self.ensure_one()
m_dict = {m.key: m.value for m in self.form_submission_metadata_ids}
metadata = {m.key: m.value for m in self.metadata_line_ids}
foundation_date = None
if (
m_dict.get("partner_foundation_date", False)
and m_dict["partner_foundation_date"]
):
if metadata.get("ce_creation_date", False) and metadata["ce_creation_date"]:
date_formats = ["%Y-%m-%d", "%d-%m-%Y", "%Y/%m/%d", "%d/%m/%Y"]
for date_format in date_formats:
try:
foundation_date = datetime.strptime(
m_dict["partner_foundation_date"], date_format
metadata["ce_creation_date"], date_format
)
except:
pass
......@@ -279,60 +109,52 @@ class CrmLead(models.Model):
raise UserError(
_(
"The Foundation Date value {} have a non valid format. It must be: yyyy-mm-dd or dd-mm-yyyy or yyyy/mm/dd or dd/mm/yyyy"
).format(m_dict["partner_foundation_date"])
).format(metadata["partner_foundation_date"])
)
initial_share_amount = 0.00
if (
m_dict.get("partner_initial_share_amount", False)
and m_dict["partner_initial_share_amount"]
or None
):
try:
initial_share_amount = float(m_dict["partner_initial_share_amount"])
except:
pass
lang_id = None
if m_dict.get("partner_language", False) and m_dict["partner_language"] or None:
if metadata.get("current_lang", False) and metadata["current_lang"] or None:
lang_id = self.env["res.lang"].search(
[("code", "=", m_dict["partner_language"])], limit=1
[("code", "=", metadata["current_lang"])], limit=1
)
create_vals = {
users = [user.id for user in self.company_id.get_users()]
return {
"name": self.name,
"street": self.street,
"street2": self.street2,
"city": self.city,
"zip": self.zip,
"state_id": self.state_id.id,
"country_id": self.country_id.id,
"website": self.website,
"phone": self.phone,
"email": self.email_from
or (m_dict.get("contact_email", False) and m_dict["contact_email"])
or None,
"vat": m_dict.get("partner_vat", False) and m_dict["partner_vat"] or None,
"social_twitter": m_dict.get("partner_twitter", False)
and m_dict["partner_twitter"]
"parent_id": self.company_id.id,
"crm_lead_id": self.id,
"user_ids": users,
"street": metadata.get("ce_address", False)
and metadata["ce_address"]
or None,
"social_facebook": m_dict.get("partner_facebook", False)
and m_dict["partner_facebook"]
"city": metadata.get("ce_city", False) and metadata["ce_city"] or None,
"zip_code": metadata.get("ce_zip", False) and metadata["ce_zip"] or None,
"phone": metadata.get("contact_phone", False)
and metadata["contact_phone"]
or None,
"social_instagram": m_dict.get("partner_instagram", False)
and m_dict["partner_instagram"]
"email": metadata.get("email_from", False)
and metadata["email_from"]
or None,
"social_telegram": m_dict.get("partner_telegram", False)
and m_dict["partner_telegram"]
or None,
"create_user": True,
"vat": metadata.get("ce_vat", False) and metadata["ce_vat"] or None,
"foundation_date": foundation_date,
"initial_subscription_share_amount": initial_share_amount,
"default_lang_id": lang_id and lang_id.id or None,
"chart_template_id": self.env.ref(
"l10n_es.account_chart_template_pymes"
).id,
"update_default_taxes": True,
"default_sale_tax_id": self.env.ref(
"l10n_es.account_tax_template_s_iva21s"
).id,
"default_purchase_tax_id": self.env.ref(
"l10n_es.account_tax_template_p_iva21_bc"
).id,
"property_cooperator_account": self.env["account.account"]
.search([("code", "like", "44000%")], limit=1)
.id,
"create_user": False,
}
return create_vals
def _create_keycloak_realm(self):
for lead in self:
if not lead.community_company_id:
......@@ -356,6 +178,34 @@ class CrmLead(models.Model):
"target": "new",
}
def action_create_community(self):
data = self._get_default_community_wizard()
wizard = self.env["account.multicompany.easy.creation.wiz"].create(data)
return {
"type": "ir.actions.act_window",
"name": _("Create community"),
"res_model": "account.multicompany.easy.creation.wiz",
"view_type": "form",
"view_mode": "form",
"target": "new",
"res_id": wizard.id,
}
@api.depends("source_id")
def _get_can_be_assigned_to_coordinator(self):
for record in self:
record.can_be_assigned_to_coordinator = (
record.source_id.id
in [
self.env.ref("energy_communities.ce_source_general_info").id,
self.env.ref("energy_communities.ce_source_existing_ce_contact").id,
self.env.ref(
"energy_communities.ce_source_creation_ce_proposal"
).id,
]
and self.company_id.hierarchy_level == "instance"
)
def add_follower(self):
instance_admin = self.env.ref("energy_communities.role_ce_manager").id
company_id = self.company_id.id
......
......@@ -2,6 +2,9 @@ from datetime import datetime
from odoo import _, api, fields, models
from ..client_map.resources.landing_cmplace import (
LandingCmPlace as LandingCmPlaceResource,
)
from ..pywordpress_client.resources.authenticate import Authenticate
from ..pywordpress_client.resources.landing_page import (
LandingPage as LandingPageResource,
......@@ -12,6 +15,8 @@ from .res_config_settings import ResConfigSettings
class LandingPage(models.Model):
_name = "landing.page"
_inherit = ["cm.coordinates.mixin"]
name = fields.Char(string="Name", translate=True)
company_id = fields.Many2one("res.company", string="Company")
wp_landing_page_id = fields.Integer(string="WP Landing Page")
......@@ -35,8 +40,6 @@ class LandingPage(models.Model):
instagram_link = fields.Char(
string="Instagram link", related="company_id.social_instagram"
)
# TODO: group_image_link Left for backward compatibility. To be removed
group_image_link = fields.Char(string="Group image link")
primary_image_file = fields.Image("Primary Image")
secondary_image_file = fields.Image("Secondary Image")
short_description = fields.Text(string="Short description", translate=True)
......@@ -45,8 +48,6 @@ class LandingPage(models.Model):
become_cooperator_process = fields.Html(
string="Become cooperator process", translate=True
)
# TODO: remove this one
map_geolocation = fields.Char(string="Map geolocation")
map_place_id = fields.Many2one("cm.place", "Place reference")
street = fields.Char(string="Street")
postal_code = fields.Char(string="Postal code")
......@@ -72,7 +73,9 @@ class LandingPage(models.Model):
required=True,
string="Community status",
)
wp_lastupdate_datetime = fields.Datetime(string="Last wordpress update date")
publicdata_lastupdate_datetime = fields.Datetime(
string="Last wordpress/map update date"
)
def _get_image_attachment(self, field_name):
file_attachment = self.env["ir.attachment"].search(
......@@ -159,8 +162,6 @@ class LandingPage(models.Model):
"instagram_link": self.instagram_link or "",
"telegram_link": self.telegram_link or "",
"community_active_services": self.company_id.get_active_services(),
# TODO: group_image_link Left for backward compatibility. To be removed
"group_image_link": self.group_image_link or "",
"primary_image_file": primary_image_file,
"primary_image_file_write_date": primary_image_file_write_date,
"secondary_image_file": secondary_image_file,
......@@ -169,7 +170,6 @@ class LandingPage(models.Model):
"long_description": self.long_description or "",
"why_become_cooperator": self.why_become_cooperator,
"become_cooperator_process": self.become_cooperator_process,
"map_geolocation": self.map_geolocation or "",
"map_reference": map_reference,
"street": self.street or "",
"postal_code": self.postal_code or "",
......@@ -182,9 +182,27 @@ class LandingPage(models.Model):
new_status = "draft" if record.status == "publish" else "publish"
record.write({"status": new_status})
def action_update_wp(self):
def action_create_landing_place(self):
for record in self:
record._create_landing_place()
def action_update_public_data(self):
for record in self:
record._update_wordpress()
record._update_landing_place()
self.write({"publicdata_lastupdate_datetime": datetime.now()})
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"type": "success",
"title": _("Public data update successful"),
"message": _(
"Wordpress landing and map place has been successfully updated."
),
"sticky": False,
},
}
def _update_wordpress(self):
instance_company = self.env["res.company"].search(
......@@ -200,4 +218,9 @@ class LandingPage(models.Model):
LandingPageResource(token, baseurl, self.wp_landing_page_id).update(
landing_page_data
)
self.write({"wp_lastupdate_datetime": datetime.now()})
def _create_landing_place(self):
LandingCmPlaceResource(self).create()
def _update_landing_place(self):
LandingCmPlaceResource(self).update()
......@@ -14,9 +14,26 @@ _HIERARCHY_LEVEL_VALUES = [
("community", _("Community")),
]
_LEGAL_FROM_VALUES = [
("Societat Cooperativa", _("Societat Cooperativa")),
("Associació sense ànim de lucre", _("Associació sense ànim de lucre")),
("Societat Limitada", _("Societat Limitada")),
("Societat Col·lectiva", _("Societat Col·lectiva")),
("Comunitat de Bens", _("Comunitat de Bens")),
("Societat Comanditària", _("Societat Comanditària")),
("Societat Anónima", _("Societat Anónima")),
("Empresari Individual", _("Empresari Individual")),
]
_CE_STATUS_VALUES = [
("active", _("active")),
("building", _("building")),
]
class ResCompany(models.Model):
_inherit = "res.company"
_name = "res.company"
_inherit = ["res.company", "mail.thread", "mail.activity.mixin"]
@api.onchange("hierarchy_level")
def onchange_hierarchy_level(self):
......@@ -75,6 +92,25 @@ class ResCompany(models.Model):
domain=[("is_share", "=", True)],
string="Voluntary share to show on website",
)
wordpress_base_url = fields.Char(string=_("Wordpress Base URL (JWT auth)"))
admins = fields.One2many(
"res.users",
string="Community admins",
compute="_get_admins",
readonly=True,
store=False,
)
legal_form = fields.Selection(
selection=_LEGAL_FROM_VALUES,
string="Legal form",
)
legal_name = fields.Char(string="Legal name")
ce_status = fields.Selection(
selection=_CE_STATUS_VALUES,
string="Energy Community state",
)
landing_page_id = fields.Many2one("landing.page", string=_("Landing Page"))
wordpress_db_username = fields.Char(string=_("Wordpress DB Admin Username"))
wordpress_db_password = fields.Char(string=_("Wordpress DB Admin Password"))
......@@ -155,6 +191,26 @@ class ResCompany(models.Model):
admins_user_ids.append(role_line.user_id.id)
return any([user in admins_user_ids for user in company_user_ids])
def _get_admin_role_name(self):
if self.hierarchy_level == "community":
return "role_ce_admin"
elif self.hierarchy_level == "coordinator":
return "role_coord_admin"
elif self.hierarchy_level == "instance":
return "role_platform_admin"
def _get_admins(self):
role_name = self._get_admin_role_name()
for rec in self:
role_lines = self.env["res.users.role.line"].search(
[
("company_id.id", "=", self.id),
("active", "=", True),
("role_id.code", "=", role_name),
]
)
rec.admins = role_lines.mapped("user_id")
def get_ce_members(self, domain_key="in_kc_and_active"):
domains_dict = {
"in_kc_and_active": [
......@@ -163,8 +219,57 @@ class ResCompany(models.Model):
("active", "=", True),
]
}
members = self.env["res.users"].sudo().search(domains_dict["in_kc_and_active"])
return members
return self.env["res.users"].sudo().search(domains_dict["in_kc_and_active"])
def get_users(self, role_codes=False):
role_codes = role_codes or []
if role_codes:
users = (
self.env["res.users.role.line"]
.sudo()
.search(
[
("company_id", "=", self.id),
("role_id.code", "in", role_codes),
]
)
.user_id
)
else:
users = (
self.env["res.users.role.line"]
.sudo()
.search(
[
("company_id", "=", self.id),
]
)
.user_id
)
wants_platform_admins = (
self.env.ref("energy_communities.role_platform_admin").code in role_codes
or not role_codes
)
if wants_platform_admins:
users += (
self.env["res.users.role.line"]
.sudo()
.search(
[
(
"role_id",
"=",
self.env.ref("energy_communities.role_platform_admin").id,
),
]
)
.user_id
)
return users
# return lines.user_id # TODO: Si?
@api.model
def _is_not_unique(self, vals):
......
import logging
from odoo import SUPERUSER_ID, api, fields, models
from odoo.exceptions import ValidationError
logger = logging.getLogger(__name__)
......@@ -38,15 +37,6 @@ class ResPartner(models.Model):
new_partner = super().create(vals)
return new_partner
# @api.constrains('email') # TODO: Remove!!
# def _check_email(self):
# count_users = self.env['res.partner'].search_count([
# ('email', '=', self.email),
# ('user_ids', '!=', False)
# ])
# if self.email and count_users > 0:
# raise ValidationError(_('The email already registered, please use another email!'))
def cron_update_company_ids_from_user(self):
partner_with_users = self.search(
[("user_ids", "!=", False), ("user_ids.id", "!=", SUPERUSER_ID)]
......
......@@ -274,36 +274,9 @@ class ResUsers(models.Model):
)
def make_coord_user(self, company_id, role_name):
role = self.env["res.users.role"].search([("code", "=", role_name)])
current_role = self.env["res.users.role.line"].search(
[
("user_id", "=", self.id),
("active", "=", True),
("company_id", "=", company_id),
]
)
if current_role:
current_role.write({"role_id": role})
else:
self.write(
{
"company_ids": [(4, company_id)],
"role_line_ids": [
(
0,
0,
{
"user_id": self.id,
"active": True,
"role_id": role.id,
"company_id": company_id,
},
)
],
}
)
# create ce user on this company
self.make_ce_user(company_id, role_name)
# apply manager role the child companies
company = self.env["res.company"].browse(company_id)
child_companies = company.get_child_companies()
for child_company in child_companies:
......@@ -328,7 +301,6 @@ class ResUsers(models.Model):
"email": email,
}
user = cls.sudo().with_context(no_reset_password=True).create(vals)
user.make_internal_user()
user.create_users_on_keycloak()
user.send_reset_password_mail()
......
......@@ -16,6 +16,23 @@ class Client:
def __init__(self, baseurl):
self.baseurl = baseurl
def get(self, route, token=None):
"""Send a GET HTTP requests
Args:
route (str): String with the route to the endpoint
Return:
**response**: Return the response object
"""
headers = {"Authorization": token, "Content-Type": "application/json"}
return self._send_request(
verb="GET",
url=self._format_url(route),
payload={},
extra_headers=headers,
)
def post(self, route, token=None, body=None):
"""Send a POST HTTP requests
......@@ -26,10 +43,7 @@ class Client:
Return:
**response**: Return the response object
"""
headers = {
"Authorization": token,
"Content-Type": "application/json"
}
headers = {"Authorization": token, "Content-Type": "application/json"}
return self._send_request(
verb="POST",
url=self._format_url(route),
......@@ -47,10 +61,7 @@ class Client:
Return:
**response**: Return the response object
"""
headers = {
"Authorization": token,
"Content-Type": "application/json"
}
headers = {"Authorization": token, "Content-Type": "application/json"}
return self._send_request(
verb="PUT", url=self._format_url(route), payload=body, extra_headers=headers
)
......@@ -84,8 +95,7 @@ class Client:
if headers.get("Content-Type") == "application/json":
payload = json.dumps(payload)
logger.info("{verb} {url} \n {body}".format(
verb=verb, url=url, body=payload))
logger.info("{verb} {url}".format(verb=verb, url=url))
try:
response = requests.request(
......
......@@ -10,6 +10,15 @@ class LandingPage:
self.token = token
self.id = id
def get(self):
"""
Get Landing Page data.
"""
response_data = Client(self.baseurl).get(
"{url_path}/{id}".format(url_path=self._url_path, id=self.id), self.token
)
return response_data
def create(self, body):
"""
Creates a Landing Page instance.
......@@ -28,5 +37,4 @@ class LandingPage:
self.token,
body,
)
return response_data
......@@ -4,6 +4,13 @@ landing_page_platform_manager,access_landing_page_platform_manager,model_landing
landing_page_public,access_landing_page_public,model_landing_page,base.group_public,1,0,0,0
assign_crm_to_coordinator_company_wizard_admin,assign_crm_to_coordinator_company_wizard_admin,model_assign_crm_to_coordinator_company_wizard,group_platform_manager,1,1,1,1
assign_admin_wizard,assign_admin_wizard_admin,model_assign_admin_wizard,group_admin,1,1,1,1
multicompany_easy_creation,multicompany_easy_creation_admin,model_account_multicompany_easy_creation_wiz,group_admin,1,1,1,1
user_role_read,user_role_read_admin,model_res_users_role,group_admin,1,0,0,0
user_role_line_read,user_role_line_read_admin,base_user_role.model_res_users_role_line,group_admin,1,0,0,0
ir_config_parameter_read,ir_config_parameter_read_admin,base.model_ir_config_parameter,group_admin,1,0,0,0
ir_actions_act_window_read,ir_actions_act_window_read_admin,base.model_ir_actions_act_window,group_admin,1,0,0,0
ir_actions_act_window_view_read,ir_actions_act_window_view_read_admin,base.model_ir_actions_act_window_view,group_admin,1,0,0,0
res_company_modify,res_company_modify_admin,model_res_company,group_admin,1,1,1,0
res_users_admin,access_res_users_admin,model_res_users,energy_communities.group_admin,1,1,1,0
res_users_role_admin,access_res_users_role_admin,model_res_users_role,energy_communities.group_admin,1,1,1,0
res_users_role_line_admin,access_res_users_role_line_admin,model_res_users_role_line,energy_communities.group_admin,1,1,1,0
......
......@@ -172,7 +172,8 @@
(4, ref('account_payment_order.group_account_payment')),
(4, ref('crm.group_use_lead')),
(4, ref('mass_mailing.group_mass_mailing_user')),
(4, ref('l10n_es_aeat.group_account_aeat'))
(4, ref('l10n_es_aeat.group_account_aeat')),
(4, ref('queue_job.group_queue_job_manager')),
]"
/>
</record>
......
......@@ -216,7 +216,6 @@ S_LANDING_PAGE_CREATE = {
"type": "list",
"schema": {"type": "dict", "schema": S_COMMUNITY_SERVICE},
},
"group_image_link": {"type": "string"},
"primary_image_file": {"type": "string"},
"primary_image_file_write_date": {"type": "string"},
"secondary_image_file": {"type": "string"},
......@@ -225,7 +224,6 @@ S_LANDING_PAGE_CREATE = {
"long_description": {"type": "string"},
"why_become_cooperator": {"type": "string"},
"become_cooperator_process": {"type": "string"},
"map_geolocation": {"type": "string"},
"map_reference": {"type": "string"},
"street": {"type": "string"},
"postal_code": {"type": "string"},
......
from . import test_res_company
from . import test_res_users
from . import test_assign_admin_wizard
from . import test_crm_lead
from . import test_multicompany_easy_creation