size
int64 0
304k
| ext
stringclasses 1
value | lang
stringclasses 1
value | branch
stringclasses 1
value | content
stringlengths 0
304k
| avg_line_length
float64 0
238
| max_line_length
int64 0
304k
|
---|---|---|---|---|---|---|
602 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Quiz and Meet on community',
'category': 'Marketing/Events',
'sequence': 1007,
'version': '1.0',
'summary': 'Quiz and Meet on community route',
'website': 'https://www.odoo.com/app/events',
'description': "",
'depends': [
'website_event_meet',
'website_event_track_quiz',
],
'data': [
'views/event_meet_templates.xml',
],
'demo': [
],
'application': False,
'auto_install': True,
'license': 'LGPL-3',
}
| 24.08 | 602 |
849 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.exceptions import Forbidden
from odoo import http
from odoo.addons.website_event.controllers.community import EventCommunityController
from odoo.http import request
class WebsiteEventTrackQuizMeetController(EventCommunityController):
@http.route(['/event/<model("event.event"):event>/community'], type='http', auth="public", website=True, sitemap=False)
def community(self, event, page=1, lang=None, **kwargs):
# website_event_track_quiz
values = self._get_community_leaderboard_render_values(event, kwargs.get('search'), page)
# website_event_meet
values.update(self._event_meeting_rooms_get_values(event, lang=lang))
return request.render('website_event_meet.event_meet', values)
| 42.45 | 849 |
1,477 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "Point of Sale Coupons",
"version": "1.0",
"category": "Sales/Point Of Sale",
"sequence": 6,
"summary": "Use coupons in Point of Sale",
"description": "",
"depends": ["coupon", "point_of_sale"],
"data": [
"data/mail_template_data.xml",
'data/default_barcode_patterns.xml',
"security/ir.model.access.csv",
"views/coupon_views.xml",
"views/coupon_program_views.xml",
"views/pos_config_views.xml",
"views/res_config_settings_views.xml",
],
"demo": [
"demo/pos_coupon_demo.xml",
],
"installable": True,
'assets': {
'point_of_sale.assets': [
'pos_coupon/static/src/css/coupon.css',
'pos_coupon/static/src/js/coupon.js',
'pos_coupon/static/src/js/Orderline.js',
'pos_coupon/static/src/js/PaymentScreen.js',
'pos_coupon/static/src/js/ProductScreen.js',
'pos_coupon/static/src/js/ActivePrograms.js',
'pos_coupon/static/src/js/ControlButtons/PromoCodeButton.js',
'pos_coupon/static/src/js/ControlButtons/ResetProgramsButton.js',
],
'web.assets_tests': [
'pos_coupon/static/src/js/tours/**/*',
],
'web.assets_qweb': [
'pos_coupon/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 33.568182 | 1,477 |
15,267 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon
from odoo.tests import Form, tagged
@tagged("post_install", "-at_install")
class TestUi(TestPointOfSaleHttpCommon):
def setUp(self):
super().setUp()
self.promo_programs = self.env["coupon.program"]
# code promo program -> discount on specific products
self.code_promo_program = self.env["coupon.program"].create(
{
"name": "Promo Code Program - Discount on Specific Products",
"program_type": "promotion_program",
"promo_code_usage": "code_needed",
"promo_code": "promocode",
"discount_apply_on": "specific_products",
"discount_percentage": 50,
"discount_specific_product_ids": (
self.whiteboard_pen | self.magnetic_board | self.desk_organizer
).ids,
}
)
self.promo_programs |= self.code_promo_program
# auto promo program on current order
# -> discount on cheapest product
self.auto_promo_program_current = self.env["coupon.program"].create(
{
"name": "Auto Promo Program - Cheapest Product",
"program_type": "promotion_program",
"promo_code_usage": "no_code_needed",
"discount_apply_on": "cheapest_product",
"discount_percentage": 90,
}
)
self.promo_programs |= self.auto_promo_program_current
# auto promo program on next order
# -> discount on order (global discount)
self.auto_promo_program_next = self.env["coupon.program"].create(
{
"name": "Auto Promo Program - Global Discount",
"program_type": "promotion_program",
"promo_code_usage": "no_code_needed",
"promo_applicability": "on_next_order",
"discount_apply_on": "on_order",
"discount_percentage": 10,
}
)
self.promo_programs |= self.auto_promo_program_next
self.code_promo_program_free_product = self.env["coupon.program"].create(
{
"name": "Promo Program - Buy 3 Whiteboard Pen, Get 1 Magnetic Board",
"program_type": "promotion_program",
"rule_products_domain": "[('name', '=', 'Whiteboard Pen')]",
"promo_code_usage": "code_needed",
"promo_code": "board",
"reward_type": "product",
"rule_min_quantity": 3,
"reward_product_id": self.magnetic_board.id,
"reward_product_quantity": 1,
}
)
self.promo_programs |= self.code_promo_program_free_product
# coupon program -> free product
self.coupon_program = self.env["coupon.program"].create(
{
"name": "Coupon Program - Buy 3 Take 2 Free Product",
"program_type": "coupon_program",
"rule_products_domain": "[('name', '=', 'Desk Organizer')]",
"reward_type": "product",
"rule_min_quantity": 3,
"reward_product_id": self.desk_organizer.id,
"reward_product_quantity": 2,
}
)
# Create coupons for the coupon program and change the code
# to be able to use them in the frontend tour.
self.env["coupon.generate.wizard"].with_context(
{"active_id": self.coupon_program.id}
).create({"nbr_coupons": 4}).generate_coupon()
(
self.coupon1,
self.coupon2,
self.coupon3,
self.coupon4,
) = self.coupon_program.coupon_ids
self.coupon1.write({"code": "1234"})
self.coupon2.write({"code": "5678"})
self.coupon3.write({"code": "1357"})
self.coupon4.write({"code": "2468"})
def test_pos_coupon_tour_basic(self):
"""PoS Coupon Basic Tour"""
# Set the programs to the pos config.
# Remove fiscal position and pricelist.
with Form(self.main_pos_config) as pos_config:
pos_config.tax_regime_selection = False
pos_config.use_pricelist = False
pos_config.pricelist_id = self.env["product.pricelist"].create(
{"name": "PoS Default Pricelist",}
)
pos_config.use_coupon_programs = True
pos_config.coupon_program_ids.add(self.coupon_program)
for promo_program in self.promo_programs:
pos_config.promo_program_ids.add(promo_program)
self.main_pos_config.open_session_cb(check_coa=False)
##
# Tour Part 1
# This part will generate coupons for `auto_promo_program_next`
# that will be used in the second part of the tour.
#
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosCouponTour1",
login="accountman",
)
# check coupon usage
self.assertEqual(
self.coupon1.state, "used", msg="`1234` coupon should have been used."
)
self.assertEqual(
self.coupon2.state,
"new",
msg="`5678` coupon code is used but was eventually freed.",
)
# check pos_order_count in each program
self.assertEqual(self.auto_promo_program_current.pos_order_count, 4)
self.assertEqual(self.auto_promo_program_next.pos_order_count, 0)
self.assertEqual(self.code_promo_program.pos_order_count, 1)
self.assertEqual(self.code_promo_program_free_product.pos_order_count, 1)
self.assertEqual(self.coupon_program.pos_order_count, 1)
# check number of generated coupons
self.assertEqual(len(self.auto_promo_program_next.coupon_ids), 6)
# check number of orders in the session
pos_session = self.main_pos_config.current_session_id
self.assertEqual(
len(pos_session.order_ids), 6, msg="6 orders were made in tour part1."
)
##
# Tour Part 2
# The coupons generated in the first part will be used in this tour.
#
# Manually set the code for some `auto_promo_program_next` coupons
# to be able to use them in defining the part2 tour.
(
promo_coupon1,
promo_coupon2,
promo_coupon3,
promo_coupon4,
*_,
) = self.auto_promo_program_next.coupon_ids
promo_coupon1.write({"code": "123456"})
promo_coupon2.write({"code": "345678"})
promo_coupon3.write({"code": "567890"})
promo_coupon4.write({"code": "098765"})
# use here the generated coupon
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosCouponTour2",
login="accountman",
)
self.assertEqual(self.coupon4.state, "new")
self.assertEqual(promo_coupon4.state, "new")
# check pos_order_count in each program
self.assertEqual(self.auto_promo_program_current.pos_order_count, 6)
self.assertEqual(self.auto_promo_program_next.pos_order_count, 2)
self.assertEqual(self.code_promo_program.pos_order_count, 2)
self.assertEqual(self.coupon_program.pos_order_count, 3)
def test_pos_coupon_tour_max_amount(self):
"""PoS Coupon Basic Tour"""
self.promo_product = self.env["product.product"].create(
{
"name": "Promo Product",
"type": "service",
"list_price": 30,
"available_in_pos": True,
}
)
tax01 = self.env["account.tax"].create({
"name": "C01 Tax",
"amount": "0.00",
})
tax02 = self.env["account.tax"].create({
"name": "C02 Tax",
"amount": "0.00",
})
self.productA = self.env["product.product"].create(
{
"name": "Product A",
"type": "product",
"list_price": 15,
"available_in_pos": True,
"taxes_id": [(6, 0, [tax01.id])],
}
)
#create another product with different taxes_id
self.productB = self.env["product.product"].create(
{
"name": "Product B",
"type": "product",
"list_price": 25,
"available_in_pos": True,
"taxes_id": [(6, 0, [tax02.id])]
}
)
# create a promo program
self.promo_program_max_amount = self.env["coupon.program"].create(
{
"name": "Promo Program - Max Amount",
"program_type": "promotion_program",
"rule_products_domain": '[["product_variant_ids","=","Promo Product"]]',
"discount_max_amount": 40,
"reward_type": "discount",
"promo_code_usage": "no_code_needed",
"discount_type": "percentage",
"discount_percentage": 100,
"discount_apply_on": "specific_products",
"discount_specific_product_ids": (
self.productA | self.productB
).ids,
}
)
with Form(self.main_pos_config) as pos_config:
pos_config.tax_regime_selection = False
pos_config.use_pricelist = False
pos_config.pricelist_id = self.env["product.pricelist"].create(
{"name": "PoS Default Pricelist",}
)
pos_config.use_coupon_programs = True
pos_config.coupon_program_ids.add(self.coupon_program)
pos_config.coupon_program_ids.add(self.promo_program_max_amount)
self.main_pos_config.open_session_cb(check_coa=False)
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosCouponTour3",
login="accountman",
)
def test_coupon_change_pricelist(self):
"""Test coupon program with different pricelists."""
product_1 = self.env["product.product"].create(
{
"name": "Test Product 1",
"type": "product",
"list_price": 25,
"available_in_pos": True,
}
)
tax01 = self.env["account.tax"].create({
"name": "C01 Tax",
"amount": "0.00",
})
product_2 = self.env["product.product"].create(
{
"name": "Test Product 2",
"type": "product",
"list_price": 25,
"available_in_pos": True,
"taxes_id": [(6, 0, [tax01.id])],
}
)
pricelist = self.env["product.pricelist"].create({
"name": "Test multi-currency",
"discount_policy": "without_discount",
"currency_id": self.env.ref("base.USD").id,
"item_ids": [
(0, 0, {
"base": "standard_price",
"product_id": product_1.id,
"compute_price": "percentage",
"percent_price": 50,
}),
(0, 0, {
"base": "standard_price",
"product_id": product_2.id,
"compute_price": "percentage",
"percent_price": 50,
})
]
})
self.free_coupon_program = self.env["coupon.program"].create(
{
"name": "Free Order",
"program_type": "coupon_program",
"reward_type": "discount",
"discount_type": "percentage",
"discount_percentage": 100,
"discount_apply_on": "on_order",
}
)
# Create coupons for the coupon program and change the code
# to be able to use them in the frontend tour.
self.env["coupon.generate.wizard"].with_context(
{"active_id": self.free_coupon_program.id}
).create({"nbr_coupons": 2}).generate_coupon()
(
coupon1, coupon2,
) = self.free_coupon_program.coupon_ids
coupon1.write({"code": "abcda"})
coupon2.write({"code": "abcdb"})
with Form(self.main_pos_config) as pos_config:
pos_config.use_pricelist = True
pos_config.available_pricelist_ids.add(pricelist)
pos_config.use_coupon_programs = True
pos_config.coupon_program_ids.add(self.free_coupon_program)
self.main_pos_config.open_session_cb(check_coa=False)
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosCouponTour4",
login="accountman",
)
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosCouponTour4.1",
login="accountman",
)
def test_promotion_program_with_global_discount(self):
"""
- Create a promotion with a discount of 10%
- Create a product with no taxes
- Enable the global discount feature, and make sure the Discount product
has a tax set on it.
"""
if not self.env["ir.module.module"].search([("name", "=", "pos_discount"), ("state", "=", "installed")]):
self.skipTest("pos_discount module is required for this test")
self.promo_program = self.env["coupon.program"].create(
{
"name": "Promo Program",
"program_type": "promotion_program",
"reward_type": "discount",
"discount_type": "percentage",
"discount_percentage": 10,
"discount_apply_on": "on_order",
"promo_code_usage": "no_code_needed",
}
)
self.product = self.env["product.product"].create(
{
"name": "Test Product 1",
"type": "product",
"list_price": 100,
"available_in_pos": True,
}
)
self.discount_product = self.env["product.product"].create(
{
"name": "Discount Product",
"type": "service",
"list_price": 0,
"available_in_pos": True,
"taxes_id": [(6, 0, self.env.ref("l10n_generic_coa.1_sale_tax_template").ids)],
}
)
with Form(self.main_pos_config) as pos_config:
pos_config.use_coupon_programs = True
pos_config.promo_program_ids.add(self.promo_program)
pos_config.module_pos_discount = True
pos_config.discount_product_id = self.discount_product
self.main_pos_config.open_session_cb(check_coa=False)
self.start_tour(
"/pos/web?config_id=%d" % self.main_pos_config.id,
"PosCouponTour5",
login="accountman",
)
| 37.511057 | 15,267 |
1,430 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# NOTE Use black to automatically format this code.
from odoo import api, fields, models, _
class Coupon(models.Model):
_inherit = "coupon.coupon"
source_pos_order_id = fields.Many2one(
"pos.order",
string="PoS Order Reference",
help="PoS order where this coupon is generated.",
)
pos_order_id = fields.Many2one(
"pos.order",
string="Applied on PoS Order",
help="PoS order where this coupon is consumed/booked.",
)
def _check_coupon_code(self, order_date, partner_id, **kwargs):
if self.program_id.id in kwargs.get("reserved_program_ids", []):
return {
"error": _("A coupon from the same program has already been reserved for this order.")
}
return super()._check_coupon_code(order_date, partner_id, **kwargs)
def _get_default_template(self):
if self.source_pos_order_id:
return self.env.ref('pos_coupon.mail_coupon_template', False)
return super()._get_default_template()
@api.model
def _generate_code(self):
"""
Modify the generated barcode to be compatible with the default
barcode rule in this module. See `data/default_barcode_patterns.xml`.
"""
code = super()._generate_code()
return '043' + code[3:]
| 34.047619 | 1,430 |
3,779 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# NOTE Use black to automatically format this code.
from datetime import datetime
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class PosConfig(models.Model):
_inherit = "pos.config"
use_coupon_programs = fields.Boolean(
"Coupons & Promotions",
help="Use coupon and promotion programs in this PoS configuration.",
)
coupon_program_ids = fields.Many2many(
"coupon.program",
string="Coupon Programs",
compute="_filter_programs",
inverse="_set_programs",
)
promo_program_ids = fields.Many2many(
"coupon.program",
string="Promotion Programs",
compute="_filter_programs",
inverse="_set_programs",
)
program_ids = fields.Many2many("coupon.program", string="Coupons and Promotions")
@api.depends("program_ids")
def _filter_programs(self):
for config in self:
config.coupon_program_ids = config.program_ids.filtered(
lambda program: program.program_type == "coupon_program"
)
config.promo_program_ids = config.program_ids.filtered(
lambda program: program.program_type == "promotion_program"
)
def _set_programs(self):
for config in self:
config.program_ids = config.coupon_program_ids | config.promo_program_ids
def open_session_cb(self, check_coa=True):
# Check validity of programs before opening a new session
invalid_reward_products_msg = ""
for program in self.program_ids:
if (
program.reward_product_id
and not program.reward_product_id.available_in_pos
):
reward_product = program.reward_product_id
invalid_reward_products_msg += "\n\t"
invalid_reward_products_msg += _(
"Program: %(name)s (%(type)s), Reward Product: `%(reward_product)s`",
name=program.name,
type=program.program_type,
reward_product=reward_product.name,
)
if invalid_reward_products_msg:
intro = _(
"To continue, make the following reward products to be available in Point of Sale."
)
raise UserError(f"{intro}\n{invalid_reward_products_msg}")
return super(PosConfig, self).open_session_cb()
def use_coupon_code(self, code, creation_date, partner_id, reserved_program_ids):
coupon_to_check = self.env["coupon.coupon"].search(
[("code", "=", code), ("program_id", "in", self.program_ids.ids)]
)
# If not unique, we only check the first coupon.
coupon_to_check = coupon_to_check[:1]
if not coupon_to_check:
return {
"successful": False,
"payload": {
"error_message": _("This coupon is invalid (%s).") % (code)
},
}
message = coupon_to_check._check_coupon_code(
fields.Date.from_string(creation_date[:11]),
partner_id,
reserved_program_ids=reserved_program_ids,
)
error_message = message.get("error", False)
if error_message:
return {
"successful": False,
"payload": {"error_message": error_message},
}
coupon_to_check.sudo().write({"state": "used"})
return {
"successful": True,
"payload": {
"program_id": coupon_to_check.program_id.id,
"coupon_id": coupon_to_check.id,
},
}
| 36.336538 | 3,779 |
3,120 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# NOTE Use black to automatically format this code.
from odoo import api, fields, models, _
import ast
class CouponProgram(models.Model):
_inherit = "coupon.program"
pos_config_ids = fields.Many2many(
"pos.config",
string="Point of Sales",
readonly=True,
)
pos_order_line_ids = fields.One2many(
"pos.order.line",
"program_id",
string="PoS Order Lines",
help="Order lines where this program is applied.",
)
promo_barcode = fields.Char(
"Barcode",
default=lambda self: self.env["coupon.coupon"]._generate_code(),
help="A technical field used as an alternative to the promo_code. "
"This is automatically generated when promo_code is changed.",
)
pos_order_ids = fields.Many2many(
"pos.order", help="The PoS orders where this program is applied.", copy=False
)
pos_order_count = fields.Integer(
"PoS Order Count", compute="_compute_pos_order_count"
)
valid_product_ids = fields.Many2many(
"product.product",
"Valid Products",
compute="_compute_valid_product_ids",
help="These are the products that are valid in this program.",
)
valid_partner_ids = fields.Many2many(
"res.partner",
"Valid Partners",
compute="_compute_valid_partner_ids",
help="These are the partners that can avail this program.",
)
@api.depends("pos_order_ids")
def _compute_pos_order_count(self):
for program in self:
program.pos_order_count = len(program.pos_order_ids)
def write(self, vals):
if "promo_code" in vals:
vals.update({"promo_barcode": self.env["coupon.coupon"]._generate_code()})
return super(CouponProgram, self).write(vals)
def action_view_pos_orders(self):
self.ensure_one()
return {
"name": _("PoS Orders"),
"view_mode": "tree,form",
"res_model": "pos.order",
"type": "ir.actions.act_window",
"domain": [("id", "in", self.pos_order_ids.ids)],
"context": dict(self._context, create=False),
}
@api.depends("rule_products_domain")
def _compute_valid_product_ids(self):
for program in self:
domain = ast.literal_eval(program.rule_products_domain) if program.rule_products_domain else []
program.valid_product_ids = self.env["product.product"].search(domain).ids
@api.depends("rule_partners_domain")
def _compute_valid_partner_ids(self):
for program in self:
domain = ast.literal_eval(program.rule_partners_domain) if program.rule_partners_domain else []
program.valid_partner_ids = self.env["res.partner"].search(domain).ids
@api.depends('pos_order_ids')
def _compute_total_order_count(self):
super(CouponProgram, self)._compute_total_order_count()
for program in self:
program.total_order_count += len(program.pos_order_ids)
| 36.27907 | 3,120 |
365 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
from odoo.tools.translate import _
class BarcodeRule(models.Model):
_inherit = 'barcode.rule'
type = fields.Selection(selection_add=[
('coupon', 'Coupon'),
], ondelete={
'coupon': 'set default',
})
| 24.333333 | 365 |
3,273 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# NOTE Use black to automatically format this code.
from collections import defaultdict
from odoo import api, fields, models, _
class PosOrder(models.Model):
_inherit = "pos.order"
applied_program_ids = fields.Many2many(
"coupon.program",
string="Applied Programs",
help="Technical field. This is set when the order is validated. "
"We normally get this value thru the `program_id` of the reward lines.",
)
used_coupon_ids = fields.One2many(
"coupon.coupon", "pos_order_id", string="Consumed Coupons"
)
generated_coupon_ids = fields.One2many(
"coupon.coupon", "source_pos_order_id", string="Generated Coupons"
)
def validate_coupon_programs(
self, program_ids_to_generate_coupons, unused_coupon_ids
):
"""This is called after create_from_ui is called. We set here fields
that are used to link programs and coupons to the order.
We also return the generated coupons that can be used in the frontend
to print the generated codes in the receipt.
"""
self.ensure_one()
program_ids_to_generate_coupons = program_ids_to_generate_coupons or []
unused_coupon_ids = unused_coupon_ids or []
self.env["coupon.coupon"].browse(unused_coupon_ids).write({"state": "new"})
self.sudo().write(
{
"applied_program_ids": [(4, i) for i in self.lines.program_id.ids],
"used_coupon_ids": [(4, i) for i in self.lines.coupon_id.ids],
"generated_coupon_ids": [
(4, i)
for i in (
self.env["coupon.program"]
.browse(program_ids_to_generate_coupons)
.sudo()._generate_coupons(self.partner_id.id)
).ids
],
}
)
return [
{
"code": coupon.code,
"expiration_date": coupon.expiration_date,
"program_name": coupon.program_id.name,
}
for coupon in self.generated_coupon_ids
]
def _get_fields_for_order_line(self):
fields = super(PosOrder, self)._get_fields_for_order_line()
fields.extend({
'is_program_reward',
'coupon_id',
'program_id',
})
return fields
def _prepare_order_line(self, order_line):
order_line = super(PosOrder, self)._prepare_order_line(order_line)
if order_line['program_id']:
order_line['program_id'] = order_line['program_id'][0]
return order_line
class PosOrderLine(models.Model):
_inherit = "pos.order.line"
is_program_reward = fields.Boolean(
"Is reward line",
help="Flag indicating that this order line is a result of coupon/promo program.",
)
program_id = fields.Many2one(
"coupon.program",
string="Program",
help="Promotion/Coupon Program where this reward line is based.",
)
coupon_id = fields.Many2one(
"coupon.coupon", string="Coupon", help="Coupon that generated this reward.",
)
| 34.819149 | 3,273 |
702 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Barcode - GS1 Nomenclature',
'version': '1.0',
'category': 'Hidden',
'summary': 'Parse barcodes according to the GS1-128 specifications',
'depends': ['barcodes', 'uom'],
'data': [
'data/barcodes_gs1_rules.xml',
'views/barcodes_view.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'web.assets_backend': [
'barcodes_gs1_nomenclature/static/src/js/barcode_parser.js',
],
'web.qunit_suite_tests': [
'barcodes_gs1_nomenclature/static/src/js/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 29.25 | 702 |
5,746 |
py
|
PYTHON
|
15.0
|
from odoo.addons.barcodes.tests.test_barcode_nomenclature import TestBarcodeNomenclature
from odoo.exceptions import ValidationError
class TestBarcodeGS1Nomenclature(TestBarcodeNomenclature):
def test_gs1_date_to_date(self):
barcode_nomenclature = self.env['barcode.nomenclature']
# 20/10/2015 -> 151020
date_gs1 = "151020"
date = barcode_nomenclature.gs1_date_to_date(date_gs1)
self.assertEqual(date.day, 20)
self.assertEqual(date.month, 10)
self.assertEqual(date.year, 2015)
# XX/03/2052 -> 520300 -> (if day no set take last day of the month -> 31)
date_gs1 = "520300"
date = barcode_nomenclature.gs1_date_to_date(date_gs1)
self.assertEqual(date.day, 31)
self.assertEqual(date.month, 3)
self.assertEqual(date.year, 2052)
# XX/02/2020 -> 520200 -> (if day no set take last day of the month -> 29)
date_gs1 = "200200"
date = barcode_nomenclature.gs1_date_to_date(date_gs1)
self.assertEqual(date.day, 29)
self.assertEqual(date.month, 2)
self.assertEqual(date.year, 2020)
def test_gs1_extanded_barcode_1(self):
barcode_nomenclature = self.env['barcode.nomenclature'].browse(self.ref('barcodes_gs1_nomenclature.default_gs1_nomenclature'))
# (01)94019097685457(10)33650100138(3102)002004(15)131018
code128 = "01940190976854571033650100138\x1D310200200415131018"
res = barcode_nomenclature.gs1_decompose_extanded(code128)
self.assertEqual(len(res), 4)
self.assertEqual(res[0]["ai"], "01")
self.assertEqual(res[1]["ai"], "10")
self.assertEqual(res[2]["ai"], "3102")
self.assertEqual(res[2]["value"], 20.04)
self.assertEqual(res[3]["ai"], "15")
self.assertEqual(res[3]["value"].year, 2013)
self.assertEqual(res[3]["value"].day, 18)
self.assertEqual(res[3]["value"].month, 10)
# (01)94019097685457(13)170119(30)17
code128 = "0194019097685457131701193017"
res = barcode_nomenclature.gs1_decompose_extanded(code128)
self.assertEqual(len(res), 3)
self.assertEqual(res[0]["ai"], "01")
self.assertEqual(res[1]["ai"], "13")
self.assertEqual(res[1]["value"].year, 2017)
self.assertEqual(res[1]["value"].day, 19)
self.assertEqual(res[1]["value"].month, 1)
self.assertEqual(res[2]["ai"], "30")
self.assertEqual(res[2]["value"], 17)
def test_gs1_extanded_barcode_2_decimal(self):
""" Parses multiples barcode with (or without) a decimal value and
checks for each of them the value is correctly parsed.
"""
# Configures a barcode GS1 nomenclature...
barcode_nomenclature = self.env['barcode.nomenclature'].create({
'name': "GS1 Nomenclature - Test",
'is_gs1_nomenclature': True,
})
default_barcode_rule_vals = {
'default_encoding': 'gs1-128',
'default_barcode_nomenclature_id': barcode_nomenclature.id,
'default_type': 'quantity',
'default_gs1_content_type': 'measure',
}
# Creates a rule who don't take any decimal.
barcode_rule = self.env['barcode.rule'].with_context(default_barcode_rule_vals).create({
'name': "GS1 Rule Test - No Decimal",
'pattern': r'(300)(\d{5,8})',
'gs1_decimal_usage': False,
})
# Creates a rule to take the four last digit as decimals.
barcode_rule_decimal = self.env['barcode.rule'].with_context(default_barcode_rule_vals).create({
'name': "GS1 Rule Test - Four Decimals",
'pattern': r'(304)(\d{5,8})',
'gs1_decimal_usage': True,
})
# Checks barcodes without decimals.
res = barcode_nomenclature.gs1_decompose_extanded('30000000')
self.assertEqual(len(res), 1)
self.assertEqual(res[0]['string_value'], '00000')
self.assertEqual(res[0]['value'], 0)
res = barcode_nomenclature.gs1_decompose_extanded('30018789')
self.assertEqual(len(res), 1)
self.assertEqual(res[0]['string_value'], '18789')
self.assertEqual(res[0]['value'], 18789)
res = barcode_nomenclature.gs1_decompose_extanded('3001515000')
self.assertEqual(len(res), 1)
self.assertEqual(res[0]['string_value'], '1515000')
self.assertEqual(res[0]['value'], 1515000)
# Checks barcodes with decimals.
res = barcode_nomenclature.gs1_decompose_extanded('30400000')
self.assertEqual(len(res), 1)
self.assertEqual(res[0]['string_value'], '00000')
self.assertEqual(res[0]['value'], 0.0)
res = barcode_nomenclature.gs1_decompose_extanded('30418789')
self.assertEqual(len(res), 1)
self.assertEqual(res[0]['string_value'], '18789')
self.assertEqual(res[0]['value'], 1.8789)
res = barcode_nomenclature.gs1_decompose_extanded('3041515000')
self.assertEqual(len(res), 1)
self.assertEqual(res[0]['string_value'], '1515000')
self.assertEqual(res[0]['value'], 151.5)
# Checks wrong configs will raise an exception.
barcode_rule_decimal.pattern = r'()(\d{0,4})'
# Barcode rule uses decimals but AI doesn't precise what is the decimal position.
with self.assertRaises(ValidationError):
res = barcode_nomenclature.gs1_decompose_extanded('1234')
# The pattern is too permissive and can catch something which can't be casted as measurement
barcode_rule.pattern = r'(300)(.*)'
with self.assertRaises(ValidationError):
res = barcode_nomenclature.gs1_decompose_extanded('300bilou4000')
| 44.2 | 5,746 |
5,682 |
py
|
PYTHON
|
15.0
|
import re
import datetime
import calendar
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
FNC1_CHAR = '\x1D'
class BarcodeNomenclature(models.Model):
_inherit = 'barcode.nomenclature'
is_gs1_nomenclature = fields.Boolean(
string="Is GS1 Nomenclature",
help="This Nomenclature use the GS1 specification, only GS1-128 encoding rules is accepted is this kind of nomenclature.")
gs1_separator_fnc1 = fields.Char(
string="FNC1 Separator", trim=False,
help="Alternative regex delimiter for the FNC1 (by default, if not set, it is <GS> ASCII 29 char). The separator must not match the begin/end of any related rules pattern.")
@api.constrains('gs1_separator_fnc1')
def _check_pattern(self):
for nom in self:
if nom.is_gs1_nomenclature and nom.gs1_separator_fnc1:
try:
re.compile("(?:%s)?" % nom.gs1_separator_fnc1)
except re.error as error:
raise ValidationError(_("The FNC1 Separator Alternative is not a valid Regex: ") + str(error))
@api.model
def gs1_date_to_date(self, gs1_date):
""" Converts a GS1 date into a datetime.date.
:param gs1_date: A year formated as yymmdd
:type gs1_date: str
:return: converted date
:rtype: datetime.date
"""
# See 7.12 Determination of century in dates:
# https://www.gs1.org/sites/default/files/docs/barcodes/GS1_General_Specifications.pdf
now = datetime.date.today()
current_century = now.year // 100
substract_year = int(gs1_date[0:2]) - (now.year % 100)
century = (51 <= substract_year <= 99 and current_century - 1) or\
(-99 <= substract_year <= -50 and current_century + 1) or\
current_century
year = century * 100 + int(gs1_date[0:2])
if gs1_date[-2:] == '00': # Day is not mandatory, when not set -> last day of the month
date = datetime.datetime.strptime(str(year) + gs1_date[2:4], '%Y%m')
date = date.replace(day=calendar.monthrange(year, int(gs1_date[2:4]))[1])
else:
date = datetime.datetime.strptime(str(year) + gs1_date[2:], '%Y%m%d')
return date.date()
def parse_gs1_rule_pattern(self, match, rule):
result = {
'rule': rule,
'ai': match.group(1),
'string_value': match.group(2),
}
if rule.gs1_content_type == 'measure':
try:
decimal_position = 0 # Decimal position begins at the end, 0 means no decimal.
if rule.gs1_decimal_usage:
decimal_position = int(match.group(1)[-1])
if decimal_position > 0:
result['value'] = float(match.group(2)[:-decimal_position] + "." + match.group(2)[-decimal_position:])
else:
result['value'] = int(match.group(2))
except Exception:
raise ValidationError(_(
"There is something wrong with the barcode rule \"%s\" pattern.\n"
"If this rule uses decimal, check it can't get sometime else than a digit as last char for the Application Identifier.\n"
"Check also the possible matched values can only be digits, otherwise the value can't be casted as a measure.",
rule.name))
elif rule.gs1_content_type == 'identifier':
# Check digit and remove it of the value
if match.group(2)[-1] != str(self.get_barcode_check_digit("0" * (18 - len(match.group(2))) + match.group(2))):
return None
result['value'] = match.group(2)
elif rule.gs1_content_type == 'date':
if len(match.group(2)) != 6:
return None
result['value'] = self.gs1_date_to_date(match.group(2))
else: # when gs1_content_type == 'alpha':
result['value'] = match.group(2)
return result
def gs1_decompose_extanded(self, barcode):
"""Try to decompose the gs1 extanded barcode into several unit of information using gs1 rules.
Return a ordered list of dict
"""
self.ensure_one()
separator_group = FNC1_CHAR + "?"
if self.gs1_separator_fnc1:
separator_group = "(?:%s)?" % self.gs1_separator_fnc1
results = []
gs1_rules = self.rule_ids.filtered(lambda r: r.encoding == 'gs1-128')
def find_next_rule(remaining_barcode):
for rule in gs1_rules:
match = re.search("^" + rule.pattern + separator_group, remaining_barcode)
# If match and contains 2 groups at minimun, the first one need to be the AI and the second the value
# We can't use regex nammed group because in JS, it is not the same regex syntax (and not compatible in all browser)
if match and len(match.groups()) >= 2:
res = self.parse_gs1_rule_pattern(match, rule)
if res:
return res, remaining_barcode[match.end():]
return None
while len(barcode) > 0:
res_bar = find_next_rule(barcode)
# Cannot continue -> Fail to decompose gs1 and return
if not res_bar or res_bar[1] == barcode:
return None
barcode = res_bar[1]
results.append(res_bar[0])
return results
def parse_barcode(self, barcode):
if self.is_gs1_nomenclature:
return self.gs1_decompose_extanded(barcode)
return super().parse_barcode(barcode)
| 45.095238 | 5,682 |
2,998 |
py
|
PYTHON
|
15.0
|
import re
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class BarcodeRule(models.Model):
_inherit = 'barcode.rule'
def _default_encoding(self):
return 'gs1-128' if self.env.context.get('is_gs1') else 'any'
encoding = fields.Selection(
selection_add=[('gs1-128', 'GS1-128')], default=_default_encoding,
ondelete={'gs1-128': 'set default'})
type = fields.Selection(
selection_add=[
('quantity', 'Quantity'),
('location', 'Location'),
('location_dest', 'Destination location'),
('lot', 'Lot number'),
('package', 'Package'),
('use_date', 'Best before Date'),
('expiration_date', 'Expiration Date'),
('package_type', 'Packaging Type'),
('packaging_date', 'Packaging Date'),
], ondelete={
'quantity': 'set default',
'location': 'set default',
'location_dest': 'set default',
'lot': 'set default',
'package': 'set default',
'use_date': 'set default',
'expiration_date': 'set default',
'package_type': 'set default',
'packaging_date': 'set default',
})
is_gs1_nomenclature = fields.Boolean(related="barcode_nomenclature_id.is_gs1_nomenclature")
gs1_content_type = fields.Selection([
('date', 'Date'),
('measure', 'Measure'),
('identifier', 'Numeric Identifier'),
('alpha', 'Alpha-Numeric Name'),
], string="GS1 Content Type",
help="The GS1 content type defines what kind of data the rule will process the barcode as:\
* Date: the barcode will be converted into a Odoo datetime;\
* Measure: the barcode's value is related to a specific UoM;\
* Numeric Identifier: fixed length barcode following a specific encoding;\
* Alpha-Numeric Name: variable length barcode.")
gs1_decimal_usage = fields.Boolean('Decimal', help="If True, use the last digit of AI to dertermine where the first decimal is")
associated_uom_id = fields.Many2one('uom.uom')
@api.constrains('pattern')
def _check_pattern(self):
gs1_rules = self.filtered(lambda rule: rule.encoding == 'gs1-128')
for rule in gs1_rules:
try:
re.compile(rule.pattern)
except re.error as error:
raise ValidationError(_("The rule pattern \"%s\" is not a valid Regex: ", rule.name) + str(error))
groups = re.findall(r'\([^)]*\)', rule.pattern)
if len(groups) != 2:
raise ValidationError(_(
"The rule pattern \"%s\" is not valid, it needs two groups:"
"\n\t- A first one for the Application Identifier (usually 2 to 4 digits);"
"\n\t- A second one to catch the value.",
rule.name))
super(BarcodeRule, (self - gs1_rules))._check_pattern()
| 43.449275 | 2,998 |
1,403 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'EU One Stop Shop (OSS)',
'category': 'Accounting/Localizations',
'description': """
EU One Stop Shop (OSS) VAT
==========================
From July 1st 2021, EU businesses that are selling goods within the EU above EUR 10 000 to buyers located in another EU Member State need to register and pay VAT in the buyers’ Member State.
Below this new EU-wide threshold you can continue to apply the domestic rules for VAT on your cross-border sales. In order to simplify the application of this EU directive, the One Stop Shop (OSS) registration scheme allows businesses to make a unique tax declaration.
This module makes it possible by helping with the creation of the required EU fiscal positions and taxes in order to automatically apply and record the required taxes.
All you have to do is check that the proposed mapping is suitable for the products and services you sell.
References
++++++++++
Council Directive (EU) 2017/2455 Council Directive (EU) 2019/1995
Council Implementing Regulation (EU) 2019/2026
""",
'depends': ['account'],
'data': [
'views/res_config_settings_views.xml',
'data/account_account_tag.xml',
],
'post_init_hook': 'l10n_eu_oss_post_init',
'uninstall_hook': 'l10n_eu_oss_uninstall',
'license': 'LGPL-3',
}
| 43.78125 | 1,401 |
5,711 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.l10n_eu_oss.models.eu_tag_map import EU_TAG_MAP
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', 'post_install_l10n', '-at_install')
class OssTemplateTestCase(AccountTestInvoicingCommon):
@classmethod
def load_specific_chart_template(cls, chart_template_ref):
try:
super().setUpClass(chart_template_ref=chart_template_ref)
except ValueError as e:
if e.args[0] == f"External ID not found in the system: {chart_template_ref}":
cls.skipTest(cls, reason=f"The {chart_template_ref} CoA is required for this testSuite but the corresponding localization module isn't installed")
else:
raise e
@tagged('post_install', 'post_install_l10n', '-at_install')
class TestOSSBelgium(OssTemplateTestCase):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_be.l10nbe_chart_template'):
cls.load_specific_chart_template(chart_template_ref)
cls.company_data['company'].country_id = cls.env.ref('base.be')
cls.company_data['company']._map_eu_taxes()
def test_country_tag_from_belgium(self):
"""
This test ensure that xml_id from `account.tax.report.line` in the EU_TAG_MAP are processed correctly by the oss
tax creation mechanism.
"""
# get an eu country which isn't the current one:
another_eu_country_code = (self.env.ref('base.europe').country_ids - self.company_data['company'].country_id)[0].code
tax_oss = self.env['account.tax'].search([('name', 'ilike', f'%{another_eu_country_code}%')], limit=1)
for doc_type, report_line_xml_id in (
("invoice", "l10n_be.tax_report_line_47"),
("refund", "l10n_be.tax_report_line_49"),
):
with self.subTest(doc_type=doc_type, report_line_xml_id=report_line_xml_id):
oss_tag_id = tax_oss[f"{doc_type}_repartition_line_ids"]\
.filtered(lambda x: x.repartition_type == 'base')\
.tag_ids
expected_tag_id = self.env.ref(report_line_xml_id)\
.tag_ids\
.filtered(lambda t: not t.tax_negate)
self.assertIn(expected_tag_id, oss_tag_id, f"{doc_type} tag from Belgian CoA not correctly linked")
@tagged('post_install', 'post_install_l10n', '-at_install')
class TestOSSSpain(OssTemplateTestCase):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_es.account_chart_template_common'):
cls.load_specific_chart_template(chart_template_ref)
cls.company_data['company'].country_id = cls.env.ref('base.es')
cls.company_data['company']._map_eu_taxes()
def test_country_tag_from_spain(self):
"""
This test ensure that xml_id from `account.account.tag` in the EU_TAG_MAP are processed correctly by the oss
tax creation mechanism.
"""
# get an eu country which isn't the current one:
another_eu_country_code = (self.env.ref('base.europe').country_ids - self.company_data['company'].country_id)[0].code
tax_oss = self.env['account.tax'].search([('name', 'ilike', f'%{another_eu_country_code}%')], limit=1)
for doc_type, tag_xml_id in (
("invoice", "l10n_es.mod_303_124"),
):
with self.subTest(doc_type=doc_type, report_line_xml_id=tag_xml_id):
oss_tag_id = tax_oss[f"{doc_type}_repartition_line_ids"]\
.filtered(lambda x: x.repartition_type == 'base')\
.tag_ids
expected_tag_id = self.env.ref(tag_xml_id)
self.assertIn(expected_tag_id, oss_tag_id, f"{doc_type} tag from Spanish CoA not correctly linked")
@tagged('post_install', 'post_install_l10n', '-at_install')
class TestOSSUSA(OssTemplateTestCase):
@classmethod
def setUpClass(cls, chart_template_ref=None):
cls.load_specific_chart_template(chart_template_ref)
cls.company_data['company'].country_id = cls.env.ref('base.us')
cls.company_data['company']._map_eu_taxes()
def test_no_oss_tax(self):
# get an eu country which isn't the current one:
another_eu_country_code = (self.env.ref('base.europe').country_ids - self.company_data['company'].country_id)[0].code
tax_oss = self.env['account.tax'].search([('name', 'ilike', f'%{another_eu_country_code}%')], limit=1)
self.assertFalse(len(tax_oss), "OSS tax shouldn't be instanced on a US company")
@tagged('post_install', 'post_install_l10n', '-at_install')
class TestOSSMap(OssTemplateTestCase):
def test_oss_eu_tag_map(self):
""" Checks that the xml_id referenced in the map are correct.
In case of failure display the couple (chart_template_xml_id, tax_report_line_xml_id).
The test doesn't fail for unreferenced char_template or unreferenced tax_report_line.
"""
chart_templates = self.env['account.chart.template'].search([])
for chart_template in chart_templates:
[chart_template_xml_id] = chart_template.get_xml_id().values()
oss_tags = EU_TAG_MAP.get(chart_template_xml_id, {})
for tax_report_line_xml_id in filter(lambda d: d, oss_tags.values()):
with self.subTest(chart_template_xml_id=chart_template_xml_id, tax_report_line_xml_id=tax_report_line_xml_id):
tag = self.env.ref(tax_report_line_xml_id, raise_if_not_found=False)
self.assertIsNotNone(tag, f"The following xml_id is incorrect in EU_TAG_MAP.py:{tax_report_line_xml_id}")
| 47.991597 | 5,711 |
5,985 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
"""
The EU_TAG_MAP answers the question: "which tag should I apply on the OSS tax repartition line?"
{
'fiscal_country_code': {
'invoice_base_tag': xml_id_of_the_tag or None,
'invoice_tax_tag': xml_id_of_the_tag or None,
'refund_base_tag': xml_id_of_the_tag or None,
'refund_tax_tag': xml_id_of_the_tag or None,
},
}
"""
EU_TAG_MAP = {
# Austria
'l10n_at.l10n_at_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Belgium
'l10n_be.l10nbe_chart_template': {
'invoice_base_tag': 'l10n_be.tax_report_line_47',
'invoice_tax_tag': None,
'refund_base_tag': 'l10n_be.tax_report_line_49',
'refund_tax_tag': None,
},
# Bulgaria
'BG': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Croatia
'l10n_hr.l10n_hr_chart_template_rrif': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Cyprus
'CY': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Czech - Done in 13.0 - CoA not available yet
'l10n_cz.cz_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Denmark
'l10n_dk.dk_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Estonia - Done in 13.0 - CoA not available yet
'EE': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Finland
'l10n_fi.fi_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# France
'l10n_fr.l10n_fr_pcg_chart_template': {
'invoice_base_tag': 'l10n_fr.tax_report_E3',
'invoice_tax_tag': None,
'refund_base_tag': 'l10n_fr.tax_report_F8',
'refund_tax_tag': None,
},
# Germany SKR03
'l10n_de_skr03.l10n_de_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Germany SKR04
'l10n_de_skr04.l10n_chart_de_skr04': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Greece
'l10n_gr.l10n_gr_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Hungary
'l10n_hu.hungarian_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Ireland
'l10n_ie.l10n_ie': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Italy
'l10n_it.l10n_it_chart_template_generic': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Latvia
'LV': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Lithuania
'l10n_lt.account_chart_template_lithuania': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Luxembourg
'l10n_lu.lu_2011_chart_1': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Malta - Done in 13.0 - CoA not available yet
'MT': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Netherlands
'l10n_nl.l10nnl_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Poland
'l10n_pl.pl_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Portugal
'l10n_pt.pt_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Romania
'l10n_ro.ro_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Slovakia - Done in 13.0 - CoA not available yet
'l10n_sk.sk_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Slovenia
'l10n_si.gd_chart': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Spain
'l10n_es.account_chart_template_common': {
'invoice_base_tag': "l10n_es.mod_303_124",
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
# Sweden
'l10n_se.l10nse_chart_template': {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
},
}
| 27.96729 | 5,985 |
62,079 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# pylint: disable=C0302
"""
The EU_TAX_MAP dictionary contains a basic Tax Mapping for EU countries. It answers the question:
for an X% tax rate in the domestic country, what is the corresponding rate in a foreign EU country?
it takes the form tuple: rate, where
(Fiscal Country Code, Domestic Tax Rate, Foreign Country Code): Foreign Tax Rate
"""
EU_TAX_MAP = {
('AT', 10.0, 'BE'): 6.0,
('AT', 10.0, 'BG'): 20.0,
('AT', 10.0, 'CY'): 5.0,
('AT', 10.0, 'CZ'): 15.0,
('AT', 10.0, 'DE'): 7.0,
('AT', 10.0, 'DK'): 25.0,
('AT', 10.0, 'EE'): 9.0,
('AT', 10.0, 'ES'): 10.0,
('AT', 10.0, 'FI'): 10.0,
('AT', 10.0, 'FR'): 5.5,
('AT', 10.0, 'GR'): 13.0,
('AT', 10.0, 'HR'): 5.0,
('AT', 10.0, 'HU'): 5.0,
('AT', 10.0, 'IE'): 13.5,
('AT', 10.0, 'IT'): 4.0,
('AT', 10.0, 'LT'): 5.0,
('AT', 10.0, 'LU'): 7.0,
('AT', 10.0, 'LV'): 12.0,
('AT', 10.0, 'MT'): 5.0,
('AT', 10.0, 'NL'): 9.0,
('AT', 10.0, 'PL'): 8.0,
('AT', 10.0, 'PT'): 6.0,
('AT', 10.0, 'RO'): 5.0,
('AT', 10.0, 'SE'): 6.0,
('AT', 10.0, 'SI'): 9.5,
('AT', 10.0, 'SK'): 10.0,
('AT', 13.0, 'BE'): 21.0,
('AT', 13.0, 'BG'): 20.0,
('AT', 13.0, 'CY'): 19.0,
('AT', 13.0, 'CZ'): 21.0,
('AT', 13.0, 'DE'): 19.0,
('AT', 13.0, 'DK'): 25.0,
('AT', 13.0, 'EE'): 20.0,
('AT', 13.0, 'ES'): 21.0,
('AT', 13.0, 'FI'): 24.0,
('AT', 13.0, 'FR'): 20.0,
('AT', 13.0, 'GR'): 24.0,
('AT', 13.0, 'HR'): 25.0,
('AT', 13.0, 'HU'): 27.0,
('AT', 13.0, 'IE'): 23.0,
('AT', 13.0, 'IT'): 22.0,
('AT', 13.0, 'LT'): 21.0,
('AT', 13.0, 'LU'): 16.0,
('AT', 13.0, 'LV'): 21.0,
('AT', 13.0, 'MT'): 18.0,
('AT', 13.0, 'NL'): 21.0,
('AT', 13.0, 'PL'): 23.0,
('AT', 13.0, 'PT'): 23.0,
('AT', 13.0, 'RO'): 19.0,
('AT', 13.0, 'SE'): 25.0,
('AT', 13.0, 'SI'): 22.0,
('AT', 13.0, 'SK'): 20.0,
('AT', 20.0, 'BE'): 21.0,
('AT', 20.0, 'BG'): 20.0,
('AT', 20.0, 'CY'): 19.0,
('AT', 20.0, 'CZ'): 21.0,
('AT', 20.0, 'DE'): 19.0,
('AT', 20.0, 'DK'): 25.0,
('AT', 20.0, 'EE'): 20.0,
('AT', 20.0, 'ES'): 21.0,
('AT', 20.0, 'FI'): 24.0,
('AT', 20.0, 'FR'): 20.0,
('AT', 20.0, 'GR'): 24.0,
('AT', 20.0, 'HR'): 25.0,
('AT', 20.0, 'HU'): 27.0,
('AT', 20.0, 'IE'): 23.0,
('AT', 20.0, 'IT'): 22.0,
('AT', 20.0, 'LT'): 21.0,
('AT', 20.0, 'LU'): 16.0,
('AT', 20.0, 'LV'): 21.0,
('AT', 20.0, 'MT'): 18.0,
('AT', 20.0, 'NL'): 21.0,
('AT', 20.0, 'PL'): 23.0,
('AT', 20.0, 'PT'): 23.0,
('AT', 20.0, 'RO'): 19.0,
('AT', 20.0, 'SE'): 25.0,
('AT', 20.0, 'SI'): 22.0,
('AT', 20.0, 'SK'): 20.0,
('BE', 12.0, 'AT'): 20.0,
('BE', 12.0, 'BG'): 20.0,
('BE', 12.0, 'CY'): 19.0,
('BE', 12.0, 'CZ'): 21.0,
('BE', 12.0, 'DE'): 19.0,
('BE', 12.0, 'DK'): 25.0,
('BE', 12.0, 'EE'): 20.0,
('BE', 12.0, 'ES'): 21.0,
('BE', 12.0, 'FI'): 24.0,
('BE', 12.0, 'FR'): 20.0,
('BE', 12.0, 'GR'): 24.0,
('BE', 12.0, 'HR'): 25.0,
('BE', 12.0, 'HU'): 27.0,
('BE', 12.0, 'IE'): 23.0,
('BE', 12.0, 'IT'): 22.0,
('BE', 12.0, 'LT'): 21.0,
('BE', 12.0, 'LU'): 16.0,
('BE', 12.0, 'LV'): 21.0,
('BE', 12.0, 'MT'): 18.0,
('BE', 12.0, 'NL'): 21.0,
('BE', 12.0, 'PL'): 23.0,
('BE', 12.0, 'PT'): 23.0,
('BE', 12.0, 'RO'): 19.0,
('BE', 12.0, 'SE'): 25.0,
('BE', 12.0, 'SI'): 22.0,
('BE', 12.0, 'SK'): 20.0,
('BE', 21.0, 'AT'): 20.0,
('BE', 21.0, 'BG'): 20.0,
('BE', 21.0, 'CY'): 19.0,
('BE', 21.0, 'CZ'): 21.0,
('BE', 21.0, 'DE'): 19.0,
('BE', 21.0, 'DK'): 25.0,
('BE', 21.0, 'EE'): 20.0,
('BE', 21.0, 'ES'): 21.0,
('BE', 21.0, 'FI'): 24.0,
('BE', 21.0, 'FR'): 20.0,
('BE', 21.0, 'GR'): 24.0,
('BE', 21.0, 'HR'): 25.0,
('BE', 21.0, 'HU'): 27.0,
('BE', 21.0, 'IE'): 23.0,
('BE', 21.0, 'IT'): 22.0,
('BE', 21.0, 'LT'): 21.0,
('BE', 21.0, 'LU'): 16.0,
('BE', 21.0, 'LV'): 21.0,
('BE', 21.0, 'MT'): 18.0,
('BE', 21.0, 'NL'): 21.0,
('BE', 21.0, 'PL'): 23.0,
('BE', 21.0, 'PT'): 23.0,
('BE', 21.0, 'RO'): 19.0,
('BE', 21.0, 'SE'): 25.0,
('BE', 21.0, 'SI'): 22.0,
('BE', 21.0, 'SK'): 20.0,
('BE', 6.0, 'AT'): 10.0,
('BE', 6.0, 'BG'): 20.0,
('BE', 6.0, 'CY'): 5.0,
('BE', 6.0, 'CZ'): 15.0,
('BE', 6.0, 'DE'): 7.0,
('BE', 6.0, 'DK'): 25.0,
('BE', 6.0, 'EE'): 9.0,
('BE', 6.0, 'ES'): 10.0,
('BE', 6.0, 'FI'): 10.0,
('BE', 6.0, 'FR'): 5.5,
('BE', 6.0, 'GR'): 13.0,
('BE', 6.0, 'HR'): 5.0,
('BE', 6.0, 'HU'): 5.0,
('BE', 6.0, 'IE'): 13.5,
('BE', 6.0, 'IT'): 4.0,
('BE', 6.0, 'LT'): 5.0,
('BE', 6.0, 'LU'): 7.0,
('BE', 6.0, 'LV'): 12.0,
('BE', 6.0, 'MT'): 5.0,
('BE', 6.0, 'NL'): 9.0,
('BE', 6.0, 'PL'): 8.0,
('BE', 6.0, 'PT'): 6.0,
('BE', 6.0, 'RO'): 5.0,
('BE', 6.0, 'SE'): 6.0,
('BE', 6.0, 'SI'): 9.5,
('BE', 6.0, 'SK'): 10.0,
('BG', 20.0, 'AT'): 20.0,
('BG', 20.0, 'BE'): 21.0,
('BG', 20.0, 'CY'): 19.0,
('BG', 20.0, 'CZ'): 21.0,
('BG', 20.0, 'DE'): 19.0,
('BG', 20.0, 'DK'): 25.0,
('BG', 20.0, 'EE'): 20.0,
('BG', 20.0, 'ES'): 21.0,
('BG', 20.0, 'FI'): 24.0,
('BG', 20.0, 'FR'): 20.0,
('BG', 20.0, 'GR'): 24.0,
('BG', 20.0, 'HR'): 25.0,
('BG', 20.0, 'HU'): 27.0,
('BG', 20.0, 'IE'): 23.0,
('BG', 20.0, 'IT'): 22.0,
('BG', 20.0, 'LT'): 21.0,
('BG', 20.0, 'LU'): 16.0,
('BG', 20.0, 'LV'): 21.0,
('BG', 20.0, 'MT'): 18.0,
('BG', 20.0, 'NL'): 21.0,
('BG', 20.0, 'PL'): 23.0,
('BG', 20.0, 'PT'): 23.0,
('BG', 20.0, 'RO'): 19.0,
('BG', 20.0, 'SE'): 25.0,
('BG', 20.0, 'SI'): 22.0,
('BG', 20.0, 'SK'): 20.0,
('BG', 9.0, 'AT'): 10.0,
('BG', 9.0, 'BE'): 6.0,
('BG', 9.0, 'CY'): 5.0,
('BG', 9.0, 'CZ'): 15.0,
('BG', 9.0, 'DE'): 7.0,
('BG', 9.0, 'DK'): 25.0,
('BG', 9.0, 'EE'): 9.0,
('BG', 9.0, 'ES'): 10.0,
('BG', 9.0, 'FI'): 10.0,
('BG', 9.0, 'FR'): 5.5,
('BG', 9.0, 'GR'): 13.0,
('BG', 9.0, 'HR'): 5.0,
('BG', 9.0, 'HU'): 5.0,
('BG', 9.0, 'IE'): 13.5,
('BG', 9.0, 'IT'): 4.0,
('BG', 9.0, 'LT'): 5.0,
('BG', 9.0, 'LU'): 7.0,
('BG', 9.0, 'LV'): 12.0,
('BG', 9.0, 'MT'): 5.0,
('BG', 9.0, 'NL'): 9.0,
('BG', 9.0, 'PL'): 8.0,
('BG', 9.0, 'PT'): 6.0,
('BG', 9.0, 'RO'): 5.0,
('BG', 9.0, 'SE'): 6.0,
('BG', 9.0, 'SI'): 9.5,
('BG', 9.0, 'SK'): 10.0,
('CY', 19.0, 'AT'): 20.0,
('CY', 19.0, 'BE'): 21.0,
('CY', 19.0, 'BG'): 20.0,
('CY', 19.0, 'CZ'): 21.0,
('CY', 19.0, 'DE'): 19.0,
('CY', 19.0, 'DK'): 25.0,
('CY', 19.0, 'EE'): 20.0,
('CY', 19.0, 'ES'): 21.0,
('CY', 19.0, 'FI'): 24.0,
('CY', 19.0, 'FR'): 20.0,
('CY', 19.0, 'GR'): 24.0,
('CY', 19.0, 'HR'): 25.0,
('CY', 19.0, 'HU'): 27.0,
('CY', 19.0, 'IE'): 23.0,
('CY', 19.0, 'IT'): 22.0,
('CY', 19.0, 'LT'): 21.0,
('CY', 19.0, 'LU'): 16.0,
('CY', 19.0, 'LV'): 21.0,
('CY', 19.0, 'MT'): 18.0,
('CY', 19.0, 'NL'): 21.0,
('CY', 19.0, 'PL'): 23.0,
('CY', 19.0, 'PT'): 23.0,
('CY', 19.0, 'RO'): 19.0,
('CY', 19.0, 'SE'): 25.0,
('CY', 19.0, 'SI'): 22.0,
('CY', 19.0, 'SK'): 20.0,
('CY', 5.0, 'AT'): 10.0,
('CY', 5.0, 'BE'): 6.0,
('CY', 5.0, 'BG'): 20.0,
('CY', 5.0, 'CZ'): 15.0,
('CY', 5.0, 'DE'): 7.0,
('CY', 5.0, 'DK'): 25.0,
('CY', 5.0, 'EE'): 9.0,
('CY', 5.0, 'ES'): 10.0,
('CY', 5.0, 'FI'): 10.0,
('CY', 5.0, 'FR'): 5.5,
('CY', 5.0, 'GR'): 13.0,
('CY', 5.0, 'HR'): 5.0,
('CY', 5.0, 'HU'): 5.0,
('CY', 5.0, 'IE'): 13.5,
('CY', 5.0, 'IT'): 4.0,
('CY', 5.0, 'LT'): 5.0,
('CY', 5.0, 'LU'): 7.0,
('CY', 5.0, 'LV'): 12.0,
('CY', 5.0, 'MT'): 5.0,
('CY', 5.0, 'NL'): 9.0,
('CY', 5.0, 'PL'): 8.0,
('CY', 5.0, 'PT'): 6.0,
('CY', 5.0, 'RO'): 5.0,
('CY', 5.0, 'SE'): 6.0,
('CY', 5.0, 'SI'): 9.5,
('CY', 5.0, 'SK'): 10.0,
('CY', 9.0, 'AT'): 10.0,
('CY', 9.0, 'BE'): 6.0,
('CY', 9.0, 'BG'): 20.0,
('CY', 9.0, 'CZ'): 15.0,
('CY', 9.0, 'DE'): 7.0,
('CY', 9.0, 'DK'): 25.0,
('CY', 9.0, 'EE'): 9.0,
('CY', 9.0, 'ES'): 10.0,
('CY', 9.0, 'FI'): 10.0,
('CY', 9.0, 'FR'): 5.5,
('CY', 9.0, 'GR'): 13.0,
('CY', 9.0, 'HR'): 13.0,
('CY', 9.0, 'HU'): 5.0,
('CY', 9.0, 'IE'): 13.5,
('CY', 9.0, 'IT'): 10.0,
('CY', 9.0, 'LT'): 5.0,
('CY', 9.0, 'LU'): 7.0,
('CY', 9.0, 'LV'): 12.0,
('CY', 9.0, 'MT'): 5.0,
('CY', 9.0, 'NL'): 9.0,
('CY', 9.0, 'PL'): 8.0,
('CY', 9.0, 'PT'): 6.0,
('CY', 9.0, 'RO'): 5.0,
('CY', 9.0, 'SE'): 6.0,
('CY', 9.0, 'SI'): 9.5,
('CY', 9.0, 'SK'): 10.0,
('CZ', 10.0, 'AT'): 10.0,
('CZ', 10.0, 'BE'): 6.0,
('CZ', 10.0, 'BG'): 20.0,
('CZ', 10.0, 'CY'): 5.0,
('CZ', 10.0, 'DE'): 7.0,
('CZ', 10.0, 'DK'): 25.0,
('CZ', 10.0, 'EE'): 9.0,
('CZ', 10.0, 'ES'): 10.0,
('CZ', 10.0, 'FI'): 10.0,
('CZ', 10.0, 'FR'): 5.5,
('CZ', 10.0, 'GR'): 13.0,
('CZ', 10.0, 'HR'): 5.0,
('CZ', 10.0, 'HU'): 5.0,
('CZ', 10.0, 'IE'): 13.5,
('CZ', 10.0, 'IT'): 4.0,
('CZ', 10.0, 'LT'): 5.0,
('CZ', 10.0, 'LU'): 7.0,
('CZ', 10.0, 'LV'): 12.0,
('CZ', 10.0, 'MT'): 5.0,
('CZ', 10.0, 'NL'): 9.0,
('CZ', 10.0, 'PL'): 8.0,
('CZ', 10.0, 'PT'): 6.0,
('CZ', 10.0, 'RO'): 5.0,
('CZ', 10.0, 'SE'): 6.0,
('CZ', 10.0, 'SI'): 9.5,
('CZ', 10.0, 'SK'): 10.0,
('CZ', 15.0, 'AT'): 10.0,
('CZ', 15.0, 'BE'): 6.0,
('CZ', 15.0, 'BG'): 20.0,
('CZ', 15.0, 'CY'): 5.0,
('CZ', 15.0, 'DE'): 7.0,
('CZ', 15.0, 'DK'): 25.0,
('CZ', 15.0, 'EE'): 9.0,
('CZ', 15.0, 'ES'): 10.0,
('CZ', 15.0, 'FI'): 10.0,
('CZ', 15.0, 'FR'): 5.5,
('CZ', 15.0, 'GR'): 13.0,
('CZ', 15.0, 'HR'): 13.0,
('CZ', 15.0, 'HU'): 5.0,
('CZ', 15.0, 'IE'): 13.5,
('CZ', 15.0, 'IT'): 10.0,
('CZ', 15.0, 'LT'): 5.0,
('CZ', 15.0, 'LU'): 7.0,
('CZ', 15.0, 'LV'): 12.0,
('CZ', 15.0, 'MT'): 5.0,
('CZ', 15.0, 'NL'): 9.0,
('CZ', 15.0, 'PL'): 8.0,
('CZ', 15.0, 'PT'): 6.0,
('CZ', 15.0, 'RO'): 5.0,
('CZ', 15.0, 'SE'): 6.0,
('CZ', 15.0, 'SI'): 9.5,
('CZ', 15.0, 'SK'): 10.0,
('CZ', 21.0, 'AT'): 20.0,
('CZ', 21.0, 'BE'): 21.0,
('CZ', 21.0, 'BG'): 20.0,
('CZ', 21.0, 'CY'): 19.0,
('CZ', 21.0, 'DE'): 19.0,
('CZ', 21.0, 'DK'): 25.0,
('CZ', 21.0, 'EE'): 20.0,
('CZ', 21.0, 'ES'): 21.0,
('CZ', 21.0, 'FI'): 24.0,
('CZ', 21.0, 'FR'): 20.0,
('CZ', 21.0, 'GR'): 24.0,
('CZ', 21.0, 'HR'): 25.0,
('CZ', 21.0, 'HU'): 27.0,
('CZ', 21.0, 'IE'): 23.0,
('CZ', 21.0, 'IT'): 22.0,
('CZ', 21.0, 'LT'): 21.0,
('CZ', 21.0, 'LU'): 16.0,
('CZ', 21.0, 'LV'): 21.0,
('CZ', 21.0, 'MT'): 18.0,
('CZ', 21.0, 'NL'): 21.0,
('CZ', 21.0, 'PL'): 23.0,
('CZ', 21.0, 'PT'): 23.0,
('CZ', 21.0, 'RO'): 19.0,
('CZ', 21.0, 'SE'): 25.0,
('CZ', 21.0, 'SI'): 22.0,
('CZ', 21.0, 'SK'): 20.0,
('DE', 19.0, 'AT'): 20.0,
('DE', 19.0, 'BE'): 21.0,
('DE', 19.0, 'BG'): 20.0,
('DE', 19.0, 'CY'): 19.0,
('DE', 19.0, 'CZ'): 21.0,
('DE', 19.0, 'DK'): 25.0,
('DE', 19.0, 'EE'): 20.0,
('DE', 19.0, 'ES'): 21.0,
('DE', 19.0, 'FI'): 24.0,
('DE', 19.0, 'FR'): 20.0,
('DE', 19.0, 'GR'): 24.0,
('DE', 19.0, 'HR'): 25.0,
('DE', 19.0, 'HU'): 27.0,
('DE', 19.0, 'IE'): 23.0,
('DE', 19.0, 'IT'): 22.0,
('DE', 19.0, 'LT'): 21.0,
('DE', 19.0, 'LU'): 16.0,
('DE', 19.0, 'LV'): 21.0,
('DE', 19.0, 'MT'): 18.0,
('DE', 19.0, 'NL'): 21.0,
('DE', 19.0, 'PL'): 23.0,
('DE', 19.0, 'PT'): 23.0,
('DE', 19.0, 'RO'): 19.0,
('DE', 19.0, 'SE'): 25.0,
('DE', 19.0, 'SI'): 22.0,
('DE', 19.0, 'SK'): 20.0,
('DE', 7.0, 'AT'): 10.0,
('DE', 7.0, 'BE'): 6.0,
('DE', 7.0, 'BG'): 20.0,
('DE', 7.0, 'CY'): 5.0,
('DE', 7.0, 'CZ'): 15.0,
('DE', 7.0, 'DK'): 25.0,
('DE', 7.0, 'EE'): 9.0,
('DE', 7.0, 'ES'): 10.0,
('DE', 7.0, 'FI'): 10.0,
('DE', 7.0, 'FR'): 5.5,
('DE', 7.0, 'GR'): 13.0,
('DE', 7.0, 'HR'): 5.0,
('DE', 7.0, 'HU'): 5.0,
('DE', 7.0, 'IE'): 13.5,
('DE', 7.0, 'IT'): 4.0,
('DE', 7.0, 'LT'): 5.0,
('DE', 7.0, 'LU'): 7.0,
('DE', 7.0, 'LV'): 12.0,
('DE', 7.0, 'MT'): 5.0,
('DE', 7.0, 'NL'): 9.0,
('DE', 7.0, 'PL'): 8.0,
('DE', 7.0, 'PT'): 6.0,
('DE', 7.0, 'RO'): 5.0,
('DE', 7.0, 'SE'): 6.0,
('DE', 7.0, 'SI'): 9.5,
('DE', 7.0, 'SK'): 10.0,
('DK', 25.0, 'AT'): 20.0,
('DK', 25.0, 'BE'): 21.0,
('DK', 25.0, 'BG'): 20.0,
('DK', 25.0, 'CY'): 19.0,
('DK', 25.0, 'CZ'): 21.0,
('DK', 25.0, 'DE'): 19.0,
('DK', 25.0, 'EE'): 20.0,
('DK', 25.0, 'ES'): 21.0,
('DK', 25.0, 'FI'): 24.0,
('DK', 25.0, 'FR'): 20.0,
('DK', 25.0, 'GR'): 24.0,
('DK', 25.0, 'HR'): 25.0,
('DK', 25.0, 'HU'): 27.0,
('DK', 25.0, 'IE'): 23.0,
('DK', 25.0, 'IT'): 22.0,
('DK', 25.0, 'LT'): 21.0,
('DK', 25.0, 'LU'): 16.0,
('DK', 25.0, 'LV'): 21.0,
('DK', 25.0, 'MT'): 18.0,
('DK', 25.0, 'NL'): 21.0,
('DK', 25.0, 'PL'): 23.0,
('DK', 25.0, 'PT'): 23.0,
('DK', 25.0, 'RO'): 19.0,
('DK', 25.0, 'SE'): 25.0,
('DK', 25.0, 'SI'): 22.0,
('DK', 25.0, 'SK'): 20.0,
('EE', 20.0, 'AT'): 20.0,
('EE', 20.0, 'BE'): 21.0,
('EE', 20.0, 'BG'): 20.0,
('EE', 20.0, 'CY'): 19.0,
('EE', 20.0, 'CZ'): 21.0,
('EE', 20.0, 'DE'): 19.0,
('EE', 20.0, 'DK'): 25.0,
('EE', 20.0, 'ES'): 21.0,
('EE', 20.0, 'FI'): 24.0,
('EE', 20.0, 'FR'): 20.0,
('EE', 20.0, 'GR'): 24.0,
('EE', 20.0, 'HR'): 25.0,
('EE', 20.0, 'HU'): 27.0,
('EE', 20.0, 'IE'): 23.0,
('EE', 20.0, 'IT'): 22.0,
('EE', 20.0, 'LT'): 21.0,
('EE', 20.0, 'LU'): 16.0,
('EE', 20.0, 'LV'): 21.0,
('EE', 20.0, 'MT'): 18.0,
('EE', 20.0, 'NL'): 21.0,
('EE', 20.0, 'PL'): 23.0,
('EE', 20.0, 'PT'): 23.0,
('EE', 20.0, 'RO'): 19.0,
('EE', 20.0, 'SE'): 25.0,
('EE', 20.0, 'SI'): 22.0,
('EE', 20.0, 'SK'): 20.0,
('EE', 9.0, 'AT'): 10.0,
('EE', 9.0, 'BE'): 6.0,
('EE', 9.0, 'BG'): 20.0,
('EE', 9.0, 'CY'): 5.0,
('EE', 9.0, 'CZ'): 15.0,
('EE', 9.0, 'DE'): 7.0,
('EE', 9.0, 'DK'): 25.0,
('EE', 9.0, 'ES'): 10.0,
('EE', 9.0, 'FI'): 10.0,
('EE', 9.0, 'FR'): 5.5,
('EE', 9.0, 'GR'): 13.0,
('EE', 9.0, 'HR'): 5.0,
('EE', 9.0, 'HU'): 5.0,
('EE', 9.0, 'IE'): 13.5,
('EE', 9.0, 'IT'): 4.0,
('EE', 9.0, 'LT'): 5.0,
('EE', 9.0, 'LU'): 7.0,
('EE', 9.0, 'LV'): 12.0,
('EE', 9.0, 'MT'): 5.0,
('EE', 9.0, 'NL'): 9.0,
('EE', 9.0, 'PL'): 8.0,
('EE', 9.0, 'PT'): 6.0,
('EE', 9.0, 'RO'): 5.0,
('EE', 9.0, 'SE'): 6.0,
('EE', 9.0, 'SI'): 9.5,
('EE', 9.0, 'SK'): 10.0,
('ES', 10.0, 'AT'): 10.0,
('ES', 10.0, 'BE'): 6.0,
('ES', 10.0, 'BG'): 20.0,
('ES', 10.0, 'CY'): 5.0,
('ES', 10.0, 'CZ'): 15.0,
('ES', 10.0, 'DE'): 7.0,
('ES', 10.0, 'DK'): 25.0,
('ES', 10.0, 'EE'): 9.0,
('ES', 10.0, 'FI'): 10.0,
('ES', 10.0, 'FR'): 5.5,
('ES', 10.0, 'GR'): 13.0,
('ES', 10.0, 'HR'): 13.0,
('ES', 10.0, 'HU'): 5.0,
('ES', 10.0, 'IE'): 13.5,
('ES', 10.0, 'IT'): 10.0,
('ES', 10.0, 'LT'): 5.0,
('ES', 10.0, 'LU'): 7.0,
('ES', 10.0, 'LV'): 12.0,
('ES', 10.0, 'MT'): 5.0,
('ES', 10.0, 'NL'): 9.0,
('ES', 10.0, 'PL'): 8.0,
('ES', 10.0, 'PT'): 6.0,
('ES', 10.0, 'RO'): 5.0,
('ES', 10.0, 'SE'): 6.0,
('ES', 10.0, 'SI'): 9.5,
('ES', 10.0, 'SK'): 10.0,
('ES', 21.0, 'AT'): 20.0,
('ES', 21.0, 'BE'): 21.0,
('ES', 21.0, 'BG'): 20.0,
('ES', 21.0, 'CY'): 19.0,
('ES', 21.0, 'CZ'): 21.0,
('ES', 21.0, 'DE'): 19.0,
('ES', 21.0, 'DK'): 25.0,
('ES', 21.0, 'EE'): 20.0,
('ES', 21.0, 'FI'): 24.0,
('ES', 21.0, 'FR'): 20.0,
('ES', 21.0, 'GR'): 24.0,
('ES', 21.0, 'HR'): 25.0,
('ES', 21.0, 'HU'): 27.0,
('ES', 21.0, 'IE'): 23.0,
('ES', 21.0, 'IT'): 22.0,
('ES', 21.0, 'LT'): 21.0,
('ES', 21.0, 'LU'): 16.0,
('ES', 21.0, 'LV'): 21.0,
('ES', 21.0, 'MT'): 18.0,
('ES', 21.0, 'NL'): 21.0,
('ES', 21.0, 'PL'): 23.0,
('ES', 21.0, 'PT'): 23.0,
('ES', 21.0, 'RO'): 19.0,
('ES', 21.0, 'SE'): 25.0,
('ES', 21.0, 'SI'): 22.0,
('ES', 21.0, 'SK'): 20.0,
('ES', 4.0, 'AT'): 10.0,
('ES', 4.0, 'BE'): 6.0,
('ES', 4.0, 'BG'): 20.0,
('ES', 4.0, 'CY'): 5.0,
('ES', 4.0, 'CZ'): 15.0,
('ES', 4.0, 'DE'): 7.0,
('ES', 4.0, 'DK'): 25.0,
('ES', 4.0, 'EE'): 9.0,
('ES', 4.0, 'FI'): 10.0,
('ES', 4.0, 'FR'): 5.5,
('ES', 4.0, 'GR'): 13.0,
('ES', 4.0, 'HR'): 5.0,
('ES', 4.0, 'HU'): 5.0,
('ES', 4.0, 'IE'): 4.8,
('ES', 4.0, 'IT'): 4.0,
('ES', 4.0, 'LT'): 5.0,
('ES', 4.0, 'LU'): 7.0,
('ES', 4.0, 'LV'): 12.0,
('ES', 4.0, 'MT'): 5.0,
('ES', 4.0, 'NL'): 9.0,
('ES', 4.0, 'PL'): 8.0,
('ES', 4.0, 'PT'): 6.0,
('ES', 4.0, 'RO'): 5.0,
('ES', 4.0, 'SE'): 6.0,
('ES', 4.0, 'SI'): 9.5,
('ES', 4.0, 'SK'): 10.0,
('FI', 10.0, 'AT'): 10.0,
('FI', 10.0, 'BE'): 6.0,
('FI', 10.0, 'BG'): 20.0,
('FI', 10.0, 'CY'): 5.0,
('FI', 10.0, 'CZ'): 15.0,
('FI', 10.0, 'DE'): 7.0,
('FI', 10.0, 'DK'): 25.0,
('FI', 10.0, 'EE'): 9.0,
('FI', 10.0, 'ES'): 10.0,
('FI', 10.0, 'FR'): 5.5,
('FI', 10.0, 'GR'): 13.0,
('FI', 10.0, 'HR'): 5.0,
('FI', 10.0, 'HU'): 5.0,
('FI', 10.0, 'IE'): 13.5,
('FI', 10.0, 'IT'): 4.0,
('FI', 10.0, 'LT'): 5.0,
('FI', 10.0, 'LU'): 7.0,
('FI', 10.0, 'LV'): 12.0,
('FI', 10.0, 'MT'): 5.0,
('FI', 10.0, 'NL'): 9.0,
('FI', 10.0, 'PL'): 8.0,
('FI', 10.0, 'PT'): 6.0,
('FI', 10.0, 'RO'): 5.0,
('FI', 10.0, 'SE'): 6.0,
('FI', 10.0, 'SI'): 9.5,
('FI', 10.0, 'SK'): 10.0,
('FI', 14.0, 'AT'): 10.0,
('FI', 14.0, 'BE'): 6.0,
('FI', 14.0, 'BG'): 20.0,
('FI', 14.0, 'CY'): 5.0,
('FI', 14.0, 'CZ'): 15.0,
('FI', 14.0, 'DE'): 7.0,
('FI', 14.0, 'DK'): 25.0,
('FI', 14.0, 'EE'): 9.0,
('FI', 14.0, 'ES'): 10.0,
('FI', 14.0, 'FR'): 5.5,
('FI', 14.0, 'GR'): 13.0,
('FI', 14.0, 'HR'): 13.0,
('FI', 14.0, 'HU'): 5.0,
('FI', 14.0, 'IE'): 13.5,
('FI', 14.0, 'IT'): 10.0,
('FI', 14.0, 'LT'): 5.0,
('FI', 14.0, 'LU'): 7.0,
('FI', 14.0, 'LV'): 12.0,
('FI', 14.0, 'MT'): 5.0,
('FI', 14.0, 'NL'): 9.0,
('FI', 14.0, 'PL'): 8.0,
('FI', 14.0, 'PT'): 6.0,
('FI', 14.0, 'RO'): 5.0,
('FI', 14.0, 'SE'): 6.0,
('FI', 14.0, 'SI'): 9.5,
('FI', 14.0, 'SK'): 10.0,
('FI', 24.0, 'AT'): 20.0,
('FI', 24.0, 'BE'): 21.0,
('FI', 24.0, 'BG'): 20.0,
('FI', 24.0, 'CY'): 19.0,
('FI', 24.0, 'CZ'): 21.0,
('FI', 24.0, 'DE'): 19.0,
('FI', 24.0, 'DK'): 25.0,
('FI', 24.0, 'EE'): 20.0,
('FI', 24.0, 'ES'): 21.0,
('FI', 24.0, 'FR'): 20.0,
('FI', 24.0, 'GR'): 24.0,
('FI', 24.0, 'HR'): 25.0,
('FI', 24.0, 'HU'): 27.0,
('FI', 24.0, 'IE'): 23.0,
('FI', 24.0, 'IT'): 22.0,
('FI', 24.0, 'LT'): 21.0,
('FI', 24.0, 'LU'): 16.0,
('FI', 24.0, 'LV'): 21.0,
('FI', 24.0, 'MT'): 18.0,
('FI', 24.0, 'NL'): 21.0,
('FI', 24.0, 'PL'): 23.0,
('FI', 24.0, 'PT'): 23.0,
('FI', 24.0, 'RO'): 19.0,
('FI', 24.0, 'SE'): 25.0,
('FI', 24.0, 'SI'): 22.0,
('FI', 24.0, 'SK'): 20.0,
('FR', 10.0, 'AT'): 10.0,
('FR', 10.0, 'BE'): 6.0,
('FR', 10.0, 'BG'): 20.0,
('FR', 10.0, 'CY'): 5.0,
('FR', 10.0, 'CZ'): 15.0,
('FR', 10.0, 'DE'): 7.0,
('FR', 10.0, 'DK'): 25.0,
('FR', 10.0, 'EE'): 9.0,
('FR', 10.0, 'ES'): 10.0,
('FR', 10.0, 'FI'): 10.0,
('FR', 10.0, 'GR'): 13.0,
('FR', 10.0, 'HR'): 13.0,
('FR', 10.0, 'HU'): 5.0,
('FR', 10.0, 'IE'): 13.5,
('FR', 10.0, 'IT'): 10.0,
('FR', 10.0, 'LT'): 5.0,
('FR', 10.0, 'LU'): 7.0,
('FR', 10.0, 'LV'): 12.0,
('FR', 10.0, 'MT'): 5.0,
('FR', 10.0, 'NL'): 9.0,
('FR', 10.0, 'PL'): 8.0,
('FR', 10.0, 'PT'): 6.0,
('FR', 10.0, 'RO'): 5.0,
('FR', 10.0, 'SE'): 6.0,
('FR', 10.0, 'SI'): 9.5,
('FR', 10.0, 'SK'): 10.0,
('FR', 2.1, 'AT'): 10.0,
('FR', 2.1, 'BE'): 6.0,
('FR', 2.1, 'BG'): 20.0,
('FR', 2.1, 'CY'): 5.0,
('FR', 2.1, 'CZ'): 15.0,
('FR', 2.1, 'DE'): 7.0,
('FR', 2.1, 'DK'): 25.0,
('FR', 2.1, 'EE'): 9.0,
('FR', 2.1, 'ES'): 4.0,
('FR', 2.1, 'FI'): 10.0,
('FR', 2.1, 'GR'): 13.0,
('FR', 2.1, 'HR'): 5.0,
('FR', 2.1, 'HU'): 5.0,
('FR', 2.1, 'IE'): 4.8,
('FR', 2.1, 'IT'): 4.0,
('FR', 2.1, 'LT'): 5.0,
('FR', 2.1, 'LU'): 7.0,
('FR', 2.1, 'LV'): 12.0,
('FR', 2.1, 'MT'): 5.0,
('FR', 2.1, 'NL'): 9.0,
('FR', 2.1, 'PL'): 8.0,
('FR', 2.1, 'PT'): 6.0,
('FR', 2.1, 'RO'): 5.0,
('FR', 2.1, 'SE'): 6.0,
('FR', 2.1, 'SI'): 9.5,
('FR', 2.1, 'SK'): 10.0,
('FR', 20.0, 'AT'): 20.0,
('FR', 20.0, 'BE'): 21.0,
('FR', 20.0, 'BG'): 20.0,
('FR', 20.0, 'CY'): 19.0,
('FR', 20.0, 'CZ'): 21.0,
('FR', 20.0, 'DE'): 19.0,
('FR', 20.0, 'DK'): 25.0,
('FR', 20.0, 'EE'): 20.0,
('FR', 20.0, 'ES'): 21.0,
('FR', 20.0, 'FI'): 24.0,
('FR', 20.0, 'GR'): 24.0,
('FR', 20.0, 'HR'): 25.0,
('FR', 20.0, 'HU'): 27.0,
('FR', 20.0, 'IE'): 23.0,
('FR', 20.0, 'IT'): 22.0,
('FR', 20.0, 'LT'): 21.0,
('FR', 20.0, 'LU'): 16.0,
('FR', 20.0, 'LV'): 21.0,
('FR', 20.0, 'MT'): 18.0,
('FR', 20.0, 'NL'): 21.0,
('FR', 20.0, 'PL'): 23.0,
('FR', 20.0, 'PT'): 23.0,
('FR', 20.0, 'RO'): 19.0,
('FR', 20.0, 'SE'): 25.0,
('FR', 20.0, 'SI'): 22.0,
('FR', 20.0, 'SK'): 20.0,
('FR', 5.5, 'AT'): 10.0,
('FR', 5.5, 'BE'): 6.0,
('FR', 5.5, 'BG'): 20.0,
('FR', 5.5, 'CY'): 5.0,
('FR', 5.5, 'CZ'): 15.0,
('FR', 5.5, 'DE'): 7.0,
('FR', 5.5, 'DK'): 25.0,
('FR', 5.5, 'EE'): 9.0,
('FR', 5.5, 'ES'): 10.0,
('FR', 5.5, 'FI'): 10.0,
('FR', 5.5, 'GR'): 13.0,
('FR', 5.5, 'HR'): 5.0,
('FR', 5.5, 'HU'): 5.0,
('FR', 5.5, 'IE'): 13.5,
('FR', 5.5, 'IT'): 4.0,
('FR', 5.5, 'LT'): 5.0,
('FR', 5.5, 'LU'): 7.0,
('FR', 5.5, 'LV'): 12.0,
('FR', 5.5, 'MT'): 5.0,
('FR', 5.5, 'NL'): 9.0,
('FR', 5.5, 'PL'): 8.0,
('FR', 5.5, 'PT'): 6.0,
('FR', 5.5, 'RO'): 5.0,
('FR', 5.5, 'SE'): 6.0,
('FR', 5.5, 'SI'): 9.5,
('FR', 5.5, 'SK'): 10.0,
('GR', 13.0, 'AT'): 10.0,
('GR', 13.0, 'BE'): 6.0,
('GR', 13.0, 'BG'): 20.0,
('GR', 13.0, 'CY'): 5.0,
('GR', 13.0, 'CZ'): 15.0,
('GR', 13.0, 'DE'): 7.0,
('GR', 13.0, 'DK'): 25.0,
('GR', 13.0, 'EE'): 9.0,
('GR', 13.0, 'ES'): 10.0,
('GR', 13.0, 'FI'): 10.0,
('GR', 13.0, 'FR'): 5.5,
('GR', 13.0, 'HR'): 13.0,
('GR', 13.0, 'HU'): 5.0,
('GR', 13.0, 'IE'): 13.5,
('GR', 13.0, 'IT'): 10.0,
('GR', 13.0, 'LT'): 5.0,
('GR', 13.0, 'LU'): 7.0,
('GR', 13.0, 'LV'): 12.0,
('GR', 13.0, 'MT'): 5.0,
('GR', 13.0, 'NL'): 9.0,
('GR', 13.0, 'PL'): 8.0,
('GR', 13.0, 'PT'): 6.0,
('GR', 13.0, 'RO'): 5.0,
('GR', 13.0, 'SE'): 6.0,
('GR', 13.0, 'SI'): 9.5,
('GR', 13.0, 'SK'): 10.0,
('GR', 24.0, 'AT'): 20.0,
('GR', 24.0, 'BE'): 21.0,
('GR', 24.0, 'BG'): 20.0,
('GR', 24.0, 'CY'): 19.0,
('GR', 24.0, 'CZ'): 21.0,
('GR', 24.0, 'DE'): 19.0,
('GR', 24.0, 'DK'): 25.0,
('GR', 24.0, 'EE'): 20.0,
('GR', 24.0, 'ES'): 21.0,
('GR', 24.0, 'FI'): 24.0,
('GR', 24.0, 'FR'): 20.0,
('GR', 24.0, 'HR'): 25.0,
('GR', 24.0, 'HU'): 27.0,
('GR', 24.0, 'IE'): 23.0,
('GR', 24.0, 'IT'): 22.0,
('GR', 24.0, 'LT'): 21.0,
('GR', 24.0, 'LU'): 16.0,
('GR', 24.0, 'LV'): 21.0,
('GR', 24.0, 'MT'): 18.0,
('GR', 24.0, 'NL'): 21.0,
('GR', 24.0, 'PL'): 23.0,
('GR', 24.0, 'PT'): 23.0,
('GR', 24.0, 'RO'): 19.0,
('GR', 24.0, 'SE'): 25.0,
('GR', 24.0, 'SI'): 22.0,
('GR', 24.0, 'SK'): 20.0,
('GR', 6.0, 'AT'): 10.0,
('GR', 6.0, 'BE'): 6.0,
('GR', 6.0, 'BG'): 20.0,
('GR', 6.0, 'CY'): 5.0,
('GR', 6.0, 'CZ'): 15.0,
('GR', 6.0, 'DE'): 7.0,
('GR', 6.0, 'DK'): 25.0,
('GR', 6.0, 'EE'): 9.0,
('GR', 6.0, 'ES'): 10.0,
('GR', 6.0, 'FI'): 10.0,
('GR', 6.0, 'FR'): 5.5,
('GR', 6.0, 'HR'): 5.0,
('GR', 6.0, 'HU'): 5.0,
('GR', 6.0, 'IE'): 13.5,
('GR', 6.0, 'IT'): 4.0,
('GR', 6.0, 'LT'): 5.0,
('GR', 6.0, 'LU'): 7.0,
('GR', 6.0, 'LV'): 12.0,
('GR', 6.0, 'MT'): 5.0,
('GR', 6.0, 'NL'): 9.0,
('GR', 6.0, 'PL'): 8.0,
('GR', 6.0, 'PT'): 6.0,
('GR', 6.0, 'RO'): 5.0,
('GR', 6.0, 'SE'): 6.0,
('GR', 6.0, 'SI'): 9.5,
('GR', 6.0, 'SK'): 10.0,
('HR', 13.0, 'AT'): 10.0,
('HR', 13.0, 'BE'): 6.0,
('HR', 13.0, 'BG'): 20.0,
('HR', 13.0, 'CY'): 5.0,
('HR', 13.0, 'CZ'): 15.0,
('HR', 13.0, 'DE'): 7.0,
('HR', 13.0, 'DK'): 25.0,
('HR', 13.0, 'EE'): 9.0,
('HR', 13.0, 'ES'): 10.0,
('HR', 13.0, 'FI'): 10.0,
('HR', 13.0, 'FR'): 5.5,
('HR', 13.0, 'GR'): 13.0,
('HR', 13.0, 'HU'): 5.0,
('HR', 13.0, 'IE'): 13.5,
('HR', 13.0, 'IT'): 10.0,
('HR', 13.0, 'LT'): 5.0,
('HR', 13.0, 'LU'): 7.0,
('HR', 13.0, 'LV'): 12.0,
('HR', 13.0, 'MT'): 5.0,
('HR', 13.0, 'NL'): 9.0,
('HR', 13.0, 'PL'): 8.0,
('HR', 13.0, 'PT'): 6.0,
('HR', 13.0, 'RO'): 5.0,
('HR', 13.0, 'SE'): 6.0,
('HR', 13.0, 'SI'): 9.5,
('HR', 13.0, 'SK'): 10.0,
('HR', 25.0, 'AT'): 20.0,
('HR', 25.0, 'BE'): 21.0,
('HR', 25.0, 'BG'): 20.0,
('HR', 25.0, 'CY'): 19.0,
('HR', 25.0, 'CZ'): 21.0,
('HR', 25.0, 'DE'): 19.0,
('HR', 25.0, 'DK'): 25.0,
('HR', 25.0, 'EE'): 20.0,
('HR', 25.0, 'ES'): 21.0,
('HR', 25.0, 'FI'): 24.0,
('HR', 25.0, 'FR'): 20.0,
('HR', 25.0, 'GR'): 24.0,
('HR', 25.0, 'HU'): 27.0,
('HR', 25.0, 'IE'): 23.0,
('HR', 25.0, 'IT'): 22.0,
('HR', 25.0, 'LT'): 21.0,
('HR', 25.0, 'LU'): 16.0,
('HR', 25.0, 'LV'): 21.0,
('HR', 25.0, 'MT'): 18.0,
('HR', 25.0, 'NL'): 21.0,
('HR', 25.0, 'PL'): 23.0,
('HR', 25.0, 'PT'): 23.0,
('HR', 25.0, 'RO'): 19.0,
('HR', 25.0, 'SE'): 25.0,
('HR', 25.0, 'SI'): 22.0,
('HR', 25.0, 'SK'): 20.0,
('HR', 5.0, 'AT'): 10.0,
('HR', 5.0, 'BE'): 6.0,
('HR', 5.0, 'BG'): 20.0,
('HR', 5.0, 'CY'): 5.0,
('HR', 5.0, 'CZ'): 15.0,
('HR', 5.0, 'DE'): 7.0,
('HR', 5.0, 'DK'): 25.0,
('HR', 5.0, 'EE'): 9.0,
('HR', 5.0, 'ES'): 10.0,
('HR', 5.0, 'FI'): 10.0,
('HR', 5.0, 'FR'): 5.5,
('HR', 5.0, 'GR'): 13.0,
('HR', 5.0, 'HU'): 5.0,
('HR', 5.0, 'IE'): 13.5,
('HR', 5.0, 'IT'): 4.0,
('HR', 5.0, 'LT'): 5.0,
('HR', 5.0, 'LU'): 7.0,
('HR', 5.0, 'LV'): 12.0,
('HR', 5.0, 'MT'): 5.0,
('HR', 5.0, 'NL'): 9.0,
('HR', 5.0, 'PL'): 8.0,
('HR', 5.0, 'PT'): 6.0,
('HR', 5.0, 'RO'): 5.0,
('HR', 5.0, 'SE'): 6.0,
('HR', 5.0, 'SI'): 9.5,
('HR', 5.0, 'SK'): 10.0,
('HU', 18.0, 'AT'): 10.0,
('HU', 18.0, 'BE'): 6.0,
('HU', 18.0, 'BG'): 20.0,
('HU', 18.0, 'CY'): 5.0,
('HU', 18.0, 'CZ'): 15.0,
('HU', 18.0, 'DE'): 7.0,
('HU', 18.0, 'DK'): 25.0,
('HU', 18.0, 'EE'): 9.0,
('HU', 18.0, 'ES'): 10.0,
('HU', 18.0, 'FI'): 10.0,
('HU', 18.0, 'FR'): 5.5,
('HU', 18.0, 'GR'): 13.0,
('HU', 18.0, 'HR'): 13.0,
('HU', 18.0, 'IE'): 13.5,
('HU', 18.0, 'IT'): 10.0,
('HU', 18.0, 'LT'): 5.0,
('HU', 18.0, 'LU'): 7.0,
('HU', 18.0, 'LV'): 12.0,
('HU', 18.0, 'MT'): 5.0,
('HU', 18.0, 'NL'): 9.0,
('HU', 18.0, 'PL'): 8.0,
('HU', 18.0, 'PT'): 6.0,
('HU', 18.0, 'RO'): 5.0,
('HU', 18.0, 'SE'): 6.0,
('HU', 18.0, 'SI'): 9.5,
('HU', 18.0, 'SK'): 10.0,
('HU', 27.0, 'AT'): 20.0,
('HU', 27.0, 'BE'): 21.0,
('HU', 27.0, 'BG'): 20.0,
('HU', 27.0, 'CY'): 19.0,
('HU', 27.0, 'CZ'): 21.0,
('HU', 27.0, 'DE'): 19.0,
('HU', 27.0, 'DK'): 25.0,
('HU', 27.0, 'EE'): 20.0,
('HU', 27.0, 'ES'): 21.0,
('HU', 27.0, 'FI'): 24.0,
('HU', 27.0, 'FR'): 20.0,
('HU', 27.0, 'GR'): 24.0,
('HU', 27.0, 'HR'): 25.0,
('HU', 27.0, 'IE'): 23.0,
('HU', 27.0, 'IT'): 22.0,
('HU', 27.0, 'LT'): 21.0,
('HU', 27.0, 'LU'): 16.0,
('HU', 27.0, 'LV'): 21.0,
('HU', 27.0, 'MT'): 18.0,
('HU', 27.0, 'NL'): 21.0,
('HU', 27.0, 'PL'): 23.0,
('HU', 27.0, 'PT'): 23.0,
('HU', 27.0, 'RO'): 19.0,
('HU', 27.0, 'SE'): 25.0,
('HU', 27.0, 'SI'): 22.0,
('HU', 27.0, 'SK'): 20.0,
('HU', 5.0, 'AT'): 10.0,
('HU', 5.0, 'BE'): 6.0,
('HU', 5.0, 'BG'): 20.0,
('HU', 5.0, 'CY'): 5.0,
('HU', 5.0, 'CZ'): 15.0,
('HU', 5.0, 'DE'): 7.0,
('HU', 5.0, 'DK'): 25.0,
('HU', 5.0, 'EE'): 9.0,
('HU', 5.0, 'ES'): 10.0,
('HU', 5.0, 'FI'): 10.0,
('HU', 5.0, 'FR'): 5.5,
('HU', 5.0, 'GR'): 13.0,
('HU', 5.0, 'HR'): 5.0,
('HU', 5.0, 'IE'): 13.5,
('HU', 5.0, 'IT'): 4.0,
('HU', 5.0, 'LT'): 5.0,
('HU', 5.0, 'LU'): 7.0,
('HU', 5.0, 'LV'): 12.0,
('HU', 5.0, 'MT'): 5.0,
('HU', 5.0, 'NL'): 9.0,
('HU', 5.0, 'PL'): 8.0,
('HU', 5.0, 'PT'): 6.0,
('HU', 5.0, 'RO'): 5.0,
('HU', 5.0, 'SE'): 6.0,
('HU', 5.0, 'SI'): 9.5,
('HU', 5.0, 'SK'): 10.0,
('IE', 13.5, 'AT'): 20.0,
('IE', 13.5, 'BE'): 21.0,
('IE', 13.5, 'BG'): 20.0,
('IE', 13.5, 'CY'): 19.0,
('IE', 13.5, 'CZ'): 21.0,
('IE', 13.5, 'DE'): 19.0,
('IE', 13.5, 'DK'): 25.0,
('IE', 13.5, 'EE'): 20.0,
('IE', 13.5, 'ES'): 21.0,
('IE', 13.5, 'FI'): 24.0,
('IE', 13.5, 'FR'): 20.0,
('IE', 13.5, 'GR'): 24.0,
('IE', 13.5, 'HR'): 25.0,
('IE', 13.5, 'HU'): 27.0,
('IE', 13.5, 'IE'): 23.0,
('IE', 13.5, 'IT'): 22.0,
('IE', 13.5, 'LT'): 21.0,
('IE', 13.5, 'LU'): 16.0,
('IE', 13.5, 'LV'): 21.0,
('IE', 13.5, 'MT'): 18.0,
('IE', 13.5, 'NL'): 21.0,
('IE', 13.5, 'PL'): 23.0,
('IE', 13.5, 'PT'): 23.0,
('IE', 13.5, 'RO'): 19.0,
('IE', 13.5, 'SE'): 25.0,
('IE', 13.5, 'SI'): 22.0,
('IE', 13.5, 'SK'): 20.0,
('IE', 23.0, 'AT'): 20.0,
('IE', 23.0, 'BE'): 21.0,
('IE', 23.0, 'BG'): 20.0,
('IE', 23.0, 'CY'): 19.0,
('IE', 23.0, 'CZ'): 21.0,
('IE', 23.0, 'DE'): 19.0,
('IE', 23.0, 'DK'): 25.0,
('IE', 23.0, 'EE'): 20.0,
('IE', 23.0, 'ES'): 21.0,
('IE', 23.0, 'FI'): 24.0,
('IE', 23.0, 'FR'): 20.0,
('IE', 23.0, 'GR'): 24.0,
('IE', 23.0, 'HR'): 25.0,
('IE', 23.0, 'HU'): 27.0,
('IE', 23.0, 'IT'): 22.0,
('IE', 23.0, 'LT'): 21.0,
('IE', 23.0, 'LU'): 16.0,
('IE', 23.0, 'LV'): 21.0,
('IE', 23.0, 'MT'): 18.0,
('IE', 23.0, 'NL'): 21.0,
('IE', 23.0, 'PL'): 23.0,
('IE', 23.0, 'PT'): 23.0,
('IE', 23.0, 'RO'): 19.0,
('IE', 23.0, 'SE'): 25.0,
('IE', 23.0, 'SI'): 22.0,
('IE', 23.0, 'SK'): 20.0,
('IE', 4.8, 'AT'): 10.0,
('IE', 4.8, 'BE'): 6.0,
('IE', 4.8, 'BG'): 20.0,
('IE', 4.8, 'CY'): 5.0,
('IE', 4.8, 'CZ'): 15.0,
('IE', 4.8, 'DE'): 7.0,
('IE', 4.8, 'DK'): 25.0,
('IE', 4.8, 'EE'): 9.0,
('IE', 4.8, 'ES'): 4.0,
('IE', 4.8, 'FI'): 10.0,
('IE', 4.8, 'FR'): 5.5,
('IE', 4.8, 'GR'): 13.0,
('IE', 4.8, 'HR'): 5.0,
('IE', 4.8, 'HU'): 5.0,
('IE', 4.8, 'IT'): 4.0,
('IE', 4.8, 'LT'): 5.0,
('IE', 4.8, 'LU'): 7.0,
('IE', 4.8, 'LV'): 12.0,
('IE', 4.8, 'MT'): 5.0,
('IE', 4.8, 'NL'): 9.0,
('IE', 4.8, 'PL'): 8.0,
('IE', 4.8, 'PT'): 6.0,
('IE', 4.8, 'RO'): 5.0,
('IE', 4.8, 'SE'): 6.0,
('IE', 4.8, 'SI'): 9.5,
('IE', 4.8, 'SK'): 10.0,
('IE', 9.0, 'AT'): 10.0,
('IE', 9.0, 'BE'): 6.0,
('IE', 9.0, 'BG'): 20.0,
('IE', 9.0, 'CY'): 5.0,
('IE', 9.0, 'CZ'): 15.0,
('IE', 9.0, 'DE'): 7.0,
('IE', 9.0, 'DK'): 25.0,
('IE', 9.0, 'EE'): 9.0,
('IE', 9.0, 'ES'): 10.0,
('IE', 9.0, 'FI'): 10.0,
('IE', 9.0, 'FR'): 5.5,
('IE', 9.0, 'GR'): 13.0,
('IE', 9.0, 'HR'): 5.0,
('IE', 9.0, 'HU'): 5.0,
('IE', 9.0, 'IT'): 10.0,
('IE', 9.0, 'LT'): 5.0,
('IE', 9.0, 'LU'): 7.0,
('IE', 9.0, 'LV'): 12.0,
('IE', 9.0, 'MT'): 5.0,
('IE', 9.0, 'NL'): 9.0,
('IE', 9.0, 'PL'): 8.0,
('IE', 9.0, 'PT'): 6.0,
('IE', 9.0, 'RO'): 5.0,
('IE', 9.0, 'SE'): 6.0,
('IE', 9.0, 'SI'): 9.5,
('IE', 9.0, 'SK'): 10.0,
('IT', 10.0, 'AT'): 10.0,
('IT', 10.0, 'BE'): 6.0,
('IT', 10.0, 'BG'): 20.0,
('IT', 10.0, 'CY'): 5.0,
('IT', 10.0, 'CZ'): 15.0,
('IT', 10.0, 'DE'): 7.0,
('IT', 10.0, 'DK'): 25.0,
('IT', 10.0, 'EE'): 9.0,
('IT', 10.0, 'ES'): 10.0,
('IT', 10.0, 'FI'): 10.0,
('IT', 10.0, 'FR'): 5.5,
('IT', 10.0, 'GR'): 13.0,
('IT', 10.0, 'HR'): 13.0,
('IT', 10.0, 'HU'): 5.0,
('IT', 10.0, 'IE'): 13.5,
('IT', 10.0, 'LT'): 5.0,
('IT', 10.0, 'LU'): 7.0,
('IT', 10.0, 'LV'): 12.0,
('IT', 10.0, 'MT'): 5.0,
('IT', 10.0, 'NL'): 9.0,
('IT', 10.0, 'PL'): 8.0,
('IT', 10.0, 'PT'): 6.0,
('IT', 10.0, 'RO'): 5.0,
('IT', 10.0, 'SE'): 6.0,
('IT', 10.0, 'SI'): 9.5,
('IT', 10.0, 'SK'): 10.0,
('IT', 22.0, 'AT'): 20.0,
('IT', 22.0, 'BE'): 21.0,
('IT', 22.0, 'BG'): 20.0,
('IT', 22.0, 'CY'): 19.0,
('IT', 22.0, 'CZ'): 21.0,
('IT', 22.0, 'DE'): 19.0,
('IT', 22.0, 'DK'): 25.0,
('IT', 22.0, 'EE'): 20.0,
('IT', 22.0, 'ES'): 21.0,
('IT', 22.0, 'FI'): 24.0,
('IT', 22.0, 'FR'): 20.0,
('IT', 22.0, 'GR'): 24.0,
('IT', 22.0, 'HR'): 25.0,
('IT', 22.0, 'HU'): 27.0,
('IT', 22.0, 'IE'): 23.0,
('IT', 22.0, 'LT'): 21.0,
('IT', 22.0, 'LU'): 16.0,
('IT', 22.0, 'LV'): 21.0,
('IT', 22.0, 'MT'): 18.0,
('IT', 22.0, 'NL'): 21.0,
('IT', 22.0, 'PL'): 23.0,
('IT', 22.0, 'PT'): 23.0,
('IT', 22.0, 'RO'): 19.0,
('IT', 22.0, 'SE'): 25.0,
('IT', 22.0, 'SI'): 22.0,
('IT', 22.0, 'SK'): 20.0,
('IT', 4.0, 'AT'): 10.0,
('IT', 4.0, 'BE'): 6.0,
('IT', 4.0, 'BG'): 20.0,
('IT', 4.0, 'CY'): 5.0,
('IT', 4.0, 'CZ'): 15.0,
('IT', 4.0, 'DE'): 7.0,
('IT', 4.0, 'DK'): 25.0,
('IT', 4.0, 'EE'): 9.0,
('IT', 4.0, 'ES'): 4.0,
('IT', 4.0, 'FI'): 10.0,
('IT', 4.0, 'FR'): 5.5,
('IT', 4.0, 'GR'): 13.0,
('IT', 4.0, 'HR'): 5.0,
('IT', 4.0, 'HU'): 5.0,
('IT', 4.0, 'IE'): 4.8,
('IT', 4.0, 'LT'): 5.0,
('IT', 4.0, 'LU'): 7.0,
('IT', 4.0, 'LV'): 12.0,
('IT', 4.0, 'MT'): 5.0,
('IT', 4.0, 'NL'): 9.0,
('IT', 4.0, 'PL'): 8.0,
('IT', 4.0, 'PT'): 6.0,
('IT', 4.0, 'RO'): 5.0,
('IT', 4.0, 'SE'): 6.0,
('IT', 4.0, 'SI'): 9.5,
('IT', 4.0, 'SK'): 10.0,
('IT', 5.0, 'AT'): 10.0,
('IT', 5.0, 'BE'): 6.0,
('IT', 5.0, 'BG'): 20.0,
('IT', 5.0, 'CY'): 5.0,
('IT', 5.0, 'CZ'): 15.0,
('IT', 5.0, 'DE'): 7.0,
('IT', 5.0, 'DK'): 25.0,
('IT', 5.0, 'EE'): 9.0,
('IT', 5.0, 'ES'): 10.0,
('IT', 5.0, 'FI'): 10.0,
('IT', 5.0, 'FR'): 5.5,
('IT', 5.0, 'GR'): 13.0,
('IT', 5.0, 'HR'): 5.0,
('IT', 5.0, 'HU'): 5.0,
('IT', 5.0, 'IE'): 13.5,
('IT', 5.0, 'LT'): 5.0,
('IT', 5.0, 'LU'): 7.0,
('IT', 5.0, 'LV'): 12.0,
('IT', 5.0, 'MT'): 5.0,
('IT', 5.0, 'NL'): 9.0,
('IT', 5.0, 'PL'): 8.0,
('IT', 5.0, 'PT'): 6.0,
('IT', 5.0, 'RO'): 5.0,
('IT', 5.0, 'SE'): 6.0,
('IT', 5.0, 'SI'): 9.5,
('IT', 5.0, 'SK'): 10.0,
('LT', 21.0, 'AT'): 20.0,
('LT', 21.0, 'BE'): 21.0,
('LT', 21.0, 'BG'): 20.0,
('LT', 21.0, 'CY'): 19.0,
('LT', 21.0, 'CZ'): 21.0,
('LT', 21.0, 'DE'): 19.0,
('LT', 21.0, 'DK'): 25.0,
('LT', 21.0, 'EE'): 20.0,
('LT', 21.0, 'ES'): 21.0,
('LT', 21.0, 'FI'): 24.0,
('LT', 21.0, 'FR'): 20.0,
('LT', 21.0, 'GR'): 24.0,
('LT', 21.0, 'HR'): 25.0,
('LT', 21.0, 'HU'): 27.0,
('LT', 21.0, 'IE'): 23.0,
('LT', 21.0, 'IT'): 22.0,
('LT', 21.0, 'LU'): 16.0,
('LT', 21.0, 'LV'): 21.0,
('LT', 21.0, 'MT'): 18.0,
('LT', 21.0, 'NL'): 21.0,
('LT', 21.0, 'PL'): 23.0,
('LT', 21.0, 'PT'): 23.0,
('LT', 21.0, 'RO'): 19.0,
('LT', 21.0, 'SE'): 25.0,
('LT', 21.0, 'SI'): 22.0,
('LT', 21.0, 'SK'): 20.0,
('LT', 5.0, 'AT'): 10.0,
('LT', 5.0, 'BE'): 6.0,
('LT', 5.0, 'BG'): 20.0,
('LT', 5.0, 'CY'): 5.0,
('LT', 5.0, 'CZ'): 15.0,
('LT', 5.0, 'DE'): 7.0,
('LT', 5.0, 'DK'): 25.0,
('LT', 5.0, 'EE'): 9.0,
('LT', 5.0, 'ES'): 10.0,
('LT', 5.0, 'FI'): 10.0,
('LT', 5.0, 'FR'): 5.5,
('LT', 5.0, 'GR'): 13.0,
('LT', 5.0, 'HR'): 5.0,
('LT', 5.0, 'HU'): 5.0,
('LT', 5.0, 'IE'): 13.5,
('LT', 5.0, 'IT'): 4.0,
('LT', 5.0, 'LU'): 7.0,
('LT', 5.0, 'LV'): 12.0,
('LT', 5.0, 'MT'): 5.0,
('LT', 5.0, 'NL'): 9.0,
('LT', 5.0, 'PL'): 8.0,
('LT', 5.0, 'PT'): 6.0,
('LT', 5.0, 'RO'): 5.0,
('LT', 5.0, 'SE'): 6.0,
('LT', 5.0, 'SI'): 9.5,
('LT', 5.0, 'SK'): 10.0,
('LT', 9.0, 'AT'): 10.0,
('LT', 9.0, 'BE'): 6.0,
('LT', 9.0, 'BG'): 20.0,
('LT', 9.0, 'CY'): 5.0,
('LT', 9.0, 'CZ'): 15.0,
('LT', 9.0, 'DE'): 7.0,
('LT', 9.0, 'DK'): 25.0,
('LT', 9.0, 'EE'): 9.0,
('LT', 9.0, 'ES'): 10.0,
('LT', 9.0, 'FI'): 10.0,
('LT', 9.0, 'FR'): 5.5,
('LT', 9.0, 'GR'): 13.0,
('LT', 9.0, 'HR'): 13.0,
('LT', 9.0, 'HU'): 5.0,
('LT', 9.0, 'IE'): 13.5,
('LT', 9.0, 'IT'): 10.0,
('LT', 9.0, 'LU'): 7.0,
('LT', 9.0, 'LV'): 12.0,
('LT', 9.0, 'MT'): 5.0,
('LT', 9.0, 'NL'): 9.0,
('LT', 9.0, 'PL'): 8.0,
('LT', 9.0, 'PT'): 6.0,
('LT', 9.0, 'RO'): 5.0,
('LT', 9.0, 'SE'): 6.0,
('LT', 9.0, 'SI'): 9.5,
('LT', 9.0, 'SK'): 10.0,
('LU', 13.0, 'AT'): 20.0,
('LU', 13.0, 'BE'): 21.0,
('LU', 13.0, 'BG'): 20.0,
('LU', 13.0, 'CY'): 19.0,
('LU', 13.0, 'CZ'): 21.0,
('LU', 13.0, 'DE'): 19.0,
('LU', 13.0, 'DK'): 25.0,
('LU', 13.0, 'EE'): 20.0,
('LU', 13.0, 'ES'): 21.0,
('LU', 13.0, 'FI'): 24.0,
('LU', 13.0, 'FR'): 20.0,
('LU', 13.0, 'GR'): 24.0,
('LU', 13.0, 'HR'): 25.0,
('LU', 13.0, 'HU'): 27.0,
('LU', 13.0, 'IE'): 23.0,
('LU', 13.0, 'IT'): 22.0,
('LU', 13.0, 'LT'): 21.0,
('LU', 13.0, 'LV'): 21.0,
('LU', 13.0, 'MT'): 18.0,
('LU', 13.0, 'NL'): 21.0,
('LU', 13.0, 'PL'): 23.0,
('LU', 13.0, 'PT'): 23.0,
('LU', 13.0, 'RO'): 21.0,
('LU', 13.0, 'SE'): 18.0,
('LU', 13.0, 'SI'): 21.0,
('LU', 13.0, 'SK'): 23.0,
('LU', 14.0, 'AT'): 20.0,
('LU', 14.0, 'BE'): 21.0,
('LU', 14.0, 'BG'): 20.0,
('LU', 14.0, 'CY'): 19.0,
('LU', 14.0, 'CZ'): 21.0,
('LU', 14.0, 'DE'): 19.0,
('LU', 14.0, 'DK'): 25.0,
('LU', 14.0, 'EE'): 20.0,
('LU', 14.0, 'ES'): 21.0,
('LU', 14.0, 'FI'): 24.0,
('LU', 14.0, 'FR'): 20.0,
('LU', 14.0, 'GR'): 24.0,
('LU', 14.0, 'HR'): 25.0,
('LU', 14.0, 'HU'): 27.0,
('LU', 14.0, 'IE'): 23.0,
('LU', 14.0, 'IT'): 22.0,
('LU', 14.0, 'LT'): 21.0,
('LU', 14.0, 'LV'): 21.0,
('LU', 14.0, 'MT'): 18.0,
('LU', 14.0, 'NL'): 21.0,
('LU', 14.0, 'PL'): 23.0,
('LU', 14.0, 'PT'): 23.0,
('LU', 14.0, 'RO'): 21.0,
('LU', 14.0, 'SE'): 18.0,
('LU', 14.0, 'SI'): 21.0,
('LU', 14.0, 'SK'): 23.0,
('LU', 16.0, 'AT'): 20.0,
('LU', 16.0, 'BE'): 21.0,
('LU', 16.0, 'BG'): 20.0,
('LU', 16.0, 'CY'): 19.0,
('LU', 16.0, 'CZ'): 21.0,
('LU', 16.0, 'DE'): 19.0,
('LU', 16.0, 'DK'): 25.0,
('LU', 16.0, 'EE'): 20.0,
('LU', 16.0, 'ES'): 21.0,
('LU', 16.0, 'FI'): 24.0,
('LU', 16.0, 'FR'): 20.0,
('LU', 16.0, 'GR'): 24.0,
('LU', 16.0, 'HR'): 25.0,
('LU', 16.0, 'HU'): 27.0,
('LU', 16.0, 'IE'): 23.0,
('LU', 16.0, 'IT'): 22.0,
('LU', 16.0, 'LT'): 21.0,
('LU', 16.0, 'LV'): 21.0,
('LU', 16.0, 'MT'): 18.0,
('LU', 16.0, 'NL'): 21.0,
('LU', 16.0, 'PL'): 23.0,
('LU', 16.0, 'PT'): 23.0,
('LU', 16.0, 'RO'): 19.0,
('LU', 16.0, 'SE'): 25.0,
('LU', 16.0, 'SI'): 22.0,
('LU', 16.0, 'SK'): 20.0,
('LU', 17.0, 'AT'): 20.0,
('LU', 17.0, 'BE'): 21.0,
('LU', 17.0, 'BG'): 20.0,
('LU', 17.0, 'CY'): 19.0,
('LU', 17.0, 'CZ'): 21.0,
('LU', 17.0, 'DE'): 19.0,
('LU', 17.0, 'DK'): 25.0,
('LU', 17.0, 'EE'): 20.0,
('LU', 17.0, 'ES'): 21.0,
('LU', 17.0, 'FI'): 24.0,
('LU', 17.0, 'FR'): 20.0,
('LU', 17.0, 'GR'): 24.0,
('LU', 17.0, 'HR'): 25.0,
('LU', 17.0, 'HU'): 27.0,
('LU', 17.0, 'IE'): 23.0,
('LU', 17.0, 'IT'): 22.0,
('LU', 17.0, 'LT'): 21.0,
('LU', 17.0, 'LV'): 21.0,
('LU', 17.0, 'MT'): 18.0,
('LU', 17.0, 'NL'): 21.0,
('LU', 17.0, 'PL'): 23.0,
('LU', 17.0, 'PT'): 23.0,
('LU', 17.0, 'RO'): 19.0,
('LU', 17.0, 'SE'): 25.0,
('LU', 17.0, 'SI'): 22.0,
('LU', 17.0, 'SK'): 20.0,
('LU', 3.0, 'AT'): 10.0,
('LU', 3.0, 'BE'): 6.0,
('LU', 3.0, 'BG'): 20.0,
('LU', 3.0, 'CY'): 5.0,
('LU', 3.0, 'CZ'): 15.0,
('LU', 3.0, 'DE'): 7.0,
('LU', 3.0, 'DK'): 25.0,
('LU', 3.0, 'EE'): 9.0,
('LU', 3.0, 'ES'): 4.0,
('LU', 3.0, 'FI'): 10.0,
('LU', 3.0, 'FR'): 5.5,
('LU', 3.0, 'GR'): 13.0,
('LU', 3.0, 'HR'): 5.0,
('LU', 3.0, 'HU'): 5.0,
('LU', 3.0, 'IE'): 4.8,
('LU', 3.0, 'IT'): 4.0,
('LU', 3.0, 'LT'): 5.0,
('LU', 3.0, 'LV'): 12.0,
('LU', 3.0, 'MT'): 5.0,
('LU', 3.0, 'NL'): 9.0,
('LU', 3.0, 'PL'): 8.0,
('LU', 3.0, 'PT'): 6.0,
('LU', 3.0, 'RO'): 5.0,
('LU', 3.0, 'SE'): 6.0,
('LU', 3.0, 'SI'): 9.5,
('LU', 3.0, 'SK'): 10.0,
('LU', 7.0, 'AT'): 10.0,
('LU', 7.0, 'BE'): 6.0,
('LU', 7.0, 'BG'): 20.0,
('LU', 7.0, 'CY'): 5.0,
('LU', 7.0, 'CZ'): 15.0,
('LU', 7.0, 'DE'): 7.0,
('LU', 7.0, 'DK'): 25.0,
('LU', 7.0, 'EE'): 9.0,
('LU', 7.0, 'ES'): 10.0,
('LU', 7.0, 'FI'): 10.0,
('LU', 7.0, 'FR'): 5.5,
('LU', 7.0, 'GR'): 13.0,
('LU', 7.0, 'HR'): 5.0,
('LU', 7.0, 'HU'): 5.0,
('LU', 7.0, 'IE'): 13.5,
('LU', 7.0, 'IT'): 10.0,
('LU', 7.0, 'LT'): 5.0,
('LU', 7.0, 'LV'): 12.0,
('LU', 7.0, 'MT'): 5.0,
('LU', 7.0, 'NL'): 9.0,
('LU', 7.0, 'PL'): 7.0,
('LU', 7.0, 'PT'): 6.0,
('LU', 7.0, 'RO'): 5.0,
('LU', 7.0, 'SE'): 6.0,
('LU', 7.0, 'SI'): 9.5,
('LU', 7.0, 'SK'): 10.0,
('LU', 8.0, 'AT'): 10.0,
('LU', 8.0, 'BE'): 6.0,
('LU', 8.0, 'BG'): 20.0,
('LU', 8.0, 'CY'): 5.0,
('LU', 8.0, 'CZ'): 15.0,
('LU', 8.0, 'DE'): 7.0,
('LU', 8.0, 'DK'): 25.0,
('LU', 8.0, 'EE'): 9.0,
('LU', 8.0, 'ES'): 10.0,
('LU', 8.0, 'FI'): 10.0,
('LU', 8.0, 'FR'): 5.5,
('LU', 8.0, 'GR'): 13.0,
('LU', 8.0, 'HR'): 5.0,
('LU', 8.0, 'HU'): 5.0,
('LU', 8.0, 'IE'): 13.5,
('LU', 8.0, 'IT'): 10.0,
('LU', 8.0, 'LT'): 5.0,
('LU', 8.0, 'LV'): 12.0,
('LU', 8.0, 'MT'): 5.0,
('LU', 8.0, 'NL'): 9.0,
('LU', 8.0, 'PL'): 8.0,
('LU', 8.0, 'PT'): 6.0,
('LU', 8.0, 'RO'): 5.0,
('LU', 8.0, 'SE'): 6.0,
('LU', 8.0, 'SI'): 9.5,
('LU', 8.0, 'SK'): 10.0,
('LV', 12.0, 'AT'): 10.0,
('LV', 12.0, 'BE'): 6.0,
('LV', 12.0, 'BG'): 20.0,
('LV', 12.0, 'CY'): 5.0,
('LV', 12.0, 'CZ'): 15.0,
('LV', 12.0, 'DE'): 7.0,
('LV', 12.0, 'DK'): 25.0,
('LV', 12.0, 'EE'): 9.0,
('LV', 12.0, 'ES'): 10.0,
('LV', 12.0, 'FI'): 10.0,
('LV', 12.0, 'FR'): 5.5,
('LV', 12.0, 'GR'): 13.0,
('LV', 12.0, 'HR'): 13.0,
('LV', 12.0, 'HU'): 5.0,
('LV', 12.0, 'IE'): 13.5,
('LV', 12.0, 'IT'): 10.0,
('LV', 12.0, 'LT'): 5.0,
('LV', 12.0, 'LU'): 7.0,
('LV', 12.0, 'MT'): 5.0,
('LV', 12.0, 'NL'): 9.0,
('LV', 12.0, 'PL'): 8.0,
('LV', 12.0, 'PT'): 6.0,
('LV', 12.0, 'RO'): 5.0,
('LV', 12.0, 'SE'): 6.0,
('LV', 12.0, 'SI'): 9.5,
('LV', 12.0, 'SK'): 10.0,
('LV', 21.0, 'AT'): 20.0,
('LV', 21.0, 'BE'): 21.0,
('LV', 21.0, 'BG'): 20.0,
('LV', 21.0, 'CY'): 19.0,
('LV', 21.0, 'CZ'): 21.0,
('LV', 21.0, 'DE'): 19.0,
('LV', 21.0, 'DK'): 25.0,
('LV', 21.0, 'EE'): 20.0,
('LV', 21.0, 'ES'): 21.0,
('LV', 21.0, 'FI'): 24.0,
('LV', 21.0, 'FR'): 20.0,
('LV', 21.0, 'GR'): 24.0,
('LV', 21.0, 'HR'): 25.0,
('LV', 21.0, 'HU'): 27.0,
('LV', 21.0, 'IE'): 23.0,
('LV', 21.0, 'IT'): 22.0,
('LV', 21.0, 'LT'): 21.0,
('LV', 21.0, 'LU'): 16.0,
('LV', 21.0, 'MT'): 18.0,
('LV', 21.0, 'NL'): 21.0,
('LV', 21.0, 'PL'): 23.0,
('LV', 21.0, 'PT'): 23.0,
('LV', 21.0, 'RO'): 19.0,
('LV', 21.0, 'SE'): 25.0,
('LV', 21.0, 'SI'): 22.0,
('LV', 21.0, 'SK'): 20.0,
('LV', 5.0, 'AT'): 10.0,
('LV', 5.0, 'BE'): 6.0,
('LV', 5.0, 'BG'): 20.0,
('LV', 5.0, 'CY'): 5.0,
('LV', 5.0, 'CZ'): 15.0,
('LV', 5.0, 'DE'): 7.0,
('LV', 5.0, 'DK'): 25.0,
('LV', 5.0, 'EE'): 9.0,
('LV', 5.0, 'ES'): 10.0,
('LV', 5.0, 'FI'): 10.0,
('LV', 5.0, 'FR'): 5.5,
('LV', 5.0, 'GR'): 13.0,
('LV', 5.0, 'HR'): 5.0,
('LV', 5.0, 'HU'): 5.0,
('LV', 5.0, 'IE'): 13.5,
('LV', 5.0, 'IT'): 4.0,
('LV', 5.0, 'LT'): 5.0,
('LV', 5.0, 'LU'): 7.0,
('LV', 5.0, 'MT'): 5.0,
('LV', 5.0, 'NL'): 9.0,
('LV', 5.0, 'PL'): 8.0,
('LV', 5.0, 'PT'): 6.0,
('LV', 5.0, 'RO'): 5.0,
('LV', 5.0, 'SE'): 6.0,
('LV', 5.0, 'SI'): 9.5,
('LV', 5.0, 'SK'): 10.0,
('MT', 18.0, 'AT'): 20.0,
('MT', 18.0, 'BE'): 21.0,
('MT', 18.0, 'BG'): 20.0,
('MT', 18.0, 'CY'): 19.0,
('MT', 18.0, 'CZ'): 21.0,
('MT', 18.0, 'DE'): 19.0,
('MT', 18.0, 'DK'): 25.0,
('MT', 18.0, 'EE'): 20.0,
('MT', 18.0, 'ES'): 21.0,
('MT', 18.0, 'FI'): 24.0,
('MT', 18.0, 'FR'): 20.0,
('MT', 18.0, 'GR'): 24.0,
('MT', 18.0, 'HR'): 25.0,
('MT', 18.0, 'HU'): 27.0,
('MT', 18.0, 'IE'): 23.0,
('MT', 18.0, 'IT'): 22.0,
('MT', 18.0, 'LT'): 21.0,
('MT', 18.0, 'LU'): 16.0,
('MT', 18.0, 'LV'): 21.0,
('MT', 18.0, 'NL'): 21.0,
('MT', 18.0, 'PL'): 23.0,
('MT', 18.0, 'PT'): 23.0,
('MT', 18.0, 'RO'): 19.0,
('MT', 18.0, 'SE'): 25.0,
('MT', 18.0, 'SI'): 22.0,
('MT', 18.0, 'SK'): 20.0,
('MT', 5.0, 'AT'): 10.0,
('MT', 5.0, 'BE'): 6.0,
('MT', 5.0, 'BG'): 20.0,
('MT', 5.0, 'CY'): 5.0,
('MT', 5.0, 'CZ'): 15.0,
('MT', 5.0, 'DE'): 7.0,
('MT', 5.0, 'DK'): 25.0,
('MT', 5.0, 'EE'): 9.0,
('MT', 5.0, 'ES'): 10.0,
('MT', 5.0, 'FI'): 10.0,
('MT', 5.0, 'FR'): 5.5,
('MT', 5.0, 'GR'): 13.0,
('MT', 5.0, 'HR'): 5.0,
('MT', 5.0, 'HU'): 5.0,
('MT', 5.0, 'IE'): 13.5,
('MT', 5.0, 'IT'): 4.0,
('MT', 5.0, 'LT'): 5.0,
('MT', 5.0, 'LU'): 7.0,
('MT', 5.0, 'LV'): 12.0,
('MT', 5.0, 'NL'): 9.0,
('MT', 5.0, 'PL'): 8.0,
('MT', 5.0, 'PT'): 6.0,
('MT', 5.0, 'RO'): 5.0,
('MT', 5.0, 'SE'): 6.0,
('MT', 5.0, 'SI'): 9.5,
('MT', 5.0, 'SK'): 10.0,
('MT', 7.0, 'AT'): 10.0,
('MT', 7.0, 'BE'): 6.0,
('MT', 7.0, 'BG'): 20.0,
('MT', 7.0, 'CY'): 5.0,
('MT', 7.0, 'CZ'): 15.0,
('MT', 7.0, 'DE'): 7.0,
('MT', 7.0, 'DK'): 25.0,
('MT', 7.0, 'EE'): 9.0,
('MT', 7.0, 'ES'): 10.0,
('MT', 7.0, 'FI'): 10.0,
('MT', 7.0, 'FR'): 5.5,
('MT', 7.0, 'GR'): 13.0,
('MT', 7.0, 'HR'): 5.0,
('MT', 7.0, 'HU'): 5.0,
('MT', 7.0, 'IE'): 13.5,
('MT', 7.0, 'IT'): 10.0,
('MT', 7.0, 'LT'): 5.0,
('MT', 7.0, 'LU'): 7.0,
('MT', 7.0, 'LV'): 12.0,
('MT', 7.0, 'NL'): 9.0,
('MT', 7.0, 'PL'): 8.0,
('MT', 7.0, 'PT'): 6.0,
('MT', 7.0, 'RO'): 5.0,
('MT', 7.0, 'SE'): 6.0,
('MT', 7.0, 'SI'): 9.5,
('MT', 7.0, 'SK'): 10.0,
('NL', 21.0, 'AT'): 20.0,
('NL', 21.0, 'BE'): 21.0,
('NL', 21.0, 'BG'): 20.0,
('NL', 21.0, 'CY'): 19.0,
('NL', 21.0, 'CZ'): 21.0,
('NL', 21.0, 'DE'): 19.0,
('NL', 21.0, 'DK'): 25.0,
('NL', 21.0, 'EE'): 20.0,
('NL', 21.0, 'ES'): 21.0,
('NL', 21.0, 'FI'): 24.0,
('NL', 21.0, 'FR'): 20.0,
('NL', 21.0, 'GR'): 24.0,
('NL', 21.0, 'HR'): 25.0,
('NL', 21.0, 'HU'): 27.0,
('NL', 21.0, 'IE'): 23.0,
('NL', 21.0, 'IT'): 22.0,
('NL', 21.0, 'LT'): 21.0,
('NL', 21.0, 'LU'): 16.0,
('NL', 21.0, 'LV'): 21.0,
('NL', 21.0, 'MT'): 18.0,
('NL', 21.0, 'PL'): 23.0,
('NL', 21.0, 'PT'): 23.0,
('NL', 21.0, 'RO'): 19.0,
('NL', 21.0, 'SE'): 25.0,
('NL', 21.0, 'SI'): 22.0,
('NL', 21.0, 'SK'): 20.0,
('NL', 9.0, 'AT'): 10.0,
('NL', 9.0, 'BE'): 6.0,
('NL', 9.0, 'BG'): 20.0,
('NL', 9.0, 'CY'): 5.0,
('NL', 9.0, 'CZ'): 15.0,
('NL', 9.0, 'DE'): 7.0,
('NL', 9.0, 'DK'): 25.0,
('NL', 9.0, 'EE'): 9.0,
('NL', 9.0, 'ES'): 10.0,
('NL', 9.0, 'FI'): 10.0,
('NL', 9.0, 'FR'): 5.5,
('NL', 9.0, 'GR'): 13.0,
('NL', 9.0, 'HR'): 5.0,
('NL', 9.0, 'HU'): 5.0,
('NL', 9.0, 'IE'): 13.5,
('NL', 9.0, 'IT'): 4.0,
('NL', 9.0, 'LT'): 5.0,
('NL', 9.0, 'LU'): 7.0,
('NL', 9.0, 'LV'): 12.0,
('NL', 9.0, 'MT'): 5.0,
('NL', 9.0, 'PL'): 8.0,
('NL', 9.0, 'PT'): 6.0,
('NL', 9.0, 'RO'): 5.0,
('NL', 9.0, 'SE'): 6.0,
('NL', 9.0, 'SI'): 9.5,
('NL', 9.0, 'SK'): 10.0,
('PL', 23.0, 'AT'): 20.0,
('PL', 23.0, 'BE'): 21.0,
('PL', 23.0, 'BG'): 20.0,
('PL', 23.0, 'CY'): 19.0,
('PL', 23.0, 'CZ'): 21.0,
('PL', 23.0, 'DE'): 19.0,
('PL', 23.0, 'DK'): 25.0,
('PL', 23.0, 'EE'): 20.0,
('PL', 23.0, 'ES'): 21.0,
('PL', 23.0, 'FI'): 24.0,
('PL', 23.0, 'FR'): 20.0,
('PL', 23.0, 'GR'): 24.0,
('PL', 23.0, 'HR'): 25.0,
('PL', 23.0, 'HU'): 27.0,
('PL', 23.0, 'IE'): 23.0,
('PL', 23.0, 'IT'): 22.0,
('PL', 23.0, 'LT'): 21.0,
('PL', 23.0, 'LU'): 16.0,
('PL', 23.0, 'LV'): 21.0,
('PL', 23.0, 'MT'): 18.0,
('PL', 23.0, 'NL'): 21.0,
('PL', 23.0, 'PT'): 23.0,
('PL', 23.0, 'RO'): 19.0,
('PL', 23.0, 'SE'): 25.0,
('PL', 23.0, 'SI'): 22.0,
('PL', 23.0, 'SK'): 20.0,
('PL', 5.0, 'AT'): 10.0,
('PL', 5.0, 'BE'): 6.0,
('PL', 5.0, 'BG'): 20.0,
('PL', 5.0, 'CY'): 5.0,
('PL', 5.0, 'CZ'): 15.0,
('PL', 5.0, 'DE'): 7.0,
('PL', 5.0, 'DK'): 25.0,
('PL', 5.0, 'EE'): 9.0,
('PL', 5.0, 'ES'): 10.0,
('PL', 5.0, 'FI'): 10.0,
('PL', 5.0, 'FR'): 5.5,
('PL', 5.0, 'GR'): 13.0,
('PL', 5.0, 'HR'): 5.0,
('PL', 5.0, 'HU'): 5.0,
('PL', 5.0, 'IE'): 13.5,
('PL', 5.0, 'IT'): 4.0,
('PL', 5.0, 'LT'): 5.0,
('PL', 5.0, 'LU'): 7.0,
('PL', 5.0, 'LV'): 12.0,
('PL', 5.0, 'MT'): 5.0,
('PL', 5.0, 'NL'): 9.0,
('PL', 5.0, 'PT'): 6.0,
('PL', 5.0, 'RO'): 5.0,
('PL', 5.0, 'SE'): 6.0,
('PL', 5.0, 'SI'): 9.5,
('PL', 5.0, 'SK'): 10.0,
('PL', 8.0, 'AT'): 10.0,
('PL', 8.0, 'BE'): 6.0,
('PL', 8.0, 'BG'): 20.0,
('PL', 8.0, 'CY'): 5.0,
('PL', 8.0, 'CZ'): 15.0,
('PL', 8.0, 'DE'): 7.0,
('PL', 8.0, 'DK'): 25.0,
('PL', 8.0, 'EE'): 9.0,
('PL', 8.0, 'ES'): 10.0,
('PL', 8.0, 'FI'): 10.0,
('PL', 8.0, 'FR'): 5.5,
('PL', 8.0, 'GR'): 13.0,
('PL', 8.0, 'HR'): 5.0,
('PL', 8.0, 'HU'): 5.0,
('PL', 8.0, 'IE'): 13.5,
('PL', 8.0, 'IT'): 10.0,
('PL', 8.0, 'LT'): 5.0,
('PL', 8.0, 'LU'): 7.0,
('PL', 8.0, 'LV'): 12.0,
('PL', 8.0, 'MT'): 5.0,
('PL', 8.0, 'NL'): 9.0,
('PL', 8.0, 'PT'): 6.0,
('PL', 8.0, 'RO'): 5.0,
('PL', 8.0, 'SE'): 6.0,
('PL', 8.0, 'SI'): 9.5,
('PL', 8.0, 'SK'): 10.0,
('PT', 13.0, 'AT'): 20.0,
('PT', 13.0, 'BE'): 21.0,
('PT', 13.0, 'BG'): 20.0,
('PT', 13.0, 'CY'): 19.0,
('PT', 13.0, 'CZ'): 21.0,
('PT', 13.0, 'DE'): 19.0,
('PT', 13.0, 'DK'): 25.0,
('PT', 13.0, 'EE'): 20.0,
('PT', 13.0, 'ES'): 21.0,
('PT', 13.0, 'FI'): 24.0,
('PT', 13.0, 'FR'): 20.0,
('PT', 13.0, 'GR'): 24.0,
('PT', 13.0, 'HR'): 25.0,
('PT', 13.0, 'HU'): 27.0,
('PT', 13.0, 'IE'): 23.0,
('PT', 13.0, 'IT'): 22.0,
('PT', 13.0, 'LT'): 21.0,
('PT', 13.0, 'LU'): 16.0,
('PT', 13.0, 'LV'): 21.0,
('PT', 13.0, 'MT'): 18.0,
('PT', 13.0, 'NL'): 21.0,
('PT', 13.0, 'PL'): 23.0,
('PT', 13.0, 'RO'): 21.0,
('PT', 13.0, 'SE'): 18.0,
('PT', 13.0, 'SI'): 21.0,
('PT', 13.0, 'SK'): 23.0,
('PT', 23.0, 'AT'): 20.0,
('PT', 23.0, 'BE'): 21.0,
('PT', 23.0, 'BG'): 20.0,
('PT', 23.0, 'CY'): 19.0,
('PT', 23.0, 'CZ'): 21.0,
('PT', 23.0, 'DE'): 19.0,
('PT', 23.0, 'DK'): 25.0,
('PT', 23.0, 'EE'): 20.0,
('PT', 23.0, 'ES'): 21.0,
('PT', 23.0, 'FI'): 24.0,
('PT', 23.0, 'FR'): 20.0,
('PT', 23.0, 'GR'): 24.0,
('PT', 23.0, 'HR'): 25.0,
('PT', 23.0, 'HU'): 27.0,
('PT', 23.0, 'IE'): 23.0,
('PT', 23.0, 'IT'): 22.0,
('PT', 23.0, 'LT'): 21.0,
('PT', 23.0, 'LU'): 16.0,
('PT', 23.0, 'LV'): 21.0,
('PT', 23.0, 'MT'): 18.0,
('PT', 23.0, 'NL'): 21.0,
('PT', 23.0, 'PL'): 23.0,
('PT', 23.0, 'RO'): 19.0,
('PT', 23.0, 'SE'): 25.0,
('PT', 23.0, 'SI'): 22.0,
('PT', 23.0, 'SK'): 20.0,
('PT', 6.0, 'AT'): 10.0,
('PT', 6.0, 'BE'): 6.0,
('PT', 6.0, 'BG'): 20.0,
('PT', 6.0, 'CY'): 5.0,
('PT', 6.0, 'CZ'): 15.0,
('PT', 6.0, 'DE'): 7.0,
('PT', 6.0, 'DK'): 25.0,
('PT', 6.0, 'EE'): 9.0,
('PT', 6.0, 'ES'): 10.0,
('PT', 6.0, 'FI'): 10.0,
('PT', 6.0, 'FR'): 5.5,
('PT', 6.0, 'GR'): 13.0,
('PT', 6.0, 'HR'): 5.0,
('PT', 6.0, 'HU'): 5.0,
('PT', 6.0, 'IE'): 13.5,
('PT', 6.0, 'IT'): 4.0,
('PT', 6.0, 'LT'): 5.0,
('PT', 6.0, 'LU'): 7.0,
('PT', 6.0, 'LV'): 12.0,
('PT', 6.0, 'MT'): 5.0,
('PT', 6.0, 'NL'): 9.0,
('PT', 6.0, 'PL'): 8.0,
('PT', 6.0, 'RO'): 5.0,
('PT', 6.0, 'SE'): 6.0,
('PT', 6.0, 'SI'): 9.5,
('PT', 6.0, 'SK'): 10.0,
('RO', 19.0, 'AT'): 20.0,
('RO', 19.0, 'BE'): 21.0,
('RO', 19.0, 'BG'): 20.0,
('RO', 19.0, 'CY'): 19.0,
('RO', 19.0, 'CZ'): 21.0,
('RO', 19.0, 'DE'): 19.0,
('RO', 19.0, 'DK'): 25.0,
('RO', 19.0, 'EE'): 20.0,
('RO', 19.0, 'ES'): 21.0,
('RO', 19.0, 'FI'): 24.0,
('RO', 19.0, 'FR'): 20.0,
('RO', 19.0, 'GR'): 24.0,
('RO', 19.0, 'HR'): 25.0,
('RO', 19.0, 'HU'): 27.0,
('RO', 19.0, 'IE'): 23.0,
('RO', 19.0, 'IT'): 22.0,
('RO', 19.0, 'LT'): 21.0,
('RO', 19.0, 'LU'): 16.0,
('RO', 19.0, 'LV'): 21.0,
('RO', 19.0, 'MT'): 18.0,
('RO', 19.0, 'NL'): 21.0,
('RO', 19.0, 'PL'): 23.0,
('RO', 19.0, 'PT'): 23.0,
('RO', 19.0, 'SE'): 25.0,
('RO', 19.0, 'SI'): 22.0,
('RO', 19.0, 'SK'): 20.0,
('RO', 5.0, 'AT'): 10.0,
('RO', 5.0, 'BE'): 6.0,
('RO', 5.0, 'BG'): 20.0,
('RO', 5.0, 'CY'): 5.0,
('RO', 5.0, 'CZ'): 15.0,
('RO', 5.0, 'DE'): 7.0,
('RO', 5.0, 'DK'): 25.0,
('RO', 5.0, 'EE'): 9.0,
('RO', 5.0, 'ES'): 10.0,
('RO', 5.0, 'FI'): 10.0,
('RO', 5.0, 'FR'): 5.5,
('RO', 5.0, 'GR'): 13.0,
('RO', 5.0, 'HR'): 5.0,
('RO', 5.0, 'HU'): 5.0,
('RO', 5.0, 'IE'): 13.5,
('RO', 5.0, 'IT'): 4.0,
('RO', 5.0, 'LT'): 5.0,
('RO', 5.0, 'LU'): 7.0,
('RO', 5.0, 'LV'): 12.0,
('RO', 5.0, 'MT'): 5.0,
('RO', 5.0, 'NL'): 9.0,
('RO', 5.0, 'PL'): 8.0,
('RO', 5.0, 'PT'): 6.0,
('RO', 5.0, 'SE'): 6.0,
('RO', 5.0, 'SI'): 9.5,
('RO', 5.0, 'SK'): 10.0,
('RO', 9.0, 'AT'): 10.0,
('RO', 9.0, 'BE'): 6.0,
('RO', 9.0, 'BG'): 20.0,
('RO', 9.0, 'CY'): 5.0,
('RO', 9.0, 'CZ'): 15.0,
('RO', 9.0, 'DE'): 7.0,
('RO', 9.0, 'DK'): 25.0,
('RO', 9.0, 'EE'): 9.0,
('RO', 9.0, 'ES'): 10.0,
('RO', 9.0, 'FI'): 10.0,
('RO', 9.0, 'FR'): 5.5,
('RO', 9.0, 'GR'): 13.0,
('RO', 9.0, 'HR'): 13.0,
('RO', 9.0, 'HU'): 5.0,
('RO', 9.0, 'IE'): 13.5,
('RO', 9.0, 'IT'): 10.0,
('RO', 9.0, 'LT'): 5.0,
('RO', 9.0, 'LU'): 7.0,
('RO', 9.0, 'LV'): 12.0,
('RO', 9.0, 'MT'): 5.0,
('RO', 9.0, 'NL'): 9.0,
('RO', 9.0, 'PL'): 8.0,
('RO', 9.0, 'PT'): 6.0,
('RO', 9.0, 'SE'): 6.0,
('RO', 9.0, 'SI'): 9.5,
('RO', 9.0, 'SK'): 10.0,
('SE', 12.0, 'AT'): 10.0,
('SE', 12.0, 'BE'): 6.0,
('SE', 12.0, 'BG'): 20.0,
('SE', 12.0, 'CY'): 5.0,
('SE', 12.0, 'CZ'): 15.0,
('SE', 12.0, 'DE'): 7.0,
('SE', 12.0, 'DK'): 25.0,
('SE', 12.0, 'EE'): 9.0,
('SE', 12.0, 'ES'): 10.0,
('SE', 12.0, 'FI'): 10.0,
('SE', 12.0, 'FR'): 5.5,
('SE', 12.0, 'GR'): 13.0,
('SE', 12.0, 'HR'): 13.0,
('SE', 12.0, 'HU'): 5.0,
('SE', 12.0, 'IE'): 13.5,
('SE', 12.0, 'IT'): 10.0,
('SE', 12.0, 'LT'): 5.0,
('SE', 12.0, 'LU'): 7.0,
('SE', 12.0, 'LV'): 12.0,
('SE', 12.0, 'MT'): 5.0,
('SE', 12.0, 'NL'): 9.0,
('SE', 12.0, 'PL'): 8.0,
('SE', 12.0, 'PT'): 6.0,
('SE', 12.0, 'RO'): 5.0,
('SE', 12.0, 'SI'): 9.5,
('SE', 12.0, 'SK'): 10.0,
('SE', 25.0, 'AT'): 20.0,
('SE', 25.0, 'BE'): 21.0,
('SE', 25.0, 'BG'): 20.0,
('SE', 25.0, 'CY'): 19.0,
('SE', 25.0, 'CZ'): 21.0,
('SE', 25.0, 'DE'): 19.0,
('SE', 25.0, 'DK'): 25.0,
('SE', 25.0, 'EE'): 20.0,
('SE', 25.0, 'ES'): 21.0,
('SE', 25.0, 'FI'): 24.0,
('SE', 25.0, 'FR'): 20.0,
('SE', 25.0, 'GR'): 24.0,
('SE', 25.0, 'HR'): 25.0,
('SE', 25.0, 'HU'): 27.0,
('SE', 25.0, 'IE'): 23.0,
('SE', 25.0, 'IT'): 22.0,
('SE', 25.0, 'LT'): 21.0,
('SE', 25.0, 'LU'): 16.0,
('SE', 25.0, 'LV'): 21.0,
('SE', 25.0, 'MT'): 18.0,
('SE', 25.0, 'NL'): 21.0,
('SE', 25.0, 'PL'): 23.0,
('SE', 25.0, 'PT'): 23.0,
('SE', 25.0, 'RO'): 19.0,
('SE', 25.0, 'SI'): 22.0,
('SE', 25.0, 'SK'): 20.0,
('SE', 6.0, 'AT'): 10.0,
('SE', 6.0, 'BE'): 6.0,
('SE', 6.0, 'BG'): 20.0,
('SE', 6.0, 'CY'): 5.0,
('SE', 6.0, 'CZ'): 15.0,
('SE', 6.0, 'DE'): 7.0,
('SE', 6.0, 'DK'): 25.0,
('SE', 6.0, 'EE'): 9.0,
('SE', 6.0, 'ES'): 10.0,
('SE', 6.0, 'FI'): 10.0,
('SE', 6.0, 'FR'): 5.5,
('SE', 6.0, 'GR'): 13.0,
('SE', 6.0, 'HR'): 5.0,
('SE', 6.0, 'HU'): 5.0,
('SE', 6.0, 'IE'): 13.5,
('SE', 6.0, 'IT'): 4.0,
('SE', 6.0, 'LT'): 5.0,
('SE', 6.0, 'LU'): 7.0,
('SE', 6.0, 'LV'): 12.0,
('SE', 6.0, 'MT'): 5.0,
('SE', 6.0, 'NL'): 9.0,
('SE', 6.0, 'PL'): 8.0,
('SE', 6.0, 'PT'): 6.0,
('SE', 6.0, 'RO'): 5.0,
('SE', 6.0, 'SI'): 9.5,
('SE', 6.0, 'SK'): 10.0,
('SI', 22.0, 'AT'): 20.0,
('SI', 22.0, 'BE'): 21.0,
('SI', 22.0, 'BG'): 20.0,
('SI', 22.0, 'CY'): 19.0,
('SI', 22.0, 'CZ'): 21.0,
('SI', 22.0, 'DE'): 19.0,
('SI', 22.0, 'DK'): 25.0,
('SI', 22.0, 'EE'): 20.0,
('SI', 22.0, 'ES'): 21.0,
('SI', 22.0, 'FI'): 24.0,
('SI', 22.0, 'FR'): 20.0,
('SI', 22.0, 'GR'): 24.0,
('SI', 22.0, 'HR'): 25.0,
('SI', 22.0, 'HU'): 27.0,
('SI', 22.0, 'IE'): 23.0,
('SI', 22.0, 'IT'): 22.0,
('SI', 22.0, 'LT'): 21.0,
('SI', 22.0, 'LU'): 16.0,
('SI', 22.0, 'LV'): 21.0,
('SI', 22.0, 'MT'): 18.0,
('SI', 22.0, 'NL'): 21.0,
('SI', 22.0, 'PL'): 23.0,
('SI', 22.0, 'PT'): 23.0,
('SI', 22.0, 'RO'): 19.0,
('SI', 22.0, 'SE'): 25.0,
('SI', 22.0, 'SK'): 20.0,
('SI', 5.0, 'AT'): 10.0,
('SI', 5.0, 'BE'): 6.0,
('SI', 5.0, 'BG'): 20.0,
('SI', 5.0, 'CY'): 5.0,
('SI', 5.0, 'CZ'): 15.0,
('SI', 5.0, 'DE'): 7.0,
('SI', 5.0, 'DK'): 25.0,
('SI', 5.0, 'EE'): 9.0,
('SI', 5.0, 'ES'): 10.0,
('SI', 5.0, 'FI'): 10.0,
('SI', 5.0, 'FR'): 5.5,
('SI', 5.0, 'GR'): 13.0,
('SI', 5.0, 'HR'): 5.0,
('SI', 5.0, 'HU'): 5.0,
('SI', 5.0, 'IE'): 13.5,
('SI', 5.0, 'IT'): 4.0,
('SI', 5.0, 'LT'): 5.0,
('SI', 5.0, 'LU'): 7.0,
('SI', 5.0, 'LV'): 12.0,
('SI', 5.0, 'MT'): 5.0,
('SI', 5.0, 'NL'): 9.0,
('SI', 5.0, 'PL'): 8.0,
('SI', 5.0, 'PT'): 6.0,
('SI', 5.0, 'RO'): 5.0,
('SI', 5.0, 'SE'): 6.0,
('SI', 5.0, 'SK'): 10.0,
('SI', 9.5, 'AT'): 10.0,
('SI', 9.5, 'BE'): 6.0,
('SI', 9.5, 'BG'): 20.0,
('SI', 9.5, 'CY'): 5.0,
('SI', 9.5, 'CZ'): 15.0,
('SI', 9.5, 'DE'): 7.0,
('SI', 9.5, 'DK'): 25.0,
('SI', 9.5, 'EE'): 9.0,
('SI', 9.5, 'ES'): 10.0,
('SI', 9.5, 'FI'): 10.0,
('SI', 9.5, 'FR'): 5.5,
('SI', 9.5, 'GR'): 13.0,
('SI', 9.5, 'HR'): 13.0,
('SI', 9.5, 'HU'): 5.0,
('SI', 9.5, 'IE'): 13.5,
('SI', 9.5, 'IT'): 10.0,
('SI', 9.5, 'LT'): 5.0,
('SI', 9.5, 'LU'): 7.0,
('SI', 9.5, 'LV'): 12.0,
('SI', 9.5, 'MT'): 5.0,
('SI', 9.5, 'NL'): 9.0,
('SI', 9.5, 'PL'): 8.0,
('SI', 9.5, 'PT'): 6.0,
('SI', 9.5, 'RO'): 5.0,
('SI', 9.5, 'SE'): 6.0,
('SI', 9.5, 'SK'): 10.0,
('SK', 10.0, 'AT'): 10.0,
('SK', 10.0, 'BE'): 6.0,
('SK', 10.0, 'BG'): 20.0,
('SK', 10.0, 'CY'): 5.0,
('SK', 10.0, 'CZ'): 15.0,
('SK', 10.0, 'DE'): 7.0,
('SK', 10.0, 'DK'): 25.0,
('SK', 10.0, 'EE'): 9.0,
('SK', 10.0, 'ES'): 10.0,
('SK', 10.0, 'FI'): 10.0,
('SK', 10.0, 'FR'): 5.5,
('SK', 10.0, 'GR'): 13.0,
('SK', 10.0, 'HR'): 5.0,
('SK', 10.0, 'HU'): 5.0,
('SK', 10.0, 'IE'): 13.5,
('SK', 10.0, 'IT'): 4.0,
('SK', 10.0, 'LT'): 5.0,
('SK', 10.0, 'LU'): 7.0,
('SK', 10.0, 'LV'): 12.0,
('SK', 10.0, 'MT'): 5.0,
('SK', 10.0, 'NL'): 9.0,
('SK', 10.0, 'PL'): 8.0,
('SK', 10.0, 'PT'): 6.0,
('SK', 10.0, 'RO'): 5.0,
('SK', 10.0, 'SE'): 6.0,
('SK', 10.0, 'SI'): 9.5,
('SK', 20.0, 'AT'): 20.0,
('SK', 20.0, 'BE'): 21.0,
('SK', 20.0, 'BG'): 20.0,
('SK', 20.0, 'CY'): 19.0,
('SK', 20.0, 'CZ'): 21.0,
('SK', 20.0, 'DE'): 19.0,
('SK', 20.0, 'DK'): 25.0,
('SK', 20.0, 'EE'): 20.0,
('SK', 20.0, 'ES'): 21.0,
('SK', 20.0, 'FI'): 24.0,
('SK', 20.0, 'FR'): 20.0,
('SK', 20.0, 'GR'): 24.0,
('SK', 20.0, 'HR'): 25.0,
('SK', 20.0, 'HU'): 27.0,
('SK', 20.0, 'IE'): 23.0,
('SK', 20.0, 'IT'): 22.0,
('SK', 20.0, 'LT'): 21.0,
('SK', 20.0, 'LU'): 16.0,
('SK', 20.0, 'LV'): 21.0,
('SK', 20.0, 'MT'): 18.0,
('SK', 20.0, 'NL'): 21.0,
('SK', 20.0, 'PL'): 23.0,
('SK', 20.0, 'PT'): 23.0,
('SK', 20.0, 'RO'): 19.0,
('SK', 20.0, 'SE'): 25.0,
('SK', 20.0, 'SI'): 22.0,
}
| 29.268741 | 62,079 |
8,061 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command, api, models
from .eu_tag_map import EU_TAG_MAP
from .eu_tax_map import EU_TAX_MAP
class Company(models.Model):
_inherit = 'res.company'
@api.model
def _map_all_eu_companies_taxes(self):
''' Identifies EU companies and calls the _map_eu_taxes function
'''
eu_countries = self.env.ref('base.europe').country_ids
companies = self.search([('account_fiscal_country_id', 'in', eu_countries.ids)])
companies._map_eu_taxes()
def _map_eu_taxes(self):
'''Creates or updates Fiscal Positions for each EU country excluding the company's account_fiscal_country_id
'''
eu_countries = self.env.ref('base.europe').country_ids
oss_tax_groups = self.env['ir.model.data'].search([
('module', '=', 'l10n_eu_oss'),
('model', '=', 'account.tax.group')])
for company in self:
invoice_repartition_lines, refund_repartition_lines = company._get_repartition_lines_oss()
taxes = self.env['account.tax'].search([
('type_tax_use', '=', 'sale'),
('amount_type', '=', 'percent'),
('company_id', '=', company.id),
('country_id', '=', company.account_fiscal_country_id.id),
('tax_group_id', 'not in', oss_tax_groups.mapped('res_id'))])
multi_tax_reports_countries_fpos = self.env['account.fiscal.position'].search([
('company_id', '=', company.id),
('foreign_vat', '!=', False),
])
oss_countries = eu_countries - company.account_fiscal_country_id - multi_tax_reports_countries_fpos.country_id
for destination_country in oss_countries:
mapping = []
fpos = self.env['account.fiscal.position'].search([
('country_id', '=', destination_country.id),
('company_id', '=', company.id),
('auto_apply', '=', True),
('vat_required', '=', False),
('foreign_vat', '=', False)], limit=1)
if not fpos:
fpos = self.env['account.fiscal.position'].create({
'name': f'OSS B2C {destination_country.name}',
'country_id': destination_country.id,
'company_id': company.id,
'auto_apply': True,
})
foreign_taxes = {tax.amount: tax for tax in fpos.tax_ids.tax_dest_id if tax.amount_type == 'percent'}
for domestic_tax in taxes:
tax_amount = EU_TAX_MAP.get((company.account_fiscal_country_id.code, domestic_tax.amount, destination_country.code), False)
if tax_amount and domestic_tax not in fpos.tax_ids.tax_src_id:
if not foreign_taxes.get(tax_amount, False):
oss_tax_group_local_xml_id = f"oss_tax_group_{str(tax_amount).replace('.', '_')}"
if not self.env.ref(f"l10n_eu_oss.{oss_tax_group_local_xml_id}", raise_if_not_found=False):
self.env['ir.model.data'].create({
'name': oss_tax_group_local_xml_id,
'module': 'l10n_eu_oss',
'model': 'account.tax.group',
'res_id': self.env['account.tax.group'].create({'name': f'OSS {tax_amount}%'}).id,
'noupdate': True,
})
foreign_taxes[tax_amount] = self.env['account.tax'].create({
'name': f'{tax_amount}% {destination_country.code} {destination_country.vat_label}',
'amount': tax_amount,
'invoice_repartition_line_ids': invoice_repartition_lines,
'refund_repartition_line_ids': refund_repartition_lines,
'type_tax_use': 'sale',
'description': f"{tax_amount}%",
'tax_group_id': self.env.ref(f'l10n_eu_oss.{oss_tax_group_local_xml_id}').id,
'country_id': company.account_fiscal_country_id.id,
'sequence': 1000,
'company_id': company.id,
})
mapping.append((0, 0, {'tax_src_id': domestic_tax.id, 'tax_dest_id': foreign_taxes[tax_amount].id}))
if mapping:
fpos.write({
'tax_ids': mapping
})
def _get_repartition_lines_oss(self):
self.ensure_one()
defaults = self.env['account.tax'].with_company(self).default_get(['invoice_repartition_line_ids', 'refund_repartition_line_ids'])
oss_account, oss_tags = self._get_oss_account(), self._get_oss_tags()
base_line, tax_line, vals = 0, 1, 2
for doc_type in 'invoice', 'refund':
if oss_account:
defaults[f'{doc_type}_repartition_line_ids'][tax_line][vals]['account_id'] = oss_account.id
if oss_tags:
defaults[f'{doc_type}_repartition_line_ids'][base_line][vals]['tag_ids'] += [Command.link(tag.id) for tag in oss_tags[f'{doc_type}_base_tag']]
defaults[f'{doc_type}_repartition_line_ids'][tax_line][vals]['tag_ids'] += [Command.link(tag.id) for tag in oss_tags[f'{doc_type}_tax_tag']]
return defaults['invoice_repartition_line_ids'], defaults['refund_repartition_line_ids']
def _get_oss_account(self):
self.ensure_one()
if not self.env.ref(f'l10n_eu_oss.oss_tax_account_company_{self.id}', raise_if_not_found=False):
sales_tax_accounts = self.env['account.tax'].search([
('type_tax_use', '=', 'sale'),
('company_id', '=', self.id)
]).invoice_repartition_line_ids.mapped('account_id')
if not sales_tax_accounts:
return False
new_code = self.env['account.account']._search_new_account_code(self, len(sales_tax_accounts[0].code), sales_tax_accounts[0].code[:-2])
oss_account = self.env['account.account'].create({
'name': f'{sales_tax_accounts[0].name} OSS',
'code': new_code,
'user_type_id': sales_tax_accounts[0].user_type_id.id,
'company_id': self.id,
})
self.env['ir.model.data'].create({
'name': f'oss_tax_account_company_{self.id}',
'module': 'l10n_eu_oss',
'model': 'account.account',
'res_id': oss_account.id,
'noupdate': True,
})
return self.env.ref(f'l10n_eu_oss.oss_tax_account_company_{self.id}')
def _get_oss_tags(self):
oss_tag = self.env.ref('l10n_eu_oss.tag_oss')
chart_template_xml_id = ''
if self.chart_template_id:
[chart_template_xml_id] = self.chart_template_id.parent_id.get_external_id().values() or self.chart_template_id.get_external_id().values()
tag_for_country = EU_TAG_MAP.get(chart_template_xml_id, {
'invoice_base_tag': None,
'invoice_tax_tag': None,
'refund_base_tag': None,
'refund_tax_tag': None,
})
mapping = {}
for repartition_line_key, tag_xml_id in tag_for_country.items():
tag = self.env.ref(tag_xml_id) if tag_xml_id else self.env['account.account.tag']
if tag and tag._name == "account.tax.report.line":
tag = tag.tag_ids.filtered(lambda t: not t.tax_negate)
mapping[repartition_line_key] = tag + oss_tag
return mapping
| 54.836735 | 8,061 |
716 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
l10n_eu_oss_eu_country = fields.Boolean('Is European country?', compute='_compute_l10n_eu_oss_european_country')
def refresh_eu_tax_mapping(self):
self.env.companies._map_eu_taxes()
@api.depends('company_id')
def _compute_l10n_eu_oss_european_country(self):
european_countries = self.env.ref('base.europe').country_ids
for record in self:
record.l10n_eu_oss_eu_country = record.company_id.account_fiscal_country_id in european_countries
| 37.684211 | 716 |
491 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
def _load(self, sale_tax_rate, purchase_tax_rate, company):
rslt = super()._load(sale_tax_rate, purchase_tax_rate, company)
if company.account_fiscal_country_id in self.env.ref('base.europe').country_ids:
company._map_eu_taxes()
return rslt
| 32.733333 | 491 |
1,141 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Turkey - Accounting',
'version': '1.0',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Türkiye için Tek düzen hesap planı şablonu Odoo Modülü.
==========================================================
Bu modül kurulduktan sonra, Muhasebe yapılandırma sihirbazı çalışır
* Sihirbaz sizden hesap planı şablonu, planın kurulacağı şirket, banka hesap
bilgileriniz, ilgili para birimi gibi bilgiler isteyecek.
""",
'author': 'Ahmet Altınışık, Can Tecim',
'maintainer':'https://launchpad.net/~openerp-turkey, http://www.cantecim.com',
'depends': [
'account',
],
'data': [
'data/l10n_tr_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_tr_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_template_data.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 33.818182 | 1,116 |
1,911 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "LATAM Document",
"version": "1.0",
"author": "ADHOC SA",
'category': 'Accounting/Localizations',
"summary": "LATAM Document Types",
'description': """
Functional
----------
In some Latinamerica countries, including Argentina and Chile, some accounting transactions like invoices and vendor bills are classified by a document types defined by the government fiscal authorities (In Argentina case AFIP, Chile case SII).
This module is intended to be extended by localizations in order to manage these document types and is an essential information that needs to be displayed in the printed reports and that needs to be easily identified, within the set of invoices as well of account moves.
Each document type have their own rules and sequence number, this last one is integrated with the invoice number and journal sequence in order to be easy for the localization user. In order to support or not this document types a Journal has a new option that lets to use document or not.
Technical
---------
If your localization needs this logic will then need to add this module as dependency and in your localization module extend:
* extend company's _localization_use_documents() method.
* create the data of the document types that exists for the specific country. The document type has a country field
""",
"depends": [
"account",
"account_debit_note",
],
"data": [
'views/account_journal_view.xml',
'views/account_move_line_view.xml',
'views/account_move_view.xml',
'views/l10n_latam_document_type_view.xml',
'views/report_templates.xml',
'report/invoice_report_view.xml',
'wizards/account_move_reversal_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'license': 'LGPL-3',
}
| 44.44186 | 1,911 |
14,218 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools.sql import column_exists, create_column
class AccountMove(models.Model):
_inherit = "account.move"
def _auto_init(self):
# Skip the computation of the field `l10n_latam_document_type_id` at the module installation
# Without this, at the module installation,
# it would call `_compute_l10n_latam_document_type` on all existing records
# which can take quite a while if you already have a lot of moves. It can even fail with a MemoryError.
# In addition, it sets `_compute_l10n_latam_document_type = False` on all records
# because this field depends on the many2many `l10n_latam_available_document_type_ids`,
# which relies on having records for the model `l10n_latam.document.type`
# which only happens once the according localization module is loaded.
# The localization module is loaded afterwards, because the localization module depends on this module,
# (e.g. `l10n_cl` depends on `l10n_latam_invoice_document`, and therefore `l10n_cl` is loaded after)
# and therefore there are no records for the model `l10n_latam.document.type` at the time this fields
# gets computed on installation. Hence, all records' `_compute_l10n_latam_document_type` are set to `False`.
# In addition, multiple localization module depends on this module (e.g. `l10n_cl`, `l10n_ar`)
# So, imagine `l10n_cl` gets installed first, and then `l10n_ar` is installed next,
# if `l10n_latam_document_type_id` needed to be computed on install,
# the install of `l10n_cl` would call the compute method,
# because `l10n_latam_invoice_document` would be installed at the same time,
# but then `l10n_ar` would miss it, because `l10n_latam_invoice_document` would already be installed.
# Besides, this field is computed only for drafts invoices, as stated in the compute method:
# `for rec in self.filtered(lambda x: x.state == 'draft'):`
# So, if we want this field to be computed on install, it must be done only on draft invoices, and only once
# the localization modules are loaded.
# It should be done in a dedicated post init hook,
# filtering correctly the invoices for which it must be computed.
# Though I don't think this is needed.
# In practical, it's very rare to already have invoices (draft, in addition)
# for a Chilian or Argentian company (`res.company`) before installing `l10n_cl` or `l10n_ar`.
if not column_exists(self.env.cr, "account_move", "l10n_latam_document_type_id"):
create_column(self.env.cr, "account_move", "l10n_latam_document_type_id", "int4")
return super()._auto_init()
l10n_latam_available_document_type_ids = fields.Many2many('l10n_latam.document.type', compute='_compute_l10n_latam_available_document_types')
l10n_latam_document_type_id = fields.Many2one(
'l10n_latam.document.type', string='Document Type', readonly=False, auto_join=True, index=True,
states={'posted': [('readonly', True)]}, compute='_compute_l10n_latam_document_type', store=True)
l10n_latam_document_number = fields.Char(
compute='_compute_l10n_latam_document_number', inverse='_inverse_l10n_latam_document_number',
string='Document Number', readonly=True, states={'draft': [('readonly', False)]})
l10n_latam_use_documents = fields.Boolean(related='journal_id.l10n_latam_use_documents')
l10n_latam_manual_document_number = fields.Boolean(compute='_compute_l10n_latam_manual_document_number', string='Manual Number')
l10n_latam_document_type_id_code = fields.Char(related='l10n_latam_document_type_id.code', string='Doc Type')
@api.depends('l10n_latam_document_type_id')
def _compute_name(self):
""" Change the way that the use_document moves name is computed:
* If move use document but does not have document type selected then name = '/' to do not show the name.
* If move use document and are numbered manually do not compute name at all (will be set manually)
* If move use document and is in draft state and has not been posted before we restart name to '/' (this is
when we change the document type) """
without_doc_type = self.filtered(lambda x: x.journal_id.l10n_latam_use_documents and not x.l10n_latam_document_type_id)
manual_documents = self.filtered(lambda x: x.journal_id.l10n_latam_use_documents and x.l10n_latam_manual_document_number)
(without_doc_type + manual_documents.filtered(lambda x: not x.name or x.name and x.state == 'draft' and not x.posted_before)).name = '/'
# if we change document or journal and we are in draft and not posted, we clean number so that is recomputed in super
self.filtered(
lambda x: x.journal_id.l10n_latam_use_documents and x.l10n_latam_document_type_id
and not x.l10n_latam_manual_document_number and x.state == 'draft' and not x.posted_before).name = '/'
# we need to group moves by document type as _compute_name will apply the same name prefix of the first record to the others
group_by_document_type = defaultdict(self.env['account.move'].browse)
for move in (self - without_doc_type - manual_documents):
group_by_document_type[move.l10n_latam_document_type_id.id] += move
for group in group_by_document_type.values():
super(AccountMove, group)._compute_name()
@api.depends('l10n_latam_document_type_id', 'journal_id')
def _compute_l10n_latam_manual_document_number(self):
""" Indicates if this document type uses a sequence or if the numbering is made manually """
recs_with_journal_id = self.filtered(lambda x: x.journal_id and x.journal_id.l10n_latam_use_documents)
for rec in recs_with_journal_id:
rec.l10n_latam_manual_document_number = rec._is_manual_document_number()
remaining = self - recs_with_journal_id
remaining.l10n_latam_manual_document_number = False
def _is_manual_document_number(self):
return self.journal_id.type == 'purchase'
@api.depends('name')
def _compute_l10n_latam_document_number(self):
recs_with_name = self.filtered(lambda x: x.name != '/')
for rec in recs_with_name:
name = rec.name
doc_code_prefix = rec.l10n_latam_document_type_id.doc_code_prefix
if doc_code_prefix and name:
name = name.split(" ", 1)[-1]
rec.l10n_latam_document_number = name
remaining = self - recs_with_name
remaining.l10n_latam_document_number = False
@api.onchange('l10n_latam_document_type_id', 'l10n_latam_document_number')
def _inverse_l10n_latam_document_number(self):
for rec in self.filtered(lambda x: x.l10n_latam_document_type_id):
if not rec.l10n_latam_document_number:
rec.name = '/'
else:
l10n_latam_document_number = rec.l10n_latam_document_type_id._format_document_number(rec.l10n_latam_document_number)
if rec.l10n_latam_document_number != l10n_latam_document_number:
rec.l10n_latam_document_number = l10n_latam_document_number
rec.name = "%s %s" % (rec.l10n_latam_document_type_id.doc_code_prefix, l10n_latam_document_number)
@api.depends('journal_id', 'l10n_latam_document_type_id')
def _compute_highest_name(self):
manual_records = self.filtered('l10n_latam_manual_document_number')
manual_records.highest_name = ''
super(AccountMove, self - manual_records)._compute_highest_name()
@api.model
def _deduce_sequence_number_reset(self, name):
if self.l10n_latam_use_documents:
return 'never'
return super(AccountMove, self)._deduce_sequence_number_reset(name)
def _get_starting_sequence(self):
if self.journal_id.l10n_latam_use_documents:
if self.l10n_latam_document_type_id:
return "%s 00000000" % (self.l10n_latam_document_type_id.doc_code_prefix)
# There was no pattern found, propose one
return ""
return super(AccountMove, self)._get_starting_sequence()
def _post(self, soft=True):
for rec in self.filtered(lambda x: x.l10n_latam_use_documents and (not x.name or x.name == '/')):
if rec.move_type in ('in_receipt', 'out_receipt'):
raise UserError(_('We do not accept the usage of document types on receipts yet. '))
return super()._post(soft)
@api.constrains('name', 'journal_id', 'state')
def _check_unique_sequence_number(self):
""" This uniqueness verification is only valid for customer invoices, and vendor bills that does not use
documents. A new constraint method _check_unique_vendor_number has been created just for validate for this purpose """
vendor = self.filtered(lambda x: x.is_purchase_document() and x.l10n_latam_use_documents)
return super(AccountMove, self - vendor)._check_unique_sequence_number()
@api.constrains('state', 'l10n_latam_document_type_id')
def _check_l10n_latam_documents(self):
""" This constraint checks that if a invoice is posted and does not have a document type configured will raise
an error. This only applies to invoices related to journals that has the "Use Documents" set as True.
And if the document type is set then check if the invoice number has been set, because a posted invoice
without a document number is not valid in the case that the related journals has "Use Docuemnts" set as True """
validated_invoices = self.filtered(lambda x: x.l10n_latam_use_documents and x.state == 'posted')
without_doc_type = validated_invoices.filtered(lambda x: not x.l10n_latam_document_type_id)
if without_doc_type:
raise ValidationError(_(
'The journal require a document type but not document type has been selected on invoices %s.',
without_doc_type.ids
))
without_number = validated_invoices.filtered(
lambda x: not x.l10n_latam_document_number and x.l10n_latam_manual_document_number)
if without_number:
raise ValidationError(_(
'Please set the document number on the following invoices %s.',
without_number.ids
))
@api.constrains('move_type', 'l10n_latam_document_type_id')
def _check_invoice_type_document_type(self):
for rec in self.filtered('l10n_latam_document_type_id.internal_type'):
internal_type = rec.l10n_latam_document_type_id.internal_type
invoice_type = rec.move_type
if internal_type in ['debit_note', 'invoice'] and invoice_type in ['out_refund', 'in_refund']:
raise ValidationError(_('You can not use a %s document type with a refund invoice', internal_type))
elif internal_type == 'credit_note' and invoice_type in ['out_invoice', 'in_invoice']:
raise ValidationError(_('You can not use a %s document type with a invoice', internal_type))
def _get_l10n_latam_documents_domain(self):
self.ensure_one()
if self.move_type in ['out_refund', 'in_refund']:
internal_types = ['credit_note']
else:
internal_types = ['invoice', 'debit_note']
return [('internal_type', 'in', internal_types), ('country_id', '=', self.company_id.account_fiscal_country_id.id)]
@api.depends('journal_id', 'partner_id', 'company_id', 'move_type')
def _compute_l10n_latam_available_document_types(self):
self.l10n_latam_available_document_type_ids = False
for rec in self.filtered(lambda x: x.journal_id and x.l10n_latam_use_documents and x.partner_id):
rec.l10n_latam_available_document_type_ids = self.env['l10n_latam.document.type'].search(rec._get_l10n_latam_documents_domain())
@api.depends('l10n_latam_available_document_type_ids', 'debit_origin_id')
def _compute_l10n_latam_document_type(self):
for rec in self.filtered(lambda x: x.state == 'draft'):
document_types = rec.l10n_latam_available_document_type_ids._origin
invoice_type = rec.move_type
if invoice_type in ['out_refund', 'in_refund']:
document_types = document_types.filtered(lambda x: x.internal_type not in ['debit_note', 'invoice'])
elif invoice_type in ['out_invoice', 'in_invoice']:
document_types = document_types.filtered(lambda x: x.internal_type not in ['credit_note'])
if rec.debit_origin_id:
document_types = document_types.filtered(lambda x: x.internal_type == 'debit_note')
rec.l10n_latam_document_type_id = document_types and document_types[0].id
@api.constrains('name', 'partner_id', 'company_id', 'posted_before')
def _check_unique_vendor_number(self):
""" The constraint _check_unique_sequence_number is valid for customer bills but not valid for us on vendor
bills because the uniqueness must be per partner """
for rec in self.filtered(
lambda x: x.name and x.name != '/' and x.is_purchase_document() and x.l10n_latam_use_documents
and x.commercial_partner_id):
domain = [
('move_type', '=', rec.move_type),
# by validating name we validate l10n_latam_document_type_id
('name', '=', rec.name),
('company_id', '=', rec.company_id.id),
('id', '!=', rec.id),
('commercial_partner_id', '=', rec.commercial_partner_id.id),
# allow to have to equal if they are cancelled
('state', '!=', 'cancel'),
]
if rec.search(domain):
raise ValidationError(_('Vendor bill number must be unique per vendor and company.'))
| 63.473214 | 14,218 |
1,714 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
from odoo.exceptions import ValidationError
class AccountJournal(models.Model):
_inherit = "account.journal"
l10n_latam_use_documents = fields.Boolean(
'Use Documents?', help="If active: will be using for legal invoicing (invoices, debit/credit notes)."
" If not set means that will be used to register accounting entries not related to invoicing legal documents."
" For Example: Receipts, Tax Payments, Register journal entries")
l10n_latam_company_use_documents = fields.Boolean(compute='_compute_l10n_latam_company_use_documents')
@api.depends('company_id')
def _compute_l10n_latam_company_use_documents(self):
for rec in self:
rec.l10n_latam_company_use_documents = rec.company_id._localization_use_documents()
@api.onchange('company_id', 'type')
def _onchange_company(self):
self.l10n_latam_use_documents = self.type in ['sale', 'purchase'] and \
self.l10n_latam_company_use_documents
@api.constrains('l10n_latam_use_documents')
def check_use_document(self):
for rec in self:
if rec.env['account.move'].search([('journal_id', '=', rec.id), ('posted_before', '=', True)], limit=1):
raise ValidationError(_(
'You can not modify the field "Use Documents?" if there are validated invoices in this journal!'))
@api.onchange('type', 'l10n_latam_use_documents')
def _onchange_type(self):
res = super()._onchange_type()
if self.l10n_latam_use_documents:
self.refund_sequence = False
return res
| 45.105263 | 1,714 |
2,572 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
from odoo.osv import expression
class L10nLatamDocumentType(models.Model):
_name = 'l10n_latam.document.type'
_description = 'Latam Document Type'
_order = 'sequence, id'
active = fields.Boolean(default=True)
sequence = fields.Integer(
default=10, required=True, help='To set in which order show the documents type taking into account the most'
' commonly used first')
country_id = fields.Many2one(
'res.country', required=True, index=True, help='Country in which this type of document is valid')
name = fields.Char(required=True, index=True, help='The document name')
doc_code_prefix = fields.Char(
'Document Code Prefix', help="Prefix for Documents Codes on Invoices and Account Moves. For eg. 'FA ' will"
" build 'FA 0001-0000001' Document Number")
code = fields.Char(help='Code used by different localizations')
report_name = fields.Char('Name on Reports', help='Name that will be printed in reports, for example "CREDIT NOTE"')
internal_type = fields.Selection(
[('invoice', 'Invoices'), ('debit_note', 'Debit Notes'), ('credit_note', 'Credit Notes')], index=True,
help='Analog to odoo account.move.move_type but with more options allowing to identify the kind of document we are'
' working with. (not only related to account.move, could be for documents of other models like stock.picking)')
def _format_document_number(self, document_number):
""" Method to be inherited by different localizations. The purpose of this method is to allow:
* making validations on the document_number. If it is wrong it should raise an exception
* format the document_number against a pattern and return it
"""
self.ensure_one()
return document_number
def name_get(self):
result = []
for rec in self:
name = rec.name
if rec.code:
name = '(%s) %s' % (rec.code, name)
result.append((rec.id, name))
return result
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
if operator == 'ilike' and not (name or '').strip():
domain = []
else:
domain = ['|', ('name', 'ilike', name), ('code', 'ilike', name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
| 48.528302 | 2,572 |
848 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
from odoo.tools.sql import column_exists, create_column
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _auto_init(self):
# Skip the computation of the field `l10n_latam_document_type_id` at the module installation
# See `_auto_init` in `l10n_latam_invoice_document/models/account_move.py` for more information
if not column_exists(self.env.cr, "account_move_line", "l10n_latam_document_type_id"):
create_column(self.env.cr, "account_move_line", "l10n_latam_document_type_id", "int4")
return super()._auto_init()
l10n_latam_document_type_id = fields.Many2one(
related='move_id.l10n_latam_document_type_id', auto_join=True, store=True, index=True)
| 44.631579 | 848 |
372 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
def _localization_use_documents(self):
""" This method is to be inherited by localizations and return True if localization use documents """
self.ensure_one()
return False
| 31 | 372 |
791 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, fields, _
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
@api.model
def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):
""" We add use_documents or not depending on the context"""
journal_data = super()._prepare_all_journals(acc_template_ref, company, journals_dict)
# if chart has localization, then we use documents by default
if company._localization_use_documents():
for vals_journal in journal_data:
if vals_journal['type'] in ['sale', 'purchase']:
vals_journal['l10n_latam_use_documents'] = True
return journal_data
| 41.631579 | 791 |
493 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
class AccountInvoiceReport(models.Model):
_inherit = 'account.invoice.report'
l10n_latam_document_type_id = fields.Many2one('l10n_latam.document.type', 'Document Type', index=True)
_depends = {'account.move': ['l10n_latam_document_type_id'],}
def _select(self):
return super()._select() + ", move.l10n_latam_document_type_id as l10n_latam_document_type_id"
| 37.923077 | 493 |
461 |
py
|
PYTHON
|
15.0
|
from odoo import models
class AccountDebitNote(models.TransientModel):
_inherit = 'account.debit.note'
def create_debit(self):
""" Properly compute the latam document type of type debit note. """
res = super().create_debit()
new_move_id = res.get('res_id')
if new_move_id:
new_move = self.env['account.move'].browse(new_move_id)
new_move._compute_l10n_latam_document_type()
return res
| 30.733333 | 461 |
5,298 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.exceptions import UserError
class AccountMoveReversal(models.TransientModel):
_inherit = "account.move.reversal"
l10n_latam_use_documents = fields.Boolean(compute='_compute_document_type')
l10n_latam_document_type_id = fields.Many2one('l10n_latam.document.type', 'Document Type', ondelete='cascade', domain="[('id', 'in', l10n_latam_available_document_type_ids)]", compute='_compute_document_type', readonly=False, inverse='_inverse_document_type')
l10n_latam_available_document_type_ids = fields.Many2many('l10n_latam.document.type', compute='_compute_document_type')
l10n_latam_document_number = fields.Char(string='Document Number')
l10n_latam_manual_document_number = fields.Boolean(compute='_compute_l10n_latam_manual_document_number', string='Manual Number')
def _inverse_document_type(self):
self._clean_pipe()
self.l10n_latam_document_number = '%s|%s' % (self.l10n_latam_document_type_id.id or '', self.l10n_latam_document_number or '')
@api.depends('l10n_latam_document_type_id')
def _compute_l10n_latam_manual_document_number(self):
self.l10n_latam_manual_document_number = False
for rec in self.filtered('move_ids'):
move = rec.move_ids[0]
if move.journal_id and move.journal_id.l10n_latam_use_documents:
rec.l10n_latam_manual_document_number = move._is_manual_document_number()
@api.model
def _reverse_type_map(self, move_type):
match = {
'entry': 'entry',
'out_invoice': 'out_refund',
'in_invoice': 'in_refund',
'in_refund': 'in_invoice',
'out_receipt': 'in_receipt',
'in_receipt': 'out_receipt'}
return match.get(move_type)
@api.depends('move_ids')
def _compute_document_type(self):
self.l10n_latam_available_document_type_ids = False
self.l10n_latam_document_type_id = False
self.l10n_latam_use_documents = False
for record in self:
if len(record.move_ids) > 1:
move_ids_use_document = record.move_ids._origin.filtered(lambda move: move.l10n_latam_use_documents)
if move_ids_use_document:
raise UserError(_('You can only reverse documents with legal invoicing documents from Latin America one at a time.\nProblematic documents: %s') % ", ".join(move_ids_use_document.mapped('name')))
else:
record.l10n_latam_use_documents = record.move_ids.journal_id.l10n_latam_use_documents
if record.l10n_latam_use_documents:
refund = record.env['account.move'].new({
'move_type': record._reverse_type_map(record.move_ids.move_type),
'journal_id': record.move_ids.journal_id.id,
'partner_id': record.move_ids.partner_id.id,
'company_id': record.move_ids.company_id.id,
})
record.l10n_latam_document_type_id = refund.l10n_latam_document_type_id
record.l10n_latam_available_document_type_ids = refund.l10n_latam_available_document_type_ids
def _prepare_default_reversal(self, move):
""" Set the default document type and number in the new revsersal move taking into account the ones selected in
the wizard """
res = super()._prepare_default_reversal(move)
# self.l10n_latam_document_number will have a ',' only if l10n_latam_document_type_id is changed and inverse methods is called
if self.l10n_latam_document_number and '|' in self.l10n_latam_document_number:
l10n_latam_document_type_id, l10n_latam_document_number = self.l10n_latam_document_number.split('|')
res.update({
'l10n_latam_document_type_id': int(l10n_latam_document_type_id) if l10n_latam_document_type_id else False,
'l10n_latam_document_number': l10n_latam_document_number or False,
})
else:
res.update({
'l10n_latam_document_type_id': self.l10n_latam_document_type_id.id,
'l10n_latam_document_number': self.l10n_latam_document_number,
})
return res
def _clean_pipe(self):
""" Clean pipe in case the user confirm but he gets a raise, the l10n_latam_document_number is stored now
with the doc type id, we should remove to append new one or to format properly"""
latam_document = self.l10n_latam_document_number or ''
if '|' in latam_document:
latam_document = latam_document[latam_document.index('|')+1:]
self.l10n_latam_document_number = latam_document
@api.onchange('l10n_latam_document_number', 'l10n_latam_document_type_id')
def _onchange_l10n_latam_document_number(self):
if self.l10n_latam_document_type_id:
self._clean_pipe()
l10n_latam_document_number = self.l10n_latam_document_type_id._format_document_number(
self.l10n_latam_document_number)
if self.l10n_latam_document_number != l10n_latam_document_number:
self.l10n_latam_document_number = l10n_latam_document_number
| 55.768421 | 5,298 |
580 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Timesheets/attendances reporting",
'description': """
Module linking the attendance module to the timesheet app.
""",
'category': 'Hidden',
'version': '1.0',
'depends': ['hr_timesheet', 'hr_attendance'],
'data': [
'security/ir.model.access.csv',
'security/hr_timesheet_attendance_report_security.xml',
'report/hr_timesheet_attendance_report_view.xml',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 29 | 580 |
2,175 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools
class TimesheetAttendance(models.Model):
_name = 'hr.timesheet.attendance.report'
_auto = False
_description = 'Timesheet Attendance Report'
user_id = fields.Many2one('res.users')
date = fields.Date()
total_timesheet = fields.Float()
total_attendance = fields.Float()
total_difference = fields.Float()
company_id = fields.Many2one('res.company', string='Company', readonly=True)
def init(self):
tools.drop_view_if_exists(self.env.cr, self._table)
self._cr.execute("""CREATE OR REPLACE VIEW %s AS (
SELECT
max(id) AS id,
t.user_id,
t.date,
t.company_id,
coalesce(sum(t.attendance), 0) AS total_attendance,
coalesce(sum(t.timesheet), 0) AS total_timesheet,
coalesce(sum(t.attendance), 0) - coalesce(sum(t.timesheet), 0) as total_difference
FROM (
SELECT
-hr_attendance.id AS id,
resource_resource.user_id AS user_id,
hr_attendance.worked_hours AS attendance,
NULL AS timesheet,
hr_attendance.check_in::date AS date,
resource_resource.company_id as company_id
FROM hr_attendance
LEFT JOIN hr_employee ON hr_employee.id = hr_attendance.employee_id
LEFT JOIN resource_resource on resource_resource.id = hr_employee.resource_id
UNION ALL
SELECT
ts.id AS id,
ts.user_id AS user_id,
NULL AS attendance,
ts.unit_amount AS timesheet,
ts.date AS date,
ts.company_id AS company_id
FROM account_analytic_line AS ts
WHERE ts.project_id IS NOT NULL
) AS t
GROUP BY t.user_id, t.date, t.company_id
ORDER BY t.date
)
""" % self._table)
| 39.545455 | 2,175 |
997 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "mrp_subcontracting",
'version': '0.1',
'summary': "Subcontract Productions",
'description': "",
'website': 'https://www.odoo.com/app/manufacturing',
'category': 'Manufacturing/Manufacturing',
'depends': ['mrp'],
'data': [
'data/mrp_subcontracting_data.xml',
'views/mrp_bom_views.xml',
'views/res_partner_views.xml',
'views/stock_warehouse_views.xml',
'views/stock_move_views.xml',
'views/stock_quant_views.xml',
'views/stock_picking_views.xml',
'views/supplier_info_views.xml',
'views/product_views.xml',
'views/mrp_production_views.xml',
'wizard/stock_picking_return_views.xml',
'report/mrp_report_bom_structure.xml',
],
'demo': [
'data/mrp_subcontracting_demo.xml',
],
'uninstall_hook': 'uninstall_hook',
'license': 'LGPL-3',
}
| 32.16129 | 997 |
54,750 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo.tests import Form
from odoo.tests.common import TransactionCase
from odoo.addons.mrp_subcontracting.tests.common import TestMrpSubcontractingCommon
from odoo.tests import tagged
from dateutil.relativedelta import relativedelta
@tagged('post_install', '-at_install')
class TestSubcontractingBasic(TransactionCase):
def test_subcontracting_location_1(self):
""" Checks the creation and presence of the subcontracting location. """
self.assertTrue(self.env.company.subcontracting_location_id)
self.assertTrue(self.env.company.subcontracting_location_id.active)
company2 = self.env['res.company'].create({'name': 'Test Company'})
self.assertTrue(company2.subcontracting_location_id)
self.assertTrue(self.env.company.subcontracting_location_id != company2.subcontracting_location_id)
class TestSubcontractingFlows(TestMrpSubcontractingCommon):
def test_flow_1(self):
""" Don't tick any route on the components and trigger the creation of the subcontracting
manufacturing order through a receipt picking. Create a reordering rule in the
subcontracting locations for a component and run the scheduler to resupply. Checks if the
resupplying actually works
"""
# Check subcontracting picking Type
self.assertTrue(all(self.env['stock.warehouse'].search([]).with_context(active_test=False).mapped('subcontracting_type_id.use_create_components_lots')))
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# Nothing should be tracked
self.assertTrue(all(m.product_uom_qty == m.reserved_availability for m in picking_receipt.move_lines))
self.assertEqual(picking_receipt.state, 'assigned')
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
# Check the created manufacturing order
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)])
self.assertEqual(len(mo), 1)
self.assertEqual(len(mo.picking_ids), 0)
wh = picking_receipt.picking_type_id.warehouse_id
self.assertEqual(mo.picking_type_id, wh.subcontracting_type_id)
self.assertFalse(mo.picking_type_id.active)
# Create a RR
pg1 = self.env['procurement.group'].create({})
self.env['stock.warehouse.orderpoint'].create({
'name': 'xxx',
'product_id': self.comp1.id,
'product_min_qty': 0,
'product_max_qty': 0,
'location_id': self.env.user.company_id.subcontracting_location_id.id,
'group_id': pg1.id,
})
# Run the scheduler and check the created picking
self.env['procurement.group'].run_scheduler()
picking = self.env['stock.picking'].search([('group_id', '=', pg1.id)])
self.assertEqual(len(picking), 1)
self.assertEqual(picking.picking_type_id, wh.subcontracting_resupply_type_id)
picking_receipt.move_lines.quantity_done = 1
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
# Available quantities should be negative at the subcontracting location for each components
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_comp2 = self.env['stock.quant']._get_available_quantity(self.comp2, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_finished = self.env['stock.quant']._get_available_quantity(self.finished, wh.lot_stock_id)
self.assertEqual(avail_qty_comp1, -1)
self.assertEqual(avail_qty_comp2, -1)
self.assertEqual(avail_qty_finished, 1)
# Ensure returns to subcontractor location
return_form = Form(self.env['stock.return.picking'].with_context(active_id=picking_receipt.id, active_model='stock.picking'))
return_wizard = return_form.save()
return_picking_id, pick_type_id = return_wizard._create_returns()
return_picking = self.env['stock.picking'].browse(return_picking_id)
self.assertEqual(len(return_picking), 1)
self.assertEqual(return_picking.move_lines.location_dest_id, self.subcontractor_partner1.property_stock_subcontractor)
def test_flow_2(self):
""" Tick "Resupply Subcontractor on Order" on the components and trigger the creation of
the subcontracting manufacturing order through a receipt picking. Checks if the resupplying
actually works. Also set a different subcontracting location on the partner.
"""
# Tick "resupply subconractor on order"
resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
(self.comp1 + self.comp2).write({'route_ids': [(4, resupply_sub_on_order_route.id, None)]})
# Create a different subcontract location
partner_subcontract_location = self.env['stock.location'].create({
'name': 'Specific partner location',
'location_id': self.env.ref('stock.stock_location_locations_partner').id,
'usage': 'internal',
'company_id': self.env.company.id,
})
self.subcontractor_partner1.property_stock_subcontractor = partner_subcontract_location.id
resupply_rule = resupply_sub_on_order_route.rule_ids.filtered(lambda l:
l.location_id == self.comp1.property_stock_production and
l.location_src_id == self.env.company.subcontracting_location_id)
resupply_rule.copy({'location_src_id': partner_subcontract_location.id})
resupply_warehouse_rule = self.warehouse.route_ids.rule_ids.filtered(lambda l:
l.location_id == self.env.company.subcontracting_location_id and
l.location_src_id == self.warehouse.lot_stock_id)
resupply_warehouse_rule.copy({'location_id': partner_subcontract_location.id})
# Add a manufacturing lead time to check that the resupply delivery is correctly planned 2 days
# before the subcontracting receipt
self.finished.produce_delay = 2
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# Nothing should be tracked
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
# Pickings should directly be created
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)])
self.assertEqual(len(mo.picking_ids), 1)
self.assertEqual(mo.state, 'confirmed')
self.assertEqual(len(mo.picking_ids.move_lines), 2)
picking = mo.picking_ids
wh = picking.picking_type_id.warehouse_id
# The picking should be a delivery order
self.assertEqual(picking.picking_type_id, wh.subcontracting_resupply_type_id)
# The date planned should be correct
self.assertEqual(picking_receipt.scheduled_date, picking.scheduled_date + relativedelta(days=self.finished.produce_delay))
self.assertEqual(mo.picking_type_id, wh.subcontracting_type_id)
self.assertFalse(mo.picking_type_id.active)
# No manufacturing order for `self.comp2`
comp2mo = self.env['mrp.production'].search([('bom_id', '=', self.comp2_bom.id)])
self.assertEqual(len(comp2mo), 0)
picking_receipt.move_lines.quantity_done = 1
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
# Available quantities should be negative at the subcontracting location for each components
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_comp2 = self.env['stock.quant']._get_available_quantity(self.comp2, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_finished = self.env['stock.quant']._get_available_quantity(self.finished, wh.lot_stock_id)
self.assertEqual(avail_qty_comp1, -1)
self.assertEqual(avail_qty_comp2, -1)
self.assertEqual(avail_qty_finished, 1)
avail_qty_comp1_in_global_location = self.env['stock.quant']._get_available_quantity(self.comp1, self.env.company.subcontracting_location_id, allow_negative=True)
avail_qty_comp2_in_global_location = self.env['stock.quant']._get_available_quantity(self.comp2, self.env.company.subcontracting_location_id, allow_negative=True)
self.assertEqual(avail_qty_comp1_in_global_location, 0.0)
self.assertEqual(avail_qty_comp2_in_global_location, 0.0)
def test_flow_3(self):
""" Tick "Resupply Subcontractor on Order" and "MTO" on the components and trigger the
creation of the subcontracting manufacturing order through a receipt picking. Checks if the
resupplying actually works. One of the component has also "manufacture" set and a BOM
linked. Checks that an MO is created for this one.
"""
# Tick "resupply subconractor on order"
resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
(self.comp1 + self.comp2).write({'route_ids': [(4, resupply_sub_on_order_route.id, None)]})
# Tick "manufacture" and MTO on self.comp2
mto_route = self.env.ref('stock.route_warehouse0_mto')
mto_route.active = True
manufacture_route = self.env['stock.location.route'].search([('name', '=', 'Manufacture')])
self.comp2.write({'route_ids': [(4, manufacture_route.id, None)]})
self.comp2.write({'route_ids': [(4, mto_route.id, None)]})
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# Nothing should be tracked
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
# Pickings should directly be created
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)])
self.assertEqual(mo.state, 'confirmed')
picking_delivery = mo.picking_ids
self.assertEqual(len(picking_delivery), 1)
self.assertEqual(len(picking_delivery.move_lines), 2)
self.assertEqual(picking_delivery.origin, picking_receipt.name)
self.assertEqual(picking_delivery.partner_id, picking_receipt.partner_id)
# The picking should be a delivery order
wh = picking_receipt.picking_type_id.warehouse_id
self.assertEqual(mo.picking_ids.picking_type_id, wh.subcontracting_resupply_type_id)
self.assertEqual(mo.picking_type_id, wh.subcontracting_type_id)
self.assertFalse(mo.picking_type_id.active)
# As well as a manufacturing order for `self.comp2`
comp2mo = self.env['mrp.production'].search([('bom_id', '=', self.comp2_bom.id)])
self.assertEqual(len(comp2mo), 1)
picking_receipt.move_lines.quantity_done = 1
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
# Available quantities should be negative at the subcontracting location for each components
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_comp2 = self.env['stock.quant']._get_available_quantity(self.comp2, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_finished = self.env['stock.quant']._get_available_quantity(self.finished, wh.lot_stock_id)
self.assertEqual(avail_qty_comp1, -1)
self.assertEqual(avail_qty_comp2, -1)
self.assertEqual(avail_qty_finished, 1)
def test_flow_4(self):
""" Tick "Manufacture" and "MTO" on the components and trigger the
creation of the subcontracting manufacturing order through a receipt
picking. Checks that the delivery and MO for its components are
automatically created.
"""
# Tick "manufacture" and MTO on self.comp2
mto_route = self.env.ref('stock.route_warehouse0_mto')
mto_route.active = True
manufacture_route = self.env['stock.location.route'].search([('name', '=', 'Manufacture')])
self.comp2.write({'route_ids': [(4, manufacture_route.id, None)]})
self.comp2.write({'route_ids': [(4, mto_route.id, None)]})
orderpoint_form = Form(self.env['stock.warehouse.orderpoint'])
orderpoint_form.product_id = self.comp2
orderpoint_form.product_min_qty = 0.0
orderpoint_form.product_max_qty = 10.0
orderpoint_form.location_id = self.env.company.subcontracting_location_id
orderpoint = orderpoint_form.save()
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
warehouse = picking_receipt.picking_type_id.warehouse_id
# Pickings should directly be created
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)])
self.assertEqual(mo.state, 'confirmed')
picking_delivery = mo.picking_ids
self.assertFalse(picking_delivery)
picking_delivery = self.env['stock.picking'].search([('origin', 'ilike', '%' + picking_receipt.name + '%')])
self.assertFalse(picking_delivery)
move = self.env['stock.move'].search([
('product_id', '=', self.comp2.id),
('location_id', '=', warehouse.lot_stock_id.id),
('location_dest_id', '=', self.env.company.subcontracting_location_id.id)
])
self.assertTrue(move)
picking_delivery = move.picking_id
self.assertTrue(picking_delivery)
self.assertEqual(move.product_uom_qty, 11.0)
# As well as a manufacturing order for `self.comp2`
comp2mo = self.env['mrp.production'].search([('bom_id', '=', self.comp2_bom.id)])
self.assertEqual(len(comp2mo), 1)
def test_flow_5(self):
""" Check that the correct BoM is chosen accordingly to the partner
"""
# We create a second partner of type subcontractor
main_partner_2 = self.env['res.partner'].create({'name': 'main_partner'})
subcontractor_partner2 = self.env['res.partner'].create({
'name': 'subcontractor_partner',
'parent_id': main_partner_2.id,
'company_id': self.env.ref('base.main_company').id
})
# We create a different BoM for the same product
comp3 = self.env['product.product'].create({
'name': 'Component1',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
bom_form = Form(self.env['mrp.bom'])
bom_form.type = 'subcontract'
bom_form.product_tmpl_id = self.finished.product_tmpl_id
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.comp1
bom_line.product_qty = 1
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = comp3
bom_line.product_qty = 1
bom2 = bom_form.save()
# We assign the second BoM to the new partner
self.bom.write({'subcontractor_ids': [(4, self.subcontractor_partner1.id, None)]})
bom2.write({'subcontractor_ids': [(4, subcontractor_partner2.id, None)]})
# Create a receipt picking from the subcontractor1
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt1 = picking_form.save()
picking_receipt1.action_confirm()
# Create a receipt picking from the subcontractor2
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = subcontractor_partner2
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt2 = picking_form.save()
picking_receipt2.action_confirm()
mo_pick1 = picking_receipt1.move_lines.mapped('move_orig_ids.production_id')
mo_pick2 = picking_receipt2.move_lines.mapped('move_orig_ids.production_id')
self.assertEqual(len(mo_pick1), 1)
self.assertEqual(len(mo_pick2), 1)
self.assertEqual(mo_pick1.bom_id, self.bom)
self.assertEqual(mo_pick2.bom_id, bom2)
def test_flow_6(self):
""" Extra quantity on the move.
"""
# We create a second partner of type subcontractor
main_partner_2 = self.env['res.partner'].create({'name': 'main_partner'})
subcontractor_partner2 = self.env['res.partner'].create({
'name': 'subcontractor_partner',
'parent_id': main_partner_2.id,
'company_id': self.env.ref('base.main_company').id,
})
self.env.cache.invalidate()
# We create a different BoM for the same product
comp3 = self.env['product.product'].create({
'name': 'Component3',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
bom_form = Form(self.env['mrp.bom'])
bom_form.type = 'subcontract'
bom_form.product_tmpl_id = self.finished.product_tmpl_id
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.comp1
bom_line.product_qty = 1
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = comp3
bom_line.product_qty = 2
bom2 = bom_form.save()
# We assign the second BoM to the new partner
self.bom.write({'subcontractor_ids': [(4, self.subcontractor_partner1.id, None)]})
bom2.write({'subcontractor_ids': [(4, subcontractor_partner2.id, None)]})
# Create a receipt picking from the subcontractor1
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = subcontractor_partner2
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
picking_receipt.move_lines.quantity_done = 3.0
picking_receipt._action_done()
mo = picking_receipt._get_subcontract_production()
move_comp1 = mo.move_raw_ids.filtered(lambda m: m.product_id == self.comp1)
move_comp3 = mo.move_raw_ids.filtered(lambda m: m.product_id == comp3)
self.assertEqual(sum(move_comp1.mapped('product_uom_qty')), 3.0)
self.assertEqual(sum(move_comp3.mapped('product_uom_qty')), 6.0)
self.assertEqual(sum(move_comp1.mapped('quantity_done')), 3.0)
self.assertEqual(sum(move_comp3.mapped('quantity_done')), 6.0)
move_finished = mo.move_finished_ids
self.assertEqual(sum(move_finished.mapped('product_uom_qty')), 3.0)
self.assertEqual(sum(move_finished.mapped('quantity_done')), 3.0)
def test_flow_8(self):
resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
(self.comp1 + self.comp2).write({'route_ids': [(4, resupply_sub_on_order_route.id, None)]})
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 5
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
picking_receipt.move_lines.quantity_done = 3
backorder_wiz = picking_receipt.button_validate()
backorder_wiz = Form(self.env[backorder_wiz['res_model']].with_context(backorder_wiz['context'])).save()
backorder_wiz.process()
backorder = self.env['stock.picking'].search([('backorder_id', '=', picking_receipt.id)])
self.assertTrue(backorder)
self.assertEqual(backorder.move_lines.product_uom_qty, 2)
mo_done = backorder.move_lines.move_orig_ids.production_id.filtered(lambda p: p.state == 'done')
backorder_mo = backorder.move_lines.move_orig_ids.production_id.filtered(lambda p: p.state != 'done')
self.assertTrue(mo_done)
self.assertEqual(mo_done.qty_produced, 3)
self.assertEqual(mo_done.product_uom_qty, 3)
self.assertTrue(backorder_mo)
self.assertEqual(backorder_mo.product_uom_qty, 2)
self.assertEqual(backorder_mo.qty_produced, 0)
backorder.move_lines.quantity_done = 2
backorder._action_done()
self.assertTrue(picking_receipt.move_lines.move_orig_ids.production_id.state == 'done')
def test_flow_9(self):
"""Ensure that cancel the subcontract moves will also delete the
components need for the subcontractor.
"""
resupply_sub_on_order_route = self.env['stock.location.route'].search([
('name', '=', 'Resupply Subcontractor on Order')
])
(self.comp1 + self.comp2).write({
'route_ids': [(4, resupply_sub_on_order_route.id)]
})
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 5
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
picking_delivery = self.env['stock.move'].search([
('product_id', 'in', (self.comp1 | self.comp2).ids)
]).picking_id
self.assertTrue(picking_delivery)
self.assertEqual(picking_delivery.state, 'confirmed')
self.assertEqual(self.comp1.virtual_available, -5)
self.assertEqual(self.comp2.virtual_available, -5)
# action_cancel is not call on the picking in order
# to test behavior from other source than picking (e.g. puchase).
picking_receipt.move_lines._action_cancel()
self.assertEqual(picking_delivery.state, 'cancel')
self.assertEqual(self.comp1.virtual_available, 0.0)
self.assertEqual(self.comp1.virtual_available, 0.0)
def test_flow_10(self):
"""Receipts from a children contact of a subcontractor are properly
handled.
"""
# Create a children contact
subcontractor_contact = self.env['res.partner'].create({
'name': 'Test children subcontractor contact',
'parent_id': self.subcontractor_partner1.id,
})
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = subcontractor_contact
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# Check that a manufacturing order is created
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)])
self.assertEqual(len(mo), 1)
def test_flow_flexible_bom_1(self):
""" Record Component for a bom subcontracted with a flexible and flexible + warning consumption """
self.bom.consumption = 'flexible'
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
self.assertEqual(picking_receipt.display_action_record_components, 'facultative')
action = picking_receipt.action_record_components()
mo = self.env['mrp.production'].browse(action['res_id'])
mo_form = Form(mo.with_context(**action['context']), view=action['view_id'])
mo_form.qty_producing = 1
with mo_form.move_line_raw_ids.edit(0) as ml:
self.assertEqual(ml.product_id, self.comp1)
self.assertEqual(ml.qty_done, 1)
ml.qty_done = 2
mo = mo_form.save()
mo.subcontracting_record_component()
self.assertEqual(mo.move_raw_ids[0].move_line_ids.qty_done, 2)
# We should not be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
self.assertEqual(avail_qty_comp1, -2)
def test_flow_warning_bom_1(self):
""" Record Component for a bom subcontracted with a flexible and flexible + warning consumption """
self.bom.consumption = 'warning'
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
self.assertEqual(picking_receipt.display_action_record_components, 'facultative')
action = picking_receipt.action_record_components()
mo = self.env['mrp.production'].browse(action['res_id'])
mo_form = Form(mo.with_context(**action['context']), view=action['view_id'])
mo_form.qty_producing = 1
with mo_form.move_line_raw_ids.edit(0) as ml:
self.assertEqual(ml.product_id, self.comp1)
self.assertEqual(ml.qty_done, 1)
ml.qty_done = 2
mo = mo_form.save()
action_warning = mo.subcontracting_record_component()
warning = Form(self.env['mrp.consumption.warning'].with_context(**action_warning['context']))
warning = warning.save()
warning.action_cancel()
action_warning = mo.subcontracting_record_component()
warning = Form(self.env['mrp.consumption.warning'].with_context(**action_warning['context']))
warning = warning.save()
warning.action_confirm()
self.assertEqual(mo.move_raw_ids[0].move_line_ids.qty_done, 2)
# We should not be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
self.assertEqual(avail_qty_comp1, -2)
def test_mrp_report_bom_structure_subcontracting(self):
self.comp2_bom.write({'type': 'subcontract', 'subcontractor_ids': [Command.link(self.subcontractor_partner1.id)]})
self.env['product.supplierinfo'].create({
'product_tmpl_id': self.finished.product_tmpl_id.id,
'name': self.subcontractor_partner1.id,
'price': 10,
})
supplier = self.env['product.supplierinfo'].create({
'product_tmpl_id': self.comp2.product_tmpl_id.id,
'name': self.subcontractor_partner1.id,
'price': 5,
})
self.env['product.supplierinfo'].create({
'product_tmpl_id': self.comp2.product_tmpl_id.id,
'name': self.subcontractor_partner1.id,
'price': 1,
'min_qty': 5,
})
self.assertTrue(supplier.is_subcontractor)
self.comp1.standard_price = 5
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, searchQty=1, searchVariant=False)
subcontracting_values = report_values['lines']['subcontracting']
self.assertEqual(subcontracting_values['name'], self.subcontractor_partner1.display_name)
self.assertEqual(report_values['lines']['total'], 20) # 10 For subcontracting + 5 for comp1 + 5 for subcontracting of comp2_bom
self.assertEqual(report_values['lines']['bom_cost'], 20)
self.assertEqual(subcontracting_values['bom_cost'], 10)
self.assertEqual(subcontracting_values['prod_cost'], 10)
self.assertEqual(report_values['lines']['components'][0]['total'], 5)
self.assertEqual(report_values['lines']['components'][1]['total'], 5)
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, searchQty=3, searchVariant=False)
subcontracting_values = report_values['lines']['subcontracting']
self.assertEqual(report_values['lines']['total'], 60) # 30 for subcontracting + 15 for comp1 + 15 for subcontracting of comp2_bom
self.assertEqual(report_values['lines']['bom_cost'], 60)
self.assertEqual(subcontracting_values['bom_cost'], 30)
self.assertEqual(subcontracting_values['prod_cost'], 30)
self.assertEqual(report_values['lines']['components'][0]['total'], 15)
self.assertEqual(report_values['lines']['components'][1]['total'], 15)
report_values = self.env['report.mrp.report_bom_structure']._get_report_data(self.bom.id, searchQty=5, searchVariant=False)
subcontracting_values = report_values['lines']['subcontracting']
self.assertEqual(report_values['lines']['total'], 80) # 50 for subcontracting + 25 for comp1 + 5 for subcontracting of comp2_bom
self.assertEqual(report_values['lines']['bom_cost'], 80)
self.assertEqual(subcontracting_values['bom_cost'], 50)
self.assertEqual(subcontracting_values['prod_cost'], 50)
self.assertEqual(report_values['lines']['components'][0]['total'], 25)
self.assertEqual(report_values['lines']['components'][1]['total'], 5)
def test_several_backorders(self):
def process_picking(picking, qty):
picking.move_lines.quantity_done = qty
action = picking.button_validate()
if isinstance(action, dict):
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
wizard.process()
resupply_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
finished, component = self.env['product.product'].create([{
'name': 'Finished Product',
'type': 'product',
}, {
'name': 'Component',
'type': 'product',
'route_ids': [(4, resupply_route.id)],
}])
bom = self.env['mrp.bom'].create({
'product_tmpl_id': finished.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'subcontract',
'subcontractor_ids': [(4, self.subcontractor_partner1.id)],
'bom_line_ids': [(0, 0, {'product_id': component.id, 'product_qty': 1.0})],
})
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = finished
move.product_uom_qty = 5
picking = picking_form.save()
picking.action_confirm()
supply_picking = self.env['mrp.production'].search([('bom_id', '=', bom.id)]).picking_ids
process_picking(supply_picking, 5)
process_picking(picking, 1.25)
backorder01 = picking.backorder_ids
process_picking(backorder01, 1)
backorder02 = backorder01.backorder_ids
process_picking(backorder02, 0)
self.assertEqual(backorder02.move_lines.quantity_done, 2.75)
self.assertEqual(self.env['mrp.production'].search_count([('bom_id', '=', bom.id)]), 3)
def test_mo_name(self):
receipt_form = Form(self.env['stock.picking'])
receipt_form.picking_type_id = self.env.ref('stock.picking_type_in')
receipt_form.partner_id = self.subcontractor_partner1
with receipt_form.move_ids_without_package.new() as move:
move.product_id = self.finished
move.product_uom_qty = 1
receipt = receipt_form.save()
receipt.action_confirm()
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom.id)])
display_name = mo.display_name
self.assertIn(receipt.name, display_name, "If subcontracted, the name of a MO should contain the associated receipt name")
self.assertIn(mo.name, display_name)
for key_search in [mo.name, receipt.name]:
res = mo.name_search(key_search)
self.assertTrue(res, 'When looking for "%s", it should find something' % key_search)
self.assertEqual(res[0][0], mo.id, 'When looking for "%s", it should find the MO processed above' % key_search)
class TestSubcontractingTracking(TransactionCase):
def setUp(self):
super(TestSubcontractingTracking, self).setUp()
# 1: Create a subcontracting partner
main_company_1 = self.env['res.partner'].create({'name': 'main_partner'})
self.subcontractor_partner1 = self.env['res.partner'].create({
'name': 'Subcontractor 1',
'parent_id': main_company_1.id,
'company_id': self.env.ref('base.main_company').id
})
# 2. Create a BOM of subcontracting type
# 2.1. Comp1 has tracking by lot
self.comp1_sn = self.env['product.product'].create({
'name': 'Component1',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'serial'
})
self.comp2 = self.env['product.product'].create({
'name': 'Component2',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
# 2.2. Finished prodcut has tracking by serial number
self.finished_product = self.env['product.product'].create({
'name': 'finished',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'lot'
})
bom_form = Form(self.env['mrp.bom'])
bom_form.type = 'subcontract'
bom_form.consumption = 'strict'
bom_form.subcontractor_ids.add(self.subcontractor_partner1)
bom_form.product_tmpl_id = self.finished_product.product_tmpl_id
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.comp1_sn
bom_line.product_qty = 1
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = self.comp2
bom_line.product_qty = 1
self.bom_tracked = bom_form.save()
def test_flow_tracked_1(self):
""" This test mimics test_flow_1 but with a BoM that has tracking included in it.
"""
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished_product
move.product_uom_qty = 1
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# We should be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'mandatory')
# Check the created manufacturing order
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom_tracked.id)])
self.assertEqual(len(mo), 1)
self.assertEqual(len(mo.picking_ids), 0)
wh = picking_receipt.picking_type_id.warehouse_id
self.assertEqual(mo.picking_type_id, wh.subcontracting_type_id)
self.assertFalse(mo.picking_type_id.active)
# Create a RR
pg1 = self.env['procurement.group'].create({})
self.env['stock.warehouse.orderpoint'].create({
'name': 'xxx',
'product_id': self.comp1_sn.id,
'product_min_qty': 0,
'product_max_qty': 0,
'location_id': self.env.user.company_id.subcontracting_location_id.id,
'group_id': pg1.id,
})
# Run the scheduler and check the created picking
self.env['procurement.group'].run_scheduler()
picking = self.env['stock.picking'].search([('group_id', '=', pg1.id)])
self.assertEqual(len(picking), 1)
self.assertEqual(picking.picking_type_id, wh.subcontracting_resupply_type_id)
lot_id = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.finished_product.id,
'company_id': self.env.company.id,
})
serial_id = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.comp1_sn.id,
'company_id': self.env.company.id,
})
action = picking_receipt.action_record_components()
mo = self.env['mrp.production'].browse(action['res_id'])
mo_form = Form(mo.with_context(**action['context']), view=action['view_id'])
mo_form.qty_producing = 1
mo_form.lot_producing_id = lot_id
with mo_form.move_line_raw_ids.edit(0) as ml:
ml.lot_id = serial_id
mo = mo_form.save()
mo.subcontracting_record_component()
# We should not be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
# Available quantities should be negative at the subcontracting location for each components
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1_sn, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_comp2 = self.env['stock.quant']._get_available_quantity(self.comp2, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_finished = self.env['stock.quant']._get_available_quantity(self.finished_product, wh.lot_stock_id)
self.assertEqual(avail_qty_comp1, -1)
self.assertEqual(avail_qty_comp2, -1)
self.assertEqual(avail_qty_finished, 1)
def test_flow_tracked_only_finished(self):
""" Test when only the finished product is tracked """
self.finished_product.tracking = "serial"
self.comp1_sn.tracking = "none"
nb_finished_product = 3
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished_product
move.product_uom_qty = nb_finished_product
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# We shouldn't be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
wh = picking_receipt.picking_type_id.warehouse_id
lot_names_finished = [f"subtracked_{i}" for i in range(nb_finished_product)]
move_details = Form(picking_receipt.move_lines, view='stock.view_stock_move_nosuggest_operations')
for lot_name in lot_names_finished:
with move_details.move_line_nosuggest_ids.new() as ml:
ml.qty_done = 1
ml.lot_name = lot_name
move_details.save()
picking_receipt.button_validate()
# Check the created manufacturing order
# Should have one mo by serial number
mos = picking_receipt.move_lines.move_orig_ids.production_id
self.assertEqual(len(mos), nb_finished_product)
self.assertEqual(mos.mapped("state"), ["done"] * nb_finished_product)
self.assertEqual(mos.picking_type_id, wh.subcontracting_type_id)
self.assertFalse(mos.picking_type_id.active)
self.assertEqual(set(mos.lot_producing_id.mapped("name")), set(lot_names_finished))
# Available quantities should be negative at the subcontracting location for each components
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1_sn, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_comp2 = self.env['stock.quant']._get_available_quantity(self.comp2, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_finished = self.env['stock.quant']._get_available_quantity(self.finished_product, wh.lot_stock_id)
self.assertEqual(avail_qty_comp1, -nb_finished_product)
self.assertEqual(avail_qty_comp2, -nb_finished_product)
self.assertEqual(avail_qty_finished, nb_finished_product)
def test_flow_tracked_backorder(self):
""" This test uses tracked (serial and lot) component and tracked (serial) finished product """
todo_nb = 4
self.comp2.tracking = 'lot'
self.finished_product.tracking = 'serial'
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.finished_product
move.product_uom_qty = todo_nb
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
# We should be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'mandatory')
# Check the created manufacturing order
mo = self.env['mrp.production'].search([('bom_id', '=', self.bom_tracked.id)])
self.assertEqual(len(mo), 1)
self.assertEqual(len(mo.picking_ids), 0)
wh = picking_receipt.picking_type_id.warehouse_id
self.assertEqual(mo.picking_type_id, wh.subcontracting_type_id)
self.assertFalse(mo.picking_type_id.active)
lot_comp2 = self.env['stock.production.lot'].create({
'name': 'lot_comp2',
'product_id': self.comp2.id,
'company_id': self.env.company.id,
})
serials_finished = []
serials_comp1 = []
for i in range(todo_nb):
serials_finished.append(self.env['stock.production.lot'].create({
'name': 'serial_fin_%s' % i,
'product_id': self.finished_product.id,
'company_id': self.env.company.id,
}))
serials_comp1.append(self.env['stock.production.lot'].create({
'name': 'serials_comp1_%s' % i,
'product_id': self.comp1_sn.id,
'company_id': self.env.company.id,
}))
for i in range(todo_nb):
action = picking_receipt.action_record_components()
mo = self.env['mrp.production'].browse(action['res_id'])
mo_form = Form(mo.with_context(**action['context']), view=action['view_id'])
mo_form.lot_producing_id = serials_finished[i]
with mo_form.move_line_raw_ids.edit(0) as ml:
self.assertEqual(ml.product_id, self.comp1_sn)
ml.lot_id = serials_comp1[i]
with mo_form.move_line_raw_ids.edit(1) as ml:
self.assertEqual(ml.product_id, self.comp2)
ml.lot_id = lot_comp2
mo = mo_form.save()
mo.subcontracting_record_component()
# We should not be able to call the 'record_components' button
self.assertEqual(picking_receipt.display_action_record_components, 'hide')
picking_receipt.button_validate()
self.assertEqual(mo.state, 'done')
self.assertEqual(mo.procurement_group_id.mrp_production_ids.mapped("state"), ['done'] * todo_nb)
self.assertEqual(len(mo.procurement_group_id.mrp_production_ids), todo_nb)
self.assertEqual(mo.procurement_group_id.mrp_production_ids.mapped("qty_produced"), [1] * todo_nb)
# Available quantities should be negative at the subcontracting location for each components
avail_qty_comp1 = self.env['stock.quant']._get_available_quantity(self.comp1_sn, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_comp2 = self.env['stock.quant']._get_available_quantity(self.comp2, self.subcontractor_partner1.property_stock_subcontractor, allow_negative=True)
avail_qty_finished = self.env['stock.quant']._get_available_quantity(self.finished_product, wh.lot_stock_id)
self.assertEqual(avail_qty_comp1, -todo_nb)
self.assertEqual(avail_qty_comp2, -todo_nb)
self.assertEqual(avail_qty_finished, todo_nb)
def test_flow_tracked_backorder02(self):
""" Both component and finished product are tracked by lot. """
todo_nb = 4
resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
finished_product, component = self.env['product.product'].create([{
'name': 'SuperProduct',
'type': 'product',
'tracking': 'lot',
}, {
'name': 'Component',
'type': 'product',
'tracking': 'lot',
'route_ids': [(4, resupply_sub_on_order_route.id)],
}])
bom_form = Form(self.env['mrp.bom'])
bom_form.type = 'subcontract'
bom_form.subcontractor_ids.add(self.subcontractor_partner1)
bom_form.product_tmpl_id = finished_product.product_tmpl_id
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = component
bom_line.product_qty = 1
bom = bom_form.save()
finished_lot, component_lot = self.env['stock.production.lot'].create([{
'name': 'lot_%s' % product.name,
'product_id': product.id,
'company_id': self.env.company.id,
} for product in [finished_product, component]])
self.env['stock.quant']._update_available_quantity(component, self.env.ref('stock.stock_location_stock'), todo_nb, lot_id=component_lot)
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = finished_product
move.product_uom_qty = todo_nb
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
mo = self.env['mrp.production'].search([('bom_id', '=', bom.id)])
# Process the delivery of the components
compo_picking = mo.picking_ids
compo_picking.action_assign()
wizard_data = compo_picking.button_validate()
wizard = Form(self.env[wizard_data['res_model']].with_context(wizard_data['context'])).save()
wizard.process()
for qty in [3, 1]:
# Record the receiption of <qty> finished products
picking_receipt = self.env['stock.picking'].search([('partner_id', '=', self.subcontractor_partner1.id), ('state', '!=', 'done')])
action = picking_receipt.action_record_components()
mo = self.env['mrp.production'].browse(action['res_id'])
mo_form = Form(mo.with_context(**action['context']), view=action['view_id'])
mo_form.qty_producing = qty
mo_form.lot_producing_id = finished_lot
with mo_form.move_line_raw_ids.edit(0) as ml:
ml.lot_id = component_lot
mo = mo_form.save()
mo.subcontracting_record_component()
# Validate the picking and create a backorder
wizard_data = picking_receipt.button_validate()
if qty == 3:
wizard = Form(self.env[wizard_data['res_model']].with_context(wizard_data['context'])).save()
wizard.process()
self.assertEqual(picking_receipt.state, 'done')
def test_flow_backorder_production(self):
""" Test subcontracted MO backorder (i.e. through record production window, NOT through
picking backorder). Finished product is serial tracked to ensure subcontracting MO window
is opened. Check that MO backorder auto-reserves components
"""
todo_nb = 3
resupply_sub_on_order_route = self.env['stock.location.route'].search([('name', '=', 'Resupply Subcontractor on Order')])
finished_product, component = self.env['product.product'].create([{
'name': 'Pepper Spray',
'type': 'product',
'tracking': 'serial',
}, {
'name': 'Pepper',
'type': 'product',
'route_ids': [(4, resupply_sub_on_order_route.id)],
}])
bom_form = Form(self.env['mrp.bom'])
bom_form.type = 'subcontract'
bom_form.subcontractor_ids.add(self.subcontractor_partner1)
bom_form.product_tmpl_id = finished_product.product_tmpl_id
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = component
bom_line.product_qty = 1
bom = bom_form.save()
finished_serials = self.env['stock.production.lot'].create([{
'name': 'sn_%s' % str(i),
'product_id': finished_product.id,
'company_id': self.env.company.id,
} for i in range(todo_nb)])
self.env['stock.quant']._update_available_quantity(component, self.env.ref('stock.stock_location_stock'), todo_nb)
# Create a receipt picking from the subcontractor
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
picking_form.partner_id = self.subcontractor_partner1
with picking_form.move_ids_without_package.new() as move:
move.product_id = finished_product
move.product_uom_qty = todo_nb
picking_receipt = picking_form.save()
picking_receipt.action_confirm()
mo = self.env['mrp.production'].search([('bom_id', '=', bom.id)])
# Process the delivery of the components
compo_picking = mo.picking_ids
compo_picking.action_assign()
wizard_data = compo_picking.button_validate()
wizard = Form(self.env[wizard_data['res_model']].with_context(wizard_data['context'])).save()
wizard.process()
picking_receipt = self.env['stock.picking'].search([('partner_id', '=', self.subcontractor_partner1.id), ('state', '!=', 'done')])
for sn in finished_serials:
# Record the production of each serial number separately
action = picking_receipt.action_record_components()
mo = self.env['mrp.production'].browse(action['res_id'])
self.assertEqual(mo.move_raw_ids.state, 'assigned')
mo_form = Form(mo.with_context(**action['context']), view=action['view_id'])
mo_form.qty_producing = 1
mo_form.lot_producing_id = sn
mo = mo_form.save()
mo.subcontracting_record_component()
# Validate the picking
picking_receipt.button_validate()
self.assertEqual(picking_receipt.state, 'done')
| 51.025163 | 54,750 |
2,499 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import Form, TransactionCase
class TestMrpSubcontractingCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestMrpSubcontractingCommon, cls).setUpClass()
# 1: Create a subcontracting partner
main_partner = cls.env['res.partner'].create({'name': 'main_partner'})
cls.subcontractor_partner1 = cls.env['res.partner'].create({
'name': 'subcontractor_partner',
'parent_id': main_partner.id,
'company_id': cls.env.ref('base.main_company').id,
})
# 2. Create a BOM of subcontracting type
cls.comp1 = cls.env['product.product'].create({
'name': 'Component1',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.comp2 = cls.env['product.product'].create({
'name': 'Component2',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.finished = cls.env['product.product'].create({
'name': 'finished',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
bom_form = Form(cls.env['mrp.bom'])
bom_form.type = 'subcontract'
bom_form.consumption = 'strict'
bom_form.product_tmpl_id = cls.finished.product_tmpl_id
bom_form.subcontractor_ids.add(cls.subcontractor_partner1)
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = cls.comp1
bom_line.product_qty = 1
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = cls.comp2
bom_line.product_qty = 1
cls.bom = bom_form.save()
# Create a BoM for cls.comp2
cls.comp2comp = cls.env['product.product'].create({
'name': 'component for Component2',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
bom_form = Form(cls.env['mrp.bom'])
bom_form.product_tmpl_id = cls.comp2.product_tmpl_id
with bom_form.bom_line_ids.new() as bom_line:
bom_line.product_id = cls.comp2comp
bom_line.product_qty = 1
cls.comp2_bom = bom_form.save()
cls.warehouse = cls.env['stock.warehouse'].search([], limit=1)
| 40.967213 | 2,499 |
1,247 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class ReturnPicking(models.TransientModel):
_inherit = 'stock.return.picking'
subcontract_location_id = fields.Many2one('stock.location', compute='_compute_subcontract_location_id')
@api.depends('picking_id')
def _compute_subcontract_location_id(self):
for record in self:
record.subcontract_location_id = record.picking_id.partner_id.with_company(
record.picking_id.company_id
).property_stock_subcontractor
@api.onchange('picking_id')
def _onchange_picking_id(self):
res = super(ReturnPicking, self)._onchange_picking_id()
if any(return_line.quantity > 0 and return_line.move_id.is_subcontract for return_line in self.product_return_moves):
self.location_id = self.picking_id.partner_id.with_company(self.picking_id.company_id).property_stock_subcontractor
return res
def _prepare_move_default_values(self, return_line, new_picking):
vals = super(ReturnPicking, self)._prepare_move_default_values(return_line, new_picking)
vals['is_subcontract'] = False
return vals
| 43 | 1,247 |
775 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MrpConsumptionWarning(models.TransientModel):
_inherit = 'mrp.consumption.warning'
def action_confirm(self):
if self.mrp_production_ids._get_subcontract_move():
return self.mrp_production_ids.with_context(skip_consumption=True).subcontracting_record_component()
return super().action_confirm()
def action_cancel(self):
mo_subcontracted_move = self.mrp_production_ids._get_subcontract_move()
if mo_subcontracted_move:
return mo_subcontracted_move.filtered(lambda move: move.state not in ('done', 'cancel'))._action_record_components()
return super().action_cancel()
| 40.789474 | 775 |
7,271 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
class StockWarehouse(models.Model):
_inherit = 'stock.warehouse'
subcontracting_to_resupply = fields.Boolean(
'Resupply Subcontractors', default=True,
help="Resupply subcontractors with components")
subcontracting_mto_pull_id = fields.Many2one(
'stock.rule', 'Subcontracting MTO Rule')
subcontracting_pull_id = fields.Many2one(
'stock.rule', 'Subcontracting MTS Rule'
)
subcontracting_route_id = fields.Many2one('stock.location.route', 'Resupply Subcontractor', ondelete='restrict')
subcontracting_type_id = fields.Many2one(
'stock.picking.type', 'Subcontracting Operation Type',
domain=[('code', '=', 'mrp_operation')])
subcontracting_resupply_type_id = fields.Many2one(
'stock.picking.type', 'Subcontracting Resupply Operation Type',
domain=[('code', '=', 'outgoing')])
def get_rules_dict(self):
result = super(StockWarehouse, self).get_rules_dict()
subcontract_location_id = self._get_subcontracting_location()
for warehouse in self:
result[warehouse.id].update({
'subcontract': [
self.Routing(warehouse.lot_stock_id, subcontract_location_id, warehouse.subcontracting_resupply_type_id, 'pull'),
]
})
return result
def _get_routes_values(self):
routes = super(StockWarehouse, self)._get_routes_values()
routes.update({
'subcontracting_route_id': {
'routing_key': 'subcontract',
'depends': ['subcontracting_to_resupply'],
'route_create_values': {
'product_categ_selectable': False,
'warehouse_selectable': True,
'product_selectable': False,
'company_id': self.company_id.id,
'sequence': 10,
'name': self._format_routename(name=_('Resupply Subcontractor'))
},
'route_update_values': {
'active': self.subcontracting_to_resupply,
},
'rules_values': {
'active': self.subcontracting_to_resupply,
}
}
})
return routes
def _get_global_route_rules_values(self):
rules = super(StockWarehouse, self)._get_global_route_rules_values()
subcontract_location_id = self._get_subcontracting_location()
production_location_id = self._get_production_location()
rules.update({
'subcontracting_mto_pull_id': {
'depends': ['subcontracting_to_resupply'],
'create_values': {
'procure_method': 'make_to_order',
'company_id': self.company_id.id,
'action': 'pull',
'auto': 'manual',
'route_id': self._find_global_route('stock.route_warehouse0_mto', _('Make To Order')).id,
'name': self._format_rulename(self.lot_stock_id, subcontract_location_id, 'MTO'),
'location_id': subcontract_location_id.id,
'location_src_id': self.lot_stock_id.id,
'picking_type_id': self.subcontracting_resupply_type_id.id
},
'update_values': {
'active': self.subcontracting_to_resupply
}
},
'subcontracting_pull_id': {
'depends': ['subcontracting_to_resupply'],
'create_values': {
'procure_method': 'make_to_order',
'company_id': self.company_id.id,
'action': 'pull',
'auto': 'manual',
'route_id': self._find_global_route('mrp_subcontracting.route_resupply_subcontractor_mto',
_('Resupply Subcontractor on Order')).id,
'name': self._format_rulename(self.lot_stock_id, subcontract_location_id, False),
'location_id': production_location_id.id,
'location_src_id': subcontract_location_id.id,
'picking_type_id': self.subcontracting_resupply_type_id.id
},
'update_values': {
'active': self.subcontracting_to_resupply
}
},
})
return rules
def _get_picking_type_create_values(self, max_sequence):
data, next_sequence = super(StockWarehouse, self)._get_picking_type_create_values(max_sequence)
data.update({
'subcontracting_type_id': {
'name': _('Subcontracting'),
'code': 'mrp_operation',
'use_create_components_lots': True,
'sequence': next_sequence + 2,
'sequence_code': 'SBC',
'company_id': self.company_id.id,
},
'subcontracting_resupply_type_id': {
'name': _('Resupply Subcontractor'),
'code': 'outgoing',
'use_create_lots': False,
'use_existing_lots': True,
'default_location_dest_id': self._get_subcontracting_location().id,
'sequence': next_sequence + 3,
'sequence_code': 'RES',
'print_label': True,
'company_id': self.company_id.id,
}
})
return data, max_sequence + 4
def _get_sequence_values(self):
values = super(StockWarehouse, self)._get_sequence_values()
values.update({
'subcontracting_type_id': {
'name': self.name + ' ' + _('Sequence subcontracting'),
'prefix': self.code + '/SBC/',
'padding': 5,
'company_id': self.company_id.id
},
'subcontracting_resupply_type_id': {
'name': self.name + ' ' + _('Sequence Resupply Subcontractor'),
'prefix': self.code + '/RES/',
'padding': 5,
'company_id': self.company_id.id
},
})
return values
def _get_picking_type_update_values(self):
data = super(StockWarehouse, self)._get_picking_type_update_values()
subcontract_location_id = self._get_subcontracting_location()
production_location_id = self._get_production_location()
data.update({
'subcontracting_type_id': {
'active': False,
'default_location_src_id': subcontract_location_id.id,
'default_location_dest_id': production_location_id.id,
},
'subcontracting_resupply_type_id': {
'default_location_src_id': self.lot_stock_id.id,
'default_location_dest_id': subcontract_location_id.id,
'barcode': self.code.replace(" ", "").upper() + "-RESUPPLY",
},
})
return data
def _get_subcontracting_location(self):
return self.company_id.subcontracting_location_id
| 43.023669 | 7,271 |
911 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, models
class StockMoveLine(models.Model):
_inherit = 'stock.move.line'
@api.onchange('lot_name', 'lot_id')
def _onchange_serial_number(self):
current_location_id = self.location_id
res = super()._onchange_serial_number()
if res and not self.lot_name and self.company_id.subcontracting_location_id == current_location_id:
# we want to avoid auto-updating source location in this case + change the warning message
self.location_id = current_location_id
res['warning']['message'] = res['warning']['message'].split("\n\n", 1)[0] + "\n\n" + \
_("Make sure you validate or adapt the related resupply picking to your subcontractor in order to avoid inconsistencies in your stock.")
return res
| 45.55 | 911 |
959 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import UserError
class StockQuant(models.Model):
_inherit = 'stock.quant'
is_subcontract = fields.Boolean(store=False, search='_search_is_subcontract')
def _search_is_subcontract(self, operator, value):
if operator not in ['=', '!='] or not isinstance(value, bool):
raise UserError(_('Operation not supported'))
subcontract_locations = self.env['res.company'].search([]).subcontracting_location_id
quant_ids = self.env['stock.quant'].search([
('location_id', 'in', subcontract_locations.ids),
]).ids
if (operator == '!=' and value is True) or (operator == '=' and value is False):
domain_operator = 'not in'
else:
domain_operator = 'in'
return [('id', domain_operator, quant_ids)]
| 36.884615 | 959 |
11,599 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import fields, models, _
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_compare, float_is_zero
class StockMove(models.Model):
_inherit = 'stock.move'
is_subcontract = fields.Boolean('The move is a subcontract receipt')
show_subcontracting_details_visible = fields.Boolean(
compute='_compute_show_subcontracting_details_visible'
)
def _compute_display_assign_serial(self):
super(StockMove, self)._compute_display_assign_serial()
for move in self:
if not move.is_subcontract:
continue
productions = move._get_subcontract_production()
if not productions or move.has_tracking != 'serial':
continue
if productions._has_tracked_component() or productions[:1].consumption != 'strict':
move.display_assign_serial = False
def _compute_show_subcontracting_details_visible(self):
""" Compute if the action button in order to see moves raw is visible """
self.show_subcontracting_details_visible = False
for move in self:
if not move.is_subcontract:
continue
if float_is_zero(move.quantity_done, precision_rounding=move.product_uom.rounding):
continue
productions = move._get_subcontract_production()
if not productions or (productions[:1].consumption == 'strict' and not productions[:1]._has_tracked_component()):
continue
move.show_subcontracting_details_visible = True
def _compute_show_details_visible(self):
""" If the move is subcontract and the components are tracked. Then the
show details button is visible.
"""
res = super(StockMove, self)._compute_show_details_visible()
for move in self:
if not move.is_subcontract:
continue
productions = move._get_subcontract_production()
if not productions._has_tracked_component() and productions[:1].consumption == 'strict':
continue
move.show_details_visible = True
return res
def copy(self, default=None):
self.ensure_one()
if not self.is_subcontract or 'location_id' in default:
return super(StockMove, self).copy(default=default)
if not default:
default = {}
default['location_id'] = self.picking_id.location_id.id
return super(StockMove, self).copy(default=default)
def write(self, values):
""" If the initial demand is updated then also update the linked
subcontract order to the new quantity.
"""
if 'product_uom_qty' in values and self.env.context.get('cancel_backorder') is not False:
self.filtered(lambda m: m.is_subcontract and m.state not in ['draft', 'cancel', 'done'])._update_subcontract_order_qty(values['product_uom_qty'])
res = super().write(values)
if 'date' in values:
for move in self:
if move.state in ('done', 'cancel') or not move.is_subcontract:
continue
move.move_orig_ids.production_id.filtered(lambda p: p.state not in ('done', 'cancel')).write({
'date_planned_finished': move.date,
'date_planned_start': move.date,
})
return res
def action_show_details(self):
""" Open the produce wizard in order to register tracked components for
subcontracted product. Otherwise use standard behavior.
"""
self.ensure_one()
if self.state != 'done' and (self._subcontrating_should_be_record() or self._subcontrating_can_be_record()):
return self._action_record_components()
action = super(StockMove, self).action_show_details()
if self.is_subcontract and all(p._has_been_recorded() for p in self._get_subcontract_production()):
action['views'] = [(self.env.ref('stock.view_stock_move_operations').id, 'form')]
action['context'].update({
'show_lots_m2o': self.has_tracking != 'none',
'show_lots_text': False,
})
return action
def action_show_subcontract_details(self):
""" Display moves raw for subcontracted product self. """
moves = self._get_subcontract_production().move_raw_ids
tree_view = self.env.ref('mrp_subcontracting.mrp_subcontracting_move_tree_view')
form_view = self.env.ref('mrp_subcontracting.mrp_subcontracting_move_form_view')
ctx = dict(self._context, search_default_by_product=True)
return {
'name': _('Raw Materials for %s') % (self.product_id.display_name),
'type': 'ir.actions.act_window',
'res_model': 'stock.move',
'views': [(tree_view.id, 'list'), (form_view.id, 'form')],
'target': 'current',
'domain': [('id', 'in', moves.ids)],
'context': ctx
}
def _set_quantities_to_reservation(self):
move_untouchable = self.filtered(lambda m: m.is_subcontract and m._get_subcontract_production()._has_tracked_component())
return super(StockMove, self - move_untouchable)._set_quantities_to_reservation()
def _action_cancel(self):
for move in self:
if move.is_subcontract:
active_production = move.move_orig_ids.production_id.filtered(lambda p: p.state not in ('done', 'cancel'))
moves = self.env.context.get('moves_todo')
if not moves or active_production not in moves.move_orig_ids.production_id:
active_production.with_context(skip_activity=True).action_cancel()
return super()._action_cancel()
def _action_confirm(self, merge=True, merge_into=False):
subcontract_details_per_picking = defaultdict(list)
move_to_not_merge = self.env['stock.move']
for move in self:
if move.location_id.usage != 'supplier' or move.location_dest_id.usage == 'supplier':
continue
if move.move_orig_ids.production_id:
continue
bom = move._get_subcontract_bom()
if not bom:
continue
if float_is_zero(move.product_qty, precision_rounding=move.product_uom.rounding) and\
move.picking_id.immediate_transfer is True:
raise UserError(_("To subcontract, use a planned transfer."))
subcontract_details_per_picking[move.picking_id].append((move, bom))
move.write({
'is_subcontract': True,
'location_id': move.picking_id.partner_id.with_company(move.company_id).property_stock_subcontractor.id
})
if float_compare(move.product_qty, 0, precision_rounding=move.product_uom.rounding) <= 0:
# If a subcontracted amount is decreased, don't create a MO that would be for a negative value.
# We don't care if the MO decreases even when done since everything is handled through picking
continue
move_to_not_merge |= move
for picking, subcontract_details in subcontract_details_per_picking.items():
picking._subcontracted_produce(subcontract_details)
# We avoid merging move due to complication with stock.rule.
res = super(StockMove, move_to_not_merge)._action_confirm(merge=False)
res |= super(StockMove, self - move_to_not_merge)._action_confirm(merge=merge, merge_into=merge_into)
if subcontract_details_per_picking:
self.env['stock.picking'].concat(*list(subcontract_details_per_picking.keys())).action_assign()
return res.exists()
def _action_record_components(self):
self.ensure_one()
production = self._get_subcontract_production()[-1:]
view = self.env.ref('mrp_subcontracting.mrp_production_subcontracting_form_view')
context = dict(self._context)
context.pop('default_picking_id', False)
return {
'name': _('Subcontract'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mrp.production',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'res_id': production.id,
'context': context,
}
def _get_subcontract_bom(self):
self.ensure_one()
bom = self.env['mrp.bom'].sudo()._bom_subcontract_find(
self.product_id,
picking_type=self.picking_type_id,
company_id=self.company_id.id,
bom_type='subcontract',
subcontractor=self.picking_id.partner_id,
)
return bom
def _subcontrating_should_be_record(self):
return self._get_subcontract_production().filtered(lambda p: not p._has_been_recorded() and p._has_tracked_component())
def _subcontrating_can_be_record(self):
return self._get_subcontract_production().filtered(lambda p: not p._has_been_recorded() and p.consumption != 'strict')
def _get_subcontract_production(self):
return self.filtered(lambda m: m.is_subcontract).move_orig_ids.production_id
# TODO: To be deleted, use self._get_subcontract_production()._has_tracked_component() instead
def _has_tracked_subcontract_components(self):
return any(m.has_tracking != 'none' for m in self._get_subcontract_production().move_raw_ids)
def _prepare_extra_move_vals(self, qty):
vals = super(StockMove, self)._prepare_extra_move_vals(qty)
vals['location_id'] = self.location_id.id
return vals
def _prepare_move_split_vals(self, qty):
vals = super(StockMove, self)._prepare_move_split_vals(qty)
vals['location_id'] = self.location_id.id
return vals
def _should_bypass_set_qty_producing(self):
if (self.production_id | self.raw_material_production_id)._get_subcontract_move():
return False
return super()._should_bypass_set_qty_producing()
def _should_bypass_reservation(self, forced_location=False):
""" If the move is subcontracted then ignore the reservation. """
should_bypass_reservation = super()._should_bypass_reservation(forced_location=forced_location)
if not should_bypass_reservation and self.is_subcontract:
return True
return should_bypass_reservation
def _update_subcontract_order_qty(self, new_quantity):
for move in self:
quantity_to_remove = move.product_uom_qty - new_quantity
productions = move.move_orig_ids.production_id.filtered(lambda p: p.state not in ('done', 'cancel'))[::-1]
# Cancel productions until reach new_quantity
for production in productions:
if quantity_to_remove <= 0.0:
break
if quantity_to_remove >= production.product_qty:
quantity_to_remove -= production.product_qty
production.with_context(skip_activity=True).action_cancel()
else:
self.env['change.production.qty'].with_context(skip_activity=True).create({
'mo_id': production.id,
'product_qty': production.product_uom_qty - quantity_to_remove
}).change_prod_qty()
| 48.128631 | 11,599 |
1,441 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
subcontracting_location_id = fields.Many2one('stock.location')
@api.model
def create_missing_subcontracting_location(self):
company_without_subcontracting_loc = self.env['res.company'].search(
[('subcontracting_location_id', '=', False)])
company_without_subcontracting_loc._create_subcontracting_location()
def _create_per_company_locations(self):
super(ResCompany, self)._create_per_company_locations()
self._create_subcontracting_location()
def _create_subcontracting_location(self):
parent_location = self.env.ref('stock.stock_location_locations', raise_if_not_found=False)
for company in self:
subcontracting_location = self.env['stock.location'].create({
'name': _('Subcontracting Location'),
'usage': 'internal',
'location_id': parent_location.id,
'company_id': company.id,
})
self.env['ir.property']._set_default(
"property_stock_subcontractor",
"res.partner",
subcontracting_location,
company,
)
company.subcontracting_location_id = subcontracting_location
| 38.945946 | 1,441 |
9,445 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_compare
from dateutil.relativedelta import relativedelta
class StockPicking(models.Model):
_inherit = 'stock.picking'
# override existing field domains to prevent suboncontracting production lines from showing in Detailed Operations tab
move_line_nosuggest_ids = fields.One2many(
domain=['&', '|', ('location_dest_id.usage', '!=', 'production'), ('move_id.picking_code', '!=', 'outgoing'),
'|', ('product_qty', '=', 0.0), '&', ('product_qty', '!=', 0.0), ('qty_done', '!=', 0.0)])
move_line_ids_without_package = fields.One2many(
domain=['&', '|', ('location_dest_id.usage', '!=', 'production'), ('move_id.picking_code', '!=', 'outgoing'),
'|', ('package_level_id', '=', False), ('picking_type_entire_packs', '=', False)])
display_action_record_components = fields.Selection(
[('hide', 'Hide'), ('facultative', 'Facultative'), ('mandatory', 'Mandatory')],
compute='_compute_display_action_record_components')
@api.depends('state', 'move_lines')
def _compute_display_action_record_components(self):
self.display_action_record_components = 'hide'
for picking in self:
# Hide if not encoding state or it is not a subcontracting picking
if picking.state in ('draft', 'cancel', 'done') or not picking._is_subcontract():
continue
subcontracted_moves = picking.move_lines.filtered(lambda m: m.is_subcontract)
if subcontracted_moves._subcontrating_should_be_record():
picking.display_action_record_components = 'mandatory'
continue
if subcontracted_moves._subcontrating_can_be_record():
picking.display_action_record_components = 'facultative'
# -------------------------------------------------------------------------
# Action methods
# -------------------------------------------------------------------------
def _action_done(self):
res = super(StockPicking, self)._action_done()
for move in self.move_lines.filtered(lambda move: move.is_subcontract):
# Auto set qty_producing/lot_producing_id of MO wasn't recorded
# manually (if the flexible + record_component or has tracked component)
productions = move._get_subcontract_production()
recorded_productions = productions.filtered(lambda p: p._has_been_recorded())
recorded_qty = sum(recorded_productions.mapped('qty_producing'))
sm_done_qty = sum(productions._get_subcontract_move().mapped('quantity_done'))
rounding = self.env['decimal.precision'].precision_get('Product Unit of Measure')
if float_compare(recorded_qty, sm_done_qty, precision_digits=rounding) >= 0:
continue
production = productions - recorded_productions
if not production:
continue
if len(production) > 1:
raise UserError("It shouldn't happen to have multiple production to record for the same subcontracted move")
# Manage additional quantities
quantity_done_move = move.product_uom._compute_quantity(move.quantity_done, production.product_uom_id)
if float_compare(production.product_qty, quantity_done_move, precision_rounding=production.product_uom_id.rounding) == -1:
change_qty = self.env['change.production.qty'].create({
'mo_id': production.id,
'product_qty': quantity_done_move
})
change_qty.with_context(skip_activity=True).change_prod_qty()
# Create backorder MO for each move lines
for move_line in move.move_line_ids:
if move_line.lot_id:
production.lot_producing_id = move_line.lot_id
production.qty_producing = move_line.product_uom_id._compute_quantity(move_line.qty_done, production.product_uom_id)
production._set_qty_producing()
production.subcontracting_has_been_recorded = True
if move_line != move.move_line_ids[-1]:
backorder = production._generate_backorder_productions(close_mo=False)
# The move_dest_ids won't be set because the _split filter out done move
backorder.move_finished_ids.filtered(lambda mo: mo.product_id == move.product_id).move_dest_ids = production.move_finished_ids.filtered(lambda mo: mo.product_id == move.product_id).move_dest_ids
production.product_qty = production.qty_producing
production = backorder
for picking in self:
productions_to_done = picking._get_subcontract_production()._subcontracting_filter_to_done()
if not productions_to_done:
continue
productions_to_done = productions_to_done.sudo()
production_ids_backorder = []
if not self.env.context.get('cancel_backorder'):
production_ids_backorder = productions_to_done.filtered(lambda mo: mo.state == "progress").ids
productions_to_done.with_context(mo_ids_to_backorder=production_ids_backorder).button_mark_done()
# For concistency, set the date on production move before the date
# on picking. (Traceability report + Product Moves menu item)
minimum_date = min(picking.move_line_ids.mapped('date'))
production_moves = productions_to_done.move_raw_ids | productions_to_done.move_finished_ids
production_moves.write({'date': minimum_date - timedelta(seconds=1)})
production_moves.move_line_ids.write({'date': minimum_date - timedelta(seconds=1)})
return res
def action_record_components(self):
self.ensure_one()
move_subcontracted = self.move_lines.filtered(lambda m: m.is_subcontract)
for move in move_subcontracted:
production = move._subcontrating_should_be_record()
if production:
return move._action_record_components()
for move in move_subcontracted:
production = move._subcontrating_can_be_record()
if production:
return move._action_record_components()
raise UserError(_("Nothing to record"))
# -------------------------------------------------------------------------
# Subcontract helpers
# -------------------------------------------------------------------------
def _is_subcontract(self):
self.ensure_one()
return self.picking_type_id.code == 'incoming' and any(m.is_subcontract for m in self.move_lines)
def _get_subcontract_production(self):
return self.move_lines._get_subcontract_production()
def _get_warehouse(self, subcontract_move):
return subcontract_move.warehouse_id or self.picking_type_id.warehouse_id or subcontract_move.move_dest_ids.picking_type_id.warehouse_id
def _prepare_subcontract_mo_vals(self, subcontract_move, bom):
subcontract_move.ensure_one()
group = self.env['procurement.group'].create({
'name': self.name,
'partner_id': self.partner_id.id,
})
product = subcontract_move.product_id
warehouse = self._get_warehouse(subcontract_move)
vals = {
'company_id': subcontract_move.company_id.id,
'procurement_group_id': group.id,
'product_id': product.id,
'product_uom_id': subcontract_move.product_uom.id,
'bom_id': bom.id,
'location_src_id': subcontract_move.picking_id.partner_id.with_company(subcontract_move.company_id).property_stock_subcontractor.id,
'location_dest_id': subcontract_move.picking_id.partner_id.with_company(subcontract_move.company_id).property_stock_subcontractor.id,
'product_qty': subcontract_move.product_uom_qty,
'picking_type_id': warehouse.subcontracting_type_id.id,
'date_planned_start': subcontract_move.date - relativedelta(days=product.produce_delay)
}
return vals
def _subcontracted_produce(self, subcontract_details):
self.ensure_one()
for move, bom in subcontract_details:
if float_compare(move.product_qty, 0, precision_rounding=move.product_uom.rounding) <= 0:
# If a subcontracted amount is decreased, don't create a MO that would be for a negative value.
continue
mo = self.env['mrp.production'].with_company(move.company_id).create(self._prepare_subcontract_mo_vals(move, bom))
self.env['stock.move'].create(mo._get_moves_raw_values())
self.env['stock.move'].create(mo._get_moves_finished_values())
mo.date_planned_finished = move.date # Avoid to have the picking late depending of the MO
mo.action_confirm()
# Link the finished to the receipt move.
finished_move = mo.move_finished_ids.filtered(lambda m: m.product_id == move.product_id)
finished_move.write({'move_dest_ids': [(4, move.id, False)]})
mo.action_assign()
| 57.944785 | 9,445 |
1,182 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class SupplierInfo(models.Model):
_inherit = 'product.supplierinfo'
is_subcontractor = fields.Boolean('Subcontracted', compute='_compute_is_subcontractor', help="Choose a vendor of type subcontractor if you want to subcontract the product")
@api.depends('name', 'product_id', 'product_tmpl_id')
def _compute_is_subcontractor(self):
for supplier in self:
boms = supplier.product_id.variant_bom_ids
boms |= supplier.product_tmpl_id.bom_ids.filtered(lambda b: not b.product_id or b.product_id in (supplier.product_id or supplier.product_tmpl_id.product_variant_ids))
supplier.is_subcontractor = supplier.name in boms.subcontractor_ids
class ProductProduct(models.Model):
_inherit = 'product.product'
def _prepare_sellers(self, params=False):
if params and params.get('subcontractor_ids'):
return super()._prepare_sellers(params=params).filtered(lambda s: s.name in params.get('subcontractor_ids'))
return super()._prepare_sellers(params=params)
| 45.461538 | 1,182 |
435 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class StockRule(models.Model):
_inherit = "stock.rule"
def _push_prepare_move_copy_values(self, move_to_copy, new_date):
new_move_vals = super(StockRule, self)._push_prepare_move_copy_values(move_to_copy, new_date)
new_move_vals["is_subcontract"] = False
return new_move_vals
| 33.461538 | 435 |
9,460 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import fields, models, _, api
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools.float_utils import float_compare, float_is_zero
class MrpProduction(models.Model):
_inherit = 'mrp.production'
move_line_raw_ids = fields.One2many(
'stock.move.line', string="Detail Component", readonly=False,
inverse='_inverse_move_line_raw_ids', compute='_compute_move_line_raw_ids'
)
subcontracting_has_been_recorded = fields.Boolean("Has been recorded?", copy=False)
incoming_picking = fields.Many2one(related='move_finished_ids.move_dest_ids.picking_id')
@api.depends('name')
def name_get(self):
return [
(record.id, "%s (%s)" % (record.incoming_picking.name, record.name)) if record.bom_id.type == 'subcontract'
else (record.id, record.name) for record in self
]
@api.model
def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
args = list(args or [])
if name == '' and operator == 'ilike':
return self._search(args, limit=limit, access_rights_uid=name_get_uid)
# search through MO
domain = [(self._rec_name, operator, name)]
# search through transfers
picking_rec_name = self.env['stock.picking']._rec_name
picking_domain = [('bom_id.type', '=', 'subcontract'), ('incoming_picking.%s' % picking_rec_name, operator, name)]
domain = expression.OR([domain, picking_domain])
args = expression.AND([args, domain])
return self._search(args, limit=limit, access_rights_uid=name_get_uid)
@api.depends('move_raw_ids.move_line_ids')
def _compute_move_line_raw_ids(self):
for production in self:
production.move_line_raw_ids = production.move_raw_ids.move_line_ids
def _inverse_move_line_raw_ids(self):
for production in self:
line_by_product = defaultdict(lambda: self.env['stock.move.line'])
for line in production.move_line_raw_ids:
line_by_product[line.product_id] |= line
for move in production.move_raw_ids:
move.move_line_ids = line_by_product.pop(move.product_id, self.env['stock.move.line'])
for product_id, lines in line_by_product.items():
qty = sum(line.product_uom_id._compute_quantity(line.qty_done, product_id.uom_id) for line in lines)
move = production._get_move_raw_values(product_id, qty, product_id.uom_id)
move['additional'] = True
production.move_raw_ids = [(0, 0, move)]
production.move_raw_ids.filtered(lambda m: m.product_id == product_id)[:1].move_line_ids = lines
def subcontracting_record_component(self):
self.ensure_one()
if not self._get_subcontract_move():
raise UserError(_("This MO isn't related to a subcontracted move"))
if float_is_zero(self.qty_producing, precision_rounding=self.product_uom_id.rounding):
return {'type': 'ir.actions.act_window_close'}
if self.product_tracking != 'none' and not self.lot_producing_id:
raise UserError(_('You must enter a serial number for %s') % self.product_id.name)
for sml in self.move_raw_ids.move_line_ids:
if sml.tracking != 'none' and not sml.lot_id:
raise UserError(_('You must enter a serial number for each line of %s') % sml.product_id.display_name)
if self.move_raw_ids and not any(self.move_raw_ids.mapped('quantity_done')):
raise UserError(_("You must indicate a non-zero amount consumed for at least one of your components"))
consumption_issues = self._get_consumption_issues()
if consumption_issues:
return self._action_generate_consumption_wizard(consumption_issues)
self._update_finished_move()
self.subcontracting_has_been_recorded = True
quantity_issues = self._get_quantity_produced_issues()
if quantity_issues:
backorder = self._generate_backorder_productions(close_mo=False)
# No qty to consume to avoid propagate additional move
# TODO avoid : stock move created in backorder with 0 as qty
backorder.move_raw_ids.filtered(lambda m: m.additional).product_uom_qty = 0.0
backorder.qty_producing = backorder.product_qty
backorder._set_qty_producing()
self.product_qty = self.qty_producing
action = self._get_subcontract_move().filtered(lambda m: m.state not in ('done', 'cancel'))._action_record_components()
action['res_id'] = backorder.id
return action
return {'type': 'ir.actions.act_window_close'}
def _pre_button_mark_done(self):
if self._get_subcontract_move():
return True
return super()._pre_button_mark_done()
def _update_finished_move(self):
""" After producing, set the move line on the subcontract picking. """
self.ensure_one()
subcontract_move_id = self._get_subcontract_move().filtered(lambda m: m.state not in ('done', 'cancel'))
if subcontract_move_id:
quantity = self.qty_producing
if self.lot_producing_id:
move_lines = subcontract_move_id.move_line_ids.filtered(lambda ml: ml.lot_id == self.lot_producing_id or not ml.lot_id)
else:
move_lines = subcontract_move_id.move_line_ids.filtered(lambda ml: not ml.lot_id)
# Update reservation and quantity done
for ml in move_lines:
rounding = ml.product_uom_id.rounding
if float_compare(quantity, 0, precision_rounding=rounding) <= 0:
break
quantity_to_process = min(quantity, ml.product_uom_qty - ml.qty_done)
quantity -= quantity_to_process
new_quantity_done = (ml.qty_done + quantity_to_process)
# on which lot of finished product
if float_compare(new_quantity_done, ml.product_uom_qty, precision_rounding=rounding) >= 0:
ml.write({
'qty_done': new_quantity_done,
'lot_id': self.lot_producing_id and self.lot_producing_id.id,
})
else:
new_qty_reserved = ml.product_uom_qty - new_quantity_done
default = {
'product_uom_qty': new_quantity_done,
'qty_done': new_quantity_done,
'lot_id': self.lot_producing_id and self.lot_producing_id.id,
}
ml.copy(default=default)
ml.with_context(bypass_reservation_update=True).write({
'product_uom_qty': new_qty_reserved,
'qty_done': 0
})
if float_compare(quantity, 0, precision_rounding=self.product_uom_id.rounding) > 0:
self.env['stock.move.line'].create({
'move_id': subcontract_move_id.id,
'picking_id': subcontract_move_id.picking_id.id,
'product_id': self.product_id.id,
'location_id': subcontract_move_id.location_id.id,
'location_dest_id': subcontract_move_id.location_dest_id.id,
'product_uom_qty': 0,
'product_uom_id': self.product_uom_id.id,
'qty_done': quantity,
'lot_id': self.lot_producing_id and self.lot_producing_id.id,
})
if not self._get_quantity_to_backorder():
ml_reserved = subcontract_move_id.move_line_ids.filtered(lambda ml:
float_is_zero(ml.qty_done, precision_rounding=ml.product_uom_id.rounding) and
not float_is_zero(ml.product_uom_qty, precision_rounding=ml.product_uom_id.rounding))
ml_reserved.unlink()
for ml in subcontract_move_id.move_line_ids:
ml.product_uom_qty = ml.qty_done
subcontract_move_id._recompute_state()
def _subcontracting_filter_to_done(self):
""" Filter subcontracting production where composant is already recorded and should be consider to be validate """
def filter_in(mo):
if mo.state in ('done', 'cancel'):
return False
if not mo.subcontracting_has_been_recorded:
return False
if not all(line.lot_id for line in mo.move_raw_ids.filtered(lambda sm: sm.has_tracking != 'none').move_line_ids):
return False
if mo.product_tracking != 'none' and not mo.lot_producing_id:
return False
return True
return self.filtered(filter_in)
def _has_been_recorded(self):
self.ensure_one()
if self.state in ('cancel', 'done'):
return True
return self.subcontracting_has_been_recorded
def _has_tracked_component(self):
return any(m.has_tracking != 'none' for m in self.move_raw_ids)
def _get_subcontract_move(self):
return self.move_finished_ids.move_dest_ids.filtered(lambda m: m.is_subcontract)
| 49.528796 | 9,460 |
1,117 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
property_stock_subcontractor = fields.Many2one(
'stock.location', string="Subcontractor Location", company_dependent=True,
help="The stock location used as source and destination when sending\
goods to this contact during a subcontracting process.")
is_subcontractor = fields.Boolean(
string="Subcontractor", store=False, search="_search_is_subcontractor")
def _search_is_subcontractor(self, operator, value):
assert operator in ('=', '!=', '<>') and value in (True, False), 'Operation not supported'
subcontractor_ids = self.env['mrp.bom'].search(
[('type', '=', 'subcontract')]).subcontractor_ids.ids
if (operator == '=' and value is True) or (operator in ('<>', '!=') and value is False):
search_operator = 'in'
else:
search_operator = 'not in'
return [('id', search_operator, subcontractor_ids)]
| 44.68 | 1,117 |
1,457 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.osv.expression import AND
class MrpBom(models.Model):
_inherit = 'mrp.bom'
type = fields.Selection(selection_add=[
('subcontract', 'Subcontracting')
], ondelete={'subcontract': lambda recs: recs.write({'type': 'normal', 'active': False})})
subcontractor_ids = fields.Many2many('res.partner', 'mrp_bom_subcontractor', string='Subcontractors', check_company=True)
def _bom_subcontract_find(self, product, picking_type=None, company_id=False, bom_type='subcontract', subcontractor=False):
domain = self._bom_find_domain(product, picking_type=picking_type, company_id=company_id, bom_type=bom_type)
if subcontractor:
domain = AND([domain, [('subcontractor_ids', 'parent_of', subcontractor.ids)]])
return self.search(domain, order='sequence, product_id, id', limit=1)
else:
return self.env['mrp.bom']
@api.constrains('operation_ids', 'byproduct_ids', 'type')
def _check_subcontracting_no_operation(self):
if self.filtered_domain([('type', '=', 'subcontract'), '|', ('operation_ids', '!=', False), ('byproduct_ids', '!=', False)]):
raise ValidationError(_('You can not set a Bill of Material with operations or by-product line as subcontracting.'))
| 53.962963 | 1,457 |
3,357 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _, fields
class ReportBomStructure(models.AbstractModel):
_inherit = 'report.mrp.report_bom_structure'
def _get_subcontracting_line(self, bom, seller, level, bom_quantity):
ratio_uom_seller = seller.product_uom.ratio / bom.product_uom_id.ratio
price = seller.currency_id._convert(seller.price, self.env.company.currency_id, (bom.company_id or self.env.company), fields.Date.today())
return {
'name': seller.name.display_name,
'partner_id': seller.name.id,
'quantity': bom_quantity,
'uom': bom.product_uom_id.name,
'prod_cost': price / ratio_uom_seller * bom_quantity,
'bom_cost': price / ratio_uom_seller * bom_quantity,
'level': level or 0
}
def _get_price(self, bom, factor, product):
price = super()._get_price(bom, factor, product)
if bom and bom.type == 'subcontract':
bom_quantity = bom.product_qty * factor
seller = product._select_seller(quantity=bom_quantity, uom_id=bom.product_uom_id, params={'subcontractor_ids': bom.subcontractor_ids})
if seller:
price += seller.product_uom._compute_price(seller.price, product.uom_id) * bom_quantity
return price
def _get_bom(self, bom_id=False, product_id=False, line_qty=False, line_id=False, level=False):
res = super(ReportBomStructure, self)._get_bom(bom_id, product_id, line_qty, line_id, level)
bom = res['bom']
if bom and bom.type == 'subcontract':
bom_quantity = line_qty
if line_id:
current_line = self.env['mrp.bom.line'].browse(int(line_id))
bom_quantity = current_line.product_uom_id._compute_quantity(line_qty, bom.product_uom_id)
seller = res['product']._select_seller(quantity=bom_quantity, uom_id=bom.product_uom_id, params={'subcontractor_ids': bom.subcontractor_ids})
if seller:
res['subcontracting'] = self._get_subcontracting_line(bom, seller, level, bom_quantity)
res['total'] += res['subcontracting']['bom_cost']
res['bom_cost'] += res['subcontracting']['bom_cost']
return res
def _get_sub_lines(self, bom, product_id, line_qty, line_id, level, child_bom_ids, unfolded):
res = super()._get_sub_lines(bom, product_id, line_qty, line_id, level, child_bom_ids, unfolded)
if bom and bom.type == 'subcontract':
product = self.env['product.product'].browse(product_id)
bom_quantity = line_qty
if line_id:
current_line = self.env['mrp.bom.line'].browse(int(line_id))
bom_quantity = current_line.product_uom_id._compute_quantity(line_qty, bom.product_uom_id)
seller = product._select_seller(quantity=bom_quantity, uom_id=bom.product_uom_id, params={'subcontractor_ids': bom.subcontractor_ids})
if seller:
values_sub = self._get_subcontracting_line(bom, seller, level, bom_quantity)
values_sub['type'] = 'bom'
values_sub['name'] = _("Subcontracting: ") + values_sub['name']
res.append(values_sub)
return res
| 51.646154 | 3,357 |
1,850 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Gamification',
'version': '1.0',
'sequence': 160,
'category': 'Human Resources',
'depends': ['mail', 'web_kanban_gauge'],
'description': """
Gamification process
====================
The Gamification module provides ways to evaluate and motivate the users of Odoo.
The users can be evaluated using goals and numerical objectives to reach.
**Goals** are assigned through **challenges** to evaluate and compare members of a team with each others and through time.
For non-numerical achievements, **badges** can be granted to users. From a simple "thank you" to an exceptional achievement, a badge is an easy way to exprimate gratitude to a user for their good work.
Both goals and badges are flexibles and can be adapted to a large range of modules and actions. When installed, this module creates easy goals to help new users to discover Odoo and configure their user profile.
""",
'data': [
'wizard/update_goal.xml',
'wizard/grant_badge.xml',
'views/badge.xml',
'views/challenge.xml',
'views/goal.xml',
'data/cron.xml',
'security/gamification_security.xml',
'security/ir.model.access.csv',
'data/mail_template_data.xml',
'data/goal_base.xml',
'data/badge.xml',
'data/gamification_karma_rank_data.xml',
'views/gamification_karma_rank_views.xml',
'views/gamification_karma_tracking_views.xml',
'views/res_users_views.xml',
],
'demo': [
'data/gamification_karma_rank_demo.xml',
'data/gamification_karma_tracking_demo.xml',
],
'assets': {
'web.assets_backend': [
'gamification/static/src/**/*',
],
},
'license': 'LGPL-3',
}
| 37.755102 | 1,850 |
6,620 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from odoo.addons.base.tests.common import TransactionCaseWithUserDemo
from odoo.exceptions import UserError
from odoo.tools import mute_logger
class TestGamificationCommon(TransactionCaseWithUserDemo):
def setUp(self):
super(TestGamificationCommon, self).setUp()
employees_group = self.env.ref('base.group_user')
self.user_ids = employees_group.users
# Push demo user into the challenge before creating a new one
self.env.ref('gamification.challenge_base_discover')._update_all()
self.robot = self.env['res.users'].with_context(no_reset_password=True).create({
'name': 'R2D2',
'login': '[email protected]',
'email': '[email protected]',
'groups_id': [(6, 0, [employees_group.id])]
})
self.badge_good_job = self.env.ref('gamification.badge_good_job')
class test_challenge(TestGamificationCommon):
def test_00_join_challenge(self):
challenge = self.env.ref('gamification.challenge_base_discover')
self.assertGreaterEqual(len(challenge.user_ids), len(self.user_ids), "Not enough users in base challenge")
challenge._update_all()
self.assertGreaterEqual(len(challenge.user_ids), len(self.user_ids)+1, "These are not droids you are looking for")
def test_10_reach_challenge(self):
Goals = self.env['gamification.goal']
challenge = self.env.ref('gamification.challenge_base_discover')
challenge.state = 'inprogress'
self.assertEqual(challenge.state, 'inprogress', "Challenge failed the change of state")
goal_ids = Goals.search([('challenge_id', '=', challenge.id), ('state', '!=', 'draft')])
self.assertEqual(len(goal_ids), len(challenge.line_ids) * len(challenge.user_ids.ids), "Incorrect number of goals generated, should be 1 goal per user, per challenge line")
demo = self.user_demo
# demo user will set a timezone
demo.tz = "Europe/Brussels"
goal_ids = Goals.search([('user_id', '=', demo.id), ('definition_id', '=', self.env.ref('gamification.definition_base_timezone').id)])
goal_ids.update_goal()
missed = goal_ids.filtered(lambda g: g.state != 'reached')
self.assertFalse(missed, "Not every goal was reached after changing timezone")
# reward for two firsts as admin may have timezone
badge_id = self.badge_good_job.id
challenge.write({'reward_first_id': badge_id, 'reward_second_id': badge_id})
challenge.state = 'done'
badge_ids = self.env['gamification.badge.user'].search([('badge_id', '=', badge_id), ('user_id', '=', demo.id)])
self.assertEqual(len(badge_ids), 1, "Demo user has not received the badge")
@mute_logger('odoo.models.unlink')
def test_20_update_all_goals_filter(self):
# Enroll two internal and two portal users in the challenge
(
portal_login_before_update,
portal_login_after_update,
internal_login_before_update,
internal_login_after_update,
) = all_test_users = self.env['res.users'].create([
{
'name': f'{kind} {age} login',
'login': f'{kind}_{age}',
'email': f'{kind}_{age}',
'groups_id': [(6, 0, groups_id)],
}
for kind, groups_id in (
('Portal', []),
('Internal', [self.env.ref('base.group_user').id]),
)
for age in ('Old', 'Recent')
])
challenge = self.env.ref('gamification.challenge_base_discover')
challenge.write({
'state': 'inprogress',
'user_domain': False,
'user_ids': [(6, 0, all_test_users.ids)]
})
# Setup user access logs
self.env['res.users.log'].search([('create_uid', 'in', challenge.user_ids.ids)]).unlink()
now = datetime.datetime.now()
# Create "old" log in records
self.env['res.users.log'].create([
{"create_uid": internal_login_before_update.id, 'create_date': now - datetime.timedelta(minutes=3)},
{"create_uid": portal_login_before_update.id, 'create_date': now - datetime.timedelta(minutes=3)},
])
# Reset goal objective values
all_test_users.partner_id.tz = False
# Regenerate all goals
self.env["gamification.goal"].search([]).unlink()
self.assertFalse(self.env['gamification.goal'].search([]))
challenge.action_check()
goal_ids = self.env['gamification.goal'].search(
[('challenge_id', '=', challenge.id), ('state', '!=', 'draft'), ('user_id', 'in', challenge.user_ids.ids)]
)
self.assertEqual(len(goal_ids), 4)
self.assertEqual(set(goal_ids.mapped('state')), {'inprogress'})
# Create more recent log in records
self.env['res.users.log'].create([
{"create_uid": internal_login_after_update.id, 'create_date': now + datetime.timedelta(minutes=3)},
{"create_uid": portal_login_after_update.id, 'create_date': now + datetime.timedelta(minutes=3)},
])
# Update goal objective checked by goal definition
all_test_users.partner_id.write({'tz': 'Europe/Paris'})
# Update goals as done by _cron_update
challenge._update_all()
unchanged_goal_id = self.env['gamification.goal'].search([
('challenge_id', '=', challenge.id),
('state', '=', 'inprogress'), # others were updated to "reached"
('user_id', 'in', challenge.user_ids.ids),
])
# Check that even though login record for internal user is older than goal update, their goal was reached.
self.assertEqual(
portal_login_before_update,
unchanged_goal_id.user_id,
"Only portal user last logged in before last challenge update should not have been updated.",
)
class test_badge_wizard(TestGamificationCommon):
def test_grant_badge(self):
wiz = self.env['gamification.badge.user.wizard'].create({
'user_id': self.env.user.id,
'badge_id': self.badge_good_job.id,
})
with self.assertRaises(UserError, msg="A user cannot grant a badge to himself"):
wiz.action_grant_badge()
wiz.user_id = self.robot.id
self.assertTrue(wiz.action_grant_badge(), "Could not grant badge")
self.assertEqual(self.badge_good_job.stat_this_month, 1)
| 43.267974 | 6,620 |
13,776 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date
from dateutil.relativedelta import relativedelta
from unittest.mock import patch
from odoo import exceptions, fields
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.tests import common
class TestKarmaTrackingCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestKarmaTrackingCommon, cls).setUpClass()
cls.test_user = mail_new_test_user(
cls.env, login='test',
name='Test User', email='[email protected]',
karma=0,
groups='base.group_user',
)
cls.test_user_2 = mail_new_test_user(
cls.env, login='test2',
name='Test User 2', email='[email protected]',
karma=0,
groups='base.group_user',
)
cls.env['gamification.karma.tracking'].search([]).unlink()
cls.test_date = fields.Date.today() + relativedelta(month=4, day=1)
@classmethod
def _create_trackings(cls, user, karma, steps, track_date, days_delta=1):
old_value = user.karma
for step in range(steps):
new_value = old_value + karma
cls.env['gamification.karma.tracking'].create([{
'user_id': user.id,
'old_value': old_value,
'new_value': new_value,
'consolidated': False,
'tracking_date': fields.Date.to_string(track_date)
}])
old_value = new_value
track_date = track_date + relativedelta(days=days_delta)
def test_computation_gain(self):
self._create_trackings(self.test_user, 20, 2, self.test_date, days_delta=30)
self._create_trackings(self.test_user_2, 10, 20, self.test_date, days_delta=2)
results = (self.test_user | self.test_user_2)._get_tracking_karma_gain_position([])
self.assertEqual(results[0]['user_id'], self.test_user_2.id)
self.assertEqual(results[0]['karma_gain_total'], 200)
self.assertEqual(results[0]['karma_position'], 1)
self.assertEqual(results[1]['user_id'], self.test_user.id)
self.assertEqual(results[1]['karma_gain_total'], 40)
self.assertEqual(results[1]['karma_position'], 2)
results = (self.test_user | self.test_user_2)._get_tracking_karma_gain_position([], to_date=self.test_date + relativedelta(day=2))
self.assertEqual(results[0]['user_id'], self.test_user.id)
self.assertEqual(results[0]['karma_gain_total'], 20)
self.assertEqual(results[0]['karma_position'], 1)
self.assertEqual(results[1]['user_id'], self.test_user_2.id)
self.assertEqual(results[1]['karma_gain_total'], 10)
self.assertEqual(results[1]['karma_position'], 2)
results = (self.test_user | self.test_user_2)._get_tracking_karma_gain_position([], from_date=self.test_date + relativedelta(months=1, day=1))
self.assertEqual(results[0]['user_id'], self.test_user_2.id)
self.assertEqual(results[0]['karma_gain_total'], 50)
self.assertEqual(results[0]['karma_position'], 1)
self.assertEqual(results[1]['user_id'], self.test_user.id)
self.assertEqual(results[1]['karma_gain_total'], 20)
self.assertEqual(results[1]['karma_position'], 2)
results = self.env['res.users']._get_tracking_karma_gain_position([])
self.assertEqual(len(results), 0)
def test_consolidation_cron(self):
self.patcher = patch('odoo.addons.gamification.models.gamification_karma_tracking.fields.Date', wraps=fields.Date)
self.mock_datetime = self.patcher.start()
self.mock_datetime.today.return_value = date(self.test_date.year, self.test_date.month + 1, self.test_date.day)
self._create_trackings(self.test_user, 20, 2, self.test_date, days_delta=30)
self._create_trackings(self.test_user_2, 10, 20, self.test_date, days_delta=2)
self.env['gamification.karma.tracking']._consolidate_last_month()
consolidated = self.env['gamification.karma.tracking'].search([
('user_id', 'in', (self.test_user | self.test_user_2).ids),
('consolidated', '=', True),
('tracking_date', '=', self.test_date)
])
self.assertEqual(len(consolidated), 2)
unconsolidated = self.env['gamification.karma.tracking'].search([
('user_id', 'in', (self.test_user | self.test_user_2).ids),
('consolidated', '=', False),
])
self.assertEqual(len(unconsolidated), 6) # 5 for test user 2, 1 for test user
self.patcher.stop()
def test_consolidation_monthly(self):
Tracking = self.env['gamification.karma.tracking']
base_test_user_karma = self.test_user.karma
base_test_user_2_karma = self.test_user_2.karma
self._create_trackings(self.test_user, 20, 2, self.test_date, days_delta=30)
self._create_trackings(self.test_user_2, 10, 20, self.test_date, days_delta=2)
Tracking._process_consolidate(self.test_date)
consolidated = Tracking.search([
('user_id', '=', self.test_user_2.id),
('consolidated', '=', True),
('tracking_date', '=', self.test_date)
])
self.assertEqual(len(consolidated), 1)
self.assertEqual(consolidated.old_value, base_test_user_2_karma) # 15 2-days span, from 1 to 29 included = 15 steps -> 150 karma
self.assertEqual(consolidated.new_value, base_test_user_2_karma + 150) # 15 2-days span, from 1 to 29 included = 15 steps -> 150 karma
remaining = Tracking.search([
('user_id', '=', self.test_user_2.id),
('consolidated', '=', False)
])
self.assertEqual(len(remaining), 5) # 15 steps consolidated, remaining 5
self.assertEqual(remaining[0].tracking_date, self.test_date + relativedelta(months=1, day=9)) # ordering: last first
self.assertEqual(remaining[-1].tracking_date, self.test_date + relativedelta(months=1, day=1))
Tracking._process_consolidate(self.test_date + relativedelta(months=1))
consolidated = Tracking.search([
('user_id', '=', self.test_user_2.id),
('consolidated', '=', True),
])
self.assertEqual(len(consolidated), 2)
self.assertEqual(consolidated[0].new_value, base_test_user_2_karma + 200) # 5 remaining 2-days span, from 1 to 9 included = 5 steps -> 50 karma
self.assertEqual(consolidated[0].old_value, base_test_user_2_karma + 150) # coming from previous iteration
self.assertEqual(consolidated[0].tracking_date, self.test_date + relativedelta(months=1)) # tracking set at beginning of month
self.assertEqual(consolidated[-1].new_value, base_test_user_2_karma + 150) # previously created one still present
self.assertEqual(consolidated[-1].old_value, base_test_user_2_karma) # previously created one still present
remaining = Tracking.search([
('user_id', '=', self.test_user_2.id),
('consolidated', '=', False)
])
self.assertFalse(remaining)
# current user not-in-details tests
current_user_trackings = Tracking.search([
('user_id', '=', self.test_user.id),
])
self.assertEqual(len(current_user_trackings), 2)
self.assertEqual(current_user_trackings[0].new_value, base_test_user_karma + 40)
self.assertEqual(current_user_trackings[-1].old_value, base_test_user_karma)
def test_user_as_erp_manager(self):
self.test_user.write({'groups_id': [
(4, self.env.ref('base.group_partner_manager').id),
(4, self.env.ref('base.group_erp_manager').id)
]})
user = self.env['res.users'].with_user(self.test_user).create({
'name': 'Test Ostérone', 'karma': '32',
'login': 'dummy', 'email': '[email protected]',
})
with self.assertRaises(exceptions.AccessError):
user.read(['karma_tracking_ids'])
user.write({'karma': 60})
user.add_karma(10)
self.assertEqual(user.karma, 70)
trackings = self.env['gamification.karma.tracking'].sudo().search([('user_id', '=', user.id)])
self.assertEqual(len(trackings), 3) # create + write + add_karma
def test_user_tracking(self):
self.test_user.write({'groups_id': [
(4, self.env.ref('base.group_partner_manager').id),
(4, self.env.ref('base.group_system').id)
]})
user = self.env['res.users'].with_user(self.test_user).create({
'name': 'Test Ostérone', 'karma': '32',
'login': 'dummy', 'email': '[email protected]',
})
self.assertEqual(user.karma, 32)
self.assertEqual(len(user.karma_tracking_ids), 1)
self.assertEqual(user.karma_tracking_ids.old_value, 0)
self.assertEqual(user.karma_tracking_ids.new_value, 32)
user.write({'karma': 60})
user.add_karma(10)
self.assertEqual(user.karma, 70)
self.assertEqual(len(user.karma_tracking_ids), 3)
self.assertEqual(user.karma_tracking_ids[2].old_value, 60)
self.assertEqual(user.karma_tracking_ids[2].new_value, 70)
self.assertEqual(user.karma_tracking_ids[1].old_value, 32)
self.assertEqual(user.karma_tracking_ids[1].new_value, 60)
self.assertEqual(user.karma_tracking_ids[0].old_value, 0)
self.assertEqual(user.karma_tracking_ids[0].new_value, 32)
class TestComputeRankCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestComputeRankCommon, cls).setUpClass()
def _patched_send_mail(*args, **kwargs):
pass
patch_email = patch('odoo.addons.mail.models.mail_template.MailTemplate.send_mail', _patched_send_mail)
patch_email.start()
cls.users = cls.env['res.users']
for k in range(-5, 1030, 30):
cls.users += mail_new_test_user(
cls.env,
name=str(k),
login="test_recompute_rank_%s" % k,
karma=k,
)
cls.env['gamification.karma.rank'].search([]).unlink()
cls.rank_1 = cls.env['gamification.karma.rank'].create({
'name': 'rank 1',
'karma_min': 1,
})
cls.rank_2 = cls.env['gamification.karma.rank'].create({
'name': 'rank 2',
'karma_min': 250,
})
cls.rank_3 = cls.env['gamification.karma.rank'].create({
'name': 'rank 3',
'karma_min': 500,
})
cls.rank_4 = cls.env['gamification.karma.rank'].create({
'name': 'rank 4',
'karma_min': 1000,
})
patch_email.stop()
def test_00_initial_compute(self):
self.assertEqual(len(self.users), 35)
self.assertEqual(
len(self.rank_1.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_1.karma_min and u.karma < self.rank_2.karma_min])
)
self.assertEqual(
len(self.rank_2.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_2.karma_min and u.karma < self.rank_3.karma_min])
)
self.assertEqual(
len(self.rank_3.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_3.karma_min and u.karma < self.rank_4.karma_min])
)
self.assertEqual(
len(self.rank_4.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_4.karma_min])
)
def test_01_switch_rank(self):
self.assertEqual(len(self.users), 35)
self.rank_3.karma_min = 100
# rank_1 -> rank_3 -> rank_2 -> rank_4
self.assertEqual(
len(self.rank_1.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_1.karma_min and u.karma < self.rank_3.karma_min])
)
self.assertEqual(
len(self.rank_3.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_3.karma_min and u.karma < self.rank_2.karma_min])
)
self.assertEqual(
len(self.rank_2.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_2.karma_min and u.karma < self.rank_4.karma_min])
)
self.assertEqual(
len(self.rank_4.user_ids & self.users),
len([u for u in self.users if u.karma >= self.rank_4.karma_min])
)
def test_02_update_rank_without_switch(self):
number_of_users = False
def _patched_recompute_rank(_self, *args, **kwargs):
nonlocal number_of_users
number_of_users = len(_self & self.users)
patch_bulk = patch('odoo.addons.gamification.models.res_users.Users._recompute_rank', _patched_recompute_rank)
patch_bulk.start()
self.rank_3.karma_min = 700
self.assertEqual(number_of_users, 7, "Should just recompute for the 7 users between 500 and 700")
patch_bulk.stop()
def test_03_test_bulk_call(self):
self.assertEqual(len(self.users), 35)
def _patched_check_in_bulk(*args, **kwargs):
raise
patch_bulk = patch('odoo.addons.gamification.models.res_users.Users._recompute_rank_bulk', _patched_check_in_bulk)
patch_bulk.start()
# call on 5 users should not trigger the bulk function
self.users[0:5]._recompute_rank()
# call on 50 users should trigger the bulk function
with self.assertRaises(Exception):
self.users[0:50]._recompute_rank()
patch_bulk.stop()
| 43.726984 | 13,774 |
1,159 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _, exceptions
class grant_badge_wizard(models.TransientModel):
""" Wizard allowing to grant a badge to a user"""
_name = 'gamification.badge.user.wizard'
_description = 'Gamification User Badge Wizard'
user_id = fields.Many2one("res.users", string='User', required=True)
badge_id = fields.Many2one("gamification.badge", string='Badge', required=True)
comment = fields.Text('Comment')
def action_grant_badge(self):
"""Wizard action for sending a badge to a chosen user"""
BadgeUser = self.env['gamification.badge.user']
uid = self.env.uid
for wiz in self:
if uid == wiz.user_id.id:
raise exceptions.UserError(_('You can not grant a badge to yourself.'))
#create the badge
BadgeUser.create({
'user_id': wiz.user_id.id,
'sender_id': uid,
'badge_id': wiz.badge_id.id,
'comment': wiz.comment,
})._send_badge()
return True
| 34.088235 | 1,159 |
781 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class goal_manual_wizard(models.TransientModel):
"""Wizard to update a manual goal"""
_name = 'gamification.goal.wizard'
_description = 'Gamification Goal Wizard'
goal_id = fields.Many2one("gamification.goal", string='Goal', required=True)
current = fields.Float('Current')
def action_update_current(self):
"""Wizard action for updating the current value"""
for wiz in self:
wiz.goal_id.write({
'current': wiz.current,
'goal_id': wiz.goal_id.id,
'to_update': False,
})
wiz.goal_id.update_goal()
return False
| 32.541667 | 781 |
11,769 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import date
from odoo import api, fields, models, _, exceptions
_logger = logging.getLogger(__name__)
class BadgeUser(models.Model):
"""User having received a badge"""
_name = 'gamification.badge.user'
_description = 'Gamification User Badge'
_order = "create_date desc"
_rec_name = "badge_name"
user_id = fields.Many2one('res.users', string="User", required=True, ondelete="cascade", index=True)
sender_id = fields.Many2one('res.users', string="Sender", help="The user who has send the badge")
badge_id = fields.Many2one('gamification.badge', string='Badge', required=True, ondelete="cascade", index=True)
challenge_id = fields.Many2one('gamification.challenge', string='Challenge originating', help="If this badge was rewarded through a challenge")
comment = fields.Text('Comment')
badge_name = fields.Char(related='badge_id.name', string="Badge Name", readonly=False)
level = fields.Selection(
string='Badge Level', related="badge_id.level", store=True, readonly=True)
def _send_badge(self):
"""Send a notification to a user for receiving a badge
Does not verify constrains on badge granting.
The users are added to the owner_ids (create badge_user if needed)
The stats counters are incremented
:param ids: list(int) of badge users that will receive the badge
"""
template = self.env.ref('gamification.email_template_badge_received')
for badge_user in self:
self.env['mail.thread'].message_post_with_template(
template.id,
model=badge_user._name,
res_id=badge_user.id,
composition_mode='mass_mail',
# `website_forum` triggers `_cron_update` which triggers this method for template `Received Badge`
# for which `badge_user.user_id.partner_id.ids` equals `[8]`, which is then passed to `self.env['mail.compose.message'].create(...)`
# which expects a command list and not a list of ids. In master, this wasn't doing anything, at the end composer.partner_ids was [] and not [8]
# I believe this line is useless, it will take the partners to which the template must be send from the template itself (`partner_to`)
# The below line was therefore pointless.
# partner_ids=badge_user.user_id.partner_id.ids,
)
return True
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
self.env['gamification.badge'].browse(vals['badge_id']).check_granting()
return super().create(vals_list)
class GamificationBadge(models.Model):
"""Badge object that users can send and receive"""
CAN_GRANT = 1
NOBODY_CAN_GRANT = 2
USER_NOT_VIP = 3
BADGE_REQUIRED = 4
TOO_MANY = 5
_name = 'gamification.badge'
_description = 'Gamification Badge'
_inherit = ['mail.thread', 'image.mixin']
name = fields.Char('Badge', required=True, translate=True)
active = fields.Boolean('Active', default=True)
description = fields.Html('Description', translate=True, sanitize_attributes=False)
level = fields.Selection([
('bronze', 'Bronze'), ('silver', 'Silver'), ('gold', 'Gold')],
string='Forum Badge Level', default='bronze')
rule_auth = fields.Selection([
('everyone', 'Everyone'),
('users', 'A selected list of users'),
('having', 'People having some badges'),
('nobody', 'No one, assigned through challenges'),
], default='everyone',
string="Allowance to Grant", help="Who can grant this badge", required=True)
rule_auth_user_ids = fields.Many2many(
'res.users', 'rel_badge_auth_users',
string='Authorized Users',
help="Only these people can give this badge")
rule_auth_badge_ids = fields.Many2many(
'gamification.badge', 'gamification_badge_rule_badge_rel', 'badge1_id', 'badge2_id',
string='Required Badges',
help="Only the people having these badges can give this badge")
rule_max = fields.Boolean('Monthly Limited Sending', help="Check to set a monthly limit per person of sending this badge")
rule_max_number = fields.Integer('Limitation Number', help="The maximum number of time this badge can be sent per month per person.")
challenge_ids = fields.One2many('gamification.challenge', 'reward_id', string="Reward of Challenges")
goal_definition_ids = fields.Many2many(
'gamification.goal.definition', 'badge_unlocked_definition_rel',
string='Rewarded by', help="The users that have succeeded theses goals will receive automatically the badge.")
owner_ids = fields.One2many(
'gamification.badge.user', 'badge_id',
string='Owners', help='The list of instances of this badge granted to users')
granted_count = fields.Integer("Total", compute='_get_owners_info', help="The number of time this badge has been received.")
granted_users_count = fields.Integer("Number of users", compute='_get_owners_info', help="The number of time this badge has been received by unique users.")
unique_owner_ids = fields.Many2many(
'res.users', string="Unique Owners", compute='_get_owners_info',
help="The list of unique users having received this badge.")
stat_this_month = fields.Integer(
"Monthly total", compute='_get_badge_user_stats',
help="The number of time this badge has been received this month.")
stat_my = fields.Integer(
"My Total", compute='_get_badge_user_stats',
help="The number of time the current user has received this badge.")
stat_my_this_month = fields.Integer(
"My Monthly Total", compute='_get_badge_user_stats',
help="The number of time the current user has received this badge this month.")
stat_my_monthly_sending = fields.Integer(
'My Monthly Sending Total',
compute='_get_badge_user_stats',
help="The number of time the current user has sent this badge this month.")
remaining_sending = fields.Integer(
"Remaining Sending Allowed", compute='_remaining_sending_calc',
help="If a maximum is set")
@api.depends('owner_ids')
def _get_owners_info(self):
"""Return:
the list of unique res.users ids having received this badge
the total number of time this badge was granted
the total number of users this badge was granted to
"""
defaults = {
'granted_count': 0,
'granted_users_count': 0,
'unique_owner_ids': [],
}
if not self.ids:
self.update(defaults)
return
Users = self.env["res.users"]
query = Users._where_calc([])
Users._apply_ir_rules(query)
badge_alias = query.join("res_users", "id", "gamification_badge_user", "user_id", "badges")
tables, where_clauses, where_params = query.get_sql()
self.env.cr.execute(
f"""
SELECT {badge_alias}.badge_id, count(res_users.id) as stat_count,
count(distinct(res_users.id)) as stat_count_distinct,
array_agg(distinct(res_users.id)) as unique_owner_ids
FROM {tables}
WHERE {where_clauses}
AND {badge_alias}.badge_id IN %s
GROUP BY {badge_alias}.badge_id
""",
[*where_params, tuple(self.ids)]
)
mapping = {
badge_id: {
'granted_count': count,
'granted_users_count': distinct_count,
'unique_owner_ids': owner_ids,
}
for (badge_id, count, distinct_count, owner_ids) in self.env.cr._obj
}
for badge in self:
badge.update(mapping.get(badge.id, defaults))
@api.depends('owner_ids.badge_id', 'owner_ids.create_date', 'owner_ids.user_id')
def _get_badge_user_stats(self):
"""Return stats related to badge users"""
first_month_day = date.today().replace(day=1)
for badge in self:
owners = badge.owner_ids
badge.stat_my = sum(o.user_id == self.env.user for o in owners)
badge.stat_this_month = sum(o.create_date.date() >= first_month_day for o in owners)
badge.stat_my_this_month = sum(
o.user_id == self.env.user and o.create_date.date() >= first_month_day
for o in owners
)
badge.stat_my_monthly_sending = sum(
o.create_uid == self.env.user and o.create_date.date() >= first_month_day
for o in owners
)
@api.depends(
'rule_auth',
'rule_auth_user_ids',
'rule_auth_badge_ids',
'rule_max',
'rule_max_number',
'stat_my_monthly_sending',
)
def _remaining_sending_calc(self):
"""Computes the number of badges remaining the user can send
0 if not allowed or no remaining
integer if limited sending
-1 if infinite (should not be displayed)
"""
for badge in self:
if badge._can_grant_badge() != self.CAN_GRANT:
# if the user cannot grant this badge at all, result is 0
badge.remaining_sending = 0
elif not badge.rule_max:
# if there is no limitation, -1 is returned which means 'infinite'
badge.remaining_sending = -1
else:
badge.remaining_sending = badge.rule_max_number - badge.stat_my_monthly_sending
def check_granting(self):
"""Check the user 'uid' can grant the badge 'badge_id' and raise the appropriate exception
if not
Do not check for SUPERUSER_ID
"""
status_code = self._can_grant_badge()
if status_code == self.CAN_GRANT:
return True
elif status_code == self.NOBODY_CAN_GRANT:
raise exceptions.UserError(_('This badge can not be sent by users.'))
elif status_code == self.USER_NOT_VIP:
raise exceptions.UserError(_('You are not in the user allowed list.'))
elif status_code == self.BADGE_REQUIRED:
raise exceptions.UserError(_('You do not have the required badges.'))
elif status_code == self.TOO_MANY:
raise exceptions.UserError(_('You have already sent this badge too many time this month.'))
else:
_logger.error("Unknown badge status code: %s" % status_code)
return False
def _can_grant_badge(self):
"""Check if a user can grant a badge to another user
:param uid: the id of the res.users trying to send the badge
:param badge_id: the granted badge id
:return: integer representing the permission.
"""
if self.env.is_admin():
return self.CAN_GRANT
if self.rule_auth == 'nobody':
return self.NOBODY_CAN_GRANT
elif self.rule_auth == 'users' and self.env.user not in self.rule_auth_user_ids:
return self.USER_NOT_VIP
elif self.rule_auth == 'having':
all_user_badges = self.env['gamification.badge.user'].search([('user_id', '=', self.env.uid)]).mapped('badge_id')
if self.rule_auth_badge_ids - all_user_badges:
return self.BADGE_REQUIRED
if self.rule_max and self.stat_my_monthly_sending >= self.rule_max_number:
return self.TOO_MANY
# badge.rule_auth == 'everyone' -> no check
return self.CAN_GRANT
| 43.914179 | 11,769 |
2,743 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.translate import html_translate
class KarmaRank(models.Model):
_name = 'gamification.karma.rank'
_description = 'Rank based on karma'
_inherit = 'image.mixin'
_order = 'karma_min'
name = fields.Text(string='Rank Name', translate=True, required=True)
description = fields.Html(string='Description', translate=html_translate, sanitize_attributes=False,)
description_motivational = fields.Html(
string='Motivational', translate=html_translate, sanitize_attributes=False,
help="Motivational phrase to reach this rank")
karma_min = fields.Integer(
string='Required Karma', required=True, default=1,
help='Minimum karma needed to reach this rank')
user_ids = fields.One2many('res.users', 'rank_id', string='Users', help="Users having this rank")
rank_users_count = fields.Integer("# Users", compute="_compute_rank_users_count")
_sql_constraints = [
('karma_min_check', "CHECK( karma_min > 0 )", 'The required karma has to be above 0.')
]
@api.depends('user_ids')
def _compute_rank_users_count(self):
requests_data = self.env['res.users'].read_group([('rank_id', '!=', False)], ['rank_id'], ['rank_id'])
requests_mapped_data = dict((data['rank_id'][0], data['rank_id_count']) for data in requests_data)
for rank in self:
rank.rank_users_count = requests_mapped_data.get(rank.id, 0)
@api.model_create_multi
def create(self, values_list):
res = super(KarmaRank, self).create(values_list)
if any(res.mapped('karma_min')) > 0:
users = self.env['res.users'].sudo().search([('karma', '>=', max(min(res.mapped('karma_min')), 1))])
if users:
users._recompute_rank()
return res
def write(self, vals):
if 'karma_min' in vals:
previous_ranks = self.env['gamification.karma.rank'].search([], order="karma_min DESC").ids
low = min(vals['karma_min'], min(self.mapped('karma_min')))
high = max(vals['karma_min'], max(self.mapped('karma_min')))
res = super(KarmaRank, self).write(vals)
if 'karma_min' in vals:
after_ranks = self.env['gamification.karma.rank'].search([], order="karma_min DESC").ids
if previous_ranks != after_ranks:
users = self.env['res.users'].sudo().search([('karma', '>=', max(low, 1))])
else:
users = self.env['res.users'].sudo().search([('karma', '>=', max(low, 1)), ('karma', '<=', high)])
users._recompute_rank()
return res
| 46.491525 | 2,743 |
2,823 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class KarmaTracking(models.Model):
_name = 'gamification.karma.tracking'
_description = 'Track Karma Changes'
_rec_name = 'user_id'
_order = 'tracking_date DESC'
user_id = fields.Many2one('res.users', 'User', index=True, readonly=True, required=True, ondelete='cascade')
old_value = fields.Integer('Old Karma Value', required=True, readonly=True)
new_value = fields.Integer('New Karma Value', required=True, readonly=True)
consolidated = fields.Boolean('Consolidated')
tracking_date = fields.Date(default=fields.Date.context_today)
@api.model
def _consolidate_last_month(self):
""" Consolidate last month. Used by a cron to cleanup tracking records. """
previous_month_start = fields.Date.today() + relativedelta(months=-1, day=1)
return self._process_consolidate(previous_month_start)
def _process_consolidate(self, from_date):
""" Consolidate trackings into a single record for a given month, starting
at a from_date (included). End date is set to last day of current month
using a smart calendar.monthrange construction. """
end_date = from_date + relativedelta(day=calendar.monthrange(from_date.year, from_date.month)[1])
select_query = """
SELECT user_id,
(
SELECT old_value from gamification_karma_tracking old_tracking
WHERE old_tracking.user_id = gamification_karma_tracking.user_id
AND tracking_date::timestamp BETWEEN %(from_date)s AND %(to_date)s
AND consolidated IS NOT TRUE
ORDER BY tracking_date ASC LIMIT 1
), (
SELECT new_value from gamification_karma_tracking new_tracking
WHERE new_tracking.user_id = gamification_karma_tracking.user_id
AND tracking_date::timestamp BETWEEN %(from_date)s AND %(to_date)s
AND consolidated IS NOT TRUE
ORDER BY tracking_date DESC LIMIT 1
)
FROM gamification_karma_tracking
WHERE tracking_date::timestamp BETWEEN %(from_date)s AND %(to_date)s
AND consolidated IS NOT TRUE
GROUP BY user_id """
self.env.cr.execute(select_query, {
'from_date': from_date,
'to_date': end_date,
})
results = self.env.cr.dictfetchall()
if results:
for result in results:
result['consolidated'] = True
result['tracking_date'] = fields.Date.to_string(from_date)
self.create(results)
self.search([
('tracking_date', '>=', from_date),
('tracking_date', '<=', end_date),
('consolidated', '!=', True)]
).unlink()
return True
| 40.913043 | 2,823 |
12,924 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class Users(models.Model):
_inherit = 'res.users'
karma = fields.Integer('Karma', default=0, copy=False)
karma_tracking_ids = fields.One2many('gamification.karma.tracking', 'user_id', string='Karma Changes', groups="base.group_system")
badge_ids = fields.One2many('gamification.badge.user', 'user_id', string='Badges', copy=False)
gold_badge = fields.Integer('Gold badges count', compute="_get_user_badge_level")
silver_badge = fields.Integer('Silver badges count', compute="_get_user_badge_level")
bronze_badge = fields.Integer('Bronze badges count', compute="_get_user_badge_level")
rank_id = fields.Many2one('gamification.karma.rank', 'Rank', index=False)
next_rank_id = fields.Many2one('gamification.karma.rank', 'Next Rank', index=False)
@api.depends('badge_ids')
def _get_user_badge_level(self):
""" Return total badge per level of users
TDE CLEANME: shouldn't check type is forum ? """
for user in self:
user.gold_badge = 0
user.silver_badge = 0
user.bronze_badge = 0
self.env.cr.execute("""
SELECT bu.user_id, b.level, count(1)
FROM gamification_badge_user bu, gamification_badge b
WHERE bu.user_id IN %s
AND bu.badge_id = b.id
AND b.level IS NOT NULL
GROUP BY bu.user_id, b.level
ORDER BY bu.user_id;
""", [tuple(self.ids)])
for (user_id, level, count) in self.env.cr.fetchall():
# levels are gold, silver, bronze but fields have _badge postfix
self.browse(user_id)['{}_badge'.format(level)] = count
@api.model_create_multi
def create(self, values_list):
res = super(Users, self).create(values_list)
karma_trackings = []
for user in res:
if user.karma:
karma_trackings.append({'user_id': user.id, 'old_value': 0, 'new_value': user.karma})
if karma_trackings:
self.env['gamification.karma.tracking'].sudo().create(karma_trackings)
res._recompute_rank()
return res
def write(self, vals):
karma_trackings = []
if 'karma' in vals:
for user in self:
if user.karma != vals['karma']:
karma_trackings.append({'user_id': user.id, 'old_value': user.karma, 'new_value': vals['karma']})
result = super(Users, self).write(vals)
if karma_trackings:
self.env['gamification.karma.tracking'].sudo().create(karma_trackings)
if 'karma' in vals:
self._recompute_rank()
return result
def add_karma(self, karma):
for user in self:
user.karma += karma
return True
def _get_tracking_karma_gain_position(self, user_domain, from_date=None, to_date=None):
""" Get absolute position in term of gained karma for users. First a ranking
of all users is done given a user_domain; then the position of each user
belonging to the current record set is extracted.
Example: in website profile, search users with name containing Norbert. Their
positions should not be 1 to 4 (assuming 4 results), but their actual position
in the karma gain ranking (with example user_domain being karma > 1,
website published True).
:param user_domain: general domain (i.e. active, karma > 1, website, ...)
to compute the absolute position of the current record set
:param from_date: compute karma gained after this date (included) or from
beginning of time;
:param to_date: compute karma gained before this date (included) or until
end of time;
:return list: [{
'user_id': user_id (belonging to current record set),
'karma_gain_total': integer, karma gained in the given timeframe,
'karma_position': integer, ranking position
}, {..}] ordered by karma_position desc
"""
if not self:
return []
where_query = self.env['res.users']._where_calc(user_domain)
user_from_clause, user_where_clause, where_clause_params = where_query.get_sql()
params = []
if from_date:
date_from_condition = 'AND tracking.tracking_date::timestamp >= timestamp %s'
params.append(from_date)
if to_date:
date_to_condition = 'AND tracking.tracking_date::timestamp <= timestamp %s'
params.append(to_date)
params.append(tuple(self.ids))
query = """
SELECT final.user_id, final.karma_gain_total, final.karma_position
FROM (
SELECT intermediate.user_id, intermediate.karma_gain_total, row_number() OVER (ORDER BY intermediate.karma_gain_total DESC) AS karma_position
FROM (
SELECT "res_users".id as user_id, COALESCE(SUM("tracking".new_value - "tracking".old_value), 0) as karma_gain_total
FROM %(user_from_clause)s
LEFT JOIN "gamification_karma_tracking" as "tracking"
ON "res_users".id = "tracking".user_id AND "res_users"."active" = TRUE
WHERE %(user_where_clause)s %(date_from_condition)s %(date_to_condition)s
GROUP BY "res_users".id
ORDER BY karma_gain_total DESC
) intermediate
) final
WHERE final.user_id IN %%s""" % {
'user_from_clause': user_from_clause,
'user_where_clause': user_where_clause or (not from_date and not to_date and 'TRUE') or '',
'date_from_condition': date_from_condition if from_date else '',
'date_to_condition': date_to_condition if to_date else ''
}
self.env.cr.execute(query, tuple(where_clause_params + params))
return self.env.cr.dictfetchall()
def _get_karma_position(self, user_domain):
""" Get absolute position in term of total karma for users. First a ranking
of all users is done given a user_domain; then the position of each user
belonging to the current record set is extracted.
Example: in website profile, search users with name containing Norbert. Their
positions should not be 1 to 4 (assuming 4 results), but their actual position
in the total karma ranking (with example user_domain being karma > 1,
website published True).
:param user_domain: general domain (i.e. active, karma > 1, website, ...)
to compute the absolute position of the current record set
:return list: [{
'user_id': user_id (belonging to current record set),
'karma_position': integer, ranking position
}, {..}] ordered by karma_position desc
"""
if not self:
return {}
where_query = self.env['res.users']._where_calc(user_domain)
user_from_clause, user_where_clause, where_clause_params = where_query.get_sql()
# we search on every user in the DB to get the real positioning (not the one inside the subset)
# then, we filter to get only the subset.
query = """
SELECT sub.user_id, sub.karma_position
FROM (
SELECT "res_users"."id" as user_id, row_number() OVER (ORDER BY res_users.karma DESC) AS karma_position
FROM %(user_from_clause)s
WHERE %(user_where_clause)s
) sub
WHERE sub.user_id IN %%s""" % {
'user_from_clause': user_from_clause,
'user_where_clause': user_where_clause or 'TRUE',
}
self.env.cr.execute(query, tuple(where_clause_params + [tuple(self.ids)]))
return self.env.cr.dictfetchall()
def _rank_changed(self):
"""
Method that can be called on a batch of users with the same new rank
"""
if self.env.context.get('install_mode', False):
# avoid sending emails in install mode (prevents spamming users when creating data ranks)
return
template = self.env.ref('gamification.mail_template_data_new_rank_reached', raise_if_not_found=False)
if template:
for u in self:
if u.rank_id.karma_min > 0:
template.send_mail(u.id, force_send=False, notif_layout='mail.mail_notification_light')
def _recompute_rank(self):
"""
The caller should filter the users on karma > 0 before calling this method
to avoid looping on every single users
Compute rank of each user by user.
For each user, check the rank of this user
"""
ranks = [{'rank': rank, 'karma_min': rank.karma_min} for rank in
self.env['gamification.karma.rank'].search([], order="karma_min DESC")]
# 3 is the number of search/requests used by rank in _recompute_rank_bulk()
if len(self) > len(ranks) * 3:
self._recompute_rank_bulk()
return
for user in self:
old_rank = user.rank_id
if user.karma == 0 and ranks:
user.write({'next_rank_id': ranks[-1]['rank'].id})
else:
for i in range(0, len(ranks)):
if user.karma >= ranks[i]['karma_min']:
user.write({
'rank_id': ranks[i]['rank'].id,
'next_rank_id': ranks[i - 1]['rank'].id if 0 < i else False
})
break
if old_rank != user.rank_id:
user._rank_changed()
def _recompute_rank_bulk(self):
"""
Compute rank of each user by rank.
For each rank, check which users need to be ranked
"""
ranks = [{'rank': rank, 'karma_min': rank.karma_min} for rank in
self.env['gamification.karma.rank'].search([], order="karma_min DESC")]
users_todo = self
next_rank_id = False
# wtf, next_rank_id should be a related on rank_id.next_rank_id and life might get easier.
# And we only need to recompute next_rank_id on write with min_karma or in the create on rank model.
for r in ranks:
rank_id = r['rank'].id
dom = [
('karma', '>=', r['karma_min']),
('id', 'in', users_todo.ids),
'|', # noqa
'|', ('rank_id', '!=', rank_id), ('rank_id', '=', False),
'|', ('next_rank_id', '!=', next_rank_id), ('next_rank_id', '=', False if next_rank_id else -1),
]
users = self.env['res.users'].search(dom)
if users:
users_to_notify = self.env['res.users'].search([
('karma', '>=', r['karma_min']),
'|', ('rank_id', '!=', rank_id), ('rank_id', '=', False),
('id', 'in', users.ids),
])
users.write({
'rank_id': rank_id,
'next_rank_id': next_rank_id,
})
users_to_notify._rank_changed()
users_todo -= users
nothing_to_do_users = self.env['res.users'].search([
('karma', '>=', r['karma_min']),
'|', ('rank_id', '=', rank_id), ('next_rank_id', '=', next_rank_id),
('id', 'in', users_todo.ids),
])
users_todo -= nothing_to_do_users
next_rank_id = r['rank'].id
if ranks:
lower_rank = ranks[-1]['rank']
users = self.env['res.users'].search([
('karma', '>=', 0),
('karma', '<', lower_rank.karma_min),
'|', ('rank_id', '!=', False), ('next_rank_id', '!=', lower_rank.id),
('id', 'in', users_todo.ids),
])
if users:
users.write({
'rank_id': False,
'next_rank_id': lower_rank.id,
})
def _get_next_rank(self):
""" For fresh users with 0 karma that don't have a rank_id and next_rank_id yet
this method returns the first karma rank (by karma ascending). This acts as a
default value in related views.
TDE FIXME in post-12.4: make next_rank_id a non-stored computed field correctly computed """
if self.next_rank_id:
return self.next_rank_id
elif not self.rank_id:
return self.env['gamification.karma.rank'].search([], order="karma_min ASC", limit=1)
else:
return self.env['gamification.karma.rank']
def get_gamification_redirection_data(self):
"""
Hook for other modules to add redirect button(s) in new rank reached mail
Must return a list of dictionnary including url and label.
E.g. return [{'url': '/forum', label: 'Go to Forum'}]
"""
self.ensure_one()
return []
| 42.37377 | 12,924 |
23,122 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import logging
from datetime import date, datetime, timedelta
from odoo import api, fields, models, _, exceptions
from odoo.osv import expression
from odoo.tools.safe_eval import safe_eval, time
_logger = logging.getLogger(__name__)
DOMAIN_TEMPLATE = "[('store', '=', True), '|', ('model_id', '=', model_id), ('model_id', 'in', model_inherited_ids)%s]"
class GoalDefinition(models.Model):
"""Goal definition
A goal definition contains the way to evaluate an objective
Each module wanting to be able to set goals to the users needs to create
a new gamification_goal_definition
"""
_name = 'gamification.goal.definition'
_description = 'Gamification Goal Definition'
name = fields.Char("Goal Definition", required=True, translate=True)
description = fields.Text("Goal Description")
monetary = fields.Boolean("Monetary Value", default=False, help="The target and current value are defined in the company currency.")
suffix = fields.Char("Suffix", help="The unit of the target and current values", translate=True)
full_suffix = fields.Char("Full Suffix", compute='_compute_full_suffix', help="The currency and suffix field")
computation_mode = fields.Selection([
('manually', "Recorded manually"),
('count', "Automatic: number of records"),
('sum', "Automatic: sum on a field"),
('python', "Automatic: execute a specific Python code"),
], default='manually', string="Computation Mode", required=True,
help="Define how the goals will be computed. The result of the operation will be stored in the field 'Current'.")
display_mode = fields.Selection([
('progress', "Progressive (using numerical values)"),
('boolean', "Exclusive (done or not-done)"),
], default='progress', string="Displayed as", required=True)
model_id = fields.Many2one('ir.model', string='Model', help='The model object for the field to evaluate')
model_inherited_ids = fields.Many2many('ir.model', related='model_id.inherited_model_ids')
field_id = fields.Many2one(
'ir.model.fields', string='Field to Sum', help='The field containing the value to evaluate',
domain=DOMAIN_TEMPLATE % ''
)
field_date_id = fields.Many2one(
'ir.model.fields', string='Date Field', help='The date to use for the time period evaluated',
domain=DOMAIN_TEMPLATE % ", ('ttype', 'in', ('date', 'datetime'))"
)
domain = fields.Char(
"Filter Domain", required=True, default="[]",
help="Domain for filtering records. General rule, not user depending,"
" e.g. [('state', '=', 'done')]. The expression can contain"
" reference to 'user' which is a browse record of the current"
" user if not in batch mode.")
batch_mode = fields.Boolean("Batch Mode", help="Evaluate the expression in batch instead of once for each user")
batch_distinctive_field = fields.Many2one('ir.model.fields', string="Distinctive field for batch user", help="In batch mode, this indicates which field distinguishes one user from the other, e.g. user_id, partner_id...")
batch_user_expression = fields.Char("Evaluated expression for batch mode", help="The value to compare with the distinctive field. The expression can contain reference to 'user' which is a browse record of the current user, e.g. user.id, user.partner_id.id...")
compute_code = fields.Text("Python Code", help="Python code to be executed for each user. 'result' should contains the new current value. Evaluated user can be access through object.user_id.")
condition = fields.Selection([
('higher', "The higher the better"),
('lower', "The lower the better")
], default='higher', required=True, string="Goal Performance",
help="A goal is considered as completed when the current value is compared to the value to reach")
action_id = fields.Many2one('ir.actions.act_window', string="Action", help="The action that will be called to update the goal value.")
res_id_field = fields.Char("ID Field of user", help="The field name on the user profile (res.users) containing the value for res_id for action.")
@api.depends('suffix', 'monetary') # also depends of user...
def _compute_full_suffix(self):
for goal in self:
items = []
if goal.monetary:
items.append(self.env.company.currency_id.symbol or u'¤')
if goal.suffix:
items.append(goal.suffix)
goal.full_suffix = u' '.join(items)
def _check_domain_validity(self):
# take admin as should always be present
for definition in self:
if definition.computation_mode not in ('count', 'sum'):
continue
Obj = self.env[definition.model_id.model]
try:
domain = safe_eval(definition.domain, {
'user': self.env.user.with_user(self.env.user)
})
# dummy search to make sure the domain is valid
Obj.search_count(domain)
except (ValueError, SyntaxError) as e:
msg = e
if isinstance(e, SyntaxError):
msg = (e.msg + '\n' + e.text)
raise exceptions.UserError(_("The domain for the definition %s seems incorrect, please check it.\n\n%s") % (definition.name, msg))
return True
def _check_model_validity(self):
""" make sure the selected field and model are usable"""
for definition in self:
try:
if not (definition.model_id and definition.field_id):
continue
Model = self.env[definition.model_id.model]
field = Model._fields.get(definition.field_id.name)
if not (field and field.store):
raise exceptions.UserError(_(
"The model configuration for the definition %(name)s seems incorrect, please check it.\n\n%(field_name)s not stored",
name=definition.name,
field_name=definition.field_id.name
))
except KeyError as e:
raise exceptions.UserError(_(
"The model configuration for the definition %(name)s seems incorrect, please check it.\n\n%(error)s not found",
name=definition.name,
error=e
))
@api.model_create_multi
def create(self, vals_list):
definitions = super(GoalDefinition, self).create(vals_list)
definitions.filtered_domain([
('computation_mode', 'in', ['count', 'sum']),
])._check_domain_validity()
definitions.filtered_domain([
('field_id', '=', 'True'),
])._check_model_validity()
return definitions
def write(self, vals):
res = super(GoalDefinition, self).write(vals)
if vals.get('computation_mode', 'count') in ('count', 'sum') and (vals.get('domain') or vals.get('model_id')):
self._check_domain_validity()
if vals.get('field_id') or vals.get('model_id') or vals.get('batch_mode'):
self._check_model_validity()
return res
class Goal(models.Model):
"""Goal instance for a user
An individual goal for a user on a specified time period"""
_name = 'gamification.goal'
_description = 'Gamification Goal'
_rec_name = 'definition_id'
_order = 'start_date desc, end_date desc, definition_id, id'
definition_id = fields.Many2one('gamification.goal.definition', string="Goal Definition", required=True, ondelete="cascade")
user_id = fields.Many2one('res.users', string="User", required=True, auto_join=True, ondelete="cascade")
line_id = fields.Many2one('gamification.challenge.line', string="Challenge Line", ondelete="cascade")
challenge_id = fields.Many2one(
related='line_id.challenge_id', store=True, readonly=True, index=True,
help="Challenge that generated the goal, assign challenge to users "
"to generate goals with a value in this field.")
start_date = fields.Date("Start Date", default=fields.Date.today)
end_date = fields.Date("End Date") # no start and end = always active
target_goal = fields.Float('To Reach', required=True)
# no goal = global index
current = fields.Float("Current Value", required=True, default=0)
completeness = fields.Float("Completeness", compute='_get_completion')
state = fields.Selection([
('draft', "Draft"),
('inprogress', "In progress"),
('reached', "Reached"),
('failed', "Failed"),
('canceled', "Canceled"),
], default='draft', string='State', required=True)
to_update = fields.Boolean('To update')
closed = fields.Boolean('Closed goal', help="These goals will not be recomputed.")
computation_mode = fields.Selection(related='definition_id.computation_mode', readonly=False)
remind_update_delay = fields.Integer(
"Remind delay", help="The number of days after which the user "
"assigned to a manual goal will be reminded. "
"Never reminded if no value is specified.")
last_update = fields.Date(
"Last Update",
help="In case of manual goal, reminders are sent if the goal as not "
"been updated for a while (defined in challenge). Ignored in "
"case of non-manual goal or goal not linked to a challenge.")
definition_description = fields.Text("Definition Description", related='definition_id.description', readonly=True)
definition_condition = fields.Selection(string="Definition Condition", related='definition_id.condition', readonly=True)
definition_suffix = fields.Char("Suffix", related='definition_id.full_suffix', readonly=True)
definition_display = fields.Selection(string="Display Mode", related='definition_id.display_mode', readonly=True)
@api.depends('current', 'target_goal', 'definition_id.condition')
def _get_completion(self):
"""Return the percentage of completeness of the goal, between 0 and 100"""
for goal in self:
if goal.definition_condition == 'higher':
if goal.current >= goal.target_goal:
goal.completeness = 100.0
else:
goal.completeness = round(100.0 * goal.current / goal.target_goal, 2) if goal.target_goal else 0
elif goal.current < goal.target_goal:
# a goal 'lower than' has only two values possible: 0 or 100%
goal.completeness = 100.0
else:
goal.completeness = 0.0
def _check_remind_delay(self):
"""Verify if a goal has not been updated for some time and send a
reminder message of needed.
:return: data to write on the goal object
"""
if not (self.remind_update_delay and self.last_update):
return {}
delta_max = timedelta(days=self.remind_update_delay)
last_update = fields.Date.from_string(self.last_update)
if date.today() - last_update < delta_max:
return {}
# generate a reminder report
body_html = self.env.ref('gamification.email_template_goal_reminder')._render_field('body_html', self.ids, compute_lang=True)[self.id]
self.message_notify(
body=body_html,
partner_ids=[self.user_id.partner_id.id],
subtype_xmlid='mail.mt_comment',
email_layout_xmlid='mail.mail_notification_light',
)
return {'to_update': True}
def _get_write_values(self, new_value):
"""Generate values to write after recomputation of a goal score"""
if new_value == self.current:
# avoid useless write if the new value is the same as the old one
return {}
result = {'current': new_value}
if (self.definition_id.condition == 'higher' and new_value >= self.target_goal) \
or (self.definition_id.condition == 'lower' and new_value <= self.target_goal):
# success, do no set closed as can still change
result['state'] = 'reached'
elif self.end_date and fields.Date.today() > self.end_date:
# check goal failure
result['state'] = 'failed'
result['closed'] = True
return {self: result}
def update_goal(self):
"""Update the goals to recomputes values and change of states
If a manual goal is not updated for enough time, the user will be
reminded to do so (done only once, in 'inprogress' state).
If a goal reaches the target value, the status is set to reached
If the end date is passed (at least +1 day, time not considered) without
the target value being reached, the goal is set as failed."""
goals_by_definition = {}
for goal in self.with_context(prefetch_fields=False):
goals_by_definition.setdefault(goal.definition_id, []).append(goal)
for definition, goals in goals_by_definition.items():
goals_to_write = {}
if definition.computation_mode == 'manually':
for goal in goals:
goals_to_write[goal] = goal._check_remind_delay()
elif definition.computation_mode == 'python':
# TODO batch execution
for goal in goals:
# execute the chosen method
cxt = {
'object': goal,
'env': self.env,
'date': date,
'datetime': datetime,
'timedelta': timedelta,
'time': time,
}
code = definition.compute_code.strip()
safe_eval(code, cxt, mode="exec", nocopy=True)
# the result of the evaluated codeis put in the 'result' local variable, propagated to the context
result = cxt.get('result')
if isinstance(result, (float, int)):
goals_to_write.update(goal._get_write_values(result))
else:
_logger.error(
"Invalid return content '%r' from the evaluation "
"of code for definition %s, expected a number",
result, definition.name)
elif definition.computation_mode in ('count', 'sum'): # count or sum
Obj = self.env[definition.model_id.model]
field_date_name = definition.field_date_id.name
if definition.batch_mode:
# batch mode, trying to do as much as possible in one request
general_domain = ast.literal_eval(definition.domain)
field_name = definition.batch_distinctive_field.name
subqueries = {}
for goal in goals:
start_date = field_date_name and goal.start_date or False
end_date = field_date_name and goal.end_date or False
subqueries.setdefault((start_date, end_date), {}).update({goal.id:safe_eval(definition.batch_user_expression, {'user': goal.user_id})})
# the global query should be split by time periods (especially for recurrent goals)
for (start_date, end_date), query_goals in subqueries.items():
subquery_domain = list(general_domain)
subquery_domain.append((field_name, 'in', list(set(query_goals.values()))))
if start_date:
subquery_domain.append((field_date_name, '>=', start_date))
if end_date:
subquery_domain.append((field_date_name, '<=', end_date))
if definition.computation_mode == 'count':
value_field_name = field_name + '_count'
if field_name == 'id':
# grouping on id does not work and is similar to search anyway
users = Obj.search(subquery_domain)
user_values = [{'id': user.id, value_field_name: 1} for user in users]
else:
user_values = Obj.read_group(subquery_domain, fields=[field_name], groupby=[field_name])
else: # sum
value_field_name = definition.field_id.name
if field_name == 'id':
user_values = Obj.search_read(subquery_domain, fields=['id', value_field_name])
else:
user_values = Obj.read_group(subquery_domain, fields=[field_name, "%s:sum" % value_field_name], groupby=[field_name])
# user_values has format of read_group: [{'partner_id': 42, 'partner_id_count': 3},...]
for goal in [g for g in goals if g.id in query_goals]:
for user_value in user_values:
queried_value = field_name in user_value and user_value[field_name] or False
if isinstance(queried_value, tuple) and len(queried_value) == 2 and isinstance(queried_value[0], int):
queried_value = queried_value[0]
if queried_value == query_goals[goal.id]:
new_value = user_value.get(value_field_name, goal.current)
goals_to_write.update(goal._get_write_values(new_value))
else:
for goal in goals:
# eval the domain with user replaced by goal user object
domain = safe_eval(definition.domain, {'user': goal.user_id})
# add temporal clause(s) to the domain if fields are filled on the goal
if goal.start_date and field_date_name:
domain.append((field_date_name, '>=', goal.start_date))
if goal.end_date and field_date_name:
domain.append((field_date_name, '<=', goal.end_date))
if definition.computation_mode == 'sum':
field_name = definition.field_id.name
res = Obj.read_group(domain, [field_name], [])
new_value = res and res[0][field_name] or 0.0
else: # computation mode = count
new_value = Obj.search_count(domain)
goals_to_write.update(goal._get_write_values(new_value))
else:
_logger.error(
"Invalid computation mode '%s' in definition %s",
definition.computation_mode, definition.name)
for goal, values in goals_to_write.items():
if not values:
continue
goal.write(values)
if self.env.context.get('commit_gamification'):
self.env.cr.commit()
return True
def action_start(self):
"""Mark a goal as started.
This should only be used when creating goals manually (in draft state)"""
self.write({'state': 'inprogress'})
return self.update_goal()
def action_reach(self):
"""Mark a goal as reached.
If the target goal condition is not met, the state will be reset to In
Progress at the next goal update until the end date."""
return self.write({'state': 'reached'})
def action_fail(self):
"""Set the state of the goal to failed.
A failed goal will be ignored in future checks."""
return self.write({'state': 'failed'})
def action_cancel(self):
"""Reset the completion after setting a goal as reached or failed.
This is only the current state, if the date and/or target criteria
match the conditions for a change of state, this will be applied at the
next goal update."""
return self.write({'state': 'inprogress'})
@api.model_create_multi
def create(self, vals_list):
return super(Goal, self.with_context(no_remind_goal=True)).create(vals_list)
def write(self, vals):
"""Overwrite the write method to update the last_update field to today
If the current value is changed and the report frequency is set to On
change, a report is generated
"""
vals['last_update'] = fields.Date.context_today(self)
result = super(Goal, self).write(vals)
for goal in self:
if goal.state != "draft" and ('definition_id' in vals or 'user_id' in vals):
# avoid drag&drop in kanban view
raise exceptions.UserError(_('Can not modify the configuration of a started goal'))
if vals.get('current') and 'no_remind_goal' not in self.env.context:
if goal.challenge_id.report_message_frequency == 'onchange':
goal.challenge_id.sudo().report_progress(users=goal.user_id)
return result
def get_action(self):
"""Get the ir.action related to update the goal
In case of a manual goal, should return a wizard to update the value
:return: action description in a dictionary
"""
if self.definition_id.action_id:
# open a the action linked to the goal
action = self.definition_id.action_id.read()[0]
if self.definition_id.res_id_field:
current_user = self.env.user.with_user(self.env.user)
action['res_id'] = safe_eval(self.definition_id.res_id_field, {
'user': current_user
})
# if one element to display, should see it in form mode if possible
action['views'] = [
(view_id, mode)
for (view_id, mode) in action['views']
if mode == 'form'
] or action['views']
return action
if self.computation_mode == 'manually':
# open a wizard window to update the value manually
action = {
'name': _("Update %s", self.definition_id.name),
'id': self.id,
'type': 'ir.actions.act_window',
'views': [[False, 'form']],
'target': 'new',
'context': {'default_goal_id': self.id, 'default_current': self.current},
'res_model': 'gamification.goal.wizard'
}
return action
return False
| 49.829741 | 23,121 |
35,772 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import itertools
import logging
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta, MO
from odoo import api, models, fields, _, exceptions
from odoo.tools import ustr
_logger = logging.getLogger(__name__)
# display top 3 in ranking, could be db variable
MAX_VISIBILITY_RANKING = 3
def start_end_date_for_period(period, default_start_date=False, default_end_date=False):
"""Return the start and end date for a goal period based on today
:param str default_start_date: string date in DEFAULT_SERVER_DATE_FORMAT format
:param str default_end_date: string date in DEFAULT_SERVER_DATE_FORMAT format
:return: (start_date, end_date), dates in string format, False if the period is
not defined or unknown"""
today = date.today()
if period == 'daily':
start_date = today
end_date = start_date
elif period == 'weekly':
start_date = today + relativedelta(weekday=MO(-1))
end_date = start_date + timedelta(days=7)
elif period == 'monthly':
start_date = today.replace(day=1)
end_date = today + relativedelta(months=1, day=1, days=-1)
elif period == 'yearly':
start_date = today.replace(month=1, day=1)
end_date = today.replace(month=12, day=31)
else: # period == 'once':
start_date = default_start_date # for manual goal, start each time
end_date = default_end_date
return (start_date, end_date)
return fields.Datetime.to_string(start_date), fields.Datetime.to_string(end_date)
class Challenge(models.Model):
"""Gamification challenge
Set of predifined objectives assigned to people with rules for recurrence and
rewards
If 'user_ids' is defined and 'period' is different than 'one', the set will
be assigned to the users for each period (eg: every 1st of each month if
'monthly' is selected)
"""
_name = 'gamification.challenge'
_description = 'Gamification Challenge'
_inherit = 'mail.thread'
_order = 'end_date, start_date, name, id'
name = fields.Char("Challenge Name", required=True, translate=True)
description = fields.Text("Description", translate=True)
state = fields.Selection([
('draft', "Draft"),
('inprogress', "In Progress"),
('done', "Done"),
], default='draft', copy=False,
string="State", required=True, tracking=True)
manager_id = fields.Many2one(
'res.users', default=lambda self: self.env.uid,
string="Responsible", help="The user responsible for the challenge.",)
user_ids = fields.Many2many('res.users', 'gamification_challenge_users_rel', string="Users", help="List of users participating to the challenge")
user_domain = fields.Char("User domain", help="Alternative to a list of users")
period = fields.Selection([
('once', "Non recurring"),
('daily', "Daily"),
('weekly', "Weekly"),
('monthly', "Monthly"),
('yearly', "Yearly")
], default='once',
string="Periodicity",
help="Period of automatic goal assigment. If none is selected, should be launched manually.",
required=True)
start_date = fields.Date("Start Date", help="The day a new challenge will be automatically started. If no periodicity is set, will use this date as the goal start date.")
end_date = fields.Date("End Date", help="The day a new challenge will be automatically closed. If no periodicity is set, will use this date as the goal end date.")
invited_user_ids = fields.Many2many('res.users', 'gamification_invited_user_ids_rel', string="Suggest to users")
line_ids = fields.One2many('gamification.challenge.line', 'challenge_id',
string="Lines",
help="List of goals that will be set",
required=True, copy=True)
reward_id = fields.Many2one('gamification.badge', string="For Every Succeeding User")
reward_first_id = fields.Many2one('gamification.badge', string="For 1st user")
reward_second_id = fields.Many2one('gamification.badge', string="For 2nd user")
reward_third_id = fields.Many2one('gamification.badge', string="For 3rd user")
reward_failure = fields.Boolean("Reward Bests if not Succeeded?")
reward_realtime = fields.Boolean("Reward as soon as every goal is reached", default=True, help="With this option enabled, a user can receive a badge only once. The top 3 badges are still rewarded only at the end of the challenge.")
visibility_mode = fields.Selection([
('personal', "Individual Goals"),
('ranking', "Leader Board (Group Ranking)"),
], default='personal',
string="Display Mode", required=True)
report_message_frequency = fields.Selection([
('never', "Never"),
('onchange', "On change"),
('daily', "Daily"),
('weekly', "Weekly"),
('monthly', "Monthly"),
('yearly', "Yearly")
], default='never',
string="Report Frequency", required=True)
report_message_group_id = fields.Many2one('mail.channel', string="Send a copy to", help="Group that will receive a copy of the report in addition to the user")
report_template_id = fields.Many2one('mail.template', default=lambda self: self._get_report_template(), string="Report Template", required=True)
remind_update_delay = fields.Integer("Non-updated manual goals will be reminded after", help="Never reminded if no value or zero is specified.")
last_report_date = fields.Date("Last Report Date", default=fields.Date.today)
next_report_date = fields.Date("Next Report Date", compute='_get_next_report_date', store=True)
challenge_category = fields.Selection([
('hr', 'Human Resources / Engagement'),
('other', 'Settings / Gamification Tools'),
], string="Appears in", required=True, default='hr',
help="Define the visibility of the challenge through menus")
REPORT_OFFSETS = {
'daily': timedelta(days=1),
'weekly': timedelta(days=7),
'monthly': relativedelta(months=1),
'yearly': relativedelta(years=1),
}
@api.depends('last_report_date', 'report_message_frequency')
def _get_next_report_date(self):
""" Return the next report date based on the last report date and
report period.
"""
for challenge in self:
last = challenge.last_report_date
offset = self.REPORT_OFFSETS.get(challenge.report_message_frequency)
if offset:
challenge.next_report_date = last + offset
else:
challenge.next_report_date = False
def _get_report_template(self):
template = self.env.ref('gamification.simple_report_template', raise_if_not_found=False)
return template.id if template else False
@api.model_create_multi
def create(self, vals_list):
"""Overwrite the create method to add the user of groups"""
for vals in vals_list:
if vals.get('user_domain'):
users = self._get_challenger_users(ustr(vals.get('user_domain')))
if not vals.get('user_ids'):
vals['user_ids'] = []
vals['user_ids'].extend((4, user.id) for user in users)
return super().create(vals_list)
def write(self, vals):
if vals.get('user_domain'):
users = self._get_challenger_users(ustr(vals.get('user_domain')))
if not vals.get('user_ids'):
vals['user_ids'] = []
vals['user_ids'].extend((4, user.id) for user in users)
write_res = super(Challenge, self).write(vals)
if vals.get('report_message_frequency', 'never') != 'never':
# _recompute_challenge_users do not set users for challenges with no reports, subscribing them now
for challenge in self:
challenge.message_subscribe([user.partner_id.id for user in challenge.user_ids])
if vals.get('state') == 'inprogress':
self._recompute_challenge_users()
self._generate_goals_from_challenge()
elif vals.get('state') == 'done':
self._check_challenge_reward(force=True)
elif vals.get('state') == 'draft':
# resetting progress
if self.env['gamification.goal'].search([('challenge_id', 'in', self.ids), ('state', '=', 'inprogress')], limit=1):
raise exceptions.UserError(_("You can not reset a challenge with unfinished goals."))
return write_res
##### Update #####
@api.model # FIXME: check how cron functions are called to see if decorator necessary
def _cron_update(self, ids=False, commit=True):
"""Daily cron check.
- Start planned challenges (in draft and with start_date = today)
- Create the missing goals (eg: modified the challenge to add lines)
- Update every running challenge
"""
# in cron mode, will do intermediate commits
# cannot be replaced by a parameter because it is intended to impact side-effects of
# write operations
self = self.with_context(commit_gamification=commit)
# start scheduled challenges
planned_challenges = self.search([
('state', '=', 'draft'),
('start_date', '<=', fields.Date.today())
])
if planned_challenges:
planned_challenges.write({'state': 'inprogress'})
# close scheduled challenges
scheduled_challenges = self.search([
('state', '=', 'inprogress'),
('end_date', '<', fields.Date.today())
])
if scheduled_challenges:
scheduled_challenges.write({'state': 'done'})
records = self.browse(ids) if ids else self.search([('state', '=', 'inprogress')])
return records._update_all()
def _update_all(self):
"""Update the challenges and related goals."""
if not self:
return True
Goals = self.env['gamification.goal']
# include yesterday goals to update the goals that just ended
# exclude goals for portal users that did not connect since the last update
yesterday = fields.Date.to_string(date.today() - timedelta(days=1))
self.env.cr.execute("""SELECT gg.id
FROM gamification_goal as gg
JOIN res_users_log as log ON gg.user_id = log.create_uid
JOIN res_users ru on log.create_uid = ru.id
WHERE (gg.write_date < log.create_date OR ru.share IS NOT TRUE)
AND ru.active IS TRUE
AND gg.closed IS NOT TRUE
AND gg.challenge_id IN %s
AND (gg.state = 'inprogress'
OR (gg.state = 'reached' AND gg.end_date >= %s))
GROUP BY gg.id
""", [tuple(self.ids), yesterday])
Goals.browse(goal_id for [goal_id] in self.env.cr.fetchall()).update_goal()
self._recompute_challenge_users()
self._generate_goals_from_challenge()
for challenge in self:
if challenge.last_report_date != fields.Date.today():
if challenge.next_report_date and fields.Date.today() >= challenge.next_report_date:
challenge.report_progress()
else:
# goals closed but still opened at the last report date
closed_goals_to_report = Goals.search([
('challenge_id', '=', challenge.id),
('start_date', '>=', challenge.last_report_date),
('end_date', '<=', challenge.last_report_date)
])
if closed_goals_to_report:
# some goals need a final report
challenge.report_progress(subset_goals=closed_goals_to_report)
self._check_challenge_reward()
return True
def _get_challenger_users(self, domain):
user_domain = ast.literal_eval(domain)
return self.env['res.users'].search(user_domain)
def _recompute_challenge_users(self):
"""Recompute the domain to add new users and remove the one no longer matching the domain"""
for challenge in self.filtered(lambda c: c.user_domain):
current_users = challenge.user_ids
new_users = self._get_challenger_users(challenge.user_domain)
if current_users != new_users:
challenge.user_ids = new_users
return True
def action_start(self):
"""Start a challenge"""
return self.write({'state': 'inprogress'})
def action_check(self):
"""Check a challenge
Create goals that haven't been created yet (eg: if added users)
Recompute the current value for each goal related"""
self.env['gamification.goal'].search([
('challenge_id', 'in', self.ids),
('state', '=', 'inprogress')
]).unlink()
return self._update_all()
def action_report_progress(self):
"""Manual report of a goal, does not influence automatic report frequency"""
for challenge in self:
challenge.report_progress()
return True
##### Automatic actions #####
def _generate_goals_from_challenge(self):
"""Generate the goals for each line and user.
If goals already exist for this line and user, the line is skipped. This
can be called after each change in the list of users or lines.
:param list(int) ids: the list of challenge concerned"""
Goals = self.env['gamification.goal']
for challenge in self:
(start_date, end_date) = start_end_date_for_period(challenge.period, challenge.start_date, challenge.end_date)
to_update = Goals.browse(())
for line in challenge.line_ids:
# there is potentially a lot of users
# detect the ones with no goal linked to this line
date_clause = ""
query_params = [line.id]
if start_date:
date_clause += " AND g.start_date = %s"
query_params.append(start_date)
if end_date:
date_clause += " AND g.end_date = %s"
query_params.append(end_date)
query = """SELECT u.id AS user_id
FROM res_users u
LEFT JOIN gamification_goal g
ON (u.id = g.user_id)
WHERE line_id = %s
{date_clause}
""".format(date_clause=date_clause)
self.env.cr.execute(query, query_params)
user_with_goal_ids = {it for [it] in self.env.cr._obj}
participant_user_ids = set(challenge.user_ids.ids)
user_squating_challenge_ids = user_with_goal_ids - participant_user_ids
if user_squating_challenge_ids:
# users that used to match the challenge
Goals.search([
('challenge_id', '=', challenge.id),
('user_id', 'in', list(user_squating_challenge_ids))
]).unlink()
values = {
'definition_id': line.definition_id.id,
'line_id': line.id,
'target_goal': line.target_goal,
'state': 'inprogress',
}
if start_date:
values['start_date'] = start_date
if end_date:
values['end_date'] = end_date
# the goal is initialised over the limit to make sure we will compute it at least once
if line.condition == 'higher':
values['current'] = min(line.target_goal - 1, 0)
else:
values['current'] = max(line.target_goal + 1, 0)
if challenge.remind_update_delay:
values['remind_update_delay'] = challenge.remind_update_delay
for user_id in (participant_user_ids - user_with_goal_ids):
values['user_id'] = user_id
to_update |= Goals.create(values)
to_update.update_goal()
if self.env.context.get('commit_gamification'):
self.env.cr.commit()
return True
##### JS utilities #####
def _get_serialized_challenge_lines(self, user=(), restrict_goals=(), restrict_top=0):
"""Return a serialised version of the goals information if the user has not completed every goal
:param user: user retrieving progress (False if no distinction,
only for ranking challenges)
:param restrict_goals: compute only the results for this subset of
gamification.goal ids, if False retrieve every
goal of current running challenge
:param int restrict_top: for challenge lines where visibility_mode is
``ranking``, retrieve only the best
``restrict_top`` results and itself, if 0
retrieve all restrict_goal_ids has priority
over restrict_top
format list
# if visibility_mode == 'ranking'
{
'name': <gamification.goal.description name>,
'description': <gamification.goal.description description>,
'condition': <reach condition {lower,higher}>,
'computation_mode': <target computation {manually,count,sum,python}>,
'monetary': <{True,False}>,
'suffix': <value suffix>,
'action': <{True,False}>,
'display_mode': <{progress,boolean}>,
'target': <challenge line target>,
'own_goal_id': <gamification.goal id where user_id == uid>,
'goals': [
{
'id': <gamification.goal id>,
'rank': <user ranking>,
'user_id': <res.users id>,
'name': <res.users name>,
'state': <gamification.goal state {draft,inprogress,reached,failed,canceled}>,
'completeness': <percentage>,
'current': <current value>,
}
]
},
# if visibility_mode == 'personal'
{
'id': <gamification.goal id>,
'name': <gamification.goal.description name>,
'description': <gamification.goal.description description>,
'condition': <reach condition {lower,higher}>,
'computation_mode': <target computation {manually,count,sum,python}>,
'monetary': <{True,False}>,
'suffix': <value suffix>,
'action': <{True,False}>,
'display_mode': <{progress,boolean}>,
'target': <challenge line target>,
'state': <gamification.goal state {draft,inprogress,reached,failed,canceled}>,
'completeness': <percentage>,
'current': <current value>,
}
"""
Goals = self.env['gamification.goal']
(start_date, end_date) = start_end_date_for_period(self.period)
res_lines = []
for line in self.line_ids:
line_data = {
'name': line.definition_id.name,
'description': line.definition_id.description,
'condition': line.definition_id.condition,
'computation_mode': line.definition_id.computation_mode,
'monetary': line.definition_id.monetary,
'suffix': line.definition_id.suffix,
'action': True if line.definition_id.action_id else False,
'display_mode': line.definition_id.display_mode,
'target': line.target_goal,
}
domain = [
('line_id', '=', line.id),
('state', '!=', 'draft'),
]
if restrict_goals:
domain.append(('id', 'in', restrict_goals.ids))
else:
# if no subset goals, use the dates for restriction
if start_date:
domain.append(('start_date', '=', start_date))
if end_date:
domain.append(('end_date', '=', end_date))
if self.visibility_mode == 'personal':
if not user:
raise exceptions.UserError(_("Retrieving progress for personal challenge without user information"))
domain.append(('user_id', '=', user.id))
goal = Goals.search(domain, limit=1)
if not goal:
continue
if goal.state != 'reached':
return []
line_data.update(goal.read(['id', 'current', 'completeness', 'state'])[0])
res_lines.append(line_data)
continue
line_data['own_goal_id'] = False,
line_data['goals'] = []
if line.condition=='higher':
goals = Goals.search(domain, order="completeness desc, current desc")
else:
goals = Goals.search(domain, order="completeness desc, current asc")
if not goals:
continue
for ranking, goal in enumerate(goals):
if user and goal.user_id == user:
line_data['own_goal_id'] = goal.id
elif restrict_top and ranking > restrict_top:
# not own goal and too low to be in top
continue
line_data['goals'].append({
'id': goal.id,
'user_id': goal.user_id.id,
'name': goal.user_id.name,
'rank': ranking,
'current': goal.current,
'completeness': goal.completeness,
'state': goal.state,
})
if len(goals) < 3:
# display at least the top 3 in the results
missing = 3 - len(goals)
for ranking, mock_goal in enumerate([{'id': False,
'user_id': False,
'name': '',
'current': 0,
'completeness': 0,
'state': False}] * missing,
start=len(goals)):
mock_goal['rank'] = ranking
line_data['goals'].append(mock_goal)
res_lines.append(line_data)
return res_lines
##### Reporting #####
def report_progress(self, users=(), subset_goals=False):
"""Post report about the progress of the goals
:param users: users that are concerned by the report. If False, will
send the report to every user concerned (goal users and
group that receive a copy). Only used for challenge with
a visibility mode set to 'personal'.
:param subset_goals: goals to restrict the report
"""
challenge = self
if challenge.visibility_mode == 'ranking':
lines_boards = challenge._get_serialized_challenge_lines(restrict_goals=subset_goals)
body_html = challenge.report_template_id.with_context(challenge_lines=lines_boards)._render_field('body_html', challenge.ids)[challenge.id]
# send to every follower and participant of the challenge
challenge.message_post(
body=body_html,
partner_ids=challenge.mapped('user_ids.partner_id.id'),
subtype_xmlid='mail.mt_comment',
email_layout_xmlid='mail.mail_notification_light',
)
if challenge.report_message_group_id:
challenge.report_message_group_id.message_post(
body=body_html,
subtype_xmlid='mail.mt_comment')
else:
# generate individual reports
for user in (users or challenge.user_ids):
lines = challenge._get_serialized_challenge_lines(user, restrict_goals=subset_goals)
if not lines:
continue
body_html = challenge.report_template_id.with_user(user).with_context(challenge_lines=lines)._render_field('body_html', challenge.ids)[challenge.id]
# notify message only to users, do not post on the challenge
challenge.message_notify(
body=body_html,
partner_ids=[user.partner_id.id],
subtype_xmlid='mail.mt_comment',
email_layout_xmlid='mail.mail_notification_light',
)
if challenge.report_message_group_id:
challenge.report_message_group_id.message_post(
body=body_html,
subtype_xmlid='mail.mt_comment',
email_layout_xmlid='mail.mail_notification_light',
)
return challenge.write({'last_report_date': fields.Date.today()})
##### Challenges #####
def accept_challenge(self):
user = self.env.user
sudoed = self.sudo()
sudoed.message_post(body=_("%s has joined the challenge", user.name))
sudoed.write({'invited_user_ids': [(3, user.id)], 'user_ids': [(4, user.id)]})
return sudoed._generate_goals_from_challenge()
def discard_challenge(self):
"""The user discard the suggested challenge"""
user = self.env.user
sudoed = self.sudo()
sudoed.message_post(body=_("%s has refused the challenge", user.name))
return sudoed.write({'invited_user_ids': (3, user.id)})
def _check_challenge_reward(self, force=False):
"""Actions for the end of a challenge
If a reward was selected, grant it to the correct users.
Rewards granted at:
- the end date for a challenge with no periodicity
- the end of a period for challenge with periodicity
- when a challenge is manually closed
(if no end date, a running challenge is never rewarded)
"""
commit = self.env.context.get('commit_gamification') and self.env.cr.commit
for challenge in self:
(start_date, end_date) = start_end_date_for_period(challenge.period, challenge.start_date, challenge.end_date)
yesterday = date.today() - timedelta(days=1)
rewarded_users = self.env['res.users']
challenge_ended = force or end_date == fields.Date.to_string(yesterday)
if challenge.reward_id and (challenge_ended or challenge.reward_realtime):
# not using start_date as intemportal goals have a start date but no end_date
reached_goals = self.env['gamification.goal'].read_group([
('challenge_id', '=', challenge.id),
('end_date', '=', end_date),
('state', '=', 'reached')
], fields=['user_id'], groupby=['user_id'])
for reach_goals_user in reached_goals:
if reach_goals_user['user_id_count'] == len(challenge.line_ids):
# the user has succeeded every assigned goal
user = self.env['res.users'].browse(reach_goals_user['user_id'][0])
if challenge.reward_realtime:
badges = self.env['gamification.badge.user'].search_count([
('challenge_id', '=', challenge.id),
('badge_id', '=', challenge.reward_id.id),
('user_id', '=', user.id),
])
if badges > 0:
# has already recieved the badge for this challenge
continue
challenge._reward_user(user, challenge.reward_id)
rewarded_users |= user
if commit:
commit()
if challenge_ended:
# open chatter message
message_body = _("The challenge %s is finished.", challenge.name)
if rewarded_users:
user_names = rewarded_users.name_get()
message_body += _(
"<br/>Reward (badge %(badge_name)s) for every succeeding user was sent to %(users)s.",
badge_name=challenge.reward_id.name,
users=", ".join(name for (user_id, name) in user_names)
)
else:
message_body += _("<br/>Nobody has succeeded to reach every goal, no badge is rewarded for this challenge.")
# reward bests
reward_message = _("<br/> %(rank)d. %(user_name)s - %(reward_name)s")
if challenge.reward_first_id:
(first_user, second_user, third_user) = challenge._get_topN_users(MAX_VISIBILITY_RANKING)
if first_user:
challenge._reward_user(first_user, challenge.reward_first_id)
message_body += _("<br/>Special rewards were sent to the top competing users. The ranking for this challenge is :")
message_body += reward_message % {
'rank': 1,
'user_name': first_user.name,
'reward_name': challenge.reward_first_id.name,
}
else:
message_body += _("Nobody reached the required conditions to receive special badges.")
if second_user and challenge.reward_second_id:
challenge._reward_user(second_user, challenge.reward_second_id)
message_body += reward_message % {
'rank': 2,
'user_name': second_user.name,
'reward_name': challenge.reward_second_id.name,
}
if third_user and challenge.reward_third_id:
challenge._reward_user(third_user, challenge.reward_third_id)
message_body += reward_message % {
'rank': 3,
'user_name': third_user.name,
'reward_name': challenge.reward_third_id.name,
}
challenge.message_post(
partner_ids=[user.partner_id.id for user in challenge.user_ids],
body=message_body)
if commit:
commit()
return True
def _get_topN_users(self, n):
"""Get the top N users for a defined challenge
Ranking criterias:
1. succeed every goal of the challenge
2. total completeness of each goal (can be over 100)
Only users having reached every goal of the challenge will be returned
unless the challenge ``reward_failure`` is set, in which case any user
may be considered.
:returns: an iterable of exactly N records, either User objects or
False if there was no user for the rank. There can be no
False between two users (if users[k] = False then
users[k+1] = False
"""
Goals = self.env['gamification.goal']
(start_date, end_date) = start_end_date_for_period(self.period, self.start_date, self.end_date)
challengers = []
for user in self.user_ids:
all_reached = True
total_completeness = 0
# every goal of the user for the running period
goal_ids = Goals.search([
('challenge_id', '=', self.id),
('user_id', '=', user.id),
('start_date', '=', start_date),
('end_date', '=', end_date)
])
for goal in goal_ids:
if goal.state != 'reached':
all_reached = False
if goal.definition_condition == 'higher':
# can be over 100
total_completeness += (100.0 * goal.current / goal.target_goal) if goal.target_goal else 0
elif goal.state == 'reached':
# for lower goals, can not get percentage so 0 or 100
total_completeness += 100
challengers.append({'user': user, 'all_reached': all_reached, 'total_completeness': total_completeness})
challengers.sort(key=lambda k: (k['all_reached'], k['total_completeness']), reverse=True)
if not self.reward_failure:
# only keep the fully successful challengers at the front, could
# probably use filter since the successful ones are at the front
challengers = itertools.takewhile(lambda c: c['all_reached'], challengers)
# append a tail of False, then keep the first N
challengers = itertools.islice(
itertools.chain(
(c['user'] for c in challengers),
itertools.repeat(False),
), 0, n
)
return tuple(challengers)
def _reward_user(self, user, badge):
"""Create a badge user and send the badge to him
:param user: the user to reward
:param badge: the concerned badge
"""
return self.env['gamification.badge.user'].create({
'user_id': user.id,
'badge_id': badge.id,
'challenge_id': self.id
})._send_badge()
class ChallengeLine(models.Model):
"""Gamification challenge line
Predefined goal for 'gamification_challenge'
These are generic list of goals with only the target goal defined
Should only be created for the gamification.challenge object
"""
_name = 'gamification.challenge.line'
_description = 'Gamification generic goal for challenge'
_order = "sequence, id"
challenge_id = fields.Many2one('gamification.challenge', string='Challenge', required=True, ondelete="cascade")
definition_id = fields.Many2one('gamification.goal.definition', string='Goal Definition', required=True, ondelete="cascade")
sequence = fields.Integer('Sequence', help='Sequence number for ordering', default=1)
target_goal = fields.Float('Target Value to Reach', required=True)
name = fields.Char("Name", related='definition_id.name', readonly=False)
condition = fields.Selection(string="Condition", related='definition_id.condition', readonly=True)
definition_suffix = fields.Char("Unit", related='definition_id.suffix', readonly=True)
definition_monetary = fields.Boolean("Monetary", related='definition_id.monetary', readonly=True)
definition_full_suffix = fields.Char("Suffix", related='definition_id.full_suffix', readonly=True)
| 45.052897 | 35,772 |
763 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Gulf Cooperation Council - Point of Sale',
'author': 'Odoo S.A',
'category': 'Accounting/Localizations/Point of Sale',
'description': """
GCC POS Localization
=======================================================
""",
'license': 'LGPL-3',
'depends': ['point_of_sale', 'l10n_gcc_invoice'],
'data': [
],
'assets': {
'web.assets_qweb': [
'l10n_gcc_pos/static/src/xml/OrderReceipt.xml',
],
'point_of_sale.assets': [
'l10n_gcc_pos/static/src/js/OrderReceipt.js',
'l10n_gcc_pos/static/src/css/OrderReceipt.css',
]
},
'auto_install': True,
}
| 30.52 | 763 |
7,598 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Discuss',
'version': '1.5',
'category': 'Productivity/Discuss',
'sequence': 145,
'summary': 'Chat, mail gateway and private channels',
'description': "",
'website': 'https://www.odoo.com/app/discuss',
'depends': ['base', 'base_setup', 'bus', 'web_tour'],
'data': [
'data/mail_groups.xml',
'wizard/mail_blacklist_remove_views.xml',
'wizard/mail_compose_message_views.xml',
'wizard/mail_resend_cancel_views.xml',
'wizard/mail_resend_message_views.xml',
'wizard/mail_template_preview_views.xml',
'wizard/mail_wizard_invite_views.xml',
'views/mail_message_subtype_views.xml',
'views/mail_tracking_views.xml',
'views/mail_notification_views.xml',
'views/mail_message_views.xml',
'views/mail_mail_views.xml',
'views/mail_followers_views.xml',
'views/mail_ice_server_views.xml',
'views/mail_channel_partner_views.xml',
'views/mail_channel_rtc_session_views.xml',
'views/mail_channel_views.xml',
'views/mail_shortcode_views.xml',
'views/mail_activity_views.xml',
'views/res_config_settings_views.xml',
'data/res_partner_data.xml',
'data/mail_message_subtype_data.xml',
'data/mail_templates.xml',
'data/mail_channel_data.xml',
'data/mail_activity_data.xml',
'data/ir_cron_data.xml',
'security/mail_security.xml',
'security/ir.model.access.csv',
'views/discuss_public_templates.xml',
'views/mail_alias_views.xml',
'views/mail_guest_views.xml',
'views/mail_message_reaction_views.xml',
'views/res_users_views.xml',
'views/res_users_settings_views.xml',
'views/mail_template_views.xml',
'views/ir_actions_server_views.xml',
'views/ir_model_views.xml',
'views/res_partner_views.xml',
'views/mail_blacklist_views.xml',
'views/mail_menus.xml',
],
'demo': [
'data/mail_channel_demo.xml',
],
'installable': True,
'application': True,
'assets': {
# Custom bundle in case we want to remove things that are later added to web.assets_common
'mail.assets_common_discuss_public': [
('include', 'web.assets_common'),
],
'mail.assets_discuss_public': [
# SCSS dependencies (the order is important)
('include', 'web._assets_helpers'),
'web/static/src/legacy/scss/bootstrap_overridden.scss',
'web/static/lib/bootstrap/scss/_variables.scss',
'web/static/src/legacy/scss/import_bootstrap.scss',
'web/static/src/legacy/scss/bootstrap_review.scss',
'web/static/src/webclient/webclient.scss',
'web/static/src/webclient/webclient_extra.scss',
'web/static/src/core/utils/*.scss',
# Dependency of notification_group, notification_request, thread_needaction_preview and thread_preview
'mail/static/src/components/notification_list/notification_list_item.scss',
'mail/static/src/component_hooks/*/*.js',
'mail/static/src/components/*/*',
# Unused by guests and depends on ViewDialogs, better to remove it instead of pulling the whole view dependency tree
('remove', 'mail/static/src/components/composer_suggested_recipient/*'),
'mail/static/src/js/emojis.js',
'mail/static/src/js/utils.js',
'mail/static/src/model/*.js',
'mail/static/src/models/*/*.js',
'mail/static/src/public/*',
'mail/static/src/services/messaging/messaging.js',
'mail/static/src/utils/*/*.js',
'mail/static/src/utils/messaging_component.js',
'mail/static/src/utils/utils.js',
# Framework JS
'bus/static/src/js/*.js',
'bus/static/src/js/services/bus_service.js',
'web/static/lib/luxon/luxon.js',
'web/static/src/core/**/*',
# FIXME: debug menu currently depends on webclient, once it doesn't we don't need to remove the contents of the debug folder
('remove', 'web/static/src/core/debug/**/*'),
'web/static/src/env.js',
'web/static/src/legacy/js/core/misc.js',
'web/static/src/legacy/js/env.js',
'web/static/src/legacy/js/fields/field_utils.js',
'web/static/src/legacy/js/owl_compatibility.js',
'web/static/src/legacy/js/services/data_manager.js',
'web/static/src/legacy/js/services/session.js',
'web/static/src/legacy/js/widgets/date_picker.js',
'web/static/src/legacy/legacy_promise_error_handler.js',
'web/static/src/legacy/legacy_rpc_error_handler.js',
'web/static/src/legacy/utils.js',
'web/static/src/legacy/xml/base.xml',
],
'web._assets_primary_variables': [
'mail/static/src/scss/variables/primary_variables.scss',
],
'web.assets_backend': [
# depends on BS variables, can't be loaded in assets_primary or assets_secondary
'mail/static/src/scss/variables/derived_variables.scss',
# defines mixins and variables used by multiple components
'mail/static/src/components/notification_list/notification_list_item.scss',
'mail/static/src/js/**/*.js',
'mail/static/src/utils/*/*.js',
'mail/static/src/utils/messaging_component.js',
'mail/static/src/utils/utils.js',
'mail/static/src/scss/*.scss',
'mail/static/src/component_hooks/*/*.js',
'mail/static/src/components/*/*.js',
'mail/static/src/components/*/*.scss',
'mail/static/src/model/*.js',
'mail/static/src/models/*/*.js',
'mail/static/src/services/*/*.js',
'mail/static/src/webclient/commands/*.js',
'mail/static/src/widgets/*/*.js',
'mail/static/src/widgets/*/*.scss',
],
'web.assets_backend_prod_only': [
'mail/static/src/main.js',
],
'mail.assets_discuss_public_test_tours': [
'mail/static/tests/tours/discuss_public_tour.js',
'mail/static/tests/tours/mail_channel_as_guest_tour.js',
],
'web.assets_tests': [
'mail/static/tests/tours/**/*',
],
'web.tests_assets': [
'mail/static/src/env/test_env.js',
'mail/static/src/utils/test_utils.js',
'mail/static/tests/helpers/mock_models.js',
'mail/static/tests/helpers/mock_server.js',
],
'web.qunit_suite_tests': [
'mail/static/tests/*.js',
'mail/static/tests/systray/systray_activity_menu_tests.js',
'mail/static/tests/tools/debug_manager_tests.js',
'mail/static/tests/webclient/commands/*.js',
'mail/static/src/components/*/tests/*.js',
'mail/static/src/model/tests/**/*.js',
'mail/static/src/models/*/tests/*.js',
'mail/static/src/utils/*/tests/*.js',
'mail/static/src/widgets/*/tests/*.js',
],
'web.qunit_mobile_suite_tests': [
'mail/static/src/components/*/mobile_tests/*.js',
],
'web.assets_qweb': [
'mail/static/src/xml/*.xml',
'mail/static/src/components/*/*.xml',
'mail/static/src/widgets/*/*.xml',
],
},
'license': 'LGPL-3',
}
| 44.95858 | 7,598 |
888 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import tools
_logger = logging.getLogger(__name__)
_flanker_lib_warning = False
try:
from flanker.addresslib import address
# Avoid warning each time a mx server is not reachable by flanker
logging.getLogger("flanker.addresslib.validate").setLevel(logging.ERROR)
def mail_validate(email):
return bool(address.validate_address(email))
except ImportError:
def mail_validate(email):
global _flanker_lib_warning
if not _flanker_lib_warning:
_flanker_lib_warning = True
_logger.info("The `flanker` Python module is not installed,"
"so email validation fallback to email_normalize. Use 'pip install flanker' to install it")
return tools.email_normalize(email)
| 32.888889 | 888 |
1,053 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import tagged, HttpCase
from odoo import Command
@tagged('-at_install', 'post_install', 'mail_composer')
class TestMailFullComposer(HttpCase):
def test_full_composer_tour(self):
self.env['mail.template'].create({
'name': 'Test template',
'partner_to': '{{ object.id }}',
'lang': '{{ object.lang }}',
'auto_delete': True,
'model_id': self.ref('base.model_res_partner'),
})
testuser = self.env['res.users'].create({
'email': '[email protected]',
'groups_id': [Command.set([self.ref('base.group_user'), self.ref('base.group_partner_manager')])],
'name': 'Test User',
'login': 'testuser',
'password': 'testuser',
})
self.start_tour("/web#id=%d&model=res.partner" % testuser.partner_id, 'mail/static/tests/tours/mail_full_composer_test_tour.js', login='testuser')
| 40.5 | 1,053 |
1,008 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged, TransactionCase
@tagged('-at_install', 'post_install')
class TestMailUninstall(TransactionCase):
def test_unlink_model(self):
model = self.env['ir.model'].create({
'name': 'Test Model',
'model': 'x_test_model',
'state': 'manual',
'is_mail_thread': True,
})
activity_type = self.env['mail.activity.type'].create({
'name': 'Test Activity Type',
'res_model': model.model,
})
record = self.env[model.model].create({})
activity = self.env['mail.activity'].create({
'activity_type_id': activity_type.id,
'res_model_id': model.id,
'res_id': record.id,
})
model.unlink()
self.assertFalse(model.exists())
self.assertFalse(activity_type.exists())
self.assertFalse(activity.exists())
| 32.516129 | 1,008 |
9,035 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import MailCommon
from odoo.tests import tagged, users
from odoo import tools
@tagged('mail_tools')
class TestMailTools(MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailTools, cls).setUpClass()
cls._test_email = '[email protected]'
cls.test_partner = cls.env['res.partner'].create({
'country_id': cls.env.ref('base.be').id,
'email': cls._test_email,
'mobile': '0456001122',
'name': 'Alfred Astaire',
'phone': '0456334455',
})
cls.sources = [
# single email
'[email protected]',
' [email protected] ',
'Fredo The Great <[email protected]>',
'"Fredo The Great" <[email protected]>',
'Fredo "The Great" <[email protected]>',
# multiple emails
'[email protected], [email protected]',
'Fredo The Great <[email protected]>, Evelyne The Goat <[email protected]>',
'"Fredo The Great" <[email protected]>, [email protected]',
'"Fredo The Great" <[email protected]>, <[email protected]>',
# text containing email
'Hello [email protected] how are you ?',
'<p>Hello [email protected]</p>',
# text containing emails
'Hello "Fredo" <[email protected]>, [email protected]',
'Hello "Fredo" <[email protected]> and [email protected]',
# falsy
'<p>Hello Fredo</p>',
'j\'adore écrire des @gmail.com ou "@gmail.com" a bit randomly',
'',
]
@users('employee')
def test_find_partner_from_emails(self):
Partner = self.env['res.partner']
test_partner = Partner.browse(self.test_partner.ids)
self.assertEqual(test_partner.email, self._test_email)
# test direct match
found = Partner._mail_find_partner_from_emails([self._test_email])
self.assertEqual(found, [test_partner])
# test encapsulated email
found = Partner._mail_find_partner_from_emails(['"Norbert Poiluchette" <%s>' % self._test_email])
self.assertEqual(found, [test_partner])
# test with wildcard "_"
found = Partner._mail_find_partner_from_emails(['[email protected]'])
self.assertEqual(found, [self.env['res.partner']])
# sub-check: this search does not consider _ as a wildcard
found = Partner._mail_search_on_partner(['[email protected]'])
self.assertEqual(found, self.env['res.partner'])
# test partners with encapsulated emails
# ------------------------------------------------------------
test_partner.sudo().write({'email': '"Alfred Mighty Power Astaire" <%s>' % self._test_email})
# test direct match
found = Partner._mail_find_partner_from_emails([self._test_email])
self.assertEqual(found, [test_partner])
# test encapsulated email
found = Partner._mail_find_partner_from_emails(['"Norbert Poiluchette" <%s>' % self._test_email])
self.assertEqual(found, [test_partner])
# test with wildcard "_"
found = Partner._mail_find_partner_from_emails(['[email protected]'])
self.assertEqual(found, [self.env['res.partner']])
# sub-check: this search does not consider _ as a wildcard
found = Partner._mail_search_on_partner(['[email protected]'])
self.assertEqual(found, self.env['res.partner'])
# test partners with look-alike emails
# ------------------------------------------------------------
for email_lookalike in [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]']:
test_partner.sudo().write({'email': '"Alfred Astaire" <%s>' % email_lookalike})
# test direct match
found = Partner._mail_find_partner_from_emails([self._test_email])
self.assertEqual(found, [self.env['res.partner']])
# test encapsulated email
found = Partner._mail_find_partner_from_emails(['"Norbert Poiluchette" <%s>' % self._test_email])
self.assertEqual(found, [self.env['res.partner']])
# test with wildcard "_"
found = Partner._mail_find_partner_from_emails(['[email protected]'])
self.assertEqual(found, [self.env['res.partner']])
@users('employee')
def test_tools_email_re(self):
expected = [
# single email
['[email protected]'],
['[email protected]'],
['[email protected]'],
['[email protected]'],
['[email protected]'],
# multiple emails
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
# text containing email
['[email protected]'],
['[email protected]'],
# text containing emails
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
# falsy
[], [], [],
]
for src, exp in zip(self.sources, expected):
res = tools.email_re.findall(src)
self.assertEqual(
res, exp,
'Seems email_re is broken with %s (expected %r, received %r)' % (src, exp, res)
)
@users('employee')
def test_tools_email_split_tuples(self):
expected = [
# single email
[('', '[email protected]')],
[('', '[email protected]')],
[('Fredo The Great', '[email protected]')],
[('Fredo The Great', '[email protected]')],
[('Fredo The Great', '[email protected]')],
# multiple emails
[('', '[email protected]'), ('', '[email protected]')],
[('Fredo The Great', '[email protected]'), ('Evelyne The Goat', '[email protected]')],
[('Fredo The Great', '[email protected]'), ('', '[email protected]')],
[('Fredo The Great', '[email protected]'), ('', '[email protected]')],
# text containing email -> probably not designed for that
[('', 'Hello [email protected]?')],
[('', 'Hello [email protected]')],
# text containing emails -> probably not designed for that
[('Hello Fredo', '[email protected]'), ('', '[email protected]')],
[('Hello Fredo', '[email protected]'), ('', 'and [email protected]')],
# falsy -> probably not designed for that
[], [('', "j'adore écrire [email protected]"), ('', '@gmail.com')], [],
]
for src, exp in zip(self.sources, expected):
res = tools.email_split_tuples(src)
self.assertEqual(
res, exp,
'Seems email_split_tuples is broken with %s (expected %r, received %r)' % (src, exp, res)
)
@users('employee')
def test_tools_single_email_re(self):
expected = [
# single email
['[email protected]'],
[], [], [], [], # formatting issue for single email re
# multiple emails -> couic
[], [], [], [],
# text containing email -> couic
[], [],
# text containing emails -> couic
[], [],
# falsy
[], [], [],
]
for src, exp in zip(self.sources, expected):
res = tools.single_email_re.findall(src)
self.assertEqual(
res, exp,
'Seems single_email_re is broken with %s (expected %r, received %r)' % (src, exp, res)
)
| 46.803109 | 9,033 |
27,677 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from datetime import datetime
from unittest.mock import patch
from odoo import Command, fields
from odoo.addons.mail.models.mail_channel import channel_avatar, group_avatar
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.mail.tests.common import MailCommon
from odoo.exceptions import AccessError
from odoo.tests import tagged, Form
from odoo.tests.common import users
from odoo.tools import html_escape, mute_logger
from odoo.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
@tagged('mail_channel')
class TestChannelAccessRights(MailCommon):
@classmethod
def setUpClass(cls):
super(TestChannelAccessRights, cls).setUpClass()
Channel = cls.env['mail.channel'].with_context(cls._test_context)
cls.user_public = mail_new_test_user(cls.env, login='user_public', groups='base.group_public', name='Bert Tartignole')
cls.user_portal = mail_new_test_user(cls.env, login='user_portal', groups='base.group_portal', name='Chell Gladys')
# Pigs: base group for tests
cls.group_groups = Channel.create({
'name': 'Pigs',
'public': 'groups',
'group_public_id': cls.env.ref('base.group_user').id})
# Jobs: public group
cls.group_public = Channel.create({
'name': 'Jobs',
'description': 'NotFalse',
'public': 'public'})
# Private: private group
cls.group_private = Channel.create({
'name': 'Private',
'public': 'private'})
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model', 'odoo.models')
@users('user_public')
def test_access_public(self):
# Read public group -> ok
self.env['mail.channel'].browse(self.group_public.id).read()
# Read groups -> ko, restricted to employees
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_groups.id).read()
# Read private -> ko, restricted to members
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_private.id).read()
# Read a private group when being a member: ok
self.group_private.write({'channel_partner_ids': [(4, self.user_public.partner_id.id)]})
self.env['mail.channel'].browse(self.group_private.id).read()
# Create group: ko, no access rights
with self.assertRaises(AccessError):
self.env['mail.channel'].create({'name': 'Test'})
# Update group: ko, no access rights
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_public.id).write({'name': 'Broutouschnouk'})
# Unlink group: ko, no access rights
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_public.id).unlink()
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.models', 'odoo.models.unlink')
@users('employee')
def test_access_employee(self):
# Employee read employee-based group: ok
group_groups = self.env['mail.channel'].browse(self.group_groups.id)
group_groups.read()
# Employee can create a group
new_channel = self.env['mail.channel'].create({'name': 'Test'})
self.assertIn(new_channel.channel_partner_ids, self.partner_employee)
# Employee update employee-based group: ok
group_groups.write({'name': 'modified'})
# Employee unlink employee-based group: ko
with self.assertRaises(AccessError):
group_groups.unlink()
# Employee cannot read a private group
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_private.id).read()
# Employee cannot write on private
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_private.id).write({'name': 're-modified'})
# Employee cannot unlink private
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_private.id).unlink()
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.models')
@users('user_portal')
def test_access_portal(self):
with self.assertRaises(AccessError):
self.env['mail.channel'].browse(self.group_private.id).name
self.group_private.write({'channel_partner_ids': [(4, self.user_portal.partner_id.id)]})
group_private_portal = self.env['mail.channel'].browse(self.group_private.id)
group_private_portal.read(['name'])
for message in group_private_portal.message_ids:
message.read(['subject'])
# no access to followers (employee only)
with self.assertRaises(AccessError):
group_private_portal.message_partner_ids
for partner in self.group_private.message_partner_ids:
if partner.id == self.user_portal.partner_id.id:
# Chell can read her own partner record
continue
with self.assertRaises(AccessError):
trigger_read = partner.with_user(self.user_portal).name
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model', 'odoo.models')
@users('user_portal')
def test_members(self):
group_public = self.env['mail.channel'].browse(self.group_public.id)
group_public.read(['name'])
self.assertFalse(group_public.is_member)
with self.assertRaises(AccessError):
group_public.write({'name': 'Better Name'})
with self.assertRaises(AccessError):
group_public.add_members(self.env.user.partner_id.ids)
group_private = self.env['mail.channel'].browse(self.group_private.id)
with self.assertRaises(AccessError):
group_private.read(['name'])
with self.assertRaises(AccessError):
self.env['mail.channel.partner'].create({
'partner_id': self.env.user.partner_id.id,
'channel_id': group_private.id,
})
@tagged('mail_channel')
class TestChannelInternals(MailCommon):
@classmethod
def setUpClass(cls):
super(TestChannelInternals, cls).setUpClass()
cls.test_channel = cls.env['mail.channel'].with_context(cls._test_context).create({
'name': 'Test',
'channel_type': 'channel',
'description': 'Description',
'alias_name': 'test',
'public': 'public',
})
cls.test_partner = cls.env['res.partner'].with_context(cls._test_context).create({
'name': 'Test Partner',
'email': '[email protected]',
})
cls.user_employee_nomail = mail_new_test_user(
cls.env, login='employee_nomail',
email=False,
groups='base.group_user',
company_id=cls.company_admin.id,
name='Evita Employee NoEmail',
notification_type='email',
signature='--\nEvite'
)
cls.partner_employee_nomail = cls.user_employee_nomail.partner_id
@users('employee')
def test_channel_form(self):
"""A user that create a private channel should be able to read it."""
channel_form = Form(self.env['mail.channel'].with_user(self.user_employee))
channel_form.name = 'Test private channel'
channel_form.public = 'private'
channel = channel_form.save()
self.assertEqual(channel.name, 'Test private channel', 'Must be able to read the created channel')
@users('employee')
def test_channel_members(self):
channel = self.env['mail.channel'].browse(self.test_channel.ids)
self.assertEqual(channel.message_partner_ids, self.env['res.partner'])
self.assertEqual(channel.channel_partner_ids, self.env['res.partner'])
channel.add_members(self.test_partner.ids)
self.assertEqual(channel.message_partner_ids, self.env['res.partner'])
self.assertEqual(channel.channel_partner_ids, self.test_partner)
channel._action_remove_members(self.test_partner)
self.assertEqual(channel.message_partner_ids, self.env['res.partner'])
self.assertEqual(channel.channel_partner_ids, self.env['res.partner'])
channel.message_post(body='Test', message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertEqual(channel.message_partner_ids, self.env['res.partner'])
self.assertEqual(channel.channel_partner_ids, self.env['res.partner'])
@users('employee')
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_channel_chat_message_post_should_update_last_interest_dt(self):
channel_info = self.env['mail.channel'].with_user(self.user_admin).channel_get((self.partner_employee | self.user_admin.partner_id).ids)
chat = self.env['mail.channel'].with_user(self.user_admin).browse(channel_info['id'])
post_time = fields.Datetime.now()
# Mocks the return value of field.Datetime.now(),
# so we can see if the `last_interest_dt` is updated correctly
with patch.object(fields.Datetime, 'now', lambda: post_time):
chat.message_post(body="Test", message_type='comment', subtype_xmlid='mail.mt_comment')
channel_partner_employee = self.env['mail.channel.partner'].search([
('partner_id', '=', self.partner_employee.id),
('channel_id', '=', chat.id),
])
channel_partner_admin = self.env['mail.channel.partner'].search([
('partner_id', '=', self.partner_admin.id),
('channel_id', '=', chat.id),
])
self.assertEqual(channel_partner_employee.last_interest_dt, post_time)
self.assertEqual(channel_partner_admin.last_interest_dt, post_time)
@users('employee')
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_channel_recipients_channel(self):
""" Posting a message on a channel should not send emails """
channel = self.env['mail.channel'].browse(self.test_channel.ids)
channel.add_members((self.partner_employee | self.partner_admin | self.test_partner).ids)
with self.mock_mail_gateway():
new_msg = channel.message_post(body="Test", message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertNotSentEmail()
self.assertEqual(new_msg.model, self.test_channel._name)
self.assertEqual(new_msg.res_id, self.test_channel.id)
self.assertEqual(new_msg.partner_ids, self.env['res.partner'])
self.assertEqual(new_msg.notified_partner_ids, self.env['res.partner'])
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_channel_recipients_chat(self):
""" Posting a message on a chat should not send emails """
self.test_channel.write({
'channel_type': 'chat',
})
self.test_channel.add_members((self.partner_employee | self.partner_admin | self.test_partner).ids)
with self.mock_mail_gateway():
with self.with_user('employee'):
channel = self.env['mail.channel'].browse(self.test_channel.ids)
new_msg = channel.message_post(body="Test", message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertNotSentEmail()
self.assertEqual(new_msg.model, self.test_channel._name)
self.assertEqual(new_msg.res_id, self.test_channel.id)
self.assertEqual(new_msg.partner_ids, self.env['res.partner'])
self.assertEqual(new_msg.notified_partner_ids, self.env['res.partner'])
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_channel_recipients_mention(self):
""" Posting a message on a classic channel should support mentioning somebody """
self.test_channel.write({'alias_name': False})
with self.mock_mail_gateway():
self.test_channel.message_post(
body="Test", partner_ids=self.test_partner.ids,
message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertSentEmail(self.test_channel.env.user.partner_id, [self.test_partner])
@mute_logger('odoo.models.unlink')
def test_channel_user_synchronize(self):
"""Archiving / deleting a user should automatically unsubscribe related partner from private channels"""
test_channel_private = self.env['mail.channel'].with_context(self._test_context).create({
'name': 'Winden caves',
'description': 'Channel to travel through time',
'public': 'private',
})
test_channel_group = self.env['mail.channel'].with_context(self._test_context).create({
'name': 'Sic Mundus',
'public': 'groups',
'group_public_id': self.env.ref('base.group_user').id})
self.test_channel.add_members((self.partner_employee | self.partner_employee_nomail).ids)
test_channel_private.add_members((self.partner_employee | self.partner_employee_nomail).ids)
test_channel_group.add_members((self.partner_employee | self.partner_employee_nomail).ids)
# Unsubscribe archived user from the private channels, but not from public channels
self.user_employee.active = False
self.assertEqual(test_channel_private.channel_partner_ids, self.partner_employee_nomail)
self.assertEqual(test_channel_group.channel_partner_ids, self.partner_employee_nomail)
self.assertEqual(self.test_channel.channel_partner_ids, self.user_employee.partner_id | self.partner_employee_nomail)
# Unsubscribe deleted user from the private channels, but not from public channels
self.user_employee_nomail.unlink()
self.assertEqual(test_channel_private.channel_partner_ids, self.env['res.partner'])
self.assertEqual(test_channel_group.channel_partner_ids, self.env['res.partner'])
self.assertEqual(self.test_channel.channel_partner_ids, self.user_employee.partner_id | self.partner_employee_nomail)
@users('employee_nomail')
def test_channel_info_get(self):
# `channel_get` should return a new channel the first time a partner is given
initial_channel_info = self.env['mail.channel'].channel_get(partners_to=self.test_partner.ids)
self.assertEqual(set(p['id'] for p in initial_channel_info['members']), {self.partner_employee_nomail.id, self.test_partner.id})
# `channel_get` should return the existing channel every time the same partner is given
same_channel_info = self.env['mail.channel'].channel_get(partners_to=self.test_partner.ids)
self.assertEqual(same_channel_info['id'], initial_channel_info['id'])
# `channel_get` should return the existing channel when the current partner is given together with the other partner
together_channel_info = self.env['mail.channel'].channel_get(partners_to=(self.partner_employee_nomail + self.test_partner).ids)
self.assertEqual(together_channel_info['id'], initial_channel_info['id'])
# `channel_get` should return a new channel the first time just the current partner is given,
# even if a channel containing the current partner together with other partners already exists
solo_channel_info = self.env['mail.channel'].channel_get(partners_to=self.partner_employee_nomail.ids)
self.assertNotEqual(solo_channel_info['id'], initial_channel_info['id'])
self.assertEqual(set(p['id'] for p in solo_channel_info['members']), {self.partner_employee_nomail.id})
# `channel_get` should return the existing channel every time the current partner is given
same_solo_channel_info = self.env['mail.channel'].channel_get(partners_to=self.partner_employee_nomail.ids)
self.assertEqual(same_solo_channel_info['id'], solo_channel_info['id'])
# `channel_get` will pin the channel by default and thus last interest will be updated.
@users('employee')
def test_channel_info_get_should_update_last_interest_dt(self):
# create the channel via `channel_get`
self.env['mail.channel'].channel_get(partners_to=self.partner_admin.ids)
retrieve_time = datetime(2021, 1, 1, 0, 0)
with patch.object(fields.Datetime, 'now', lambda: retrieve_time):
# `last_interest_dt` should be updated again when `channel_get` is called
# because `channel_pin` is called.
channel_info = self.env['mail.channel'].channel_get(partners_to=self.partner_admin.ids)
self.assertEqual(channel_info['last_interest_dt'], retrieve_time.strftime(DEFAULT_SERVER_DATETIME_FORMAT))
@users('employee')
def test_channel_info_seen(self):
""" In case of concurrent channel_seen RPC, ensure the oldest call has no effect. """
channel = self.env['mail.channel'].browse(self.test_channel.id)
channel.write({'channel_type': 'chat'})
channel.add_members(self.env.user.partner_id.ids)
msg_1 = self._add_messages(self.test_channel, 'Body1', author=self.user_employee.partner_id)
msg_2 = self._add_messages(self.test_channel, 'Body2', author=self.user_employee.partner_id)
self.test_channel._channel_seen(msg_2.id)
self.assertEqual(
channel.channel_info()[0]['seen_partners_info'][0]['seen_message_id'],
msg_2.id,
"Last message id should have been updated"
)
self.test_channel._channel_seen(msg_1.id)
self.assertEqual(
channel.channel_info()[0]['seen_partners_info'][0]['seen_message_id'],
msg_2.id,
"Last message id should stay the same after mark channel as seen with an older message"
)
def test_channel_message_post_should_not_allow_adding_wrong_parent(self):
channels = self.env['mail.channel'].create([{'name': '1'}, {'name': '2'}])
message = self._add_messages(channels[0], 'Body1')
message_format2 = channels[1].message_post(body='Body2', parent_id=message.id)
self.assertFalse(message_format2['parent_id'], "should not allow parent from wrong thread")
message_format3 = channels[1].message_post(body='Body3', parent_id=message.id + 100)
self.assertFalse(message_format3['parent_id'], "should not allow non-existing parent")
@mute_logger('odoo.models.unlink')
def test_channel_unsubscribe_auto(self):
""" Archiving / deleting a user should automatically unsubscribe related
partner from private channels """
test_user = self.env['res.users'].create({
"login": "adam",
"name": "Jonas",
})
test_partner = test_user.partner_id
test_channel_private = self.env['mail.channel'].with_context(self._test_context).create({
'name': 'Winden caves',
'description': 'Channel to travel through time',
'public': 'private',
'channel_partner_ids': [Command.link(self.user_employee.partner_id.id), Command.link(test_partner.id)],
})
test_channel_group = self.env['mail.channel'].with_context(self._test_context).create({
'name': 'Sic Mundus',
'public': 'groups',
'group_public_id': self.env.ref('base.group_user').id,
'channel_partner_ids': [Command.link(self.user_employee.partner_id.id), Command.link(test_partner.id)],
})
self.test_channel.with_context(self._test_context).write({
'channel_partner_ids': [Command.link(self.user_employee.partner_id.id), Command.link(test_partner.id)],
})
test_chat = self.env['mail.channel'].with_user(self.user_employee).with_context(self._test_context).create({
'name': 'test',
'channel_type': 'chat',
'public': 'private',
'channel_partner_ids': [Command.link(self.user_employee.partner_id.id), Command.link(test_partner.id)],
})
# Unsubscribe archived user from the private channels, but not from public channels and not from chat
self.user_employee.active = False
(test_chat | self.test_channel).invalidate_cache(fnames=['channel_partner_ids'])
self.assertEqual(test_channel_private.channel_partner_ids, test_partner)
self.assertEqual(test_channel_group.channel_partner_ids, test_partner)
self.assertEqual(self.test_channel.channel_partner_ids, self.user_employee.partner_id | test_partner)
self.assertEqual(test_chat.channel_partner_ids, self.user_employee.partner_id | test_partner)
# Unsubscribe deleted user from the private channels, but not from public channels and not from chat
test_user.unlink()
self.assertEqual(test_channel_private.channel_partner_ids, self.env['res.partner'])
self.assertEqual(test_channel_group.channel_partner_ids, self.env['res.partner'])
self.assertEqual(self.test_channel.channel_partner_ids, self.user_employee.partner_id | test_partner)
self.assertEqual(test_chat.channel_partner_ids, self.user_employee.partner_id | test_partner)
@users('employee')
def test_channel_private_unfollow(self):
""" Test that a partner can leave (unfollow) a private channel. """
channel_private = self.env['mail.channel'].create({
'name': 'Winden caves',
'public': 'private',
})
channel_private.action_unfollow()
self.assertEqual(channel_private.channel_partner_ids, self.env['res.partner'])
def test_channel_unfollow_should_not_post_message_if_the_partner_has_been_removed(self):
'''
When a partner leaves a channel, the system will help post a message under
that partner's name in the channel to notify others if `email_sent` is set `False`.
The message should only be posted when the partner is still a member of the channel
before method `_action_unfollow()` is called.
If the partner has been removed earlier, no more messages will be posted
even if `_action_unfollow()` is called again.
'''
channel = self.env['mail.channel'].browse(self.test_channel.id)
channel.add_members(self.test_partner.ids)
# no message should be posted under test_partner's name
messages_0 = self.env['mail.message'].search([
('model', '=', 'mail.channel'),
('res_id', '=', channel.id),
('author_id', '=', self.test_partner.id)
])
self.assertEqual(len(messages_0), 0)
# a message should be posted to notify others when a partner is about to leave
channel._action_unfollow(self.test_partner)
messages_1 = self.env['mail.message'].search([
('model', '=', 'mail.channel'),
('res_id', '=', channel.id),
('author_id', '=', self.test_partner.id)
])
self.assertEqual(len(messages_1), 1)
# no more messages should be posted if the partner has been removed before.
channel._action_unfollow(self.test_partner)
messages_2 = self.env['mail.message'].search([
('model', '=', 'mail.channel'),
('res_id', '=', channel.id),
('author_id', '=', self.test_partner.id)
])
self.assertEqual(len(messages_2), 1)
self.assertEqual(messages_1, messages_2)
def test_channel_should_generate_correct_default_avatar(self):
channel = self.env['mail.channel'].create({'name': '', 'uuid': 'test-uuid'})
bgcolor = html_escape('hsl(288, 51%, 45%)') # depends on uuid
expceted_avatar_channel = (channel_avatar.replace('fill="#875a7b"', f'fill="{bgcolor}"')).encode()
expected_avatar_group = (group_avatar.replace('fill="#875a7b"', f'fill="{bgcolor}"')).encode()
channel.channel_type = 'group'
self.assertEqual(base64.b64decode(channel.avatar_128), expected_avatar_group)
channel.channel_type = 'channel'
self.assertEqual(base64.b64decode(channel.avatar_128), expceted_avatar_channel)
channel.image_128 = base64.b64encode(("<svg/>").encode())
self.assertEqual(channel.avatar_128, channel.image_128)
def test_channel_write_should_send_notification_if_image_128_changed(self):
channel = self.env['mail.channel'].create({'name': '', 'uuid': 'test-uuid'})
# do the operation once before the assert to grab the value to expect
channel.image_128 = base64.b64encode(("<svg/>").encode())
avatar_cache_key = channel._get_avatar_cache_key()
channel.image_128 = False
self.env['bus.bus'].search([]).unlink()
with self.assertBus(
[(self.cr.dbname, 'mail.channel', channel.id)],
[{
"type": "mail.channel/insert",
"payload": {
"id": channel.id,
"avatarCacheKey": avatar_cache_key,
},
}]
):
channel.image_128 = base64.b64encode(("<svg/>").encode())
def test_mail_message_starred_private_channel(self):
""" Test starred message computation for a private channel. A starred
message in a private channel should be considered only if:
- It's our message
- OR we have access to the channel
"""
self.assertEqual(self.user_employee._init_messaging()['starred_counter'], 0)
private_channel = self.env['mail.channel'].create({
'name': 'Private Channel',
'public': 'private',
'channel_partner_ids': [(6, 0, self.partner_employee.id)]
})
private_channel_own_message = private_channel.with_user(self.user_employee.id).message_post(body='TestingMessage')
private_channel_own_message.write({'starred_partner_ids': [(6, 0, self.partner_employee.ids)]})
self.assertEqual(self.user_employee.with_user(self.user_employee)._init_messaging()['starred_counter'], 1)
private_channel_message = private_channel.message_post(body='TestingMessage')
private_channel_message.write({'starred_partner_ids': [(6, 0, self.partner_employee.ids)]})
self.assertEqual(self.user_employee.with_user(self.user_employee)._init_messaging()['starred_counter'], 2)
private_channel.write({'channel_partner_ids': False})
self.assertEqual(self.user_employee.with_user(self.user_employee)._init_messaging()['starred_counter'], 1)
def test_multi_company_chat(self):
self._activate_multi_company()
self.assertEqual(self.env.user.company_id, self.company_admin)
with self.with_user('employee'):
initial_channel_info = self.env['mail.channel'].with_context(
allowed_company_ids=self.company_admin.ids
).channel_get(self.partner_employee_c2.ids)
self.assertTrue(initial_channel_info, 'should be able to chat with multi company user')
@users('employee')
def test_create_chat_channel_should_only_pin_the_channel_for_the_current_user(self):
chat = self.env['mail.channel'].channel_get(partners_to=self.test_partner.ids)
member_of_current_user = self.env['mail.channel.partner'].search([('channel_id', '=', chat['id']), ('partner_id', '=', self.env.user.partner_id.id)])
member_of_correspondent = self.env['mail.channel.partner'].search([('channel_id', '=', chat['id']), ('partner_id', '=', self.test_partner.id)])
self.assertTrue(member_of_current_user.is_pinned)
self.assertFalse(member_of_correspondent.is_pinned)
| 51.73271 | 27,677 |
7,738 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form, users
from odoo.exceptions import AccessError
from odoo.addons.mail.tests.common import MailCommon
class TestMailTemplate(MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailTemplate, cls).setUpClass()
# Enable the Jinja rendering restriction
cls.env['ir.config_parameter'].set_param('mail.restrict.template.rendering', True)
cls.user_employee.groups_id -= cls.env.ref('mail.group_mail_template_editor')
cls.mail_template = cls.env['mail.template'].create({
'name': 'Test template',
'subject': '{{ 1 + 5 }}',
'body_html': '<t t-out="4 + 9"/>',
'lang': '{{ object.lang }}',
'auto_delete': True,
'model_id': cls.env.ref('base.model_res_partner').id,
})
@users('employee')
def test_mail_compose_message_content_from_template(self):
form = Form(self.env['mail.compose.message'])
form.template_id = self.mail_template
mail_compose_message = form.save()
self.assertEqual(mail_compose_message.subject, '6', 'We must trust mail template values')
@users('employee')
def test_mail_compose_message_content_from_template_mass_mode(self):
mail_compose_message = self.env['mail.compose.message'].create({
'composition_mode': 'mass_mail',
'model': 'res.partner',
'template_id': self.mail_template.id,
'subject': '{{ 1 + 5 }}',
})
values = mail_compose_message.get_mail_values(self.partner_employee.ids)
self.assertEqual(values[self.partner_employee.id]['subject'], '6', 'We must trust mail template values')
self.assertIn('13', values[self.partner_employee.id]['body_html'], 'We must trust mail template values')
def test_mail_template_acl(self):
# Sanity check
self.assertTrue(self.user_admin.has_group('mail.group_mail_template_editor'))
self.assertFalse(self.user_employee.has_group('mail.group_mail_template_editor'))
# Group System can create / write / unlink mail template
mail_template = self.env['mail.template'].with_user(self.user_admin).create({'name': 'Test template'})
self.assertEqual(mail_template.name, 'Test template')
mail_template.with_user(self.user_admin).name = 'New name'
self.assertEqual(mail_template.name, 'New name')
# Standard employee can create and edit non-dynamic templates
employee_template = self.env['mail.template'].with_user(self.user_employee).create({'body_html': '<p>foo</p>'})
employee_template.with_user(self.user_employee).body_html = '<p>bar</p>'
employee_template = self.env['mail.template'].with_user(self.user_employee).create({'email_to': '[email protected]'})
employee_template.with_user(self.user_employee).email_to = '[email protected]'
# Standard employee cannot create and edit templates with dynamic qweb
with self.assertRaises(AccessError):
self.env['mail.template'].with_user(self.user_employee).create({'body_html': '<p t-esc="\'foo\'"></p>'})
# Standard employee cannot edit templates from another user, non-dynamic and dynamic
with self.assertRaises(AccessError):
mail_template.with_user(self.user_employee).body_html = '<p>foo</p>'
with self.assertRaises(AccessError):
mail_template.with_user(self.user_employee).body_html = '<p t-esc="\'foo\'"></p>'
# Standard employee can edit his own templates if not dynamic
employee_template.with_user(self.user_employee).body_html = '<p>foo</p>'
# Standard employee cannot create and edit templates with dynamic inline fields
with self.assertRaises(AccessError):
self.env['mail.template'].with_user(self.user_employee).create({'email_to': '{{ object.partner_id.email }}'})
# Standard employee cannot edit his own templates if dynamic
with self.assertRaises(AccessError):
employee_template.with_user(self.user_employee).body_html = '<p t-esc="\'foo\'"></p>'
with self.assertRaises(AccessError):
employee_template.with_user(self.user_employee).email_to = '{{ object.partner_id.email }}'
def test_mail_template_acl_translation(self):
''' Test that a user that doenn't have the group_mail_template_editor cannot create / edit
translation with dynamic code if he cannot write dynamic code on the related record itself.
'''
self.env.ref('base.lang_fr').sudo().active = True
employee_template = self.env['mail.template'].with_user(self.user_employee).create({
'model_id': self.env.ref('base.model_res_partner').id,
'subject': 'The subject',
'body_html': '<p>foo</p>',
})
Translation = self.env['ir.translation']
### check qweb dynamic
Translation.insert_missing(employee_template._fields['body_html'], employee_template)
employee_translations_of_body = Translation.with_user(self.user_employee).search(
[('res_id', '=', employee_template.id), ('name', '=', 'mail.template,body_html'), ('lang', '=', 'fr_FR')],
limit=1
)
# keep a copy to create new translation later
body_translation_vals = employee_translations_of_body.read([])[0]
# write on translation for template without dynamic code is allowed
employee_translations_of_body.value = 'non-qweb'
# cannot write dynamic code on mail_template translation for employee without the group mail_template_editor.
with self.assertRaises(AccessError):
employee_translations_of_body.value = '<t t-esc="foo"/>'
employee_translations_of_body.unlink() # delete old translation, to test the creation now
body_translation_vals['value'] = '<p t-esc="foo"/>'
# admin can create
new = Translation.create(body_translation_vals)
new.unlink()
# Employee without mail_template_editor group cannot create dynamic translation for mail.render.mixin
with self.assertRaises(AccessError):
Translation.with_user(self.user_employee).create(body_translation_vals)
### check qweb inline dynamic
Translation.insert_missing(employee_template._fields['subject'], employee_template)
employee_translations_of_subject = Translation.with_user(self.user_employee).search(
[('res_id', '=', employee_template.id), ('name', '=', 'mail.template,subject'), ('lang', '=', 'fr_FR')],
limit=1
)
# keep a copy to create new translation later
subject_translation_vals = employee_translations_of_subject.read([])[0]
# write on translation for template without dynamic code is allowed
employee_translations_of_subject.value = 'non-qweb'
# cannot write dynamic code on mail_template translation for employee without the group mail_template_editor.
with self.assertRaises(AccessError):
employee_translations_of_subject.value = '{{ object.foo }}'
employee_translations_of_subject.unlink() # delete old translation, to test the creation now
subject_translation_vals['value'] = '{{ object.foo }}'
# admin can create
new = Translation.create(subject_translation_vals)
new.unlink()
# Employee without mail_template_editor group cannot create dynamic translation for mail.render.mixin
with self.assertRaises(AccessError):
Translation.with_user(self.user_employee).create(subject_translation_vals)
| 48.062112 | 7,738 |
2,430 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import MailCommon
from odoo.tests.common import users
class TestResUsersSettings(MailCommon):
@users('employee')
def test_find_or_create_for_user_should_create_record_if_not_existing(self):
settings = self.user_employee.res_users_settings_ids
self.assertFalse(settings, "no records should exist")
self.env['res.users.settings']._find_or_create_for_user(self.user_employee)
settings = self.user_employee.res_users_settings_ids
self.assertTrue(settings, "a record should be created after _find_or_create_for_user is called")
@users('employee')
def test_find_or_create_for_user_should_return_correct_res_users_settings(self):
settings = self.env['res.users.settings'].create({
'user_id': self.user_employee.id,
})
result = self.env['res.users.settings']._find_or_create_for_user(self.user_employee)
self.assertEqual(result, settings, "Correct mail user settings should be returned")
@users('employee')
def test_set_res_users_settings_should_send_notification_on_bus(self):
settings = self.env['res.users.settings'].create({
'is_discuss_sidebar_category_channel_open': False,
'is_discuss_sidebar_category_chat_open': False,
'user_id': self.user_employee.id,
})
with self.assertBus(
[(self.cr.dbname, 'res.partner', self.partner_employee.id)],
[{
"type": "res.users.settings/changed",
"payload": {"is_discuss_sidebar_category_chat_open": True}
}]):
settings.set_res_users_settings({'is_discuss_sidebar_category_chat_open': True})
@users('employee')
def test_set_res_users_settings_should_set_settings_properly(self):
settings = self.env['res.users.settings'].create({
'is_discuss_sidebar_category_channel_open': False,
'is_discuss_sidebar_category_chat_open': False,
'user_id': self.user_employee.id,
})
settings.set_res_users_settings({'is_discuss_sidebar_category_chat_open': True})
self.assertEqual(
settings.is_discuss_sidebar_category_chat_open,
True,
"category state should be updated correctly"
)
| 44.181818 | 2,430 |
46,102 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import email
import email.policy
import time
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
from lxml import html
from unittest.mock import patch
from smtplib import SMTPServerDisconnected
from odoo import exceptions
from odoo.addons.base.models.ir_mail_server import IrMailServer, MailDeliveryException
from odoo.addons.bus.models.bus import ImBus, json_dump
from odoo.addons.mail.models.mail_mail import MailMail
from odoo.addons.mail.models.mail_message import Message
from odoo.addons.mail.models.mail_notification import MailNotification
from odoo.tests import common, new_test_user
from odoo.tools import formataddr, pycompat
mail_new_test_user = partial(new_test_user, context={'mail_create_nolog': True, 'mail_create_nosubscribe': True, 'mail_notrack': True, 'no_reset_password': True})
class MockEmail(common.BaseCase):
""" Tools, helpers and asserts for mailgateway-related tests
Useful reminders
Mail state: ('outgoing', 'Outgoing'), ('sent', 'Sent'),
('received', 'Received'), ('exception', 'Delivery Failed'),
('cancel', 'Cancelled')
"""
# ------------------------------------------------------------
# GATEWAY MOCK
# ------------------------------------------------------------
@contextmanager
def mock_mail_gateway(self, mail_unlink_sent=False, sim_error=None):
build_email_origin = IrMailServer.build_email
mail_create_origin = MailMail.create
mail_unlink_origin = MailMail.unlink
self.mail_unlink_sent = mail_unlink_sent
self._init_mail_mock()
def _ir_mail_server_connect(model, *args, **kwargs):
if sim_error and sim_error == 'connect_smtp_notfound':
raise exceptions.UserError(
"Missing SMTP Server\nPlease define at least one SMTP server, or provide the SMTP parameters explicitly.")
if sim_error and sim_error == 'connect_failure':
raise Exception("Some exception")
return None
def _ir_mail_server_build_email(model, *args, **kwargs):
self._mails.append(kwargs)
self._mails_args.append(args)
return build_email_origin(model, *args, **kwargs)
def _ir_mail_server_send_email(model, message, *args, **kwargs):
if '@' not in message['To']:
raise AssertionError(model.NO_VALID_RECIPIENT)
if sim_error and sim_error == 'send_assert':
raise AssertionError('AssertionError')
elif sim_error and sim_error == 'send_disconnect':
raise SMTPServerDisconnected('SMTPServerDisconnected')
elif sim_error and sim_error == 'send_delivery':
raise MailDeliveryException('MailDeliveryException')
return message['Message-Id']
def _mail_mail_create(model, *args, **kwargs):
res = mail_create_origin(model, *args, **kwargs)
self._new_mails += res.sudo()
return res
def _mail_mail_unlink(model, *args, **kwargs):
if self.mail_unlink_sent:
return mail_unlink_origin(model, *args, **kwargs)
return True
with patch.object(IrMailServer, 'connect', autospec=True, wraps=IrMailServer, side_effect=_ir_mail_server_connect) as ir_mail_server_connect_mock, \
patch.object(IrMailServer, 'build_email', autospec=True, wraps=IrMailServer, side_effect=_ir_mail_server_build_email) as ir_mail_server_build_email_mock, \
patch.object(IrMailServer, 'send_email', autospec=True, wraps=IrMailServer, side_effect=_ir_mail_server_send_email) as ir_mail_server_send_email_mock, \
patch.object(MailMail, 'create', autospec=True, wraps=MailMail, side_effect=_mail_mail_create) as _mail_mail_create_mock, \
patch.object(MailMail, 'unlink', autospec=True, wraps=MailMail, side_effect=_mail_mail_unlink) as mail_mail_unlink_mock:
yield
def _init_mail_mock(self):
self._mails = []
self._mails_args = []
self._new_mails = self.env['mail.mail'].sudo()
# ------------------------------------------------------------
# GATEWAY TOOLS
# ------------------------------------------------------------
@classmethod
def _init_mail_gateway(cls):
cls.alias_domain = 'test.com'
cls.alias_catchall = 'catchall.test'
cls.alias_bounce = 'bounce.test'
cls.default_from = 'notifications'
cls.env['ir.config_parameter'].set_param('mail.bounce.alias', cls.alias_bounce)
cls.env['ir.config_parameter'].set_param('mail.catchall.domain', cls.alias_domain)
cls.env['ir.config_parameter'].set_param('mail.catchall.alias', cls.alias_catchall)
cls.env['ir.config_parameter'].set_param('mail.default.from', cls.default_from)
cls.mailer_daemon_email = formataddr(('MAILER-DAEMON', '%s@%s' % (cls.alias_bounce, cls.alias_domain)))
def format(self, template, to='[email protected], [email protected]', subject='Frogs',
email_from='Sylvie Lelitre <[email protected]>', return_path='', cc='',
extra='', msg_id='<[email protected]>',
**kwargs):
return template.format(
subject=subject, to=to, cc=cc,
email_from=email_from, return_path=return_path,
extra=extra, msg_id=msg_id,
**kwargs)
def format_and_process(self, template, email_from, to, subject='Frogs', cc='',
return_path='', extra='', msg_id=False,
model=None, target_model='mail.test.gateway', target_field='name',
**kwargs):
self.assertFalse(self.env[target_model].search([(target_field, '=', subject)]))
if not msg_id:
msg_id = "<%[email protected]>" % (time.time())
mail = self.format(template, to=to, subject=subject, cc=cc,
return_path=return_path, extra=extra,
email_from=email_from, msg_id=msg_id,
**kwargs)
self.env['mail.thread'].message_process(model, mail)
return self.env[target_model].search([(target_field, '=', subject)])
def gateway_reply_wrecord(self, template, record, use_in_reply_to=True):
""" Deprecated, remove in 14.4 """
return self.gateway_mail_reply_wrecord(template, record, use_in_reply_to=use_in_reply_to)
def gateway_mail_reply_wrecord(self, template, record, use_in_reply_to=True,
target_model=None, target_field=None):
""" Simulate a reply through the mail gateway. Usage: giving a record,
find an email sent to him and use its message-ID to simulate a reply.
Some noise is added in References just to test some robustness. """
mail_mail = self._find_mail_mail_wrecord(record)
if use_in_reply_to:
extra = 'In-Reply-To:\r\n\t%s\n' % mail_mail.message_id
else:
disturbing_other_msg_id = '<[email protected]>'
extra = 'References:\r\n\t%s\n\r%s' % (mail_mail.message_id, disturbing_other_msg_id)
return self.format_and_process(
template,
mail_mail.email_to,
mail_mail.reply_to,
subject='Re: %s' % mail_mail.subject,
extra=extra,
msg_id='<123456.%s.%[email protected]>' % (record._name, record.id),
target_model=target_model or record._name,
target_field=target_field or record._rec_name,
)
def gateway_mail_reply_wemail(self, template, email_to, use_in_reply_to=True,
target_model=None, target_field=None):
""" Simulate a reply through the mail gateway. Usage: giving a record,
find an email sent to him and use its message-ID to simulate a reply.
Some noise is added in References just to test some robustness. """
sent_mail = self._find_sent_mail_wemail(email_to)
if use_in_reply_to:
extra = 'In-Reply-To:\r\n\t%s\n' % sent_mail['message_id']
else:
disturbing_other_msg_id = '<[email protected]>'
extra = 'References:\r\n\t%s\n\r%s' % (sent_mail['message_id'], disturbing_other_msg_id)
return self.format_and_process(
template,
sent_mail['email_to'],
sent_mail['reply_to'],
subject='Re: %s' % sent_mail['subject'],
extra=extra,
target_model=target_model,
target_field=target_field or 'name',
)
def from_string(self, text):
return email.message_from_string(pycompat.to_text(text), policy=email.policy.SMTP)
def assertHtmlEqual(self, value, expected, message=None):
tree = html.fragment_fromstring(value, parser=html.HTMLParser(encoding='utf-8'), create_parent='body')
# mass mailing: add base tag we have to remove
for base_node in tree.xpath('//base'):
base_node.getparent().remove(base_node)
# chatter: read more / read less TODO
# mass mailing: add base tag we have to remove
expected_node = html.fragment_fromstring(expected, create_parent='body')
if message:
self.assertEqual(tree, expected_node, message)
else:
self.assertEqual(tree, expected_node)
# ------------------------------------------------------------
# GATEWAY GETTERS
# ------------------------------------------------------------
def _find_sent_mail_wemail(self, email_to):
""" Find a sent email with a given list of recipients. Email should match
exactly the recipients.
:param email-to: a list of emails that will be compared to email_to
of sent emails (also a list of emails);
:return email: an email which is a dictionary mapping values given to
``build_email``;
"""
for sent_email in self._mails:
if set(sent_email['email_to']) == set([email_to]):
break
else:
raise AssertionError('sent mail not found for email_to %s' % (email_to))
return sent_email
def _filter_mail(self, status=None, mail_message=None, author=None):
""" Filter mail generated during mock, based on common parameters
:param status: state of mail.mail. If not void use it to filter mail.mail
record;
:param mail_message: optional check/filter on mail_message_id field aka
a ``mail.message`` record;
:param author: optional check/filter on author_id field aka a ``res.partner``
record;
"""
filtered = self._new_mails.env['mail.mail']
for mail in self._new_mails:
if status is not None and mail.state != status:
continue
if mail_message is not None and mail.mail_message_id != mail_message:
continue
if author is not None and mail.author_id != author:
continue
filtered += mail
return filtered
def _find_mail_mail_wid(self, mail_id, status=None, mail_message=None, author=None):
""" Find a ``mail.mail`` record based on a given ID (used notably when having
mail ID in mailing traces).
:return mail: a ``mail.mail`` record generated during the mock and matching
given ID;
"""
filtered = self._filter_mail(status=status, mail_message=mail_message, author=author)
for mail in filtered:
if mail.id == mail_id:
break
else:
raise AssertionError('mail.mail not found for ID %s' % (mail_id))
return mail
def _find_mail_mail_wpartners(self, recipients, status, mail_message=None, author=None):
""" Find a mail.mail record based on various parameters, notably a list
of recipients (partners).
:param recipients: a ``res.partner`` recordset Check all of them are in mail
recipients to find the right mail.mail record;
:return mail: a ``mail.mail`` record generated during the mock and matching
given parameters and filters;
"""
filtered = self._filter_mail(status=status, mail_message=mail_message, author=author)
for mail in filtered:
if all(p in mail.recipient_ids for p in recipients):
break
else:
raise AssertionError('mail.mail not found for message %s / status %s / recipients %s / author %s' % (mail_message, status, recipients.ids, author))
return mail
def _find_mail_mail_wemail(self, email_to, status, mail_message=None, author=None):
""" Find a mail.mail record based on various parameters, notably a list
of email to (string emails).
:param email_to: either matching mail.email_to value, either a mail sent
to a single recipient whose email is email_to;
:return mail: a ``mail.mail`` record generated during the mock and matching
given parameters and filters;
"""
filtered = self._filter_mail(status=status, mail_message=mail_message, author=author)
for mail in filtered:
if (mail.email_to == email_to and not mail.recipient_ids) or (not mail.email_to and mail.recipient_ids.email == email_to):
break
else:
raise AssertionError('mail.mail not found for email_to %s / status %s in %s' % (email_to, status, repr([m.email_to for m in self._new_mails])))
return mail
def _find_mail_mail_wrecord(self, record, status=None, mail_message=None, author=None):
""" Find a mail.mail record based on model / res_id of a record.
:return mail: a ``mail.mail`` record generated during the mock;
"""
filtered = self._filter_mail(status=status, mail_message=mail_message, author=author)
for mail in filtered:
if mail.model == record._name and mail.res_id == record.id:
break
else:
raise AssertionError('mail.mail not found for record %s in %s' % (record, repr([m.email_to for m in self._new_mails])))
return mail
# ------------------------------------------------------------
# GATEWAY ASSERTS
# ------------------------------------------------------------
def assertMailMail(self, recipients, status,
check_mail_mail=True, mail_message=None, author=None,
content=None, fields_values=None, email_values=None):
""" Assert mail.mail records are created and maybe sent as emails. Allow
asserting their content. Records to check are the one generated when
using mock (mail.mail and outgoing emails). This method takes partners
as source of record fetch and assert.
:param recipients: a ``res.partner`` recordset. See ``_find_mail_mail_wpartners``;
:param status: mail.mail state used to filter mails. If ``sent`` this method
also check that emails have been sent trough gateway;
:param mail_message: see ``_find_mail_mail_wpartners``;
:param author: see ``_find_mail_mail_wpartners``;
:param content: if given, check it is contained within mail html body;
:param fields_values: if given, should be a dictionary of field names /
values allowing to check ``mail.mail`` additional values (subject,
reply_to, ...);
:param email_values: if given, should be a dictionary of keys / values
allowing to check sent email additional values (if any).
See ``assertSentEmail``;
:param check_mail_mail: deprecated, use ``assertSentEmail`` if False
"""
found_mail = self._find_mail_mail_wpartners(recipients, status, mail_message=mail_message, author=author)
self.assertTrue(bool(found_mail))
if content:
self.assertIn(content, found_mail.body_html)
for fname, fvalue in (fields_values or {}).items():
self.assertEqual(
found_mail[fname], fvalue,
'Mail: expected %s for %s, got %s' % (fvalue, fname, found_mail[fname]))
if status == 'sent':
for recipient in recipients:
self.assertSentEmail(email_values['email_from'] if email_values and email_values.get('email_from') else author, [recipient], **(email_values or {}))
def assertMailMailWEmails(self, emails, status,
mail_message=None, author=None,
content=None, fields_values=None, email_values=None):
""" Assert mail.mail records are created and maybe sent as emails. Allow
asserting their content. Records to check are the one generated when
using mock (mail.mail and outgoing emails). This method takes emails
as source of record fetch and assert.
:param emails: a list of emails. See ``_find_mail_mail_wemail``;
:param status: mail.mail state used to filter mails. If ``sent`` this method
also check that emails have been sent trough gateway;
:param mail_message: see ``_find_mail_mail_wemail``;
:param author: see ``_find_mail_mail_wemail``;;
:param content: if given, check it is contained within mail html body;
:param fields_values: if given, should be a dictionary of field names /
values allowing to check ``mail.mail`` additional values (subject,
reply_to, ...);
:param email_values: if given, should be a dictionary of keys / values
allowing to check sent email additional values (if any).
See ``assertSentEmail``;
:param check_mail_mail: deprecated, use ``assertSentEmail`` if False
"""
for email_to in emails:
found_mail = self._find_mail_mail_wemail(email_to, status, mail_message=mail_message, author=author)
if content:
self.assertIn(content, found_mail.body_html)
for fname, fvalue in (fields_values or {}).items():
self.assertEqual(
found_mail[fname], fvalue,
'Mail: expected %s for %s, got %s' % (fvalue, fname, found_mail[fname]))
if status == 'sent':
for email_to in emails:
self.assertSentEmail(email_values['email_from'] if email_values and email_values.get('email_from') else author, [email_to], **(email_values or {}))
def assertMailMailWId(self, mail_id, status,
content=None, fields_values=None):
""" Assert mail.mail records are created and maybe sent as emails. Allow
asserting their content. Records to check are the one generated when
using mock (mail.mail and outgoing emails). This method takes partners
as source of record fetch and assert.
:param mail_id: a ``mail.mail`` DB ID. See ``_find_mail_mail_wid``;
:param status: mail.mail state to check upon found mail;
:param content: if given, check it is contained within mail html body;
:param fields_values: if given, should be a dictionary of field names /
values allowing to check ``mail.mail`` additional values (subject,
reply_to, ...);
"""
found_mail = self._find_mail_mail_wid(mail_id)
self.assertTrue(bool(found_mail))
if status:
self.assertEqual(found_mail.state, status)
if content:
self.assertIn(content, found_mail.body_html)
for fname, fvalue in (fields_values or {}).items():
self.assertEqual(
found_mail[fname], fvalue,
'Mail: expected %s for %s, got %s' % (fvalue, fname, found_mail[fname]))
def assertNoMail(self, recipients, mail_message=None, author=None):
""" Check no mail.mail and email was generated during gateway mock. """
try:
self._find_mail_mail_wpartners(recipients, False, mail_message=mail_message, author=author)
except AssertionError:
pass
else:
raise AssertionError('mail.mail exists for message %s / recipients %s but should not exist' % (mail_message, recipients.ids))
finally:
self.assertNotSentEmail(recipients)
def assertNotSentEmail(self, recipients=None):
"""Check no email was generated during gateway mock.
:param recipients:
List of partner for which we will check that no email have been sent
Or list of email address
If None, we will check that no email at all have been sent
"""
if recipients is None:
mails = self._mails
else:
all_emails = [
email_to.email if isinstance(email_to, self.env['res.partner'].__class__)
else email_to
for email_to in recipients
]
mails = [
mail
for mail in self._mails
if any(email in all_emails for email in mail['email_to'])
]
self.assertEqual(len(mails), 0)
def assertSentEmail(self, author, recipients, **values):
""" Tool method to ease the check of send emails.
:param author: email author, either a string (email), either a partner
record;
:param recipients: list of recipients, each being either a string (email),
either a partner record;
:param values: dictionary of additional values to check email content;
"""
direct_check = ['attachments', 'body_alternative', 'email_from', 'references', 'reply_to', 'subject']
content_check = ['body_alternative_content', 'body_content', 'references_content']
other_check = ['body', 'attachments_info']
expected = {}
for fname in direct_check + content_check + other_check:
if fname in values:
expected[fname] = values[fname]
unknown = set(values.keys()) - set(direct_check + content_check + other_check)
if unknown:
raise NotImplementedError('Unsupported %s' % ', '.join(unknown))
if isinstance(author, self.env['res.partner'].__class__):
expected['email_from'] = formataddr((author.name, author.email))
else:
expected['email_from'] = author
email_to_list = []
for email_to in recipients:
if isinstance(email_to, self.env['res.partner'].__class__):
email_to_list.append(formataddr((email_to.name, email_to.email)))
else:
email_to_list.append(email_to)
expected['email_to'] = email_to_list
sent_mail = next(
(mail for mail in self._mails
if set(mail['email_to']) == set(expected['email_to']) and mail['email_from'] == expected['email_from']
), False)
debug_info = '-'.join('From: %s-To: %s' % (mail['email_from'], mail['email_to']) for mail in self._mails) if not bool(sent_mail) else ''
self.assertTrue(bool(sent_mail), 'Expected mail from %s to %s not found in %s' % (expected['email_from'], expected['email_to'], debug_info))
for val in direct_check:
if val in expected:
self.assertEqual(expected[val], sent_mail[val], 'Value for %s: expected %s, received %s' % (val, expected[val], sent_mail[val]))
if 'attachments_info' in expected:
attachments = sent_mail['attachments']
for attachment_info in expected['attachments_info']:
attachment = next(attach for attach in attachments if attach[0] == attachment_info['name'])
if attachment_info.get('raw'):
self.assertEqual(attachment[1], attachment_info['raw'])
if attachment_info.get('type'):
self.assertEqual(attachment[2], attachment_info['type'])
self.assertEqual(len(expected['attachments_info']), len(attachments))
if 'body' in expected:
self.assertHtmlEqual(expected['body'], sent_mail['body'], 'Value for %s: expected %s, received %s' % ('body', expected['body'], sent_mail['body']))
for val in content_check:
if val in expected:
self.assertIn(expected[val], sent_mail[val[:-8]], 'Value for %s: %s does not contain %s' % (val, sent_mail[val[:-8]], expected[val]))
class MailCase(MockEmail):
""" Tools, helpers and asserts for mail-related tests, including mail
gateway mock and helpers (see ´´MockEmail´´).
Useful reminders
Notif type: ('inbox', 'Inbox'), ('email', 'Email')
Notif status: ('ready', 'Ready to Send'), ('sent', 'Sent'),
('bounce', 'Bounced'), ('exception', 'Exception'),
('canceled', 'Canceled')
Notif failure type: ("SMTP", "Connection failed (outgoing mail server problem)"),
("RECIPIENT", "Invalid email address"),
("BOUNCE", "Email address rejected by destination"),
("UNKNOWN", "Unknown error")
"""
_test_context = {
'mail_create_nolog': True,
'mail_create_nosubscribe': True,
'mail_notrack': True,
'no_reset_password': True
}
@classmethod
def _reset_mail_context(cls, record):
return record.with_context(
mail_create_nolog=False,
mail_create_nosubscribe=False,
mail_notrack=False
)
def flush_tracking(self):
""" Force the creation of tracking values. """
self.env['base'].flush()
self.cr.flush()
# ------------------------------------------------------------
# MAIL MOCKS
# ------------------------------------------------------------
@contextmanager
def mock_bus(self):
bus_bus_create_origin = ImBus.create
self._init_mock_bus()
def _bus_bus_create(model, *args, **kwargs):
res = bus_bus_create_origin(model, *args, **kwargs)
self._new_bus_notifs += res.sudo()
return res
with patch.object(ImBus, 'create', autospec=True, wraps=ImBus, side_effect=_bus_bus_create) as _bus_bus_create_mock:
yield
def _init_mock_bus(self):
self._new_bus_notifs = self.env['bus.bus'].sudo()
def _reset_bus(self):
self.env['bus.bus'].sudo().search([]).unlink()
@contextmanager
def mock_mail_app(self):
message_create_origin = Message.create
notification_create_origin = MailNotification.create
self._init_mock_mail()
def _mail_message_create(model, *args, **kwargs):
res = message_create_origin(model, *args, **kwargs)
self._new_msgs += res.sudo()
return res
def _mail_notification_create(model, *args, **kwargs):
res = notification_create_origin(model, *args, **kwargs)
self._new_notifs += res.sudo()
return res
with patch.object(Message, 'create', autospec=True, wraps=Message, side_effect=_mail_message_create) as _mail_message_create_mock, \
patch.object(MailNotification, 'create', autospec=True, wraps=MailNotification, side_effect=_mail_notification_create) as _mail_notification_create_mock:
yield
def _init_mock_mail(self):
self._new_msgs = self.env['mail.message'].sudo()
self._new_notifs = self.env['mail.notification'].sudo()
# ------------------------------------------------------------
# MAIL TOOLS
# ------------------------------------------------------------
@classmethod
def _add_messages(cls, record, body_content, count=1, author=None, **kwargs):
""" Helper: add #count messages in record history """
author = author if author else cls.env.user.partner_id
if 'email_from' not in kwargs:
kwargs['email_from'] = author.email_formatted
subtype_id = kwargs.get('subtype_id', cls.env.ref('mail.mt_comment').id)
values = {
'model': record._name,
'res_id': record.id,
'author_id': author.id,
'subtype_id': subtype_id,
}
values.update(kwargs)
create_vals = [dict(
values, body='%s/%02d' % (body_content, counter))
for counter in range(count)]
return cls.env['mail.message'].sudo().create(create_vals)
@classmethod
def _create_template(cls, model, template_values=None):
create_values = {
'name': 'TestTemplate',
'subject': 'About {{ object.name }}',
'body_html': '<p>Hello <t t-out="object.name"/></p>',
'model_id': cls.env['ir.model']._get(model).id,
}
if template_values:
create_values.update(template_values)
cls.email_template = cls.env['mail.template'].create(create_values)
return cls.email_template
def _generate_notify_recipients(self, partners):
""" Tool method to generate recipients data according to structure used
in notification methods. Purpose is to allow testing of internals of
some notification methods, notably testing links or group-based notification
details.
See notably ``MailThread._notify_compute_recipients()``.
"""
return [
{'id': partner.id,
'active': True,
'share': partner.partner_share,
'groups': partner.user_ids.groups_id.ids,
'notif': partner.user_ids.notification_type or 'email',
'type': 'user' if partner.user_ids and not partner.partner_share else partner.user_ids and 'portal' or 'customer',
} for partner in partners
]
# ------------------------------------------------------------
# MAIL ASSERTS WRAPPERS
# ------------------------------------------------------------
@contextmanager
def assertSinglePostNotifications(self, recipients_info, message_info=None, mail_unlink_sent=False, sim_error=None):
""" Shortcut to assertMsgNotifications when having a single message to check. """
r_info = dict(message_info if message_info else {})
r_info.setdefault('content', '')
r_info['notif'] = recipients_info
with self.assertPostNotifications([r_info], mail_unlink_sent=mail_unlink_sent, sim_error=sim_error):
yield
@contextmanager
def assertPostNotifications(self, recipients_info, mail_unlink_sent=False, sim_error=None):
""" Check content of notifications. """
try:
with self.mock_mail_gateway(mail_unlink_sent=mail_unlink_sent, sim_error=sim_error), self.mock_bus(), self.mock_mail_app():
yield
finally:
done_msgs, done_notifs = self.assertMailNotifications(self._new_msgs, recipients_info)
self.assertEqual(self._new_msgs, done_msgs, 'Mail: invalid message creation (%s) / expected (%s)' % (len(self._new_msgs), len(done_msgs)))
self.assertEqual(self._new_notifs, done_notifs, 'Mail: invalid notification creation (%s) / expected (%s)' % (len(self._new_notifs), len(done_notifs)))
@contextmanager
def assertBus(self, channels, message_items=None):
""" Check content of bus notifications. """
try:
with self.mock_bus():
yield
finally:
found_bus_notifs = self.assertBusNotifications(channels, message_items=message_items)
self.assertEqual(self._new_bus_notifs, found_bus_notifs)
@contextmanager
def assertNoNotifications(self):
try:
with self.mock_mail_gateway(mail_unlink_sent=False, sim_error=None), self.mock_bus(), self.mock_mail_app():
yield
finally:
self.assertFalse(bool(self._new_msgs))
self.assertFalse(bool(self._new_notifs))
# ------------------------------------------------------------
# MAIL MODELS ASSERTS
# ------------------------------------------------------------
def assertMailNotifications(self, messages, recipients_info):
""" Check bus notifications content. Mandatory and basic check is about
channels being notified. Content check is optional.
GNERATED INPUT
:param messages: generated messages to check;
EXPECTED
:param recipients_info: list of data dict: [
{'content': message content,
'message_type': message_type (default: 'comment'),
'subtype': xml id of message subtype (default: 'mail.mt_comment'),
'notif': list of notified recipients: [
{'partner': res.partner record (may be empty),
'email': NOT SUPPORTED YET,
'status': notification_status to check,
'type': notification_type to check,
'is_read': is_read to check,
'check_send': whether outgoing stuff has to be checked;
'failure_type': optional: one of failure_type key
}, { ... }]
}, {...}]
PARAMETERS
:param unlink_sent: to know whether to compute
"""
partners = self.env['res.partner'].sudo().concat(*list(p['partner'] for i in recipients_info for p in i['notif'] if p.get('partner')))
base_domain = [('res_partner_id', 'in', partners.ids)]
if messages is not None:
base_domain += [('mail_message_id', 'in', messages.ids)]
notifications = self.env['mail.notification'].sudo().search(base_domain)
done_msgs = self.env['mail.message'].sudo()
done_notifs = self.env['mail.notification'].sudo()
for message_info in recipients_info:
mbody, mtype = message_info.get('content', ''), message_info.get('message_type', 'comment')
msubtype = self.env.ref(message_info.get('subtype', 'mail.mt_comment'))
# find message
if messages:
message = messages.filtered(lambda message: mbody in message.body and message.message_type == mtype and message.subtype_id == msubtype)
else:
message = self.env['mail.message'].sudo().search([('body', 'ilike', mbody), ('message_type', '=', mtype), ('subtype_id', '=', msubtype.id)], limit=1, order='id DESC')
self.assertTrue(message, 'Mail: not found message (content: %s, message_type: %s, subtype: %s)' % (mbody, mtype, msubtype.name))
# check notifications and prepare assert data
email_groups = defaultdict(list)
mail_groups = {'failure': [], 'outgoing': []}
for recipient in message_info['notif']:
partner, ntype, ngroup, nstatus = recipient['partner'], recipient['type'], recipient.get('group'), recipient.get('status', 'sent')
nis_read, ncheck_send = recipient.get('is_read', False if recipient['type'] == 'inbox' else True), recipient.get('check_send', True)
if not ngroup:
ngroup = 'user'
if partner and not partner.user_ids:
ngroup = 'customer'
elif partner and partner.partner_share:
ngroup = 'portal'
# find notification
partner_notif = notifications.filtered(
lambda n: n.mail_message_id == message and
n.res_partner_id == partner and
n.notification_type == ntype and
n.notification_status == nstatus and
n.is_read == nis_read
)
self.assertTrue(partner_notif, 'Mail: not found notification for %s (type: %s, state: %s, message: %s)' % (partner, ntype, nstatus, message.id))
# prepare further asserts
if ntype == 'email':
if nstatus == 'sent':
if ncheck_send:
email_groups[ngroup].append(partner)
# when force_send is False notably, notifications are ready and emails outgoing
elif nstatus == 'ready':
mail_groups['outgoing'].append(partner)
if ncheck_send:
email_groups[ngroup].append(partner)
# canceled: currently nothing checked
elif nstatus == 'exception':
mail_groups['failure'].append(partner)
if ncheck_send:
email_groups[ngroup].append(partner)
elif nstatus == 'canceled':
pass
else:
raise NotImplementedError()
done_notifs |= partner_notif
done_msgs |= message
# check bus notifications that should be sent (hint: message author, multiple notifications)
bus_notifications = message.notification_ids._filtered_for_web_client().filtered(lambda n: n.notification_status == 'exception')
if bus_notifications:
self.assertMessageBusNotifications(message)
# check emails that should be sent (hint: mail.mail per group, email par recipient)
email_values = {'body_content': mbody,
'references_content': message.message_id}
if message_info.get('email_values'):
email_values.update(message_info['email_values'])
for recipients in email_groups.values():
partners = self.env['res.partner'].sudo().concat(*recipients)
if all(p in mail_groups['failure'] for p in partners):
mail_status = 'exception'
elif all(p in mail_groups['outgoing'] for p in partners):
mail_status = 'outgoing'
else:
mail_status = 'sent'
if not self.mail_unlink_sent:
self.assertMailMail(
partners, mail_status,
author=message.author_id if message.author_id else message.email_from,
mail_message=message,
email_values=email_values,
)
else:
for recipient in partners:
self.assertSentEmail(
message.author_id if message.author_id else message.email_from,
[recipient],
**email_values
)
if not any(p for recipients in email_groups.values() for p in recipients):
self.assertNoMail(partners, mail_message=message, author=message.author_id)
return done_msgs, done_notifs
def assertMessageBusNotifications(self, message):
"""Asserts that the expected notification updates have been sent on the
bus for the given message."""
self.assertBusNotifications([(self.cr.dbname, 'res.partner', message.author_id.id)], [{
'type': 'mail.message/notification_update',
'payload': {
'elements': message._message_notification_format(),
},
}], check_unique=False)
def assertBusNotifications(self, channels, message_items=None, check_unique=True):
""" Check bus notifications content. Mandatory and basic check is about
channels being notified. Content check is optional.
EXPECTED
:param channels: list of expected bus channels, like [
(self.cr.dbname, 'mail.channel', self.channel_1.id),
(self.cr.dbname, 'res.partner', self.partner_employee_2.id)
]
:param message_items: if given, list of expected message making a valid
pair (channel, message) to be found in bus.bus, like [
{'type': 'mail.message/notification_update',
'elements': {self.msg.id: {
'message_id': self.msg.id,
'message_type': 'sms',
'notifications': {...},
...
}}
}, {...}]
"""
bus_notifs = self.env['bus.bus'].sudo().search([('channel', 'in', [json_dump(channel) for channel in channels])])
if check_unique:
self.assertEqual(len(bus_notifs), len(channels))
self.assertEqual(set(bus_notifs.mapped('channel')), set([json_dump(channel) for channel in channels]))
notif_messages = [n.message for n in bus_notifs]
for expected in message_items or []:
for notification in notif_messages:
if json_dump(expected) == notification:
break
else:
raise AssertionError('No notification was found with the expected value.\nExpected:\n%s\nReturned:\n%s' %
(json_dump(expected), '\n'.join([n for n in notif_messages])))
return bus_notifs
def assertNotified(self, message, recipients_info, is_complete=False):
""" Lightweight check for notifications (mail.notification).
:param recipients_info: list notified recipients: [
{'partner': res.partner record (may be empty),
'type': notification_type to check,
'is_read': is_read to check,
}, {...}]
"""
notifications = self._new_notifs.filtered(lambda notif: notif in message.notification_ids)
if is_complete:
self.assertEqual(len(notifications), len(recipients_info))
for rinfo in recipients_info:
recipient_notif = next(
(notif
for notif in notifications
if notif.res_partner_id == rinfo['partner']
), False
)
self.assertTrue(recipient_notif)
self.assertEqual(recipient_notif.is_read, rinfo['is_read'])
self.assertEqual(recipient_notif.notification_type, rinfo['type'])
def assertTracking(self, message, data):
tracking_values = message.sudo().tracking_value_ids
for field_name, value_type, old_value, new_value in data:
tracking = tracking_values.filtered(lambda track: track.field.name == field_name)
self.assertEqual(len(tracking), 1)
if value_type in ('char', 'integer'):
self.assertEqual(tracking.old_value_char, old_value)
self.assertEqual(tracking.new_value_char, new_value)
elif value_type in ('many2one'):
self.assertEqual(tracking.old_value_integer, old_value and old_value.id or False)
self.assertEqual(tracking.new_value_integer, new_value and new_value.id or False)
self.assertEqual(tracking.old_value_char, old_value and old_value.display_name or '')
self.assertEqual(tracking.new_value_char, new_value and new_value.display_name or '')
elif value_type in ('monetary'):
self.assertEqual(tracking.old_value_monetary, old_value)
self.assertEqual(tracking.new_value_monetary, new_value)
else:
self.assertEqual(1, 0)
class MailCommon(common.TransactionCase, MailCase):
""" Almost-void class definition setting the savepoint case + mock of mail.
Used mainly for class inheritance in other applications and test modules. """
@classmethod
def setUpClass(cls):
super(MailCommon, cls).setUpClass()
# give default values for all email aliases and domain
cls._init_mail_gateway()
# ensure admin configuration
cls.user_admin = cls.env.ref('base.user_admin')
cls.user_admin.write({'notification_type': 'inbox'})
cls.partner_admin = cls.env.ref('base.partner_admin')
cls.company_admin = cls.user_admin.company_id
cls.company_admin.write({'email': '[email protected]'})
# have root available at hand, just in case
cls.user_root = cls.env.ref('base.user_root')
cls.partner_root = cls.user_root.partner_id
cls.env['ir.config_parameter'].set_param('mail.restrict.template.rendering', False)
# test standard employee
cls.user_employee = mail_new_test_user(
cls.env, login='employee',
groups='base.group_user,mail.group_mail_template_editor',
company_id=cls.company_admin.id,
name='Ernest Employee',
notification_type='inbox',
signature='--\nErnest'
)
cls.partner_employee = cls.user_employee.partner_id
@classmethod
def _create_portal_user(cls):
cls.user_portal = mail_new_test_user(
cls.env, login='portal_test', groups='base.group_portal', company_id=cls.company_admin.id,
name='Chell Gladys', notification_type='email')
cls.partner_portal = cls.user_portal.partner_id
return cls.user_portal
@classmethod
def _activate_multi_company(cls):
""" Create another company, add it to admin and create an user that
belongs to that new company. It allows to test flows with users from
different companies. """
cls.company_2 = cls.env['res.company'].create({
'name': 'Company 2',
'email': '[email protected]',
})
cls.user_admin.write({'company_ids': [(4, cls.company_2.id)]})
cls.user_employee_c2 = mail_new_test_user(
cls.env, login='employee_c2',
groups='base.group_user',
company_id=cls.company_2.id,
company_ids=[(4, cls.company_2.id)],
name='Enguerrand Employee C2',
notification_type='inbox',
signature='--\nEnguerrand'
)
cls.partner_employee_c2 = cls.user_employee_c2.partner_id
| 47.28 | 46,098 |
8,972 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from uuid import uuid4
from odoo.addons.mail.tests.common import MailCommon, mail_new_test_user
from odoo.tests.common import Form, users
# samples use effective TLDs from the Mozilla public suffix
# list at http://publicsuffix.org
SAMPLES = [
('"Raoul Grosbedon" <[email protected]> ', 'Raoul Grosbedon', '[email protected]'),
('[email protected]', '', '[email protected]'),
('Raoul chirurgiens-dentistes.fr', 'Raoul chirurgiens-dentistes.fr', ''),
(" Raoul O'hara <[email protected]>", "Raoul O'hara", '[email protected]'),
('Raoul Grosbedon <[email protected]> ', 'Raoul Grosbedon', '[email protected]'),
('Raoul [email protected]', 'Raoul', '[email protected]'),
('"Patrick Da Beast Poilvache" <[email protected]>', 'Patrick Poilvache', '[email protected]'),
('Patrick Caché <[email protected]>', 'Patrick Poilvache', '[email protected]'),
('Patrick Caché <[email protected]>', 'Patrick Caché', '[email protected]'),
]
class TestPartner(MailCommon):
def _check_find_or_create(self, test_string, expected_name, expected_email, expected_email_normalized=False, check_partner=False, should_create=False):
expected_email_normalized = expected_email_normalized or expected_email
partner = self.env['res.partner'].find_or_create(test_string)
if should_create and check_partner:
self.assertTrue(partner.id > check_partner.id, 'find_or_create failed - should have found existing')
elif check_partner:
self.assertEqual(partner, check_partner, 'find_or_create failed - should have found existing')
self.assertEqual(partner.name, expected_name)
self.assertEqual(partner.email or '', expected_email)
self.assertEqual(partner.email_normalized or '', expected_email_normalized)
return partner
def test_res_partner_find_or_create(self):
Partner = self.env['res.partner']
partner = Partner.browse(Partner.name_create(SAMPLES[0][0])[0])
self._check_find_or_create(
SAMPLES[0][0], SAMPLES[0][1], SAMPLES[0][2],
check_partner=partner, should_create=False
)
partner_2 = Partner.browse(Partner.name_create('[email protected]')[0])
found_2 = self._check_find_or_create(
'[email protected]', '[email protected]', '[email protected]',
check_partner=partner_2, should_create=True
)
new = self._check_find_or_create(
SAMPLES[1][0], SAMPLES[1][2].lower(), SAMPLES[1][2].lower(),
check_partner=found_2, should_create=True
)
new2 = self._check_find_or_create(
SAMPLES[2][0], SAMPLES[2][1], SAMPLES[2][2],
check_partner=new, should_create=True
)
self._check_find_or_create(
SAMPLES[3][0], SAMPLES[3][1], SAMPLES[3][2],
check_partner=new2, should_create=True
)
new4 = self._check_find_or_create(
SAMPLES[4][0], SAMPLES[0][1], SAMPLES[0][2],
check_partner=partner, should_create=False
)
self._check_find_or_create(
SAMPLES[5][0], SAMPLES[5][1], SAMPLES[5][2],
check_partner=new4, should_create=True
)
existing = Partner.create({
'name': SAMPLES[6][1],
'email': SAMPLES[6][0],
})
self.assertEqual(existing.name, SAMPLES[6][1])
self.assertEqual(existing.email, SAMPLES[6][0])
self.assertEqual(existing.email_normalized, SAMPLES[6][2])
new6 = self._check_find_or_create(
SAMPLES[7][0], SAMPLES[6][1], SAMPLES[6][0],
expected_email_normalized=SAMPLES[6][2],
check_partner=existing, should_create=False
)
self._check_find_or_create(
SAMPLES[8][0], SAMPLES[8][1], SAMPLES[8][2],
check_partner=new6, should_create=True
)
with self.assertRaises(ValueError):
self.env['res.partner'].find_or_create("Raoul chirurgiens-dentistes.fr", assert_valid_email=True)
def test_res_partner_log_portal_group(self):
Users = self.env['res.users']
subtype_note = self.env.ref('mail.mt_note')
group_portal, group_user = self.env.ref('base.group_portal'), self.env.ref('base.group_user')
# check at update
new_user = Users.create({
'email': '[email protected]',
'login': 'michmich',
'name': 'Micheline Employee',
})
self.assertEqual(len(new_user.message_ids), 1, 'Should contain Contact created log message')
new_msg = new_user.message_ids
self.assertNotIn('Portal Access Granted', new_msg.body)
self.assertIn('Contact created', new_msg.body)
new_user.write({'groups_id': [(4, group_portal.id), (3, group_user.id)]})
new_msg = new_user.message_ids[0]
self.assertIn('Portal Access Granted', new_msg.body)
self.assertEqual(new_msg.subtype_id, subtype_note)
# check at create
new_user = Users.create({
'email': '[email protected]',
'groups_id': [(4, group_portal.id)],
'login': 'michmich.2',
'name': 'Micheline Portal',
})
self.assertEqual(len(new_user.message_ids), 2, 'Should contain Contact created + Portal access log messages')
new_msg = new_user.message_ids[0]
self.assertIn('Portal Access Granted', new_msg.body)
self.assertEqual(new_msg.subtype_id, subtype_note)
def test_res_partner_get_mention_suggestions_priority(self):
name = uuid4() # unique name to avoid conflict with already existing users
self.env['res.partner'].create([{'name': f'{name}-{i}-not-user'} for i in range(0, 2)])
for i in range(0, 2):
mail_new_test_user(self.env, login=f'{name}-{i}-portal-user', groups='base.group_portal')
mail_new_test_user(self.env, login=f'{name}-{i}-internal-user', groups='base.group_user')
partners_format = self.env['res.partner'].get_mention_suggestions(name, limit=5)
self.assertEqual(len(partners_format), 5, "should have found limit (5) partners")
self.assertEqual(list(map(lambda p: p['is_internal_user'], partners_format)), [True, True, False, False, False], "should return internal users in priority")
self.assertEqual(list(map(lambda p: bool(p['user_id']), partners_format)), [True, True, True, True, False], "should return partners without users last")
@users('admin')
def test_res_partner_merge_wizards(self):
Partner = self.env['res.partner']
p1 = Partner.create({'name': 'Customer1', 'email': '[email protected]'})
p1_msg_ids_init = p1.message_ids
p2 = Partner.create({'name': 'Customer2', 'email': '[email protected]'})
p2_msg_ids_init = p2.message_ids
p3 = Partner.create({'name': 'Other (dup email)', 'email': '[email protected]'})
# add some mail related documents
p1.message_subscribe(partner_ids=p3.ids)
p1_act1 = p1.activity_schedule(act_type_xmlid='mail.mail_activity_data_todo')
p1_msg1 = p1.message_post(
body='<p>Log on P1</p>',
subtype_id=self.env.ref('mail.mt_comment').id
)
self.assertEqual(p1.activity_ids, p1_act1)
self.assertEqual(p1.message_follower_ids.partner_id, self.partner_admin + p3)
self.assertEqual(p1.message_ids, p1_msg_ids_init + p1_msg1)
self.assertEqual(p2.activity_ids, self.env['mail.activity'])
self.assertEqual(p2.message_follower_ids.partner_id, self.partner_admin)
self.assertEqual(p2.message_ids, p2_msg_ids_init)
MergeForm = Form(self.env['base.partner.merge.automatic.wizard'].with_context(
active_model='res.partner',
active_ids=(p1 + p2).ids
))
self.assertEqual(MergeForm.partner_ids[:], p1 + p2)
self.assertEqual(MergeForm.dst_partner_id, p2)
merge_form = MergeForm.save()
merge_form.action_merge()
# check destination and removal
self.assertFalse(p1.exists())
self.assertTrue(p2.exists())
# check mail documents have been moved
self.assertEqual(p2.activity_ids, p1_act1)
# TDE note: currently not working as soon as there is a single partner duplicated -> should be improved
# self.assertEqual(p2.message_follower_ids.partner_id, self.partner_admin + p3)
all_msg = p2_msg_ids_init + p1_msg_ids_init + p1_msg1
self.assertEqual(len(p2.message_ids), len(all_msg) + 1, 'Should have original messages + a log')
self.assertTrue(all(msg in p2.message_ids for msg in all_msg))
| 47.962567 | 8,969 |
10,614 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import MailCommon
from odoo.exceptions import AccessError
from odoo.tests import Form, tagged, users
from odoo.tools import mute_logger
class TestMailComposer(MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailComposer, cls).setUpClass()
cls.env['ir.config_parameter'].set_param('mail.restrict.template.rendering', True)
cls.user_employee.groups_id -= cls.env.ref('mail.group_mail_template_editor')
cls.test_record = cls.env['res.partner'].with_context(cls._test_context).create({
'name': 'Test',
})
cls.body_html = """<div>
<h1>Hello sir!</h1>
<p>Here! <a href="https://www.example.com">
<!--[if mso]>
<i style="letter-spacing: 25px; mso-font-width: -100%; mso-text-raise: 30pt;"> </i>
<![endif]-->
A link for you! <!-- my favorite example -->
<!--[if mso]>
<i style="letter-spacing: 25px; mso-font-width: -100%;"> </i>
<![endif]-->
</a> Make good use of it.</p>
</div>"""
cls.mail_template = cls.env['mail.template'].create({
'auto_delete': True,
'body_html': cls.body_html,
'lang': '{{ object.lang }}',
'model_id': cls.env['ir.model']._get_id('res.partner'),
'subject': 'MSO FTW',
'name': 'Test template with mso conditionals',
})
@tagged('mail_composer')
class TestMailComposerForm(TestMailComposer):
""" Test mail composer form view usage. """
@classmethod
def setUpClass(cls):
super(TestMailComposerForm, cls).setUpClass()
cls.user_employee.write({'groups_id': [
(4, cls.env.ref('base.group_private_addresses').id),
(4, cls.env.ref('base.group_partner_manager').id),
]})
cls.partner_private, cls.partner_private_2, cls.partner_classic = cls.env['res.partner'].create([
{
'email': '[email protected]',
'phone': '0032455112233',
'name': 'Private Customer',
'type': 'private',
},
{
'email': '[email protected]',
'phone': '0032455445566',
'name': 'Private Customer 2',
'type': 'private',
},
{
'email': '[email protected]',
'phone': '0032455778899',
'name': 'Classic Customer',
'type': 'contact',
}
])
@mute_logger('odoo.addons.mail.models.mail_mail')
@users('employee')
def test_composer_default_recipients(self):
""" Test usage of a private partner in composer, as default value """
partner_classic = self.partner_classic.with_env(self.env)
test_record = self.test_record.with_env(self.env)
form = Form(self.env['mail.compose.message'].with_context({
'default_partner_ids': partner_classic.ids,
'default_model': test_record._name,
'default_res_id': test_record.id,
}))
form.body = '<p>Hello</p>'
self.assertEqual(
form.partner_ids._get_ids(), partner_classic.ids,
'Default populates the field'
)
saved_form = form.save()
self.assertEqual(
saved_form.partner_ids, partner_classic,
'Default value is kept at save'
)
with self.mock_mail_gateway():
saved_form._action_send_mail()
message = self.test_record.message_ids[0]
self.assertEqual(message.body, '<p>Hello</p>')
self.assertEqual(message.partner_ids, partner_classic)
self.assertEqual(message.subject, f'Re: {test_record.name}')
@mute_logger('odoo.addons.mail.models.mail_mail')
@users('employee')
def test_composer_default_recipients_private(self):
""" Test usage of a private partner in composer, as default value """
partner_private = self.partner_private.with_env(self.env)
partner_classic = self.partner_classic.with_env(self.env)
test_record = self.test_record.with_env(self.env)
form = Form(self.env['mail.compose.message'].with_context({
'default_partner_ids': (partner_private + partner_classic).ids,
'default_model': test_record._name,
'default_res_id': test_record.id,
}))
form.body = '<p>Hello</p>'
self.assertEqual(
sorted(form.partner_ids._get_ids()),
sorted((partner_private + partner_classic).ids),
'Default populates the field'
)
saved_form = form.save()
self.assertEqual(
saved_form.partner_ids, partner_private + partner_classic,
'Default value is kept at save'
)
with self.mock_mail_gateway():
saved_form._action_send_mail()
message = self.test_record.message_ids[0]
self.assertEqual(message.body, '<p>Hello</p>')
self.assertEqual(message.partner_ids, partner_private + partner_classic)
self.assertEqual(message.subject, f'Re: {test_record.name}')
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.mail.models.mail_mail')
@users('employee')
def test_composer_default_recipients_private_norights(self):
""" Test usage of a private partner in composer when not having the
rights to see them, as default value """
self.user_employee.write({'groups_id': [
(3, self.env.ref('base.group_private_addresses').id),
]})
with self.assertRaises(AccessError):
_name = self.partner_private.with_env(self.env).name
partner_classic = self.partner_classic.with_env(self.env)
test_record = self.test_record.with_env(self.env)
with self.assertRaises(AccessError):
_form = Form(self.env['mail.compose.message'].with_context({
'default_partner_ids': (self.partner_private + partner_classic).ids,
'default_model': test_record._name,
'default_res_id': test_record.id,
}))
@mute_logger('odoo.addons.mail.models.mail_mail')
@users('employee')
def test_composer_template_recipients_private(self):
""" Test usage of a private partner in composer, comint from template
value """
email_to_new = '[email protected]'
self.mail_template.write({
'email_to': f'{self.partner_private_2.email_formatted}, {email_to_new}',
'partner_to': f'{self.partner_private.id},{self.partner_classic.id}',
})
template = self.mail_template.with_env(self.env)
partner_private = self.partner_private.with_env(self.env)
partner_private_2 = self.partner_private_2.with_env(self.env)
partner_classic = self.partner_classic.with_env(self.env)
test_record = self.test_record.with_env(self.env)
form = Form(self.env['mail.compose.message'].with_context({
'default_model': test_record._name,
'default_res_id': test_record.id,
'default_template_id': template.id,
}))
# transformation from email_to into partner_ids: find or create
existing_partner = self.env['res.partner'].search(
[('email_normalized', '=', self.partner_private_2.email_normalized)]
)
self.assertEqual(existing_partner, partner_private_2, 'Should find existing private contact')
new_partner = self.env['res.partner'].search(
[('email_normalized', '=', email_to_new)]
)
self.assertEqual(new_partner.type, 'contact', 'Should create a new contact')
self.assertEqual(
sorted(form.partner_ids._get_ids()),
sorted((partner_private + partner_classic + partner_private_2 + new_partner).ids),
'Template populates the field with both email_to and partner_to'
)
saved_form = form.save()
self.assertEqual(
# saved_form.partner_ids, partner_private + partner_classic + partner_private_2 + new_partner,
saved_form.partner_ids, partner_classic + new_partner,
'Template value is kept at save (FIXME: loosing private partner)'
)
with self.mock_mail_gateway():
saved_form._action_send_mail()
message = self.test_record.message_ids[0]
self.assertIn('<h1>Hello sir!</h1>', message.body)
# self.assertEqual(message.partner_ids, partner_private + partner_classic + partner_private_2 + new_partner)
self.assertEqual(
message.partner_ids, partner_classic + new_partner,
'FIXME: loosing private partner'
)
self.assertEqual(message.subject, 'MSO FTW')
@tagged('mail_composer')
class TestMailComposerRendering(TestMailComposer):
""" Test rendering and support of various html tweaks in composer """
@users('employee')
def test_mail_mass_mode_template_with_mso(self):
mail_compose_message = self.env['mail.compose.message'].create({
'composition_mode': 'mass_mail',
'model': 'res.partner',
'template_id': self.mail_template.id,
'subject': 'MSO FTW',
})
values = mail_compose_message.get_mail_values(self.partner_employee.ids)
self.assertIn(self.body_html,
values[self.partner_employee.id]['body_html'],
'We must preserve (mso) comments in email html')
@mute_logger('odoo.addons.mail.models.mail_mail')
@users('employee')
def test_mail_mass_mode_compose_with_mso(self):
composer = self.env['mail.compose.message'].with_context({
'default_model': self.test_record._name,
'default_composition_mode': 'mass_mail',
'active_ids': [self.test_record.id],
'active_model': self.test_record._name,
'active_id': self.test_record.id
}).create({
'body': self.body_html,
'partner_ids': [(4, self.partner_employee.id)],
'composition_mode': 'mass_mail',
})
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
values = composer.get_mail_values(self.partner_employee.ids)
self.assertIn(self.body_html,
values[self.partner_employee.id]['body_html'],
'We must preserve (mso) comments in email html')
| 41.139535 | 10,614 |
12,826 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.mail.tests.common import MailCommon
from odoo.exceptions import AccessError, UserError
class TestMailChannelMembers(MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailChannelMembers, cls).setUpClass()
cls.secret_group = cls.env['res.groups'].create({
'name': 'Secret User Group',
})
cls.env['ir.model.data'].create({
'name': 'secret_group',
'module': 'mail',
'model': cls.secret_group._name,
'res_id': cls.secret_group.id,
})
cls.user_1 = mail_new_test_user(
cls.env, login='user_1',
name='User 1',
groups='base.group_user,mail.secret_group')
cls.user_2 = mail_new_test_user(
cls.env, login='user_2',
name='User 2',
groups='base.group_user,mail.secret_group')
cls.user_portal = mail_new_test_user(
cls.env, login='user_portal',
name='User Portal',
groups='base.group_portal')
cls.user_public = mail_new_test_user(
cls.env, login='user_ublic',
name='User Public',
groups='base.group_public')
cls.private_channel = cls.env['mail.channel'].create({
'name': 'Secret channel',
'public': 'private',
'channel_type': 'channel',
})
cls.group_channel = cls.env['mail.channel'].create({
'name': 'Group channel',
'public': 'groups',
'channel_type': 'channel',
'group_public_id': cls.secret_group.id,
})
cls.public_channel = cls.env['mail.channel'].create({
'name': 'Public channel of user 1',
'public': 'public',
'channel_type': 'channel',
})
(cls.private_channel | cls.group_channel | cls.public_channel).channel_last_seen_partner_ids.unlink()
# ------------------------------------------------------------
# PRIVATE CHANNELS
# ------------------------------------------------------------
def test_channel_private_01(self):
"""Test access on private channel."""
res = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertFalse(res)
# User 1 can join private channel with SUDO
self.private_channel.with_user(self.user_1).sudo().add_members(self.user_1.partner_id.ids)
res = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(res.partner_id, self.user_1.partner_id)
# User 2 can not join private channel
with self.assertRaises(AccessError):
self.private_channel.with_user(self.user_2).add_members(self.user_2.partner_id.ids)
# User 2 can not create a `mail.channel.partner` to join the private channel
with self.assertRaises(AccessError):
self.env['mail.channel.partner'].with_user(self.user_2).create({
'partner_id': self.user_2.partner_id.id,
'channel_id': self.private_channel.id,
})
# User 2 can not write on `mail.channel.partner` to join the private channel
channel_partner = self.env['mail.channel.partner'].with_user(self.user_2).search([('partner_id', '=', self.user_2.partner_id.id)])[0]
with self.assertRaises(AccessError):
channel_partner.channel_id = self.private_channel.id
with self.assertRaises(AccessError):
channel_partner.write({'channel_id': self.private_channel.id})
# Even with SUDO, channel_id of channel.partner should not be changed.
with self.assertRaises(AccessError):
channel_partner.sudo().channel_id = self.private_channel.id
# User 2 can not write on the `partner_id` of `mail.channel.partner`
# of an other partner to join a private channel
channel_partner_1 = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id), ('partner_id', '=', self.user_1.partner_id.id)])
with self.assertRaises(AccessError):
channel_partner_1.with_user(self.user_2).partner_id = self.user_2.partner_id
self.assertEqual(channel_partner_1.partner_id, self.user_1.partner_id)
# Even with SUDO, partner_id of channel.partner should not be changed.
with self.assertRaises(AccessError):
channel_partner_1.with_user(self.user_2).sudo().partner_id = self.user_2.partner_id
def test_channel_private_members(self):
"""Test invitation in private channel part 1 (invite using crud methods)."""
self.private_channel.with_user(self.user_1).sudo().add_members(self.user_1.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(len(channel_partners), 1)
# User 2 is not in the private channel, he can not invite user 3
with self.assertRaises(AccessError):
self.env['mail.channel.partner'].with_user(self.user_2).create({
'partner_id': self.user_portal.partner_id.id,
'channel_id': self.private_channel.id,
})
# User 1 is in the private channel, he can invite other users
self.env['mail.channel.partner'].with_user(self.user_1).create({
'partner_id': self.user_portal.partner_id.id,
'channel_id': self.private_channel.id,
})
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id | self.user_portal.partner_id)
# But User 3 can not write on the `mail.channel.partner` of other user
channel_partner_1 = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id), ('partner_id', '=', self.user_1.partner_id.id)])
channel_partner_3 = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id), ('partner_id', '=', self.user_portal.partner_id.id)])
channel_partner_3.with_user(self.user_portal).custom_channel_name = 'Test'
with self.assertRaises(AccessError):
channel_partner_1.with_user(self.user_2).custom_channel_name = 'Blabla'
self.assertNotEqual(channel_partner_1.custom_channel_name, 'Blabla')
def test_channel_private_invite(self):
"""Test invitation in private channel part 2 (use `invite` action)."""
self.private_channel.with_user(self.user_1).sudo().add_members(self.user_1.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id)
# User 2 is not in the channel, he can not invite user_portal
with self.assertRaises(AccessError):
self.private_channel.with_user(self.user_2).add_members(self.user_portal.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id)
# User 1 is in the channel, he can invite user_portal
self.private_channel.with_user(self.user_1).add_members(self.user_portal.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id | self.user_portal.partner_id)
def test_channel_private_leave(self):
"""Test kick/leave channel."""
self.private_channel.with_user(self.user_1).sudo().add_members(self.user_1.partner_id.ids)
self.private_channel.with_user(self.user_portal).sudo().add_members(self.user_portal.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.private_channel.id)])
self.assertEqual(len(channel_partners), 2)
# User 2 is not in the channel, he can not kick user 1
with self.assertRaises(AccessError):
channel_partners.with_user(self.user_2).unlink()
# User 3 is in the channel, he can kick user 1
channel_partners.with_user(self.user_portal).unlink()
# ------------------------------------------------------------
# GROUP BASED CHANNELS
# ------------------------------------------------------------
def test_channel_group(self):
"""Test basics on group channel."""
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.group_channel.id)])
self.assertFalse(channel_partners)
# user 1 is in the group, he can join the channel
self.group_channel.with_user(self.user_1).add_members(self.user_1.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.group_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id)
# user 3 is not in the group, he can not join
with self.assertRaises(AccessError):
self.group_channel.with_user(self.user_portal).add_members(self.user_portal.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.group_channel.id)])
with self.assertRaises(AccessError):
channel_partners.with_user(self.user_portal).partner_id = self.user_portal.partner_id
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.group_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id)
# user 1 can not invite user 3 because he's not in the group
with self.assertRaises(UserError):
self.group_channel.with_user(self.user_1).add_members(self.user_portal.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.group_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id)
# but user 2 is in the group and can be invited by user 1
self.group_channel.with_user(self.user_1).add_members(self.user_2.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.group_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id | self.user_2.partner_id)
# ------------------------------------------------------------
# PUBLIC CHANNELS
# ------------------------------------------------------------
def test_channel_public(self):
""" Test access on public channels """
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.public_channel.id)])
self.assertFalse(channel_partners)
self.public_channel.with_user(self.user_1).add_members(self.user_1.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.public_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id)
self.public_channel.with_user(self.user_2).add_members(self.user_2.partner_id.ids)
channel_partners = self.env['mail.channel.partner'].search([('channel_id', '=', self.public_channel.id)])
self.assertEqual(channel_partners.mapped('partner_id'), self.user_1.partner_id | self.user_2.partner_id)
# portal/public users still cannot join a public channel, should go through dedicated controllers
with self.assertRaises(AccessError):
self.public_channel.with_user(self.user_portal).add_members(self.user_portal.partner_id.ids)
with self.assertRaises(AccessError):
self.public_channel.with_user(self.user_public).add_members(self.user_public.partner_id.ids)
def test_channel_partner_invite_with_guest(self):
guest = self.env['mail.guest'].create({'name': 'Guest'})
partner = self.env['res.partner'].create({
'name': 'ToInvite',
'active': True,
'type': 'contact',
'user_ids': self.user_1,
})
self.public_channel.add_members(guest_ids=[guest.id])
search = self.env['res.partner'].search_for_channel_invite(partner.name, channel_id=self.public_channel.id)
self.assertEqual(len(search['partners']), 1)
self.assertEqual(search['partners'][0]['id'], partner.id)
| 54.118143 | 12,826 |
8,568 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import odoo
from odoo.tools import mute_logger
from odoo.tests import HttpCase
@odoo.tests.tagged("-at_install", "post_install")
class TestDiscussController(HttpCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.channel = cls.env["mail.channel"].create(
{
"name": "Test channel",
"public": "public",
}
)
cls.public_user = cls.env.ref("base.public_user")
cls.attachments = (
cls.env["ir.attachment"]
.with_user(cls.public_user)
.sudo()
.create(
[
{
"access_token": cls.env["ir.attachment"]._generate_access_token(),
"name": "File 1",
"res_id": 0,
"res_model": "mail.compose.message",
},
{
"access_token": cls.env["ir.attachment"]._generate_access_token(),
"name": "File 2",
"res_id": 0,
"res_model": "mail.compose.message",
},
]
)
)
cls.guest = cls.env["mail.guest"].create({"name": "Guest"})
cls.channel.add_members(guest_ids=cls.guest.ids)
@mute_logger("odoo.addons.http_routing.models.ir_http", "odoo.http")
def test_channel_message_attachments(self):
self.authenticate(None, None)
self.opener.cookies[
self.guest._cookie_name
] = f"{self.guest.id}{self.guest._cookie_separator}{self.guest.access_token}"
# test message post: token error
res1 = self.url_open(
url="/mail/message/post",
data=json.dumps(
{
"params": {
"thread_model": self.channel._name,
"thread_id": self.channel.id,
"post_data": {
"body": "test",
"attachment_ids": [self.attachments[0].id],
"attachment_tokens": ["wrong token"],
},
},
}
),
headers={"Content-Type": "application/json"},
)
self.assertEqual(res1.status_code, 200)
self.assertIn(
f"The attachment {self.attachments[0].id} does not exist or you do not have the rights to access it",
res1.text,
"guest should not be allowed to add attachment without token when posting message",
)
# test message post: token ok
res2 = self.url_open(
url="/mail/message/post",
data=json.dumps(
{
"params": {
"thread_model": self.channel._name,
"thread_id": self.channel.id,
"post_data": {
"body": "test",
"attachment_ids": [self.attachments[0].id],
"attachment_tokens": [self.attachments[0].access_token],
"message_type": "comment",
},
},
}
),
headers={"Content-Type": "application/json"},
)
self.assertEqual(res2.status_code, 200)
message_format1 = res2.json()["result"]
self.assertEqual(
message_format1["attachment_ids"],
self.attachments[0]._attachment_format(),
"guest should be allowed to add attachment with token when posting message",
)
# test message update: token error
res3 = self.url_open(
url="/mail/message/update_content",
data=json.dumps(
{
"params": {
"message_id": message_format1["id"],
"body": "test",
"attachment_ids": [self.attachments[1].id],
"attachment_tokens": ["wrong token"],
},
}
),
headers={"Content-Type": "application/json"},
)
self.assertEqual(res3.status_code, 200)
self.assertIn(
f"The attachment {self.attachments[1].id} does not exist or you do not have the rights to access it",
res3.text,
"guest should not be allowed to add attachment without token when updating message",
)
# test message update: token ok
res4 = self.url_open(
url="/mail/message/update_content",
data=json.dumps(
{
"params": {
"message_id": message_format1["id"],
"body": "test",
"attachment_ids": [self.attachments[1].id],
"attachment_tokens": [self.attachments[1].access_token],
},
}
),
headers={"Content-Type": "application/json"},
)
self.assertEqual(res4.status_code, 200)
message_format2 = res4.json()["result"]
self.assertEqual(
message_format2["attachments"],
json.loads(
json.dumps([("insert-and-replace", self.attachments.sorted()._attachment_format(commands=True))])
),
"guest should be allowed to add attachment with token when updating message",
)
# test message update: own attachment ok
res5 = self.url_open(
url="/mail/message/update_content",
data=json.dumps(
{
"params": {
"message_id": message_format2["id"],
"body": "test",
"attachment_ids": [self.attachments[1].id],
},
}
),
headers={"Content-Type": "application/json"},
)
self.assertEqual(res5.status_code, 200)
message_format3 = res5.json()["result"]
self.assertEqual(
message_format3["attachments"],
json.loads(
json.dumps([("insert-and-replace", self.attachments.sorted()._attachment_format(commands=True))])
),
"guest should be allowed to add own attachment without token when updating message",
)
@mute_logger("odoo.addons.http_routing.models.ir_http", "odoo.http")
def test_attachment_hijack(self):
att = self.env["ir.attachment"].create(
[
{
"name": "arguments_for_firing_marc_demo",
"res_id": 0,
"res_model": "mail.compose.message",
},
]
)
demo = self.authenticate("demo", "demo")
channel = self.env["mail.channel"].create({"name": "public_channel", "public": "public"})
channel.add_members(
self.env["res.users"].browse(demo.uid).partner_id.id
) # don't care, we just need a channel where demo is follower
no_access_request = self.url_open("/web/content/" + str(att.id))
self.assertFalse(
no_access_request.ok
) # if this test breaks, it might be due to a change in /web/content, or the default rules for accessing an attachment. This is not an issue but it makes this test irrelevant.
response = self.url_open(
url="/mail/message/post",
headers={"Content-Type": "application/json"}, # route called as demo
data=json.dumps(
{
"params": {
"post_data": {
"attachment_ids": [att.id], # demo does not have access to this attachment id
"body": "",
"message_type": "comment",
"partner_ids": [],
"subtype_xmlid": "mail.mt_comment",
},
"thread_id": channel.id,
"thread_model": "mail.channel",
}
},
),
)
self.assertNotIn(
"arguments_for_firing_marc_demo", response.text
) # demo should not be able to see the name of the document
| 40.225352 | 8,568 |
20,143 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from markupsafe import Markup
from odoo.addons.mail.tests import common
from odoo.exceptions import AccessError
from odoo.tests import tagged, users
@tagged('mail_render')
class TestMailRender(common.MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailRender, cls).setUpClass()
# activate multi language support
cls.env['res.lang']._activate_lang('fr_FR')
cls.user_admin.write({'lang': 'en_US'})
# test records
cls.render_object = cls.env['res.partner'].create({
'name': 'TestRecord',
'lang': 'en_US',
})
cls.render_object_fr = cls.env['res.partner'].create({
'name': 'Element de Test',
'lang': 'fr_FR',
})
# some jinja templates
cls.base_inline_template_bits = [
'<p>Hello</p>',
'<p>Hello {{ object.name }}</p>',
"""<p>
{{ '<span>English Speaker</span>' if object.lang == 'en_US' else '<span>Other Speaker</span>' }}
</p>""",
"""
<p>{{ 13 + 13 }}</p>
<h1>This is a test</h1>
""",
"""
<b>Test</b>
{{ '' if True else '<b>Code not executed</b>' }}
""",
]
cls.base_inline_template_bits_fr = [
'<p>Bonjour</p>',
'<p>Bonjour {{ object.name }}</p>',
"""<p>
{{ '<span>Narrateur Anglais</span>' if object.lang == 'en_US' else '<span>Autre Narrateur</span>' }}
</p>"""
]
# some qweb templates, their views and their xml ids
cls.base_qweb_bits = [
'<p>Hello</p>',
'<p>Hello <t t-esc="object.name"/></p>',
"""<p>
<span t-if="object.lang == 'en_US'">English Speaker</span>
<span t-else="">Other Speaker</span>
</p>"""
]
cls.base_qweb_bits_fr = [
'<p>Bonjour</p>',
'<p>Bonjour <t t-esc="object.name"/></p>',
"""<p>
<span t-if="object.lang == 'en_US'">Narrateur Anglais</span>
<span t-else="">Autre Narrateur</span>
</p>"""
]
cls.base_qweb_templates = cls.env['ir.ui.view'].create([
{'name': 'TestRender%d' % index,
'type': 'qweb',
'arch': qweb_content,
} for index, qweb_content in enumerate(cls.base_qweb_bits)
])
cls.base_qweb_templates_data = cls.env['ir.model.data'].create([
{'name': template.name, 'module': 'mail',
'model': template._name, 'res_id': template.id,
} for template in cls.base_qweb_templates
])
cls.base_qweb_templates_xmlids = [
model_data.complete_name
for model_data in cls.base_qweb_templates_data
]
# render result
cls.base_rendered = [
'<p>Hello</p>',
'<p>Hello %s</p>' % cls.render_object.name,
"""<p>
<span>English Speaker</span>
</p>"""
]
cls.base_rendered_fr = [
'<p>Bonjour</p>',
'<p>Bonjour %s</p>' % cls.render_object_fr.name,
"""<p>
<span>Autre Narrateur</span>
</p>"""
]
# link to mail template
cls.test_template = cls.env['mail.template'].create({
'name': 'Test Template',
'subject': cls.base_inline_template_bits[0],
'body_html': cls.base_qweb_bits[1],
'model_id': cls.env['ir.model']._get('res.partner').id,
'lang': '{{ object.lang }}'
})
# some translations
cls.env['ir.translation'].create({
'type': 'model',
'name': 'mail.template,subject',
'lang': 'fr_FR',
'res_id': cls.test_template.id,
'src': cls.test_template.subject,
'value': cls.base_qweb_bits_fr[0],
})
cls.env['ir.translation'].create({
'type': 'model',
'name': 'mail.template,body_html',
'lang': 'fr_FR',
'res_id': cls.test_template.id,
'src': cls.test_template.body_html,
'value': cls.base_qweb_bits_fr[1],
})
cls.env['ir.model.data'].create({
'name': 'test_template_xmlid',
'module': 'mail',
'model': cls.test_template._name,
'res_id': cls.test_template.id,
})
# Enable group-based template management
cls.env['ir.config_parameter'].set_param('mail.restrict.template.rendering', True)
# User without the group "mail.group_mail_template_editor"
cls.user_rendering_restricted = common.mail_new_test_user(
cls.env, login='user_rendering_restricted',
groups='base.group_user',
company_id=cls.company_admin.id,
name='Code Template Restricted User',
notification_type='inbox',
signature='--\nErnest'
)
cls.user_rendering_restricted.groups_id -= cls.env.ref('mail.group_mail_template_editor')
cls.user_employee.groups_id += cls.env.ref('mail.group_mail_template_editor')
@users('employee')
def test_evaluation_context(self):
""" Test evaluation context and various ways of tweaking it. """
partner = self.env['res.partner'].browse(self.render_object.ids)
MailRenderMixin = self.env['mail.render.mixin']
custom_ctx = {'custom_ctx': 'Custom Context Value'}
add_context = {
'custom_value': 'Custom Render Value'
}
srces = [
'<b>I am {{ user.name }}</b>',
'<span>Datetime is {{ format_datetime(datetime.datetime(2021, 6, 1), dt_format="MM - d - YYY") }}</span>',
'<span>Context {{ ctx.get("custom_ctx") }}, value {{ custom_value }}</span>',
]
results = [
'<b>I am %s</b>' % self.env.user.name,
'<span>Datetime is 06 - 1 - 2021</span>',
'<span>Context Custom Context Value, value Custom Render Value</span>'
]
for src, expected in zip(srces, results):
for engine in ['inline_template']:
result = MailRenderMixin.with_context(**custom_ctx)._render_template(
src, partner._name, partner.ids,
engine=engine, add_context=add_context
)[partner.id]
self.assertEqual(expected, result)
@users('employee')
def test_render_field(self):
template = self.env['mail.template'].browse(self.test_template.ids)
partner = self.env['res.partner'].browse(self.render_object.ids)
for fname, expected in zip(['subject', 'body_html'], self.base_rendered):
rendered = template._render_field(
fname,
partner.ids,
compute_lang=True
)[partner.id]
self.assertEqual(rendered, expected)
partner = self.env['res.partner'].browse(self.render_object_fr.ids)
for fname, expected in zip(['subject', 'body_html'], self.base_rendered_fr):
rendered = template._render_field(
fname,
partner.ids,
compute_lang=True
)[partner.id]
self.assertEqual(rendered, expected)
@users('employee')
def test_render_template_inline_template(self):
partner = self.env['res.partner'].browse(self.render_object.ids)
for source, expected in zip(self.base_inline_template_bits, self.base_rendered):
rendered = self.env['mail.render.mixin']._render_template(
source,
partner._name,
partner.ids,
engine='inline_template',
)[partner.id]
self.assertEqual(rendered, expected)
@users('employee')
def test_render_template_local_links(self):
local_links_template_bits = [
'<div style="background-image:url(/web/path?a=a&b=b);"/>',
'<div style="background-image:url(\'/web/path?a=a&b=b\');"/>',
'<div style="background-image:url("/web/path?a=a&b=b");"/>',
]
base_url = self.env['mail.render.mixin'].get_base_url()
rendered_local_links = [
'<div style="background-image:url(%s/web/path?a=a&b=b);"/>' % base_url,
'<div style="background-image:url(\'%s/web/path?a=a&b=b\');"/>' % base_url,
'<div style="background-image:url("%s/web/path?a=a&b=b");"/>' % base_url
]
for source, expected in zip(local_links_template_bits, rendered_local_links):
rendered = self.env['mail.render.mixin']._replace_local_links(source)
self.assertEqual(rendered, expected)
@users('employee')
def test_render_template_qweb(self):
partner = self.env['res.partner'].browse(self.render_object.ids)
for source, expected in zip(self.base_qweb_bits, self.base_rendered):
rendered = self.env['mail.render.mixin']._render_template(
source,
partner._name,
partner.ids,
engine='qweb',
)[partner.id]
self.assertEqual(rendered, expected)
@users('employee')
def test_render_template_qweb_view(self):
partner = self.env['res.partner'].browse(self.render_object.ids)
for source, expected in zip(self.base_qweb_templates_xmlids, self.base_rendered):
rendered = self.env['mail.render.mixin']._render_template(
source,
partner._name,
partner.ids,
engine='qweb_view',
)[partner.id]
self.assertEqual(rendered, expected)
@users('employee')
def test_template_rendering_impersonate(self):
""" Test that the use of SUDO do not change the current user. """
partner = self.env['res.partner'].browse(self.render_object.ids)
src = '{{ user.name }} - {{ object.name }}'
expected = '%s - %s' % (self.env.user.name, partner.name)
result = self.env['mail.render.mixin'].sudo()._render_template_inline_template(
src, partner._name, partner.ids
)[partner.id]
self.assertIn(expected, result)
@users('user_rendering_restricted')
def test_template_rendering_function_call(self):
"""Test the case when the template call a custom function.
This function should not be called when the template is not rendered.
"""
model = 'res.partner'
res_ids = self.env[model].search([], limit=1).ids
partner = self.env[model].browse(res_ids)
MailRenderMixin = self.env['mail.render.mixin']
def cust_function():
# Can not use "MagicMock" in a Jinja sand-boxed environment
# so create our own function
cust_function.call = True
return 'return value'
cust_function.call = False
src = """<h1>This is a test</h1>
<p>{{ cust_function() }}</p>"""
expected = """<h1>This is a test</h1>
<p>return value</p>"""
context = {'cust_function': cust_function}
result = self.env['mail.render.mixin'].with_user(self.user_admin)._render_template_inline_template(
src, partner._name, partner.ids,
add_context=context
)[partner.id]
self.assertEqual(expected, result)
self.assertTrue(cust_function.call)
with self.assertRaises(AccessError, msg='Simple user should not be able to render dynamic code'):
MailRenderMixin._render_template_inline_template(src, model, res_ids, add_context=context)
@users('user_rendering_restricted')
def test_template_render_static(self):
"""Test that we render correctly static templates (without placeholders)."""
model = 'res.partner'
res_ids = self.env[model].search([], limit=1).ids
MailRenderMixin = self.env['mail.render.mixin']
result = MailRenderMixin._render_template_inline_template(self.base_inline_template_bits[0], model, res_ids)[res_ids[0]]
self.assertEqual(result, self.base_inline_template_bits[0])
@users('user_rendering_restricted')
def test_template_rendering_restricted(self):
"""Test if we correctly detect static template."""
res_ids = self.env['res.partner'].search([], limit=1).ids
with self.assertRaises(AccessError, msg='Simple user should not be able to render dynamic code'):
self.env['mail.render.mixin']._render_template_inline_template(self.base_inline_template_bits[3], 'res.partner', res_ids)
@users('employee')
def test_template_rendering_unrestricted(self):
"""Test if we correctly detect static template."""
res_ids = self.env['res.partner'].search([], limit=1).ids
result = self.env['mail.render.mixin']._render_template_inline_template(self.base_inline_template_bits[3], 'res.partner', res_ids)[res_ids[0]]
self.assertIn('26', result, 'Template Editor should be able to render inline_template code')
@users('employee')
def test_template_rendering_various(self):
""" Test static rendering """
partner = self.env['res.partner'].browse(self.render_object.ids)
MailRenderMixin = self.env['mail.render.mixin']
# static string
src = 'This is a string'
expected = 'This is a string'
for engine in ['inline_template']:
result = MailRenderMixin._render_template(
src, partner._name, partner.ids, engine=engine,
)[partner.id]
self.assertEqual(expected, result)
# code string
src = 'This is a string with a number {{ 13+13 }}'
expected = 'This is a string with a number 26'
for engine in ['inline_template']:
result = MailRenderMixin._render_template(
src, partner._name, partner.ids, engine=engine,
)[partner.id]
self.assertEqual(expected, result)
# block string
src = "This is a string with a block {{ 'hidden' if False else 'displayed' }}"
expected = 'This is a string with a block displayed'
for engine in ['inline_template']:
result = MailRenderMixin._render_template(
src, partner._name, partner.ids, engine=engine,
)[partner.id]
self.assertEqual(expected, result)
# static xml
src = '<p class="text-muted"><span>This is a string</span></p>'
expected = '<p class="text-muted"><span>This is a string</span></p>'
for engine in ['inline_template', 'qweb']:
result = MailRenderMixin._render_template(
src, partner._name, partner.ids, engine=engine,
)[partner.id]
self.assertEqual(expected, result) # tde: checkme
# code xml
srces = [
'<p class="text-muted"><span>This is a string with a number {{ 13+13 }}</span></p>',
'<p class="text-muted"><span>This is a string with a number <t t-out="13+13"/></span></p>',
]
expected = '<p class="text-muted"><span>This is a string with a number 26</span></p>'
for engine, src in zip(['inline_template', 'qweb'], srces):
result = MailRenderMixin._render_template(
src, partner._name, partner.ids, engine=engine,
)[partner.id]
self.assertEqual(expected, str(result))
src = """<p>
<t t-set="line_statement_variable" t-value="3" />
<span>We have <t t-out="line_statement_variable" /> cookies in stock</span>
<span>We have <t t-set="block_variable" t-value="4" /><t t-out="block_variable" /> cookies in stock</span>
</p>"""
expected = """<p>
<span>We have 3 cookies in stock</span>
<span>We have 4 cookies in stock</span>
</p>"""
for engine in ['qweb']:
result = MailRenderMixin._render_template(
src, partner._name, partner.ids, engine=engine,
)[partner.id]
self.assertEqual(result, expected)
@users('user_rendering_restricted')
def test_security_inline_template_restricted(self):
"""Test if we correctly detect condition block (which might contains code)."""
res_ids = self.env['res.partner'].search([], limit=1).ids
with self.assertRaises(AccessError, msg='Simple user should not be able to render dynamic code'):
self.env['mail.render.mixin']._render_template_inline_template(self.base_inline_template_bits[4], 'res.partner', res_ids)
@users('employee')
def test_is_inline_template_condition_block_unrestricted(self):
"""Test if we correctly detect condition block (which might contains code)."""
res_ids = self.env['res.partner'].search([], limit=1).ids
result = self.env['mail.render.mixin']._render_template_inline_template(self.base_inline_template_bits[4], 'res.partner', res_ids)[res_ids[0]]
self.assertNotIn('Code not executed', result, 'The condition block did not work')
@users('user_rendering_restricted')
def test_security_qweb_template_restricted(self):
"""Test if we correctly detect condition block (which might contains code)."""
res_ids = self.env['res.partner'].search([], limit=1).ids
with self.assertRaises(AccessError, msg='Simple user should not be able to render qweb code'):
self.env['mail.render.mixin']._render_template_qweb(self.base_qweb_bits[1], 'res.partner', res_ids)
@users('user_rendering_restricted')
def test_security_qweb_template_restricted_cached(self):
"""Test if we correctly detect condition block (which might contains code)."""
res_ids = self.env['res.partner'].search([], limit=1).ids
# Render with the admin first to fill the cache
self.env['mail.render.mixin'].with_user(self.user_admin)._render_template_qweb(
self.base_qweb_bits[1], 'res.partner', res_ids)
# Check that it raise even when rendered previously by an admin
with self.assertRaises(AccessError, msg='Simple user should not be able to render qweb code'):
self.env['mail.render.mixin']._render_template_qweb(
self.base_qweb_bits[1], 'res.partner', res_ids)
@users('employee')
def test_security_qweb_template_unrestricted(self):
"""Test if we correctly detect condition block (which might contains code)."""
res_ids = self.env['res.partner'].search([], limit=1).ids
result = self.env['mail.render.mixin']._render_template_qweb(self.base_qweb_bits[1], 'res.partner', res_ids)[res_ids[0]]
self.assertNotIn('Code not executed', result, 'The condition block did not work')
@users('user_rendering_restricted')
def test_template_rendering_static_inline_template(self):
model = 'res.partner'
res_ids = self.env[model].search([], limit=1).ids
partner = self.env[model].browse(res_ids)
src = """<h1>This is a static template</h1>"""
result = self.env['mail.render.mixin']._render_template_inline_template(
src, model, res_ids)[partner.id]
self.assertEqual(src, str(result))
@users('user_rendering_restricted')
def test_template_rendering_static_qweb(self):
model = 'res.partner'
res_ids = self.env[model].search([], limit=1).ids
partner = self.env[model].browse(res_ids)
src = """<h1>This is a static template</h1>"""
result = self.env['mail.render.mixin']._render_template_qweb(src, model, res_ids)[
partner.id]
self.assertEqual(src, str(result))
@users('employee')
def test_prepend_preview_inline_template_to_qweb(self):
body = 'body'
preview = 'foo{{"false" if 1 > 2 else "true"}}bar'
result = self.env['mail.render.mixin']._prepend_preview(Markup(body), preview)
self.assertEqual(result, '''<div style="display:none;font-size:1px;height:0px;width:0px;opacity:0;">
foo<t t-out=""false" if 1 > 2 else "true""/>bar
</div>body''')
| 43.225322 | 20,143 |
4,141 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
from odoo.tests import HttpCase
from odoo.addons.mail.tests.common import mail_new_test_user
@odoo.tests.tagged('-at_install', 'post_install')
class TestMailPublicPage(HttpCase):
"""Checks that the invite page redirects to the channel and that all
modules load correctly on the welcome and channel page when authenticated as various users"""
def setUp(self):
super().setUp()
portal_user = mail_new_test_user(
self.env,
name='Portal Bowser',
login='portal_bowser',
email='[email protected]',
groups='base.group_portal',
)
internal_user = mail_new_test_user(
self.env,
name='Internal Luigi',
login='internal_luigi',
email='[email protected]',
groups='base.group_user',
)
guest = self.env['mail.guest'].create({'name': 'Guest Mario'})
self.channel = self.env['mail.channel'].create({
'name': 'Test channel',
'public': 'public',
})
self.group = self.env['mail.channel'].create({
'name': 'Test channel',
'channel_type': 'group',
'public': 'public',
})
self.channel.add_members(portal_user.partner_id.ids)
self.channel.add_members(internal_user.partner_id.ids)
self.channel.add_members(guest_ids=[guest.id])
self.group.add_members(portal_user.partner_id.ids)
self.group.add_members(internal_user.partner_id.ids)
self.group.add_members(guest_ids=[guest.id])
self.channel_route = f"/chat/{self.channel.id}/{self.channel.uuid}"
self.group_route = f"/chat/{self.group.id}/{self.group.uuid}"
self.tour = "mail/static/tests/tours/discuss_public_tour.js"
def _open_channel_page_as_user(self, login):
self.start_tour(self.channel_route, self.tour, login=login)
# Second run of the tour as the first call has side effects, like creating user settings or adding members to
# the channel, so we need to run it again to test different parts of the code.
self.start_tour(self.channel_route, self.tour, login=login)
def _open_group_page_as_user(self, login):
self.start_tour(self.group_route, self.tour, login=login)
# Second run of the tour as the first call has side effects, like creating user settings or adding members to
# the group chat, so we need to run it again to test different parts of the code.
self.start_tour(self.group_route, self.tour, login=login)
def test_mail_channel_public_page_as_admin(self):
self._open_channel_page_as_user('admin')
def test_mail_group_public_page_as_admin(self):
self._open_group_page_as_user('admin')
def test_mail_channel_public_page_as_guest(self):
self.start_tour(self.channel_route, "mail/static/tests/tours/mail_channel_as_guest_tour.js")
guest = self.env['mail.guest'].search([('channel_ids', 'in', self.channel.id)], limit=1, order='id desc')
self.start_tour(self.channel_route, self.tour, cookies={guest._cookie_name: f"{guest.id}{guest._cookie_separator}{guest.access_token}"})
def test_mail_group_public_page_as_guest(self):
self.start_tour(self.group_route, "mail/static/tests/tours/mail_channel_as_guest_tour.js")
guest = self.env['mail.guest'].search([('channel_ids', 'in', self.group.id)], limit=1, order='id desc')
self.start_tour(self.group_route, self.tour, cookies={guest._cookie_name: f"{guest.id}{guest._cookie_separator}{guest.access_token}"})
def test_mail_channel_public_page_as_internal(self):
self._open_channel_page_as_user('demo')
def test_mail_group_public_page_as_internal(self):
self._open_group_page_as_user('demo')
def test_mail_channel_public_page_as_portal(self):
self._open_channel_page_as_user('portal')
def test_mail_group_public_page_as_portal(self):
self._open_group_page_as_user('portal')
| 46.011111 | 4,141 |
31,767 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.addons.mail.tests.common import MailCommon
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.tools import mute_logger
@tagged('RTC')
class TestChannelInternals(MailCommon):
@users('employee')
@mute_logger('odoo.models.unlink')
def test_01_join_call(self):
"""Join call should remove existing sessions, remove invitation, create a new session, and return data."""
channel = self.env['mail.channel'].browse(self.env['mail.channel'].channel_create(name='Test Channel')['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # end of previous session
(self.cr.dbname, 'mail.channel', channel.id), # update sessions
(self.cr.dbname, 'mail.channel', channel.id), # update sessions
],
[
{
'type': 'mail.channel.rtc.session/ended',
'payload': {
'sessionId': channel_partner.rtc_session_ids.id,
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': channel_partner.rtc_session_ids.id}])],
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert', [{
'id': channel_partner.rtc_session_ids.id + 1,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
}])],
},
},
]
):
res = channel_partner._rtc_join_call()
self.assertEqual(res, {
'iceServers': False,
'rtcSessions': [
('insert', [{
'id': channel_partner.rtc_session_ids.id,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
}]),
('insert-and-unlink', [{'id': channel_partner.rtc_session_ids.id - 1}]),
],
'sessionId': channel_partner.rtc_session_ids.id,
})
@users('employee')
@mute_logger('odoo.models.unlink')
def test_10_start_call_in_chat_should_invite_all_members_to_call(self):
test_user = self.env['res.users'].sudo().create({'name': "Test User", 'login': 'test'})
channel = self.env['mail.channel'].browse(self.env['mail.channel'].channel_get(partners_to=(self.user_employee.partner_id + test_user.partner_id).ids)['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
last_rtc_session_id = channel_partner.rtc_session_ids.id
channel_partner._rtc_leave_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'mail.channel', channel.id), # update new session
(self.cr.dbname, 'mail.channel', channel.id), # message_post "started a live conference" (not asserted below)
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # incoming invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
],
[
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert', [{
'id': last_rtc_session_id + 1,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
}])],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedPartners': [('insert', [{'id': test_user.partner_id.id, 'name': 'Test User'}])],
},
},
]
):
res = channel_partner._rtc_join_call()
self.assertNotIn('invitedGuests', res)
self.assertIn('invitedPartners', res)
self.assertEqual(res['invitedPartners'], [('insert', [{'id': test_user.partner_id.id, 'name': "Test User"}])])
@users('employee')
@mute_logger('odoo.models.unlink')
def test_11_start_call_in_group_should_invite_all_members_to_call(self):
test_user = self.env['res.users'].sudo().create({'name': "Test User", 'login': 'test'})
test_guest = self.env['mail.guest'].sudo().create({'name': "Test Guest"})
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=(self.user_employee.partner_id + test_user.partner_id).ids)['id'])
channel.add_members(guest_ids=test_guest.ids)
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
last_rtc_session_id = channel_partner.rtc_session_ids.id
channel_partner._rtc_leave_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'mail.channel', channel.id), # update new session
(self.cr.dbname, 'mail.channel', channel.id), # message_post "started a live conference" (not asserted below)
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # incoming invitation
(self.cr.dbname, 'mail.guest', test_guest.id), # incoming invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
],
[
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert', [{
'id': last_rtc_session_id + 1,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
}])],
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert', [{
'id': last_rtc_session_id + 1,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
}])],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedGuests': [('insert', [{'id': test_guest.id, 'name': 'Test Guest'}])],
'invitedPartners': [('insert', [{'id': test_user.partner_id.id, 'name': 'Test User'}])],
},
},
]
):
res = channel_partner._rtc_join_call()
self.assertIn('invitedGuests', res)
self.assertEqual(res['invitedGuests'], [('insert', [{'id': test_guest.id, 'name': 'Test Guest'}])])
self.assertIn('invitedPartners', res)
self.assertEqual(res['invitedPartners'], [('insert', [{'id': test_user.partner_id.id, 'name': "Test User"}])])
@users('employee')
@mute_logger('odoo.models.unlink')
def test_20_join_call_should_cancel_pending_invitations(self):
test_user = self.env['res.users'].sudo().create({'name': "Test User", 'login': 'test'})
test_guest = self.env['mail.guest'].sudo().create({'name': "Test Guest"})
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=(self.user_employee.partner_id + test_user.partner_id).ids)['id'])
channel.add_members(guest_ids=test_guest.ids)
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
channel_partner_test_user = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == test_user.partner_id)
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
(self.cr.dbname, 'mail.channel', channel.id), # update sessions
],
[
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('unlink',)],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedPartners': [('insert-and-unlink', [{'id': test_user.partner_id.id}])],
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert', [
{
'id': channel_partner.rtc_session_ids.id + 1,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': test_user.partner_id.id,
'name': 'Test User',
})],
},
])],
},
},
]
):
channel_partner_test_user._rtc_join_call()
channel_partner_test_guest = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.guest_id == test_guest)
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'mail.guest', test_guest.id), # update invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
(self.cr.dbname, 'mail.channel', channel.id), # update sessions
],
[
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('unlink',)],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedGuests': [('insert-and-unlink', [{'id': test_guest.id}])],
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert', [
{
'id': channel_partner.rtc_session_ids.id + 2,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'guest': [('insert', {
'id': test_guest.id,
'name': 'Test Guest',
})],
},
])],
},
},
]
):
channel_partner_test_guest._rtc_join_call()
@users('employee')
@mute_logger('odoo.models.unlink')
def test_21_leave_call_should_cancel_pending_invitations(self):
test_user = self.env['res.users'].sudo().create({'name': "Test User", 'login': 'test'})
test_guest = self.env['mail.guest'].sudo().create({'name': "Test Guest"})
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=(self.user_employee.partner_id + test_user.partner_id).ids)['id'])
channel.add_members(guest_ids=test_guest.ids)
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
channel_partner_test_user = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == test_user.partner_id)
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
],
[
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('unlink',)],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedPartners': [('insert-and-unlink', [{'id': test_user.partner_id.id}])],
},
},
]
):
channel_partner_test_user._rtc_leave_call()
channel_partner_test_guest = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.guest_id == test_guest)
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'mail.guest', test_guest.id), # update invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
],
[
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('unlink',)],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedGuests': [('insert-and-unlink', [{'id': test_guest.id}])],
},
},
]
):
channel_partner_test_guest._rtc_leave_call()
@users('employee')
@mute_logger('odoo.models.unlink')
def test_25_lone_call_participant_leaving_call_should_cancel_pending_invitations(self):
test_user = self.env['res.users'].sudo().create({'name': "Test User", 'login': 'test'})
test_guest = self.env['mail.guest'].sudo().create({'name': "Test Guest"})
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=(self.user_employee.partner_id + test_user.partner_id).ids)['id'])
channel.add_members(guest_ids=test_guest.ids)
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # end session
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update invitation
(self.cr.dbname, 'mail.guest', test_guest.id), # update invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
(self.cr.dbname, 'mail.channel', channel.id), # update sessions
],
[
{
'type': 'mail.channel.rtc.session/ended',
'payload': {
'sessionId': channel_partner.rtc_session_ids.id,
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('unlink',)],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('unlink',)],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedGuests': [('insert-and-unlink', [{'id': test_guest.id}])],
'invitedPartners': [('insert-and-unlink', [{'id': test_user.partner_id.id}])],
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': channel_partner.rtc_session_ids.id}])],
},
},
]
):
channel_partner._rtc_leave_call()
@users('employee')
@mute_logger('odoo.models.unlink')
def test_30_add_members_while_in_call_should_invite_new_members_to_call(self):
test_user = self.env['res.users'].sudo().create({'name': "Test User", 'login': 'test'})
test_guest = self.env['mail.guest'].sudo().create({'name': "Test Guest"})
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=self.user_employee.partner_id.ids)['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # channel joined (not asserted below)
(self.cr.dbname, 'mail.channel', channel.id), # message_post "invited" (not asserted below)
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'mail.channel', channel.id), # new members (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # incoming invitation
(self.cr.dbname, 'mail.guest', test_guest.id), # incoming invitation
(self.cr.dbname, 'mail.channel', channel.id), # update list of invitations
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'res.partner', test_user.partner_id.id), # update of last interest (not asserted below)
(self.cr.dbname, 'mail.channel', channel.id), # new member (guest) (not asserted below)
(self.cr.dbname, 'mail.guest', test_guest.id), # channel joined for guest (not asserted below)
],
[
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('insert', {
'id': channel_partner.rtc_session_ids.id,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
})],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'rtcInvitingSession': [('insert', {
'id': channel_partner.rtc_session_ids.id,
'isCameraOn': False,
'isDeaf': False,
'isMuted': False,
'isScreenSharingOn': False,
'partner': [('insert', {
'id': self.user_employee.partner_id.id,
'name': "Ernest Employee",
})],
})],
},
},
{
'type': 'mail.channel/insert',
'payload': {
'id': channel.id,
'invitedGuests': [('insert', [{'id': test_guest.id, 'name': 'Test Guest'}])],
'invitedPartners': [('insert', [{'id': test_user.partner_id.id, 'name': 'Test User'}])],
},
},
],
):
channel.add_members(partner_ids=test_user.partner_id.ids, guest_ids=test_guest.ids, invite_to_rtc_call=True)
@users('employee')
@mute_logger('odoo.models.unlink')
def test_40_leave_call_should_remove_existing_sessions_of_user_in_channel_and_return_data(self):
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=self.user_employee.partner_id.ids)['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # end session
(self.cr.dbname, 'mail.channel', channel.id), # update list of sessions
],
[
{
'type': 'mail.channel.rtc.session/ended',
'payload': {
'sessionId': channel_partner.rtc_session_ids.id,
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': channel_partner.rtc_session_ids.id}])],
},
},
],
):
channel_partner._rtc_leave_call()
@users('employee')
@mute_logger('odoo.models.unlink')
def test_50_garbage_collect_should_remove_old_sessions_and_notify_data(self):
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=self.user_employee.partner_id.ids)['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
channel_partner.rtc_session_ids.flush()
channel_partner.rtc_session_ids._write({'write_date': fields.Datetime.now() - relativedelta(days=2)})
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # session ended
(self.cr.dbname, 'mail.channel', channel.id), # update list of sessions
],
[
{
'type': 'mail.channel.rtc.session/ended',
'payload': {
'sessionId': channel_partner.rtc_session_ids.id,
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': channel_partner.rtc_session_ids.id}])],
},
},
],
):
self.env['mail.channel.rtc.session'].sudo()._gc_inactive_sessions()
self.assertFalse(channel_partner.rtc_session_ids)
@users('employee')
@mute_logger('odoo.models.unlink')
def test_51_action_disconnect_should_remove_selected_session_and_notify_data(self):
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=self.user_employee.partner_id.ids)['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
channel_partner._rtc_join_call()
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'res.partner', self.user_employee.partner_id.id), # session ended
(self.cr.dbname, 'mail.channel', channel.id), # update list of sessions
],
[
{
'type': 'mail.channel.rtc.session/ended',
'payload': {
'sessionId': channel_partner.rtc_session_ids.id,
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': channel_partner.rtc_session_ids.id}])],
},
},
],
):
channel_partner.rtc_session_ids.action_disconnect()
self.assertFalse(channel_partner.rtc_session_ids)
@users('employee')
@mute_logger('odoo.models.unlink')
def test_60_rtc_sync_sessions_should_gc_and_return_outdated_and_active_sessions(self):
channel = self.env['mail.channel'].browse(self.env['mail.channel'].create_group(partners_to=self.user_employee.partner_id.ids)['id'])
channel_partner = channel.sudo().channel_last_seen_partner_ids.filtered(lambda channel_partner: channel_partner.partner_id == self.user_employee.partner_id)
join_call_values = channel_partner._rtc_join_call()
test_guest = self.env['mail.guest'].sudo().create({'name': "Test Guest"})
test_channel_partner = self.env['mail.channel.partner'].create({
'guest_id': test_guest.id,
'channel_id': channel.id,
})
test_session = self.env['mail.channel.rtc.session'].sudo().create({'channel_partner_id': test_channel_partner.id})
test_session.flush()
test_session._write({'write_date': fields.Datetime.now() - relativedelta(days=2)})
unused_ids = [9998, 9999]
self.env['bus.bus'].sudo().search([]).unlink()
with self.assertBus(
[
(self.cr.dbname, 'mail.guest', test_guest.id), # session ended
(self.cr.dbname, 'mail.channel', channel.id), # update list of sessions
],
[
{
'type': 'mail.channel.rtc.session/ended',
'payload': {
'sessionId': test_session.id,
},
},
{
'type': 'mail.channel/rtc_sessions_update',
'payload': {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': test_session.id}])],
},
},
],
):
current_rtc_sessions, outdated_rtc_sessions = channel_partner._rtc_sync_sessions(check_rtc_session_ids=[join_call_values['sessionId']] + unused_ids)
self.assertEqual(channel_partner.rtc_session_ids, current_rtc_sessions)
self.assertEqual(unused_ids, outdated_rtc_sessions.ids)
self.assertFalse(outdated_rtc_sessions.exists())
| 49.869702 | 31,767 |
733 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase
class TestUpdateNotification(TransactionCase):
def test_user_count(self):
ping_msg = self.env['publisher_warranty.contract'].with_context(active_test=False)._get_message()
user_count = self.env['res.users'].search_count([('active', '=', True)])
self.assertEqual(ping_msg.get('nbr_users'), user_count, 'Update Notification: Users count is badly computed in ping message')
share_user_count = self.env['res.users'].search_count([('active', '=', True), ('share', '=', True)])
self.assertEqual(ping_msg.get('nbr_share_users'), share_user_count, 'Update Notification: Portal Users count is badly computed in ping message')
| 66.636364 | 733 |
399 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class BaseModuleUninstall(models.TransientModel):
_inherit = "base.module.uninstall"
def _get_models(self):
# consider mail-thread models only
models = super(BaseModuleUninstall, self)._get_models()
return models.filtered('is_mail_thread')
| 30.692308 | 399 |
5,689 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _, Command
from odoo.exceptions import UserError
class MailResendMessage(models.TransientModel):
_name = 'mail.resend.message'
_description = 'Email resend wizard'
mail_message_id = fields.Many2one('mail.message', 'Message', readonly=True)
partner_ids = fields.One2many('mail.resend.partner', 'resend_wizard_id', string='Recipients')
notification_ids = fields.Many2many('mail.notification', string='Notifications', readonly=True)
has_cancel = fields.Boolean(compute='_compute_has_cancel')
partner_readonly = fields.Boolean(compute='_compute_partner_readonly')
@api.depends("partner_ids")
def _compute_has_cancel(self):
self.has_cancel = self.partner_ids.filtered(lambda p: not p.resend)
def _compute_partner_readonly(self):
self.partner_readonly = not self.env['res.partner'].check_access_rights('write', raise_exception=False)
@api.model
def default_get(self, fields):
rec = super(MailResendMessage, self).default_get(fields)
message_id = self._context.get('mail_message_to_resend')
if message_id:
mail_message_id = self.env['mail.message'].browse(message_id)
notification_ids = mail_message_id.notification_ids.filtered(lambda notif: notif.notification_type == 'email' and notif.notification_status in ('exception', 'bounce'))
partner_ids = [Command.create({
"partner_id": notif.res_partner_id.id,
"name": notif.res_partner_id.name,
"email": notif.res_partner_id.email,
"resend": True,
"message": notif.format_failure_reason(),
}) for notif in notification_ids]
has_user = any(notif.res_partner_id.user_ids for notif in notification_ids)
if has_user:
partner_readonly = not self.env['res.users'].check_access_rights('write', raise_exception=False)
else:
partner_readonly = not self.env['res.partner'].check_access_rights('write', raise_exception=False)
rec['partner_readonly'] = partner_readonly
rec['notification_ids'] = [Command.set(notification_ids.ids)]
rec['mail_message_id'] = mail_message_id.id
rec['partner_ids'] = partner_ids
else:
raise UserError(_('No message_id found in context'))
return rec
def resend_mail_action(self):
""" Process the wizard content and proceed with sending the related
email(s), rendering any template patterns on the fly if needed. """
for wizard in self:
"If a partner disappeared from partner list, we cancel the notification"
to_cancel = wizard.partner_ids.filtered(lambda p: not p.resend).mapped("partner_id")
to_send = wizard.partner_ids.filtered(lambda p: p.resend).mapped("partner_id")
notif_to_cancel = wizard.notification_ids.filtered(lambda notif: notif.notification_type == 'email' and notif.res_partner_id in to_cancel and notif.notification_status in ('exception', 'bounce'))
notif_to_cancel.sudo().write({'notification_status': 'canceled'})
if to_send:
message = wizard.mail_message_id
record = self.env[message.model].browse(message.res_id) if message.is_thread_message() else self.env['mail.thread']
email_partners_data = []
for pid, active, pshare, notif, groups in self.env['mail.followers']._get_recipient_data(None, 'comment', False, pids=to_send.ids):
if pid and notif == 'email' or not notif:
pdata = {'id': pid, 'share': pshare, 'active': active, 'notif': 'email', 'groups': groups or []}
if not pshare and notif: # has an user and is not shared, is therefore user
email_partners_data.append(dict(pdata, type='user'))
elif pshare and notif: # has an user and is shared, is therefore portal
email_partners_data.append(dict(pdata, type='portal'))
else: # has no user, is therefore customer
email_partners_data.append(dict(pdata, type='customer'))
record._notify_record_by_email(message, email_partners_data, check_existing=True, send_after_commit=False)
self.mail_message_id._notify_message_notification_update()
return {'type': 'ir.actions.act_window_close'}
def cancel_mail_action(self):
for wizard in self:
for notif in wizard.notification_ids:
notif.filtered(lambda notif: notif.notification_type == 'email' and notif.notification_status in ('exception', 'bounce')).sudo().write({'notification_status': 'canceled'})
wizard.mail_message_id._notify_message_notification_update()
return {'type': 'ir.actions.act_window_close'}
class PartnerResend(models.TransientModel):
_name = 'mail.resend.partner'
_description = 'Partner with additional information for mail resend'
partner_id = fields.Many2one('res.partner', string='Partner', required=True, ondelete='cascade')
name = fields.Char(related="partner_id.name", related_sudo=False, readonly=False)
email = fields.Char(related="partner_id.email", related_sudo=False, readonly=False)
resend = fields.Boolean(string="Send Again", default=True)
resend_wizard_id = fields.Many2one('mail.resend.message', string="Resend wizard")
message = fields.Char(string="Help message")
| 58.05102 | 5,689 |
1,826 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
class MailResendCancel(models.TransientModel):
_name = 'mail.resend.cancel'
_description = 'Dismiss notification for resend by model'
model = fields.Char(string='Model')
help_message = fields.Char(string='Help message', compute='_compute_help_message')
@api.depends('model')
def _compute_help_message(self):
for wizard in self:
wizard.help_message = _("Are you sure you want to discard %s mail delivery failures? You won't be able to re-send these mails later!") % (wizard._context.get('unread_counter'))
def cancel_resend_action(self):
author_id = self.env.user.partner_id.id
for wizard in self:
self._cr.execute("""
SELECT notif.id, mes.id
FROM mail_notification notif
JOIN mail_message mes
ON notif.mail_message_id = mes.id
WHERE notif.notification_type = 'email' AND notif.notification_status IN ('bounce', 'exception')
AND mes.model = %s
AND mes.author_id = %s
""", (wizard.model, author_id))
res = self._cr.fetchall()
notif_ids = [row[0] for row in res]
messages_ids = list(set([row[1] for row in res]))
if notif_ids:
self.env["mail.notification"].browse(notif_ids).sudo().write({'notification_status': 'canceled'})
self.env["mail.message"].browse(messages_ids)._notify_message_notification_update()
return {'type': 'ir.actions.act_window_close'}
| 49.351351 | 1,826 |
36,799 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import base64
import re
from odoo import _, api, fields, models, tools, Command
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import email_re
def _reopen(self, res_id, model, context=None):
# save original model in context, because selecting the list of available
# templates requires a model in context
context = dict(context or {}, default_model=model)
return {'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_id': res_id,
'res_model': self._name,
'target': 'new',
'context': context,
}
class MailComposer(models.TransientModel):
""" Generic message composition wizard. You may inherit from this wizard
at model and view levels to provide specific features.
The behavior of the wizard depends on the composition_mode field:
- 'comment': post on a record. The wizard is pre-populated via ``get_record_data``
- 'mass_mail': wizard in mass mailing mode where the mail details can
contain template placeholders that will be merged with actual data
before being sent to each recipient.
"""
_name = 'mail.compose.message'
_inherit = 'mail.composer.mixin'
_description = 'Email composition wizard'
_log_access = True
_batch_size = 500
@api.model
def default_get(self, fields):
""" Handle composition mode. Some details about context keys:
- comment: default mode, model and ID of a record the user comments
- default_model or active_model
- default_res_id or active_id
- mass_mail: model and IDs of records the user mass-mails
- active_ids: record IDs
- default_model or active_model
"""
result = super(MailComposer, self).default_get(fields)
# author
missing_author = 'author_id' in fields and 'author_id' not in result
missing_email_from = 'email_from' in fields and 'email_from' not in result
if missing_author or missing_email_from:
author_id, email_from = self.env['mail.thread']._message_compute_author(result.get('author_id'), result.get('email_from'), raise_exception=False)
if missing_email_from:
result['email_from'] = email_from
if missing_author:
result['author_id'] = author_id
if 'model' in fields and 'model' not in result:
result['model'] = self._context.get('active_model')
if 'res_id' in fields and 'res_id' not in result:
result['res_id'] = self._context.get('active_id')
if 'reply_to_mode' in fields and 'reply_to_mode' not in result and result.get('model'):
# doesn't support threading
if result['model'] not in self.env or not hasattr(self.env[result['model']], 'message_post'):
result['reply_to_mode'] = 'new'
if 'active_domain' in self._context: # not context.get() because we want to keep global [] domains
result['active_domain'] = '%s' % self._context.get('active_domain')
if result.get('composition_mode') == 'comment' and (set(fields) & set(['model', 'res_id', 'partner_ids', 'record_name', 'subject'])):
result.update(self.get_record_data(result))
# when being in new mode, create_uid is not granted -> ACLs issue may arise
if 'create_uid' in fields and 'create_uid' not in result:
result['create_uid'] = self.env.uid
filtered_result = dict((fname, result[fname]) for fname in result if fname in fields)
return filtered_result
def _partner_ids_domain(self):
return expression.OR([
[('type', '!=', 'private')],
[('id', 'in', self.env.context.get('default_partner_ids', []))],
])
# content
subject = fields.Char('Subject', compute=False)
body = fields.Html('Contents', render_engine='qweb', compute=False, default='', sanitize_style=True)
parent_id = fields.Many2one(
'mail.message', 'Parent Message', index=True, ondelete='set null',
help="Initial thread message.")
template_id = fields.Many2one(
'mail.template', 'Use template', index=True,
domain="[('model', '=', model)]")
attachment_ids = fields.Many2many(
'ir.attachment', 'mail_compose_message_ir_attachments_rel',
'wizard_id', 'attachment_id', 'Attachments')
layout = fields.Char('Layout', copy=False) # xml id of layout
add_sign = fields.Boolean(default=True)
# origin
email_from = fields.Char('From', help="Email address of the sender. This field is set when no matching partner is found and replaces the author_id field in the chatter.")
author_id = fields.Many2one(
'res.partner', 'Author', index=True,
help="Author of the message. If not set, email_from may hold an email address that did not match any partner.")
# composition
composition_mode = fields.Selection(selection=[
('comment', 'Post on a document'),
('mass_mail', 'Email Mass Mailing'),
('mass_post', 'Post on Multiple Documents')], string='Composition mode', default='comment')
model = fields.Char('Related Document Model', index=True)
res_id = fields.Integer('Related Document ID', index=True)
record_name = fields.Char('Message Record Name', help="Name get of the related document.")
use_active_domain = fields.Boolean('Use active domain')
active_domain = fields.Text('Active domain', readonly=True)
# characteristics
message_type = fields.Selection([
('comment', 'Comment'),
('notification', 'System notification')],
'Type', required=True, default='comment',
help="Message type: email for email message, notification for system "
"message, comment for other messages such as user replies")
subtype_id = fields.Many2one(
'mail.message.subtype', 'Subtype', ondelete='set null', index=True,
default=lambda self: self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment'))
mail_activity_type_id = fields.Many2one(
'mail.activity.type', 'Mail Activity Type',
index=True, ondelete='set null')
# destination
reply_to = fields.Char('Reply To', help='Reply email address. Setting the reply_to bypasses the automatic thread creation.')
reply_to_force_new = fields.Boolean(
string='Considers answers as new thread',
help='Manage answers as new incoming emails instead of replies going to the same thread.')
reply_to_mode = fields.Selection([
('update', 'Log in the original discussion thread'),
('new', 'Redirect to another email address')],
string='Replies', compute='_compute_reply_to_mode', inverse='_inverse_reply_to_mode',
help="Original Discussion: Answers go in the original document discussion thread. \n Another Email Address: Answers go to the email address mentioned in the tracking message-id instead of original document discussion thread. \n This has an impact on the generated message-id.")
is_log = fields.Boolean('Log an Internal Note',
help='Whether the message is an internal note (comment mode only)')
partner_ids = fields.Many2many(
'res.partner', 'mail_compose_message_res_partner_rel',
'wizard_id', 'partner_id', 'Additional Contacts',
domain=_partner_ids_domain)
# mass mode options
notify = fields.Boolean('Notify followers', help='Notify followers of the document (mass post only)')
auto_delete = fields.Boolean('Delete Emails',
help='This option permanently removes any track of email after it\'s been sent, including from the Technical menu in the Settings, in order to preserve storage space of your Odoo database.')
auto_delete_message = fields.Boolean('Delete Message Copy', help='Do not keep a copy of the email in the document communication history (mass mailing only)')
mail_server_id = fields.Many2one('ir.mail_server', 'Outgoing mail server')
@api.depends('reply_to_force_new')
def _compute_reply_to_mode(self):
for composer in self:
composer.reply_to_mode = 'new' if composer.reply_to_force_new else 'update'
def _inverse_reply_to_mode(self):
for composer in self:
composer.reply_to_force_new = composer.reply_to_mode == 'new'
# Overrides of mail.render.mixin
@api.depends('model')
def _compute_render_model(self):
for composer in self:
composer.render_model = composer.model
# Onchanges
@api.onchange('template_id')
def _onchange_template_id_wrapper(self):
self.ensure_one()
values = self._onchange_template_id(self.template_id.id, self.composition_mode, self.model, self.res_id)['value']
for fname, value in values.items():
setattr(self, fname, value)
def _compute_can_edit_body(self):
"""Can edit the body if we are not in "mass_mail" mode because the template is
rendered before it's modified.
"""
non_mass_mail = self.filtered(lambda m: m.composition_mode != 'mass_mail')
non_mass_mail.can_edit_body = True
super(MailComposer, self - non_mass_mail)._compute_can_edit_body()
@api.model
def get_record_data(self, values):
""" Returns a defaults-like dict with initial values for the composition
wizard when sending an email related a previous email (parent_id) or
a document (model, res_id). This is based on previously computed default
values. """
result, subject = {}, False
if values.get('parent_id'):
parent = self.env['mail.message'].browse(values.get('parent_id'))
result['record_name'] = parent.record_name
subject = tools.ustr(parent.subject or parent.record_name or '')
if not values.get('model'):
result['model'] = parent.model
if not values.get('res_id'):
result['res_id'] = parent.res_id
partner_ids = values.get('partner_ids', list()) + parent.partner_ids.ids
result['partner_ids'] = partner_ids
elif values.get('model') and values.get('res_id'):
doc_name_get = self.env[values.get('model')].browse(values.get('res_id')).name_get()
result['record_name'] = doc_name_get and doc_name_get[0][1] or ''
subject = tools.ustr(result['record_name'])
re_prefix = _('Re:')
if subject and not (subject.startswith('Re:') or subject.startswith(re_prefix)):
subject = "%s %s" % (re_prefix, subject)
result['subject'] = subject
return result
# ------------------------------------------------------------
# CRUD / ORM
# ------------------------------------------------------------
@api.autovacuum
def _gc_lost_attachments(self):
""" Garbage collect lost mail attachments. Those are attachments
- linked to res_model 'mail.compose.message', the composer wizard
- with res_id 0, because they were created outside of an existing
wizard (typically user input through Chatter or reports
created on-the-fly by the templates)
- unused since at least one day (create_date and write_date)
"""
limit_date = fields.Datetime.subtract(fields.Datetime.now(), days=1)
self.env['ir.attachment'].search([
('res_model', '=', self._name),
('res_id', '=', 0),
('create_date', '<', limit_date),
('write_date', '<', limit_date)]
).unlink()
# ------------------------------------------------------------
# ACTIONS
# ------------------------------------------------------------
def action_send_mail(self):
""" Used for action button that do not accept arguments. """
self._action_send_mail(auto_commit=False)
return {'type': 'ir.actions.act_window_close'}
def _action_send_mail(self, auto_commit=False):
""" Process the wizard content and proceed with sending the related
email(s), rendering any template patterns on the fly if needed. """
notif_layout = self._context.get('custom_layout')
# Several custom layouts make use of the model description at rendering, e.g. in the
# 'View <document>' button. Some models are used for different business concepts, such as
# 'purchase.order' which is used for a RFQ and and PO. To avoid confusion, we must use a
# different wording depending on the state of the object.
# Therefore, we can set the description in the context from the beginning to avoid falling
# back on the regular display_name retrieved in '_notify_prepare_template_context'.
model_description = self._context.get('model_description')
for wizard in self:
# Duplicate attachments linked to the email.template.
# Indeed, basic mail.compose.message wizard duplicates attachments in mass
# mailing mode. But in 'single post' mode, attachments of an email template
# also have to be duplicated to avoid changing their ownership.
if wizard.attachment_ids and wizard.composition_mode != 'mass_mail' and wizard.template_id:
new_attachment_ids = []
for attachment in wizard.attachment_ids:
if attachment in wizard.template_id.attachment_ids:
new_attachment_ids.append(attachment.copy({'res_model': 'mail.compose.message', 'res_id': wizard.id}).id)
else:
new_attachment_ids.append(attachment.id)
new_attachment_ids.reverse()
wizard.write({'attachment_ids': [Command.set(new_attachment_ids)]})
# Mass Mailing
mass_mode = wizard.composition_mode in ('mass_mail', 'mass_post')
ActiveModel = self.env[wizard.model] if wizard.model and hasattr(self.env[wizard.model], 'message_post') else self.env['mail.thread']
if wizard.composition_mode == 'mass_post':
# do not send emails directly but use the queue instead
# add context key to avoid subscribing the author
ActiveModel = ActiveModel.with_context(mail_notify_force_send=False, mail_create_nosubscribe=True)
# wizard works in batch mode: [res_id] or active_ids or active_domain
if mass_mode and wizard.use_active_domain and wizard.model:
res_ids = self.env[wizard.model].search(ast.literal_eval(wizard.active_domain)).ids
elif mass_mode and wizard.model and self._context.get('active_ids'):
res_ids = self._context['active_ids']
else:
res_ids = [wizard.res_id]
batch_size = int(self.env['ir.config_parameter'].sudo().get_param('mail.batch_size')) or self._batch_size
sliced_res_ids = [res_ids[i:i + batch_size] for i in range(0, len(res_ids), batch_size)]
if wizard.composition_mode == 'mass_mail' or wizard.is_log or (wizard.composition_mode == 'mass_post' and not wizard.notify): # log a note: subtype is False
subtype_id = False
elif wizard.subtype_id:
subtype_id = wizard.subtype_id.id
else:
subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment')
for res_ids in sliced_res_ids:
# mass mail mode: mail are sudo-ed, as when going through get_mail_values
# standard access rights on related records will be checked when browsing them
# to compute mail values. If people have access to the records they have rights
# to create lots of emails in sudo as it is consdiered as a technical model.
batch_mails_sudo = self.env['mail.mail'].sudo()
all_mail_values = wizard.get_mail_values(res_ids)
for res_id, mail_values in all_mail_values.items():
if wizard.composition_mode == 'mass_mail':
batch_mails_sudo |= self.env['mail.mail'].sudo().create(mail_values)
else:
post_params = dict(
message_type=wizard.message_type,
subtype_id=subtype_id,
email_layout_xmlid=notif_layout,
add_sign=not bool(wizard.template_id),
mail_auto_delete=wizard.template_id.auto_delete if wizard.template_id else self._context.get('mail_auto_delete', True),
model_description=model_description)
post_params.update(mail_values)
if ActiveModel._name == 'mail.thread':
if wizard.model:
post_params['model'] = wizard.model
post_params['res_id'] = res_id
if not ActiveModel.message_notify(**post_params):
# if message_notify returns an empty record set, no recipients where found.
raise UserError(_("No recipient found."))
else:
ActiveModel.browse(res_id).message_post(**post_params)
if wizard.composition_mode == 'mass_mail':
batch_mails_sudo.send(auto_commit=auto_commit)
def action_save_as_template(self):
""" hit save as template button: current form value will be a new
template attached to the current document. """
for record in self:
model = self.env['ir.model']._get(record.model or 'mail.message')
model_name = model.name or ''
template_name = "%s: %s" % (model_name, tools.ustr(record.subject))
values = {
'name': template_name,
'subject': record.subject or False,
'body_html': record.body or False,
'model_id': model.id or False,
'use_default_to': True,
}
template = self.env['mail.template'].create(values)
if record.attachment_ids:
attachments = self.env['ir.attachment'].sudo().browse(record.attachment_ids.ids).filtered(
lambda a: a.res_model == 'mail.compose.message' and a.create_uid.id == self._uid)
if attachments:
attachments.write({'res_model': template._name, 'res_id': template.id})
template.attachment_ids |= record.attachment_ids
# generate the saved template
record.write({'template_id': template.id})
record._onchange_template_id_wrapper()
return _reopen(self, record.id, record.model, context=self._context)
# ------------------------------------------------------------
# RENDERING / VALUES GENERATION
# ------------------------------------------------------------
def get_mail_values(self, res_ids):
"""Generate the values that will be used by send_mail to create mail_messages
or mail_mails. """
self.ensure_one()
results = dict.fromkeys(res_ids, False)
rendered_values = {}
mass_mail_mode = self.composition_mode == 'mass_mail'
# render all template-based value at once
if mass_mail_mode and self.model:
rendered_values = self.render_message(res_ids)
# compute alias-based reply-to in batch
reply_to_value = dict.fromkeys(res_ids, None)
if mass_mail_mode and not self.reply_to_force_new:
records = self.env[self.model].browse(res_ids)
reply_to_value = records._notify_get_reply_to(default=False)
# when having no specific reply-to, fetch rendered email_from value
for res_id, reply_to in reply_to_value.items():
if not reply_to:
reply_to_value[res_id] = rendered_values.get(res_id, {}).get('email_from', False)
for res_id in res_ids:
# static wizard (mail.message) values
mail_values = {
'subject': self.subject,
'body': self.body or '',
'parent_id': self.parent_id and self.parent_id.id,
'partner_ids': [partner.id for partner in self.partner_ids],
'attachment_ids': [attach.id for attach in self.attachment_ids],
'author_id': self.author_id.id,
'email_from': self.email_from,
'record_name': self.record_name,
'reply_to_force_new': self.reply_to_force_new,
'mail_server_id': self.mail_server_id.id,
'mail_activity_type_id': self.mail_activity_type_id.id,
}
# mass mailing: rendering override wizard static values
if mass_mail_mode and self.model:
record = self.env[self.model].browse(res_id)
mail_values['headers'] = record._notify_email_headers()
# keep a copy unless specifically requested, reset record name (avoid browsing records)
mail_values.update(is_notification=not self.auto_delete_message, model=self.model, res_id=res_id, record_name=False)
# auto deletion of mail_mail
if self.auto_delete or self.template_id.auto_delete:
mail_values['auto_delete'] = True
# rendered values using template
email_dict = rendered_values[res_id]
mail_values['partner_ids'] += email_dict.pop('partner_ids', [])
mail_values.update(email_dict)
if not self.reply_to_force_new:
mail_values.pop('reply_to')
if reply_to_value.get(res_id):
mail_values['reply_to'] = reply_to_value[res_id]
if self.reply_to_force_new and not mail_values.get('reply_to'):
mail_values['reply_to'] = mail_values['email_from']
# mail_mail values: body -> body_html, partner_ids -> recipient_ids
mail_values['body_html'] = mail_values.get('body', '')
mail_values['recipient_ids'] = [Command.link(id) for id in mail_values.pop('partner_ids', [])]
# process attachments: should not be encoded before being processed by message_post / mail_mail create
mail_values['attachments'] = [(name, base64.b64decode(enc_cont)) for name, enc_cont in email_dict.pop('attachments', list())]
attachment_ids = []
for attach_id in mail_values.pop('attachment_ids'):
new_attach_id = self.env['ir.attachment'].browse(attach_id).copy({'res_model': self._name, 'res_id': self.id})
attachment_ids.append(new_attach_id.id)
attachment_ids.reverse()
mail_values['attachment_ids'] = self.env['mail.thread'].with_context(attached_to=record)._message_post_process_attachments(
mail_values.pop('attachments', []),
attachment_ids,
{'model': 'mail.message', 'res_id': 0}
)['attachment_ids']
results[res_id] = mail_values
results = self._process_state(results)
return results
def _process_recipient_values(self, mail_values_dict):
# Preprocess res.partners to batch-fetch from db if recipient_ids is present
# it means they are partners (the only object to fill get_default_recipient this way)
recipient_pids = [
recipient_command[1]
for mail_values in mail_values_dict.values()
# recipient_ids is a list of x2m command tuples at this point
for recipient_command in mail_values.get('recipient_ids') or []
if recipient_command[1]
]
recipient_emails = {
p.id: p.email
for p in self.env['res.partner'].browse(set(recipient_pids))
} if recipient_pids else {}
recipients_info = {}
for record_id, mail_values in mail_values_dict.items():
mail_to = []
if mail_values.get('email_to'):
mail_to += email_re.findall(mail_values['email_to'])
# if unrecognized email in email_to -> keep it as used for further processing
if not mail_to:
mail_to.append(mail_values['email_to'])
# add email from recipients (res.partner)
mail_to += [
recipient_emails[recipient_command[1]]
for recipient_command in mail_values.get('recipient_ids') or []
if recipient_command[1]
]
mail_to = list(set(mail_to))
recipients_info[record_id] = {
'mail_to': mail_to,
'mail_to_normalized': [
tools.email_normalize(mail)
for mail in mail_to
if tools.email_normalize(mail)
]
}
return recipients_info
def _process_state(self, mail_values_dict):
recipients_info = self._process_recipient_values(mail_values_dict)
blacklist_ids = self._get_blacklist_record_ids(mail_values_dict, recipients_info)
optout_emails = self._get_optout_emails(mail_values_dict)
done_emails = self._get_done_emails(mail_values_dict)
# in case of an invoice e.g.
mailing_document_based = self.env.context.get('mailing_document_based')
for record_id, mail_values in mail_values_dict.items():
recipients = recipients_info[record_id]
# when having more than 1 recipient: we cannot really decide when a single
# email is linked to several to -> skip that part. Mass mailing should
# anyway always have a single recipient per record as this is default behavior.
if len(recipients['mail_to']) > 1:
continue
mail_to = recipients['mail_to'][0] if recipients['mail_to'] else ''
mail_to_normalized = recipients['mail_to_normalized'][0] if recipients['mail_to_normalized'] else ''
# prevent sending to blocked addresses that were included by mistake
# blacklisted or optout or duplicate -> cancel
if record_id in blacklist_ids:
mail_values['state'] = 'cancel'
mail_values['failure_type'] = 'mail_bl'
# Do not post the mail into the recipient's chatter
mail_values['is_notification'] = False
elif optout_emails and mail_to in optout_emails:
mail_values['state'] = 'cancel'
mail_values['failure_type'] = 'mail_optout'
elif done_emails and mail_to in done_emails and not mailing_document_based:
mail_values['state'] = 'cancel'
mail_values['failure_type'] = 'mail_dup'
# void of falsy values -> error
elif not mail_to:
mail_values['state'] = 'cancel'
mail_values['failure_type'] = 'mail_email_missing'
elif not mail_to_normalized or not email_re.findall(mail_to):
mail_values['state'] = 'cancel'
mail_values['failure_type'] = 'mail_email_invalid'
elif done_emails is not None and not mailing_document_based:
done_emails.append(mail_to)
return mail_values_dict
def _get_blacklist_record_ids(self, mail_values_dict, recipients_info=None):
"""Get record ids for which at least one recipient is black listed.
:param dict mail_values_dict: mail values per record id
:param dict recipients_info: optional dict of recipients info per record id
Optional for backward compatibility but without, result can be incomplete.
:return set: record ids with at least one black listed recipient.
"""
blacklisted_rec_ids = set()
if self.composition_mode == 'mass_mail':
self.env['mail.blacklist'].flush(['email'])
self._cr.execute("SELECT email FROM mail_blacklist WHERE active=true")
blacklist = {x[0] for x in self._cr.fetchall()}
if not blacklist:
return blacklisted_rec_ids
if issubclass(type(self.env[self.model]), self.pool['mail.thread.blacklist']):
targets = self.env[self.model].browse(mail_values_dict.keys()).read(['email_normalized'])
# First extract email from recipient before comparing with blacklist
blacklisted_rec_ids.update(target['id'] for target in targets
if target['email_normalized'] in blacklist)
elif recipients_info:
# Note that we exclude the record if at least one recipient is blacklisted (-> even if not all)
# But as commented above: Mass mailing should always have a single recipient per record.
blacklisted_rec_ids.update(res_id for res_id, recipient_info in recipients_info.items()
if blacklist & set(recipient_info['mail_to_normalized']))
return blacklisted_rec_ids
def _get_done_emails(self, mail_values_dict):
return []
def _get_optout_emails(self, mail_values_dict):
return []
def _onchange_template_id(self, template_id, composition_mode, model, res_id):
""" - mass_mailing: we cannot render, so return the template values
- normal mode: return rendered values
/!\ for x2many field, this onchange return command instead of ids
"""
if template_id and composition_mode == 'mass_mail':
template = self.env['mail.template'].browse(template_id)
fields = ['subject', 'body_html', 'email_from', 'reply_to', 'mail_server_id']
values = dict((field, getattr(template, field)) for field in fields if getattr(template, field))
if template.attachment_ids:
values['attachment_ids'] = [att.id for att in template.attachment_ids]
if template.mail_server_id:
values['mail_server_id'] = template.mail_server_id.id
elif template_id:
values = self.generate_email_for_composer(
template_id, [res_id],
['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to', 'attachment_ids', 'mail_server_id']
)[res_id]
# transform attachments into attachment_ids; not attached to the document because this will
# be done further in the posting process, allowing to clean database if email not send
attachment_ids = []
Attachment = self.env['ir.attachment']
for attach_fname, attach_datas in values.pop('attachments', []):
data_attach = {
'name': attach_fname,
'datas': attach_datas,
'res_model': 'mail.compose.message',
'res_id': 0,
'type': 'binary', # override default_type from context, possibly meant for another model!
}
attachment_ids.append(Attachment.create(data_attach).id)
if values.get('attachment_ids', []) or attachment_ids:
values['attachment_ids'] = [Command.set(values.get('attachment_ids', []) + attachment_ids)]
else:
default_values = self.with_context(default_composition_mode=composition_mode, default_model=model, default_res_id=res_id).default_get(['composition_mode', 'model', 'res_id', 'parent_id', 'partner_ids', 'subject', 'body', 'email_from', 'reply_to', 'attachment_ids', 'mail_server_id'])
values = dict((key, default_values[key]) for key in ['subject', 'body', 'partner_ids', 'email_from', 'reply_to', 'attachment_ids', 'mail_server_id'] if key in default_values)
if values.get('body_html'):
values['body'] = values.pop('body_html')
# This onchange should return command instead of ids for x2many field.
values = self._convert_to_write(values)
return {'value': values}
def render_message(self, res_ids):
"""Generate template-based values of wizard, for the document records given
by res_ids. This method is meant to be inherited by email_template that
will produce a more complete dictionary, using qweb templates.
Each template is generated for all res_ids, allowing to parse the template
once, and render it multiple times. This is useful for mass mailing where
template rendering represent a significant part of the process.
Default recipients are also computed, based on mail_thread method
_message_get_default_recipients. This allows to ensure a mass mailing has
always some recipients specified.
:param browse wizard: current mail.compose.message browse record
:param list res_ids: list of record ids
:return dict results: for each res_id, the generated template values for
subject, body, email_from and reply_to
"""
self.ensure_one()
multi_mode = True
if isinstance(res_ids, int):
multi_mode = False
res_ids = [res_ids]
subjects = self._render_field('subject', res_ids, options={"render_safe": True})
# We want to preserve comments in emails so as to keep mso conditionals
bodies = self.with_context(preserve_comments=self.composition_mode == 'mass_mail')._render_field('body', res_ids, post_process=True)
emails_from = self._render_field('email_from', res_ids)
replies_to = self._render_field('reply_to', res_ids)
default_recipients = {}
if not self.partner_ids:
records = self.env[self.model].browse(res_ids).sudo()
default_recipients = records._message_get_default_recipients()
results = dict.fromkeys(res_ids, False)
for res_id in res_ids:
results[res_id] = {
'subject': subjects[res_id],
'body': bodies[res_id],
'email_from': emails_from[res_id],
'reply_to': replies_to[res_id],
}
results[res_id].update(default_recipients.get(res_id, dict()))
# generate template-based values
if self.template_id:
template_values = self.generate_email_for_composer(
self.template_id.id, res_ids,
['email_to', 'partner_to', 'email_cc', 'attachment_ids', 'mail_server_id'])
else:
template_values = {}
for res_id in res_ids:
if template_values.get(res_id):
# recipients are managed by the template
results[res_id].pop('partner_ids', None)
results[res_id].pop('email_to', None)
results[res_id].pop('email_cc', None)
# remove attachments from template values as they should not be rendered
template_values[res_id].pop('attachment_ids', None)
else:
template_values[res_id] = dict()
# update template values by composer values
template_values[res_id].update(results[res_id])
return multi_mode and template_values or template_values[res_ids[0]]
@api.model
def generate_email_for_composer(self, template_id, res_ids, fields):
""" Call email_template.generate_email(), get fields relevant for
mail.compose.message, transform email_cc and email_to into partner_ids """
multi_mode = True
if isinstance(res_ids, int):
multi_mode = False
res_ids = [res_ids]
returned_fields = fields + ['partner_ids', 'attachments']
values = dict.fromkeys(res_ids, False)
template_values = self.env['mail.template'].with_context(tpl_partners_only=True).browse(template_id).generate_email(res_ids, fields)
for res_id in res_ids:
res_id_values = dict((field, template_values[res_id][field]) for field in returned_fields if template_values[res_id].get(field))
res_id_values['body'] = res_id_values.pop('body_html', '')
values[res_id] = res_id_values
return multi_mode and values or values[res_ids[0]]
| 53.331884 | 36,799 |
573 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
class MergePartnerAutomatic(models.TransientModel):
_inherit = 'base.partner.merge.automatic.wizard'
def _log_merge_operation(self, src_partners, dst_partner):
super(MergePartnerAutomatic, self)._log_merge_operation(src_partners, dst_partner)
dst_partner.message_post(body='%s %s' % (_("Merged with the following partners:"), ", ".join('%s <%s> (ID %s)' % (p.name, p.email or 'n/a', p.id) for p in src_partners)))
| 47.75 | 573 |
444 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class MailBlacklistRemove(models.TransientModel):
_name = 'mail.blacklist.remove'
_description = 'Remove email from blacklist wizard'
email = fields.Char(name="Email", readonly=True, required=True)
reason = fields.Char(name="Reason")
def action_unblacklist_apply(self):
return self.env['mail.blacklist'].action_remove_with_reason(self.email, self.reason)
| 31.714286 | 444 |
4,755 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import etree
from lxml.html import builder as html
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class Invite(models.TransientModel):
""" Wizard to invite partners (or channels) and make them followers. """
_name = 'mail.wizard.invite'
_description = 'Invite wizard'
@api.model
def default_get(self, fields):
result = super(Invite, self).default_get(fields)
if 'message' not in fields:
return result
user_name = self.env.user.display_name
model = result.get('res_model')
res_id = result.get('res_id')
if model and res_id:
document = self.env['ir.model']._get(model).display_name
title = self.env[model].browse(res_id).display_name
msg_fmt = _('%(user_name)s invited you to follow %(document)s document: %(title)s')
else:
msg_fmt = _('%(user_name)s invited you to follow a new document.')
text = msg_fmt % locals()
message = html.DIV(
html.P(_('Hello,')),
html.P(text)
)
result['message'] = etree.tostring(message)
return result
res_model = fields.Char('Related Document Model', required=True, index=True, help='Model of the followed resource')
res_id = fields.Integer('Related Document ID', index=True, help='Id of the followed resource')
partner_ids = fields.Many2many('res.partner', string='Recipients', help="List of partners that will be added as follower of the current document.",
domain=[('type', '!=', 'private')])
message = fields.Html('Message')
send_mail = fields.Boolean('Send Email', default=True, help="If checked, the partners will receive an email warning they have been added in the document's followers.")
def add_followers(self):
if not self.env.user.email:
raise UserError(_("Unable to post message, please configure the sender's email address."))
email_from = self.env.user.email_formatted
for wizard in self:
Model = self.env[wizard.res_model]
document = Model.browse(wizard.res_id)
# filter partner_ids to get the new followers, to avoid sending email to already following partners
new_partners = wizard.partner_ids - document.sudo().message_partner_ids
document.message_subscribe(partner_ids=new_partners.ids)
model_name = self.env['ir.model']._get(wizard.res_model).display_name
# send an email if option checked and if a message exists (do not send void emails)
if wizard.send_mail and wizard.message and not wizard.message == '<br>': # when deleting the message, cleditor keeps a <br>
message = self.env['mail.message'].create({
'subject': _('Invitation to follow %(document_model)s: %(document_name)s', document_model=model_name, document_name=document.display_name),
'body': wizard.message,
'record_name': document.display_name,
'email_from': email_from,
'reply_to': email_from,
'model': wizard.res_model,
'res_id': wizard.res_id,
'reply_to_force_new': True,
'add_sign': True,
})
partners_data = []
recipient_data = self.env['mail.followers']._get_recipient_data(document, 'comment', False, pids=new_partners.ids)
for pid, active, pshare, notif, groups in recipient_data:
pdata = {'id': pid, 'share': pshare, 'active': active, 'notif': 'email', 'groups': groups or []}
if not pshare and notif: # has an user and is not shared, is therefore user
partners_data.append(dict(pdata, type='user'))
elif pshare and notif: # has an user and is shared, is therefore portal
partners_data.append(dict(pdata, type='portal'))
else: # has no user, is therefore customer
partners_data.append(dict(pdata, type='customer'))
document._notify_record_by_email(message, partners_data, send_after_commit=False)
# in case of failure, the web client must know the message was
# deleted to discard the related failure notification
self.env['bus.bus']._sendone(self.env.user.partner_id, 'mail.message/delete', {'message_ids': message.ids})
message.unlink()
return {'type': 'ir.actions.act_window_close'}
| 53.426966 | 4,755 |
4,904 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.exceptions import UserError
class MailTemplatePreview(models.TransientModel):
_name = 'mail.template.preview'
_description = 'Email Template Preview'
_MAIL_TEMPLATE_FIELDS = ['subject', 'body_html', 'email_from', 'email_to',
'email_cc', 'reply_to', 'scheduled_date', 'attachment_ids']
@api.model
def _selection_target_model(self):
return [(model.model, model.name) for model in self.env['ir.model'].sudo().search([])]
@api.model
def _selection_languages(self):
return self.env['res.lang'].get_installed()
@api.model
def default_get(self, fields):
result = super(MailTemplatePreview, self).default_get(fields)
if not result.get('mail_template_id') or 'resource_ref' not in fields:
return result
mail_template = self.env['mail.template'].browse(result['mail_template_id']).sudo()
model = mail_template.model
res = self.env[model].search([], limit=1)
if res:
result['resource_ref'] = '%s,%s' % (model, res.id)
return result
mail_template_id = fields.Many2one('mail.template', string='Related Mail Template', required=True)
model_id = fields.Many2one('ir.model', string='Targeted model', related="mail_template_id.model_id")
resource_ref = fields.Reference(string='Record', selection='_selection_target_model')
lang = fields.Selection(_selection_languages, string='Template Preview Language')
no_record = fields.Boolean('No Record', compute='_compute_no_record')
error_msg = fields.Char('Error Message', readonly=True)
# Fields same than the mail.template model, computed with resource_ref and lang
subject = fields.Char('Subject', compute='_compute_mail_template_fields')
email_from = fields.Char('From', compute='_compute_mail_template_fields', help="Sender address")
email_to = fields.Char('To', compute='_compute_mail_template_fields',
help="Comma-separated recipient addresses")
email_cc = fields.Char('Cc', compute='_compute_mail_template_fields', help="Carbon copy recipients")
reply_to = fields.Char('Reply-To', compute='_compute_mail_template_fields', help="Preferred response address")
scheduled_date = fields.Char('Scheduled Date', compute='_compute_mail_template_fields',
help="The queue manager will send the email after the date")
body_html = fields.Html('Body', compute='_compute_mail_template_fields', sanitize=False)
attachment_ids = fields.Many2many('ir.attachment', 'Attachments', compute='_compute_mail_template_fields')
# Extra fields info generated by generate_email
partner_ids = fields.Many2many('res.partner', string='Recipients', compute='_compute_mail_template_fields')
@api.depends('model_id')
def _compute_no_record(self):
for preview, preview_sudo in zip(self, self.sudo()):
model_id = preview_sudo.model_id
preview.no_record = not model_id or not self.env[model_id.model].search_count([])
@api.depends('lang', 'resource_ref')
def _compute_mail_template_fields(self):
""" Preview the mail template (body, subject, ...) depending of the language and
the record reference, more precisely the record id for the defined model of the mail template.
If no record id is selectable/set, the inline_template placeholders won't be replace in the display information. """
copy_depends_values = {'lang': self.lang}
mail_template = self.mail_template_id.with_context(lang=self.lang)
try:
if not self.resource_ref:
self._set_mail_attributes()
else:
copy_depends_values['resource_ref'] = '%s,%s' % (self.resource_ref._name, self.resource_ref.id)
mail_values = mail_template.with_context(template_preview_lang=self.lang).generate_email(
self.resource_ref.id, self._MAIL_TEMPLATE_FIELDS + ['partner_to'])
self._set_mail_attributes(values=mail_values)
self.error_msg = False
except UserError as user_error:
self._set_mail_attributes()
self.error_msg = user_error.args[0]
finally:
# Avoid to be change by a invalidate_cache call (in generate_mail), e.g. Quotation / Order report
for key, value in copy_depends_values.items():
self[key] = value
def _set_mail_attributes(self, values=None):
for field in self._MAIL_TEMPLATE_FIELDS:
field_value = values.get(field, False) if values else self.mail_template_id[field]
self[field] = field_value
self.partner_ids = values.get('partner_ids', False) if values else False
| 55.727273 | 4,904 |
5,508 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import logging
import requests
import werkzeug.urls
from ast import literal_eval
from odoo import api, release, SUPERUSER_ID
from odoo.exceptions import UserError
from odoo.models import AbstractModel
from odoo.tools.translate import _
from odoo.tools import config, misc, ustr
_logger = logging.getLogger(__name__)
class PublisherWarrantyContract(AbstractModel):
_name = "publisher_warranty.contract"
_description = 'Publisher Warranty Contract'
@api.model
def _get_message(self):
Users = self.env['res.users']
IrParamSudo = self.env['ir.config_parameter'].sudo()
dbuuid = IrParamSudo.get_param('database.uuid')
db_create_date = IrParamSudo.get_param('database.create_date')
limit_date = datetime.datetime.now()
limit_date = limit_date - datetime.timedelta(15)
limit_date_str = limit_date.strftime(misc.DEFAULT_SERVER_DATETIME_FORMAT)
nbr_users = Users.search_count([('active', '=', True)])
nbr_active_users = Users.search_count([("login_date", ">=", limit_date_str), ('active', '=', True)])
nbr_share_users = 0
nbr_active_share_users = 0
if "share" in Users._fields:
nbr_share_users = Users.search_count([("share", "=", True), ('active', '=', True)])
nbr_active_share_users = Users.search_count([("share", "=", True), ("login_date", ">=", limit_date_str), ('active', '=', True)])
user = self.env.user
domain = [('application', '=', True), ('state', 'in', ['installed', 'to upgrade', 'to remove'])]
apps = self.env['ir.module.module'].sudo().search_read(domain, ['name'])
enterprise_code = IrParamSudo.get_param('database.enterprise_code')
web_base_url = IrParamSudo.get_param('web.base.url')
msg = {
"dbuuid": dbuuid,
"nbr_users": nbr_users,
"nbr_active_users": nbr_active_users,
"nbr_share_users": nbr_share_users,
"nbr_active_share_users": nbr_active_share_users,
"dbname": self._cr.dbname,
"db_create_date": db_create_date,
"version": release.version,
"language": user.lang,
"web_base_url": web_base_url,
"apps": [app['name'] for app in apps],
"enterprise_code": enterprise_code,
}
if user.partner_id.company_id:
company_id = user.partner_id.company_id
msg.update(company_id.read(["name", "email", "phone"])[0])
return msg
@api.model
def _get_sys_logs(self):
"""
Utility method to send a publisher warranty get logs messages.
"""
msg = self._get_message()
arguments = {'arg0': ustr(msg), "action": "update"}
url = config.get("publisher_warranty_url")
r = requests.post(url, data=arguments, timeout=30)
r.raise_for_status()
return literal_eval(r.text)
def update_notification(self, cron_mode=True):
"""
Send a message to Odoo's publisher warranty server to check the
validity of the contracts, get notifications, etc...
@param cron_mode: If true, catch all exceptions (appropriate for usage in a cron).
@type cron_mode: boolean
"""
try:
try:
result = self._get_sys_logs()
except Exception:
if cron_mode: # we don't want to see any stack trace in cron
return False
_logger.debug("Exception while sending a get logs messages", exc_info=1)
raise UserError(_("Error during communication with the publisher warranty server."))
# old behavior based on res.log; now on mail.message, that is not necessarily installed
user = self.env['res.users'].sudo().browse(SUPERUSER_ID)
poster = self.sudo().env.ref('mail.channel_all_employees')
if not (poster and poster.exists()):
if not user.exists():
return True
poster = user
for message in result["messages"]:
try:
poster.message_post(body=message, subtype_xmlid='mail.mt_comment', partner_ids=[user.partner_id.id])
except Exception:
pass
if result.get('enterprise_info'):
# Update expiration date
set_param = self.env['ir.config_parameter'].sudo().set_param
set_param('database.expiration_date', result['enterprise_info'].get('expiration_date'))
set_param('database.expiration_reason', result['enterprise_info'].get('expiration_reason', 'trial'))
set_param('database.enterprise_code', result['enterprise_info'].get('enterprise_code'))
set_param('database.already_linked_subscription_url', result['enterprise_info'].get('database_already_linked_subscription_url'))
set_param('database.already_linked_email', result['enterprise_info'].get('database_already_linked_email'))
set_param('database.already_linked_send_mail_url', result['enterprise_info'].get('database_already_linked_send_mail_url'))
except Exception:
if cron_mode:
return False # we don't want to see any stack trace in cron
else:
raise
return True
| 44.064 | 5,508 |
2,499 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
import requests
class MailIceServer(models.Model):
_name = 'mail.ice.server'
_description = 'ICE server'
server_type = fields.Selection([('stun', 'stun:'), ('turn', 'turn:')], string='Type', required=True, default='stun')
uri = fields.Char('URI', required=True)
username = fields.Char()
credential = fields.Char()
def _get_local_ice_servers(self):
"""
:return: List of up to 5 dict, each of which representing a stun or turn server
"""
# firefox has a hard cap of 5 ice servers
ice_servers = self.sudo().search([], limit=5)
formatted_ice_servers = []
for ice_server in ice_servers:
formatted_ice_server = {
'urls': '%s:%s' % (ice_server.server_type, ice_server.uri),
}
if ice_server.username:
formatted_ice_server['username'] = ice_server.username
if ice_server.credential:
formatted_ice_server['credential'] = ice_server.credential
formatted_ice_servers.append(formatted_ice_server)
return formatted_ice_servers
def _get_twilio_credentials(self):
""" To be overridable if we need to obtain credentials from another source.
:return: tuple
"""
account_sid = self.env['ir.config_parameter'].sudo().get_param('mail.twilio_account_sid')
auth_token = self.env['ir.config_parameter'].sudo().get_param('mail.twilio_account_token')
return account_sid, auth_token
def _get_ice_servers(self):
"""
:return: List of dict, each of which representing a stun or turn server,
formatted as expected by the specifications of RTCConfiguration.iceServers
"""
if self.env['ir.config_parameter'].sudo().get_param('mail.use_twilio_rtc_servers'):
(account_sid, auth_token) = self._get_twilio_credentials()
if account_sid and auth_token:
url = f'https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Tokens.json'
response = requests.post(url, auth=(account_sid, auth_token), timeout=60)
if response.ok:
response_content = response.json()
if response_content:
return response_content['ice_servers']
return self._get_local_ice_servers()
| 43.842105 | 2,499 |
10,962 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.exceptions import NotFound
from odoo import api, fields, models, _
from odoo.exceptions import AccessError
from odoo.osv import expression
class ChannelPartner(models.Model):
_name = 'mail.channel.partner'
_description = 'Listeners of a Channel'
_table = 'mail_channel_partner'
# identity
partner_id = fields.Many2one('res.partner', string='Recipient', ondelete='cascade', index=True)
guest_id = fields.Many2one(string="Guest", comodel_name='mail.guest', ondelete='cascade', readonly=True, index=True)
partner_email = fields.Char('Email', related='partner_id.email', readonly=False)
# channel
channel_id = fields.Many2one('mail.channel', string='Channel', ondelete='cascade', readonly=True, required=True)
# state
custom_channel_name = fields.Char('Custom channel name')
fetched_message_id = fields.Many2one('mail.message', string='Last Fetched')
seen_message_id = fields.Many2one('mail.message', string='Last Seen')
fold_state = fields.Selection([('open', 'Open'), ('folded', 'Folded'), ('closed', 'Closed')], string='Conversation Fold State', default='open')
is_minimized = fields.Boolean("Conversation is minimized")
is_pinned = fields.Boolean("Is pinned on the interface", default=True)
last_interest_dt = fields.Datetime("Last Interest", default=fields.Datetime.now, help="Contains the date and time of the last interesting event that happened in this channel for this partner. This includes: creating, joining, pinning, and new message posted.")
# RTC
rtc_session_ids = fields.One2many(string="RTC Sessions", comodel_name='mail.channel.rtc.session', inverse_name='channel_partner_id')
rtc_inviting_session_id = fields.Many2one('mail.channel.rtc.session', string='Ringing session')
def name_get(self):
return [(record.id, record.partner_id.name or record.guest_id.name) for record in self]
def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
domain = [[('partner_id', operator, name)], [('guest_id', operator, name)]]
if '!' in operator or 'not' in operator:
domain = expression.AND(domain)
else:
domain = expression.OR(domain)
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
def init(self):
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS mail_channel_partner_partner_unique ON %s (channel_id, partner_id) WHERE partner_id IS NOT NULL" % self._table)
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS mail_channel_partner_guest_unique ON %s (channel_id, guest_id) WHERE guest_id IS NOT NULL" % self._table)
_sql_constraints = [
("partner_or_guest_exists", "CHECK((partner_id IS NOT NULL AND guest_id IS NULL) OR (partner_id IS NULL AND guest_id IS NOT NULL))", "A channel member must be a partner or a guest."),
]
@api.model_create_multi
def create(self, vals_list):
"""Similar access rule as the access rule of the mail channel.
It can not be implemented in XML, because when the record will be created, the
partner will be added in the channel and the security rule will always authorize
the creation.
"""
if not self.env.is_admin():
for vals in vals_list:
if 'channel_id' in vals:
channel_id = self.env['mail.channel'].browse(vals['channel_id'])
if not channel_id._can_invite(vals.get('partner_id')):
raise AccessError(_('This user can not be added in this channel'))
return super(ChannelPartner, self).create(vals_list)
def write(self, vals):
for channel_partner in self:
for field_name in {'channel_id', 'partner_id', 'guest_id'}:
if field_name in vals and vals[field_name] != channel_partner[field_name].id:
raise AccessError(_('You can not write on %(field_name)s.', field_name=field_name))
return super(ChannelPartner, self).write(vals)
def unlink(self):
self.sudo().rtc_session_ids.unlink()
return super().unlink()
@api.model
def _get_as_sudo_from_request_or_raise(self, request, channel_id):
channel_partner = self._get_as_sudo_from_request(request=request, channel_id=channel_id)
if not channel_partner:
raise NotFound()
return channel_partner
@api.model
def _get_as_sudo_from_request(self, request, channel_id):
""" Seeks a channel partner matching the provided `channel_id` and the
current user or guest.
:param channel_id: The id of the channel of which the user/guest is
expected to be member.
:type channel_id: int
:return: A record set containing the channel partner if found, or an
empty record set otherwise. In case of guest, the record is returned
with the 'guest' record in the context.
:rtype: mail.channel.partner
"""
if request.session.uid:
return self.env['mail.channel.partner'].sudo().search([('channel_id', '=', channel_id), ('partner_id', '=', self.env.user.partner_id.id)], limit=1)
guest = self.env['mail.guest']._get_guest_from_request(request)
if guest:
return guest.env['mail.channel.partner'].sudo().search([('channel_id', '=', channel_id), ('guest_id', '=', guest.id)], limit=1)
return self.env['mail.channel.partner'].sudo()
# --------------------------------------------------------------------------
# RTC (voice/video)
# --------------------------------------------------------------------------
def _rtc_join_call(self, check_rtc_session_ids=None):
self.ensure_one()
check_rtc_session_ids = (check_rtc_session_ids or []) + self.rtc_session_ids.ids
self.channel_id._rtc_cancel_invitations(partner_ids=self.partner_id.ids, guest_ids=self.guest_id.ids)
self.rtc_session_ids.unlink()
rtc_session = self.env['mail.channel.rtc.session'].create({'channel_partner_id': self.id})
current_rtc_sessions, outdated_rtc_sessions = self._rtc_sync_sessions(check_rtc_session_ids=check_rtc_session_ids)
res = {
'iceServers': self.env['mail.ice.server']._get_ice_servers() or False,
'rtcSessions': [
('insert', [rtc_session_sudo._mail_rtc_session_format() for rtc_session_sudo in current_rtc_sessions]),
('insert-and-unlink', [{'id': missing_rtc_session_sudo.id} for missing_rtc_session_sudo in outdated_rtc_sessions]),
],
'sessionId': rtc_session.id,
}
if len(self.channel_id.rtc_session_ids) == 1 and self.channel_id.channel_type in {'chat', 'group'}:
self.channel_id.message_post(body=_("%s started a live conference", self.partner_id.name or self.guest_id.name), message_type='notification')
invited_partners, invited_guests = self._rtc_invite_members()
if invited_guests:
res['invitedGuests'] = [('insert', [{'id': guest.id, 'name': guest.name} for guest in invited_guests])]
if invited_partners:
res['invitedPartners'] = [('insert', [{'id': partner.id, 'name': partner.name} for partner in invited_partners])]
return res
def _rtc_leave_call(self):
self.ensure_one()
if self.rtc_session_ids:
self.rtc_session_ids.unlink()
else:
return self.channel_id._rtc_cancel_invitations(partner_ids=self.partner_id.ids, guest_ids=self.guest_id.ids)
def _rtc_sync_sessions(self, check_rtc_session_ids=None):
"""Synchronize the RTC sessions for self channel partner.
- Inactive sessions of the channel are deleted.
- Current sessions are returned.
- Sessions given in check_rtc_session_ids that no longer exists
are returned as non-existing.
:param list check_rtc_session_ids: list of the ids of the sessions to check
:returns tuple: (current_rtc_sessions, outdated_rtc_sessions)
"""
self.ensure_one()
self.channel_id.rtc_session_ids._delete_inactive_rtc_sessions()
check_rtc_sessions = self.env['mail.channel.rtc.session'].browse([int(check_rtc_session_id) for check_rtc_session_id in (check_rtc_session_ids or [])])
return self.channel_id.rtc_session_ids, check_rtc_sessions - self.channel_id.rtc_session_ids
def _rtc_invite_members(self, partner_ids=None, guest_ids=None):
""" Sends invitations to join the RTC call to all connected members of the thread who are not already invited.
:param list partner_ids: list of the partner ids to invite
:param list guest_ids: list of the guest ids to invite
if either partner_ids or guest_ids is set, only the specified ids will be invited.
"""
self.ensure_one()
channel_partner_domain = [
('channel_id', '=', self.channel_id.id),
('rtc_inviting_session_id', '=', False),
('rtc_session_ids', '=', False),
]
if partner_ids or guest_ids:
channel_partner_domain = expression.AND([channel_partner_domain, [
'|',
('partner_id', 'in', partner_ids or []),
('guest_id', 'in', guest_ids or []),
]])
invitation_notifications = []
invited_partners = self.env['res.partner']
invited_guests = self.env['mail.guest']
for member in self.env['mail.channel.partner'].search(channel_partner_domain):
member.rtc_inviting_session_id = self.rtc_session_ids.id
if member.partner_id:
invited_partners |= member.partner_id
target = member.partner_id
else:
invited_guests |= member.guest_id
target = member.guest_id
invitation_notifications.append((target, 'mail.channel/insert', {
'id': self.channel_id.id,
'rtcInvitingSession': [('insert', self.rtc_session_ids._mail_rtc_session_format())],
}))
self.env['bus.bus']._sendmany(invitation_notifications)
if invited_guests or invited_partners:
channel_data = {'id': self.channel_id.id}
if invited_guests:
channel_data['invitedGuests'] = [('insert', [{'id': guest.id, 'name': guest.name} for guest in invited_guests])]
if invited_partners:
channel_data['invitedPartners'] = [('insert', [{'id': partner.id, 'name': partner.name} for partner in invited_partners])]
self.env['bus.bus']._sendone(self.channel_id, 'mail.channel/insert', channel_data)
return invited_partners, invited_guests
| 55.363636 | 10,962 |
16,350 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
import itertools
from odoo import api, fields, models, Command
class Followers(models.Model):
""" mail_followers holds the data related to the follow mechanism inside
Odoo. Partners can choose to follow documents (records) of any kind
that inherits from mail.thread. Following documents allow to receive
notifications for new messages. A subscription is characterized by:
:param: res_model: model of the followed objects
:param: res_id: ID of resource (may be 0 for every objects)
"""
_name = 'mail.followers'
_rec_name = 'partner_id'
_log_access = False
_description = 'Document Followers'
# Note. There is no integrity check on model names for performance reasons.
# However, followers of unlinked models are deleted by models themselves
# (see 'ir.model' inheritance).
res_model = fields.Char(
'Related Document Model Name', required=True, index=True)
res_id = fields.Many2oneReference(
'Related Document ID', index=True, help='Id of the followed resource', model_field='res_model')
partner_id = fields.Many2one(
'res.partner', string='Related Partner', index=True, ondelete='cascade', required=True, domain=[('type', '!=', 'private')])
subtype_ids = fields.Many2many(
'mail.message.subtype', string='Subtype',
help="Message subtypes followed, meaning subtypes that will be pushed onto the user's Wall.")
name = fields.Char('Name', related='partner_id.name')
email = fields.Char('Email', related='partner_id.email')
is_active = fields.Boolean('Is Active', related='partner_id.active')
def _invalidate_documents(self, vals_list=None):
""" Invalidate the cache of the documents followed by ``self``.
Modifying followers change access rights to individual documents. As the
cache may contain accessible/inaccessible data, one has to refresh it.
"""
to_invalidate = defaultdict(list)
for record in (vals_list or [{'res_model': rec.res_model, 'res_id': rec.res_id} for rec in self]):
if record.get('res_id'):
to_invalidate[record.get('res_model')].append(record.get('res_id'))
@api.model_create_multi
def create(self, vals_list):
res = super(Followers, self).create(vals_list)
res._invalidate_documents(vals_list)
return res
def write(self, vals):
if 'res_model' in vals or 'res_id' in vals:
self._invalidate_documents()
res = super(Followers, self).write(vals)
if any(x in vals for x in ['res_model', 'res_id', 'partner_id']):
self._invalidate_documents()
return res
def unlink(self):
self._invalidate_documents()
return super(Followers, self).unlink()
_sql_constraints = [
('mail_followers_res_partner_res_model_id_uniq', 'unique(res_model,res_id,partner_id)', 'Error, a partner cannot follow twice the same object.'),
]
# --------------------------------------------------
# Private tools methods to fetch followers data
# --------------------------------------------------
def _get_recipient_data(self, records, message_type, subtype_id, pids=None):
""" Private method allowing to fetch recipients data based on a subtype.
Purpose of this method is to fetch all data necessary to notify recipients
in a single query. It fetches data from
* followers (partners and channels) of records that follow the given
subtype if records and subtype are set;
* partners if pids is given;
:param records: fetch data from followers of records that follow subtype_id;
:param message_type: mail.message.message_type in order to allow custom behavior depending on it (SMS for example);
:param subtype_id: mail.message.subtype to check against followers;
:param pids: additional set of partner IDs from which to fetch recipient data;
:return: list of recipient data which is a tuple containing
partner ID ,
active value (always True for channels),
share status of partner,
notification status of partner or channel (email or inbox),
user groups of partner,
"""
self.env['mail.followers'].flush(['partner_id', 'subtype_ids'])
self.env['mail.message.subtype'].flush(['internal'])
self.env['res.users'].flush(['notification_type', 'active', 'partner_id', 'groups_id'])
self.env['res.partner'].flush(['active', 'partner_share'])
self.env['res.groups'].flush(['users'])
if records and subtype_id:
query = """
SELECT DISTINCT ON (pid) * FROM (
WITH sub_followers AS (
SELECT fol.partner_id,
coalesce(subtype.internal, false) as internal
FROM mail_followers fol
JOIN mail_followers_mail_message_subtype_rel subrel ON subrel.mail_followers_id = fol.id
JOIN mail_message_subtype subtype ON subtype.id = subrel.mail_message_subtype_id
WHERE subrel.mail_message_subtype_id = %s
AND fol.res_model = %s
AND fol.res_id IN %s
UNION ALL
SELECT id,
FALSE
FROM res_partner
WHERE id=ANY(%s)
)
SELECT partner.id as pid,
partner.active as active,
partner.partner_share as pshare,
users.notification_type AS notif,
array_agg(groups_rel.gid) AS groups
FROM res_partner partner
LEFT JOIN res_users users ON users.partner_id = partner.id
AND users.active
LEFT JOIN res_groups_users_rel groups_rel ON groups_rel.uid = users.id
JOIN sub_followers ON sub_followers.partner_id = partner.id
AND (NOT sub_followers.internal OR partner.partner_share IS NOT TRUE)
GROUP BY partner.id,
users.notification_type
) AS x
ORDER BY pid, notif
"""
params = [subtype_id, records._name, tuple(records.ids), list(pids) or []]
self.env.cr.execute(query, tuple(params))
res = self.env.cr.fetchall()
elif pids:
params = []
query_pid = """
SELECT partner.id as pid,
partner.active as active, partner.partner_share as pshare,
users.notification_type AS notif,
array_agg(groups_rel.gid) FILTER (WHERE groups_rel.gid IS NOT NULL) AS groups
FROM res_partner partner
LEFT JOIN res_users users ON users.partner_id = partner.id AND users.active
LEFT JOIN res_groups_users_rel groups_rel ON groups_rel.uid = users.id
WHERE partner.id IN %s
GROUP BY partner.id, users.notification_type"""
params.append(tuple(pids))
query = 'SELECT DISTINCT ON (pid) * FROM (%s) AS x ORDER BY pid, notif' % query_pid
self.env.cr.execute(query, tuple(params))
res = self.env.cr.fetchall()
else:
res = []
return res
def _get_subscription_data(self, doc_data, pids, include_pshare=False, include_active=False):
""" Private method allowing to fetch follower data from several documents of a given model.
Followers can be filtered given partner IDs and channel IDs.
:param doc_data: list of pair (res_model, res_ids) that are the documents from which we
want to have subscription data;
:param pids: optional partner to filter; if None take all, otherwise limitate to pids
:param include_pshare: optional join in partner to fetch their share status
:param include_active: optional join in partner to fetch their active flag
:return: list of followers data which is a list of tuples containing
follower ID,
document ID,
partner ID,
followed subtype IDs,
share status of partner (returned only if include_pshare is True)
active flag status of partner (returned only if include_active is True)
"""
# base query: fetch followers of given documents
where_clause = ' OR '.join(['fol.res_model = %s AND fol.res_id IN %s'] * len(doc_data))
where_params = list(itertools.chain.from_iterable((rm, tuple(rids)) for rm, rids in doc_data))
# additional: filter on optional pids
sub_where = []
if pids:
sub_where += ["fol.partner_id IN %s"]
where_params.append(tuple(pids))
elif pids is not None:
sub_where += ["fol.partner_id IS NULL"]
if sub_where:
where_clause += "AND (%s)" % " OR ".join(sub_where)
query = """
SELECT fol.id, fol.res_id, fol.partner_id, array_agg(subtype.id)%s%s
FROM mail_followers fol
%s
LEFT JOIN mail_followers_mail_message_subtype_rel fol_rel ON fol_rel.mail_followers_id = fol.id
LEFT JOIN mail_message_subtype subtype ON subtype.id = fol_rel.mail_message_subtype_id
WHERE %s
GROUP BY fol.id%s%s""" % (
', partner.partner_share' if include_pshare else '',
', partner.active' if include_active else '',
'LEFT JOIN res_partner partner ON partner.id = fol.partner_id' if (include_pshare or include_active) else '',
where_clause,
', partner.partner_share' if include_pshare else '',
', partner.active' if include_active else ''
)
self.env.cr.execute(query, tuple(where_params))
return self.env.cr.fetchall()
# --------------------------------------------------
# Private tools methods to generate new subscription
# --------------------------------------------------
def _insert_followers(self, res_model, res_ids,
partner_ids, subtypes=None,
customer_ids=None, check_existing=True, existing_policy='skip'):
""" Main internal method allowing to create or update followers for documents, given a
res_model and the document res_ids. This method does not handle access rights. This is the
role of the caller to ensure there is no security breach.
:param subtypes: see ``_add_followers``. If not given, default ones are computed.
:param customer_ids: see ``_add_default_followers``
:param check_existing: see ``_add_followers``;
:param existing_policy: see ``_add_followers``;
"""
sudo_self = self.sudo().with_context(default_partner_id=False)
if not subtypes: # no subtypes -> default computation, no force, skip existing
new, upd = self._add_default_followers(
res_model, res_ids, partner_ids,
customer_ids=customer_ids,
check_existing=check_existing,
existing_policy=existing_policy)
else:
new, upd = self._add_followers(
res_model, res_ids,
partner_ids, subtypes,
check_existing=check_existing,
existing_policy=existing_policy)
if new:
sudo_self.create([
dict(values, res_id=res_id)
for res_id, values_list in new.items()
for values in values_list
])
for fol_id, values in upd.items():
sudo_self.browse(fol_id).write(values)
def _add_default_followers(self, res_model, res_ids, partner_ids, customer_ids=None,
check_existing=True, existing_policy='skip'):
""" Shortcut to ``_add_followers`` that computes default subtypes. Existing
followers are skipped as their subscription is considered as more important
compared to new default subscription.
:param customer_ids: optional list of partner ids that are customers. It is used if computing
default subtype is necessary and allow to avoid the check of partners being customers (no
user or share user). It is just a matter of saving queries if the info is already known;
:param check_existing: see ``_add_followers``;
:param existing_policy: see ``_add_followers``;
:return: see ``_add_followers``
"""
if not partner_ids:
return dict(), dict()
default, _, external = self.env['mail.message.subtype'].default_subtypes(res_model)
if partner_ids and customer_ids is None:
customer_ids = self.env['res.partner'].sudo().search([('id', 'in', partner_ids), ('partner_share', '=', True)]).ids
p_stypes = dict((pid, external.ids if pid in customer_ids else default.ids) for pid in partner_ids)
return self._add_followers(res_model, res_ids, partner_ids, p_stypes, check_existing=check_existing, existing_policy=existing_policy)
def _add_followers(self, res_model, res_ids, partner_ids, subtypes,
check_existing=False, existing_policy='skip'):
""" Internal method that generates values to insert or update followers. Callers have to
handle the result, for example by making a valid ORM command, inserting or updating directly
follower records, ... This method returns two main data
* first one is a dict which keys are res_ids. Value is a list of dict of values valid for
creating new followers for the related res_id;
* second one is a dict which keys are follower ids. Value is a dict of values valid for
updating the related follower record;
:param subtypes: optional subtypes for new partner followers. This
is a dict whose keys are partner IDs and value subtype IDs for that
partner.
:param channel_subtypes: optional subtypes for new channel followers. This
is a dict whose keys are channel IDs and value subtype IDs for that
channel.
:param check_existing: if True, check for existing followers for given
documents and handle them according to existing_policy parameter.
Setting to False allows to save some computation if caller is sure
there are no conflict for followers;
:param existing policy: if check_existing, tells what to do with already
existing followers:
* skip: simply skip existing followers, do not touch them;
* force: update existing with given subtypes only;
* replace: replace existing with new subtypes (like force without old / new follower);
* update: gives an update dict allowing to add missing subtypes (no subtype removal);
"""
_res_ids = res_ids or [0]
data_fols, doc_pids = dict(), dict((i, set()) for i in _res_ids)
if check_existing and res_ids:
for fid, rid, pid, sids in self._get_subscription_data([(res_model, res_ids)], partner_ids or None):
if existing_policy != 'force':
if pid:
doc_pids[rid].add(pid)
data_fols[fid] = (rid, pid, sids)
if existing_policy == 'force':
self.sudo().browse(data_fols.keys()).unlink()
new, update = dict(), dict()
for res_id in _res_ids:
for partner_id in set(partner_ids or []):
if partner_id not in doc_pids[res_id]:
new.setdefault(res_id, list()).append({
'res_model': res_model,
'partner_id': partner_id,
'subtype_ids': [Command.set(subtypes[partner_id])],
})
elif existing_policy in ('replace', 'update'):
fol_id, sids = next(((key, val[2]) for key, val in data_fols.items() if val[0] == res_id and val[1] == partner_id), (False, []))
new_sids = set(subtypes[partner_id]) - set(sids)
old_sids = set(sids) - set(subtypes[partner_id])
update_cmd = []
if fol_id and new_sids:
update_cmd += [Command.link(sid) for sid in new_sids]
if fol_id and old_sids and existing_policy == 'replace':
update_cmd += [Command.unlink(sid) for sid in old_sids]
if update_cmd:
update[fol_id] = {'subtype_ids': update_cmd}
return new, update
| 48.372781 | 16,350 |
2,586 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import AccessError
class IrTranslation(models.Model):
_inherit = 'ir.translation'
@api.model_create_multi
def create(self, vals_list):
translations = super().create(vals_list)
translations._check_is_dynamic()
return translations
def write(self, vals):
res = super().write(vals)
self._check_is_dynamic()
return res
def _check_is_dynamic(self):
# if we don't modify translation of at least a model that inherits from mail.render.mixin, we ignore it
# translation.name can be a path, and so not in the pool, so type(None) will exclude these translations.
translations_for_mail_render_mixin = self.filtered(
lambda translation: issubclass(type(self.env.get(translation.name.split(',')[0])), self.pool['mail.render.mixin'])
)
if not translations_for_mail_render_mixin:
return
# if we are admin, or that we can update mail.template we ignore
if self.env.is_admin() or self.env.user.has_group('mail.group_mail_template_editor'):
return
# Check that we don't add qweb code in translation when you don't have the rights
# prefill cache
ids_by_model_by_lang = {}
tuple_lang_model_id = translations_for_mail_render_mixin.mapped(
lambda translation: (translation.lang, translation.name.split(',')[0], translation.res_id)
)
for lang, model, _id in tuple_lang_model_id:
ids_by_model_by_lang.setdefault(lang, {}).setdefault(model, set()).add(_id)
for lang in ids_by_model_by_lang:
for res_model, res_ids in ids_by_model_by_lang[lang].items():
self.env[res_model].with_context(lang=lang).browse(res_ids)
for trans in translations_for_mail_render_mixin:
res_model, res_id = trans.name.split(',')[0], trans.res_id
rec = self.env[res_model].with_context(lang=trans.lang).browse(res_id)
if rec._is_dynamic():
group = self.env.ref('mail.group_mail_template_editor')
more_info = len(self) > 1 and ' [%s]' % rec or ''
raise AccessError(
_('Only users belonging to the "%(group)s" group can modify translation related to dynamic templates.%(xtra)s',
group=group.name,
xtra=more_info
)
)
| 43.1 | 2,586 |
5,948 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class MailRtcSession(models.Model):
_name = 'mail.channel.rtc.session'
_description = 'Mail RTC session'
channel_partner_id = fields.Many2one('mail.channel.partner', index=True, required=True, ondelete='cascade')
channel_id = fields.Many2one('mail.channel', related='channel_partner_id.channel_id', store=True, readonly=True)
partner_id = fields.Many2one('res.partner', related='channel_partner_id.partner_id', string="Partner")
guest_id = fields.Many2one('mail.guest', related='channel_partner_id.guest_id')
write_date = fields.Datetime("Last Updated On", index=True)
is_screen_sharing_on = fields.Boolean(string="Is sharing the screen")
is_camera_on = fields.Boolean(string="Is sending user video")
is_muted = fields.Boolean(string="Is microphone muted")
is_deaf = fields.Boolean(string="Has disabled incoming sound")
_sql_constraints = [
('channel_partner_unique', 'UNIQUE(channel_partner_id)',
'There can only be one rtc session per channel partner')
]
@api.model_create_multi
def create(self, vals_list):
rtc_sessions = super().create(vals_list)
self.env['bus.bus']._sendmany([(channel, 'mail.channel/rtc_sessions_update', {
'id': channel.id,
'rtcSessions': [('insert', sessions_data)],
}) for channel, sessions_data in rtc_sessions._mail_rtc_session_format_by_channel().items()])
return rtc_sessions
def unlink(self):
channels = self.channel_id
for channel in channels:
if channel.rtc_session_ids and len(channel.rtc_session_ids - self) == 0:
# If there is no member left in the RTC call, all invitations are cancelled.
# Note: invitation depends on field `rtc_inviting_session_id` so the cancel must be
# done before the delete to be able to know who was invited.
channel._rtc_cancel_invitations()
notifications = [(channel, 'mail.channel/rtc_sessions_update', {
'id': channel.id,
'rtcSessions': [('insert-and-unlink', [{'id': session_data['id']} for session_data in sessions_data])],
}) for channel, sessions_data in self._mail_rtc_session_format_by_channel().items()]
for rtc_session in self:
target = rtc_session.guest_id or rtc_session.partner_id
notifications.append((target, 'mail.channel.rtc.session/ended', {'sessionId': rtc_session.id}))
self.env['bus.bus']._sendmany(notifications)
return super().unlink()
def _update_and_broadcast(self, values):
""" Updates the session and notifies all members of the channel
of the change.
"""
valid_values = {'is_screen_sharing_on', 'is_camera_on', 'is_muted', 'is_deaf'}
self.write({key: values[key] for key in valid_values if key in valid_values})
session_data = self._mail_rtc_session_format()
self.env['bus.bus']._sendone(self.channel_id, 'mail.channel.rtc.session/insert', session_data)
@api.autovacuum
def _gc_inactive_sessions(self):
""" Garbage collect sessions that aren't active anymore,
this can happen when the server or the user's browser crash
or when the user's odoo session ends.
"""
self.search(self._inactive_rtc_session_domain()).unlink()
def action_disconnect(self):
self.unlink()
def _delete_inactive_rtc_sessions(self):
"""Deletes the inactive sessions from self."""
self.filtered_domain(self._inactive_rtc_session_domain()).unlink()
def _notify_peers(self, notifications):
""" Used for peer-to-peer communication,
guarantees that the sender is the current guest or partner.
:param notifications: list of tuple with the following elements:
- target_session_ids: a list of mail.channel.rtc.session ids
- content: a string with the content to be sent to the targets
"""
self.ensure_one()
payload_by_target = defaultdict(lambda: {'sender': self.id, 'notifications': []})
for target_session_ids, content in notifications:
for target_session in self.env['mail.channel.rtc.session'].browse(target_session_ids).exists():
target = target_session.guest_id or target_session.partner_id
payload_by_target[target]['notifications'].append(content)
return self.env['bus.bus']._sendmany([(target, 'mail.channel.rtc.session/peer_notification', payload) for target, payload in payload_by_target.items()])
def _mail_rtc_session_format(self, complete_info=True):
self.ensure_one()
vals = {
'id': self.id,
}
if complete_info:
vals.update({
'isCameraOn': self.is_camera_on,
'isDeaf': self.is_deaf,
'isMuted': self.is_muted,
'isScreenSharingOn': self.is_screen_sharing_on,
})
if self.guest_id:
vals['guest'] = [('insert', {
'id': self.guest_id.id,
'name': self.guest_id.name,
})]
else:
vals['partner'] = [('insert', {
'id': self.partner_id.id,
'name': self.partner_id.name,
})]
return vals
def _mail_rtc_session_format_by_channel(self):
data = {}
for rtc_session in self:
data.setdefault(rtc_session.channel_id, []).append(rtc_session._mail_rtc_session_format())
return data
@api.model
def _inactive_rtc_session_domain(self):
return [('write_date', '<', fields.Datetime.now() - relativedelta(minutes=1))]
| 45.753846 | 5,948 |
4,313 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError
class MailBlackList(models.Model):
""" Model of blacklisted email addresses to stop sending emails."""
_name = 'mail.blacklist'
_inherit = ['mail.thread']
_description = 'Mail Blacklist'
_rec_name = 'email'
email = fields.Char(string='Email Address', required=True, index=True, help='This field is case insensitive.',
tracking=True)
active = fields.Boolean(default=True, tracking=True)
_sql_constraints = [
('unique_email', 'unique (email)', 'Email address already exists!')
]
@api.model_create_multi
def create(self, values):
# First of all, extract values to ensure emails are really unique (and don't modify values in place)
new_values = []
all_emails = []
for value in values:
email = tools.email_normalize(value.get('email'))
if not email:
raise UserError(_('Invalid email address %r', value['email']))
if email in all_emails:
continue
all_emails.append(email)
new_value = dict(value, email=email)
new_values.append(new_value)
""" To avoid crash during import due to unique email, return the existing records if any """
sql = '''SELECT email, id FROM mail_blacklist WHERE email = ANY(%s)'''
emails = [v['email'] for v in new_values]
self._cr.execute(sql, (emails,))
bl_entries = dict(self._cr.fetchall())
to_create = [v for v in new_values if v['email'] not in bl_entries]
# TODO DBE Fixme : reorder ids according to incoming ids.
results = super(MailBlackList, self).create(to_create)
return self.env['mail.blacklist'].browse(bl_entries.values()) | results
def write(self, values):
if 'email' in values:
values['email'] = tools.email_normalize(values['email'])
return super(MailBlackList, self).write(values)
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
""" Override _search in order to grep search on email field and make it
lower-case and sanitized """
if args:
new_args = []
for arg in args:
if isinstance(arg, (list, tuple)) and arg[0] == 'email' and isinstance(arg[2], str):
normalized = tools.email_normalize(arg[2])
if normalized:
new_args.append([arg[0], arg[1], normalized])
else:
new_args.append(arg)
else:
new_args.append(arg)
else:
new_args = args
return super(MailBlackList, self)._search(new_args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
def _add(self, email):
normalized = tools.email_normalize(email)
record = self.env["mail.blacklist"].with_context(active_test=False).search([('email', '=', normalized)])
if len(record) > 0:
record.action_unarchive()
else:
record = self.create({'email': email})
return record
def action_remove_with_reason(self, email, reason=None):
record = self._remove(email)
if reason:
record.message_post(body=_("Unblacklisting Reason: %s", reason))
return record
def _remove(self, email):
normalized = tools.email_normalize(email)
record = self.env["mail.blacklist"].with_context(active_test=False).search([('email', '=', normalized)])
if len(record) > 0:
record.action_archive()
else:
record = record.create({'email': email, 'active': False})
return record
def mail_action_blacklist_remove(self):
return {
'name': _('Are you sure you want to unblacklist this Email Address?'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.blacklist.remove',
'target': 'new',
}
def action_add(self):
self._add(self.email)
| 40.308411 | 4,313 |
5,261 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class IrModel(models.Model):
_inherit = 'ir.model'
_order = 'is_mail_thread DESC, name ASC'
is_mail_thread = fields.Boolean(
string="Mail Thread", default=False,
help="Whether this model supports messages and notifications.",
)
is_mail_activity = fields.Boolean(
string="Mail Activity", default=False,
help="Whether this model supports activities.",
)
is_mail_blacklist = fields.Boolean(
string="Mail Blacklist", default=False,
help="Whether this model supports blacklist.",
)
def unlink(self):
""" Delete mail data (followers, messages, activities) associated with
the models being deleted.
"""
mail_models = self.search([
('model', 'in', ('mail.activity', 'mail.activity.type', 'mail.followers', 'mail.message'))
], order='id')
if not (self & mail_models):
models = tuple(self.mapped('model'))
model_ids = tuple(self.ids)
query = "DELETE FROM mail_activity WHERE res_model_id IN %s"
self.env.cr.execute(query, [model_ids])
query = "DELETE FROM mail_activity_type WHERE res_model IN %s"
self.env.cr.execute(query, [models])
query = "DELETE FROM mail_followers WHERE res_model IN %s"
self.env.cr.execute(query, [models])
query = "DELETE FROM mail_message WHERE model in %s"
self.env.cr.execute(query, [models])
# Get files attached solely to the models being deleted (and none other)
models = tuple(self.mapped('model'))
query = """
SELECT DISTINCT store_fname
FROM ir_attachment
WHERE res_model IN %s
EXCEPT
SELECT store_fname
FROM ir_attachment
WHERE res_model not IN %s;
"""
self.env.cr.execute(query, [models, models])
fnames = self.env.cr.fetchall()
query = """DELETE FROM ir_attachment WHERE res_model in %s"""
self.env.cr.execute(query, [models])
for (fname,) in fnames:
self.env['ir.attachment']._file_delete(fname)
return super(IrModel, self).unlink()
def write(self, vals):
if self and ('is_mail_thread' in vals or 'is_mail_activity' in vals or 'is_mail_blacklist' in vals):
if any(rec.state != 'manual' for rec in self):
raise UserError(_('Only custom models can be modified.'))
if 'is_mail_thread' in vals and any(rec.is_mail_thread > vals['is_mail_thread'] for rec in self):
raise UserError(_('Field "Mail Thread" cannot be changed to "False".'))
if 'is_mail_activity' in vals and any(rec.is_mail_activity > vals['is_mail_activity'] for rec in self):
raise UserError(_('Field "Mail Activity" cannot be changed to "False".'))
if 'is_mail_blacklist' in vals and any(rec.is_mail_blacklist > vals['is_mail_blacklist'] for rec in self):
raise UserError(_('Field "Mail Blacklist" cannot be changed to "False".'))
res = super(IrModel, self).write(vals)
self.flush()
# setup models; this reloads custom models in registry
self.pool.setup_models(self._cr)
# update database schema of models
models = self.pool.descendants(self.mapped('model'), '_inherits')
self.pool.init_models(self._cr, models, dict(self._context, update_custom_fields=True))
else:
res = super(IrModel, self).write(vals)
return res
def _reflect_model_params(self, model):
vals = super(IrModel, self)._reflect_model_params(model)
vals['is_mail_thread'] = issubclass(type(model), self.pool['mail.thread'])
vals['is_mail_activity'] = issubclass(type(model), self.pool['mail.activity.mixin'])
vals['is_mail_blacklist'] = issubclass(type(model), self.pool['mail.thread.blacklist'])
return vals
@api.model
def _instanciate(self, model_data):
model_class = super(IrModel, self)._instanciate(model_data)
if model_data.get('is_mail_blacklist') and model_class._name != 'mail.thread.blacklist':
parents = model_class._inherit or []
parents = [parents] if isinstance(parents, str) else parents
model_class._inherit = parents + ['mail.thread.blacklist']
if model_class._custom:
model_class._primary_email = 'x_email'
elif model_data.get('is_mail_thread') and model_class._name != 'mail.thread':
parents = model_class._inherit or []
parents = [parents] if isinstance(parents, str) else parents
model_class._inherit = parents + ['mail.thread']
if model_data.get('is_mail_activity') and model_class._name != 'mail.activity.mixin':
parents = model_class._inherit or []
parents = [parents] if isinstance(parents, str) else parents
model_class._inherit = parents + ['mail.activity.mixin']
return model_class
| 45.353448 | 5,261 |
5,133 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
from odoo.exceptions import AccessError
from odoo.tools.translate import _
class MailNotification(models.Model):
_name = 'mail.notification'
_table = 'mail_notification'
_rec_name = 'res_partner_id'
_log_access = False
_description = 'Message Notifications'
# origin
mail_message_id = fields.Many2one('mail.message', 'Message', index=True, ondelete='cascade', required=True)
mail_mail_id = fields.Many2one('mail.mail', 'Mail', index=True, help='Optional mail_mail ID. Used mainly to optimize searches.')
# recipient
res_partner_id = fields.Many2one('res.partner', 'Recipient', index=True, ondelete='cascade')
# status
notification_type = fields.Selection([
('inbox', 'Inbox'), ('email', 'Email')
], string='Notification Type', default='inbox', index=True, required=True)
notification_status = fields.Selection([
('ready', 'Ready to Send'),
('sent', 'Sent'),
('bounce', 'Bounced'),
('exception', 'Exception'),
('canceled', 'Canceled')
], string='Status', default='ready', index=True)
is_read = fields.Boolean('Is Read', index=True)
read_date = fields.Datetime('Read Date', copy=False)
failure_type = fields.Selection(selection=[
# generic
("unknown", "Unknown error"),
# mail
("mail_email_invalid", "Invalid email address"),
("mail_email_missing", "Missing email addresss"),
("mail_smtp", "Connection failed (outgoing mail server problem)"),
], string='Failure type')
failure_reason = fields.Text('Failure reason', copy=False)
_sql_constraints = [
# email notification;: partner is required
('notification_partner_required',
"CHECK(notification_type NOT IN ('email', 'inbox') OR res_partner_id IS NOT NULL)",
'Customer is required for inbox / email notification'),
]
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
def init(self):
self._cr.execute("""
CREATE INDEX IF NOT EXISTS mail_notification_res_partner_id_is_read_notification_status_mail_message_id
ON mail_notification (res_partner_id, is_read, notification_status, mail_message_id)
""")
@api.model_create_multi
def create(self, vals_list):
messages = self.env['mail.message'].browse(vals['mail_message_id'] for vals in vals_list)
messages.check_access_rights('read')
messages.check_access_rule('read')
for vals in vals_list:
if vals.get('is_read'):
vals['read_date'] = fields.Datetime.now()
return super(MailNotification, self).create(vals_list)
def write(self, vals):
if ('mail_message_id' in vals or 'res_partner_id' in vals) and not self.env.is_admin():
raise AccessError(_("Can not update the message or recipient of a notification."))
if vals.get('is_read'):
vals['read_date'] = fields.Datetime.now()
return super(MailNotification, self).write(vals)
@api.model
def _gc_notifications(self, max_age_days=180):
domain = [
('is_read', '=', True),
('read_date', '<', fields.Datetime.now() - relativedelta(days=max_age_days)),
('res_partner_id.partner_share', '=', False),
('notification_status', 'in', ('sent', 'canceled'))
]
return self.search(domain).unlink()
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
def format_failure_reason(self):
self.ensure_one()
if self.failure_type != 'unknown':
return dict(type(self).failure_type.selection).get(self.failure_type, _('No Error'))
else:
return _("Unknown error") + ": %s" % (self.failure_reason or '')
# ------------------------------------------------------------
# DISCUSS
# ------------------------------------------------------------
def _filtered_for_web_client(self):
"""Returns only the notifications to show on the web client."""
return self.filtered(lambda n:
n.notification_type != 'inbox' and
(n.notification_status in ['bounce', 'exception', 'canceled'] or n.res_partner_id.partner_share)
)
def _notification_format(self):
"""Returns the current notifications in the format expected by the web
client."""
return [{
'id': notif.id,
'notification_type': notif.notification_type,
'notification_status': notif.notification_status,
'failure_type': notif.failure_type,
'res_partner_id': [notif.res_partner_id.id, notif.res_partner_id.display_name] if notif.res_partner_id else False,
} for notif in self]
| 42.421488 | 5,133 |
4,211 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import pytz
import uuid
from odoo.tools import consteq
from odoo import _, api, fields, models
from odoo.addons.base.models.res_partner import _tz_get
from odoo.exceptions import UserError
class MailGuest(models.Model):
_name = 'mail.guest'
_description = "Guest"
_inherit = ['avatar.mixin']
_avatar_name_field = "name"
_cookie_name = 'dgid'
_cookie_separator = '|'
@api.model
def _lang_get(self):
return self.env['res.lang'].get_installed()
name = fields.Char(string="Name", required=True)
access_token = fields.Char(string="Access Token", default=lambda self: str(uuid.uuid4()), groups='base.group_system', required=True, readonly=True, copy=False)
country_id = fields.Many2one(string="Country", comodel_name='res.country')
lang = fields.Selection(string="Language", selection=_lang_get)
timezone = fields.Selection(string="Timezone", selection=_tz_get)
channel_ids = fields.Many2many(string="Channels", comodel_name='mail.channel', relation='mail_channel_partner', column1='guest_id', column2='channel_id', copy=False)
def _get_guest_from_context(self):
"""Returns the current guest record from the context, if applicable."""
guest = self.env.context.get('guest')
if isinstance(guest, self.pool['mail.guest']):
return guest
return self.env['mail.guest']
def _get_guest_from_request(self, request):
parts = request.httprequest.cookies.get(self._cookie_name, '').split(self._cookie_separator)
if len(parts) != 2:
return self.env['mail.guest']
guest_id, guest_access_token = parts
if not guest_id or not guest_access_token:
return self.env['mail.guest']
guest = self.env['mail.guest'].browse(int(guest_id)).sudo().exists()
if not guest or not guest.access_token or not consteq(guest.access_token, guest_access_token):
return self.env['mail.guest']
if not guest.timezone:
timezone = self._get_timezone_from_request(request)
if timezone:
guest._update_timezone(timezone)
return guest.sudo(False).with_context(guest=guest)
def _get_timezone_from_request(self, request):
timezone = request.httprequest.cookies.get('tz')
return timezone if timezone in pytz.all_timezones else False
def _update_name(self, name):
self.ensure_one()
name = name.strip()
if len(name) < 1:
raise UserError(_("Guest's name cannot be empty."))
if len(name) > 512:
raise UserError(_("Guest's name is too long."))
self.name = name
guest_data = {
'id': self.id,
'name': self.name
}
bus_notifs = [(channel, 'mail.guest/insert', guest_data) for channel in self.channel_ids]
bus_notifs.append((self, 'mail.guest/insert', guest_data))
self.env['bus.bus']._sendmany(bus_notifs)
def _update_timezone(self, timezone):
query = """
UPDATE mail_guest
SET timezone = %s
WHERE id IN (
SELECT id FROM mail_guest WHERE id = %s
FOR NO KEY UPDATE SKIP LOCKED
)
"""
self.env.cr.execute(query, (timezone, self.id))
def _init_messaging(self):
self.ensure_one()
partner_root = self.env.ref('base.partner_root')
return {
'channels': self.channel_ids.channel_info(),
'companyName': self.env.company.name,
'currentGuest': {
'id': self.id,
'name': self.name,
},
'current_partner': False,
'current_user_id': False,
'current_user_settings': False,
'mail_failures': [],
'menu_id': False,
'needaction_inbox_counter': False,
'partner_root': {
'id': partner_root.id,
'name': partner_root.name,
},
'public_partners': [],
'shortcodes': [],
'starred_counter': False,
}
| 38.633028 | 4,211 |
1,356 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
from odoo import models
from odoo.addons.web.controllers.main import HomeStaticTemplateHelpers
from odoo.http import request
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
def session_info(self):
user = request.env.user
result = super(IrHttp, self).session_info()
if self.env.user.has_group('base.group_user'):
result['notification_type'] = user.notification_type
assets_discuss_public_hash = HomeStaticTemplateHelpers.get_qweb_templates_checksum(debug=request.session.debug, bundle='mail.assets_discuss_public')
result['cache_hashes']['assets_discuss_public'] = assets_discuss_public_hash
guest = self.env['mail.guest']._get_guest_from_context()
if not request.session.uid and guest:
user_context = {'lang': guest.lang}
mods = odoo.conf.server_wide_modules or []
lang = user_context.get("lang")
translation_hash = request.env['ir.translation'].sudo().get_web_translations_hash(mods, lang)
result['cache_hashes']['translations'] = translation_hash
result.update({
'name': guest.name,
'user_context': user_context,
})
return result
| 43.741935 | 1,356 |
11,930 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml.builder import E
from odoo import api, models, tools, _
class BaseModel(models.AbstractModel):
_inherit = 'base'
def _valid_field_parameter(self, field, name):
# allow tracking on abstract models; see also 'mail.thread'
return (
name == 'tracking' and self._abstract
or super()._valid_field_parameter(field, name)
)
# ------------------------------------------------------------
# GENERIC MAIL FEATURES
# ------------------------------------------------------------
def _mail_track(self, tracked_fields, initial):
""" For a given record, fields to check (tuple column name, column info)
and initial values, return a valid command to create tracking values.
:param tracked_fields: fields_get of updated fields on which tracking
is checked and performed;
:param initial: dict of initial values for each updated fields;
:return: a tuple (changes, tracking_value_ids) where
changes: set of updated column names;
tracking_value_ids: a list of ORM (0, 0, values) commands to create
``mail.tracking.value`` records;
Override this method on a specific model to implement model-specific
behavior. Also consider inheriting from ``mail.thread``. """
self.ensure_one()
changes = set() # contains onchange tracked fields that changed
tracking_value_ids = []
# generate tracked_values data structure: {'col_name': {col_info, new_value, old_value}}
for col_name, col_info in tracked_fields.items():
if col_name not in initial:
continue
initial_value = initial[col_name]
new_value = self[col_name]
if new_value != initial_value and (new_value or initial_value): # because browse null != False
tracking_sequence = getattr(self._fields[col_name], 'tracking',
getattr(self._fields[col_name], 'track_sequence', 100)) # backward compatibility with old parameter name
if tracking_sequence is True:
tracking_sequence = 100
tracking = self.env['mail.tracking.value'].create_tracking_values(initial_value, new_value, col_name, col_info, tracking_sequence, self._name)
if tracking:
if tracking['field_type'] == 'monetary':
tracking['currency_id'] = self[col_info['currency_field']].id
tracking_value_ids.append([0, 0, tracking])
changes.add(col_name)
return changes, tracking_value_ids
def _message_get_default_recipients(self):
""" Generic implementation for finding default recipient to mail on
a recordset. This method is a generic implementation available for
all models as we could send an email through mail templates on models
not inheriting from mail.thread.
Override this method on a specific model to implement model-specific
behavior. Also consider inheriting from ``mail.thread``. """
res = {}
for record in self:
recipient_ids, email_to, email_cc = [], False, False
if 'partner_id' in record and record.partner_id:
recipient_ids.append(record.partner_id.id)
elif 'email_normalized' in record and record.email_normalized:
email_to = record.email_normalized
elif 'email_from' in record and record.email_from:
email_to = record.email_from
elif 'partner_email' in record and record.partner_email:
email_to = record.partner_email
elif 'email' in record and record.email:
email_to = record.email
res[record.id] = {'partner_ids': recipient_ids, 'email_to': email_to, 'email_cc': email_cc}
return res
def _notify_get_reply_to(self, default=None, records=None, company=None, doc_names=None):
""" Returns the preferred reply-to email address when replying to a thread
on documents. This method is a generic implementation available for
all models as we could send an email through mail templates on models
not inheriting from mail.thread.
Reply-to is formatted like "MyCompany MyDocument <reply.to@domain>".
Heuristic it the following:
* search for specific aliases as they always have priority; it is limited
to aliases linked to documents (like project alias for task for example);
* use catchall address;
* use default;
This method can be used as a generic tools if self is a void recordset.
Override this method on a specific model to implement model-specific
behavior. Also consider inheriting from ``mail.thread``.
An example would be tasks taking their reply-to alias from their project.
:param default: default email if no alias or catchall is found;
:param records: DEPRECATED, self should be a valid record set or an
empty recordset if a generic reply-to is required;
:param company: used to compute company name part of the from name; provide
it if already known, otherwise use records company it they all belong to the same company
and fall back on user's company in mixed companies environments;
:param doc_names: dict(res_id, doc_name) used to compute doc name part of
the from name; provide it if already known to avoid queries, otherwise
name_get on document will be performed;
:return result: dictionary. Keys are record IDs and value is formatted
like an email "Company_name Document_name <reply_to@email>"/
"""
if records:
raise ValueError('Use of records is deprecated as this method is available on BaseModel.')
_records = self
model = _records._name if _records and _records._name != 'mail.thread' else False
res_ids = _records.ids if _records and model else []
_res_ids = res_ids or [False] # always have a default value located in False
alias_domain = self.env['ir.config_parameter'].sudo().get_param("mail.catchall.domain")
result = dict.fromkeys(_res_ids, False)
result_email = dict()
doc_names = doc_names if doc_names else dict()
if alias_domain:
if model and res_ids:
if not doc_names:
doc_names = dict((rec.id, rec.display_name) for rec in _records)
if not company and 'company_id' in self and len(self.company_id) == 1:
company = self.company_id
mail_aliases = self.env['mail.alias'].sudo().search([
('alias_parent_model_id.model', '=', model),
('alias_parent_thread_id', 'in', res_ids),
('alias_name', '!=', False)])
# take only first found alias for each thread_id, to match order (1 found -> limit=1 for each res_id)
for alias in mail_aliases:
result_email.setdefault(alias.alias_parent_thread_id, '%s@%s' % (alias.alias_name, alias_domain))
# left ids: use catchall
left_ids = set(_res_ids) - set(result_email)
if left_ids:
catchall = self.env['ir.config_parameter'].sudo().get_param("mail.catchall.alias")
if catchall:
result_email.update(dict((rid, '%s@%s' % (catchall, alias_domain)) for rid in left_ids))
for res_id in result_email:
result[res_id] = self._notify_get_reply_to_formatted_email(
result_email[res_id],
doc_names.get(res_id) or '',
company
)
left_ids = set(_res_ids) - set(result_email)
if left_ids:
result.update(dict((res_id, default) for res_id in left_ids))
return result
def _notify_get_reply_to_formatted_email(self, record_email, record_name, company):
""" Compute formatted email for reply_to and try to avoid refold issue
with python that splits the reply-to over multiple lines. It is due to
a bad management of quotes (missing quotes after refold). This appears
therefore only when having quotes (aka not simple names, and not when
being unicode encoded).
To avoid that issue when formataddr would return more than 78 chars we
return a simplified name/email to try to stay under 78 chars. If not
possible we return only the email and skip the formataddr which causes
the issue in python. We do not use hacks like crop the name part as
encoding and quoting would be error prone.
"""
# address itself is too long for 78 chars limit: return only email
if len(record_email) >= 78:
return record_email
company_name = company.name if company else self.env.company.name
# try company_name + record_name, or record_name alone (or company_name alone)
name = f"{company_name} {record_name}" if record_name else company_name
formatted_email = tools.formataddr((name, record_email))
if len(formatted_email) > 78:
formatted_email = tools.formataddr((record_name or company_name, record_email))
if len(formatted_email) > 78:
formatted_email = record_email
return formatted_email
# ------------------------------------------------------------
# ALIAS MANAGEMENT
# ------------------------------------------------------------
def _alias_get_error_message(self, message, message_dict, alias):
""" Generic method that takes a record not necessarily inheriting from
mail.alias.mixin. """
author = self.env['res.partner'].browse(message_dict.get('author_id', False))
if alias.alias_contact == 'followers':
if not self.ids:
return _('incorrectly configured alias (unknown reference record)')
if not hasattr(self, "message_partner_ids"):
return _('incorrectly configured alias')
if not author or author not in self.message_partner_ids:
return _('restricted to followers')
elif alias.alias_contact == 'partners' and not author:
return _('restricted to known authors')
return False
# ------------------------------------------------------------
# ACTIVITY
# ------------------------------------------------------------
@api.model
def _get_default_activity_view(self):
""" Generates an empty activity view.
:returns: a activity view as an lxml document
:rtype: etree._Element
"""
field = E.field(name=self._rec_name_fallback())
activity_box = E.div(field, {'t-name': "activity-box"})
templates = E.templates(activity_box)
return E.activity(templates, string=self._description)
# ------------------------------------------------------------
# GATEWAY: NOTIFICATION
# ------------------------------------------------------------
def _mail_get_message_subtypes(self):
return self.env['mail.message.subtype'].search([
'&', ('hidden', '=', False),
'|', ('res_model', '=', self._name), ('res_model', '=', False)])
def _notify_email_headers(self):
"""
Generate the email headers based on record
"""
if not self:
return {}
self.ensure_one()
return repr(self._notify_email_header_dict())
def _notify_email_header_dict(self):
return {
'X-Odoo-Objects': "%s-%s" % (self._name, self.id),
}
| 47.34127 | 11,930 |
1,996 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResUsersSettingsVolumes(models.Model):
""" Represents the volume of the sound that the user of user_setting_id will receive from partner_id. """
_name = 'res.users.settings.volumes'
_description = 'User Settings Volumes'
user_setting_id = fields.Many2one('res.users.settings', required=True, ondelete='cascade', index=True)
partner_id = fields.Many2one('res.partner', ondelete='cascade', index=True)
guest_id = fields.Many2one('res.partner', ondelete='cascade', index=True)
volume = fields.Float(default=0.5, help="Ranges between 0.0 and 1.0, scale depends on the browser implementation")
def init(self):
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS res_users_settings_volumes_partner_unique ON %s (user_setting_id, partner_id) WHERE partner_id IS NOT NULL" % self._table)
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS res_users_settings_volumes_guest_unique ON %s (user_setting_id, guest_id) WHERE guest_id IS NOT NULL" % self._table)
_sql_constraints = [
("partner_or_guest_exists", "CHECK((partner_id IS NOT NULL AND guest_id IS NULL) OR (partner_id IS NULL AND guest_id IS NOT NULL))", "A volume setting must have a partner or a guest."),
]
def _discuss_users_settings_volume_format(self):
return [{
'id': volume_setting.id,
'volume': volume_setting.volume,
'guest': [('insert-and-replace', {
'id': volume_setting.guest_id.id,
'name': volume_setting.guest_id.name,
})] if volume_setting.guest_id else [('clear',)],
'partner': [('insert-and-replace', {
'id': volume_setting.partner_id.id,
'name': volume_setting.partner_id.name,
})] if volume_setting.partner_id else [('clear',)]
} for volume_setting in self]
| 53.945946 | 1,996 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.