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
|
|---|---|---|---|---|---|---|
1,303
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Quizzes on Tracks',
'category': 'Marketing/Events',
'sequence': 1007,
'version': '1.0',
'summary': 'Quizzes on tracks',
'website': 'https://www.odoo.com/app/events',
'description': "",
'depends': [
'website_profile',
'website_event_track',
],
'data': [
'security/ir.model.access.csv',
'views/event_leaderboard_templates.xml',
'views/event_quiz_views.xml',
'views/event_quiz_question_views.xml',
'views/event_track_views.xml',
'views/event_track_visitor_views.xml',
'views/event_menus.xml',
'views/event_quiz_templates.xml',
'views/event_track_templates_page.xml',
'views/event_event_views.xml',
'views/event_type_views.xml'
],
'demo': [
'data/quiz_demo.xml',
],
'application': False,
'installable': True,
'assets': {
'web.assets_frontend': [
'website_event_track_quiz/static/src/scss/event_quiz.scss',
'website_event_track_quiz/static/src/js/event_quiz.js',
'website_event_track_quiz/static/src/js/event_quiz_leaderboard.js',
],
},
'license': 'LGPL-3',
}
| 30.302326
| 1,303
|
3,032
|
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
class Quiz(models.Model):
_name = "event.quiz"
_description = "Quiz"
name = fields.Char('Name', required=True, translate=True)
question_ids = fields.One2many('event.quiz.question', 'quiz_id', string="Questions")
event_track_id = fields.Many2one('event.track', readonly=True)
event_id = fields.Many2one(
'event.event', related='event_track_id.event_id',
readonly=True, store=True)
repeatable = fields.Boolean('Unlimited Tries',
help='Let attendees reset the quiz and try again.')
class QuizQuestion(models.Model):
_name = "event.quiz.question"
_description = "Content Quiz Question"
_order = "quiz_id, sequence, id"
name = fields.Char("Question", required=True, translate=True)
sequence = fields.Integer("Sequence")
quiz_id = fields.Many2one("event.quiz", "Quiz", required=True, ondelete='cascade')
correct_answer_id = fields.One2many('event.quiz.answer', compute='_compute_correct_answer_id')
awarded_points = fields.Integer("Number of Points", compute='_compute_awarded_points')
answer_ids = fields.One2many('event.quiz.answer', 'question_id', string="Answer")
@api.depends('answer_ids.awarded_points')
def _compute_awarded_points(self):
for question in self:
question.awarded_points = sum(question.answer_ids.mapped('awarded_points'))
@api.depends('answer_ids.is_correct')
def _compute_correct_answer_id(self):
for question in self:
question.correct_answer_id = question.answer_ids.filtered(lambda e: e.is_correct)
@api.constrains('answer_ids')
def _check_answers_integrity(self):
for question in self:
if len(question.correct_answer_id) != 1:
raise ValidationError(_('Question "%s" must have 1 correct answer to be valid.', question.name))
if len(question.answer_ids) < 2:
raise ValidationError(_('Question "%s" must have 1 correct answer and at least 1 incorrect answer to be valid.', question.name))
class QuizAnswer(models.Model):
_name = "event.quiz.answer"
_rec_name = "text_value"
_description = "Question's Answer"
_order = 'question_id, sequence, id'
sequence = fields.Integer("Sequence")
question_id = fields.Many2one('event.quiz.question', string="Question", required=True, ondelete='cascade')
text_value = fields.Char("Answer", required=True, translate=True)
is_correct = fields.Boolean('Correct', default=False)
comment = fields.Text(
'Extra Comment', translate=True,
help='''This comment will be displayed to the user if he selects this answer, after submitting the quiz.
It is used as a small informational text helping to understand why this answer is correct / incorrect.''')
awarded_points = fields.Integer('Points', default=0)
| 45.253731
| 3,032
|
829
|
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 Event(models.Model):
_inherit = "event.event"
@api.depends("event_type_id", "website_menu", "community_menu")
def _compute_community_menu(self):
""" At type onchange: synchronize. At website_menu update: synchronize. """
for event in self:
if event.event_type_id and event.event_type_id != event._origin.event_type_id:
event.community_menu = event.event_type_id.community_menu
elif event.website_menu and (event.website_menu != event._origin.website_menu or not event.community_menu):
event.community_menu = True
elif not event.website_menu:
event.community_menu = False
| 43.631579
| 829
|
4,340
|
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.osv import expression
class EventTrack(models.Model):
_inherit = ['event.track']
quiz_id = fields.Many2one('event.quiz', string="Quiz", compute='_compute_quiz_id', store=True, groups="event.group_event_user")
quiz_ids = fields.One2many('event.quiz', 'event_track_id', string="Quizzes")
quiz_questions_count = fields.Integer(string="# Quiz Questions", compute='_compute_quiz_questions_count', groups="event.group_event_user")
is_quiz_completed = fields.Boolean('Is Quiz Done', compute='_compute_quiz_data')
quiz_points = fields.Integer('Quiz Points', compute='_compute_quiz_data')
@api.depends('quiz_ids.event_track_id')
def _compute_quiz_id(self):
for track in self:
track.quiz_id = track.quiz_ids[0] if track.quiz_ids else False
@api.depends('quiz_id.question_ids')
def _compute_quiz_questions_count(self):
for track in self:
track.quiz_questions_count = len(track.quiz_id.question_ids)
@api.depends('quiz_id', 'event_track_visitor_ids.visitor_id',
'event_track_visitor_ids.partner_id', 'event_track_visitor_ids.quiz_completed',
'event_track_visitor_ids.quiz_points')
@api.depends_context('uid')
def _compute_quiz_data(self):
tracks_quiz = self.filtered(lambda track: track.quiz_id)
(self - tracks_quiz).is_quiz_completed = False
(self - tracks_quiz).quiz_points = 0
if tracks_quiz:
current_visitor = self.env['website.visitor']._get_visitor_from_request(force_create=False)
if self.env.user._is_public() and not current_visitor:
for track in tracks_quiz:
track.is_quiz_completed = False
track.quiz_points = 0
else:
if self.env.user._is_public():
domain = [('visitor_id', '=', current_visitor.id)]
elif current_visitor:
domain = [
'|',
('partner_id', '=', self.env.user.partner_id.id),
('visitor_id', '=', current_visitor.id)
]
else:
domain = [('partner_id', '=', self.env.user.partner_id.id)]
event_track_visitors = self.env['event.track.visitor'].sudo().search_read(
expression.AND([
domain,
[('track_id', 'in', tracks_quiz.ids)]
]), fields=['track_id', 'quiz_completed', 'quiz_points']
)
quiz_visitor_map = {
track_visitor['track_id'][0]: {
'quiz_completed': track_visitor['quiz_completed'],
'quiz_points': track_visitor['quiz_points']
} for track_visitor in event_track_visitors
}
for track in tracks_quiz:
if quiz_visitor_map.get(track.id):
track.is_quiz_completed = quiz_visitor_map[track.id]['quiz_completed']
track.quiz_points = quiz_visitor_map[track.id]['quiz_points']
else:
track.is_quiz_completed = False
track.quiz_points = 0
def action_add_quiz(self):
self.ensure_one()
event_quiz_form = self.env.ref('website_event_track_quiz.event_quiz_view_form')
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'event.quiz',
'view_id': event_quiz_form.id,
'context': {
'default_event_track_id': self.id,
'create': False,
},
}
def action_view_quiz(self):
self.ensure_one()
event_quiz_form = self.env.ref('website_event_track_quiz.event_quiz_view_form')
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'event.quiz',
'res_id' : self.quiz_id.id,
'view_id': event_quiz_form.id,
'context': {
'create': False,
}
}
| 43.4
| 4,340
|
350
|
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 TrackVisitor(models.Model):
_name = 'event.track.visitor'
_inherit = ['event.track.visitor']
quiz_completed = fields.Boolean('Completed')
quiz_points = fields.Integer("Quiz Points", default=0)
| 29.166667
| 350
|
3,347
|
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_track.controllers.event_track import EventTrackController
from odoo.http import request
class WebsiteEventTrackQuiz(EventTrackController):
# QUIZZES IN PAGE
# ----------------------------------------------------------
@http.route('/event_track/quiz/submit', type="json", auth="public", website=True)
def event_track_quiz_submit(self, event_id, track_id, answer_ids):
track = self._fetch_track(track_id)
track_sudo = track.sudo()
event_track_visitor = track._get_event_track_visitors(force_create=True)
visitor_sudo = event_track_visitor.visitor_id
if event_track_visitor.quiz_completed:
return {'error': 'track_quiz_done'}
# fetch as sudo because questions / answers may not be freely available to public
answers_details = self._get_quiz_answers_details(track_sudo, answer_ids)
if answers_details.get('error'):
return answers_details
event_track_visitor.write({
'quiz_completed': True,
'quiz_points': answers_details['points'],
})
result = {
'answers': {
answer.question_id.id: {
'awarded_points': answer.awarded_points,
'correct_answer': answer.question_id.correct_answer_id.text_value,
'is_correct': answer.is_correct,
'comment': answer.comment
} for answer in answers_details['user_answers']
},
'quiz_completed': event_track_visitor.quiz_completed,
'quiz_points': answers_details['points']
}
if visitor_sudo and request.httprequest.cookies.get('visitor_uuid', '') != visitor_sudo.access_token:
result['visitor_uuid'] = visitor_sudo.access_token
return result
@http.route('/event_track/quiz/reset', type="json", auth="public", website=True)
def quiz_reset(self, event_id, track_id):
track = self._fetch_track(track_id)
# When the 'unlimited tries' option is disabled and the user is not
# identifed as an event manager, we do not allow the user to reset
# the quiz. The event managers will always be able to reset the quiz
# even if the option is disabled (for testing purposes).
if not request.env.user.has_group('event.group_event_manager') and not track.sudo().quiz_id.repeatable:
raise Forbidden()
event_track_visitor = track._get_event_track_visitors(force_create=True)
event_track_visitor.write({
'quiz_completed': False,
'quiz_points': 0,
})
def _get_quiz_answers_details(self, track, answer_ids):
questions_count = track.quiz_questions_count
user_answers = request.env['event.quiz.answer'].sudo().search([('id', 'in', answer_ids)])
if len(user_answers.mapped('question_id')) != questions_count:
return {'error': 'quiz_incomplete'}
return {
'user_answers': user_answers,
'points': sum([
answer.awarded_points
for answer in user_answers
])
}
| 41.320988
| 3,347
|
4,553
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import math
from odoo import http
from odoo.addons.http_routing.models.ir_http import slug
from odoo.addons.website_event.controllers.community import EventCommunityController
from odoo.http import request
class WebsiteEventTrackQuizCommunityController(EventCommunityController):
_visitors_per_page = 30
_pager_max_pages = 5
@http.route(['/event/<model("event.event"):event>/community/leaderboard/results',
'/event/<model("event.event"):event>/community/leaderboard/results/page/<int:page>'],
type='http', auth="public", website=True, sitemap=False)
def leaderboard(self, event, page=1, lang=None, **kwargs):
values = self._get_community_leaderboard_render_values(event, kwargs.get('search'), page)
return request.render('website_event_track_quiz.event_leaderboard', values)
@http.route('/event/<model("event.event"):event>/community/leaderboard',
type='http', auth="public", website=True, sitemap=False)
def community_leaderboard(self, event, **kwargs):
values = self._get_community_leaderboard_render_values(event, None, None)
return request.render('website_event_track_quiz.event_leaderboard', values)
@http.route('/event/<model("event.event"):event>/community',
type='http', auth="public", website=True, sitemap=False)
def community(self, event, **kwargs):
values = self._get_community_leaderboard_render_values(event, None, None)
return request.render('website_event_track_quiz.event_leaderboard', values)
def _get_community_leaderboard_render_values(self, event, search_term, page):
values = self._get_leaderboard(event, search_term)
values.update({'event': event, 'search': search_term})
user_count = len(values['visitors'])
if user_count:
page_count = math.ceil(user_count / self._visitors_per_page)
url = '/event/%s/community/leaderboard/results' % (slug(event))
if values.get('current_visitor_position') and not page:
values['scroll_to_position'] = True
page = math.ceil(values['current_visitor_position'] / self._visitors_per_page)
elif not page:
page = 1
pager = request.website.pager(url=url, total=user_count, page=page, step=self._visitors_per_page,
scope=page_count if page_count < self._pager_max_pages else self._pager_max_pages,
url_args={'search': search_term})
values['visitors'] = values['visitors'][(page - 1) * self._visitors_per_page: (page) * self._visitors_per_page]
else:
pager = {'page_count': 0}
values.update({'pager': pager})
return values
def _get_leaderboard(self, event, searched_name=None):
current_visitor = request.env['website.visitor']._get_visitor_from_request(force_create=False)
track_visitor_data = request.env['event.track.visitor'].sudo().read_group(
[('track_id', 'in', event.track_ids.ids),
('visitor_id', '!=', False),
('quiz_points', '>', 0)],
['id', 'visitor_id', 'points:sum(quiz_points)'],
['visitor_id'], orderby="points DESC")
data_map = {datum['visitor_id'][0]: datum['points'] for datum in track_visitor_data if datum.get('visitor_id')}
leaderboard = []
position = 1
current_visitor_position = False
visitors_by_id = {
visitor.id: visitor
for visitor in request.env['website.visitor'].sudo().browse(data_map.keys())
}
for visitor_id, points in data_map.items():
visitor = visitors_by_id.get(visitor_id)
if not visitor:
continue
if (searched_name and searched_name.lower() in visitor.display_name.lower()) or not searched_name:
leaderboard.append({'visitor': visitor, 'points': points, 'position': position})
if current_visitor and current_visitor == visitor:
current_visitor_position = position
position = position + 1
return {
'top3_visitors': leaderboard[:3],
'visitors': leaderboard,
'current_visitor_position': current_visitor_position,
'current_visitor': current_visitor,
'searched_name': searched_name
}
| 50.588889
| 4,553
|
731
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Event CRM',
'version': '1.0',
'category': 'Marketing/Events',
'website': 'https://www.odoo.com/app/events',
'description': "Create leads from event registrations.",
'depends': ['event', 'crm'],
'data': [
'security/event_crm_security.xml',
'security/ir.model.access.csv',
'views/crm_lead_views.xml',
'views/event_registration_views.xml',
'views/event_lead_rule_views.xml',
'views/event_event_views.xml',
],
'demo': [
'data/event_crm_demo.xml',
],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 29.24
| 731
|
5,913
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.addons.event.tests.common import TestEventCommon
class TestEventCrmCommon(TestCrmCommon, TestEventCommon):
@classmethod
def setUpClass(cls):
super(TestEventCrmCommon, cls).setUpClass()
# avoid clash with existing rules
cls.env['event.lead.rule'].search([]).write({'active': False})
cls.test_lead_tag = cls.env['crm.tag'].create({'name': 'TagTest'})
cls.test_rule_attendee = cls.env['event.lead.rule'].create({
'name': 'Rule Attendee',
'lead_creation_basis': 'attendee',
'lead_creation_trigger': 'create',
'event_id': cls.event_0.id,
'event_registration_filter': [['email', 'ilike', '@test.example.com']],
'lead_type': 'lead',
'lead_user_id': cls.user_sales_salesman.id,
'lead_tag_ids': cls.test_lead_tag,
})
cls.test_rule_order = cls.env['event.lead.rule'].create({
'name': 'Rule Order',
'lead_creation_basis': 'order',
'lead_creation_trigger': 'create',
'event_id': cls.event_0.id,
'event_registration_filter': [['email', 'ilike', '@test.example.com']],
'lead_type': 'opportunity',
'lead_user_id': cls.user_sales_leads.id,
'lead_sales_team_id': cls.sales_team_1.id,
})
cls.test_rule_order_done = cls.env['event.lead.rule'].create({
'name': 'Rule Order: confirmed partner only',
'lead_creation_basis': 'order',
'lead_creation_trigger': 'done',
'event_registration_filter': [['partner_id', '!=', False]],
'lead_type': 'opportunity',
})
cls.batch_customer_data = [{
'partner_id': cls.event_customer.id,
}] + [{
'name': 'My Customer 00',
'partner_id': cls.event_customer2.id,
'email': 'email.00@test.example.com',
'phone': '0456000000',
}] + [{
'name': 'My Customer %02d' % x,
'partner_id': cls.env.ref('base.public_partner').id if x == 0 else False,
'email': 'email.%02d@test.example.com' % x,
'phone': '04560000%02d' % x,
} for x in range(1, 4)]
def assertLeadConvertion(self, rule, registrations, partner=None, **expected):
""" Tool method hiding details of lead value generation and check
:param lead: lead created through automated rule;
:param rule: event.lead.rule that created the lead;
:param event: original event;
:param registrations: source registrations (singleton or record set if done in batch);
:param partner: partner on lead;
"""
registrations = registrations.sorted('id') # currently order is forced to id ASC
lead = self.env['crm.lead'].sudo().search([
('registration_ids', 'in', registrations.ids),
('event_lead_rule_id', '=', rule.id)
])
self.assertEqual(len(lead), 1, 'Invalid registrations -> lead creation, found %s leads where only 1 is expected.' % len(lead))
self.assertEqual(lead.registration_ids, registrations, 'Invalid registrations -> lead creation, too much registrations on it.')
event = registrations.event_id
self.assertEqual(len(event), 1, 'Invalid registrations -> event assertion, all registrations should belong to same event')
if partner is None:
partner = self.env['res.partner']
expected_reg_name = partner.name or registrations._find_first_notnull('name') or registrations._find_first_notnull('email')
if partner:
expected_contact_name = partner.name if not partner.is_company else False
expected_partner_name = partner.name if partner.is_company else False
else:
expected_contact_name = registrations._find_first_notnull('name')
expected_partner_name = False
# event information
self.assertEqual(lead.event_id, event)
self.assertEqual(lead.referred, event.name)
# registration information
self.assertEqual(lead.partner_id, partner)
self.assertEqual(lead.name, '%s - %s' % (event.name, expected_reg_name))
self.assertNotIn('False', lead.name) # avoid a "Dear False" like construct ^^ (this assert is serious and intended)
self.assertEqual(lead.contact_name, expected_contact_name)
self.assertEqual(lead.partner_name, expected_partner_name)
self.assertEqual(lead.email_from, partner.email if partner else registrations._find_first_notnull('email'))
self.assertEqual(lead.phone, partner.phone if partner else registrations._find_first_notnull('phone'))
self.assertEqual(lead.mobile, partner.mobile if partner and partner.mobile else registrations._find_first_notnull('mobile'))
# description: to improve
self.assertNotIn('False', lead.description) # avoid a "Dear False" like construct ^^ (this assert is serious and intended)
for registration in registrations:
if registration.name:
self.assertIn(registration.name, lead.description)
elif registration.partner_id.name:
self.assertIn(registration.partner_id.name, lead.description)
if registration.email:
self.assertIn(registration.email, lead.description)
if registration.phone:
self.assertIn(registration.phone, lead.description)
# lead configuration
self.assertEqual(lead.type, rule.lead_type)
self.assertEqual(lead.user_id, rule.lead_user_id)
self.assertEqual(lead.team_id, rule.lead_sales_team_id)
self.assertEqual(lead.tag_ids, rule.lead_tag_ids)
| 48.467213
| 5,913
|
8,659
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.event_crm.tests.common import TestEventCrmCommon
from odoo.tests.common import users
from odoo.tools import mute_logger
class TestEventCrmFlow(TestEventCrmCommon):
@classmethod
def setUpClass(cls):
super(TestEventCrmFlow, cls).setUpClass()
cls.registration_values = [
dict(customer_data, event_id=cls.event_0.id)
for customer_data in cls.batch_customer_data
]
cls.registration_values[-1]['email'] = '"John Doe" <invalid@not.example.com>'
def assert_initial_data(self):
self.assertEqual(len(self.registration_values), 5)
self.assertEqual(self.event_customer.email_normalized, 'constantin@test.example.com')
self.assertEqual(self.event_customer.phone, '0485112233')
self.assertFalse(self.event_customer.mobile)
@users('user_eventregistrationdesk')
def test_event_crm_flow_batch_create(self):
""" Test attendee- and order-based registrations creation. Event-based
creation mimics a simplified website_event flow where grouping is done
at create. """
new_registrations = self.env['event.registration'].create(self.registration_values)
self.assertEqual(len(self.event_0.registration_ids), 5)
# per-attendee rule: one lead for each registration
self.assertEqual(len(self.test_rule_attendee.lead_ids), 4)
for registration in new_registrations:
lead = self.test_rule_attendee.lead_ids.filtered(lambda lead: registration in lead.registration_ids)
# test filtering out based on domain
if registration.email == '"John Doe" <invalid@not.example.com>':
self.assertEqual(lead, self.env['crm.lead'])
continue
# only partner with matching email / phone is kept in mono attendee mode to avoid
# loosing registration-specific email / phone informations due to lead synchronization
expected_partner = registration.partner_id if registration.partner_id == self.event_customer else None
self.assertTrue(bool(lead))
self.assertLeadConvertion(self.test_rule_attendee, registration, partner=expected_partner)
# per-order rule: one lead for all registrations (same event -> same batch, website_event style)
self.assertEqual(len(self.test_rule_order.lead_ids), 1)
lead = self.test_rule_order.lead_ids
self.assertLeadConvertion(
self.test_rule_order,
new_registrations.filtered(lambda reg: reg.email != '"John Doe" <invalid@not.example.com>'),
partner=new_registrations[0].partner_id
)
# ensuring filtering out worked also at description level
self.assertNotIn('invalid@not.example.com', lead.description)
@users('user_eventregistrationdesk')
def test_event_crm_flow_batch_update(self):
""" Test update of contact or description fields that leads to lead
update. """
# initial data: create registrations in batch
new_registrations = self.env['event.registration'].create(self.registration_values)
self.assertEqual(len(self.event_0.registration_ids), 5)
self.assertEqual(len(self.test_rule_attendee.lead_ids), 4)
self.assertEqual(len(self.test_rule_order.lead_ids), 1)
# customer is updated (like a SO setting its customer)
new_registrations.write({'partner_id': self.event_customer2.id})
# per-attendee rule
self.assertEqual(len(self.test_rule_attendee.lead_ids), 4)
for registration in new_registrations:
lead = self.test_rule_attendee.lead_ids.filtered(lambda lead: registration in lead.registration_ids)
# test filtering out based on domain
if registration.email == '"John Doe" <invalid@not.example.com>':
self.assertEqual(lead, self.env['crm.lead'])
continue
# only partner with matching email / phone is kept in mono attendee mode to avoid
# loosing registration-specific email / phone informations due to lead synchronization
self.assertLeadConvertion(self.test_rule_attendee, registration, partner=None)
# per-order rule
self.assertEqual(len(self.test_rule_order.lead_ids), 1)
self.assertEqual(self.test_rule_order.lead_ids.event_id, self.event_0)
lead = self.test_rule_order.lead_ids
self.assertLeadConvertion(
self.test_rule_order,
new_registrations.filtered(lambda reg: reg.email != '"John Doe" <invalid@not.example.com>'),
partner=new_registrations[0].partner_id
)
# ensuring filtering out worked also at description level
self.assertNotIn('invalid@not.example.com', lead.description)
@users('user_eventregistrationdesk')
def test_event_crm_flow_per_attendee_single(self):
self.assert_initial_data()
# test: partner-based contact information, everything synchonized
registration = self.env['event.registration'].create({
'partner_id': self.event_customer.id,
'event_id': self.event_0.id,
})
self.assertEqual(registration.email, self.event_customer.email)
self.assertEqual(registration.phone, self.event_customer.phone)
# per-attendee rule
self.assertLeadConvertion(self.test_rule_attendee, registration, partner=registration.partner_id)
# test: no partner and contact information
registration = self.env['event.registration'].create({
'name': 'My Registration',
'partner_id': False,
'email': 'super.email@test.example.com',
'phone': False,
'mobile': '0456332211',
'event_id': self.event_0.id,
})
self.assertEqual(len(self.event_0.registration_ids), 2)
self.assertLeadConvertion(self.test_rule_attendee, registration, partner=None)
# test: no partner and few information
registration = self.env['event.registration'].create({
'name': False,
'partner_id': False,
'email': 'giga.email@test.example.com',
'phone': False,
'mobile': False,
'event_id': self.event_0.id,
})
self.assertEqual(len(self.event_0.registration_ids), 3)
self.assertLeadConvertion(self.test_rule_attendee, registration, partner=None)
# test: partner but with other contact information -> registration prior
registration = self.env['event.registration'].create({
'partner_id': self.event_customer.id,
'email': 'other.email@test.example.com',
'phone': False,
'mobile': '0456112233',
'event_id': self.event_0.id,
})
self.assertEqual(len(self.event_0.registration_ids), 4)
self.assertLeadConvertion(self.test_rule_attendee, registration, partner=None)
@users('user_eventregistrationdesk')
def test_event_crm_trigger_done(self):
"""Test the case when the "crm.lead.rule" is executed when we write on the
registration state. """
registration = self.env['event.registration'].create({
'partner_id': self.event_customer.id,
'email': 'trigger.test@not.test.example.com',
'phone': False,
'mobile': '0456112233',
'event_id': self.event_0.id,
})
leads = self.env['crm.lead'].sudo().search([
('registration_ids', 'in', registration.ids),
])
self.assertFalse(leads, 'The lead must not be created yet')
registration.action_set_done()
self.assertLeadConvertion(self.test_rule_order_done, registration)
@users('user_eventmanager')
def test_order_rule_duplicate_lead(self):
""" Check when two rules match one event
but only one match the registration,
only one lead should be created
"""
test_rule_order_2 = self.test_rule_order.copy(default={
'event_registration_filter': [['email', 'not ilike', '@test.example.com']]
})
self.env['event.registration'].create({
'name': 'My Registration',
'partner_id': False,
'email': 'super.email@test.example.com',
'phone': False,
'mobile': '0456332211',
'event_id': self.event_0.id,
})
self.assertEqual(len(self.test_rule_order.lead_ids), 1)
self.assertEqual(len(test_rule_order_2.lead_ids), 0)
| 46.058511
| 8,659
|
1,649
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.test_crm_lead_merge import TestLeadMergeCommon
from odoo.addons.event_crm.tests.common import TestEventCrmCommon
from odoo.tests.common import tagged, users
@tagged('lead_manage')
class TestLeadCrmMerge(TestLeadMergeCommon, TestEventCrmCommon):
@users('user_sales_manager')
def test_merge_method_dependencies(self):
""" Test if dependences for leads are not lost while merging leads. In
this test leads are ordered as
lead_w_contact -----------lead---seq=30
lead_w_email -------------lead---seq=3
lead_1 -------------------lead---seq=1
lead_w_partner_company ---lead---seq=1----------------registrations
lead_w_partner -----------lead---seq=False
"""
TestLeadMergeCommon.merge_fields.append('registration_ids')
registration = self.env['event.registration'].sudo().create({
'partner_id': self.event_customer.id,
'event_id': self.event_0.id,
'lead_ids': [(4, self.lead_w_partner_company.id)],
})
self.assertEqual(self.lead_w_partner_company.registration_ids, registration)
leads = self.env['crm.lead'].browse(self.leads.ids)._sort_by_confidence_level(reverse=True)
with self.assertLeadMerged(self.lead_w_contact, leads,
name=self.lead_w_contact.name,
registration_ids=registration
):
leads._merge_opportunity(auto_unlink=False, max_length=None)
| 44.567568
| 1,649
|
16,735
|
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 api, fields, models, _
class EventRegistration(models.Model):
_inherit = 'event.registration'
lead_ids = fields.Many2many(
'crm.lead', string='Leads', copy=False, readonly=True,
groups='sales_team.group_sale_salesman',
help="Leads generated from the registration.")
lead_count = fields.Integer(
'# Leads', compute='_compute_lead_count', compute_sudo=True,
help="Counter for the leads linked to this registration")
@api.depends('lead_ids')
def _compute_lead_count(self):
for record in self:
record.lead_count = len(record.lead_ids)
@api.model_create_multi
def create(self, vals_list):
""" Trigger rules based on registration creation, and check state for
rules based on confirmed / done attendees. """
registrations = super(EventRegistration, self).create(vals_list)
# handle triggers based on creation, then those based on confirm and done
# as registrations can be automatically confirmed, or even created directly
# with a state given in values
if not self.env.context.get('event_lead_rule_skip'):
self.env['event.lead.rule'].search([('lead_creation_trigger', '=', 'create')]).sudo()._run_on_registrations(registrations)
open_registrations = registrations.filtered(lambda reg: reg.state == 'open')
if open_registrations:
self.env['event.lead.rule'].search([('lead_creation_trigger', '=', 'confirm')]).sudo()._run_on_registrations(open_registrations)
done_registrations = registrations.filtered(lambda reg: reg.state == 'done')
if done_registrations:
self.env['event.lead.rule'].search([('lead_creation_trigger', '=', 'done')]).sudo()._run_on_registrations(done_registrations)
return registrations
def write(self, vals):
""" Update the lead values depending on fields updated in registrations.
There are 2 main use cases
* first is when we update the partner_id of multiple registrations. It
happens when a public user fill its information when he register to
an event;
* second is when we update specific values of one registration like
updating question answers or a contact information (email, phone);
Also trigger rules based on confirmed and done attendees (state written
to open and done).
"""
to_update, event_lead_rule_skip = False, self.env.context.get('event_lead_rule_skip')
if not event_lead_rule_skip:
to_update = self.filtered(lambda reg: reg.lead_count)
if to_update:
lead_tracked_vals = to_update._get_lead_tracked_values()
res = super(EventRegistration, self).write(vals)
if not event_lead_rule_skip and to_update:
to_update.flush() # compute notably partner-based fields if necessary
to_update.sudo()._update_leads(vals, lead_tracked_vals)
# handle triggers based on state
if not event_lead_rule_skip:
if vals.get('state') == 'open':
self.env['event.lead.rule'].search([('lead_creation_trigger', '=', 'confirm')]).sudo()._run_on_registrations(self)
elif vals.get('state') == 'done':
self.env['event.lead.rule'].search([('lead_creation_trigger', '=', 'done')]).sudo()._run_on_registrations(self)
return res
def _load_records_create(self, values):
""" In import mode: do not run rules those are intended to run when customers
buy tickets, not when bootstrapping a database. """
return super(EventRegistration, self.with_context(event_lead_rule_skip=True))._load_records_create(values)
def _load_records_write(self, values):
""" In import mode: do not run rules those are intended to run when customers
buy tickets, not when bootstrapping a database. """
return super(EventRegistration, self.with_context(event_lead_rule_skip=True))._load_records_write(values)
def _update_leads(self, new_vals, lead_tracked_vals):
""" Update leads linked to some registrations. Update is based depending
on updated fields, see ``_get_lead_contact_fields()`` and ``_get_lead_
description_fields()``. Main heuristic is
* check attendee-based leads, for each registration recompute contact
information if necessary (changing partner triggers the whole contact
computation); update description if necessary;
* check order-based leads, for each existing group-based lead, only
partner change triggers a contact and description update. We consider
that group-based rule works mainly with the main contact and less
with further details of registrations. Those can be found in stat
button if necessary.
:param new_vals: values given to write. Used to determine updated fields;
:param lead_tracked_vals: dict(registration_id, registration previous values)
based on new_vals;
"""
for registration in self:
leads_attendee = registration.lead_ids.filtered(
lambda lead: lead.event_lead_rule_id.lead_creation_basis == 'attendee'
)
if not leads_attendee:
continue
old_vals = lead_tracked_vals[registration.id]
# if partner has been updated -> update registration contact information
# as they are computed (and therefore not given to write values)
if 'partner_id' in new_vals:
new_vals.update(**dict(
(field, registration[field])
for field in self._get_lead_contact_fields()
if field != 'partner_id')
)
lead_values = {}
# update contact fields: valid for all leads of registration
upd_contact_fields = [field for field in self._get_lead_contact_fields() if field in new_vals.keys()]
if any(new_vals[field] != old_vals[field] for field in upd_contact_fields):
lead_values = registration._get_lead_contact_values()
# update description fields: each lead has to be updated, otherwise
# update in batch
upd_description_fields = [field for field in self._get_lead_description_fields() if field in new_vals.keys()]
if any(new_vals[field] != old_vals[field] for field in upd_description_fields):
for lead in leads_attendee:
lead_values['description'] = "%s<br/>%s" % (
lead.description,
registration._get_lead_description(_("Updated registrations"), line_counter=True)
)
lead.write(lead_values)
elif lead_values:
leads_attendee.write(lead_values)
leads_order = self.lead_ids.filtered(lambda lead: lead.event_lead_rule_id.lead_creation_basis == 'order')
for lead in leads_order:
lead_values = {}
if new_vals.get('partner_id'):
lead_values.update(lead.registration_ids._get_lead_contact_values())
if not lead.partner_id:
lead_values['description'] = lead.registration_ids._get_lead_description(_("Participants"), line_counter=True)
elif new_vals['partner_id'] != lead.partner_id.id:
lead_values['description'] = lead.description + "<br/>" + lead.registration_ids._get_lead_description(_("Updated registrations"), line_counter=True, line_suffix=_("(updated)"))
if lead_values:
lead.write(lead_values)
def _get_lead_values(self, rule):
""" Get lead values from registrations. Self can contain multiple records
in which case first found non void value is taken. Note that all
registrations should belong to the same event.
:return dict lead_values: values used for create / write on a lead
"""
lead_values = {
# from rule
'type': rule.lead_type,
'user_id': rule.lead_user_id.id,
'team_id': rule.lead_sales_team_id.id,
'tag_ids': rule.lead_tag_ids.ids,
'event_lead_rule_id': rule.id,
# event and registration
'event_id': self.event_id.id,
'referred': self.event_id.name,
'registration_ids': self.ids,
'campaign_id': self._find_first_notnull('utm_campaign_id'),
'source_id': self._find_first_notnull('utm_source_id'),
'medium_id': self._find_first_notnull('utm_medium_id'),
}
lead_values.update(self._get_lead_contact_values())
lead_values['description'] = self._get_lead_description(_("Participants"), line_counter=True)
return lead_values
def _get_lead_contact_values(self):
""" Specific management of contact values. Rule creation basis has some
effect on contact management
* in attendee mode: keep registration partner only if partner phone and
email match. Indeed lead are synchronized with their contact and it
would imply rewriting on partner, and therefore on other documents;
* in batch mode: if a customer is found use it as main contact. Registrations
details are included in lead description;
:return dict: values used for create / write on a lead
"""
valid_partner = related_partner = next(
(reg.partner_id for reg in self if reg.partner_id != self.env.ref('base.public_partner')),
self.env['res.partner']
) # CHECKME: broader than just public partner
# mono registration mode: keep partner only if email and phone matches, otherwise registration > partner
if len(self) == 1:
if (related_partner.phone and self.phone and related_partner.phone != self.phone) or \
(related_partner.email and self.email and related_partner.email != self.email):
valid_partner = self.env['res.partner']
if valid_partner:
contact_vals = self.env['crm.lead']._prepare_values_from_partner(valid_partner)
# force email_from / phone only if not set on partner because those fields are now synchronized automatically
if not valid_partner.email:
contact_vals['email_from'] = self._find_first_notnull('email')
if not valid_partner.phone:
contact_vals['email_from'] = self._find_first_notnull('phone')
else:
# don't force email_from + partner_id because those fields are now synchronized automatically
contact_vals = {
'contact_name': self._find_first_notnull('name'),
'email_from': self._find_first_notnull('email'),
'phone': self._find_first_notnull('phone'),
}
contact_vals.update({
'name': "%s - %s" % (self.event_id.name, valid_partner.name or self._find_first_notnull('name') or self._find_first_notnull('email')),
'partner_id': valid_partner.id,
'mobile': valid_partner.mobile or self._find_first_notnull('mobile'),
})
return contact_vals
def _get_lead_description(self, prefix='', line_counter=True, line_suffix=''):
""" Build the description for the lead using a prefix for all generated
lines. For example to enumerate participants or inform of an update in
the information of a participant.
:return string description: complete description for a lead taking into
account all registrations contained in self
"""
reg_lines = [
registration._get_lead_description_registration(
line_suffix=line_suffix
) for registration in self
]
return ("%s<br/>" % prefix if prefix else "") + (
"<ol>" if line_counter else "<ul>") + ("".join(reg_lines)) + ("</ol>" if line_counter else "</ul>")
def _get_lead_description_registration(self, line_suffix=''):
""" Build the description line specific to a given registration. """
self.ensure_one()
return "<li>%s (%s)%s</li>" % (
self.name or self.partner_id.name or self.email,
" - ".join(self[field] for field in ('email', 'phone') if self[field]),
" %s" % line_suffix if line_suffix else "",
)
def _get_lead_tracked_values(self):
""" Tracked values are based on two subset of fields to track in order
to fill or update leads. Two main use cases are
* description fields: registration contact fields: email, phone, ...
on registration. Other fields are added by inheritance like
question answers;
* contact fields: registration contact fields + partner_id field as
contact of a lead is managed specifically. Indeed email and phone
synchronization of lead / partner_id implies paying attention to
not rewrite partner values from registration values.
Tracked values are therefore the union of those two field sets. """
tracked_fields = list(set(self._get_lead_contact_fields()) or set(self._get_lead_description_fields()))
return dict(
(registration.id,
dict((field, self._convert_value(registration[field], field)) for field in tracked_fields)
) for registration in self
)
def _get_lead_grouping(self, rules, rule_to_new_regs):
""" Perform grouping of registrations in order to enable order-based
lead creation and update existing groups with new registrations.
Heuristic in event is the following. Registrations created in multi-mode
are grouped by event. Customer use case: website_event flow creates
several registrations in a create-multi.
Update is not supported as there is no way to determine if a registration
is part of an existing batch.
:param rules: lead creation rules to run on registrations given by self;
:param rule_to_new_regs: dict: for each rule, subset of self matching
rule conditions. Used to speedup batch computation;
:return dict: for each rule, rule (key of dict) gives a list of groups.
Each group is a tuple (
existing_lead: existing lead to update;
group_record: record used to group;
registrations: sub record set of self, containing registrations
belonging to the same group;
)
"""
event_to_reg_ids = defaultdict(lambda: self.env['event.registration'])
for registration in self:
event_to_reg_ids[registration.event_id] += registration
return dict(
(rule, [(False, event, (registrations & rule_to_new_regs[rule]).sorted('id'))
for event, registrations in event_to_reg_ids.items()])
for rule in rules
)
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
@api.model
def _get_lead_contact_fields(self):
""" Get registration fields linked to lead contact. Those are used notably
to see if an update of lead is necessary or to fill contact values
in ``_get_lead_contact_values())`` """
return ['name', 'email', 'phone', 'mobile', 'partner_id']
@api.model
def _get_lead_description_fields(self):
""" Get registration fields linked to lead description. Those are used
notablyto see if an update of lead is necessary or to fill description
in ``_get_lead_description())`` """
return ['name', 'email', 'phone']
def _find_first_notnull(self, field_name):
""" Small tool to extract the first not nullvalue of a field: its value
or the ids if this is a relational field. """
value = next((reg[field_name] for reg in self if reg[field_name]), False)
return self._convert_value(value, field_name)
def _convert_value(self, value, field_name):
""" Small tool because convert_to_write is touchy """
if value and self._fields[field_name].type in ['many2many', 'one2many']:
return value.ids
if value and self._fields[field_name].type == 'many2one':
return value.id
return value
| 50.255255
| 16,735
|
11,050
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from collections import defaultdict
from odoo import fields, models, _
class EventLeadRule(models.Model):
""" Rule model for creating / updating leads from event registrations.
SPECIFICATIONS: CREATION TYPE
There are two types of lead creation:
* per attendee: create a lead for each registration;
* per order: create a lead for a group of registrations;
The last one is only available through interface if it is possible to register
a group of attendees in one action (when event_sale or website_event are
installed). Behavior itself is implemented directly in event_crm.
Basically a group is either a list of registrations belonging to the same
event and created in batch (website_event flow). With event_sale this
definition will be improved to be based on sale_order.
SPECIFICATIONS: CREATION TRIGGERS
There are three options to trigger lead creation. We consider basically that
lead quality increases if attendees confirmed or went to the event. Triggers
allow therefore to run rules:
* at attendee creation;
* at attendee confirmation;
* at attendee venue;
This trigger defines when the rule will run.
SPECIFICATIONS: FILTERING REGISTRATIONS
When a batch of registrations matches the rule trigger we filter them based
on conditions and rules defines on event_lead_rule model. Heuristic is the
following:
* the rule is active;
* if a filter is set: filter registrations based on this filter. This is
done like a search, and filter is a domain;
* if a company is set on the rule, it must match event's company. Note
that multi-company rules apply on event_lead_rule;
* if an event category it set, it must match;
* if an event is set, it must match;
* if both event and category are set, one of them must match (OR). If none
of those are set, it is considered as OK;
If conditions are met, leads are created with pre-filled informations defined
on the rule (type, user_id, team_id). Contact information coming from the
registrations are computed (customer, name, email, phone, mobile, contact_name).
SPECIFICATIONS: OTHER POINTS
Note that all rules matching their conditions are applied. This means more
than one lead can be created depending on the configuration. This is
intended in order to give more freedom to the user using the automatic
lead generation.
"""
_name = "event.lead.rule"
_description = "Event Lead Rules"
# Definition
name = fields.Char('Rule Name', required=True, translate=True)
active = fields.Boolean('Active', default=True)
lead_ids = fields.One2many(
'crm.lead', 'event_lead_rule_id', string='Created Leads',
groups='sales_team.group_sale_salesman')
# Triggers
lead_creation_basis = fields.Selection([
('attendee', 'Per Attendee'), ('order', 'Per Order')],
string='Create', default='attendee', required=True,
help='Per Attendee : A Lead is created for each Attendee (B2C).\n'
'Per Order : A single Lead is created per Ticket Batch/Sale Order (B2B)')
lead_creation_trigger = fields.Selection([
('create', 'Attendees are created'),
('confirm', 'Attendees are confirmed'),
('done', 'Attendees attended')],
string='When', default='create', required=True,
help='Creation: at attendee creation;\n'
'Confirmation: when attendee is confirmed, manually or automatically;\n'
'Attended: when attendance is confirmed and registration set to done;')
# Filters
event_type_ids = fields.Many2many(
'event.type', string='Event Categories',
help='Filter the attendees to include those of this specific event category. If not set, no event category restriction will be applied.')
event_id = fields.Many2one(
'event.event', string='Event',
domain="[('company_id', 'in', [company_id or current_company_id, False])]",
help='Filter the attendees to include those of this specific event. If not set, no event restriction will be applied.')
company_id = fields.Many2one(
'res.company', string='Company',
help="Restrict the trigger of this rule to events belonging to a specific company.\nIf not set, no company restriction will be applied.")
event_registration_filter = fields.Text(string="Registrations Domain", help="Filter the attendees that will or not generate leads.")
# Lead default_value fields
lead_type = fields.Selection([
('lead', 'Lead'), ('opportunity', 'Opportunity')], string="Lead Type", required=True,
default=lambda self: 'lead' if self.env['res.users'].has_group('crm.group_use_lead') else 'opportunity',
help="Default lead type when this rule is applied.")
lead_sales_team_id = fields.Many2one(
'crm.team', string='Sales Team', ondelete="set null",
help="Automatically assign the created leads to this Sales Team.")
lead_user_id = fields.Many2one('res.users', string='Salesperson', help="Automatically assign the created leads to this Salesperson.")
lead_tag_ids = fields.Many2many('crm.tag', string='Tags', help="Automatically add these tags to the created leads.")
def _run_on_registrations(self, registrations):
""" Create or update leads based on rule configuration. Two main lead
management type exists
* per attendee: each registration creates a lead;
* per order: registrations are grouped per group and one lead is created
or updated with the batch (used mainly with sale order configuration
in event_sale);
Heuristic
* first, check existing lead linked to registrations to ensure no
duplication. Indeed for example attendee status change may trigger
the same rule several times;
* then for each rule, get the subset of registrations matching its
filters;
* then for each order-based rule, get the grouping information. This
give a list of registrations by group (event, sale_order), with maybe
an already-existing lead to update instead of creating a new one;
* finally apply rules. Attendee-based rules create a lead for each
attendee, group-based rules use the grouping information to create
or update leads;
:param registrations: event.registration recordset on which rules given by
self have to run. Triggers should already be checked, only filters are
applied here.
:return leads: newly-created leads. Updated leads are not returned.
"""
# order by ID, ensure first created wins
registrations = registrations.sorted('id')
# first: ensure no duplicate by searching existing registrations / rule
existing_leads = self.env['crm.lead'].search([
('registration_ids', 'in', registrations.ids),
('event_lead_rule_id', 'in', self.ids)
])
rule_to_existing_regs = defaultdict(lambda: self.env['event.registration'])
for lead in existing_leads:
rule_to_existing_regs[lead.event_lead_rule_id] += lead.registration_ids
# second: check registrations matching rules (in batch)
new_registrations = self.env['event.registration']
rule_to_new_regs = dict()
for rule in self:
new_for_rule = registrations.filtered(lambda reg: reg not in rule_to_existing_regs[rule])
rule_registrations = rule._filter_registrations(new_for_rule)
new_registrations |= rule_registrations
rule_to_new_regs[rule] = rule_registrations
new_registrations.sorted('id') # as an OR was used, re-ensure order
# third: check grouping
order_based_rules = self.filtered(lambda rule: rule.lead_creation_basis == 'order')
rule_group_info = new_registrations._get_lead_grouping(order_based_rules, rule_to_new_regs)
lead_vals_list = []
for rule in self:
if rule.lead_creation_basis == 'attendee':
matching_registrations = rule_to_new_regs[rule].sorted('id')
for registration in matching_registrations:
lead_vals_list.append(registration._get_lead_values(rule))
else:
# check if registrations are part of a group, for example a sale order, to know if we update or create leads
for (toupdate_leads, group_key, group_registrations) in rule_group_info[rule]:
if toupdate_leads:
additionnal_description = group_registrations._get_lead_description(_("New registrations"), line_counter=True)
for lead in toupdate_leads:
lead.write({
'description': "%s<br/>%s" % (lead.description, additionnal_description),
'registration_ids': [(4, reg.id) for reg in group_registrations],
})
elif group_registrations:
lead_vals_list.append(group_registrations._get_lead_values(rule))
return self.env['crm.lead'].create(lead_vals_list)
def _filter_registrations(self, registrations):
""" Keep registrations matching rule conditions. Those are
* if a filter is set: filter registrations based on this filter. This is
done like a search, and filter is a domain;
* if a company is set on the rule, it must match event's company. Note
that multi-company rules apply on event_lead_rule;
* if an event category it set, it must match;
* if an event is set, it must match;
* if both event and category are set, one of them must match (OR). If none
of those are set, it is considered as OK;
:param registrations: event.registration recordset on which rule filters
will be evaluated;
:return: subset of registrations matching rules
"""
self.ensure_one()
if self.event_registration_filter and self.event_registration_filter != '[]':
registrations = registrations.filtered_domain(literal_eval(self.event_registration_filter))
# check from direct m2o to linked m2o / o2m to filter first without inner search
company_ok = lambda registration: registration.company_id == self.company_id if self.company_id else True
event_or_event_type_ok = \
lambda registration: \
registration.event_id == self.event_id or registration.event_id.event_type_id in self.event_type_ids \
if (self.event_id or self.event_type_ids) else True
return registrations.filtered(lambda r: company_ok(r) and event_or_event_type_ok(r))
| 51.157407
| 11,050
|
974
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class EventEvent(models.Model):
_name = "event.event"
_inherit = "event.event"
lead_ids = fields.One2many(
'crm.lead', 'event_id', string="Leads", groups='sales_team.group_sale_salesman',
help="Leads generated from this event")
lead_count = fields.Integer(
string="# Leads", compute='_compute_lead_count', groups='sales_team.group_sale_salesman',
help="Counter for the leads linked to this event")
@api.depends('lead_ids')
def _compute_lead_count(self):
lead_data = self.env['crm.lead'].read_group(
[('event_id', 'in', self.ids)],
['event_id'], ['event_id']
)
mapped_data = {item['event_id'][0]: item['event_id_count'] for item in lead_data}
for event in self:
event.lead_count = mapped_data.get(event.id, 0)
| 37.461538
| 974
|
1,435
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class Lead(models.Model):
_inherit = 'crm.lead'
event_lead_rule_id = fields.Many2one('event.lead.rule', string="Registration Rule", help="Rule that created this lead")
event_id = fields.Many2one('event.event', string="Source Event", help="Event triggering the rule that created this lead")
registration_ids = fields.Many2many(
'event.registration', string="Source Registrations",
groups='event.group_event_registration_desk',
help="Registrations triggering the rule that created this lead")
registration_count = fields.Integer(
string="# Registrations", compute='_compute_registration_count',
groups='event.group_event_registration_desk',
help="Counter for the registrations linked to this lead")
@api.depends('registration_ids')
def _compute_registration_count(self):
for record in self:
record.registration_count = len(record.registration_ids)
def _merge_dependences(self, opportunities):
super(Lead, self)._merge_dependences(opportunities)
# merge registrations as sudo, as crm people may not have access to event rights
self.sudo().write({
'registration_ids': [(4, registration.id) for registration in opportunities.sudo().registration_ids]
})
| 44.84375
| 1,435
|
1,037
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Purchase Matrix",
'summary': """
Add variants to your purchase orders through an Order Grid Entry.
""",
'description': """
This module allows to fill Purchase Orders rapidly
by choosing product variants quantity through a Grid Entry.
""",
'category': 'Inventory/Purchase',
'version': '1.0',
'depends': ['purchase', 'product_matrix'],
'data': [
'views/purchase_views.xml',
'report/purchase_quotation_templates.xml',
'report/purchase_order_templates.xml',
],
'assets': {
'web.assets_backend': [
'purchase_product_matrix/static/src/**/*',
],
'web.qunit_suite_tests': [
'purchase_product_matrix/static/tests/section_and_note_widget_tests.js',
],
'web.assets_tests': [
'purchase_product_matrix/static/tests/tours/**/*',
],
},
'license': 'LGPL-3',
}
| 32.40625
| 1,037
|
1,713
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
from odoo.addons.product_matrix.tests.common import TestMatrixCommon
@odoo.tests.tagged('post_install', '-at_install')
class TestPurchaseMatrixUi(TestMatrixCommon):
def test_purchase_matrix_ui(self):
self.start_tour("/web", 'purchase_matrix_tour', login="admin")
# Ensures some dynamic create variants have been created by the matrix
# Ensures a PO has been created with exactly x lines ...
self.assertEqual(len(self.matrix_template.product_variant_ids), 8)
self.assertEqual(len(self.matrix_template.product_variant_ids.product_template_attribute_value_ids), 6)
self.assertEqual(len(self.matrix_template.attribute_line_ids.product_template_value_ids), 8)
self.env['purchase.order.line'].search([('product_id', 'in', self.matrix_template.product_variant_ids.ids)]).order_id.button_confirm()
self.matrix_template.flush()
self.assertEqual(round(self.matrix_template.purchased_product_qty, 2), 56.8)
for variant in self.matrix_template.product_variant_ids:
# 5 and 9.2 because of no variant attributes
self.assertIn(round(variant.purchased_product_qty, 2), [5, 9.2])
# Ensure no duplicate line has been created on the PO.
# NB: the *2 is because the no_variant attribute doesn't create a variant
# but still gives different order lines.
self.assertEqual(
len(self.env['purchase.order.line'].search([('product_id', 'in', self.matrix_template.product_variant_ids.ids)])),
len(self.matrix_template.product_variant_ids)*2
)
| 50.382353
| 1,713
|
9,074
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
report_grids = fields.Boolean(string="Print Variant Grids", default=True, help="If set, the matrix of configurable products will be shown on the report of this order.")
""" Matrix loading and update: fields and methods :
NOTE: The matrix functionality was done in python, server side, to avoid js
restriction. Indeed, the js framework only loads the x first lines displayed
in the client, which means in case of big matrices and lots of po_lines,
the js doesn't have access to the 41st and following lines.
To force the loading, a 'hack' of the js framework would have been needed...
"""
grid_product_tmpl_id = fields.Many2one('product.template', store=False, help="Technical field for product_matrix functionalities.")
grid_update = fields.Boolean(default=False, store=False, help="Whether the grid field contains a new matrix to apply or not.")
grid = fields.Char(store=False, help="Technical storage of grid. \nIf grid_update, will be loaded on the PO. \nIf not, represents the matrix to open.")
@api.onchange('grid_product_tmpl_id')
def _set_grid_up(self):
if self.grid_product_tmpl_id:
self.grid_update = False
self.grid = json.dumps(self._get_matrix(self.grid_product_tmpl_id))
def _must_delete_date_planned(self, field_name):
return super()._must_delete_date_planned(field_name) or field_name == "grid"
@api.onchange('grid')
def _apply_grid(self):
if self.grid and self.grid_update:
grid = json.loads(self.grid)
product_template = self.env['product.template'].browse(grid['product_template_id'])
product_ids = set()
dirty_cells = grid['changes']
Attrib = self.env['product.template.attribute.value']
default_po_line_vals = {}
new_lines = []
for cell in dirty_cells:
combination = Attrib.browse(cell['ptav_ids'])
no_variant_attribute_values = combination - combination._without_no_variant_attributes()
# create or find product variant from combination
product = product_template._create_product_variant(combination)
# TODO replace the check on product_id by a first check on the ptavs and pnavs?
# and only create/require variant after no line has been found ???
order_lines = self.order_line.filtered(lambda line: (line._origin or line).product_id == product and (line._origin or line).product_no_variant_attribute_value_ids == no_variant_attribute_values)
# if product variant already exist in order lines
old_qty = sum(order_lines.mapped('product_qty'))
qty = cell['qty']
diff = qty - old_qty
if not diff:
continue
product_ids.add(product.id)
if order_lines:
if qty == 0:
if self.state in ['draft', 'sent']:
# Remove lines if qty was set to 0 in matrix
# only if PO state = draft/sent
self.order_line -= order_lines
else:
order_lines.update({'product_qty': 0.0})
else:
"""
When there are multiple lines for same product and its quantity was changed in the matrix,
An error is raised.
A 'good' strategy would be to:
* Sets the quantity of the first found line to the cell value
* Remove the other lines.
But this would remove all business logic linked to the other lines...
Therefore, it only raises an Error for now.
"""
if len(order_lines) > 1:
raise ValidationError(_("You cannot change the quantity of a product present in multiple purchase lines."))
else:
order_lines[0].product_qty = qty
order_lines[0]._onchange_quantity()
# If we want to support multiple lines edition:
# removal of other lines.
# For now, an error is raised instead
# if len(order_lines) > 1:
# # Remove 1+ lines
# self.order_line -= order_lines[1:]
else:
if not default_po_line_vals:
OrderLine = self.env['purchase.order.line']
default_po_line_vals = OrderLine.default_get(OrderLine._fields.keys())
last_sequence = self.order_line[-1:].sequence
if last_sequence:
default_po_line_vals['sequence'] = last_sequence
new_lines.append((0, 0, dict(
default_po_line_vals,
product_id=product.id,
product_qty=qty,
product_no_variant_attribute_value_ids=no_variant_attribute_values.ids)
))
if product_ids:
res = False
if new_lines:
# Add new PO lines
self.update(dict(order_line=new_lines))
# Recompute prices for new/modified lines:
for line in self.order_line.filtered(lambda line: line.product_id.id in product_ids):
line._product_id_change()
line._onchange_quantity()
line._onchange_suggest_packaging()
line._onchange_update_product_packaging_qty()
res = line.onchange_product_id_warning() or res
return res
def _get_matrix(self, product_template):
def has_ptavs(line, sorted_attr_ids):
ptav = line.product_template_attribute_value_ids.ids
pnav = line.product_no_variant_attribute_value_ids.ids
pav = pnav + ptav
pav.sort()
return pav == sorted_attr_ids
matrix = product_template._get_template_matrix(
company_id=self.company_id,
currency_id=self.currency_id)
if self.order_line:
lines = matrix['matrix']
order_lines = self.order_line.filtered(lambda line: line.product_template_id == product_template)
for line in lines:
for cell in line:
if not cell.get('name', False):
line = order_lines.filtered(lambda line: has_ptavs(line, cell['ptav_ids']))
if line:
cell.update({
'qty': sum(line.mapped('product_qty'))
})
return matrix
def get_report_matrixes(self):
"""Reporting method."""
matrixes = []
if self.report_grids:
grid_configured_templates = self.order_line.filtered('is_configurable_product').product_template_id
# TODO is configurable product and product_variant_count > 1
# configurable products are only configured through the matrix in purchase, so no need to check product_add_mode.
for template in grid_configured_templates:
if len(self.order_line.filtered(lambda line: line.product_template_id == template)) > 1:
matrixes.append(self._get_matrix(template))
return matrixes
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
product_template_id = fields.Many2one('product.template', string='Product Template', related="product_id.product_tmpl_id", domain=[('purchase_ok', '=', True)])
is_configurable_product = fields.Boolean('Is the product configurable?', related="product_template_id.has_configurable_attributes")
product_template_attribute_value_ids = fields.Many2many(related='product_id.product_template_attribute_value_ids', readonly=True)
product_no_variant_attribute_value_ids = fields.Many2many('product.template.attribute.value', string='Product attribute values that do not create variants', ondelete='restrict')
def _get_product_purchase_description(self, product):
name = super(PurchaseOrderLine, self)._get_product_purchase_description(product)
for no_variant_attribute_value in self.product_no_variant_attribute_value_ids:
name += "\n" + no_variant_attribute_value.attribute_id.name + ': ' + no_variant_attribute_value.name
return name
| 52.149425
| 9,074
|
593
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Indian - Purchase Report(GST)',
'icon': '/l10n_in/static/description/icon.png',
'version': '1.0',
'description': """GST Purchase Report""",
'category': 'Accounting/Localizations/Purchase',
'depends': [
'l10n_in',
'purchase',
],
'data': [
'views/report_purchase_order.xml',
'views/purchase_order_views.xml',
],
'installable': True,
'application': False,
'auto_install': True,
'license': 'LGPL-3',
}
| 26.954545
| 593
|
828
|
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 AccountMove(models.Model):
_inherit = 'account.move'
@api.onchange('purchase_vendor_bill_id', 'purchase_id')
def _onchange_purchase_auto_complete(self):
purchase_order_id = self.purchase_vendor_bill_id.purchase_order_id or self.purchase_id
if purchase_order_id and purchase_order_id.l10n_in_company_country_code == 'IN':
journal_id = self.purchase_vendor_bill_id.purchase_order_id.l10n_in_journal_id or self.purchase_id.l10n_in_journal_id
if journal_id:
self.journal_id = journal_id
self.l10n_in_gst_treatment = purchase_order_id.l10n_in_gst_treatment
return super()._onchange_purchase_auto_complete()
| 46
| 828
|
2,458
|
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.addons.purchase.models.purchase import PurchaseOrder as Purchase
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
l10n_in_journal_id = fields.Many2one('account.journal', string="Journal", \
states=Purchase.READONLY_STATES, domain="[('type', '=', 'purchase')]")
l10n_in_gst_treatment = fields.Selection([
('regular', 'Registered Business - Regular'),
('composition', 'Registered Business - Composition'),
('unregistered', 'Unregistered Business'),
('consumer', 'Consumer'),
('overseas', 'Overseas'),
('special_economic_zone', 'Special Economic Zone'),
('deemed_export', 'Deemed Export')
], string="GST Treatment", states=Purchase.READONLY_STATES, compute="_compute_l10n_in_gst_treatment", store=True)
l10n_in_company_country_code = fields.Char(related='company_id.account_fiscal_country_id.code', string="Country code")
@api.onchange('company_id')
def l10n_in_onchange_company_id(self):
if self.l10n_in_company_country_code == 'IN':
domain = [('company_id', '=', self.company_id.id), ('type', '=', 'purchase')]
journal = self.env['account.journal'].search(domain, limit=1)
if journal:
self.l10n_in_journal_id = journal.id
@api.depends('partner_id')
def _compute_l10n_in_gst_treatment(self):
for order in self:
# set default value as False so CacheMiss error never occurs for this field.
order.l10n_in_gst_treatment = False
if order.l10n_in_company_country_code == 'IN':
l10n_in_gst_treatment = order.partner_id.l10n_in_gst_treatment
if not l10n_in_gst_treatment and order.partner_id.country_id and order.partner_id.country_id.code != 'IN':
l10n_in_gst_treatment = 'overseas'
if not l10n_in_gst_treatment:
l10n_in_gst_treatment = order.partner_id.vat and 'regular' or 'consumer'
order.l10n_in_gst_treatment = l10n_in_gst_treatment
def _prepare_invoice(self):
invoice_vals = super()._prepare_invoice()
if self.l10n_in_journal_id:
invoice_vals.update({'journal_id': self.l10n_in_journal_id.id})
return invoice_vals
| 50.163265
| 2,458
|
480
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "Google Gmail",
"version": "1.0",
"category": "Hidden",
"description": "Gmail support for incoming / outgoing mail servers",
"depends": [
"mail",
"google_account",
],
"data": [
"views/ir_mail_server_views.xml",
"views/res_config_settings_views.xml",
],
"auto_install": True,
"license": "LGPL-3",
}
| 25.263158
| 480
|
2,139
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo import _, models, api
from odoo.exceptions import UserError
class IrMailServer(models.Model):
"""Represents an SMTP server, able to send outgoing emails, with SSL and TLS capabilities."""
_name = 'ir.mail_server'
_inherit = ['ir.mail_server', 'google.gmail.mixin']
@api.constrains('use_google_gmail_service')
def _check_use_google_gmail_service(self):
if self.filtered(lambda server: server.use_google_gmail_service and not server.smtp_user):
raise UserError(_(
'Please fill the "Username" field with your Gmail username (your email address). '
'This should be the same account as the one used for the Gmail OAuthentication Token.'))
@api.onchange('smtp_encryption')
def _onchange_encryption(self):
"""Do not change the SMTP configuration if it's a Gmail server
(e.g. the port which is already set)"""
if not self.use_google_gmail_service:
super()._onchange_encryption()
@api.onchange('use_google_gmail_service')
def _onchange_use_google_gmail_service(self):
if self.use_google_gmail_service:
self.smtp_host = 'smtp.gmail.com'
self.smtp_encryption = 'starttls'
self.smtp_port = 587
else:
self.google_gmail_authorization_code = False
self.google_gmail_refresh_token = False
self.google_gmail_access_token = False
self.google_gmail_access_token_expiration = False
def _smtp_login(self, connection, smtp_user, smtp_password):
if len(self) == 1 and self.use_google_gmail_service:
auth_string = self._generate_oauth2_string(smtp_user, self.google_gmail_refresh_token)
oauth_param = base64.b64encode(auth_string.encode()).decode()
connection.ehlo()
connection.docmd('AUTH', 'XOAUTH2 %s' % oauth_param)
else:
super(IrMailServer, self)._smtp_login(connection, smtp_user, smtp_password)
| 42.78
| 2,139
|
7,372
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import time
import requests
from werkzeug.urls import url_encode, url_join
from odoo import _, api, fields, models, tools
from odoo.exceptions import AccessError, UserError
_logger = logging.getLogger(__name__)
class GoogleGmailMixin(models.AbstractModel):
_name = 'google.gmail.mixin'
_description = 'Google Gmail Mixin'
_SERVICE_SCOPE = 'https://mail.google.com/'
use_google_gmail_service = fields.Boolean('Gmail Authentication')
google_gmail_authorization_code = fields.Char(string='Authorization Code', groups='base.group_system', copy=False)
google_gmail_refresh_token = fields.Char(string='Refresh Token', groups='base.group_system', copy=False)
google_gmail_access_token = fields.Char(string='Access Token', groups='base.group_system', copy=False)
google_gmail_access_token_expiration = fields.Integer(string='Access Token Expiration Timestamp', groups='base.group_system', copy=False)
google_gmail_uri = fields.Char(compute='_compute_gmail_uri', string='URI', help='The URL to generate the authorization code from Google', groups='base.group_system')
@api.depends('google_gmail_authorization_code')
def _compute_gmail_uri(self):
Config = self.env['ir.config_parameter'].sudo()
google_gmail_client_id = Config.get_param('google_gmail_client_id')
google_gmail_client_secret = Config.get_param('google_gmail_client_secret')
base_url = self.get_base_url()
redirect_uri = url_join(base_url, '/google_gmail/confirm')
if not google_gmail_client_id or not google_gmail_client_secret:
self.google_gmail_uri = False
else:
for record in self:
google_gmail_uri = 'https://accounts.google.com/o/oauth2/v2/auth?%s' % url_encode({
'client_id': google_gmail_client_id,
'redirect_uri': redirect_uri,
'response_type': 'code',
'scope': self._SERVICE_SCOPE,
# access_type and prompt needed to get a refresh token
'access_type': 'offline',
'prompt': 'consent',
'state': json.dumps({
'model': record._name,
'id': record.id or False,
'csrf_token': record._get_gmail_csrf_token() if record.id else False,
})
})
record.google_gmail_uri = google_gmail_uri
def open_google_gmail_uri(self):
"""Open the URL to accept the Gmail permission.
This is done with an action, so we can force the user the save the form.
We need him to save the form so the current mail server record exist in DB, and
we can include the record ID in the URL.
"""
self.ensure_one()
if not self.env.user.has_group('base.group_system'):
raise AccessError(_('Only the administrator can link a Gmail mail server.'))
if not self.google_gmail_uri:
raise UserError(_('Please configure your Gmail credentials.'))
return {
'type': 'ir.actions.act_url',
'url': self.google_gmail_uri,
}
def _fetch_gmail_refresh_token(self, authorization_code):
"""Request the refresh token and the initial access token from the authorization code.
:return:
refresh_token, access_token, access_token_expiration
"""
response = self._fetch_gmail_token('authorization_code', code=authorization_code)
return (
response['refresh_token'],
response['access_token'],
int(time.time()) + response['expires_in'],
)
def _fetch_gmail_access_token(self, refresh_token):
"""Refresh the access token thanks to the refresh token.
:return:
access_token, access_token_expiration
"""
response = self._fetch_gmail_token('refresh_token', refresh_token=refresh_token)
return (
response['access_token'],
int(time.time()) + response['expires_in'],
)
def _fetch_gmail_token(self, grant_type, **values):
"""Generic method to request an access token or a refresh token.
Return the JSON response of the GMail API and manage the errors which can occur.
:param grant_type: Depends the action we want to do (refresh_token or authorization_code)
:param values: Additional parameters that will be given to the GMail endpoint
"""
Config = self.env['ir.config_parameter'].sudo()
google_gmail_client_id = Config.get_param('google_gmail_client_id')
google_gmail_client_secret = Config.get_param('google_gmail_client_secret')
base_url = self.get_base_url()
redirect_uri = url_join(base_url, '/google_gmail/confirm')
response = requests.post(
'https://oauth2.googleapis.com/token',
data={
'client_id': google_gmail_client_id,
'client_secret': google_gmail_client_secret,
'grant_type': grant_type,
'redirect_uri': redirect_uri,
**values,
},
timeout=5,
)
if not response.ok:
raise UserError(_('An error occurred when fetching the access token.'))
return response.json()
def _generate_oauth2_string(self, user, refresh_token):
"""Generate a OAuth2 string which can be used for authentication.
:param user: Email address of the Gmail account to authenticate
:param refresh_token: Refresh token for the given Gmail account
:return: The SASL argument for the OAuth2 mechanism.
"""
self.ensure_one()
now_timestamp = int(time.time())
if not self.google_gmail_access_token \
or not self.google_gmail_access_token_expiration \
or self.google_gmail_access_token_expiration < now_timestamp:
access_token, expiration = self._fetch_gmail_access_token(self.google_gmail_refresh_token)
self.write({
'google_gmail_access_token': access_token,
'google_gmail_access_token_expiration': expiration,
})
_logger.info(
'Google Gmail: fetch new access token. Expires in %i minutes',
(self.google_gmail_access_token_expiration - now_timestamp) // 60)
else:
_logger.info(
'Google Gmail: reuse existing access token. Expire in %i minutes',
(self.google_gmail_access_token_expiration - now_timestamp) // 60)
return 'user=%s\1auth=Bearer %s\1\1' % (user, self.google_gmail_access_token)
def _get_gmail_csrf_token(self):
"""Generate a CSRF token that will be verified in `google_gmail_callback`.
This will prevent a malicious person to make an admin user disconnect the mail servers.
"""
self.ensure_one()
_logger.info('Google Gmail: generate CSRF token for %s #%i', self._name, self.id)
return tools.misc.hmac(
env=self.env(su=True),
scope='google_gmail_oauth',
message=(self._name, self.id),
)
| 40.955556
| 7,372
|
446
|
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 ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
google_gmail_client_identifier = fields.Char('Gmail Client Id', config_parameter='google_gmail_client_id')
google_gmail_client_secret = fields.Char('Gmail Client Secret', config_parameter='google_gmail_client_secret')
| 40.545455
| 446
|
2,665
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
from werkzeug.exceptions import Forbidden
from werkzeug.urls import url_encode
from odoo import _, http
from odoo.exceptions import UserError
from odoo.http import request
from odoo.tools import consteq
_logger = logging.getLogger(__name__)
class GoogleGmailController(http.Controller):
@http.route('/google_gmail/confirm', type='http', auth='user')
def google_gmail_callback(self, code=None, state=None, error=None, **kwargs):
"""Callback URL during the OAuth process.
Gmail redirects the user browser to this endpoint with the authorization code.
We will fetch the refresh token and the access token thanks to this authorization
code and save those values on the given mail server.
"""
if not request.env.user.has_group('base.group_system'):
_logger.error('Google Gmail: non-system user trying to link an Gmail account.')
raise Forbidden()
if error:
return _('An error occur during the authentication process.')
try:
state = json.loads(state)
model_name = state['model']
rec_id = state['id']
csrf_token = state['csrf_token']
except Exception:
_logger.error('Google Gmail: Wrong state value %r.', state)
raise Forbidden()
model = request.env[model_name]
if not issubclass(type(model), request.env.registry['google.gmail.mixin']):
# The model must inherits from the "google.gmail.mixin" mixin
raise Forbidden()
record = model.browse(rec_id).exists()
if not record:
raise Forbidden()
if not csrf_token or not consteq(csrf_token, record._get_gmail_csrf_token()):
_logger.error('Google Gmail: Wrong CSRF token during Gmail authentication.')
raise Forbidden()
try:
refresh_token, access_token, expiration = record._fetch_gmail_refresh_token(code)
except UserError:
return _('An error occur during the authentication process.')
record.write({
'google_gmail_access_token': access_token,
'google_gmail_access_token_expiration': expiration,
'google_gmail_authorization_code': code,
'google_gmail_refresh_token': refresh_token,
})
url_params = {
'id': rec_id,
'model': model_name,
'view_type': 'form'
}
url = '/web?#' + url_encode(url_params)
return request.redirect(url)
| 35.533333
| 2,665
|
833
|
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Default Theme',
'description': 'Default website theme',
'category': 'Theme',
'sequence': 1000,
'version': '1.0',
'depends': ['website'],
'data': [],
'images': [
'static/description/cover.png',
'static/description/theme_default_screenshot.jpg',
],
'snippet_lists': {
'homepage': ['s_cover', 's_text_image', 's_numbers'],
'about_us': ['s_text_image', 's_image_text', 's_title', 's_company_team'],
'our_services': ['s_three_columns', 's_quotes_carousel', 's_references'],
'pricing': ['s_comparisons'],
'privacy_policy': ['s_faq_collapse'],
},
'application': False,
'auto_install': False,
'license': 'LGPL-3',
}
| 32.038462
| 833
|
2,514
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Events',
'version': '1.4',
'category': 'Marketing/Events',
'sequence': 140,
'summary': 'Publish events, sell tickets',
'website': 'https://www.odoo.com/app/events',
'description': "",
'depends': [
'event',
'website',
'website_partner',
'website_mail',
],
'data': [
'data/event_data.xml',
'views/res_config_settings_views.xml',
'views/event_snippets.xml',
'views/event_templates_list.xml',
'views/event_templates_page.xml',
'views/event_templates_page_registration.xml',
'views/event_templates_page_misc.xml',
'views/event_templates_widgets.xml',
'views/website_templates.xml',
'views/event_event_views.xml',
'views/event_registration_views.xml',
'views/event_tag_category_views.xml',
'views/event_type_views.xml',
'views/website_event_menu_views.xml',
'views/website_visitor_views.xml',
'views/event_menus.xml',
'security/ir.model.access.csv',
'security/event_security.xml',
],
'demo': [
'data/res_partner_demo.xml',
'data/website_visitor_demo.xml',
'data/event_demo.xml',
'data/event_registration_demo.xml',
],
'application': True,
'assets': {
'web.assets_common': [
'website_event/static/src/js/tours/**/*',
],
'web.assets_tests': [
'website_event/static/tests/**/*',
],
'web.assets_frontend': [
'website_event/static/src/scss/event_templates_common.scss',
'website_event/static/src/scss/event_templates_list.scss',
'website_event/static/src/scss/event_templates_page.scss',
'website_event/static/src/snippets/s_country_events_list/000.scss',
'website_event/static/src/js/display_timer_widget.js',
'website_event/static/src/js/register_toaster_widget.js',
'website_event/static/src/js/website_geolocation.js',
'website_event/static/src/js/website_event.js',
'website_event/static/src/js/website_event_ticket_details.js',
'website_event/static/src/js/website_event_set_customize_options.js',
],
'website.assets_editor': [
'website_event/static/src/js/website_event.editor.js',
],
},
'license': 'LGPL-3',
}
| 36.434783
| 2,514
|
3,094
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo import fields
from odoo.addons.website_event.tests.common import TestWebsiteEventCommon
from odoo.tests.common import users
class TestEventMenus(TestWebsiteEventCommon):
@users('user_eventmanager')
def test_menu_management(self):
event = self.env['event.event'].create({
'name': 'TestEvent',
'date_begin': fields.Datetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': fields.Datetime.to_string(datetime.today() + timedelta(days=15)),
'website_menu': True,
'community_menu': False,
})
self.assertTrue(event.website_menu)
self.assertTrue(event.introduction_menu)
self.assertTrue(event.location_menu)
self.assertTrue(event.register_menu)
self.assertFalse(event.community_menu)
self._assert_website_menus(event, ['Introduction', 'Location', 'Register'], menus_out=['Community'])
event.community_menu = True
self._assert_website_menus(event, ['Introduction', 'Location', 'Register', 'Community'])
# test create without any requested menus
event = self.env['event.event'].create({
'name': 'TestEvent',
'date_begin': fields.Datetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': fields.Datetime.to_string(datetime.today() + timedelta(days=15)),
'website_menu': False,
})
self.assertFalse(event.website_menu)
self.assertFalse(event.introduction_menu)
self.assertFalse(event.location_menu)
self.assertFalse(event.register_menu)
self.assertFalse(event.community_menu)
self.assertFalse(event.menu_id)
# test update of website_menu triggering 3 sub menus
event.write({'website_menu': True})
self._assert_website_menus(event, ['Introduction', 'Location', 'Register'], menus_out=['Community'])
@users('user_event_web_manager')
def test_menu_management_frontend(self):
event = self.env['event.event'].create({
'name': 'TestEvent',
'date_begin': fields.Datetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': fields.Datetime.to_string(datetime.today() + timedelta(days=15)),
'website_menu': True,
'community_menu': False,
})
self._assert_website_menus(event, ['Introduction', 'Location', 'Register'], menus_out=['Community'])
# simulate menu removal from frontend: aka unlinking a menu
event.menu_id.child_id.filtered(lambda menu: menu.name == 'Introduction').unlink()
self.assertTrue(event.website_menu)
self._assert_website_menus(event, ['Location', 'Register'], menus_out=['Introduction', 'Community'])
# re-created from backend
event.introduction_menu = True
self._assert_website_menus(event, ['Introduction', 'Location', 'Register'], menus_out=['Community'])
| 44.84058
| 3,094
|
4,656
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta, time
from unittest.mock import patch
from odoo.addons.event.tests.common import TestEventCommon
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.fields import Datetime as FieldsDatetime, Date as FieldsDate
from odoo.tests.common import TransactionCase
class EventDtPatcher(TransactionCase):
@classmethod
def setUpClass(cls):
super(EventDtPatcher, cls).setUpClass()
# Mock dates to have reproducible computed fields based on time
cls.reference_now = datetime(2020, 7, 6, 10, 0, 0)
cls.reference_today = datetime(2020, 7, 6)
cls.event_dt = patch(
'odoo.addons.event.models.event_event.fields.Datetime',
wraps=FieldsDatetime
)
cls.wevent_dt = patch(
'odoo.addons.website_event.models.event_event.fields.Datetime',
wraps=FieldsDatetime
)
cls.wevent_main_dt = patch(
'odoo.addons.website_event.controllers.main.fields.Datetime',
wraps=FieldsDatetime
)
cls.event_date = patch(
'odoo.addons.event.models.event_event.fields.Date',
wraps=FieldsDate
)
cls.wevent_main_date = patch(
'odoo.addons.website_event.controllers.main.fields.Date',
wraps=FieldsDate
)
cls.mock_event_dt = cls.event_dt.start()
cls.mock_wevent_dt = cls.wevent_dt.start()
cls.mock_wevent_main_dt = cls.wevent_main_dt.start()
cls.mock_event_date = cls.event_date.start()
cls.mock_wevent_main_date = cls.wevent_main_date.start()
cls.mock_event_dt.now.return_value = cls.reference_now
cls.mock_wevent_dt.now.return_value = cls.reference_now
cls.mock_wevent_main_dt.now.return_value = cls.reference_now
cls.mock_event_date.today.return_value = cls.reference_today
cls.mock_wevent_main_date.today.return_value = cls.reference_today
cls.addClassCleanup(cls.event_dt.stop)
cls.addClassCleanup(cls.wevent_dt.stop)
cls.addClassCleanup(cls.wevent_main_dt.stop)
cls.addClassCleanup(cls.event_date.stop)
cls.addClassCleanup(cls.wevent_main_date.stop)
class TestWebsiteEventCommon(TestEventCommon):
@classmethod
def setUpClass(cls):
super(TestWebsiteEventCommon, cls).setUpClass()
cls.company_main = cls.env.user.company_id
cls.user_event_web_manager = mail_new_test_user(
cls.env, login='user_event_web_manager',
name='Martin Sales Manager', email='crm_manager@test.example.com',
company_id=cls.company_main.id,
notification_type='inbox',
groups='event.group_event_manager,website.group_website_designer',
)
def _get_menus(self):
return set(['Introduction', 'Location', 'Register', 'Community'])
def _assert_website_menus(self, event, menus_in=None, menus_out=None):
self.assertTrue(event.menu_id)
if menus_in is None:
menus_in = list(self._get_menus())
menus = self.env['website.menu'].search([('parent_id', '=', event.menu_id.id)])
self.assertTrue(len(menus) >= len(menus_in))
self.assertTrue(all(menu_name in menus.mapped('name') for menu_name in menus_in))
if menus_out:
self.assertTrue(all(menu_name not in menus.mapped('name') for menu_name in menus_out))
for page_specific in ['Introduction', 'Location']:
view = self.env['ir.ui.view'].search(
[('name', '=', page_specific + ' ' + event.name)]
)
if page_specific in menus_in:
self.assertTrue(bool(view))
else:
self.assertFalse(bool(view))
class TestEventOnlineCommon(TestEventCommon, EventDtPatcher):
@classmethod
def setUpClass(cls):
super(TestEventOnlineCommon, cls).setUpClass()
# event if 8-18 in Europe/Brussels (DST) (first day: begins at 9, last day: ends at 15)
cls.event_0.write({
'date_begin': datetime.combine(cls.reference_now, time(7, 0)) - timedelta(days=1),
'date_end': datetime.combine(cls.reference_now, time(13, 0)) + timedelta(days=1),
})
cls.event_customer.write({
'website_description': '<p>I am your best customer, %s</p>' % cls.event_customer.name,
})
cls.event_customer2.write({
'website_description': '<p>I am your best customer, %s</p>' % cls.event_customer2.name,
})
| 39.794872
| 4,656
|
2,038
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo import fields
from odoo.addons.website_event.tests.common import TestWebsiteEventCommon
class TestEventVisitor(TestWebsiteEventCommon):
def test_visitor_events(self):
event_1 = self.env['event.event'].create({
'name': 'OtherEvent',
'auto_confirm': True,
'date_begin': fields.Datetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': fields.Datetime.to_string(datetime.today() + timedelta(days=15)),
})
[main_visitor, child_visitor] = self.env['website.visitor'].create([{
'name': 'Main Visitor',
'event_registration_ids': [(0, 0, {
'event_id': self.event_0.id
})]
}, {
'name': 'Child Visitor',
'event_registration_ids': [(0, 0, {
'event_id': event_1.id
})]
}])
self.assertEqual(self.event_0, main_visitor.event_registered_ids)
self.assertEqual(event_1, child_visitor.event_registered_ids)
self.assertEqual(
main_visitor,
self.env['website.visitor'].search([('event_registered_ids', 'in', self.event_0.ids)])
)
self.assertEqual(
child_visitor,
self.env['website.visitor'].search([('event_registered_ids', 'in', event_1.ids)])
)
child_visitor._link_to_visitor(main_visitor)
self.assertEqual(self.event_0 | event_1, main_visitor.event_registered_ids)
self.assertEqual(
main_visitor | child_visitor,
self.env['website.visitor'].with_context(active_test=False).search([('event_registered_ids', 'in', self.event_0.ids)])
)
self.assertEqual(
main_visitor | child_visitor,
self.env['website.visitor'].with_context(active_test=False).search([('event_registered_ids', 'in', event_1.ids)])
)
| 39.960784
| 2,038
|
6,296
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo.addons.base.tests.common import HttpCaseWithUserDemo
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.website.tests.test_base_url import TestUrlCommon
from odoo.addons.website_event.tests.common import TestWebsiteEventCommon
from odoo.tests import tagged
from odoo.tools import mute_logger
@tagged('post_install', '-at_install')
class TestUi(HttpCaseWithUserDemo):
def test_website_event_tour_admin(self):
self.start_tour("/", 'website_event_tour', login='admin', step_delay=100)
@tagged('-at_install', 'post_install')
class TestURLs(TestUrlCommon):
def test_canonical_url(self):
self._assertCanonical('/event?date=all', self.domain + '/event')
self._assertCanonical('/event?date=old', self.domain + '/event?date=old')
@tagged('post_install', '-at_install')
class TestWebsiteAccess(HttpCaseWithUserDemo, TestWebsiteEventCommon):
def setUp(self):
super(TestWebsiteAccess, self).setUp()
self.events = self.env['event.event'].create([{
'name': 'Event 0 - Sitemap test',
'website_published': True,
'date_begin': datetime.today() - timedelta(days=1),
'date_end': datetime.today() + timedelta(days=1),
}, {
'name': 'Event 1 - Sitemap test',
'website_published': True,
'date_begin': datetime.today() - timedelta(days=1),
'date_end': datetime.today() + timedelta(days=1),
}, {
'name': 'Event 2 - Sitemap test',
'date_begin': datetime.today() - timedelta(days=1),
'date_end': datetime.today() + timedelta(days=1),
}])
self.portal_user = mail_new_test_user(
self.env, name='Smeagol', login='user_portal', password='user_portal', email='portal@example.com',
groups='base.group_portal'
)
def test_website_access_event_manager(self):
""" Event managers are allowed to access both published and unpublished events """
self.authenticate('user_eventmanager', 'user_eventmanager')
published_events = self.events.filtered(lambda event: event.website_published)
resp = self.url_open('/event/%i' % published_events[0].id)
self.assertEqual(resp.status_code, 200, 'Managers must have access to published event.')
unpublished_events = self.events.filtered(lambda event: not event.website_published)
resp = self.url_open('/event/%i' % unpublished_events[0].id)
self.assertEqual(resp.status_code, 200, 'Managers must have access to unpublished event.')
resp = self.url_open('/event')
self.assertTrue(published_events[0].name in resp.text, 'Managers must see the unpublished events.')
self.assertTrue(unpublished_events[0].name in resp.text, 'Managers must see the published events.')
def test_website_access_event_uer(self):
""" Event users are allowed to access both published and unpublished events """
self.authenticate('user_eventuser', 'user_eventuser')
published_events = self.events.filtered(lambda event: event.website_published)
resp = self.url_open('/event/%i' % published_events[0].id)
self.assertEqual(resp.status_code, 200, 'Event user must have access to published event.')
unpublished_events = self.events.filtered(lambda event: not event.website_published)
resp = self.url_open('/event/%i' % unpublished_events[0].id)
self.assertEqual(resp.status_code, 200, 'Event user must have access to unpublished event.')
resp = self.url_open('/event')
self.assertTrue(published_events[0].name in resp.text, 'Event user must see the unpublished events.')
self.assertTrue(unpublished_events[0].name in resp.text, 'Event user must see the published events.')
@mute_logger('odoo.addons.http_routing.models.ir_http')
def test_website_access_portal(self):
""" Portal users access only published events """
self.authenticate('user_portal', 'user_portal')
published_events = self.events.filtered(lambda event: event.website_published)
resp = self.url_open('/event/%i' % published_events[0].id)
self.assertEqual(resp.status_code, 200, 'Portal user must have access to published event.')
unpublished_events = self.events.filtered(lambda event: not event.website_published)
resp = self.url_open('/event/%i' % unpublished_events[0].id)
self.assertEqual(resp.status_code, 403, 'Portal user must not have access to unpublished event.')
resp = self.url_open('/event')
self.assertTrue(published_events[0].name in resp.text, 'Portal must see the published events.')
self.assertFalse(unpublished_events[0].name in resp.text, 'Portal should not see the unpublished events.')
@mute_logger('odoo.addons.http_routing.models.ir_http')
def test_website_access_public(self):
""" Public users access only published events """
published_events = self.events.filtered(lambda event: event.website_published)
resp = self.url_open('/event/%i' % published_events[0].id)
self.assertEqual(resp.status_code, 200, 'Public must have access to published event')
unpublished_events = self.events.filtered(lambda event: not event.website_published)
resp = self.url_open('/event/%i' % unpublished_events[0].id)
self.assertEqual(resp.status_code, 403, 'Public must not have access to unpublished event')
resp = self.url_open('/event')
self.assertTrue(published_events[0].name in resp.text, 'Public must see the published events.')
self.assertFalse(unpublished_events[0].name in resp.text, 'Public should not see the unpublished events.')
def test_sitemap(self):
resp = self.url_open('/sitemap.xml')
self.assertTrue('/event/event-0' in resp.text, 'Published events must be present in the sitemap')
self.assertTrue('/event/event-1' in resp.text, 'Published events must be present in the sitemap')
self.assertFalse('/event/event-2' in resp.text, 'Unpublished events must not be present in the sitemap')
| 52.033058
| 6,296
|
320
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class EventTagCategory(models.Model):
_name = 'event.tag.category'
_inherit = ['event.tag.category', 'website.published.mixin']
def _default_is_published(self):
return True
| 26.666667
| 320
|
973
|
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 EventType(models.Model):
_name = 'event.type'
_inherit = ['event.type']
website_menu = fields.Boolean('Display a dedicated menu on Website')
community_menu = fields.Boolean(
"Community Menu", compute="_compute_community_menu",
readonly=False, store=True,
help="Display community tab on website")
menu_register_cta = fields.Boolean(
'Extra Register Button', compute='_compute_menu_register_cta',
readonly=False, store=True)
@api.depends('website_menu')
def _compute_community_menu(self):
for event_type in self:
event_type.community_menu = event_type.website_menu
@api.depends('website_menu')
def _compute_menu_register_cta(self):
for event_type in self:
event_type.menu_register_cta = event_type.website_menu
| 34.75
| 973
|
490
|
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 EventRegistration(models.Model):
_name = 'event.registration'
_inherit = ['event.registration']
visitor_id = fields.Many2one('website.visitor', string='Visitor', ondelete='set null')
def _get_website_registration_allowed_fields(self):
return {'name', 'phone', 'email', 'mobile', 'event_id', 'partner_id', 'event_ticket_id'}
| 35
| 490
|
1,189
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class WebsiteMenu(models.Model):
_inherit = "website.menu"
def unlink(self):
""" Override to synchronize event configuration fields with menu deletion. """
event_updates = {}
website_event_menus = self.env['website.event.menu'].search([('menu_id', 'in', self.ids)])
for event_menu in website_event_menus:
to_update = event_updates.setdefault(event_menu.event_id, list())
for menu_type, fname in event_menu.event_id._get_menu_type_field_matching().items():
if event_menu.menu_type == menu_type:
to_update.append(fname)
# manually remove website_event_menus to call their ``unlink`` method. Otherwise
# super unlinks at db level and skip model-specific behavior.
website_event_menus.unlink()
res = super(WebsiteMenu, self).unlink()
# update events
for event, to_update in event_updates.items():
if to_update:
event.write(dict((fname, False) for fname in to_update))
return res
| 39.633333
| 1,189
|
25,606
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from collections import defaultdict
from dateutil.relativedelta import relativedelta
import json
import werkzeug.urls
from pytz import utc
from odoo import api, fields, models, _
from odoo.addons.http_routing.models.ir_http import slug
from odoo.osv import expression
from odoo.tools.misc import get_lang, format_date
GOOGLE_CALENDAR_URL = 'https://www.google.com/calendar/render?'
class Event(models.Model):
_name = 'event.event'
_inherit = [
'event.event',
'website.seo.metadata',
'website.published.multi.mixin',
'website.cover_properties.mixin',
'website.searchable.mixin',
]
def _default_cover_properties(self):
res = super()._default_cover_properties()
res.update({
'background-image': "url('/website_event/static/src/img/event_cover_4.jpg')",
'opacity': '0.4',
'resize_class': 'cover_auto'
})
return res
# description
subtitle = fields.Char('Event Subtitle', translate=True)
# registration
is_participating = fields.Boolean("Is Participating", compute="_compute_is_participating")
# website
website_published = fields.Boolean(tracking=True)
website_menu = fields.Boolean(
string='Website Menu',
compute='_compute_website_menu', readonly=False, store=True,
help="Allows to display and manage event-specific menus on website.")
menu_id = fields.Many2one('website.menu', 'Event Menu', copy=False)
menu_register_cta = fields.Boolean(
'Extra Register Button', compute='_compute_menu_register_cta',
readonly=False, store=True)
# sub-menus management
introduction_menu = fields.Boolean(
"Introduction Menu", compute="_compute_website_menu_data",
readonly=False, store=True)
introduction_menu_ids = fields.One2many(
"website.event.menu", "event_id", string="Introduction Menus",
domain=[("menu_type", "=", "introduction")])
location_menu = fields.Boolean(
"Location Menu", compute="_compute_website_menu_data",
readonly=False, store=True)
location_menu_ids = fields.One2many(
"website.event.menu", "event_id", string="Location Menus",
domain=[("menu_type", "=", "location_menu")])
register_menu = fields.Boolean(
"Register Menu", compute="_compute_website_menu_data",
readonly=False, store=True)
register_menu_ids = fields.One2many(
"website.event.menu", "event_id", string="Register Menus",
domain=[("menu_type", "=", "register")])
community_menu = fields.Boolean(
"Community Menu", compute="_compute_community_menu",
readonly=False, store=True,
help="Display community tab on website")
community_menu_ids = fields.One2many(
"website.event.menu", "event_id", string="Event Community Menus",
domain=[("menu_type", "=", "community")])
# live information
is_ongoing = fields.Boolean(
'Is Ongoing', compute='_compute_time_data', search='_search_is_ongoing',
help="Whether event has begun")
is_done = fields.Boolean(
'Is Done', compute='_compute_time_data',
help="Whether event is finished")
start_today = fields.Boolean(
'Start Today', compute='_compute_time_data',
help="Whether event is going to start today if still not ongoing")
start_remaining = fields.Integer(
'Remaining before start', compute='_compute_time_data',
help="Remaining time before event starts (minutes)")
def _compute_is_participating(self):
"""Heuristic
* public, no visitor: not participating as we have no information;
* public and visitor: check visitor is linked to a registration. As
visitors are merged on the top parent, current visitor check is
sufficient even for successive visits;
* logged, no visitor: check partner is linked to a registration. Do
not check the email as it is not really secure;
* logged as visitor: check partner or visitor are linked to a
registration;
"""
current_visitor = self.env['website.visitor']._get_visitor_from_request(force_create=False)
if self.env.user._is_public() and not current_visitor:
events = self.env['event.event']
elif self.env.user._is_public():
events = self.env['event.registration'].sudo().search([
('event_id', 'in', self.ids),
('state', '!=', 'cancel'),
('visitor_id', '=', current_visitor.id),
]).event_id
else:
if current_visitor:
domain = [
'|',
('partner_id', '=', self.env.user.partner_id.id),
('visitor_id', '=', current_visitor.id)
]
else:
domain = [('partner_id', '=', self.env.user.partner_id.id)]
events = self.env['event.registration'].sudo().search(
expression.AND([
domain,
['&', ('event_id', 'in', self.ids), ('state', '!=', 'cancel')]
])
).event_id
for event in self:
event.is_participating = event in events
@api.depends('event_type_id')
def _compute_website_menu(self):
""" Also ensure a value for website_menu as it is a trigger notably for
track related menus. """
for event in self:
if event.event_type_id and event.event_type_id != event._origin.event_type_id:
event.website_menu = event.event_type_id.website_menu
elif not event.website_menu:
event.website_menu = False
@api.depends("event_type_id", "website_menu", "community_menu")
def _compute_community_menu(self):
""" Set False in base module. Sub modules will add their own logic
(meet or track_quiz). """
for event in self:
event.community_menu = False
@api.depends("website_menu")
def _compute_website_menu_data(self):
""" Synchronize with website_menu at change and let people update them
at will afterwards. """
for event in self:
event.introduction_menu = event.website_menu
event.location_menu = event.website_menu
event.register_menu = event.website_menu
@api.depends("event_type_id", "website_menu")
def _compute_menu_register_cta(self):
""" At type onchange: synchronize. At website_menu update: synchronize. """
for event in self:
if event.event_type_id and event.event_type_id != event._origin.event_type_id:
event.menu_register_cta = event.event_type_id.menu_register_cta
elif event.website_menu and (event.website_menu != event._origin.website_menu or not event.menu_register_cta):
event.menu_register_cta = True
elif not event.website_menu:
event.menu_register_cta = False
@api.depends('date_begin', 'date_end')
def _compute_time_data(self):
""" Compute start and remaining time. Do everything in UTC as we compute only
time deltas here. """
now_utc = utc.localize(fields.Datetime.now().replace(microsecond=0))
for event in self:
date_begin_utc = utc.localize(event.date_begin, is_dst=False)
date_end_utc = utc.localize(event.date_end, is_dst=False)
event.is_ongoing = date_begin_utc <= now_utc <= date_end_utc
event.is_done = now_utc > date_end_utc
event.start_today = date_begin_utc.date() == now_utc.date()
if date_begin_utc >= now_utc:
td = date_begin_utc - now_utc
event.start_remaining = int(td.total_seconds() / 60)
else:
event.start_remaining = 0
@api.depends('name')
def _compute_website_url(self):
super(Event, self)._compute_website_url()
for event in self:
if event.id: # avoid to perform a slug on a not yet saved record in case of an onchange.
event.website_url = '/event/%s' % slug(event)
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
events = super().create(vals_list)
events._update_website_menus()
return events
def write(self, vals):
menus_state_by_field = self._split_menus_state_by_field()
res = super(Event, self).write(vals)
menus_update_by_field = self._get_menus_update_by_field(menus_state_by_field, force_update=vals.keys())
self._update_website_menus(menus_update_by_field=menus_update_by_field)
return res
# ------------------------------------------------------------
# WEBSITE MENU MANAGEMENT
# ------------------------------------------------------------
def toggle_website_menu(self, val):
self.website_menu = val
def _get_menu_update_fields(self):
"""" Return a list of fields triggering a split of menu to activate /
menu to de-activate. Due to saas-13.3 improvement of menu management
this is done using side-methods to ease inheritance.
:return list: list of fields, each of which triggering a menu update
like website_menu, website_track, ... """
return ['community_menu', 'introduction_menu', 'location_menu', 'register_menu']
def _get_menu_type_field_matching(self):
return {
'community': 'community_menu',
'introduction': 'introduction_menu',
'location': 'location_menu',
'register': 'register_menu',
}
def _split_menus_state_by_field(self):
""" For each field linked to a menu, get the set of events having this
menu activated and de-activated. Purpose is to find those whose value
changed and update the underlying menus.
:return dict: key = name of field triggering a website menu update, get {
'activated': subset of self having its menu currently set to True
'deactivated': subset of self having its menu currently set to False
} """
menus_state_by_field = dict()
for fname in self._get_menu_update_fields():
activated = self.filtered(lambda event: event[fname])
menus_state_by_field[fname] = {
'activated': activated,
'deactivated': self - activated,
}
return menus_state_by_field
def _get_menus_update_by_field(self, menus_state_by_field, force_update=None):
""" For each field linked to a menu, get the set of events requiring
this menu to be activated or de-activated based on previous recorded
value.
:param menus_state_by_field: see ``_split_menus_state_by_field``;
:param force_update: list of field to which we force update of menus. This
is used notably when a direct write to a stored editable field messes with
its pre-computed value, notably in a transient mode (aka demo for example);
:return dict: key = name of field triggering a website menu update, get {
'activated': subset of self having its menu toggled to True
'deactivated': subset of self having its menu toggled to False
} """
menus_update_by_field = dict()
for fname in self._get_menu_update_fields():
if fname in force_update:
menus_update_by_field[fname] = self
else:
menus_update_by_field[fname] = self.env['event.event']
menus_update_by_field[fname] |= menus_state_by_field[fname]['activated'].filtered(lambda event: not event[fname])
menus_update_by_field[fname] |= menus_state_by_field[fname]['deactivated'].filtered(lambda event: event[fname])
return menus_update_by_field
def _get_website_menu_entries(self):
""" Method returning menu entries to display on the website view of the
event, possibly depending on some options in inheriting modules.
Each menu entry is a tuple containing :
* name: menu item name
* url: if set, url to a route (do not use xml_id in that case);
* xml_id: template linked to the page (do not use url in that case);
* sequence: specific sequence of menu entry to be set on the menu;
* menu_type: type of menu entry (used in inheriting modules to ease
menu management; not used in this module in 13.3 due to technical
limitations);
"""
self.ensure_one()
return [
(_('Introduction'), False, 'website_event.template_intro', 1, 'introduction'),
(_('Location'), False, 'website_event.template_location', 50, 'location'),
(_('Register'), '/event/%s/register' % slug(self), False, 100, 'register'),
(_('Community'), '/event/%s/community' % slug(self), False, 80, 'community'),
]
def _update_website_menus(self, menus_update_by_field=None):
""" Synchronize event configuration and its menu entries for frontend.
:param menus_update_by_field: see ``_get_menus_update_by_field``"""
for event in self:
if event.menu_id and not event.website_menu:
# do not rely on cascade, as it is done in SQL -> not calling override and
# letting some ir.ui.views in DB
(event.menu_id + event.menu_id.child_id).sudo().unlink()
elif event.website_menu and not event.menu_id:
root_menu = self.env['website.menu'].sudo().create({'name': event.name, 'website_id': event.website_id.id})
event.menu_id = root_menu
if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('community_menu')):
event._update_website_menu_entry('community_menu', 'community_menu_ids', 'community')
if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('introduction_menu')):
event._update_website_menu_entry('introduction_menu', 'introduction_menu_ids', 'introduction')
if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('location_menu')):
event._update_website_menu_entry('location_menu', 'location_menu_ids', 'location')
if event.menu_id and (not menus_update_by_field or event in menus_update_by_field.get('register_menu')):
event._update_website_menu_entry('register_menu', 'register_menu_ids', 'register')
def _update_website_menu_entry(self, fname_bool, fname_o2m, fmenu_type):
""" Generic method to create menu entries based on a flag on event. This
method is a bit obscure, but is due to preparation of adding new menus
entries and pages for event in a stable version, leading to some constraints
while developing.
:param fname_bool: field name (e.g. website_track)
:param fname_o2m: o2m linking towards website.event.menu matching the
boolean fields (normally an entry ot website.event.menu with type matching
the boolean field name)
:param method_name: method returning menu entries information: url, sequence, ...
"""
self.ensure_one()
new_menu = None
menu_data = [menu_info for menu_info in self._get_website_menu_entries()
if menu_info[4] == fmenu_type]
if self[fname_bool] and not self[fname_o2m]:
# menus not found but boolean True: get menus to create
for name, url, xml_id, menu_sequence, menu_type in menu_data:
new_menu = self._create_menu(menu_sequence, name, url, xml_id, menu_type)
elif not self[fname_bool]:
# will cascade delete to the website.event.menu
self[fname_o2m].mapped('menu_id').sudo().unlink()
return new_menu
def _create_menu(self, sequence, name, url, xml_id, menu_type):
""" Create a new menu for the current event.
If url: create a website menu. Menu leads directly to the URL that
should be a valid route.
If xml_id: create a new page using the qweb template given by its
xml_id. Take its url back thanks to new_page of website, then link
it to a menu. Template is duplicated and linked to a new url, meaning
each menu will have its own copy of the template. This is currently
limited to two menus: introduction and location.
:param menu_type: type of menu. Mainly used for inheritance purpose
allowing more fine-grain tuning of menus.
"""
self.check_access_rights('write')
view_id = False
if not url:
# add_menu=False, ispage=False -> simply create a new ir.ui.view with name
# and template
page_result = self.env['website'].sudo().new_page(
name=name + ' ' + self.name, template=xml_id,
add_menu=False, ispage=False)
url = "/event/" + slug(self) + "/page" + page_result['url'] # url contains starting "/"
view_id = page_result['view_id']
website_menu = self.env['website.menu'].sudo().create({
'name': name,
'url': url,
'parent_id': self.menu_id.id,
'sequence': sequence,
'website_id': self.website_id.id,
})
self.env['website.event.menu'].create({
'menu_id': website_menu.id,
'event_id': self.id,
'menu_type': menu_type,
'view_id': view_id,
})
return website_menu
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
def google_map_link(self, zoom=8):
""" Temporary method for stable """
return self._google_map_link(zoom=zoom)
def _google_map_link(self, zoom=8):
self.ensure_one()
if self.address_id:
return self.sudo().address_id.google_map_link(zoom=zoom)
return None
def _track_subtype(self, init_values):
self.ensure_one()
if 'is_published' in init_values and self.is_published:
return self.env.ref('website_event.mt_event_published')
elif 'is_published' in init_values and not self.is_published:
return self.env.ref('website_event.mt_event_unpublished')
return super(Event, self)._track_subtype(init_values)
def _get_event_resource_urls(self):
url_date_start = self.date_begin.strftime('%Y%m%dT%H%M%SZ')
url_date_stop = self.date_end.strftime('%Y%m%dT%H%M%SZ')
params = {
'action': 'TEMPLATE',
'text': self.name,
'dates': url_date_start + '/' + url_date_stop,
'details': self.name,
}
if self.address_id:
params.update(location=self.sudo().address_id.contact_address.replace('\n', ' '))
encoded_params = werkzeug.urls.url_encode(params)
google_url = GOOGLE_CALENDAR_URL + encoded_params
iCal_url = '/event/%d/ics?%s' % (self.id, encoded_params)
return {'google_url': google_url, 'iCal_url': iCal_url}
def _default_website_meta(self):
res = super(Event, self)._default_website_meta()
event_cover_properties = json.loads(self.cover_properties)
# background-image might contain single quotes eg `url('/my/url')`
res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = event_cover_properties.get('background-image', 'none')[4:-1].strip("'")
res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name
res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = self.subtitle
res['default_twitter']['twitter:card'] = 'summary'
res['default_meta_description'] = self.subtitle
return res
def get_backend_menu_id(self):
return self.env.ref('event.event_main_menu').id
@api.model
def _search_build_dates(self):
today = fields.Datetime.today()
def sdn(date):
return fields.Datetime.to_string(date.replace(hour=23, minute=59, second=59))
def sd(date):
return fields.Datetime.to_string(date)
def get_month_filter_domain(filter_name, months_delta):
first_day_of_the_month = today.replace(day=1)
filter_string = _('This month') if months_delta == 0 \
else format_date(self.env, value=today + relativedelta(months=months_delta),
date_format='LLLL', lang_code=get_lang(self.env).code).capitalize()
return [filter_name, filter_string, [
("date_end", ">=", sd(first_day_of_the_month + relativedelta(months=months_delta))),
("date_begin", "<", sd(first_day_of_the_month + relativedelta(months=months_delta+1)))],
0]
return [
['all', _('Upcoming Events'), [("date_end", ">", sd(today))], 0],
['today', _('Today'), [
("date_end", ">", sd(today)),
("date_begin", "<", sdn(today))],
0],
get_month_filter_domain('month', 0),
['old', _('Past Events'), [
("date_end", "<", sd(today))],
0],
]
@api.model
def _search_get_detail(self, website, order, options):
with_description = options['displayDescription']
with_date = options['displayDetail']
date = options.get('date', 'all')
country = options.get('country')
tags = options.get('tags')
event_type = options.get('type', 'all')
domain = [website.website_domain()]
if event_type != 'all':
domain.append([("event_type_id", "=", int(event_type))])
search_tags = self.env['event.tag']
if tags:
try:
tag_ids = literal_eval(tags)
except SyntaxError:
pass
else:
# perform a search to filter on existing / valid tags implicitely + apply rules on color
search_tags = self.env['event.tag'].search([('id', 'in', tag_ids)])
# Example: You filter on age: 10-12 and activity: football.
# Doing it this way allows to only get events who are tagged "age: 10-12" AND "activity: football".
# Add another tag "age: 12-15" to the search and it would fetch the ones who are tagged:
# ("age: 10-12" OR "age: 12-15") AND "activity: football
grouped_tags = defaultdict(list)
for tag in search_tags:
grouped_tags[tag.category_id].append(tag)
for group in grouped_tags:
domain.append([('tag_ids', 'in', [tag.id for tag in grouped_tags[group]])])
no_country_domain = domain.copy()
if country:
if country == 'online':
domain.append([("country_id", "=", False)])
elif country != 'all':
domain.append(['|', ("country_id", "=", int(country)), ("country_id", "=", False)])
no_date_domain = domain.copy()
dates = self._search_build_dates()
current_date = None
for date_details in dates:
if date == date_details[0]:
domain.append(date_details[2])
no_country_domain.append(date_details[2])
if date_details[0] != 'all':
current_date = date_details[1]
search_fields = ['name']
fetch_fields = ['name', 'website_url']
mapping = {
'name': {'name': 'name', 'type': 'text', 'match': True},
'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False},
}
if with_description:
search_fields.append('subtitle')
fetch_fields.append('subtitle')
mapping['description'] = {'name': 'subtitle', 'type': 'text', 'match': True}
if with_date:
mapping['detail'] = {'name': 'range', 'type': 'html'}
return {
'model': 'event.event',
'base_domain': domain,
'search_fields': search_fields,
'fetch_fields': fetch_fields,
'mapping': mapping,
'icon': 'fa-ticket',
# for website_event main controller:
'dates': dates,
'current_date': current_date,
'search_tags': search_tags,
'no_date_domain': no_date_domain,
'no_country_domain': no_country_domain,
}
def _search_render_results(self, fetch_fields, mapping, icon, limit):
with_date = 'detail' in mapping
results_data = super()._search_render_results(fetch_fields, mapping, icon, limit)
if with_date:
for event, data in zip(self, results_data):
begin = self.env['ir.qweb.field.date'].record_to_html(event, 'date_begin', {})
end = self.env['ir.qweb.field.date'].record_to_html(event, 'date_end', {})
data['range'] = '%s🠖%s' % (begin, end) if begin != end else begin
return results_data
| 46.131532
| 25,603
|
869
|
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 EventMenu(models.Model):
_name = "website.event.menu"
_description = "Website Event Menu"
menu_id = fields.Many2one('website.menu', string='Menu', ondelete='cascade')
event_id = fields.Many2one('event.event', string='Event', ondelete='cascade')
view_id = fields.Many2one('ir.ui.view', string='View', ondelete='cascade', help='Used when not being an url based menu')
menu_type = fields.Selection(
[('community', 'Community Menu'),
('introduction', 'Introduction'),
('location', 'Location'),
('register', 'Register'),
], string="Menu Type", required=True)
def unlink(self):
self.view_id.sudo().unlink()
return super(EventMenu, self).unlink()
| 37.782609
| 869
|
1,147
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
from odoo.addons.http_routing.models.ir_http import url_for
class Website(models.Model):
_inherit = "website"
def get_suggested_controllers(self):
suggested_controllers = super(Website, self).get_suggested_controllers()
suggested_controllers.append((_('Events'), url_for('/event'), 'website_event'))
return suggested_controllers
def get_cta_data(self, website_purpose, website_type):
cta_data = super(Website, self).get_cta_data(website_purpose, website_type)
if website_purpose == 'sell_more' and website_type == 'event':
cta_btn_text = _('Next Events')
return {'cta_btn_text': cta_btn_text, 'cta_btn_href': '/event'}
return cta_data
def _search_get_details(self, search_type, order, options):
result = super()._search_get_details(search_type, order, options)
if search_type in ['events', 'all']:
result.append(self.env['event.event']._search_get_detail(self, order, options))
return result
| 44.115385
| 1,147
|
6,101
|
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 WebsiteVisitor(models.Model):
_name = 'website.visitor'
_inherit = ['website.visitor']
parent_id = fields.Many2one(
'website.visitor', string="Parent", ondelete='set null',
help="Main identity")
event_registration_ids = fields.One2many(
'event.registration', 'visitor_id', string='Event Registrations',
groups="event.group_event_registration_desk")
event_registration_count = fields.Integer(
'# Registrations', compute='_compute_event_registration_count',
groups="event.group_event_registration_desk")
event_registered_ids = fields.Many2many(
'event.event', string="Registered Events",
compute="_compute_event_registered_ids", compute_sudo=True,
search="_search_event_registered_ids",
groups="event.group_event_registration_desk")
@api.depends('event_registration_ids')
def _compute_event_registration_count(self):
if self.ids:
read_group_res = self.env['event.registration'].read_group(
[('visitor_id', 'in', self.ids)],
['visitor_id'], ['visitor_id'])
visitor_mapping = dict(
(item['visitor_id'][0], item['visitor_id_count'])
for item in read_group_res)
else:
visitor_mapping = dict()
for visitor in self:
visitor.event_registration_count = visitor_mapping.get(visitor.id) or 0
@api.depends('event_registration_ids.email', 'event_registration_ids.mobile', 'event_registration_ids.phone')
def _compute_email_phone(self):
super(WebsiteVisitor, self)._compute_email_phone()
self.flush()
for visitor in self.filtered(lambda visitor: not visitor.email or not visitor.mobile):
linked_registrations = visitor.event_registration_ids.sorted(lambda reg: (reg.create_date, reg.id), reverse=False)
if not visitor.email:
visitor.email = next((reg.email for reg in linked_registrations if reg.email), False)
if not visitor.mobile:
visitor.mobile = next((reg.mobile or reg.phone for reg in linked_registrations if reg.mobile or reg.phone), False)
@api.depends('parent_id', 'event_registration_ids')
def _compute_event_registered_ids(self):
# include parent's registrations in a visitor o2m field. We don't add
# child one as child should not have registrations (moved to the parent)
for visitor in self:
all_registrations = visitor.event_registration_ids | visitor.parent_id.event_registration_ids
visitor.event_registered_ids = all_registrations.mapped('event_id')
def _search_event_registered_ids(self, operator, operand):
""" Search visitors with terms on events within their event registrations. E.g. [('event_registered_ids',
'in', [1, 2])] should return visitors having a registration on events 1, 2 as
well as their children for notification purpose. """
if operator == "not in":
raise NotImplementedError("Unsupported 'Not In' operation on visitors registrations")
all_registrations = self.env['event.registration'].sudo().search([
('event_id', operator, operand)
])
if all_registrations:
# search children, even archived one, to contact them
visitors = all_registrations.with_context(active_test=False).mapped('visitor_id')
children = self.env['website.visitor'].with_context(
active_test=False
).sudo().search([('parent_id', 'in', visitors.ids)])
visitor_ids = (visitors + children).ids
else:
visitor_ids = []
return [('id', 'in', visitor_ids)]
def _link_to_partner(self, partner, update_values=None):
""" Propagate partner update to registration records """
if partner:
registration_wo_partner = self.event_registration_ids.filtered(lambda registration: not registration.partner_id)
if registration_wo_partner:
registration_wo_partner.partner_id = partner
super(WebsiteVisitor, self)._link_to_partner(partner, update_values=update_values)
def _link_to_visitor(self, target, keep_unique=True):
""" Override linking process to link registrations to the final visitor. """
self.event_registration_ids.write({'visitor_id': target.id})
res = super(WebsiteVisitor, self)._link_to_visitor(target, keep_unique=False)
if keep_unique:
self.partner_id = False
self.parent_id = target.id
self.active = False
return res
def _get_visitor_from_request(self, force_create=False):
""" When fetching visitor, now that duplicates are linked to a main visitor
instead of unlinked, you may have more collisions issues with cookie being
set after a de-connection for example.
In base method, visitor associated to a partner in case of public user is
not taken into account. It is considered as desynchronized cookie. Here
we also discard if the visitor has a main visitor whose partner is set
(aka wrong after logout partner). """
visitor = super(WebsiteVisitor, self)._get_visitor_from_request(force_create=force_create)
# also check that visitor parent partner is not different from user's one (indicates duplicate due to invalid or wrong cookie)
if visitor and visitor.parent_id.partner_id:
if self.env.user._is_public():
visitor = self.env['website.visitor'].sudo()
elif not visitor.partner_id:
visitor = self.env['website.visitor'].sudo().with_context(active_test=False).search(
[('partner_id', '=', self.env.user.partner_id.id)]
)
if not visitor and force_create:
visitor = self._create_visitor()
return visitor
| 48.420635
| 6,101
|
560
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
class EventCommunityController(http.Controller):
@http.route('/event/<model("event.event"):event>/community', type="http", auth="public", website=True, sitemap=False)
def community(self, event, lang=None, **kwargs):
""" This skeleton route will be overriden in website_event_track_quiz, website_event_meet and website_event_meet_quiz. """
return request.render('website.page_404')
| 43.076923
| 560
|
20,022
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import babel.dates
import pytz
import re
import werkzeug
from ast import literal_eval
from collections import defaultdict
from datetime import datetime, timedelta
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from werkzeug.datastructures import OrderedMultiDict
from werkzeug.exceptions import NotFound
from odoo import fields, http, _
from odoo.addons.http_routing.models.ir_http import slug
from odoo.addons.website.controllers.main import QueryURL
from odoo.http import request
from odoo.osv import expression
from odoo.tools.misc import get_lang
from odoo.exceptions import UserError
class WebsiteEventController(http.Controller):
def sitemap_event(env, rule, qs):
if not qs or qs.lower() in '/events':
yield {'loc': '/events'}
# ------------------------------------------------------------
# EVENT LIST
# ------------------------------------------------------------
@http.route(['/event', '/event/page/<int:page>', '/events', '/events/page/<int:page>'], type='http', auth="public", website=True, sitemap=sitemap_event)
def events(self, page=1, **searches):
Event = request.env['event.event']
SudoEventType = request.env['event.type'].sudo()
searches.setdefault('search', '')
searches.setdefault('date', 'all')
searches.setdefault('tags', '')
searches.setdefault('type', 'all')
searches.setdefault('country', 'all')
website = request.website
step = 12 # Number of events per page
options = {
'displayDescription': False,
'displayDetail': False,
'displayExtraDetail': False,
'displayExtraLink': False,
'displayImage': False,
'allowFuzzy': not searches.get('noFuzzy'),
'date': searches.get('date'),
'tags': searches.get('tags'),
'type': searches.get('type'),
'country': searches.get('country'),
}
order = 'date_begin'
if searches.get('date', 'all') == 'old':
order = 'date_begin desc'
order = 'is_published desc, ' + order
search = searches.get('search')
event_count, details, fuzzy_search_term = website._search_with_fuzzy("events", search,
limit=page * step, order=order, options=options)
event_details = details[0]
events = event_details.get('results', Event)
events = events[(page - 1) * step:page * step]
# count by domains without self search
domain_search = [('name', 'ilike', fuzzy_search_term or searches['search'])] if searches['search'] else []
no_date_domain = event_details['no_date_domain']
dates = event_details['dates']
for date in dates:
if date[0] != 'old':
date[3] = Event.search_count(expression.AND(no_date_domain) + domain_search + date[2])
no_country_domain = event_details['no_country_domain']
countries = Event.read_group(expression.AND(no_country_domain) + domain_search, ["id", "country_id"],
groupby="country_id", orderby="country_id")
countries.insert(0, {
'country_id_count': sum([int(country['country_id_count']) for country in countries]),
'country_id': ("all", _("All Countries"))
})
search_tags = event_details['search_tags']
current_date = event_details['current_date']
current_type = None
current_country = None
if searches["type"] != 'all':
current_type = SudoEventType.browse(int(searches['type']))
if searches["country"] != 'all' and searches["country"] != 'online':
current_country = request.env['res.country'].browse(int(searches['country']))
pager = website.pager(
url="/event",
url_args=searches,
total=event_count,
page=page,
step=step,
scope=5)
keep = QueryURL('/event', **{key: value for key, value in searches.items() if (key == 'search' or value != 'all')})
searches['search'] = fuzzy_search_term or search
values = {
'current_date': current_date,
'current_country': current_country,
'current_type': current_type,
'event_ids': events, # event_ids used in website_event_track so we keep name as it is
'dates': dates,
'categories': request.env['event.tag.category'].search([('is_published', '=', True)]),
'countries': countries,
'pager': pager,
'searches': searches,
'search_tags': search_tags,
'keep': keep,
'search_count': event_count,
'original_search': fuzzy_search_term and search,
}
if searches['date'] == 'old':
# the only way to display this content is to set date=old so it must be canonical
values['canonical_params'] = OrderedMultiDict([('date', 'old')])
return request.render("website_event.index", values)
# ------------------------------------------------------------
# EVENT PAGE
# ------------------------------------------------------------
@http.route(['''/event/<model("event.event"):event>/page/<path:page>'''], type='http', auth="public", website=True, sitemap=False)
def event_page(self, event, page, **post):
values = {
'event': event,
}
if '.' not in page:
page = 'website_event.%s' % page
try:
# Every event page view should have its own SEO.
values['seo_object'] = request.website.get_template(page)
values['main_object'] = event
except ValueError:
# page not found
values['path'] = re.sub(r"^website_event\.", '', page)
values['from_template'] = 'website_event.default_page' # .strip('website_event.')
page = request.website.is_publisher() and 'website.page_404' or 'http_routing.404'
return request.render(page, values)
@http.route(['''/event/<model("event.event"):event>'''], type='http', auth="public", website=True, sitemap=True)
def event(self, event, **post):
if event.menu_id and event.menu_id.child_id:
target_url = event.menu_id.child_id[0].url
else:
target_url = '/event/%s/register' % str(event.id)
if post.get('enable_editor') == '1':
target_url += '?enable_editor=1'
return request.redirect(target_url)
@http.route(['''/event/<model("event.event"):event>/register'''], type='http', auth="public", website=True, sitemap=False)
def event_register(self, event, **post):
values = self._prepare_event_register_values(event, **post)
return request.render("website_event.event_description_full", values)
def _prepare_event_register_values(self, event, **post):
"""Return the require values to render the template."""
urls = event._get_event_resource_urls()
return {
'event': event,
'main_object': event,
'range': range,
'google_url': urls.get('google_url'),
'iCal_url': urls.get('iCal_url'),
}
def _process_tickets_form(self, event, form_details):
""" Process posted data about ticket order. Generic ticket are supported
for event without tickets (generic registration).
:return: list of order per ticket: [{
'id': if of ticket if any (0 if no ticket),
'ticket': browse record of ticket if any (None if no ticket),
'name': ticket name (or generic 'Registration' name if no ticket),
'quantity': number of registrations for that ticket,
}, {...}]
"""
ticket_order = {}
for key, value in form_details.items():
registration_items = key.split('nb_register-')
if len(registration_items) != 2:
continue
ticket_order[int(registration_items[1])] = int(value)
ticket_dict = dict((ticket.id, ticket) for ticket in request.env['event.event.ticket'].sudo().search([
('id', 'in', [tid for tid in ticket_order.keys() if tid]),
('event_id', '=', event.id)
]))
return [{
'id': tid if ticket_dict.get(tid) else 0,
'ticket': ticket_dict.get(tid),
'name': ticket_dict[tid]['name'] if ticket_dict.get(tid) else _('Registration'),
'quantity': count,
} for tid, count in ticket_order.items() if count]
@http.route(['/event/<model("event.event"):event>/registration/new'], type='json', auth="public", methods=['POST'], website=True)
def registration_new(self, event, **post):
tickets = self._process_tickets_form(event, post)
availability_check = True
if event.seats_limited:
ordered_seats = 0
for ticket in tickets:
ordered_seats += ticket['quantity']
if event.seats_available < ordered_seats:
availability_check = False
if not tickets:
return False
default_first_attendee = {}
if not request.env.user._is_public():
default_first_attendee = {
"name": request.env.user.name,
"email": request.env.user.email,
"phone": request.env.user.mobile or request.env.user.phone,
}
else:
visitor = request.env['website.visitor']._get_visitor_from_request()
if visitor.email:
default_first_attendee = {
"name": visitor.name,
"email": visitor.email,
"phone": visitor.mobile,
}
return request.env['ir.ui.view']._render_template("website_event.registration_attendee_details", {
'tickets': tickets,
'event': event,
'availability_check': availability_check,
'default_first_attendee': default_first_attendee,
})
def _process_attendees_form(self, event, form_details):
""" Process data posted from the attendee details form.
:param form_details: posted data from frontend registration form, like
{'1-name': 'r', '1-email': 'r@r.com', '1-phone': '', '1-event_ticket_id': '1'}
"""
allowed_fields = request.env['event.registration']._get_website_registration_allowed_fields()
registration_fields = {key: v for key, v in request.env['event.registration']._fields.items() if key in allowed_fields}
for ticket_id in list(filter(lambda x: x is not None, [form_details[field] if 'event_ticket_id' in field else None for field in form_details.keys()])):
if int(ticket_id) not in event.event_ticket_ids.ids and len(event.event_ticket_ids.ids) > 0:
raise UserError(_("This ticket is not available for sale for this event"))
registrations = {}
global_values = {}
for key, value in form_details.items():
counter, attr_name = key.split('-', 1)
field_name = attr_name.split('-')[0]
if field_name not in registration_fields:
continue
elif isinstance(registration_fields[field_name], (fields.Many2one, fields.Integer)):
value = int(value) or False # 0 is considered as a void many2one aka False
else:
value = value
if counter == '0':
global_values[attr_name] = value
else:
registrations.setdefault(counter, dict())[attr_name] = value
for key, value in global_values.items():
for registration in registrations.values():
registration[key] = value
return list(registrations.values())
def _create_attendees_from_registration_post(self, event, registration_data):
""" Also try to set a visitor (from request) and
a partner (if visitor linked to a user for example). Purpose is to gather
as much informations as possible, notably to ease future communications.
Also try to update visitor informations based on registration info. """
visitor_sudo = request.env['website.visitor']._get_visitor_from_request(force_create=True)
visitor_sudo._update_visitor_last_visit()
visitor_values = {}
registrations_to_create = []
for registration_values in registration_data:
registration_values['event_id'] = event.id
if not registration_values.get('partner_id') and visitor_sudo.partner_id:
registration_values['partner_id'] = visitor_sudo.partner_id.id
elif not registration_values.get('partner_id'):
registration_values['partner_id'] = False if request.env.user._is_public() else request.env.user.partner_id.id
if visitor_sudo:
# registration may give a name to the visitor, yay
if registration_values.get('name') and not visitor_sudo.name and not visitor_values.get('name'):
visitor_values['name'] = registration_values['name']
# update registration based on visitor
registration_values['visitor_id'] = visitor_sudo.id
registrations_to_create.append(registration_values)
if visitor_values:
visitor_sudo.write(visitor_values)
return request.env['event.registration'].sudo().create(registrations_to_create)
@http.route(['''/event/<model("event.event"):event>/registration/confirm'''], type='http', auth="public", methods=['POST'], website=True)
def registration_confirm(self, event, **post):
registrations = self._process_attendees_form(event, post)
attendees_sudo = self._create_attendees_from_registration_post(event, registrations)
visitor_sudo = attendees_sudo.visitor_id
redirect = request.redirect(('/event/%s/registration/success?' % event.id) + werkzeug.urls.url_encode({'registration_ids': ",".join([str(id) for id in attendees_sudo.ids])}))
# make sure the vistor's uuid is correctly logged in cookies when disabling "Track Visitor" on all the pages of the event
# we set visitor_uuid in the cookie to be sure "event_registration_success" can retrieve the visitor
if request.httprequest.cookies.get('visitor_uuid', '') != visitor_sudo.access_token:
expiration_date = datetime.now() + timedelta(days=365)
redirect.set_cookie('visitor_uuid', visitor_sudo.access_token, expires=expiration_date)
return redirect
@http.route(['/event/<model("event.event"):event>/registration/success'], type='http', auth="public", methods=['GET'], website=True, sitemap=False)
def event_registration_success(self, event, registration_ids):
# fetch the related registrations, make sure they belong to the correct visitor / event pair
visitor = request.env['website.visitor']._get_visitor_from_request()
if not visitor:
raise NotFound()
attendees_sudo = request.env['event.registration'].sudo().search([
('id', 'in', [str(registration_id) for registration_id in registration_ids.split(',')]),
('event_id', '=', event.id),
('visitor_id', '=', visitor.id),
])
return request.render("website_event.registration_complete",
self._get_registration_confirm_values(event, attendees_sudo))
def _get_registration_confirm_values(self, event, attendees_sudo):
urls = event._get_event_resource_urls()
return {
'attendees': attendees_sudo,
'event': event,
'google_url': urls.get('google_url'),
'iCal_url': urls.get('iCal_url')
}
# ------------------------------------------------------------
# EDITOR (NEW EVENT)
# ------------------------------------------------------------
@http.route('/event/add_event', type='json', auth="user", methods=['POST'], website=True)
def add_event(self, name, event_start, event_end, address_values, **kwargs):
values = self._prepare_event_values(name, event_start, event_end, address_values)
event = request.env['event.event'].create(values)
return "/event/%s/register?enable_editor=1" % slug(event)
def _prepare_event_values(self, name, event_start, event_end, address_values=None):
"""
Return the values to create a new event.
event_start,event_date are datetimes in the user tz.
address_values is used to either choose an existing location or create one as we allow it in the frontend.
"""
date_begin = parse(event_start).astimezone(pytz.utc).replace(tzinfo=None)
date_end = parse(event_end).astimezone(pytz.utc).replace(tzinfo=None)
address_id = request.env['res.partner']
if address_values:
(address_pid, address_vals) = int(address_values[0]), address_values[1]
address_id = address_pid
if address_pid == 0:
address_id = request.env['res.partner'].create(address_vals).id
return {
'name': name,
'date_begin': date_begin,
'date_end': date_end,
'address_id': address_id,
'seats_available': 1000,
'website_id': request.website.id,
'event_ticket_ids': request.env['event.event.ticket'],
}
# ------------------------------------------------------------
# TOOLS (JSON)
# ------------------------------------------------------------
@http.route('/event/get_country_event_list', type='json', auth='public', website=True)
def get_country_events(self, **post):
Event = request.env['event.event']
country_code = request.session['geoip'].get('country_code')
result = {'events': [], 'country': False}
events = None
domain = request.website.website_domain()
if country_code:
country = request.env['res.country'].search([('code', '=', country_code)], limit=1)
events = Event.search(domain + ['|', ('address_id', '=', None), ('country_id.code', '=', country_code), ('date_begin', '>=', '%s 00:00:00' % fields.Date.today())], order="date_begin")
if not events:
events = Event.search(domain + [('date_begin', '>=', '%s 00:00:00' % fields.Date.today())], order="date_begin")
for event in events:
if country_code and event.country_id.code == country_code:
result['country'] = country
result['events'].append({
"date": self.get_formated_date(event),
"event": event,
"url": event.website_url})
return request.env['ir.ui.view']._render_template("website_event.country_events_list", result)
# ------------------------------------------------------------
# TOOLS (HELPERS)
# ------------------------------------------------------------
def get_formated_date(self, event):
start_date = fields.Datetime.from_string(event.date_begin).date()
end_date = fields.Datetime.from_string(event.date_end).date()
month = babel.dates.get_month_names('abbreviated', locale=get_lang(event.env).code)[start_date.month]
return ('%s %s%s') % (month, start_date.strftime("%e"), (end_date != start_date and ("-" + end_date.strftime("%e")) or ""))
def _extract_searched_event_tags(self, searches):
tags = request.env['event.tag']
if searches.get('tags'):
try:
tag_ids = literal_eval(searches['tags'])
except:
pass
else:
# perform a search to filter on existing / valid tags implicitely + apply rules on color
tags = request.env['event.tag'].search([('id', 'in', tag_ids)])
return tags
| 46.347222
| 20,022
|
750
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Mail Tests',
'version': '1.0',
'category': 'Hidden',
'sequence': 9876,
'summary': 'Mail Tests: performances and tests specific to mail',
'description': """This module contains tests related to mail. Those are
present in a separate module as it contains models used only to perform
tests independently to functional aspects of other models. """,
'depends': ['test_performance', 'mail'],
'data': [
'security/ir.model.access.csv',
'security/test_mail_security.xml',
'data/data.xml',
'data/mail_template_data.xml',
'data/subtype_data.xml',
],
'demo': [
],
'installable': True,
'application': False,
'license': 'LGPL-3',
}
| 30
| 750
|
27,200
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from unittest.mock import patch
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.addons.test_mail.models.test_mail_models import MailTestSimple
from odoo.exceptions import AccessError, UserError
from odoo.tools import is_html_empty, mute_logger, formataddr
from odoo.tests import tagged, users
@tagged('mail_message')
class TestMessageValues(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestMessageValues, cls).setUpClass()
cls._init_mail_gateway()
cls.alias_record = cls.env['mail.test.container'].with_context(cls._test_context).create({
'name': 'Pigs',
'alias_name': 'pigs',
'alias_contact': 'followers',
})
cls.Message = cls.env['mail.message'].with_user(cls.user_employee)
@users('employee')
def test_empty_message(self):
""" Test that message is correctly considered as empty (see `_filter_empty()`).
Message considered as empty if:
- no body or empty body
- AND no subtype or no subtype description
- AND no tracking values
- AND no attachment
Check _update_content behavior when voiding messages (cleanup side
records: stars, notifications).
"""
note_subtype = self.env.ref('mail.mt_note')
_attach_1 = self.env['ir.attachment'].with_user(self.user_employee).create({
'name': 'Attach1',
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'res_id': 0,
'res_model': 'mail.compose.message',
})
record = self.env['mail.test.track'].create({'name': 'EmptyTesting'})
self.flush_tracking()
record.message_subscribe(partner_ids=self.partner_admin.ids, subtype_ids=note_subtype.ids)
message = record.message_post(
attachment_ids=_attach_1.ids,
body='Test',
message_type='comment',
subtype_id=note_subtype.id,
)
message.write({'starred_partner_ids': [(4, self.partner_admin.id)]})
# check content
self.assertEqual(len(message.attachment_ids), 1)
self.assertFalse(is_html_empty(message.body))
self.assertEqual(len(message.sudo().notification_ids), 1)
self.assertEqual(message.notified_partner_ids, self.partner_admin)
self.assertEqual(message.starred_partner_ids, self.partner_admin)
self.assertFalse(message.sudo().tracking_value_ids)
# Reset body case
message._update_content('<p><br /></p>', attachment_ids=message.attachment_ids.ids)
self.assertTrue(is_html_empty(message.body))
self.assertFalse(message.sudo()._filter_empty(), 'Still having attachments')
# Subtype content
note_subtype.write({'description': 'Very important discussions'})
message._update_content('', None)
self.assertFalse(message.attachment_ids)
self.assertEqual(message.notified_partner_ids, self.partner_admin)
self.assertEqual(message.starred_partner_ids, self.partner_admin)
self.assertFalse(message.sudo()._filter_empty(), 'Subtype with description')
# Completely void now
note_subtype.write({'description': ''})
self.assertEqual(message.sudo()._filter_empty(), message)
message._update_content('', None)
self.assertFalse(message.notified_partner_ids)
self.assertFalse(message.starred_partner_ids)
# test tracking values
record.write({'user_id': self.user_admin.id})
self.flush_tracking()
tracking_message = record.message_ids[0]
self.assertFalse(tracking_message.attachment_ids)
self.assertTrue(is_html_empty(tracking_message.body))
self.assertFalse(tracking_message.subtype_id.description)
self.assertFalse(tracking_message.sudo()._filter_empty(), 'Has tracking values')
with self.assertRaises(UserError, msg='Tracking values prevent from updating content'):
tracking_message._update_content('', None)
@mute_logger('odoo.models.unlink')
def test_mail_message_format(self):
record1 = self.env['mail.test.simple'].create({'name': 'Test1'})
message = self.env['mail.message'].create([{
'model': 'mail.test.simple',
'res_id': record1.id,
}])
res = message.message_format()
self.assertEqual(res[0].get('record_name'), 'Test1')
record1.write({"name": "Test2"})
res = message.message_format()
self.assertEqual(res[0].get('record_name'), 'Test2')
@mute_logger('odoo.models.unlink')
def test_mail_message_format_access(self):
"""
User that doesn't have access to a record should still be able to fetch
the record_name inside message_format.
"""
company_2 = self.env['res.company'].create({'name': 'Second Test Company'})
record1 = self.env['mail.test.multi.company'].create({
'name': 'Test1',
'company_id': company_2.id,
})
message = record1.message_post(body='', partner_ids=[self.user_employee.partner_id.id])
# We need to flush and invalidate the ORM cache since the record_name
# is already cached from the creation. Otherwise it will leak inside
# message_format.
message.flush()
message.invalidate_cache()
res = message.with_user(self.user_employee).message_format()
self.assertEqual(res[0].get('record_name'), 'Test1')
def test_mail_message_values_body_base64_image(self):
msg = self.env['mail.message'].with_user(self.user_employee).create({
'body': 'taratata <img src="data:image/png;base64,iV/+OkI=" width="2"> <img src="data:image/png;base64,iV/+OkI=" width="2">',
})
self.assertEqual(len(msg.attachment_ids), 1)
self.assertEqual(
msg.body,
'<p>taratata <img src="/web/image/{attachment.id}?access_token={attachment.access_token}" alt="image0" width="2"> '
'<img src="/web/image/{attachment.id}?access_token={attachment.access_token}" alt="image0" width="2"></p>'.format(attachment=msg.attachment_ids[0])
)
@mute_logger('odoo.models.unlink')
@users('employee')
def test_mail_message_values_fromto_long_name(self):
""" Long headers may break in python if above 78 chars as folding is not
done correctly (see ``_notify_get_reply_to_formatted_email`` docstring
+ commit linked to this test). """
# name would make it blow up: keep only email
test_record = self.env['mail.test.container'].browse(self.alias_record.ids)
test_record.write({
'name': 'Super Long Name That People May Enter "Even with an internal quoting of stuff"'
})
msg = self.env['mail.message'].create({
'model': test_record._name,
'res_id': test_record.id
})
reply_to_email = f"{test_record.alias_name}@{self.alias_domain}"
self.assertEqual(msg.reply_to, reply_to_email,
'Reply-To: use only email when formataddr > 78 chars')
# name + company_name would make it blow up: keep record_name in formatting
test_record.write({'name': 'Name that would be more than 78 with company name'})
msg = self.env['mail.message'].create({
'model': test_record._name,
'res_id': test_record.id
})
self.assertEqual(msg.reply_to, formataddr((test_record.name, reply_to_email)),
'Reply-To: use recordname as name in format if recordname + company > 78 chars')
# no record_name: keep company_name in formatting if ok
test_record.write({'name': ''})
msg = self.env['mail.message'].create({
'model': test_record._name,
'res_id': test_record.id
})
self.assertEqual(msg.reply_to, formataddr((self.env.user.company_id.name, reply_to_email)),
'Reply-To: use company as name in format when no record name and still < 78 chars')
# no record_name and company_name make it blow up: keep only email
self.env.user.company_id.write({'name': 'Super Long Name That People May Enter "Even with an internal quoting of stuff"'})
msg = self.env['mail.message'].create({
'model': test_record._name,
'res_id': test_record.id
})
self.assertEqual(msg.reply_to, reply_to_email,
'Reply-To: use only email when formataddr > 78 chars')
# whatever the record and company names, email is too long: keep only email
test_record.write({
'alias_name': 'Waaaay too long alias name that should make any reply-to blow the 78 characters limit',
'name': 'Short',
})
self.env.user.company_id.write({'name': 'Comp'})
sanitized_alias_name = 'waaaay-too-long-alias-name-that-should-make-any-reply-to-blow-the-78-characters-limit'
msg = self.env['mail.message'].create({
'model': test_record._name,
'res_id': test_record.id
})
self.assertEqual(msg.reply_to, f"{sanitized_alias_name}@{self.alias_domain}",
'Reply-To: even a long email is ok as only formataddr is problematic')
@mute_logger('odoo.models.unlink')
def test_mail_message_values_fromto_no_document_values(self):
msg = self.Message.create({
'reply_to': 'test.reply@example.com',
'email_from': 'test.from@example.com',
})
self.assertIn('-private', msg.message_id.split('@')[0], 'mail_message: message_id for a void message should be a "private" one')
self.assertEqual(msg.reply_to, 'test.reply@example.com')
self.assertEqual(msg.email_from, 'test.from@example.com')
@mute_logger('odoo.models.unlink')
def test_mail_message_values_fromto_no_document(self):
msg = self.Message.create({})
self.assertIn('-private', msg.message_id.split('@')[0], 'mail_message: message_id for a void message should be a "private" one')
reply_to_name = self.env.user.company_id.name
reply_to_email = '%s@%s' % (self.alias_catchall, self.alias_domain)
self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
# no alias domain -> author
self.env['ir.config_parameter'].search([('key', '=', 'mail.catchall.domain')]).unlink()
msg = self.Message.create({})
self.assertIn('-private', msg.message_id.split('@')[0], 'mail_message: message_id for a void message should be a "private" one')
self.assertEqual(msg.reply_to, formataddr((self.user_employee.name, self.user_employee.email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
# no alias catchall, no alias -> author
self.env['ir.config_parameter'].set_param('mail.catchall.domain', self.alias_domain)
self.env['ir.config_parameter'].search([('key', '=', 'mail.catchall.alias')]).unlink()
msg = self.Message.create({})
self.assertIn('-private', msg.message_id.split('@')[0], 'mail_message: message_id for a void message should be a "private" one')
self.assertEqual(msg.reply_to, formataddr((self.user_employee.name, self.user_employee.email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
@mute_logger('odoo.models.unlink')
def test_mail_message_values_fromto_document_alias(self):
msg = self.Message.create({
'model': 'mail.test.container',
'res_id': self.alias_record.id
})
self.assertIn('-openerp-%d-mail.test' % self.alias_record.id, msg.message_id.split('@')[0])
reply_to_name = '%s %s' % (self.env.user.company_id.name, self.alias_record.name)
reply_to_email = '%s@%s' % (self.alias_record.alias_name, self.alias_domain)
self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
# no alias domain -> author
self.env['ir.config_parameter'].search([('key', '=', 'mail.catchall.domain')]).unlink()
msg = self.Message.create({
'model': 'mail.test.container',
'res_id': self.alias_record.id
})
self.assertIn('-openerp-%d-mail.test' % self.alias_record.id, msg.message_id.split('@')[0])
self.assertEqual(msg.reply_to, formataddr((self.user_employee.name, self.user_employee.email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
# no catchall -> don't care, alias
self.env['ir.config_parameter'].set_param('mail.catchall.domain', self.alias_domain)
self.env['ir.config_parameter'].search([('key', '=', 'mail.catchall.alias')]).unlink()
msg = self.Message.create({
'model': 'mail.test.container',
'res_id': self.alias_record.id
})
self.assertIn('-openerp-%d-mail.test' % self.alias_record.id, msg.message_id.split('@')[0])
reply_to_name = '%s %s' % (self.env.company.name, self.alias_record.name)
reply_to_email = '%s@%s' % (self.alias_record.alias_name, self.alias_domain)
self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
@mute_logger('odoo.models.unlink')
def test_mail_message_values_fromto_document_no_alias(self):
test_record = self.env['mail.test.simple'].create({'name': 'Test', 'email_from': 'ignasse@example.com'})
msg = self.Message.create({
'model': 'mail.test.simple',
'res_id': test_record.id
})
self.assertIn('-openerp-%d-mail.test.simple' % test_record.id, msg.message_id.split('@')[0])
reply_to_name = '%s %s' % (self.env.user.company_id.name, test_record.name)
reply_to_email = '%s@%s' % (self.alias_catchall, self.alias_domain)
self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
@mute_logger('odoo.models.unlink')
def test_mail_message_values_fromto_document_manual_alias(self):
test_record = self.env['mail.test.simple'].create({'name': 'Test', 'email_from': 'ignasse@example.com'})
alias = self.env['mail.alias'].create({
'alias_name': 'MegaLias',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.simple').id,
'alias_parent_model_id': self.env['ir.model']._get('mail.test.simple').id,
'alias_parent_thread_id': test_record.id,
})
msg = self.Message.create({
'model': 'mail.test.simple',
'res_id': test_record.id
})
self.assertIn('-openerp-%d-mail.test.simple' % test_record.id, msg.message_id.split('@')[0])
reply_to_name = '%s %s' % (self.env.user.company_id.name, test_record.name)
reply_to_email = '%s@%s' % (alias.alias_name, self.alias_domain)
self.assertEqual(msg.reply_to, formataddr((reply_to_name, reply_to_email)))
self.assertEqual(msg.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
def test_mail_message_values_fromto_reply_to_force_new(self):
msg = self.Message.create({
'model': 'mail.test.container',
'res_id': self.alias_record.id,
'reply_to_force_new': True,
})
self.assertIn('reply_to', msg.message_id.split('@')[0])
self.assertNotIn('mail.test.container', msg.message_id.split('@')[0])
self.assertNotIn('-%d-' % self.alias_record.id, msg.message_id.split('@')[0])
@tagged('mail_message')
class TestMessageAccess(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestMessageAccess, cls).setUpClass()
cls.user_public = mail_new_test_user(cls.env, login='bert', groups='base.group_public', name='Bert Tartignole')
cls.user_portal = mail_new_test_user(cls.env, login='chell', groups='base.group_portal', name='Chell Gladys')
Channel = cls.env['mail.channel'].with_context(cls._test_context)
# Pigs: base group for tests
cls.group_pigs = 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 gtroup
cls.group_private = Channel.create({
'name': 'Private',
'public': 'private'})
cls.message = cls.env['mail.message'].create({
'body': 'My Body',
'model': 'mail.channel',
'res_id': cls.group_private.id,
})
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_message_access_search(self):
# Data: various author_ids, partner_ids, documents
msg1 = self.env['mail.message'].create({
'subject': '_ZTest', 'body': 'A', 'subtype_id': self.ref('mail.mt_comment')})
msg2 = self.env['mail.message'].create({
'subject': '_ZTest', 'body': 'A+B', 'subtype_id': self.ref('mail.mt_comment'),
'partner_ids': [(6, 0, [self.user_public.partner_id.id])]})
msg3 = self.env['mail.message'].create({
'subject': '_ZTest', 'body': 'A Pigs', 'subtype_id': False,
'model': 'mail.channel', 'res_id': self.group_pigs.id})
msg4 = self.env['mail.message'].create({
'subject': '_ZTest', 'body': 'A+P Pigs', 'subtype_id': self.ref('mail.mt_comment'),
'model': 'mail.channel', 'res_id': self.group_pigs.id,
'partner_ids': [(6, 0, [self.user_public.partner_id.id])]})
msg5 = self.env['mail.message'].create({
'subject': '_ZTest', 'body': 'A+E Pigs', 'subtype_id': self.ref('mail.mt_comment'),
'model': 'mail.channel', 'res_id': self.group_pigs.id,
'partner_ids': [(6, 0, [self.user_employee.partner_id.id])]})
msg6 = self.env['mail.message'].create({
'subject': '_ZTest', 'body': 'A Birds', 'subtype_id': self.ref('mail.mt_comment'),
'model': 'mail.channel', 'res_id': self.group_private.id})
msg7 = self.env['mail.message'].with_user(self.user_employee).create({
'subject': '_ZTest', 'body': 'B', 'subtype_id': self.ref('mail.mt_comment')})
msg8 = self.env['mail.message'].with_user(self.user_employee).create({
'subject': '_ZTest', 'body': 'B+E', 'subtype_id': self.ref('mail.mt_comment'),
'partner_ids': [(6, 0, [self.user_employee.partner_id.id])]})
# Test: Public: 2 messages (recipient)
messages = self.env['mail.message'].with_user(self.user_public).search([('subject', 'like', '_ZTest')])
self.assertEqual(messages, msg2 | msg4)
# Test: Employee: 3 messages on Pigs Raoul can read (employee can read group with default values)
messages = self.env['mail.message'].with_user(self.user_employee).search([('subject', 'like', '_ZTest'), ('body', 'ilike', 'A')])
self.assertEqual(messages, msg3 | msg4 | msg5)
# Test: Raoul: 3 messages on Pigs Raoul can read (employee can read group with default values), 0 on Birds (private group) + 2 messages as author
messages = self.env['mail.message'].with_user(self.user_employee).search([('subject', 'like', '_ZTest')])
self.assertEqual(messages, msg3 | msg4 | msg5 | msg7 | msg8)
# Test: Admin: all messages
messages = self.env['mail.message'].search([('subject', 'like', '_ZTest')])
self.assertEqual(messages, msg1 | msg2 | msg3 | msg4 | msg5 | msg6 | msg7 | msg8)
# Test: Portal: 0 (no access to groups, not recipient)
messages = self.env['mail.message'].with_user(self.user_portal).search([('subject', 'like', '_ZTest')])
self.assertFalse(messages)
# Test: Portal: 2 messages (public group with a subtype)
self.group_pigs.write({'public': 'public'})
messages = self.env['mail.message'].with_user(self.user_portal).search([('subject', 'like', '_ZTest')])
self.assertEqual(messages, msg4 | msg5)
# --------------------------------------------------
# READ
# --------------------------------------------------
@mute_logger('odoo.addons.base.models.ir_model', 'odoo.models')
def test_mail_message_access_read_crash(self):
with self.assertRaises(AccessError):
self.message.with_user(self.user_employee).read()
@mute_logger('odoo.models')
def test_mail_message_access_read_crash_portal(self):
with self.assertRaises(AccessError):
self.message.with_user(self.user_portal).read(['body', 'message_type', 'subtype_id'])
def test_mail_message_access_read_ok_portal(self):
self.message.write({'subtype_id': self.ref('mail.mt_comment'), 'res_id': self.group_public.id})
self.message.with_user(self.user_portal).read(['body', 'message_type', 'subtype_id'])
def test_mail_message_access_read_notification(self):
attachment = self.env['ir.attachment'].create({
'datas': base64.b64encode(b'My attachment'),
'name': 'doc.txt',
'res_model': self.message._name,
'res_id': self.message.id})
# attach the attachment to the message
self.message.write({'attachment_ids': [(4, attachment.id)]})
self.message.write({'partner_ids': [(4, self.user_employee.partner_id.id)]})
self.message.with_user(self.user_employee).read()
# Test: Bert has access to attachment, ok because he can read message
attachment.with_user(self.user_employee).read(['name', 'datas'])
def test_mail_message_access_read_author(self):
self.message.write({'author_id': self.user_employee.partner_id.id})
self.message.with_user(self.user_employee).read()
def test_mail_message_access_read_doc(self):
self.message.write({'model': 'mail.channel', 'res_id': self.group_public.id})
# Test: Bert reads the message, ok because linked to a doc he is allowed to read
self.message.with_user(self.user_employee).read()
# --------------------------------------------------
# CREATE
# --------------------------------------------------
@mute_logger('odoo.addons.base.models.ir_model')
def test_mail_message_access_create_crash_public(self):
# Do: Bert creates a message on Pigs -> ko, no creation rights
with self.assertRaises(AccessError):
self.env['mail.message'].with_user(self.user_public).create({'model': 'mail.channel', 'res_id': self.group_pigs.id, 'body': 'Test'})
# Do: Bert create a message on Jobs -> ko, no creation rights
with self.assertRaises(AccessError):
self.env['mail.message'].with_user(self.user_public).create({'model': 'mail.channel', 'res_id': self.group_public.id, 'body': 'Test'})
@mute_logger('odoo.models')
def test_mail_message_access_create_crash(self):
# Do: Bert create a private message -> ko, no creation rights
with self.assertRaises(AccessError):
self.env['mail.message'].with_user(self.user_employee).create({'model': 'mail.channel', 'res_id': self.group_private.id, 'body': 'Test'})
@mute_logger('odoo.models')
def test_mail_message_access_create_doc(self):
Message = self.env['mail.message'].with_user(self.user_employee)
# Do: Raoul creates a message on Jobs -> ok, write access to the related document
Message.create({'model': 'mail.channel', 'res_id': self.group_public.id, 'body': 'Test'})
# Do: Raoul creates a message on Priv -> ko, no write access to the related document
with self.assertRaises(AccessError):
Message.create({'model': 'mail.channel', 'res_id': self.group_private.id, 'body': 'Test'})
def test_mail_message_access_create_private(self):
self.env['mail.message'].with_user(self.user_employee).create({'body': 'Test'})
def test_mail_message_access_create_reply(self):
# TDE FIXME: should it really work ? not sure - catchall makes crash (aka, post will crash also)
self.env['ir.config_parameter'].set_param('mail.catchall.domain', False)
self.message.write({'partner_ids': [(4, self.user_employee.partner_id.id)]})
self.env['mail.message'].with_user(self.user_employee).create({'model': 'mail.channel', 'res_id': self.group_private.id, 'body': 'Test', 'parent_id': self.message.id})
def test_mail_message_access_create_wo_parent_access(self):
""" Purpose is to test posting a message on a record whose first message / parent
is not accessible by current user. """
test_record = self.env['mail.test.simple'].with_context(self._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
partner_1 = self.env['res.partner'].create({
'name': 'Jitendra Prajapati (jpr-odoo)',
'email': 'jpr@odoo.com',
})
test_record.message_subscribe((partner_1 | self.user_admin.partner_id).ids)
message = test_record.message_post(
body='<p>This is First Message</p>', subject='Subject',
message_type='comment', subtype_xmlid='mail.mt_note')
# portal user have no rights to read the message
with self.assertRaises(AccessError):
message.with_user(self.user_portal).read(['subject, body'])
with patch.object(MailTestSimple, 'check_access_rights', return_value=True):
with self.assertRaises(AccessError):
message.with_user(self.user_portal).read(['subject, body'])
# parent message is accessible to references notification mail values
# for _notify method and portal user have no rights to send the message for this model
new_msg = test_record.with_user(self.user_portal).message_post(
body='<p>This is Second Message</p>',
subject='Subject',
parent_id=message.id,
message_type='comment',
subtype_xmlid='mail.mt_comment',
mail_auto_delete=False)
new_mail = self.env['mail.mail'].sudo().search([
('mail_message_id', '=', new_msg.id),
('references', '=', f'{message.message_id} {new_msg.message_id}'),
])
self.assertTrue(new_mail)
self.assertEqual(new_msg.parent_id, message)
| 52.007648
| 27,200
|
2,140
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.base.tests.test_ir_actions import TestServerActionsBase
from odoo.addons.test_mail.tests.common import TestMailCommon
class TestServerActionsEmail(TestMailCommon, TestServerActionsBase):
def test_action_email(self):
email_template = self._create_template('res.partner', {'partner_to': '%s' % self.test_partner.id})
self.action.write({'state': 'email', 'template_id': email_template.id})
self.action.with_context(self.context).run()
# check an email is waiting for sending
mail = self.env['mail.mail'].sudo().search([('subject', '=', 'About TestingPartner')])
self.assertEqual(len(mail), 1)
# check email content
self.assertEqual(mail.body, '<p>Hello TestingPartner</p>')
def test_action_followers(self):
self.test_partner.message_unsubscribe(self.test_partner.message_partner_ids.ids)
random_partner = self.env['res.partner'].create({'name': 'Thierry Wololo'})
self.action.write({
'state': 'followers',
'partner_ids': [(4, self.env.ref('base.partner_admin').id), (4, random_partner.id)],
})
self.action.with_context(self.context).run()
self.assertEqual(self.test_partner.message_partner_ids, self.env.ref('base.partner_admin') | random_partner)
def test_action_next_activity(self):
self.action.write({
'state': 'next_activity',
'activity_user_type': 'specific',
'activity_type_id': self.env.ref('mail.mail_activity_data_meeting').id,
'activity_summary': 'TestNew',
})
before_count = self.env['mail.activity'].search_count([])
run_res = self.action.with_context(self.context).run()
self.assertFalse(run_res, 'ir_actions_server: create next activity action correctly finished should return False')
self.assertEqual(self.env['mail.activity'].search_count([]), before_count + 1)
self.assertEqual(self.env['mail.activity'].search_count([('summary', '=', 'TestNew')]), 1)
| 52.195122
| 2,140
|
2,397
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_mail.tests.test_mail_template import TestMailTemplate
from odoo.tests import tagged, users
from odoo.tests.common import Form
@tagged('mail_template')
class TestMailTemplateTools(TestMailTemplate):
@classmethod
def setUpClass(cls):
super(TestMailTemplateTools, cls).setUpClass()
cls.test_template_preview = cls.env['mail.template.preview'].create({
'mail_template_id': cls.test_template.id,
})
def test_initial_values(self):
self.assertTrue(self.test_template.email_to)
self.assertTrue(self.test_template.email_cc)
self.assertEqual(len(self.test_template.partner_to.split(',')), 2)
self.assertTrue(self.test_record.email_from)
def test_mail_template_preview_force_lang(self):
test_record = self.env['mail.test.lang'].browse(self.test_record.ids)
test_record.write({
'lang': 'es_ES',
})
test_template = self.env['mail.template'].browse(self.test_template.ids)
preview = self.env['mail.template.preview'].create({
'mail_template_id': test_template.id,
'resource_ref': test_record,
'lang': 'es_ES',
})
self.assertEqual(preview.body_html, '<p>Spanish Body for %s</p>' % test_record.name)
preview.write({'lang': 'en_US'})
self.assertEqual(preview.body_html, '<p>English Body for %s</p>' % test_record.name)
@users('employee')
def test_mail_template_preview_recipients(self):
form = Form(self.test_template_preview)
form.resource_ref = self.test_record
self.assertEqual(form.email_to, self.test_template.email_to)
self.assertEqual(form.email_cc, self.test_template.email_cc)
self.assertEqual(set(record.id for record in form.partner_ids),
{int(pid) for pid in self.test_template.partner_to.split(',') if pid})
@users('employee')
def test_mail_template_preview_recipients_use_default_to(self):
self.test_template.use_default_to = True
form = Form(self.test_template_preview)
form.resource_ref = self.test_record
self.assertEqual(form.email_to, self.test_record.email_from)
self.assertFalse(form.email_cc)
self.assertFalse(form.partner_ids)
| 41.327586
| 2,397
|
9,582
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.tests import tagged
from odoo.tools import mute_logger
@tagged('mail_template')
class TestMailTemplate(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestMailTemplate, cls).setUpClass()
cls.test_record = cls.env['mail.test.lang'].with_context(cls._test_context).create({
'email_from': 'ignasse@example.com',
'name': 'Test',
})
cls.user_employee.write({
'groups_id': [(4, cls.env.ref('base.group_partner_manager').id)],
})
cls._attachments = [{
'name': 'first.txt',
'datas': base64.b64encode(b'My first attachment'),
'res_model': 'res.partner',
'res_id': cls.user_admin.partner_id.id
}, {
'name': 'second.txt',
'datas': base64.b64encode(b'My second attachment'),
'res_model': 'res.partner',
'res_id': cls.user_admin.partner_id.id
}]
cls.email_1 = 'test1@example.com'
cls.email_2 = 'test2@example.com'
cls.email_3 = cls.partner_1.email
# activate translations
cls.env['res.lang']._activate_lang('es_ES')
cls.env.ref('base.module_base')._update_translations(['es_ES'])
# create a complete test template
cls.test_template = cls._create_template('mail.test.lang', {
'attachment_ids': [(0, 0, cls._attachments[0]), (0, 0, cls._attachments[1])],
'body_html': '<p>English Body for <t t-out="object.name"/></p>',
'lang': '{{ object.customer_id.lang or object.lang }}',
'email_to': '%s, %s' % (cls.email_1, cls.email_2),
'email_cc': '%s' % cls.email_3,
'partner_to': '%s,%s' % (cls.partner_2.id, cls.user_admin.partner_id.id),
'subject': 'English for {{ object.name }}',
})
# Make sure Spanish translations have not been altered
description_translations = cls.env['ir.translation'].search([
('module', '=', 'test_mail'),
('src', '=', cls.test_record._description),
('lang', '=', 'es_ES')
])
if description_translations:
description_translations.update({'value': 'Spanish description'})
else:
description_translations.create({
'type': 'model',
'name': 'ir.model,name',
'module': 'test_mail',
'lang': 'es_ES',
'res_id': cls.env['ir.model']._get_id('mail.test.lang'),
'src': cls.test_record._description,
'value': 'Spanish description',
'state': 'translated',
})
cls.env['ir.translation'].create({
'type': 'model',
'name': 'mail.template,subject',
'module': 'mail',
'lang': 'es_ES',
'res_id': cls.test_template.id,
'value': 'Spanish for {{ object.name }}',
'state': 'translated',
})
cls.env['ir.translation'].create({
'type': 'model',
'name': 'mail.template,body_html',
'module': 'mail',
'lang': 'es_ES',
'res_id': cls.test_template.id,
'value': '<p>Spanish Body for <t t-out="object.name" /></p>',
'state': 'translated',
})
view = cls.env['ir.ui.view'].create({
'name': 'test_layout',
'key': 'test_layout',
'type': 'qweb',
'arch_db': '<body><t t-out="message.body"/> English Layout <t t-esc="model_description"/></body>'
})
cls.env['ir.model.data'].create({
'name': 'test_layout',
'module': 'test_mail',
'model': 'ir.ui.view',
'res_id': view.id
})
cls.env['ir.translation'].create({
'type': 'model_terms',
'name': 'ir.ui.view,arch_db',
'module': 'test_mail',
'lang': 'es_ES',
'res_id': view.id,
'src': 'English Layout',
'value': 'Spanish Layout',
'state': 'translated',
})
# admin should receive emails
cls.user_admin.write({'notification_type': 'email'})
# Force the attachments of the template to be in the natural order.
cls.test_template.invalidate_cache(['attachment_ids'], ids=cls.test_template.ids)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_template_send_email(self):
mail_id = self.test_template.send_mail(self.test_record.id)
mail = self.env['mail.mail'].sudo().browse(mail_id)
self.assertEqual(mail.email_cc, self.test_template.email_cc)
self.assertEqual(mail.email_to, self.test_template.email_to)
self.assertEqual(mail.recipient_ids, self.partner_2 | self.user_admin.partner_id)
self.assertEqual(mail.subject, 'English for %s' % self.test_record.name)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_template_translation_lang(self):
test_record = self.env['mail.test.lang'].browse(self.test_record.ids)
test_record.write({
'lang': 'es_ES',
})
test_template = self.env['mail.template'].browse(self.test_template.ids)
mail_id = test_template.send_mail(test_record.id, notif_layout='test_mail.test_layout')
mail = self.env['mail.mail'].sudo().browse(mail_id)
self.assertEqual(mail.body_html,
'<body><p>Spanish Body for %s</p> Spanish Layout Spanish description</body>' % self.test_record.name)
self.assertEqual(mail.subject, 'Spanish for %s' % self.test_record.name)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_template_translation_partner_lang(self):
test_record = self.env['mail.test.lang'].browse(self.test_record.ids)
customer = self.env['res.partner'].create({
'email': 'robert.carlos@test.example.com',
'lang': 'es_ES',
'name': 'Roberto Carlos',
})
test_record.write({
'customer_id': customer.id,
})
test_template = self.env['mail.template'].browse(self.test_template.ids)
mail_id = test_template.send_mail(test_record.id, notif_layout='test_mail.test_layout')
mail = self.env['mail.mail'].sudo().browse(mail_id)
self.assertEqual(mail.body_html,
'<body><p>Spanish Body for %s</p> Spanish Layout Spanish description</body>' % self.test_record.name)
self.assertEqual(mail.subject, 'Spanish for %s' % self.test_record.name)
def test_template_add_context_action(self):
self.test_template.create_action()
# check template act_window has been updated
self.assertTrue(bool(self.test_template.ref_ir_act_window))
# check those records
action = self.test_template.ref_ir_act_window
self.assertEqual(action.name, 'Send Mail (%s)' % self.test_template.name)
self.assertEqual(action.binding_model_id.model, 'mail.test.lang')
# def test_template_scheduled_date(self):
# from unittest.mock import patch
# self.email_template_in_2_days = self.email_template.copy()
# with patch('odoo.addons.mail.tests.test_mail_template.datetime', wraps=datetime) as mock_datetime:
# mock_datetime.now.return_value = datetime(2017, 11, 15, 11, 30, 28)
# mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
# self.email_template_in_2_days.write({
# 'scheduled_date': "{{ (datetime.datetime.now() + relativedelta(days=2)).strftime('%s') }}" % DEFAULT_SERVER_DATETIME_FORMAT,
# })
# mail_now_id = self.email_template.send_mail(self.test_record.id)
# mail_in_2_days_id = self.email_template_in_2_days.send_mail(self.test_record.id)
# mail_now = self.env['mail.mail'].browse(mail_now_id)
# mail_in_2_days = self.env['mail.mail'].browse(mail_in_2_days_id)
# # mail preparation
# self.assertEqual(mail_now.exists() | mail_in_2_days.exists(), mail_now | mail_in_2_days)
# self.assertEqual(bool(mail_now.scheduled_date), False)
# self.assertEqual(mail_now.state, 'outgoing')
# self.assertEqual(mail_in_2_days.state, 'outgoing')
# scheduled_date = datetime.strptime(mail_in_2_days.scheduled_date, DEFAULT_SERVER_DATETIME_FORMAT)
# date_in_2_days = datetime.now() + timedelta(days = 2)
# self.assertEqual(scheduled_date, date_in_2_days)
# # self.assertEqual(scheduled_date.month, date_in_2_days.month)
# # self.assertEqual(scheduled_date.year, date_in_2_days.year)
# # Launch the scheduler on the first mail, it should be reported in self.mails
# # and the mail_mail is now deleted
# self.env['mail.mail'].process_email_queue()
# self.assertEqual(mail_now.exists() | mail_in_2_days.exists(), mail_in_2_days)
# # Launch the scheduler on the first mail, it's still in 'outgoing' state
# self.env['mail.mail'].process_email_queue(ids=[mail_in_2_days.id])
# self.assertEqual(mail_in_2_days.state, 'outgoing')
# self.assertEqual(mail_now.exists() | mail_in_2_days.exists(), mail_in_2_days)
| 44.775701
| 9,582
|
7,470
|
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.test_mail.tests.common import TestMailCommon
from odoo.tests import tagged
from odoo.tools import mute_logger
@tagged('mail_wizards')
class TestMailResend(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestMailResend, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
#Two users
cls.user1 = mail_new_test_user(cls.env, login='e1', groups='base.group_public', name='Employee 1', notification_type='email', email='e1') # invalid email
cls.user2 = mail_new_test_user(cls.env, login='e2', groups='base.group_portal', name='Employee 2', notification_type='email', email='e2@example.com')
#Two partner
cls.partner1 = cls.env['res.partner'].with_context(cls._test_context).create({
'name': 'Partner 1',
'email': 'p1' # invalid email
})
cls.partner2 = cls.env['res.partner'].with_context(cls._test_context).create({
'name': 'Partner 2',
'email': 'p2@example.com'
})
cls.partners = cls.env['res.partner'].concat(cls.user1.partner_id, cls.user2.partner_id, cls.partner1, cls.partner2)
cls.invalid_email_partners = cls.env['res.partner'].concat(cls.user1.partner_id, cls.partner1)
# @mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_resend_workflow(self):
with self.assertSinglePostNotifications(
[{'partner': partner, 'type': 'email', 'status': 'exception'} for partner in self.partners],
message_info={'message_type': 'notification'},
sim_error='connect_failure'):
message = self.test_record.with_user(self.user_admin).message_post(partner_ids=self.partners.ids, subtype_xmlid='mail.mt_comment', message_type='notification')
wizard = self.env['mail.resend.message'].with_context({'mail_message_to_resend': message.id}).create({})
self.assertEqual(wizard.notification_ids.mapped('res_partner_id'), self.partners, "wizard should manage notifications for each failed partner")
# three more failure sent on bus, one for each mail in failure and one for resend
self._reset_bus()
expected_bus_notifications = [
(self.cr.dbname, 'res.partner', self.partner_admin.id),
(self.cr.dbname, 'res.partner', self.env.user.partner_id.id),
]
with self.mock_mail_gateway(), self.assertBus(expected_bus_notifications * 3):
wizard.resend_mail_action()
done_msgs, done_notifs = self.assertMailNotifications(message, [
{'content': '', 'message_type': 'notification',
'notif': [{'partner': partner, 'type': 'email', 'status': 'exception' if partner in self.user1.partner_id | self.partner1 else 'sent'} for partner in self.partners]}]
)
self.assertEqual(wizard.notification_ids, done_notifs)
self.assertEqual(done_msgs, message)
self.user1.write({"email": 'u1@example.com'})
# two more failure update sent on bus, one for failed mail and one for resend
self._reset_bus()
with self.mock_mail_gateway(), self.assertBus(expected_bus_notifications * 2):
self.env['mail.resend.message'].with_context({'mail_message_to_resend': message.id}).create({}).resend_mail_action()
done_msgs, done_notifs = self.assertMailNotifications(message, [
{'content': '', 'message_type': 'notification',
'notif': [{'partner': partner, 'type': 'email', 'status': 'exception' if partner == self.partner1 else 'sent', 'check_send': partner == self.partner1} for partner in self.partners]}]
)
self.assertEqual(wizard.notification_ids, done_notifs)
self.assertEqual(done_msgs, message)
self.partner1.write({"email": 'p1@example.com'})
# A success update should be sent on bus once the email has no more failure
self._reset_bus()
with self.mock_mail_gateway(), self.assertBus(expected_bus_notifications):
self.env['mail.resend.message'].with_context({'mail_message_to_resend': message.id}).create({}).resend_mail_action()
self.assertMailNotifications(message, [
{'content': '', 'message_type': 'notification',
'notif': [{'partner': partner, 'type': 'email', 'status': 'sent', 'check_send': partner == self.partner1} for partner in self.partners]}]
)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_remove_mail_become_canceled(self):
# two failure sent on bus, one for each mail
self._reset_bus()
with self.mock_mail_gateway(), self.assertBus([(self.cr.dbname, 'res.partner', self.partner_admin.id)] * 2):
message = self.test_record.with_user(self.user_admin).message_post(partner_ids=self.partners.ids, subtype_xmlid='mail.mt_comment', message_type='notification')
self.assertMailNotifications(message, [
{'content': '', 'message_type': 'notification',
'notif': [{'partner': partner, 'type': 'email', 'status': 'exception' if partner in self.user1.partner_id | self.partner1 else 'sent'} for partner in self.partners]}]
)
wizard = self.env['mail.resend.message'].with_context({'mail_message_to_resend': message.id}).create({})
partners = wizard.partner_ids.mapped("partner_id")
self.assertEqual(self.invalid_email_partners, partners)
wizard.partner_ids.filtered(lambda p: p.partner_id == self.partner1).write({"resend": False})
wizard.resend_mail_action()
self.assertMailNotifications(message, [
{'content': '', 'message_type': 'notification',
'notif': [{'partner': partner, 'type': 'email',
'status': (partner == self.user1.partner_id and 'exception') or (partner == self.partner1 and 'canceled') or 'sent'} for partner in self.partners]}]
)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_cancel_all(self):
self._reset_bus()
with self.mock_mail_gateway(), self.assertBus([(self.cr.dbname, 'res.partner', self.partner_admin.id)] * 2):
message = self.test_record.with_user(self.user_admin).message_post(partner_ids=self.partners.ids, subtype_xmlid='mail.mt_comment', message_type='notification')
wizard = self.env['mail.resend.message'].with_context({'mail_message_to_resend': message.id}).create({})
# one update for cancell
self._reset_bus()
expected_bus_notifications = [
(self.cr.dbname, 'res.partner', self.partner_admin.id),
(self.cr.dbname, 'res.partner', self.env.user.partner_id.id),
]
with self.mock_mail_gateway(), self.assertBus(expected_bus_notifications):
wizard.cancel_mail_action()
self.assertMailNotifications(message, [
{'content': '', 'message_type': 'notification',
'notif': [{'partner': partner, 'type': 'email',
'check_send': partner in self.user1.partner_id | self.partner1,
'status': 'canceled' if partner in self.user1.partner_id | self.partner1 else 'sent'} for partner in self.partners]}]
)
| 58.359375
| 7,470
|
11,708
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import psycopg2
import pytz
from datetime import datetime, timedelta
from freezegun import freeze_time
from unittest.mock import call
from odoo import api, tools
from odoo.addons.base.tests.common import MockSmtplibCase
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.tests import common, tagged
from odoo.tools import mute_logger, DEFAULT_SERVER_DATETIME_FORMAT
@tagged('mail_mail')
class TestMailMail(TestMailCommon, MockSmtplibCase):
@classmethod
def setUpClass(cls):
super(TestMailMail, cls).setUpClass()
cls._init_mail_gateway()
cls._init_mail_servers()
cls.server_domain_2 = cls.env['ir.mail_server'].create({
'name': 'Server 2',
'smtp_host': 'test_2.com',
'from_filter': 'test_2.com',
})
cls.test_record = cls.env['mail.test.gateway'].with_context(cls._test_context).create({
'name': 'Test',
'email_from': 'ignasse@example.com',
}).with_context({})
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_message_notify_from_mail_mail(self):
# Due ot post-commit hooks, store send emails in every step
mail = self.env['mail.mail'].sudo().create({
'body_html': '<p>Test</p>',
'email_to': 'test@example.com',
'partner_ids': [(4, self.user_employee.partner_id.id)]
})
with self.mock_mail_gateway():
mail.send()
self.assertSentEmail(mail.env.user.partner_id, ['test@example.com'])
self.assertEqual(len(self._mails), 1)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_mail_return_path(self):
# mail without thread-enabled record
base_values = {
'body_html': '<p>Test</p>',
'email_to': 'test@example.com',
}
mail = self.env['mail.mail'].create(base_values)
with self.mock_mail_gateway():
mail.send()
self.assertEqual(self._mails[0]['headers']['Return-Path'], '%s@%s' % (self.alias_bounce, self.alias_domain))
# mail on thread-enabled record
mail = self.env['mail.mail'].create(dict(base_values, **{
'model': self.test_record._name,
'res_id': self.test_record.id,
}))
with self.mock_mail_gateway():
mail.send()
self.assertEqual(self._mails[0]['headers']['Return-Path'], '%s@%s' % (self.alias_bounce, self.alias_domain))
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.tests')
def test_mail_mail_schedule(self):
"""Test that a mail scheduled in the past/future are sent or not"""
now = datetime(2022, 6, 28, 14, 0, 0)
scheduled_datetimes = [
# falsy values
False, '', 'This is not a date format',
# datetimes (UTC/GMT +10 hours for Australia/Brisbane)
now, pytz.timezone('Australia/Brisbane').localize(now),
# string
(now - timedelta(days=1)).strftime(DEFAULT_SERVER_DATETIME_FORMAT),
(now + timedelta(days=1)).strftime(DEFAULT_SERVER_DATETIME_FORMAT),
(now + timedelta(days=1)).strftime("%H:%M:%S %d-%m-%Y"),
# tz: is actually 1 hour before now in UTC
(now + timedelta(hours=3)).strftime("%H:%M:%S %d-%m-%Y") + " +0400",
# tz: is actually 1 hour after now in UTC
(now + timedelta(hours=-3)).strftime("%H:%M:%S %d-%m-%Y") + " -0400",
]
expected_datetimes = [
False, '', False,
now, now - pytz.timezone('Australia/Brisbane').utcoffset(now),
now - timedelta(days=1), now + timedelta(days=1), now + timedelta(days=1),
now + timedelta(hours=-1),
now + timedelta(hours=1),
]
expected_states = [
# falsy values = send now
'sent', 'sent', 'sent',
'sent', 'sent',
'sent', 'outgoing', 'outgoing',
'sent', 'outgoing'
]
mails = self.env['mail.mail'].create([
{'body_html': '<p>Test</p>',
'email_to': 'test@example.com',
'scheduled_date': scheduled_datetime,
} for scheduled_datetime in scheduled_datetimes
])
for mail, expected_datetime, scheduled_datetime in zip(mails, expected_datetimes, scheduled_datetimes):
expected = expected_datetime.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT) if expected_datetime else expected_datetime
self.assertEqual(mail.scheduled_date, expected,
'Scheduled date: %s should be stored as %s, received %s' % (scheduled_datetime, expected, mail.scheduled_date))
self.assertEqual(mail.state, 'outgoing')
with freeze_time(now):
self.env['mail.mail'].process_email_queue()
for mail, expected_state in zip(mails, expected_states):
self.assertEqual(mail.state, expected_state)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_mail_send_server(self):
"""Test that the mails are send in batch.
Batch are defined by the mail server and the email from field.
"""
self.assertEqual(self.env['ir.mail_server']._get_default_from_address(), 'notifications@test.com')
mail_values = {
'body_html': '<p>Test</p>',
'email_to': 'user@example.com',
}
# Should be encapsulated in the notification email
mails = self.env['mail.mail'].create([{
**mail_values,
'email_from': 'test@unknown_domain.com',
} for _ in range(5)]) | self.env['mail.mail'].create([{
**mail_values,
'email_from': 'test_2@unknown_domain.com',
} for _ in range(5)])
# Should use the test_2 mail server
# Once with "user_1@test_2.com" as login
# Once with "user_2@test_2.com" as login
mails |= self.env['mail.mail'].create([{
**mail_values,
'email_from': 'user_1@test_2.com',
} for _ in range(5)]) | self.env['mail.mail'].create([{
**mail_values,
'email_from': 'user_2@test_2.com',
} for _ in range(5)])
# Mail server is forced
mails |= self.env['mail.mail'].create([{
**mail_values,
'email_from': 'user_1@test_2.com',
'mail_server_id': self.server_domain.id,
} for _ in range(5)])
with self.mock_smtplib_connection():
mails.send()
self.assertEqual(self.find_mail_server_mocked.call_count, 4, 'Must be called only once per "mail from" when the mail server is not forced')
self.assertEqual(len(self.emails), 25)
# Check call to the connect method to ensure that we authenticate
# to the right mail server with the right login
self.assertEqual(self.connect_mocked.call_count, 4, 'Must be called once per batch which share the same mail server and the same smtp from')
self.connect_mocked.assert_has_calls(
calls=[
call(smtp_from='notifications@test.com', mail_server_id=self.server_notification.id),
call(smtp_from='user_1@test_2.com', mail_server_id=self.server_domain_2.id),
call(smtp_from='user_2@test_2.com', mail_server_id=self.server_domain_2.id),
call(smtp_from='user_1@test_2.com', mail_server_id=self.server_domain.id),
],
any_order=True,
)
self.assert_email_sent_smtp(message_from='"test" <notifications@test.com>',
emails_count=5, from_filter=self.server_notification.from_filter)
self.assert_email_sent_smtp(message_from='"test_2" <notifications@test.com>',
emails_count=5, from_filter=self.server_notification.from_filter)
self.assert_email_sent_smtp(message_from='user_1@test_2.com', emails_count=5, from_filter=self.server_domain_2.from_filter)
self.assert_email_sent_smtp(message_from='user_2@test_2.com', emails_count=5, from_filter=self.server_domain_2.from_filter)
self.assert_email_sent_smtp(message_from='user_1@test_2.com', emails_count=5, from_filter=self.server_domain.from_filter)
class TestMailMailRace(common.TransactionCase):
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_bounce_during_send(self):
self.partner = self.env['res.partner'].create({
'name': 'Ernest Partner',
})
# we need to simulate a mail sent by the cron task, first create mail, message and notification by hand
mail = self.env['mail.mail'].sudo().create({
'body_html': '<p>Test</p>',
'is_notification': True,
'state': 'outgoing',
'recipient_ids': [(4, self.partner.id)]
})
mail_message = mail.mail_message_id
message = self.env['mail.message'].create({
'subject': 'S',
'body': 'B',
'subtype_id': self.ref('mail.mt_comment'),
'notification_ids': [(0, 0, {
'res_partner_id': self.partner.id,
'mail_mail_id': mail.id,
'notification_type': 'email',
'is_read': True,
'notification_status': 'ready',
})],
})
notif = self.env['mail.notification'].search([('res_partner_id', '=', self.partner.id)])
# we need to commit transaction or cr will keep the lock on notif
self.cr.commit()
# patch send_email in order to create a concurent update and check the notif is already locked by _send()
this = self # coding in javascript ruinned my life
bounce_deferred = []
@api.model
def send_email(self, message, *args, **kwargs):
with this.registry.cursor() as cr, mute_logger('odoo.sql_db'):
try:
# try ro aquire lock (no wait) on notification (should fail)
cr.execute("SELECT notification_status FROM mail_notification WHERE id = %s FOR UPDATE NOWAIT", [notif.id])
except psycopg2.OperationalError:
# record already locked by send, all good
bounce_deferred.append(True)
else:
# this should trigger psycopg2.extensions.TransactionRollbackError in send().
# Only here to simulate the initial use case
# If the record is lock, this line would create a deadlock since we are in the same thread
# In practice, the update will wait the end of the send() transaction and set the notif as bounce, as expeced
cr.execute("UPDATE mail_notification SET notification_status='bounce' WHERE id = %s", [notif.id])
return message['Message-Id']
self.env['ir.mail_server']._patch_method('send_email', send_email)
mail.send()
self.assertTrue(bounce_deferred, "The bounce should have been deferred")
self.assertEqual(notif.notification_status, 'sent')
# some cleaning since we commited the cr
self.env['ir.mail_server']._revert_method('send_email')
notif.unlink()
mail.unlink()
(mail_message | message).unlink()
self.partner.unlink()
self.env.cr.commit()
# because we committed the cursor, the savepoint of the test method is
# gone, and this would break TransactionCase cleanups
self.cr.execute('SAVEPOINT test_%d' % self._savepoint_id)
| 44.858238
| 11,708
|
738
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
from odoo import Command
@odoo.tests.tagged('post_install', '-at_install')
class TestUi(odoo.tests.HttpCase):
def test_01_mail_tour(self):
self.start_tour("/web", 'mail_tour', login="admin")
def test_02_mail_create_channel_no_mail_tour(self):
self.env['res.users'].create({
'email': '', # User should be able to create a channel even if no email is defined
'groups_id': [Command.set([self.ref('base.group_user')])],
'name': 'Test User',
'login': 'testuser',
'password': 'testuser',
})
self.start_tour("/web", 'mail_tour', login='testuser')
| 35.142857
| 738
|
87,629
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import socket
from unittest.mock import DEFAULT
from unittest.mock import patch
from odoo import exceptions
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.test_mail.data import test_mail_data
from odoo.addons.test_mail.data.test_mail_data import MAIL_TEMPLATE
from odoo.addons.test_mail.models.test_mail_models import MailTestGateway
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.tools import email_split_and_format, formataddr, mute_logger
@tagged('mail_gateway')
class TestEmailParsing(TestMailCommon):
def test_message_parse_and_replace_binary_octetstream(self):
""" Incoming email containing a wrong Content-Type as described in RFC2046/section-3 """
received_mail = self.from_string(test_mail_data.MAIL_MULTIPART_BINARY_OCTET_STREAM)
with self.assertLogs('odoo.addons.mail.models.mail_thread', level="WARNING") as capture:
extracted_mail = self.env['mail.thread']._message_parse_extract_payload(received_mail)
self.assertEqual(len(extracted_mail['attachments']), 1)
attachment = extracted_mail['attachments'][0]
self.assertEqual(attachment.fname, 'hello_world.dat')
self.assertEqual(attachment.content, b'Hello world\n')
self.assertEqual(capture.output, [
("WARNING:odoo.addons.mail.models.mail_thread:Message containing an unexpected "
"Content-Type 'binary/octet-stream', assuming 'application/octet-stream'"),
])
def test_message_parse_body(self):
# test pure plaintext
plaintext = self.format(test_mail_data.MAIL_TEMPLATE_PLAINTEXT, email_from='"Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>')
res = self.env['mail.thread'].message_parse(self.from_string(plaintext))
self.assertIn('Please call me as soon as possible this afternoon!', res['body'])
# test multipart / text and html -> html has priority
multipart = self.format(MAIL_TEMPLATE, email_from='"Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>')
res = self.env['mail.thread'].message_parse(self.from_string(multipart))
self.assertIn('<p>Please call me as soon as possible this afternoon!</p>', res['body'])
# test multipart / mixed
res = self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_MULTIPART_MIXED))
self.assertNotIn(
'Should create a multipart/mixed: from gmail, *bold*, with attachment', res['body'],
'message_parse: text version should not be in body after parsing multipart/mixed')
self.assertIn(
'<div dir="ltr">Should create a multipart/mixed: from gmail, <b>bold</b>, with attachment.<br clear="all"><div><br></div>', res['body'],
'message_parse: html version should be in body after parsing multipart/mixed')
res = self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_MULTIPART_MIXED_TWO))
self.assertNotIn('First and second part', res['body'],
'message_parse: text version should not be in body after parsing multipart/mixed')
self.assertIn('First part', res['body'],
'message_parse: first part of the html version should be in body after parsing multipart/mixed')
self.assertIn('Second part', res['body'],
'message_parse: second part of the html version should be in body after parsing multipart/mixed')
res = self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_SINGLE_BINARY))
self.assertEqual(res['body'], '')
self.assertEqual(res['attachments'][0][0], 'thetruth.pdf')
res = self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_FORWARDED))
self.assertIn(res['recipients'], ['lucie@petitebedaine.fr,raoul@grosbedon.fr', 'raoul@grosbedon.fr,lucie@petitebedaine.fr'])
res = self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_MULTIPART_WEIRD_FILENAME))
self.assertEqual(res['attachments'][0][0], '62_@;,][)=.(ÇÀÉ.txt')
def test_message_parse_bugs(self):
""" Various corner cases or message parsing """
# message without Final-Recipient
self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_NO_FINAL_RECIPIENT))
# message with empty body (including only void characters)
res = self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_NO_BODY))
self.assertEqual(res['body'], '\n \n', 'Gateway should not crash with void content')
def test_message_parse_eml(self):
# Test that the parsing of mail with embedded emails as eml(msg) which generates empty attachments, can be processed.
mail = self.format(test_mail_data.MAIL_EML_ATTACHMENT, email_from='"Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>', to='generic@test.com')
self.env['mail.thread'].message_parse(self.from_string(mail))
def test_message_parse_eml_bounce_headers(self):
# Test Text/RFC822-Headers MIME content-type
msg_id = '<861878175823148.1577183525.736005783081055-openerp-19177-account.invoice@mycompany.example.com>'
mail = self.format(
test_mail_data.MAIL_EML_ATTACHMENT_BOUNCE_HEADERS,
email_from='MAILER-DAEMON@example.com (Mail Delivery System)',
to='test_bounce+82240-account.invoice-19177@mycompany.example.com',
# msg_id goes to the attachment's Message-Id header
msg_id=msg_id,
)
res = self.env['mail.thread'].message_parse(self.from_string(mail))
self.assertEqual(res['bounced_msg_id'], [msg_id], "Message-Id is not extracted from Text/RFC822-Headers attachment")
def test_message_parse_extract_bounce_rfc822_headers_qp(self):
# Incoming bounce for unexisting Outlook address
# bounce back sometimes with a Content-Type `text/rfc822-headers`
# and Content-Type-Encoding `quoted-printable`
partner = self.env['res.partner'].create({
'name':'Mitchelle Admine',
'email':'rdesfrdgtfdrfesd@outlook.com'
})
message = self.env['mail.message'].create({
'message_id' : '<368396033905967.1673346177.695352554321289-openerp-11-sale.order@eupp00>'
})
incoming_bounce = self.format(
test_mail_data.MAIL_BOUNCE_QP_RFC822_HEADERS,
email_from='MAILER-DAEMON@mailserver.odoo.com (Mail Delivery System)',
email_to='bounce@xxx.odoo.com',
delivered_to='bounce@xxx.odoo.com'
)
msg_dict = {}
msg = self.env['mail.thread']._message_parse_extract_bounce(self.from_string(incoming_bounce), msg_dict)
self.assertEqual(msg['bounced_email'], partner.email, "The sender email should be correctly parsed")
self.assertEqual(msg['bounced_partner'], partner, "A partner with this email should exist")
self.assertEqual(msg['bounced_msg_id'][0], message.message_id, "The sender message-id should correctly parsed")
self.assertEqual(msg['bounced_message'], message, "An existing message with this message_id should exist")
def test_message_parse_plaintext(self):
""" Incoming email in plaintext should be stored as html """
mail = self.format(test_mail_data.MAIL_TEMPLATE_PLAINTEXT, email_from='"Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>', to='generic@test.com')
res = self.env['mail.thread'].message_parse(self.from_string(mail))
self.assertIn('<pre>\nPlease call me as soon as possible this afternoon!\n\n--\nSylvie\n</pre>', res['body'])
def test_message_parse_xhtml(self):
# Test that the parsing of XHTML mails does not fail
self.env['mail.thread'].message_parse(self.from_string(test_mail_data.MAIL_XHTML))
@tagged('mail_gateway')
class TestMailAlias(TestMailCommon):
@users('employee')
@mute_logger('odoo.addons.base.models.ir_model')
def test_alias_creation(self):
record = self.env['mail.test.container'].create({
'name': 'Test Record',
'alias_name': 'alias.test',
'alias_contact': 'followers',
})
self.assertEqual(record.alias_id.alias_model_id, self.env['ir.model']._get('mail.test.container'))
self.assertEqual(record.alias_id.alias_force_thread_id, record.id)
self.assertEqual(record.alias_id.alias_parent_model_id, self.env['ir.model']._get('mail.test.container'))
self.assertEqual(record.alias_id.alias_parent_thread_id, record.id)
self.assertEqual(record.alias_id.alias_name, 'alias.test')
self.assertEqual(record.alias_id.alias_contact, 'followers')
record.write({
'alias_name': 'better.alias.test',
'alias_defaults': "{'default_name': 'defaults'}"
})
self.assertEqual(record.alias_id.alias_name, 'better.alias.test')
self.assertEqual(record.alias_id.alias_defaults, "{'default_name': 'defaults'}")
with self.assertRaises(exceptions.AccessError):
record.write({
'alias_force_thread_id': 0,
})
with self.assertRaises(exceptions.AccessError):
record.write({
'alias_model_id': self.env['ir.model']._get('mail.test.gateway').id,
})
with self.assertRaises(exceptions.ValidationError):
record.write({'alias_defaults': "{'custom_field': brokendict"})
def test_alias_sanitize(self):
alias = self.env['mail.alias'].create({
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_name': 'bidule...inc.',
})
self.assertEqual(alias.alias_name, 'bidule.inc', 'Emails cannot start or end with a dot, there cannot be a sequence of dots.')
def test_alias_setup(self):
alias = self.env['mail.alias'].create({
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_name': 'b4r+_#_R3wl$$',
})
self.assertEqual(alias.alias_name, 'b4r+_-_r3wl-', 'Disallowed chars should be replaced by hyphens')
with self.assertRaises(exceptions.ValidationError):
alias.write({'alias_defaults': "{'custom_field': brokendict"})
def test_alias_name_unique(self):
alias_model_id = self.env['ir.model']._get('mail.test.gateway').id
catchall_alias = self.env['ir.config_parameter'].sudo().get_param('mail.catchall.alias')
bounce_alias = self.env['ir.config_parameter'].sudo().get_param('mail.bounce.alias')
# test you cannot create aliases matching bounce / catchall
with self.assertRaises(exceptions.UserError), self.cr.savepoint():
self.env['mail.alias'].create({'alias_model_id': alias_model_id, 'alias_name': catchall_alias})
with self.assertRaises(exceptions.UserError), self.cr.savepoint():
self.env['mail.alias'].create({'alias_model_id': alias_model_id, 'alias_name': bounce_alias})
new_mail_alias = self.env['mail.alias'].create({
'alias_model_id': alias_model_id,
'alias_name': 'unused.test.alias'
})
# test that re-using catchall and bounce alias raises UserError
with self.assertRaises(exceptions.UserError), self.cr.savepoint():
new_mail_alias.write({
'alias_name': catchall_alias
})
with self.assertRaises(exceptions.UserError), self.cr.savepoint():
new_mail_alias.write({
'alias_name': bounce_alias
})
new_mail_alias.write({'alias_name': 'another.unused.test.alias'})
# test that duplicating an alias should have blank name
copy_new_mail_alias = new_mail_alias.copy()
self.assertFalse(copy_new_mail_alias.alias_name)
# cannot set catchall / bounce to used alias
with self.assertRaises(exceptions.UserError), self.cr.savepoint():
self.env['ir.config_parameter'].sudo().set_param('mail.catchall.alias', new_mail_alias.alias_name)
with self.assertRaises(exceptions.UserError), self.cr.savepoint():
self.env['ir.config_parameter'].sudo().set_param('mail.bounce.alias', new_mail_alias.alias_name)
@tagged('mail_gateway')
class TestMailAliasMixin(TestMailCommon):
@users('employee')
def test_alias_mixin_copy_content(self):
self.assertFalse(self.env.user.has_group('base.group_system'), 'Test user should not have Administrator access')
record = self.env['mail.test.container'].create({
'name': 'Test Record',
'alias_name': 'test.record',
'alias_contact': 'followers',
'alias_bounced_content': False,
})
self.assertFalse(record.alias_bounced_content)
record_copy = record.copy()
self.assertFalse(record_copy.alias_bounced_content)
new_content = '<p>Bounced Content</p>'
record_copy.write({'alias_bounced_content': new_content})
self.assertEqual(record_copy.alias_bounced_content, new_content)
record_copy2 = record_copy.copy()
self.assertEqual(record_copy2.alias_bounced_content, new_content)
@tagged('mail_gateway')
class TestMailgateway(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestMailgateway, cls).setUpClass()
cls.test_model = cls.env['ir.model']._get('mail.test.gateway')
cls.email_from = '"Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>'
cls.test_record = cls.env['mail.test.gateway'].with_context(cls._test_context).create({
'name': 'Test',
'email_from': 'ignasse@example.com',
}).with_context({})
cls.partner_1 = cls.env['res.partner'].with_context(cls._test_context).create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com',
})
# groups@.. will cause the creation of new mail.test.gateway
cls.alias = cls.env['mail.alias'].create({
'alias_name': 'groups',
'alias_user_id': False,
'alias_model_id': cls.test_model.id,
'alias_contact': 'everyone'})
# Set a first message on public group to test update and hierarchy
cls.fake_email = cls._create_gateway_message(cls.test_record, '123456')
cls._init_mail_gateway()
@classmethod
def _create_gateway_message(cls, record, msg_id_prefix, **values):
msg_values = {
'author_id': cls.partner_1.id,
'email_from': cls.partner_1.email_formatted,
'body': '<p>Generic body</p>',
'message_id': f'<{msg_id_prefix}-openerp-{record.id}-{record._name}@{socket.gethostname()}>',
'message_type': 'email',
'model': record._name,
'res_id': record.id,
'subject': 'Generic Message',
'subtype_id': cls.env.ref('mail.mt_comment').id,
}
msg_values.update(**values)
return cls.env['mail.message'].create(msg_values)
# --------------------------------------------------
# Base low-level tests
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_alias_basic(self):
""" Test details of created message going through mailgateway """
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Specific')
# Test: one group created by mailgateway administrator as user_id is not set
self.assertEqual(len(record), 1, 'message_process: a new mail.test should have been created')
res = record.get_metadata()[0].get('create_uid') or [None]
self.assertEqual(res[0], self.env.uid)
# Test: one message that is the incoming email
self.assertEqual(len(record.message_ids), 1)
msg = record.message_ids[0]
self.assertEqual(msg.subject, 'Specific')
self.assertIn('Please call me as soon as possible this afternoon!', msg.body)
self.assertEqual(msg.message_type, 'email')
self.assertEqual(msg.subtype_id, self.env.ref('mail.mt_comment'))
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_cid(self):
record = self.format_and_process(test_mail_data.MAIL_MULTIPART_IMAGE, self.email_from, 'groups@test.com')
message = record.message_ids[0]
for attachment in message.attachment_ids:
self.assertIn('/web/image/%s' % attachment.id, message.body)
self.assertEqual(
set(message.attachment_ids.mapped('name')),
set(['rosaçée.gif', 'verte!µ.gif', 'orangée.gif']))
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_followers(self):
""" Incoming email: recognized author not archived and not odoobot:
added as follower. Also test corner cases: archived, private. """
partner_archived, partner_private = self.env['res.partner'].create([
{
'active': False,
'email': 'archived.customer@text.example.com',
'phone': '0032455112233',
'name': 'Archived Customer',
'type': 'contact',
},
{
'email': 'private.customer@text.example.com',
'phone': '0032455112233',
'name': 'Private Customer',
'type': 'private',
},
])
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@test.com')
self.assertEqual(record.message_ids[0].author_id, self.partner_1,
'message_process: recognized email -> author_id')
self.assertEqual(record.message_ids[0].email_from, self.partner_1.email_formatted)
self.assertEqual(record.message_follower_ids.partner_id, self.partner_1,
'message_process: recognized email -> added as follower')
self.assertEqual(record.message_partner_ids, self.partner_1,
'message_process: recognized email -> added as follower')
# just an email -> no follower
with self.mock_mail_gateway():
record2 = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com',
subject='Another Email')
self.assertEqual(record2.message_ids[0].author_id, self.env['res.partner'])
self.assertEqual(record2.message_ids[0].email_from, self.email_from)
self.assertEqual(record2.message_follower_ids.partner_id, self.env['res.partner'],
'message_process: unrecognized email -> no follower')
self.assertEqual(record2.message_partner_ids, self.env['res.partner'],
'message_process: unrecognized email -> no follower')
# archived partner -> no follower
with self.mock_mail_gateway():
record3 = self.format_and_process(
MAIL_TEMPLATE, partner_archived.email_formatted, 'groups@test.com',
subject='Archived Partner')
self.assertEqual(record3.message_ids[0].author_id, self.env['res.partner'])
self.assertEqual(record3.message_ids[0].email_from, partner_archived.email_formatted)
self.assertEqual(record3.message_follower_ids.partner_id, self.env['res.partner'],
'message_process: archived partner -> no follower')
self.assertEqual(record3.message_partner_ids, self.env['res.partner'],
'message_process: archived partner -> no follower')
# partner_root -> never again
odoobot = self.env.ref('base.partner_root')
odoobot.active = True
odoobot.email = 'odoobot@example.com'
with self.mock_mail_gateway():
record4 = self.format_and_process(
MAIL_TEMPLATE, odoobot.email_formatted, 'groups@test.com',
subject='Odoobot Automatic Answer')
self.assertEqual(record4.message_ids[0].author_id, odoobot)
self.assertEqual(record4.message_ids[0].email_from, odoobot.email_formatted)
self.assertEqual(record4.message_follower_ids.partner_id, self.env['res.partner'],
'message_process: odoobot -> no follower')
self.assertEqual(record4.message_partner_ids, self.env['res.partner'],
'message_process: odoobot -> no follower')
# private partner
with self.mock_mail_gateway():
record5 = self.format_and_process(
MAIL_TEMPLATE, partner_private.email_formatted, 'groups@test.com',
subject='Private Partner')
self.assertEqual(record5.message_ids[0].author_id, partner_private)
self.assertEqual(record5.message_ids[0].email_from, partner_private.email_formatted)
self.assertEqual(record5.message_follower_ids.partner_id, partner_private,
'message_process: private partner is recognized')
self.assertEqual(record5.message_partner_ids, partner_private,
'message_process: private partner is recognized')
# --------------------------------------------------
# Author recognition
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_email_email_from(self):
""" Incoming email: not recognized author: email_from, no author_id, no followers """
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com')
self.assertFalse(record.message_ids[0].author_id, 'message_process: unrecognized email -> no author_id')
self.assertEqual(record.message_ids[0].email_from, self.email_from)
self.assertEqual(len(record.message_partner_ids), 0,
'message_process: newly create group should not have any follower')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_email_author(self):
""" Incoming email: recognized author: email_from, author_id, added as follower """
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@test.com', subject='Test1')
self.assertEqual(record.message_ids[0].author_id, self.partner_1,
'message_process: recognized email -> author_id')
self.assertEqual(record.message_ids[0].email_from, self.partner_1.email_formatted)
self.assertNotSentEmail() # No notification / bounce should be sent
# Email recognized if partner has a formatted email
self.partner_1.write({'email': '"Valid Lelitre" <%s>' % self.partner_1.email})
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email, 'groups@test.com', subject='Test2')
self.assertEqual(record.message_ids[0].author_id, self.partner_1,
'message_process: recognized email -> author_id')
self.assertEqual(record.message_ids[0].email_from, self.partner_1.email)
self.assertNotSentEmail() # No notification / bounce should be sent
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink')
def test_message_process_email_partner_find(self):
""" Finding the partner based on email, based on partner / user / follower """
self.alias.write({'alias_force_thread_id': self.test_record.id})
from_1 = self.env['res.partner'].create({'name': 'Brice Denisse', 'email': 'from.test@example.com'})
self.format_and_process(MAIL_TEMPLATE, from_1.email_formatted, 'groups@test.com')
self.assertEqual(self.test_record.message_ids[0].author_id, from_1)
self.test_record.message_unsubscribe([from_1.id])
from_2 = mail_new_test_user(self.env, login='B', groups='base.group_user', name='User Denisse', email='from.test@example.com')
self.format_and_process(MAIL_TEMPLATE, from_1.email_formatted, 'groups@test.com')
self.assertEqual(self.test_record.message_ids[0].author_id, from_2.partner_id)
self.test_record.message_unsubscribe([from_2.partner_id.id])
from_3 = self.env['res.partner'].create({'name': 'FOllower Denisse', 'email': 'from.test@example.com'})
self.test_record.message_subscribe([from_3.id])
self.format_and_process(MAIL_TEMPLATE, from_1.email_formatted, 'groups@test.com')
self.assertEqual(self.test_record.message_ids[0].author_id, from_3)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_email_author_exclude_alias(self):
""" Do not set alias as author to avoid including aliases in discussions """
from_1 = self.env['res.partner'].create({'name': 'Brice Denisse', 'email': 'from.test@test.com'})
self.env['mail.alias'].create({
'alias_name': 'from.test',
'alias_model_id': self.env['ir.model']._get('mail.test.gateway').id
})
record = self.format_and_process(MAIL_TEMPLATE, from_1.email_formatted, 'groups@test.com')
self.assertFalse(record.message_ids[0].author_id)
self.assertEqual(record.message_ids[0].email_from, from_1.email_formatted)
# --------------------------------------------------
# Alias configuration
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_message_process_alias_config_bounced_content(self):
""" Custom bounced message for the alias => Received this custom message """
self.alias.write({
'alias_contact': 'partners',
'alias_bounced_content': '<p>What Is Dead May Never Die</p>'
})
# Test: custom bounced content
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Should Bounce')
self.assertFalse(record, 'message_process: should have bounced')
self.assertSentEmail('"MAILER-DAEMON" <bounce.test@test.com>', ['whatever-2a840@postmaster.twitter.com'], body_content='<p>What Is Dead May Never Die</p>')
for empty_content in [
'<p><br></p>', '<p><br> </p>', '<p><br /></p >',
'<p style="margin: 4px"></p>',
'<div style="margin: 4px"></div>',
'<p class="oe_testing"><br></p>',
'<p><span style="font-weight: bolder;"><font style="color: rgb(255, 0, 0);" class=" "></font></span><br></p>',
]:
self.alias.write({
'alias_contact': 'partners',
'alias_bounced_content': empty_content,
})
# Test: with "empty" bounced content (simulate view, putting always '<p></br></p>' in html field)
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Should Bounce')
self.assertFalse(record, 'message_process: should have bounced')
# Check if default (hardcoded) value is in the mail content
self.assertSentEmail(
'"MAILER-DAEMON" <bounce.test@test.com>', ['whatever-2a840@postmaster.twitter.com'],
body_content='<p>Dear Sender,<br /><br />\nThe message below could not be accepted by the address %s' % self.alias.display_name.lower()
)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_message_process_alias_config_bounced_to(self):
""" Check bounce message contains the bouncing alias, not a generic "to" """
self.alias.write({'alias_contact': 'partners'})
bounce_message_with_alias = '<p>Dear Sender,<br /><br />\nThe message below could not be accepted by the address %s' % self.alias.display_name.lower()
# Bounce is To
with self.mock_mail_gateway():
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@example.com',
cc='other@gmail.com', subject='Should Bounce')
self.assertIn(bounce_message_with_alias, self._mails[0].get('body'))
# Bounce is CC
with self.mock_mail_gateway():
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'other@gmail.com',
cc='groups@example.com', subject='Should Bounce')
self.assertIn(bounce_message_with_alias, self._mails[0].get('body'))
# Bounce is part of To
with self.mock_mail_gateway():
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'other@gmail.com, groups@example.com',
subject='Should Bounce')
self.assertIn(bounce_message_with_alias, self._mails[0].get('body'))
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_alias_defaults(self):
""" Test alias defaults and inner values """
self.alias.write({
'alias_user_id': self.user_employee.id,
'alias_defaults': "{'custom_field': 'defaults_custom'}"
})
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Specific')
self.assertEqual(len(record), 1)
res = record.get_metadata()[0].get('create_uid') or [None]
self.assertEqual(res[0], self.user_employee.id)
self.assertEqual(record.name, 'Specific')
self.assertEqual(record.custom_field, 'defaults_custom')
self.alias.write({'alias_defaults': '""'})
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Specific2')
self.assertEqual(len(record), 1)
res = record.get_metadata()[0].get('create_uid') or [None]
self.assertEqual(res[0], self.user_employee.id)
self.assertEqual(record.name, 'Specific2')
self.assertFalse(record.custom_field)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_alias_user_id(self):
""" Test alias ownership """
self.alias.write({'alias_user_id': self.user_employee.id})
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com')
self.assertEqual(len(record), 1)
res = record.get_metadata()[0].get('create_uid') or [None]
self.assertEqual(res[0], self.user_employee.id)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_alias_everyone(self):
""" Incoming email: everyone: new record + message_new """
self.alias.write({'alias_contact': 'everyone'})
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Specific')
self.assertEqual(len(record), 1)
self.assertEqual(len(record.message_ids), 1)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_message_process_alias_partners_bounce(self):
""" Incoming email from an unknown partner on a Partners only alias -> bounce + test bounce email """
self.alias.write({'alias_contact': 'partners'})
# Test: no group created, email bounced
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Should Bounce')
self.assertFalse(record)
self.assertSentEmail('"MAILER-DAEMON" <bounce.test@test.com>', ['whatever-2a840@postmaster.twitter.com'], subject='Re: Should Bounce')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_message_process_alias_followers_bounce(self):
""" Incoming email from unknown partner / not follower partner on a Followers only alias -> bounce """
self.alias.write({
'alias_contact': 'followers',
'alias_parent_model_id': self.env['ir.model']._get('mail.test.gateway').id,
'alias_parent_thread_id': self.test_record.id,
})
# Test: unknown on followers alias -> bounce
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Should Bounce')
self.assertFalse(record, 'message_process: should have bounced')
self.assertSentEmail('"MAILER-DAEMON" <bounce.test@test.com>', ['whatever-2a840@postmaster.twitter.com'], subject='Re: Should Bounce')
# Test: partner on followers alias -> bounce
self._init_mail_mock()
with self.mock_mail_gateway():
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@test.com', subject='Should Bounce')
self.assertFalse(record, 'message_process: should have bounced')
self.assertSentEmail('"MAILER-DAEMON" <bounce.test@test.com>', ['whatever-2a840@postmaster.twitter.com'], subject='Re: Should Bounce')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_alias_partner(self):
""" Incoming email from a known partner on a Partners alias -> ok (+ test on alias.user_id) """
self.alias.write({'alias_contact': 'partners'})
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@test.com')
# Test: one group created by alias user
self.assertEqual(len(record), 1)
self.assertEqual(len(record.message_ids), 1)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_alias_followers(self):
""" Incoming email from a parent document follower on a Followers only alias -> ok """
self.alias.write({
'alias_contact': 'followers',
'alias_parent_model_id': self.env['ir.model']._get('mail.test.gateway').id,
'alias_parent_thread_id': self.test_record.id,
})
self.test_record.message_subscribe(partner_ids=[self.partner_1.id])
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@test.com')
# Test: one group created by Raoul (or Sylvie maybe, if we implement it)
self.assertEqual(len(record), 1)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_message_process_alias_update(self):
""" Incoming email update discussion + notification email """
self.alias.write({'alias_force_thread_id': self.test_record.id})
self.test_record.message_subscribe(partner_ids=[self.partner_1.id])
with self.mock_mail_gateway():
record = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com>',
msg_id='<1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>', subject='Re: cats')
# Test: no new group + new message
self.assertFalse(record, 'message_process: alias update should not create new records')
self.assertEqual(len(self.test_record.message_ids), 2)
# Test: sent emails: 1 (Sylvie copy of the incoming email)
self.assertSentEmail(self.email_from, [self.partner_1], subject='Re: cats')
# --------------------------------------------------
# Creator recognition
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_create_uid_crash(self):
def _employee_crash(*args, **kwargs):
""" If employee is test employee, consider he has no access on document """
recordset = args[0]
if recordset.env.uid == self.user_employee.id and not recordset.env.su:
if kwargs.get('raise_exception', True):
raise exceptions.AccessError('Hop hop hop Ernest, please step back.')
return False
return DEFAULT
with patch.object(MailTestGateway, 'check_access_rights', autospec=True, side_effect=_employee_crash):
record = self.format_and_process(MAIL_TEMPLATE, self.user_employee.email_formatted, 'groups@test.com', subject='NoEmployeeAllowed')
self.assertEqual(record.create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].subject, 'NoEmployeeAllowed')
self.assertEqual(record.message_ids[0].create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].author_id, self.user_employee.partner_id)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_create_uid_email(self):
record = self.format_and_process(MAIL_TEMPLATE, self.user_employee.email_formatted, 'groups@test.com', subject='Email Found')
self.assertEqual(record.create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].subject, 'Email Found')
self.assertEqual(record.message_ids[0].create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].author_id, self.user_employee.partner_id)
record = self.format_and_process(MAIL_TEMPLATE, 'Another name <%s>' % self.user_employee.email, 'groups@test.com', subject='Email OtherName')
self.assertEqual(record.create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].subject, 'Email OtherName')
self.assertEqual(record.message_ids[0].create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].author_id, self.user_employee.partner_id)
record = self.format_and_process(MAIL_TEMPLATE, self.user_employee.email_normalized, 'groups@test.com', subject='Email SimpleEmail')
self.assertEqual(record.create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].subject, 'Email SimpleEmail')
self.assertEqual(record.message_ids[0].create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].author_id, self.user_employee.partner_id)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink')
def test_message_process_create_uid_email_follower(self):
self.alias.write({
'alias_parent_model_id': self.test_model.id,
'alias_parent_thread_id': self.test_record.id,
})
follower_user = mail_new_test_user(self.env, login='better', groups='base.group_user', name='Ernest Follower', email=self.user_employee.email)
self.test_record.message_subscribe(follower_user.partner_id.ids)
record = self.format_and_process(MAIL_TEMPLATE, self.user_employee.email_formatted, 'groups@test.com', subject='FollowerWinner')
self.assertEqual(record.create_uid, follower_user)
self.assertEqual(record.message_ids[0].subject, 'FollowerWinner')
self.assertEqual(record.message_ids[0].create_uid, follower_user)
self.assertEqual(record.message_ids[0].author_id, follower_user.partner_id)
# name order win
self.test_record.message_unsubscribe(follower_user.partner_id.ids)
self.test_record.flush()
record = self.format_and_process(MAIL_TEMPLATE, self.user_employee.email_formatted, 'groups@test.com', subject='FirstFoundWinner')
self.assertEqual(record.create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].subject, 'FirstFoundWinner')
self.assertEqual(record.message_ids[0].create_uid, self.user_employee)
self.assertEqual(record.message_ids[0].author_id, self.user_employee.partner_id)
# --------------------------------------------------
# Alias routing management
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_alias_no_domain(self):
""" Incoming email: write to alias even if no domain set: considered as valid alias """
self.env['ir.config_parameter'].set_param('mail.catchall.domain', '')
new_record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, 'groups@another.domain.com', subject='Test Subject')
# Test: one group created
self.assertEqual(len(new_record), 1, 'message_process: a new mail.test.simple should have been created')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_alias_forward_bypass_reply_first(self):
""" Incoming email: write to two "new thread" alias, one as a reply, one being another model -> consider as a forward """
self.assertEqual(len(self.test_record.message_ids), 1)
# test@.. will cause the creation of new mail.test
new_alias_2 = self.env['mail.alias'].create({
'alias_name': 'test',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_contact': 'everyone',
})
new_rec = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (new_alias_2.alias_name, self.alias_domain, self.alias.alias_name, self.alias_domain),
subject='Test Subject',
extra='In-Reply-To:\r\n\t%s\n' % self.fake_email.message_id,
target_model=new_alias_2.alias_model_id.model
)
# Forward created a new record in mail.test
self.assertEqual(len(new_rec), 1, 'message_process: a new mail.test should have been created')
self.assertEqual(new_rec._name, new_alias_2.alias_model_id.model)
# No new post on test_record, no new record in mail.test.simple either
self.assertEqual(len(self.test_record.message_ids), 1, 'message_process: should not post on replied record as forward should bypass it')
new_simple = self.env['mail.test.simple'].search([('name', '=', 'Test Subject')])
self.assertEqual(len(new_simple), 0, 'message_process: a new mail.test should not have been created')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_alias_forward_bypass_reply_second(self):
""" Incoming email: write to two "new thread" alias, one as a reply, one being another model -> consider as a forward """
self.assertEqual(len(self.test_record.message_ids), 1)
# test@.. will cause the creation of new mail.test
new_alias_2 = self.env['mail.alias'].create({
'alias_name': 'test',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_contact': 'everyone',
})
new_rec = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (self.alias.alias_name, self.alias_domain, new_alias_2.alias_name, self.alias_domain),
subject='Test Subject',
extra='In-Reply-To:\r\n\t%s\n' % self.fake_email.message_id,
target_model=new_alias_2.alias_model_id.model
)
# Forward created a new record in mail.test
self.assertEqual(len(new_rec), 1, 'message_process: a new mail.test should have been created')
self.assertEqual(new_rec._name, new_alias_2.alias_model_id.model)
# No new post on test_record, no new record in mail.test.simple either
self.assertEqual(len(self.test_record.message_ids), 1, 'message_process: should not post on replied record as forward should bypass it')
new_simple = self.env['mail.test.simple'].search([('name', '=', 'Test Subject')])
self.assertEqual(len(new_simple), 0, 'message_process: a new mail.test should not have been created')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_alias_forward_bypass_update_alias(self):
""" Incoming email: write to one "update", one "new thread" alias, one as a reply, one being another model -> consider as a forward """
self.assertEqual(len(self.test_record.message_ids), 1)
self.alias.write({
'alias_force_thread_id': self.test_record.id,
})
# test@.. will cause the creation of new mail.test
new_alias_2 = self.env['mail.alias'].create({
'alias_name': 'test',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_contact': 'everyone',
})
new_rec = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (new_alias_2.alias_name, self.alias_domain, self.alias.alias_name, self.alias_domain),
subject='Test Subject',
extra='In-Reply-To:\r\n\t%s\n' % self.fake_email.message_id,
target_model=new_alias_2.alias_model_id.model
)
# Forward created a new record in mail.test
self.assertEqual(len(new_rec), 1, 'message_process: a new mail.test should have been created')
self.assertEqual(new_rec._name, new_alias_2.alias_model_id.model)
# No new post on test_record, no new record in mail.test.simple either
self.assertEqual(len(self.test_record.message_ids), 1, 'message_process: should not post on replied record as forward should bypass it')
# No new record on first alias model
new_simple = self.env['mail.test.gateway'].search([('name', '=', 'Test Subject')])
self.assertEqual(len(new_simple), 0, 'message_process: a new mail.test should not have been created')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_alias_multiple_new(self):
""" Incoming email: write to two aliases creating records: both should be activated """
# test@.. will cause the creation of new mail.test
new_alias_2 = self.env['mail.alias'].create({
'alias_name': 'test',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_contact': 'everyone',
})
new_rec = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (self.alias.alias_name, self.alias_domain, new_alias_2.alias_name, self.alias_domain),
subject='Test Subject',
target_model=new_alias_2.alias_model_id.model
)
# New record in both mail.test (new_alias_2) and mail.test.simple (self.alias)
self.assertEqual(len(new_rec), 1, 'message_process: a new mail.test should have been created')
self.assertEqual(new_rec._name, new_alias_2.alias_model_id.model)
new_simple = self.env['mail.test.gateway'].search([('name', '=', 'Test Subject')])
self.assertEqual(len(new_simple), 1, 'message_process: a new mail.test should have been created')
# --------------------------------------------------
# Email Management
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_bounce(self):
"""Incoming email: bounce using bounce alias: no record creation """
with self.mock_mail_gateway():
new_recs = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s' % (self.alias_bounce, self.alias_domain),
subject='Should bounce',
)
self.assertFalse(new_recs)
self.assertNotSentEmail()
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_bounce_other_recipients(self):
"""Incoming email: bounce processing: bounce should be computed even if not first recipient """
with self.mock_mail_gateway():
new_recs = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (
self.alias.alias_name, self.alias_domain,
self.alias_bounce, self.alias_domain
),
subject='Should bounce',
)
self.assertFalse(new_recs)
self.assertNotSentEmail()
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_message_route_write_to_catchall(self):
""" Writing directly to catchall should bounce """
# Test: no group created, email bounced
with self.mock_mail_gateway():
record = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'"My Super Catchall" <%s@%s>' % (self.alias_catchall, self.alias_domain),
subject='Should Bounce')
self.assertFalse(record)
self.assertSentEmail('"MAILER-DAEMON" <bounce.test@test.com>', ['whatever-2a840@postmaster.twitter.com'], subject='Re: Should Bounce')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_write_to_catchall_other_recipients_first(self):
""" Writing directly to catchall and a valid alias should take alias """
# Test: no group created, email bounced
with self.mock_mail_gateway():
record = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (self.alias_catchall, self.alias_domain, self.alias.alias_name, self.alias_domain),
subject='Catchall Not Blocking'
)
# Test: one group created
self.assertEqual(len(record), 1, 'message_process: a new mail.test should have been created')
# No bounce email
self.assertNotSentEmail()
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_route_write_to_catchall_other_recipients_second(self):
""" Writing directly to catchall and a valid alias should take alias """
# Test: no group created, email bounced
with self.mock_mail_gateway():
record = self.format_and_process(
MAIL_TEMPLATE, self.partner_1.email_formatted,
'%s@%s, %s@%s' % (self.alias.alias_name, self.alias_domain, self.alias_catchall, self.alias_domain),
subject='Catchall Not Blocking'
)
# Test: one group created
self.assertEqual(len(record), 1, 'message_process: a new mail.test should have been created')
# No bounce email
self.assertNotSentEmail()
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_alias(self):
""" Writing to bounce alias is considered as a bounce even if not multipart/report bounce structure """
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
bounced_mail_id = 4442
bounce_email_to = '%s@%s' % ('bounce.test', 'test.com')
record = self.format_and_process(MAIL_TEMPLATE, self.partner_1.email_formatted, bounce_email_to, subject='Undelivered Mail Returned to Sender')
self.assertFalse(record)
# No information found in bounce email -> not possible to do anything except avoiding email
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_from_mailer_demon(self):
""" MAILER_DAEMON emails are considered as bounce """
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
record = self.format_and_process(MAIL_TEMPLATE, 'MAILER-DAEMON@example.com', 'groups@test.com', subject='Undelivered Mail Returned to Sender')
self.assertFalse(record)
# No information found in bounce email -> not possible to do anything except avoiding email
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_multipart_alias(self):
""" Multipart/report bounce correctly make related partner bounce """
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
bounced_mail_id = 4442
bounce_email_to = '%s@%s' % ('bounce.test', 'test.com')
record = self.format_and_process(test_mail_data.MAIL_BOUNCE, self.partner_1.email_formatted, bounce_email_to, subject='Undelivered Mail Returned to Sender')
self.assertFalse(record)
# Missing in reply to message_id -> cannot find original record
self.assertEqual(self.partner_1.message_bounce, 1)
self.assertEqual(self.test_record.message_bounce, 0)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_multipart_alias_reply(self):
""" Multipart/report bounce correctly make related partner and record found in bounce email bounce """
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
bounced_mail_id = 4442
bounce_email_to = '%s@%s' % ('bounce.test', 'test.com')
extra = self.fake_email.message_id
record = self.format_and_process(test_mail_data.MAIL_BOUNCE, self.partner_1.email_formatted, bounce_email_to, subject='Undelivered Mail Returned to Sender', extra=extra)
self.assertFalse(record)
self.assertEqual(self.partner_1.message_bounce, 1)
self.assertEqual(self.test_record.message_bounce, 1)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_multipart_alias_whatever_from(self):
""" Multipart/report bounce correctly make related record found in bounce email bounce """
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
bounced_mail_id = 4442
bounce_email_to = '%s@%s' % ('bounce.test', 'test.com')
extra = self.fake_email.message_id
record = self.format_and_process(test_mail_data.MAIL_BOUNCE, 'Whatever <what@ever.com>', bounce_email_to, subject='Undelivered Mail Returned to Sender', extra=extra)
self.assertFalse(record)
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 1)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_multipart_whatever_to_and_from(self):
""" Multipart/report bounce correctly make related record found in bounce email bounce """
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 0)
extra = self.fake_email.message_id
record = self.format_and_process(test_mail_data.MAIL_BOUNCE, 'Whatever <what@ever.com>', 'groups@test.com', subject='Undelivered Mail Returned to Sender', extra=extra)
self.assertFalse(record)
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(self.test_record.message_bounce, 1)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink')
def test_message_process_bounce_records_channel(self):
""" Test blacklist allow to multi-bounce and auto update of mail.channel """
other_record = self.env['mail.test.gateway'].create({
'email_from': 'Another name <%s>' % self.partner_1.email
})
yet_other_record = self.env['mail.test.gateway'].create({
'email_from': 'Yet Another name <%s>' % self.partner_1.email.upper()
})
test_channel = self.env['mail.channel'].create({
'name': 'Test',
'channel_partner_ids': [(4, self.partner_1.id)],
})
self.fake_email.write({
'model': 'mail.channel',
'res_id': test_channel.id,
})
self.assertIn(self.partner_1, test_channel.channel_partner_ids)
self.assertEqual(self.partner_1.message_bounce, 0)
self.assertEqual(other_record.message_bounce, 0)
self.assertEqual(yet_other_record.message_bounce, 0)
extra = self.fake_email.message_id
for i in range(10):
record = self.format_and_process(test_mail_data.MAIL_BOUNCE, 'A third name <%s>' % self.partner_1.email, 'groups@test.com', subject='Undelivered Mail Returned to Sender', extra=extra)
self.assertFalse(record)
self.assertEqual(self.partner_1.message_bounce, 10)
self.assertEqual(self.test_record.message_bounce, 0)
self.assertEqual(other_record.message_bounce, 10)
self.assertEqual(yet_other_record.message_bounce, 10)
self.assertNotIn(self.partner_1, test_channel.channel_partner_ids)
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_bounce_records_partner(self):
""" Test blacklist + bounce on ``res.partner`` model """
self.assertEqual(self.partner_1.message_bounce, 0)
self.fake_email.write({
'model': 'res.partner',
'res_id': self.partner_1.id,
})
extra = self.fake_email.message_id
record = self.format_and_process(test_mail_data.MAIL_BOUNCE, self.partner_1.email_formatted, 'groups@test.com', subject='Undelivered Mail Returned to Sender', extra=extra)
self.assertFalse(record)
self.assertEqual(self.partner_1.message_bounce, 1)
self.assertEqual(self.test_record.message_bounce, 0)
# --------------------------------------------------
# Thread formation
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_in_reply_to(self):
""" Incoming email using in-rely-to should go into the right destination even with a wrong destination """
init_msg_count = len(self.test_record.message_ids)
self.format_and_process(
MAIL_TEMPLATE, 'valid.other@gmail.com', 'erroneous@test.com>',
subject='Re: news', extra='In-Reply-To:\r\n\t%s\n' % self.fake_email.message_id)
self.assertEqual(len(self.test_record.message_ids), init_msg_count + 1)
self.assertEqual(self.fake_email.child_ids, self.test_record.message_ids[0])
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_references(self):
""" Incoming email using references should go into the right destination even with a wrong destination """
init_msg_count = len(self.test_record.message_ids)
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'erroneous@test.com',
extra='References: <2233@a.com>\r\n\t<3edss_dsa@b.com> %s' % self.fake_email.message_id)
self.assertEqual(len(self.test_record.message_ids), init_msg_count + 1)
self.assertEqual(self.fake_email.child_ids, self.test_record.message_ids[0])
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail', 'odoo.tests')
def test_message_process_references_multi_parent(self):
""" Incoming email with multiple references """
reply1 = self._create_gateway_message(
self.test_record, 'reply1', parent_id=self.fake_email.id,
)
reply2 = self._create_gateway_message(
self.test_record, 'reply2', parent_id=self.fake_email.id,
subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
)
reply1_1 = self._create_gateway_message(
self.test_record, 'reply1_1', parent_id=reply1.id,
subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
)
reply2_1 = self._create_gateway_message(
self.test_record, 'reply2_1', parent_id=reply2.id,
)
# reply to reply1 using multiple references
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com',
subject='Reply to reply1',
extra=f'References: {reply1.message_id} {self.fake_email.message_id}'
)
new_msg = self.test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, self.fake_email, 'Mail: flattening attach to original message')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: reply to a comment should be a comment')
# ordering should not impact
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com',
subject='Reply to reply1 (order issue)',
extra=f'References: {self.fake_email.message_id} {reply1.message_id}'
)
new_msg = self.test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, self.fake_email, 'Mail: flattening attach to original message')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: reply to a comment should be a comment')
# history with last one being a note
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com',
subject='Reply to reply1_1',
extra=f'References: {reply1_1.message_id} {self.fake_email.message_id}'
)
new_msg = self.test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, self.fake_email, 'Mail: flattening attach to original message')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_note'), 'Mail: reply to a note should be a note')
# messed up history (two child branches): gateway initial parent is newest one
# (then may change with flattening when posting on record)
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com',
subject='Reply to reply2_1 (with noise)',
extra=f'References: {reply1_1.message_id} {reply2_1.message_id}'
)
new_msg = self.test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, self.fake_email, 'Mail: flattening attach to original message')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: parent should be a comment (before flattening)')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail', 'odoo.tests')
def test_message_process_references_multi_parent_notflat(self):
""" Incoming email with multiple references with ``_mail_flat_thread``
being False (mail.group/mail.channel behavior like). """
test_record = self.env['mail.test.gateway.groups'].create({
'alias_name': 'test.gateway',
'name': 'Test',
'email_from': 'ignasse@example.com',
})
# Set a first message on public group to test update and hierarchy
first_msg = self._create_gateway_message(test_record, 'first_msg')
reply1 = self._create_gateway_message(
test_record, 'reply1', parent_id=first_msg.id,
)
reply2 = self._create_gateway_message(
test_record, 'reply2', parent_id=first_msg.id,
subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
)
reply1_1 = self._create_gateway_message(
test_record, 'reply1_1', parent_id=reply1.id,
subtype_id=self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
)
reply2_1 = self._create_gateway_message(
test_record, 'reply2_1', parent_id=reply2.id,
)
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.gateway@test.com',
subject='Reply to reply1',
extra=f'References: {reply1.message_id}'
)
new_msg = test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, first_msg, 'Mail: pseudo no flattening: getting up one level (reply1 parent)')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: parent should be a comment')
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.gateway@test.com',
subject='Reply to reply1_1 (with noise)',
extra=f'References: {reply1_1.message_id} {reply1.message_id} {reply1.message_id}'
)
new_msg = test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, reply1, 'Mail: pseudo no flattening: getting up one level (reply1_1 parent)')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_note'), 'Mail: reply to a note should be a note')
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.gateway@test.com',
subject='Reply to reply2_1 (with noise)',
extra=f'References: {reply2_1.message_id} {reply1_1.message_id}'
)
new_msg = test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, reply2, 'Mail: pseudo no flattening: getting up one level (reply2_1 parent')
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: parent should be a comment')
# no references: new discussion thread started
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.gateway@test.com',
subject='New thread',
extra='References:'
)
new_thread = test_record.message_ids[0]
self.assertFalse(new_thread.parent_id, 'Mail: pseudo no flattening: no parent means new thread')
self.assertEqual(new_thread.subject, 'New thread')
self.assertEqual(new_thread.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: parent should be a comment')
# mixed up references: newer message wins
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.gateway@test.com',
subject='New thread',
extra=f'References: {new_thread.message_id} {reply1_1.message_id}'
)
new_msg = test_record.message_ids[0]
self.assertEqual(new_msg.parent_id, new_thread)
self.assertEqual(new_msg.subtype_id, self.env.ref('mail.mt_comment'), 'Mail: parent should be a comment')
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_references_external(self):
""" Incoming email being a reply to an external email processed by odoo should update thread accordingly """
new_message_id = '<ThisIsTooMuchFake.MonsterEmail.789@agrolait.com>'
self.fake_email.write({
'message_id': new_message_id
})
init_msg_count = len(self.test_record.message_ids)
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'erroneous@test.com',
extra='References: <2233@a.com>\r\n\t<3edss_dsa@b.com> %s' % self.fake_email.message_id)
self.assertEqual(len(self.test_record.message_ids), init_msg_count + 1)
self.assertEqual(self.fake_email.child_ids, self.test_record.message_ids[0])
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_references_external_buggy_message_id(self):
"""
Incoming email being a reply to an external email processed by
odoo should update thread accordingly. Special case when the
external mail service wrongly folds the message_id on several
lines.
"""
new_message_id = '<ThisIsTooMuchFake.MonsterEmail.789@agrolait.com>'
buggy_message_id = new_message_id.replace('MonsterEmail', 'Monster\r\n Email')
self.fake_email.write({
'message_id': new_message_id
})
init_msg_count = len(self.test_record.message_ids)
self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'erroneous@test.com',
extra='References: <2233@a.com>\r\n\t<3edss_dsa@b.com> %s' % buggy_message_id)
self.assertEqual(len(self.test_record.message_ids), init_msg_count + 1)
self.assertEqual(self.fake_email.child_ids, self.test_record.message_ids[0])
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_references_forward(self):
""" Incoming email using references but with alias forward should not go into references destination """
self.env['mail.alias'].create({
'alias_name': 'test.alias',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_contact': 'everyone',
})
init_msg_count = len(self.test_record.message_ids)
res_test = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.alias@test.com',
subject='My Dear Forward', extra='References: <2233@a.com>\r\n\t<3edss_dsa@b.com> %s' % self.fake_email.message_id,
target_model='mail.test.container')
self.assertEqual(len(self.test_record.message_ids), init_msg_count)
self.assertEqual(len(self.fake_email.child_ids), 0)
self.assertEqual(res_test.name, 'My Dear Forward')
self.assertEqual(len(res_test.message_ids), 1)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_references_forward_same_model(self):
""" Incoming email using references but with alias forward on same model should be considered as a reply """
self.env['mail.alias'].create({
'alias_name': 'test.alias',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.gateway').id,
'alias_contact': 'everyone',
})
init_msg_count = len(self.test_record.message_ids)
res_test = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test.alias@test.com',
subject='My Dear Forward', extra='References: <2233@a.com>\r\n\t<3edss_dsa@b.com> %s' % self.fake_email.message_id,
target_model='mail.test.container')
self.assertEqual(len(self.test_record.message_ids), init_msg_count + 1)
self.assertEqual(len(self.fake_email.child_ids), 1)
self.assertFalse(res_test)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_references_forward_cc(self):
""" Incoming email using references but with alias forward in CC should be considered as a repy (To > Cc) """
self.env['mail.alias'].create({
'alias_name': 'test.alias',
'alias_user_id': False,
'alias_model_id': self.env['ir.model']._get('mail.test.container').id,
'alias_contact': 'everyone',
})
init_msg_count = len(self.test_record.message_ids)
res_test = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'catchall.test@test.com', cc='test.alias@test.com',
subject='My Dear Forward', extra='References: <2233@a.com>\r\n\t<3edss_dsa@b.com> %s' % self.fake_email.message_id,
target_model='mail.test.container')
self.assertEqual(len(self.test_record.message_ids), init_msg_count + 1)
self.assertEqual(len(self.fake_email.child_ids), 1)
self.assertFalse(res_test)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_message_process_reply_to_new_thread(self):
""" Test replies not being considered as replies but use destination information instead (aka, mass post + specific reply to using aliases) """
first_record = self.env['mail.test.simple'].with_user(self.user_employee).create({'name': 'Replies to Record'})
record_msg = first_record.message_post(
subject='Discussion',
reply_to_force_new=False,
subtype_xmlid='mail.mt_comment',
)
self.assertEqual(record_msg.reply_to, formataddr(('%s %s' % (self.user_employee.company_id.name, first_record.name), '%s@%s' % ('catchall.test', 'test.com'))))
mail_msg = first_record.message_post(
subject='Replies to Record',
reply_to='groups@test.com',
reply_to_force_new=True,
subtype_xmlid='mail.mt_comment',
)
self.assertEqual(mail_msg.reply_to, 'groups@test.com')
# reply to mail but should be considered as a new mail for alias
msgID = '<this.is.duplicate.test@iron.sky>'
res_test = self.format_and_process(
MAIL_TEMPLATE, self.email_from, record_msg.reply_to, cc='',
subject='Re: Replies to Record', extra='In-Reply-To: %s' % record_msg.message_id,
msg_id=msgID, target_model='mail.test.simple')
incoming_msg = self.env['mail.message'].search([('message_id', '=', msgID)])
self.assertFalse(res_test)
self.assertEqual(incoming_msg.model, 'mail.test.simple')
self.assertEqual(incoming_msg.parent_id, first_record.message_ids[-1])
self.assertTrue(incoming_msg.res_id == first_record.id)
# reply to mail but should be considered as a new mail for alias
msgID = '<this.is.for.testing@iron.sky>'
res_test = self.format_and_process(
MAIL_TEMPLATE, self.email_from, mail_msg.reply_to, cc='',
subject='Re: Replies to Record', extra='In-Reply-To: %s' % mail_msg.message_id,
msg_id=msgID, target_model='mail.test.gateway')
incoming_msg = self.env['mail.message'].search([('message_id', '=', msgID)])
self.assertEqual(len(res_test), 1)
self.assertEqual(res_test.name, 'Re: Replies to Record')
self.assertEqual(incoming_msg.model, 'mail.test.gateway')
self.assertFalse(incoming_msg.parent_id)
self.assertTrue(incoming_msg.res_id == res_test.id)
# --------------------------------------------------
# Gateway / Record synchronization
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_gateway_values_base64_image(self):
"""New record with mail that contains base64 inline image."""
target_model = "mail.test.field.type"
alias = self.env["mail.alias"].create({
"alias_name": "base64-lover",
"alias_model_id": self.env["ir.model"]._get(target_model).id,
"alias_defaults": "{}",
"alias_contact": "everyone",
})
record = self.format_and_process(
test_mail_data.MAIL_TEMPLATE_EXTRA_HTML, self.email_from,
'%s@%s' % (alias.alias_name, self.alias_catchall),
subject='base64 image to alias',
target_model=target_model,
extra_html='<img src="data:image/png;base64,iV/+OkI=">',
)
self.assertEqual(record.type, "first")
self.assertEqual(len(record.message_ids[0].attachment_ids), 1)
self.assertEqual(record.message_ids[0].attachment_ids[0].name, "image0")
self.assertEqual(record.message_ids[0].attachment_ids[0].type, "binary")
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_gateway_values_base64_image_walias(self):
"""New record with mail that contains base64 inline image + default values
coming from alias."""
target_model = "mail.test.field.type"
alias = self.env["mail.alias"].create({
"alias_name": "base64-lover",
"alias_model_id": self.env["ir.model"]._get(target_model).id,
"alias_defaults": "{'type': 'second'}",
"alias_contact": "everyone",
})
record = self.format_and_process(
test_mail_data.MAIL_TEMPLATE_EXTRA_HTML, self.email_from,
'%s@%s' % (alias.alias_name, self.alias_catchall),
subject='base64 image to alias',
target_model=target_model,
extra_html='<img src="data:image/png;base64,iV/+OkI=">',
)
self.assertEqual(record.type, "second")
self.assertEqual(len(record.message_ids[0].attachment_ids), 1)
self.assertEqual(record.message_ids[0].attachment_ids[0].name, "image0")
self.assertEqual(record.message_ids[0].attachment_ids[0].type, "binary")
# --------------------------------------------------
# Thread formation: mail gateway corner cases
# --------------------------------------------------
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_extra_model_res_id(self):
""" Incoming email with ref holding model / res_id but that does not match any message in the thread: must raise since OpenERP saas-3 """
self.assertRaises(ValueError,
self.format_and_process, MAIL_TEMPLATE,
self.partner_1.email_formatted, 'noone@test.com', subject='spam',
extra='In-Reply-To: <12321321-openerp-%d-mail.test.gateway@%s>' % (self.test_record.id, socket.gethostname()))
# when 6.1 messages are present, compat mode is available
# Odoo 10 update: compat mode has been removed and should not work anymore
self.fake_email.write({'message_id': False})
# Do: compat mode accepts partial-matching emails
self.assertRaises(
ValueError,
self.format_and_process, MAIL_TEMPLATE,
self.partner_1.email_formatted, 'noone@test.com>', subject='spam',
extra='In-Reply-To: <12321321-openerp-%d-mail.test.gateway@%s>' % (self.test_record.id, socket.gethostname()))
# Test created messages
self.assertEqual(len(self.test_record.message_ids), 1)
self.assertEqual(len(self.test_record.message_ids[0].child_ids), 0)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_duplicate(self):
""" Duplicate emails (same message_id) are not processed """
self.alias.write({'alias_force_thread_id': self.test_record.id,})
# Post a base message
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Re: super cats', msg_id='<123?456.diff1@agrolait.com>')
self.assertFalse(record)
self.assertEqual(len(self.test_record.message_ids), 2)
# Do: due to some issue, same email goes back into the mailgateway
record = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'groups@test.com', subject='Re: news',
msg_id='<123?456.diff1@agrolait.com>', extra='In-Reply-To: <1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>\n')
self.assertFalse(record)
self.assertEqual(len(self.test_record.message_ids), 2)
# Test: message_id is still unique
no_of_msg = self.env['mail.message'].search_count([('message_id', 'ilike', '<123?456.diff1@agrolait.com>')])
self.assertEqual(no_of_msg, 1,
'message_process: message with already existing message_id should not have been duplicated')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_crash_wrong_model(self):
""" Incoming email with model that does not accepts incoming emails must raise """
self.assertRaises(ValueError,
self.format_and_process,
MAIL_TEMPLATE, self.email_from, 'noone@test.com',
subject='spam', extra='', model='res.country')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_crash_no_data(self):
""" Incoming email without model and without alias must raise """
self.assertRaises(ValueError,
self.format_and_process,
MAIL_TEMPLATE, self.email_from, 'noone@test.com',
subject='spam', extra='')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.models')
def test_message_process_fallback(self):
""" Incoming email with model that accepting incoming emails as fallback """
record = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'noone@test.com',
subject='Spammy', extra='', model='mail.test.gateway')
self.assertEqual(len(record), 1)
self.assertEqual(record.name, 'Spammy')
self.assertEqual(record._name, 'mail.test.gateway')
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_process_file_encoding(self):
""" Incoming email with file encoding """
file_content = 'Hello World'
for encoding in ['', 'UTF-8', 'UTF-16LE', 'UTF-32BE']:
file_content_b64 = base64.b64encode(file_content.encode(encoding or 'utf-8')).decode()
record = self.format_and_process(test_mail_data.MAIL_FILE_ENCODING,
self.email_from, 'groups@test.com',
subject='Test Charset %s' % encoding or 'Unset',
charset='; charset="%s"' % encoding if encoding else '',
content=file_content_b64
)
attachment = record.message_ids.attachment_ids
self.assertEqual(file_content, attachment.raw.decode(encoding or 'utf-8'))
if encoding not in ['', 'UTF-8']:
self.assertNotEqual(file_content, attachment.raw.decode('utf-8'))
# --------------------------------------------------
# Corner cases / Bugs during message process
# --------------------------------------------------
def test_message_process_file_encoding_ascii(self):
""" Incoming email containing an xml attachment with unknown characters (�) but an ASCII charset should not
raise an Exception. UTF-8 is used as a safe fallback.
"""
record = self.format_and_process(test_mail_data.MAIL_MULTIPART_INVALID_ENCODING, self.email_from, 'groups@test.com')
self.assertEqual(record.message_main_attachment_id.name, 'bis3_with_error_encoding_address.xml')
# NB: the xml received by email contains b"Chauss\xef\xbf\xbd\xef\xbf\xbde" with "\xef\xbf\xbd" being the
# replacement character � in UTF-8.
# When calling `_message_parse_extract_payload`, `part.get_content()` will be called on the attachment part of
# the email, triggering the decoding of the base64 attachment, so b"Chauss\xef\xbf\xbd\xef\xbf\xbde" is
# first retrieved. Then, `get_text_content` in `email` tries to decode this using the charset of the email
# part, i.e: `content.decode('us-ascii', errors='replace')`. So the errors are replaced using the Unicode
# replacement marker and the string "Chauss������e" is used to create the attachment.
# This explains the multiple "�" in the attachment.
self.assertIn("Chauss������e de Bruxelles", record.message_main_attachment_id.raw.decode())
def test_message_process_file_omitted_charset(self):
""" For incoming email containing an xml attachment with omitted charset and containing an UTF8 payload we
should parse the attachment using UTF-8.
"""
record = self.format_and_process(test_mail_data.MAIL_MULTIPART_OMITTED_CHARSET, self.email_from, 'groups@test.com')
self.assertEqual(record.message_main_attachment_id.name, 'bis3.xml')
self.assertEqual("<Invoice>Chaussée de Bruxelles</Invoice>", record.message_main_attachment_id.raw.decode())
def test_message_route_reply_model_none(self):
"""
Test the message routing and reply functionality when the model is None.
This test case verifies the behavior of the message routing and reply process
when the 'model' field of a mail.message is set to None. It checks that the
message is correctly processed and associated with the appropriate record.
The code invokes function `format_and_process` to automatically test rounting
and then makes checks on created record.
"""
message = self.env['mail.message'].create({
'body': '<p>test</p>',
'email_from': self.email_from,
'message_type': 'email',
'model': None,
'res_id': None,
})
self.env['mail.alias'].create({'alias_name': 'test', 'alias_model_id': self.env['ir.model']._get('mail.test.gateway').id})
record = self.format_and_process(
MAIL_TEMPLATE, self.email_from, 'test@test.com',
subject=message.message_id, extra=f'In-Reply-To:\r\n\t{message.message_id}\n',
model=None)
self.assertTrue(record)
self.assertEqual(record._name, 'mail.test.gateway')
self.assertEqual(record.message_ids.subject, message.message_id)
self.assertFalse(record.message_ids.parent_id)
class TestMailThreadCC(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestMailThreadCC, cls).setUpClass()
cls.email_from = 'Sylvie Lelitre <test.sylvie.lelitre@agrolait.com>'
cls.alias = cls.env['mail.alias'].create({
'alias_name': 'cc_record',
'alias_user_id': False,
'alias_model_id': cls.env['ir.model']._get('mail.test.cc').id,
'alias_contact': 'everyone'})
cls._init_mail_gateway()
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_cc_new(self):
record = self.format_and_process(MAIL_TEMPLATE, self.email_from, 'cc_record@test.com',
cc='cc1@example.com, cc2@example.com', target_model='mail.test.cc')
cc = email_split_and_format(record.email_cc)
self.assertEqual(sorted(cc), ['cc1@example.com', 'cc2@example.com'])
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_cc_update_with_old(self):
record = self.env['mail.test.cc'].create({'email_cc': 'cc1 <cc1@example.com>, cc2@example.com'})
self.alias.write({'alias_force_thread_id': record.id})
self.format_and_process(MAIL_TEMPLATE, self.email_from, 'cc_record@test.com',
cc='cc2 <cc2@example.com>, cc3@example.com', target_model='mail.test.cc')
cc = email_split_and_format(record.email_cc)
self.assertEqual(sorted(cc), ['"cc1" <cc1@example.com>', 'cc2@example.com', 'cc3@example.com'], 'new cc should have been added on record (unique)')
@mute_logger('odoo.addons.mail.models.mail_thread')
def test_message_cc_update_no_old(self):
record = self.env['mail.test.cc'].create({})
self.alias.write({'alias_force_thread_id': record.id})
self.format_and_process(MAIL_TEMPLATE, self.email_from, 'cc_record@test.com',
cc='cc2 <cc2@example.com>, cc3@example.com', target_model='mail.test.cc')
cc = email_split_and_format(record.email_cc)
self.assertEqual(sorted(cc), ['"cc2" <cc2@example.com>', 'cc3@example.com'], 'new cc should have been added on record (unique)')
| 54.881579
| 87,591
|
34,304
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from freezegun import freeze_time
from unittest.mock import patch
from unittest.mock import DEFAULT
import pytz
from odoo import fields, exceptions, tests
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.addons.test_mail.models.test_mail_models import MailTestActivity
from odoo.tools import mute_logger
from odoo.tests.common import Form, users
class TestActivityCommon(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestActivityCommon, cls).setUpClass()
cls.test_record = cls.env['mail.test.activity'].with_context(cls._test_context).create({'name': 'Test'})
# reset ctx
cls._reset_mail_context(cls.test_record)
@tests.tagged('mail_activity')
class TestActivityRights(TestActivityCommon):
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_security_user_access_other(self):
activity = self.test_record.with_user(self.user_employee).activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_admin.id)
self.assertTrue(activity.can_write)
activity.write({'user_id': self.user_employee.id})
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_security_user_access_own(self):
activity = self.test_record.with_user(self.user_employee).activity_schedule(
'test_mail.mail_act_test_todo')
self.assertTrue(activity.can_write)
activity.write({'user_id': self.user_admin.id})
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_security_user_noaccess_automated(self):
def _employee_crash(*args, **kwargs):
""" If employee is test employee, consider he has no access on document """
recordset = args[0]
if recordset.env.uid == self.user_employee.id:
raise exceptions.AccessError('Hop hop hop Ernest, please step back.')
return DEFAULT
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
activity = self.test_record.activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_employee.id)
activity2 = self.test_record.activity_schedule('test_mail.mail_act_test_todo')
activity2.write({'user_id': self.user_employee.id})
def test_activity_security_user_noaccess_manual(self):
def _employee_crash(*args, **kwargs):
""" If employee is test employee, consider he has no access on document """
recordset = args[0]
if recordset.env.uid == self.user_employee.id:
raise exceptions.AccessError('Hop hop hop Ernest, please step back.')
return DEFAULT
test_activity = self.env['mail.activity'].with_user(self.user_admin).create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_todo').id,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': self.test_record.id,
'user_id': self.user_admin.id,
'summary': 'Summary',
})
# can _search activities if access to the document
self.env['mail.activity'].with_user(self.user_employee)._search(
[('id', '=', test_activity.id)], count=False)
# cannot _search activities if no access to the document
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.AccessError):
searched_activity = self.env['mail.activity'].with_user(self.user_employee)._search(
[('id', '=', test_activity.id)], count=False)
# can read_group activities if access to the document
read_group_result = self.env['mail.activity'].with_user(self.user_employee).read_group(
[('id', '=', test_activity.id)],
['summary'],
['summary'],
)
self.assertEqual(1, read_group_result[0]['summary_count'])
self.assertEqual('Summary', read_group_result[0]['summary'])
# cannot read_group activities if no access to the document
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.AccessError):
self.env['mail.activity'].with_user(self.user_employee).read_group(
[('id', '=', test_activity.id)],
['summary'],
['summary'],
)
# cannot read activities if no access to the document
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.AccessError):
searched_activity = self.env['mail.activity'].with_user(self.user_employee).search(
[('id', '=', test_activity.id)])
searched_activity.read(['summary'])
# cannot search_read activities if no access to the document
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.AccessError):
self.env['mail.activity'].with_user(self.user_employee).search_read(
[('id', '=', test_activity.id)],
['summary'])
# cannot create activities for people that cannot access record
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.UserError):
activity = self.env['mail.activity'].create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_todo').id,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': self.test_record.id,
'user_id': self.user_employee.id,
})
# cannot create activities if no access to the document
with patch.object(MailTestActivity, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.AccessError):
activity = self.test_record.with_user(self.user_employee).activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_admin.id)
@tests.tagged('mail_activity')
class TestActivityFlow(TestActivityCommon):
def test_activity_flow_employee(self):
with self.with_user('employee'):
test_record = self.env['mail.test.activity'].browse(self.test_record.id)
self.assertEqual(test_record.activity_ids, self.env['mail.activity'])
# employee record an activity and check the deadline
self.env['mail.activity'].create({
'summary': 'Test Activity',
'date_deadline': date.today() + relativedelta(days=1),
'activity_type_id': self.env.ref('mail.mail_activity_data_email').id,
'res_model_id': self.env['ir.model']._get(test_record._name).id,
'res_id': test_record.id,
})
self.assertEqual(test_record.activity_summary, 'Test Activity')
self.assertEqual(test_record.activity_state, 'planned')
test_record.activity_ids.write({'date_deadline': date.today() - relativedelta(days=1)})
test_record.invalidate_cache() # TDE note: should not have to do it I think
self.assertEqual(test_record.activity_state, 'overdue')
test_record.activity_ids.write({'date_deadline': date.today()})
test_record.invalidate_cache() # TDE note: should not have to do it I think
self.assertEqual(test_record.activity_state, 'today')
# activity is done
test_record.activity_ids.action_feedback(feedback='So much feedback')
self.assertEqual(test_record.activity_ids, self.env['mail.activity'])
self.assertEqual(test_record.message_ids[0].subtype_id, self.env.ref('mail.mt_activities'))
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_notify_other_user(self):
self.user_admin.notification_type = 'email'
rec = self.test_record.with_user(self.user_employee)
with self.assertSinglePostNotifications(
[{'partner': self.partner_admin, 'type': 'email'}],
message_info={'content': 'assigned you an activity', 'subtype': 'mail.mt_note', 'message_type': 'user_notification'}):
activity = rec.activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_admin.id)
self.assertEqual(activity.create_uid, self.user_employee)
self.assertEqual(activity.user_id, self.user_admin)
def test_activity_notify_same_user(self):
self.user_employee.notification_type = 'email'
rec = self.test_record.with_user(self.user_employee)
with self.assertNoNotifications():
activity = rec.activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_employee.id)
self.assertEqual(activity.create_uid, self.user_employee)
self.assertEqual(activity.user_id, self.user_employee)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_dont_notify_no_user_change(self):
self.user_employee.notification_type = 'email'
activity = self.test_record.activity_schedule('test_mail.mail_act_test_todo', user_id=self.user_employee.id)
with self.assertNoNotifications():
activity.with_user(self.user_admin).write({'user_id': self.user_employee.id})
self.assertEqual(activity.user_id, self.user_employee)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_summary_sync(self):
""" Test summary from type is copied on activities if set (currently only in form-based onchange) """
ActivityType = self.env['mail.activity.type']
email_activity_type = ActivityType.create({
'name': 'email',
'summary': 'Email Summary',
})
call_activity_type = ActivityType.create({'name': 'call'})
with Form(self.env['mail.activity'].with_context(default_res_model_id=self.env.ref('base.model_res_partner'))) as ActivityForm:
ActivityForm.res_model_id = self.env.ref('base.model_res_partner')
ActivityForm.activity_type_id = call_activity_type
# activity summary should be empty
self.assertEqual(ActivityForm.summary, False)
ActivityForm.activity_type_id = email_activity_type
# activity summary should be replaced with email's default summary
self.assertEqual(ActivityForm.summary, email_activity_type.summary)
ActivityForm.activity_type_id = call_activity_type
# activity summary remains unchanged from change of activity type as call activity doesn't have default summary
self.assertEqual(ActivityForm.summary, email_activity_type.summary)
@tests.tagged('mail_activity')
class TestActivityMixin(TestActivityCommon):
@classmethod
def setUpClass(cls):
super(TestActivityMixin, cls).setUpClass()
cls.user_utc = mail_new_test_user(
cls.env,
name='User UTC',
login='User UTC',
)
cls.user_utc.tz = 'UTC'
cls.user_australia = mail_new_test_user(
cls.env,
name='user Australia',
login='user Australia',
)
cls.user_australia.tz = 'Australia/ACT'
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_mixin(self):
self.user_employee.tz = self.user_admin.tz
with self.with_user('employee'):
self.test_record = self.env['mail.test.activity'].browse(self.test_record.id)
self.assertEqual(self.test_record.env.user, self.user_employee)
now_utc = datetime.now(pytz.UTC)
now_user = now_utc.astimezone(pytz.timezone(self.env.user.tz or 'UTC'))
today_user = now_user.date()
# Test various scheduling of activities
act1 = self.test_record.activity_schedule(
'test_mail.mail_act_test_todo',
today_user + relativedelta(days=1),
user_id=self.user_admin.id)
self.assertEqual(act1.automated, True)
act_type = self.env.ref('test_mail.mail_act_test_todo')
self.assertEqual(self.test_record.activity_summary, act_type.summary)
self.assertEqual(self.test_record.activity_state, 'planned')
self.assertEqual(self.test_record.activity_user_id, self.user_admin)
act2 = self.test_record.activity_schedule(
'test_mail.mail_act_test_meeting',
today_user + relativedelta(days=-1))
self.assertEqual(self.test_record.activity_state, 'overdue')
# `activity_user_id` is defined as `fields.Many2one('res.users', 'Responsible User', related='activity_ids.user_id')`
# it therefore relies on the natural order of `activity_ids`, according to which activity comes first.
# As we just created the activity, its not yet in the right order.
# We force it by invalidating it so it gets fetched from database, in the right order.
self.test_record.invalidate_cache(['activity_ids'])
self.assertEqual(self.test_record.activity_user_id, self.user_employee)
act3 = self.test_record.activity_schedule(
'test_mail.mail_act_test_todo',
today_user + relativedelta(days=3),
user_id=self.user_employee.id)
self.assertEqual(self.test_record.activity_state, 'overdue')
# `activity_user_id` is defined as `fields.Many2one('res.users', 'Responsible User', related='activity_ids.user_id')`
# it therefore relies on the natural order of `activity_ids`, according to which activity comes first.
# As we just created the activity, its not yet in the right order.
# We force it by invalidating it so it gets fetched from database, in the right order.
self.test_record.invalidate_cache(['activity_ids'])
self.assertEqual(self.test_record.activity_user_id, self.user_employee)
self.test_record.invalidate_cache(ids=self.test_record.ids)
self.assertEqual(self.test_record.activity_ids, act1 | act2 | act3)
# Perform todo activities for admin
self.test_record.activity_feedback(
['test_mail.mail_act_test_todo'],
user_id=self.user_admin.id,
feedback='Test feedback',)
self.assertEqual(self.test_record.activity_ids, act2 | act3)
# Reschedule all activities, should update the record state
self.assertEqual(self.test_record.activity_state, 'overdue')
self.test_record.activity_reschedule(
['test_mail.mail_act_test_meeting', 'test_mail.mail_act_test_todo'],
date_deadline=today_user + relativedelta(days=3)
)
self.assertEqual(self.test_record.activity_state, 'planned')
# Perform todo activities for remaining people
self.test_record.activity_feedback(
['test_mail.mail_act_test_todo'],
feedback='Test feedback')
# Setting activities as done should delete them and post messages
self.assertEqual(self.test_record.activity_ids, act2)
self.assertEqual(len(self.test_record.message_ids), 2)
self.assertEqual(self.test_record.message_ids.mapped('subtype_id'), self.env.ref('mail.mt_activities'))
# Perform meeting activities
self.test_record.activity_unlink(['test_mail.mail_act_test_meeting'])
# Canceling activities should simply remove them
self.assertEqual(self.test_record.activity_ids, self.env['mail.activity'])
self.assertEqual(len(self.test_record.message_ids), 2)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_mixin_archive(self):
rec = self.test_record.with_user(self.user_employee)
new_act = rec.activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_admin.id)
self.assertEqual(rec.activity_ids, new_act)
rec.toggle_active()
self.assertEqual(rec.active, False)
self.assertEqual(rec.activity_ids, self.env['mail.activity'])
rec.toggle_active()
self.assertEqual(rec.active, True)
self.assertEqual(rec.activity_ids, self.env['mail.activity'])
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_activity_mixin_reschedule_user(self):
rec = self.test_record.with_user(self.user_employee)
rec.activity_schedule(
'test_mail.mail_act_test_todo',
user_id=self.user_admin.id)
self.assertEqual(rec.activity_ids[0].user_id, self.user_admin)
# reschedule its own should not alter other's activities
rec.activity_reschedule(
['test_mail.mail_act_test_todo'],
user_id=self.user_employee.id,
new_user_id=self.user_employee.id)
self.assertEqual(rec.activity_ids[0].user_id, self.user_admin)
rec.activity_reschedule(
['test_mail.mail_act_test_todo'],
user_id=self.user_admin.id,
new_user_id=self.user_employee.id)
self.assertEqual(rec.activity_ids[0].user_id, self.user_employee)
@users('employee')
def test_feedback_w_attachments(self):
test_record = self.env['mail.test.activity'].browse(self.test_record.ids)
activity = self.env['mail.activity'].create({
'activity_type_id': 1,
'res_id': test_record.id,
'res_model_id': self.env['ir.model']._get_id('mail.test.activity'),
'summary': 'Test',
})
attachments = self.env['ir.attachment'].create([{
'name': 'test',
'res_name': 'test',
'res_model': 'mail.activity',
'res_id': activity.id,
'datas': 'test',
}, {
'name': 'test2',
'res_name': 'test',
'res_model': 'mail.activity',
'res_id': activity.id,
'datas': 'testtest',
}])
# Checking if the attachment has been forwarded to the message
# when marking an activity as "Done"
activity.action_feedback()
activity_message = test_record.message_ids[-1]
self.assertEqual(set(activity_message.attachment_ids.ids), set(attachments.ids))
for attachment in attachments:
self.assertEqual(attachment.res_id, activity_message.id)
self.assertEqual(attachment.res_model, activity_message._name)
@users('employee')
def test_feedback_chained_current_date(self):
frozen_now = datetime(2021, 10, 10, 14, 30, 15)
test_record = self.env['mail.test.activity'].browse(self.test_record.ids)
first_activity = self.env['mail.activity'].create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_chained_1').id,
'date_deadline': frozen_now + relativedelta(days=-2),
'res_id': test_record.id,
'res_model_id': self.env['ir.model']._get_id('mail.test.activity'),
'summary': 'Test',
})
first_activity_id = first_activity.id
with freeze_time(frozen_now):
first_activity.action_feedback(feedback='Done')
self.assertFalse(first_activity.exists())
# check chained activity
new_activity = test_record.activity_ids
self.assertNotEqual(new_activity.id, first_activity_id)
self.assertEqual(new_activity.summary, 'Take the second step.')
self.assertEqual(new_activity.date_deadline, frozen_now.date() + relativedelta(days=10))
@users('employee')
def test_feedback_chained_previous(self):
self.env.ref('test_mail.mail_act_test_chained_2').sudo().write({'delay_from': 'previous_activity'})
frozen_now = datetime(2021, 10, 10, 14, 30, 15)
test_record = self.env['mail.test.activity'].browse(self.test_record.ids)
first_activity = self.env['mail.activity'].create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_chained_1').id,
'date_deadline': frozen_now + relativedelta(days=-2),
'res_id': test_record.id,
'res_model_id': self.env['ir.model']._get_id('mail.test.activity'),
'summary': 'Test',
})
first_activity_id = first_activity.id
with freeze_time(frozen_now):
first_activity.action_feedback(feedback='Done')
self.assertFalse(first_activity.exists())
# check chained activity
new_activity = test_record.activity_ids
self.assertNotEqual(new_activity.id, first_activity_id)
self.assertEqual(new_activity.summary, 'Take the second step.')
self.assertEqual(new_activity.date_deadline, frozen_now.date() + relativedelta(days=8),
'New deadline should take into account original activity deadline, not current date')
def test_mail_activity_state(self):
"""Create 3 activity for 2 different users in 2 different timezones.
User UTC (+0h)
User Australia (+11h)
Today datetime: 1/1/2020 16h
Activity 1 & User UTC
1/1/2020 - 16h UTC -> The state is today
Activity 2 & User Australia
1/1/2020 - 16h UTC
2/1/2020 - 1h Australia -> State is overdue
Activity 3 & User UTC
1/1/2020 - 23h UTC -> The state is today
"""
today_utc = datetime(2020, 1, 1, 16, 0, 0)
class MockedDatetime(datetime):
@classmethod
def utcnow(cls):
return today_utc
record = self.env['mail.test.activity'].create({'name': 'Record'})
with patch('odoo.addons.mail.models.mail_activity.datetime', MockedDatetime):
activity_1 = self.env['mail.activity'].create({
'summary': 'Test',
'activity_type_id': 1,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': record.id,
'date_deadline': today_utc,
'user_id': self.user_utc.id,
})
activity_2 = activity_1.copy()
activity_2.user_id = self.user_australia
activity_3 = activity_1.copy()
activity_3.date_deadline += relativedelta(hours=7)
self.assertEqual(activity_1.state, 'today')
self.assertEqual(activity_2.state, 'overdue')
self.assertEqual(activity_3.state, 'today')
def test_mail_activity_mixin_search_state_basic(self):
"""Test the search method on the "activity_state".
Test all the operators and also test the case where the "activity_state" is
different because of the timezone. There's also a tricky case for which we
"reverse" the domain for performance purpose.
"""
today_utc = datetime(2020, 1, 1, 16, 0, 0)
class MockedDatetime(datetime):
@classmethod
def utcnow(cls):
return today_utc
# Create some records without activity schedule on it for testing
self.env['mail.test.activity'].create([
{'name': 'Record %i' % record_i}
for record_i in range(5)
])
origin_1, origin_2 = self.env['mail.test.activity'].search([], limit=2)
with patch('odoo.addons.mail.models.mail_activity.datetime', MockedDatetime), \
patch('odoo.addons.mail.models.mail_activity_mixin.datetime', MockedDatetime):
origin_1_activity_1 = self.env['mail.activity'].create({
'summary': 'Test',
'activity_type_id': 1,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': origin_1.id,
'date_deadline': today_utc,
'user_id': self.user_utc.id,
})
origin_1_activity_2 = origin_1_activity_1.copy()
origin_1_activity_2.user_id = self.user_australia
origin_1_activity_3 = origin_1_activity_1.copy()
origin_1_activity_3.date_deadline += relativedelta(hours=8)
self.assertEqual(origin_1_activity_1.state, 'today')
self.assertEqual(origin_1_activity_2.state, 'overdue')
self.assertEqual(origin_1_activity_3.state, 'today')
origin_2_activity_1 = self.env['mail.activity'].create({
'summary': 'Test',
'activity_type_id': 1,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': origin_2.id,
'date_deadline': today_utc + relativedelta(hours=8),
'user_id': self.user_utc.id,
})
origin_2_activity_2 = origin_2_activity_1.copy()
origin_2_activity_2.user_id = self.user_australia
origin_2_activity_3 = origin_2_activity_1.copy()
origin_2_activity_3.date_deadline -= relativedelta(hours=8)
origin_2_activity_4 = origin_2_activity_1.copy()
origin_2_activity_4.date_deadline = datetime(2020, 1, 2, 0, 0, 0)
self.assertEqual(origin_2_activity_1.state, 'planned')
self.assertEqual(origin_2_activity_2.state, 'today')
self.assertEqual(origin_2_activity_3.state, 'today')
self.assertEqual(origin_2_activity_4.state, 'planned')
all_activity_mixin_record = self.env['mail.test.activity'].search([])
result = self.env['mail.test.activity'].search([('activity_state', '=', 'today')])
self.assertTrue(len(result) > 0)
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: p.activity_state == 'today'))
result = self.env['mail.test.activity'].search([('activity_state', 'in', ('today', 'overdue'))])
self.assertTrue(len(result) > 0)
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: p.activity_state in ('today', 'overdue')))
result = self.env['mail.test.activity'].search([('activity_state', 'not in', ('today',))])
self.assertTrue(len(result) > 0)
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: p.activity_state not in ('today',)))
result = self.env['mail.test.activity'].search([('activity_state', '=', False)])
self.assertTrue(len(result) >= 3, "There is more than 3 records without an activity schedule on it")
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: not p.activity_state))
result = self.env['mail.test.activity'].search([('activity_state', 'not in', ('planned', 'overdue', 'today'))])
self.assertTrue(len(result) >= 3, "There is more than 3 records without an activity schedule on it")
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: not p.activity_state))
# test tricky case when the domain will be reversed in the search method
# because of falsy value
result = self.env['mail.test.activity'].search([('activity_state', 'not in', ('today', False))])
self.assertTrue(len(result) > 0)
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: p.activity_state not in ('today', False)))
result = self.env['mail.test.activity'].search([('activity_state', 'in', ('today', False))])
self.assertTrue(len(result) > 0)
self.assertEqual(result, all_activity_mixin_record.filtered(lambda p: p.activity_state in ('today', False)))
def test_mail_activity_mixin_search_state_different_day_but_close_time(self):
"""Test the case where there's less than 24 hours between the deadline and now_tz,
but one day of difference (e.g. 23h 01/01/2020 & 1h 02/02/2020). So the state
should be "planned" and not "today". This case was tricky to implement in SQL
that's why it has its own test.
"""
today_utc = datetime(2020, 1, 1, 23, 0, 0)
class MockedDatetime(datetime):
@classmethod
def utcnow(cls):
return today_utc
# Create some records without activity schedule on it for testing
self.env['mail.test.activity'].create([
{'name': 'Record %i' % record_i}
for record_i in range(5)
])
origin_1 = self.env['mail.test.activity'].search([], limit=1)
with patch('odoo.addons.mail.models.mail_activity.datetime', MockedDatetime):
origin_1_activity_1 = self.env['mail.activity'].create({
'summary': 'Test',
'activity_type_id': 1,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': origin_1.id,
'date_deadline': today_utc + relativedelta(hours=2),
'user_id': self.user_utc.id,
})
self.assertEqual(origin_1_activity_1.state, 'planned')
result = self.env['mail.test.activity'].search([('activity_state', '=', 'today')])
self.assertNotIn(origin_1, result, 'The activity state miss calculated during the search')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_my_activity_flow_employee(self):
Activity = self.env['mail.activity']
date_today = date.today()
Activity.create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_todo').id,
'date_deadline': date_today,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': self.test_record.id,
'user_id': self.user_admin.id,
})
Activity.create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_call').id,
'date_deadline': date_today + relativedelta(days=1),
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': self.test_record.id,
'user_id': self.user_employee.id,
})
test_record_1 = self.env['mail.test.activity'].with_context(self._test_context).create({'name': 'Test 1'})
Activity.create({
'activity_type_id': self.env.ref('test_mail.mail_act_test_todo').id,
'date_deadline': date_today,
'res_model_id': self.env.ref('test_mail.model_mail_test_activity').id,
'res_id': test_record_1.id,
'user_id': self.user_employee.id,
})
with self.with_user('employee'):
record = self.env['mail.test.activity'].search([('my_activity_date_deadline', '=', date_today)])
self.assertEqual(test_record_1, record)
class TestReadProgressBar(tests.TransactionCase):
"""Test for read_progress_bar"""
def test_week_grouping(self):
"""The labels associated to each record in read_progress_bar should match
the ones from read_group, even in edge cases like en_US locale on sundays
"""
model = self.env['mail.test.activity'].with_context(lang='en_US')
# Don't mistake fields date and date_deadline:
# * date is just a random value
# * date_deadline defines activity_state
model.create({
'date': '2021-05-02',
'name': "Yesterday, all my troubles seemed so far away",
}).activity_schedule(
'test_mail.mail_act_test_todo',
summary="Make another test super asap (yesterday)",
date_deadline=fields.Date.context_today(model) - timedelta(days=7),
)
model.create({
'date': '2021-05-09',
'name': "Things we said today",
}).activity_schedule(
'test_mail.mail_act_test_todo',
summary="Make another test asap",
date_deadline=fields.Date.context_today(model),
)
model.create({
'date': '2021-05-16',
'name': "Tomorrow Never Knows",
}).activity_schedule(
'test_mail.mail_act_test_todo',
summary="Make a test tomorrow",
date_deadline=fields.Date.context_today(model) + timedelta(days=7),
)
domain = [('date', "!=", False)]
groupby = "date:week"
progress_bar = {
'field': 'activity_state',
'colors': {
"overdue": 'danger',
"today": 'warning',
"planned": 'success',
}
}
# call read_group to compute group names
groups = model.read_group(domain, fields=['date'], groupby=[groupby])
progressbars = model.read_progress_bar(domain, group_by=groupby, progress_bar=progress_bar)
self.assertEqual(len(groups), 3)
self.assertEqual(len(progressbars), 3)
# format the read_progress_bar result to get a dictionary under this
# format: {activity_state: group_name}; the original format
# (after read_progress_bar) is {group_name: {activity_state: count}}
pg_groups = {
next(state for state, count in data.items() if count): group_name
for group_name, data in progressbars.items()
}
self.assertEqual(groups[0][groupby], pg_groups["overdue"])
self.assertEqual(groups[1][groupby], pg_groups["today"])
self.assertEqual(groups[2][groupby], pg_groups["planned"])
| 47.644444
| 34,304
|
43,929
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo.addons.base.tests.common import TransactionCaseWithUserDemo
from odoo.tests.common import users, warmup
from odoo.tests import tagged
from odoo.tools import mute_logger, formataddr
@tagged('mail_performance', 'post_install', '-at_install')
class BaseMailPerformance(TransactionCaseWithUserDemo):
def setUp(self):
super(BaseMailPerformance, self).setUp()
self._quick_create_ctx = {
'no_reset_password': True,
'mail_create_nolog': True,
'mail_create_nosubscribe': True,
'mail_notrack': True,
'mail_channel_nosubscribe': True,
}
self.user_employee = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'Ernest Employee',
'login': 'emp',
'email': 'e.e@example.com',
'signature': '--\nErnest',
'notification_type': 'inbox',
'groups_id': [(6, 0, [self.env.ref('base.group_user').id, self.env.ref('base.group_partner_manager').id])],
})
# patch registry to simulate a ready environment
self.patch(self.env.registry, 'ready', True)
def _init_mail_gateway(self):
# setup mail gateway
self.alias_domain = 'example.com'
self.alias_catchall = 'catchall.test'
self.alias_bounce = 'bounce.test'
self.default_from = 'notifications'
self.env['ir.config_parameter'].set_param('mail.bounce.alias', self.alias_bounce)
self.env['ir.config_parameter'].set_param('mail.catchall.domain', self.alias_domain)
self.env['ir.config_parameter'].set_param('mail.catchall.alias', self.alias_catchall)
self.env['ir.config_parameter'].set_param('mail.default.from', self.default_from)
@tagged('mail_performance', 'post_install', '-at_install')
class TestBaseMailPerformance(BaseMailPerformance):
def setUp(self):
super(TestBaseMailPerformance, self).setUp()
self.res_partner_3 = self.env['res.partner'].create({
'name': 'Gemini Furniture',
'email': 'gemini.furniture39@example.com',
})
self.res_partner_4 = self.env['res.partner'].create({
'name': 'Ready Mat',
'email': 'ready.mat28@example.com',
})
self.res_partner_10 = self.env['res.partner'].create({
'name': 'The Jackson Group',
'email': 'jackson.group82@example.com',
})
self.res_partner_12 = self.env['res.partner'].create({
'name': 'Azure Interior',
'email': 'azure.Interior24@example.com',
})
self.env['mail.performance.thread'].create([
{
'name': 'Object 0',
'value': 0,
'partner_id': self.res_partner_3.id,
}, {
'name': 'Object 1',
'value': 10,
'partner_id': self.res_partner_3.id,
}, {
'name': 'Object 2',
'value': 20,
'partner_id': self.res_partner_4.id,
}, {
'name': 'Object 3',
'value': 30,
'partner_id': self.res_partner_10.id,
}, {
'name': 'Object 4',
'value': 40,
'partner_id': self.res_partner_12.id,
}
])
self._init_mail_gateway()
@users('__system__', 'demo')
@warmup
def test_read_mail(self):
""" Read records inheriting from 'mail.thread'. """
records = self.env['mail.performance.thread'].search([])
self.assertEqual(len(records), 5)
with self.assertQueryCount(__system__=2, demo=2):
# without cache
for record in records:
record.partner_id.country_id.name
with self.assertQueryCount(0):
# with cache
for record in records:
record.partner_id.country_id.name
with self.assertQueryCount(0):
# value_pc must have been prefetched, too
for record in records:
record.value_pc
@users('__system__', 'demo')
@warmup
def test_write_mail(self):
""" Write records inheriting from 'mail.thread' (no recomputation). """
records = self.env['mail.performance.thread'].search([])
self.assertEqual(len(records), 5)
with self.assertQueryCount(__system__=2, demo=2):
records.write({'name': 'X'})
@users('__system__', 'demo')
@warmup
def test_write_mail_with_recomputation(self):
""" Write records inheriting from 'mail.thread' (with recomputation). """
records = self.env['mail.performance.thread'].search([])
self.assertEqual(len(records), 5)
with self.assertQueryCount(__system__=2, demo=2):
records.write({'value': 42})
@users('__system__', 'demo')
@warmup
def test_write_mail_with_tracking(self):
""" Write records inheriting from 'mail.thread' (with field tracking). """
record = self.env['mail.performance.thread'].create({
'name': 'Test',
'track': 'Y',
'value': 40,
'partner_id': self.res_partner_12.id,
})
with self.assertQueryCount(__system__=3, demo=3):
record.track = 'X'
@users('__system__', 'demo')
@warmup
def test_create_mail(self):
""" Create records inheriting from 'mail.thread' (without field tracking). """
model = self.env['mail.performance.thread']
with self.assertQueryCount(__system__=2, demo=2):
model.with_context(tracking_disable=True).create({'name': 'X'})
@users('__system__', 'demo')
@warmup
def test_create_mail_with_tracking(self):
""" Create records inheriting from 'mail.thread' (with field tracking). """
with self.assertQueryCount(__system__=8, demo=8):
self.env['mail.performance.thread'].create({'name': 'X'})
@users('__system__', 'emp')
@warmup
def test_create_mail_simple(self):
with self.assertQueryCount(__system__=7, emp=7):
self.env['mail.test.simple'].create({'name': 'Test'})
@users('__system__', 'emp')
@warmup
def test_write_mail_simple(self):
rec = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=1, emp=1):
rec.write({
'name': 'Test2',
'email_from': 'test@test.com',
})
@tagged('mail_performance', 'post_install', '-at_install')
class TestMailAPIPerformance(BaseMailPerformance):
def setUp(self):
super(TestMailAPIPerformance, self).setUp()
self.customer = self.env['res.partner'].with_context(self._quick_create_ctx).create({
'name': 'Test Customer',
'email': 'customer.test@example.com',
})
self.user_test = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'Paulette Testouille',
'login': 'paul',
'email': 'user.test.paulette@example.com',
'notification_type': 'inbox',
'groups_id': [(6, 0, [self.env.ref('base.group_user').id])],
})
self._init_mail_gateway()
# automatically follow activities, for backward compatibility concerning query count
self.env.ref('mail.mt_activities').write({'default': True})
def _create_test_records(self):
self.test_record_full = self.env['mail.test.ticket'].with_context(self._quick_create_ctx).create({
'name': 'TestRecord',
'customer_id': self.customer.id,
'user_id': self.user_test.id,
'email_from': 'nopartner.test@example.com',
})
self.test_template_full = self.env['mail.template'].create({
'name': 'TestTemplate',
'model_id': self.env['ir.model']._get('mail.test.ticket').id,
'subject': 'About {{ object.name }}',
'body_html': '<p>Hello <t t-out="object.name"/></p>',
'email_from': '{{ object.user_id.email_formatted }}',
'partner_to': '{{ object.customer_id.id }}',
'email_to': '{{ ("%s Customer <%s>" % (object.name, object.email_from)) }}',
})
@users('__system__', 'emp')
@warmup
def test_adv_activity(self):
model = self.env['mail.test.activity']
with self.assertQueryCount(__system__=7, emp=7):
model.create({'name': 'Test'})
@users('__system__', 'emp')
@warmup
@mute_logger('odoo.models.unlink')
def test_adv_activity_full(self):
record = self.env['mail.test.activity'].create({'name': 'Test'})
MailActivity = self.env['mail.activity'].with_context({
'default_res_model': 'mail.test.activity',
})
with self.assertQueryCount(__system__=6, emp=6):
activity = MailActivity.create({
'summary': 'Test Activity',
'res_id': record.id,
'activity_type_id': self.env.ref('mail.mail_activity_data_todo').id,
})
#read activity_type to normalize cache between enterprise and community
#voip module read activity_type during create leading to one less query in enterprise on action_feedback
category = activity.activity_type_id.category
with self.assertQueryCount(__system__=19, emp=21): # tm 17/19 - com 18/20
activity.action_feedback(feedback='Zizisse Done !')
@users('__system__', 'emp')
@warmup
@mute_logger('odoo.models.unlink')
def test_adv_activity_mixin(self):
record = self.env['mail.test.activity'].create({'name': 'Test'})
with self.assertQueryCount(__system__=8, emp=8):
activity = record.action_start('Test Start')
#read activity_type to normalize cache between enterprise and community
#voip module read activity_type during create leading to one less query in enterprise on action_close
category = activity.activity_type_id.category
record.write({'name': 'Dupe write'})
with self.assertQueryCount(__system__=20, emp=23): # tm 18/21 - com 19/22
record.action_close('Dupe feedback')
self.assertEqual(record.activity_ids, self.env['mail.activity'])
@users('__system__', 'emp')
@warmup
@mute_logger('odoo.models.unlink', 'odoo.tests', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer(self):
self._create_test_records()
test_record = self.env['mail.test.ticket'].browse(self.test_record_full.id)
customer_id = self.customer.id
with self.assertQueryCount(__system__=2, emp=2):
composer = self.env['mail.compose.message'].with_context({
'default_composition_mode': 'comment',
'default_model': test_record._name,
'default_res_id': test_record.id,
}).create({
'body': '<p>Test Body</p>',
'partner_ids': [(4, customer_id)],
})
with self.assertQueryCount(__system__=35, emp=41): # tm 33/39
composer._action_send_mail()
@users('__system__', 'emp')
@warmup
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_nodelete(self):
self._create_test_records()
test_record = self.env['mail.test.ticket'].browse(self.test_record_full.id)
customer_id = self.customer.id
with self.assertQueryCount(__system__=2, emp=2):
composer = self.env['mail.compose.message'].with_context({
'default_composition_mode': 'comment',
'default_model': test_record._name,
'default_res_id': test_record.id,
'mail_auto_delete': False,
}).create({
'body': '<p>Test Body</p>',
'partner_ids': [(4, customer_id)],
})
with self.assertQueryCount(__system__=28, emp=34): # tm 26/32
composer._action_send_mail()
@users('__system__', 'emp')
@warmup
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_mail_composer_w_template(self):
self._create_test_records()
test_record = self.env['mail.test.ticket'].browse(self.test_record_full.id)
test_template = self.env['mail.template'].browse(self.test_template_full.id)
with self.assertQueryCount(__system__=25, emp=26): # tm 13/14
composer = self.env['mail.compose.message'].with_context({
'default_composition_mode': 'comment',
'default_model': test_record._name,
'default_res_id': test_record.id,
'default_template_id': test_template.id,
}).create({})
composer._onchange_template_id_wrapper()
with self.assertQueryCount(__system__=35, emp=41): # tm 33/39
composer._action_send_mail()
# remove created partner to ensure tests are the same each run
self.env['res.partner'].sudo().search([('email', '=', 'nopartner.test@example.com')]).unlink()
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_message_assignation_email(self):
self.user_test.write({'notification_type': 'email'})
record = self.env['mail.test.track'].create({'name': 'Test'})
with self.assertQueryCount(__system__=41, emp=42): # tm 38/39
record.write({
'user_id': self.user_test.id,
})
@users('__system__', 'emp')
@warmup
def test_message_assignation_inbox(self):
record = self.env['mail.test.track'].create({'name': 'Test'})
with self.assertQueryCount(__system__=19, emp=21): # tm 18/20
record.write({
'user_id': self.user_test.id,
})
@users('__system__', 'emp')
@warmup
def test_message_log(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=1, emp=1):
record._message_log(
body='<p>Test _message_log</p>',
message_type='comment')
@users('__system__', 'emp')
@warmup
def test_message_log_with_post(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=4, emp=7):
record.message_post(
body='<p>Test message_post as log</p>',
subtype_xmlid='mail.mt_note',
message_type='comment')
@users('__system__', 'emp')
@warmup
def test_message_post_no_notification(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=4, emp=7):
record.message_post(
body='<p>Test Post Performances basic</p>',
partner_ids=[],
message_type='comment',
subtype_xmlid='mail.mt_comment')
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_message_post_one_email_notification(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=31, emp=34): # tm 29/32
record.message_post(
body='<p>Test Post Performances with an email ping</p>',
partner_ids=self.customer.ids,
message_type='comment',
subtype_xmlid='mail.mt_comment')
@users('__system__', 'emp')
@warmup
def test_message_post_one_inbox_notification(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=14, emp=18):
record.message_post(
body='<p>Test Post Performances with an inbox ping</p>',
partner_ids=self.user_test.partner_id.ids,
message_type='comment',
subtype_xmlid='mail.mt_comment')
@mute_logger('odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_message_subscribe_default(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
with self.assertQueryCount(__system__=6, emp=6):
record.message_subscribe(partner_ids=self.user_test.partner_id.ids)
with self.assertQueryCount(__system__=3, emp=3):
record.message_subscribe(partner_ids=self.user_test.partner_id.ids)
@mute_logger('odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_message_subscribe_subtypes(self):
record = self.env['mail.test.simple'].create({'name': 'Test'})
subtype_ids = (self.env.ref('test_mail.st_mail_test_simple_external') | self.env.ref('mail.mt_comment')).ids
with self.assertQueryCount(__system__=5, emp=5):
record.message_subscribe(partner_ids=self.user_test.partner_id.ids, subtype_ids=subtype_ids)
with self.assertQueryCount(__system__=2, emp=2):
record.message_subscribe(partner_ids=self.user_test.partner_id.ids, subtype_ids=subtype_ids)
@mute_logger('odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_message_track(self):
record = self.env['mail.performance.tracking'].create({'name': 'Zizizatestname'})
with self.assertQueryCount(__system__=3, emp=3):
record.write({'name': 'Zizizanewtestname'})
record.flush()
with self.assertQueryCount(__system__=5, emp=5):
record.write({'field_%s' % (i): 'Tracked Char Fields %s' % (i) for i in range(3)})
record.flush()
with self.assertQueryCount(__system__=6, emp=6):
record.write({'field_%s' % (i): 'Field Without Cache %s' % (i) for i in range(3)})
record.flush()
record.write({'field_%s' % (i): 'Field With Cache %s' % (i) for i in range(3)})
record.flush()
@users('__system__', 'emp')
@warmup
def test_notification_reply_to_batch(self):
test_records_sudo = self.env['mail.test.container'].sudo().create([
{'alias_name': 'alias.test.%s.%d' % (self.env.user.name, index),
'customer_id': self.customer.id,
'name': 'Test_%d' % index,
} for index in range(10)
])
with self.assertQueryCount(__system__=1, emp=1):
test_records = self.env['mail.test.container'].browse(test_records_sudo.ids)
reply_to = test_records._notify_get_reply_to(
default=self.env.user.email_formatted
)
for record in test_records:
self.assertEqual(
reply_to[record.id],
formataddr(
("%s %s" % (self.env.user.company_id.name, record.name),
"%s@%s" % (record.alias_name, self.alias_domain)
)
)
)
@tagged('mail_performance', 'post_install', '-at_install')
class TestMailComplexPerformance(BaseMailPerformance):
def setUp(self):
super(TestMailComplexPerformance, self).setUp()
self.user_portal = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'Olivia Portal',
'login': 'port',
'email': 'p.p@example.com',
'signature': '--\nOlivia',
'notification_type': 'email',
'groups_id': [(6, 0, [self.env.ref('base.group_portal').id])],
})
self.admin = self.env.user
# prepare recipients to test for more realistic workload
self.customer = self.env['res.partner'].with_context(self._quick_create_ctx).create({
'name': 'Test Customer',
'email': 'test@example.com'
})
self.container = self.env['mail.test.container'].with_context(mail_create_nosubscribe=True).create({
'name': 'Test Container',
'customer_id': self.customer.id,
'alias_name': 'test-alias',
})
Partners = self.env['res.partner'].with_context(self._quick_create_ctx)
self.partners = self.env['res.partner']
for x in range(0, 10):
self.partners |= Partners.create({'name': 'Test %s' % x, 'email': 'test%s@example.com' % x})
self.container.message_subscribe(self.partners.ids, subtype_ids=[
self.env.ref('mail.mt_comment').id,
self.env.ref('test_mail.st_mail_test_container_child_full').id]
)
self._init_mail_gateway()
# `test_complex_mail_mail_send`
self.container.flush()
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_mail_mail_send(self):
message = self.env['mail.message'].sudo().create({
'subject': 'Test',
'body': '<p>Test</p>',
'author_id': self.env.user.partner_id.id,
'email_from': self.env.user.partner_id.email,
'model': 'mail.test.container',
'res_id': self.container.id,
})
mail = self.env['mail.mail'].sudo().create({
'body_html': '<p>Test</p>',
'mail_message_id': message.id,
'recipient_ids': [(4, pid) for pid in self.partners.ids],
})
mail_ids = mail.ids
with self.assertQueryCount(__system__=8, emp=8):
self.env['mail.mail'].sudo().browse(mail_ids).send()
self.assertEqual(mail.body_html, '<p>Test</p>')
self.assertEqual(mail.reply_to, formataddr(('%s %s' % (self.env.company.name, self.container.name), 'test-alias@example.com')))
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_message_post(self):
self.container.message_subscribe(self.user_portal.partner_id.ids)
record = self.container.with_user(self.env.user)
with self.assertQueryCount(__system__=66, emp=67): # tm 63/64
record.message_post(
body='<p>Test Post Performances</p>',
message_type='comment',
subtype_xmlid='mail.mt_comment')
self.assertEqual(record.message_ids[0].body, '<p>Test Post Performances</p>')
self.assertEqual(record.message_ids[0].notified_partner_ids, self.partners | self.user_portal.partner_id)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_message_post_template(self):
self.container.message_subscribe(self.user_portal.partner_id.ids)
record = self.container.with_user(self.env.user)
template_id = self.env.ref('test_mail.mail_test_container_tpl').id
with self.assertQueryCount(__system__=77, emp=78): # tm 72/73
record.message_post_with_template(template_id, message_type='comment', composition_mode='comment')
self.assertEqual(record.message_ids[0].body, '<p>Adding stuff on %s</p>' % record.name)
self.assertEqual(record.message_ids[0].notified_partner_ids, self.partners | self.user_portal.partner_id | self.customer)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_message_subscribe(self):
pids = self.partners.ids
subtypes = self.env.ref('mail.mt_comment') | self.env.ref('test_mail.st_mail_test_ticket_container_upd')
subtype_ids = subtypes.ids
rec = self.env['mail.test.ticket'].create({
'name': 'Test',
'container_id': False,
'customer_id': False,
'user_id': self.user_portal.id,
})
rec1 = rec.with_context(active_test=False) # to see inactive records
self.assertEqual(rec1.message_partner_ids, self.env.user.partner_id | self.user_portal.partner_id)
# subscribe new followers with forced given subtypes
with self.assertQueryCount(__system__=7, emp=7):
rec.message_subscribe(
partner_ids=pids[:4],
subtype_ids=subtype_ids
)
self.assertEqual(rec1.message_partner_ids, self.env.user.partner_id | self.user_portal.partner_id | self.partners[:4])
# subscribe existing and new followers with force=False, meaning only some new followers will be added
with self.assertQueryCount(__system__=6, emp=6):
rec.message_subscribe(
partner_ids=pids[:6],
subtype_ids=None
)
self.assertEqual(rec1.message_partner_ids, self.env.user.partner_id | self.user_portal.partner_id | self.partners[:6])
# subscribe existing and new followers with force=True, meaning all will have the same subtypes
with self.assertQueryCount(__system__=7, emp=7):
rec.message_subscribe(
partner_ids=pids,
subtype_ids=subtype_ids
)
self.assertEqual(rec1.message_partner_ids, self.env.user.partner_id | self.user_portal.partner_id | self.partners)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_tracking_assignation(self):
""" Assignation performance test on already-created record """
rec = self.env['mail.test.ticket'].create({
'name': 'Test',
'container_id': self.container.id,
'customer_id': self.customer.id,
'user_id': self.env.uid,
})
rec1 = rec.with_context(active_test=False) # to see inactive records
self.assertEqual(rec1.message_partner_ids, self.partners | self.env.user.partner_id)
with self.assertQueryCount(__system__=41, emp=42): # tm 38/39
rec.write({'user_id': self.user_portal.id})
self.assertEqual(rec1.message_partner_ids, self.partners | self.env.user.partner_id | self.user_portal.partner_id)
# write tracking message
self.assertEqual(rec1.message_ids[0].subtype_id, self.env.ref('mail.mt_note'))
self.assertEqual(rec1.message_ids[0].notified_partner_ids, self.env['res.partner'])
# creation message
self.assertEqual(rec1.message_ids[1].subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
self.assertEqual(rec1.message_ids[1].notified_partner_ids, self.partners)
self.assertEqual(len(rec1.message_ids), 2)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_tracking_subscription_create(self):
""" Creation performance test involving auto subscription, assignation, tracking with subtype and template send. """
container_id = self.container.id
customer_id = self.customer.id
user_id = self.user_portal.id
with self.assertQueryCount(__system__=116, emp=117): # tm 110/111
rec = self.env['mail.test.ticket'].create({
'name': 'Test',
'container_id': container_id,
'customer_id': customer_id,
'user_id': user_id,
})
rec1 = rec.with_context(active_test=False) # to see inactive records
self.assertEqual(rec1.message_partner_ids, self.partners | self.env.user.partner_id | self.user_portal.partner_id)
# creation message
self.assertEqual(rec1.message_ids[0].subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
self.assertEqual(rec1.message_ids[0].notified_partner_ids, self.partners | self.user_portal.partner_id)
self.assertEqual(len(rec1.message_ids), 1)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_tracking_subscription_subtype(self):
""" Write performance test involving auto subscription, tracking with subtype """
rec = self.env['mail.test.ticket'].create({
'name': 'Test',
'container_id': False,
'customer_id': False,
'user_id': self.user_portal.id,
})
rec1 = rec.with_context(active_test=False) # to see inactive records
self.assertEqual(rec1.message_partner_ids, self.user_portal.partner_id | self.env.user.partner_id)
self.assertEqual(len(rec1.message_ids), 1)
with self.assertQueryCount(__system__=81, emp=81): # tm 78/78
rec.write({
'name': 'Test2',
'container_id': self.container.id,
})
self.assertEqual(rec1.message_partner_ids, self.partners | self.env.user.partner_id | self.user_portal.partner_id)
# write tracking message
self.assertEqual(rec1.message_ids[0].subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
self.assertEqual(rec1.message_ids[0].notified_partner_ids, self.partners | self.user_portal.partner_id)
# creation message
self.assertEqual(rec1.message_ids[1].subtype_id, self.env.ref('mail.mt_note'))
self.assertEqual(rec1.message_ids[1].notified_partner_ids, self.env['res.partner'])
self.assertEqual(len(rec1.message_ids), 2)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_tracking_subscription_write(self):
""" Write performance test involving auto subscription, tracking with subtype and template send """
container_id = self.container.id
customer_id = self.customer.id
container2 = self.env['mail.test.container'].with_context(mail_create_nosubscribe=True).create({
'name': 'Test Container 2',
'customer_id': False,
'alias_name': False,
})
rec = self.env['mail.test.ticket'].create({
'name': 'Test',
'container_id': container2.id,
'customer_id': False,
'user_id': self.user_portal.id,
})
rec1 = rec.with_context(active_test=False) # to see inactive records
self.assertEqual(rec1.message_partner_ids, self.user_portal.partner_id | self.env.user.partner_id)
with self.assertQueryCount(__system__=88, emp=88): # tm 85/85
rec.write({
'name': 'Test2',
'container_id': container_id,
'customer_id': customer_id,
})
self.assertEqual(rec1.message_partner_ids, self.partners | self.env.user.partner_id | self.user_portal.partner_id)
# write tracking message
self.assertEqual(rec1.message_ids[0].subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
self.assertEqual(rec1.message_ids[0].notified_partner_ids, self.partners | self.user_portal.partner_id)
# creation message
self.assertEqual(rec1.message_ids[1].subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
self.assertEqual(rec1.message_ids[1].notified_partner_ids, self.user_portal.partner_id)
self.assertEqual(len(rec1.message_ids), 2)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('__system__', 'emp')
@warmup
def test_complex_tracking_template(self):
""" Write performance test involving assignation, tracking with template """
customer_id = self.customer.id
self.assertTrue(self.env.registry.ready, "We need to simulate that registery is ready")
rec = self.env['mail.test.ticket'].create({
'name': 'Test',
'container_id': self.container.id,
'customer_id': False,
'user_id': self.user_portal.id,
'mail_template': self.env.ref('test_mail.mail_test_ticket_tracking_tpl').id,
})
rec1 = rec.with_context(active_test=False) # to see inactive records
self.assertEqual(rec1.message_partner_ids, self.partners | self.env.user.partner_id | self.user_portal.partner_id)
with self.assertQueryCount(__system__=31, emp=32): # tm 30/31
rec.write({
'name': 'Test2',
'customer_id': customer_id,
'user_id': self.env.uid,
})
# write template message (sent to customer, mass mailing kept for history)
self.assertEqual(rec1.message_ids[0].subtype_id, self.env['mail.message.subtype'])
self.assertEqual(rec1.message_ids[0].subject, 'Test Template')
# write tracking message
self.assertEqual(rec1.message_ids[1].subtype_id, self.env.ref('mail.mt_note'))
self.assertEqual(rec1.message_ids[1].notified_partner_ids, self.env['res.partner'])
# creation message
self.assertEqual(rec1.message_ids[2].subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
self.assertEqual(rec1.message_ids[2].notified_partner_ids, self.partners | self.user_portal.partner_id)
self.assertEqual(len(rec1.message_ids), 3)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('emp')
@warmup
def test_message_format(self):
"""Test performance of `_message_format` and of `message_format` with
multiple messages with multiple attachments, different authors, various
notifications, and different tracking values.
Those messages might not make sense functionally but they are crafted to
cover as much of the code as possible in regard to number of queries.
"""
name_field = self.env['ir.model.fields']._get(self.container._name, 'name')
customer_id_field = self.env['ir.model.fields']._get(self.container._name, 'customer_id')
messages = self.env['mail.message'].sudo().create([{
'subject': 'Test 0',
'body': '<p>Test 0</p>',
'author_id': self.partners[0].id,
'email_from': self.partners[0].email,
'model': 'mail.test.container',
'res_id': self.container.id,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment'),
'attachment_ids': [
(0, 0, {
'name': 'test file 0 - %d' % j,
'datas': 'data',
}) for j in range(2)
],
'notification_ids': [
(0, 0, {
'res_partner_id': self.partners[3].id,
'notification_type': 'inbox',
}),
(0, 0, {
'res_partner_id': self.partners[4].id,
'notification_type': 'email',
'notification_status': 'exception',
}),
(0, 0, {
'res_partner_id': self.partners[6].id,
'notification_type': 'email',
'notification_status': 'exception',
}),
],
'tracking_value_ids': [
(0, 0, {
'field': name_field.id,
'field_desc': 'Name',
'old_value_char': 'old 0',
'new_value_char': 'new 0',
}),
(0, 0, {
'field': customer_id_field.id,
'field_desc': 'Customer',
'old_value_integer': self.partners[7].id,
'new_value_integer': self.partners[8].id,
}),
]
}, {
'subject': 'Test 1',
'body': '<p>Test 1</p>',
'author_id': self.partners[1].id,
'email_from': self.partners[1].email,
'model': 'mail.test.container',
'res_id': self.container.id,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
'attachment_ids': [
(0, 0, {
'name': 'test file 1 - %d' % j,
'datas': 'data',
}) for j in range(2)
],
'notification_ids': [
(0, 0, {
'res_partner_id': self.partners[5].id,
'notification_type': 'inbox',
}),
(0, 0, {
'res_partner_id': self.partners[6].id,
'notification_type': 'email',
'notification_status': 'exception',
}),
],
'tracking_value_ids': [
(0, 0, {
'field': name_field.id,
'field_desc': 'Name',
'old_value_char': 'old 1',
'new_value_char': 'new 1',
}),
(0, 0, {
'field': customer_id_field.id,
'field_desc': 'Customer',
'old_value_integer': self.partners[7].id,
'new_value_integer': self.partners[8].id,
}),
]
}])
with self.assertQueryCount(emp=6):
res = messages.message_format()
self.assertEqual(len(res), 2)
for message in res:
self.assertEqual(len(message['attachment_ids']), 2)
messages.flush()
messages.invalidate_cache()
with self.assertQueryCount(emp=18):
res = messages.message_format()
self.assertEqual(len(res), 2)
for message in res:
self.assertEqual(len(message['attachment_ids']), 2)
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('emp')
@warmup
def test_message_format_group_thread_name_by_model(self):
"""Ensures the fetch of multiple thread names is grouped by model."""
records = []
for _i in range(5):
records.append(self.env['mail.test.simple'].create({'name': 'Test'}))
records.append(self.env['mail.test.track'].create({'name': 'Test'}))
messages = self.env['mail.message'].create([{
'model': record._name,
'res_id': record.id
} for record in records])
with self.assertQueryCount(emp=5):
res = messages.message_format()
self.assertEqual(len(res), 6)
messages.flush()
messages.invalidate_cache()
with self.assertQueryCount(emp=14):
res = messages.message_format()
self.assertEqual(len(res), 6)
@tagged('mail_performance', 'post_install', '-at_install')
class TestMailHeavyPerformancePost(BaseMailPerformance):
def setUp(self):
super(TestMailHeavyPerformancePost, self).setUp()
# record
self.customer = self.env['res.partner'].with_context(self._quick_create_ctx).create({
'name': 'customer',
'email': 'customer@example.com',
})
self.record = self.env['mail.test.container'].with_context(mail_create_nosubscribe=True).create({
'name': 'Test record',
'customer_id': self.customer.id,
'alias_name': 'test-alias',
})
# followers
self.user_follower_email = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'user_follower_email',
'login': 'user_follower_email',
'email': 'user_follower_email@example.com',
'notification_type': 'email',
'groups_id': [(6, 0, [self.env.ref('base.group_user').id])],
})
self.user_follower_inbox = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'user_follower_inbox',
'login': 'user_follower_inbox',
'email': 'user_follower_inbox@example.com',
'notification_type': 'inbox',
'groups_id': [(6, 0, [self.env.ref('base.group_user').id])],
})
self.partner_follower = self.env['res.partner'].with_context(self._quick_create_ctx).create({
'name': 'partner_follower',
'email': 'partner_follower@example.com',
})
self.record.message_subscribe([
self.partner_follower.id,
self.user_follower_inbox.partner_id.id,
self.user_follower_email.partner_id.id
])
# partner_ids
self.user_inbox = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'user_inbox',
'login': 'user_inbox',
'email': 'user_inbox@example.com',
'notification_type': 'inbox',
'groups_id': [(6, 0, [self.env.ref('base.group_user').id])],
})
self.user_email = self.env['res.users'].with_context(self._quick_create_ctx).create({
'name': 'user_email',
'login': 'user_email',
'email': 'user_email@example.com',
'notification_type': 'email',
'groups_id': [(6, 0, [self.env.ref('base.group_user').id])],
})
self.partner = self.env['res.partner'].with_context(self._quick_create_ctx).create({
'name': 'partner',
'email': 'partner@example.com',
})
self.vals = [{
'datas': base64.b64encode(bytes("attachement content %s" % i, 'utf-8')),
'name': 'fileText_test%s.txt' % i,
'mimetype': 'text/plain',
'res_model': 'mail.compose.message',
'res_id': 0,
} for i in range(3)]
self._init_mail_gateway()
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
@users('emp')
@warmup
def test_complete_message_post(self):
# aims to cover as much features of message_post as possible
partner_ids = [self.user_inbox.partner_id.id, self.user_email.partner_id.id, self.partner.id]
record = self.record.with_user(self.env.user)
attachements = [ # not linear on number of attachements
('attach tuple 1', "attachement tupple content 1"),
('attach tuple 2', "attachement tupple content 2", {'cid': 'cid1'}),
('attach tuple 3', "attachement tupple content 3", {'cid': 'cid2'}),
]
self.attachements = self.env['ir.attachment'].with_user(self.env.user).create(self.vals)
attachement_ids = self.attachements.ids
with self.assertQueryCount(emp=80): # tm 71 - com 78
self.cr.sql_log = self.warm and self.cr.sql_log_count
record.with_context({}).message_post(
body='<p>Test body <img src="cid:cid1"> <img src="cid:cid2"></p>',
subject='Test Subject',
message_type='notification',
subtype_xmlid=None,
partner_ids=partner_ids,
parent_id=False,
attachments=attachements,
attachment_ids=attachement_ids,
add_sign=True,
model_description=False,
mail_auto_delete=True
)
self.cr.sql_log = False
self.assertTrue(record.message_ids[0].body.startswith('<p>Test body <img src="/web/image/'))
self.assertEqual(self.attachements.mapped('res_model'), [record._name for i in range(3)])
self.assertEqual(self.attachements.mapped('res_id'), [record.id for i in range(3)])
# self.assertEqual(record.message_ids[0].notified_partner_ids, [])
| 43.322485
| 43,929
|
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 TransactionCase
class TestMailCommon(MailCommon):
""" Main entry point for functional tests. """
@classmethod
def _create_channel_listener(cls):
cls.channel_listen = cls.env['mail.channel'].with_context(cls._test_context).create({'name': 'Listener'})
@classmethod
def _create_records_for_batch(cls, model, count):
# TDE note: to be cleaned in master
records = cls.env[model]
partners = cls.env['res.partner']
country_id = cls.env.ref('base.be').id
partners = cls.env['res.partner'].with_context(**cls._test_context).create([{
'name': 'Partner_%s' % (x),
'email': '_test_partner_%s@example.com' % (x),
'country_id': country_id,
'mobile': '047500%02d%02d' % (x, x)
} for x in range(count)])
records = cls.env[model].with_context(**cls._test_context).create([{
'name': 'Test_%s' % (x),
'customer_id': partners[x].id,
} for x in range(count)])
cls.records = cls._reset_mail_context(records)
cls.partners = partners
return cls.records, cls.partners
class TestMailMultiCompanyCommon(MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailMultiCompanyCommon, cls).setUpClass()
cls.company_2 = cls.env['res.company'].create({
'name': 'Second Test Company',
'currency_id': 2,
})
class TestRecipients(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestRecipients, cls).setUpClass()
Partner = cls.env['res.partner'].with_context({
'mail_create_nolog': True,
'mail_create_nosubscribe': True,
'mail_notrack': True,
'no_reset_password': True,
})
cls.partner_1 = Partner.create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com',
'country_id': cls.env.ref('base.be').id,
'mobile': '0456001122',
})
cls.partner_2 = Partner.create({
'name': 'Valid Poilvache',
'email': 'valid.other@gmail.com',
'country_id': cls.env.ref('base.be').id,
'mobile': '+32 456 22 11 00',
})
| 33.75
| 2,430
|
51,983
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from unittest.mock import patch
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.test_mail.models.test_mail_models import MailTestTicket
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.exceptions import AccessError
from odoo.tests import tagged
from odoo.tests.common import users, Form
from odoo.tools import mute_logger, formataddr
@tagged('mail_composer')
class TestMailComposer(TestMailCommon, TestRecipients):
""" Test Composer internals """
@classmethod
def setUpClass(cls):
super(TestMailComposer, cls).setUpClass()
cls._init_mail_gateway()
# ensure employee can create partners, necessary for templates
cls.user_employee.write({
'groups_id': [(4, cls.env.ref('base.group_partner_manager').id)],
})
cls.user_employee_2 = mail_new_test_user(
cls.env, login='employee2', groups='base.group_user',
notification_type='email', email='eglantine@example.com',
name='Eglantine Employee', signature='--\nEglantine')
cls.partner_employee_2 = cls.user_employee_2.partner_id
# User without the group "mail.group_mail_template_editor"
cls.user_rendering_restricted = 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.env.ref('mail.group_mail_template_editor').users -= cls.user_rendering_restricted
cls.test_record = cls.env['mail.test.ticket'].with_context(cls._test_context).create({
'name': 'TestRecord',
'customer_id': cls.partner_1.id,
'user_id': cls.user_employee_2.id,
})
cls.test_records, cls.test_partners = cls._create_records_for_batch('mail.test.ticket', 2)
cls.test_report = cls.env['ir.actions.report'].create({
'name': 'Test Report on mail test ticket',
'model': 'mail.test.ticket',
'report_type': 'qweb-pdf',
'report_name': 'test_mail.mail_test_ticket_test_template',
})
cls.test_record_report = cls.test_report._render_qweb_pdf(cls.test_report.ids)
cls.test_from = '"John Doe" <john@example.com>'
cls.mail_server = cls.env['ir.mail_server'].create({
'name': 'Dummy Test Server',
'smtp_host': 'smtp.pizza.moc',
'smtp_port': 17,
'smtp_encryption': 'ssl',
'sequence': 666,
})
cls.template = cls.env['mail.template'].create({
'name': 'TestTemplate',
'subject': 'TemplateSubject {{ object.name }}',
'body_html': '<p>TemplateBody <t t-esc="object.name"></t></p>',
'partner_to': '{{ object.customer_id.id if object.customer_id else "" }}',
'email_to': '{{ (object.email_from if not object.customer_id else "") }}',
'email_from': '{{ (object.user_id.email_formatted or user.email_formatted) }}',
'model_id': cls.env['ir.model']._get('mail.test.ticket').id,
'mail_server_id': cls.mail_server.id,
'auto_delete': True,
})
def _generate_attachments_data(self, count, res_model=None, res_id=None):
# attachment visibility depends on what they are attached to
if res_model is None:
res_model = self.template._name
if res_id is None:
res_id = self.template.id
return [{
'name': '%02d.txt' % x,
'datas': base64.b64encode(b'Att%02d' % x),
'res_model': res_model,
'res_id': res_id,
} for x in range(count)]
def _get_web_context(self, records, add_web=True, **values):
""" Helper to generate composer context. Will make tests a bit less
verbose.
:param add_web: add web context, generally making noise especially in
mass mail mode (active_id/ids both present in context)
"""
base_context = {
'default_model': records._name,
}
if len(records) == 1:
base_context['default_composition_mode'] = 'comment'
base_context['default_res_id'] = records.id
else:
base_context['default_composition_mode'] = 'mass_mail'
base_context['active_ids'] = records.ids
if add_web:
base_context['active_model'] = records._name
base_context['active_id'] = records[0].id
if values:
base_context.update(**values)
return base_context
@tagged('mail_composer')
class TestComposerForm(TestMailComposer):
@users('employee')
def test_mail_composer_comment(self):
composer_form = Form(self.env['mail.compose.message'].with_context(self._get_web_context(self.test_record, add_web=True)))
self.assertEqual(
composer_form.subject, 'Re: %s' % self.test_record.name,
'MailComposer: comment mode should have default subject Re: record_name')
# record name not displayed currently in view
# self.assertEqual(composer_form.record_name, self.test_record.name, 'MailComposer: comment mode should compute record name')
self.assertFalse(composer_form.reply_to_force_new)
self.assertEqual(composer_form.composition_mode, 'comment')
self.assertEqual(composer_form.model, self.test_record._name)
@users('employee')
def test_mail_composer_comment_attachments(self):
"""Tests that all attachments are added to the composer, static attachments
are not duplicated and while reports are re-generated, and that intermediary
attachments are dropped."""
attachment_data = self._generate_attachments_data(2)
template_1 = self.template.copy({
'attachment_ids': [(0, 0, a) for a in attachment_data],
'report_name': 'TestReport for {{ object.name }}.html', # test cursor forces html
'report_template': self.test_report.id,
})
template_1_attachments = template_1.attachment_ids
self.assertEqual(len(template_1_attachments), 2)
template_2 = self.template.copy({
'attachment_ids': False,
'report_template': self.test_report.id,
})
# begins without attachments
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record, add_web=True, default_attachment_ids=[])
))
self.assertEqual(len(composer_form.attachment_ids), 0)
# change template: 2 static (attachment_ids) and 1 dynamic (report)
composer_form.template_id = template_1
self.assertEqual(len(composer_form.attachment_ids), 3)
report_attachments = [att for att in composer_form.attachment_ids if att not in template_1_attachments]
self.assertEqual(len(report_attachments), 1)
tpl_attachments = composer_form.attachment_ids[:] - report_attachments[0]
self.assertEqual(tpl_attachments, template_1_attachments)
# change template: 0 static (attachment_ids) and 1 dynamic (report)
composer_form.template_id = template_2
self.assertEqual(len(composer_form.attachment_ids), 1)
report_attachments = [att for att in composer_form.attachment_ids if att not in template_1_attachments]
self.assertEqual(len(report_attachments), 1)
tpl_attachments = composer_form.attachment_ids[:] - report_attachments[0]
self.assertEqual(tpl_attachments, self.env['ir.attachment'])
# change back to template 1
composer_form.template_id = template_1
self.assertEqual(len(composer_form.attachment_ids), 3)
report_attachments = [att for att in composer_form.attachment_ids if att not in template_1_attachments]
self.assertEqual(len(report_attachments), 1)
tpl_attachments = composer_form.attachment_ids[:] - report_attachments[0]
self.assertEqual(tpl_attachments, template_1_attachments)
# reset template
composer_form.template_id = self.env['mail.template']
self.assertEqual(len(composer_form.attachment_ids), 0)
@users('employee')
def test_mail_composer_mass(self):
composer_form = Form(self.env['mail.compose.message'].with_context(self._get_web_context(self.test_records, add_web=True)))
self.assertFalse(composer_form.subject, 'MailComposer: mass mode should have void default subject if no template')
# record name not displayed currently in view
# self.assertFalse(composer_form.record_name, 'MailComposer: mass mode should have void record name')
self.assertFalse(composer_form.reply_to_force_new)
self.assertEqual(composer_form.composition_mode, 'mass_mail')
self.assertEqual(composer_form.model, self.test_records._name)
@users('employee')
def test_mail_composer_mass_wtpl(self):
ctx = self._get_web_context(self.test_records, add_web=True, default_template_id=self.template.id)
composer_form = Form(self.env['mail.compose.message'].with_context(ctx))
self.assertEqual(composer_form.subject, self.template.subject,
'MailComposer: mass mode should have template raw subject if template')
self.assertEqual(composer_form.body, self.template.body_html,
'MailComposer: mass mode should have template raw body if template')
# record name not displayed currently in view
# self.assertFalse(composer_form.record_name, 'MailComposer: mass mode should have void record name')
self.assertFalse(composer_form.reply_to_force_new)
self.assertEqual(composer_form.composition_mode, 'mass_mail')
self.assertEqual(composer_form.model, self.test_records._name)
@tagged('mail_composer')
class TestComposerInternals(TestMailComposer):
@users('employee')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_composer_attachments_comment(self):
""" Test attachments management in comment mode. """
attachment_data = self._generate_attachments_data(3)
self.template.write({
'attachment_ids': [(0, 0, a) for a in attachment_data],
'report_name': 'TestReport for {{ object.name }}.html', # test cursor forces html
'report_template': self.test_report.id,
})
attachs = self.env['ir.attachment'].search([('name', 'in', [a['name'] for a in attachment_data])])
self.assertEqual(len(attachs), 3)
composer = self.env['mail.compose.message'].with_context({
'default_composition_mode': 'comment',
'default_model': self.test_record._name,
'default_res_id': self.test_record.id,
'default_template_id': self.template.id,
}).create({
'body': '<p>Test Body</p>',
})
# currently onchange necessary
composer._onchange_template_id_wrapper()
# values coming from template
self.assertEqual(len(composer.attachment_ids), 4)
for attach in attachs:
self.assertIn(attach, composer.attachment_ids)
generated = composer.attachment_ids - attachs
self.assertEqual(len(generated), 1, 'MailComposer: should have 1 additional attachment for report')
self.assertEqual(generated.name, 'TestReport for %s.html' % self.test_record.name)
self.assertEqual(generated.res_model, 'mail.compose.message')
self.assertEqual(generated.res_id, 0)
@users('employee')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_composer_author(self):
""" Test author_id / email_from synchronization, in both comment and mass mail
modes. """
for composition_mode in ['comment', 'mass_mail']:
if composition_mode == 'comment':
ctx = self._get_web_context(self.test_record, add_web=False)
else:
ctx = self._get_web_context(self.test_records, add_web=False)
composer = self.env['mail.compose.message'].with_context(ctx).create({
'body': '<p>Test Body</p>',
})
# default values are current user
self.assertEqual(composer.author_id, self.env.user.partner_id)
self.assertEqual(composer.email_from, self.env.user.email_formatted)
# author values reset email (FIXME: currently not synchronized)
composer.write({'author_id': self.partner_1})
self.assertEqual(composer.author_id, self.partner_1)
self.assertEqual(composer.email_from, self.env.user.email_formatted)
# self.assertEqual(composer.email_from, self.partner_1.email_formatted)
# changing template should update its email_from
composer.write({'template_id': self.template.id, 'author_id': self.env.user.partner_id})
# currently onchange necessary
composer._onchange_template_id_wrapper()
self.assertEqual(composer.author_id, self.env.user.partner_id,
'MailComposer: should take value given by user')
if composition_mode == 'comment':
self.assertEqual(composer.email_from, self.test_record.user_id.email_formatted,
'MailComposer: should take email_from rendered from template')
else:
self.assertEqual(composer.email_from, self.template.email_from,
'MailComposer: should take email_from raw from template')
# manual values are kept over template values
composer.write({'email_from': self.test_from})
self.assertEqual(composer.author_id, self.env.user.partner_id)
self.assertEqual(composer.email_from, self.test_from)
@users('employee')
def test_mail_composer_content(self):
""" Test content management (subject, body, server) in both comment and
mass mailing mode. Template update is also tested. """
for composition_mode in ['comment', 'mass_mail']:
if composition_mode == 'comment':
ctx = self._get_web_context(self.test_record, add_web=False)
else:
ctx = self._get_web_context(self.test_records, add_web=False)
# 1. check without template + template update
composer = self.env['mail.compose.message'].with_context(ctx).create({
'subject': 'My amazing subject',
'body': '<p>Test Body</p>',
})
# creation values are taken
self.assertEqual(composer.subject, 'My amazing subject')
self.assertEqual(composer.body, '<p>Test Body</p>')
self.assertEqual(composer.mail_server_id.id, False)
# changing template should update its content
composer.write({'template_id': self.template.id})
# currently onchange necessary
composer._onchange_template_id_wrapper()
# values come from template
if composition_mode == 'comment':
self.assertEqual(composer.subject, 'TemplateSubject %s' % self.test_record.name)
self.assertEqual(composer.body, '<p>TemplateBody %s</p>' % self.test_record.name)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
else:
self.assertEqual(composer.subject, self.template.subject)
self.assertEqual(composer.body, self.template.body_html)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
# manual values is kept over template
composer.write({'subject': 'Back to my amazing subject'})
self.assertEqual(composer.subject, 'Back to my amazing subject')
# reset template should reset values
composer.write({'template_id': False})
# currently onchange necessary
composer._onchange_template_id_wrapper()
# values are reset
if composition_mode == 'comment':
self.assertEqual(composer.subject, 'Re: %s' % self.test_record.name)
self.assertEqual(composer.body, '')
# TDE FIXME: server id is kept, not sure why
# self.assertFalse(composer.mail_server_id.id)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
else:
# values are reset TDE FIXME: strange for subject
self.assertEqual(composer.subject, 'Back to my amazing subject')
self.assertEqual(composer.body, '')
# TDE FIXME: server id is kept, not sure why
# self.assertFalse(composer.mail_server_id.id)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
# 2. check with default
ctx['default_template_id'] = self.template.id
composer = self.env['mail.compose.message'].with_context(ctx).create({
'template_id': self.template.id,
})
# currently onchange necessary
composer._onchange_template_id_wrapper()
# values come from template
if composition_mode == 'comment':
self.assertEqual(composer.subject, 'TemplateSubject %s' % self.test_record.name)
self.assertEqual(composer.body, '<p>TemplateBody %s</p>' % self.test_record.name)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
else:
self.assertEqual(composer.subject, self.template.subject)
self.assertEqual(composer.body, self.template.body_html)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
# 3. check at create
ctx.pop('default_template_id')
composer = self.env['mail.compose.message'].with_context(ctx).create({
'template_id': self.template.id,
})
# currently onchange necessary
composer._onchange_template_id_wrapper()
# values come from template
if composition_mode == 'comment':
self.assertEqual(composer.subject, 'TemplateSubject %s' % self.test_record.name)
self.assertEqual(composer.body, '<p>TemplateBody %s</p>' % self.test_record.name)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
else:
self.assertEqual(composer.subject, self.template.subject)
self.assertEqual(composer.body, self.template.body_html)
self.assertEqual(composer.mail_server_id, self.template.mail_server_id)
# 4. template + user input
ctx['default_template_id'] = self.template.id
composer = self.env['mail.compose.message'].with_context(ctx).create({
'subject': 'My amazing subject',
'body': '<p>Test Body</p>',
'mail_server_id': False,
})
# creation values are taken
self.assertEqual(composer.subject, 'My amazing subject')
self.assertEqual(composer.body, '<p>Test Body</p>')
self.assertEqual(composer.mail_server_id.id, False)
@users('employee')
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_mail_composer_parent(self):
""" Test specific management in comment mode when having parent_id set:
record_name, subject, parent's partners. """
parent = self.test_record.message_post(body='Test', partner_ids=(self.partner_1 + self.partner_2).ids)
composer = self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record, add_web=False, default_parent_id=parent.id)
).create({
'body': '<p>Test Body</p>',
})
# creation values taken from parent
self.assertEqual(composer.subject, 'Re: %s' % self.test_record.name)
self.assertEqual(composer.body, '<p>Test Body</p>')
self.assertEqual(composer.partner_ids, self.partner_1 + self.partner_2)
@users('user_rendering_restricted')
@mute_logger('odoo.tests', 'odoo.addons.base.models.ir_rule', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_mail_composer_rights_attachments(self):
""" Ensure a user without write access to a template can send an email"""
template_1 = self.template.copy({
'report_name': 'TestReport for {{ object.name }} (thanks TDE).html', # test cursor forces html
'report_template': self.test_report.id,
})
attachment_data = self._generate_attachments_data(2)
template_1.write({
'attachment_ids': [(0, 0, dict(a, res_model="mail.template", res_id=template_1.id)) for a in attachment_data]
})
with self.assertRaises(AccessError):
# ensure user_rendering_restricted has no write access
template_1.with_user(self.env.user).write({'name': 'New Name'})
template_1_attachments = template_1.attachment_ids
self.assertEqual(len(template_1_attachments), 2)
template_1_attachment_name = list(template_1_attachments.mapped('name')) + ["TestReport for TestRecord (thanks TDE).html"]
composer = self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record)
).create({
'subject': 'Template Subject',
'body': '<p>Template Body</p>',
'template_id': template_1.id,
'attachment_ids': template_1_attachments.ids,
'partner_ids': [self.partner_employee_2.id],
})
composer._onchange_template_id_wrapper()
composer._action_send_mail()
self.assertEqual(self.test_record.message_ids[0].subject, 'TemplateSubject TestRecord')
self.assertEqual(
sorted(self.test_record.message_ids[0].attachment_ids.mapped('name')),
sorted(template_1_attachment_name))
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_mail_composer_rights_portal(self):
portal_user = self._create_portal_user()
with patch.object(MailTestTicket, 'check_access_rights', return_value=True):
self.env['mail.compose.message'].with_user(portal_user).with_context(
self._get_web_context(self.test_record)
).create({
'subject': 'Subject',
'body': '<p>Body text</p>',
'partner_ids': []
})._action_send_mail()
self.assertEqual(self.test_record.message_ids[0].body, '<p>Body text</p>')
self.assertEqual(self.test_record.message_ids[0].author_id, portal_user.partner_id)
self.env['mail.compose.message'].with_user(portal_user).with_context({
'default_composition_mode': 'comment',
'default_parent_id': self.test_record.message_ids.ids[0],
}).create({
'subject': 'Subject',
'body': '<p>Body text 2</p>'
})._action_send_mail()
self.assertEqual(self.test_record.message_ids[0].body, '<p>Body text 2</p>')
self.assertEqual(self.test_record.message_ids[0].author_id, portal_user.partner_id)
@users('employee')
def test_mail_composer_save_template(self):
self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record, add_web=False)
).create({
'subject': 'Template Subject',
'body': '<p>Template Body</p>',
}).action_save_as_template()
# Test: email_template subject, body_html, model
template = self.env['mail.template'].search([
('model', '=', self.test_record._name),
('subject', '=', 'Template Subject')
], limit=1)
self.assertEqual(template.name, "%s: %s" % (self.env['ir.model']._get(self.test_record._name).name, 'Template Subject'))
self.assertEqual(template.body_html, '<p>Template Body</p>', 'email_template incorrect body_html')
@tagged('mail_composer')
class TestComposerResultsComment(TestMailComposer):
""" Test global output of composer used in comment mode. Test notably
notification and emails generated during this process. """
@users('employee')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_composer_document_based(self):
""" Tests a document-based mass mailing with the same address mails
This should be allowed and not considered as duplicate in this context
"""
attachment_data = self._generate_attachments_data(2)
email_to_1 = self.test_record.customer_id.email
self.template.write({
'auto_delete': False, # keep sent emails to check content
'attachment_ids': [(0, 0, a) for a in attachment_data],
'email_to': '%s, %s' % (email_to_1, email_to_1),
'report_name': 'TestReport for {{ object.name }}', # test cursor forces html
'report_template': self.test_report.id,
})
# launch composer in mass mode
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record, add_web=True,
default_template_id=self.template.id)
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=False), self.mock_mail_app():
composer.with_context(mailing_document_based=True)._action_send_mail()
self.assertEqual(len(self._mails), 2, 'Should have sent 2 emails.')
@users('employee')
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_mail_composer_notifications_delete(self):
""" Notifications are correctly deleted once sent """
composer = self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record)
).create({
'body': '<p>Test Body</p>',
'partner_ids': [(4, self.partner_1.id), (4, self.partner_2.id)]
})
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# notifications
message = self.test_record.message_ids[0]
self.assertEqual(message.notified_partner_ids, self.partner_employee_2 + self.partner_1 + self.partner_2)
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 2 mail.mail (1 for users, 1 for customers)')
self.assertEqual(len(self._mails), 3, 'Should have sent an email each recipient')
self.assertEqual(self._new_mails.exists(), self.env['mail.mail'], 'Should have deleted mail.mail records')
# ensure ``mail_auto_delete`` context key allow to override this behavior
composer = self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record),
mail_auto_delete=False,
).create({
'body': '<p>Test Body</p>',
'partner_ids': [(4, self.partner_1.id), (4, self.partner_2.id)]
})
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# notifications
message = self.test_record.message_ids[0]
self.assertEqual(message.notified_partner_ids, self.partner_employee_2 + self.partner_1 + self.partner_2)
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 2 mail.mail (1 for users, 1 for customers)')
self.assertEqual(len(self._mails), 3, 'Should have sent an email each recipient')
self.assertEqual(len(self._new_mails.exists()), 2, 'Should not have deleted mail.mail records')
@users('employee')
@mute_logger('odoo.tests', 'odoo.addons.mail.models.mail_mail', 'odoo.models.unlink')
def test_mail_composer_recipients(self):
""" Test partner_ids given to composer are given to the final message. """
composer = self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record)
).create({
'body': '<p>Test Body</p>',
'partner_ids': [(4, self.partner_1.id), (4, self.partner_2.id)]
})
composer._action_send_mail()
message = self.test_record.message_ids[0]
self.assertEqual(message.body, '<p>Test Body</p>')
self.assertEqual(message.author_id, self.user_employee.partner_id)
self.assertEqual(message.subject, 'Re: %s' % self.test_record.name)
self.assertEqual(message.subtype_id, self.env.ref('mail.mt_comment'))
self.assertEqual(message.partner_ids, self.partner_1 | self.partner_2)
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl_complete(self):
""" Test a posting process using a complex template, holding several
additional recipients and attachments.
This tests notifies: 2 new email_to (+ 1 duplicated), 1 email_cc,
test_record followers and partner_admin added in partner_to."""
attachment_data = self._generate_attachments_data(2)
email_to_1 = 'test.to.1@test.example.com'
email_to_2 = 'test.to.2@test.example.com'
email_to_3 = 'test.to.1@test.example.com' # duplicate: should not sent twice the email
email_cc_1 = 'test.cc.1@test.example.com'
self.template.write({
'auto_delete': False, # keep sent emails to check content
'attachment_ids': [(0, 0, a) for a in attachment_data],
'email_to': '%s, %s, %s' % (email_to_1, email_to_2, email_to_3),
'email_cc': email_cc_1,
'partner_to': '%s, {{ object.customer_id.id if object.customer_id else "" }}' % self.partner_admin.id,
'report_name': 'TestReport for {{ object.name }}', # test cursor forces html
'report_template': self.test_report.id,
})
attachs = self.env['ir.attachment'].search([('name', 'in', [a['name'] for a in attachment_data])])
self.assertEqual(len(attachs), 2)
# ensure initial data
self.assertEqual(self.test_record.user_id, self.user_employee_2)
self.assertEqual(self.test_record.message_partner_ids, self.partner_employee_2)
# open a composer and run it in comment mode
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_record, add_web=True,
default_template_id=self.template.id)
))
composer = composer_form.save()
self.assertFalse(composer.reply_to_force_new, 'Mail: thread-enabled models should use auto thread by default')
with self.mock_mail_gateway(mail_unlink_sent=False), self.mock_mail_app():
composer._action_send_mail()
# check new partners have been created based on emails given
new_partners = self.env['res.partner'].search([
('email', 'in', [email_to_1, email_to_2, email_to_3, email_cc_1])
])
self.assertEqual(len(new_partners), 3)
self.assertEqual(set(new_partners.mapped('email')),
set(['test.to.1@test.example.com', 'test.to.2@test.example.com', 'test.cc.1@test.example.com'])
)
# global outgoing: one mail.mail (all customer recipients, then all employee recipients)
# and 5 emails, and 1 inbox notification (admin)
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail')
self.assertEqual(len(self._mails), 5, 'Should have sent 5 emails, one per recipient')
# template is sent only to partners (email_to are transformed)
message = self.test_record.message_ids[0]
self.assertMailMail(self.partner_employee_2, 'sent',
mail_message=message,
author=self.partner_employee, # author != email_from (template sets only email_from)
email_values={
'body_content': 'TemplateBody %s' % self.test_record.name,
'email_from': self.test_record.user_id.email_formatted, # set by template
'subject': 'TemplateSubject %s' % self.test_record.name,
'attachments_info': [
{'name': '00.txt', 'raw': b'Att00', 'type': 'text/plain'},
{'name': '01.txt', 'raw': b'Att01', 'type': 'text/plain'},
{'name': 'TestReport for %s.html' % self.test_record.name, 'type': 'text/plain'},
]
},
fields_values={},
)
self.assertMailMail(self.test_record.customer_id + new_partners, 'sent',
mail_message=message,
author=self.partner_employee, # author != email_from (template sets only email_from)
email_values={
'body_content': 'TemplateBody %s' % self.test_record.name,
'email_from': self.test_record.user_id.email_formatted, # set by template
'subject': 'TemplateSubject %s' % self.test_record.name,
'attachments_info': [
{'name': '00.txt', 'raw': b'Att00', 'type': 'text/plain'},
{'name': '01.txt', 'raw': b'Att01', 'type': 'text/plain'},
{'name': 'TestReport for %s.html' % self.test_record.name, 'type': 'text/plain'},
]
},
fields_values={},
)
# message is posted and notified admin
self.assertEqual(message.subtype_id, self.env.ref('mail.mt_comment'))
self.assertNotified(message, [{'partner': self.partner_admin, 'is_read': False, 'type': 'inbox'}])
# attachments are copied on message and linked to document
self.assertEqual(
set(message.attachment_ids.mapped('name')),
set(['00.txt', '01.txt', 'TestReport for %s.html' % self.test_record.name])
)
self.assertEqual(set(message.attachment_ids.mapped('res_model')), set([self.test_record._name]))
self.assertEqual(set(message.attachment_ids.mapped('res_id')), set(self.test_record.ids))
self.assertTrue(all(attach not in message.attachment_ids for attach in attachs), 'Should have copied attachments')
@tagged('mail_composer')
class TestComposerResultsMass(TestMailComposer):
@classmethod
def setUpClass(cls):
super(TestComposerResultsMass, cls).setUpClass()
# ensure employee can create partners, necessary for templates
cls.user_employee.write({
'groups_id': [(4, cls.env.ref('base.group_partner_manager').id)],
})
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl(self):
self.template.auto_delete = False # keep sent emails to check content
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id)
))
composer = composer_form.save()
self.assertFalse(composer.reply_to_force_new, 'Mail: thread-enabled models should use auto thread by default')
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 2, 'Should have sent 1 email per record')
for record in self.test_records:
# message copy is kept
message = record.message_ids[0]
# template is sent directly using customer field, meaning we have recipients
self.assertMailMail(record.customer_id, 'sent',
mail_message=message,
author=self.partner_employee)
# message content
self.assertEqual(message.subject, 'TemplateSubject %s' % record.name)
self.assertEqual(message.body, '<p>TemplateBody %s</p>' % record.name)
self.assertEqual(message.author_id, self.user_employee.partner_id)
# post-related fields are void
self.assertEqual(message.subtype_id, self.env['mail.message.subtype'])
self.assertEqual(message.partner_ids, self.env['res.partner'])
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl_complete(self):
""" Test a composer in mass mode with a quite complete template, containing
notably email-based recipients and attachments. """
attachment_data = self._generate_attachments_data(2)
email_to_1 = 'test.to.1@test.example.com'
email_to_2 = 'test.to.2@test.example.com'
email_to_3 = 'test.to.1@test.example.com' # duplicate: should not sent twice the email
email_cc_1 = 'test.cc.1@test.example.com'
self.template.write({
'auto_delete': False, # keep sent emails to check content
'attachment_ids': [(0, 0, a) for a in attachment_data],
'email_to': '%s, %s, %s' % (email_to_1, email_to_2, email_to_3),
'email_cc': email_cc_1,
'partner_to': '%s, {{ object.customer_id.id if object.customer_id else "" }}' % self.partner_admin.id,
'report_name': 'TestReport for {{ object.name }}', # test cursor forces html
'report_template': self.test_report.id,
})
attachs = self.env['ir.attachment'].search([('name', 'in', [a['name'] for a in attachment_data])])
self.assertEqual(len(attachs), 2)
# ensure initial data
self.assertEqual(self.test_records.user_id, self.env['res.users'])
self.assertEqual(self.test_records.message_partner_ids, self.env['res.partner'])
# launch composer in mass mode
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id)
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=False):
composer._action_send_mail()
new_partners = self.env['res.partner'].search([
('email', 'in', [email_to_1, email_to_2, email_to_3, email_cc_1])
])
self.assertEqual(len(new_partners), 3)
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 10, 'Should have sent 5 emails per record')
# hack to use assertEmails: filtering on from/to only is not sufficient to distinguish emails
_mails_records = [
[mail for mail in self._mails if '%s-%s' % (record.id, record._name) in mail['message_id']]
for record in self.test_records
]
for record, _mails in zip(self.test_records, _mails_records):
# message copy is kept
message = record.message_ids[0]
# template is sent only to partners (email_to are transformed)
self._mails = _mails
self.assertMailMail(record.customer_id + new_partners + self.partner_admin,
'sent',
mail_message=message,
author=self.partner_employee,
email_values={
'attachments_info': [
{'name': '00.txt', 'raw': b'Att00', 'type': 'text/plain'},
{'name': '01.txt', 'raw': b'Att01', 'type': 'text/plain'},
{'name': 'TestReport for %s.html' % record.name, 'type': 'text/plain'},
],
'body_content': 'TemplateBody %s' % record.name,
'email_from': self.partner_employee.email_formatted,
'reply_to': formataddr((
f'{self.env.user.company_id.name} {record.name}',
f'{self.alias_catchall}@{self.alias_domain}'
)),
'subject': 'TemplateSubject %s' % record.name,
},
fields_values={
'email_from': self.partner_employee.email_formatted,
'reply_to': formataddr((
f'{self.env.user.company_id.name} {record.name}',
f'{self.alias_catchall}@{self.alias_domain}'
)),
},
)
# test without catchall filling reply-to
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id)
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=True):
# remove alias so that _notify_get_reply_to will return the default value instead of alias
self.env['ir.config_parameter'].sudo().set_param("mail.catchall.domain", None)
composer.action_send_mail()
# hack to use assertEmails: filtering on from/to only is not sufficient to distinguish emails
_mails_records = [
[mail for mail in self._mails if '%s-%s' % (record.id, record._name) in mail['message_id']]
for record in self.test_records
]
for record, _mails in zip(self.test_records, _mails_records):
# template is sent only to partners (email_to are transformed)
self._mails = _mails
self.assertMailMail(record.customer_id + new_partners + self.partner_admin,
'sent',
mail_message=record.message_ids[0],
author=self.partner_employee,
email_values={
'email_from': self.partner_employee.email_formatted,
'reply_to': self.partner_employee.email_formatted,
},
fields_values={
'email_from': self.partner_employee.email_formatted,
'reply_to': self.partner_employee.email_formatted,
},
)
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl_delete(self):
self.template.auto_delete = True
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id)
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 2, 'Should have sent 1 email per record')
self.assertEqual(self._new_mails.exists(), self.env['mail.mail'], 'Should have deleted mail.mail records')
for record in self.test_records:
# message copy is kept
message = record.message_ids[0]
# template is sent directly using customer field
self.assertSentEmail(self.partner_employee, record.customer_id)
# message content
self.assertEqual(message.subject, 'TemplateSubject %s' % record.name)
self.assertEqual(message.body, '<p>TemplateBody %s</p>' % record.name)
self.assertEqual(message.author_id, self.user_employee.partner_id)
# post-related fields are void
self.assertEqual(message.subtype_id, self.env['mail.message.subtype'])
self.assertEqual(message.partner_ids, self.env['res.partner'])
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl_delete_notif(self):
self.template.auto_delete = True
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id,
default_auto_delete_message=True)
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 2, 'Should have sent 1 email per record')
self.assertEqual(self._new_mails.exists(), self.env['mail.mail'], 'Should have deleted mail.mail records')
for record in self.test_records:
# message copy is unlinked
self.assertEqual(record.message_ids, self.env['mail.message'], 'Should have deleted mail.message records')
# template is sent directly using customer field
self.assertSentEmail(self.partner_employee, record.customer_id)
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl_recipients(self):
""" Test various combinations of recipients: active_domain, active_id,
active_ids, ... to ensure fallback behavior are working. """
# 1: active_domain
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id,
active_ids=[],
default_use_active_domain=True,
default_active_domain=[('id', 'in', self.test_records.ids)])
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 2, 'Should have sent 1 email per record')
for record in self.test_records:
# template is sent directly using customer field
self.assertSentEmail(self.partner_employee, record.customer_id)
# 2: active_domain not taken into account if use_active_domain is False
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id,
default_use_active_domain=False,
default_active_domain=[('id', 'in', -1)])
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=True):
composer._action_send_mail()
# global outgoing
self.assertEqual(len(self._new_mails), 2, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 2, 'Should have sent 1 email per record')
# 3: fallback on active_id if not active_ids
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id,
active_ids=[])
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=False):
composer._action_send_mail()
# global outgoing
self.assertEqual(len(self._new_mails), 1, 'Should have created 1 mail.mail per record')
self.assertEqual(len(self._mails), 1, 'Should have sent 1 email per record')
# 3: void is void
composer_form = Form(self.env['mail.compose.message'].with_context(
default_model='mail.test.ticket',
default_template_id=self.template.id
))
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=False), self.assertRaises(ValueError):
composer._action_send_mail()
@users('employee')
@mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail')
def test_mail_composer_wtpl_reply_to_force_new(self):
""" Test no auto thread behavior, notably with reply-to. """
# launch composer in mass mode
composer_form = Form(self.env['mail.compose.message'].with_context(
self._get_web_context(self.test_records, add_web=True,
default_template_id=self.template.id)
))
composer_form.reply_to_force_new = True
composer_form.reply_to = "{{ '\"' + object.name + '\" <%s>' % 'dynamic.reply.to@test.com' }}"
composer = composer_form.save()
with self.mock_mail_gateway(mail_unlink_sent=False):
composer.action_send_mail()
for record in self.test_records:
self.assertMailMail(record.customer_id,
'sent',
mail_message=record.message_ids[0],
author=self.partner_employee,
email_values={
'body_content': 'TemplateBody %s' % record.name,
'email_from': self.partner_employee.email_formatted,
'reply_to': formataddr((
f'{record.name}',
'dynamic.reply.to@test.com'
)),
'subject': 'TemplateSubject %s' % record.name,
},
fields_values={
'email_from': self.partner_employee.email_formatted,
'reply_to': formataddr((
f'{record.name}',
'dynamic.reply.to@test.com'
)),
},
)
| 51.519326
| 51,983
|
6,542
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import socket
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.tools import formataddr
@tagged('multi_company')
class TestMultiCompanySetup(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestMultiCompanySetup, cls).setUpClass()
cls._activate_multi_company()
cls.test_model = cls.env['ir.model']._get('mail.test.gateway')
cls.email_from = '"Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>'
cls.test_record = cls.env['mail.test.gateway'].with_context(cls._test_context).create({
'name': 'Test',
'email_from': 'ignasse@example.com',
}).with_context({})
cls.partner_1 = cls.env['res.partner'].with_context(cls._test_context).create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com',
})
# groups@.. will cause the creation of new mail.test.gateway
cls.alias = cls.env['mail.alias'].create({
'alias_name': 'groups',
'alias_user_id': False,
'alias_model_id': cls.test_model.id,
'alias_contact': 'everyone'})
# Set a first message on public group to test update and hierarchy
cls.fake_email = cls.env['mail.message'].create({
'model': 'mail.test.gateway',
'res_id': cls.test_record.id,
'subject': 'Public Discussion',
'message_type': 'email',
'subtype_id': cls.env.ref('mail.mt_comment').id,
'author_id': cls.partner_1.id,
'message_id': '<123456-openerp-%s-mail.test.gateway@%s>' % (cls.test_record.id, socket.gethostname()),
})
cls._init_mail_gateway()
@users('employee')
def test_notify_reply_to_computation(self):
test_record = self.env['mail.test.gateway'].browse(self.test_record.ids)
res = test_record._notify_get_reply_to()
self.assertEqual(
res[test_record.id],
formataddr((
"%s %s" % (self.user_employee.company_id.name, test_record.name),
"%s@%s" % (self.alias_catchall, self.alias_domain)))
)
@users('employee_c2')
def test_notify_reply_to_computation_mc(self):
""" Test reply-to computation in multi company mode. Add notably tests
depending on user and records company_id / company_ids. """
company_3 = self.env['res.company'].sudo().create({'name': 'ELIT'})
# Test1: no company_id field
test_record = self.env['mail.test.gateway'].browse(self.test_record.ids)
res = test_record._notify_get_reply_to()
self.assertEqual(
res[test_record.id],
formataddr((
"%s %s" % (self.user_employee_c2.company_id.name, test_record.name),
"%s@%s" % (self.alias_catchall, self.alias_domain)))
)
# Test2: MC environment get default value from env
self.user_employee_c2.write({'company_ids': [(4, self.user_employee.company_id.id)]})
test_records = self.env['mail.test.multi.company'].create([
{'name': 'Test',
'company_id': self.user_employee.company_id.id},
{'name': 'Test',
'company_id': self.user_employee_c2.company_id.id},
])
res = test_records._notify_get_reply_to()
for test_record in test_records:
self.assertEqual(
res[test_record.id],
formataddr((
"%s %s" % (self.user_employee_c2.company_id.name, test_record.name),
"%s@%s" % (self.alias_catchall, self.alias_domain)))
)
# Test3: get company from record (company_id field)
test_records = self.env['mail.test.multi.company'].create([
{'name': 'Test1',
'company_id': company_3.id},
{'name': 'Test2',
'company_id': company_3.id},
])
res = test_records._notify_get_reply_to()
for test_record in test_records:
self.assertEqual(
res[test_record.id],
formataddr((
"%s %s" % (company_3.name, test_record.name),
"%s@%s" % (self.alias_catchall, self.alias_domain)))
)
def test_systray_get_activities(self):
self.env["mail.activity"].search([]).unlink()
user_admin = self.user_admin.with_user(self.user_admin)
test_records = self.env["mail.test.multi.company.with.activity"].create(
[
{"name": "Test1", "company_id": user_admin.company_id.id},
{"name": "Test2", "company_id": self.company_2.id},
]
)
test_records[0].activity_schedule("test_mail.mail_act_test_todo", user_id=user_admin.id)
test_records[1].activity_schedule("test_mail.mail_act_test_todo", user_id=user_admin.id)
test_activity = next(
a for a in user_admin.systray_get_activities()
if a['model'] == 'mail.test.multi.company.with.activity'
)
self.assertEqual(
test_activity,
{
"actions": [{"icon": "fa-clock-o", "name": "Summary"}],
"icon": "/base/static/description/icon.png",
"model": "mail.test.multi.company.with.activity",
"name": "Test Multi Company Mail With Activity",
"overdue_count": 0,
"planned_count": 0,
"today_count": 2,
"total_count": 2,
"type": "activity",
}
)
test_activity = next(
a for a in user_admin.with_context(allowed_company_ids=[self.company_2.id]).systray_get_activities()
if a['model'] == 'mail.test.multi.company.with.activity'
)
self.assertEqual(
test_activity,
{
"actions": [{"icon": "fa-clock-o", "name": "Summary"}],
"icon": "/base/static/description/icon.png",
"model": "mail.test.multi.company.with.activity",
"name": "Test Multi Company Mail With Activity",
"overdue_count": 0,
"planned_count": 0,
"today_count": 1,
"total_count": 1,
"type": "activity",
}
)
| 41.144654
| 6,542
|
18,062
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from unittest.mock import DEFAULT
from werkzeug.urls import url_parse, url_decode
from odoo import exceptions
from odoo.addons.test_mail.models.test_mail_models import MailTestSimple
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.tests.common import tagged, HttpCase, users
from odoo.tools import mute_logger
@tagged('mail_thread')
class TestChatterTweaks(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestChatterTweaks, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
def test_post_no_subscribe_author(self):
original = self.test_record.message_follower_ids
self.test_record.with_user(self.user_employee).with_context({'mail_create_nosubscribe': True}).message_post(
body='Test Body', message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertEqual(self.test_record.message_follower_ids.mapped('partner_id'), original.mapped('partner_id'))
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_no_subscribe_recipients(self):
original = self.test_record.message_follower_ids
self.test_record.with_user(self.user_employee).with_context({'mail_create_nosubscribe': True}).message_post(
body='Test Body', message_type='comment', subtype_xmlid='mail.mt_comment', partner_ids=[self.partner_1.id, self.partner_2.id])
self.assertEqual(self.test_record.message_follower_ids.mapped('partner_id'), original.mapped('partner_id'))
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_subscribe_recipients(self):
original = self.test_record.message_follower_ids
self.test_record.with_user(self.user_employee).with_context({'mail_create_nosubscribe': True, 'mail_post_autofollow': True}).message_post(
body='Test Body', message_type='comment', subtype_xmlid='mail.mt_comment', partner_ids=[self.partner_1.id, self.partner_2.id])
self.assertEqual(self.test_record.message_follower_ids.mapped('partner_id'), original.mapped('partner_id') | self.partner_1 | self.partner_2)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_chatter_context_cleaning(self):
""" Test default keys are not propagated to message creation as it may
induce wrong values for some fields, like parent_id. """
parent = self.env['res.partner'].create({'name': 'Parent'})
partner = self.env['res.partner'].with_context(default_parent_id=parent.id).create({'name': 'Contact'})
self.assertFalse(partner.message_ids[-1].parent_id)
def test_chatter_mail_create_nolog(self):
""" Test disable of automatic chatter message at create """
rec = self.env['mail.test.simple'].with_user(self.user_employee).with_context({'mail_create_nolog': True}).create({'name': 'Test'})
self.flush_tracking()
self.assertEqual(rec.message_ids, self.env['mail.message'])
rec = self.env['mail.test.simple'].with_user(self.user_employee).with_context({'mail_create_nolog': False}).create({'name': 'Test'})
self.flush_tracking()
self.assertEqual(len(rec.message_ids), 1)
def test_chatter_mail_notrack(self):
""" Test disable of automatic value tracking at create and write """
rec = self.env['mail.test.track'].with_user(self.user_employee).create({'name': 'Test', 'user_id': self.user_employee.id})
self.flush_tracking()
self.assertEqual(len(rec.message_ids), 1,
"A creation message without tracking values should have been posted")
self.assertEqual(len(rec.message_ids.sudo().tracking_value_ids), 0,
"A creation message without tracking values should have been posted")
rec.with_context({'mail_notrack': True}).write({'user_id': self.user_admin.id})
self.flush_tracking()
self.assertEqual(len(rec.message_ids), 1,
"No new message should have been posted with mail_notrack key")
rec.with_context({'mail_notrack': False}).write({'user_id': self.user_employee.id})
self.flush_tracking()
self.assertEqual(len(rec.message_ids), 2,
"A tracking message should have been posted")
self.assertEqual(len(rec.message_ids.sudo().mapped('tracking_value_ids')), 1,
"New tracking message should have tracking values")
def test_chatter_tracking_disable(self):
""" Test disable of all chatter features at create and write """
rec = self.env['mail.test.track'].with_user(self.user_employee).with_context({'tracking_disable': True}).create({'name': 'Test', 'user_id': self.user_employee.id})
self.flush_tracking()
self.assertEqual(rec.sudo().message_ids, self.env['mail.message'])
self.assertEqual(rec.sudo().mapped('message_ids.tracking_value_ids'), self.env['mail.tracking.value'])
rec.write({'user_id': self.user_admin.id})
self.flush_tracking()
self.assertEqual(rec.sudo().mapped('message_ids.tracking_value_ids'), self.env['mail.tracking.value'])
rec.with_context({'tracking_disable': False}).write({'user_id': self.user_employee.id})
self.flush_tracking()
self.assertEqual(len(rec.sudo().mapped('message_ids.tracking_value_ids')), 1)
rec = self.env['mail.test.track'].with_user(self.user_employee).with_context({'tracking_disable': False}).create({'name': 'Test', 'user_id': self.user_employee.id})
self.flush_tracking()
self.assertEqual(len(rec.sudo().message_ids), 1,
"Creation message without tracking values should have been posted")
self.assertEqual(len(rec.sudo().mapped('message_ids.tracking_value_ids')), 0,
"Creation message without tracking values should have been posted")
def test_cache_invalidation(self):
""" Test that creating a mail-thread record does not invalidate the whole cache. """
# make a new record in cache
record = self.env['res.partner'].new({'name': 'Brave New Partner'})
self.assertTrue(record.name)
# creating a mail-thread record should not invalidate the whole cache
self.env['res.partner'].create({'name': 'Actual Partner'})
self.assertTrue(record.name)
class TestDiscuss(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestDiscuss, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({
'name': 'Test',
'email_from': 'ignasse@example.com'
})
@mute_logger('openerp.addons.mail.models.mail_mail')
def test_mark_all_as_read(self):
def _employee_crash(*args, **kwargs):
""" If employee is test employee, consider he has no access on document """
recordset = args[0]
if recordset.env.uid == self.user_employee.id and not recordset.env.su:
if kwargs.get('raise_exception', True):
raise exceptions.AccessError('Hop hop hop Ernest, please step back.')
return False
return DEFAULT
with patch.object(MailTestSimple, 'check_access_rights', autospec=True, side_effect=_employee_crash):
with self.assertRaises(exceptions.AccessError):
self.env['mail.test.simple'].with_user(self.user_employee).browse(self.test_record.ids).read(['name'])
employee_partner = self.env['res.partner'].with_user(self.user_employee).browse(self.partner_employee.ids)
# mark all as read clear needactions
msg1 = self.test_record.message_post(body='Test', message_type='comment', subtype_xmlid='mail.mt_comment', partner_ids=[employee_partner.id])
self._reset_bus()
with self.assertBus(
[(self.cr.dbname, 'res.partner', employee_partner.id)],
message_items=[{
'type': 'mail.message/mark_as_read',
'payload': {
'message_ids': [msg1.id],
'needaction_inbox_counter': 0,
},
}]):
employee_partner.env['mail.message'].mark_all_as_read(domain=[])
na_count = employee_partner._get_needaction_count()
self.assertEqual(na_count, 0, "mark all as read should conclude all needactions")
# mark all as read also clear inaccessible needactions
msg2 = self.test_record.message_post(body='Zest', message_type='comment', subtype_xmlid='mail.mt_comment', partner_ids=[employee_partner.id])
needaction_accessible = len(employee_partner.env['mail.message'].search([['needaction', '=', True]]))
self.assertEqual(needaction_accessible, 1, "a new message to a partner is readable to that partner")
msg2.sudo().partner_ids = self.env['res.partner']
employee_partner.env['mail.message'].search([['needaction', '=', True]])
needaction_length = len(employee_partner.env['mail.message'].search([['needaction', '=', True]]))
self.assertEqual(needaction_length, 1, "message should still be readable when notified")
na_count = employee_partner._get_needaction_count()
self.assertEqual(na_count, 1, "message not accessible is currently still counted")
self._reset_bus()
with self.assertBus(
[(self.cr.dbname, 'res.partner', employee_partner.id)],
message_items=[{
'type': 'mail.message/mark_as_read',
'payload': {
'message_ids': [msg2.id],
'needaction_inbox_counter': 0,
},
}]):
employee_partner.env['mail.message'].mark_all_as_read(domain=[])
na_count = employee_partner._get_needaction_count()
self.assertEqual(na_count, 0, "mark all read should conclude all needactions even inacessible ones")
def test_set_message_done_user(self):
with self.assertSinglePostNotifications([{'partner': self.partner_employee, 'type': 'inbox'}], message_info={'content': 'Test'}):
message = self.test_record.message_post(
body='Test', message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.user_employee.partner_id.id])
message.with_user(self.user_employee).set_message_done()
self.assertMailNotifications(message, [{'notif': [{'partner': self.partner_employee, 'type': 'inbox', 'is_read': True}]}])
# TDE TODO: it seems bus notifications could be checked
def test_set_star(self):
msg = self.test_record.with_user(self.user_admin).message_post(body='My Body', subject='1')
msg_emp = self.env['mail.message'].with_user(self.user_employee).browse(msg.id)
# Admin set as starred
msg.toggle_message_starred()
self.assertTrue(msg.starred)
# Employee set as starred
msg_emp.toggle_message_starred()
self.assertTrue(msg_emp.starred)
# Do: Admin unstars msg
msg.toggle_message_starred()
self.assertFalse(msg.starred)
self.assertTrue(msg_emp.starred)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_mail_cc_recipient_suggestion(self):
record = self.env['mail.test.cc'].create({'email_cc': 'cc1@example.com, cc2@example.com, cc3 <cc3@example.com>'})
suggestions = record._message_get_suggested_recipients()[record.id]
self.assertEqual(sorted(suggestions), [
(False, '"cc3" <cc3@example.com>', 'CC Email'),
(False, 'cc1@example.com', 'CC Email'),
(False, 'cc2@example.com', 'CC Email'),
], 'cc should be in suggestions')
def test_inbox_message_fetch_needaction(self):
user1 = self.env['res.users'].create({'login': 'user1', 'name': 'User 1'})
user1.notification_type = 'inbox'
user2 = self.env['res.users'].create({'login': 'user2', 'name': 'User 2'})
user2.notification_type = 'inbox'
message1 = self.test_record.with_user(self.user_admin).message_post(body='Message 1', partner_ids=[user1.partner_id.id, user2.partner_id.id])
message2 = self.test_record.with_user(self.user_admin).message_post(body='Message 2', partner_ids=[user1.partner_id.id, user2.partner_id.id])
# both notified users should have the 2 messages in Inbox initially
messages = self.env['mail.message'].with_user(user1)._message_fetch(domain=[['needaction', '=', True]])
self.assertEqual(len(messages), 2)
messages = self.env['mail.message'].with_user(user2)._message_fetch(domain=[['needaction', '=', True]])
self.assertEqual(len(messages), 2)
# first user is marking one message as done: the other message is still Inbox, while the other user still has the 2 messages in Inbox
message1.with_user(user1).set_message_done()
messages = self.env['mail.message'].with_user(user1)._message_fetch(domain=[['needaction', '=', True]])
self.assertEqual(len(messages), 1)
self.assertEqual(messages[0].get('id'), message2.id)
messages = self.env['mail.message'].with_user(user2)._message_fetch(domain=[['needaction', '=', True]])
self.assertEqual(len(messages), 2)
def test_notification_has_error_filter(self):
"""Ensure message_has_error filter is only returning threads for which
the current user is author of a failed message."""
message = self.test_record.with_user(self.user_admin).message_post(
body='Test', message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.user_employee.partner_id.id]
)
self.assertFalse(message.has_error)
with self.mock_mail_gateway(sim_error='connect_smtp_notfound'):
self.user_admin.notification_type = 'email'
message2 = self.test_record.with_user(self.user_employee).message_post(
body='Test', message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.user_admin.partner_id.id]
)
self.assertTrue(message2.has_error)
# employee is author of message which has a failure
threads_employee = self.test_record.with_user(self.user_employee).search([('message_has_error', '=', True)])
self.assertEqual(len(threads_employee), 1)
# admin is also author of a message, but it doesn't have a failure
# and the failure from employee's message should not be taken into account for admin
threads_admin = self.test_record.with_user(self.user_admin).search([('message_has_error', '=', True)])
self.assertEqual(len(threads_admin), 0)
@users("employee")
def test_unlink_notification_message(self):
channel = self.env['mail.channel'].create({'name': 'testChannel'})
channel.message_notify(
body='test',
message_type='user_notification',
partner_ids=[self.partner_2.id],
author_id=2
)
channel_message = self.env['mail.message'].sudo().search([('model', '=', 'mail.channel'), ('res_id', 'in', channel.ids)])
self.assertEqual(len(channel_message), 1, "Test message should have been posted")
channel.sudo().unlink()
remaining_message = channel_message.exists()
self.assertEqual(len(remaining_message), 0, "Test message should have been deleted")
@tagged('-at_install', 'post_install')
class TestMultiCompany(HttpCase):
def test_redirect_to_records(self):
self.company_A = self.env['res.company'].create({
'name': 'Company A',
'user_ids': [(4, self.ref('base.user_admin'))],
})
self.company_B = self.env['res.company'].create({
'name': 'Company B',
})
self.multi_company_record = self.env['mail.test.multi.company'].create({
'name': 'Multi Company Record',
'company_id': self.company_A.id,
})
# Test Case 0
# Not logged, redirect to web/login
response = self.url_open('/mail/view?model=%s&res_id=%s' % (
self.multi_company_record._name,
self.multi_company_record.id), timeout=15)
path = url_parse(response.url).path
self.assertEqual(path, '/web/login')
self.authenticate('admin', 'admin')
# Test Case 1
# Logged into company 1, try accessing record in company A
# _redirect_to_record should add company A in allowed_company_ids
response = self.url_open('/mail/view?model=%s&res_id=%s' % (
self.multi_company_record._name,
self.multi_company_record.id), timeout=15)
self.assertEqual(response.status_code, 200)
fragment = url_parse(response.url).fragment
cids = url_decode(fragment)['cids']
self.assertEqual(cids, '1,%s' % (self.company_A.id))
# Test Case 2
# Logged into company 1, try accessing record in company B
# _redirect_to_record should redirect to messaging as the user
# doesn't have any access for this company
self.multi_company_record.company_id = self.company_B
response = self.url_open('/mail/view?model=%s&res_id=%s' % (
self.multi_company_record._name,
self.multi_company_record.id), timeout=15)
self.assertEqual(response.status_code, 200)
fragment = url_parse(response.url).fragment
action = url_decode(fragment)['action']
self.assertEqual(action, 'mail.action_discuss')
| 52.658892
| 18,062
|
26,105
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from psycopg2 import IntegrityError
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.tests import tagged
from odoo.tests import users
from odoo.tools.misc import mute_logger
from odoo.tests.common import users
@tagged('mail_followers')
class BaseFollowersTest(TestMailCommon):
@classmethod
def setUpClass(cls):
super(BaseFollowersTest, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
cls._create_portal_user()
cls._create_channel_listener()
# allow employee to update partners
cls.user_employee.write({'groups_id': [(4, cls.env.ref('base.group_partner_manager').id)]})
Subtype = cls.env['mail.message.subtype']
# global
cls.mt_al_def = Subtype.create({'name': 'mt_al_def', 'default': True, 'res_model': False})
cls.mt_al_nodef = Subtype.create({'name': 'mt_al_nodef', 'default': False, 'res_model': False})
# mail.test.simple
cls.mt_mg_def = Subtype.create({'name': 'mt_mg_def', 'default': True, 'res_model': 'mail.test.simple'})
cls.mt_mg_nodef = Subtype.create({'name': 'mt_mg_nodef', 'default': False, 'res_model': 'mail.test.simple'})
cls.mt_mg_def_int = Subtype.create({'name': 'mt_mg_def', 'default': True, 'res_model': 'mail.test.simple', 'internal': True})
# mail.test.container
cls.mt_cl_def = Subtype.create({'name': 'mt_cl_def', 'default': True, 'res_model': 'mail.test.container'})
cls.default_group_subtypes = Subtype.search([('default', '=', True), '|', ('res_model', '=', 'mail.test.simple'), ('res_model', '=', False)])
cls.default_group_subtypes_portal = Subtype.search([('internal', '=', False), ('default', '=', True), '|', ('res_model', '=', 'mail.test.simple'), ('res_model', '=', False)])
def test_field_message_is_follower(self):
test_record = self.test_record.with_user(self.user_employee)
followed_before = test_record.search([('message_is_follower', '=', True)])
self.assertFalse(test_record.message_is_follower)
test_record.message_subscribe(partner_ids=[self.user_employee.partner_id.id])
followed_after = test_record.search([('message_is_follower', '=', True)])
self.assertTrue(test_record.message_is_follower)
self.assertEqual(followed_before | test_record, followed_after)
def test_field_followers(self):
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.user_employee.partner_id.id, self.user_admin.partner_id.id])
followers = self.env['mail.followers'].search([
('res_model', '=', 'mail.test.simple'),
('res_id', '=', test_record.id)])
self.assertEqual(followers, test_record.message_follower_ids)
self.assertEqual(test_record.message_partner_ids, self.user_employee.partner_id | self.user_admin.partner_id)
def test_followers_subtypes_default(self):
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.user_employee.partner_id.id])
self.assertEqual(test_record.message_partner_ids, self.user_employee.partner_id)
follower = self.env['mail.followers'].search([
('res_model', '=', 'mail.test.simple'),
('res_id', '=', test_record.id),
('partner_id', '=', self.user_employee.partner_id.id)])
self.assertEqual(follower, test_record.message_follower_ids)
self.assertEqual(follower.subtype_ids, self.default_group_subtypes)
def test_followers_subtypes_default_internal(self):
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.partner_portal.id])
self.assertEqual(test_record.message_partner_ids, self.partner_portal)
follower = self.env['mail.followers'].search([
('res_model', '=', 'mail.test.simple'),
('res_id', '=', test_record.id),
('partner_id', '=', self.partner_portal.id)])
self.assertEqual(follower.subtype_ids, self.default_group_subtypes_portal)
def test_followers_subtypes_specified(self):
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.user_employee.partner_id.id], subtype_ids=[self.mt_mg_nodef.id])
self.assertEqual(test_record.message_partner_ids, self.user_employee.partner_id)
follower = self.env['mail.followers'].search([
('res_model', '=', 'mail.test.simple'),
('res_id', '=', test_record.id),
('partner_id', '=', self.user_employee.partner_id.id)])
self.assertEqual(follower, test_record.message_follower_ids)
self.assertEqual(follower.subtype_ids, self.mt_mg_nodef)
def test_followers_multiple_subscription_force(self):
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.user_admin.partner_id.id], subtype_ids=[self.mt_mg_nodef.id])
self.assertEqual(test_record.message_partner_ids, self.user_admin.partner_id)
self.assertEqual(test_record.message_follower_ids.subtype_ids, self.mt_mg_nodef)
test_record.message_subscribe(partner_ids=[self.user_admin.partner_id.id], subtype_ids=[self.mt_mg_nodef.id, self.mt_al_nodef.id])
self.assertEqual(test_record.message_partner_ids, self.user_admin.partner_id)
self.assertEqual(test_record.message_follower_ids.subtype_ids, self.mt_mg_nodef | self.mt_al_nodef)
def test_followers_multiple_subscription_noforce(self):
""" Calling message_subscribe without subtypes on an existing subscription should not do anything (default < existing) """
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.user_admin.partner_id.id], subtype_ids=[self.mt_mg_nodef.id, self.mt_al_nodef.id])
self.assertEqual(test_record.message_partner_ids, self.user_admin.partner_id)
self.assertEqual(test_record.message_follower_ids.subtype_ids, self.mt_mg_nodef | self.mt_al_nodef)
# set new subtypes with force=False, meaning no rewriting of the subscription is done -> result should not change
test_record.message_subscribe(partner_ids=[self.user_admin.partner_id.id])
self.assertEqual(test_record.message_partner_ids, self.user_admin.partner_id)
self.assertEqual(test_record.message_follower_ids.subtype_ids, self.mt_mg_nodef | self.mt_al_nodef)
def test_followers_multiple_subscription_update(self):
""" Calling message_subscribe with subtypes on an existing subscription should replace them (new > existing) """
test_record = self.test_record.with_user(self.user_employee)
test_record.message_subscribe(partner_ids=[self.user_employee.partner_id.id], subtype_ids=[self.mt_mg_def.id, self.mt_cl_def.id])
self.assertEqual(test_record.message_partner_ids, self.user_employee.partner_id)
follower = self.env['mail.followers'].search([
('res_model', '=', 'mail.test.simple'),
('res_id', '=', test_record.id),
('partner_id', '=', self.user_employee.partner_id.id)])
self.assertEqual(follower, test_record.message_follower_ids)
self.assertEqual(follower.subtype_ids, self.mt_mg_def | self.mt_cl_def)
# remove one subtype `mt_mg_def` and set new subtype `mt_al_def`
test_record.message_subscribe(partner_ids=[self.user_employee.partner_id.id], subtype_ids=[self.mt_cl_def.id, self.mt_al_def.id])
self.assertEqual(follower.subtype_ids, self.mt_cl_def | self.mt_al_def)
@users('employee')
def test_followers_inactive(self):
""" Test standard API does not subscribe inactive partners """
customer = self.env['res.partner'].create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com',
'country_id': self.env.ref('base.be').id,
'mobile': '0456001122',
'active': False,
})
document = self.env['mail.test.simple'].browse(self.test_record.id)
self.assertEqual(document.message_partner_ids, self.env['res.partner'])
document.message_subscribe(partner_ids=(self.partner_portal | customer).ids)
self.assertEqual(document.message_partner_ids, self.partner_portal)
self.assertEqual(document.message_follower_ids.partner_id, self.partner_portal)
# works through low-level API
document._message_subscribe(partner_ids=(self.partner_portal | customer).ids)
self.assertEqual(document.message_partner_ids, self.partner_portal, 'No active test: customer not visible')
self.assertEqual(document.message_follower_ids.partner_id, self.partner_portal | customer)
@users('employee')
def test_followers_private_address(self):
""" Test standard API does not subscribe private addresses """
private_address = self.env['res.partner'].sudo().create({
'name': 'Private Address',
'type': 'private',
})
document = self.env['mail.test.simple'].browse(self.test_record.id)
document.message_subscribe(partner_ids=(self.partner_portal | private_address).ids)
self.assertEqual(document.message_follower_ids.partner_id, self.partner_portal)
# works through low-level API
document._message_subscribe(partner_ids=(self.partner_portal | private_address).ids)
self.assertEqual(document.message_follower_ids.partner_id, self.partner_portal | private_address)
@users('employee')
def test_recipients_fetch_pids_only(self):
""" Test that _get_recipient_data correctly fetch groups for additional pids
"""
users = self.user_admin + self.user_employee + self.user_portal
recipient_data = self.env['mail.followers']._get_recipient_data(self.env['mail.thread'], False, False, pids=users.partner_id.ids)
groups = {pid: set(groups) for pid, _, _, _, groups in recipient_data}
self.assertEqual(groups[self.user_admin.partner_id.id], set(self.user_admin.groups_id.ids), "User Admin groups are not correctly fetched")
self.assertEqual(groups[self.user_employee.partner_id.id], set(self.user_employee.groups_id.ids), "User Employee groups are not correctly fetched")
self.assertEqual(groups[self.user_portal.partner_id.id], set(self.user_portal.groups_id.ids), "User Portal groups are not correctly fetched")
@tagged('mail_followers')
class AdvancedFollowersTest(TestMailCommon):
@classmethod
def setUpClass(cls):
super(AdvancedFollowersTest, cls).setUpClass()
cls._create_portal_user()
cls.test_track = cls.env['mail.test.track'].with_user(cls.user_employee).create({
'name': 'Test',
})
Subtype = cls.env['mail.message.subtype']
# clean demo data to avoid interferences
Subtype.search([('res_model', 'in', ['mail.test.container', 'mail.test.track'])]).unlink()
# mail.test.track subtypes (aka: task records)
cls.sub_track_1 = Subtype.create({
'name': 'Track (with child relation) 1', 'default': False,
'res_model': 'mail.test.track'
})
cls.sub_track_2 = Subtype.create({
'name': 'Track (with child relation) 2', 'default': False,
'res_model': 'mail.test.track'
})
cls.sub_track_nodef = Subtype.create({
'name': 'Generic Track subtype', 'default': False, 'internal': False,
'res_model': 'mail.test.track'
})
cls.sub_track_def = Subtype.create({
'name': 'Default track subtype', 'default': True, 'internal': False,
'res_model': 'mail.test.track'
})
# mail.test.container subtypes (aka: project records)
cls.umb_nodef = Subtype.create({
'name': 'Container NoDefault', 'default': False,
'res_model': 'mail.test.container'
})
cls.umb_def = Subtype.create({
'name': 'Container Default', 'default': True,
'res_model': 'mail.test.container'
})
cls.umb_def_int = Subtype.create({
'name': 'Container Default', 'default': True, 'internal': True,
'res_model': 'mail.test.container'
})
# -> subtypes for auto subscription from container to sub records
cls.umb_autosub_def = Subtype.create({
'name': 'Container AutoSub (default)', 'default': True, 'res_model': 'mail.test.container',
'parent_id': cls.sub_track_1.id, 'relation_field': 'container_id'
})
cls.umb_autosub_nodef = Subtype.create({
'name': 'Container AutoSub 2', 'default': False, 'res_model': 'mail.test.container',
'parent_id': cls.sub_track_2.id, 'relation_field': 'container_id'
})
# generic subtypes
cls.sub_comment = cls.env.ref('mail.mt_comment')
cls.sub_generic_int_nodef = Subtype.create({
'name': 'Generic internal subtype',
'default': False,
'internal': True,
})
cls.sub_generic_int_def = Subtype.create({
'name': 'Generic internal subtype (default)',
'default': True,
'internal': True,
})
def test_auto_subscribe_create(self):
""" Creator of records are automatically added as followers """
self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id)
def test_auto_subscribe_inactive(self):
""" Test inactive are not added as followers in automated subscription """
self.test_track.user_id = False
self.user_admin.active = False
self.user_admin.flush()
self.partner_admin.active = False
self.partner_admin.flush()
self.test_track.with_user(self.user_admin).message_post(body='Coucou hibou', message_type='comment')
self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id)
self.assertEqual(self.test_track.message_follower_ids.partner_id, self.user_employee.partner_id)
self.test_track.write({'user_id': self.user_admin.id})
self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id)
self.assertEqual(self.test_track.message_follower_ids.partner_id, self.user_employee.partner_id)
def test_auto_subscribe_post(self):
""" People posting a message are automatically added as followers """
self.test_track.with_user(self.user_admin).message_post(body='Coucou hibou', message_type='comment')
self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id | self.user_admin.partner_id)
def test_auto_subscribe_post_email(self):
""" People posting an email are automatically added as followers """
self.test_track.with_user(self.user_admin).message_post(body='Coucou hibou', message_type='email')
self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id | self.user_admin.partner_id)
def test_auto_subscribe_not_on_notification(self):
""" People posting an automatic notification are not subscribed """
self.test_track.with_user(self.user_admin).message_post(body='Coucou hibou', message_type='notification')
self.assertEqual(self.test_track.message_partner_ids, self.user_employee.partner_id)
def test_auto_subscribe_responsible(self):
""" Responsibles are tracked and added as followers """
sub = self.env['mail.test.track'].with_user(self.user_employee).create({
'name': 'Test',
'user_id': self.user_admin.id,
})
self.assertEqual(sub.message_partner_ids, (self.user_employee.partner_id | self.user_admin.partner_id))
def test_auto_subscribe_defaults(self):
""" Test auto subscription based on an container record. This mimics
the behavior of addons like project and task where subscribing to
some project's subtypes automatically subscribe the follower to its tasks.
Functional rules applied here
* subscribing to an container subtype with parent_id / relation_field set
automatically create subscription with matching subtypes
* subscribing to a sub-record as creator applies default subtype values
* portal user should not have access to internal subtypes
Inactive partners should not be auto subscribed.
"""
container = self.env['mail.test.container'].with_context(self._test_context).create({
'name': 'Project-Like',
})
# have an inactive partner to check auto subscribe does not subscribe it
user_root = self.env.ref('base.user_root')
self.assertFalse(user_root.active)
self.assertFalse(user_root.partner_id.active)
container.message_subscribe(partner_ids=(self.partner_portal | user_root.partner_id).ids)
container.message_subscribe(partner_ids=self.partner_admin.ids, subtype_ids=(self.sub_comment | self.umb_autosub_nodef | self.sub_generic_int_nodef).ids)
self.assertEqual(container.message_partner_ids, self.partner_portal | self.partner_admin)
follower_por = container.message_follower_ids.filtered(lambda f: f.partner_id == self.partner_portal)
follower_adm = container.message_follower_ids.filtered(lambda f: f.partner_id == self.partner_admin)
self.assertEqual(
follower_por.subtype_ids,
self.sub_comment | self.umb_def | self.umb_autosub_def,
'Subscribe: Default subtypes: comment (default generic) and two model-related defaults')
self.assertEqual(
follower_adm.subtype_ids,
self.sub_comment | self.umb_autosub_nodef | self.sub_generic_int_nodef,
'Subscribe: Asked subtypes when subscribing')
sub1 = self.env['mail.test.track'].with_user(self.user_employee).create({
'name': 'Task-Like Test',
'container_id': container.id,
})
self.assertEqual(
sub1.message_partner_ids, self.partner_portal | self.partner_admin | self.user_employee.partner_id,
'Followers: creator (employee) + auto subscribe from parent (portal)')
follower_por = sub1.message_follower_ids.filtered(lambda fol: fol.partner_id == self.partner_portal)
follower_adm = sub1.message_follower_ids.filtered(lambda fol: fol.partner_id == self.partner_admin)
follower_emp = sub1.message_follower_ids.filtered(lambda fol: fol.partner_id == self.user_employee.partner_id)
self.assertEqual(
follower_por.subtype_ids, self.sub_comment | self.sub_track_1,
'AutoSubscribe: comment (generic checked), Track (with child relation) 1 as Umbrella AutoSub (default) was checked'
)
self.assertEqual(
follower_adm.subtype_ids, self.sub_comment | self.sub_track_2 | self.sub_generic_int_nodef,
'AutoSubscribe: comment (generic checked), Track (with child relation) 2) as Umbrella AutoSub 2 was checked, Generic internal subtype (generic checked)'
)
self.assertEqual(
follower_emp.subtype_ids, self.sub_comment | self.sub_track_def | self.sub_generic_int_def,
'AutoSubscribe: only default one as no subscription on parent'
)
# check portal generic subscribe
sub1.message_unsubscribe(partner_ids=self.partner_portal.ids)
sub1.message_subscribe(partner_ids=self.partner_portal.ids)
follower_por = sub1.message_follower_ids.filtered(lambda fol: fol.partner_id == self.partner_portal)
self.assertEqual(
follower_por.subtype_ids, self.sub_comment | self.sub_track_def,
'AutoSubscribe: only default one as no subscription on parent (no internal as portal)'
)
# check auto subscribe as creator + auto subscribe as parent follower takes both subtypes
container.message_subscribe(
partner_ids=self.user_employee.partner_id.ids,
subtype_ids=(self.sub_comment | self.sub_generic_int_nodef | self.umb_autosub_nodef).ids)
sub2 = self.env['mail.test.track'].with_user(self.user_employee).create({
'name': 'Task-Like Test',
'container_id': container.id,
})
follower_emp = sub2.message_follower_ids.filtered(lambda fol: fol.partner_id == self.user_employee.partner_id)
defaults = self.sub_comment | self.sub_track_def | self.sub_generic_int_def
parents = self.sub_generic_int_nodef | self.sub_track_2
self.assertEqual(
follower_emp.subtype_ids, defaults + parents,
'AutoSubscribe: at create auto subscribe as creator + from parent take both subtypes'
)
class AdvancedResponsibleNotifiedTest(TestMailCommon):
def setUp(self):
super(AdvancedResponsibleNotifiedTest, self).setUp()
# patch registry to simulate a ready environment so that _message_auto_subscribe_notify
# will be executed with the associated notification
old = self.env.registry.ready
self.env.registry.ready = True
self.addCleanup(setattr, self.env.registry, 'ready', old)
def test_auto_subscribe_notify_email(self):
""" Responsible is notified when assigned """
partner = self.env['res.partner'].create({"name": "demo1", "email": "demo1@test.com"})
notified_user = self.env['res.users'].create({
'login': 'demo1',
'partner_id': partner.id,
'notification_type': 'email',
})
# TODO master: add a 'state' selection field on 'mail.test.track' with a 'done' value to have a complete test
# check that 'default_state' context does not collide with mail.mail default values
sub = self.env['mail.test.track'].with_user(self.user_employee).with_context({
'default_state': 'done',
'mail_notify_force_send': False
}).create({
'name': 'Test',
'user_id': notified_user.id,
})
self.assertEqual(sub.message_partner_ids, (self.user_employee.partner_id | notified_user.partner_id))
# fetch created "You have been assigned to 'Test'" mail.message
mail_message = self.env['mail.message'].search([
('model', '=', 'mail.test.track'),
('res_id', '=', sub.id),
('partner_ids', 'in', partner.id),
])
self.assertEqual(1, len(mail_message))
# verify that a mail.mail is attached to it with the correct state ('outgoing')
mail_notification = mail_message.notification_ids
self.assertEqual(1, len(mail_notification))
self.assertTrue(bool(mail_notification.mail_mail_id))
self.assertEqual(mail_notification.mail_mail_id.state, 'outgoing')
@tagged('post_install', '-at_install')
class DuplicateNotificationTest(TestMailCommon):
def test_no_duplicate_notification(self):
"""
Check that we only create one mail.notification per partner
Post install because we need the registery to be ready to send notification
"""
#Simulate case of 2 users that got their partner merged
common_partner = self.env['res.partner'].create({"name": "demo1", "email": "demo1@test.com"})
user_1 = self.env['res.users'].create({'login': 'demo1', 'partner_id': common_partner.id, 'notification_type': 'email'})
user_2 = self.env['res.users'].create({'login': 'demo2', 'partner_id': common_partner.id, 'notification_type': 'inbox'})
#Trigger auto subscribe notification
test = self.env['mail.test.track'].create({"name": "Test Track", "user_id": user_2.id})
mail_message = self.env['mail.message'].search([
('res_id', '=', test.id),
('model', '=', 'mail.test.track'),
('message_type', '=', 'user_notification')
])
notif = self.env['mail.notification'].search([
('mail_message_id', '=', mail_message.id),
('res_partner_id', '=', common_partner.id)
])
self.assertEqual(len(notif), 1)
self.assertEqual(notif.notification_type, 'email')
subtype = self.env.ref('mail.mt_comment')
res = self.env['mail.followers']._get_recipient_data(test, 'comment', subtype.id, pids=common_partner.ids)
partner_notif = [r for r in res if r[0] == common_partner.id]
self.assertEqual(len(partner_notif), 1)
self.assertEqual(partner_notif[0][3], 'email')
@tagged('post_install', '-at_install')
class UnlinkedNotificationTest(TestMailCommon):
def test_unlinked_notification(self):
"""
Check that we unlink the created user_notification after unlinked the related document
Post install because we need the registery to be ready to send notification
"""
common_partner = self.env['res.partner'].create({"name": "demo1", "email": "demo1@test.com"})
user_1 = self.env['res.users'].create({'login': 'demo1', 'partner_id': common_partner.id, 'notification_type': 'inbox'})
test = self.env['mail.test.track'].create({"name": "Test Track", "user_id": user_1.id})
test_id = test.id
mail_message = self.env['mail.message'].search([
('res_id', '=', test_id),
('model', '=', 'mail.test.track'),
('message_type', '=', 'user_notification')
])
self.assertEqual(len(mail_message), 1)
test.unlink()
mail_message = self.env['mail.message'].search([
('res_id', '=', test_id),
('model', '=', 'mail.test.track'),
('message_type', '=', 'user_notification')
])
self.assertEqual(len(mail_message), 0)
| 53.93595
| 26,105
|
1,433
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_mail.tests.common import TestMailCommon
from odoo.tools import mute_logger
class TestInvite(TestMailCommon):
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_invite_email(self):
test_record = self.env['mail.test.simple'].with_context(self._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
test_partner = self.env['res.partner'].with_context(self._test_context).create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com'})
mail_invite = self.env['mail.wizard.invite'].with_context({
'default_res_model': 'mail.test.simple',
'default_res_id': test_record.id
}).with_user(self.user_employee).create({
'partner_ids': [(4, test_partner.id), (4, self.user_admin.partner_id.id)],
'send_mail': True})
with self.mock_mail_gateway():
mail_invite.add_followers()
# check added followers and that emails were sent
self.assertEqual(test_record.message_partner_ids,
test_partner | self.user_admin.partner_id)
self.assertSentEmail(self.partner_employee, [test_partner])
self.assertSentEmail(self.partner_employee, [self.partner_admin])
self.assertEqual(len(self._mails), 2)
| 46.225806
| 1,433
|
18,688
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.addons.test_mail.tests.common import TestMailCommon, TestMailMultiCompanyCommon
from odoo.tests.common import tagged
from odoo.tests import Form
@tagged('mail_track')
class TestTracking(TestMailCommon):
def setUp(self):
super(TestTracking, self).setUp()
record = self.env['mail.test.ticket'].with_user(self.user_employee).with_context(self._test_context).create({
'name': 'Test',
})
self.flush_tracking()
self.record = record.with_context(mail_notrack=False)
def test_message_track_no_tracking(self):
""" Update a set of non tracked fields -> no message, no tracking """
self.record.write({
'name': 'Tracking or not',
'count': 32,
})
self.flush_tracking()
self.assertEqual(self.record.message_ids, self.env['mail.message'])
def test_message_track_no_subtype(self):
""" Update some tracked fields not linked to some subtype -> message with onchange """
customer = self.env['res.partner'].create({'name': 'Customer', 'email': 'cust@example.com'})
with self.mock_mail_gateway():
self.record.write({
'name': 'Test2',
'customer_id': customer.id,
})
self.flush_tracking()
# one new message containing tracking; without subtype linked to tracking, a note is generated
self.assertEqual(len(self.record.message_ids), 1)
self.assertEqual(self.record.message_ids.subtype_id, self.env.ref('mail.mt_note'))
# no specific recipients except those following notes, no email
self.assertEqual(self.record.message_ids.partner_ids, self.env['res.partner'])
self.assertEqual(self.record.message_ids.notified_partner_ids, self.env['res.partner'])
self.assertNotSentEmail()
# verify tracked value
self.assertTracking(
self.record.message_ids,
[('customer_id', 'many2one', False, customer) # onchange tracked field
])
def test_message_track_subtype(self):
""" Update some tracked fields linked to some subtype -> message with onchange """
self.record.message_subscribe(
partner_ids=[self.user_admin.partner_id.id],
subtype_ids=[self.env.ref('test_mail.st_mail_test_ticket_container_upd').id]
)
container = self.env['mail.test.container'].with_context(mail_create_nosubscribe=True).create({'name': 'Container'})
self.record.write({
'name': 'Test2',
'email_from': 'noone@example.com',
'container_id': container.id,
})
self.flush_tracking()
# one new message containing tracking; subtype linked to tracking
self.assertEqual(len(self.record.message_ids), 1)
self.assertEqual(self.record.message_ids.subtype_id, self.env.ref('test_mail.st_mail_test_ticket_container_upd'))
# no specific recipients except those following container
self.assertEqual(self.record.message_ids.partner_ids, self.env['res.partner'])
self.assertEqual(self.record.message_ids.notified_partner_ids, self.user_admin.partner_id)
# verify tracked value
self.assertTracking(
self.record.message_ids,
[('container_id', 'many2one', False, container) # onchange tracked field
])
def test_message_track_template(self):
""" Update some tracked fields linked to some template -> message with onchange """
self.record.write({'mail_template': self.env.ref('test_mail.mail_test_ticket_tracking_tpl').id})
self.assertEqual(self.record.message_ids, self.env['mail.message'])
with self.mock_mail_gateway():
self.record.write({
'name': 'Test2',
'customer_id': self.user_admin.partner_id.id,
})
self.flush_tracking()
self.assertEqual(len(self.record.message_ids), 2, 'should have 2 new messages: one for tracking, one for template')
# one new message containing the template linked to tracking
self.assertEqual(self.record.message_ids[0].subject, 'Test Template')
self.assertEqual(self.record.message_ids[0].body, '<p>Hello Test2</p>')
# one email send due to template
self.assertSentEmail(self.record.env.user.partner_id, [self.partner_admin], body='<p>Hello Test2</p>')
# one new message containing tracking; without subtype linked to tracking
self.assertEqual(self.record.message_ids[1].subtype_id, self.env.ref('mail.mt_note'))
self.assertTracking(
self.record.message_ids[1],
[('customer_id', 'many2one', False, self.user_admin.partner_id) # onchange tracked field
])
def test_message_track_template_at_create(self):
""" Create a record with tracking template on create, template should be sent."""
Model = self.env['mail.test.ticket'].with_user(self.user_employee).with_context(self._test_context)
Model = Model.with_context(mail_notrack=False)
with self.mock_mail_gateway():
record = Model.create({
'name': 'Test',
'customer_id': self.user_admin.partner_id.id,
'mail_template': self.env.ref('test_mail.mail_test_ticket_tracking_tpl').id,
})
self.flush_tracking()
self.assertEqual(len(record.message_ids), 1, 'should have 1 new messages for template')
# one new message containing the template linked to tracking
self.assertEqual(record.message_ids[0].subject, 'Test Template')
self.assertEqual(record.message_ids[0].body, '<p>Hello Test</p>')
# one email send due to template
self.assertSentEmail(self.record.env.user.partner_id, [self.partner_admin], body='<p>Hello Test</p>')
def test_create_partner_from_tracking_multicompany(self):
company1 = self.env['res.company'].create({'name': 'company1'})
self.env.user.write({'company_ids': [(4, company1.id, False)]})
self.assertNotEqual(self.env.company, company1)
email_new_partner = "diamonds@rust.com"
Partner = self.env['res.partner']
self.assertFalse(Partner.search([('email', '=', email_new_partner)]))
template = self.env['mail.template'].create({
'model_id': self.env['ir.model']._get('mail.test.track').id,
'name': 'AutoTemplate',
'subject': 'autoresponse',
'email_from': self.env.user.email_formatted,
'email_to': "{{ object.email_from }}",
'body_html': "<div>A nice body</div>",
})
def patched_message_track_post_template(*args, **kwargs):
if args[0]._name == "mail.test.track":
args[0].message_post_with_template(template.id)
return True
with patch('odoo.addons.mail.models.mail_thread.MailThread._message_track_post_template', patched_message_track_post_template):
self.env['mail.test.track'].create({
'email_from': email_new_partner,
'company_id': company1.id,
'user_id': self.env.user.id, # trigger track template
})
self.flush_tracking()
new_partner = Partner.search([('email', '=', email_new_partner)])
self.assertTrue(new_partner)
self.assertEqual(new_partner.company_id, company1)
def test_track_invalid_selection(self):
# Test: Check that initial invalid selection values are allowed when tracking
# Create a record with an initially invalid selection value
invalid_value = 'I love writing tests!'
record = self.env['mail.test.track.selection'].create({
'name': 'Test Invalid Selection Values',
"type": "first",
})
self.flush_tracking()
self.env.cr.execute(
"""
UPDATE mail_test_track_selection
SET type = %s
WHERE id = %s
""",
[invalid_value, record.id]
)
record.invalidate_cache()
self.assertEqual(record.type, invalid_value)
# Write a valid selection value
record.type = "second"
self.flush_tracking()
self.assertTracking(record.message_ids, [
('type', 'char', invalid_value, 'Second'),
])
def test_track_template(self):
# Test: Check that default_* keys are not taken into account in _message_track_post_template
magic_code = 'Up-Up-Down-Down-Left-Right-Left-Right-Square-Triangle'
mt_name_changed = self.env['mail.message.subtype'].create({
'name': 'MAGIC CODE WOOP WOOP',
'description': 'SPECIAL CONTENT UNLOCKED'
})
self.env['ir.model.data'].create({
'name': 'mt_name_changed',
'model': 'mail.message.subtype',
'module': 'mail',
'res_id': mt_name_changed.id
})
mail_template = self.env['mail.template'].create({
'name': 'SPECIAL CONTENT UNLOCKED',
'subject': 'SPECIAL CONTENT UNLOCKED',
'model_id': self.env.ref('test_mail.model_mail_test_container').id,
'auto_delete': True,
'body_html': '''<div>WOOP WOOP</div>''',
})
def _track_subtype(self, init_values):
if 'name' in init_values and init_values['name'] == magic_code:
return 'mail.mt_name_changed'
return False
self.registry('mail.test.container')._patch_method('_track_subtype', _track_subtype)
def _track_template(self, changes):
res = {}
if 'name' in changes:
res['name'] = (mail_template, {'composition_mode': 'mass_mail'})
return res
self.registry('mail.test.container')._patch_method('_track_template', _track_template)
cls = type(self.env['mail.test.container'])
self.assertFalse(hasattr(getattr(cls, 'name'), 'track_visibility'))
getattr(cls, 'name').track_visibility = 'always'
@self.addCleanup
def cleanup():
del getattr(cls, 'name').track_visibility
test_mail_record = self.env['mail.test.container'].create({
'name': 'Zizizatestmailname',
'description': 'Zizizatestmaildescription',
})
test_mail_record.with_context(default_parent_id=2147483647).write({'name': magic_code})
def test_message_track_multiple(self):
""" check that multiple updates generate a single tracking message """
container = self.env['mail.test.container'].with_context(mail_create_nosubscribe=True).create({'name': 'Container'})
self.record.name = 'Zboub'
self.record.customer_id = self.user_admin.partner_id
self.record.user_id = self.user_admin
self.record.container_id = container
self.flush_tracking()
# should have a single message with all tracked fields
self.assertEqual(len(self.record.message_ids), 1, 'should have 1 tracking message')
self.assertTracking(self.record.message_ids[0], [
('customer_id', 'many2one', False, self.user_admin.partner_id),
('user_id', 'many2one', False, self.user_admin),
('container_id', 'many2one', False, container),
])
def test_tracked_compute(self):
# no tracking at creation
record = self.env['mail.test.track.compute'].create({})
self.flush_tracking()
self.assertEqual(len(record.message_ids), 1)
self.assertEqual(len(record.message_ids[0].tracking_value_ids), 0)
# assign partner_id: one tracking message for the modified field and all
# the stored and non-stored computed fields on the record
partner = self.env['res.partner'].create({
'name': 'Foo',
'email': 'foo@example.com',
'phone': '1234567890',
})
record.partner_id = partner
self.flush_tracking()
self.assertEqual(len(record.message_ids), 2)
self.assertEqual(len(record.message_ids[0].tracking_value_ids), 4)
self.assertTracking(record.message_ids[0], [
('partner_id', 'many2one', False, partner),
('partner_name', 'char', False, 'Foo'),
('partner_email', 'char', False, 'foo@example.com'),
('partner_phone', 'char', False, '1234567890'),
])
# modify partner: one tracking message for the only recomputed field
partner.write({'name': 'Fool'})
self.flush_tracking()
self.assertEqual(len(record.message_ids), 3)
self.assertEqual(len(record.message_ids[0].tracking_value_ids), 1)
self.assertTracking(record.message_ids[0], [
('partner_name', 'char', 'Foo', 'Fool'),
])
# modify partner: one tracking message for both stored computed fields;
# the non-stored computed fields have no tracking
partner.write({
'name': 'Bar',
'email': 'bar@example.com',
'phone': '0987654321',
})
# force recomputation of 'partner_phone' to make sure it does not
# generate tracking values
self.assertEqual(record.partner_phone, '0987654321')
self.flush_tracking()
self.assertEqual(len(record.message_ids), 4)
self.assertEqual(len(record.message_ids[0].tracking_value_ids), 2)
self.assertTracking(record.message_ids[0], [
('partner_name', 'char', 'Fool', 'Bar'),
('partner_email', 'char', 'foo@example.com', 'bar@example.com'),
])
@tagged('mail_track')
class TestTrackingMonetary(TestMailMultiCompanyCommon):
def setUp(self):
super(TestTrackingMonetary, self).setUp()
record = self.env['mail.test.track.monetary'].with_user(self.user_employee).with_context(self._test_context).create({
'company_id': self.user_employee.company_id.id,
})
self.flush_tracking()
self.record = record.with_context(mail_notrack=False)
def test_message_track_monetary(self):
""" Update a record with a tracked monetary field """
# Check if the tracking value have the correct currency and values
self.record.write({
'revenue': 100,
})
self.flush_tracking()
self.assertEqual(len(self.record.message_ids), 1)
self.assertTracking(self.record.message_ids[0], [
('revenue', 'monetary', 0, 100),
])
# Check if the tracking value have the correct currency and values after changing the value and the company
self.record.write({
'revenue': 200,
'company_id': self.company_2.id,
})
self.flush_tracking()
self.assertEqual(len(self.record.message_ids), 2)
self.assertTracking(self.record.message_ids[0], [
('revenue', 'monetary', 100, 200),
('company_currency', 'many2one', self.user_employee.company_id.currency_id, self.company_2.currency_id)
])
@tagged('mail_track')
class TestTrackingInternals(TestMailCommon):
def setUp(self):
super(TestTrackingInternals, self).setUp()
record = self.env['mail.test.ticket'].with_user(self.user_employee).with_context(self._test_context).create({
'name': 'Test',
})
self.flush_tracking()
self.record = record.with_context(mail_notrack=False)
def test_track_groups(self):
field = self.record._fields['email_from']
self.addCleanup(setattr, field, 'groups', field.groups)
field.groups = 'base.group_erp_manager'
self.record.sudo().write({'email_from': 'X'})
self.flush_tracking()
msg_emp = self.record.message_ids.message_format()
msg_sudo = self.record.sudo().message_ids.message_format()
self.assertFalse(msg_emp[0].get('tracking_value_ids'), "should not have protected tracking values")
self.assertTrue(msg_sudo[0].get('tracking_value_ids'), "should have protected tracking values")
msg_emp = self.record._notify_prepare_template_context(self.record.message_ids, {})
msg_sudo = self.record.sudo()._notify_prepare_template_context(self.record.message_ids, {})
self.assertFalse(msg_emp.get('tracking_values'), "should not have protected tracking values")
self.assertTrue(msg_sudo.get('tracking_values'), "should have protected tracking values")
# test editing the record with user not in the group of the field
self.record.invalidate_cache()
self.record.clear_caches()
record_form = Form(self.record.with_user(self.user_employee))
record_form.name = 'TestDoNoCrash'
# the employee user must be able to save the fields on which he can write
# if we fetch all the tracked fields, ignoring the group of the current user
# it will crash and it shouldn't
record = record_form.save()
self.assertEqual(record.name, 'TestDoNoCrash')
def test_track_sequence(self):
""" Update some tracked fields and check that the mail.tracking.value are ordered according to their tracking_sequence"""
self.record.write({
'name': 'Zboub',
'customer_id': self.user_admin.partner_id.id,
'user_id': self.user_admin.id,
'container_id': self.env['mail.test.container'].with_context(mail_create_nosubscribe=True).create({'name': 'Container'}).id
})
self.flush_tracking()
self.assertEqual(len(self.record.message_ids), 1, 'should have 1 tracking message')
tracking_values = self.env['mail.tracking.value'].search([('mail_message_id', '=', self.record.message_ids.id)])
self.assertEqual(tracking_values[0].tracking_sequence, 1)
self.assertEqual(tracking_values[1].tracking_sequence, 2)
self.assertEqual(tracking_values[2].tracking_sequence, 100)
def test_unlinked_field(self):
record_sudo = self.record.sudo()
record_sudo.write({'email_from': 'new_value'}) # create a tracking value
self.flush_tracking()
self.assertEqual(len(record_sudo.message_ids.tracking_value_ids), 1)
ir_model_field = self.env['ir.model.fields'].search([
('model', '=', 'mail.test.ticket'),
('name', '=', 'email_from')])
ir_model_field.with_context(_force_unlink=True).unlink()
self.assertEqual(len(record_sudo.message_ids.tracking_value_ids), 0)
| 44.28436
| 18,688
|
2,243
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.tests import tagged
from odoo.tests.common import users
@tagged('mail_composer_mixin')
class TestMailComposerMixin(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestMailComposerMixin, cls).setUpClass()
cls._init_mail_gateway()
cls.mail_template = cls.env['mail.template'].create({
'subject': 'Subject for {{ object.name }}',
'body_html': '<p>Body for <t t-out="object.name"/></p>',
})
@users("employee")
def test_content_sync(self):
record = self.env['mail.test.composer.mixin'].create({
'name': 'Invite',
'template_id': self.mail_template.id,
})
self.assertEqual(record.subject, self.mail_template.subject)
self.assertEqual(record.body, self.mail_template.body_html)
subject = record._render_field('subject', record.ids)[record.id]
self.assertEqual(subject, 'Subject for %s' % record.name)
body = record._render_field('body', record.ids)[record.id]
self.assertEqual(body, '<p>Body for %s</p>' % record.name)
@users("employee")
def test_rendering(self):
record = self.env['mail.test.composer.mixin'].create({
'name': 'Invite',
'subject': 'Subject for {{ object.name }}',
'body': '<p>Content from <t t-out="user.name"/></p>',
'description': '<p>Description for <t t-esc="object.name"/></p>',
})
self.assertEqual(record.subject, 'Subject for {{ object.name }}')
self.assertEqual(record.body, '<p>Content from <t t-out="user.name"/></p>')
subject = record._render_field('subject', record.ids)[record.id]
self.assertEqual(subject, 'Subject for %s' % record.name)
body = record._render_field('body', record.ids)[record.id]
self.assertEqual(body, '<p>Content from %s</p>' % self.env.user.name)
description = record._render_field('description', record.ids)[record.id]
self.assertEqual(description, '<p>Description for Invite</p>')
| 43.134615
| 2,243
|
31,868
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from unittest.mock import patch
from odoo import tools
from odoo.addons.test_mail.data.test_mail_data import MAIL_TEMPLATE_PLAINTEXT
from odoo.addons.test_mail.models.test_mail_models import MailTestSimple
from odoo.addons.test_mail.tests.common import TestMailCommon, TestRecipients
from odoo.api import call_kw
from odoo.exceptions import AccessError
from odoo.tests import tagged
from odoo.tools import mute_logger, formataddr
from odoo.tests.common import users
from markupsafe import escape
@tagged('mail_post')
class TestMessagePost(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestMessagePost, cls).setUpClass()
cls._create_portal_user()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({
'name': 'Test',
'email_from': 'ignasse@example.com'
})
cls._reset_mail_context(cls.test_record)
cls.test_message = cls.env['mail.message'].create({
'author_id': cls.partner_employee.id,
'body': '<p>Notify Body <span>Woop Woop</span></p>',
'email_from': cls.partner_employee.email_formatted,
'is_internal': False,
'message_id': tools.generate_tracking_message_id('dummy-generate'),
'message_type': 'comment',
'model': cls.test_record._name,
'record_name': False,
'reply_to': 'wrong.alias@test.example.com',
'subtype_id': cls.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment'),
'subject': 'Notify Test',
})
cls.user_admin.write({'notification_type': 'email'})
@users('employee')
def test_notify_email_layouts(self):
self.user_employee.write({'notification_type': 'email'})
test_record = self.env['mail.test.simple'].browse(self.test_record.ids)
test_message = self.env['mail.message'].browse(self.test_message.ids)
recipients_data = self._generate_notify_recipients(self.partner_1 + self.partner_2 + self.partner_employee)
for email_xmlid in ['mail.message_notification_email',
'mail.mail_notification_borders',
'mail.mail_notification_light',
'mail.mail_notification_paynow']:
test_message.write({'email_layout_xmlid': email_xmlid})
with self.mock_mail_gateway():
test_record._notify_record_by_email(
test_message,
recipients_data,
force_send=False
)
self.assertEqual(len(self._new_mails), 2, 'Should have 2 emails: one for customers, one for internal users')
# check customer email
customer_email = self._new_mails.filtered(lambda mail: mail.recipient_ids == self.partner_1 + self.partner_2)
self.assertTrue(customer_email)
# check internal user email
user_email = self._new_mails.filtered(lambda mail: mail.recipient_ids == self.partner_employee)
self.assertTrue(user_email)
@users('employee')
def test_notify_mail_add_signature(self):
self.test_track = self.env['mail.test.track'].with_context(self._test_context).with_user(self.user_employee).create({
'name': 'Test',
'email_from': 'ignasse@example.com'
})
self.test_track.user_id = self.env.user
signature = self.env.user.signature
template = self.env.ref('mail.mail_notification_paynow', raise_if_not_found=True).sudo()
self.assertIn("record.user_id.sudo().signature", template.arch)
with self.mock_mail_gateway():
self.test_track.message_post(body="Test body", mail_auto_delete=False, add_sign=True, partner_ids=[self.partner_1.id, self.partner_2.id], email_layout_xmlid="mail.mail_notification_paynow")
found_mail = self._new_mails
self.assertIn(signature, found_mail.body_html)
self.assertEqual(found_mail.body_html.count(signature), 1)
with self.mock_mail_gateway():
self.test_track.message_post(body="Test body", mail_auto_delete=False, add_sign=False, partner_ids=[self.partner_1.id, self.partner_2.id], email_layout_xmlid="mail.mail_notification_paynow")
found_mail = self._new_mails
self.assertNotIn(signature, found_mail.body_html)
self.assertEqual(found_mail.body_html.count(signature), 0)
@users('employee')
def test_notify_mail_add_signature_no_author_user_or_no_user(self):
self.test_message.author_id = self.env['res.partner'].sudo().create({
'name': 'Steve',
}).id
template_values = self.test_record._notify_prepare_template_context(self.test_message, {})
self.assertNotEqual(escape(template_values['signature']), escape('<p>-- <br/>Steve</p>'))
self.test_message.author_id = None
template_values = self.test_record._notify_prepare_template_context(self.test_message, {})
self.assertEqual(template_values['signature'], '')
@users('employee')
def test_notify_prepare_template_context_company_value(self):
""" Verify that the template context company value is right
after switching the env company or if a company_id is set
on mail record.
"""
current_user = self.env.user
main_company = current_user.company_id
other_company = self.env['res.company'].with_user(self.user_admin).create({'name': 'Company B'})
current_user.sudo().write({'company_ids': [(4, other_company.id)]})
test_record = self.env['mail.test.multi.company'].with_user(self.user_admin).create({
'name': 'Multi Company Record',
'company_id': False,
})
# self.env.company.id = Main Company AND test_record.company_id = False
self.assertEqual(self.env.company.id, main_company.id)
self.assertEqual(test_record.company_id.id, False)
template_values = test_record._notify_prepare_template_context(test_record.message_ids, {})
self.assertEqual(template_values.get('company').id, self.env.company.id)
# self.env.company.id = Other Company AND test_record.company_id = False
current_user.company_id = other_company
test_record = self.env['mail.test.multi.company'].browse(test_record.id)
self.assertEqual(self.env.company.id, other_company.id)
self.assertEqual(test_record.company_id.id, False)
template_values = test_record._notify_prepare_template_context(test_record.message_ids, {})
self.assertEqual(template_values.get('company').id, self.env.company.id)
# self.env.company.id = Other Company AND test_record.company_id = Main Company
test_record.company_id = main_company
test_record = self.env['mail.test.multi.company'].browse(test_record.id)
self.assertEqual(self.env.company.id, other_company.id)
self.assertEqual(test_record.company_id.id, main_company.id)
template_values = test_record._notify_prepare_template_context(test_record.message_ids, {})
self.assertEqual(template_values.get('company').id, main_company.id)
def test_notify_recipients_internals(self):
pdata = self._generate_notify_recipients(self.partner_1 | self.partner_employee)
msg_vals = {
'body': 'Message body',
'model': self.test_record._name,
'res_id': self.test_record.id,
'subject': 'Message subject',
}
link_vals = {
'token': 'token_val',
'access_token': 'access_token_val',
'auth_signup_token': 'auth_signup_token_val',
'auth_login': 'auth_login_val',
}
notify_msg_vals = dict(msg_vals, **link_vals)
classify_res = self.env[self.test_record._name]._notify_classify_recipients(pdata, 'My Custom Model Name', msg_vals=notify_msg_vals)
# find back information for each recipients
partner_info = next(item for item in classify_res if item['recipients'] == self.partner_1.ids)
emp_info = next(item for item in classify_res if item['recipients'] == self.partner_employee.ids)
# partner: no access button
self.assertFalse(partner_info['has_button_access'])
# employee: access button and link
self.assertTrue(emp_info['has_button_access'])
for param, value in link_vals.items():
self.assertIn('%s=%s' % (param, value), emp_info['button_access']['url'])
self.assertIn('model=%s' % self.test_record._name, emp_info['button_access']['url'])
self.assertIn('res_id=%s' % self.test_record.id, emp_info['button_access']['url'])
self.assertNotIn('body', emp_info['button_access']['url'])
self.assertNotIn('subject', emp_info['button_access']['url'])
# test when notifying on non-records (e.g. MailThread._message_notify())
for model, res_id in ((self.test_record._name, False),
(self.test_record._name, 0), # browse(0) does not return a valid recordset
(False, self.test_record.id),
(False, False),
('mail.thread', False),
('mail.thread', self.test_record.id)):
msg_vals.update({
'model': model,
'res_id': res_id,
})
# note that msg_vals wins over record on which method is called
notify_msg_vals = dict(msg_vals, **link_vals)
classify_res = self.test_record._notify_classify_recipients(
pdata, 'Test', msg_vals=notify_msg_vals)
# find back information for partner
partner_info = next(item for item in classify_res if item['recipients'] == self.partner_1.ids)
emp_info = next(item for item in classify_res if item['recipients'] == self.partner_employee.ids)
# check there is no access button
self.assertFalse(partner_info['has_button_access'])
self.assertFalse(emp_info['has_button_access'])
# test on falsy records (False model cannot be browsed, skipped)
if model:
record_falsy = self.env[model].browse(res_id)
classify_res = record_falsy._notify_classify_recipients(
pdata, 'Test', msg_vals=notify_msg_vals)
# find back information for partner
partner_info = next(item for item in classify_res if item['recipients'] == self.partner_1.ids)
emp_info = next(item for item in classify_res if item['recipients'] == self.partner_employee.ids)
# check there is no access button
self.assertFalse(partner_info['has_button_access'])
self.assertFalse(emp_info['has_button_access'])
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_needaction(self):
(self.user_employee | self.user_admin).write({'notification_type': 'inbox'})
with self.assertSinglePostNotifications([{'partner': self.partner_employee, 'type': 'inbox'}], {'content': 'Body'}):
self.test_record.message_post(
body='Body', message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.user_employee.partner_id.id])
self.test_record.message_subscribe([self.partner_1.id])
with self.assertSinglePostNotifications([
{'partner': self.partner_employee, 'type': 'inbox'},
{'partner': self.partner_1, 'type': 'email'}], {'content': 'NewBody'}):
self.test_record.message_post(
body='NewBody', message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.user_employee.partner_id.id])
with self.assertSinglePostNotifications([
{'partner': self.partner_1, 'type': 'email'},
{'partner': self.partner_portal, 'type': 'email'}], {'content': 'ToPortal'}):
self.test_record.message_post(
body='ToPortal', message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.partner_portal.id])
def test_post_inactive_follower(self):
# In some case odoobot is follower of a record.
# Even if it shouldn't be the case, we want to be sure that odoobot is not notified
(self.user_employee | self.user_admin).write({'notification_type': 'inbox'})
self.test_record._message_subscribe(self.user_employee.partner_id.ids)
with self.assertSinglePostNotifications([{'partner': self.partner_employee, 'type': 'inbox'}], {'content': 'Test'}):
self.test_record.message_post(
body='Test', message_type='comment', subtype_xmlid='mail.mt_comment')
self.user_employee.active = False
# at this point, partner is still active and would receive an email notification
self.user_employee.partner_id._write({'active': False})
with self.assertPostNotifications([{'content': 'Test', 'notif': []}]):
self.test_record.message_post(
body='Test', message_type='comment', subtype_xmlid='mail.mt_comment')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_notifications(self):
_body, _subject = '<p>Test Body</p>', 'Test Subject'
# subscribe second employee to the group to test notifications
self.test_record.message_subscribe(partner_ids=[self.user_admin.partner_id.id])
with self.assertSinglePostNotifications(
[{'partner': self.partner_1, 'type': 'email'},
{'partner': self.partner_2, 'type': 'email'},
{'partner': self.partner_admin, 'type': 'email'}],
{'content': _body},
mail_unlink_sent=True):
msg = self.test_record.with_user(self.user_employee).message_post(
body=_body, subject=_subject,
message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.partner_1.id, self.partner_2.id]
)
# message content
self.assertEqual(msg.subject, _subject)
self.assertEqual(msg.body, _body)
self.assertEqual(msg.partner_ids, self.partner_1 | self.partner_2)
self.assertEqual(msg.notified_partner_ids, self.user_admin.partner_id | self.partner_1 | self.partner_2)
# notifications emails should have been deleted
self.assertFalse(self.env['mail.mail'].sudo().search([('mail_message_id', '=', msg.id)]),
'message_post: mail.mail notifications should have been auto-deleted')
# notified_partner_ids should be empty after copying the message
copy = msg.copy()
self.assertFalse(copy.notified_partner_ids)
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.tests')
def test_post_notifications_keep_emails(self):
self.test_record.message_subscribe(partner_ids=[self.user_admin.partner_id.id])
msg = self.test_record.with_user(self.user_employee).message_post(
body='Test', subject='Test',
message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.partner_1.id, self.partner_2.id],
mail_auto_delete=False
)
# notifications emails should not have been deleted: one for customers, one for user
self.assertEqual(len(self.env['mail.mail'].sudo().search([('mail_message_id', '=', msg.id)])), 2)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_notifications_emails_tweak(self):
pass
# we should check _notification_groups behavior, for emails and buttons
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_attachments(self):
_attachments = [
('List1', b'My first attachment'),
('List2', b'My second attachment')
]
_attach_1 = self.env['ir.attachment'].with_user(self.user_employee).create({
'name': 'Attach1',
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'res_model': 'mail.compose.message', 'res_id': 0})
_attach_2 = self.env['ir.attachment'].with_user(self.user_employee).create({
'name': 'Attach2',
'datas': 'bWlncmF0aW9uIHRlc3Q=',
'res_model': 'mail.compose.message', 'res_id': 0})
with self.mock_mail_gateway():
msg = self.test_record.with_user(self.user_employee).message_post(
body='Test', subject='Test',
message_type='comment', subtype_xmlid='mail.mt_comment',
attachment_ids=[_attach_1.id, _attach_2.id],
partner_ids=[self.partner_1.id],
attachments=_attachments,
)
# message attachments
self.assertEqual(len(msg.attachment_ids), 4)
self.assertEqual(set(msg.attachment_ids.mapped('res_model')), set([self.test_record._name]))
self.assertEqual(set(msg.attachment_ids.mapped('res_id')), set([self.test_record.id]))
self.assertEqual(set([base64.b64decode(x) for x in msg.attachment_ids.mapped('datas')]),
set([b'migration test', _attachments[0][1], _attachments[1][1]]))
self.assertTrue(set([_attach_1.id, _attach_2.id]).issubset(msg.attachment_ids.ids),
'message_post: mail.message attachments duplicated')
# notification email attachments
self.assertSentEmail(self.user_employee.partner_id, [self.partner_1])
# self.assertEqual(len(self._mails), 1)
self.assertEqual(len(self._mails[0]['attachments']), 4)
self.assertIn(('List1', b'My first attachment', 'application/octet-stream'), self._mails[0]['attachments'])
self.assertIn(('List2', b'My second attachment', 'application/octet-stream'), self._mails[0]['attachments'])
self.assertIn(('Attach1', b'migration test', 'application/octet-stream'), self._mails[0]['attachments'])
self.assertIn(('Attach2', b'migration test', 'application/octet-stream'), self._mails[0]['attachments'])
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_answer(self):
with self.mock_mail_gateway():
parent_msg = self.test_record.with_user(self.user_employee).message_post(
body='<p>Test</p>',
message_type='comment',
subject='Test Subject',
subtype_xmlid='mail.mt_comment',
)
self.assertEqual(parent_msg.partner_ids, self.env['res.partner'])
self.assertNotSentEmail()
# post a first reply
with self.assertPostNotifications([{'content': '<p>Test Answer</p>', 'notif': [{'partner': self.partner_1, 'type': 'email'}]}]):
msg = self.test_record.with_user(self.user_employee).message_post(
body='<p>Test Answer</p>',
message_type='comment',
subject='Welcome',
subtype_xmlid='mail.mt_comment',
parent_id=parent_msg.id,
partner_ids=[self.partner_1.id],
)
self.assertEqual(msg.parent_id.id, parent_msg.id)
self.assertEqual(msg.partner_ids, self.partner_1)
self.assertEqual(parent_msg.partner_ids, self.env['res.partner'])
# check notification emails: references
self.assertSentEmail(
self.user_employee.partner_id,
[self.partner_1],
references_content='openerp-%d-mail.test.simple' % self.test_record.id,
# references should be sorted from the oldest to the newest
references='%s %s' % (parent_msg.message_id, msg.message_id),
)
# post a reply to the reply: check parent is the first one
with self.mock_mail_gateway():
new_msg = self.test_record.with_user(self.user_employee).message_post(
body='<p>Test Answer Bis</p>',
message_type='comment',
subtype_xmlid='mail.mt_comment',
parent_id=msg.id,
partner_ids=[self.partner_2.id],
)
self.assertEqual(new_msg.parent_id.id, parent_msg.id, 'message_post: flatten error')
self.assertEqual(new_msg.partner_ids, self.partner_2)
self.assertSentEmail(
self.user_employee.partner_id,
[self.partner_2],
body_content='<p>Test Answer Bis</p>',
reply_to=msg.reply_to,
subject='Re: %s' % self.test_record.name,
references_content='openerp-%d-mail.test.simple' % self.test_record.id,
references='%s %s' % (parent_msg.message_id, new_msg.message_id),
)
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_email_with_multiline_subject(self):
_body, _body_alt, _subject = '<p>Test Body</p>', 'Test Body', '1st line\n2nd line'
msg = self.test_record.with_user(self.user_employee).message_post(
body=_body, subject=_subject,
message_type='comment', subtype_xmlid='mail.mt_comment',
partner_ids=[self.partner_1.id, self.partner_2.id]
)
self.assertEqual(msg.subject, '1st line 2nd line')
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_portal_ok(self):
self.test_record.message_subscribe((self.partner_1 | self.user_employee.partner_id).ids)
with self.assertPostNotifications([{'content': '<p>Test</p>', 'notif': [
{'partner': self.partner_employee, 'type': 'inbox'},
{'partner': self.partner_1, 'type': 'email'}]}
]), patch.object(MailTestSimple, 'check_access_rights', return_value=True):
new_msg = self.test_record.with_user(self.user_portal).message_post(
body='<p>Test</p>', subject='Subject',
message_type='comment', subtype_xmlid='mail.mt_comment')
self.assertEqual(new_msg.sudo().notified_partner_ids, (self.partner_1 | self.user_employee.partner_id))
def test_post_portal_crash(self):
with self.assertRaises(AccessError):
self.test_record.with_user(self.user_portal).message_post(
body='<p>Test</p>', subject='Subject',
message_type='comment', subtype_xmlid='mail.mt_comment')
@mute_logger('odoo.addons.mail.models.mail_mail', 'odoo.addons.mail.models.mail_thread')
def test_post_internal(self):
self.test_record.message_subscribe([self.user_admin.partner_id.id])
msg = self.test_record.with_user(self.user_employee).message_post(
body='My Body', subject='My Subject',
message_type='comment', subtype_xmlid='mail.mt_note')
self.assertEqual(msg.partner_ids, self.env['res.partner'])
self.assertEqual(msg.notified_partner_ids, self.env['res.partner'])
self.format_and_process(
MAIL_TEMPLATE_PLAINTEXT, self.user_admin.email, 'not_my_businesss@example.com',
msg_id='<1198923581.41972151344608186800.JavaMail.diff1@agrolait.com>',
extra='In-Reply-To:\r\n\t%s\n' % msg.message_id,
target_model='mail.test.simple')
reply = self.test_record.message_ids - msg
self.assertTrue(reply)
self.assertEqual(reply.subtype_id, self.env.ref('mail.mt_note'))
self.assertEqual(reply.notified_partner_ids, self.user_employee.partner_id)
self.assertEqual(reply.parent_id, msg)
def test_post_log(self):
new_note = self.test_record.with_user(self.user_employee)._message_log(
body='<p>Labrador</p>',
)
self.assertEqual(new_note.subtype_id, self.env.ref('mail.mt_note'))
self.assertEqual(new_note.body, '<p>Labrador</p>')
self.assertEqual(new_note.author_id, self.user_employee.partner_id)
self.assertEqual(new_note.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
self.assertEqual(new_note.notified_partner_ids, self.env['res.partner'])
def test_post_log_with_view(self):
new_note = self.test_record.with_user(self.user_employee)._message_log_with_view(
'test_mail.mail_template_simple_test', values={'partner': self.user_employee.partner_id}
)
self.assertEqual(new_note.subtype_id, self.env.ref('mail.mt_note'))
self.assertTrue('<p>Hello %s,</p>' % self.user_employee.name in new_note.body)
self.assertEqual(new_note.author_id, self.user_employee.partner_id)
self.assertEqual(new_note.email_from, formataddr((self.user_employee.name, self.user_employee.email)))
self.assertEqual(new_note.notified_partner_ids, self.env['res.partner'])
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_notify(self):
self.user_employee.write({'notification_type': 'inbox'})
with self.mock_mail_gateway():
new_notification = self.test_record.message_notify(
subject='This should be a subject',
body='<p>You have received a notification</p>',
partner_ids=[self.partner_1.id, self.partner_admin.id, self.user_employee.partner_id.id],
)
self.assertEqual(new_notification.subtype_id, self.env.ref('mail.mt_note'))
self.assertEqual(new_notification.message_type, 'user_notification')
self.assertEqual(new_notification.body, '<p>You have received a notification</p>')
self.assertEqual(new_notification.author_id, self.env.user.partner_id)
self.assertEqual(new_notification.email_from, formataddr((self.env.user.name, self.env.user.email)))
self.assertEqual(new_notification.notified_partner_ids, self.partner_1 | self.user_employee.partner_id | self.partner_admin)
self.assertNotIn(new_notification, self.test_record.message_ids)
admin_mails = [x for x in self._mails if self.partner_admin.name in x.get('email_to')[0]]
self.assertEqual(len(admin_mails), 1, 'There should be exactly one email sent to admin')
admin_mail = admin_mails[0].get('body')
admin_access_link = admin_mail[admin_mail.index('model='):admin_mail.index('/>') - 1] if 'model=' in admin_mail else None
self.assertIsNotNone(admin_access_link, 'The email sent to admin should contain an access link')
self.assertIn('model=%s' % self.test_record._name, admin_access_link, 'The access link should contain a valid model argument')
self.assertIn('res_id=%d' % self.test_record.id, admin_access_link, 'The access link should contain a valid res_id argument')
partner_mails = [x for x in self._mails if self.partner_1.name in x.get('email_to')[0]]
self.assertEqual(len(partner_mails), 1, 'There should be exactly one email sent to partner')
partner_mail = partner_mails[0].get('body')
self.assertNotIn('/mail/view?model=', partner_mail, 'The email sent to admin should not contain an access link')
# todo xdo add test message_notify on thread with followers and stuff
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_post_w_template(self):
test_record = self.env['mail.test.simple'].with_context(self._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
self.user_employee.write({
'groups_id': [(4, self.env.ref('base.group_partner_manager').id)],
})
_attachments = [{
'name': 'first.txt',
'datas': base64.b64encode(b'My first attachment'),
'res_model': 'res.partner',
'res_id': self.user_admin.partner_id.id
}, {
'name': 'second.txt',
'datas': base64.b64encode(b'My second attachment'),
'res_model': 'res.partner',
'res_id': self.user_admin.partner_id.id
}]
email_1 = 'test1@example.com'
email_2 = 'test2@example.com'
email_3 = self.partner_1.email
self._create_template('mail.test.simple', {
'attachment_ids': [(0, 0, _attachments[0]), (0, 0, _attachments[1])],
'partner_to': '%s,%s' % (self.partner_2.id, self.user_admin.partner_id.id),
'email_to': '%s, %s' % (email_1, email_2),
'email_cc': '%s' % email_3,
})
# admin should receive emails
self.user_admin.write({'notification_type': 'email'})
# Force the attachments of the template to be in the natural order.
self.email_template.invalidate_cache(['attachment_ids'], ids=self.email_template.ids)
with self.mock_mail_gateway():
test_record.with_user(self.user_employee).message_post_with_template(self.email_template.id, composition_mode='comment')
new_partners = self.env['res.partner'].search([('email', 'in', [email_1, email_2])])
for r in [self.partner_1, self.partner_2, new_partners[0], new_partners[1], self.partner_admin]:
self.assertSentEmail(
self.user_employee.partner_id,
[r],
subject='About %s' % test_record.name,
body_content=test_record.name,
attachments=[('first.txt', b'My first attachment', 'text/plain'), ('second.txt', b'My second attachment', 'text/plain')])
@mute_logger('odoo.addons.mail.models.mail_mail')
def test_post_post_w_template_mass_mode(self):
test_record = self.env['mail.test.simple'].with_context(self._test_context).create({'name': 'Test', 'email_from': 'ignasse@example.com'})
self.user_employee.write({
'groups_id': [(4, self.env.ref('base.group_partner_manager').id)],
})
self._create_template('mail.test.simple', {
'partner_to': '%s,%s' % (self.partner_2.id, self.user_admin.partner_id.id),
'email_to': 'test@example.com',
'email_cc': self.partner_1.email,
# After the HTML sanitizer, it will become "<p>Body for: <t t-out="object.name" /><a href="">link</a></p>"
'body_html': 'Body for: <t t-out="object.name" /><script>test</script><a href="javascript:alert(1)">link</a>',
})
with self.mock_mail_gateway():
test_record.with_user(self.user_employee).message_post_with_template(self.email_template.id, composition_mode='mass_mail')
new_partner = self.env['res.partner'].search([('email', '=', 'test@example.com')])
self.assertSentEmail(
self.user_employee.partner_id,
[new_partner],
subject='About %s' % test_record.name,
body_content=test_record.name,
attachments=[])
@tagged('mail_post', 'post_install', '-at_install')
class TestMessagePostGlobal(TestMailCommon, TestRecipients):
@classmethod
def setUpClass(cls):
super(TestMessagePostGlobal, cls).setUpClass()
cls.test_record = cls.env['mail.test.simple'].with_context(cls._test_context).create({
'email_from': 'ignasse@example.com',
'name': 'Test',
})
cls._reset_mail_context(cls.test_record)
cls.user_admin.write({'notification_type': 'email'})
@users('employee')
def test_message_post_return(self):
""" Ensures calling message_post through RPC always return an ID. """
test_record = self.env['mail.test.simple'].browse(self.test_record.ids)
# Use call_kw as shortcut to simulate a RPC call.
message_id = call_kw(self.env['mail.test.simple'],
'message_post',
[test_record.id],
{'body': 'test'}
)
self.assertTrue(isinstance(message_id, int))
| 52.328407
| 31,868
|
300
|
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 MailTestCC(models.Model):
_name = 'mail.test.cc'
_description = "Test Email CC Thread"
_inherit = ['mail.thread.cc']
name = fields.Char()
| 25
| 300
|
6,398
|
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 MailTestSimple(models.Model):
""" A very simple model only inheriting from mail.thread when only
communication history is necessary. """
_description = 'Simple Chatter Model'
_name = 'mail.test.simple'
_inherit = ['mail.thread']
name = fields.Char()
email_from = fields.Char()
class MailTestGateway(models.Model):
""" A very simple model only inheriting from mail.thread to test pure mass
mailing features and base performances. """
_description = 'Simple Chatter Model for Mail Gateway'
_name = 'mail.test.gateway'
_inherit = ['mail.thread.blacklist']
_primary_email = 'email_from'
name = fields.Char()
email_from = fields.Char()
custom_field = fields.Char()
class MailTestGatewayGroups(models.Model):
""" A model looking like discussion channels / groups (flat thread and
alias). Used notably for advanced gatewxay tests. """
_description = 'Channel/Group-like Chatter Model for Mail Gateway'
_name = 'mail.test.gateway.groups'
_inherit = ['mail.thread.blacklist', 'mail.alias.mixin']
_mail_flat_thread = False
_primary_email = 'email_from'
name = fields.Char()
email_from = fields.Char()
custom_field = fields.Char()
customer_id = fields.Many2one('res.partner', 'Customer')
def _alias_get_creation_values(self):
values = super(MailTestGatewayGroups, self)._alias_get_creation_values()
values['alias_model_id'] = self.env['ir.model']._get('mail.test.gateway.groups').id
if self.id:
values['alias_force_thread_id'] = self.id
values['alias_parent_thread_id'] = self.id
return values
class MailTestStandard(models.Model):
""" This model can be used in tests when automatic subscription and simple
tracking is necessary. Most features are present in a simple way. """
_description = 'Standard Chatter Model'
_name = 'mail.test.track'
_inherit = ['mail.thread']
name = fields.Char()
email_from = fields.Char()
user_id = fields.Many2one('res.users', 'Responsible', tracking=True)
container_id = fields.Many2one('mail.test.container', tracking=True)
company_id = fields.Many2one('res.company')
def _get_share_url(self, redirect, signup_partner, share_token):
"""This function is required for a test on 'mail.mail_notification_paynow' template (test_message_post/test_mail_add_signature),
another model should be created in master"""
return '/mail/view'
class MailTestActivity(models.Model):
""" This model can be used to test activities in addition to simple chatter
features. """
_description = 'Activity Model'
_name = 'mail.test.activity'
_inherit = ['mail.thread', 'mail.activity.mixin']
name = fields.Char()
date = fields.Date()
email_from = fields.Char()
active = fields.Boolean(default=True)
def action_start(self, action_summary):
return self.activity_schedule(
'test_mail.mail_act_test_todo',
summary=action_summary
)
def action_close(self, action_feedback):
self.activity_feedback(['test_mail.mail_act_test_todo'], feedback=action_feedback)
class MailTestTicket(models.Model):
""" This model can be used in tests when complex chatter features are
required like modeling tasks or tickets. """
_description = 'Ticket-like model'
_name = 'mail.test.ticket'
_inherit = ['mail.thread']
name = fields.Char()
email_from = fields.Char(tracking=True)
count = fields.Integer(default=1)
datetime = fields.Datetime(default=fields.Datetime.now)
mail_template = fields.Many2one('mail.template', 'Template')
customer_id = fields.Many2one('res.partner', 'Customer', tracking=2)
user_id = fields.Many2one('res.users', 'Responsible', tracking=1)
container_id = fields.Many2one('mail.test.container', tracking=True)
def _track_template(self, changes):
res = super(MailTestTicket, self)._track_template(changes)
record = self[0]
if 'customer_id' in changes and record.mail_template:
res['customer_id'] = (record.mail_template, {'composition_mode': 'mass_mail'})
elif 'datetime' in changes:
res['datetime'] = ('test_mail.mail_test_ticket_tracking_view', {'composition_mode': 'mass_mail'})
return res
def _creation_subtype(self):
if self.container_id:
return self.env.ref('test_mail.st_mail_test_ticket_container_upd')
return super(MailTestTicket, self)._creation_subtype()
def _track_subtype(self, init_values):
self.ensure_one()
if 'container_id' in init_values and self.container_id:
return self.env.ref('test_mail.st_mail_test_ticket_container_upd')
return super(MailTestTicket, self)._track_subtype(init_values)
class MailTestContainer(models.Model):
""" This model can be used in tests when container records like projects
or teams are required. """
_description = 'Project-like model with alias'
_name = 'mail.test.container'
_mail_post_access = 'read'
_inherit = ['mail.thread', 'mail.alias.mixin']
name = fields.Char()
description = fields.Text()
customer_id = fields.Many2one('res.partner', 'Customer')
alias_id = fields.Many2one(
'mail.alias', 'Alias',
delegate=True)
def _alias_get_creation_values(self):
values = super(MailTestContainer, self)._alias_get_creation_values()
values['alias_model_id'] = self.env['ir.model']._get('mail.test.container').id
if self.id:
values['alias_force_thread_id'] = self.id
values['alias_parent_thread_id'] = self.id
return values
class MailTestComposerMixin(models.Model):
""" A simple invite-like wizard using the composer mixin, rendering on
itself. """
_description = 'Invite-like Wizard'
_name = 'mail.test.composer.mixin'
_inherit = ['mail.composer.mixin']
name = fields.Char('Name')
author_id = fields.Many2one('res.partner')
description = fields.Html('Description', render_engine="qweb", render_options={"post_process": True}, sanitize=False)
def _compute_render_model(self):
self.render_model = self._name
| 38.311377
| 6,398
|
4,205
|
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 MailPerformanceThread(models.Model):
_name = 'mail.performance.thread'
_description = 'Performance: mail.thread'
_inherit = ['mail.thread']
name = fields.Char()
value = fields.Integer()
value_pc = fields.Float(compute="_value_pc", store=True)
track = fields.Char(default='test', tracking=True)
partner_id = fields.Many2one('res.partner', string='Customer')
@api.depends('value')
def _value_pc(self):
for record in self:
record.value_pc = float(record.value) / 100
class MailPerformanceTracking(models.Model):
_name = 'mail.performance.tracking'
_description = 'Performance: multi tracking'
_inherit = ['mail.thread']
name = fields.Char(required=True, tracking=True)
field_0 = fields.Char(tracking=True)
field_1 = fields.Char(tracking=True)
field_2 = fields.Char(tracking=True)
class MailTestFieldType(models.Model):
""" Test default values, notably type, messing through models during gateway
processing (i.e. lead.type versus attachment.type). """
_description = 'Test Field Type'
_name = 'mail.test.field.type'
_inherit = ['mail.thread']
name = fields.Char()
email_from = fields.Char()
datetime = fields.Datetime(default=fields.Datetime.now)
customer_id = fields.Many2one('res.partner', 'Customer')
type = fields.Selection([('first', 'First'), ('second', 'Second')])
user_id = fields.Many2one('res.users', 'Responsible', tracking=True)
@api.model_create_multi
def create(self, vals_list):
# Emulate an addon that alters the creation context, such as `crm`
if not self._context.get('default_type'):
self = self.with_context(default_type='first')
return super(MailTestFieldType, self).create(vals_list)
class MailTestLang(models.Model):
""" A simple chatter model with lang-based capabilities, allowing to
test translations. """
_description = 'Lang Chatter Model'
_name = 'mail.test.lang'
_inherit = ['mail.thread']
name = fields.Char()
email_from = fields.Char()
customer_id = fields.Many2one('res.partner')
lang = fields.Char('Lang')
class MailTestTrackCompute(models.Model):
_name = 'mail.test.track.compute'
_description = "Test tracking with computed fields"
_inherit = ['mail.thread']
partner_id = fields.Many2one('res.partner', tracking=True)
partner_name = fields.Char(related='partner_id.name', store=True, tracking=True)
partner_email = fields.Char(related='partner_id.email', store=True, tracking=True)
partner_phone = fields.Char(related='partner_id.phone', tracking=True)
class MailTestTrackMonetary(models.Model):
_name = 'mail.test.track.monetary'
_description = 'Test tracking monetary field'
_inherit = ['mail.thread']
company_id = fields.Many2one('res.company')
company_currency = fields.Many2one("res.currency", string='Currency', related='company_id.currency_id', readonly=True, tracking=True)
revenue = fields.Monetary('Revenue', currency_field='company_currency', tracking=True)
class MailTestMultiCompanyWithActivity(models.Model):
""" This model can be used in multi company tests with activity"""
_name = "mail.test.multi.company.with.activity"
_description = "Test Multi Company Mail With Activity"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char()
company_id = fields.Many2one("res.company")
class MailTestSelectionTracking(models.Model):
""" Test tracking for selection fields """
_description = 'Test Selection Tracking'
_name = 'mail.test.track.selection'
_inherit = ['mail.thread']
name = fields.Char()
type = fields.Selection([('first', 'First'), ('second', 'Second')], tracking=True)
class MailTestMultiCompany(models.Model):
""" This model can be used in multi company tests"""
_name = 'mail.test.multi.company'
_description = "Test Multi Company Mail"
_inherit = 'mail.thread'
name = fields.Char()
company_id = fields.Many2one('res.company')
| 36.25
| 4,205
|
49,270
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
MAIL_TEMPLATE = """Return-Path: <whatever-2a840@postmaster.twitter.com>
To: {to}
cc: {cc}
Received: by mail1.openerp.com (Postfix, from userid 10002)
id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)
From: {email_from}
Subject: {subject}
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_Part_4200734_24778174.1344608186754"
Date: Fri, 10 Aug 2012 14:16:26 +0000
Message-ID: {msg_id}
{extra}
------=_Part_4200734_24778174.1344608186754
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Please call me as soon as possible this afternoon!
--
Sylvie
------=_Part_4200734_24778174.1344608186754
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>=20
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8" />
</head>=20
<body style=3D"margin: 0; padding: 0; background: #ffffff;-webkit-text-size-adjust: 100%;">=20
<p>Please call me as soon as possible this afternoon!</p>
<p>--<br/>
Sylvie
<p>
</body>
</html>
------=_Part_4200734_24778174.1344608186754--
"""
MAIL_TEMPLATE_EXTRA_HTML = """Return-Path: <whatever-2a840@postmaster.twitter.com>
To: {to}
cc: {cc}
Received: by mail1.openerp.com (Postfix, from userid 10002)
id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)
From: {email_from}
Subject: {subject}
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_Part_4200734_24778174.1344608186754"
Date: Fri, 10 Aug 2012 14:16:26 +0000
Message-ID: {msg_id}
{extra}
------=_Part_4200734_24778174.1344608186754
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Please call me as soon as possible this afternoon!
--
Sylvie
------=_Part_4200734_24778174.1344608186754
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>=20
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8" />
</head>=20
<body style=3D"margin: 0; padding: 0; background: #ffffff;-webkit-text-size-adjust: 100%;">=20
<p>Please call me as soon as possible this afternoon!</p>
{extra_html}
<p>--<br/>
Sylvie
<p>
</body>
</html>
------=_Part_4200734_24778174.1344608186754--
"""
MAIL_TEMPLATE_PLAINTEXT = """Return-Path: <whatever-2a840@postmaster.twitter.com>
To: {to}
Received: by mail1.openerp.com (Postfix, from userid 10002)
id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)
From: {email_from}
Subject: {subject}
MIME-Version: 1.0
Content-Type: text/plain
Date: Fri, 10 Aug 2012 14:16:26 +0000
Message-ID: {msg_id}
{extra}
Please call me as soon as possible this afternoon!
--
Sylvie
"""
MAIL_MULTIPART_MIXED = """Return-Path: <ignasse.carambar@gmail.com>
X-Original-To: raoul@grosbedon.fr
Delivered-To: raoul@grosbedon.fr
Received: by mail1.grosbedon.com (Postfix, from userid 10002)
id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)
X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on mail1.grosbedon.com
X-Spam-Level:
X-Spam-Status: No, score=-2.6 required=5.0 tests=BAYES_00,FREEMAIL_FROM,
HTML_MESSAGE,RCVD_IN_DNSWL_LOW autolearn=unavailable version=3.3.1
Received: from mail-ie0-f173.google.com (mail-ie0-f173.google.com [209.85.223.173])
by mail1.grosbedon.com (Postfix) with ESMTPS id 9BBD7BFAAA
for <raoul@openerp.fr>; Fri, 23 Aug 2013 13:17:55 +0200 (CEST)
Received: by mail-ie0-f173.google.com with SMTP id qd12so575130ieb.4
for <raoul@grosbedon.fr>; Fri, 23 Aug 2013 04:17:54 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20120113;
h=mime-version:date:message-id:subject:from:to:content-type;
bh=dMNHV52EC7GAa7+9a9tqwT9joy9z+1950J/3A6/M/hU=;
b=DGuv0VjegdSrEe36ADC8XZ9Inrb3Iu+3/52Bm+caltddXFH9yewTr0JkCRQaJgMwG9
qXTQgP8qu/VFEbCh6scu5ZgU1hknzlNCYr3LT+Ih7dAZVUEHUJdwjzUU1LFV95G2RaCd
/Lwff6CibuUvrA+0CBO7IRKW0Sn5j0mukYu8dbaKsm6ou6HqS8Nuj85fcXJfHSHp6Y9u
dmE8jBh3fHCHF/nAvU+8aBNSIzl1FGfiBYb2jCoapIuVFitKR4q5cuoodpkH9XqqtOdH
DG+YjEyi8L7uvdOfN16eMr7hfUkQei1yQgvGu9/5kXoHg9+Gx6VsZIycn4zoaXTV3Nhn
nu4g==
MIME-Version: 1.0
X-Received: by 10.50.124.65 with SMTP id mg1mr1144467igb.43.1377256674216;
Fri, 23 Aug 2013 04:17:54 -0700 (PDT)
Received: by 10.43.99.71 with HTTP; Fri, 23 Aug 2013 04:17:54 -0700 (PDT)
Date: Fri, 23 Aug 2013 13:17:54 +0200
Message-ID: <CAP76m_V4BY2F7DWHzwfjteyhW8L2LJswVshtmtVym+LUJ=rASQ@mail.gmail.com>
Subject: Test mail multipart/mixed
From: =?ISO-8859-1?Q?Raoul Grosbedon=E9e?= <ignasse.carambar@gmail.com>
To: Followers of ASUSTeK-Joseph-Walters <raoul@grosbedon.fr>
Content-Type: multipart/mixed; boundary=089e01536c4ed4d17204e49b8e96
--089e01536c4ed4d17204e49b8e96
Content-Type: multipart/alternative; boundary=089e01536c4ed4d16d04e49b8e94
--089e01536c4ed4d16d04e49b8e94
Content-Type: text/plain; charset=ISO-8859-1
Should create a multipart/mixed: from gmail, *bold*, with attachment.
--
Marcel Boitempoils.
--089e01536c4ed4d16d04e49b8e94
Content-Type: text/html; charset=ISO-8859-1
<div dir="ltr">Should create a multipart/mixed: from gmail, <b>bold</b>, with attachment.<br clear="all"><div><br></div>-- <br>Marcel Boitempoils.</div>
--089e01536c4ed4d16d04e49b8e94--
--089e01536c4ed4d17204e49b8e96
Content-Type: text/plain; charset=US-ASCII; name="test.txt"
Content-Disposition: attachment; filename="test.txt"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_hkpb27k00
dGVzdAo=
--089e01536c4ed4d17204e49b8e96--"""
MAIL_MULTIPART_MIXED_TWO = """X-Original-To: raoul@grosbedon.fr
Delivered-To: raoul@grosbedon.fr
Received: by mail1.grosbedon.com (Postfix, from userid 10002)
id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)
From: "Bruce Wayne" <bruce@wayneenterprises.com>
Content-Type: multipart/alternative;
boundary="Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227"
Message-Id: <6BB1FAB2-2104-438E-9447-07AE2C8C4A92@sexample.com>
Mime-Version: 1.0 (Mac OS X Mail 7.3 \(1878.6\))
--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=us-ascii
First and second part
--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227
Content-Type: multipart/mixed;
boundary="Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F"
--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F
Content-Transfer-Encoding: 7bit
Content-Type: text/html;
charset=us-ascii
<html><head></head><body>First part</body></html>
--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F
Content-Disposition: inline;
filename=thetruth.pdf
Content-Type: application/pdf;
name="thetruth.pdf"
Content-Transfer-Encoding: base64
SSBhbSB0aGUgQmF0TWFuCg==
--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F
Content-Transfer-Encoding: 7bit
Content-Type: text/html;
charset=us-ascii
<html><head></head><body>Second part</body></html>
--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F--
--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227--
"""
MAIL_FILE_ENCODING = """MIME-Version: 1.0
Date: Sun, 26 Mar 2023 05:23:22 +0200
Message-ID: {msg_id}
Subject: {subject}
From: "Sylvie Lelitre" <test.sylvie.lelitre@agrolait.com>
To: groups@test.com
Content-Type: multipart/mixed; boundary="000000000000b951de05f7c47a9e"
--000000000000b951de05f7c47a9e
Content-Type: multipart/alternative; boundary="000000000000b951da05f7c47a9c"
--000000000000b951da05f7c47a9c
Content-Type: text/plain; charset="UTF-8"
Test Body
--000000000000b951da05f7c47a9c
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Test Body</div>
--000000000000b951da05f7c47a9c--
--000000000000b951de05f7c47a9e
Content-Type: text/plain; name="test.txt"{charset}
Content-Disposition: attachment; filename="test.txt"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_lfosfm0l0
Content-ID: <f_lfosfm0l0>
{content}
--000000000000b951de05f7c47a9e--
"""
MAIL_MULTIPART_BINARY_OCTET_STREAM = """X-Original-To: raoul@grosbedon.fr
Delivered-To: raoul@grosbedon.fr
Received: by mail1.grosbedon.com (Postfix, from userid 10002)
id E8166BFACA; Fri, 10 Nov 2021 06:04:01 +0200 (CEST)
From: "Bruce Wayne" <bruce@wayneenterprises.com>
Content-Type: multipart/alternative;
boundary="Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227"
Message-Id: <6BB1FAB2-2104-438E-9447-07AE2C8C4A92@sexample.com>
Mime-Version: 1.0 (Mac OS X Mail 7.3 \\(1878.6\\))
--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=us-ascii
The attached file contains b"Hello world\\n"
--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227
Content-Disposition: attachment;
filename="hello_world.dat"
Content-Type: binary/octet-stream;
name="hello_world.dat"
Content-Transfer-Encoding: base64
SGVsbG8gd29ybGQK
--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227--
"""
MAIL_MULTIPART_INVALID_ENCODING = """Return-Path: <whatever-2a840@postmaster.twitter.com>
To: {to}
cc: {cc}
Received: by mail1.openerp.com (Postfix, from userid 10002)
id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)
From: {email_from}
Subject: {subject}
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="00000000000005d9da05fa394cc0"
Date: Fri, 10 Aug 2012 14:16:26 +0000
Message-ID: {msg_id}
{extra}
--00000000000005d9da05fa394cc0
Content-Type: multipart/alternative; boundary="00000000000005d9d905fa394cbe"
--00000000000005d9d905fa394cbe
Content-Type: text/plain; charset="UTF-8"
Dear customer,
Please find attached the Peppol Bis 3 attachment of your invoice (with an
encoding error in the address)
Cheers,
--00000000000005d9d905fa394cbe
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Dear customer,<div><br></div><div>Please find attached the Peppol Bis 3 attachment of your invoice (with an encoding error in the address)</div><div><br></div><div>Cheers,</div></div>
--00000000000005d9d905fa394cbe--
--00000000000005d9da05fa394cc0
Content-Type: text/xml; charset="US-ASCII";
name="bis3_with_error_encoding_address.xml"
Content-Disposition: attachment;
filename="bis3_with_error_encoding_address.xml"
Content-Transfer-Encoding: base64
Content-ID: <f_lgxgdqx40>
X-Attachment-Id: f_lgxgdqx40
PEludm9pY2UgeG1sbnM6Y2JjPSJ1cm46b2FzaXM6bmFtZXM6c3BlY2lmaWNhdGlvbjp1Ymw6c2No
ZW1hOnhzZDpDb21tb25CYXNpY0NvbXBvbmVudHMtMiIgeG1sbnM9InVybjpvYXNpczpuYW1lczpz
cGVjaWZpY2F0aW9uOnVibDpzY2hlbWE6eHNkOkludm9pY2UtMiI+DQo8Y2JjOlN0cmVldE5hbWU+
Q2hhdXNz77+977+9ZSBkZSBCcnV4ZWxsZXM8L2NiYzpTdHJlZXROYW1lPg0KPC9JbnZvaWNlPg0K
--00000000000005d9da05fa394cc0--
"""
MAIL_MULTIPART_OMITTED_CHARSET = """Return-Path: <whatever-2a840@postmaster.twitter.com>
To: {to}
cc: {cc}
Received: by mail1.openerp.com (Postfix, from userid 10002)
id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)
From: {email_from}
Subject: {subject}
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="00000000000005d9da05fa394cc0"
Date: Fri, 10 Aug 2012 14:16:26 +0000
Message-ID: {msg_id}
{extra}
--00000000000005d9da05fa394cc0
Content-Type: multipart/alternative; boundary="00000000000005d9d905fa394cbe"
--00000000000005d9d905fa394cbe
Content-Type: text/plain; charset="UTF-8"
Dear customer,
Please find attached the UBL attachment of your invoice
Cheers,
--00000000000005d9d905fa394cbe
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Dear customer,<div><br></div><div>Please find attached the UBL attachment of your invoice</div><div><br></div><div>Cheers,</div></div>
--00000000000005d9d905fa394cbe--
--00000000000005d9da05fa394cc0
Content-Disposition: attachment; filename="bis3.xml"
Content-Transfer-Encoding: base64
Content-Type: text/xml; name="bis3.xml"
Content-ID: <f_lgxgdqx40>
X-Attachment-Id: f_lgxgdqx40
PEludm9pY2U+Q2hhdXNzw6llIGRlIEJydXhlbGxlczwvSW52b2ljZT4=
--00000000000005d9da05fa394cc0--
"""
MAIL_SINGLE_BINARY = """X-Original-To: raoul@grosbedon.fr
Delivered-To: raoul@grosbedon.fr
Received: by mail1.grosbedon.com (Postfix, from userid 10002)
id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)
From: "Bruce Wayne" <bruce@wayneenterprises.com>
Content-Type: application/pdf;
Content-Disposition: filename=thetruth.pdf
Content-Transfer-Encoding: base64
Message-Id: <6BB1FAB2-2104-438E-9447-07AE2C8C4A92@sexample.com>
Mime-Version: 1.0 (Mac OS X Mail 7.3 \(1878.6\))
SSBhbSB0aGUgQmF0TWFuCg=="""
MAIL_MULTIPART_WEIRD_FILENAME = """X-Original-To: john@doe.com
Delivered-To: johndoe@example.com
Received: by mail.example.com (Postfix, from userid 10002)
id E8166BFACB; Fri, 23 Aug 2013 13:18:02 +0200 (CEST)
From: "Bruce Wayne" <bruce@wayneenterprises.com>
Subject: test
Message-ID: <c0c20fdd-a38e-b296-865b-d9232bf30ce5@odoo.com>
Date: Mon, 26 Aug 2019 16:55:09 +0200
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="------------FACA7766210AAA981EAE01F3"
Content-Language: en-US
This is a multi-part message in MIME format.
--------------FACA7766210AAA981EAE01F3
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit
plop
--------------FACA7766210AAA981EAE01F3
Content-Type: text/plain; charset=UTF-8;
name="=?UTF-8?B?NjJfQDssXVspPS4ow4fDgMOJLnR4dA==?="
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename*0*=utf-8'en-us'%36%32%5F%40%3B%2C%5D%5B%29%3D%2E%28%C3%87%C3%80%C3%89;
filename*1*=%2E%74%78%74
SSBhbSBhIGZpbGUgd2l0aCBhIHZhbGlkIHdpbmRvd3MgZmlsZW5hbWUK
--------------FACA7766210AAA981EAE01F3--
"""
MAIL_MULTIPART_IMAGE = """X-Original-To: raoul@example.com
Delivered-To: micheline@example.com
Received: by mail1.example.com (Postfix, from userid 99999)
id 9DFB7BF509; Thu, 17 Dec 2015 15:22:56 +0100 (CET)
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on mail1.example.com
X-Spam-Level: *
X-Spam-Status: No, score=1.1 required=5.0 tests=FREEMAIL_FROM,
HTML_IMAGE_ONLY_08,HTML_MESSAGE,RCVD_IN_DNSWL_LOW,RCVD_IN_MSPIKE_H3,
RCVD_IN_MSPIKE_WL,T_DKIM_INVALID autolearn=no autolearn_force=no version=3.4.0
Received: from mail-lf0-f44.example.com (mail-lf0-f44.example.com [209.85.215.44])
by mail1.example.com (Postfix) with ESMTPS id 1D80DBF509
for <micheline@example.com>; Thu, 17 Dec 2015 15:22:56 +0100 (CET)
Authentication-Results: mail1.example.com; dkim=pass
reason="2048-bit key; unprotected key"
header.d=example.com header.i=@example.com header.b=kUkTIIlt;
dkim-adsp=pass; dkim-atps=neutral
Received: by mail-lf0-f44.example.com with SMTP id z124so47959461lfa.3
for <micheline@example.com>; Thu, 17 Dec 2015 06:22:56 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=example.com; s=20120113;
h=mime-version:date:message-id:subject:from:to:content-type;
bh=GdrEuMrz6vxo/Z/F+mJVho/1wSe6hbxLx2SsP8tihzw=;
b=kUkTIIlt6fe4dftKHPNBkdHU2rO052o684R0e2bqH7roGUQFb78scYE+kqX0wo1zlk
zhKPVBR1TqTsYlqcHu+D3aUzai7L/Q5m40sSGn7uYGkZJ6m1TwrWNqVIgTZibarqvy94
NWhrjjK9gqd8segQdSjCgTipNSZME4bJCzPyBg/D5mqe07FPBJBGoF9SmIzEBhYeqLj1
GrXjb/D8J11aOyzmVvyt+bT+oeLUJI8E7qO5g2eQkMncyu+TyIXaRofOOBA14NhQ+0nS
w5O9rzzqkKuJEG4U2TJ2Vi2nl2tHJW2QPfTtFgcCzGxQ0+5n88OVlbGTLnhEIJ/SYpem
O5EA==
MIME-Version: 1.0
X-Received: by 10.25.167.197 with SMTP id q188mr22222517lfe.129.1450362175493;
Thu, 17 Dec 2015 06:22:55 -0800 (PST)
Received: by 10.25.209.145 with HTTP; Thu, 17 Dec 2015 06:22:55 -0800 (PST)
Date: Thu, 17 Dec 2015 15:22:55 +0100
Message-ID: <CAP76m_UB=aLqWEFccnq86AhkpwRB3aZoGL9vMffX7co3YEro_A@mail.gmail.com>
Subject: {subject}
From: =?UTF-8?Q?Thibault_Delavall=C3=A9e?= <raoul@example.com>
To: {to}
Content-Type: multipart/related; boundary=001a11416b9e9b229a05272b7052
--001a11416b9e9b229a05272b7052
Content-Type: multipart/alternative; boundary=001a11416b9e9b229805272b7051
--001a11416b9e9b229805272b7051
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Premi=C3=A8re image, orang=C3=A9e.
[image: Inline image 1]
Seconde image, rosa=C3=A7=C3=A9e.
[image: Inline image 2]
Troisi=C3=A8me image, verte!=C2=B5
[image: Inline image 3]
J'esp=C3=A8re que tout se passera bien.
--=20
Thibault Delavall=C3=A9e
--001a11416b9e9b229805272b7051
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
<div dir=3D"ltr"><div>Premi=C3=A8re image, orang=C3=A9e.</div><div><br></di=
v><div><img src=3D"cid:ii_151b519fc025fdd3" alt=3D"Inline image 1" width=3D=
"2" height=3D"2"><br></div><div><br></div><div>Seconde image, rosa=C3=A7=C3=
=A9e.</div><div><br></div><div><img src=3D"cid:ii_151b51a290ed6a91" alt=3D"=
Inline image 2" width=3D"2" height=3D"2"></div><div><br></div><div>Troisi=
=C3=A8me image, verte!=C2=B5</div><div><br></div><div><img src=3D"cid:ii_15=
1b51a37e5eb7a6" alt=3D"Inline image 3" width=3D"10" height=3D"10"><br></div=
><div><br></div><div>J'esp=C3=A8re que tout se passera bien.</div>-- <b=
r><div class=3D"gmail_signature">Thibault Delavall=C3=A9e</div>
</div>
--001a11416b9e9b229805272b7051--
--001a11416b9e9b229a05272b7052
Content-Type: image/gif; name="=?UTF-8?B?b3JhbmfDqWUuZ2lm?="
Content-Disposition: inline; filename="=?UTF-8?B?b3JhbmfDqWUuZ2lm?="
Content-Transfer-Encoding: base64
Content-ID: <ii_151b519fc025fdd3>
X-Attachment-Id: ii_151b519fc025fdd3
R0lGODdhAgACALMAAAAAAP///wAAAP//AP8AAP+AAAD/AAAAAAAA//8A/wAAAAAAAAAAAAAAAAAA
AAAAACwAAAAAAgACAAAEA7DIEgA7
--001a11416b9e9b229a05272b7052
Content-Type: image/gif; name="=?UTF-8?B?dmVydGUhwrUuZ2lm?="
Content-Disposition: inline; filename="=?UTF-8?B?dmVydGUhwrUuZ2lm?="
Content-Transfer-Encoding: base64
Content-ID: <ii_151b51a37e5eb7a6>
X-Attachment-Id: ii_151b51a37e5eb7a6
R0lGODlhCgAKALMAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwICAgP8AAAD/AP//AAAA//8A/wD/
/////ywAAAAACgAKAAAEClDJSau9OOvNe44AOw==
--001a11416b9e9b229a05272b7052
Content-Type: image/gif; name="=?UTF-8?B?cm9zYcOnw6llLmdpZg==?="
Content-Disposition: inline; filename="=?UTF-8?B?cm9zYcOnw6llLmdpZg==?="
Content-Transfer-Encoding: base64
Content-ID: <ii_151b51a290ed6a91>
X-Attachment-Id: ii_151b51a290ed6a91
R0lGODdhAgACALMAAAAAAP///wAAAP//AP8AAP+AAAD/AAAAAAAA//8A/wAAAP+AgAAAAAAAAAAA
AAAAACwAAAAAAgACAAAEA3DJFQA7
--001a11416b9e9b229a05272b7052--
"""
MAIL_EML_ATTACHMENT = """Subject: Re: test attac
From: {email_from}
To: {to}
References: <f3b9f8f8-28fa-2543-cab2-7aa68f679ebb@odoo.com>
Message-ID: <cb7eaf62-58dc-2017-148c-305d0c78892f@odoo.com>
Date: Wed, 14 Mar 2018 14:26:58 +0100
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101
Thunderbird/52.6.0
MIME-Version: 1.0
In-Reply-To: <f3b9f8f8-28fa-2543-cab2-7aa68f679ebb@odoo.com>
Content-Type: multipart/mixed;
boundary="------------A6B5FD5F68F4D73ECD739009"
Content-Language: en-US
This is a multi-part message in MIME format.
--------------A6B5FD5F68F4D73ECD739009
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit
On 14/03/18 14:20, Anon wrote:
> Some nice content
>
--------------A6B5FD5F68F4D73ECD739009
Content-Type: message/rfc822;
name="original_msg.eml"
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment;
filename="original_msg.eml"
Delivered-To: anon2@gmail1.openerp.com
Received: by 10.46.1.170 with SMTP id f42csp2379722lji;
Mon, 5 Mar 2018 01:19:23 -0800 (PST)
X-Google-Smtp-Source: AG47ELsYTlAcblMxfnaEENQuF+MFoac5Q07wieyw0cybq/qOX4+DmayqoQILkiWT+NiTOcnr/ACO
X-Received: by 10.28.154.213 with SMTP id c204mr7237750wme.64.1520241563503;
Mon, 05 Mar 2018 01:19:23 -0800 (PST)
ARC-Seal: i=1; a=rsa-sha256; t=1520241563; cv=none;
d=google.com; s=arc-20160816;
b=BqgMSbqmbpYW1ZtfGTVjj/654MBmabw4XadNZEaI96hDaub6N6cP8Guu3PoxscI9os
0OLYVP1s/B+Vv9rIzulCwHyHsgnX+aTxGYepTDN6x8SA9Qeb9aQoNSVvQLryTAoGpaFr
vXhw8aPWyr28edE03TDFA/s7X65Bf6dV5zJdMiUPVqGkfYfcTHMf3nDER5vk8vQj7tve
Cfyy0h9vLU9RSEtdFwmlEkLmgT9NQ3GDf0jQ97eMXPgR2q6duCPoMcz15KlWOno53xgH
EiV7aIZ5ZMN/m+/2xt3br/ubJ5euFojWhDnHUZoaqd08TCSQPd4fFCCx75MjDeCnwYMn
iKSg==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
h=content-language:mime-version:user-agent:date:message-id:subject
:from:to:dkim-signature:arc-authentication-results;
bh=/UIFqhjCCbwBLsI4w7YY98QH6G/wxe+2W4bbMDCskjM=;
b=Wv5jt+usnSgWI96GaZWUN8/VKl1drueDpU/4gkyX/iK4d6S4CuSDjwYAc3guz/TjeW
GoKCqT30IGZoStpXQbuLry7ezXNK+Fp8MJKN2n/x5ClJWHxIsxIGlP2QC3TO8RI0P5o0
GXG9izW93q1ubkdPJFt3unSjjwSYf5XVQAZQtRm9xKjqA+lbtFbsnbjJ4wgYBURnD8ma
Qxb2xsxXDelaZvtdlzHRDn5SEkbqhcCclEYw6oRLpVQFZeYtPxcCleVybtj2owJxdaLp
7wXuo/gpYe6E2cPuS2opei8AzjEhYTNzlYXTPvaoxCCTTjfGTaPv22TeRDehuIXngSEl
Nmmw==
ARC-Authentication-Results: i=1; mx.google.com;
dkim=pass header.i=@odoo.com header.s=mail header.b=MCzhjB9b;
spf=pass (google.com: domain of soup@odoo.com designates 149.202.180.44 as permitted sender) smtp.mailfrom=soup@odoo.com;
dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=odoo.com
Return-Path: <soup@odoo.com>
Received: from mail2.odoo.com (mail2.odoo.com. [149.202.180.44])
by mx.google.com with ESMTPS id y4si4279200wmy.148.2018.03.05.01.19.22
(version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
Mon, 05 Mar 2018 01:19:23 -0800 (PST)
Received-SPF: pass (google.com: domain of soup@odoo.com designates 149.202.180.44 as permitted sender) client-ip=149.202.180.44;
Authentication-Results: mx.google.com;
dkim=pass header.i=@odoo.com header.s=mail header.b=MCzhjB9b;
spf=pass (google.com: domain of soup@odoo.com designates 149.202.180.44 as permitted sender) smtp.mailfrom=soup@odoo.com;
dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=odoo.com
Received: from [10.10.31.24] (unknown [91.183.114.50])
(Authenticated sender: soup)
by mail2.odoo.com (Postfix) with ESMTPSA id 7B571A4085
for <what@odoo.com>; Mon, 5 Mar 2018 10:19:21 +0100 (CET)
DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=odoo.com; s=mail;
t=1520241562; bh=L2r7Sp/vjogIdM1k8H9zDGDjnhKolsTTLLjndnFC4Jc=;
h=To:From:Subject:Date:From;
b=MCzhjB9bnsrJ3uKjq+GjujFxmtrq3fc7Vv7Vg2C72EPKnkxgqy6yPjWKtXbBlaiT3
YjKI24aiSQlOeOPQiqFgiDzeqqemNDp+CRuhoYz1Vbz+ESRaHtkWRLb7ZjvohS2k7e
RTq7tUxY2nUL2YrNHV7DFYtJVBwiTuyLP6eAiJdE=
To: what@odoo.com
From: Soup <soup@odoo.com>
Subject: =?UTF-8?Q?Soupe_du_jour_:_Pois_cass=c3=a9s?=
Message-ID: <a05d8334-7b7c-df68-c96a-4a88ed19f31b@odoo.com>
Date: Mon, 5 Mar 2018 10:19:21 +0100
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101
Thunderbird/52.6.0
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="------------1F2D18B1129FC2F0B9EECF50"
Content-Language: en-US
X-Spam-Status: No, score=-1.2 required=5.0 tests=ALL_TRUSTED,BAYES_00,
HTML_IMAGE_ONLY_08,HTML_MESSAGE,T_REMOTE_IMAGE autolearn=no
autolearn_force=no version=3.4.0
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on mail2.odoo.com
This is a multi-part message in MIME format.
--------------1F2D18B1129FC2F0B9EECF50
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 8bit
Résultat de recherche d'images pour "dessin la princesse au petit pois"
--
Soup
Odoo S.A.
Chaussée de Namur, 40
B-1367 Grand Rosière
Web: http://www.odoo.com
--------------1F2D18B1129FC2F0B9EECF50
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 8bit
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body text="#000000" bgcolor="#FFFFFF">
<p><img
src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQjCNAadd3NDM8g9w0P_-gAVYrrqC0wmBNYKGsTZ2Pst5SsNxTRnA"
alt="Résultat de recherche d'images pour "dessin la
princesse au petit pois""></p>
<pre class="moz-signature" cols="72">--
Soup
Odoo S.A.
Chaussée de Namur, 40
B-1367 Grand Rosière
Web: <a class="moz-txt-link-freetext" href="http://www.odoo.com">http://www.odoo.com</a> </pre>
</body>
</html>
--------------1F2D18B1129FC2F0B9EECF50--
--------------A6B5FD5F68F4D73ECD739009--"""
MAIL_EML_ATTACHMENT_BOUNCE_HEADERS="""\
Date: Tue, 24 Dec 2019 11:32:07 +0100 (CET)
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=16063919151.b32bE0eD.7
Content-Transfer-Encoding: 7bit
Subject: Undelivered Mail Returned to Sender
From: {email_from}
To: {to}
Message-Id: <20191224103207.415713014C@example.com>
Return-Path: <MAILER-DAEMON>
Delivered-To: odoo+82240-account.invoice-19177@mycompany.example.com
Received: by example.com (Postfix) id 415713014C; Tue, 24 Dec
2019 11:32:07 +0100 (CET)
Auto-Submitted: auto-replied
--16063919151.b32bE0eD.7
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=16063919150.2cD3F37.7
Content-Transfer-Encoding: 7bit
Content-ID: <16063919152.fD96.7@8f286b7b7880>
--16063919150.2cD3F37.7
Content-Type: text/plain; charset=US-ASCII
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
This is the mail system at host example.com.
I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.
For further assistance, please send mail to postmaster.
If you do so, please include this problem report. You can
delete your own text from the attached returned message.
--16063919151.b32bE0eD.7
Content-Type: text/rfc822-headers
Content-Transfer-Encoding: 7bit
Return-Path: <bounce+82240-account.invoice-19177@mycompany.example.com>
Received: by example.com (Postfix) id 415713014C; Tue, 24 Dec
Content-Type: multipart/mixed; boundary="===============3600759226158551994=="
MIME-Version: 1.0
Message-Id: {msg_id}
references: <1571814481.189281940460205.799582441238467-openerp-19177-account.invoice@mycompany.example.com>
Subject: Test
From: "Test" <noreply+srglvrz-gmail.com@mycompany.example.com>
Reply-To: "MY COMPANY" <info@mycompany.example.com>
To: "Test" <test@anothercompany.example.com>
Date: Tue, 24 Dec 2019 10:32:05 -0000
X-Odoo-Objects: account.invoice-19177
--16063919151.b32bE0eD.7--"""
MAIL_XHTML = """Return-Path: <xxxx@xxxx.com>
Received: from xxxx.internal (xxxx.xxxx.internal [1.1.1.1])
by xxxx (xxxx 1.1.1-111-g972eecc-slipenbois) with LMTPA;
Fri, 13 Apr 2018 22:11:52 -0400
X-Cyrus-Session-Id: sloti35d1t38-1111111-11111111111-5-11111111111111111111
X-Sieve: CMU Sieve 1.0
X-Spam-known-sender: no ("Email failed DMARC policy for domain"); in-addressbook
X-Spam-score: 0.0
X-Spam-hits: ALL_TRUSTED -1, BAYES_00 -1.9, FREEMAIL_FROM 0.001,
HTML_FONT_LOW_CONTRAST 0.001, HTML_MESSAGE 0.001, SPF_SOFTFAIL 0.665,
LANGUAGES en, BAYES_USED global, SA_VERSION 1.1.0
X-Spam-source: IP='1.1.1.1', Host='unk', Country='unk', FromHeader='com',
MailFrom='com'
X-Spam-charsets: plain='utf-8', html='utf-8'
X-IgnoreVacation: yes ("Email failed DMARC policy for domain")
X-Resolved-to: catchall@xxxx.xxxx
X-Delivered-to: catchall@xxxx.xxxx
X-Mail-from: xxxx@xxxx.com
Received: from mx4 ([1.1.1.1])
by xxxx.internal (LMTPProxy); Fri, 13 Apr 2018 22:11:52 -0400
Received: from xxxx.xxxx.com (localhost [127.0.0.1])
by xxxx.xxxx.internal (Postfix) with ESMTP id E1111C1111;
Fri, 13 Apr 2018 22:11:51 -0400 (EDT)
Received: from xxxx.xxxx.internal (localhost [127.0.0.1])
by xxxx.xxxx.com (Authentication Milter) with ESMTP
id BBDD1111D1A;
Fri, 13 Apr 2018 22:11:51 -0400
ARC-Authentication-Results: i=1; xxxx.xxxx.com; arc=none (no signatures found);
dkim=pass (2048-bit rsa key sha256) header.d=xxxx.com header.i=@xxxx.com header.b=P1aaAAaa x-bits=2048 x-keytype=rsa x-algorithm=sha256 x-selector=fm2;
dmarc=fail (p=none,d=none) header.from=xxxx.com;
iprev=pass policy.iprev=1.1.1.1 (out1-smtp.xxxx.com);
spf=softfail smtp.mailfrom=xxxx@xxxx.com smtp.helo=out1-smtp.xxxx.com;
x-aligned-from=pass (Address match);
x-cm=none score=0;
x-ptr=pass x-ptr-helo=out1-smtp.xxxx.com x-ptr-lookup=out1-smtp.xxxx.com;
x-return-mx=pass smtp.domain=xxxx.com smtp.result=pass smtp_is_org_domain=yes header.domain=xxxx.com header.result=pass header_is_org_domain=yes;
x-tls=pass version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128;
x-vs=clean score=0 state=0
Authentication-Results: xxxx.xxxx.com;
arc=none (no signatures found);
dkim=pass (2048-bit rsa key sha256) header.d=xxxx.com header.i=@xxxx.com header.b=P1awJPiy x-bits=2048 x-keytype=rsa x-algorithm=sha256 x-selector=fm2;
dmarc=fail (p=none,d=none) header.from=xxxx.com;
iprev=pass policy.iprev=66.111.4.25 (out1-smtp.xxxx.com);
spf=softfail smtp.mailfrom=xxxx@xxxx.com smtp.helo=out1-smtp.xxxx.com;
x-aligned-from=pass (Address match);
x-cm=none score=0;
x-ptr=pass x-ptr-helo=out1-smtp.xxxx.com x-ptr-lookup=out1-smtp.xxxx.com;
x-return-mx=pass smtp.domain=xxxx.com smtp.result=pass smtp_is_org_domain=yes header.domain=xxxx.com header.result=pass header_is_org_domain=yes;
x-tls=pass version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128;
x-vs=clean score=0 state=0
X-ME-VSCategory: clean
X-ME-CMScore: 0
X-ME-CMCategory: none
Received-SPF: softfail
(gmail.com ... _spf.xxxx.com: Sender is not authorized by default to use 'xxxx@xxxx.com' in 'mfrom' identity, however domain is not currently prepared for false failures (mechanism '~all' matched))
receiver=xxxx.xxxx.com;
identity=mailfrom;
envelope-from="xxxx@xxxx.com";
helo=out1-smtp.xxxx.com;
client-ip=1.1.1.1
Received: from xxxx.xxxx.internal (gateway1.xxxx.internal [1.1.1.1])
(using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits))
(No client certificate requested)
by xxxx.xxxx.internal (Postfix) with ESMTPS;
Fri, 13 Apr 2018 22:11:51 -0400 (EDT)
Received: from compute3.internal (xxxx.xxxx.internal [10.202.2.43])
by xxxx.xxxx.internal (Postfix) with ESMTP id 8BD5B21BBD;
Fri, 13 Apr 2018 22:11:51 -0400 (EDT)
Received: from xxxx ([10.202.2.163])
by xxxx.internal (MEProxy); Fri, 13 Apr 2018 22:11:51 -0400
X-ME-Sender: <xms:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>
Received: from [1.1.1.1] (unknown [1.1.1.1])
by mail.xxxx.com (Postfix) with ESMTPA id BF5E1111D
for <catchall@xxxx.xxxx>; Fri, 13 Apr 2018 22:11:50 -0400 (EDT)
From: Sylvie Lelitre <test.sylvie.lelitre@agrolait.com>
To: generic@mydomain.com
Subject: Re: xxxx (Ref PO1)
Date: Sat, 14 Apr 2018 02:11:42 +0000
Message-Id: <em67f5c44a-xxxx-xxxx-xxxx-69f56d618a94@wswin7hg4n4l1ce>
In-Reply-To: <829228111124527.1111111602.256611118262939-openerp-129-xxxx.xxxx@ip-1-1-1-1>
References: <867911111953277.1523671337.187951111160400-openerp-129-xxxx.xxxx@ip-1-1-1-1>
<867911111953277.1523671337.256611118262939-openerp-129-xxxx.xxxx@ip-1-1-1-1>
Reply-To: "xxxx xxxx" <xxxx@xxxx.com>
User-Agent: eM_Client/7.0.26687.0
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="------=_MB48E455BD-1111-42EC-1111-886CDF48905E"
--------=_MB48E455BD-1111-42EC-1111-886CDF48905E
Content-Type: text/plain; format=flowed; charset=utf-8
Content-Transfer-Encoding: quoted-printable
xxxx
------ Original Message ------
From: "xxxx" <xxxx@xxxx.com>
To: "xxxx" <xxxx@xxxx.com>
Sent: 4/13/2018 7:06:43 PM
Subject: xxxx
>xxxx
--------=_MB48E455BD-1111-42EC-1111-886CDF48905E
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<?xml version=3D"1.0" encoding=3D"utf-16"?><html><head><style type=3D"text/=
css"><!--blockquote.cite
{margin-left: 5px; margin-right: 0px; padding-left: 10px; padding-right:=
0px; border-left-width: 1px; border-left-style: solid; border-left-color:=
rgb(204, 204, 204);}
blockquote.cite2
{margin-left: 5px; margin-right: 0px; padding-left: 10px; padding-right:=
0px; border-left-width: 1px; border-left-style: solid; border-left-color:=
rgb(204, 204, 204); margin-top: 3px; padding-top: 0px;}
a img
{border: 0px;}
body
{font-family: Tahoma; font-size: 12pt;}
--></style></head><body><div>this is a reply to PO200109 from emClient</div=
><div id=3D"signature_old"><div style=3D"font-family: Tahoma; font-size:=
12 pt;">-- <br /><span><span class=3D"__postbox-detected-content __postbox=
-detected-address" style=3D"TEXT-DECORATION: underline; COLOR: rgb(115,133,=
172); PADDING-BOTTOM: 0pt; PADDING-TOP: 0pt; PADDING-LEFT: 0pt; DISPLAY:=
inline; PADDING-RIGHT: 0pt" __postbox-detected-content=3D"__postbox-detect=
ed-address"></span>xxxx<br />xxxx<br /><b=
r />xxxx</span></=
div></div><div><br /></div><div><br /></div><div><br /></div>
<div>------ Original Message ------</div>
<div>From: "xxxx" <<a href=3D"mailto:xxxx@xxxx.com">xxxx=
@xxxx.com</a>></div>
<div>To: "xxxx" <<a href=3D"mailto:xxxx@xxxx.com">a=
xxxx@xxxx.com</a>></div>
<div>Sent: 4/13/2018 7:06:43 PM</div>
<div>Subject: xxxx</div><div><br /></div=
>
<div id=3D"x00b4101ba6e64ce"><blockquote cite=3D"829228972724527.1523671602=
.256660938262939-openerp-129-xxxx.xxxx@ip-1-1-1-1" type=3D"cite"=
class=3D"cite2">
<table border=3D"0" width=3D"100%" cellpadding=3D"0" bgcolor=3D"#ededed"=
style=3D"padding: 20px; background-color: #ededed" summary=3D"o_mail_notif=
ication">
<tbody>
<!-- HEADER -->
<tr>
<td align=3D"center" style=3D"min-width: 590px;">
<table width=3D"590" border=3D"0" cellpadding=3D=
"0" bgcolor=3D"#875A7B" style=3D"min-width: 590px; background-color: rgb(13=
5,90,123); padding: 20px;">
<tbody><tr>
<td valign=3D"middle">
<span style=3D"font-size:20px; color:whit=
e; font-weight: bold;">
mangez des saucisses
</span>
</td>
<td valign=3D"middle" align=3D"right">
<img src=3D"http://erp.xxxx.xxxx/logo.png=
" style=3D"padding: 0px; margin: 0px; height: auto; width: 80px;" alt=3D=
"xxxx" />
</td>
</tr>
</tbody></table>
</td>
</tr>
<!-- CONTENT -->
<tr>
<td align=3D"center" style=3D"min-width: 590px;">
<table width=3D"590" border=3D"0" cellpadding=3D=
"0" bgcolor=3D"#ffffff" style=3D"min-width: 590px; background-color: rgb(25=
5, 255, 255); padding: 20px;">
<tbody>
<tr><td valign=3D"top" style=3D"font-family:A=
rial,Helvetica,sans-serif; color: #555; font-size: 14px;">
<p style=3D"margin: 0px 0px 9px 0px; font-s=
ize: 13px; font-family: "Lucida Grande", Helvetica, Verdana, Aria=
l, sans-serif">xxxx.=20
,</p>
<p style=3D"margin: 0px 0px 9px 0px; font-size: 13px; font-family: "Lu=
cida Grande", Helvetica, Verdana, Arial, sans-serif">
xxxx.
</p>
<p style=3D"margin: 0px 0px 9px 0px; font-size: 13px; font-family: "Lu=
cida Grande", Helvetica, Verdana, Arial, sans-serif">You can reply =
to this email if you have any questions.</p>
<p style=3D"margin: 0px 0px 9px 0px; font-size: 13px; font-family: "Lu=
cida Grande", Helvetica, Verdana, Arial, sans-serif">Thank you,</p>
</td>
</tr></tbody>
</table>
</td>
</tr>
<!-- FOOTER -->
<tr>
<td align=3D"center" style=3D"min-width: 590px;">
<table width=3D"590" border=3D"0" cellpadding=3D=
"0" bgcolor=3D"#875A7B" style=3D"min-width: 590px; background-color: rgb(13=
5,90,123); padding: 20px;">
<tbody><tr>
<td valign=3D"middle" align=3D"left" style=
=3D"color: #fff; padding-top: 10px; padding-bottom: 10px; font-size: 12px;"=
>
xxxx<br />
+1-801-980-4240
</td>
<td valign=3D"middle" align=3D"right" style=
=3D"color: #fff; padding-top: 10px; padding-bottom: 10px; font-size: 12px;"=
>
<a href=3D"http://erp.xxxx.xxxx/info@xxxx-a=
aa.com" style=3D"text-decoration:none; color: white;">info@aust-mfg.com</a>=
<br />
<a href=3D"http://www.xxxx=
.com" style=3D"text-decoration:none; color: white;">
http://www.xxxx.com
</a>
</td>
</tr>
</tbody></table>
</td>
</tr>
<tr>
<td align=3D"center">
Powered by <a href=3D"https://www.odoo.com">Odo=
o</a>.
</td>
</tr>
</tbody>
</table>
=20
<pre style=3D"white-space: pre-wrap">xxxx.
</pre>
</blockquote></div>
</body></html>
--------=_MB48E455BD-2850-42EC-B1CA-886CDF48905E--"""
MAIL_BOUNCE = """Return-Path: <>
X-Original-To: {to}
Delivered-To: {to}
Received: by mail2.test.ironsky (Postfix)
id 93A83A5F0D; Mon, 15 Apr 2019 15:41:06 +0200 (CEST)
Date: Mon, 15 Apr 2019 15:41:06 +0200 (CEST)
From: MAILER-DAEMON@mail2.test.ironsky (Mail Delivery System)
Subject: {subject}
To: {to}
Auto-Submitted: auto-replied
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="92726A5F09.1555335666/mail2.test.ironsky"
Message-Id: <20190415134106.93A83A5F0D@mail2.test.ironsky>
This is a MIME-encapsulated message.
--92726A5F09.1555335666/mail2.test.ironsky
Content-Description: Notification
Content-Type: text/plain; charset=us-ascii
This is the mail system at host mail2.test.ironsky.
I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.
For further assistance, please send mail to postmaster.
If you do so, please include this problem report. You can
delete your own text from the attached returned message.
The mail system
<{email_from}>: host tribulant.com[23.22.38.89] said: 550 No such
person at this address. (in reply to RCPT TO command)
--92726A5F09.1555335666/mail2.test.ironsky
Content-Description: Delivery report
Content-Type: message/delivery-status
Reporting-MTA: dns; mail2.test.ironsky
X-Postfix-Queue-ID: 92726A5F09
X-Postfix-Sender: rfc822; {to}
Arrival-Date: Mon, 15 Apr 2019 15:40:24 +0200 (CEST)
Final-Recipient: rfc822; {email_from}
Original-Recipient: rfc822;{email_from}
Action: failed
Status: 5.0.0
Remote-MTA: dns; tribulant.com
Diagnostic-Code: smtp; 550 No such person at this address.
--92726A5F09.1555335666/mail2.test.ironsky
Content-Description: Undelivered Message
Content-Type: message/rfc822
Return-Path: <{to}>
Received: from [127.0.0.1] (host-212-68-194-133.dynamic.voo.be [212.68.194.133])
(Authenticated sender: aaa)
by mail2.test.ironsky (Postfix) with ESMTPSA id 92726A5F09
for <{email_from}>; Mon, 15 Apr 2019 15:40:24 +0200 (CEST)
DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=test.ironsky; s=mail;
t=1555335624; bh=x6cSjphxNDiRDMmm24lMAUKtdCFfftM8w/fdUyfoeFs=;
h=references:Subject:From:Reply-To:To:Date:From;
b=Bo0BsXAHgKiBfBtMvvO/+KaS9PuuS0+AozL4SxU05jHZcJFc7qFIPEpqkJIdbzNcQ
wq0PJYclgX7QZDOMm3VHQwcwOxBDXAbdnpfkPM9/wa+FWKfr6ikowMTHHT3CA1qNbe
h+BQVyBKIvr/LDFPSN2hQmfXWwWupm1lgUhJ07T4=
Content-Type: multipart/mixed; boundary="===============7355787381227985247=="
MIME-Version: 1.0
Message-Id: {extra}
references: <670034078674109.1555335454.587288856506348-openerp-32-project.task@aaa>
Subject: Re: Test
From: Mitchell Admin <admin@yourcompany.example.com>
Reply-To: YourCompany Research & Development <aaa+catchall@test.ironsky>
To: Raoul <{email_from}>
Date: Mon, 15 Apr 2019 13:40:24 -0000
X-Odoo-Objects: project.project-3, ,project.task-32
X-Spam-Status: No, score=-2.0 required=5.0 tests=ALL_TRUSTED,BAYES_00,
DKIM_ADSP_NXDOMAIN,HEADER_FROM_DIFFERENT_DOMAINS,HTML_MESSAGE
shortcircuit=no autolearn=no autolearn_force=no version=3.4.2
X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on mail2.test.ironsky
--===============7355787381227985247==
Content-Type: multipart/alternative; boundary="===============8588563873240298690=="
MIME-Version: 1.0
--===============8588563873240298690==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
CgpaYm91bGl1b2l1b2l6ZWYKCi0tCkFkbWluaXN0cmF0b3IKU2VudApieQpbMV0gWW91ckNvbXBh
bnkKCnVzaW5nCk9kb28gWzJdIC4KCgoKWzFdIGh0dHA6Ly93d3cuZXhhbXBsZS5jb20KWzJdIGh0
dHBzOi8vd3d3Lm9kb28uY29tP3V0bV9zb3VyY2U9ZGImdXRtX21lZGl1bT1lbWFpbAo=
--===============8588563873240298690==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
CjxkaXY+CgoKPGRpdj48cD5aYm91bGl1b2l1b2l6ZWY8L3A+PC9kaXY+Cgo8ZGl2IGNsYXNzPSJm
b250LXNpemU6IDEzcHg7Ij48c3BhbiBkYXRhLW8tbWFpbC1xdW90ZT0iMSI+LS0gPGJyIGRhdGEt
by1tYWlsLXF1b3RlPSIxIj4KQWRtaW5pc3RyYXRvcjwvc3Bhbj48L2Rpdj4KPHAgc3R5bGU9ImNv
bG9yOiAjNTU1NTU1OyBtYXJnaW4tdG9wOjMycHg7Ij4KICAgIFNlbnQKICAgIDxzcGFuPgogICAg
YnkKICAgIDxhIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246bm9uZTsgY29sb3I6ICM4NzVBN0I7IiBo
cmVmPSJodHRwOi8vd3d3LmV4YW1wbGUuY29tIj4KICAgICAgICA8c3Bhbj5Zb3VyQ29tcGFueTwv
c3Bhbj4KICAgIDwvYT4KICAgIAogICAgPC9zcGFuPgogICAgdXNpbmcKICAgIDxhIHRhcmdldD0i
X2JsYW5rIiBocmVmPSJodHRwczovL3d3dy5vZG9vLmNvbT91dG1fc291cmNlPWRiJmFtcDt1dG1f
bWVkaXVtPWVtYWlsIiBzdHlsZT0idGV4dC1kZWNvcmF0aW9uOm5vbmU7IGNvbG9yOiAjODc1QTdC
OyI+T2RvbzwvYT4uCjwvcD4KPC9kaXY+CiAgICAgICAg
--===============8588563873240298690==--
--===============7355787381227985247==--
--92726A5F09.1555335666/mail2.test.ironsky--
"""
MAIL_BOUNCE_QP_RFC822_HEADERS = """\
Received: by mailserver.odoo.com (Postfix)
id EA0B917B8E4; Tue, 29 Feb 2023 11:11:11 +0100 (CET)
From: {email_from}
Subject: Undelivered Mail Returned to Sender
To: {email_to}
Auto-Submitted: auto-replied
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="DFFDC17AA03.1673346179/mailserver.odoo.com"
Message-Id: <40230110102259.EA0B917B8E4@mailserver.odoo.com>
Content-Transfer-Encoding: 7bit
Delivered-To: {delivered_to}
Return-Path: <>
--DFFDC17AA03.1673346179/mailserver.odoo.com
Content-Description: Notification
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
I'm sorry to have to inform you that your message could not
be delivered to one or more recipients.
<rdesfrdgtfdrfesd@outlook.com>: host
outlook-com.olc.protection.outlook.com[104.47.56.33] said: 550 5.5.0
Requested action not taken: mailbox unavailable (S2017062302). (in re=
ply to
RCPT TO command)
--DFFDC17AA03.1673346179/mailserver.odoo.com
Content-Description: Delivery report
Content-Type: message/delivery-status
Reporting-MTA: dns; mailserver.odoo.com
X-Postfix-Queue-ID: DFFDC17AA03
X-Postfix-Sender: rfc822; bounce@xxx.odoo.com
Arrival-Date: Tue, 29 Feb 2023 10:10:10 +0100 (CET)
Final-Recipient: rfc822; rdesfrdgtfdrfesd@outlook.com
Original-Recipient: rfc822;rdesfrdgtfdrfesd@outlook.com
Action: failed
Status: 5.5.0
Remote-MTA: dns; outlook-com.olc.protection.outlook.com
Diagnostic-Code: smtp; 550 5.5.0 Requested action not taken: mailbox
unavailable (S2017062302).
--DFFDC17AA03.1673346179/mailserver.odoo.com
Content-Description: Undelivered Message Headers
Content-Type: text/rfc822-headers
Content-Transfer-Encoding: quoted-printable
Return-Path: <bounce@xxx.odoo.com>
Received: from eupp00.odoo.com (00.72.79.34.bc.googleusercontent.com [34.=
79.72.00])
by mailserver.odoo.com (Postfix) with ESMTPS id DFFDC17AA03;
Tue, 10 Jan 2023 11:22:57 +0100 (CET)
DKIM-Signature: v=3D1; a=3Drsa-sha256; c=3Dsimple/simple; d=3Dxxx.be;
s=3Dodoo; t=3D1673346178;
bh=3DYPJOqkUi8B28X1MrRUsgmsL8KRz/ZIkpbYyc6wNITXA=3D;
h=3Dreferences:Subject:From:Reply-To:To:Date:From;
b=3DCMqh7mUvpgUw+JpCeGluv1+MZ3y6EsXd0acmsfzpYBjcoy1InvD6FLT1/lQCcgetf
cGyL/8R4vvDKATyE0AtOIpoYDsbpnMoiYWqaSXnDVuLTrEZzyrK/2j10ZTnHZ2uDTC
b7wPjFfQ9pted/t6CAUhVT1XydDNalSwEZovy/QI=3D
Message-Id: <368396033905967.1673346177.695352554321289-openerp-11-sale.o=
rder@eupp00>
references: <792105153140463.1673746527.352018594741821-openerp-11-sale.o=
rder@xxx.odoo.com> <368396033905967.1673346177.695352554321289-openerp-11=
-sale.order@eupp00>
Subject: Thi is a SO (Ref SO/11)
From: info@xxx.odoo.com
Reply-To: "SO/11" <catchall@xxx.odoo.com=
>
To: "rdesfrdgtfdrfesd@outlook.com" <rdesfrdgtfdrfesd@outlook.com>
Date: Tue, 29 Feb 2023 06:09:06 -0000
X-Odoo-Objects: sale.order-11
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=3D"=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D5706316606908750110=3D=3D"
--DFFDC17AA03.1673346179/mailserver.odoo.com--
"""
MAIL_NO_BODY = '''\
Return-Path: <{email_from}>
Delivered-To: catchall@xxxx.xxxx
Received: from in66.mail.ovh.net (unknown [10.101.4.66])
by vr38.mail.ovh.net (Postfix) with ESMTP id 4GLCGr70Kyz1myr75
for <catchall@xxxx.xxxx>; Thu, 8 Jul 2021 10:30:12 +0000 (UTC)
X-Comment: SPF check N/A for local connections - client-ip=213.186.33.59; helo=mail663.ha.ovh.net; envelope-from={email_from}; receiver=catchall@xxxx.xxxx
Authentication-Results: in66.mail.ovh.net; dkim=none; dkim-atps=neutral
Delivered-To: xxxx.xxxx-{email_to}
X-ME-Helo: opme11oxm23aub.bagnolet.francetelecom.fr
X-ME-Auth: ZnJlZGVyaWMuYmxhY2hvbjA3QG9yYW5nZS5mcg==
X-ME-Date: Thu, 08 Jul 2021 12:30:11 +0200
X-ME-IP: 86.221.151.111
Date: Thu, 8 Jul 2021 12:30:11 +0200 (CEST)
From: =?UTF-8?Q?Fr=C3=A9d=C3=A9ric_BLACHON?= <{email_from}>
Reply-To:
=?UTF-8?Q?Fr=C3=A9d=C3=A9ric_BLACHON?= <{email_from}>
To: {email_to}
Message-ID: <1024471522.82574.1625740211606.JavaMail.open-xchange@opme11oxm23aub.bagnolet.francetelecom.fr>
Subject: transport autorisation 19T
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_82573_178179506.1625740211587"
------=_Part_82573_178179506.1625740211587
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head><body style="font-family: arial,helvetica,sans-serif; font-size: 13pt"></body></html>
'''
MAIL_NO_FINAL_RECIPIENT = """\
Return-Path: <bounce-md_9656353.6125275c.v1-f28f7746389e45f0bfbf9faefe9e0dc8@mandrillapp.com>
Delivered-To: catchall@xxxx.xxxx
Received: from in58.mail.ovh.net (unknown [10.101.4.58])
by vr46.mail.ovh.net (Postfix) with ESMTP id 4GvFsq2QLYz1t0N7r
for <catchall@xxxx.xxxx>; Tue, 24 Aug 2021 17:07:43 +0000 (UTC)
Received-SPF: Softfail (mailfrom) identity=mailfrom; client-ip=46.105.72.169; helo=40.mo36.mail-out.ovh.net; envelope-from=bounce-md_9656353.6125275c.v1-f28f7746389e45f0bfbf9faefe9e0dc8@mandrillapp.com; receiver=catchall@xxxx.xxxx
Authentication-Results: in58.mail.ovh.net;
dkim=pass (1024-bit key; unprotected) header.d=mandrillapp.com header.i=bounces-noreply@mandrillapp.com header.b="TDzUcdJs";
dkim=pass (1024-bit key) header.d=mandrillapp.com header.i=@mandrillapp.com header.b="MyjddTY5";
dkim-atps=neutral
Delivered-To: xxxx.xxxx-{email_to}
Authentication-Results: in62.mail.ovh.net;
dkim=pass (1024-bit key; unprotected) header.d=mandrillapp.com header.i=bounces-noreply@mandrillapp.com header.b="TDzUcdJs";
dkim=pass (1024-bit key) header.d=mandrillapp.com header.i=@mandrillapp.com header.b="MyjddTY5";
dkim-atps=neutral
From: MAILER-DAEMON <bounces-noreply@mandrillapp.com>
Subject: Undelivered Mail Returned to Sender
To: {email_to}
X-Report-Abuse: Please forward a copy of this message, including all headers, to abuse@mandrill.com
X-Report-Abuse: You can also report abuse here: http://mandrillapp.com/contact/abuse?id=9656353.f28f7746389e45f0bfbf9faefe9e0dc8
X-Mandrill-User: md_9656353
Feedback-ID: 9656353:9656353.20210824:md
Message-Id: <9656353.20210824170740.6125275cf21879.17950539@mail9.us4.mandrillapp.com>
Date: Tue, 24 Aug 2021 17:07:40 +0000
MIME-Version: 1.0
Content-Type: multipart/report; boundary="_av-UfLe6y6qxNo54-urtAxbJQ"
--_av-UfLe6y6qxNo54-urtAxbJQ
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
--- The following addresses had delivery problems ---
<{email_from}> (5.7.1 <{email_from}>: Recipient address rejected: Access denied)
--_av-UfLe6y6qxNo54-urtAxbJQ
Content-Type: message/delivery-status
Content-Transfer-Encoding: 7bit
Original-Recipient: <{email_from}>
Action: failed
Diagnostic-Code: smtp; 554 5.7.1 <{email_from}>: Recipient address rejected: Access denied
Remote-MTA: 10.245.192.40
--_av-UfLe6y6qxNo54-urtAxbJQ--"""
MAIL_FORWARDED = """X-Original-To: lucie@petitebedaine.fr
Delivered-To: raoul@grosbedon.fr
Delivered-To: lucie@petitebedaine.fr
To: lucie@petitebedaine.fr
From: "Bruce Wayne" <bruce@wayneenterprises.com>
SSBhbSB0aGUgQmF0TWFuCg=="""
| 38.974684
| 49,264
|
296
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Germany - Purchase',
'category': 'Accounting/Localizations',
'depends': [
'l10n_de',
'purchase',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 22.769231
| 296
|
2,235
|
py
|
PYTHON
|
15.0
|
from odoo import models, fields, _
from odoo.tools import format_date
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data')
l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title')
l10n_de_addresses = fields.Binary(compute='_compute_l10n_de_addresses')
def _compute_l10n_de_template_data(self):
for record in self:
record.l10n_de_template_data = data = []
if record.state == 'draft':
data.append((_("Request for Quotation No."), record.name))
elif record.state in ['sent', 'to approve', 'purchase', 'done']:
data.append((_("Purchase Order No."), record.name))
elif record.state == 'cancel':
data.append((_("Cancelled Purchase Order No."), record.name))
if record.user_id:
data.append((_("Purchase Representative"), record.user_id.name))
if record.partner_ref:
data.append((_("Order Reference"), record.partner_ref))
if record.date_order:
data.append((_("Order Date"), format_date(self.env, record.date_order)))
if record.incoterm_id:
data.append((_("Incoterm"), record.incoterm_id.code))
def _compute_l10n_de_document_title(self):
for record in self:
if record.state in ['draft', 'sent', 'to approve']:
record.l10n_de_document_title = _("Request for Quotation")
elif record.state in ['purchase', 'done']:
record.l10n_de_document_title = _("Purchase Order")
elif record.state == 'cancel':
record.l10n_de_document_title = _("Cancelled Purchase Order")
def _compute_l10n_de_addresses(self):
for record in self:
record.l10n_de_addresses = data = []
if record.dest_address_id:
data.append((_("Shipping Address:"), record.dest_address_id))
elif 'picking_type_id' in record._fields and record.picking_type_id.warehouse_id:
data.append((_("Shipping Address:"), record.picking_type_id.warehouse_id.partner_id))
| 46.5625
| 2,235
|
1,651
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "Import/Export electronic invoices with UBL/CII",
'version': '1.0',
'category': 'Accounting/Accounting',
'description': """
Electronic invoicing module
===========================
Allows to export and import formats: E-FFF, UBL Bis 3, EHF3, NLCIUS, Factur-X (CII), XRechnung (UBL).
When generating the PDF on the invoice, the PDF will be embedded inside the xml for all UBL formats. This allows the
receiver to retrieve the PDF with only the xml file. Note that **EHF3 is fully implemented by UBL Bis 3** (`reference
<https://anskaffelser.dev/postaward/g3/spec/current/billing-3.0/norway/#_implementation>`_).
The formats can be chosen from the journal (Journal > Advanced Settings) linked to the invoice.
Note that E-FFF, NLCIUS and XRechnung (UBL) are only available for Belgian, Dutch and German companies,
respectively. UBL Bis 3 is only available for companies which country is present in the `EAS list
<https://docs.peppol.eu/poacc/billing/3.0/codelist/eas/>`_.
Note also that you need to activate PDF A in order to be able to submit a Factur-X pdf on Chorus Pro:
go to Settings > Technical (debug mode) > System Parameters > select/create one with Key: edi.use_pdfa, Value: true.
With this setting, Chorus Pro will automatically detect the "PDF/A-3 (Factur-X)" format.
""",
'depends': ['account_edi'],
'data': [
'data/account_edi_data.xml',
'data/cii_22_templates.xml',
'data/ubl_20_templates.xml',
'data/ubl_21_templates.xml',
],
'installable': True,
'application': False,
'auto_install': False,
'license': 'LGPL-3',
}
| 45.861111
| 1,651
|
22,310
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, _
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, float_repr, is_html_empty, html2plaintext, cleanup_xml_node
from lxml import etree
from datetime import datetime
import logging
_logger = logging.getLogger(__name__)
DEFAULT_FACTURX_DATE_FORMAT = '%Y%m%d'
class AccountEdiXmlCII(models.AbstractModel):
_name = "account.edi.xml.cii"
_inherit = 'account.edi.common'
_description = "Factur-x/XRechnung CII 2.2.0"
def _export_invoice_filename(self, invoice):
return "factur-x.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'de.xrechnung:cii:2.2.0',
'credit_note': 'de.xrechnung:cii:2.2.0',
}
def _export_invoice_constraints(self, invoice, vals):
constraints = self._invoice_constraints_common(invoice)
constraints.update({
# [BR-08]-An Invoice shall contain the Seller postal address (BG-5).
# [BR-09]-The Seller postal address (BG-5) shall contain a Seller country code (BT-40).
'seller_postal_address': self._check_required_fields(
vals['record']['company_id']['partner_id']['commercial_partner_id'], 'country_id'
),
# [BR-DE-9] The element "Buyer post code" (BT-53) must be transmitted. (only mandatory in Germany ?)
'buyer_postal_address': self._check_required_fields(
vals['record']['commercial_partner_id'], 'zip'
),
# [BR-DE-4] The element "Seller post code" (BT-38) must be transmitted. (only mandatory in Germany ?)
'seller_post_code': self._check_required_fields(
vals['record']['company_id']['partner_id']['commercial_partner_id'], 'zip'
),
# [BR-CO-26]-In order for the buyer to automatically identify a supplier, the Seller identifier (BT-29),
# the Seller legal registration identifier (BT-30) and/or the Seller VAT identifier (BT-31) shall be present.
'seller_identifier': self._check_required_fields(
vals['record']['company_id'], ['vat'] # 'siret'
),
# [BR-DE-1] An Invoice must contain information on "PAYMENT INSTRUCTIONS" (BG-16)
# first check that a partner_bank_id exists, then check that there is an account number
'seller_payment_instructions_1': self._check_required_fields(
vals['record'], 'partner_bank_id'
),
'seller_payment_instructions_2': self._check_required_fields(
vals['record']['partner_bank_id'], 'sanitized_acc_number',
_("The field 'Sanitized Account Number' is required on the Recipient Bank.")
),
# [BR-DE-6] The element "Seller contact telephone number" (BT-42) must be transmitted.
'seller_phone': self._check_required_fields(
vals['record']['company_id']['partner_id']['commercial_partner_id'], ['phone', 'mobile'],
),
# [BR-DE-7] The element "Seller contact email address" (BT-43) must be transmitted.
'seller_email': self._check_required_fields(
vals['record']['company_id'], 'email'
),
# [BR-CO-04]-Each Invoice line (BG-25) shall be categorized with an Invoiced item VAT category code (BT-151).
'tax_invoice_line': self._check_required_tax(vals),
# [BR-IC-02]-An Invoice that contains an Invoice line (BG-25) where the Invoiced item VAT category code (BT-151)
# is "Intra-community supply" shall contain the Seller VAT Identifier (BT-31) or the Seller tax representative
# VAT identifier (BT-63) and the Buyer VAT identifier (BT-48).
'intracom_seller_vat': self._check_required_fields(vals['record']['company_id'], 'vat') if vals['intracom_delivery'] else None,
'intracom_buyer_vat': self._check_required_fields(vals['record']['commercial_partner_id'], 'vat') if vals['intracom_delivery'] else None,
# [BR-IG-05]-In an Invoice line (BG-25) where the Invoiced item VAT category code (BT-151) is "IGIC" the
# invoiced item VAT rate (BT-152) shall be greater than 0 (zero).
'igic_tax_rate': self._check_non_0_rate_tax(vals)
if vals['record']['commercial_partner_id']['country_id']['code'] == 'ES'
and vals['record']['commercial_partner_id']['zip']
and vals['record']['commercial_partner_id']['zip'][:2] in ['35', '38'] else None,
})
return constraints
def _check_required_tax(self, vals):
for line_vals in vals['invoice_line_vals_list']:
line = line_vals['line']
if not vals['tax_details']['invoice_line_tax_details'][line]['tax_details']:
return _("You should include at least one tax per invoice line. [BR-CO-04]-Each Invoice line (BG-25) "
"shall be categorized with an Invoiced item VAT category code (BT-151).")
def _check_non_0_rate_tax(self, vals):
for line_vals in vals['invoice_line_vals_list']:
tax_rate_list = line_vals['line'].tax_ids.flatten_taxes_hierarchy().mapped("amount")
if not any([rate > 0 for rate in tax_rate_list]):
return _("When the Canary Island General Indirect Tax (IGIC) applies, the tax rate on "
"each invoice line should be greater than 0.")
def _get_scheduled_delivery_time(self, invoice):
# don't create a bridge only to get line.sale_line_ids.order_id.picking_ids.date_done
# line.sale_line_ids.order_id.picking_ids.scheduled_date or line.sale_line_ids.order_id.commitment_date
return invoice.invoice_date
def _get_invoicing_period(self, invoice):
# get the Invoicing period (BG-14): a list of dates covered by the invoice
# don't create a bridge to get the date range from the timesheet_ids
return [invoice.invoice_date]
def _get_exchanged_document_vals(self, invoice):
return {
'id': invoice.name,
'type_code': '380' if invoice.move_type == 'out_invoice' else '381',
'issue_date_time': invoice.invoice_date,
'included_note': html2plaintext(invoice.narration) if invoice.narration else "",
}
def _export_invoice_vals(self, invoice):
def format_date(dt):
# Format the date in the Factur-x standard.
dt = dt or datetime.now()
return dt.strftime(DEFAULT_FACTURX_DATE_FORMAT)
def format_monetary(number, decimal_places=2):
# Facturx requires the monetary values to be rounded to 2 decimal values
return float_repr(number, decimal_places)
def grouping_key_generator(tax_values):
tax = tax_values['tax_id']
grouping_key = {
**self._get_tax_unece_codes(invoice, tax),
'amount': tax.amount,
'amount_type': tax.amount_type,
}
# If the tax is fixed, we want to have one group per tax
# s.t. when the invoice is imported, we can try to guess the fixed taxes
if tax.amount_type == 'fixed':
grouping_key['tax_name'] = tax.name
return grouping_key
# Validate the structure of the taxes
self._validate_taxes(invoice)
# Create file content.
tax_details = invoice._prepare_edi_tax_details(grouping_key_generator=grouping_key_generator)
# Fixed Taxes: filter them on the document level, and adapt the totals
# Fixed taxes are not supposed to be taxes in real live. However, this is the way in Odoo to manage recupel
# taxes in Belgium. Since only one tax is allowed, the fixed tax is removed from totals of lines but added
# as an extra charge/allowance.
fixed_taxes_keys = [k for k in tax_details['tax_details'] if k['amount_type'] == 'fixed']
for key in fixed_taxes_keys:
fixed_tax_details = tax_details['tax_details'].pop(key)
tax_details['tax_amount_currency'] -= fixed_tax_details['tax_amount_currency']
tax_details['tax_amount'] -= fixed_tax_details['tax_amount']
tax_details['base_amount_currency'] += fixed_tax_details['tax_amount_currency']
tax_details['base_amount'] += fixed_tax_details['tax_amount']
if 'siret' in invoice.company_id._fields and invoice.company_id.siret:
seller_siret = invoice.company_id.siret
else:
seller_siret = invoice.company_id.company_registry
buyer_siret = False
if 'siret' in invoice.commercial_partner_id._fields and invoice.commercial_partner_id.siret:
buyer_siret = invoice.commercial_partner_id.siret
template_values = {
**invoice._prepare_edi_vals_to_export(),
'tax_details': tax_details,
'format_date': format_date,
'format_monetary': format_monetary,
'is_html_empty': is_html_empty,
'scheduled_delivery_time': self._get_scheduled_delivery_time(invoice),
'intracom_delivery': False,
'ExchangedDocument_vals': self._get_exchanged_document_vals(invoice),
'seller_specified_legal_organization': seller_siret,
'buyer_specified_legal_organization': buyer_siret,
'ship_to_trade_party': invoice.partner_shipping_id if 'partner_shipping_id' in invoice._fields and invoice.partner_shipping_id
else invoice.commercial_partner_id,
# Chorus Pro fields
'buyer_reference': invoice.buyer_reference if 'buyer_reference' in invoice._fields
and invoice.buyer_reference else invoice.commercial_partner_id.ref,
'purchase_order_reference': invoice.purchase_order_reference if 'purchase_order_reference' in invoice._fields
and invoice.purchase_order_reference else invoice.ref or invoice.name,
'contract_reference': invoice.contract_reference if 'contract_reference' in invoice._fields
and invoice.contract_reference else '',
}
# data used for IncludedSupplyChainTradeLineItem / SpecifiedLineTradeSettlement
for line_vals in template_values['invoice_line_vals_list']:
line = line_vals['line']
line_vals['unece_uom_code'] = self._get_uom_unece_code(line)
# data used for ApplicableHeaderTradeSettlement / ApplicableTradeTax (at the end of the xml)
for tax_detail_vals in template_values['tax_details']['tax_details'].values():
# /!\ -0.0 == 0.0 in python but not in XSLT, so it can raise a fatal error when validating the XML
# if 0.0 is expected and -0.0 is given.
amount_currency = tax_detail_vals['tax_amount_currency']
tax_detail_vals['calculated_amount'] = template_values['balance_multiplicator'] * amount_currency \
if not invoice.currency_id.is_zero(amount_currency) else 0
if tax_detail_vals.get('tax_category_code') == 'K':
template_values['intracom_delivery'] = True
# [BR - IC - 11] - In an Invoice with a VAT breakdown (BG-23) where the VAT category code (BT-118) is
# "Intra-community supply" the Actual delivery date (BT-72) or the Invoicing period (BG-14) shall not be blank.
if tax_detail_vals.get('tax_category_code') == 'K' and not template_values['scheduled_delivery_time']:
date_range = self._get_invoicing_period(invoice)
template_values['billing_start'] = min(date_range)
template_values['billing_end'] = max(date_range)
# One of the difference between XRechnung and Facturx is the following. Submitting a Facturx to XRechnung
# validator raises a warning, but submitting a XRechnung to Facturx raises an error.
supplier = invoice.company_id.partner_id.commercial_partner_id
if supplier.country_id.code == 'DE':
template_values['document_context_id'] = "urn:cen.eu:en16931:2017#compliant#urn:xoev-de:kosit:standard:xrechnung_2.2"
else:
template_values['document_context_id'] = "urn:cen.eu:en16931:2017#conformant#urn:factur-x.eu:1p0:extended"
# Fixed taxes: add them as charges on the invoice lines
balance_sign = -1 if invoice.is_inbound() else 1
for line_vals in template_values['invoice_line_vals_list']:
line_vals['allowance_charge_vals_list'] = []
for grouping_key, tax_detail in tax_details['invoice_line_tax_details'][line_vals['line']]['tax_details'].items():
if grouping_key['amount_type'] == 'fixed':
line_vals['allowance_charge_vals_list'].append({
'indicator': 'true',
'reason': tax_detail['group_tax_details'][0]['tax_id'].name,
'reason_code': 'AEO',
'amount': balance_sign * tax_detail['tax_amount_currency'],
})
sum_fixed_taxes = sum(x['amount'] for x in line_vals['allowance_charge_vals_list'])
line_vals['line_total_amount'] = line_vals['line'].price_subtotal + sum_fixed_taxes
# Fixed taxes: set the total adjusted amounts on the document level
template_values['tax_basis_total_amount'] = balance_sign * tax_details['base_amount_currency']
template_values['tax_total_amount'] = balance_sign * tax_details['tax_amount_currency']
return template_values
def _export_invoice(self, invoice):
vals = self._export_invoice_vals(invoice)
errors = [constraint for constraint in self._export_invoice_constraints(invoice, vals).values() if constraint]
xml_content = self.env['ir.qweb']._render('account_edi_ubl_cii.account_invoice_facturx_export_22', vals)
return etree.tostring(cleanup_xml_node(xml_content), xml_declaration=True, encoding='UTF-8'), set(errors)
# -------------------------------------------------------------------------
# IMPORT
# -------------------------------------------------------------------------
def _import_fill_invoice_form(self, journal, tree, invoice_form, qty_factor):
def _find_value(xpath, element=tree):
return self.env['account.edi.format']._find_value(xpath, element, tree.nsmap)
logs = []
if qty_factor == -1:
logs.append(_("The invoice has been converted into a credit note and the quantities have been reverted."))
# ==== partner_id ====
role = invoice_form.journal_id.type == 'purchase' and 'SellerTradeParty' or 'BuyerTradeParty'
name = _find_value(f"//ram:{role}/ram:Name")
mail = _find_value(f"//ram:{role}//ram:URIID[@schemeID='SMTP']")
vat = _find_value(f"//ram:{role}/ram:SpecifiedTaxRegistration/ram:ID")
phone = _find_value(f"//ram:{role}/ram:DefinedTradeContact/ram:TelephoneUniversalCommunication/ram:CompleteNumber")
self._import_retrieve_and_fill_partner(invoice_form, name=name, phone=phone, mail=mail, vat=vat)
# ==== currency_id ====
currency_code_node = tree.find('.//{*}InvoiceCurrencyCode')
if currency_code_node is not None:
currency = self.env['res.currency'].with_context(active_test=False).search([
('name', '=', currency_code_node.text),
], limit=1)
if currency:
if not currency.active:
logs.append(_("The currency '%s' is not active.", currency.name))
invoice_form.currency_id = currency
else:
logs.append(_("Could not retrieve currency: %s. Did you enable the multicurrency option and "
"activate the currency ?", currency_code_node.text))
# ==== Reference ====
ref_node = tree.find('./{*}ExchangedDocument/{*}ID')
if ref_node is not None:
invoice_form.ref = ref_node.text
# === Note/narration ====
narration = ""
note_node = tree.find('./{*}ExchangedDocument/{*}IncludedNote/{*}Content')
if note_node is not None and note_node.text:
narration += note_node.text + "\n"
payment_terms_node = tree.find('.//{*}SpecifiedTradePaymentTerms/{*}Description')
if payment_terms_node is not None and payment_terms_node.text:
narration += payment_terms_node.text + "\n"
invoice_form.narration = narration
# ==== payment_reference ====
payment_reference_node = tree.find('.//{*}BuyerOrderReferencedDocument/{*}IssuerAssignedID')
if payment_reference_node is not None:
invoice_form.payment_reference = payment_reference_node.text
# ==== invoice_date ====
invoice_date_node = tree.find('./{*}ExchangedDocument/{*}IssueDateTime/{*}DateTimeString')
if invoice_date_node is not None and invoice_date_node.text:
date_str = invoice_date_node.text
date_obj = datetime.strptime(date_str, DEFAULT_FACTURX_DATE_FORMAT)
invoice_form.invoice_date = date_obj.strftime(DEFAULT_SERVER_DATE_FORMAT)
# ==== invoice_date_due ====
invoice_date_due_node = tree.find('.//{*}SpecifiedTradePaymentTerms/{*}DueDateDateTime/{*}DateTimeString')
if invoice_date_due_node is not None and invoice_date_due_node.text:
date_str = invoice_date_due_node.text
date_obj = datetime.strptime(date_str, DEFAULT_FACTURX_DATE_FORMAT)
invoice_form.invoice_date_due = date_obj.strftime(DEFAULT_SERVER_DATE_FORMAT)
# ==== invoice_line_ids: AllowanceCharge (document level) ====
logs += self._import_fill_invoice_allowance_charge(tree, invoice_form, journal, qty_factor)
# ==== Prepaid amount ====
prepaid_node = tree.find('.//{*}ApplicableHeaderTradeSettlement/'
'{*}SpecifiedTradeSettlementHeaderMonetarySummation/{*}TotalPrepaidAmount')
logs += self._import_log_prepaid_amount(invoice_form, prepaid_node, qty_factor)
# ==== invoice_line_ids ====
line_nodes = tree.findall('./{*}SupplyChainTradeTransaction/{*}IncludedSupplyChainTradeLineItem')
if line_nodes is not None:
for i, invl_el in enumerate(line_nodes):
with invoice_form.invoice_line_ids.new() as invoice_line_form:
invoice_line_form.sequence = i
invl_logs = self._import_fill_invoice_line_form(journal, invl_el, invoice_form, invoice_line_form, qty_factor)
logs += invl_logs
return invoice_form, logs
def _import_fill_invoice_line_form(self, journal, tree, invoice_form, invoice_line_form, qty_factor):
logs = []
def _find_value(xpath, element=tree):
return self.env['account.edi.format']._find_value(xpath, element, tree.nsmap)
# Product.
name = _find_value('.//ram:SpecifiedTradeProduct/ram:Name', tree)
invoice_line_form.product_id = self.env['account.edi.format']._retrieve_product(
default_code=_find_value('.//ram:SpecifiedTradeProduct/ram:SellerAssignedID', tree),
name=_find_value('.//ram:SpecifiedTradeProduct/ram:Name', tree),
barcode=_find_value('.//ram:SpecifiedTradeProduct/ram:GlobalID', tree)
)
# force original line description instead of the one copied from product's Sales Description
if name:
invoice_line_form.name = name
xpath_dict = {
'basis_qty': [
'./{*}SpecifiedLineTradeAgreement/{*}GrossPriceProductTradePrice/{*}BasisQuantity',
'./{*}SpecifiedLineTradeAgreement/{*}NetPriceProductTradePrice/{*}BasisQuantity'
],
'gross_price_unit': './{*}SpecifiedLineTradeAgreement/{*}GrossPriceProductTradePrice/{*}ChargeAmount',
'rebate': './{*}SpecifiedLineTradeAgreement/{*}GrossPriceProductTradePrice/{*}AppliedTradeAllowanceCharge/{*}ActualAmount',
'net_price_unit': './{*}SpecifiedLineTradeAgreement/{*}NetPriceProductTradePrice/{*}ChargeAmount',
'billed_qty': './{*}SpecifiedLineTradeDelivery/{*}BilledQuantity',
'allowance_charge': './/{*}SpecifiedLineTradeSettlement/{*}SpecifiedTradeAllowanceCharge',
'allowance_charge_indicator': './{*}ChargeIndicator/{*}Indicator',
'allowance_charge_amount': './{*}ActualAmount',
'allowance_charge_reason': './{*}Reason',
'allowance_charge_reason_code': './{*}ReasonCode',
'line_total_amount': './{*}SpecifiedLineTradeSettlement/{*}SpecifiedTradeSettlementLineMonetarySummation/{*}LineTotalAmount',
}
inv_line_vals = self._import_fill_invoice_line_values(tree, xpath_dict, invoice_line_form, qty_factor)
# retrieve tax nodes
tax_nodes = tree.findall('.//{*}ApplicableTradeTax/{*}RateApplicablePercent')
return self._import_fill_invoice_line_taxes(journal, tax_nodes, invoice_line_form, inv_line_vals, logs)
# -------------------------------------------------------------------------
# IMPORT : helpers
# -------------------------------------------------------------------------
def _get_import_document_amount_sign(self, filename, tree):
"""
In factur-x, an invoice has code 380 and a credit note has code 381. However, a credit note can be expressed
as an invoice with negative amounts. For this case, we need a factor to take the opposite of each quantity
in the invoice.
"""
move_type_code = tree.find('.//{*}ExchangedDocument/{*}TypeCode')
if move_type_code is None:
return None, None
if move_type_code.text == '381':
return ('in_refund', 'out_refund'), 1
if move_type_code.text == '380':
amount_node = tree.find('.//{*}SpecifiedTradeSettlementHeaderMonetarySummation/{*}TaxBasisTotalAmount')
if amount_node is not None and float(amount_node.text) < 0:
return ('in_refund', 'out_refund'), -1
return ('in_invoice', 'out_invoice'), 1
| 55.63591
| 22,310
|
9,405
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, SUPERUSER_ID
from odoo.tools import str2bool
from odoo.addons.account_edi_ubl_cii.models.account_edi_common import COUNTRY_EAS
import logging
_logger = logging.getLogger(__name__)
FORMAT_CODES = [
'facturx_1_0_05',
'ubl_bis3',
'ubl_de',
'nlcius_1',
'efff_1',
'ubl_2_1',
'ehf_3',
'ubl_sg',
]
class AccountEdiFormat(models.Model):
_inherit = 'account.edi.format'
####################################################
# Helpers
####################################################
def _infer_xml_builder_from_tree(self, tree):
self.ensure_one()
ubl_version = tree.find('{*}UBLVersionID')
customization_id = tree.find('{*}CustomizationID')
if tree.tag == '{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}CrossIndustryInvoice':
return self.env['account.edi.xml.cii']
if ubl_version is not None:
if ubl_version.text == '2.0':
return self.env['account.edi.xml.ubl_20']
if ubl_version.text == '2.1':
return self.env['account.edi.xml.ubl_21']
if customization_id is not None:
if 'xrechnung' in customization_id.text:
return self.env['account.edi.xml.ubl_de']
if customization_id.text == 'urn:cen.eu:en16931:2017#compliant#urn:fdc:nen.nl:nlcius:v1.0':
return self.env['account.edi.xml.ubl_nl']
if customization_id.text == 'urn:cen.eu:en16931:2017#conformant#urn:fdc:peppol.eu:2017:poacc:billing:international:sg:3.0':
return self.env['account.edi.xml.ubl_sg']
# Allow to parse any format derived from the european semantic norm EN16931
if 'urn:cen.eu:en16931:2017' in customization_id.text:
return self.env['account.edi.xml.ubl_bis3']
return
def _get_xml_builder(self, company):
# see https://communaute.chorus-pro.gouv.fr/wp-content/uploads/2017/08/20170630_Solution-portail_Dossier_Specifications_Fournisseurs_Chorus_Facture_V.1.pdf
# page 45 -> ubl 2.1 for France seems also supported
if self.code == 'facturx_1_0_05':
return self.env['account.edi.xml.cii']
# if the company's country is not in the EAS mapping, nothing is generated
if self.code == 'ubl_bis3' and company.country_id.code in COUNTRY_EAS:
return self.env['account.edi.xml.ubl_bis3']
# the EDI option will only appear on the journal of dutch companies
if self.code == 'nlcius_1' and company.country_id.code == 'NL':
return self.env['account.edi.xml.ubl_nl']
# the EDI option will only appear on the journal of german companies
if self.code == 'ubl_de' and company.country_id.code == 'DE':
return self.env['account.edi.xml.ubl_de']
# the EDI option will only appear on the journal of belgian companies
if self.code == 'efff_1' and company.country_id.code == 'BE':
return self.env['account.edi.xml.ubl_efff']
if self.code == 'ubl_sg' and company.country_id.code == 'SG':
return self.env['account.edi.xml.ubl_sg']
def _is_ubl_cii_available(self, company):
"""
Returns a boolean indicating whether it is possible to generate an xml file using one of the formats from this
module or not
"""
return self._get_xml_builder(company) is not None
####################################################
# Export: Account.edi.format override
####################################################
def _is_required_for_invoice(self, invoice):
# EXTENDS account_edi
self.ensure_one()
if self.code not in FORMAT_CODES:
return super()._is_required_for_invoice(invoice)
return self._is_ubl_cii_available(invoice.company_id) and invoice.move_type in ('out_invoice', 'out_refund')
def _is_compatible_with_journal(self, journal):
# EXTENDS account_edi
# the formats appear on the journal only if they are compatible (e.g. NLCIUS only appear for dutch companies)
self.ensure_one()
if self.code not in FORMAT_CODES:
return super()._is_compatible_with_journal(journal)
return self._is_ubl_cii_available(journal.company_id) and journal.type == 'sale'
def _is_enabled_by_default_on_journal(self, journal):
# EXTENDS account_edi
# only facturx is enabled by default, the other formats aren't
self.ensure_one()
if self.code not in FORMAT_CODES:
return super()._is_enabled_by_default_on_journal(journal)
return self.code == 'facturx_1_0_05'
def _post_invoice_edi(self, invoices):
# EXTENDS account_edi
self.ensure_one()
if self.code not in FORMAT_CODES:
return super()._post_invoice_edi(invoices)
res = {}
for invoice in invoices:
builder = self._get_xml_builder(invoice.company_id)
# For now, the errors are not displayed anywhere, don't want to annoy the user
xml_content, errors = builder._export_invoice(invoice)
# DEBUG: send directly to the test platform (the one used by ecosio)
#response = self.env['account.edi.common']._check_xml_ecosio(invoice, xml_content, builder._export_invoice_ecosio_schematrons())
attachment_create_vals = {
'name': builder._export_invoice_filename(invoice),
'raw': xml_content,
'mimetype': 'application/xml',
}
# we don't want the Factur-X, E-FFF and NLCIUS xml to appear in the attachment of the invoice when confirming it
# E-FFF and NLCIUS will appear after the pdf is generated, Factur-X will never appear (it's contained in the PDF)
if self.code not in ['facturx_1_0_05', 'efff_1', 'nlcius_1']:
attachment_create_vals.update({'res_id': invoice.id, 'res_model': 'account.move'})
attachment = self.env['ir.attachment'].with_user(SUPERUSER_ID).create(attachment_create_vals)
res[invoice] = {
'success': True,
'attachment': attachment,
}
return res
def _is_embedding_to_invoice_pdf_needed(self):
# EXTENDS account_edi
self.ensure_one()
if self.code == 'facturx_1_0_05':
return True
return super()._is_embedding_to_invoice_pdf_needed()
def _prepare_invoice_report(self, pdf_writer, edi_document):
# EXTENDS account_edi
self.ensure_one()
if self.code != 'facturx_1_0_05':
return super()._prepare_invoice_report(pdf_writer, edi_document)
if not edi_document.attachment_id:
return
pdf_writer.embed_odoo_attachment(edi_document.attachment_id, subtype='text/xml')
if not pdf_writer.is_pdfa and str2bool(
self.env['ir.config_parameter'].sudo().get_param('edi.use_pdfa', 'False')):
try:
pdf_writer.convert_to_pdfa()
except Exception as e:
_logger.exception("Error while converting to PDF/A: %s", e)
metadata_template = self.env.ref('account_edi_ubl_cii.account_invoice_pdfa_3_facturx_metadata',
raise_if_not_found=False)
if metadata_template:
content = self.env['ir.qweb']._render('account_edi_ubl_cii.account_invoice_pdfa_3_facturx_metadata', {
'title': edi_document.move_id.name,
'date': fields.Date.context_today(self),
})
pdf_writer.add_file_metadata(content.encode())
####################################################
# Import: Account.edi.format override
####################################################
def _create_invoice_from_xml_tree(self, filename, tree, journal=None):
# EXTENDS account_edi
self.ensure_one()
journal = journal or self.env['account.move']._get_default_journal()
if not self._is_ubl_cii_available(journal.company_id):
return super()._create_invoice_from_xml_tree(filename, tree, journal=journal)
# infer the xml builder
invoice_xml_builder = self._infer_xml_builder_from_tree(tree)
if invoice_xml_builder is not None:
invoice = invoice_xml_builder._import_invoice(journal, filename, tree)
if invoice:
return invoice
return super()._create_invoice_from_xml_tree(filename, tree, journal=journal)
def _update_invoice_from_xml_tree(self, filename, tree, invoice):
# EXTENDS account_edi
self.ensure_one()
if not self._is_ubl_cii_available(invoice.company_id):
return super()._update_invoice_from_xml_tree(filename, tree, invoice)
# infer the xml builder
invoice_xml_builder = self._infer_xml_builder_from_tree(tree)
if invoice_xml_builder is not None:
invoice = invoice_xml_builder._import_invoice(invoice.journal_id, filename, tree, invoice)
if invoice:
return invoice
return super()._update_invoice_from_xml_tree(filename, tree, invoice)
| 44.15493
| 9,405
|
3,069
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.tools import cleanup_xml_node
from lxml import etree
import base64
from xml.sax.saxutils import escape, quoteattr
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'
def _postprocess_pdf_report(self, record, buffer):
"""
EXTENDS account
Add the pdf report in XML as base64 string.
"""
result = super()._postprocess_pdf_report(record, buffer)
if record._name == 'account.move':
# exclude efff because it's handled by l10n_be_edi
format_codes = ['ubl_bis3', 'ubl_de', 'nlcius_1']
edi_attachments = record.edi_document_ids.filtered(lambda d: d.edi_format_id.code in format_codes).attachment_id
for edi_attachment in edi_attachments:
old_xml = base64.b64decode(edi_attachment.with_context(bin_size=False).datas, validate=True)
tree = etree.fromstring(old_xml)
anchor_elements = tree.xpath("//*[local-name()='AccountingSupplierParty']")
additional_document_elements = tree.xpath("//*[local-name()='AdditionalDocumentReference']")
# with this clause, we ensure the xml are only postprocessed once (even when the invoice is reset to
# draft then validated again)
if anchor_elements and not additional_document_elements:
pdf = base64.b64encode(buffer.getvalue()).decode()
pdf_name = '%s.pdf' % record.name.replace('/', '_')
to_inject = '''
<cac:AdditionalDocumentReference
xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2">
<cbc:ID>%s</cbc:ID>
<cac:Attachment>
<cbc:EmbeddedDocumentBinaryObject mimeCode="application/pdf" filename=%s>
%s
</cbc:EmbeddedDocumentBinaryObject>
</cac:Attachment>
</cac:AdditionalDocumentReference>
''' % (escape(pdf_name), quoteattr(pdf_name), pdf)
anchor_index = tree.index(anchor_elements[0])
tree.insert(anchor_index, etree.fromstring(to_inject))
new_xml = etree.tostring(cleanup_xml_node(tree), xml_declaration=True, encoding='UTF-8')
edi_attachment.write({
'res_model': 'account.move',
'res_id': record.id,
'datas': base64.b64encode(new_xml),
'mimetype': 'application/xml',
})
return result
| 51.15
| 3,069
|
2,473
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class AccountEdiXmlUBLSG(models.AbstractModel):
_inherit = "account.edi.xml.ubl_bis3"
_name = "account.edi.xml.ubl_sg"
_description = "SG BIS Billing 3.0"
"""
Documentation: https://www.peppolguide.sg/billing/bis/
"""
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
return f"{invoice.name.replace('/', '_')}_sg.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'eu.peppol.bis3.sg.ubl:invoice:1.0.3',
'credit_note': 'eu.peppol.bis3.sg.ubl:creditnote:1.0.3',
}
def _get_partner_party_vals(self, partner, role):
# EXTENDS account.edi.xml.ubl_bis3
vals = super()._get_partner_party_vals(partner, role)
for party_tax_scheme in vals['party_tax_scheme_vals']:
party_tax_scheme['tax_scheme_id'] = 'GST'
return vals
def _get_invoice_payment_means_vals_list(self, invoice):
""" https://www.peppolguide.sg/billing/bis/#_payment_means_information
"""
vals_list = super()._get_invoice_payment_means_vals_list(invoice)
for vals in vals_list:
vals.update({
'payment_means_code': 54,
'payment_means_code_attrs': {'name': 'Credit Card'},
})
return vals_list
def _get_tax_sg_codes(self, invoice, tax):
""" https://www.peppolguide.sg/billing/bis/#_gst_category_codes
"""
tax_category_code = 'SR'
if tax.amount == 0:
tax_category_code = 'ZR'
return tax_category_code
def _get_tax_category_list(self, invoice, taxes):
# OVERRIDE
res = []
for tax in taxes:
res.append({
'id': self._get_tax_sg_codes(invoice, tax),
'percent': tax.amount if tax.amount_type == 'percent' else False,
'tax_scheme_id': 'GST',
})
return res
def _export_invoice_vals(self, invoice):
# EXTENDS account.edi.xml.ubl_bis3
vals = super()._export_invoice_vals(invoice)
vals['vals'].update({
'customization_id': 'urn:cen.eu:en16931:2017#conformant#urn:fdc:peppol.eu:2017:poacc:billing:international:sg:3.0',
})
return vals
| 32.973333
| 2,473
|
1,547
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class AccountEdiXmlUBLDE(models.AbstractModel):
_inherit = "account.edi.xml.ubl_bis3"
_name = 'account.edi.xml.ubl_de'
_description = "BIS3 DE (XRechnung)"
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
return f"{invoice.name.replace('/', '_')}_ubl_de.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'de.xrechnung:ubl-invoice:2.2.0',
'credit_note': 'de.xrechnung:ubl-creditnote:2.2.0',
}
def _export_invoice_vals(self, invoice):
# EXTENDS account.edi.xml.ubl_bis3
vals = super()._export_invoice_vals(invoice)
vals['vals'].update({
'customization_id': 'urn:cen.eu:en16931:2017#compliant#urn:xoev-de:kosit:standard:xrechnung_2.2#conformant#urn:xoev-de:kosit:extension:xrechnung_2.2',
})
return vals
def _export_invoice_constraints(self, invoice, vals):
# EXTENDS account.edi.xml.ubl_bis3
constraints = super()._export_invoice_constraints(invoice, vals)
constraints.update({
'bis3_de_supplier_telephone_required': self._check_required_fields(vals['supplier'], ['phone', 'mobile']),
'bis3_de_supplier_electronic_mail_required': self._check_required_fields(vals['supplier'], 'email'),
})
return constraints
| 36.833333
| 1,547
|
33,693
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, _
from odoo.osv import expression
from odoo.tools import html2plaintext, cleanup_xml_node
from lxml import etree
class AccountEdiXmlUBL20(models.AbstractModel):
_name = "account.edi.xml.ubl_20"
_inherit = 'account.edi.common'
_description = "UBL 2.0"
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
return f"{invoice.name.replace('/', '_')}_ubl_20.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'org.oasis-open:invoice:2.0',
'credit_note': 'org.oasis-open:creditnote:2.0',
}
def _get_country_vals(self, country):
return {
'country': country,
'identification_code': country.code,
'name': country.name,
}
def _get_partner_party_identification_vals_list(self, partner):
return []
def _get_partner_address_vals(self, partner):
return {
'street_name': partner.street,
'additional_street_name': partner.street2,
'city_name': partner.city,
'postal_zone': partner.zip,
'country_subentity': partner.state_id.name,
'country_subentity_code': partner.state_id.code,
'country_vals': self._get_country_vals(partner.country_id),
}
def _get_partner_party_tax_scheme_vals_list(self, partner, role):
return [{
'registration_name': partner.name,
'company_id': partner.vat,
'registration_address_vals': self._get_partner_address_vals(partner),
'TaxScheme_vals': {},
'tax_scheme_id': 'VAT',
}]
def _get_partner_party_legal_entity_vals_list(self, partner):
commercial_partner = partner.commercial_partner_id
return [{
'commercial_partner': commercial_partner,
'registration_name': commercial_partner.name,
'company_id': commercial_partner.vat,
'registration_address_vals': self._get_partner_address_vals(commercial_partner),
}]
def _get_partner_contact_vals(self, partner):
return {
'id': partner.id,
'name': partner.name,
'telephone': partner.phone or partner.mobile,
'electronic_mail': partner.email,
}
def _get_partner_party_vals(self, partner, role):
return {
'partner': partner,
'party_identification_vals': self._get_partner_party_identification_vals_list(partner),
'party_name_vals': [{'name': partner.name}],
'postal_address_vals': self._get_partner_address_vals(partner),
'party_tax_scheme_vals': self._get_partner_party_tax_scheme_vals_list(partner, role),
'party_legal_entity_vals': self._get_partner_party_legal_entity_vals_list(partner),
'contact_vals': self._get_partner_contact_vals(partner),
}
def _get_invoice_period_vals_list(self, invoice):
"""
For now, we cannot fill this data from an invoice
This corresponds to the 'delivery or invoice period'. For UBL Bis 3, in the case of intra-community supply,
the Actual delivery date (BT-72) or the Invoicing period (BG-14) should be present under the form:
{
'start_date': str,
'end_date': str,
}.
"""
return []
def _get_delivery_vals_list(self, invoice):
# the data is optional, except for ubl bis3 (see the override, where we need to set a default delivery address)
if 'partner_shipping_id' in invoice._fields:
return [{
'actual_delivery_date': None,
'delivery_location_vals': {
'delivery_address_vals': self._get_partner_address_vals(invoice.partner_shipping_id),
},
}]
else:
return []
def _get_bank_address_vals(self, bank):
return {
'street_name': bank.street,
'additional_street_name': bank.street2,
'city_name': bank.city,
'postal_zone': bank.zip,
'country_subentity': bank.state.name,
'country_subentity_code': bank.state.code,
'country_vals': self._get_country_vals(bank.country),
}
def _get_financial_institution_vals(self, bank):
return {
'bank': bank,
'id': bank.bic,
'id_attrs': {'schemeID': 'BIC'},
'name': bank.name,
'address_vals': self._get_bank_address_vals(bank),
}
def _get_financial_institution_branch_vals(self, bank):
return {
'bank': bank,
'id': bank.bic,
'id_attrs': {'schemeID': 'BIC'},
'financial_institution_vals': self._get_financial_institution_vals(bank),
}
def _get_financial_account_vals(self, partner_bank):
vals = {
'bank_account': partner_bank,
'id': partner_bank.acc_number.replace(' ', ''),
}
if partner_bank.bank_id:
vals['financial_institution_branch_vals'] = self._get_financial_institution_branch_vals(partner_bank.bank_id)
return vals
def _get_invoice_payment_means_vals_list(self, invoice):
vals = {
'payment_means_code': 30,
'payment_means_code_attrs': {'name': 'credit transfer'},
'payment_due_date': invoice.invoice_date_due or invoice.invoice_date,
'instruction_id': invoice.payment_reference,
'payment_id_vals': [invoice.payment_reference or invoice.name],
}
if invoice.partner_bank_id:
vals['payee_financial_account_vals'] = self._get_financial_account_vals(invoice.partner_bank_id)
return [vals]
def _get_invoice_payment_terms_vals_list(self, invoice):
payment_term = invoice.invoice_payment_term_id
if payment_term:
return [{'note_vals': [payment_term.name]}]
else:
return []
def _get_invoice_tax_totals_vals_list(self, invoice, taxes_vals):
balance_sign = -1 if invoice.is_inbound() else 1
tax_totals_vals = {
'currency': invoice.currency_id,
'currency_dp': invoice.currency_id.decimal_places,
'tax_amount': balance_sign * taxes_vals['tax_amount_currency'],
'tax_subtotal_vals': [],
}
for grouping_key, vals in taxes_vals['tax_details'].items():
if grouping_key['tax_amount_type'] != 'fixed':
tax_totals_vals['tax_subtotal_vals'].append({
'currency': invoice.currency_id,
'currency_dp': invoice.currency_id.decimal_places,
'taxable_amount': balance_sign * vals['base_amount_currency'],
'tax_amount': balance_sign * vals['tax_amount_currency'],
'percent': vals['_tax_category_vals_']['percent'],
'tax_category_vals': vals['_tax_category_vals_'],
})
return [tax_totals_vals]
def _get_invoice_line_item_vals(self, line, taxes_vals):
""" Method used to fill the cac:InvoiceLine/cac:Item node.
It provides information about what the product you are selling.
:param line: An invoice line.
:param taxes_vals: The tax details for the current invoice line.
:return: A python dictionary.
"""
product = line.product_id
taxes = line.tax_ids.flatten_taxes_hierarchy().filtered(lambda t: t.amount_type != 'fixed')
tax_category_vals_list = self._get_tax_category_list(line.move_id, taxes)
description = line.name and line.name.replace('\n', ', ')
return {
# Simple description about what you are selling.
'description': description,
# The name of the item.
'name': product.name,
# Identifier of the product.
'sellers_item_identification_vals': {'id': product.code},
# The main tax applied. Only one is allowed.
'classified_tax_category_vals': tax_category_vals_list,
}
def _get_document_allowance_charge_vals_list(self, invoice):
"""
https://docs.peppol.eu/poacc/billing/3.0/bis/#_document_level_allowance_or_charge
"""
return []
def _get_invoice_line_allowance_vals_list(self, line, tax_values_list=None):
""" Method used to fill the cac:InvoiceLine>cac:AllowanceCharge node.
Allowances are distinguished from charges using the ChargeIndicator node with 'false' as value.
Note that allowance charges do not exist for credit notes in UBL 2.0, so if we apply discount in Odoo
the net price will not be consistent with the unit price, but we cannot do anything about it
:param line: An invoice line.
:return: A list of python dictionaries.
"""
fixed_tax_charge_vals_list = []
balance_sign = -1 if line.move_id.is_inbound() else 1
for grouping_key, tax_details in tax_values_list['tax_details'].items():
if grouping_key['tax_amount_type'] == 'fixed':
fixed_tax_charge_vals_list.append({
'currency_name': line.currency_id.name,
'currency_dp': line.currency_id.decimal_places,
'charge_indicator': 'true',
'allowance_charge_reason_code': 'AEO',
'allowance_charge_reason': tax_details['group_tax_details'][0]['tax_id'].name,
'amount': balance_sign * tax_details['tax_amount_currency'],
})
if not line.discount:
return fixed_tax_charge_vals_list
# Price subtotal without discount:
net_price_subtotal = line.price_subtotal
# Price subtotal with discount:
if line.discount == 100.0:
gross_price_subtotal = 0.0
else:
gross_price_subtotal = line.currency_id.round(net_price_subtotal / (1.0 - (line.discount or 0.0) / 100.0))
allowance_vals = {
'currency_name': line.currency_id.name,
'currency_dp': line.currency_id.decimal_places,
# Must be 'false' since this method is for allowances.
'charge_indicator': 'false',
# A reason should be provided. In Odoo, we only manage discounts.
# Full code list is available here:
# https://docs.peppol.eu/poacc/billing/3.0/codelist/UNCL5189/
'allowance_charge_reason_code': 95,
# The discount should be provided as an amount.
'amount': gross_price_subtotal - net_price_subtotal,
}
return [allowance_vals] + fixed_tax_charge_vals_list
def _get_invoice_line_price_vals(self, line):
""" Method used to fill the cac:InvoiceLine/cac:Price node.
It provides information about the price applied for the goods and services invoiced.
:param line: An invoice line.
:return: A python dictionary.
"""
# Price subtotal without discount:
net_price_subtotal = line.price_subtotal
# Price subtotal with discount:
if line.discount == 100.0:
gross_price_subtotal = 0.0
else:
gross_price_subtotal = net_price_subtotal / (1.0 - (line.discount or 0.0) / 100.0)
# Price subtotal with discount / quantity:
gross_price_unit = gross_price_subtotal / line.quantity if line.quantity else 0.0
uom = super()._get_uom_unece_code(line)
return {
'currency': line.currency_id,
'currency_dp': line.currency_id.decimal_places,
# The price of an item, exclusive of VAT, after subtracting item price discount.
'price_amount': gross_price_unit,
'product_price_dp': self.env['decimal.precision'].precision_get('Product Price'),
# The number of item units to which the price applies.
# setting to None -> the xml will not comprise the BaseQuantity (it's not mandatory)
'base_quantity': None,
'base_quantity_attrs': {'unitCode': uom},
}
def _get_invoice_line_vals(self, line, taxes_vals):
""" Method used to fill the cac:InvoiceLine node.
It provides information about the invoice line.
:param line: An invoice line.
:return: A python dictionary.
"""
allowance_charge_vals_list = self._get_invoice_line_allowance_vals_list(line, tax_values_list=taxes_vals)
uom = super()._get_uom_unece_code(line)
total_fixed_tax_amount = sum([
vals['amount']
for vals in allowance_charge_vals_list
if vals['allowance_charge_reason_code'] == 'AEO'
])
return {
'currency': line.currency_id,
'currency_dp': line.currency_id.decimal_places,
# The requirement is the id has to be unique by invoice line.
'id': line.id,
'invoiced_quantity': line.quantity,
'invoiced_quantity_attrs': {'unitCode': uom},
'line_extension_amount': line.price_subtotal + total_fixed_tax_amount,
'allowance_charge_vals': allowance_charge_vals_list,
'tax_total_vals': self._get_invoice_tax_totals_vals_list(line.move_id, taxes_vals),
'item_vals': self._get_invoice_line_item_vals(line, taxes_vals),
'price_vals': self._get_invoice_line_price_vals(line),
}
def _apply_invoice_tax_filter(self, tax_values):
"""
To be overridden to apply a specific tax filter
"""
return True
def _apply_invoice_line_filter(self, invoice_line):
"""
To be overridden to apply a specific invoice line filter
"""
return True
def _export_invoice_vals(self, invoice):
def grouping_key_generator(tax_values):
tax = tax_values['tax_id']
tax_category_vals = self._get_tax_category_list(invoice, tax)[0]
grouping_key = {
'tax_category_id': tax_category_vals['id'],
'tax_category_percent': tax_category_vals['percent'],
'_tax_category_vals_': tax_category_vals,
'tax_amount_type': tax.amount_type,
}
# If the tax is fixed, we want to have one group per tax
# s.t. when the invoice is imported, we can try to guess the fixed taxes
if tax.amount_type == 'fixed':
grouping_key['tax_name'] = tax.name
return grouping_key
# Validate the structure of the taxes
self._validate_taxes(invoice)
# Compute the tax details for the whole invoice and each invoice line separately.
taxes_vals = invoice._prepare_edi_tax_details(grouping_key_generator=grouping_key_generator,
filter_to_apply=self._apply_invoice_tax_filter,
filter_invl_to_apply=self._apply_invoice_line_filter)
# Fixed Taxes: filter them on the document level, and adapt the totals
# Fixed taxes are not supposed to be taxes in real live. However, this is the way in Odoo to manage recupel
# taxes in Belgium. Since only one tax is allowed, the fixed tax is removed from totals of lines but added
# as an extra charge/allowance.
fixed_taxes_keys = [k for k in taxes_vals['tax_details'] if k['tax_amount_type'] == 'fixed']
for key in fixed_taxes_keys:
fixed_tax_details = taxes_vals['tax_details'].pop(key)
taxes_vals['tax_amount_currency'] -= fixed_tax_details['tax_amount_currency']
taxes_vals['tax_amount'] -= fixed_tax_details['tax_amount']
taxes_vals['base_amount_currency'] += fixed_tax_details['tax_amount_currency']
taxes_vals['base_amount'] += fixed_tax_details['tax_amount']
# Compute values for invoice lines.
line_extension_amount = 0.0
invoice_lines = invoice.invoice_line_ids.filtered(lambda line: not line.display_type)
document_allowance_charge_vals_list = self._get_document_allowance_charge_vals_list(invoice)
invoice_line_vals_list = []
for line in invoice_lines:
line_taxes_vals = taxes_vals['invoice_line_tax_details'][line]
line_vals = self._get_invoice_line_vals(line, line_taxes_vals)
invoice_line_vals_list.append(line_vals)
line_extension_amount += line_vals['line_extension_amount']
# Compute the total allowance/charge amounts.
allowance_total_amount = 0.0
for allowance_charge_vals in document_allowance_charge_vals_list:
if allowance_charge_vals['charge_indicator'] == 'false':
allowance_total_amount += allowance_charge_vals['amount']
supplier = invoice.company_id.partner_id.commercial_partner_id
customer = invoice.commercial_partner_id
# OrderReference/SalesOrderID (sales_order_id) is optional
sales_order_id = 'sale_line_ids' in invoice.invoice_line_ids._fields \
and ",".join(invoice.invoice_line_ids.sale_line_ids.order_id.mapped('name'))
# OrderReference/ID (order_reference) is mandatory inside the OrderReference node !
order_reference = invoice.ref or invoice.name if sales_order_id else invoice.ref
balance_sign = -1 if invoice.is_inbound() else 1
vals = {
'builder': self,
'invoice': invoice,
'supplier': supplier,
'customer': customer,
'taxes_vals': taxes_vals,
'format_float': self.format_float,
'AddressType_template': 'account_edi_ubl_cii.ubl_20_AddressType',
'ContactType_template': 'account_edi_ubl_cii.ubl_20_ContactType',
'PartyType_template': 'account_edi_ubl_cii.ubl_20_PartyType',
'PaymentMeansType_template': 'account_edi_ubl_cii.ubl_20_PaymentMeansType',
'TaxCategoryType_template': 'account_edi_ubl_cii.ubl_20_TaxCategoryType',
'TaxTotalType_template': 'account_edi_ubl_cii.ubl_20_TaxTotalType',
'AllowanceChargeType_template': 'account_edi_ubl_cii.ubl_20_AllowanceChargeType',
'InvoiceLineType_template': 'account_edi_ubl_cii.ubl_20_InvoiceLineType',
'InvoiceType_template': 'account_edi_ubl_cii.ubl_20_InvoiceType',
'vals': {
'ubl_version_id': 2.0,
'id': invoice.name,
'issue_date': invoice.invoice_date,
'due_date': invoice.invoice_date_due,
'note_vals': [html2plaintext(invoice.narration)] if invoice.narration else [],
'order_reference': order_reference,
'sales_order_id': sales_order_id,
'accounting_supplier_party_vals': {
'party_vals': self._get_partner_party_vals(supplier, role='supplier'),
},
'accounting_customer_party_vals': {
'party_vals': self._get_partner_party_vals(customer, role='customer'),
},
'invoice_period_vals_list': self._get_invoice_period_vals_list(invoice),
'delivery_vals_list': self._get_delivery_vals_list(invoice),
'payment_means_vals_list': self._get_invoice_payment_means_vals_list(invoice),
'payment_terms_vals': self._get_invoice_payment_terms_vals_list(invoice),
# allowances at the document level, the allowances on invoices (eg. discount) are on invoice_line_vals
'allowance_charge_vals': document_allowance_charge_vals_list,
'tax_total_vals': self._get_invoice_tax_totals_vals_list(invoice, taxes_vals),
'legal_monetary_total_vals': {
'currency': invoice.currency_id,
'currency_dp': invoice.currency_id.decimal_places,
'line_extension_amount': line_extension_amount,
'tax_exclusive_amount': balance_sign * taxes_vals['base_amount_currency'],
'tax_inclusive_amount': invoice.amount_total,
'allowance_total_amount': allowance_total_amount or None,
'prepaid_amount': invoice.amount_total - invoice.amount_residual,
'payable_amount': invoice.amount_residual,
},
'invoice_line_vals': invoice_line_vals_list,
'currency_dp': invoice.currency_id.decimal_places, # currency decimal places
},
}
if invoice.move_type == 'out_invoice':
vals['main_template'] = 'account_edi_ubl_cii.ubl_20_Invoice'
vals['vals']['invoice_type_code'] = 380
else:
vals['main_template'] = 'account_edi_ubl_cii.ubl_20_CreditNote'
vals['vals']['credit_note_type_code'] = 381
return vals
def _export_invoice_constraints(self, invoice, vals):
constraints = self._invoice_constraints_common(invoice)
constraints.update({
'ubl20_supplier_name_required': self._check_required_fields(vals['supplier'], 'name'),
'ubl20_customer_name_required': self._check_required_fields(vals['customer'], 'name'),
'ubl20_commercial_customer_name_required': self._check_required_fields(vals['customer'].commercial_partner_id, 'name'),
'ubl20_invoice_name_required': self._check_required_fields(invoice, 'name'),
'ubl20_invoice_date_required': self._check_required_fields(invoice, 'invoice_date'),
})
return constraints
def _export_invoice(self, invoice):
vals = self._export_invoice_vals(invoice)
errors = [constraint for constraint in self._export_invoice_constraints(invoice, vals).values() if constraint]
xml_content = self.env['ir.qweb']._render(vals['main_template'], vals)
return etree.tostring(cleanup_xml_node(xml_content), xml_declaration=True, encoding='UTF-8'), set(errors)
# -------------------------------------------------------------------------
# IMPORT
# -------------------------------------------------------------------------
def _import_fill_invoice_form(self, journal, tree, invoice_form, qty_factor):
def _find_value(xpath, element=tree):
# avoid 'TypeError: empty namespace prefix is not supported in XPath'
nsmap = {k: v for k, v in tree.nsmap.items() if k is not None}
return self.env['account.edi.format']._find_value(xpath, element, nsmap)
logs = []
if qty_factor == -1:
logs.append(_("The invoice has been converted into a credit note and the quantities have been reverted."))
# ==== partner_id ====
role = "Customer" if invoice_form.journal_id.type == 'sale' else "Supplier"
vat = _find_value(f'//cac:Accounting{role}Party/cac:Party//cbc:CompanyID')
phone = _find_value(f'//cac:Accounting{role}Party/cac:Party//cbc:Telephone')
mail = _find_value(f'//cac:Accounting{role}Party/cac:Party//cbc:ElectronicMail')
name = _find_value(f'//cac:Accounting{role}Party/cac:Party//cbc:Name')
country_code = _find_value(f'//cac:Accounting{role}Party/cac:Party//cac:Country//cbc:IdentificationCode')
self._import_retrieve_and_fill_partner(invoice_form, name=name, phone=phone, mail=mail, vat=vat, country_code=country_code)
# ==== currency_id ====
currency_code_node = tree.find('.//{*}DocumentCurrencyCode')
if currency_code_node is not None:
currency = self.env['res.currency'].with_context(active_test=False).search([
('name', '=', currency_code_node.text),
], limit=1)
if currency:
if not currency.active:
logs.append(_("The currency '%s' is not active.", currency.name))
invoice_form.currency_id = currency
else:
logs.append(_("Could not retrieve currency: %s. Did you enable the multicurrency option "
"and activate the currency ?", currency_code_node.text))
# ==== Reference ====
ref_node = tree.find('./{*}ID')
if ref_node is not None:
invoice_form.ref = ref_node.text
# === Note/narration ====
narration = ""
note_node = tree.find('./{*}Note')
if note_node is not None and note_node.text:
narration += note_node.text + "\n"
payment_terms_node = tree.find('./{*}PaymentTerms/{*}Note') # e.g. 'Payment within 10 days, 2% discount'
if payment_terms_node is not None and payment_terms_node.text:
narration += payment_terms_node.text + "\n"
invoice_form.narration = narration
# ==== payment_reference ====
payment_reference_node = tree.find('./{*}PaymentMeans/{*}PaymentID')
if payment_reference_node is not None:
invoice_form.payment_reference = payment_reference_node.text
# ==== invoice_date ====
invoice_date_node = tree.find('./{*}IssueDate')
if invoice_date_node is not None:
invoice_form.invoice_date = invoice_date_node.text
# ==== invoice_date_due ====
for xpath in ('./{*}DueDate', './/{*}PaymentDueDate'):
invoice_date_due_node = tree.find(xpath)
if invoice_date_due_node is not None:
invoice_form.invoice_date_due = invoice_date_due_node.text
break
# ==== invoice_incoterm_id ====
incoterm_code_node = tree.find('./{*}TransportExecutionTerms/{*}DeliveryTerms/{*}ID')
if incoterm_code_node is not None and incoterm_code_node.text:
incoterm = self.env['account.incoterms'].search([('code', '=', incoterm_code_node.text)], limit=1)
if incoterm:
invoice_form.invoice_incoterm_id = incoterm
# ==== invoice_line_ids: AllowanceCharge (document level) ====
logs += self._import_fill_invoice_allowance_charge(tree, invoice_form, journal, qty_factor)
# ==== Prepaid amount ====
prepaid_node = tree.find('./{*}LegalMonetaryTotal/{*}PrepaidAmount')
logs += self._import_log_prepaid_amount(invoice_form, prepaid_node, qty_factor)
# ==== invoice_line_ids: InvoiceLine/CreditNoteLine ====
invoice_line_tag = 'InvoiceLine' if invoice_form.move_type in ('in_invoice', 'out_invoice') or qty_factor == -1 else 'CreditNoteLine'
for i, invl_el in enumerate(tree.findall('./{*}' + invoice_line_tag)):
with invoice_form.invoice_line_ids.new() as invoice_line_form:
invoice_line_form.sequence = i
invl_logs = self._import_fill_invoice_line_form(journal, invl_el, invoice_form, invoice_line_form, qty_factor)
logs += invl_logs
return invoice_form, logs
def _import_fill_invoice_line_form(self, journal, tree, invoice_form, invoice_line_form, qty_factor):
logs = []
# Product
product = self._import_retrieve_info_from_map(
tree,
self._import_retrieve_product_map(journal),
)
if product is not None:
invoice_line_form.product_id = product
# Description
description_node = tree.find('./{*}Item/{*}Description')
name_node = tree.find('./{*}Item/{*}Name')
if description_node is not None:
invoice_line_form.name = description_node.text
elif name_node is not None:
invoice_line_form.name = name_node.text # Fallback on Name if Description is not found.
xpath_dict = {
'basis_qty': [
'./{*}Price/{*}BaseQuantity',
],
'gross_price_unit': './{*}Price/{*}AllowanceCharge/{*}BaseAmount',
'rebate': './{*}Price/{*}AllowanceCharge/{*}Amount',
'net_price_unit': './{*}Price/{*}PriceAmount',
'billed_qty': './{*}InvoicedQuantity' if invoice_form.move_type in ('in_invoice', 'out_invoice') or qty_factor == -1 else './{*}CreditedQuantity',
'allowance_charge': './/{*}AllowanceCharge',
'allowance_charge_indicator': './{*}ChargeIndicator',
'allowance_charge_amount': './{*}Amount',
'allowance_charge_reason': './{*}AllowanceChargeReason',
'allowance_charge_reason_code': './{*}AllowanceChargeReasonCode',
'line_total_amount': './{*}LineExtensionAmount',
}
inv_line_vals = self._import_fill_invoice_line_values(tree, xpath_dict, invoice_line_form, qty_factor)
# retrieve tax nodes
tax_nodes = tree.findall('.//{*}Item/{*}ClassifiedTaxCategory/{*}Percent')
if not tax_nodes:
for elem in tree.findall('.//{*}TaxTotal'):
tax_nodes += elem.findall('.//{*}TaxSubtotal/{*}Percent')
return self._import_fill_invoice_line_taxes(journal, tax_nodes, invoice_line_form, inv_line_vals, logs)
# -------------------------------------------------------------------------
# IMPORT : helpers
# -------------------------------------------------------------------------
def _get_import_document_amount_sign(self, filename, tree):
"""
In UBL, an invoice has tag 'Invoice' and a credit note has tag 'CreditNote'. However, a credit note can be
expressed as an invoice with negative amounts. For this case, we need a factor to take the opposite
of each quantity in the invoice.
"""
if tree.tag == '{urn:oasis:names:specification:ubl:schema:xsd:Invoice-2}Invoice':
amount_node = tree.find('.//{*}LegalMonetaryTotal/{*}TaxExclusiveAmount')
if amount_node is not None and float(amount_node.text) < 0:
return ('in_refund', 'out_refund'), -1
return ('in_invoice', 'out_invoice'), 1
if tree.tag == '{urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2}CreditNote':
return ('in_refund', 'out_refund'), 1
return None, None
def _import_retrieve_partner_map(self, company, move_type='purchase'):
role = "Customer" if move_type == 'sale' else "Supplier"
def with_vat(tree, extra_domain):
vat_node = tree.find(f'.//{{*}}Accounting{role}Party/{{*}}Party//{{*}}CompanyID')
vat = None if vat_node is None else vat_node.text
return self.env['account.edi.format']._retrieve_partner_with_vat(vat, extra_domain)
def with_phone_mail(tree, extra_domain):
phone_node = tree.find(f'.//{{*}}Accounting{role}Party/{{*}}Party//{{*}}Telephone')
mail_node = tree.find(f'.//{{*}}Accounting{role}Party/{{*}}Party//{{*}}ElectronicMail')
phone = None if phone_node is None else phone_node.text
mail = None if mail_node is None else mail_node.text
return self.env['account.edi.format']._retrieve_partner_with_phone_mail(phone, mail, extra_domain)
def with_name(tree, extra_domain):
name_node = tree.find(f'.//{{*}}Accounting{role}Party/{{*}}Party//{{*}}Name')
name = None if name_node is None else name_node.text
return self.env['account.edi.format']._retrieve_partner_with_name(name, extra_domain)
return {
10: lambda tree: with_vat(tree, [('company_id', '=', company.id)]),
20: lambda tree: with_vat(tree, []),
30: lambda tree: with_phone_mail(tree, [('company_id', '=', company.id)]),
40: lambda tree: with_phone_mail(tree, []),
50: lambda tree: with_name(tree, [('company_id', '=', company.id)]),
60: lambda tree: with_name(tree, []),
}
def _import_retrieve_product_map(self, company):
def with_code_barcode(tree, extra_domain):
domains = []
default_code_node = tree.find('./{*}Item/{*}SellersItemIdentification/{*}ID')
if default_code_node is not None:
domains.append([('default_code', '=', default_code_node.text)])
barcode_node = tree.find("./{*}Item/{*}StandardItemIdentification/{*}ID[@schemeID='0160']")
if barcode_node is not None:
domains.append([('barcode', '=', barcode_node.text)])
if not domains:
return None
return self.env['product.product'].search(extra_domain + expression.OR(domains), limit=1)
def with_name(tree, extra_domain):
name_node = tree.find('./{*}Item/{*}Name')
if name_node is None:
return None
return self.env['product.product'].search(extra_domain + [('name', 'ilike', name_node.text)], limit=1)
return {
10: lambda tree: with_code_barcode(tree, [('company_id', '=', company.id)]),
20: lambda tree: with_code_barcode(tree, []),
30: lambda tree: with_name(tree, [('company_id', '=', company.id)]),
40: lambda tree: with_name(tree, []),
}
def _import_retrieve_info_from_map(self, tree, import_method_map):
for key in sorted(import_method_map.keys()):
record = import_method_map[key](tree)
if record:
return record
return None
| 45.469636
| 33,693
|
1,183
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class AccountEdiXmlUBL21(models.AbstractModel):
_name = "account.edi.xml.ubl_21"
_inherit = 'account.edi.xml.ubl_20'
_description = "UBL 2.1"
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
return f"{invoice.name.replace('/', '_')}_ubl_21.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'org.oasis-open:invoice:2.1',
'credit_note': 'org.oasis-open:creditnote:2.1',
}
def _export_invoice_vals(self, invoice):
# EXTENDS account.edi.xml.ubl_20
vals = super()._export_invoice_vals(invoice)
vals.update({
'InvoiceType_template': 'account_edi_ubl_cii.ubl_21_InvoiceType',
'InvoiceLineType_template': 'account_edi_ubl_cii.ubl_21_InvoiceLineType',
})
vals['vals'].update({
'ubl_version_id': 2.1,
'buyer_reference': invoice.commercial_partner_id.ref,
})
return vals
| 31.972973
| 1,183
|
23,255
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models, _
from odoo.addons.account_edi_ubl_cii.models.account_edi_common import COUNTRY_EAS
from stdnum.no import mva
class AccountEdiXmlUBLBIS3(models.AbstractModel):
_name = "account.edi.xml.ubl_bis3"
_inherit = 'account.edi.xml.ubl_21'
_description = "UBL BIS Billing 3.0.12"
"""
* Documentation of EHF Billing 3.0: https://anskaffelser.dev/postaward/g3/
* EHF 2.0 is no longer used:
https://anskaffelser.dev/postaward/g2/announcement/2019-11-14-removal-old-invoicing-specifications/
* Official doc for EHF Billing 3.0 is the OpenPeppol BIS 3 doc +
https://anskaffelser.dev/postaward/g3/spec/current/billing-3.0/norway/
"Based on work done in PEPPOL BIS Billing 3.0, Difi has included Norwegian rules in PEPPOL BIS Billing 3.0 and
does not see a need to implement a different CIUS targeting the Norwegian market. Implementation of EHF Billing
3.0 is therefore done by implementing PEPPOL BIS Billing 3.0 without extensions or extra rules."
Thus, EHF 3 and Bis 3 are actually the same format. The specific rules for NO defined in Bis 3 are added in Bis 3.
"""
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
return f"{invoice.name.replace('/', '_')}_ubl_bis3.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'eu.peppol.bis3:invoice:3.13.0',
'credit_note': 'eu.peppol.bis3:creditnote:3.13.0',
}
def _get_country_vals(self, country):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_country_vals(country)
vals.pop('name', None)
return vals
def _get_partner_party_tax_scheme_vals_list(self, partner, role):
# EXTENDS account.edi.xml.ubl_21
vals_list = super()._get_partner_party_tax_scheme_vals_list(partner, role)
if not partner.vat:
return []
for vals in vals_list:
vals.pop('registration_name', None)
vals.pop('registration_address_vals', None)
# /!\ For Australian companies, the ABN is encoded on the VAT field, but doesn't have the 2 digits prefix,
# causing a validation error
if partner.country_id.code == "AU" and partner.vat and not partner.vat.upper().startswith("AU"):
vals['company_id'] = "AU" + partner.vat
if partner.country_id.code == "LU" and 'l10n_lu_peppol_identifier' in partner._fields and partner.l10n_lu_peppol_identifier:
vals['company_id'] = partner.l10n_lu_peppol_identifier
# sources:
# https://anskaffelser.dev/postaward/g3/spec/current/billing-3.0/norway/#_applying_foretaksregisteret
# https://docs.peppol.eu/poacc/billing/3.0/bis/#national_rules (NO-R-002 (warning))
if partner.country_id.code == "NO" and role == 'supplier':
vals_list.append({
'company_id': "Foretaksregisteret",
'tax_scheme_id': "TAX",
})
return vals_list
def _get_partner_party_legal_entity_vals_list(self, partner):
# EXTENDS account.edi.xml.ubl_21
vals_list = super()._get_partner_party_legal_entity_vals_list(partner)
for vals in vals_list:
vals.pop('registration_address_vals', None)
if partner.country_code == 'NL' and 'l10n_nl_oin' in partner._fields:
endpoint = partner.l10n_nl_oin or partner.l10n_nl_kvk
scheme = '0190' if partner.l10n_nl_oin else '0106'
vals.update({
'company_id': endpoint,
'company_id_attrs': {'schemeID': scheme},
})
if partner.country_id.code == "LU" and 'l10n_lu_peppol_identifier' in partner._fields and partner.l10n_lu_peppol_identifier:
vals['company_id'] = partner.l10n_lu_peppol_identifier
return vals_list
def _get_partner_contact_vals(self, partner):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_partner_contact_vals(partner)
vals.pop('id', None)
return vals
def _get_partner_party_vals(self, partner, role):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_partner_party_vals(partner, role)
vals['endpoint_id'] = partner.vat
vals['endpoint_id_attrs'] = {'schemeID': COUNTRY_EAS.get(partner.country_id.code)}
if partner.country_code == 'NO' and 'l10n_no_bronnoysund_number' in partner._fields:
vals.update({
'endpoint_id': partner.l10n_no_bronnoysund_number,
'endpoint_id_attrs': {'schemeID': '0192'},
})
# [BR-NL-1] Dutch supplier registration number ( AccountingSupplierParty/Party/PartyLegalEntity/CompanyID );
# With a Dutch supplier (NL), SchemeID may only contain 106 (Chamber of Commerce number) or 190 (OIN number).
# [BR-NL-10] At a Dutch supplier, for a Dutch customer ( AccountingCustomerParty ) the customer registration
# number must be filled with Chamber of Commerce or OIN. SchemeID may only contain 106 (Chamber of
# Commerce number) or 190 (OIN number).
if partner.country_code == 'NL' and 'l10n_nl_oin' in partner._fields:
if partner.l10n_nl_oin:
vals.update({
'endpoint_id': partner.l10n_nl_oin,
'endpoint_id_attrs': {'schemeID': '0190'},
})
elif partner.l10n_nl_kvk:
vals.update({
'endpoint_id': partner.l10n_nl_kvk,
'endpoint_id_attrs': {'schemeID': '0106'},
})
if partner.country_id.code == 'SG' and 'l10n_sg_unique_entity_number' in partner._fields:
vals.update({
'endpoint_id': partner.l10n_sg_unique_entity_number,
'endpoint_id_attrs': {'schemeID': '0195'},
})
if partner.country_id.code == "LU" and 'l10n_lu_peppol_identifier' in partner._fields and partner.l10n_lu_peppol_identifier:
vals['endpoint_id'] = partner.l10n_lu_peppol_identifier
return vals
def _get_partner_party_identification_vals_list(self, partner):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_partner_party_identification_vals_list(partner)
if partner.country_code == 'NL' and 'l10n_nl_oin' in partner._fields:
endpoint = partner.l10n_nl_oin or partner.l10n_nl_kvk
vals.append({
'id': endpoint,
})
return vals
def _get_delivery_vals_list(self, invoice):
# EXTENDS account.edi.xml.ubl_21
supplier = invoice.company_id.partner_id.commercial_partner_id
customer = invoice.commercial_partner_id
economic_area = self.env.ref('base.europe').country_ids.mapped('code') + ['NO']
intracom_delivery = (customer.country_id.code in economic_area
and supplier.country_id.code in economic_area
and supplier.country_id != customer.country_id)
if not intracom_delivery:
return []
# [BR-IC-12]-In an Invoice with a VAT breakdown (BG-23) where the VAT category code (BT-118) is
# "Intra-community supply" the Deliver to country code (BT-80) shall not be blank.
# [BR-IC-11]-In an Invoice with a VAT breakdown (BG-23) where the VAT category code (BT-118) is
# "Intra-community supply" the Actual delivery date (BT-72) or the Invoicing period (BG-14)
# shall not be blank.
if 'partner_shipping_id' in invoice._fields:
partner_shipping = invoice.partner_shipping_id
else:
partner_shipping = customer
return [{
'actual_delivery_date': invoice.invoice_date,
'delivery_location_vals': {
'delivery_address_vals': self._get_partner_address_vals(partner_shipping),
},
}]
def _get_partner_address_vals(self, partner):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_partner_address_vals(partner)
# schematron/openpeppol/3.13.0/xslt/CEN-EN16931-UBL.xslt
# [UBL-CR-225]-A UBL invoice should not include the AccountingCustomerParty Party PostalAddress CountrySubentityCode
vals.pop('country_subentity_code', None)
return vals
def _get_financial_institution_branch_vals(self, bank):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_financial_institution_branch_vals(bank)
# schematron/openpeppol/3.13.0/xslt/CEN-EN16931-UBL.xslt
# [UBL-CR-664]-A UBL invoice should not include the FinancialInstitutionBranch FinancialInstitution
# xpath test: not(//cac:FinancialInstitution)
vals.pop('id_attrs', None)
vals.pop('financial_institution_vals', None)
return vals
def _get_invoice_payment_means_vals_list(self, invoice):
# EXTENDS account.edi.xml.ubl_21
vals_list = super()._get_invoice_payment_means_vals_list(invoice)
for vals in vals_list:
vals.pop('payment_due_date', None)
vals.pop('instruction_id', None)
if vals.get('payment_id_vals'):
vals['payment_id_vals'] = vals['payment_id_vals'][:1]
return vals_list
def _get_tax_category_list(self, invoice, taxes):
# EXTENDS account.edi.xml.ubl_21
vals_list = super()._get_tax_category_list(invoice, taxes)
for vals in vals_list:
vals.pop('name')
# [UBL-CR-601]-A UBL invoice should not include the InvoiceLine Item ClassifiedTaxCategory TaxExemptionReason
#vals.pop('tax_exemption_reason')
return vals_list
def _get_invoice_tax_totals_vals_list(self, invoice, taxes_vals):
# EXTENDS account.edi.xml.ubl_21
vals_list = super()._get_invoice_tax_totals_vals_list(invoice, taxes_vals)
for vals in vals_list:
vals['currency_dp'] = 2
for subtotal_vals in vals.get('tax_subtotal_vals', []):
subtotal_vals.pop('percent', None)
subtotal_vals['currency_dp'] = 2
return vals_list
def _get_invoice_line_allowance_vals_list(self, line, tax_values_list=None):
# EXTENDS account.edi.xml.ubl_21
vals_list = super()._get_invoice_line_allowance_vals_list(line, tax_values_list=tax_values_list)
for vals in vals_list:
vals['currency_dp'] = 2
return vals_list
def _get_invoice_line_vals(self, line, taxes_vals):
# EXTENDS account.edi.xml.ubl_21
vals = super()._get_invoice_line_vals(line, taxes_vals)
vals.pop('tax_total_vals', None)
vals['currency_dp'] = 2
vals['price_vals']['currency_dp'] = 2
return vals
def _export_invoice_vals(self, invoice):
# EXTENDS account.edi.xml.ubl_21
vals = super()._export_invoice_vals(invoice)
vals['vals'].update({
'customization_id': 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0',
'profile_id': 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0',
'currency_dp': 2,
'ubl_version_id': None,
})
vals['vals']['legal_monetary_total_vals']['currency_dp'] = 2
# [NL-R-001] For suppliers in the Netherlands, if the document is a creditnote, the document MUST
# contain an invoice reference (cac:BillingReference/cac:InvoiceDocumentReference/cbc:ID)
if vals['supplier'].country_id.code == 'NL' and 'refund' in invoice.move_type:
vals['vals'].update({
'billing_reference_vals': {
'id': invoice.ref,
'issue_date': None,
}
})
return vals
def _export_invoice_constraints(self, invoice, vals):
# EXTENDS account.edi.xml.ubl_21
constraints = super()._export_invoice_constraints(invoice, vals)
constraints.update(
self._invoice_constraints_peppol_en16931_ubl(invoice, vals)
)
constraints.update(
self._invoice_constraints_cen_en16931_ubl(invoice, vals)
)
return constraints
def _invoice_constraints_cen_en16931_ubl(self, invoice, vals):
"""
corresponds to the errors raised by ' schematron/openpeppol/3.13.0/xslt/CEN-EN16931-UBL.xslt' for invoices.
This xslt was obtained by transforming the corresponding sch
https://docs.peppol.eu/poacc/billing/3.0/files/CEN-EN16931-UBL.sch.
"""
eu_countries = self.env.ref('base.europe').country_ids
intracom_delivery = (vals['customer'].country_id in eu_countries
and vals['supplier'].country_id in eu_countries
and vals['customer'].country_id != vals['supplier'].country_id)
constraints = {
# [BR-S-02]-An Invoice that contains an Invoice line (BG-25) where the Invoiced item VAT category code
# (BT-151) is "Standard rated" shall contain the Seller VAT Identifier (BT-31), the Seller tax registration
# identifier (BT-32) and/or the Seller tax representative VAT identifier (BT-63).
# ---
# [BR-CO-26]-In order for the buyer to automatically identify a supplier, the Seller identifier (BT-29),
# the Seller legal registration identifier (BT-30) and/or the Seller VAT identifier (BT-31) shall be present.
'cen_en16931_seller_vat_identifier': self._check_required_fields(
vals['supplier'], 'vat' # this check is larger than the rules above
),
# [BR-61]-If the Payment means type code (BT-81) means SEPA credit transfer, Local credit transfer or
# Non-SEPA international credit transfer, the Payment account identifier (BT-84) shall be present.
# note: Payment account identifier is <cac:PayeeFinancialAccount>
# note: no need to check account_number, because it's a required field for a partner_bank
'cen_en16931_payment_account_identifier': self._check_required_fields(
invoice, 'partner_bank_id'
) if vals['vals']['payment_means_vals_list'][0]['payment_means_code'] in (30, 58) else None,
# [BR-62]-The Seller electronic address (BT-34) shall have a Scheme identifier.
# if this fails, it might just be a missing country when mapping the country to the EAS code
'cen_en16931_seller_EAS': self._check_required_fields(
vals['vals']['accounting_supplier_party_vals']['party_vals']['endpoint_id_attrs'], 'schemeID',
_("No Electronic Address Scheme (EAS) could be found for %s.", vals['customer'].name)
),
# [BR-63]-The Buyer electronic address (BT-49) shall have a Scheme identifier.
# if this fails, it might just be a missing country when mapping the country to the EAS code
'cen_en16931_buyer_EAS': self._check_required_fields(
vals['vals']['accounting_customer_party_vals']['party_vals']['endpoint_id_attrs'], 'schemeID',
_("No Electronic Address Scheme (EAS) could be found for %s.", vals['customer'].name)
),
# [BR-IC-12]-In an Invoice with a VAT breakdown (BG-23) where the VAT category code (BT-118) is
# "Intra-community supply" the Deliver to country code (BT-80) shall not be blank.
'cen_en16931_delivery_country_code': self._check_required_fields(
vals['vals']['delivery_vals_list'][0], 'delivery_location_vals',
_("For intracommunity supply, the delivery address should be included.")
) if intracom_delivery else None,
# [BR-IC-11]-In an Invoice with a VAT breakdown (BG-23) where the VAT category code (BT-118) is
# "Intra-community supply" the Actual delivery date (BT-72) or the Invoicing period (BG-14)
# shall not be blank.
'cen_en16931_delivery_date_invoicing_period': self._check_required_fields(
vals['vals']['delivery_vals_list'][0], 'actual_delivery_date',
_("For intracommunity supply, the actual delivery date or the invoicing period should be included.")
) and self._check_required_fields(
vals['vals']['invoice_period_vals_list'][0], ['start_date', 'end_date'],
_("For intracommunity supply, the actual delivery date or the invoicing period should be included.")
) if intracom_delivery else None,
}
for line in invoice.invoice_line_ids.filtered(lambda x: x.display_type not in ('line_note', 'line_section')):
if len(line.tax_ids.flatten_taxes_hierarchy().filtered(lambda t: t.amount_type != 'fixed')) != 1:
# [UBL-SR-48]-Invoice lines shall have one and only one classified tax category.
# /!\ exception: possible to have any number of ecotaxes (fixed tax) with a regular percentage tax
constraints.update({'cen_en16931_tax_line': _("Each invoice line shall have one and only one tax.")})
return constraints
def _invoice_constraints_peppol_en16931_ubl(self, invoice, vals):
"""
corresponds to the errors raised by 'schematron/openpeppol/3.13.0/xslt/PEPPOL-EN16931-UBL.xslt' for
invoices in ecosio. This xslt was obtained by transforming the corresponding sch
https://docs.peppol.eu/poacc/billing/3.0/files/PEPPOL-EN16931-UBL.sch.
The national rules (https://docs.peppol.eu/poacc/billing/3.0/bis/#national_rules) are included in this file.
They always refer to the supplier's country.
"""
constraints = {
# PEPPOL-EN16931-R020: Seller electronic address MUST be provided
'peppol_en16931_ubl_seller_endpoint': self._check_required_fields(
vals['supplier'], 'vat'
),
# PEPPOL-EN16931-R010: Buyer electronic address MUST be provided
'peppol_en16931_ubl_buyer_endpoint': self._check_required_fields(
vals['customer'], 'vat'
),
# PEPPOL-EN16931-R003: A buyer reference or purchase order reference MUST be provided.
'peppol_en16931_ubl_buyer_ref_po_ref':
"A buyer reference or purchase order reference must be provided." if self._check_required_fields(
vals['vals'], 'buyer_reference'
) and self._check_required_fields(vals['vals'], 'order_reference') else None,
}
if vals['supplier'].country_id.code == 'NL':
constraints.update({
# [NL-R-001] For suppliers in the Netherlands, if the document is a creditnote, the document MUST contain
# an invoice reference (cac:BillingReference/cac:InvoiceDocumentReference/cbc:ID)
'nl_r_001': self._check_required_fields(invoice, 'ref') if 'refund' in invoice.move_type else '',
# [NL-R-002] For suppliers in the Netherlands the supplier’s address (cac:AccountingSupplierParty/cac:Party
# /cac:PostalAddress) MUST contain street name (cbc:StreetName), city (cbc:CityName) and post code (cbc:PostalZone)
'nl_r_002_street': self._check_required_fields(vals['supplier'], 'street'),
'nl_r_002_zip': self._check_required_fields(vals['supplier'], 'zip'),
'nl_r_002_city': self._check_required_fields(vals['supplier'], 'city'),
# [NL-R-003] For suppliers in the Netherlands, the legal entity identifier MUST be either a
# KVK or OIN number (schemeID 0106 or 0190)
'nl_r_003': _(
"The supplier %s must have a KVK or OIN number.",
vals['supplier'].display_name
) if 'l10n_nl_oin' not in vals['supplier']._fields or 'l10n_nl_kvk' not in vals['supplier']._fields else '',
# [NL-R-007] For suppliers in the Netherlands, the supplier MUST provide a means of payment
# (cac:PaymentMeans) if the payment is from customer to supplier
'nl_r_007': self._check_required_fields(invoice, 'partner_bank_id')
})
if vals['customer'].country_id.code == 'NL':
constraints.update({
# [NL-R-004] For suppliers in the Netherlands, if the customer is in the Netherlands, the customer
# address (cac:AccountingCustomerParty/cac:Party/cac:PostalAddress) MUST contain the street name
# (cbc:StreetName), the city (cbc:CityName) and post code (cbc:PostalZone)
'nl_r_004_street': self._check_required_fields(vals['customer'], 'street'),
'nl_r_004_city': self._check_required_fields(vals['customer'], 'city'),
'nl_r_004_zip': self._check_required_fields(vals['customer'], 'zip'),
# [NL-R-005] For suppliers in the Netherlands, if the customer is in the Netherlands,
# the customer’s legal entity identifier MUST be either a KVK or OIN number (schemeID 0106 or 0190)
'nl_r_005': _(
"The customer %s must have a KVK or OIN number.",
vals['customer'].display_name
) if 'l10n_nl_oin' not in vals['customer']._fields or 'l10n_nl_kvk' not in vals['customer']._fields else '',
})
if vals['supplier'].country_id.code == 'NO':
vat = vals['supplier'].vat
constraints.update({
# NO-R-001: For Norwegian suppliers, a VAT number MUST be the country code prefix NO followed by a
# valid Norwegian organization number (nine numbers) followed by the letters MVA.
# Note: mva.is_valid("179728982MVA") is True while it lacks the NO prefix
'no_r_001': _(
"The VAT number of the supplier does not seem to be valid. It should be of the form: NO179728982MVA."
) if not mva.is_valid(vat) or len(vat) != 14 or vat[:2] != 'NO' or vat[-3:] != 'MVA' else "",
'no_supplier_bronnoysund': _(
"The supplier %s must have a Bronnoysund company registry.",
vals['supplier'].display_name
) if 'l10n_no_bronnoysund_number' not in vals['supplier']._fields or not vals['supplier'].l10n_no_bronnoysund_number else "",
})
if vals['customer'].country_id.code == 'NO':
constraints.update({
'no_customer_bronnoysund': _(
"The supplier %s must have a Bronnoysund company registry.",
vals['customer'].display_name
) if 'l10n_no_bronnoysund_number' not in vals['customer']._fields or not vals['customer'].l10n_no_bronnoysund_number else "",
})
return constraints
| 51.554324
| 23,251
|
35,985
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import _, models
from odoo.tools import float_repr
from odoo.tests.common import Form
from odoo.exceptions import UserError, ValidationError
from odoo.tools.float_utils import float_round
from odoo.tools.misc import formatLang
from zeep import Client
# -------------------------------------------------------------------------
# UNIT OF MEASURE
# -------------------------------------------------------------------------
UOM_TO_UNECE_CODE = {
'uom.product_uom_unit': 'C62',
'uom.product_uom_dozen': 'DZN',
'uom.product_uom_kgm': 'KGM',
'uom.product_uom_gram': 'GRM',
'uom.product_uom_day': 'DAY',
'uom.product_uom_hour': 'HUR',
'uom.product_uom_ton': 'TNE',
'uom.product_uom_meter': 'MTR',
'uom.product_uom_km': 'KTM',
'uom.product_uom_cm': 'CMT',
'uom.product_uom_litre': 'LTR',
'uom.product_uom_cubic_meter': 'MTQ',
'uom.product_uom_lb': 'LBR',
'uom.product_uom_oz': 'ONZ',
'uom.product_uom_inch': 'INH',
'uom.product_uom_foot': 'FOT',
'uom.product_uom_mile': 'SMI',
'uom.product_uom_floz': 'OZA',
'uom.product_uom_qt': 'QT',
'uom.product_uom_gal': 'GLL',
'uom.product_uom_cubic_inch': 'INQ',
'uom.product_uom_cubic_foot': 'FTQ',
}
# -------------------------------------------------------------------------
# ELECTRONIC ADDRESS SCHEME (EAS), see https://docs.peppol.eu/poacc/billing/3.0/codelist/eas/
# -------------------------------------------------------------------------
COUNTRY_EAS = {
'HU': 9910,
'AT': 9915,
'ES': 9920,
'AD': 9922,
'AL': 9923,
'BA': 9924,
'BE': 9925,
'BG': 9926,
'CH': 9927,
'CY': 9928,
'CZ': 9929,
'DE': 9930,
'EE': 9931,
'GB': 9932,
'GR': 9933,
'HR': 9934,
'IE': 9935,
'IT': '0211',
'LI': 9936,
'LT': 9937,
'LU': 9938,
'LV': 9939,
'MC': 9940,
'ME': 9941,
'MK': 9942,
'MT': 9943,
'NL': 9944,
'PL': 9945,
'PT': 9946,
'RO': 9947,
'RS': 9948,
'SI': 9949,
'SK': 9950,
'SM': 9951,
'TR': 9952,
'VA': 9953,
'SE': 9955,
'FR': 9957,
'NO': '0192',
'SG': '0195',
'AU': '0151',
'FI': '0213',
}
class AccountEdiCommon(models.AbstractModel):
_name = "account.edi.common"
_description = "Common functions for EDI documents: generate the data, the constraints, etc"
# -------------------------------------------------------------------------
# HELPERS
# -------------------------------------------------------------------------
def format_float(self, amount, precision_digits):
if amount is None:
return None
return float_repr(float_round(amount, precision_digits), precision_digits)
def _get_uom_unece_code(self, line):
"""
list of codes: https://docs.peppol.eu/poacc/billing/3.0/codelist/UNECERec20/
or https://unece.org/fileadmin/DAM/cefact/recommendations/bkup_htm/add2c.htm (sorted by letter)
"""
xmlid = line.product_uom_id.get_external_id()
if xmlid and line.product_uom_id.id in xmlid:
return UOM_TO_UNECE_CODE.get(xmlid[line.product_uom_id.id], 'C62')
return 'C62'
# -------------------------------------------------------------------------
# TAXES
# -------------------------------------------------------------------------
def _validate_taxes(self, invoice):
""" Validate the structure of the tax repartition lines (invalid structure could lead to unexpected results)
"""
for tax in invoice.invoice_line_ids.tax_ids:
try:
tax._validate_repartition_lines()
except ValidationError as e:
error_msg = _("Tax '%s' is invalid: %s", tax.name, e.args[0]) # args[0] gives the error message
raise ValidationError(error_msg)
def _get_tax_unece_codes(self, invoice, tax):
"""
Source: doc of Peppol (but the CEF norm is also used by factur-x, yet not detailed)
https://docs.peppol.eu/poacc/billing/3.0/syntax/ubl-invoice/cac-TaxTotal/cac-TaxSubtotal/cac-TaxCategory/cbc-TaxExemptionReasonCode/
https://docs.peppol.eu/poacc/billing/3.0/codelist/vatex/
https://docs.peppol.eu/poacc/billing/3.0/codelist/UNCL5305/
:returns: {
tax_category_code: str,
tax_exemption_reason_code: str,
tax_exemption_reason: str,
}
"""
def create_dict(tax_category_code=None, tax_exemption_reason_code=None, tax_exemption_reason=None):
return {
'tax_category_code': tax_category_code,
'tax_exemption_reason_code': tax_exemption_reason_code,
'tax_exemption_reason': tax_exemption_reason,
}
supplier = invoice.company_id.partner_id.commercial_partner_id
customer = invoice.commercial_partner_id
# add Norway, Iceland, Liechtenstein
european_economic_area = self.env.ref('base.europe').country_ids.mapped('code') + ['NO', 'IS', 'LI']
if customer.country_id.code == 'ES' and customer.zip:
if customer.zip[:2] in ('35', '38'): # Canary
# [BR-IG-10]-A VAT breakdown (BG-23) with VAT Category code (BT-118) "IGIC" shall not have a VAT
# exemption reason code (BT-121) or VAT exemption reason text (BT-120).
return create_dict(tax_category_code='L')
if customer.zip[:2] in ('51', '52'):
return create_dict(tax_category_code='M') # Ceuta & Mellila
# see: https://anskaffelser.dev/postaward/g3/spec/current/billing-3.0/norway/#_value_added_tax_norwegian_mva
if customer.country_id.code == 'NO':
if tax.amount == 25:
return create_dict(tax_category_code='S', tax_exemption_reason=_('Output VAT, regular rate'))
if tax.amount == 15:
return create_dict(tax_category_code='S', tax_exemption_reason=_('Output VAT, reduced rate, middle'))
if tax.amount == 11.11:
return create_dict(tax_category_code='S', tax_exemption_reason=_('Output VAT, reduced rate, raw fish'))
if tax.amount == 12:
return create_dict(tax_category_code='S', tax_exemption_reason=_('Output VAT, reduced rate, low'))
if supplier.country_id == customer.country_id:
if not tax or tax.amount == 0:
# in theory, you should indicate the precise law article
return create_dict(tax_category_code='E', tax_exemption_reason=_('Articles 226 items 11 to 15 Directive 2006/112/EN'))
else:
return create_dict(tax_category_code='S') # standard VAT
if supplier.country_id.code in european_economic_area:
if tax.amount != 0:
# otherwise, the validator will complain because G and K code should be used with 0% tax
return create_dict(tax_category_code='S')
if customer.country_id.code not in european_economic_area:
return create_dict(
tax_category_code='G',
tax_exemption_reason_code='VATEX-EU-G',
tax_exemption_reason=_('Export outside the EU'),
)
if customer.country_id.code in european_economic_area:
return create_dict(
tax_category_code='K',
tax_exemption_reason_code='VATEX-EU-IC',
tax_exemption_reason=_('Intra-Community supply'),
)
if tax.amount != 0:
return create_dict(tax_category_code='S')
else:
return create_dict(tax_category_code='E', tax_exemption_reason=_('Articles 226 items 11 to 15 Directive 2006/112/EN'))
def _get_tax_category_list(self, invoice, taxes):
""" Full list: https://unece.org/fileadmin/DAM/trade/untdid/d16b/tred/tred5305.htm
Subset: https://docs.peppol.eu/poacc/billing/3.0/codelist/UNCL5305/
:param taxes: account.tax records.
:return: A list of values to fill the TaxCategory foreach template.
"""
res = []
for tax in taxes:
tax_unece_codes = self._get_tax_unece_codes(invoice, tax)
res.append({
'id': tax_unece_codes.get('tax_category_code'),
'percent': tax.amount if tax.amount_type == 'percent' else False,
'name': tax_unece_codes.get('tax_exemption_reason'),
**tax_unece_codes,
})
return res
# -------------------------------------------------------------------------
# CONSTRAINTS
# -------------------------------------------------------------------------
def _check_required_fields(self, record, field_names, custom_warning_message=""):
"""
This function check that a field exists on a record or dictionaries
returns a generic error message if it's not the case or a custom one if specified
"""
if not record:
return custom_warning_message or _("The element %s is required on %s.", record, ', '.join(field_names))
if not isinstance(field_names, list):
field_names = [field_names]
has_values = any(record[field_name] for field_name in field_names)
# field is present
if has_values:
return
# field is not present
if custom_warning_message or isinstance(record, dict):
return custom_warning_message or _("The element %s is required on %s.", record, ', '.join(field_names))
display_field_names = record.fields_get(field_names)
if len(field_names) == 1:
display_field = f"'{display_field_names[field_names[0]]['string']}'"
return _("The field %s is required on %s.", display_field, record.display_name)
else:
display_fields = ', '.join(f"'{display_field_names[x]['string']}'" for x in display_field_names)
return _("At least one of the following fields %s is required on %s.", display_fields, record.display_name)
# -------------------------------------------------------------------------
# COMMON CONSTRAINTS
# -------------------------------------------------------------------------
def _invoice_constraints_common(self, invoice):
# check that there is a tax on each line
for line in invoice.invoice_line_ids.filtered(lambda x: not x.display_type):
if not line.tax_ids:
return {'tax_on_line': _("Each invoice line should have at least one tax.")}
return {}
# -------------------------------------------------------------------------
# Import invoice
# -------------------------------------------------------------------------
def _import_invoice(self, journal, filename, tree, existing_invoice=None):
move_types, qty_factor = self._get_import_document_amount_sign(filename, tree)
if not move_types:
return
if journal.type == 'purchase':
move_type = move_types[0]
elif journal.type == 'sale':
move_type = move_types[1]
else:
return
if existing_invoice and existing_invoice.move_type != move_type:
# with an email alias to create account_move, first the move is created (using alias_defaults, which
# contains move_type = 'out_invoice') then the attachment is decoded, if it represents a credit note,
# the move type needs to be changed to 'out_refund'
types = {move_type, existing_invoice.move_type}
if types == {'out_invoice', 'out_refund'} or types == {'in_invoice', 'in_refund'}:
existing_invoice.move_type = move_type
else:
return
invoice = existing_invoice or self.env['account.move']
invoice_form = Form(invoice.with_context(
account_predictive_bills_disable_prediction=True,
default_move_type=move_type,
default_journal_id=journal.id,
))
invoice_form, logs = self._import_fill_invoice_form(journal, tree, invoice_form, qty_factor)
invoice = invoice_form.save()
if invoice:
if logs:
body = _(
"<strong>Format used to import the invoice: %s</strong> <p><li> %s </li></p>",
str(self._description), "</li><li>".join(logs)
)
else:
body = _("<strong>Format used to import the invoice: %s</strong>", str(self._description))
invoice.with_context(no_new_invoice=True).message_post(body=body)
# === Import the embedded PDF in the xml if some are found ===
attachments = self.env['ir.attachment']
additional_docs = tree.findall('./{*}AdditionalDocumentReference')
for document in additional_docs:
attachment_name = document.find('{*}ID')
attachment_data = document.find('{*}Attachment/{*}EmbeddedDocumentBinaryObject')
if attachment_name is not None \
and attachment_data is not None \
and attachment_data.attrib.get('mimeCode') == 'application/pdf':
text = attachment_data.text
# Normalize the name of the file : some e-fff emitters put the full path of the file
# (Windows or Linux style) and/or the name of the xml instead of the pdf.
# Get only the filename with a pdf extension.
name = attachment_name.text.split('\\')[-1].split('/')[-1].split('.')[0] + '.pdf'
attachment = self.env['ir.attachment'].create({
'name': name,
'res_id': invoice.id,
'res_model': 'account.move',
'datas': text + '=' * (len(text) % 3), # Fix incorrect padding
'type': 'binary',
'mimetype': 'application/pdf',
})
# Upon receiving an email (containing an xml) with a configured alias to create invoice, the xml is
# set as the main_attachment. To be rendered in the form view, the pdf should be the main_attachment.
if invoice.message_main_attachment_id and \
invoice.message_main_attachment_id.name.endswith('.xml') and \
'pdf' not in invoice.message_main_attachment_id.mimetype:
invoice.message_main_attachment_id = attachment
attachments |= attachment
if attachments:
invoice.with_context(no_new_invoice=True).message_post(attachment_ids=attachments.ids)
return invoice
def _import_retrieve_and_fill_partner(self, invoice, name, phone, mail, vat, country_code=False):
""" Retrieve the partner, if no matching partner is found, create it (only if he has a vat and a name)
"""
invoice.partner_id = self.env['account.edi.format']._retrieve_partner(name=name, phone=phone, mail=mail, vat=vat)
if not invoice.partner_id and name and vat:
partner_vals = {'name': name, 'email': mail, 'phone': phone}
country = self.env.ref(f'base.{country_code.lower()}', raise_if_not_found=False) if country_code else False
if country:
partner_vals['country_id'] = country.id
invoice.partner_id = self.env['res.partner'].create(partner_vals)
if vat and self.env['res.partner']._run_vat_test(vat, country, invoice.partner_id.is_company):
invoice.partner_id.vat = vat
def _import_fill_invoice_allowance_charge(self, tree, invoice_form, journal, qty_factor):
logs = []
if '{urn:oasis:names:specification:ubl:schema:xsd' in tree.tag:
is_ubl = True
elif '{urn:un:unece:uncefact:data:standard:' in tree.tag:
is_ubl = False
else:
return
xpath = './{*}AllowanceCharge' if is_ubl else './{*}SupplyChainTradeTransaction/{*}ApplicableHeaderTradeSettlement/{*}SpecifiedTradeAllowanceCharge'
allowance_charge_nodes = tree.findall(xpath)
for allow_el in allowance_charge_nodes:
with invoice_form.invoice_line_ids.new() as invoice_line_form:
invoice_line_form.sequence = 0 # be sure to put these lines above the 'real' invoice lines
charge_factor = -1 # factor is -1 for discount, 1 for charge
if is_ubl:
charge_indicator_node = allow_el.find('./{*}ChargeIndicator')
else:
charge_indicator_node = allow_el.find('./{*}ChargeIndicator/{*}Indicator')
if charge_indicator_node is not None:
charge_factor = -1 if charge_indicator_node.text == 'false' else 1
name = ""
reason_code_node = allow_el.find('./{*}AllowanceChargeReasonCode' if is_ubl else './{*}ReasonCode')
if reason_code_node is not None:
name += reason_code_node.text + " "
reason_node = allow_el.find('./{*}AllowanceChargeReason' if is_ubl else './{*}Reason')
if reason_node is not None:
name += reason_node.text
invoice_line_form.name = name
amount_node = allow_el.find('./{*}Amount' if is_ubl else './{*}ActualAmount')
base_amount_node = allow_el.find('./{*}BaseAmount' if is_ubl else './{*}BasisAmount')
# Since there is no quantity associated for the allowance/charge on document level,
# if we have an invoice with negative amounts, the price was multiplied by -1 and not the quantity
# See the file in test_files: 'base-negative-inv-correction.xml' VS 'base-example.xml' for 'Insurance'
if base_amount_node is not None:
invoice_line_form.price_unit = float(base_amount_node.text) * charge_factor * qty_factor
percent_node = allow_el.find('./{*}MultiplierFactorNumeric' if is_ubl else './{*}CalculationPercent')
if percent_node is not None:
invoice_line_form.quantity = float(percent_node.text) / 100
elif amount_node is not None:
invoice_line_form.price_unit = float(amount_node.text) * charge_factor * qty_factor
invoice_line_form.tax_ids.clear() # clear the default taxes applied to the line
tax_xpath = './{*}TaxCategory/{*}Percent' if is_ubl else './{*}CategoryTradeTax/{*}RateApplicablePercent'
for tax_categ_percent_el in allow_el.findall(tax_xpath):
tax = self.env['account.tax'].search([
('company_id', '=', journal.company_id.id),
('amount', '=', float(tax_categ_percent_el.text)),
('amount_type', '=', 'percent'),
('type_tax_use', '=', journal.type),
], limit=1)
if tax:
invoice_line_form.tax_ids.add(tax)
else:
logs.append(
_("Could not retrieve the tax: %s %% for line '%s'.",
float(tax_categ_percent_el.text),
name)
)
return logs
def _import_fill_invoice_down_payment(self, invoice_form, prepaid_node, qty_factor):
"""
DEPRECATED: removed in master
Creates a down payment line on the invoice at import if prepaid_node (TotalPrepaidAmount in CII,
PrepaidAmount in UBL) exists.
qty_factor -1 if the xml is labelled as an invoice but has negative amounts -> conversion into a credit note
needed, so we need this multiplier. Otherwise, qty_factor is 1.
"""
if prepaid_node is not None and float(prepaid_node.text) != 0:
# create a section
with invoice_form.invoice_line_ids.new() as invoice_line_form:
invoice_line_form.sequence = 998
invoice_line_form.display_type = 'line_section'
invoice_line_form.name = _("Down Payments")
invoice_line_form.price_unit = 0
invoice_line_form.quantity = 0
invoice_line_form.account_id = self.env['account.account']
# create the line with the down payment
with invoice_form.invoice_line_ids.new() as invoice_line_form:
invoice_line_form.sequence = 999
invoice_line_form.name = _("Down Payment")
invoice_line_form.price_unit = float(prepaid_node.text)
invoice_line_form.quantity = qty_factor * -1
invoice_line_form.tax_ids.clear()
def _import_log_prepaid_amount(self, invoice_form, prepaid_node, qty_factor):
"""
Log a message in the chatter at import if prepaid_node (TotalPrepaidAmount in CII, PrepaidAmount in UBL) exists.
"""
prepaid_amount = float(prepaid_node.text) if prepaid_node is not None else 0.0
if not invoice_form.currency_id.is_zero(prepaid_amount):
amount = prepaid_amount * qty_factor
formatted_amount = formatLang(self.env, amount, currency_obj=invoice_form.currency_id)
return [
_("A payment of %s was detected.", formatted_amount)
]
return []
def _import_fill_invoice_line_values(self, tree, xpath_dict, invoice_line_form, qty_factor):
"""
Read the xml invoice, extract the invoice line values, compute the odoo values
to fill an invoice line form: quantity, price_unit, discount, product_uom_id.
The way of computing invoice line is quite complicated:
https://docs.peppol.eu/poacc/billing/3.0/bis/#_calculation_on_line_level (same as in factur-x documentation)
line_net_subtotal = ( gross_unit_price - rebate ) * (billed_qty / basis_qty) - allow_charge_amount
with (UBL | CII):
* net_unit_price = 'Price/PriceAmount' | 'NetPriceProductTradePrice' (mandatory) (BT-146)
* gross_unit_price = 'Price/AllowanceCharge/BaseAmount' | 'GrossPriceProductTradePrice' (optional) (BT-148)
* basis_qty = 'Price/BaseQuantity' | 'BasisQuantity' (optional, either below net_price node or
gross_price node) (BT-149)
* billed_qty = 'InvoicedQuantity' | 'BilledQuantity' (mandatory) (BT-129)
* allow_charge_amount = sum of 'AllowanceCharge' | 'SpecifiedTradeAllowanceCharge' (same level as Price)
ON THE LINE level (optional) (BT-136 / BT-141)
* line_net_subtotal = 'LineExtensionAmount' | 'LineTotalAmount' (mandatory) (BT-131)
* rebate = 'Price/AllowanceCharge' | 'AppliedTradeAllowanceCharge' below gross_price node ! (BT-147)
"item price discount" which is different from the usual allow_charge_amount
gross_unit_price (BT-148) - rebate (BT-147) = net_unit_price (BT-146)
In Odoo, we obtain:
(1) = price_unit = gross_price_unit / basis_qty = (net_price_unit + rebate) / basis_qty
(2) = quantity = billed_qty
(3) = discount (converted into a percentage) = 100 * (1 - price_subtotal / (billed_qty * price_unit))
(4) = price_subtotal
Alternatively, we could also set: quantity = billed_qty/basis_qty
WARNING, the basis quantity parameter is annoying, for instance, an invoice with a line:
item A | price per unit of measure/unit price: 30 | uom = 3 pieces | billed qty = 3 | rebate = 2 | untaxed total = 28
Indeed, 30 $ / 3 pieces = 10 $ / piece => 10 * 3 (billed quantity) - 2 (rebate) = 28
UBL ROUNDING: "the result of Item line net
amount = ((Item net price (BT-146)÷Item price base quantity (BT-149))×(Invoiced Quantity (BT-129))
must be rounded to two decimals, and the allowance/charge amounts are also rounded separately."
It is not possible to do it in Odoo.
:params tree
:params xpath_dict dict: {
'basis_qty': list of str,
'gross_price_unit': str,
'rebate': str,
'net_price_unit': str,
'billed_qty': str,
'allowance_charge': str, to be used in a findall !,
'allowance_charge_indicator': str, relative xpath from allowance_charge,
'allowance_charge_amount': str, relative xpath from allowance_charge,
'line_total_amount': str,
}
:params: invoice_line_form
:params: qty_factor
:returns: {
'quantity': float,
'product_uom_id': (optional) uom.uom,
'price_unit': float,
'discount': float,
}
"""
# basis_qty (optional)
basis_qty = 1
for xpath in xpath_dict['basis_qty']:
basis_quantity_node = tree.find(xpath)
if basis_quantity_node is not None:
basis_qty = float(basis_quantity_node.text)
# gross_price_unit (optional)
gross_price_unit = None
gross_price_unit_node = tree.find(xpath_dict['gross_price_unit'])
if gross_price_unit_node is not None:
gross_price_unit = float(gross_price_unit_node.text)
# rebate (optional)
# Discount. /!\ as no percent discount can be set on a line, need to infer the percentage
# from the amount of the actual amount of the discount (the allowance charge)
rebate = 0
rebate_node = tree.find(xpath_dict['rebate'])
net_price_unit_node = tree.find(xpath_dict['net_price_unit'])
if rebate_node is not None:
rebate = float(rebate_node.text)
elif net_price_unit_node is not None and gross_price_unit_node is not None:
rebate = float(gross_price_unit_node.text) - float(net_price_unit_node.text)
# net_price_unit (mandatory)
net_price_unit = None
if net_price_unit_node is not None:
net_price_unit = float(net_price_unit_node.text)
# billed_qty (mandatory)
billed_qty = 1
product_uom_id = None
quantity_node = tree.find(xpath_dict['billed_qty'])
if quantity_node is not None:
billed_qty = float(quantity_node.text)
uom_xml = quantity_node.attrib.get('unitCode')
if uom_xml:
uom_infered_xmlid = [
odoo_xmlid for odoo_xmlid, uom_unece in UOM_TO_UNECE_CODE.items() if uom_unece == uom_xml
]
if uom_infered_xmlid:
product_uom_id = self.env.ref(uom_infered_xmlid[0], raise_if_not_found=False)
# allow_charge_amount
fixed_taxes_list = []
allow_charge_amount = 0 # if positive: it's a discount, if negative: it's a charge
allow_charge_nodes = tree.findall(xpath_dict['allowance_charge'])
for allow_charge_el in allow_charge_nodes:
charge_indicator = allow_charge_el.find(xpath_dict['allowance_charge_indicator'])
if charge_indicator.text and charge_indicator.text.lower() == 'false':
discount_factor = 1 # it's a discount
else:
discount_factor = -1 # it's a charge
amount = allow_charge_el.find(xpath_dict['allowance_charge_amount'])
reason_code = allow_charge_el.find(xpath_dict['allowance_charge_reason_code'])
reason = allow_charge_el.find(xpath_dict['allowance_charge_reason'])
if amount is not None:
if reason_code is not None and reason_code.text == 'AEO' and reason is not None:
# Handle Fixed Taxes: when exporting from Odoo, we use the allowance_charge node
fixed_taxes_list.append({
'tax_name': reason.text,
'tax_amount': float(amount.text),
})
else:
allow_charge_amount += float(amount.text) * discount_factor
# line_net_subtotal (mandatory)
price_subtotal = None
line_total_amount_node = tree.find(xpath_dict['line_total_amount'])
if line_total_amount_node is not None:
price_subtotal = float(line_total_amount_node.text)
####################################################
# Setting the values on the invoice_line_form
####################################################
# quantity
quantity = billed_qty * qty_factor
# price_unit
if gross_price_unit is not None:
price_unit = gross_price_unit / basis_qty
elif net_price_unit is not None:
price_unit = (net_price_unit + rebate) / basis_qty
else:
raise UserError(_("No gross price nor net price found for line in xml"))
# discount
discount = 0
amount_fixed_taxes = sum(d['tax_amount'] for d in fixed_taxes_list)
if billed_qty * price_unit != 0 and price_subtotal is not None:
discount = 100 * (1 - (price_subtotal - amount_fixed_taxes) / (billed_qty * price_unit))
# Sometimes, the xml received is very bad: unit price = 0, qty = 1, but price_subtotal = -200
# for instance, when filling a down payment as an invoice line. The equation in the docstring is not
# respected, and the result will not be correct, so we just follow the simple rule below:
if net_price_unit == 0 and price_subtotal != net_price_unit * (billed_qty / basis_qty) - allow_charge_amount:
price_unit = price_subtotal / (billed_qty or 1)
return {
'quantity': quantity,
'price_unit': price_unit,
'discount': discount,
'product_uom_id': product_uom_id,
'fixed_taxes_list': fixed_taxes_list,
}
def _import_retrieve_fixed_tax(self, invoice_line_form, fixed_tax_vals):
""" Retrieve the fixed tax at import, iteratively search for a tax:
1. not price_include matching the name and the amount
2. not price_include matching the amount
3. price_include matching the name and the amount
4. price_include matching the amount
"""
base_domain = [
('company_id', '=', invoice_line_form.company_id.id),
('amount_type', '=', 'fixed'),
('amount', '=', fixed_tax_vals['tax_amount']),
]
for price_include in (False, True):
for name in (fixed_tax_vals['tax_name'], False):
domain = base_domain + [('price_include', '=', price_include)]
if name:
domain.append(('name', '=', name))
tax = self.env['account.tax'].search(domain, limit=1)
if tax:
return tax
return self.env['account.tax']
def _import_fill_invoice_line_taxes(self, journal, tax_nodes, invoice_line_form, inv_line_vals, logs):
# Taxes: all amounts are tax excluded, so first try to fetch price_include=False taxes,
# if no results, try to fetch the price_include=True taxes. If results, need to adapt the price_unit.
inv_line_vals['taxes'] = []
for tax_node in tax_nodes:
amount = float(tax_node.text)
domain = [
('company_id', '=', journal.company_id.id),
('amount_type', '=', 'percent'),
('type_tax_use', '=', journal.type),
('amount', '=', amount),
]
tax_excl = self.env['account.tax'].search(domain + [('price_include', '=', False)], limit=1)
tax_incl = self.env['account.tax'].search(domain + [('price_include', '=', True)], limit=1)
if tax_excl:
inv_line_vals['taxes'].append(tax_excl)
elif tax_incl:
inv_line_vals['taxes'].append(tax_incl)
inv_line_vals['price_unit'] *= (1 + tax_incl.amount / 100)
else:
logs.append(_("Could not retrieve the tax: %s %% for line '%s'.", amount, invoice_line_form.name))
# Handle Fixed Taxes
for fixed_tax_vals in inv_line_vals['fixed_taxes_list']:
tax = self._import_retrieve_fixed_tax(invoice_line_form, fixed_tax_vals)
if not tax:
# Nothing found: fix the price_unit s.t. line subtotal is matching the original invoice
inv_line_vals['price_unit'] += fixed_tax_vals['tax_amount']
elif tax.price_include:
inv_line_vals['taxes'].append(tax)
inv_line_vals['price_unit'] += tax.amount
else:
inv_line_vals['taxes'].append(tax)
# Set the values on the line_form
invoice_line_form.quantity = inv_line_vals['quantity']
if inv_line_vals.get('product_uom_id'):
invoice_line_form.product_uom_id = inv_line_vals['product_uom_id']
else:
logs.append(
_("Could not retrieve the unit of measure for line with label '%s'.", invoice_line_form.name))
invoice_line_form.price_unit = inv_line_vals['price_unit']
invoice_line_form.discount = inv_line_vals['discount']
invoice_line_form.tax_ids.clear()
for tax in inv_line_vals['taxes']:
invoice_line_form.tax_ids.add(tax)
return logs
# -------------------------------------------------------------------------
# Check xml using the free API from Ph. Helger, don't abuse it !
# -------------------------------------------------------------------------
def _check_xml_ecosio(self, invoice, xml_content, ecosio_formats):
# see https://peppol.helger.com/public/locale-en_US/menuitem-validation-ws2
if not ecosio_formats:
return
soap_client = Client('https://peppol.helger.com/wsdvs?wsdl')
if invoice.move_type == 'out_invoice':
ecosio_format = ecosio_formats['invoice']
elif invoice.move_type == 'out_refund':
ecosio_format = ecosio_formats['credit_note']
else:
invoice.with_context(no_new_invoice=True).message_post(
body="ECOSIO: could not validate xml, formats only exist for invoice or credit notes"
)
return
if not ecosio_format:
return
response = soap_client.service.validate(xml_content, ecosio_format)
report = []
errors_cnt = 0
for item in response['Result']:
if item['artifactPath']:
report.append(
"<li><font style='color:Blue;'><strong>" + item['artifactPath'] + "</strong></font></li>")
for detail in item['Item']:
if detail['errorLevel'] == 'WARN':
errors_cnt += 1
report.append(
"<li><font style='color:Orange;'><strong>" + detail['errorText'] + "</strong></font></li>")
elif detail['errorLevel'] == 'ERROR':
errors_cnt += 1
report.append(
"<li><font style='color:Tomato;'><strong>" + detail['errorText'] + "</strong></font></li>")
if errors_cnt == 0:
invoice.with_context(no_new_invoice=True).message_post(
body=f"<font style='color:Green;'><strong>ECOSIO: All clear for format {ecosio_format}!</strong></font>"
)
else:
invoice.with_context(no_new_invoice=True).message_post(
body=f"<font style='color:Tomato;'><strong>ECOSIO ERRORS/WARNINGS for format {ecosio_format}</strong></font>: <ul> "
+ "\n".join(report) + " </ul>"
)
return response
| 48.823609
| 35,983
|
4,100
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class AccountEdiXmlUBLNL(models.AbstractModel):
_inherit = "account.edi.xml.ubl_bis3"
_name = 'account.edi.xml.ubl_nl'
_description = "SI-UBL 2.0 (NLCIUS)"
"""
SI-UBL 2.0 (NLCIUS) and UBL Bis 3 are 2 different formats used in the Netherlands.
(source: https://github.com/peppolautoriteit-nl/publications/tree/master/NLCIUS-PEPPOLBIS-Differences)
NLCIUS defines a set of rules
(source: https://www.softwarepakketten.nl/wiki_uitleg/60&bronw=7/Nadere_specificaties_EN_16931_1_norm_voor_de_Europese_kernfactuur.htm)
Fortunately, some of these rules are already present in UBL Bis 3, but some are missing.
For instance, Bis 3 states that the customizationID should be
"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0".
while in NLCIUS:
"urn:cen.eu:en16931:2017#compliant#urn:fdc:nen.nl:nlcius:v1.0".
Bis 3 and NLCIUS are thus incompatible. Hence, the two separate formats and the additional rules in this file.
The trick is to understand which rules are only NLCIUS specific and which are applied to the Bis 3 format.
"""
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
return f"{invoice.name.replace('/', '_')}_nlcius.xml"
def _export_invoice_ecosio_schematrons(self):
return {
'invoice': 'org.simplerinvoicing:invoice:2.0.3.3',
'credit_note': 'org.simplerinvoicing:creditnote:2.0.3.3',
}
def _get_tax_category_list(self, invoice, taxes):
# EXTENDS account.edi.xml.ubl_bis3
vals_list = super()._get_tax_category_list(invoice, taxes)
for tax in vals_list:
# [BR-NL-35] The use of a tax exemption reason code (cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory
# /cbc:TaxExemptionReasonCode) is not recommended
tax.pop('tax_exemption_reason_code')
return vals_list
def _get_partner_address_vals(self, partner):
# EXTENDS account.edi.xml.ubl_bis3
vals = super()._get_partner_address_vals(partner)
# [BR-NL-28] The use of a country subdivision (cac:AccountingCustomerParty/cac:Party/cac:PostalAddress
# /cbc:CountrySubentity) is not recommended
vals.pop('country_subentity')
return vals
def _get_invoice_line_allowance_vals_list(self, line, tax_values_list=None):
# EXTENDS account.edi.xml.ubl_bis3
vals_list = super()._get_invoice_line_allowance_vals_list(line, tax_values_list=tax_values_list)
# [BR-NL-32] Use of Discount reason code ( AllowanceChargeReasonCode ) is not recommended.
# [BR-EN-34] Use of Charge reason code ( AllowanceChargeReasonCode ) is not recommended.
# Careful ! [BR-42]-Each Invoice line allowance (BG-27) shall have an Invoice line allowance reason (BT-139)
# or an Invoice line allowance reason code (BT-140).
for vals in vals_list:
if vals.get('allowance_charge_reason'):
vals.pop('allowance_charge_reason_code')
return vals_list
def _get_invoice_payment_means_vals_list(self, invoice):
# EXTENDS account.edi.xml.ubl_bis3
vals_list = super()._get_invoice_payment_means_vals_list(invoice)
# [BR-NL-29] The use of a payment means text (cac:PaymentMeans/cbc:PaymentMeansCode/@name) is not recommended
for vals in vals_list:
vals.pop('payment_means_code_attrs')
return vals_list
def _export_invoice_vals(self, invoice):
# EXTENDS account.edi.xml.ubl_bis3
vals = super()._export_invoice_vals(invoice)
vals['vals']['customization_id'] = 'urn:cen.eu:en16931:2017#compliant#urn:fdc:nen.nl:nlcius:v1.0'
# [BR-NL-24] Use of previous invoice date ( IssueDate ) is not recommended.
# vals['vals'].pop('issue_date') # careful, this causes other errors from the validator...
return vals
| 47.126437
| 4,100
|
728
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
import re
class AccountEdiXmlUBLEFFF(models.AbstractModel):
_inherit = "account.edi.xml.ubl_20"
_name = 'account.edi.xml.ubl_efff'
_description = "E-FFF (BE)"
# -------------------------------------------------------------------------
# EXPORT
# -------------------------------------------------------------------------
def _export_invoice_filename(self, invoice):
# official naming convention
vat = invoice.company_id.partner_id.commercial_partner_id.vat
return 'efff_%s%s%s.xml' % (vat or '', '_' if vat else '', re.sub(r'[\W_]', '', invoice.name))
def _export_invoice_ecosio_schematrons(self):
return None
| 31.652174
| 728
|
1,062
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Proxy features for account_edi',
'description': """
This module adds generic features to register an Odoo DB on the proxy responsible for receiving data (via requests from web-services).
- An edi_proxy_user has a unique identification on a specific format (for example, the vat for Peppol) which
allows to identify him when receiving a document addressed to him. It is linked to a specific company on a specific
Odoo database.
- Encryption features allows to decrypt all the user's data when receiving it from the proxy.
- Authentication offers an additionnal level of security to avoid impersonification, in case someone gains to the user's database.
""",
'version': '1.0',
'category': 'Accounting/Accounting',
'depends': ['account_edi'],
'external_dependencies': {
'python': ['cryptography']
},
'data': [
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'license': 'LGPL-3',
'post_init_hook': '_create_demo_config_param',
}
| 42.48
| 1,062
|
1,005
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
class AccountEdiFormat(models.Model):
_inherit = 'account.edi.format'
# -------------------------------------------------------------------------
# Helpers
# -------------------------------------------------------------------------
def _get_proxy_user(self, company):
'''Returns the proxy_user associated with this edi format.
'''
self.ensure_one()
return company.account_edi_proxy_client_ids.filtered(lambda u: u.edi_format_id == self)
# -------------------------------------------------------------------------
# To override
# -------------------------------------------------------------------------
def _get_proxy_identification(self, company):
'''Returns the key that will identify company uniquely for this edi format (for example, the vat)
or raises a UserError (if the user didn't fill the related field).
TO OVERRIDE
'''
return False
| 37.222222
| 1,005
|
10,127
|
py
|
PYTHON
|
15.0
|
from odoo import models, fields, _
from odoo.exceptions import UserError
from .account_edi_proxy_auth import OdooEdiProxyAuth
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.fernet import Fernet
from psycopg2 import OperationalError
import requests
import uuid
import base64
import logging
_logger = logging.getLogger(__name__)
DEFAULT_SERVER_URL = 'https://l10n-it-edi.api.odoo.com'
DEFAULT_TEST_SERVER_URL = 'https://iap-services-test.odoo.com'
TIMEOUT = 30
class AccountEdiProxyError(Exception):
def __init__(self, code, message=False):
self.code = code
self.message = message
super().__init__(message or code)
class AccountEdiProxyClientUser(models.Model):
"""Represents a user of the proxy for an electronic invoicing format.
An edi_proxy_user has a unique identification on a specific format (for example, the vat for Peppol) which
allows to identify him when receiving a document addressed to him. It is linked to a specific company on a specific
Odoo database.
It also owns a key with which each file should be decrypted with (the proxy encrypt all the files with the public key).
"""
_name = 'account_edi_proxy_client.user'
_description = 'Account EDI proxy user'
active = fields.Boolean(default=True)
id_client = fields.Char(required=True, index=True)
company_id = fields.Many2one('res.company', string='Company', required=True,
default=lambda self: self.env.company)
edi_format_id = fields.Many2one('account.edi.format', required=True)
edi_format_code = fields.Char(related='edi_format_id.code', readonly=True)
edi_identification = fields.Char(required=True, help="The unique id that identifies this user for on the edi format, typically the vat")
private_key = fields.Binary(required=True, attachment=False, groups="base.group_system", help="The key to encrypt all the user's data")
refresh_token = fields.Char(groups="base.group_system")
_sql_constraints = [
('unique_id_client', 'unique(id_client)', 'This id_client is already used on another user.'),
('unique_edi_identification_per_format', 'unique(edi_identification, edi_format_id)', 'This edi identification is already assigned to a user'),
]
def _get_demo_state(self):
demo_state = self.env['ir.config_parameter'].sudo().get_param('account_edi_proxy_client.demo', False)
return 'prod' if demo_state in ['prod', False] else 'test' if demo_state == 'test' else 'demo'
def _get_server_url(self):
return DEFAULT_TEST_SERVER_URL if self._get_demo_state() == 'test' else self.env['ir.config_parameter'].sudo().get_param('account_edi_proxy_client.edi_server_url', DEFAULT_SERVER_URL)
def _make_request(self, url, params=False):
''' Make a request to proxy and handle the generic elements of the reponse (errors, new refresh token).
'''
payload = {
'jsonrpc': '2.0',
'method': 'call',
'params': params or {},
'id': uuid.uuid4().hex,
}
if self._get_demo_state() == 'demo':
# Last barrier : in case the demo mode is not handled by the caller, we block access.
raise Exception("Can't access the proxy in demo mode")
try:
response = requests.post(
url,
json=payload,
timeout=TIMEOUT,
headers={'content-type': 'application/json'},
auth=OdooEdiProxyAuth(user=self)).json()
except (ValueError, requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.Timeout, requests.exceptions.HTTPError):
raise AccountEdiProxyError('connection_error',
_('The url that this service requested returned an error. The url it tried to contact was %s', url))
if 'error' in response:
message = _('The url that this service requested returned an error. The url it tried to contact was %s. %s', url, response['error']['message'])
if response['error']['code'] == 404:
message = _('The url that this service tried to contact does not exist. The url was %r', url)
raise AccountEdiProxyError('connection_error', message)
proxy_error = response['result'].pop('proxy_error', False)
if proxy_error:
error_code = proxy_error['code']
if error_code == 'refresh_token_expired':
self._renew_token()
if not self.env.context.get('test_skip_commit'):
self.env.cr.commit() # We do not want to lose it if in the _make_request below something goes wrong
return self._make_request(url, params)
if error_code == 'no_such_user':
# This error is also raised if the user didn't exchange data and someone else claimed the edi_identificaiton.
self.sudo().active = False
raise AccountEdiProxyError(error_code, proxy_error['message'] or False)
return response['result']
def _register_proxy_user(self, company, edi_format, edi_identification):
''' Generate the public_key/private_key that will be used to encrypt the file, send a request to the proxy
to register the user with the public key and create the user with the private key.
:param company: the company of the user.
:param edi_identification: The unique ID that identifies this user on this edi network and to which the files will be addressed.
Typically the vat.
'''
# public_exponent=65537 is a default value that should be used most of the time, as per the documentation of cryptography.
# key_size=2048 is considered a reasonable default key size, as per the documentation of cryptography.
# see https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_key = private_key.public_key()
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
if self._get_demo_state() == 'demo':
# simulate registration
response = {'id_client': f'demo{company.id}', 'refresh_token': 'demo'}
else:
try:
# b64encode returns a bytestring, we need it as a string
response = self._make_request(self._get_server_url() + '/iap/account_edi/1/create_user', params={
'dbuuid': company.env['ir.config_parameter'].get_param('database.uuid'),
'company_id': company.id,
'edi_format_code': edi_format.code,
'edi_identification': edi_identification,
'public_key': base64.b64encode(public_pem).decode()
})
except AccountEdiProxyError as e:
raise UserError(e.message)
if 'error' in response:
raise UserError(response['error'])
self.create({
'id_client': response['id_client'],
'company_id': company.id,
'edi_format_id': edi_format.id,
'edi_identification': edi_identification,
'private_key': base64.b64encode(private_pem),
'refresh_token': response['refresh_token'],
})
def _renew_token(self):
''' Request the proxy for a new refresh token.
Request to the proxy should be made with a refresh token that expire after 24h to avoid
that multiple database use the same credentials. When receiving an error for an expired refresh_token,
This method makes a request to get a new refresh token.
'''
try:
with self.env.cr.savepoint(flush=False):
self.env.cr.execute('SELECT * FROM account_edi_proxy_client_user WHERE id IN %s FOR UPDATE NOWAIT', [tuple(self.ids)])
except OperationalError as e:
if e.pgcode == '55P03':
return
raise e
response = self._make_request(self._get_server_url() + '/iap/account_edi/1/renew_token')
if 'error' in response:
# can happen if the database was duplicated and the refresh_token was refreshed by the other database.
# we don't want two database to be able to query the proxy with the same user
# because it could lead to not inconsistent data.
_logger.error(response['error'])
self.sudo().refresh_token = response['refresh_token']
def _decrypt_data(self, data, symmetric_key):
''' Decrypt the data. Note that the data is encrypted with a symmetric key, which is encrypted with an asymmetric key.
We must therefore decrypt the symmetric key.
:param data: The data to decrypt.
:param symmetric_key: The symmetric_key encrypted with self.private_key.public_key()
'''
private_key = serialization.load_pem_private_key(
base64.b64decode(self.sudo().private_key),
password=None,
backend=default_backend()
)
key = private_key.decrypt(
base64.b64decode(symmetric_key),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
f = Fernet(key)
return f.decrypt(base64.b64decode(data))
| 48.6875
| 10,127
|
1,836
|
py
|
PYTHON
|
15.0
|
import base64
import hashlib
import hmac
import json
import requests
import time
import werkzeug.urls
class OdooEdiProxyAuth(requests.auth.AuthBase):
""" For routes that needs to be authenticated and verified for access.
Allows:
1) to preserve the integrity of the message between the endpoints.
2) to check user access rights and account validity
3) to avoid that multiple database use the same credentials, via a refresh_token that expire after 24h.
"""
def __init__(self, user=False):
self.id_client = user and user.id_client or False
self.refresh_token = user and user.sudo().refresh_token or False
def __call__(self, request):
# We don't sign request that still don't have a id_client/refresh_token
if not self.id_client or not self.refresh_token:
return request
# craft the message (timestamp|url path|id_client|query params|body content)
msg_timestamp = int(time.time())
parsed_url = werkzeug.urls.url_parse(request.path_url)
body = request.body
if isinstance(body, bytes):
body = body.decode()
body = json.loads(body)
message = '%s|%s|%s|%s|%s' % (
msg_timestamp, # timestamp
parsed_url.path, # url path
self.id_client,
json.dumps(werkzeug.urls.url_decode(parsed_url.query), sort_keys=True), # url query params sorted by key
json.dumps(body, sort_keys=True)) # http request body
h = hmac.new(base64.b64decode(self.refresh_token), message.encode(), digestmod=hashlib.sha256)
request.headers.update({
'odoo-edi-client-id': self.id_client,
'odoo-edi-signature': h.hexdigest(),
'odoo-edi-timestamp': msg_timestamp,
})
return request
| 38.25
| 1,836
|
305
|
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 ResCompany(models.Model):
_inherit = 'res.company'
account_edi_proxy_client_ids = fields.One2many('account_edi_proxy_client.user', inverse_name='company_id')
| 33.888889
| 305
|
405
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.http import request
from odoo.addons.auth_signup.controllers.main import AuthSignupHome
class AddPolicyData(AuthSignupHome):
def get_auth_signup_config(self):
d = super(AddPolicyData, self).get_auth_signup_config()
d['password_minimum_length'] = request.env['ir.config_parameter'].sudo().get_param('auth_password_policy.minlength')
return d
| 40.5
| 405
|
374
|
py
|
PYTHON
|
15.0
|
{
'name': "Password Policy support for Signup",
'depends': ['auth_password_policy', 'auth_signup'],
'category': 'Hidden/Tools',
'auto_install': True,
'data': [
'views/signup_templates.xml',
],
'assets': {
'web.assets_frontend': [
'auth_password_policy_signup/static/**/*',
],
},
'license': 'LGPL-3',
}
| 24.933333
| 374
|
5,821
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name' : 'Invoicing',
'version' : '1.2',
'summary': 'Invoices & Payments',
'sequence': 10,
'description': """
Invoicing & Payments
====================
The specific and easy-to-use Invoicing system in Odoo allows you to keep track of your accounting, even when you are not an accountant. It provides an easy way to follow up on your vendors and customers.
You could use this simplified accounting in case you work with an (external) account to keep your books, and you still want to keep track of payments. This module also offers you an easy method of registering payments, without having to encode complete abstracts of account.
""",
'category': 'Accounting/Accounting',
'website': 'https://www.odoo.com/app/invoicing',
'images' : ['images/accounts.jpeg','images/bank_statement.jpeg','images/cash_register.jpeg','images/chart_of_accounts.jpeg','images/customer_invoice.jpeg','images/journal_entries.jpeg'],
'depends' : ['base_setup', 'product', 'analytic', 'portal', 'digest'],
'data': [
'security/account_security.xml',
'security/ir.model.access.csv',
'data/data_account_type.xml',
'data/account_data.xml',
'data/digest_data.xml',
'views/account_report.xml',
'data/mail_template_data.xml',
'views/account_payment_view.xml',
'wizard/account_automatic_entry_wizard_views.xml',
'wizard/account_unreconcile_view.xml',
'wizard/account_move_reversal_view.xml',
'wizard/account_resequence_views.xml',
'wizard/account_payment_register_views.xml',
'views/account_move_views.xml',
'wizard/setup_wizards_view.xml',
'wizard/pos_box.xml',
'views/account_account_type_views.xml',
'views/account_account_views.xml',
'views/account_group_views.xml',
'views/account_journal_views.xml',
'views/account_account_tag_views.xml',
'views/account_bank_statement_views.xml',
'views/account_reconcile_model_views.xml',
'views/account_tax_views.xml',
'views/account_full_reconcile_views.xml',
'views/account_payment_term_views.xml',
'views/account_chart_template_views.xml',
'views/res_partner_bank_views.xml',
'views/report_statement.xml',
'views/terms_template.xml',
'wizard/account_validate_move_view.xml',
'views/res_company_views.xml',
'views/product_view.xml',
'views/account_analytic_view.xml',
'views/report_invoice.xml',
'report/account_invoice_report_view.xml',
'views/account_cash_rounding_view.xml',
'wizard/account_report_common_view.xml',
'views/report_journal.xml',
'views/tax_adjustments.xml',
'wizard/wizard_tax_adjustments_view.xml',
'views/ir_module_views.xml',
'views/res_config_settings_views.xml',
'views/partner_view.xml',
'views/account_journal_dashboard_view.xml',
'views/account_portal_templates.xml',
'views/report_payment_receipt_templates.xml',
'views/account_onboarding_templates.xml',
'data/service_cron.xml',
'views/account_incoterms_view.xml',
'data/account_incoterms_data.xml',
'views/digest_views.xml',
'wizard/account_invoice_send_views.xml',
'views/account_tax_report_views.xml',
'report/account_hash_integrity_templates.xml',
'views/res_currency.xml',
'views/account_menuitem.xml',
'views/account_analytic_default_view.xml',
'wizard/account_tour_upload_bill.xml',
'wizard/accrued_orders.xml',
'views/bill_preview_template.xml',
],
'demo': [
'demo/account_demo.xml',
],
'installable': True,
'application': True,
'auto_install': False,
'post_init_hook': '_account_post_init',
'assets': {
'web._assets_primary_variables': [
'account/static/src/scss/variables.scss',
],
'web.assets_backend': [
'account/static/src/css/account_bank_and_cash.css',
'account/static/src/css/account.css',
'account/static/src/css/tax_totals.css',
'account/static/src/scss/account_reconciliation.scss',
'account/static/src/scss/account_journal_dashboard.scss',
'account/static/src/scss/account_dashboard.scss',
'account/static/src/scss/account_searchpanel.scss',
'account/static/src/scss/section_and_note_backend.scss',
'account/static/src/scss/account_activity.scss',
'account/static/src/js/account_payment_field.js',
'account/static/src/js/account_resequence_field.js',
'account/static/src/js/grouped_view_widget.js',
'account/static/src/js/mail_activity.js',
'account/static/src/js/tax_totals.js',
'account/static/src/js/section_and_note_fields_backend.js',
'account/static/src/js/tours/account.js',
'account/static/src/js/bills_upload.js',
'account/static/src/js/account_selection.js',
],
'web.assets_frontend': [
'account/static/src/js/account_portal_sidebar.js',
],
'web.assets_tests': [
'account/static/tests/tours/**/*',
],
'web.qunit_suite_tests': [
('after', 'web/static/tests/legacy/views/kanban_tests.js', 'account/static/tests/account_payment_field_tests.js'),
('after', 'web/static/tests/legacy/views/kanban_tests.js', 'account/static/tests/section_and_note_tests.js'),
],
'web.assets_qweb': [
'account/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 45.476563
| 5,821
|
16,560
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import logging
import time
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, Command
from odoo.exceptions import UserError, ValidationError
from odoo.tools.misc import file_open, formatLang
_logger = logging.getLogger(__name__)
class AccountChartTemplate(models.Model):
_inherit = "account.chart.template"
@api.model
def _get_demo_data(self):
"""Generate the demo data related to accounting."""
# This is a generator because data created here might be referenced by xml_id to data
# created later but defined in this same function.
yield self._get_demo_data_move()
yield self._get_demo_data_statement()
yield self._get_demo_data_reconcile_model()
yield self._get_demo_data_attachment()
yield self._get_demo_data_mail_message()
yield self._get_demo_data_mail_activity()
@api.model
def _get_demo_data_move(self):
cid = self.env.company.id
ref = self.env.ref
return ('account.move', {
f'{cid}_demo_invoice_1': {
'move_type': 'out_invoice',
'partner_id': ref('base.res_partner_12').id,
'invoice_user_id': ref('base.user_demo').id,
'invoice_payment_term_id': ref('account.account_payment_term_end_following_month').id,
'invoice_date': time.strftime('%Y-%m-01'),
'invoice_line_ids': [
Command.create({'product_id': ref('product.consu_delivery_02').id, 'quantity': 5}),
Command.create({'product_id': ref('product.consu_delivery_03').id, 'quantity': 5}),
],
},
f'{cid}_demo_invoice_2': {
'move_type': 'out_invoice',
'partner_id': ref('base.res_partner_2').id,
'invoice_user_id': False,
'invoice_date': time.strftime('%Y-%m-08'),
'invoice_line_ids': [
Command.create({'product_id': ref('product.consu_delivery_03').id, 'quantity': 5}),
Command.create({'product_id': ref('product.consu_delivery_01').id, 'quantity': 20}),
],
},
f'{cid}_demo_invoice_3': {
'move_type': 'out_invoice',
'partner_id': ref('base.res_partner_2').id,
'invoice_user_id': False,
'invoice_date': time.strftime('%Y-%m-08'),
'invoice_line_ids': [
Command.create({'product_id': ref('product.consu_delivery_01').id, 'quantity': 5}),
Command.create({'product_id': ref('product.consu_delivery_03').id, 'quantity': 5}),
],
},
f'{cid}_demo_invoice_followup': {
'move_type': 'out_invoice',
'partner_id': ref('base.res_partner_2').id,
'invoice_user_id': ref('base.user_demo').id,
'invoice_payment_term_id': ref('account.account_payment_term_immediate').id,
'invoice_date': (fields.Date.today() + timedelta(days=-15)).strftime('%Y-%m-%d'),
'invoice_line_ids': [
Command.create({'product_id': ref('product.consu_delivery_02').id, 'quantity': 5}),
Command.create({'product_id': ref('product.consu_delivery_03').id, 'quantity': 5}),
],
},
f'{cid}_demo_invoice_5': {
'move_type': 'in_invoice',
'partner_id': ref('base.res_partner_12').id,
'invoice_user_id': ref('base.user_demo').id,
'invoice_payment_term_id': ref('account.account_payment_term_end_following_month').id,
'invoice_date': time.strftime('%Y-%m-01'),
'invoice_line_ids': [
Command.create({'product_id': ref('product.product_delivery_01'), 'price_unit': 10.0, 'quantity': 1}),
Command.create({'product_id': ref('product.product_order_01'), 'price_unit': 4.0, 'quantity': 5}),
],
},
f'{cid}_demo_invoice_extract': {
'move_type': 'in_invoice',
'invoice_user_id': ref('base.user_demo').id,
},
f'{cid}_demo_invoice_equipment_purchase': {
'move_type': 'in_invoice',
'ref': 'INV/2018/0057',
'partner_id': ref('base.res_partner_12').id,
'invoice_user_id': False,
'invoice_date': '2018-09-17',
'invoice_line_ids': [
Command.create({'name': 'Redeem Reference Number: PO02529', 'quantity': 1, 'price_unit': 541.10}),
],
},
})
@api.model
def _get_demo_data_statement(self):
cid = self.env.company.id
ref = self.env.ref
return ('account.bank.statement', {
f'{cid}_demo_bank_statement_1': {
'journal_id': self.env['account.journal'].search([
('type', '=', 'bank'),
('company_id', '=', cid),
], limit=1).id,
'date': time.strftime('%Y')+'-01-01',
'balance_end_real': 9944.87,
'balance_start': 5103.0,
'line_ids': [
Command.create({
'payment_ref': time.strftime('INV/%Y/00002 and INV/%Y/00003'),
'amount': 1275.0,
'date': time.strftime('%Y-01-01'),
'partner_id': ref('base.res_partner_12').id
}),
Command.create({
'payment_ref': 'Bank Fees',
'amount': -32.58,
'date': time.strftime('%Y-01-01'),
}),
Command.create({
'payment_ref': 'Prepayment',
'amount': 650,
'date': time.strftime('%Y-01-01'),
'partner_id': ref('base.res_partner_12').id
}),
Command.create({
'payment_ref': time.strftime(f'First {formatLang(self.env, 2000, currency_obj=self.env.company.currency_id)} of invoice %Y/00001'),
'amount': 2000,
'date': time.strftime('%Y-01-01'),
'partner_id': ref('base.res_partner_12').id
}),
Command.create({
'payment_ref': 'Last Year Interests',
'amount': 102.78,
'date': time.strftime('%Y-01-01'),
}),
Command.create({
'payment_ref': time.strftime('INV/%Y/00002'),
'amount': 750,
'date': time.strftime('%Y-01-01'),
'partner_id': ref('base.res_partner_2').id
}),
Command.create({
'payment_ref': f'R:9772938 10/07 AX 9415116318 T:5 BRT: {formatLang(self.env, 96.67, currency_obj=self.env.company.currency_id)} C/ croip',
'amount': 96.67,
'date': time.strftime('%Y-01-01'),
}),
]
},
})
@api.model
def _get_demo_data_reconcile_model(self):
cid = self.env.company.id
return ('account.reconcile.model', {
f'{cid}_reconcile_from_label': {
'name': 'Line with Bank Fees',
'rule_type': 'writeoff_suggestion',
'match_label': 'contains',
'match_label_param': 'BRT',
'decimal_separator': ',',
'line_ids': [
Command.create({
'label': 'Due amount',
'account_id': self._get_demo_account(
'income',
'account.data_account_type_revenue',
self.env.company,
).id,
'amount_type': 'regex',
'amount_string': r'BRT: ([\d,]+)',
}),
Command.create({
'label': 'Bank Fees',
'account_id': self._get_demo_account(
'cost_of_goods_sold',
'account.data_account_type_direct_costs',
self.env.company,
).id,
'amount_type': 'percentage',
'amount_string': '100',
}),
]
},
})
@api.model
def _get_demo_data_attachment(self):
cid = self.env.company.id
ref = self.env.ref
return ('ir.attachment', {
f'{cid}_ir_attachment_bank_statement_1': {
'type': 'binary',
'name': 'bank_statement_yourcompany_demo.pdf',
'res_model': 'account.bank.statement',
'res_id': ref(f'account.{cid}_demo_bank_statement_1').id,
'raw': file_open(
'account/static/demo/bank_statement_yourcompany_1.pdf', 'rb'
).read()
},
f'{cid}_ir_attachment_in_invoice_1': {
'type': 'binary',
'name': 'in_invoice_yourcompany_demo.pdf',
'res_model': 'account.move',
'res_id': ref(f'account.{cid}_demo_invoice_extract').id,
'raw': file_open(
'account/static/demo/in_invoice_yourcompany_demo_1.pdf', 'rb'
).read()
},
f'{cid}_ir_attachment_in_invoice_2': {
'type': 'binary',
'name': 'in_invoice_yourcompany_demo.pdf',
'res_model': 'account.move',
'res_id': ref(f'account.{cid}_demo_invoice_equipment_purchase').id,
'raw': file_open(
'account/static/demo/in_invoice_yourcompany_demo_2.pdf', 'rb'
).read()
},
})
@api.model
def _get_demo_data_mail_message(self):
cid = self.env.company.id
ref = self.env.ref
return ('mail.message', {
f'{cid}_mail_message_bank_statement_1': {
'model': 'account.bank.statement',
'res_id': ref(f'account.{cid}_demo_bank_statement_1').id,
'body': 'Bank statement attachment',
'message_type': 'comment',
'author_id': ref('base.partner_demo').id,
'attachment_ids': [Command.set([
ref(f'account.{cid}_ir_attachment_bank_statement_1').id
])]
},
f'{cid}_mail_message_in_invoice_1': {
'model': 'account.move',
'res_id': ref(f'account.{cid}_demo_invoice_extract').id,
'body': 'Vendor Bill attachment',
'message_type': 'comment',
'author_id': ref('base.partner_demo').id,
'attachment_ids': [Command.set([
ref(f'account.{cid}_ir_attachment_in_invoice_1').id
])]
},
f'{cid}_mail_message_in_invoice_2': {
'model': 'account.move',
'res_id': ref(f'account.{cid}_demo_invoice_equipment_purchase').id,
'body': 'Vendor Bill attachment',
'message_type': 'comment',
'author_id': ref('base.partner_demo').id,
'attachment_ids': [Command.set([
ref(f'account.{cid}_ir_attachment_in_invoice_2').id
])]
},
})
@api.model
def _get_demo_data_mail_activity(self):
cid = self.env.company.id
ref = self.env.ref
return ('mail.activity', {
f'{cid}_invoice_activity_1': {
'res_id': ref(f'account.{cid}_demo_invoice_3').id,
'res_model_id': ref('account.model_account_move').id,
'activity_type_id': ref('mail.mail_activity_data_todo').id,
'date_deadline': (fields.Datetime.today() + relativedelta(days=5)).strftime('%Y-%m-%d %H:%M'),
'summary': 'Follow-up on payment',
'create_uid': ref('base.user_admin').id,
'user_id': ref('base.user_admin').id,
},
f'{cid}_invoice_activity_2': {
'res_id': ref(f'account.{cid}_demo_invoice_2').id,
'res_model_id': ref('account.model_account_move').id,
'activity_type_id': ref('mail.mail_activity_data_call').id,
'date_deadline': fields.Datetime.today().strftime('%Y-%m-%d %H:%M'),
'create_uid': ref('base.user_admin').id,
'user_id': ref('base.user_admin').id,
},
f'{cid}_invoice_activity_3': {
'res_id': ref(f'account.{cid}_demo_invoice_1').id,
'res_model_id': ref('account.model_account_move').id,
'activity_type_id': ref('mail.mail_activity_data_todo').id,
'date_deadline': (fields.Datetime.today() + relativedelta(days=5)).strftime('%Y-%m-%d %H:%M'),
'summary': 'Include upsell',
'create_uid': ref('base.user_admin').id,
'user_id': ref('base.user_admin').id,
},
f'{cid}_invoice_activity_4': {
'res_id': ref(f'account.{cid}_demo_invoice_extract').id,
'res_model_id': ref('account.model_account_move').id,
'activity_type_id': ref('mail.mail_activity_data_todo').id,
'date_deadline': (fields.Datetime.today() + relativedelta(days=5)).strftime('%Y-%m-%d %H:%M'),
'summary': 'Update address',
'create_uid': ref('base.user_admin').id,
'user_id': ref('base.user_admin').id,
},
})
@api.model
def _post_create_demo_data(self, created):
cid = self.env.company.id
if created._name == 'account.move':
created = created.with_context(check_move_validity=False)
# We need to recompute some onchanges. Invoice lines VS journal items are already
# synchronized in the create, but the onchange were not applied on the invoice lines.
for move in created:
move._onchange_partner_id()
created.line_ids._onchange_product_id()
created.line_ids._onchange_account_id()
created.line_ids._onchange_price_subtotal()
created._recompute_dynamic_lines(
recompute_all_taxes=True,
recompute_tax_base_amount=True,
)
# the invoice_extract acts like a placeholder for the OCR to be ran and doesn't contain
# any lines yet
for move in created - self.env.ref(f'account.{cid}_demo_invoice_extract'):
try:
move.action_post()
except (UserError, ValidationError):
_logger.exception('Error while posting demo data')
elif created._name == 'account.bank.statement':
created.button_post()
@api.model
def _get_demo_account(self, xml_id, user_type_id, company):
"""Find the most appropriate account possible for demo data creation.
:param xml_id (str): the xml_id of the account template in the generic coa
:param user_type_id (str): the full xml_id of the account type wanted
:param company (Model<res.company>): the company for which we search the account
:return (Model<account.account>): the most appropriate record found
"""
return (
self.env['account.account'].browse(self.env['ir.model.data'].sudo().search([
('name', '=', '%d_%s' % (company.id, xml_id)),
('model', '=', 'account.account'),
('module', '=like', 'l10n%')
], limit=1).res_id)
or self.env['account.account'].search([
('user_type_id', '=', self.env.ref(user_type_id).id),
('company_id', '=', company.id)
], limit=1)
or self.env['account.account'].search([('company_id', '=', company.id)], limit=1)
)
| 46.386555
| 16,560
|
11,335
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
"""Classes defining the populate factory for Journal Entries, Invoices and related models."""
from odoo import models, fields
from odoo.tools import populate
import logging
import math
from functools import lru_cache
from dateutil.relativedelta import relativedelta
_logger = logging.getLogger(__name__)
class AccountMove(models.Model):
"""Populate factory part for account.move.
Because of the complicated nature of the interraction of account.move and account.move.line,
both models are actualy generated in the same factory.
"""
_inherit = "account.move"
_populate_sizes = {
'small': 1000,
'medium': 10000,
'large': 500000,
}
_populate_dependencies = ['res.partner', 'account.journal']
def _populate_factories(self):
@lru_cache()
def search_account_ids(company_id, type=None, group=None):
"""Search all the accounts of a certain type and group for a company.
This method is cached, only one search is done per tuple(company_id, type, group).
:param company_id (int): the company to search accounts for.
:param type (str): the type to filter on. If not set, do not filter. Valid values are:
payable, receivable, liquidity, other, False.
:param group (str): the group to filter on. If not set, do not filter. Valid values are:
asset, liability, equity, off_balance, False.
:return (Model<account.account>): the recordset of accounts found.
"""
domain = [('company_id', '=', company_id)]
if type:
domain += [('internal_type', '=', type)]
if group:
domain += [('internal_group', '=', group)]
return self.env['account.account'].search(domain)
@lru_cache()
def search_journal_ids(company_id, journal_type):
"""Search all the journal of a certain type for a company.
This method is cached, only one search is done per tuple(company_id, journal_type).
:param company_id (int): the company to search journals for.
:param journal_type (str): the journal type to filter on.
Valid values are sale, purchase, cash, bank and general.
:return (list<int>): the ids of the journals of a company and a certain type
"""
return self.env['account.journal'].search([
('company_id', '=', company_id),
('type', '=', journal_type),
]).ids
@lru_cache()
def search_partner_ids(company_id):
"""Search all the partners that a company has access to.
This method is cached, only one search is done per company_id.
:param company_id (int): the company to search partners for.
:return (list<int>): the ids of partner the company has access to.
"""
return self.env['res.partner'].search([
'|', ('company_id', '=', company_id), ('company_id', '=', False),
('id', 'in', self.env.registry.populated_models['res.partner']),
]).ids
def get_invoice_date(values, **kwargs):
"""Get the invoice date date.
:param values (dict): the values already selected for the record.
:return (datetime.date, bool): the accounting date if it is an invoice (or similar) document
or False otherwise.
"""
if values['move_type'] in self.get_invoice_types(include_receipts=True):
return values['date']
return False
def get_lines(random, values, **kwargs):
"""Build the dictionary of account.move.line.
Generate lines depending on the move_type, company_id and currency_id.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return list: list of ORM create commands for the field line_ids
"""
def get_line(account, label, balance=None, balance_sign=False, exclude_from_invoice_tab=False):
company_currency = account.company_id.currency_id
currency = self.env['res.currency'].browse(currency_id)
balance = balance or balance_sign * round(random.uniform(0, 1000))
amount_currency = company_currency._convert(balance, currency, account.company_id, date)
return (0, 0, {
'name': 'label_%s' % label,
'debit': balance > 0 and balance or 0,
'credit': balance < 0 and -balance or 0,
'account_id': account.id,
'partner_id': partner_id,
'currency_id': currency_id,
'amount_currency': amount_currency,
'exclude_from_invoice_tab': exclude_from_invoice_tab,
})
move_type = values['move_type']
date = values['date']
company_id = values['company_id']
currency_id = values['currency_id']
partner_id = values['partner_id']
# Determine the right sets of accounts depending on the move_type
if move_type in self.get_sale_types(include_receipts=True):
account_ids = search_account_ids(company_id, 'other', 'income')
balance_account_ids = search_account_ids(company_id, 'receivable', 'asset')
elif move_type in self.get_purchase_types(include_receipts=True):
account_ids = search_account_ids(company_id, 'other', 'expense')
balance_account_ids = search_account_ids(company_id, 'payable', 'liability')
else:
account_ids = search_account_ids(company_id, 'other', 'asset')
balance_account_ids = account_ids
# Determine the right balance sign depending on the move_type
if move_type in self.get_inbound_types(include_receipts=True):
balance_sign = -1
elif move_type in self.get_outbound_types(include_receipts=True):
balance_sign = 1
else:
# balance sign will be alternating each line
balance_sign = False
# Add a random number of lines (between 1 and 20)
lines = [get_line(
account=random.choice(account_ids),
label=i,
balance_sign=balance_sign or (i % 2) or -1, # even -> negative, odd -> positive if balance_sign=False
) for i in range(random.randint(1, 20))]
# Add a last line containing the balance.
# For invoices, etc., it will be on the receivable/payable account.
lines += [get_line(
account=random.choice(balance_account_ids),
balance=sum(l[2]['credit'] - l[2]['debit'] for l in lines),
label='balance',
exclude_from_invoice_tab=move_type in self.get_invoice_types(include_receipts=True),
)]
return lines
def get_journal(random, values, **kwargs):
"""Get a random journal depending on the company and the move_type.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int): the id of the journal randomly selected
"""
move_type = values['move_type']
company_id = values['company_id']
if move_type in self.get_sale_types(include_receipts=True):
journal_type = 'sale'
elif move_type in self.get_purchase_types(include_receipts=True):
journal_type = 'purchase'
else:
journal_type = 'general'
journal = search_journal_ids(company_id, journal_type)
return random.choice(journal)
def get_partner(random, values, **kwargs):
"""Get a random partner depending on the company and the move_type.
The first 3/5 of the available partners are used as customer
The last 3/5 of the available partners are used as suppliers
It means 1/5 is both customer/supplier
-> Same proportions as in account.payment
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int, bool): the id of the partner randomly selected if it is an invoice document
False if it is a Journal Entry.
"""
move_type = values['move_type']
company_id = values['company_id']
partner_ids = search_partner_ids(company_id)
if move_type in self.get_sale_types(include_receipts=True):
return random.choice(partner_ids[:math.ceil(len(partner_ids)/5*2)])
if move_type in self.get_purchase_types(include_receipts=True):
return random.choice(partner_ids[math.floor(len(partner_ids)/5*2):])
return False
company_ids = self.env['res.company'].search([
('chart_template_id', '!=', False),
('id', 'in', self.env.registry.populated_models['res.company']),
])
return [
('move_type', populate.randomize(
['entry', 'in_invoice', 'out_invoice', 'in_refund', 'out_refund', 'in_receipt', 'out_receipt'],
[0.2, 0.3, 0.3, 0.07, 0.07, 0.03, 0.03],
)),
('company_id', populate.randomize(company_ids.ids)),
('currency_id', populate.randomize(self.env['res.currency'].search([
('active', '=', True),
]).ids)),
('journal_id', populate.compute(get_journal)),
('date', populate.randdatetime(relative_before=relativedelta(years=-4), relative_after=relativedelta(years=1))),
('invoice_date', populate.compute(get_invoice_date)),
('partner_id', populate.compute(get_partner)),
('line_ids', populate.compute(get_lines)),
]
def _populate(self, size):
records = super()._populate(size)
_logger.info('Posting Journal Entries')
to_post = records.filtered(lambda r: r.date < fields.Date.today())
to_post.action_post()
# TODO add some reconciliations. Not done initially because of perfs.
# _logger.info('Registering Payments for Invoices and Bills')
# random = populate.Random('account.move+register_payment')
# for invoice in to_post:
# if invoice.is_invoice() and random.uniform(0, 1) < 0.9: # 90% of invoices are at least partialy paid
# payment_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({})
# if random.uniform(0, 1) > 0.9: # 90% of paid invoices have the exact amount, others vary a little
# payment_wizard.amount *= random.uniform(0.5, 1.5)
# payment_wizard._create_payments()
return records
| 48.648069
| 11,335
|
4,204
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
"""Classes defining the populate factory for Bank Statements and related models."""
from odoo import models
from odoo.tools import populate
import logging
_logger = logging.getLogger(__name__)
class AccountReconcileModel(models.Model):
"""Populate factory part for account.reconcile.model."""
_inherit = "account.reconcile.model"
_populate_sizes = {
'small': 5,
'medium': 100,
'large': 1000,
}
_populate_dependencies = ['res.company']
def _populate_factories(self):
def get_name(counter, **kwargs):
return 'model_%s' % counter
company_ids = self.env['res.company'].search([
('chart_template_id', '!=', False),
('id', 'in', self.env.registry.populated_models['res.company']),
])
return [
('company_id', populate.cartesian(company_ids.ids)),
('rule_type', populate.cartesian(['writeoff_button', 'writeoff_suggestion'])),
# ('auto_reconcile', populate.cartesian([True, False], [0.1, 0.9])),
('name', populate.compute(get_name)),
]
class AccountReconcileModelLine(models.Model):
"""Populate factory part for account.reconcile.model.line."""
_inherit = "account.reconcile.model.line"
_populate_sizes = {
'small': 10,
'medium': 200,
'large': 2000,
}
_populate_dependencies = ['account.reconcile.model']
def _populate_factories(self):
def search_account_ids(company_id, type=None, group=None):
"""Search all the accounts of a certain type and group for a company.
This method is cached, only one search is done per tuple(company_id, type, group).
:param company_id (int): the company to search accounts for.
:param type (str): the type to filter on. If not set, do not filter. Valid values are:
payable, receivable, liquidity, other, False.
:param group (str): the group to filter on. If not set, do not filter. Valid values are:
asset, liability, equity, off_balance, False.
:return (Model<account.account>): the recordset of accounts found.
"""
domain = [('company_id', '=', company_id)]
if type:
domain += [('internal_type', '=', type)]
if group:
domain += [('internal_group', '=', group)]
return self.env['account.account'].search(domain)
def get_amount(random, values, **kwargs):
"""Get an amount dending on the amount_type.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int, str):
If amount_type is fixed, a random number between 1 and 1000
If amount type is percentage, a random number between 1 and 100
Else, amount_type is regex, a random regex out of 2
"""
if values['amount_type'] == 'fixed':
return '%s' % random.randint(1, 1000)
elif values['amount_type'] == 'percentage':
return '%s' % random.randint(1, 100)
else:
return random.choice([r'^invoice \d+ (\d+)$', r'xd no-(\d+)'])
def get_account(random, values, **kwargs):
"""Get a random account depending on the company.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int): the id of the account randomly selected
"""
company_id = self.env['account.reconcile.model'].browse(values['model_id']).company_id.id
return random.choice(search_account_ids(company_id).ids)
return [
('model_id', populate.cartesian(self.env.registry.populated_models['account.reconcile.model'])),
('amount_type', populate.randomize(['fixed', 'percentage', 'regex'])),
('amount_string', populate.compute(get_amount)),
('account_id', populate.compute(get_account)),
]
| 40.423077
| 4,204
|
1,198
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
"""Classes defining the populate factory for Accounting Journals and related models."""
import logging
from odoo import models
from odoo.tools import populate
_logger = logging.getLogger(__name__)
class AccountJournal(models.Model):
"""Populate factory part for account.journal."""
_inherit = "account.journal"
_populate_sizes = {
'small': 10,
'medium': 30,
'large': 100,
}
_populate_dependencies = ['res.company']
def _populate_factories(self):
company_ids = self.env['res.company'].search([
('chart_template_id', '!=', False),
('id', 'in', self.env.registry.populated_models['res.company']),
])
return [
('company_id', populate.cartesian(company_ids.ids)),
('type', populate.cartesian(['sale', 'purchase', 'cash', 'bank', 'general'])),
('currency_id', populate.randomize(self.env['res.currency'].search([
('active', '=', True),
]).ids + [False])),
('name', populate.constant("Journal {values[type]} {counter}")),
('code', populate.constant("{values[type]:.2}{counter}")),
]
| 34.228571
| 1,198
|
5,531
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
"""Classes defining the populate factory for Payments and related models."""
from odoo import models, fields
from odoo.tools import populate
from dateutil.relativedelta import relativedelta
import logging
import math
from functools import lru_cache
_logger = logging.getLogger(__name__)
class AccountPayment(models.Model):
"""Populate factory part for account.payment."""
_inherit = "account.payment"
_populate_sizes = {
'small': 100,
'medium': 5000,
'large': 50000,
}
_populate_dependencies = ['res.company', 'res.partner', 'account.journal']
def _populate_factories(self):
@lru_cache()
def search_partner_ids(company_id):
"""Search all the partners that a company has access to.
This method is cached, only one search is done per company_id.
:param company_id (int): the company to search partners for.
:return (list<int>): the ids of partner the company has access to.
"""
return self.env['res.partner'].search([
'|', ('company_id', '=', company_id), ('company_id', '=', False),
('id', 'in', self.env.registry.populated_models['res.partner']),
]).ids
@lru_cache()
def search_journal_ids(company_id):
"""Search all the journal of a certain type for a company.
This method is cached, only one search is done per company_id.
:param company_id (int): the company to search journals for.
:return (list<int>): the ids of the bank and cash journals of a company
"""
return self.env['account.journal'].search([
('company_id', '=', company_id),
('type', 'in', ('cash', 'bank')),
]).ids
@lru_cache()
def search_payment_method_line_ids(payment_type, journal):
"""Search all the payment methods of a certain type.
This method is cached, only one search is done per type.
:param payment_type (str): the type of payment method. Valid values are customer and supplier.
:param journal (int): the journal of the payment method.
:return list<int>: list of ids of payment methods of the selected type
"""
need_bank_account = self._get_method_codes_needing_bank_account()
other_blacklist = ['sdd']
return self.env['account.payment.method.line'].search([
('journal_id', '=', journal),
('payment_method_id.payment_type', '=', payment_type),
('code', 'not in', need_bank_account + other_blacklist),
]).ids
def get_partner(random, values, **kwargs):
"""Get a random partner depending on the company and the partner_type.
The first 3/5 of the available partners are used as customer
The last 3/5 of the available partners are used as suppliers
It means 1/5 is both customer/supplier
-> Same proportions as in account.move
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int): the id of the partner randomly selected.
"""
partner_type = values['partner_type']
company_id = values['company_id']
partner_ids = search_partner_ids(company_id)
if partner_type == 'customer':
return random.choice(partner_ids[:math.ceil(len(partner_ids)/5*2)])
else:
return random.choice(partner_ids[math.floor(len(partner_ids)/5*2):])
def get_journal(random, values, **kwargs):
"""Get a random bank or cash journal depending on the company.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int): the id of the journal randomly selected
"""
return random.choice(search_journal_ids(values['company_id']))
def get_payment_method_line(random, values, **kwargs):
"""Get the payment method depending on the payment type.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
"""
return random.choice(search_payment_method_line_ids(values['payment_type'], values['journal_id']))
company_ids = self.env['res.company'].search([
('chart_template_id', '!=', False),
('id', 'in', self.env.registry.populated_models['res.company']),
])
return [
('company_id', populate.cartesian(company_ids.ids)),
('payment_type', populate.cartesian(['inbound', 'outbound'])),
('partner_type', populate.cartesian(['customer', 'supplier'])),
('journal_id', populate.compute(get_journal)),
('payment_method_line_id', populate.compute(get_payment_method_line)),
('partner_id', populate.compute(get_partner)),
('amount', populate.randfloat(0, 1000)),
('date', populate.randdatetime(relative_before=relativedelta(years=-4))),
]
def _populate(self, size):
records = super()._populate(size)
_logger.info('Validating Payments')
records.move_id.filtered(lambda r: r.date < fields.Date.today()).action_post()
return records
| 43.896825
| 5,531
|
2,562
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
"""Classes extending the populate factory for Companies and related models.
Only adding specificities of basic accounting applications.
"""
from odoo import models, _
from odoo.tools import populate
from odoo.exceptions import UserError
import logging
from functools import lru_cache
_logger = logging.getLogger(__name__)
class ResCompany(models.Model):
"""Populate factory part for the accountings applications of res.company."""
_inherit = "res.company"
def _populate(self, size):
@lru_cache()
def search_coa_ids(currency_id):
return self.env['account.chart.template'].search([('currency_id', '=', currency_id)])
records = super()._populate(size)
_logger.info('Loading Chart Template')
default_chart_templates = self.env['account.chart.template'].search([], limit=1)
if not default_chart_templates:
# TODO install l10n_generic_coa ?
raise UserError(_(
"At least one localization is needed to be installed in order to populate the "
"database with accounting"
))
random = populate.Random('res.company+chart_template_selector')
# Load the a chart of accounts matching the currency of the company for the 3 first created companies
# We are loading an existing CoA and not populating it because:
# * it reflects best real use cases.
# * it allows checking reports by localization
# * the config is complete with try_loading(), no need to adapt when the model changes
# * it is way easier :-)
# We are loading only for 3 companies because:
# * It takes a few hundreds of a second to create account.move records in batch.
# Because we want to have a lot of entries for at least one company (in order to test
# reports, functions and widgets performances for instance), we can't afford to do it for
# a lot of companies.
# * it would be useless to have entries for all the companies, we can already do everything with
# entries in only a few (but multiple) companies.
# Note that we can still populate some new records on top of the CoA if it makes sense,
# like account.journal for instance.
for company in records[:3]:
chart_templates_cur = search_coa_ids(company.currency_id.id) or default_chart_templates
random.choice(chart_templates_cur).with_company(company.id).try_loading()
return records
| 46.581818
| 2,562
|
5,988
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
"""Classes defining the populate factory for Bank Statements and related models."""
from odoo import models
from odoo.tools import populate
from dateutil.relativedelta import relativedelta
from functools import lru_cache
from collections import defaultdict
import logging
_logger = logging.getLogger(__name__)
class AccountBankStatement(models.Model):
"""Populate factory part for account.bank.statements."""
_inherit = "account.bank.statement"
_populate_sizes = {
'small': 10,
'medium': 1000,
'large': 20000,
}
_populate_dependencies = ['account.journal', 'res.company']
def _populate_factories(self):
company_ids = self.env['res.company'].search([
('chart_template_id', '!=', False),
('id', 'in', self.env.registry.populated_models['res.company']),
])
journal_ids = self.env['account.journal'].search([
('company_id', 'in', company_ids.ids),
('type', 'in', ('cash', 'bank')),
]).ids
return [
('journal_id', populate.iterate(journal_ids)),
('name', populate.constant('statement_{counter}')),
('date', populate.randdatetime(relative_before=relativedelta(years=-4))),
]
class AccountBankStatementLine(models.Model):
"""Populate factory part for account.bank.statements.line."""
_inherit = "account.bank.statement.line"
_populate_sizes = {
'small': 100,
'medium': 10000,
'large': 200000,
}
_populate_dependencies = ['account.bank.statement', 'res.partner']
def _populate_factories(self):
@lru_cache()
def search_partner_ids(company_id):
"""Search all the partners that a company has access to.
This method is cached, only one search is done per company_id.
:param company_id (int): the company to search partners for.
:return (list<int>): the ids of partner the company has access to.
"""
return self.env['res.partner'].search([
'|', ('company_id', '=', company_id), ('company_id', '=', False),
('id', 'in', self.env.registry.populated_models['res.partner']),
]).ids
def get_partner(random, values, **kwargs):
"""Get a partner by selecting inside the list of partner a company has access to.
There is also a chance of having no partner set.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int): an id of a partner accessible by the company of the statement.
"""
company_id = self.env['account.bank.statement'].browse(values['statement_id']).company_id.id
partner = search_partner_ids(company_id)
return random.choices(partner + [False], [1/len(partner)] * len(partner) + [1])[0]
def get_date(random, values, **kwargs):
"""Get a date in the past.
This date can but up to 31 days before the statement linked to this line.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (datetime.date): a date up to 31 days before the date of the statement.
"""
statement_date = self.env['account.bank.statement'].browse(values['statement_id']).date
return statement_date + relativedelta(days=random.randint(-31, 0))
def get_amount(random, **kwargs):
"""Get a random amount between -1000 and 1000.
It is impossible to get a null amount. Because it would not be a valid statement line.
:param random: seeded random number generator.
:return (float): a number between -1000 and 1000.
"""
return random.uniform(-1000, 1000) or 1
def get_currency(random, values, **kwargs):
"""Get a randome currency.
The currency has to be empty if it is the same as the currency of the statement's journal's.
:param random: seeded random number generator.
:param values (dict): the values already selected for the record.
:return (int, bool): the id of an active currency or False if it is the same currency as
the statement's journal's currency.
"""
journal = self.env['account.bank.statement'].browse(values['statement_id']).journal_id
currency = random.choice(self.env['res.currency'].search([('active', '=', True)]).ids)
return currency if currency != (journal.currency_id or journal.company_id.currency_id).id else False
# Because we are accessing related fields of bank statements, a prefetch can improve the performances.
self = self.with_prefetch(self.env.registry.populated_models['account.bank.statement'])
return [
('statement_id', populate.randomize(self.env.registry.populated_models['account.bank.statement'])),
('partner_id', populate.compute(get_partner)),
('payment_ref', populate.constant('statement_{values[statement_id]}_{counter}')),
('date', populate.compute(get_date)),
('amount', populate.compute(get_amount)),
('currency_id', populate.compute(get_currency)),
]
def _populate(self, size):
records = super()._populate(size)
_logger.info('Posting Bank Statements')
statements = records.statement_id.sorted(lambda r: (r.date, r.name, r.id))
previous = defaultdict(int)
for statement in statements:
statement.balance_start = previous[statement.journal_id]
previous[statement.journal_id] = statement.balance_end_real = statement.balance_start + statement.total_entry_encoding
statements.button_post()
return records
| 44.686567
| 5,988
|
1,353
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestAccountMoveRounding(AccountTestInvoicingCommon):
def test_move_line_rounding(self):
"""Whatever arguments we give to the creation of an account move,
in every case the amounts should be properly rounded to the currency's precision.
In other words, we don't fall victim of the limitation introduced by 9d87d15db6dd40
Here the rounding should be done according to company_currency_id, which is a related
on move_id.company_id.currency_id.
In principle, it should not be necessary to add it to the create values,
since it is supposed to be computed by the ORM...
"""
move = self.env['account.move'].create({
'line_ids': [
(0, 0, {'debit': 100.0 / 3, 'account_id': self.company_data['default_account_revenue'].id}),
(0, 0, {'credit': 100.0 / 3, 'account_id': self.company_data['default_account_revenue'].id}),
],
})
self.assertEqual(
[(33.33, 0.0), (0.0, 33.33)],
move.line_ids.mapped(lambda x: (x.debit, x.credit)),
"Quantities should have been rounded according to the currency."
)
| 43.645161
| 1,353
|
6,299
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
import json
@tagged('post_install', '-at_install')
class TestAccountIncomingSupplierInvoice(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.env['ir.config_parameter'].sudo().set_param('mail.catchall.domain', 'test-company.odoo.com')
cls.internal_user = cls.env['res.users'].create({
'name': 'Internal User',
'login': 'internal.user@test.odoo.com',
'email': 'internal.user@test.odoo.com',
})
cls.supplier_partner = cls.env['res.partner'].create({
'name': 'Your Supplier',
'email': 'supplier@other.company.com',
'supplier_rank': 10,
})
cls.journal = cls.company_data['default_journal_purchase']
journal_alias = cls.env['mail.alias'].create({
'alias_name': 'test-bill',
'alias_model_id': cls.env.ref('account.model_account_move').id,
'alias_defaults': json.dumps({
'move_type': 'in_invoice',
'company_id': cls.env.user.company_id.id,
'journal_id': cls.journal.id,
}),
})
cls.journal.write({'alias_id': journal_alias.id})
def test_supplier_invoice_mailed_from_supplier(self):
message_parsed = {
'message_id': 'message-id-dead-beef',
'subject': 'Incoming bill',
'from': '%s <%s>' % (self.supplier_partner.name, self.supplier_partner.email),
'to': '%s@%s' % (self.journal.alias_id.alias_name, self.journal.alias_id.alias_domain),
'body': "You know, that thing that you bought.",
'attachments': [b'Hello, invoice'],
}
invoice = self.env['account.move'].message_new(message_parsed, {'move_type': 'in_invoice', 'journal_id': self.journal.id})
message_ids = invoice.message_ids
self.assertEqual(len(message_ids), 1, 'Only one message should be posted in the chatter')
self.assertEqual(message_ids.body, '<p>Vendor Bill Created</p>', 'Only the invoice creation should be posted')
following_partners = invoice.message_follower_ids.mapped('partner_id')
self.assertEqual(following_partners, self.env.user.partner_id)
self.assertRegex(invoice.name, 'BILL/\d{4}/\d{2}/0001')
def test_supplier_invoice_forwarded_by_internal_user_without_supplier(self):
""" In this test, the bill was forwarded by an employee,
but no partner email address is found in the body."""
message_parsed = {
'message_id': 'message-id-dead-beef',
'subject': 'Incoming bill',
'from': '%s <%s>' % (self.internal_user.name, self.internal_user.email),
'to': '%s@%s' % (self.journal.alias_id.alias_name, self.journal.alias_id.alias_domain),
'body': "You know, that thing that you bought.",
'attachments': [b'Hello, invoice'],
}
invoice = self.env['account.move'].message_new(message_parsed, {'move_type': 'in_invoice', 'journal_id': self.journal.id})
message_ids = invoice.message_ids
self.assertEqual(len(message_ids), 1, 'Only one message should be posted in the chatter')
self.assertEqual(message_ids.body, '<p>Vendor Bill Created</p>', 'Only the invoice creation should be posted')
following_partners = invoice.message_follower_ids.mapped('partner_id')
self.assertEqual(following_partners, self.env.user.partner_id | self.internal_user.partner_id)
def test_supplier_invoice_forwarded_by_internal_with_supplier_in_body(self):
""" In this test, the bill was forwarded by an employee,
and the partner email address is found in the body."""
message_parsed = {
'message_id': 'message-id-dead-beef',
'subject': 'Incoming bill',
'from': '%s <%s>' % (self.internal_user.name, self.internal_user.email),
'to': '%s@%s' % (self.journal.alias_id.alias_name, self.journal.alias_id.alias_domain),
'body': "Mail sent by %s <%s>:\nYou know, that thing that you bought." % (self.supplier_partner.name, self.supplier_partner.email),
'attachments': [b'Hello, invoice'],
}
invoice = self.env['account.move'].message_new(message_parsed, {'move_type': 'in_invoice', 'journal_id': self.journal.id})
message_ids = invoice.message_ids
self.assertEqual(len(message_ids), 1, 'Only one message should be posted in the chatter')
self.assertEqual(message_ids.body, '<p>Vendor Bill Created</p>', 'Only the invoice creation should be posted')
following_partners = invoice.message_follower_ids.mapped('partner_id')
self.assertEqual(following_partners, self.env.user.partner_id | self.internal_user.partner_id)
def test_supplier_invoice_forwarded_by_internal_with_internal_in_body(self):
""" In this test, the bill was forwarded by an employee,
and the internal user email address is found in the body."""
message_parsed = {
'message_id': 'message-id-dead-beef',
'subject': 'Incoming bill',
'from': '%s <%s>' % (self.internal_user.name, self.internal_user.email),
'to': '%s@%s' % (self.journal.alias_id.alias_name, self.journal.alias_id.alias_domain),
'body': "Mail sent by %s <%s>:\nYou know, that thing that you bought." % (self.internal_user.name, self.internal_user.email),
'attachments': [b'Hello, invoice'],
}
invoice = self.env['account.move'].message_new(message_parsed, {'move_type': 'in_invoice', 'journal_id': self.journal.id})
message_ids = invoice.message_ids
self.assertEqual(len(message_ids), 1, 'Only one message should be posted in the chatter')
self.assertEqual(message_ids.body, '<p>Vendor Bill Created</p>', 'Only the invoice creation should be posted')
following_partners = invoice.message_follower_ids.mapped('partner_id')
self.assertEqual(following_partners, self.env.user.partner_id | self.internal_user.partner_id)
| 51.211382
| 6,299
|
19,372
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TaxReportTest(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.test_country_1 = cls.env['res.country'].create({
'name': "The Old World",
'code': 'YY',
})
cls.test_country_2 = cls.env['res.country'].create({
'name': "The Principality of Zeon",
'code': 'ZZ',
})
cls.tax_report_1 = cls.env['account.tax.report'].create({
'name': "Tax report 1",
'country_id': cls.test_country_1.id,
})
cls.tax_report_line_1_1 = cls.env['account.tax.report.line'].create({
'name': "[01] Line 01",
'tag_name': '01',
'report_id': cls.tax_report_1.id,
'sequence': 2,
})
cls.tax_report_line_1_2 = cls.env['account.tax.report.line'].create({
'name': "[01] Line 02",
'tag_name': '02',
'report_id': cls.tax_report_1.id,
'sequence': 3,
})
cls.tax_report_line_1_3 = cls.env['account.tax.report.line'].create({
'name': "[03] Line 03",
'tag_name': '03',
'report_id': cls.tax_report_1.id,
'sequence': 4,
})
cls.tax_report_line_1_4 = cls.env['account.tax.report.line'].create({
'name': "[04] Line 04",
'report_id': cls.tax_report_1.id,
'sequence': 5,
})
cls.tax_report_line_1_5 = cls.env['account.tax.report.line'].create({
'name': "[05] Line 05",
'report_id': cls.tax_report_1.id,
'sequence': 6,
})
cls.tax_report_line_1_55 = cls.env['account.tax.report.line'].create({
'name': "[55] Line 55",
'tag_name': '55',
'report_id': cls.tax_report_1.id,
'sequence': 7,
})
cls.tax_report_line_1_6 = cls.env['account.tax.report.line'].create({
'name': "[100] Line 100",
'tag_name': '100',
'report_id': cls.tax_report_1.id,
'sequence': 8,
})
cls.tax_report_2 = cls.env['account.tax.report'].create({
'name': "Tax report 2",
'country_id': cls.test_country_1.id,
})
cls.tax_report_line_2_1 = cls.env['account.tax.report.line'].create({
'name': "[01] Line 01, but in report 2",
'tag_name': '01',
'report_id': cls.tax_report_2.id,
'sequence': 1,
})
cls.tax_report_line_2_2 = cls.env['account.tax.report.line'].create({
'name': "[02] Line 02, but in report 2",
'report_id': cls.tax_report_2.id,
'sequence': 2,
})
cls.tax_report_line_2_42 = cls.env['account.tax.report.line'].create({
'name': "[42] Line 42",
'tag_name': '42',
'report_id': cls.tax_report_2.id,
'sequence': 3,
})
cls.tax_report_line_2_6 = cls.env['account.tax.report.line'].create({
'name': "[100] Line 100",
'tag_name': '100',
'report_id': cls.tax_report_2.id,
'sequence': 4,
})
def _get_tax_tags(self, tag_name=None, active_test=True):
domain = [('country_id', '=', self.test_country_1.id), ('applicability', '=', 'taxes')]
if tag_name:
domain.append(('name', 'like', '_' + tag_name))
return self.env['account.account.tag'].with_context(active_test=active_test).search(domain)
def test_write_add_tagname(self):
""" Adding a tag_name to a line without any should create new tags.
"""
tags_before = self._get_tax_tags()
self.tax_report_line_2_2.tag_name = 'tournicoti'
tags_after = self._get_tax_tags()
self.assertEqual(len(tags_after), len(tags_before) + 2, "Two tags should have been created, +tournicoti and -tournicoti.")
def test_write_single_line_tagname(self):
""" Writing on the tag_name of a line with a non-null tag_name used in
no other line should overwrite the name of the existing tags.
"""
start_tags = self._get_tax_tags()
original_tag_name = self.tax_report_line_1_55.tag_name
original_tags = self.tax_report_line_1_55.tag_ids
self.tax_report_line_1_55.tag_name = 'Mille sabords !'
self.assertEqual(len(self._get_tax_tags(tag_name=original_tag_name)), 0, "The original tag name of the line should not correspond to any tag anymore.")
self.assertEqual(original_tags, self.tax_report_line_1_55.tag_ids, "The tax report line should still be linked to the same tags.")
self.assertEqual(len(self._get_tax_tags()), len(start_tags), "No new tag should have been created.")
def test_write_single_line_remove_tagname(self):
""" Setting None as the tag_name of a line with a non-null tag_name used
in a unique line should delete the tags, also removing all the references to it
from tax repartition lines and account move lines
"""
test_tax = self.env['account.tax'].create({
'name': "Test tax",
'amount_type': 'percent',
'amount': 25,
'type_tax_use': 'sale',
'country_id': self.tax_report_1.country_id.id,
'invoice_repartition_line_ids': [
(0,0, {
'factor_percent': 100,
'repartition_type': 'base',
}),
(0,0, {
'factor_percent': 100,
'repartition_type': 'tax',
'tag_ids': [(6, 0, self.tax_report_line_1_55.tag_ids[0].ids)],
}),
],
'refund_repartition_line_ids': [
(0,0, {
'factor_percent': 100,
'repartition_type': 'base',
}),
(0,0, {
'factor_percent': 100,
'repartition_type': 'tax',
}),
],
})
# Make sure the fiscal country allows using this tax directly
self.env.company.account_fiscal_country_id = self.tax_report_1.country_id.id
test_invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '1992-12-22',
'invoice_line_ids': [
(0, 0, {'quantity': 1, 'price_unit': 42, 'tax_ids': [(6, 0, test_tax.ids)]}),
],
})
test_invoice.action_post()
self.assertTrue(any(line.tax_tag_ids == self.tax_report_line_1_55.tag_ids[0] for line in test_invoice.line_ids), "The test invoice should contain a tax line with tag 55")
tag_name_before = self.tax_report_line_1_55.tag_name
tag_nber_before = len(self._get_tax_tags())
self.tax_report_line_1_55.tag_name = None
self.assertFalse(self.tax_report_line_1_55.tag_name, "The tag name for line 55 should now be None")
self.assertEqual(len(self._get_tax_tags(tag_name=tag_name_before)), 0, "None of the original tags for this line should be left after setting tag_name to None if no other line was using this tag_name.")
self.assertEqual(len(self._get_tax_tags()), tag_nber_before - 2, "No new tag should have been created, and the two that were assigned to the report line should have been removed.")
self.assertFalse(test_tax.mapped('invoice_repartition_line_ids.tag_ids'), "There should be no tag left on test tax's repartition lines after the removal of tag 55.")
self.assertFalse(test_invoice.mapped('line_ids.tax_tag_ids'), "The link between test invoice and tag 55 should have been broken. There should be no tag left on the invoice's lines.")
def test_write_multi_no_change(self):
""" Writing the same tag_name as they already use on a set of tax report
lines with the same tag_name should not do anything.
"""
tags_before = self._get_tax_tags().ids
(self.tax_report_line_1_1 + self.tax_report_line_2_1).write({'tag_name': '01'})
tags_after = self._get_tax_tags().ids
self.assertEqual(tags_before, tags_after, "Re-assigning the same tag_name should keep the same tags.")
def test_edit_line_shared_tags(self):
""" Setting the tag_name of a tax report line sharing its tags with another line
should edit the tags' name and the tag_name of this other report line, to
keep consistency.
"""
original_tag_name = self.tax_report_line_1_1.tag_name
self.tax_report_line_1_1.tag_name = 'Groucha'
self.assertEqual(self.tax_report_line_2_1.tag_name, self.tax_report_line_1_1.tag_name, "Modifying the tag name of a tax report line sharing it with another one should also modify the other's.")
def test_edit_multi_line_tagname_all_different_new(self):
""" Writing a tag_name on multiple lines with distinct tag_names should
delete all the former tags and replace them by new ones (also on lines
sharing tags with them).
"""
lines = self.tax_report_line_1_1 + self.tax_report_line_2_2 + self.tax_report_line_2_42
previous_tag_ids = lines.mapped('tag_ids.id')
lines.write({'tag_name': 'crabe'})
new_tags = lines.mapped('tag_ids')
self.assertNotEqual(new_tags.ids, previous_tag_ids, "All the tags should have changed")
self.assertEqual(len(new_tags), 2, "Only two distinct tags should be assigned to all the lines after writing tag_name on them all")
surviving_tags = self.env['account.account.tag'].search([('id', 'in', previous_tag_ids)])
self.assertEqual(len(surviving_tags), 0, "All former tags should have been deleted")
self.assertEqual(self.tax_report_line_1_1.tag_ids, self.tax_report_line_2_1.tag_ids, "The report lines initially sharing their tag_name with the written-on lines should also have been impacted")
def test_remove_line_dependency(self):
""" Setting to None the tag_name of a report line sharing its tags with
other lines should only impact this line ; the other ones should keep their
link to the initial tags (their tag_name will hence differ in the end).
"""
tags_before = self.tax_report_line_1_1.tag_ids
self.tax_report_line_1_1.tag_name = None
self.assertEqual(len(self.tax_report_line_1_1.tag_ids), 0, "Setting the tag_name to None should have removed the tags.")
self.assertEqual(self.tax_report_line_2_1.tag_ids, tags_before, "Setting tag_name to None on a line linked to another one via tag_name should break this link.")
def test_tax_report_change_country(self):
""" Tests that duplicating and modifying the country of a tax report works
as intended (countries wanting to use the tax report of another
country need that).
"""
# Copy our first report
tags_before = self._get_tax_tags().ids
copied_report_1 = self.tax_report_1.copy()
copied_report_2 = self.tax_report_1.copy()
tags_after = self._get_tax_tags().ids
self.assertEqual(tags_before, tags_after, "Report duplication should not create or remove any tag")
for original, copy in zip(self.tax_report_1.get_lines_in_hierarchy(), copied_report_1.get_lines_in_hierarchy()):
self.assertEqual(original.tag_ids, copy.tag_ids, "Copying the lines of a tax report should keep the same tags on lines")
# Assign another country to one of the copies
copied_report_1.country_id = self.test_country_2
for original, copy in zip(self.tax_report_1.get_lines_in_hierarchy(), copied_report_1.get_lines_in_hierarchy()):
if original.tag_ids or copy.tag_ids:
self.assertNotEqual(original.tag_ids, copy.tag_ids, "Changing the country of a copied report should create brand new tags for all of its lines")
for original, copy in zip(self.tax_report_1.get_lines_in_hierarchy(), copied_report_2.get_lines_in_hierarchy()):
self.assertEqual(original.tag_ids, copy.tag_ids, "Changing the country of a copied report should not impact the other copies or the original report")
# Direclty change the country of a report without copying it first (some of its tags are shared, but not all)
original_report_2_tags = {line.id: line.tag_ids.ids for line in self.tax_report_2.get_lines_in_hierarchy()}
self.tax_report_2.country_id = self.test_country_2
for line in self.tax_report_2.get_lines_in_hierarchy():
if line == self.tax_report_line_2_42:
# This line is the only one of the report not sharing its tags
self.assertEqual(line.tag_ids.ids, original_report_2_tags[line.id], "The tax report lines not sharing their tags with any other report should keep the same tags when the country of their report is changed")
elif line.tag_ids or original_report_2_tags[line.id]:
self.assertNotEqual(line.tag_ids.ids, original_report_2_tags[line.id], "The tax report lines sharing their tags with other report should receive new tags when the country of their report is changed")
def test_unlink_report_line_tags(self):
""" Under certain circumstances, unlinking a tax report line should also unlink
the tags that are linked to it. We test those cases here.
"""
def check_tags_unlink(tag_name, report_lines, unlinked, error_message):
report_lines.unlink()
surviving_tags = self._get_tax_tags(tag_name=tag_name)
required_len = 0 if unlinked else 2 # 2 for + and - tag
self.assertEqual(len(surviving_tags), required_len, error_message)
check_tags_unlink('42', self.tax_report_line_2_42, True, "Unlinking one line not sharing its tags should also unlink them")
check_tags_unlink('01', self.tax_report_line_1_1, False, "Unlinking one line sharing its tags with others should keep the tags")
check_tags_unlink('100', self.tax_report_line_1_6 + self.tax_report_line_2_6, True, "Unlinkink all the lines sharing the same tags should also unlink them")
def test_unlink_report_line_tags_used_by_amls(self):
"""
Deletion of a report line whose tags are still referenced by an aml should archive tags and not delete them.
"""
test_tax = self.env['account.tax'].create({
'name': "Test tax",
'amount_type': 'percent',
'amount': 25,
'country_id': self.tax_report_1.country_id.id,
'type_tax_use': 'sale',
'invoice_repartition_line_ids': [
(0, 0, {
'factor_percent': 100,
'repartition_type': 'base',
}),
(0, 0, {
'factor_percent': 100,
'repartition_type': 'tax',
'tag_ids': [(6, 0, self.tax_report_line_1_55.tag_ids.filtered(lambda tag: not tag.tax_negate).ids)],
}),
],
'refund_repartition_line_ids': [
(0, 0, {
'factor_percent': 100,
'repartition_type': 'base',
}),
(0, 0, {
'factor_percent': 100,
'repartition_type': 'tax',
}),
],
})
# Make sure the fiscal country allows using this tax directly
self.env.company.account_fiscal_country_id = self.tax_report_1.country_id.id
test_invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '1992-12-22',
'invoice_line_ids': [
(0, 0, {'quantity': 1, 'price_unit': 42, 'tax_ids': [(6, 0, test_tax.ids)]}),
],
})
test_invoice.action_post()
tag_name = self.tax_report_line_1_55.tag_name
self.tax_report_line_1_55.unlink()
tags_after = self._get_tax_tags(tag_name=tag_name, active_test=False)
# only the +tag_name should be kept (and archived), -tag_name should be unlinked
self.assertEqual(tags_after.mapped('tax_negate'), [False], "Unlinking a report line should keep the tag if it was used on move lines, and unlink it otherwise.")
self.assertEqual(tags_after.mapped('active'), [False], "Unlinking a report line should archive the tag if it was used on move lines, and unlink it otherwise.")
self.assertEqual(len(test_tax.invoice_repartition_line_ids.tag_ids), 0, "After a tag is archived it shouldn't be on tax repartition lines.")
def test_unlink_report_line_tags_used_by_other_report_line(self):
"""
Deletion of a report line whose tags are still referenced in other report line should not delete nor archive tags.
"""
tag_name = self.tax_report_line_1_1.tag_name # tag "O1" is used in both line 1.1 and line 2.1
tags_before = self._get_tax_tags(tag_name=tag_name, active_test=False)
tags_archived_before = tags_before.filtered(lambda tag: not tag.active)
self.tax_report_line_1_1.unlink()
tags_after = self._get_tax_tags(tag_name=tag_name, active_test=False)
tags_archived_after = tags_after.filtered(lambda tag: not tag.active)
self.assertEqual(len(tags_after), len(tags_before), "Unlinking a report line whose tags are used by another line should not delete them.")
self.assertEqual(len(tags_archived_after), len(tags_archived_before), "Unlinking a report line whose tags are used by another line should not archive them.")
def test_tag_recreation_archived(self):
"""
In a situation where we have only one of the two (+ and -) sign that exist
we want only the missing sign to be re-created if we try to reuse the same tag name.
(We can get into this state when only one of the signs was used by aml: then we archived it and deleted the complement.)
"""
tag_name = self.tax_report_line_1_55.tag_name
tags_before = self._get_tax_tags(tag_name=tag_name, active_test=False)
tags_before[0].unlink() # we unlink one and archive the other, doesn't matter which one
tags_before[1].active = False
self.env['account.tax.report.line'].create({
'name': "[55] Line 55 bis",
'tag_name': tag_name,
'report_id': self.tax_report_1.id,
'sequence': 9,
})
tags_after = self._get_tax_tags(tag_name=tag_name, active_test=False)
self.assertEqual(len(tags_after), 2, "When creating a tax report line with an archived tag and its complement doesn't exist, it should be re-created.")
self.assertEqual(
tags_after.mapped('name'), ['+' + tag_name, '-' + tag_name],
"After creating a tax report line with an archived tag and when its complement doesn't exist, both a negative and a positive tag should "
"exist (the missing one being recreated)."
)
| 51.248677
| 19,372
|
11,361
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, Command
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
import freezegun
@tagged('post_install', '-at_install')
class TestAccountMoveDateAlgorithm(AccountTestInvoicingCommon):
# -------------------------------------------------------------------------
# HELPERS
# -------------------------------------------------------------------------
def _create_invoice(self, move_type, date, **kwargs):
return self.env['account.move'].create({
'invoice_date': date,
'partner_id': self.partner_a.id,
**kwargs,
'move_type': move_type,
'date': date,
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 1200.0,
**line_kwargs,
})
for line_kwargs in kwargs.get('invoice_line_ids', [{}])
],
})
def _create_payment(self, date, **kwargs):
return self.env['account.payment'].create({
'partner_id': self.partner_a.id,
'payment_type': 'inbound',
'partner_type': 'customer',
**kwargs,
'date': date,
})
def _set_lock_date(self, lock_date, period_lock_date=None):
self.env.company.fiscalyear_lock_date = fields.Date.from_string(lock_date)
self.env.company.period_lock_date = fields.Date.from_string(period_lock_date)
def _reverse_invoice(self, invoice):
move_reversal = self.env['account.move.reversal']\
.with_context(active_model="account.move", active_ids=invoice.ids)\
.create({
'journal_id': invoice.journal_id.id,
'reason': "no reason",
'refund_method': 'cancel',
})
reversal = move_reversal.reverse_moves()
return self.env['account.move'].browse(reversal['res_id'])
# -------------------------------------------------------------------------
# TESTS
# -------------------------------------------------------------------------
@freezegun.freeze_time('2017-01-12')
def test_out_invoice_date_with_lock_date(self):
self._set_lock_date('2016-12-31')
move = self._create_invoice('out_invoice', '2016-01-01')
move.action_post()
self.assertRecordValues(move, [{
'invoice_date': fields.Date.from_string('2016-01-01'),
'date': fields.Date.from_string('2017-01-12'),
}])
@freezegun.freeze_time('2017-01-12')
def test_out_invoice_reverse_date_with_lock_date(self):
move = self._create_invoice('out_invoice', '2016-01-01')
move.action_post()
self._set_lock_date('2016-12-31')
reverse_move = self._reverse_invoice(move)
self.assertRecordValues(reverse_move, [{
'invoice_date': fields.Date.from_string('2017-01-12'),
'date': fields.Date.from_string('2017-01-12'),
}])
@freezegun.freeze_time('2017-01-12')
def test_out_refund_date_with_lock_date(self):
self._set_lock_date('2016-12-31')
move = self._create_invoice('out_refund', '2016-01-01')
move.action_post()
self.assertRecordValues(move, [{
'invoice_date': fields.Date.from_string('2016-01-01'),
'date': fields.Date.from_string('2017-01-12'),
}])
@freezegun.freeze_time('2017-01-12')
def test_out_refund_reverse_date_with_lock_date(self):
move = self._create_invoice('out_refund', '2016-01-01')
move.action_post()
self._set_lock_date('2016-12-31')
reverse_move = self._reverse_invoice(move)
self.assertRecordValues(reverse_move, [{'date': fields.Date.from_string('2017-01-12')}])
@freezegun.freeze_time('2017-01-12')
def test_in_invoice_date_with_lock_date(self):
self._set_lock_date('2016-12-31')
move = self._create_invoice('in_invoice', '2016-01-01')
move.action_post()
self.assertRecordValues(move, [{
'invoice_date': fields.Date.from_string('2016-01-01'),
'date': fields.Date.from_string('2017-01-12'),
}])
@freezegun.freeze_time('2017-01-12')
def test_in_invoice_reverse_date_with_lock_date(self):
move = self._create_invoice('in_invoice', '2016-01-01')
move.action_post()
self._set_lock_date('2016-12-31')
reverse_move = self._reverse_invoice(move)
self.assertRecordValues(reverse_move, [{
'invoice_date': fields.Date.from_string('2017-01-12'),
'date': fields.Date.from_string('2017-01-12'),
}])
@freezegun.freeze_time('2017-01-12')
def test_in_refund_date_with_lock_date(self):
self._set_lock_date('2016-12-31')
move = self._create_invoice('in_refund', '2016-01-01')
move.action_post()
self.assertRecordValues(move, [{
'invoice_date': fields.Date.from_string('2016-01-01'),
'date': fields.Date.from_string('2017-01-12'),
}])
@freezegun.freeze_time('2017-01-12')
def test_in_refund_reverse_date_with_lock_date(self):
move = self._create_invoice('in_refund', '2016-01-01')
move.action_post()
self._set_lock_date('2016-12-31')
reverse_move = self._reverse_invoice(move)
self.assertRecordValues(reverse_move, [{'date': fields.Date.from_string('2017-01-12')}])
@freezegun.freeze_time('2017-02-12')
def test_reconcile_with_lock_date(self):
invoice = self._create_invoice('out_invoice', '2016-01-01', currency_id=self.currency_data['currency'].id)
refund = self._create_invoice('out_refund', '2017-01-01', currency_id=self.currency_data['currency'].id)
(invoice + refund).action_post()
self._set_lock_date('2017-01-31')
res = (invoice + refund).line_ids\
.filtered(lambda x: x.account_id.internal_type == 'receivable')\
.reconcile()
exchange_move = res['full_reconcile'].exchange_move_id
self.assertRecordValues(exchange_move, [{
'date': fields.Date.from_string('2017-02-01'),
'amount_total_signed': 200.0,
}])
@freezegun.freeze_time('2017-02-12')
def test_unreconcile_with_lock_date(self):
invoice = self._create_invoice('out_invoice', '2016-01-01', currency_id=self.currency_data['currency'].id)
refund = self._create_invoice('out_refund', '2017-01-01', currency_id=self.currency_data['currency'].id)
(invoice + refund).action_post()
res = (invoice + refund).line_ids\
.filtered(lambda x: x.account_id.internal_type == 'receivable')\
.reconcile()
exchange_move = res['full_reconcile'].exchange_move_id
self._set_lock_date('2017-01-31')
(invoice + refund).line_ids.remove_move_reconcile()
reverse_exchange_move = exchange_move.line_ids.matched_credit_ids.credit_move_id.move_id
self.assertRecordValues(reverse_exchange_move, [{
'date': fields.Date.from_string('2017-02-12'),
'amount_total_signed': 200.0,
}])
def test_caba_with_lock_date(self):
self.env.company.tax_exigibility = True
tax_waiting_account = self.env['account.account'].create({
'name': 'TAX_WAIT',
'code': 'TWAIT',
'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id,
'reconcile': True,
})
tax = self.env['account.tax'].create({
'name': 'cash basis 10%',
'type_tax_use': 'sale',
'amount': 10,
'tax_exigibility': 'on_payment',
'cash_basis_transition_account_id': tax_waiting_account.id,
})
invoice = self._create_invoice(
'out_invoice', '2016-01-01',
currency_id=self.currency_data['currency'].id,
invoice_line_ids=[{'tax_ids': [Command.set(tax.ids)]}],
)
payment = self._create_payment('2016-02-01', amount=invoice.amount_total)
(invoice + payment.move_id).action_post()
self._set_lock_date('2017-01-03')
with freezegun.freeze_time('2017-01-12'):
(invoice + payment.move_id).line_ids\
.filtered(lambda x: x.account_id.internal_type == 'receivable')\
.reconcile()
caba_move = self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', invoice.id)])
self.assertRecordValues(caba_move, [{
'date': fields.Date.from_string('2017-01-12'),
'amount_total_signed': 440.0,
}])
self._set_lock_date('2017-02-01')
with freezegun.freeze_time('2017-03-12'):
(invoice + payment.move_id).line_ids.remove_move_reconcile()
reverse_exchange_move = self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', invoice.id)]) - caba_move
self.assertRecordValues(reverse_exchange_move, [{
'date': fields.Date.from_string('2017-02-28'),
'amount_total_signed': 440.0,
}])
@freezegun.freeze_time('2023-05-01')
def test_caba_with_different_lock_dates(self):
"""
Test the date of the CABA move when reconciling a payment with an invoice
with date before fiscalyear_period but after period_lock_date either when
having accountant rights or not.
"""
self.env.company.tax_exigibility = True
tax_waiting_account = self.env['account.account'].create({
'name': 'TAX_WAIT',
'code': 'TWAIT',
'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id,
'reconcile': True,
})
tax = self.env['account.tax'].create({
'name': 'cash basis 10%',
'type_tax_use': 'sale',
'amount': 10,
'tax_exigibility': 'on_payment',
'cash_basis_transition_account_id': tax_waiting_account.id,
})
self._set_lock_date('2023-01-01', '2023-02-01')
for group, expected_date in (
('account.group_account_manager', '2023-01-30'),
('account.group_account_invoice', '2023-05-01'),
):
with self.subTest(group=group, expected_date=expected_date):
self.env.user.groups_id = [Command.set(self.env.ref(group).ids)]
self.assertTrue(self.env.user.user_has_groups(group))
invoice = self._create_invoice(
'out_invoice', '2023-01-02',
invoice_line_ids=[{'tax_ids': [Command.set(tax.ids)]}],
)
payment = self._create_payment('2023-01-30', amount=invoice.amount_total)
(invoice + payment.move_id).action_post()
(invoice + payment.move_id).line_ids\
.filtered(lambda x: x.account_id.internal_type == 'receivable')\
.reconcile()
caba_move = self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', invoice.id)])
self.assertRecordValues(caba_move, [{
'date': fields.Date.from_string(expected_date),
}])
| 40.003521
| 11,361
|
13,074
|
py
|
PYTHON
|
15.0
|
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.models import Model
from odoo.tests import tagged
from odoo import fields
from odoo.exceptions import UserError
from odoo.tools import format_date
@tagged('post_install', '-at_install')
class TestAccountMoveInalterableHash(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
def test_account_move_inalterable_hash(self):
"""Test that we cannot alter a field used for the computation of the inalterable hash"""
self.company_data['default_journal_sale'].restrict_mode_hash_table = True
move = self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000], post=True)
with self.assertRaisesRegex(UserError, "You cannot overwrite the values ensuring the inalterability of the accounting."):
move.inalterable_hash = 'fake_hash'
with self.assertRaisesRegex(UserError, "You cannot overwrite the values ensuring the inalterability of the accounting."):
move.secure_sequence_number = 666
with self.assertRaisesRegex(UserError, "You cannot edit the following fields due to restrict mode being activated.*"):
move.name = "fake name"
with self.assertRaisesRegex(UserError, "You cannot edit the following fields due to restrict mode being activated.*"):
move.date = fields.Date.from_string('2023-01-02')
with self.assertRaisesRegex(UserError, "You cannot edit the following fields due to restrict mode being activated.*"):
move.company_id = 666
with self.assertRaisesRegex(UserError, "You cannot edit the following fields due to restrict mode being activated.*"):
move.write({
'company_id': 666,
'date': fields.Date.from_string('2023-01-03')
})
with self.assertRaisesRegex(UserError, "You cannot edit the following fields.*Account.*"):
move.line_ids[0].account_id = move.line_ids[1]['account_id']
with self.assertRaisesRegex(UserError, "You cannot edit the following fields.*Partner.*"):
move.line_ids[0].partner_id = 666
# The following fields are not part of the hash so they can be modified
move.invoice_date_due = fields.Date.from_string('2023-01-02')
move.line_ids[0].date_maturity = fields.Date.from_string('2023-01-02')
def test_account_move_hash_integrity_report(self):
"""Test the hash integrity report"""
moves = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-02", amounts=[1000, 2000])
)
moves.action_post()
# No records to be hashed because the restrict mode is not activated yet
integrity_check = moves.company_id._check_hash_integrity()['results'][0] # First journal
self.assertEqual(integrity_check['msg_cover'], 'This journal is not in strict mode.')
# No records to be hashed even if the restrict mode is activated because the hashing is not retroactive
self.company_data['default_journal_sale'].restrict_mode_hash_table = True
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], 'There isn\'t any journal entry flagged for data inalterability yet for this journal.')
# Everything should be correctly hashed and verified
new_moves = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-03", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-04", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_a, "2023-01-05", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-06", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_a, "2023-01-07", amounts=[1000, 2000])
)
new_moves.action_post()
moves |= new_moves
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertRegex(integrity_check['msg_cover'], f'Entries are hashed from {moves[2].name}.*')
self.assertEqual(integrity_check['first_move_date'], format_date(self.env, fields.Date.to_string(moves[2].date)))
self.assertEqual(integrity_check['last_move_date'], format_date(self.env, fields.Date.to_string(moves[-1].date)))
# Let's change one of the fields used by the hash. It should be detected by the integrity report.
# We need to bypass the write method of account.move to do so.
Model.write(moves[4], {'date': fields.Date.from_string('2023-01-07')})
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves[4].id}.')
# Let's try with the one of the subfields
Model.write(moves[4], {'date': fields.Date.from_string("2023-01-05")}) # Revert the previous change
Model.write(moves[-1].line_ids[0], {'partner_id': self.partner_b.id})
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves[-1].id}.')
# Let's try with the inalterable_hash field itself
Model.write(moves[-1].line_ids[0], {'partner_id': self.partner_a.id}) # Revert the previous change
Model.write(moves[-1], {'inalterable_hash': 'fake_hash'})
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves[-1].id}.')
def test_account_move_hash_versioning_1(self):
"""We are updating the hash algorithm. We want to make sure that we do not break the integrity report.
This test focuses on the case where the user has only moves with the old hash algorithm."""
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000], post=True) # Not hashed
self.company_data['default_journal_sale'].restrict_mode_hash_table = True
moves = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-02", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-03", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-04", amounts=[1000, 2000])
)
moves.with_context(hash_version=1).action_post()
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertRegex(integrity_check['msg_cover'], f'Entries are hashed from {moves[0].name}.*')
self.assertEqual(integrity_check['first_move_date'], format_date(self.env, fields.Date.to_string(moves[0].date)))
self.assertEqual(integrity_check['last_move_date'], format_date(self.env, fields.Date.to_string(moves[-1].date)))
# Let's change one of the fields used by the hash. It should be detected by the integrity report
# independently of the hash version used. I.e. we first try the v1 hash, then the v2 hash and neither should work.
# We need to bypass the write method of account.move to do so.
Model.write(moves[1], {'date': fields.Date.from_string('2023-01-07')})
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves[1].id}.')
def test_account_move_hash_versioning_2(self):
"""We are updating the hash algorithm. We want to make sure that we do not break the integrity report.
This test focuses on the case where the user has only moves with the new hash algorithm."""
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000], post=True) # Not hashed
self.company_data['default_journal_sale'].restrict_mode_hash_table = True
moves = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-02", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-03", amounts=[1000, 2000])
)
moves.action_post()
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertRegex(integrity_check['msg_cover'], f'Entries are hashed from {moves[0].name}.*')
self.assertEqual(integrity_check['first_move_date'], format_date(self.env, fields.Date.to_string(moves[0].date)))
self.assertEqual(integrity_check['last_move_date'], format_date(self.env, fields.Date.to_string(moves[-1].date)))
# Let's change one of the fields used by the hash. It should be detected by the integrity report
# independently of the hash version used. I.e. we first try the v1 hash, then the v2 hash and neither should work.
# We need to bypass the write method of account.move to do so.
Model.write(moves[1], {'date': fields.Date.from_string('2023-01-07')})
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves[1].id}.')
def test_account_move_hash_versioning_v1_to_v2(self):
"""We are updating the hash algorithm. We want to make sure that we do not break the integrity report.
This test focuses on the case where the user has moves with both hash algorithms."""
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000], post=True) # Not hashed
self.company_data['default_journal_sale'].restrict_mode_hash_table = True
moves_v1 = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-02", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-03", amounts=[1000, 2000])
)
moves_v1.with_context(hash_version=1).action_post()
fields_v1 = moves_v1.with_context(hash_version=1)._get_integrity_hash_fields()
moves_v2 = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-01", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-02", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-03", amounts=[1000, 2000])
)
moves_v2.with_context(hash_version=2).action_post()
fields_v2 = moves_v2._get_integrity_hash_fields()
self.assertNotEqual(fields_v1, fields_v2) # Make sure two different hash algorithms were used
moves = moves_v1 | moves_v2
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertRegex(integrity_check['msg_cover'], f'Entries are hashed from {moves[0].name}.*')
self.assertEqual(integrity_check['first_move_date'], format_date(self.env, fields.Date.to_string(moves[0].date)))
self.assertEqual(integrity_check['last_move_date'], format_date(self.env, fields.Date.to_string(moves[-1].date)))
# Let's change one of the fields used by the hash. It should be detected by the integrity report
# independently of the hash version used. I.e. we first try the v1 hash, then the v2 hash and neither should work.
# We need to bypass the write method of account.move to do so.
Model.write(moves[4], {'date': fields.Date.from_string('2023-01-07')})
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves[4].id}.')
# Let's revert the change and make sure that we cannot use the v1 after the v2.
# This means we don't simply check whether the move is correctly hashed with either algorithms,
# but that we can only use v2 after v1 and not go back to v1 afterwards.
Model.write(moves[4], {'date': fields.Date.from_string("2023-01-02")}) # Revert the previous change
moves_v1_bis = (
self.init_invoice("out_invoice", self.partner_a, "2023-01-10", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-11", amounts=[1000, 2000])
| self.init_invoice("out_invoice", self.partner_b, "2023-01-12", amounts=[1000, 2000])
)
moves_v1_bis.with_context(hash_version=1).action_post()
integrity_check = moves.company_id._check_hash_integrity()['results'][0]
self.assertEqual(integrity_check['msg_cover'], f'Corrupted data on journal entry with id {moves_v1_bis[0].id}.')
| 70.290323
| 13,074
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.