Skip to content
Snippets Groups Projects
Commit de27ed0b authored by Benjami's avatar Benjami
Browse files

Something new :panda_face:

parent 59ebb9d7
No related branches found
No related tags found
2 merge requests!253[REL] Release 06/11/23,!191V1 imrpvements to CompanyEasyCreation wizard (CRM Lead execution)🙋‍
Pipeline #45532 passed with warnings
......@@ -234,7 +234,9 @@ 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_default_community_wizard())
company = self.env["res.company"].create(
lead._get_default_community_wizard()
)
# Update Lead & Map Place (if exist) fields accordingly
lead.community_company_id = company.id
......@@ -251,49 +253,70 @@ class CrmLead(models.Model):
lead.community_company_id._create_keycloak_realm()
lead.community_company_id._community_post_keycloak_creation_tasks()
def _get_default_community_wizard(self):
self.ensure_one()
metadata = {m.key: m.value for m in self.metadata_line_ids}
foundation_date = None
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']
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(metadata['ce_creation_date'], date_format)
foundation_date = datetime.strptime(
metadata["ce_creation_date"], date_format
)
except:
pass
if not foundation_date:
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(metadata['partner_foundation_date']))
_(
"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(metadata["partner_foundation_date"])
)
lang_id = None
if metadata.get('current_lang',False) and metadata['current_lang'] or None:
lang_id = self.env['res.lang'].search([('code','=',metadata['current_lang'])],limit=1)
if metadata.get("current_lang", False) and metadata["current_lang"] or None:
lang_id = self.env["res.lang"].search(
[("code", "=", metadata["current_lang"])], limit=1
)
users = [user.id for user in self.company_id.get_users()]
return {
'name': self.name,
'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,
'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,
'email': metadata.get('email_from',False) and metadata['email_from'] or None,
'vat': metadata.get('ce_vat',False) and metadata['ce_vat'] or None,
'foundation_date': foundation_date,
'default_lang_id': lang_id and lang_id.id or None,
'hierarchy_level': 'community' if self.source_id == self.env.ref("energy_communities.ce_source_creation_ce_proposal") else None,
'chart_template_id': self.env["account.chart.template"].search([("name", "=", "PGCE PYMEs 2008")])[0].id,
'update_default_taxes': True,
'default_sale_tax_id': self.env["account.tax.template"].search([("name", "=", "IVA 21% (Servicios)")])[0].id,
'default_purchase_tax_id': self.env["account.tax.template"].search([("name", "=", "21% IVA soportado (bienes corrientes)")])[0].id,
'property_cooperator_account': self.env.ref("l10n_es.account_common_4400").id,
'create_user': False,
"name": self.name,
"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,
"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,
"email": metadata.get("email_from", False)
and metadata["email_from"]
or None,
"vat": metadata.get("ce_vat", False) and metadata["ce_vat"] or None,
"foundation_date": foundation_date,
"default_lang_id": lang_id and lang_id.id or None,
"hierarchy_level": "community"
if self.source_id
== self.env.ref("energy_communities.ce_source_creation_ce_proposal")
else None,
"chart_template_id": self.env["account.chart.template"]
.search([("name", "=", "PGCE PYMEs 2008")])[0]
.id,
"update_default_taxes": True,
"default_sale_tax_id": self.env["account.tax.template"]
.search([("name", "=", "IVA 21% (Servicios)")])[0]
.id,
"default_purchase_tax_id": self.env["account.tax.template"]
.search([("name", "=", "21% IVA soportado (bienes corrientes)")])[0]
.id,
# 'property_cooperator_account': self.env.ref("l10n_es.account_common_4400").id,
"create_user": False,
}
def _create_keycloak_realm(self):
......@@ -324,17 +347,17 @@ class CrmLead(models.Model):
def action_create_community(self):
default_company_vals = {
'default_{}'.format(field): value
"default_{}".format(field): value
for field, value in self._get_default_community_wizard().items()
}
return {
'type': 'ir.actions.act_window',
'name': 'Create community',
'res_model': 'account.multicompany.easy.creation.wiz',
'view_mode': 'form',
'target': 'new',
'context': default_company_vals,
"type": "ir.actions.act_window",
"name": "Create community",
"res_model": "account.multicompany.easy.creation.wiz",
"view_mode": "form",
"target": "new",
"context": default_company_vals,
}
......
......@@ -196,6 +196,7 @@ class ResCompany(models.Model):
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"]
......
......@@ -61,12 +61,16 @@ class ResUsers(models.Model):
# already sync'ed somewhere else
continue
keycloak_user = self._get_or_create_kc_user(token, provider_id, user)
keycloak_key = self._LOGIN_MATCH_KEY.split(':')[0]
keycloak_login_provider = self.env.ref('energy_communities.keycloak_login_provider')
user.update({
'oauth_uid': keycloak_user[keycloak_key],
'oauth_provider_id': keycloak_login_provider.id,
})
keycloak_key = self._LOGIN_MATCH_KEY.split(":")[0]
keycloak_login_provider = self.env.ref(
"energy_communities.keycloak_login_provider"
)
user.update(
{
"oauth_uid": keycloak_user[keycloak_key],
"oauth_provider_id": keycloak_login_provider.id,
}
)
# action = self.env.ref('base.action_res_users').read()[0]
# action['domain'] = [('id', 'in', self.user_ids.ids)]
logger.debug("Create keycloak users STOP")
......@@ -122,9 +126,10 @@ class ResUsers(models.Model):
:param token: valid auth token from Keycloak
:param odoo_user: res.users record
"""
odoo_key = self._LOGIN_MATCH_KEY.split(':')[1]
odoo_key = self._LOGIN_MATCH_KEY.split(":")[1]
keycloak_user = self._get_kc_users(
token, provider_id, search=odoo_user.mapped(odoo_key)[0])
token, provider_id, search=odoo_user.mapped(odoo_key)[0]
)
if keycloak_user:
if len(keycloak_user) > 1:
# TODO: warn user?
......@@ -138,10 +143,10 @@ class ResUsers(models.Model):
def _create_user_values(self, odoo_user):
"""Prepare Keycloak values for given Odoo user."""
values = {
'username': odoo_user.login,
'email': odoo_user.partner_id.email,
'attributes': {'lang': [odoo_user.lang]},
'enabled': True,
"username": odoo_user.login,
"email": odoo_user.partner_id.email,
"attributes": {"lang": [odoo_user.lang]},
"enabled": True,
}
if "firstname" in odoo_user.partner_id:
......@@ -186,90 +191,119 @@ class ResUsers(models.Model):
self._validate_response(resp, no_json=True)
# yes, Keycloak sends back NOTHING on create
# so we are forced to do anothe call to get its data :(
return self._get_kc_users(token, provider_id, search=data['username'])[0]
return self._get_kc_users(token, provider_id, search=data["username"])[0]
def get_role_codes(self):
# TODO Map all code to company and enable (We should update the API schema too)
return self.role_line_ids[0].role_id.code
def send_reset_password_mail(self):
provider_id = self.env.ref('energy_communities.keycloak_admin_provider')
provider_id = self.env.ref("energy_communities.keycloak_admin_provider")
provider_id.validate_admin_provider()
headers = {
'Authorization': 'Bearer %s' % self._get_admin_token(provider_id)
}
headers['Content-Type'] = "application/json"
headers = {"Authorization": "Bearer %s" % self._get_admin_token(provider_id)}
headers["Content-Type"] = "application/json"
endpoint = provider_id.reset_password_endpoint.format(
kc_uid = self.oauth_uid
endpoint = provider_id.reset_password_endpoint.format(kc_uid=self.oauth_uid)
response = requests.put(
endpoint, headers=headers, data='["UPDATE_PASSWORD", "VERIFY_EMAIL"]'
)
response = requests.put(endpoint, headers=headers, data='["UPDATE_PASSWORD", "VERIFY_EMAIL"]')
if response.status_code != 204:
raise exceptions.UserError(
_('Something went wrong. Mail can not be sended. More details: {}').format(response.json())
_(
"Something went wrong. Mail can not be sended. More details: {}"
).format(response.json())
)
def make_internal_user(self):
already_user = self.env["res.users.role.line"].search([
("user_id.id", "=", self.id),
("active", "=", True),
("role_id.code", "=", "role_internal_user")
])
already_user = self.env["res.users.role.line"].search(
[
("user_id.id", "=", self.id),
("active", "=", True),
("role_id.code", "=", "role_internal_user"),
]
)
if not already_user:
role = self.env["res.users.role"].search([(
"code", "=", "role_internal_user"
)])
self.write({'role_line_ids': [(0, 0, {
'user_id': self.id,
'active': True,
'role_id': role.id,
})]})
role = self.env["res.users.role"].search(
[("code", "=", "role_internal_user")]
)
self.write(
{
"role_line_ids": [
(
0,
0,
{
"user_id": self.id,
"active": True,
"role_id": role.id,
},
)
]
}
)
# TODO: Strategy refactor i feature/assign_ce_admin branch
def make_ce_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.id)
])
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), # .id??
]
)
if current_role:
current_role.write({"role_id": role})
current_role.write({"role_id": role})
else:
self.write({
"company_ids": [(4, company_id.id)],
"role_line_ids": [(0, 0, {
'user_id': self.id,
'active': True,
'role_id': role.id,
'company_id': company_id.id,
})]
})
self.write(
{
"company_ids": [(4, company_id)], # .id??
"role_line_ids": [
(
0,
0,
{
"user_id": self.id,
"active": True,
"role_id": role.id,
"company_id": company_id, # .id??
},
)
],
}
)
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)
])
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})
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,
})]
})
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,
},
)
],
}
)
company = self.env["res.company"].browse(company_id)
child_companies = company.get_child_companies()
......@@ -277,14 +311,12 @@ class ResUsers(models.Model):
self.make_ce_user(child_company.id, "role_ce_manager")
def add_energy_community_role(self, company_id, role_name):
if role_name == 'role_ce_member' or role_name == 'role_ce_admin':
if role_name == "role_ce_member" or role_name == "role_ce_admin":
self.make_ce_user(company_id, role_name)
elif role_name == 'role_coord_worker' or role_name == 'role_coord_admin':
elif role_name == "role_coord_worker" or role_name == "role_coord_admin":
self.make_coord_user(company_id, role_name)
else:
raise exceptions.UserError(
_('Role not found')
)
raise exceptions.UserError(_("Role not found"))
def create_energy_community_base_user(
cls, vat, first_name, last_name, lang_code, email
......
......@@ -4,3 +4,4 @@ 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
......@@ -22,21 +22,15 @@
<xpath expr="//sheet" position="before">
<header>
<button
name="action_assign_crm_to_coordinator_company"
type="object"
string="Assing CRM to coordinator company"
groups="energy_communities.group_platform_manager"
/>
<field name="source_id" invisible="1"/>
<field name="finished" invisible="1"/>
<field name="company_hierarchy_level" invisible="1"/>
<button
name="action_create_community"
type="object"
string="Create community"
groups="energy_communities.group_admin"
attrs="{'invisible': ['|', '|', ('source_id', '!=', %(ce_source_creation_ce_proposal)d), ('finished', '=', False), ('company_hierarchy_level', '!=', 'coordinator')]}"
/>
name="action_assign_crm_to_coordinator_company"
type="object"
string="Assing CRM to coordinator company"
groups="energy_communities.group_platform_manager"
/>
<field name="source_id" invisible="1" />
<field name="finished" invisible="1" />
<field name="company_hierarchy_level" invisible="1" />
<button name="action_create_community" type="object" string="Create community" />
</header>
</xpath>
</field>
......
......@@ -23,7 +23,7 @@ class AccountMulticompanyEasyCreationWiz(models.TransientModel):
)
crm_lead_id = fields.Many2one("crm.lead", string="CRM Lead")
property_cooperator_account = fields.Many2one(
comodel_name="account.account.template",
comodel_name="account.account",
string="Cooperator Account",
help="This account will be"
" the default one as the"
......@@ -66,9 +66,7 @@ class AccountMulticompanyEasyCreationWiz(models.TransientModel):
string="ZIP code",
)
foundation_date = fields.Date(
string="Foundation date"
)
foundation_date = fields.Date(string="Foundation date")
vat = fields.Char(
string="ZIP code",
......@@ -82,14 +80,28 @@ class AccountMulticompanyEasyCreationWiz(models.TransientModel):
string="Phone",
)
website = fields.Char(
string="Website",
)
state_id = fields.Many2one(
comodel_name="res.country.state",
string="State",
)
def add_company_managers(self):
coord_members = self.parent_id.get_users(["role_coord_admin", "role_coord_worker"])
coord_members = self.parent_id.get_users(
["role_coord_admin", "role_coord_worker"]
)
for manager in coord_members:
manager.make_ce_user(self.new_company_id, "role_ce_manager")
def add_company_log(self):
message = _("Community created from: <a href='/web#id={id}&view_type=form&model=crm.lead&menu_id={menu_id}'>{name}</a>")
self.new_company_id.message_post(
message = _(
"Community created from: <a href='/web#id={id}&view_type=form&model=crm.lead&menu_id={menu_id}'>{name}</a>"
)
self_new_company = self.with_company(self.new_company_id)
self_new_company.new_company_id.message_post(
body=message.format(
id=self.crm_lead_id.id,
menu_id=self.env.ref("crm.crm_menu_root").id,
......@@ -159,7 +171,8 @@ class AccountMulticompanyEasyCreationWiz(models.TransientModel):
self.new_company_id.write(vals)
def set_cooperative_account(self):
new_company = self.new_company_id
self_new_company = self.with_company(new_company_id)
new_company = self_new_company.new_company_id
new_company.write(
{
"property_cooperator_account": self.match_account(
......@@ -185,23 +198,28 @@ class AccountMulticompanyEasyCreationWiz(models.TransientModel):
def action_accept(self):
action = super().action_accept()
self.update_values_from_crm_lead()
# self.update_values_from_crm_lead()
if self.property_cooperator_account:
self.set_cooperative_account()
self.new_company_id.create_user = self.create_user
self_new_company = self.with_company(self.new_company_id)
self_new_company.new_company_id.create_user = self.create_user
self.update_product_category_company_share()
self.create_capital_share_product_template()
# self.create_capital_share_product_template()
self.add_company_managers()
self.add_company_log()
return action
def create_company(self):
self.new_company_id = self.env["res.company"].create(
{
"name": self.name,
"user_ids": [(6, 0, self.user_ids.ids)],
"parent_id": self.parent_id.id,
}
self.new_company_id = (
self.env["res.company"]
.sudo()
.create(
{
"name": self.name,
"user_ids": [(6, 0, self.user_ids.ids)],
"parent_id": self.parent_id.id,
}
)
)
allowed_company_ids = (
self.env.context.get("allowed_company_ids", []) + self.new_company_id.ids
......
......@@ -25,15 +25,17 @@
<xpath expr="//page" position="before">
<page string="Energy Community">
<group string="Energy Community">
<field name="parent_id"></field>
<field name="default_lang_id"></field>
<field name="street"></field>
<field name="city"></field>
<field name="zip_code"></field>
<field name="foundation_date"></field>
<field name="vat"></field>
<field name="email"></field>
<field name="phone"></field>
<field name="parent_id" required="1" />
<field name="vat" required="1" />
<field name="state_id" required="1" />
<field name="city" required="1" />
<field name="street" required="1" />
<field name="zip_code" required="1" />
<field name="foundation_date" required="1" />
<field name="email" required="1" />
<field name="phone" required="1" />
<field name="default_lang_id" required="1" />
<field name="website" />
</group>
</page>
</xpath>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment