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,009 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models, exceptions, _
class Rating(models.Model):
_inherit = 'rating.rating'
# Adding information for comment a rating message
publisher_comment = fields.Text("Publisher comment")
publisher_id = fields.Many2one('res.partner', 'Commented by',
ondelete='set null', readonly=True)
publisher_datetime = fields.Datetime("Commented on", readonly=True)
def write(self, values):
if values.get('publisher_comment'):
if not self.env.user.has_group("website.group_website_publisher"):
raise exceptions.AccessError(_("Only the publisher of the website can change the rating comment"))
if not values.get('publisher_datetime'):
values['publisher_datetime'] = fields.Datetime.now()
if not values.get('publisher_id'):
values['publisher_id'] = self.env.user.partner_id.id
return super(Rating, self).write(values)
| 43.869565 | 1,009 |
1,276 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailMessage(models.Model):
_inherit = 'mail.message'
def _portal_message_format(self, field_list):
# inlude rating value in data if requested
if self._context.get('rating_include'):
field_list += ['rating_value']
return super(MailMessage, self)._portal_message_format(field_list)
def _message_format(self, fnames, format_reply=True):
""" Override the method to add information about a publisher comment
on each rating messages if requested, and compute a plaintext value of it.
"""
vals_list = super(MailMessage, self)._message_format(fnames, format_reply=format_reply)
if self._context.get('rating_include'):
infos = ["id", "publisher_comment", "publisher_id", "publisher_datetime", "message_id"]
related_rating = self.env['rating.rating'].sudo().search([('message_id', 'in', self.ids)]).read(infos)
mid_rating_tree = dict((rating['message_id'][0], rating) for rating in related_rating)
for vals in vals_list:
vals["rating"] = mid_rating_tree.get(vals['id'], {})
return vals_list
| 45.571429 | 1,276 |
749 |
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 PortalRating(http.Controller):
@http.route(['/website/rating/comment'], type='json', auth="user", methods=['POST'], website=True)
def publish_rating_comment(self, rating_id, publisher_comment):
rating = request.env['rating.rating'].search([('id', '=', int(rating_id))])
if not rating:
return {'error': _('Invalid rating')}
rating.write({'publisher_comment': publisher_comment})
# return to the front-end the created/updated publisher comment
return rating.read(['publisher_comment', 'publisher_id', 'publisher_datetime'])[0]
| 44.058824 | 749 |
2,143 |
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
from odoo.addons.portal.controllers import mail
class PortalChatter(mail.PortalChatter):
def _portal_post_filter_params(self):
fields = super(PortalChatter, self)._portal_post_filter_params()
fields += ['rating_value', 'rating_feedback']
return fields
def _portal_rating_stats(self, res_model, res_id, **kwargs):
# get the rating statistics for the record
if kwargs.get('rating_include'):
record = request.env[res_model].browse(res_id)
if hasattr(record, 'rating_get_stats'):
return {'rating_stats': record.sudo().rating_get_stats()}
return {}
@http.route()
def portal_chatter_post(self, res_model, res_id, message, attachment_ids='', attachment_tokens='', **kwargs):
if kwargs.get('rating_value'):
kwargs['rating_feedback'] = kwargs.pop('rating_feedback', message)
return super(PortalChatter, self).portal_chatter_post(res_model, res_id, message, attachment_ids=attachment_ids, attachment_tokens=attachment_tokens, **kwargs)
@http.route()
def portal_chatter_init(self, res_model, res_id, domain=False, limit=False, **kwargs):
result = super(PortalChatter, self).portal_chatter_init(res_model, res_id, domain=domain, limit=limit, **kwargs)
result.update(self._portal_rating_stats(res_model, res_id, **kwargs))
return result
@http.route()
def portal_message_fetch(self, res_model, res_id, domain=False, limit=False, offset=False, **kw):
# add 'rating_include' in context, to fetch them in portal_message_format
if kw.get('rating_include'):
context = dict(request.context)
context['rating_include'] = True
request.context = context
result = super(PortalChatter, self).portal_message_fetch(res_model, res_id, domain=domain, limit=limit, offset=offset, **kw)
result.update(self._portal_rating_stats(res_model, res_id, **kw))
return result
| 46.586957 | 2,143 |
1,082 |
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Copyright (C) 2017 Paradigm Digital (<http://www.paradigmdigital.co.za>).
{
'name': 'South Africa - Accounting',
'version': '1.0',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the latest basic South African localisation necessary to run Odoo in ZA:
================================================================================
- a generic chart of accounts
- SARS VAT Ready Structure""",
'author': 'Paradigm Digital',
'website': 'https://www.paradigmdigital.co.za',
'depends': ['account', 'base_vat'],
'data': [
'data/account.account.tag.csv',
'data/account_tax_report_data.xml',
'data/account.tax.group.csv',
'data/account_chart_template_data.xml',
'data/account.account.template.csv',
'data/account_tax_template_data.xml',
'data/account_chart_template_post_data.xml',
'data/account_chart_template_configure_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 34.903226 | 1,082 |
566 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Attachments List and Document Indexation',
'version': '2.1',
'category': 'Hidden/Tools',
'description': """
Attachments list and document indexation
========================================
* Show attachment on the top of the forms
* Document Indexation: odt, pdf, xlsx, docx
The `pdfminer.six` Python library has to be installed in order to index PDF files
""",
'depends': ['web'],
'installable': True,
'license': 'LGPL-3',
}
| 31.444444 | 566 |
751 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase, tagged
from unittest import skipIf
import os
directory = os.path.dirname(__file__)
try:
from pdfminer.pdfinterp import PDFResourceManager
except ImportError:
PDFResourceManager = None
@tagged('post_install', '-at_install')
class TestCaseIndexation(TransactionCase):
@skipIf(PDFResourceManager is None, "pdfminer not installed")
def test_attachment_pdf_indexation(self):
with open(os.path.join(directory, 'files', 'test_content.pdf'), 'rb') as file:
pdf = file.read()
text = self.env['ir.attachment']._index(pdf, 'application/pdf')
self.assertEqual(text, 'TestContent!!\x0c', 'the index content should be correct')
| 32.652174 | 751 |
5,032 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import io
import logging
import xml.dom.minidom
import zipfile
from odoo import api, models
from odoo.tools.lru import LRU
_logger = logging.getLogger(__name__)
try:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.pdfpage import PDFPage
except ImportError:
PDFResourceManager = PDFPageInterpreter = TextConverter = PDFPage = None
_logger.warning("Attachment indexation of PDF documents is unavailable because the 'pdfminer' Python library cannot be found on the system. "
"You may install it from https://pypi.org/project/pdfminer.six/ (e.g. `pip3 install pdfminer.six`)")
FTYPES = ['docx', 'pptx', 'xlsx', 'opendoc', 'pdf']
index_content_cache = LRU(1)
def textToString(element):
buff = u""
for node in element.childNodes:
if node.nodeType == xml.dom.Node.TEXT_NODE:
buff += node.nodeValue
elif node.nodeType == xml.dom.Node.ELEMENT_NODE:
buff += textToString(node)
return buff
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
def _index_docx(self, bin_data):
'''Index Microsoft .docx documents'''
buf = u""
f = io.BytesIO(bin_data)
if zipfile.is_zipfile(f):
try:
zf = zipfile.ZipFile(f)
content = xml.dom.minidom.parseString(zf.read("word/document.xml"))
for val in ["w:p", "w:h", "text:list"]:
for element in content.getElementsByTagName(val):
buf += textToString(element) + "\n"
except Exception:
pass
return buf
def _index_pptx(self, bin_data):
'''Index Microsoft .pptx documents'''
buf = u""
f = io.BytesIO(bin_data)
if zipfile.is_zipfile(f):
try:
zf = zipfile.ZipFile(f)
zf_filelist = [x for x in zf.namelist() if x.startswith('ppt/slides/slide')]
for i in range(1, len(zf_filelist) + 1):
content = xml.dom.minidom.parseString(zf.read('ppt/slides/slide%s.xml' % i))
for val in ["a:t"]:
for element in content.getElementsByTagName(val):
buf += textToString(element) + "\n"
except Exception:
pass
return buf
def _index_xlsx(self, bin_data):
'''Index Microsoft .xlsx documents'''
buf = u""
f = io.BytesIO(bin_data)
if zipfile.is_zipfile(f):
try:
zf = zipfile.ZipFile(f)
content = xml.dom.minidom.parseString(zf.read("xl/sharedStrings.xml"))
for val in ["t"]:
for element in content.getElementsByTagName(val):
buf += textToString(element) + "\n"
except Exception:
pass
return buf
def _index_opendoc(self, bin_data):
'''Index OpenDocument documents (.odt, .ods...)'''
buf = u""
f = io.BytesIO(bin_data)
if zipfile.is_zipfile(f):
try:
zf = zipfile.ZipFile(f)
content = xml.dom.minidom.parseString(zf.read("content.xml"))
for val in ["text:p", "text:h", "text:list"]:
for element in content.getElementsByTagName(val):
buf += textToString(element) + "\n"
except Exception:
pass
return buf
def _index_pdf(self, bin_data):
'''Index PDF documents'''
if PDFResourceManager is None:
return
buf = u""
if bin_data.startswith(b'%PDF-'):
f = io.BytesIO(bin_data)
try:
resource_manager = PDFResourceManager()
with io.StringIO() as content, TextConverter(resource_manager, content) as device:
logging.getLogger("pdfminer").setLevel(logging.CRITICAL)
interpreter = PDFPageInterpreter(resource_manager, device)
for page in PDFPage.get_pages(f):
interpreter.process_page(page)
buf = content.getvalue()
except Exception:
pass
return buf
@api.model
def _index(self, bin_data, mimetype, checksum=None):
if checksum:
cached_content = index_content_cache.get(checksum)
if cached_content:
return cached_content
res = False
for ftype in FTYPES:
buf = getattr(self, '_index_%s' % ftype)(bin_data)
if buf:
res = buf.replace('\x00', '')
break
res = res or super(IrAttachment, self)._index(bin_data, mimetype, checksum=checksum)
if checksum:
index_content_cache[checksum] = res
return res
| 35.43662 | 5,032 |
2,025 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Customer Portal',
'summary': 'Customer Portal',
'sequence': '9000',
'category': 'Hidden',
'description': """
This module adds required base code for a fully integrated customer portal.
It contains the base controller class and base templates. Business addons
will add their specific templates and controllers to extend the customer
portal.
This module contains most code coming from odoo v10 website_portal. Purpose
of this module is to allow the display of a customer portal without having
a dependency towards website editing and customization capabilities.""",
'depends': ['web', 'web_editor', 'http_routing', 'mail', 'auth_signup'],
'data': [
'security/ir.model.access.csv',
'data/mail_template_data.xml',
'data/mail_templates.xml',
'views/portal_templates.xml',
'views/res_config_settings_views.xml',
'wizard/portal_share_views.xml',
'wizard/portal_wizard_views.xml',
],
'assets': {
'web._assets_primary_variables': [
'portal/static/src/scss/primary_variables.scss',
],
'web._assets_frontend_helpers': [
('prepend', 'portal/static/src/scss/bootstrap_overridden.scss'),
],
'web.assets_frontend': [
'portal/static/src/scss/bootstrap.extend.scss',
'portal/static/src/scss/portal.scss',
'portal/static/src/js/portal.js',
'portal/static/src/js/portal_chatter.js',
'portal/static/src/js/portal_composer.js',
'portal/static/src/js/portal_signature.js',
'portal/static/src/js/portal_sidebar.js',
],
'web.assets_tests': [
'portal/static/tests/**/*',
],
'web.assets_qweb': [
'portal/static/src/xml/portal_chatter.xml',
'portal/static/src/xml/portal_signature.xml',
],
},
'license': 'LGPL-3',
}
| 38.207547 | 2,025 |
1,738 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tools import mute_logger
from odoo.tests import common, tagged
@tagged('mail_message')
class TestMessageFormatPortal(common.TransactionCase):
@mute_logger('odoo.models.unlink')
def test_mail_message_format(self):
""" Test the specific message formatting for the portal.
Notably the flag that tells if the message is of subtype 'note'. """
partner = self.env['res.partner'].create({'name': 'Partner'})
message_no_subtype = self.env['mail.message'].create([{
'model': 'res.partner',
'res_id': partner.id,
}])
formatted_result = message_no_subtype.portal_message_format()
# no defined subtype -> should return False
self.assertFalse(formatted_result[0].get('is_message_subtype_note'))
message_comment = self.env['mail.message'].create([{
'model': 'res.partner',
'res_id': partner.id,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment'),
}])
formatted_result = message_comment.portal_message_format()
# subtype is a comment -> should return False
self.assertFalse(formatted_result[0].get('is_message_subtype_note'))
message_note = self.env['mail.message'].create([{
'model': 'res.partner',
'res_id': partner.id,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
}])
formatted_result = message_note.portal_message_format()
# subtype is note -> should return True
self.assertTrue(formatted_result[0].get('is_message_subtype_note'))
| 42.390244 | 1,738 |
7,669 |
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, mail_new_test_user
from odoo.exceptions import UserError, AccessError
from odoo.tests.common import users
class TestPortalWizard(MailCommon):
def setUp(self):
super(TestPortalWizard, self).setUp()
self.partner = self.env['res.partner'].create({
'name': 'Testing Partner',
'email': '[email protected]',
})
self.public_user = mail_new_test_user(
self.env,
name='Public user',
login='public_user',
email='[email protected]',
groups='base.group_public',
)
self.portal_user = mail_new_test_user(
self.env,
name='Portal user',
login='portal_user',
email='[email protected]',
groups='base.group_portal',
)
self.internal_user = mail_new_test_user(
self.env,
name='Internal user',
login='internal_user',
email='[email protected]',
groups='base.group_user',
)
def test_portal_wizard_acl(self):
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).create({})
with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'):
self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).with_user(self.user_employee).create({})
portal_wizard.invalidate_cache()
with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'):
portal_wizard.with_user(self.user_employee).welcome_message
portal_wizard.user_ids.invalidate_cache()
with self.assertRaises(AccessError, msg='Standard users should not be able to open the portal wizard'):
portal_wizard.user_ids.with_user(self.user_employee).email
@users('admin')
def test_portal_wizard_partner(self):
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.partner.id]).create({})
self.assertEqual(len(portal_wizard.user_ids), 1)
portal_user = portal_wizard.user_ids
self.assertFalse(portal_user.user_id.id)
self.assertFalse(portal_user.is_portal)
self.assertFalse(portal_user.is_internal)
portal_user.email = '[email protected]'
with self.mock_mail_gateway():
portal_user.action_grant_access()
new_user = portal_user.user_id
self.assertTrue(new_user.id, 'Must create a new user')
self.assertTrue(new_user.has_group('base.group_portal'), 'Must add the group to the user')
self.assertEqual(self.partner.email, '[email protected]', 'Must write on the email of the partner')
self.assertEqual(new_user.email, '[email protected]', 'Must create the user with the right email')
self.assertSentEmail(self.env.user.partner_id, [self.partner])
@users('admin')
def test_portal_wizard_public_user(self):
"""Test to grant the access to a public user.
Should remove the group "base.group_public" and add the group "base.group_portal"
"""
group_public = self.env.ref('base.group_public')
public_partner = self.public_user.partner_id
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[public_partner.id]).create({})
self.assertEqual(len(portal_wizard.user_ids), 1)
portal_user = portal_wizard.user_ids
self.assertEqual(portal_user.user_id, self.public_user)
self.assertFalse(portal_user.is_portal)
self.assertFalse(portal_user.is_internal)
portal_user.email = '[email protected]'
with self.mock_mail_gateway():
portal_user.action_grant_access()
self.assertTrue(portal_user.is_portal)
self.assertFalse(portal_user.is_internal)
self.assertTrue(self.public_user.has_group('base.group_portal'), 'Must add the group portal')
self.assertFalse(self.public_user.has_group('base.group_public'), 'Must remove the group public')
self.assertEqual(public_partner.email, '[email protected]', 'Must change the email of the partner')
self.assertEqual(self.public_user.email, '[email protected]', 'Must change the email of the user')
self.assertSentEmail(self.env.user.partner_id, [public_partner])
with self.mock_mail_gateway():
portal_user.action_revoke_access()
self.assertEqual(portal_user.user_id, self.public_user, 'Must keep the user even if it is archived')
self.assertEqual(group_public, portal_user.user_id.groups_id, 'Must add the group public after removing the portal group')
self.assertFalse(portal_user.user_id.active, 'Must have archived the user')
self.assertFalse(portal_user.is_portal)
self.assertFalse(portal_user.is_internal)
self.assertNotSentEmail()
@users('admin')
def test_portal_wizard_internal_user(self):
"""Internal user can not be managed from this wizard."""
internal_partner = self.internal_user.partner_id
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[internal_partner.id]).create({})
self.assertEqual(len(portal_wizard.user_ids), 1)
portal_user = portal_wizard.user_ids
self.assertTrue(portal_user.is_internal)
with self.assertRaises(UserError, msg='Should not be able to manage internal user'), self.mock_mail_gateway():
portal_wizard.user_ids.action_grant_access()
self.assertNotSentEmail()
with self.assertRaises(UserError, msg='Should not be able to manage internal user'):
portal_wizard.user_ids.action_revoke_access()
@users('admin')
def test_portal_wizard_error(self):
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.portal_user.partner_id.id]).create({})
self.assertEqual(len(portal_wizard.user_ids), 1)
portal_user = portal_wizard.user_ids
self.internal_user.login = '[email protected]'
portal_user.email = '[email protected]'
with self.assertRaises(UserError, msg='Must detect the already used email.'):
portal_user.action_revoke_access()
portal_user.email = 'wrong email format'
with self.assertRaises(UserError, msg='Must detect wrong email format.'):
portal_user.action_revoke_access()
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[self.internal_user.partner_id.id]).create({})
with self.assertRaises(UserError, msg='Must not be able to change internal user group.'):
portal_user.action_revoke_access()
def test_portal_wizard_multi_company(self):
company_1 = self.env['res.company'].search([], limit=1)
company_2 = self.env['res.company'].create({'name': 'Company 2'})
partner_company_2 = self.env['res.partner'].with_company(company_2).create({
'name': 'Testing Partner',
'email': '[email protected]',
'company_id': company_2.id,
})
portal_wizard = self.env['portal.wizard'].with_context(active_ids=[partner_company_2.id]).create({})
portal_user = portal_wizard.user_ids
portal_user.with_company(company_1).action_grant_access()
self.assertEqual(portal_user.user_id.company_id, company_2, 'Must create the user in the same company as the partner.')
| 43.573864 | 7,669 |
383 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.base.tests.common import HttpCaseWithUserPortal
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestUi(HttpCaseWithUserPortal):
def test_01_portal_load_tour(self):
self.start_tour("/", 'portal_load_homepage', login="portal")
| 34.818182 | 383 |
5,806 |
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 PortalShare(models.TransientModel):
_name = 'portal.share'
_description = 'Portal Sharing'
@api.model
def default_get(self, fields):
result = super(PortalShare, self).default_get(fields)
result['res_model'] = self._context.get('active_model', False)
result['res_id'] = self._context.get('active_id', False)
if result['res_model'] and result['res_id']:
record = self.env[result['res_model']].browse(result['res_id'])
result['share_link'] = record.get_base_url() + record._get_share_url(redirect=True)
return result
@api.model
def _selection_target_model(self):
return [(model.model, model.name) for model in self.env['ir.model'].sudo().search([])]
res_model = fields.Char('Related Document Model', required=True)
res_id = fields.Integer('Related Document ID', required=True)
resource_ref = fields.Reference('_selection_target_model', 'Related Document', compute='_compute_resource_ref')
partner_ids = fields.Many2many('res.partner', string="Recipients", required=True)
note = fields.Text(help="Add extra content to display in the email")
share_link = fields.Char(string="Link", compute='_compute_share_link')
access_warning = fields.Text("Access warning", compute="_compute_access_warning")
@api.depends('res_model', 'res_id')
def _compute_resource_ref(self):
for wizard in self:
if wizard.res_model and wizard.res_model in self.env:
wizard.resource_ref = '%s,%s' % (wizard.res_model, wizard.res_id or 0)
else:
wizard.resource_ref = None
@api.depends('res_model', 'res_id')
def _compute_share_link(self):
for rec in self:
rec.share_link = False
if rec.res_model:
res_model = self.env[rec.res_model]
if isinstance(res_model, self.pool['portal.mixin']) and rec.res_id:
record = res_model.browse(rec.res_id)
rec.share_link = record.get_base_url() + record._get_share_url(redirect=True)
@api.depends('res_model', 'res_id')
def _compute_access_warning(self):
for rec in self:
rec.access_warning = False
if rec.res_model:
res_model = self.env[rec.res_model]
if isinstance(res_model, self.pool['portal.mixin']) and rec.res_id:
record = res_model.browse(rec.res_id)
rec.access_warning = record.access_warning
@api.model
def _get_note(self):
return self.env.ref('mail.mt_note')
def _send_public_link(self, note, partners=None):
if partners is None:
partners = self.partner_ids
for partner in partners:
share_link = self.resource_ref.get_base_url() + self.resource_ref._get_share_url(redirect=True, pid=partner.id)
saved_lang = self.env.lang
self = self.with_context(lang=partner.lang)
template = self.env.ref('portal.portal_share_template', False)
self.resource_ref.message_post_with_view(template,
values={'partner': partner, 'note': self.note, 'record': self.resource_ref,
'share_link': share_link},
subject=_("You are invited to access %s", self.resource_ref.display_name),
subtype_id=note.id,
email_layout_xmlid='mail.mail_notification_light',
partner_ids=[(6, 0, partner.ids)])
self = self.with_context(lang=saved_lang)
def _send_signup_link(self, note, partners=None):
if partners is None:
partners = self.partner_ids.filtered(lambda partner: not partner.user_ids)
for partner in partners:
# prepare partner for signup and send singup url with redirect url
partner.signup_get_auth_param()
share_link = partner._get_signup_url_for_action(action='/mail/view', res_id=self.res_id, model=self.res_model)[partner.id]
saved_lang = self.env.lang
self = self.with_context(lang=partner.lang)
template = self.env.ref('portal.portal_share_template', False)
self.resource_ref.message_post_with_view(template,
values={'partner': partner, 'note': self.note, 'record': self.resource_ref,
'share_link': share_link},
subject=_("You are invited to access %s", self.resource_ref.display_name),
subtype_id=note.id,
email_layout_xmlid='mail.mail_notification_light',
partner_ids=[(6, 0, partner.ids)])
self = self.with_context(lang=saved_lang)
def action_send_mail(self):
note = self._get_note()
signup_enabled = self.env['ir.config_parameter'].sudo().get_param('auth_signup.invitation_scope') == 'b2c'
if getattr(self.resource_ref, 'access_token', False) or not signup_enabled:
partner_ids = self.partner_ids
else:
partner_ids = self.partner_ids.filtered(lambda x: x.user_ids)
# if partner already user or record has access token send common link in batch to all user
self._send_public_link(note, partner_ids)
# when partner not user send individual mail with signup token
self._send_signup_link(note, self.partner_ids - partner_ids)
# subscribe all recipients so that they receive future communication (better than
# using autofollow as more precise)
self.resource_ref.message_subscribe(partner_ids=self.partner_ids.ids)
return {'type': 'ir.actions.act_window_close'}
| 49.623932 | 5,806 |
9,692 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo.tools.translate import _
from odoo.tools import email_normalize
from odoo.exceptions import UserError
from odoo import api, fields, models, Command
_logger = logging.getLogger(__name__)
class PortalWizard(models.TransientModel):
"""
A wizard to manage the creation/removal of portal users.
"""
_name = 'portal.wizard'
_description = 'Grant Portal Access'
def _default_partner_ids(self):
partner_ids = self.env.context.get('default_partner_ids', []) or self.env.context.get('active_ids', [])
contact_ids = set()
for partner in self.env['res.partner'].sudo().browse(partner_ids):
contact_partners = partner.child_ids.filtered(lambda p: p.type in ('contact', 'other')) | partner
contact_ids |= set(contact_partners.ids)
return [Command.link(contact_id) for contact_id in contact_ids]
partner_ids = fields.Many2many('res.partner', string='Partners', default=_default_partner_ids)
user_ids = fields.One2many('portal.wizard.user', 'wizard_id', string='Users', compute='_compute_user_ids', store=True, readonly=False)
welcome_message = fields.Text('Invitation Message', help="This text is included in the email sent to new users of the portal.")
@api.depends('partner_ids')
def _compute_user_ids(self):
for portal_wizard in self:
portal_wizard.user_ids = [
Command.create({
'partner_id': partner.id,
'email': partner.email,
})
for partner in portal_wizard.partner_ids
]
@api.model
def action_open_wizard(self):
"""Create a "portal.wizard" and open the form view.
We need a server action for that because the one2many "user_ids" records need to
exist to be able to execute an a button action on it. If they have no ID, the
buttons will be disabled and we won't be able to click on them.
That's why we need a server action, to create the records and then open the form
view on them.
"""
portal_wizard = self.create({})
return portal_wizard._action_open_modal()
def _action_open_modal(self):
"""Allow to keep the wizard modal open after executing the action."""
self.refresh()
return {
'name': _('Portal Access Management'),
'type': 'ir.actions.act_window',
'res_model': 'portal.wizard',
'view_type': 'form',
'view_mode': 'form',
'res_id': self.id,
'target': 'new',
}
class PortalWizardUser(models.TransientModel):
"""
A model to configure users in the portal wizard.
"""
_name = 'portal.wizard.user'
_description = 'Portal User Config'
wizard_id = fields.Many2one('portal.wizard', string='Wizard', required=True, ondelete='cascade')
partner_id = fields.Many2one('res.partner', string='Contact', required=True, readonly=True, ondelete='cascade')
email = fields.Char('Email')
user_id = fields.Many2one('res.users', string='User', compute='_compute_user_id', compute_sudo=True)
login_date = fields.Datetime(related='user_id.login_date', string='Latest Authentication')
is_portal = fields.Boolean('Is Portal', compute='_compute_group_details')
is_internal = fields.Boolean('Is Internal', compute='_compute_group_details')
@api.depends('partner_id')
def _compute_user_id(self):
for portal_wizard_user in self:
user = portal_wizard_user.partner_id.with_context(active_test=False).user_ids
portal_wizard_user.user_id = user[0] if user else False
@api.depends('user_id', 'user_id.groups_id')
def _compute_group_details(self):
for portal_wizard_user in self:
user = portal_wizard_user.user_id
if user and user.has_group('base.group_user'):
portal_wizard_user.is_internal = True
portal_wizard_user.is_portal = False
elif user and user.has_group('base.group_portal'):
portal_wizard_user.is_internal = False
portal_wizard_user.is_portal = True
else:
portal_wizard_user.is_internal = False
portal_wizard_user.is_portal = False
def action_grant_access(self):
"""Grant the portal access to the partner.
If the partner has no linked user, we will create a new one in the same company
as the partner (or in the current company if not set).
An invitation email will be sent to the partner.
"""
self.ensure_one()
self._assert_user_email_uniqueness()
if self.is_portal or self.is_internal:
raise UserError(_('The partner "%s" already has the portal access.', self.partner_id.name))
group_portal = self.env.ref('base.group_portal')
group_public = self.env.ref('base.group_public')
# update partner email, if a new one was introduced
if self.partner_id.email != self.email:
self.partner_id.write({'email': self.email})
user_sudo = self.user_id.sudo()
if not user_sudo:
# create a user if necessary and make sure it is in the portal group
company = self.partner_id.company_id or self.env.company
user_sudo = self.sudo().with_company(company.id)._create_user()
if not user_sudo.active or not self.is_portal:
user_sudo.write({'active': True, 'groups_id': [(4, group_portal.id), (3, group_public.id)]})
# prepare for the signup process
user_sudo.partner_id.signup_prepare()
self.with_context(active_test=True)._send_email()
return self.wizard_id._action_open_modal()
def action_revoke_access(self):
"""Remove the user of the partner from the portal group.
If the user was only in the portal group, we archive it.
"""
self.ensure_one()
self._assert_user_email_uniqueness()
if not self.is_portal:
raise UserError(_('The partner "%s" has no portal access.', self.partner_id.name))
group_portal = self.env.ref('base.group_portal')
group_public = self.env.ref('base.group_public')
# update partner email, if a new one was introduced
if self.partner_id.email != self.email:
self.partner_id.write({'email': self.email})
# Remove the sign up token, so it can not be used
self.partner_id.sudo().signup_token = False
user_sudo = self.user_id.sudo()
# remove the user from the portal group
if user_sudo and user_sudo.has_group('base.group_portal'):
# if user belongs to portal only, deactivate it
if len(user_sudo.groups_id) <= 1:
user_sudo.write({'groups_id': [(3, group_portal.id), (4, group_public.id)], 'active': False})
else:
user_sudo.write({'groups_id': [(3, group_portal.id), (4, group_public.id)]})
return self.wizard_id._action_open_modal()
def action_invite_again(self):
"""Re-send the invitation email to the partner."""
self.ensure_one()
if not self.is_portal:
raise UserError(_('You should first grant the portal access to the partner "%s".', self.partner_id.name))
# update partner email, if a new one was introduced
if self.partner_id.email != self.email:
self.partner_id.write({'email': self.email})
self.with_context(active_test=True)._send_email()
return self.wizard_id._action_open_modal()
def _create_user(self):
""" create a new user for wizard_user.partner_id
:returns record of res.users
"""
return self.env['res.users'].with_context(no_reset_password=True)._create_user_from_template({
'email': email_normalize(self.email),
'login': email_normalize(self.email),
'partner_id': self.partner_id.id,
'company_id': self.env.company.id,
'company_ids': [(6, 0, self.env.company.ids)],
})
def _send_email(self):
""" send notification email to a new portal user """
self.ensure_one()
# determine subject and body in the portal user's language
template = self.env.ref('portal.mail_template_data_portal_welcome')
if not template:
raise UserError(_('The template "Portal: new user" not found for sending email to the portal user.'))
lang = self.user_id.sudo().lang
partner = self.user_id.sudo().partner_id
portal_url = partner.with_context(signup_force_type_in_url='', lang=lang)._get_signup_url_for_action()[partner.id]
partner.signup_prepare()
template.with_context(dbname=self._cr.dbname, portal_url=portal_url, lang=lang).send_mail(self.id, force_send=True)
return True
def _assert_user_email_uniqueness(self):
"""Check that the email can be used to create a new user."""
self.ensure_one()
email = email_normalize(self.email)
if not email:
raise UserError(_('The contact "%s" does not have a valid email.', self.partner_id.name))
user = self.env['res.users'].sudo().with_context(active_test=False).search([
('id', '!=', self.user_id.id),
('login', '=ilike', email),
])
if user:
raise UserError(_('The contact "%s" has the same email has an existing user (%s).', self.partner_id.name, user.name))
| 39.559184 | 9,692 |
642 |
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.http import request
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
@classmethod
def _get_translation_frontend_modules_name(cls):
mods = super(IrHttp, cls)._get_translation_frontend_modules_name()
return mods + ['portal']
@classmethod
def _get_frontend_langs(cls):
if request and request.is_frontend:
return [lang[0] for lang in filter(lambda l: l[3], request.env['res.lang'].get_available())]
return super()._get_frontend_langs()
| 32.1 | 642 |
1,691 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import hashlib
import hmac
from odoo import api, fields, models, _
class MailThread(models.AbstractModel):
_inherit = 'mail.thread'
_mail_post_token_field = 'access_token' # token field for external posts, to be overridden
website_message_ids = fields.One2many('mail.message', 'res_id', string='Website Messages',
domain=lambda self: [('model', '=', self._name), '|', ('message_type', '=', 'comment'), ('message_type', '=', 'email')], auto_join=True,
help="Website communication history")
def _sign_token(self, pid):
"""Generate a secure hash for this record with the email of the recipient with whom the record have been shared.
This is used to determine who is opening the link
to be able for the recipient to post messages on the document's portal view.
:param str email:
Email of the recipient that opened the link.
"""
self.ensure_one()
# check token field exists
if self._mail_post_token_field not in self._fields:
raise NotImplementedError(_(
"Model %(model_name)s does not support token signature, as it does not have %(field_name)s field.",
model_name=self._name,
field_name=self._mail_post_token_field
))
# sign token
secret = self.env["ir.config_parameter"].sudo().get_param("database.secret")
token = (self.env.cr.dbname, self[self._mail_post_token_field], pid)
return hmac.new(secret.encode('utf-8'), repr(token).encode('utf-8'), hashlib.sha256).hexdigest()
| 43.358974 | 1,691 |
1,123 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
from odoo.http import request
from odoo.addons.http_routing.models.ir_http import url_for
from odoo.tools import is_html_empty
class View(models.Model):
_inherit = "ir.ui.view"
customize_show = fields.Boolean("Show As Optional Inherit", default=False)
@api.model
def _prepare_qcontext(self):
""" Returns the qcontext : rendering context with portal specific value (required
to render portal layout template)
"""
qcontext = super(View, self)._prepare_qcontext()
if request and getattr(request, 'is_frontend', False):
Lang = request.env['res.lang']
portal_lang_code = request.env['ir.http']._get_frontend_langs()
qcontext.update(dict(
self._context.copy(),
languages=[lang for lang in Lang.get_available() if lang[0] in portal_lang_code],
url_for=url_for,
is_html_empty=is_html_empty,
))
return qcontext
| 37.433333 | 1,123 |
6,583 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import uuid
from werkzeug.urls import url_encode
from odoo import api, exceptions, fields, models, _
class PortalMixin(models.AbstractModel):
_name = "portal.mixin"
_description = 'Portal Mixin'
access_url = fields.Char(
'Portal Access URL', compute='_compute_access_url',
help='Customer Portal URL')
access_token = fields.Char('Security Token', copy=False)
# to display the warning from specific model
access_warning = fields.Text("Access warning", compute="_compute_access_warning")
def _compute_access_warning(self):
for mixin in self:
mixin.access_warning = ''
def _compute_access_url(self):
for record in self:
record.access_url = '#'
def _portal_ensure_token(self):
""" Get the current record access token """
if not self.access_token:
# we use a `write` to force the cache clearing otherwise `return self.access_token` will return False
self.sudo().write({'access_token': str(uuid.uuid4())})
return self.access_token
def _get_share_url(self, redirect=False, signup_partner=False, pid=None, share_token=True):
"""
Build the url of the record that will be sent by mail and adds additional parameters such as
access_token to bypass the recipient's rights,
signup_partner to allows the user to create easily an account,
hash token to allow the user to be authenticated in the chatter of the record portal view, if applicable
:param redirect : Send the redirect url instead of the direct portal share url
:param signup_partner: allows the user to create an account with pre-filled fields.
:param pid: = partner_id - when given, a hash is generated to allow the user to be authenticated
in the portal chatter, if any in the target page,
if the user is redirected to the portal instead of the backend.
:return: the url of the record with access parameters, if any.
"""
self.ensure_one()
params = {
'model': self._name,
'res_id': self.id,
}
if share_token and hasattr(self, 'access_token'):
params['access_token'] = self._portal_ensure_token()
if pid:
params['pid'] = pid
params['hash'] = self._sign_token(pid)
if signup_partner and hasattr(self, 'partner_id') and self.partner_id:
params.update(self.partner_id.signup_get_auth_param()[self.partner_id.id])
return '%s?%s' % ('/mail/view' if redirect else self.access_url, url_encode(params))
def _notify_get_groups(self, msg_vals=None):
access_token = self._portal_ensure_token()
groups = super(PortalMixin, self)._notify_get_groups(msg_vals=msg_vals)
local_msg_vals = dict(msg_vals or {})
if access_token and 'partner_id' in self._fields and self['partner_id']:
customer = self['partner_id']
local_msg_vals['access_token'] = self.access_token
local_msg_vals.update(customer.signup_get_auth_param()[customer.id])
access_link = self._notify_get_action_link('view', **local_msg_vals)
new_group = [
('portal_customer', lambda pdata: pdata['id'] == customer.id, {
'has_button_access': False,
'button_access': {
'url': access_link,
},
'notification_is_customer': True,
})
]
else:
new_group = []
return new_group + groups
def get_access_action(self, access_uid=None):
""" Instead of the classic form view, redirect to the online document for
portal users or if force_website=True in the context. """
self.ensure_one()
user, record = self.env.user, self
if access_uid:
try:
record.check_access_rights('read')
record.check_access_rule("read")
except exceptions.AccessError:
return super(PortalMixin, self).get_access_action(access_uid)
user = self.env['res.users'].sudo().browse(access_uid)
record = self.with_user(user)
if user.share or self.env.context.get('force_website'):
try:
record.check_access_rights('read')
record.check_access_rule('read')
except exceptions.AccessError:
if self.env.context.get('force_website'):
return {
'type': 'ir.actions.act_url',
'url': record.access_url,
'target': 'self',
'res_id': record.id,
}
else:
pass
else:
return {
'type': 'ir.actions.act_url',
'url': record._get_share_url(),
'target': 'self',
'res_id': record.id,
}
return super(PortalMixin, self).get_access_action(access_uid)
@api.model
def action_share(self):
action = self.env["ir.actions.actions"]._for_xml_id("portal.portal_share_action")
action['context'] = {'active_id': self.env.context['active_id'],
'active_model': self.env.context['active_model']}
return action
def get_portal_url(self, suffix=None, report_type=None, download=None, query_string=None, anchor=None):
"""
Get a portal url for this model, including access_token.
The associated route must handle the flags for them to have any effect.
- suffix: string to append to the url, before the query string
- report_type: report_type query string, often one of: html, pdf, text
- download: set the download query string to true
- query_string: additional query string
- anchor: string to append after the anchor #
"""
self.ensure_one()
url = self.access_url + '%s?access_token=%s%s%s%s%s' % (
suffix if suffix else '',
self._portal_ensure_token(),
'&report_type=%s' % report_type if report_type else '',
'&download=true' if download else '',
query_string if query_string else '',
'#%s' % anchor if anchor else ''
)
return url
| 43.886667 | 6,583 |
1,000 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
portal_allow_api_keys = fields.Boolean(
string='Customer API Keys',
compute='_compute_portal_allow_api_keys',
inverse='_inverse_portal_allow_api_keys',
)
def _compute_portal_allow_api_keys(self):
for setting in self:
setting.portal_allow_api_keys = self.env['ir.config_parameter'].sudo().get_param('portal.allow_api_keys')
def _inverse_portal_allow_api_keys(self):
self.env['ir.config_parameter'].sudo().set_param('portal.allow_api_keys', self.portal_allow_api_keys)
@api.model
def get_values(self):
res = super(ResConfigSettings, self).get_values()
res['portal_allow_api_keys'] = bool(self.env['ir.config_parameter'].sudo().get_param('portal.allow_api_keys'))
return res
| 37.037037 | 1,000 |
1,211 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailMessage(models.Model):
_inherit = 'mail.message'
def portal_message_format(self):
return self._portal_message_format([
'id', 'body', 'date', 'author_id', 'email_from', # base message fields
'message_type', 'subtype_id', 'is_internal', 'subject', # message specific
'model', 'res_id', 'record_name', # document related
])
def _portal_message_format(self, fields_list):
vals_list = self._message_format(fields_list)
message_subtype_note_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note')
IrAttachmentSudo = self.env['ir.attachment'].sudo()
for vals in vals_list:
vals['is_message_subtype_note'] = message_subtype_note_id and (vals.get('subtype_id') or [False])[0] == message_subtype_note_id
for attachment in vals.get('attachment_ids', []):
if not attachment.get('access_token'):
attachment['access_token'] = IrAttachmentSudo.browse(attachment['id']).generate_access_token()[0]
return vals_list
| 46.576923 | 1,211 |
445 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ResPartner(models.Model):
_inherit = 'res.partner'
def can_edit_vat(self):
''' `vat` is a commercial field, synced between the parent (commercial
entity) and the children. Only the commercial entity should be able to
edit it (as in backend). '''
return not self.parent_id
| 31.785714 | 445 |
708 |
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.exceptions import AccessError
class APIKeyDescription(models.TransientModel):
_inherit = 'res.users.apikeys.description'
def check_access_make_key(self):
try:
return super().check_access_make_key()
except AccessError:
if self.env['ir.config_parameter'].sudo().get_param('portal.allow_api_keys'):
if self.user_has_groups('base.group_portal'):
return
else:
raise AccessError(_("Only internal and portal users can create API keys"))
raise
| 35.4 | 708 |
12,360 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug import urls
from werkzeug.exceptions import NotFound, Forbidden
from odoo import http
from odoo.http import request
from odoo.osv import expression
from odoo.tools import consteq, plaintext2html
from odoo.addons.mail.controllers import mail
from odoo.exceptions import AccessError
def _check_special_access(res_model, res_id, token='', _hash='', pid=False):
record = request.env[res_model].browse(res_id).sudo()
if _hash and pid: # Signed Token Case: hash implies token is signed by partner pid
return consteq(_hash, record._sign_token(pid))
elif token: # Token Case: token is the global one of the document
token_field = request.env[res_model]._mail_post_token_field
return (token and record and consteq(record[token_field], token))
else:
raise Forbidden()
def _message_post_helper(res_model, res_id, message, token='', _hash=False, pid=False, nosubscribe=True, **kw):
""" Generic chatter function, allowing to write on *any* object that inherits mail.thread. We
distinguish 2 cases:
1/ If a token is specified, all logged in users will be able to write a message regardless
of access rights; if the user is the public user, the message will be posted under the name
of the partner_id of the object (or the public user if there is no partner_id on the object).
2/ If a signed token is specified (`hash`) and also a partner_id (`pid`), all post message will
be done under the name of the partner_id (as it is signed). This should be used to avoid leaking
token to all users.
Required parameters
:param string res_model: model name of the object
:param int res_id: id of the object
:param string message: content of the message
Optional keywords arguments:
:param string token: access token if the object's model uses some kind of public access
using tokens (usually a uuid4) to bypass access rules
:param string hash: signed token by a partner if model uses some token field to bypass access right
post messages.
:param string pid: identifier of the res.partner used to sign the hash
:param bool nosubscribe: set False if you want the partner to be set as follower of the object when posting (default to True)
The rest of the kwargs are passed on to message_post()
"""
record = request.env[res_model].browse(res_id)
# check if user can post with special token/signed token. The "else" will try to post message with the
# current user access rights (_mail_post_access use case).
if token or (_hash and pid):
pid = int(pid) if pid else False
if _check_special_access(res_model, res_id, token=token, _hash=_hash, pid=pid):
record = record.sudo()
else:
raise Forbidden()
# deduce author of message
author_id = request.env.user.partner_id.id if request.env.user.partner_id else False
# Signed Token Case: author_id is forced
if _hash and pid:
author_id = pid
# Token Case: author is document customer (if not logged) or itself even if user has not the access
elif token:
if request.env.user._is_public():
# TODO : After adding the pid and sign_token in access_url when send invoice by email, remove this line
# TODO : Author must be Public User (to rename to 'Anonymous')
author_id = record.partner_id.id if hasattr(record, 'partner_id') and record.partner_id.id else author_id
else:
if not author_id:
raise NotFound()
email_from = None
if author_id and 'email_from' not in kw:
partner = request.env['res.partner'].sudo().browse(author_id)
email_from = partner.email_formatted if partner.email else None
message_post_args = dict(
body=message,
message_type=kw.pop('message_type', "comment"),
subtype_xmlid=kw.pop('subtype_xmlid', "mail.mt_comment"),
author_id=author_id,
**kw
)
# This is necessary as mail.message checks the presence
# of the key to compute its default email from
if email_from:
message_post_args['email_from'] = email_from
return record.with_context(mail_create_nosubscribe=nosubscribe).message_post(**message_post_args)
class PortalChatter(http.Controller):
def _portal_post_filter_params(self):
return ['token', 'pid']
def _portal_post_check_attachments(self, attachment_ids, attachment_tokens):
request.env['ir.attachment'].browse(attachment_ids)._check_attachments_access(attachment_tokens)
@http.route(['/mail/chatter_post'], type='json', methods=['POST'], auth='public', website=True)
def portal_chatter_post(self, res_model, res_id, message, attachment_ids=None, attachment_tokens=None, **kw):
"""Create a new `mail.message` with the given `message` and/or `attachment_ids` and return new message values.
The message will be associated to the record `res_id` of the model
`res_model`. The user must have access rights on this target document or
must provide valid identifiers through `kw`. See `_message_post_helper`.
"""
res_id = int(res_id)
self._portal_post_check_attachments(attachment_ids or [], attachment_tokens or [])
if message or attachment_ids:
result = {'default_message': message}
# message is received in plaintext and saved in html
if message:
message = plaintext2html(message)
post_values = {
'res_model': res_model,
'res_id': res_id,
'message': message,
'send_after_commit': False,
'attachment_ids': False, # will be added afterward
}
post_values.update((fname, kw.get(fname)) for fname in self._portal_post_filter_params())
post_values['_hash'] = kw.get('hash')
message = _message_post_helper(**post_values)
result.update({'default_message_id': message.id})
if attachment_ids:
# sudo write the attachment to bypass the read access
# verification in mail message
record = request.env[res_model].browse(res_id)
message_values = {'res_id': res_id, 'model': res_model}
attachments = record._message_post_process_attachments([], attachment_ids, message_values)
if attachments.get('attachment_ids'):
message.sudo().write(attachments)
result.update({'default_attachment_ids': message.attachment_ids.sudo().read(['id', 'name', 'mimetype', 'file_size', 'access_token'])})
return result
@http.route('/mail/chatter_init', type='json', auth='public', website=True)
def portal_chatter_init(self, res_model, res_id, domain=False, limit=False, **kwargs):
is_user_public = request.env.user.has_group('base.group_public')
message_data = self.portal_message_fetch(res_model, res_id, domain=domain, limit=limit, **kwargs)
display_composer = False
if kwargs.get('allow_composer'):
display_composer = kwargs.get('token') or not is_user_public
return {
'messages': message_data['messages'],
'options': {
'message_count': message_data['message_count'],
'is_user_public': is_user_public,
'is_user_employee': request.env.user.has_group('base.group_user'),
'is_user_publisher': request.env.user.has_group('website.group_website_publisher'),
'display_composer': display_composer,
'partner_id': request.env.user.partner_id.id
}
}
@http.route('/mail/chatter_fetch', type='json', auth='public', website=True)
def portal_message_fetch(self, res_model, res_id, domain=False, limit=10, offset=0, **kw):
if not domain:
domain = []
# Only search into website_message_ids, so apply the same domain to perform only one search
# extract domain from the 'website_message_ids' field
model = request.env[res_model]
field = model._fields['website_message_ids']
field_domain = field.get_domain_list(model)
domain = expression.AND([
domain,
field_domain,
[('res_id', '=', res_id), '|', ('body', '!=', ''), ('attachment_ids', '!=', False)]
])
# Check access
Message = request.env['mail.message']
if kw.get('token'):
access_as_sudo = _check_special_access(res_model, res_id, token=kw.get('token'))
if not access_as_sudo: # if token is not correct, raise Forbidden
raise Forbidden()
# Non-employee see only messages with not internal subtype (aka, no internal logs)
if not request.env['res.users'].has_group('base.group_user'):
domain = expression.AND([Message._get_search_domain_share(), domain])
Message = request.env['mail.message'].sudo()
return {
'messages': Message.search(domain, limit=limit, offset=offset).portal_message_format(),
'message_count': Message.search_count(domain)
}
@http.route(['/mail/update_is_internal'], type='json', auth="user", website=True)
def portal_message_update_is_internal(self, message_id, is_internal):
message = request.env['mail.message'].browse(int(message_id))
message.write({'is_internal': is_internal})
return message.is_internal
class MailController(mail.MailController):
@classmethod
def _redirect_to_record(cls, model, res_id, access_token=None, **kwargs):
""" If the current user doesn't have access to the document, but provided
a valid access token, redirect him to the front-end view.
If the partner_id and hash parameters are given, add those parameters to the redirect url
to authentify the recipient in the chatter, if any.
:param model: the model name of the record that will be visualized
:param res_id: the id of the record
:param access_token: token that gives access to the record
bypassing the rights and rules restriction of the user.
:param kwargs: Typically, it can receive a partner_id and a hash (sign_token).
If so, those two parameters are used to authentify the recipient in the chatter, if any.
:return:
"""
# no model / res_id, meaning no possible record -> direct skip to super
if not model or not res_id or model not in request.env:
return super(MailController, cls)._redirect_to_record(model, res_id, access_token=access_token, **kwargs)
if issubclass(type(request.env[model]), request.env.registry['portal.mixin']):
uid = request.session.uid or request.env.ref('base.public_user').id
record_sudo = request.env[model].sudo().browse(res_id).exists()
try:
record_sudo.with_user(uid).check_access_rights('read')
record_sudo.with_user(uid).check_access_rule('read')
except AccessError:
if record_sudo.access_token and access_token and consteq(record_sudo.access_token, access_token):
record_action = record_sudo.with_context(force_website=True).get_access_action()
if record_action['type'] == 'ir.actions.act_url':
pid = kwargs.get('pid')
hash = kwargs.get('hash')
url = record_action['url']
if pid and hash:
url = urls.url_parse(url)
url_params = url.decode_query()
url_params.update([("pid", pid), ("hash", hash)])
url = url.replace(query=urls.url_encode(url_params)).to_url()
return request.redirect(url)
return super(MailController, cls)._redirect_to_record(model, res_id, access_token=access_token, **kwargs)
| 50.243902 | 12,360 |
1,145 |
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.addons.web.controllers import main
from odoo.http import request
class Home(main.Home):
@http.route()
def index(self, *args, **kw):
if request.session.uid and not request.env['res.users'].sudo().browse(request.session.uid).has_group('base.group_user'):
return request.redirect_query('/my', query=request.params)
return super(Home, self).index(*args, **kw)
def _login_redirect(self, uid, redirect=None):
if not redirect and not request.env['res.users'].sudo().browse(uid).has_group('base.group_user'):
redirect = '/my'
return super(Home, self)._login_redirect(uid, redirect=redirect)
@http.route('/web', type='http', auth="none")
def web_client(self, s_action=None, **kw):
if request.session.uid and not request.env['res.users'].sudo().browse(request.session.uid).has_group('base.group_user'):
return request.redirect_query('/my', query=request.params)
return super(Home, self).web_client(s_action, **kw)
| 44.038462 | 1,145 |
18,930 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import functools
import json
import logging
import math
import re
from werkzeug import urls
from odoo import fields as odoo_fields, http, tools, _, SUPERUSER_ID
from odoo.exceptions import ValidationError, AccessError, MissingError, UserError, AccessDenied
from odoo.http import content_disposition, Controller, request, route
from odoo.tools import consteq
# --------------------------------------------------
# Misc tools
# --------------------------------------------------
_logger = logging.getLogger(__name__)
def pager(url, total, page=1, step=30, scope=5, url_args=None):
""" Generate a dict with required value to render `website.pager` template. This method compute
url, page range to display, ... in the pager.
:param url : base url of the page link
:param total : number total of item to be splitted into pages
:param page : current page
:param step : item per page
:param scope : number of page to display on pager
:param url_args : additionnal parameters to add as query params to page url
:type url_args : dict
:returns dict
"""
# Compute Pager
page_count = int(math.ceil(float(total) / step))
page = max(1, min(int(page if str(page).isdigit() else 1), page_count))
scope -= 1
pmin = max(page - int(math.floor(scope/2)), 1)
pmax = min(pmin + scope, page_count)
if pmax - pmin < scope:
pmin = pmax - scope if pmax - scope > 0 else 1
def get_url(page):
_url = "%s/page/%s" % (url, page) if page > 1 else url
if url_args:
_url = "%s?%s" % (_url, urls.url_encode(url_args))
return _url
return {
"page_count": page_count,
"offset": (page - 1) * step,
"page": {
'url': get_url(page),
'num': page
},
"page_first": {
'url': get_url(1),
'num': 1
},
"page_start": {
'url': get_url(pmin),
'num': pmin
},
"page_previous": {
'url': get_url(max(pmin, page - 1)),
'num': max(pmin, page - 1)
},
"page_next": {
'url': get_url(min(pmax, page + 1)),
'num': min(pmax, page + 1)
},
"page_end": {
'url': get_url(pmax),
'num': pmax
},
"page_last": {
'url': get_url(page_count),
'num': page_count
},
"pages": [
{'url': get_url(page_num), 'num': page_num} for page_num in range(pmin, pmax+1)
]
}
def get_records_pager(ids, current):
if current.id in ids and (hasattr(current, 'website_url') or hasattr(current, 'access_url')):
attr_name = 'access_url' if hasattr(current, 'access_url') else 'website_url'
idx = ids.index(current.id)
prev_record = idx != 0 and current.browse(ids[idx - 1])
next_record = idx < len(ids) - 1 and current.browse(ids[idx + 1])
if prev_record and prev_record[attr_name] and attr_name == "access_url":
prev_url = '%s?access_token=%s' % (prev_record[attr_name], prev_record._portal_ensure_token())
elif prev_record and prev_record[attr_name]:
prev_url = prev_record[attr_name]
else:
prev_url = prev_record
if next_record and next_record[attr_name] and attr_name == "access_url":
next_url = '%s?access_token=%s' % (next_record[attr_name], next_record._portal_ensure_token())
elif next_record and next_record[attr_name]:
next_url = next_record[attr_name]
else:
next_url = next_record
return {
'prev_record': prev_url,
'next_record': next_url,
}
return {}
def _build_url_w_params(url_string, query_params, remove_duplicates=True):
""" Rebuild a string url based on url_string and correctly compute query parameters
using those present in the url and those given by query_params. Having duplicates in
the final url is optional. For example:
* url_string = '/my?foo=bar&error=pay'
* query_params = {'foo': 'bar2', 'alice': 'bob'}
* if remove duplicates: result = '/my?foo=bar2&error=pay&alice=bob'
* else: result = '/my?foo=bar&foo=bar2&error=pay&alice=bob'
"""
url = urls.url_parse(url_string)
url_params = url.decode_query()
if remove_duplicates: # convert to standard dict instead of werkzeug multidict to remove duplicates automatically
url_params = url_params.to_dict()
url_params.update(query_params)
return url.replace(query=urls.url_encode(url_params)).to_url()
class CustomerPortal(Controller):
MANDATORY_BILLING_FIELDS = ["name", "phone", "email", "street", "city", "country_id"]
OPTIONAL_BILLING_FIELDS = ["zipcode", "state_id", "vat", "company_name"]
_items_per_page = 80
def _prepare_portal_layout_values(self):
"""Values for /my/* templates rendering.
Does not include the record counts.
"""
# get customer sales rep
sales_user = False
partner = request.env.user.partner_id
if partner.user_id and not partner.user_id._is_public():
sales_user = partner.user_id
return {
'sales_user': sales_user,
'page_name': 'home',
}
def _prepare_home_portal_values(self, counters):
"""Values for /my & /my/home routes template rendering.
Includes the record count for the displayed badges.
where 'coutners' is the list of the displayed badges
and so the list to compute.
"""
return {}
@route(['/my/counters'], type='json', auth="user", website=True)
def counters(self, counters, **kw):
return self._prepare_home_portal_values(counters)
@route(['/my', '/my/home'], type='http', auth="user", website=True)
def home(self, **kw):
values = self._prepare_portal_layout_values()
return request.render("portal.portal_my_home", values)
@route(['/my/account'], type='http', auth='user', website=True)
def account(self, redirect=None, **post):
values = self._prepare_portal_layout_values()
partner = request.env.user.partner_id
values.update({
'error': {},
'error_message': [],
})
if post and request.httprequest.method == 'POST':
error, error_message = self.details_form_validate(post)
values.update({'error': error, 'error_message': error_message})
values.update(post)
if not error:
values = {key: post[key] for key in self.MANDATORY_BILLING_FIELDS}
values.update({key: post[key] for key in self.OPTIONAL_BILLING_FIELDS if key in post})
for field in set(['country_id', 'state_id']) & set(values.keys()):
try:
values[field] = int(values[field])
except:
values[field] = False
values.update({'zip': values.pop('zipcode', '')})
partner.sudo().write(values)
if redirect:
return request.redirect(redirect)
return request.redirect('/my/home')
countries = request.env['res.country'].sudo().search([])
states = request.env['res.country.state'].sudo().search([])
values.update({
'partner': partner,
'countries': countries,
'states': states,
'has_check_vat': hasattr(request.env['res.partner'], 'check_vat'),
'redirect': redirect,
'page_name': 'my_details',
})
response = request.render("portal.portal_my_details", values)
response.headers['X-Frame-Options'] = 'DENY'
return response
@route('/my/security', type='http', auth='user', website=True, methods=['GET', 'POST'])
def security(self, **post):
values = self._prepare_portal_layout_values()
values['get_error'] = get_error
values['allow_api_keys'] = bool(request.env['ir.config_parameter'].sudo().get_param('portal.allow_api_keys'))
if request.httprequest.method == 'POST':
values.update(self._update_password(
post['old'].strip(),
post['new1'].strip(),
post['new2'].strip()
))
return request.render('portal.portal_my_security', values, headers={
'X-Frame-Options': 'DENY'
})
def _update_password(self, old, new1, new2):
for k, v in [('old', old), ('new1', new1), ('new2', new2)]:
if not v:
return {'errors': {'password': {k: _("You cannot leave any password empty.")}}}
if new1 != new2:
return {'errors': {'password': {'new2': _("The new password and its confirmation must be identical.")}}}
try:
request.env['res.users'].change_password(old, new1)
except UserError as e:
return {'errors': {'password': e.name}}
except AccessDenied as e:
msg = e.args[0]
if msg == AccessDenied().args[0]:
msg = _('The old password you provided is incorrect, your password was not changed.')
return {'errors': {'password': {'old': msg}}}
# update session token so the user does not get logged out (cache cleared by passwd change)
new_token = request.env.user._compute_session_token(request.session.sid)
request.session.session_token = new_token
return {'success': {'password': True}}
@http.route('/portal/attachment/add', type='http', auth='public', methods=['POST'], website=True)
def attachment_add(self, name, file, res_model, res_id, access_token=None, **kwargs):
"""Process a file uploaded from the portal chatter and create the
corresponding `ir.attachment`.
The attachment will be created "pending" until the associated message
is actually created, and it will be garbage collected otherwise.
:param name: name of the file to save.
:type name: string
:param file: the file to save
:type file: werkzeug.FileStorage
:param res_model: name of the model of the original document.
To check access rights only, it will not be saved here.
:type res_model: string
:param res_id: id of the original document.
To check access rights only, it will not be saved here.
:type res_id: int
:param access_token: access_token of the original document.
To check access rights only, it will not be saved here.
:type access_token: string
:return: attachment data {id, name, mimetype, file_size, access_token}
:rtype: dict
"""
try:
self._document_check_access(res_model, int(res_id), access_token=access_token)
except (AccessError, MissingError) as e:
raise UserError(_("The document does not exist or you do not have the rights to access it."))
IrAttachment = request.env['ir.attachment']
access_token = False
# Avoid using sudo or creating access_token when not necessary: internal
# users can create attachments, as opposed to public and portal users.
if not request.env.user.has_group('base.group_user'):
IrAttachment = IrAttachment.sudo().with_context(binary_field_real_user=IrAttachment.env.user)
access_token = IrAttachment._generate_access_token()
# At this point the related message does not exist yet, so we assign
# those specific res_model and res_is. They will be correctly set
# when the message is created: see `portal_chatter_post`,
# or garbage collected otherwise: see `_garbage_collect_attachments`.
attachment = IrAttachment.create({
'name': name,
'datas': base64.b64encode(file.read()),
'res_model': 'mail.compose.message',
'res_id': 0,
'access_token': access_token,
})
return request.make_response(
data=json.dumps(attachment.read(['id', 'name', 'mimetype', 'file_size', 'access_token'])[0]),
headers=[('Content-Type', 'application/json')]
)
@http.route('/portal/attachment/remove', type='json', auth='public')
def attachment_remove(self, attachment_id, access_token=None):
"""Remove the given `attachment_id`, only if it is in a "pending" state.
The user must have access right on the attachment or provide a valid
`access_token`.
"""
try:
attachment_sudo = self._document_check_access('ir.attachment', int(attachment_id), access_token=access_token)
except (AccessError, MissingError) as e:
raise UserError(_("The attachment does not exist or you do not have the rights to access it."))
if attachment_sudo.res_model != 'mail.compose.message' or attachment_sudo.res_id != 0:
raise UserError(_("The attachment %s cannot be removed because it is not in a pending state.", attachment_sudo.name))
if attachment_sudo.env['mail.message'].search([('attachment_ids', 'in', attachment_sudo.ids)]):
raise UserError(_("The attachment %s cannot be removed because it is linked to a message.", attachment_sudo.name))
return attachment_sudo.unlink()
def details_form_validate(self, data):
error = dict()
error_message = []
# Validation
for field_name in self.MANDATORY_BILLING_FIELDS:
if not data.get(field_name):
error[field_name] = 'missing'
# email validation
if data.get('email') and not tools.single_email_re.match(data.get('email')):
error["email"] = 'error'
error_message.append(_('Invalid Email! Please enter a valid email address.'))
# vat validation
partner = request.env.user.partner_id
if data.get("vat") and partner and partner.vat != data.get("vat"):
if partner.can_edit_vat():
if hasattr(partner, "check_vat"):
if data.get("country_id"):
data["vat"] = request.env["res.partner"].fix_eu_vat_number(int(data.get("country_id")), data.get("vat"))
partner_dummy = partner.new({
'vat': data['vat'],
'country_id': (int(data['country_id'])
if data.get('country_id') else False),
})
try:
partner_dummy.check_vat()
except ValidationError:
error["vat"] = 'error'
else:
error_message.append(_('Changing VAT number is not allowed once document(s) have been issued for your account. Please contact us directly for this operation.'))
# error message for empty required fields
if [err for err in error.values() if err == 'missing']:
error_message.append(_('Some required fields are empty.'))
unknown = [k for k in data if k not in self.MANDATORY_BILLING_FIELDS + self.OPTIONAL_BILLING_FIELDS]
if unknown:
error['common'] = 'Unknown field'
error_message.append("Unknown field '%s'" % ','.join(unknown))
return error, error_message
def _document_check_access(self, model_name, document_id, access_token=None):
document = request.env[model_name].browse([document_id])
document_sudo = document.with_user(SUPERUSER_ID).exists()
if not document_sudo:
raise MissingError(_("This document does not exist."))
try:
document.check_access_rights('read')
document.check_access_rule('read')
except AccessError:
if not access_token or not document_sudo.access_token or not consteq(document_sudo.access_token, access_token):
raise
return document_sudo
def _get_page_view_values(self, document, access_token, values, session_history, no_breadcrumbs, **kwargs):
if access_token:
# if no_breadcrumbs = False -> force breadcrumbs even if access_token to `invite` users to register if they click on it
values['no_breadcrumbs'] = no_breadcrumbs
values['access_token'] = access_token
values['token'] = access_token # for portal chatter
# Those are used notably whenever the payment form is implied in the portal.
if kwargs.get('error'):
values['error'] = kwargs['error']
if kwargs.get('warning'):
values['warning'] = kwargs['warning']
if kwargs.get('success'):
values['success'] = kwargs['success']
# Email token for posting messages in portal view with identified author
if kwargs.get('pid'):
values['pid'] = kwargs['pid']
if kwargs.get('hash'):
values['hash'] = kwargs['hash']
history = request.session.get(session_history, [])
values.update(get_records_pager(history, document))
return values
def _show_report(self, model, report_type, report_ref, download=False):
if report_type not in ('html', 'pdf', 'text'):
raise UserError(_("Invalid report type: %s", report_type))
report_sudo = request.env.ref(report_ref).with_user(SUPERUSER_ID)
if not isinstance(report_sudo, type(request.env['ir.actions.report'])):
raise UserError(_("%s is not the reference of a report", report_ref))
if hasattr(model, 'company_id'):
report_sudo = report_sudo.with_company(model.company_id)
method_name = '_render_qweb_%s' % (report_type)
report = getattr(report_sudo, method_name)([model.id], data={'report_type': report_type})[0]
reporthttpheaders = [
('Content-Type', 'application/pdf' if report_type == 'pdf' else 'text/html'),
('Content-Length', len(report)),
]
if report_type == 'pdf' and download:
filename = "%s.pdf" % (re.sub('\W+', '-', model._get_report_base_filename()))
reporthttpheaders.append(('Content-Disposition', content_disposition(filename)))
return request.make_response(report, headers=reporthttpheaders)
def get_error(e, path=''):
""" Recursively dereferences `path` (a period-separated sequence of dict
keys) in `e` (an error dict or value), returns the final resolution IIF it's
an str, otherwise returns None
"""
for k in (path.split('.') if path else []):
if not isinstance(e, dict):
return None
e = e.get(k)
return e if isinstance(e, str) else None
| 41.604396 | 18,930 |
1,023 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2012 Thinkopen Solutions, Lda. All Rights Reserved
# http://www.thinkopensolutions.com.
{
'name': 'Portugal - Accounting',
'version': '0.011',
'author': 'ThinkOpen Solutions',
'website': 'http://www.thinkopensolutions.com/',
'category': 'Accounting/Localizations/Account Charts',
'description': 'Plano de contas SNC para Portugal',
'depends': ['base',
'account',
'base_vat',
],
'data': [
'data/l10n_pt_chart_data.xml',
'data/account_chart_template_data.xml',
'data/account_fiscal_position_template_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_report.xml',
'data/account_tax_data.xml',
'data/account_chart_template_configure_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 33 | 1,023 |
706 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'pos_epson_printer_restaurant',
'version': '1.0',
'category': 'Sales/Point of Sale',
'sequence': 6,
'summary': 'Epson Printers as Order Printers',
'description': """
Use Epson Printers as Order Printers in the Point of Sale without the IoT Box
""",
'depends': ['pos_epson_printer', 'pos_restaurant'],
'data': [
'views/pos_restaurant_views.xml',
],
'installable': True,
'auto_install': True,
'assets': {
'point_of_sale.assets': [
'pos_epson_printer_restaurant/static/**/*',
],
},
'license': 'LGPL-3',
}
| 26.148148 | 706 |
434 |
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 RestaurantPrinter(models.Model):
_inherit = 'restaurant.printer'
printer_type = fields.Selection(selection_add=[('epson_epos', 'Use an Epson printer')])
epson_printer_ip = fields.Char(string='Epson Receipt Printer IP Address', help="Local IP address of an Epson receipt printer.")
| 39.454545 | 434 |
710 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Online Event Booth Sale',
'category': 'Marketing/Events',
'version': '1.0',
'summary': 'Events, sell your booths online',
'description': """
Use the e-commerce to sell your event booths.
""",
'depends': ['event_booth_sale', 'website_event_booth', 'website_sale'],
'data': [
'views/event_booth_templates.xml',
],
'demo': [],
'auto_install': True,
'assets': {
'web.assets_frontend': [
'/website_event_booth_sale/static/src/js/booth_register.js',
],
'web.assets_tests': [
'/website_event_booth_sale/static/tests/tours/**/**.js'
],
},
'license': 'LGPL-3',
}
| 27.307692 | 710 |
2,641 |
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 Command, fields
from odoo.addons.website_event_sale.tests.common import TestWebsiteEventSaleCommon
from odoo.tests import HttpCase
from odoo.tests.common import tagged
@tagged('post_install', '-at_install')
class TestWebsiteEventBoothSale(HttpCase, TestWebsiteEventSaleCommon):
def setUp(self):
super().setUp()
self.env['ir.config_parameter'].sudo().set_param('account.show_line_subtotals_tax_selection', 'tax_included')
self.tax = self.env['account.tax'].sudo().create({
'name': 'Tax 10',
'amount': 10,
})
self.booth_product = self.env['product.product'].create({
'name': 'Test Booth Product',
'description_sale': 'Mighty Booth Description',
'list_price': 20,
'standard_price': 60.0,
'taxes_id': [(6, 0, [self.tax.id])],
'detailed_type': 'event_booth',
})
self.event_booth_category = self.env['event.booth.category'].create({
'name': 'Standard',
'description': '<p>Standard</p>',
'product_id': self.booth_product.id,
'price': 100.0,
})
self.event_type = self.env['event.type'].create({
'name': 'Booth Type',
'event_type_booth_ids': [
Command.create({
'name': 'Standard 1',
'booth_category_id': self.event_booth_category.id,
}),
Command.create({
'name': 'Standard 2',
'booth_category_id': self.event_booth_category.id,
}),
Command.create({
'name': 'Standard 3',
'booth_category_id': self.event_booth_category.id,
}),
],
})
self.env['event.event'].create({
'name': 'Test Event Booths',
'event_type_id': self.event_type.id,
'date_begin': fields.Datetime.to_string(datetime.today() + timedelta(days=1)),
'date_end': fields.Datetime.to_string(datetime.today() + timedelta(days=15)),
'website_published': True,
'website_menu': True,
'booth_menu': True,
})
def test_tour(self):
self.start_tour('/event', 'website_event_booth_tour', login='portal')
def test_booth_pricelists_different_currencies(self):
self.start_tour("/web", 'event_booth_sale_pricelists_different_currencies')
| 38.838235 | 2,641 |
3,633 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.event_booth_sale.tests.common import TestEventBoothSaleCommon
from odoo.addons.website_event_sale.tests.common import TestWebsiteEventSaleCommon
from odoo.addons.website_sale.controllers.main import WebsiteSale
from odoo.addons.website.tools import MockRequest
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestWebsiteBoothPriceList(TestEventBoothSaleCommon, TestWebsiteEventSaleCommon):
@classmethod
def setUpClass(cls):
super(TestWebsiteBoothPriceList, cls).setUpClass()
cls.WebsiteSaleController = WebsiteSale()
cls.booth_1 = cls.env['event.booth'].create({
'booth_category_id': cls.event_booth_category_1.id,
'event_id': cls.event_0.id,
'name': 'Test Booth 1',
})
cls.booth_2 = cls.env['event.booth'].create({
'booth_category_id': cls.event_booth_category_1.id,
'event_id': cls.event_0.id,
'name': 'Test Booth 2',
})
def test_pricelist_different_currency(self):
so_line = self.env['sale.order.line'].create({
'event_booth_category_id': self.event_booth_category_1.id,
'event_booth_pending_ids': (self.booth_1 + self.booth_2).ids,
'event_id': self.event_0.id,
'order_id': self.so.id,
'product_id': self.event_booth_product.id,
})
# set pricelist to 0 - currency: company
self.pricelist.write({
'currency_id': self.env.company.currency_id.id,
'discount_policy': 'with_discount',
'item_ids': [(5, 0, 0), (0, 0, {
'applied_on': '3_global',
'compute_price': 'percentage',
'percent_price': 0,
})],
'name': 'With Discount Included',
})
with MockRequest(self.env, sale_order_id=self.so.id, website=self.current_website):
self.WebsiteSaleController.pricelist('With Discount Included')
self.so._cart_update(line_id=so_line.id, product_id=self.event_booth_product.id, set_qty=1)
self.assertEqual(so_line.price_reduce, 40)
# set pricelist to 10% - without discount
self.pricelist.write({
'currency_id': self.currency_test.id,
'discount_policy': 'without_discount',
'item_ids': [(5, 0, 0), (0, 0, {
'applied_on': '3_global',
'compute_price': 'percentage',
'percent_price': 10,
})],
'name': 'Without Discount Included',
})
with MockRequest(self.env, sale_order_id=self.so.id, website=self.current_website):
self.WebsiteSaleController.pricelist('Without Discount Included')
self.so._cart_update(line_id=so_line.id, product_id=self.event_booth_product.id, set_qty=1)
self.assertEqual(so_line.price_reduce, 360, 'Incorrect amount based on the pricelist and its currency.')
# set pricelist to 10% - with discount
self.pricelist.write({
'discount_policy': 'with_discount',
'name': 'With Discount Included',
})
with MockRequest(self.env, sale_order_id=self.so.id, website=self.current_website):
self.WebsiteSaleController.pricelist('With Discount Included')
self.so._cart_update(line_id=so_line.id, product_id=self.event_booth_product.id, set_qty=1)
self.assertEqual(so_line.price_reduce, 360, 'Incorrect amount based on the pricelist and its currency.')
| 45.987342 | 3,633 |
5,459 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo import fields, models, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
def _cart_find_product_line(self, product_id=None, line_id=None, **kwargs):
"""Check if there is another sale order line which already contains the requested event_booth_pending_ids
to overwrite it with the newly requested booths to avoid having multiple so_line related to the same booths"""
self.ensure_one()
lines = super(SaleOrder, self)._cart_find_product_line(product_id, line_id, **kwargs)
if line_id:
return lines
event_booth_pending_ids = kwargs.get('event_booth_pending_ids')
if event_booth_pending_ids:
lines = lines.filtered(
lambda line: any(booth.id in event_booth_pending_ids for booth in line.event_booth_pending_ids)
)
return lines
def _website_product_id_change(self, order_id, product_id, qty=0, **kwargs):
values = super(SaleOrder, self)._website_product_id_change(order_id, product_id, qty=qty, **kwargs)
event_booth_pending_ids = kwargs.get('event_booth_pending_ids')
if event_booth_pending_ids:
order_line = self.env['sale.order.line'].sudo().search([
('id', 'in', self.order_line.ids),
('event_booth_pending_ids', 'in', event_booth_pending_ids)])
booths = self.env['event.booth'].browse(event_booth_pending_ids).with_context(pricelist=self.pricelist_id.id)
if order_line.event_booth_pending_ids.ids != event_booth_pending_ids:
new_registrations_commands = [Command.create({
'event_booth_id': booth.id,
**kwargs.get('registration_values'),
}) for booth in booths]
if order_line:
event_booth_registrations_command = [Command.delete(reg.id) for reg in
order_line.event_booth_registration_ids] + new_registrations_commands
else:
event_booth_registrations_command = new_registrations_commands
values['event_booth_registration_ids'] = event_booth_registrations_command
discount = 0
order = self.env['sale.order'].sudo().browse(order_id)
booth_currency = booths.product_id.currency_id
pricelist_currency = order.pricelist_id.currency_id
price_reduce = sum(booth.booth_category_id.price_reduce for booth in booths)
if booth_currency != pricelist_currency:
price_reduce = booth_currency._convert(
price_reduce,
pricelist_currency,
order.company_id,
order.date_order or fields.Datetime.now()
)
if order.pricelist_id.discount_policy == 'without_discount':
price = sum(booth.booth_category_id.price for booth in booths)
if price != 0:
if booth_currency != pricelist_currency:
price = booth_currency._convert(
price,
pricelist_currency,
order.company_id,
order.date_order or fields.Datetime.now()
)
discount = (price - price_reduce) / price * 100
price_unit = price
if discount < 0:
discount = 0
price_unit = price_reduce
else:
price_unit = price_reduce
else:
price_unit = price_reduce
if order.pricelist_id and order.partner_id:
order_line = order._cart_find_product_line(booths.product_id.id)
if order_line:
price_unit = self.env['account.tax']._fix_tax_included_price_company(price_unit, booths.product_id.taxes_id, order_line[0].tax_id, self.company_id)
values.update(
event_id=booths.event_id.id,
discount=discount,
price_unit=price_unit,
name=booths._get_booth_multiline_description(),
)
return values
def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
values = {}
product = self.env['product.product'].browse(product_id)
if product.detailed_type == 'event_booth' and line_id:
if set_qty > 1:
set_qty = 1
values['warning'] = _('You cannot manually change the quantity of an Event Booth product.')
if add_qty == 0 and not kwargs.get('event_booth_pending_ids'):
# when updating the pricelist, the website_sale module call this method without the 'event.booth' ids
# -> we manually set the argument to make sure the price is updated in '_website_product_id_change'
kwargs['event_booth_pending_ids'] = self.env['sale.order.line'].browse(line_id).event_booth_pending_ids.ids
values.update(super(SaleOrder, self)._cart_update(product_id, line_id, add_qty, set_qty, **kwargs))
return values
| 52.490385 | 5,459 |
498 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ProductProduct(models.Model):
_inherit = 'product.product'
def _is_add_to_cart_allowed(self):
# `event_booth_registration_confirm` calls `_cart_update` with specific products, allow those aswell.
return super()._is_add_to_cart_allowed() or\
self.env['event.booth.category'].sudo().search_count([('product_id', '=', self.id)])
| 41.5 | 498 |
325 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class Website(models.Model):
_inherit = 'website'
def sale_product_domain(self):
return ['&'] + super(Website, self).sale_product_domain() + [('detailed_type', '!=', 'event_booth')]
| 29.545455 | 325 |
1,550 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import werkzeug
from odoo import http
from odoo.http import request
from odoo.addons.website_event.controllers.main import WebsiteEventController
class WebsiteEventBoothController(WebsiteEventController):
@http.route()
def event_booth_main(self, event):
pricelist = request.website.get_current_pricelist()
if pricelist:
event = event.with_context(pricelist=pricelist.id)
return super(WebsiteEventBoothController, self).event_booth_main(event)
@http.route()
def event_booth_registration_confirm(self, event, booth_category_id, event_booth_ids, **kwargs):
booths = self._get_requested_booths(event, event_booth_ids)
booth_category = request.env['event.booth.category'].sudo().browse(int(booth_category_id))
order = request.website.sale_get_order(force_create=1)
order._cart_update(
product_id=booth_category.product_id.id,
set_qty=1,
event_booth_pending_ids=booths.ids,
registration_values=self._prepare_booth_registration_values(event, kwargs),
)
if order.amount_total:
return request.redirect('/shop/checkout')
elif order:
order.action_confirm()
request.website.sale_reset()
return request.redirect(('/event/%s/booth/success?' % event.id) + werkzeug.urls.url_encode({
'booths': ','.join([str(id) for id in booths.ids]),
}))
| 39.74359 | 1,550 |
592 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Customer Rating',
'version': '1.0',
'category': 'Productivity',
'description': """
This module allows a customer to give rating.
""",
'depends': [
'mail',
],
'data': [
'views/rating_rating_views.xml',
'views/rating_template.xml',
'views/mail_message_views.xml',
'security/ir.model.access.csv'
],
'installable': True,
'auto_install': False,
'assets': {
'web.assets_frontend': [
'rating/static/src/scss/**/*',
],
},
'license': 'LGPL-3',
}
| 22.769231 | 592 |
3,062 |
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.exceptions import AccessError
from odoo.tests import tagged, common, new_test_user
from odoo.tools import mute_logger
@tagged('security')
class TestAccessRating(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestAccessRating, cls).setUpClass()
cls.user_manager_partner = mail_new_test_user(
cls.env, name='Jean Admin', login='user_mana', email='[email protected]',
groups='base.group_partner_manager,base.group_system'
)
cls.user_emp = mail_new_test_user(
cls.env, name='Eglantine Employee', login='user_emp', email='[email protected]',
groups='base.group_user'
)
cls.user_portal = mail_new_test_user(
cls.env, name='Patrick Portal', login='user_portal', email='[email protected]',
groups='base.group_portal'
)
cls.user_public = mail_new_test_user(
cls.env, name='Pauline Public', login='user_public', email='[email protected]',
groups='base.group_public'
)
cls.partner_to_rate = cls.env['res.partner'].with_user(cls.user_manager_partner).create({
"name": "Partner to Rate :("
})
@mute_logger('odoo.addons.base.models.ir_model')
def test_rating_access(self):
""" Security test : only a employee (user group) can create and write rating object """
# Public and portal user can't Access direclty to the ratings
with self.assertRaises(AccessError):
self.env['rating.rating'].with_user(self.user_portal).create({
'res_model_id': self.env['ir.model'].sudo().search([('model', '=', 'res.partner')], limit=1).id,
'res_model': 'res.partner',
'res_id': self.partner_to_rate.id,
'rating': 1
})
with self.assertRaises(AccessError):
self.env['rating.rating'].with_user(self.user_public).create({
'res_model_id': self.env['ir.model'].sudo().search([('model', '=', 'res.partner')], limit=1).id,
'res_model': 'res.partner',
'res_id': self.partner_to_rate.id,
'rating': 3
})
# No error with employee
ratting = self.env['rating.rating'].with_user(self.user_emp).create({
'res_model_id': self.env['ir.model'].sudo().search([('model', '=', 'res.partner')], limit=1).id,
'res_model': 'res.partner',
'res_id': self.partner_to_rate.id,
'rating': 3
})
with self.assertRaises(AccessError):
ratting.with_user(self.user_portal).write({
'feedback': 'You should not pass!'
})
with self.assertRaises(AccessError):
ratting.with_user(self.user_public).write({
'feedback': 'You should not pass!'
})
| 40.289474 | 3,062 |
1,037 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import HttpCase, tagged, new_test_user
@tagged('post_install', '-at_install')
class TestControllersRoute(HttpCase):
def setUp(self):
super(TestControllersRoute, self).setUp()
self.user = new_test_user(self.env, "test_user_1", email="[email protected]", tz="UTC")
self.partner = self.user.partner_id
def test_controller_rating(self):
rating_test = self.env['rating.rating'].with_user(self.user).create({
'res_model_id': self.env['ir.model'].sudo().search([('model', '=', 'res.partner')], limit=1).id,
'res_model': 'res.partner',
'res_id': self.partner.id,
'rating': 3
})
self.authenticate(None, None)
access_token = rating_test.access_token
url = '/rate/%s/submit_feedback' % access_token
req = self.url_open(url)
self.assertEqual(req.status_code, 200, "Response should = OK")
| 41.48 | 1,037 |
8,125 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import uuid
from odoo import api, fields, models
from odoo.modules.module import get_resource_path
RATING_LIMIT_SATISFIED = 5
RATING_LIMIT_OK = 3
RATING_LIMIT_MIN = 1
class Rating(models.Model):
_name = "rating.rating"
_description = "Rating"
_order = 'write_date desc'
_rec_name = 'res_name'
_sql_constraints = [
('rating_range', 'check(rating >= 0 and rating <= 5)', 'Rating should be between 0 and 5'),
]
@api.depends('res_model', 'res_id')
def _compute_res_name(self):
for rating in self:
name = self.env[rating.res_model].sudo().browse(rating.res_id).name_get()
rating.res_name = name and name[0][1] or ('%s/%s') % (rating.res_model, rating.res_id)
@api.model
def _default_access_token(self):
return uuid.uuid4().hex
@api.model
def _selection_target_model(self):
return [(model.model, model.name) for model in self.env['ir.model'].sudo().search([])]
create_date = fields.Datetime(string="Submitted on")
res_name = fields.Char(string='Resource name', compute='_compute_res_name', store=True, help="The name of the rated resource.")
res_model_id = fields.Many2one('ir.model', 'Related Document Model', index=True, ondelete='cascade', help='Model of the followed resource')
res_model = fields.Char(string='Document Model', related='res_model_id.model', store=True, index=True, readonly=True)
res_id = fields.Integer(string='Document', required=True, help="Identifier of the rated object", index=True)
resource_ref = fields.Reference(
string='Resource Ref', selection='_selection_target_model',
compute='_compute_resource_ref', readonly=True)
parent_res_name = fields.Char('Parent Document Name', compute='_compute_parent_res_name', store=True)
parent_res_model_id = fields.Many2one('ir.model', 'Parent Related Document Model', index=True, ondelete='cascade')
parent_res_model = fields.Char('Parent Document Model', store=True, related='parent_res_model_id.model', index=True, readonly=False)
parent_res_id = fields.Integer('Parent Document', index=True)
parent_ref = fields.Reference(
string='Parent Ref', selection='_selection_target_model',
compute='_compute_parent_ref', readonly=True)
rated_partner_id = fields.Many2one('res.partner', string="Rated Operator", help="Owner of the rated resource")
rated_partner_name = fields.Char(related="rated_partner_id.name")
partner_id = fields.Many2one('res.partner', string='Customer', help="Author of the rating")
rating = fields.Float(string="Rating Value", group_operator="avg", default=0, help="Rating value: 0=Unhappy, 5=Happy")
rating_image = fields.Binary('Image', compute='_compute_rating_image')
rating_text = fields.Selection([
('top', 'Satisfied'),
('ok', 'Okay'),
('ko', 'Dissatisfied'),
('none', 'No Rating yet')], string='Rating', store=True, compute='_compute_rating_text', readonly=True)
feedback = fields.Text('Comment', help="Reason of the rating")
message_id = fields.Many2one(
'mail.message', string="Message",
index=True, ondelete='cascade',
help="Associated message when posting a review. Mainly used in website addons.")
is_internal = fields.Boolean('Visible Internally Only', readonly=False, related='message_id.is_internal', store=True)
access_token = fields.Char('Security Token', default=_default_access_token, help="Access token to set the rating of the value")
consumed = fields.Boolean(string="Filled Rating", help="Enabled if the rating has been filled.")
@api.depends('res_model', 'res_id')
def _compute_resource_ref(self):
for rating in self:
if rating.res_model and rating.res_model in self.env:
rating.resource_ref = '%s,%s' % (rating.res_model, rating.res_id or 0)
else:
rating.resource_ref = None
@api.depends('parent_res_model', 'parent_res_id')
def _compute_parent_ref(self):
for rating in self:
if rating.parent_res_model and rating.parent_res_model in self.env:
rating.parent_ref = '%s,%s' % (rating.parent_res_model, rating.parent_res_id or 0)
else:
rating.parent_ref = None
@api.depends('parent_res_model', 'parent_res_id')
def _compute_parent_res_name(self):
for rating in self:
name = False
if rating.parent_res_model and rating.parent_res_id:
name = self.env[rating.parent_res_model].sudo().browse(rating.parent_res_id).name_get()
name = name and name[0][1] or ('%s/%s') % (rating.parent_res_model, rating.parent_res_id)
rating.parent_res_name = name
def _get_rating_image_filename(self):
self.ensure_one()
if self.rating >= RATING_LIMIT_SATISFIED:
rating_int = 5
elif self.rating >= RATING_LIMIT_OK:
rating_int = 3
elif self.rating >= RATING_LIMIT_MIN:
rating_int = 1
else:
rating_int = 0
return 'rating_%s.png' % rating_int
def _compute_rating_image(self):
for rating in self:
try:
image_path = get_resource_path('rating', 'static/src/img', rating._get_rating_image_filename())
rating.rating_image = base64.b64encode(open(image_path, 'rb').read()) if image_path else False
except (IOError, OSError):
rating.rating_image = False
@api.depends('rating')
def _compute_rating_text(self):
for rating in self:
if rating.rating >= RATING_LIMIT_SATISFIED:
rating.rating_text = 'top'
elif rating.rating >= RATING_LIMIT_OK:
rating.rating_text = 'ok'
elif rating.rating >= RATING_LIMIT_MIN:
rating.rating_text = 'ko'
else:
rating.rating_text = 'none'
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if values.get('res_model_id') and values.get('res_id'):
values.update(self._find_parent_data(values))
return super().create(vals_list)
def write(self, values):
if values.get('res_model_id') and values.get('res_id'):
values.update(self._find_parent_data(values))
return super(Rating, self).write(values)
def unlink(self):
# OPW-2181568: Delete the chatter message too
self.env['mail.message'].search([('rating_ids', 'in', self.ids)]).unlink()
return super(Rating, self).unlink()
def _find_parent_data(self, values):
""" Determine the parent res_model/res_id, based on the values to create or write """
current_model_name = self.env['ir.model'].sudo().browse(values['res_model_id']).model
current_record = self.env[current_model_name].browse(values['res_id'])
data = {
'parent_res_model_id': False,
'parent_res_id': False,
}
if hasattr(current_record, '_rating_get_parent_field_name'):
current_record_parent = current_record._rating_get_parent_field_name()
if current_record_parent:
parent_res_model = getattr(current_record, current_record_parent)
data['parent_res_model_id'] = self.env['ir.model']._get(parent_res_model._name).id
data['parent_res_id'] = parent_res_model.id
return data
def reset(self):
for record in self:
record.write({
'rating': 0,
'access_token': record._default_access_token(),
'feedback': False,
'consumed': False,
})
def action_open_rated_object(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'res_model': self.res_model,
'res_id': self.res_id,
'views': [[False, 'form']]
}
| 45.646067 | 8,125 |
1,176 |
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 MailThread(models.AbstractModel):
_inherit = 'mail.thread'
@api.returns('mail.message', lambda value: value.id)
def message_post(self, **kwargs):
rating_value = kwargs.pop('rating_value', False)
rating_feedback = kwargs.pop('rating_feedback', False)
message = super(MailThread, self).message_post(**kwargs)
# create rating.rating record linked to given rating_value. Using sudo as portal users may have
# rights to create messages and therefore ratings (security should be checked beforehand)
if rating_value:
self.env['rating.rating'].sudo().create({
'rating': float(rating_value) if rating_value is not None else False,
'feedback': rating_feedback,
'res_model_id': self.env['ir.model']._get_id(self._name),
'res_id': self.id,
'message_id': message.id,
'consumed': True,
'partner_id': self.env.user.partner_id.id,
})
return message
| 42 | 1,176 |
1,142 |
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 MailMessage(models.Model):
_inherit = 'mail.message'
rating_ids = fields.One2many('rating.rating', 'message_id', groups='base.group_user', string='Related ratings')
rating_value = fields.Float(
'Rating Value', compute='_compute_rating_value', compute_sudo=True,
store=False, search='_search_rating_value')
@api.depends('rating_ids', 'rating_ids.rating')
def _compute_rating_value(self):
ratings = self.env['rating.rating'].search([('message_id', 'in', self.ids), ('consumed', '=', True)], order='create_date DESC')
mapping = dict((r.message_id.id, r.rating) for r in ratings)
for message in self:
message.rating_value = mapping.get(message.id, 0.0)
def _search_rating_value(self, operator, operand):
ratings = self.env['rating.rating'].sudo().search([
('rating', operator, operand),
('message_id', '!=', False)
])
return [('id', 'in', ratings.mapped('message_id').ids)]
| 42.296296 | 1,142 |
14,877 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo import api, fields, models, tools
from odoo.addons.rating.models.rating import RATING_LIMIT_SATISFIED, RATING_LIMIT_OK, RATING_LIMIT_MIN
from odoo.osv import expression
class RatingParentMixin(models.AbstractModel):
_name = 'rating.parent.mixin'
_description = "Rating Parent Mixin"
_rating_satisfaction_days = False # Number of last days used to compute parent satisfaction. Set to False to include all existing rating.
rating_ids = fields.One2many(
'rating.rating', 'parent_res_id', string='Ratings',
auto_join=True, groups='base.group_user',
domain=lambda self: [('parent_res_model', '=', self._name)])
rating_percentage_satisfaction = fields.Integer(
"Rating Satisfaction",
compute="_compute_rating_percentage_satisfaction", compute_sudo=True,
store=False, help="Percentage of happy ratings")
rating_count = fields.Integer(string='# Ratings', compute="_compute_rating_percentage_satisfaction", compute_sudo=True)
@api.depends('rating_ids.rating', 'rating_ids.consumed')
def _compute_rating_percentage_satisfaction(self):
# build domain and fetch data
domain = [('parent_res_model', '=', self._name), ('parent_res_id', 'in', self.ids), ('rating', '>=', 1), ('consumed', '=', True)]
if self._rating_satisfaction_days:
domain += [('write_date', '>=', fields.Datetime.to_string(fields.datetime.now() - timedelta(days=self._rating_satisfaction_days)))]
data = self.env['rating.rating'].read_group(domain, ['parent_res_id', 'rating'], ['parent_res_id', 'rating'], lazy=False)
# get repartition of grades per parent id
default_grades = {'great': 0, 'okay': 0, 'bad': 0}
grades_per_parent = dict((parent_id, dict(default_grades)) for parent_id in self.ids) # map: {parent_id: {'great': 0, 'bad': 0, 'ok': 0}}
for item in data:
parent_id = item['parent_res_id']
rating = item['rating']
if rating > RATING_LIMIT_OK:
grades_per_parent[parent_id]['great'] += item['__count']
elif rating > RATING_LIMIT_MIN:
grades_per_parent[parent_id]['okay'] += item['__count']
else:
grades_per_parent[parent_id]['bad'] += item['__count']
# compute percentage per parent
for record in self:
repartition = grades_per_parent.get(record.id, default_grades)
record.rating_count = sum(repartition.values())
record.rating_percentage_satisfaction = repartition['great'] * 100 / sum(repartition.values()) if sum(repartition.values()) else -1
class RatingMixin(models.AbstractModel):
_name = 'rating.mixin'
_description = "Rating Mixin"
rating_ids = fields.One2many('rating.rating', 'res_id', string='Rating', groups='base.group_user', domain=lambda self: [('res_model', '=', self._name)], auto_join=True)
rating_last_value = fields.Float('Rating Last Value', groups='base.group_user', compute='_compute_rating_last_value', compute_sudo=True, store=True)
rating_last_feedback = fields.Text('Rating Last Feedback', groups='base.group_user', related='rating_ids.feedback')
rating_last_image = fields.Binary('Rating Last Image', groups='base.group_user', related='rating_ids.rating_image')
rating_count = fields.Integer('Rating count', compute="_compute_rating_stats", compute_sudo=True)
rating_avg = fields.Float("Rating Average", compute='_compute_rating_stats', compute_sudo=True)
@api.depends('rating_ids.rating', 'rating_ids.consumed')
def _compute_rating_last_value(self):
for record in self:
ratings = self.env['rating.rating'].search([('res_model', '=', self._name), ('res_id', '=', record.id), ('consumed', '=', True)], limit=1)
record.rating_last_value = ratings and ratings.rating or 0
@api.depends('rating_ids.res_id', 'rating_ids.rating')
def _compute_rating_stats(self):
""" Compute avg and count in one query, as thoses fields will be used together most of the time. """
domain = expression.AND([self._rating_domain(), [('rating', '>=', RATING_LIMIT_MIN)]])
read_group_res = self.env['rating.rating'].read_group(domain, ['rating:avg'], groupby=['res_id'], lazy=False) # force average on rating column
mapping = {item['res_id']: {'rating_count': item['__count'], 'rating_avg': item['rating']} for item in read_group_res}
for record in self:
record.rating_count = mapping.get(record.id, {}).get('rating_count', 0)
record.rating_avg = mapping.get(record.id, {}).get('rating_avg', 0)
def write(self, values):
""" If the rated ressource name is modified, we should update the rating res_name too.
If the rated ressource parent is changed we should update the parent_res_id too"""
with self.env.norecompute():
result = super(RatingMixin, self).write(values)
for record in self:
if record._rec_name in values: # set the res_name of ratings to be recomputed
res_name_field = self.env['rating.rating']._fields['res_name']
self.env.add_to_compute(res_name_field, record.rating_ids)
if record._rating_get_parent_field_name() in values:
record.rating_ids.sudo().write({'parent_res_id': record[record._rating_get_parent_field_name()].id})
return result
def unlink(self):
""" When removing a record, its rating should be deleted too. """
record_ids = self.ids
result = super(RatingMixin, self).unlink()
self.env['rating.rating'].sudo().search([('res_model', '=', self._name), ('res_id', 'in', record_ids)]).unlink()
return result
def _rating_get_parent_field_name(self):
"""Return the parent relation field name
Should return a Many2One"""
return None
def _rating_domain(self):
""" Returns a normalized domain on rating.rating to select the records to
include in count, avg, ... computation of current model.
"""
return ['&', '&', ('res_model', '=', self._name), ('res_id', 'in', self.ids), ('consumed', '=', True)]
def rating_get_partner_id(self):
if hasattr(self, 'partner_id') and self.partner_id:
return self.partner_id
return self.env['res.partner']
def rating_get_rated_partner_id(self):
if hasattr(self, 'user_id') and self.user_id.partner_id:
return self.user_id.partner_id
return self.env['res.partner']
def rating_get_access_token(self, partner=None):
""" Return access token linked to existing ratings, or create a new rating
that will create the asked token. An explicit call to access rights is
performed as sudo is used afterwards as this method could be used from
different sources, notably templates. """
self.check_access_rights('read')
self.check_access_rule('read')
if not partner:
partner = self.rating_get_partner_id()
rated_partner = self.rating_get_rated_partner_id()
ratings = self.rating_ids.sudo().filtered(lambda x: x.partner_id.id == partner.id and not x.consumed)
if not ratings:
rating = self.env['rating.rating'].sudo().create({
'partner_id': partner.id,
'rated_partner_id': rated_partner.id,
'res_model_id': self.env['ir.model']._get_id(self._name),
'res_id': self.id,
'is_internal': False,
})
else:
rating = ratings[0]
return rating.access_token
def rating_send_request(self, template, lang=False, subtype_id=False, force_send=True, composition_mode='comment', notif_layout=None):
""" This method send rating request by email, using a template given
in parameter.
:param template: a mail.template record used to compute the message body;
:param lang: optional lang; it can also be specified directly on the template
itself in the lang field;
:param subtype_id: optional subtype to use when creating the message; is
a note by default to avoid spamming followers;
:param force_send: whether to send the request directly or use the mail
queue cron (preferred option);
:param composition_mode: comment (message_post) or mass_mail (template.send_mail);
:param notif_layout: layout used to encapsulate the content when sending email;
"""
if lang:
template = template.with_context(lang=lang)
if subtype_id is False:
subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note')
if force_send:
self = self.with_context(mail_notify_force_send=True) # default value is True, should be set to false if not?
for record in self:
record.message_post_with_template(
template.id,
composition_mode=composition_mode,
email_layout_xmlid=notif_layout if notif_layout is not None else 'mail.mail_notification_light',
subtype_id=subtype_id
)
def rating_apply(self, rate, token=None, feedback=None, subtype_xmlid=None):
""" Apply a rating given a token. If the current model inherits from
mail.thread mixin, a message is posted on its chatter. User going through
this method should have at least employee rights because of rating
manipulation (either employee, either sudo-ed in public controllers after
security check granting access).
:param float rate : the rating value to apply
:param string token : access token
:param string feedback : additional feedback
:param string subtype_xmlid : xml id of a valid mail.message.subtype
:returns rating.rating record
"""
rating = None
if token:
rating = self.env['rating.rating'].search([('access_token', '=', token)], limit=1)
else:
rating = self.env['rating.rating'].search([('res_model', '=', self._name), ('res_id', '=', self.ids[0])], limit=1)
if rating:
rating.write({'rating': rate, 'feedback': feedback, 'consumed': True})
if hasattr(self, 'message_post'):
feedback = tools.plaintext2html(feedback or '')
self.message_post(
body="<img src='/rating/static/src/img/rating_%s.png' alt=':%s/5' style='width:18px;height:18px;float:left;margin-right: 5px;'/>%s"
% (rate, rate, feedback),
subtype_xmlid=subtype_xmlid or "mail.mt_comment",
author_id=rating.partner_id and rating.partner_id.id or None # None will set the default author in mail_thread.py
)
if hasattr(self, 'stage_id') and self.stage_id and hasattr(self.stage_id, 'auto_validation_kanban_state') and self.stage_id.auto_validation_kanban_state:
if rating.rating > 2:
self.write({'kanban_state': 'done'})
else:
self.write({'kanban_state': 'blocked'})
return rating
def _rating_get_repartition(self, add_stats=False, domain=None):
""" get the repatition of rating grade for the given res_ids.
:param add_stats : flag to add stat to the result
:type add_stats : boolean
:param domain : optional extra domain of the rating to include/exclude in repartition
:return dictionnary
if not add_stats, the dict is like
- key is the rating value (integer)
- value is the number of object (res_model, res_id) having the value
otherwise, key is the value of the information (string) : either stat name (avg, total, ...) or 'repartition'
containing the same dict if add_stats was False.
"""
base_domain = expression.AND([self._rating_domain(), [('rating', '>=', 1)]])
if domain:
base_domain += domain
data = self.env['rating.rating'].read_group(base_domain, ['rating'], ['rating', 'res_id'])
# init dict with all posible rate value, except 0 (no value for the rating)
values = dict.fromkeys(range(1, 6), 0)
values.update((d['rating'], d['rating_count']) for d in data)
# add other stats
if add_stats:
rating_number = sum(values.values())
result = {
'repartition': values,
'avg': sum(float(key * values[key]) for key in values) / rating_number if rating_number > 0 else 0,
'total': sum(it['rating_count'] for it in data),
}
return result
return values
def rating_get_grades(self, domain=None):
""" get the repatition of rating grade for the given res_ids.
:param domain : optional domain of the rating to include/exclude in grades computation
:return dictionnary where the key is the grade (great, okay, bad), and the value, the number of object (res_model, res_id) having the grade
the grade are compute as 0-30% : Bad
31-69%: Okay
70-100%: Great
"""
data = self._rating_get_repartition(domain=domain)
res = dict.fromkeys(['great', 'okay', 'bad'], 0)
for key in data:
if key >= RATING_LIMIT_SATISFIED:
res['great'] += data[key]
elif key >= RATING_LIMIT_OK:
res['okay'] += data[key]
else:
res['bad'] += data[key]
return res
def rating_get_stats(self, domain=None):
""" get the statistics of the rating repatition
:param domain : optional domain of the rating to include/exclude in statistic computation
:return dictionnary where
- key is the name of the information (stat name)
- value is statistic value : 'percent' contains the repartition in percentage, 'avg' is the average rate
and 'total' is the number of rating
"""
data = self._rating_get_repartition(domain=domain, add_stats=True)
result = {
'avg': data['avg'],
'total': data['total'],
'percent': dict.fromkeys(range(1, 6), 0),
}
for rate in data['repartition']:
result['percent'][rate] = (data['repartition'][rate] * 100) / data['total'] if data['total'] > 0 else 0
return result
| 54.29562 | 14,877 |
2,917 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import http
from odoo.http import request
from odoo.tools.translate import _
from odoo.tools.misc import get_lang
_logger = logging.getLogger(__name__)
MAPPED_RATES = {
1: 1,
5: 3,
10: 5,
}
class Rating(http.Controller):
@http.route('/rating/<string:token>/<int:rate>', type='http', auth="public", website=True)
def open_rating(self, token, rate, **kwargs):
_logger.warning('/rating is deprecated, use /rate instead')
assert rate in (1, 5, 10), "Incorrect rating"
return self.action_open_rating(token, MAPPED_RATES.get(rate), **kwargs)
@http.route(['/rating/<string:token>/submit_feedback'], type="http", auth="public", methods=['post'], website=True)
def submit_rating(self, token, **kwargs):
_logger.warning('/rating is deprecated, use /rate instead')
rate = int(kwargs.get('rate'))
assert rate in (1, 5, 10), "Incorrect rating"
kwargs['rate'] = MAPPED_RATES.gate(rate)
return self.action_submit_rating(token, **kwargs)
@http.route('/rate/<string:token>/<int:rate>', type='http', auth="public", website=True)
def action_open_rating(self, token, rate, **kwargs):
assert rate in (1, 3, 5), "Incorrect rating"
rating = request.env['rating.rating'].sudo().search([('access_token', '=', token)])
if not rating:
return request.not_found()
rate_names = {
5: _("Satisfied"),
3: _("Okay"),
1: _("Dissatisfied")
}
rating.write({'rating': rate, 'consumed': True})
lang = rating.partner_id.lang or get_lang(request.env).code
return request.env['ir.ui.view'].with_context(lang=lang)._render_template('rating.rating_external_page_submit', {
'rating': rating, 'token': token,
'rate_names': rate_names, 'rate': rate
})
@http.route(['/rate/<string:token>/submit_feedback'], type="http", auth="public", methods=['post', 'get'], website=True)
def action_submit_rating(self, token, **kwargs):
rating = request.env['rating.rating'].sudo().search([('access_token', '=', token)])
if not rating:
return request.not_found()
if request.httprequest.method == "POST":
rate = int(kwargs.get('rate'))
assert rate in (1, 3, 5), "Incorrect rating"
record_sudo = request.env[rating.res_model].sudo().browse(rating.res_id)
record_sudo.rating_apply(rate, token=token, feedback=kwargs.get('feedback'))
lang = rating.partner_id.lang or get_lang(request.env).code
return request.env['ir.ui.view'].with_context(lang=lang)._render_template('rating.rating_external_page_view', {
'web_base_url': rating.get_base_url(),
'rating': rating,
})
| 43.537313 | 2,917 |
1,246 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2011 Smartmode LTD (<http://www.smartmode.co.uk>).
{
'name': 'United Kingdom - Accounting',
'version': '1.0',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the latest UK Odoo localisation necessary to run Odoo accounting for UK SME's with:
=================================================================================================
- a CT600-ready chart of accounts
- VAT100-ready tax structure
- InfoLogic UK counties listing
- a few other adaptations""",
'author': 'SmartMode LTD',
'website': 'https://www.odoo.com/app/accounting',
'depends': [
'account',
'base_iban',
'base_vat',
],
'data': [
'data/l10n_uk_chart_data.xml',
'data/account.account.template.csv',
'data/account.chart.template.csv',
'data/account.tax.group.csv',
'data/account_tax_report_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/l10n_uk_demo.xml',
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 32.789474 | 1,246 |
820 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Mail Plugin',
'version': '1.0',
'category': 'Sales/CRM',
'sequence': 5,
'summary': 'Allows integration with mail plugins.',
'description': "Integrate Odoo with your mailbox, get information about contacts directly inside your mailbox, log content of emails as internal notes",
'depends': [
'web',
'contacts',
'iap'
],
'web.assets_backend': [
'mail_plugin/static/src/to_translate/**/*',
],
'data': [
'views/mail_plugin_login.xml',
'views/res_partner_iap_views.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': False,
'license': 'LGPL-3',
}
| 29.285714 | 820 |
3,204 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from contextlib import contextmanager
from unittest.mock import patch
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.http import request
from odoo.tests.common import HttpCase
@contextmanager
def mock_auth_method_outlook(login):
"""Mock the Outlook auth method.
This must be used as a method decorator.
:param login: Login of the user used for the authentication
"""
def patched_auth_method_outlook(*args, **kwargs):
request.uid = request.env['res.users'].search([('login', '=', login)], limit=1).id
with patch(
'odoo.addons.mail_plugin.models.ir_http.IrHttp'
'._auth_method_outlook',
new=patched_auth_method_outlook):
yield
class TestMailPluginControllerCommon(HttpCase):
def setUp(self):
super(TestMailPluginControllerCommon, self).setUp()
self.user_test = mail_new_test_user(
self.env,
login="employee",
groups="base.group_user,base.group_partner_manager",
)
@mock_auth_method_outlook('employee')
def mock_plugin_partner_get(self, name, email, patched_iap_enrich):
"""Simulate a HTTP call to /partner/get with the given email and name.
The authentication process is patched to allow all queries.
The third argument "patched_iap_enrich" allow you to mock the IAP request and
to return the response you want.
"""
data = {
"id": 0,
"jsonrpc": "2.0",
"method": "call",
"params": {"email": email, "name": name},
}
with patch(
"odoo.addons.mail_plugin.controllers.mail_plugin.MailPluginController"
"._iap_enrich",
new=patched_iap_enrich,
):
result = self.url_open(
"/mail_plugin/partner/get",
data=json.dumps(data).encode(),
headers={"Content-Type": "application/json"},
)
if not result.ok:
return {}
return result.json().get("result", {})
@mock_auth_method_outlook('employee')
def mock_enrich_and_create_company(self, partner_id, patched_iap_enrich):
"""Simulate a HTTP call to /partner/enrich_and_create_company on the given partner.
The third argument "patched_iap_enrich" allow you to mock the IAP request and
to return the response you want.
"""
data = {
"id": 0,
"jsonrpc": "2.0",
"method": "call",
"params": {"partner_id": partner_id},
}
with patch(
"odoo.addons.mail_plugin.controllers.mail_plugin.MailPluginController"
"._iap_enrich",
new=patched_iap_enrich,
):
result = self.url_open(
"/mail_plugin/partner/enrich_and_create_company",
data=json.dumps(data).encode(),
headers={"Content-Type": "application/json"},
)
if not result.ok:
return {}
return result.json().get("result", {})
| 32.04 | 3,204 |
3,457 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import psycopg2
from odoo.addons.mail.tests.common import MailCommon
from odoo.tools import mute_logger
class TestResPartnerIap(MailCommon):
@mute_logger("odoo.sql_db")
def test_res_partner_iap_constraint(self):
partner = self.partner_employee
self.env["res.partner.iap"].search([("partner_id", "=", partner.id)]).unlink()
self.env["res.partner.iap"].create({"partner_id": partner.id, "iap_enrich_info": "test info"})
with self.assertRaises(psycopg2.IntegrityError, msg="Can create only one partner IAP per partner"):
self.env["res.partner.iap"].create({"partner_id": partner.id, "iap_enrich_info": "test info"})
def test_res_partner_iap_compute_iap_enrich_info(self):
partner = self.partner_employee
self.assertFalse(partner.iap_enrich_info)
partner_iap = self.env["res.partner.iap"].create({"partner_id": partner.id, "iap_enrich_info": "test info"})
partner.invalidate_cache()
self.assertEqual(partner.iap_enrich_info, "test info")
partner_iap.unlink()
partner.iap_enrich_info = "test info 2"
partner_iap = self.env["res.partner.iap"].search([("partner_id", "=", partner.id)])
self.assertTrue(partner_iap, "Should have create the <res.partner.iap>")
self.assertEqual(partner_iap.iap_enrich_info, "test info 2")
partner.iap_enrich_info = "test info 3"
partner_iap.invalidate_cache()
new_partner_iap = self.env["res.partner.iap"].search([("partner_id", "=", partner.id)])
self.assertEqual(new_partner_iap, partner_iap, "Should have write on the existing one")
self.assertEqual(partner_iap.iap_enrich_info, "test info 3")
def test_res_partner_iap_creation(self):
partner = self.env['res.partner'].create({
'name': 'Test partner',
'iap_enrich_info': 'enrichment information',
'iap_search_domain': '[email protected]',
})
partner.invalidate_cache()
self.assertEqual(partner.iap_enrich_info, 'enrichment information')
self.assertEqual(partner.iap_search_domain, '[email protected]')
partner_iap = self.env['res.partner.iap'].search([('partner_id', '=', partner.id)])
self.assertEqual(len(partner_iap), 1, 'Should create only one <res.partner.iap>')
self.assertEqual(partner_iap.iap_enrich_info, 'enrichment information')
self.assertEqual(partner_iap.iap_search_domain, '[email protected]')
def test_res_partner_iap_writing(self):
partner = self.env['res.partner'].create({
'name': 'Test partner 2',
})
partner.write({
'iap_enrich_info': 'second information',
'iap_search_domain': '[email protected]',
})
partner_iap = self.env['res.partner.iap'].search([('partner_id', '=', partner.id)])
self.assertEqual(len(partner_iap), 1, 'Should create only one <res.partner.iap>')
self.assertEqual(partner_iap.iap_enrich_info, 'second information')
self.assertEqual(partner_iap.iap_search_domain, '[email protected]')
partner.iap_search_domain = "only write on domain"
partner_iap.invalidate_cache()
self.assertEqual(partner_iap.iap_enrich_info, 'second information')
self.assertEqual(partner_iap.iap_search_domain, 'only write on domain')
| 44.896104 | 3,457 |
6,189 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from unittest.mock import Mock, patch
from odoo.addons.iap.tools import iap_tools
from odoo.addons.mail_plugin.tests.common import TestMailPluginControllerCommon, mock_auth_method_outlook
class TestMailPluginController(TestMailPluginControllerCommon):
def test_enrich_and_create_company(self):
partner = self.env["res.partner"].create({
"name": "Test partner",
"email": "test@test_domain.xyz",
"is_company": False,
})
result = self.mock_enrich_and_create_company(
partner.id,
lambda _, domain: {"return": domain},
)
self.assertEqual(result["enrichment_info"], {"type": "company_created"})
self.assertEqual(result["company"]["additionalInfo"]["return"], "test_domain.xyz")
company_id = result["company"]["id"]
company = self.env["res.partner"].browse(company_id)
partner.invalidate_cache()
self.assertEqual(partner.parent_id, company, "Should change the company of the partner")
@mock_auth_method_outlook('employee')
def test_get_partner_blacklisted_domain(self):
"""Test enrichment on a blacklisted domain, should return an error."""
domain = list(iap_tools._MAIL_DOMAIN_BLACKLIST)[0]
data = {
"id": 0,
"jsonrpc": "2.0",
"method": "call",
"params": {"email": "contact@" + domain, "name": "test"},
}
mocked_request_enrich = Mock()
with patch(
"odoo.addons.iap.models.iap_enrich_api.IapEnrichAPI"
"._request_enrich",
new=mocked_request_enrich,
):
result = self.url_open(
"/mail_plugin/partner/get",
data=json.dumps(data).encode(),
headers={"Content-Type": "application/json"},
).json().get("result", {})
self.assertFalse(mocked_request_enrich.called)
self.assertEqual(result['partner']['enrichment_info']['type'], 'missing_data')
def test_get_partner_company_found(self):
company = self.env["res.partner"].create({
"name": "Test partner",
"email": "test@test_domain.xyz",
"is_company": True,
})
mock_iap_enrich = Mock()
result = self.mock_plugin_partner_get("Test", "qsd@test_domain.xyz", mock_iap_enrich)
self.assertFalse(mock_iap_enrich.called)
self.assertEqual(result["partner"]["id"], -1)
self.assertEqual(result["partner"]["email"], "qsd@test_domain.xyz")
self.assertEqual(result["partner"]["company"]["id"], company.id)
self.assertFalse(result["partner"]["company"]["additionalInfo"])
def test_get_partner_company_not_found(self):
self.env["res.partner"].create({
"name": "Test partner",
"email": "test@test_domain.xyz",
"is_company": False,
})
result = self.mock_plugin_partner_get(
"Test",
"qsd@test_domain.xyz",
lambda _, domain: {"enrichment_info": "missing_data"},
)
self.assertEqual(result["partner"]["id"], -1)
self.assertEqual(result["partner"]["email"], "qsd@test_domain.xyz")
self.assertEqual(result["partner"]["company"]["id"], -1)
def test_get_partner_iap_return_different_domain(self):
"""
Test the case where the domain of the email returned by IAP is not the same as
the domain requested.
"""
result = self.mock_plugin_partner_get(
"Test",
"qsd@test_domain.xyz",
lambda _, domain: {
"name": "Name",
"email": ["[email protected]"],
"iap_information": "test",
},
)
first_company_id = result["partner"]["company"]["id"]
first_company = self.env["res.partner"].browse(first_company_id)
self.assertEqual(result["partner"]["id"], -1)
self.assertEqual(result["partner"]["email"], "qsd@test_domain.xyz")
self.assertTrue(first_company_id, "Should have created the company")
self.assertEqual(result["partner"]["company"]["additionalInfo"]["iap_information"], "test")
self.assertEqual(first_company.name, "Name")
self.assertEqual(first_company.email, "[email protected]")
# Test that we do not duplicate the company and that we return the previous one
mock_iap_enrich = Mock()
result = self.mock_plugin_partner_get("Test", "qsd@test_domain.xyz", mock_iap_enrich)
self.assertFalse(mock_iap_enrich.called, "We already enriched this company, should not call IAP a second time")
second_company_id = result["partner"]["company"]["id"]
self.assertEqual(first_company_id, second_company_id, "Should not create a new company")
self.assertEqual(result["partner"]["company"]["additionalInfo"]["iap_information"], "test")
def test_get_partner_no_email_returned_by_iap(self):
"""Test the case where IAP do not return an email address.
We should not duplicate the previously enriched company and we should be able to
retrieve the first one.
"""
result = self.mock_plugin_partner_get(
"Test", "[email protected]",
lambda _, domain: {"name": "Name", "email": []},
)
first_company_id = result["partner"]["company"]["id"]
self.assertTrue(first_company_id and first_company_id > 0)
first_company = self.env["res.partner"].browse(first_company_id)
self.assertEqual(first_company.name, "Name")
self.assertFalse(first_company.email)
# Test that we do not duplicate the company and that we return the previous one
result = self.mock_plugin_partner_get(
"Test", "[email protected]",
lambda _, domain: {"name": "Name", "email": ["contact@" + domain]},
)
second_company_id = result["partner"]["company"]["id"]
self.assertEqual(first_company_id, second_company_id, "Should not create a new company")
| 40.45098 | 6,189 |
833 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.exceptions import BadRequest
from odoo import models
from odoo.http import request
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
@classmethod
def _auth_method_outlook(cls):
access_token = request.httprequest.headers.get('Authorization')
if not access_token:
raise BadRequest('Access token missing')
if access_token.startswith('Bearer '):
access_token = access_token[7:]
user_id = request.env["res.users.apikeys"]._check_credentials(scope='odoo.plugin.outlook', key=access_token)
if not user_id:
raise BadRequest('Access token invalid')
# take the identity of the API key user
request.uid = user_id
| 32.038462 | 833 |
1,105 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class ResPartnerIap(models.Model):
"""Technical model which stores the response returned by IAP.
The goal of this model is to not enrich 2 times the same company. We do it in a
separate model to not add heavy field (iap_enrich_info) on the <res.partner>
model.
We also save the requested domain, so whatever the values are on the <res.partner>,
we will always retrieve the already enriched <res.partner> and the corresponding
IAP information.
"""
_name = 'res.partner.iap'
_description = 'Partner IAP'
partner_id = fields.Many2one('res.partner', string='Partner', help='Corresponding partner',
ondelete='cascade', required=True)
iap_search_domain = fields.Char('Search Domain / Email', help='Domain used to find the company')
iap_enrich_info = fields.Text('IAP Enrich Info', help='IAP response stored as a JSON string', readonly=True)
_sql_constraints = [('unique_partner_id', 'UNIQUE(partner_id)', 'Only one partner IAP is allowed for one partner')]
| 40.925926 | 1,105 |
2,878 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
iap_enrich_info = fields.Text('IAP Enrich Info', help='IAP response stored as a JSON string',
compute='_compute_partner_iap_info')
iap_search_domain = fields.Char('Search Domain / Email',
compute='_compute_partner_iap_info')
def _compute_partner_iap_info(self):
partner_iaps = self.env['res.partner.iap'].sudo().search([('partner_id', 'in', self.ids)])
partner_iaps_per_partner = {
partner_iap.partner_id: partner_iap
for partner_iap in partner_iaps
}
for partner in self:
partner_iap = partner_iaps_per_partner.get(partner)
if partner_iap:
partner.iap_enrich_info = partner_iap.iap_enrich_info
partner.iap_search_domain = partner_iap.iap_search_domain
else:
partner.iap_enrich_info = False
partner.iap_search_domain = False
@api.model
def create(self, vals):
partner = super(ResPartner, self).create(vals)
if vals.get('iap_enrich_info') or vals.get('iap_search_domain'):
# Not done with inverse method so we do not need to search
# for existing <res.partner.iap>
self.env['res.partner.iap'].sudo().create({
'partner_id': partner.id,
'iap_enrich_info': vals.get('iap_enrich_info'),
'iap_search_domain': vals.get('iap_search_domain'),
})
return partner
def write(self, vals):
res = super(ResPartner, self).write(vals)
if 'iap_enrich_info' in vals or 'iap_search_domain' in vals:
# Not done with inverse method so we do need to search
# for existing <res.partner.iap> only once
partner_iaps = self.env['res.partner.iap'].sudo().search([('partner_id', 'in', self.ids)])
missing_partners = self
for partner_iap in partner_iaps:
if 'iap_enrich_info' in vals:
partner_iap.iap_enrich_info = vals['iap_enrich_info']
if 'iap_search_domain' in vals:
partner_iap.iap_search_domain = vals['iap_search_domain']
missing_partners -= partner_iap.partner_id
if missing_partners:
# Create new <res.partner.iap> for missing records
self.env['res.partner.iap'].sudo().create([
{
'partner_id': partner.id,
'iap_enrich_info': vals.get('iap_enrich_info'),
'iap_search_domain': vals.get('iap_search_domain'),
} for partner in missing_partners
])
return res
| 41.114286 | 2,878 |
18,707 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import json
import logging
import requests
from werkzeug.exceptions import Forbidden
from odoo import http, tools, _
from odoo.addons.iap.tools import iap_tools
from odoo.exceptions import AccessError
from odoo.http import request
_logger = logging.getLogger(__name__)
class MailPluginController(http.Controller):
@http.route('/mail_client_extension/modules/get', type="json", auth="outlook", csrf=False, cors="*")
def modules_get(self, **kwargs):
"""
deprecated as of saas-14.3, not needed for newer versions of the mail plugin but necessary
for supporting older versions
"""
return {'modules': ['contacts', 'crm']}
@http.route('/mail_plugin/partner/enrich_and_create_company',
type="json", auth="outlook", cors="*")
def res_partner_enrich_and_create_company(self, partner_id):
"""
Route used when the user clicks on the create and enrich partner button
it will try to find a company using IAP, if a company is found
the enriched company will then be created in the database
"""
partner = request.env['res.partner'].browse(partner_id).exists()
if not partner:
return {'error': _("This partner does not exist")}
if partner.parent_id:
return {'error': _("The partner already has a company related to him")}
normalized_email = partner.email_normalized
if not normalized_email:
return {'error': _('Contact has no valid email')}
company, enrichment_info = self._create_company_from_iap(normalized_email)
if company:
partner.write({'parent_id': company})
return {
'enrichment_info': enrichment_info,
'company': self._get_company_data(company),
}
@http.route('/mail_plugin/partner/enrich_and_update_company', type='json', auth='outlook', cors='*')
def res_partner_enrich_and_update_company(self, partner_id):
"""
Enriches an existing company using IAP
"""
partner = request.env['res.partner'].browse(partner_id).exists()
if not partner:
return {'error': _("This partner does not exist")}
if not partner.is_company:
return {'error': 'Contact must be a company'}
normalized_email = partner.email_normalized
if not normalized_email:
return {'error': 'Contact has no valid email'}
domain = tools.email_domain_extract(normalized_email)
iap_data = self._iap_enrich(domain)
if 'enrichment_info' in iap_data: # means that an issue happened with the enrichment request
return {
'enrichment_info': iap_data['enrichment_info'],
'company': self._get_company_data(partner),
}
phone_numbers = iap_data.get('phone_numbers')
partner_values = {}
if not partner.phone and phone_numbers:
partner_values.update({'phone': phone_numbers[0]})
if not partner.iap_enrich_info:
partner_values.update({'iap_enrich_info': json.dumps(iap_data)})
if not partner.image_128:
logo_url = iap_data.get('logo')
if logo_url:
try:
response = requests.get(logo_url, timeout=2)
if response.ok:
partner_values.update({'image_1920': base64.b64encode(response.content)})
except Exception:
pass
model_fields_to_iap_mapping = {
'street': 'street_name',
'city': 'city',
'zip': 'postal_code',
'website': 'domain',
}
# only update keys for which we dont have values yet
partner_values.update({
model_field: iap_data.get(iap_key)
for model_field, iap_key in model_fields_to_iap_mapping.items() if not partner[model_field]
})
partner.write(partner_values)
partner.message_post_with_view(
'iap_mail.enrich_company',
values=iap_data,
subtype_id=request.env.ref('mail.mt_note').id,
)
return {
'enrichment_info': {'type': 'company_updated'},
'company': self._get_company_data(partner),
}
@http.route(['/mail_client_extension/partner/get', '/mail_plugin/partner/get']
, type="json", auth="outlook", cors="*")
def res_partner_get(self, email=None, name=None, partner_id=None, **kwargs):
"""
returns a partner given it's id or an email and a name.
In case the partner does not exist, we return partner having an id -1, we also look if an existing company
matching the contact exists in the database, if none is found a new company is enriched and created automatically
old route name "/mail_client_extension/partner/get is deprecated as of saas-14.3, it is not needed for newer
versions of the mail plugin but necessary for supporting older versions, only the route name is deprecated not
the entire method.
"""
if not (partner_id or (name and email)):
return {'error': _('You need to specify at least the partner_id or the name and the email')}
if partner_id:
partner = request.env['res.partner'].browse(partner_id).exists()
return self._get_contact_data(partner)
normalized_email = tools.email_normalize(email)
if not normalized_email:
return {'error': _('Bad Email.')}
# Search for the partner based on the email.
# If multiple are found, take the first one.
partner = request.env['res.partner'].search(['|', ('email', 'in', [normalized_email, email]),
('email_normalized', '=', normalized_email)], limit=1)
response = self._get_contact_data(partner)
# if no partner is found in the database, we should also return an empty one having id = -1, otherwise older versions of
# plugin won't work
if not response['partner']:
response['partner'] = {
'id': -1,
'email': email,
'name': name,
'enrichment_info': None,
}
company = self._find_existing_company(normalized_email)
can_create_partner = request.env['res.partner'].check_access_rights('create', raise_exception=False)
if not company and can_create_partner: # create and enrich company
company, enrichment_info = self._create_company_from_iap(normalized_email)
response['partner']['enrichment_info'] = enrichment_info
response['partner']['company'] = self._get_company_data(company)
return response
@http.route('/mail_plugin/partner/search', type="json", auth="outlook", cors="*")
def res_partners_search(self, search_term, limit=30, **kwargs):
"""
Used for the plugin search contact functionality where the user types a string query in order to search for
matching contacts, the string query can either be the name of the contact, it's reference or it's email.
We choose these fields because these are probably the most interesting fields that the user can perform a
search on.
The method returns an array containing the dicts of the matched contacts.
"""
normalized_email = tools.email_normalize(search_term)
if normalized_email:
filter_domain = [('email_normalized', 'ilike', search_term)]
else:
filter_domain = ['|', '|', ('display_name', 'ilike', search_term), ('ref', '=', search_term),
('email', 'ilike', search_term)]
# Search for the partner based on the email.
# If multiple are found, take the first one.
partners = request.env['res.partner'].search(filter_domain, limit=limit)
partners = [
self._get_partner_data(partner)
for partner in partners
]
return {"partners": partners}
@http.route(['/mail_client_extension/partner/create', '/mail_plugin/partner/create'],
type="json", auth="outlook", cors="*")
def res_partner_create(self, email, name, company):
"""
params email: email of the new partner
params name: name of the new partner
params company: parent company id of the new partner
"""
# old route name "/mail_client_extension/partner/create is deprecated as of saas-14.3,it is not needed for newer
# versions of the mail plugin but necessary for supporting older versions
# TODO search the company again instead of relying on the one provided here?
# Create the partner if needed.
partner_info = {
'name': name,
'email': email,
}
#see if the partner has a parent company
if company and company > -1:
partner_info['parent_id'] = company
partner = request.env['res.partner'].create(partner_info)
response = {'id': partner.id}
return response
@http.route('/mail_plugin/log_mail_content', type="json", auth="outlook", cors="*")
def log_mail_content(self, model, res_id, message, attachments=None):
"""Log the email on the given record.
:param model: Model of the record on which we want to log the email
:param res_id: ID of the record
:param message: Body of the email
:param attachments: List of attachments of the email.
List of tuple: (filename, base 64 encoded content)
"""
if model not in self._mail_content_logging_models_whitelist():
raise Forbidden()
if attachments:
attachments = [
(name, base64.b64decode(content))
for name, content in attachments
]
request.env[model].browse(res_id).message_post(body=message, attachments=attachments)
return True
@http.route('/mail_plugin/get_translations', type="json", auth="outlook", cors="*")
def get_translations(self):
return self._prepare_translations()
def _iap_enrich(self, domain):
"""
Returns enrichment data for a given domain, in case an error happens the response will
contain an enrichment_info key explaining what went wrong
"""
if domain in iap_tools._MAIL_DOMAIN_BLACKLIST:
# Can not enrich the provider domain names (gmail.com; outlook.com, etc)
return {'enrichment_info': {'type': 'missing_data'}}
enriched_data = {}
try:
response = request.env['iap.enrich.api']._request_enrich({domain: domain}) # The key doesn't matter
except iap_tools.InsufficientCreditError:
enriched_data['enrichment_info'] = {'type': 'insufficient_credit', 'info': request.env['iap.account'].get_credits_url('reveal')}
except Exception:
enriched_data["enrichment_info"] = {'type': 'other', 'info': 'Unknown reason'}
else:
enriched_data = response.get(domain)
if not enriched_data:
enriched_data = {'enrichment_info': {'type': 'no_data', 'info': 'The enrichment API found no data for the email provided.'}}
return enriched_data
def _find_existing_company(self, email):
"""Find the company corresponding to the given domain and its IAP cache.
:param email: Email of the company we search
:return: The partner corresponding to the company
"""
search = self._get_iap_search_term(email)
partner_iap = request.env["res.partner.iap"].sudo().search([("iap_search_domain", "=", search)], limit=1)
if partner_iap:
return partner_iap.partner_id
return request.env["res.partner"].search([("is_company", "=", True), ("email_normalized", "=ilike", "%" + search)], limit=1)
def _get_company_data(self, company):
if not company:
return {'id': -1}
fields_list = ['id', 'name', 'phone', 'mobile', 'email', 'website']
company_values = dict((fname, company[fname]) for fname in fields_list)
company_values['address'] = {'street': company.street,
'city': company.city,
'zip': company.zip,
'country': company.country_id.name if company.country_id else ''}
company_values['additionalInfo'] = json.loads(company.iap_enrich_info) if company.iap_enrich_info else {}
company_values['image'] = company.image_1920
return company_values
def _create_company_from_iap(self, email):
domain = tools.email_domain_extract(email)
iap_data = self._iap_enrich(domain)
if 'enrichment_info' in iap_data:
return None, iap_data['enrichment_info']
phone_numbers = iap_data.get('phone_numbers')
emails = iap_data.get('email')
new_company_info = {
'is_company': True,
'name': iap_data.get("name") or domain,
'street': iap_data.get("street_name"),
'city': iap_data.get("city"),
'zip': iap_data.get("postal_code"),
'phone': phone_numbers[0] if phone_numbers else None,
'website': iap_data.get("domain"),
'email': emails[0] if emails else None
}
logo_url = iap_data.get('logo')
if logo_url:
try:
response = requests.get(logo_url, timeout=2)
if response.ok:
new_company_info['image_1920'] = base64.b64encode(response.content)
except Exception as e:
_logger.warning('Download of image for new company %s failed, error %s', new_company_info.name, e)
if iap_data.get('country_code'):
country = request.env['res.country'].search([('code', '=', iap_data['country_code'].upper())])
if country:
new_company_info['country_id'] = country.id
if iap_data.get('state_code'):
state = request.env['res.country.state'].search([
('code', '=', iap_data['state_code']),
('country_id', '=', country.id)
])
if state:
new_company_info['state_id'] = state.id
new_company_info.update({
'iap_search_domain': self._get_iap_search_term(email),
'iap_enrich_info': json.dumps(iap_data),
})
new_company = request.env['res.partner'].create(new_company_info)
new_company.message_post_with_view(
'iap_mail.enrich_company',
values=iap_data,
subtype_id=request.env.ref('mail.mt_note').id,
)
return new_company, {'type': 'company_created'}
def _get_partner_data(self, partner):
fields_list = ['id', 'name', 'email', 'phone', 'mobile', 'is_company']
partner_values = dict((fname, partner[fname]) for fname in fields_list)
partner_values['image'] = partner.image_128
partner_values['title'] = partner.function
partner_values['enrichment_info'] = None
try:
partner.check_access_rights('write')
partner.check_access_rule('write')
partner_values['can_write_on_partner'] = True
except AccessError:
partner_values['can_write_on_partner'] = False
if not partner_values['name']:
# Always ensure that the partner has a name
name, email = request.env['res.partner']._parse_partner_name(
partner_values['email'])
partner_values['name'] = name or email
return partner_values
def _get_contact_data(self, partner):
"""
method used to return partner related values, it can be overridden by other modules if extra information have to
be returned with the partner (e.g., leads, ...)
"""
if partner:
partner_response = self._get_partner_data(partner)
if partner.company_type == 'company':
partner_response['company'] = self._get_company_data(partner)
elif partner.parent_id:
partner_response['company'] = self._get_company_data(partner.parent_id)
else:
partner_response['company'] = self._get_company_data(None)
else: # no partner found
partner_response = {}
return {
'partner': partner_response,
'user_companies': request.env.user.company_ids.ids,
'can_create_partner': request.env['res.partner'].check_access_rights(
'create', raise_exception=False),
}
def _mail_content_logging_models_whitelist(self):
"""
Returns all models that emails can be logged to and that can be used by the "log_mail_content" method,
it can be overridden by sub modules in order to whitelist more models
"""
return ['res.partner']
def _get_iap_search_term(self, email):
"""Return the domain or the email depending if the domain is blacklisted or not.
So if the domain is blacklisted, we search based on the entire email address
(e.g. [email protected]). But if the domain is not blacklisted, we search based on
the domain (e.g. [email protected] -> sncb.be)
"""
domain = tools.email_domain_extract(email)
return ("@" + domain) if domain not in iap_tools._MAIL_DOMAIN_BLACKLIST else email
def _translation_modules_whitelist(self):
"""
Returns the list of modules to be translated
Other mail plugin modules have to override this method to include their module names
"""
return ['mail_plugin']
def _prepare_translations(self):
lang = request.env['res.users'].browse(request.uid).lang
translations_per_module = request.env["ir.translation"].get_translations_for_webclient(
self._translation_modules_whitelist(), lang)[0]
translations_dict = {}
for module in self._translation_modules_whitelist():
translations = translations_per_module.get(module, {})
messages = translations.get('messages', {})
for message in messages:
translations_dict.update({message['id']: message['string']})
return translations_dict
| 41.663697 | 18,707 |
5,284 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import datetime
import hmac
import json
import logging
import odoo
import werkzeug
from odoo import http
from odoo.http import request
_logger = logging.getLogger(__name__)
class Authenticate(http.Controller):
@http.route(['/mail_client_extension/auth', '/mail_plugin/auth'], type='http', auth="user", methods=['GET'], website=True)
def auth(self, **values):
"""
Once authenticated this route renders the view that shows an app wants to access Odoo.
The user is invited to allow or deny the app. The form posts to `/mail_client_extension/auth/confirm`.
old route name "/mail_client_extension/auth is deprecated as of saas-14.3,it is not needed for newer
versions of the mail plugin but necessary for supporting older versions
"""
return request.render('mail_plugin.app_auth', values)
@http.route(['/mail_client_extension/auth/confirm', '/mail_plugin/auth/confirm'], type='http', auth="user", methods=['POST'])
def auth_confirm(self, scope, friendlyname, redirect, info=None, do=None, **kw):
"""
Called by the `app_auth` template. If the user decided to allow the app to access Odoo, a temporary auth code
is generated and he is redirected to `redirect` with this code in the URL. It should redirect to the app, and
the app should then exchange this auth code for an access token by calling
`/mail_client/auth/access_token`.
old route name "/mail_client_extension/auth/confirm is deprecated as of saas-14.3,it is not needed for newer
versions of the mail plugin but necessary for supporting older versions
"""
parsed_redirect = werkzeug.urls.url_parse(redirect)
params = parsed_redirect.decode_query()
if do:
name = friendlyname if not info else f'{friendlyname}: {info}'
auth_code = self._generate_auth_code(scope, name)
# params is a MultiDict which does not support .update() with kwargs
# the state attribute is needed for the gmail connector
params.update({'success': 1, 'auth_code': auth_code, 'state': kw.get('state', '')})
else:
params.update({'success': 0, 'state': kw.get('state', '')})
updated_redirect = parsed_redirect.replace(query=werkzeug.urls.url_encode(params))
return request.redirect(updated_redirect.to_url(), local=False)
# In this case, an exception will be thrown in case of preflight request if only POST is allowed.
@http.route(['/mail_client_extension/auth/access_token', '/mail_plugin/auth/access_token'], type='json', auth="none", cors="*",
methods=['POST', 'OPTIONS'])
def auth_access_token(self, auth_code='', **kw):
"""
Called by the external app to exchange an auth code, which is temporary and was passed in a URL, for an
access token, which is permanent, and can be used in the `Authorization` header to authorize subsequent requests
old route name "/mail_client_extension/auth/access_token is deprecated as of saas-14.3,it is not needed for newer
versions of the mail plugin but necessary for supporting older versions
"""
if not auth_code:
return {"error": "Invalid code"}
auth_message = self._get_auth_code_data(auth_code)
if not auth_message:
return {"error": "Invalid code"}
request.uid = auth_message['uid']
scope = 'odoo.plugin.' + auth_message.get('scope', '')
api_key = request.env['res.users.apikeys']._generate(scope, auth_message['name'])
return {'access_token': api_key}
def _get_auth_code_data(self, auth_code):
data, auth_code_signature = auth_code.split('.')
data = base64.b64decode(data)
auth_code_signature = base64.b64decode(auth_code_signature)
signature = odoo.tools.misc.hmac(request.env(su=True), 'mail_plugin', data).encode()
if not hmac.compare_digest(auth_code_signature, signature):
return None
auth_message = json.loads(data)
# Check the expiration
if datetime.datetime.utcnow() - datetime.datetime.fromtimestamp(auth_message['timestamp']) > datetime.timedelta(
minutes=3):
return None
return auth_message
# Using UTC explicitly in case of a distributed system where the generation and the signature verification do not
# necessarily happen on the same server
def _generate_auth_code(self, scope, name):
auth_dict = {
'scope': scope,
'name': name,
'timestamp': int(datetime.datetime.utcnow().timestamp()),
# <- elapsed time should be < 3 mins when verifying
'uid': request.uid,
}
auth_message = json.dumps(auth_dict, sort_keys=True).encode()
signature = odoo.tools.misc.hmac(request.env(su=True), 'mail_plugin', auth_message).encode()
auth_code = "%s.%s" % (base64.b64encode(auth_message).decode(), base64.b64encode(signature).decode())
_logger.info('Auth code created - user %s, scope %s', request.env.user, scope)
return auth_code
| 49.849057 | 5,284 |
851 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Sell Courses",
'summary': 'Sell your courses online',
'description': """Sell your courses using the e-commerce features of the website.""",
'category': 'Hidden',
'version': '1.0',
'depends': ['website_slides', 'website_sale'],
'installable': True,
'data': [
'report/sale_report_views.xml',
'views/website_slides_menu_views.xml',
'views/slide_channel_views.xml',
'views/website_slides_templates.xml',
],
'demo': [
'data/product_demo.xml',
'data/slide_demo.xml',
'data/sale_order_demo.xml',
],
'assets': {
'web.assets_frontend': [
'website_sale_slides/static/src/js/**/*',
],
},
'license': 'LGPL-3',
}
| 29.344828 | 851 |
2,707 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_slides.tests import common
class TestCoursePurchaseFlow(common.SlidesCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user_salesman = cls.env['res.users'].create({
'name': 'salesman',
'login': 'salesman',
'email': '[email protected]',
'groups_id': [(6, 0, cls.env.ref('sales_team.group_sale_salesman').ids)],
})
def test_course_purchase_flow(self):
# Step1: create a course product and assign it to 2 slide.channels
course_product = self.env['product.product'].create({
'name': "Course Product",
'standard_price': 100,
'list_price': 150,
'type': 'service',
'invoice_policy': 'order',
'is_published': True,
})
self.channel.write({
'enroll': 'payment',
'product_id': course_product.id
})
self.channel_2 = self.env['slide.channel'].with_user(self.user_officer).create({
'name': 'Test Channel',
'enroll': 'payment',
'product_id': course_product.id,
'is_published': True,
})
# Step 2: create a sale_order with the course product
sale_order = self.env['sale.order'].create({
'partner_id': self.customer.id,
'order_line': [
(0, 0, {
'name': course_product.name,
'product_id': course_product.id,
'product_uom_qty': 1,
'price_unit': course_product.list_price,
})
],
})
sale_order.action_confirm()
# Step 3: check that the customer is now a member of both channel
self.assertIn(self.customer, self.channel.partner_ids)
self.assertIn(self.customer, self.channel_2.partner_ids)
# Step 4: Same test as salesman
salesman_sale_order = self.env['sale.order'].with_user(self.user_salesman).create({
'partner_id': self.user_portal.partner_id.id,
'order_line': [
(0, 0, {
'name': course_product.name,
'product_id': course_product.id,
'product_uom_qty': 1,
'price_unit': course_product.list_price,
})
],
})
salesman_sale_order.action_confirm()
self.assertIn(self.user_portal.partner_id, self.channel.partner_ids)
self.assertIn(self.user_portal.partner_id, self.channel_2.partner_ids)
| 35.618421 | 2,707 |
3,141 |
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 Channel(models.Model):
_inherit = 'slide.channel'
enroll = fields.Selection(selection_add=[
('payment', 'On payment')
], ondelete={'payment': lambda recs: recs.write({'enroll': 'invite'})})
product_id = fields.Many2one('product.product', 'Product', index=True)
product_sale_revenues = fields.Monetary(
string='Total revenues', compute='_compute_product_sale_revenues',
groups="sales_team.group_sale_salesman")
currency_id = fields.Many2one(related='product_id.currency_id')
_sql_constraints = [
('product_id_check', "CHECK( enroll!='payment' OR product_id IS NOT NULL )", "Product is required for on payment channels.")
]
@api.depends('product_id')
def _compute_product_sale_revenues(self):
domain = [
('state', 'in', self.env['sale.report']._get_done_states()),
('product_id', 'in', self.product_id.ids),
]
rg_data = dict(
(item['product_id'][0], item['price_total'])
for item in self.env['sale.report'].read_group(domain, ['product_id', 'price_total'], ['product_id'])
)
for channel in self:
channel.product_sale_revenues = rg_data.get(channel.product_id.id, 0)
@api.model_create_multi
def create(self, vals_list):
channels = super(Channel, self).create(vals_list)
channels.filtered(lambda channel: channel.enroll == 'payment')._synchronize_product_publish()
return channels
def write(self, vals):
res = super(Channel, self).write(vals)
if 'is_published' in vals:
self.filtered(lambda channel: channel.enroll == 'payment')._synchronize_product_publish()
return res
def _synchronize_product_publish(self):
if not self:
return
self.filtered(lambda channel: channel.is_published and not channel.product_id.is_published).sudo().product_id.write({'is_published': True})
self.filtered(lambda channel: not channel.is_published and channel.product_id.is_published).sudo().product_id.write({'is_published': False})
def action_view_sales(self):
action = self.env["ir.actions.actions"]._for_xml_id("website_sale_slides.sale_report_action_slides")
action['domain'] = [('product_id', 'in', self.product_id.ids)]
return action
def _filter_add_members(self, target_partners, **member_values):
""" Overridden to add 'payment' channels to the filtered channels. People
that can write on payment-based channels can add members. """
result = super(Channel, self)._filter_add_members(target_partners, **member_values)
on_payment = self.filtered(lambda channel: channel.enroll == 'payment')
if on_payment:
try:
on_payment.check_access_rights('write')
on_payment.check_access_rule('write')
except:
pass
else:
result |= on_payment
return result
| 43.625 | 3,141 |
1,404 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
class SaleOrder(models.Model):
_inherit = "sale.order"
def _action_confirm(self):
""" If the product of an order line is a 'course', we add the client of the sale_order
as a member of the channel(s) on which this product is configured (see slide.channel.product_id). """
result = super(SaleOrder, self)._action_confirm()
so_lines = self.env['sale.order.line'].search(
[('order_id', 'in', self.ids)]
)
products = so_lines.mapped('product_id')
related_channels = self.env['slide.channel'].search(
[('product_id', 'in', products.ids)]
)
channel_products = related_channels.mapped('product_id')
channels_per_so = {sale_order: self.env['slide.channel'] for sale_order in self}
for so_line in so_lines:
if so_line.product_id in channel_products:
for related_channel in related_channels:
if related_channel.product_id == so_line.product_id:
channels_per_so[so_line.order_id] = channels_per_so[so_line.order_id] | related_channel
for sale_order, channels in channels_per_so.items():
channels.sudo()._action_add_members(sale_order.partner_id)
return result
| 41.294118 | 1,404 |
280 |
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 Product(models.Model):
_inherit = "product.product"
channel_ids = fields.One2many('slide.channel', 'product_id', string='Courses')
| 28 | 280 |
826 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_slides.controllers.main import WebsiteSlides
from odoo.http import request
class WebsiteSaleSlides(WebsiteSlides):
def _prepare_additional_channel_values(self, values, **kwargs):
values = super(WebsiteSaleSlides, self)._prepare_additional_channel_values(values, **kwargs)
channel = values['channel']
if channel.enroll == 'payment' and channel.product_id:
pricelist = request.website.get_current_pricelist()
values['product_info'] = channel.product_id.product_tmpl_id._get_combination_info(product_id=channel.product_id.id, pricelist=pricelist)
values['product_info']['currency_id'] = request.website.currency_id
return values
| 48.588235 | 826 |
2,046 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Calendar',
'version': '1.1',
'sequence': 165,
'depends': ['base', 'mail'],
'summary': "Schedule employees' meetings",
'description': """
This is a full-featured calendar system.
========================================
It supports:
------------
- Calendar of events
- Recurring events
If you need to manage your meetings, you should install the CRM module.
""",
'category': 'Productivity/Calendar',
'demo': [
'data/calendar_demo.xml'
],
'data': [
'security/ir.model.access.csv',
'security/calendar_security.xml',
'data/calendar_cron.xml',
'data/mail_template_data.xml',
'data/calendar_data.xml',
'data/mail_data_various.xml',
'views/mail_activity_views.xml',
'views/calendar_templates.xml',
'views/calendar_views.xml',
'views/res_partner_views.xml',
],
'installable': True,
'application': True,
'auto_install': False,
'assets': {
'web.assets_backend': [
'calendar/static/src/models/activity/activity.js',
'calendar/static/src/components/activity/activity.js',
'calendar/static/src/scss/calendar.scss',
'calendar/static/src/js/base_calendar.js',
'calendar/static/src/js/calendar_renderer.js',
'calendar/static/src/js/calendar_controller.js',
'calendar/static/src/js/calendar_model.js',
'calendar/static/src/js/calendar_view.js',
'calendar/static/src/js/systray_activity_menu.js',
'calendar/static/src/js/services/calendar_notification_service.js',
],
'web.qunit_suite_tests': [
'calendar/static/tests/**/*',
],
'web.assets_qweb': [
'calendar/static/src/xml/base_calendar.xml',
'calendar/static/src/components/activity/activity.xml',
],
},
'license': 'LGPL-3',
}
| 33 | 2,046 |
6,259 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from odoo.tests.common import TransactionCase, new_test_user
from odoo.exceptions import AccessError
from odoo.tools import mute_logger
class TestAccessRights(TransactionCase):
@classmethod
@mute_logger('odoo.tests', 'odoo.addons.auth_signup.models.res_users')
def setUpClass(cls):
super().setUpClass()
cls.john = new_test_user(cls.env, login='john', groups='base.group_user')
cls.raoul = new_test_user(cls.env, login='raoul', groups='base.group_user')
cls.george = new_test_user(cls.env, login='george', groups='base.group_user')
cls.portal = new_test_user(cls.env, login='pot', groups='base.group_portal')
def create_event(self, user, **values):
return self.env['calendar.event'].with_user(user).create({
'name': 'Event',
'start': datetime(2020, 2, 2, 8, 0),
'stop': datetime(2020, 2, 2, 18, 0),
'user_id': user.id,
'partner_ids': [(4, self.george.partner_id.id, 0)],
**values
})
def read_event(self, user, events, field):
data = events.with_user(user).read([field])
if len(events) == 1:
return data[0][field]
return [r[field] for r in data]
# don't spam logs with ACL failures from portal
@mute_logger('odoo.addons.base.models.ir_rule')
def test_privacy(self):
event = self.create_event(
self.john,
privacy='private',
name='my private event',
location='in the Sky'
)
for user, field, expect, error in [
# public field, any employee can read
(self.john, 'privacy', 'private', None),
(self.george, 'privacy', 'private', None),
(self.raoul, 'privacy', 'private', None),
(self.portal, 'privacy', None, AccessError),
# substituted private field, only owner and invitees can read, other
# employees get substitution
(self.john, 'name', 'my private event', None),
(self.george, 'name', 'my private event', None),
(self.raoul, 'name', 'Busy', None),
(self.portal, 'name', None, AccessError),
# computed from private field
(self.john, 'display_name', 'my private event', None),
(self.george, 'display_name', 'my private event', None),
(self.raoul, 'display_name', 'Busy', None),
(self.portal, 'display_name', None, AccessError),
# non-substituted private field, only owner and invitees can read,
# other employees get an empty field
(self.john, 'location', 'in the Sky', None),
(self.george, 'location', 'in the Sky', None),
(self.raoul, 'location', False, None),
(self.portal, 'location', None, AccessError),
# non-substituted sequence field
(self.john, 'partner_ids', self.george.partner_id, None),
(self.george, 'partner_ids', self.george.partner_id, None),
(self.raoul, 'partner_ids', self.env['res.partner'], None),
(self.portal, 'partner_ids', None, AccessError),
]:
event.invalidate_cache()
with self.subTest("private read", user=user.display_name, field=field, error=error):
e = event.with_user(user)
if error:
with self.assertRaises(error):
_ = e[field]
else:
self.assertEqual(e[field], expect)
def test_private_and_public(self):
private = self.create_event(
self.john,
privacy='private',
location='in the Sky',
)
public = self.create_event(
self.john,
privacy='public',
location='In Hell',
)
[private_location, public_location] = self.read_event(self.raoul, private + public, 'location')
self.assertEqual(private_location, False, "Private value should be obfuscated")
self.assertEqual(public_location, 'In Hell', "Public value should not be obfuscated")
def test_read_group_public(self):
event = self.create_event(self.john)
data = self.env['calendar.event'].with_user(self.raoul).read_group([('id', '=', event.id)], fields=['start'], groupby='start')
self.assertTrue(data, "It should be able to read group")
data = self.env['calendar.event'].with_user(self.raoul).read_group([('id', '=', event.id)], fields=['name'],
groupby='name')
self.assertTrue(data, "It should be able to read group")
def test_read_group_private(self):
event = self.create_event(self.john, privacy='private')
result = self.env['calendar.event'].with_user(self.raoul).read_group([('id', '=', event.id)], fields=['name'], groupby='name')
self.assertFalse(result, "Private events should not be fetched")
def test_read_group_agg(self):
event = self.create_event(self.john)
data = self.env['calendar.event'].with_user(self.raoul).read_group([('id', '=', event.id)], fields=['start'], groupby='start:week')
self.assertTrue(data, "It should be able to read group")
def test_read_group_list(self):
event = self.create_event(self.john)
data = self.env['calendar.event'].with_user(self.raoul).read_group([('id', '=', event.id)], fields=['start'], groupby=['start'])
self.assertTrue(data, "It should be able to read group")
def test_private_attendee(self):
event = self.create_event(
self.john,
privacy='private',
location='in the Sky',
)
partners = (self.john|self.raoul).mapped('partner_id')
event.write({'partner_ids': [(6, 0, partners.ids)]})
self.assertEqual(self.read_event(self.raoul, event, 'location'), 'in the Sky',
"Owner should be able to read the event")
with self.assertRaises(AccessError):
self.read_event(self.portal, event, 'location')
| 46.362963 | 6,259 |
2,241 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from odoo.tests.common import HttpCase, new_test_user, tagged
@tagged("post_install", "-at_install")
class TestCalendarController(HttpCase):
def setUp(self):
super().setUp()
self.user = new_test_user(self.env, "test_user_1", email="[email protected]", tz="UTC")
self.other_user = new_test_user(self.env, "test_user_2", email="[email protected]", password="P@ssw0rd!", tz="UTC")
self.partner = self.user.partner_id
self.event = (
self.env["calendar.event"]
.create(
{
"name": "Doom's day",
"start": datetime(2019, 10, 25, 8, 0),
"stop": datetime(2019, 10, 27, 18, 0),
"partner_ids": [(4, self.partner.id)],
}
)
.with_context(mail_notrack=True)
)
def test_accept_meeting_unauthenticated(self):
self.event.write({"partner_ids": [(4, self.other_user.partner_id.id)]})
attendee = self.event.attendee_ids.filtered(lambda att: att.partner_id.id == self.other_user.partner_id.id)
token = attendee.access_token
url = "/calendar/meeting/accept?token=%s&id=%d" % (token, self.event.id)
res = self.url_open(url)
self.assertEqual(res.status_code, 200, "Response should = OK")
attendee.invalidate_cache()
self.assertEqual(attendee.state, "accepted", "Attendee should have accepted")
def test_accept_meeting_authenticated(self):
self.event.write({"partner_ids": [(4, self.other_user.partner_id.id)]})
attendee = self.event.attendee_ids.filtered(lambda att: att.partner_id.id == self.other_user.partner_id.id)
token = attendee.access_token
url = "/calendar/meeting/accept?token=%s&id=%d" % (token, self.event.id)
self.authenticate("test_user_2", "P@ssw0rd!")
res = self.url_open(url)
self.assertEqual(res.status_code, 200, "Response should = OK")
attendee.invalidate_cache()
self.assertEqual(attendee.state, "accepted", "Attendee should have accepted")
| 45.734694 | 2,241 |
2,065 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
class TestRecurrentEvent(common.TransactionCase):
def setUp(self):
super(TestRecurrentEvent, self).setUp()
self.CalendarEvent = self.env['calendar.event']
def test_recurrent_meeting1(self):
# In order to test recurrent meetings in Odoo, I create meetings with different recurrence using different test cases.
# I create a recurrent meeting with daily recurrence and fixed amount of time.
self.CalendarEvent.create({
'count': 5,
'start': '2011-04-13 11:04:00',
'stop': '2011-04-13 12:04:00',
'duration': 1.0,
'name': 'Test Meeting',
'recurrency': True,
'rrule_type': 'daily'
})
# I search for all the recurrent meetings
meetings_count = self.CalendarEvent.with_context({'virtual_id': True}).search_count([
('start', '>=', '2011-03-13'), ('stop', '<=', '2011-05-13')
])
self.assertEqual(meetings_count, 5, 'Recurrent daily meetings are not created !')
def test_recurrent_meeting2(self):
# I create a weekly meeting till a particular end date.
self.CalendarEvent.create({
'start': '2011-04-18 11:47:00',
'stop': '2011-04-18 12:47:00',
'day': 1,
'duration': 1.0,
'until': '2011-04-30',
'end_type': 'end_date',
'fri': True,
'mon': True,
'thu': True,
'tue': True,
'wed': True,
'name': 'Review code with programmer',
'recurrency': True,
'rrule_type': 'weekly'
})
# I search for all the recurrent weekly meetings.
meetings_count = self.CalendarEvent.search_count([
('start', '>=', '2011-03-13'), ('stop', '<=', '2011-05-13')
])
self.assertEqual(meetings_count, 10, 'Recurrent weekly meetings are not created !')
| 37.545455 | 2,065 |
3,272 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, time
from dateutil.relativedelta import relativedelta
import pytz
from odoo import Command
from odoo import tests
from odoo.addons.mail.tests.common import MailCommon
@tests.tagged('mail_activity_mixin')
class TestMailActivityMixin(MailCommon):
@classmethod
def setUpClass(cls):
super(TestMailActivityMixin, cls).setUpClass()
# using res.partner as the model inheriting from mail.activity.mixin
cls.test_record = cls.env['res.partner'].with_context(cls._test_context).create({'name': 'Test'})
cls.activity_type_1 = cls.env['mail.activity.type'].create({
'name': 'Calendar Activity Test Default',
'summary': 'default activity',
'res_model': 'res.partner',
})
cls.env['ir.model.data'].create({
'name': cls.activity_type_1.name.lower().replace(' ', '_'),
'module': 'calendar',
'model': cls.activity_type_1._name,
'res_id': cls.activity_type_1.id,
})
# reset ctx
cls._reset_mail_context(cls.test_record)
def test_activity_calendar_event_id(self):
"""Test the computed field "activity_calendar_event_id" which is the event of the
next activity. It must evaluate to False if the next activity is not related to an event"""
def create_event(name, event_date):
return self.env['calendar.event'].create({
'name': name,
'start': datetime.combine(event_date, time(12, 0, 0)),
'stop': datetime.combine(event_date, time(14, 0, 0)),
})
def schedule_meeting_activity(record, date_deadline, calendar_event=False):
meeting = record.activity_schedule('calendar.calendar_activity_test_default', date_deadline=date_deadline)
meeting.calendar_event_id = calendar_event
return meeting
group_partner_manager = self.env['ir.model.data']._xmlid_to_res_id('base.group_partner_manager')
self.user_employee.write({
'tz': self.user_admin.tz,
'groups_id': [Command.link(group_partner_manager)]
})
with self.with_user('employee'):
test_record = self.env['res.partner'].browse(self.test_record.id)
self.assertEqual(test_record.activity_ids, self.env['mail.activity'])
now_utc = datetime.now(pytz.UTC)
now_user = now_utc.astimezone(pytz.timezone(self.env.user.tz or 'UTC'))
today_user = now_user.date()
date1 = today_user + relativedelta(days=1)
date2 = today_user + relativedelta(days=2)
ev1 = create_event('ev1', date1)
ev2 = create_event('ev2', date2)
act1 = schedule_meeting_activity(test_record, date1)
schedule_meeting_activity(test_record, date2, ev2)
self.assertFalse(test_record.activity_calendar_event_id, "The next activity does not have a calendar event")
act1.calendar_event_id = ev1
self.assertEqual(test_record.activity_calendar_event_id.name, ev1.name, "This should be the calendar event of the next activity")
| 42.493506 | 3,272 |
3,556 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
from odoo.tests.common import new_test_user
class TestResPartner(TransactionCase):
def test_meeting_count(self):
test_user = new_test_user(self.env, login='test_user', groups='base.group_user, base.group_partner_manager')
Partner = self.env['res.partner'].with_user(test_user)
Event = self.env['calendar.event'].with_user(test_user)
# Partner hierarchy
# 1 5
# /|
# 2 3
# |
# 4
test_partner_1 = Partner.create({'name': 'test_partner_1'})
test_partner_2 = Partner.create({'name': 'test_partner_2', 'parent_id': test_partner_1.id})
test_partner_3 = Partner.create({'name': 'test_partner_3', 'parent_id': test_partner_1.id})
test_partner_4 = Partner.create({'name': 'test_partner_4', 'parent_id': test_partner_3.id})
test_partner_5 = Partner.create({'name': 'test_partner_5'})
Event.create({'name': 'event_1',
'partner_ids': [(6, 0, [test_partner_1.id,
test_partner_2.id,
test_partner_3.id,
test_partner_4.id])]})
Event.create({'name': 'event_2',
'partner_ids': [(6, 0, [test_partner_1.id,
test_partner_3.id])]})
Event.create({'name': 'event_2',
'partner_ids': [(6, 0, [test_partner_2.id,
test_partner_3.id])]})
Event.create({'name': 'event_3',
'partner_ids': [(6, 0, [test_partner_3.id,
test_partner_4.id])]})
Event.create({'name': 'event_4',
'partner_ids': [(6, 0, [test_partner_1.id])]})
Event.create({'name': 'event_5',
'partner_ids': [(6, 0, [test_partner_3.id])]})
Event.create({'name': 'event_6',
'partner_ids': [(6, 0, [test_partner_4.id])]})
Event.create({'name': 'event_7',
'partner_ids': [(6, 0, [test_partner_5.id])]})
Event.create({'name': 'event_8',
'partner_ids': [(6, 0, [test_partner_5.id])]})
#Test rule to see if ir.rules are applied
calendar_event_model_id = self.env['ir.model']._get('calendar.event').id
self.env['ir.rule'].create({'name': 'test_rule',
'model_id': calendar_event_model_id,
'domain_force': [('name', 'not in', ['event_9', 'event_10'])],
'perm_read': True,
'perm_create': False,
'perm_write': False})
Event.create({'name': 'event_9',
'partner_ids': [(6, 0, [test_partner_2.id,
test_partner_3.id])]})
Event.create({'name': 'event_10',
'partner_ids': [(6, 0, [test_partner_5.id])]})
self.assertEqual(test_partner_1.meeting_count, 7)
self.assertEqual(test_partner_2.meeting_count, 2)
self.assertEqual(test_partner_3.meeting_count, 6)
self.assertEqual(test_partner_4.meeting_count, 3)
self.assertEqual(test_partner_5.meeting_count, 2)
| 48.712329 | 3,556 |
5,780 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from odoo.tests.common import TransactionCase, new_test_user
class TestEventNotifications(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = new_test_user(cls.env, 'xav', email='[email protected]', notification_type='inbox')
cls.event = cls.env['calendar.event'].with_user(cls.user).create({
'name': "Doom's day",
'start': datetime(2019, 10, 25, 8, 0),
'stop': datetime(2019, 10, 27, 18, 0),
}).with_context(mail_notrack=True)
cls.partner = cls.user.partner_id
def test_attendee_added(self):
self.event.partner_ids = self.partner
self.assertTrue(self.event.attendee_ids, "It should have created an attendee")
self.assertEqual(self.event.attendee_ids.partner_id, self.partner, "It should be linked to the partner")
self.assertIn(self.partner, self.event.message_follower_ids.partner_id, "He should be follower of the event")
def test_attendee_added_create(self):
event = self.env['calendar.event'].create({
'name': "Doom's day",
'start': datetime(2019, 10, 25, 8, 0),
'stop': datetime(2019, 10, 27, 18, 0),
'partner_ids': [(4, self.partner.id)],
})
self.assertTrue(event.attendee_ids, "It should have created an attendee")
self.assertEqual(event.attendee_ids.partner_id, self.partner, "It should be linked to the partner")
self.assertIn(self.partner, event.message_follower_ids.partner_id, "He should be follower of the event")
def test_attendee_added_create_with_specific_states(self):
"""
When an event is created from an external calendar account (such as Google) which is not linked to an
Odoo account, attendee info such as email and state are given at sync.
In this case, attendee_ids should be created accordingly.
"""
organizer_partner = self.env['res.partner'].create({'name': "orga", "email": "[email protected]"})
event = self.env['calendar.event'].with_user(self.user).create({
'name': "Doom's day",
'start': datetime(2019, 10, 25, 8, 0),
'stop': datetime(2019, 10, 27, 18, 0),
'attendee_ids': [
(0, 0, {'partner_id': self.partner.id, 'state': 'needsAction'}),
(0, 0, {'partner_id': organizer_partner.id, 'state': 'accepted'})
],
'partner_ids': [(4, self.partner.id), (4, organizer_partner.id)],
})
attendees_info = [(a.email, a.state) for a in event.attendee_ids]
self.assertEqual(len(event.attendee_ids), 2)
self.assertIn((self.partner.email, "needsAction"), attendees_info)
self.assertIn((organizer_partner.email, "accepted"), attendees_info)
def test_attendee_added_multi(self):
event = self.env['calendar.event'].create({
'name': "Doom's day",
'start': datetime(2019, 10, 25, 8, 0),
'stop': datetime(2019, 10, 27, 18, 0),
})
events = self.event | event
events.partner_ids = self.partner
self.assertEqual(len(events.attendee_ids), 2, "It should have created one attendee per event")
def test_existing_attendee_added(self):
self.event.partner_ids = self.partner
attendee = self.event.attendee_ids
self.event.write({'partner_ids': [(4, self.partner.id)]}) # Add existing partner
self.assertEqual(self.event.attendee_ids, attendee, "It should not have created an new attendee record")
def test_attendee_add_self(self):
self.event.with_user(self.user).partner_ids = self.partner
self.assertTrue(self.event.attendee_ids, "It should have created an attendee")
self.assertEqual(self.event.attendee_ids.partner_id, self.partner, "It should be linked to the partner")
self.assertEqual(self.event.attendee_ids.state, 'accepted', "It should be accepted for the current user")
def test_attendee_removed(self):
partner_bis = self.env['res.partner'].create({'name': "Xavier"})
self.event.partner_ids = partner_bis
attendee = self.event.attendee_ids
self.event.partner_ids |= self.partner
self.event.partner_ids -= self.partner
self.assertEqual(attendee, self.event.attendee_ids, "It should not have re-created an attendee record")
self.assertNotIn(self.partner, self.event.attendee_ids.partner_id, "It should have removed the attendee")
self.assertNotIn(self.partner, self.event.message_follower_ids.partner_id, "It should have unsubscribed the partner")
self.assertIn(partner_bis, self.event.attendee_ids.partner_id, "It should have left the attendee")
def test_default_attendee(self):
"""
Check if priority list id correctly followed
1) vals_list[0]['attendee_ids']
2) vals_list[0]['partner_ids']
3) context.get('default_attendee_ids')
"""
partner_bis = self.env['res.partner'].create({'name': "Xavier"})
event = self.env['calendar.event'].with_user(
self.user
).with_context(
default_attendee_ids=[(0, 0, {'partner_id': partner_bis.id})]
).create({
'name': "Doom's day",
'partner_ids': [(4, self.partner.id)],
'start': datetime(2019, 10, 25, 8, 0),
'stop': datetime(2019, 10, 27, 18, 0),
})
self.assertIn(self.partner, event.attendee_ids.partner_id, "Partner should be in attendee")
self.assertNotIn(partner_bis, event.attendee_ids.partner_id, "Partner bis should not be in attendee")
| 51.150442 | 5,780 |
16,635 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from datetime import datetime, timedelta, time
from odoo import fields
from odoo.tests import Form
from odoo.addons.base.tests.common import SavepointCaseWithUserDemo
import pytz
import re
class TestCalendar(SavepointCaseWithUserDemo):
def setUp(self):
super(TestCalendar, self).setUp()
self.CalendarEvent = self.env['calendar.event']
# In Order to test calendar, I will first create One Simple Event with real data
self.event_tech_presentation = self.CalendarEvent.create({
'privacy': 'private',
'start': '2011-04-30 16:00:00',
'stop': '2011-04-30 18:30:00',
'description': 'The Technical Presentation will cover following topics:\n* Creating Odoo class\n* Views\n* Wizards\n* Workflows',
'duration': 2.5,
'location': 'Odoo S.A.',
'name': 'Technical Presentation'
})
def test_event_order(self):
""" check the ordering of events when searching """
def create_event(name, date):
return self.CalendarEvent.create({
'name': name,
'start': date + ' 12:00:00',
'stop': date + ' 14:00:00',
})
foo1 = create_event('foo', '2011-04-01')
foo2 = create_event('foo', '2011-06-01')
bar1 = create_event('bar', '2011-05-01')
bar2 = create_event('bar', '2011-06-01')
domain = [('id', 'in', (foo1 + foo2 + bar1 + bar2).ids)]
# sort them by name only
events = self.CalendarEvent.search(domain, order='name')
self.assertEqual(events.mapped('name'), ['bar', 'bar', 'foo', 'foo'])
events = self.CalendarEvent.search(domain, order='name desc')
self.assertEqual(events.mapped('name'), ['foo', 'foo', 'bar', 'bar'])
# sort them by start date only
events = self.CalendarEvent.search(domain, order='start')
self.assertEqual(events.mapped('start'), (foo1 + bar1 + foo2 + bar2).mapped('start'))
events = self.CalendarEvent.search(domain, order='start desc')
self.assertEqual(events.mapped('start'), (foo2 + bar2 + bar1 + foo1).mapped('start'))
# sort them by name then start date
events = self.CalendarEvent.search(domain, order='name asc, start asc')
self.assertEqual(list(events), [bar1, bar2, foo1, foo2])
events = self.CalendarEvent.search(domain, order='name asc, start desc')
self.assertEqual(list(events), [bar2, bar1, foo2, foo1])
events = self.CalendarEvent.search(domain, order='name desc, start asc')
self.assertEqual(list(events), [foo1, foo2, bar1, bar2])
events = self.CalendarEvent.search(domain, order='name desc, start desc')
self.assertEqual(list(events), [foo2, foo1, bar2, bar1])
# sort them by start date then name
events = self.CalendarEvent.search(domain, order='start asc, name asc')
self.assertEqual(list(events), [foo1, bar1, bar2, foo2])
events = self.CalendarEvent.search(domain, order='start asc, name desc')
self.assertEqual(list(events), [foo1, bar1, foo2, bar2])
events = self.CalendarEvent.search(domain, order='start desc, name asc')
self.assertEqual(list(events), [bar2, foo2, bar1, foo1])
events = self.CalendarEvent.search(domain, order='start desc, name desc')
self.assertEqual(list(events), [foo2, bar2, bar1, foo1])
def test_event_activity(self):
# ensure meeting activity type exists
meeting_act_type = self.env['mail.activity.type'].search([('category', '=', 'meeting')], limit=1)
if not meeting_act_type:
meeting_act_type = self.env['mail.activity.type'].create({
'name': 'Meeting Test',
'category': 'meeting',
})
# have a test model inheriting from activities
test_record = self.env['res.partner'].create({
'name': 'Test',
})
now = datetime.now()
test_user = self.user_demo
test_name, test_description, test_description2 = 'Test-Meeting', 'Test-Description', 'NotTest'
test_note, test_note2 = '<p>Test-Description</p>', '<p>NotTest</p>'
# create using default_* keys
test_event = self.env['calendar.event'].with_user(test_user).with_context(
default_res_model=test_record._name,
default_res_id=test_record.id,
).create({
'name': test_name,
'description': test_description,
'start': fields.Datetime.to_string(now + timedelta(days=-1)),
'stop': fields.Datetime.to_string(now + timedelta(hours=2)),
'user_id': self.env.user.id,
})
self.assertEqual(test_event.res_model, test_record._name)
self.assertEqual(test_event.res_id, test_record.id)
self.assertEqual(len(test_record.activity_ids), 1)
self.assertEqual(test_record.activity_ids.summary, test_name)
self.assertEqual(test_record.activity_ids.note, test_note)
self.assertEqual(test_record.activity_ids.user_id, self.env.user)
self.assertEqual(test_record.activity_ids.date_deadline, (now + timedelta(days=-1)).date())
# updating event should update activity
test_event.write({
'name': '%s2' % test_name,
'description': test_description2,
'start': fields.Datetime.to_string(now + timedelta(days=-2)),
'user_id': test_user.id,
})
self.assertEqual(test_record.activity_ids.summary, '%s2' % test_name)
self.assertEqual(test_record.activity_ids.note, test_note2)
self.assertEqual(test_record.activity_ids.user_id, test_user)
self.assertEqual(test_record.activity_ids.date_deadline, (now + timedelta(days=-2)).date())
# update event with a description that have a special character and a new line
test_description3 = 'Test & <br> Description'
test_note3 = '<p>Test & <br> Description</p>'
test_event.write({
'description': test_description3,
})
self.assertEqual(test_record.activity_ids.note, test_note3)
# deleting meeting should delete its activity
test_record.activity_ids.unlink()
self.assertEqual(self.env['calendar.event'], self.env['calendar.event'].search([('name', '=', test_name)]))
# create using active_model keys
test_event = self.env['calendar.event'].with_user(self.user_demo).with_context(
active_model=test_record._name,
active_id=test_record.id,
).create({
'name': test_name,
'description': test_description,
'start': now + timedelta(days=-1),
'stop': now + timedelta(hours=2),
'user_id': self.env.user.id,
})
self.assertEqual(test_event.res_model, test_record._name)
self.assertEqual(test_event.res_id, test_record.id)
self.assertEqual(len(test_record.activity_ids), 1)
def test_event_allday(self):
self.env.user.tz = 'Pacific/Honolulu'
event = self.CalendarEvent.create({
'name': 'All Day',
'start': "2018-10-16 00:00:00",
'start_date': "2018-10-16",
'stop': "2018-10-18 00:00:00",
'stop_date': "2018-10-18",
'allday': True,
})
event.invalidate_cache()
self.assertEqual(str(event.start), '2018-10-16 08:00:00')
self.assertEqual(str(event.stop), '2018-10-18 18:00:00')
def test_recurring_around_dst(self):
m = self.CalendarEvent.create({
'name': "wheee",
'start': '2018-10-27 14:30:00',
'allday': False,
'rrule': u'FREQ=DAILY;INTERVAL=1;COUNT=4',
'recurrency': True,
'stop': '2018-10-27 16:30:00',
'event_tz': 'Europe/Brussels',
})
start_recurring_dates = m.recurrence_id.calendar_event_ids.sorted('start').mapped('start')
self.assertEqual(len(start_recurring_dates), 4)
for d in start_recurring_dates:
if d.day < 28: # DST switch happens between 2018-10-27 and 2018-10-28
self.assertEqual(d.hour, 14)
else:
self.assertEqual(d.hour, 15)
self.assertEqual(d.minute, 30)
def test_recurring_ny(self):
self.env.user.tz = 'US/Eastern'
f = Form(self.CalendarEvent.with_context(tz='US/Eastern'))
f.name = 'test'
f.start = '2022-07-07 01:00:00' # This is in UTC. In NY, it corresponds to the 6th of july at 9pm.
f.recurrency = True
self.assertEqual(f.weekday, 'WED')
self.assertEqual(f.event_tz, 'US/Eastern', "The value should correspond to the user tz")
self.assertEqual(f.count, 1, "The default value should be displayed")
self.assertEqual(f.interval, 1, "The default value should be displayed")
self.assertEqual(f.month_by, "date", "The default value should be displayed")
self.assertEqual(f.end_type, "count", "The default value should be displayed")
self.assertEqual(f.rrule_type, "weekly", "The default value should be displayed")
def test_event_activity_timezone(self):
activty_type = self.env['mail.activity.type'].create({
'name': 'Meeting',
'category': 'meeting'
})
activity_id = self.env['mail.activity'].create({
'summary': 'Meeting with partner',
'activity_type_id': activty_type.id,
'res_model_id': self.env['ir.model']._get_id('res.partner'),
'res_id': self.env['res.partner'].create({'name': 'A Partner'}).id,
})
calendar_event = self.env['calendar.event'].create({
'name': 'Meeting with partner',
'activity_ids': [(6, False, activity_id.ids)],
'start': '2018-11-12 21:00:00',
'stop': '2018-11-13 00:00:00',
})
# Check output in UTC
self.assertEqual(str(activity_id.date_deadline), '2018-11-12')
# Check output in the user's tz
# write on the event to trigger sync of activities
calendar_event.with_context({'tz': 'Australia/Brisbane'}).write({
'start': '2018-11-12 21:00:00',
})
self.assertEqual(str(activity_id.date_deadline), '2018-11-13')
def test_event_allday_activity_timezone(self):
# Covers use case of commit eef4c3b48bcb4feac028bf640b545006dd0c9b91
# Also, read the comment in the code at calendar.event._inverse_dates
activty_type = self.env['mail.activity.type'].create({
'name': 'Meeting',
'category': 'meeting'
})
activity_id = self.env['mail.activity'].create({
'summary': 'Meeting with partner',
'activity_type_id': activty_type.id,
'res_model_id': self.env['ir.model']._get_id('res.partner'),
'res_id': self.env['res.partner'].create({'name': 'A Partner'}).id,
})
calendar_event = self.env['calendar.event'].create({
'name': 'All Day',
'start': "2018-10-16 00:00:00",
'start_date': "2018-10-16",
'stop': "2018-10-18 00:00:00",
'stop_date': "2018-10-18",
'allday': True,
'activity_ids': [(6, False, activity_id.ids)],
})
# Check output in UTC
self.assertEqual(str(activity_id.date_deadline), '2018-10-16')
# Check output in the user's tz
# write on the event to trigger sync of activities
calendar_event.with_context({'tz': 'Pacific/Honolulu'}).write({
'start': '2018-10-16 00:00:00',
'start_date': '2018-10-16',
})
self.assertEqual(str(activity_id.date_deadline), '2018-10-16')
def test_event_creation_mail(self):
"""
Check that mail are sent to the attendees on event creation
Check that mail are sent to the added attendees on event edit
Check that mail are NOT sent to the attendees when the event date is past
"""
def _test_one_mail_per_attendee(self, partners):
# check that every attendee receive a (single) mail for the event
for partner in partners:
mail = self.env['mail.message'].sudo().search([
('notified_partner_ids', 'in', partner.id),
])
self.assertEqual(len(mail), 1)
partners = [
self.env['res.partner'].create({'name': 'testuser0', 'email': u'[email protected]'}),
self.env['res.partner'].create({'name': 'testuser1', 'email': u'[email protected]'}),
]
partner_ids = [(6, False, [p.id for p in partners]),]
now = fields.Datetime.context_timestamp(partners[0], fields.Datetime.now())
m = self.CalendarEvent.create({
'name': "mailTest1",
'allday': False,
'rrule': u'FREQ=DAILY;INTERVAL=1;COUNT=5',
'recurrency': True,
'partner_ids': partner_ids,
'start': fields.Datetime.to_string(now + timedelta(days=10)),
'stop': fields.Datetime.to_string(now + timedelta(days=15)),
})
# every partner should have 1 mail sent
_test_one_mail_per_attendee(self, partners)
# adding more partners to the event
partners.extend([
self.env['res.partner'].create({'name': 'testuser2', 'email': u'[email protected]'}),
self.env['res.partner'].create({'name': 'testuser3', 'email': u'[email protected]'}),
self.env['res.partner'].create({'name': 'testuser4', 'email': u'[email protected]'}),
])
partner_ids = [(6, False, [p.id for p in partners]),]
m.write({
'partner_ids': partner_ids,
'recurrence_update': 'all_events',
})
# more email should be sent
_test_one_mail_per_attendee(self, partners)
# create a new event in the past
self.CalendarEvent.create({
'name': "NOmailTest",
'allday': False,
'recurrency': False,
'partner_ids': partner_ids,
'start': fields.Datetime.to_string(now - timedelta(days=10)),
'stop': fields.Datetime.to_string(now - timedelta(days=9)),
})
# no more email should be sent
_test_one_mail_per_attendee(self, partners)
def test_event_creation_sudo_other_company(self):
""" Check Access right issue when create event with sudo
Create a company, a user in that company
Create an event for someone else in another company as sudo
Should not failed for acces right check
"""
now = fields.Datetime.context_timestamp(self.partner_demo, fields.Datetime.now())
web_company = self.env['res.company'].sudo().create({'name': "Website Company"})
web_user = self.env['res.users'].with_company(web_company).sudo().create({
'name': 'web user',
'login': 'web',
'company_id': web_company.id
})
self.CalendarEvent.with_user(web_user).with_company(web_company).sudo().create({
'name': "Test",
'allday': False,
'recurrency': False,
'partner_ids': [(6, 0, self.partner_demo.ids)],
'alarm_ids': [(0, 0, {
'name': 'Alarm',
'alarm_type': 'notification',
'interval': 'minutes',
'duration': 30,
})],
'user_id': self.user_demo.id,
'start': fields.Datetime.to_string(now + timedelta(hours=5)),
'stop': fields.Datetime.to_string(now + timedelta(hours=6)),
})
def test_meeting_creation_from_partner_form(self):
""" When going from a partner to the Calendar and adding a meeting, both current user and partner
should be attendees of the event """
calendar_action = self.partner_demo.schedule_meeting()
event = self.env['calendar.event'].with_context(calendar_action['context']).create({
'name': 'Super Meeting',
'start': datetime(2020, 12, 13, 17),
'stop': datetime(2020, 12, 13, 22),
})
self.assertEqual(len(event.attendee_ids), 2)
self.assertTrue(self.partner_demo in event.attendee_ids.mapped('partner_id'))
self.assertTrue(self.env.user.partner_id in event.attendee_ids.mapped('partner_id'))
| 44.242021 | 16,635 |
7,498 |
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 datetime import datetime, date
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests.common import TransactionCase, new_test_user
from odoo.addons.base.tests.test_ir_cron import CronMixinCase
from odoo.addons.mail.tests.common import MailCase
class TestEventNotifications(TransactionCase, MailCase, CronMixinCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.event = cls.env['calendar.event'].create({
'name': "Doom's day",
'start': datetime(2019, 10, 25, 8, 0),
'stop': datetime(2019, 10, 27, 18, 0),
}).with_context(mail_notrack=True)
cls.user = new_test_user(cls.env, 'xav', email='[email protected]', notification_type='inbox')
cls.partner = cls.user.partner_id
def test_message_invite(self):
with self.assertSinglePostNotifications([{'partner': self.partner, 'type': 'inbox'}], {
'message_type': 'user_notification',
'subtype': 'mail.mt_note',
}):
self.event.partner_ids = self.partner
def test_message_invite_allday(self):
with self.assertSinglePostNotifications([{'partner': self.partner, 'type': 'inbox'}], {
'message_type': 'user_notification',
'subtype': 'mail.mt_note',
}):
self.env['calendar.event'].with_context(mail_create_nolog=True).create([{
'name': 'Meeting',
'allday': True,
'start_date': fields.Date.today() + relativedelta(days=7),
'stop_date': fields.Date.today() + relativedelta(days=8),
'partner_ids': [(4, self.partner.id)],
}])
def test_message_invite_self(self):
with self.assertNoNotifications():
self.event.with_user(self.user).partner_ids = self.partner
def test_message_inactive_invite(self):
self.event.active = False
with self.assertNoNotifications():
self.event.partner_ids = self.partner
def test_message_set_inactive_invite(self):
self.event.active = False
with self.assertNoNotifications():
self.event.write({
'partner_ids': [(4, self.partner.id)],
'active': False,
})
def test_message_datetime_changed(self):
self.event.partner_ids = self.partner
"Invitation to Presentation of the new Calendar"
with self.assertSinglePostNotifications([{'partner': self.partner, 'type': 'inbox'}], {
'message_type': 'user_notification',
'subtype': 'mail.mt_note',
}):
self.event.start = fields.Datetime.now() + relativedelta(days=1)
def test_message_date_changed(self):
self.event.write({
'allday': True,
'start_date': fields.Date.today() + relativedelta(days=7),
'stop_date': fields.Date.today() + relativedelta(days=8),
})
self.event.partner_ids = self.partner
with self.assertSinglePostNotifications([{'partner': self.partner, 'type': 'inbox'}], {
'message_type': 'user_notification',
'subtype': 'mail.mt_note',
}):
self.event.start_date += relativedelta(days=-1)
def test_message_date_changed_past(self):
self.event.write({
'allday': True,
'start_date': fields.Date.today(),
'stop_date': fields.Date.today() + relativedelta(days=1),
})
self.event.partner_ids = self.partner
with self.assertNoNotifications():
self.event.write({'start': date(2019, 1, 1)})
def test_message_set_inactive_date_changed(self):
self.event.write({
'allday': True,
'start_date': date(2019, 10, 15),
'stop_date': date(2019, 10, 15),
})
self.event.partner_ids = self.partner
with self.assertNoNotifications():
self.event.write({
'start_date': self.event.start_date - relativedelta(days=1),
'active': False,
})
def test_message_inactive_date_changed(self):
self.event.write({
'allday': True,
'start_date': date(2019, 10, 15),
'stop_date': date(2019, 10, 15),
'active': False,
})
self.event.partner_ids = self.partner
with self.assertNoNotifications():
self.event.start_date += relativedelta(days=-1)
def test_message_add_and_date_changed(self):
self.event.partner_ids -= self.partner
with self.assertSinglePostNotifications([{'partner': self.partner, 'type': 'inbox'}], {
'message_type': 'user_notification',
'subtype': 'mail.mt_note',
}):
self.event.write({
'start': self.event.start - relativedelta(days=1),
'partner_ids': [(4, self.partner.id)],
})
def test_bus_notif(self):
alarm = self.env['calendar.alarm'].create({
'name': 'Alarm',
'alarm_type': 'notification',
'interval': 'minutes',
'duration': 30,
})
now = fields.Datetime.now()
with patch.object(fields.Datetime, 'now', lambda: now):
with self.assertBus([(self.env.cr.dbname, 'res.partner', self.partner.id)], [
{
"type": "calendar.alarm",
"payload": [{
"alarm_id": alarm.id,
"event_id": self.event.id,
"title": "Doom's day",
"message": self.event.display_time,
"timer": 20 * 60,
"notify_at": fields.Datetime.to_string(now + relativedelta(minutes=20)),
}],
},
]):
self.event.with_context(no_mail_to_attendees=True).write({
'start': now + relativedelta(minutes=50),
'stop': now + relativedelta(minutes=55),
'partner_ids': [(4, self.partner.id)],
'alarm_ids': [(4, alarm.id)]
})
def test_email_alarm(self):
now = fields.Datetime.now()
with self.capture_triggers('calendar.ir_cron_scheduler_alarm') as capt:
alarm = self.env['calendar.alarm'].create({
'name': 'Alarm',
'alarm_type': 'email',
'interval': 'minutes',
'duration': 20,
})
self.event.write({
'name': 'test event',
'start': now + relativedelta(minutes=15),
'stop': now + relativedelta(minutes=18),
'partner_ids': [fields.Command.link(self.partner.id)],
'alarm_ids': [fields.Command.link(alarm.id)],
})
capt.records.ensure_one()
self.assertLessEqual(capt.records.call_at, now)
with patch.object(fields.Datetime, 'now', lambda: now):
with self.assertSinglePostNotifications([{'partner': self.partner, 'type': 'inbox'}], {
'message_type': 'user_notification',
'subtype': 'mail.mt_note',
}):
self.env['calendar.alarm_manager'].with_context(lastcall=now - relativedelta(minutes=15))._send_reminder()
| 40.311828 | 7,498 |
33,589 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
import pytz
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from odoo.tests.common import TransactionCase
from freezegun import freeze_time
class TestRecurrentEvents(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestRecurrentEvents, cls).setUpClass()
lang = cls.env['res.lang']._lang_get(cls.env.user.lang)
lang.week_start = '1' # Monday
def assertEventDates(self, events, dates):
events = events.sorted('start')
self.assertEqual(len(events), len(dates), "Wrong number of events in the recurrence")
self.assertTrue(all(events.mapped('active')), "All events should be active")
for event, dates in zip(events, dates):
start, stop = dates
self.assertEqual(event.start, start)
self.assertEqual(event.stop, stop)
class TestCreateRecurrentEvents(TestRecurrentEvents):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.event = cls.env['calendar.event'].create({
'name': 'Recurrent Event',
'start': datetime(2019, 10, 21, 8, 0),
'stop': datetime(2019, 10, 23, 18, 0),
'recurrency': True,
})
def test_weekly_count(self):
""" Every week, on Tuesdays, for 3 occurences """
detached_events = self.event._apply_recurrence_values({
'rrule_type': 'weekly',
'tue': True,
'interval': 1,
'count': 3,
'event_tz': 'UTC',
})
self.assertEqual(detached_events, self.event, "It should be detached from the recurrence")
self.assertFalse(self.event.recurrence_id, "It should be detached from the recurrence")
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 3, "It should have 3 events in the recurrence")
self.assertEventDates(events, [
(datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 10, 29, 8, 0), datetime(2019, 10, 31, 18, 0)),
(datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)),
])
def test_weekly_interval_2(self):
self.event._apply_recurrence_values({
'interval': 2,
'rrule_type': 'weekly',
'tue': True,
'count': 2,
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEventDates(events, [
(datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)),
])
def test_weekly_interval_2_week_start_sunday(self):
lang = self.env['res.lang']._lang_get(self.env.user.lang)
lang.week_start = '7' # Sunday
self.event._apply_recurrence_values({
'interval': 2,
'rrule_type': 'weekly',
'tue': True,
'count': 2,
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEventDates(events, [
(datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)),
])
lang.week_start = '1' # Monday
def test_weekly_until(self):
self.event._apply_recurrence_values({
'rrule_type': 'weekly',
'tue': True,
'interval': 2,
'end_type': 'end_date',
'until': datetime(2019, 11, 15),
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 2, "It should have 2 events in the recurrence")
self.assertEventDates(events, [
(datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)),
])
def test_monthly_count_by_date(self):
self.event._apply_recurrence_values({
'rrule_type': 'monthly',
'interval': 2,
'month_by': 'date',
'day': 27,
'end_type': 'count',
'count': 3,
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 3, "It should have 3 events in the recurrence")
self.assertEventDates(events, [
(datetime(2019, 10, 27, 8, 0), datetime(2019, 10, 29, 18, 0)),
(datetime(2019, 12, 27, 8, 0), datetime(2019, 12, 29, 18, 0)),
(datetime(2020, 2, 27, 8, 0), datetime(2020, 2, 29, 18, 0)),
])
def test_monthly_count_by_date_31(self):
self.event._apply_recurrence_values({
'rrule_type': 'monthly',
'interval': 1,
'month_by': 'date',
'day': 31,
'end_type': 'count',
'count': 3,
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 3, "It should have 3 events in the recurrence")
self.assertEventDates(events, [
(datetime(2019, 10, 31, 8, 0), datetime(2019, 11, 2, 18, 0)),
# Missing 31th in November
(datetime(2019, 12, 31, 8, 0), datetime(2020, 1, 2, 18, 0)),
(datetime(2020, 1, 31, 8, 0), datetime(2020, 2, 2, 18, 0)),
])
def test_monthly_until_by_day(self):
""" Every 2 months, on the third Tuesday, until 27th March 2020 """
self.event.start = datetime(2019, 10, 1, 8, 0)
self.event.stop = datetime(2019, 10, 3, 18, 0)
self.event._apply_recurrence_values({
'rrule_type': 'monthly',
'interval': 2,
'month_by': 'day',
'byday': '3',
'weekday': 'TUE',
'end_type': 'end_date',
'until': date(2020, 3, 27),
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 3, "It should have 3 events in the recurrence")
self.assertEventDates(events, [
(datetime(2019, 10, 15, 8, 0), datetime(2019, 10, 17, 18, 0)),
(datetime(2019, 12, 17, 8, 0), datetime(2019, 12, 19, 18, 0)),
(datetime(2020, 2, 18, 8, 0), datetime(2020, 2, 20, 18, 0)),
])
def test_monthly_until_by_day_last(self):
""" Every 2 months, on the last Wednesday, until 15th January 2020 """
self.event._apply_recurrence_values({
'interval': 2,
'rrule_type': 'monthly',
'month_by': 'day',
'weekday': 'WED',
'byday': '-1',
'end_type': 'end_date',
'until': date(2020, 1, 15),
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 2, "It should have 3 events in the recurrence")
self.assertEventDates(events, [
(datetime(2019, 10, 30, 8, 0), datetime(2019, 11, 1, 18, 0)),
(datetime(2019, 12, 25, 8, 0), datetime(2019, 12, 27, 18, 0)),
])
def test_yearly_count(self):
self.event._apply_recurrence_values({
'interval': 2,
'rrule_type': 'yearly',
'count': 2,
'event_tz': 'UTC',
})
events = self.event.recurrence_id.calendar_event_ids
self.assertEqual(len(events), 2, "It should have 3 events in the recurrence")
self.assertEventDates(events, [
(self.event.start, self.event.stop),
(self.event.start + relativedelta(years=2), self.event.stop + relativedelta(years=2)),
])
def test_dst_timezone(self):
""" Test hours stays the same, regardless of DST changes """
self.event.start = datetime(2002, 10, 28, 10, 0)
self.event.stop = datetime(2002, 10, 28, 12, 0)
self.event._apply_recurrence_values({
'interval': 2,
'rrule_type': 'weekly',
'mon': True,
'count': '2',
'event_tz': 'US/Eastern', # DST change on 2002/10/27
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2002, 10, 28, 10, 0), datetime(2002, 10, 28, 12, 0)),
(datetime(2002, 11, 11, 10, 0), datetime(2002, 11, 11, 12, 0)),
])
def test_ambiguous_dst_time_winter(self):
""" Test hours stays the same, regardless of DST changes """
eastern = pytz.timezone('US/Eastern')
dt = eastern.localize(datetime(2002, 10, 20, 1, 30, 00)).astimezone(pytz.utc).replace(tzinfo=None)
# Next occurence happens at 1:30am on 27th Oct 2002 which happened twice in the US/Eastern
# timezone when the clocks where put back at the end of Daylight Saving Time
self.event.start = dt
self.event.stop = dt + relativedelta(hours=1)
self.event._apply_recurrence_values({
'interval': 1,
'rrule_type': 'weekly',
'sun': True,
'count': '2',
'event_tz': 'US/Eastern' # DST change on 2002/4/7
})
events = self.event.recurrence_id.calendar_event_ids
self.assertEqual(events.mapped('duration'), [1, 1])
self.assertEventDates(events, [
(datetime(2002, 10, 20, 5, 30), datetime(2002, 10, 20, 6, 30)),
(datetime(2002, 10, 27, 6, 30), datetime(2002, 10, 27, 7, 30)),
])
def test_ambiguous_dst_time_spring(self):
""" Test hours stays the same, regardless of DST changes """
eastern = pytz.timezone('US/Eastern')
dt = eastern.localize(datetime(2002, 3, 31, 2, 30, 00)).astimezone(pytz.utc).replace(tzinfo=None)
# Next occurence happens 2:30am on 7th April 2002 which never happened at all in the
# US/Eastern timezone, as the clocks where put forward at 2:00am skipping the entire hour
self.event.start = dt
self.event.stop = dt + relativedelta(hours=1)
self.event._apply_recurrence_values({
'interval': 1,
'rrule_type': 'weekly',
'sun': True,
'count': '2',
'event_tz': 'US/Eastern' # DST change on 2002/4/7
})
events = self.event.recurrence_id.calendar_event_ids
self.assertEqual(events.mapped('duration'), [1, 1])
# The event begins at "the same time" (i.e. 2h30 after midnight), but that day, 2h30 after midnight happens to be at 3:30 am
self.assertEventDates(events, [
(datetime(2002, 3, 31, 7, 30), datetime(2002, 3, 31, 8, 30)),
(datetime(2002, 4, 7, 7, 30), datetime(2002, 4, 7, 8, 30)),
])
def test_ambiguous_full_day(self):
""" Test date stays the same, regardless of DST changes """
self.event.write({
'start': datetime(2020, 3, 23, 0, 0),
'stop': datetime(2020, 3, 23, 23, 59),
})
self.event.allday = True
self.event._apply_recurrence_values({
'interval': 1,
'rrule_type': 'weekly',
'mon': True,
'count': 2,
'event_tz': 'Europe/Brussels' # DST change on 2020/3/23
})
events = self.event.recurrence_id.calendar_event_ids
self.assertEventDates(events, [
(datetime(2020, 3, 23, 0, 0), datetime(2020, 3, 23, 23, 59)),
(datetime(2020, 3, 30, 0, 0), datetime(2020, 3, 30, 23, 59)),
])
@freeze_time('2023-03-27')
def test_backward_pass_dst(self):
"""
When we apply the rule to compute the period of the recurrence,
we take an earlier date (in `_get_start_of_period` method).
However, it is possible that this earlier date has a different DST.
This causes time difference problems.
"""
# In Europe/Brussels: 26 March 2023 from winter to summer (from no DST to DST)
# We are in the case where we create a recurring event after the time change (there is the DST).
timezone = 'Europe/Brussels'
tz = pytz.timezone(timezone)
dt = tz.localize(datetime(2023, 3, 27, 9, 0, 00)).astimezone(pytz.utc).replace(tzinfo=None)
self.event.start = dt
self.event.stop = dt + relativedelta(hours=1)
# Check before apply the recurrence
self.assertEqual(self.event.start, datetime(2023, 3, 27, 7, 0, 00)) # Because 2023-03-27 in Europe/Brussels is UTC+2
self.event._apply_recurrence_values({
'rrule_type': 'monthly', # Because we will take the first day of the month (jump back)
'interval': 1,
'end_type': 'count',
'count': 2, # To have the base event and the unique recurrence event
'month_by': 'date',
'day': 27,
'event_tz': timezone,
})
# What we expect:
# - start date of base event: datetime(2023, 3, 27, 7, 0, 00)
# - start date of the unique recurrence event: datetime(2023, 4, 27, 7, 0, 00)
# With the FIX, we replace the following lines with
# `events = self.event.recurrence_id.calendar_event_ids`
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 2, "It should have 2 events in the recurrence")
self.assertIn(self.event, events)
self.assertEventDates(events, [
(datetime(2023, 3, 27, 7, 00), datetime(2023, 3, 27, 8, 00)),
(datetime(2023, 4, 27, 7, 00), datetime(2023, 4, 27, 8, 00)),
])
class TestUpdateRecurrentEvents(TestRecurrentEvents):
@classmethod
def setUpClass(cls):
super().setUpClass()
event = cls.env['calendar.event'].create({
'name': 'Recurrent Event',
'start': datetime(2019, 10, 22, 1, 0),
'stop': datetime(2019, 10, 24, 18, 0),
'recurrency': True,
'rrule_type': 'weekly',
'tue': True,
'interval': 1,
'count': 3,
'event_tz': 'Etc/GMT-4',
})
cls.recurrence = event.recurrence_id
cls.events = event.recurrence_id.calendar_event_ids.sorted('start')
def test_shift_future(self):
event = self.events[1]
self.events[1].write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
self.assertEqual(self.recurrence.end_type, 'end_date')
self.assertEqual(self.recurrence.until, date(2019, 10, 27))
self.assertEventDates(self.recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)),
])
new_recurrence = event.recurrence_id
self.assertNotEqual(self.recurrence, new_recurrence)
self.assertEqual(new_recurrence.count, 2)
self.assertEqual(new_recurrence.dtstart, datetime(2019, 11, 2, 1, 0))
self.assertFalse(new_recurrence.tue)
self.assertTrue(new_recurrence.sat)
self.assertEventDates(new_recurrence.calendar_event_ids, [
(datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 5, 18, 0)),
(datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 12, 18, 0)),
])
def test_shift_future_first(self):
event = self.events[0]
self.events[0].write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
new_recurrence = event.recurrence_id
self.assertFalse(self.recurrence.exists())
self.assertEqual(new_recurrence.count, 3)
self.assertEqual(new_recurrence.dtstart, datetime(2019, 10, 26, 1, 0))
self.assertFalse(new_recurrence.tue)
self.assertTrue(new_recurrence.sat)
self.assertEventDates(new_recurrence.calendar_event_ids, [
(datetime(2019, 10, 26, 1, 0), datetime(2019, 10, 29, 18, 0)),
(datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 5, 18, 0)),
(datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 12, 18, 0)),
])
def test_shift_reapply(self):
event = self.events[2]
self.events[2].write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
# re-Applying the first recurrence should be idempotent
self.recurrence._apply_recurrence()
self.assertEventDates(self.recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)),
])
def test_shift_all(self):
event = self.events[1]
self.assertEventDates(event.recurrence_id.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)),
(datetime(2019, 11, 5, 1, 0), datetime(2019, 11, 7, 18, 0)),
])
event.write({
'recurrence_update': 'all_events',
'tue': False,
'fri': False,
'sat': True,
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
recurrence = self.env['calendar.recurrence'].search([])
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 26, 1, 0), datetime(2019, 10, 29, 18, 0)),
(datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 5, 18, 0)),
(datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 12, 18, 0)),
])
def test_shift_stop_all(self):
# testing the case where we only want to update the stop time
event = self.events[0]
event.write({
'recurrence_update': 'all_events',
'stop': event.stop + relativedelta(hours=1),
})
self.assertEventDates(event.recurrence_id.calendar_event_ids, [
(datetime(2019, 10, 22, 2, 0), datetime(2019, 10, 24, 19, 0)),
(datetime(2019, 10, 29, 2, 0), datetime(2019, 10, 31, 19, 0)),
(datetime(2019, 11, 5, 2, 0), datetime(2019, 11, 7, 19, 0)),
])
def test_change_week_day_rrule(self):
recurrence = self.events.recurrence_id
recurrence.rrule = 'FREQ=WEEKLY;COUNT=3;BYDAY=WE' # from TU to WE
self.assertFalse(self.recurrence.tue)
self.assertTrue(self.recurrence.wed)
def test_shift_all_base_inactive(self):
self.recurrence.base_event_id.active = False
event = self.events[1]
event.write({
'recurrence_update': 'all_events',
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
self.assertFalse(self.recurrence.calendar_event_ids, "Inactive event should not create recurrent events")
def test_shift_all_with_outlier(self):
outlier = self.events[1]
outlier.write({
'recurrence_update': 'self_only',
'start': datetime(2019, 10, 31, 1, 0), # Thursday
'stop': datetime(2019, 10, 31, 18, 0),
})
event = self.events[0]
event.write({
'recurrence_update': 'all_events',
'tue': False,
'fri': False,
'sat': True,
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=4),
})
self.assertEventDates(event.recurrence_id.calendar_event_ids, [
(datetime(2019, 10, 26, 1, 0), datetime(2019, 10, 28, 18, 0)),
(datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 4, 18, 0)),
(datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 11, 18, 0))
])
self.assertFalse(outlier.exists(), 'The outlier should have been deleted')
def test_update_recurrence_future(self):
event = self.events[1]
event.write({
'recurrence_update': 'future_events',
'fri': True, # recurrence is now Tuesday AND Friday
'count': 4,
})
self.assertEventDates(self.recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), # Tu
])
self.assertEventDates(event.recurrence_id.calendar_event_ids, [
(datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)), # Tu
(datetime(2019, 11, 1, 1, 0), datetime(2019, 11, 3, 18, 0)), # Fr
(datetime(2019, 11, 5, 1, 0), datetime(2019, 11, 7, 18, 0)), # Tu
(datetime(2019, 11, 8, 1, 0), datetime(2019, 11, 10, 18, 0)), # Fr
])
events = event.recurrence_id.calendar_event_ids.sorted('start')
self.assertEqual(events[0], self.events[1], "Events on Tuesdays should not have changed")
self.assertEqual(events[2], self.events[2], "Events on Tuesdays should not have changed")
self.assertNotEqual(events.recurrence_id, self.recurrence, "Events should no longer be linked to the original recurrence")
self.assertEqual(events.recurrence_id.count, 4, "The new recurrence should have 4")
self.assertTrue(event.recurrence_id.tue)
self.assertTrue(event.recurrence_id.fri)
def test_update_recurrence_all(self):
self.events[1].write({
'recurrence_update': 'all_events',
'mon': True, # recurrence is now Tuesday AND Monday
})
recurrence = self.env['calendar.recurrence'].search([])
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)),
(datetime(2019, 10, 28, 1, 0), datetime(2019, 10, 30, 18, 0)),
(datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)),
])
def test_shift_single(self):
event = self.events[1]
event.write({
'recurrence_update': 'self_only',
'name': "Updated event",
'start': event.start - relativedelta(hours=2)
})
self.events[0].write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(hours=4),
'stop': event.stop + relativedelta(hours=5),
})
def test_break_recurrence_future(self):
event = self.events[1]
event.write({
'recurrence_update': 'future_events',
'recurrency': False,
})
self.assertFalse(event.recurrence_id)
self.assertTrue(self.events[0].active)
self.assertTrue(self.events[1].active)
self.assertFalse(self.events[2].exists())
self.assertEqual(self.recurrence.until, date(2019, 10, 27))
self.assertEqual(self.recurrence.end_type, 'end_date')
self.assertEventDates(self.recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)),
])
def test_break_recurrence_all(self):
event = self.events[1]
event.write({
'recurrence_update': 'all_events',
'recurrency': False,
'count': 0, # In practice, JS framework sends updated recurrency fields, since they have been recomputed, triggered by the `recurrency` change
})
self.assertFalse(self.events[0].exists())
self.assertTrue(event.active)
self.assertFalse(self.events[2].exists())
self.assertFalse(event.recurrence_id)
self.assertFalse(self.recurrence.exists())
def test_all_day_shift(self):
recurrence = self.env['calendar.event'].create({
'name': 'Recurrent Event',
'start_date': datetime(2019, 10, 22),
'stop_date': datetime(2019, 10, 24),
'recurrency': True,
'rrule_type': 'weekly',
'tue': True,
'interval': 1,
'count': 3,
'event_tz': 'Etc/GMT-4',
'allday': True,
}).recurrence_id
events = recurrence.calendar_event_ids.sorted('start')
event = events[1]
event.write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
self.assertEqual(recurrence.end_type, 'end_date')
self.assertEqual(recurrence.until, date(2019, 10, 27))
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)),
])
new_recurrence = event.recurrence_id
self.assertNotEqual(recurrence, new_recurrence)
self.assertEqual(new_recurrence.count, 2)
self.assertEqual(new_recurrence.dtstart, datetime(2019, 11, 2, 8, 0))
self.assertFalse(new_recurrence.tue)
self.assertTrue(new_recurrence.sat)
self.assertEventDates(new_recurrence.calendar_event_ids, [
(datetime(2019, 11, 2, 8, 0), datetime(2019, 11, 5, 18, 0)),
(datetime(2019, 11, 9, 8, 0), datetime(2019, 11, 12, 18, 0)),
])
def test_archive_recurrence_all(self):
self.events[1].action_mass_archive('all_events')
self.assertEqual([False, False, False], self.events.mapped('active'))
def test_archive_recurrence_future(self):
event = self.events[1]
event.action_mass_archive('future_events')
self.assertEqual([True, False, False], self.events.mapped('active'))
def test_unlink_recurrence_all(self):
event = self.events[1]
event.action_mass_deletion('all_events')
self.assertFalse(self.recurrence.exists())
self.assertFalse(self.events.exists())
def test_unlink_recurrence_future(self):
event = self.events[1]
event.action_mass_deletion('future_events')
self.assertTrue(self.recurrence)
self.assertEqual(self.events.exists(), self.events[0])
class TestUpdateMultiDayWeeklyRecurrentEvents(TestRecurrentEvents):
@classmethod
def setUpClass(cls):
super().setUpClass()
event = cls.env['calendar.event'].create({
'name': 'Recurrent Event',
'start': datetime(2019, 10, 22, 1, 0),
'stop': datetime(2019, 10, 24, 18, 0),
'recurrency': True,
'rrule_type': 'weekly',
'tue': True,
'fri': True,
'interval': 1,
'count': 3,
'event_tz': 'Etc/GMT-4',
})
cls.recurrence = event.recurrence_id
cls.events = event.recurrence_id.calendar_event_ids.sorted('start')
# Tuesday datetime(2019, 10, 22, 1, 0)
# Friday datetime(2019, 10, 25, 1, 0)
# Tuesday datetime(2019, 10, 29, 1, 0)
def test_shift_all_multiple_weekdays(self):
event = self.events[0] # Tuesday
# We go from 2 days a week Thuesday and Friday to one day a week, Thursday
event.write({
'recurrence_update': 'all_events',
'tue': False,
'thu': True,
'fri': False,
'start': event.start + relativedelta(days=2),
'stop': event.stop + relativedelta(days=2),
})
recurrence = self.env['calendar.recurrence'].search([])
# We don't try to do magic tricks. First event is moved, other remain
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 24, 1, 0), datetime(2019, 10, 26, 18, 0)),
(datetime(2019, 10, 31, 1, 0), datetime(2019, 11, 2, 18, 0)),
(datetime(2019, 11, 7, 1, 0), datetime(2019, 11, 9, 18, 0)),
])
def test_shift_all_multiple_weekdays_duration(self):
event = self.events[0] # Tuesday
event.write({
'recurrence_update': 'all_events',
'tue': False,
'thu': True,
'fri': False,
'start': event.start + relativedelta(days=2),
'stop': event.stop + relativedelta(days=3),
})
recurrence = self.env['calendar.recurrence'].search([])
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 24, 1, 0), datetime(2019, 10, 27, 18, 0)),
(datetime(2019, 10, 31, 1, 0), datetime(2019, 11, 3, 18, 0)),
(datetime(2019, 11, 7, 1, 0), datetime(2019, 11, 10, 18, 0)),
])
def test_shift_future_multiple_weekdays(self):
event = self.events[1] # Friday
event.write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(days=3),
'stop': event.stop + relativedelta(days=3),
})
self.assertTrue(self.recurrence.fri)
self.assertTrue(self.recurrence.tue)
self.assertTrue(event.recurrence_id.tue)
self.assertTrue(event.recurrence_id.mon)
self.assertFalse(event.recurrence_id.fri)
self.assertEqual(event.recurrence_id.count, 2)
class TestUpdateMonthlyByDay(TestRecurrentEvents):
@classmethod
def setUpClass(cls):
super().setUpClass()
event = cls.env['calendar.event'].create({
'name': 'Recurrent Event',
'start': datetime(2019, 10, 15, 1, 0),
'stop': datetime(2019, 10, 16, 18, 0),
'recurrency': True,
'rrule_type': 'monthly',
'interval': 1,
'count': 3,
'month_by': 'day',
'weekday': 'TUE',
'byday': '3',
'event_tz': 'Etc/GMT-4',
})
cls.recurrence = event.recurrence_id
cls.events = event.recurrence_id.calendar_event_ids.sorted('start')
# datetime(2019, 10, 15, 1, 0)
# datetime(2019, 11, 19, 1, 0)
# datetime(2019, 12, 17, 1, 0)
def test_shift_all(self):
event = self.events[1]
event.write({
'recurrence_update': 'all_events',
'start': event.start + relativedelta(hours=5),
'stop': event.stop + relativedelta(hours=5),
})
recurrence = self.env['calendar.recurrence'].search([])
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 15, 6, 0), datetime(2019, 10, 16, 23, 0)),
(datetime(2019, 11, 19, 6, 0), datetime(2019, 11, 20, 23, 0)),
(datetime(2019, 12, 17, 6, 0), datetime(2019, 12, 18, 23, 0)),
])
class TestUpdateMonthlyByDate(TestRecurrentEvents):
@classmethod
def setUpClass(cls):
super().setUpClass()
event = cls.env['calendar.event'].create({
'name': 'Recurrent Event',
'start': datetime(2019, 10, 22, 1, 0),
'stop': datetime(2019, 10, 24, 18, 0),
'recurrency': True,
'rrule_type': 'monthly',
'interval': 1,
'count': 3,
'month_by': 'date',
'day': 22,
'event_tz': 'Etc/GMT-4',
})
cls.recurrence = event.recurrence_id
cls.events = event.recurrence_id.calendar_event_ids.sorted('start')
# datetime(2019, 10, 22, 1, 0)
# datetime(2019, 11, 22, 1, 0)
# datetime(2019, 12, 22, 1, 0)
def test_shift_future(self):
event = self.events[1]
event.write({
'recurrence_update': 'future_events',
'start': event.start + relativedelta(days=4),
'stop': event.stop + relativedelta(days=5),
})
self.assertEventDates(self.recurrence.calendar_event_ids, [
(datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)),
])
self.assertEventDates(event.recurrence_id.calendar_event_ids, [
(datetime(2019, 11, 26, 1, 0), datetime(2019, 11, 29, 18, 0)),
(datetime(2019, 12, 26, 1, 0), datetime(2019, 12, 29, 18, 0)),
])
def test_update_all(self):
event = self.events[1]
event.write({
'recurrence_update': 'all_events',
'day': 25,
})
recurrence = self.env['calendar.recurrence'].search([('day', '=', 25)])
self.assertEventDates(recurrence.calendar_event_ids, [
(datetime(2019, 10, 25, 1, 0), datetime(2019, 10, 27, 18, 0)),
(datetime(2019, 11, 25, 1, 0), datetime(2019, 11, 27, 18, 0)),
(datetime(2019, 12, 25, 1, 0), datetime(2019, 12, 27, 18, 0)),
])
| 42.679797 | 33,589 |
10,836 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
from odoo.tools import plaintext2html
_logger = logging.getLogger(__name__)
class AlarmManager(models.AbstractModel):
_name = 'calendar.alarm_manager'
_description = 'Event Alarm Manager'
def _get_next_potential_limit_alarm(self, alarm_type, seconds=None, partners=None):
result = {}
delta_request = """
SELECT
rel.calendar_event_id, max(alarm.duration_minutes) AS max_delta,min(alarm.duration_minutes) AS min_delta
FROM
calendar_alarm_calendar_event_rel AS rel
LEFT JOIN calendar_alarm AS alarm ON alarm.id = rel.calendar_alarm_id
WHERE alarm.alarm_type = %s
GROUP BY rel.calendar_event_id
"""
base_request = """
SELECT
cal.id,
cal.start - interval '1' minute * calcul_delta.max_delta AS first_alarm,
CASE
WHEN cal.recurrency THEN rrule.until - interval '1' minute * calcul_delta.min_delta
ELSE cal.stop - interval '1' minute * calcul_delta.min_delta
END as last_alarm,
cal.start as first_event_date,
CASE
WHEN cal.recurrency THEN rrule.until
ELSE cal.stop
END as last_event_date,
calcul_delta.min_delta,
calcul_delta.max_delta,
rrule.rrule AS rule
FROM
calendar_event AS cal
RIGHT JOIN calcul_delta ON calcul_delta.calendar_event_id = cal.id
LEFT JOIN calendar_recurrence as rrule ON rrule.id = cal.recurrence_id
"""
filter_user = """
RIGHT JOIN calendar_event_res_partner_rel AS part_rel ON part_rel.calendar_event_id = cal.id
AND part_rel.res_partner_id IN %s
"""
# Add filter on alarm type
tuple_params = (alarm_type,)
# Add filter on partner_id
if partners:
base_request += filter_user
tuple_params += (tuple(partners.ids), )
# Upper bound on first_alarm of requested events
first_alarm_max_value = ""
if seconds is None:
# first alarm in the future + 3 minutes if there is one, now otherwise
first_alarm_max_value = """
COALESCE((SELECT MIN(cal.start - interval '1' minute * calcul_delta.max_delta)
FROM calendar_event cal
RIGHT JOIN calcul_delta ON calcul_delta.calendar_event_id = cal.id
WHERE cal.start - interval '1' minute * calcul_delta.max_delta > now() at time zone 'utc'
) + interval '3' minute, now() at time zone 'utc')"""
else:
# now + given seconds
first_alarm_max_value = "(now() at time zone 'utc' + interval '%s' second )"
tuple_params += (seconds,)
self.flush()
self._cr.execute("""
WITH calcul_delta AS (%s)
SELECT *
FROM ( %s WHERE cal.active = True ) AS ALL_EVENTS
WHERE ALL_EVENTS.first_alarm < %s
AND ALL_EVENTS.last_event_date > (now() at time zone 'utc')
""" % (delta_request, base_request, first_alarm_max_value), tuple_params)
for event_id, first_alarm, last_alarm, first_meeting, last_meeting, min_duration, max_duration, rule in self._cr.fetchall():
result[event_id] = {
'event_id': event_id,
'first_alarm': first_alarm,
'last_alarm': last_alarm,
'first_meeting': first_meeting,
'last_meeting': last_meeting,
'min_duration': min_duration,
'max_duration': max_duration,
'rrule': rule
}
# determine accessible events
events = self.env['calendar.event'].browse(result)
result = {
key: result[key]
for key in set(events._filter_access_rules('read').ids)
}
return result
def do_check_alarm_for_one_date(self, one_date, event, event_maxdelta, in_the_next_X_seconds, alarm_type, after=False, missing=False):
""" Search for some alarms in the interval of time determined by some parameters (after, in_the_next_X_seconds, ...)
:param one_date: date of the event to check (not the same that in the event browse if recurrent)
:param event: Event browse record
:param event_maxdelta: biggest duration from alarms for this event
:param in_the_next_X_seconds: looking in the future (in seconds)
:param after: if not False: will return alert if after this date (date as string - todo: change in master)
:param missing: if not False: will return alert even if we are too late
:param notif: Looking for type notification
:param mail: looking for type email
"""
result = []
# TODO: remove event_maxdelta and if using it
past = one_date - timedelta(minutes=(missing * event_maxdelta))
future = fields.Datetime.now() + timedelta(seconds=in_the_next_X_seconds)
if future <= past:
return result
for alarm in event.alarm_ids:
if alarm.alarm_type != alarm_type:
continue
past = one_date - timedelta(minutes=(missing * alarm.duration_minutes))
if future <= past:
continue
if after and past <= fields.Datetime.from_string(after):
continue
result.append({
'alarm_id': alarm.id,
'event_id': event.id,
'notify_at': one_date - timedelta(minutes=alarm.duration_minutes),
})
return result
def _get_events_by_alarm_to_notify(self, alarm_type):
"""
Get the events with an alarm of the given type between the cron
last call and now.
Please note that all new reminders created since the cron last
call with an alarm prior to the cron last call are skipped by
design. The attendees receive an invitation for any new event
already.
"""
lastcall = self.env.context.get('lastcall', False) or fields.date.today() - relativedelta(weeks=1)
self.env.cr.execute('''
SELECT "alarm"."id", "event"."id"
FROM "calendar_event" AS "event"
JOIN "calendar_alarm_calendar_event_rel" AS "event_alarm_rel"
ON "event"."id" = "event_alarm_rel"."calendar_event_id"
JOIN "calendar_alarm" AS "alarm"
ON "event_alarm_rel"."calendar_alarm_id" = "alarm"."id"
WHERE (
"alarm"."alarm_type" = %s
AND "event"."active"
AND "event"."start" - CAST("alarm"."duration" || ' ' || "alarm"."interval" AS Interval) >= %s
AND "event"."start" - CAST("alarm"."duration" || ' ' || "alarm"."interval" AS Interval) < now() at time zone 'utc'
)''', [alarm_type, lastcall])
events_by_alarm = {}
for alarm_id, event_id in self.env.cr.fetchall():
events_by_alarm.setdefault(alarm_id, list()).append(event_id)
return events_by_alarm
@api.model
def _send_reminder(self):
# Executed via cron
events_by_alarm = self._get_events_by_alarm_to_notify('email')
if not events_by_alarm:
return
event_ids = list(set(event_id for event_ids in events_by_alarm.values() for event_id in event_ids))
events = self.env['calendar.event'].browse(event_ids)
attendees = events.attendee_ids.filtered(lambda a: a.state != 'declined')
alarms = self.env['calendar.alarm'].browse(events_by_alarm.keys())
for alarm in alarms:
alarm_attendees = attendees.filtered(lambda attendee: attendee.event_id.id in events_by_alarm[alarm.id])
alarm_attendees.with_context(
mail_notify_force_send=True,
calendar_template_ignore_recurrence=True
)._send_mail_to_attendees(
alarm.mail_template_id,
force_send=True
)
@api.model
def get_next_notif(self):
partner = self.env.user.partner_id
all_notif = []
if not partner:
return []
all_meetings = self._get_next_potential_limit_alarm('notification', partners=partner)
time_limit = 3600 * 24 # return alarms of the next 24 hours
for event_id in all_meetings:
max_delta = all_meetings[event_id]['max_duration']
meeting = self.env['calendar.event'].browse(event_id)
in_date_format = fields.Datetime.from_string(meeting.start)
last_found = self.do_check_alarm_for_one_date(in_date_format, meeting, max_delta, time_limit, 'notification', after=partner.calendar_last_notif_ack)
if last_found:
for alert in last_found:
all_notif.append(self.do_notif_reminder(alert))
return all_notif
def do_notif_reminder(self, alert):
alarm = self.env['calendar.alarm'].browse(alert['alarm_id'])
meeting = self.env['calendar.event'].browse(alert['event_id'])
if alarm.alarm_type == 'notification':
message = meeting.display_time
if alarm.body:
message += '<p>%s</p>' % plaintext2html(alarm.body)
delta = alert['notify_at'] - fields.Datetime.now()
delta = delta.seconds + delta.days * 3600 * 24
return {
'alarm_id': alarm.id,
'event_id': meeting.id,
'title': meeting.name,
'message': message,
'timer': delta,
'notify_at': fields.Datetime.to_string(alert['notify_at']),
}
def _notify_next_alarm(self, partner_ids):
""" Sends through the bus the next alarm of given partners """
notifications = []
users = self.env['res.users'].search([('partner_id', 'in', tuple(partner_ids))])
for user in users:
notif = self.with_user(user).with_context(allowed_company_ids=user.company_ids.ids).get_next_notif()
notifications.append([user.partner_id, 'calendar.alarm', notif])
if len(notifications) > 0:
self.env['bus.bus']._sendmany(notifications)
| 45.15 | 10,836 |
7,311 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import uuid
import base64
import logging
from collections import defaultdict
from odoo import api, fields, models, _
from odoo.addons.base.models.res_partner import _tz_get
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
class Attendee(models.Model):
""" Calendar Attendee Information """
_name = 'calendar.attendee'
_rec_name = 'common_name'
_description = 'Calendar Attendee Information'
_order = 'create_date ASC'
def _default_access_token(self):
return uuid.uuid4().hex
STATE_SELECTION = [
('needsAction', 'Needs Action'),
('tentative', 'Uncertain'),
('declined', 'Declined'),
('accepted', 'Accepted'),
]
# event
event_id = fields.Many2one('calendar.event', 'Meeting linked', required=True, ondelete='cascade')
recurrence_id = fields.Many2one('calendar.recurrence', related='event_id.recurrence_id')
# attendee
partner_id = fields.Many2one('res.partner', 'Attendee', required=True, readonly=True)
email = fields.Char('Email', related='partner_id.email', help="Email of Invited Person")
phone = fields.Char('Phone', related='partner_id.phone', help="Phone number of Invited Person")
common_name = fields.Char('Common name', compute='_compute_common_name', store=True)
access_token = fields.Char('Invitation Token', default=_default_access_token)
mail_tz = fields.Selection(_tz_get, compute='_compute_mail_tz', help='Timezone used for displaying time in the mail template')
# state
state = fields.Selection(STATE_SELECTION, string='Status', readonly=True, default='needsAction',
help="Status of the attendee's participation")
availability = fields.Selection(
[('free', 'Available'), ('busy', 'Busy')], 'Available/Busy', readonly=True)
@api.depends('partner_id', 'partner_id.name', 'email')
def _compute_common_name(self):
for attendee in self:
attendee.common_name = attendee.partner_id.name or attendee.email
def _compute_mail_tz(self):
for attendee in self:
attendee.mail_tz = attendee.partner_id.tz
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
# by default, if no state is given for the attendee corresponding to the current user
# that means he's the event organizer so we can set his state to "accepted"
if 'state' not in values and values.get('partner_id') == self.env.user.partner_id.id:
values['state'] = 'accepted'
if not values.get("email") and values.get("common_name"):
common_nameval = values.get("common_name").split(':')
email = [x for x in common_nameval if '@' in x]
values['email'] = email[0] if email else ''
values['common_name'] = values.get("common_name")
attendees = super().create(vals_list)
attendees._subscribe_partner()
return attendees
def unlink(self):
self._unsubscribe_partner()
return super().unlink()
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
raise UserError(_('You cannot duplicate a calendar attendee.'))
def _subscribe_partner(self):
mapped_followers = defaultdict(lambda: self.env['calendar.event'])
for event in self.event_id:
partners = (event.attendee_ids & self).partner_id - event.message_partner_ids
# current user is automatically added as followers, don't add it twice.
partners -= self.env.user.partner_id
mapped_followers[partners] |= event
for partners, events in mapped_followers.items():
events.message_subscribe(partner_ids=partners.ids)
def _unsubscribe_partner(self):
for event in self.event_id:
partners = (event.attendee_ids & self).partner_id & event.message_partner_ids
event.message_unsubscribe(partner_ids=partners.ids)
def _send_mail_to_attendees(self, mail_template, force_send=False):
""" Send mail for event invitation to event attendees.
:param mail_template: a mail.template record
:param force_send: if set to True, the mail(s) will be sent immediately (instead of the next queue processing)
"""
if isinstance(mail_template, str):
raise ValueError('Template should be a template record, not an XML ID anymore.')
if self.env['ir.config_parameter'].sudo().get_param('calendar.block_mail') or self._context.get("no_mail_to_attendees"):
return False
if not mail_template:
_logger.warning("No template passed to %s notification process. Skipped.", self)
return False
# get ics file for all meetings
ics_files = self.mapped('event_id')._get_ics_file()
for attendee in self:
if attendee.email and attendee.partner_id != self.env.user.partner_id:
event_id = attendee.event_id.id
ics_file = ics_files.get(event_id)
attachment_values = []
if ics_file:
attachment_values = [
(0, 0, {'name': 'invitation.ics',
'mimetype': 'text/calendar',
'datas': base64.b64encode(ics_file)})
]
body = mail_template._render_field(
'body_html',
attendee.ids,
compute_lang=True,
post_process=True)[attendee.id]
subject = mail_template._render_field(
'subject',
attendee.ids,
compute_lang=True)[attendee.id]
attendee.event_id.with_context(no_document=True).message_notify(
email_from=attendee.event_id.user_id.email_formatted or self.env.user.email_formatted,
author_id=attendee.event_id.user_id.partner_id.id or self.env.user.partner_id.id,
body=body,
subject=subject,
partner_ids=attendee.partner_id.ids,
email_layout_xmlid='mail.mail_notification_light',
attachment_ids=attachment_values,
force_send=force_send)
def do_tentative(self):
""" Makes event invitation as Tentative. """
return self.write({'state': 'tentative'})
def do_accept(self):
""" Marks event invitation as Accepted. """
for attendee in self:
attendee.event_id.message_post(
body=_("%s has accepted invitation") % (attendee.common_name),
subtype_xmlid="calendar.subtype_invitation")
return self.write({'state': 'accepted'})
def do_decline(self):
""" Marks event invitation as Declined. """
for attendee in self:
attendee.event_id.message_post(
body=_("%s has declined invitation") % (attendee.common_name),
subtype_xmlid="calendar.subtype_invitation")
return self.write({'state': 'declined'})
| 45.409938 | 7,311 |
1,160 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.exceptions import BadRequest
from odoo import models
from odoo.http import request
class IrHttp(models.AbstractModel):
_inherit = 'ir.http'
@classmethod
def _auth_method_calendar(cls):
token = request.params.get('token', '')
error_message = False
attendee = request.env['calendar.attendee'].sudo().search([('access_token', '=', token)], limit=1)
if not attendee:
error_message = """Invalid Invitation Token."""
elif request.session.uid and request.session.login != 'anonymous':
# if valid session but user is not match
user = request.env['res.users'].sudo().browse(request.session.uid)
if attendee.partner_id != user.partner_id:
error_message = """Invitation cannot be forwarded via email. This event/meeting belongs to %s and you are logged in as %s. Please ask organizer to add you.""" % (attendee.email, user.email)
if error_message:
raise BadRequest(error_message)
cls._auth_method_public()
| 38.666667 | 1,160 |
539 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from random import randint
from odoo import fields, models
class MeetingType(models.Model):
_name = 'calendar.event.type'
_description = 'Event Meeting Type'
def _default_color(self):
return randint(1, 11)
name = fields.Char('Name', required=True)
color = fields.Integer('Color', default=_default_color)
_sql_constraints = [
('name_uniq', 'unique (name)', "Tag name already exists !"),
]
| 24.5 | 539 |
21,446 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, time
import pytz
from dateutil import rrule
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.addons.base.models.res_partner import _tz_get
MAX_RECURRENT_EVENT = 720
SELECT_FREQ_TO_RRULE = {
'daily': rrule.DAILY,
'weekly': rrule.WEEKLY,
'monthly': rrule.MONTHLY,
'yearly': rrule.YEARLY,
}
RRULE_FREQ_TO_SELECT = {
rrule.DAILY: 'daily',
rrule.WEEKLY: 'weekly',
rrule.MONTHLY: 'monthly',
rrule.YEARLY: 'yearly',
}
RRULE_WEEKDAY_TO_FIELD = {
rrule.MO.weekday: 'mon',
rrule.TU.weekday: 'tue',
rrule.WE.weekday: 'wed',
rrule.TH.weekday: 'thu',
rrule.FR.weekday: 'fri',
rrule.SA.weekday: 'sat',
rrule.SU.weekday: 'sun',
}
RRULE_WEEKDAYS = {'SUN': 'SU', 'MON': 'MO', 'TUE': 'TU', 'WED': 'WE', 'THU': 'TH', 'FRI': 'FR', 'SAT': 'SA'}
RRULE_TYPE_SELECTION = [
('daily', 'Days'),
('weekly', 'Weeks'),
('monthly', 'Months'),
('yearly', 'Years'),
]
END_TYPE_SELECTION = [
('count', 'Number of repetitions'),
('end_date', 'End date'),
('forever', 'Forever'),
]
MONTH_BY_SELECTION = [
('date', 'Date of month'),
('day', 'Day of month'),
]
WEEKDAY_SELECTION = [
('MON', 'Monday'),
('TUE', 'Tuesday'),
('WED', 'Wednesday'),
('THU', 'Thursday'),
('FRI', 'Friday'),
('SAT', 'Saturday'),
('SUN', 'Sunday'),
]
BYDAY_SELECTION = [
('1', 'First'),
('2', 'Second'),
('3', 'Third'),
('4', 'Fourth'),
('-1', 'Last'),
]
def freq_to_select(rrule_freq):
return RRULE_FREQ_TO_SELECT[rrule_freq]
def freq_to_rrule(freq):
return SELECT_FREQ_TO_RRULE[freq]
def weekday_to_field(weekday_index):
return RRULE_WEEKDAY_TO_FIELD.get(weekday_index)
class RecurrenceRule(models.Model):
_name = 'calendar.recurrence'
_description = 'Event Recurrence Rule'
name = fields.Char(compute='_compute_name', store=True)
base_event_id = fields.Many2one(
'calendar.event', ondelete='set null', copy=False) # store=False ?
calendar_event_ids = fields.One2many('calendar.event', 'recurrence_id')
event_tz = fields.Selection(
_tz_get, string='Timezone',
default=lambda self: self.env.context.get('tz') or self.env.user.tz)
rrule = fields.Char(compute='_compute_rrule', inverse='_inverse_rrule', store=True)
dtstart = fields.Datetime(compute='_compute_dtstart')
rrule_type = fields.Selection(RRULE_TYPE_SELECTION, default='weekly')
end_type = fields.Selection(END_TYPE_SELECTION, default='count')
interval = fields.Integer(default=1)
count = fields.Integer(default=1)
mon = fields.Boolean()
tue = fields.Boolean()
wed = fields.Boolean()
thu = fields.Boolean()
fri = fields.Boolean()
sat = fields.Boolean()
sun = fields.Boolean()
month_by = fields.Selection(MONTH_BY_SELECTION, default='date')
day = fields.Integer(default=1)
weekday = fields.Selection(WEEKDAY_SELECTION, string='Weekday')
byday = fields.Selection(BYDAY_SELECTION, string='By day')
until = fields.Date('Repeat Until')
_sql_constraints = [
('month_day',
"CHECK (rrule_type != 'monthly' "
"OR month_by != 'day' "
"OR day >= 1 AND day <= 31 "
"OR weekday in %s AND byday in %s)"
% (tuple(wd[0] for wd in WEEKDAY_SELECTION), tuple(bd[0] for bd in BYDAY_SELECTION)),
"The day must be between 1 and 31"),
]
@api.depends('rrule')
def _compute_name(self):
for recurrence in self:
period = dict(RRULE_TYPE_SELECTION)[recurrence.rrule_type]
every = _("Every %(count)s %(period)s", count=recurrence.interval, period=period)
if recurrence.end_type == 'count':
end = _("for %s events", recurrence.count)
elif recurrence.end_type == 'end_date':
end = _("until %s", recurrence.until)
else:
end = ''
if recurrence.rrule_type == 'weekly':
weekdays = recurrence._get_week_days()
# Convert Weekday object
weekdays = [str(w) for w in weekdays]
# We need to get the day full name from its three first letters.
week_map = {v: k for k, v in RRULE_WEEKDAYS.items()}
weekday_short = [week_map[w] for w in weekdays]
day_strings = [d[1] for d in WEEKDAY_SELECTION if d[0] in weekday_short]
on = _("on %s") % ", ".join([day_name for day_name in day_strings])
elif recurrence.rrule_type == 'monthly':
if recurrence.month_by == 'day':
weekday_label = dict(BYDAY_SELECTION)[recurrence.byday]
on = _("on the %(position)s %(weekday)s", position=recurrence.byday, weekday=weekday_label)
else:
on = _("day %s", recurrence.day)
else:
on = ''
recurrence.name = ' '.join(filter(lambda s: s, [every, on, end]))
@api.depends('calendar_event_ids.start')
def _compute_dtstart(self):
groups = self.env['calendar.event'].read_group([('recurrence_id', 'in', self.ids)], ['start:min'], ['recurrence_id'])
start_mapping = {
group['recurrence_id'][0]: group['start']
for group in groups
}
for recurrence in self:
recurrence.dtstart = start_mapping.get(recurrence.id)
@api.depends(
'byday', 'until', 'rrule_type', 'month_by', 'interval', 'count', 'end_type',
'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', 'day', 'weekday')
def _compute_rrule(self):
for recurrence in self:
recurrence.rrule = recurrence._rrule_serialize()
def _inverse_rrule(self):
for recurrence in self:
if recurrence.rrule:
values = self._rrule_parse(recurrence.rrule, recurrence.dtstart)
recurrence.write(values)
def _reconcile_events(self, ranges):
"""
:param ranges: iterable of tuples (datetime_start, datetime_stop)
:return: tuple (events of the recurrence already in sync with ranges,
and ranges not covered by any events)
"""
ranges = set(ranges)
synced_events = self.calendar_event_ids.filtered(lambda e: e._range() in ranges)
existing_ranges = set(event._range() for event in synced_events)
ranges_to_create = (event_range for event_range in ranges if event_range not in existing_ranges)
return synced_events, ranges_to_create
def _select_new_base_event(self):
"""
when the base event is no more available (archived, deleted, etc.), a new one should be selected
"""
for recurrence in self:
recurrence.base_event_id = recurrence._get_first_event()
def _apply_recurrence(self, specific_values_creation=None, no_send_edit=False, generic_values_creation=None):
"""Create missing events in the recurrence and detach events which no longer
follow the recurrence rules.
:return: detached events
"""
event_vals = []
keep = self.env['calendar.event']
if specific_values_creation is None:
specific_values_creation = {}
for recurrence in self.filtered('base_event_id'):
recurrence.calendar_event_ids |= recurrence.base_event_id
event = recurrence.base_event_id or recurrence._get_first_event(include_outliers=False)
duration = event.stop - event.start
if specific_values_creation:
ranges = set([(x[1], x[2]) for x in specific_values_creation if x[0] == recurrence.id])
else:
ranges = recurrence._range_calculation(event, duration)
events_to_keep, ranges = recurrence._reconcile_events(ranges)
keep |= events_to_keep
[base_values] = event.copy_data()
values = []
for start, stop in ranges:
value = dict(base_values, start=start, stop=stop, recurrence_id=recurrence.id, follow_recurrence=True)
if (recurrence.id, start, stop) in specific_values_creation:
value.update(specific_values_creation[(recurrence.id, start, stop)])
if generic_values_creation and recurrence.id in generic_values_creation:
value.update(generic_values_creation[recurrence.id])
values += [value]
event_vals += values
events = self.calendar_event_ids - keep
detached_events = self._detach_events(events)
self.env['calendar.event'].with_context(no_mail_to_attendees=True, mail_create_nolog=True).create(event_vals)
return detached_events
def _split_from(self, event, recurrence_values=None):
"""Stops the current recurrence at the given event and creates a new one starting
with the event.
:param event: starting point of the new recurrence
:param recurrence_values: values applied to the new recurrence
:return: new recurrence
"""
if recurrence_values is None:
recurrence_values = {}
event.ensure_one()
if not self:
return
[values] = self.copy_data()
detached_events = self._stop_at(event)
count = recurrence_values.get('count', 0) or len(detached_events)
return self.create({
**values,
**recurrence_values,
'base_event_id': event.id,
'calendar_event_ids': [(6, 0, detached_events.ids)],
'count': max(count, 1),
})
def _stop_at(self, event):
"""Stops the recurrence at the given event. Detach the event and all following
events from the recurrence.
:return: detached events from the recurrence
"""
self.ensure_one()
events = self._get_events_from(event.start)
detached_events = self._detach_events(events)
if not self.calendar_event_ids:
self.with_context(archive_on_error=True).unlink()
return detached_events
if event.allday:
until = self._get_start_of_period(event.start_date)
else:
until_datetime = self._get_start_of_period(event.start)
until_timezoned = pytz.utc.localize(until_datetime).astimezone(self._get_timezone())
until = until_timezoned.date()
self.write({
'end_type': 'end_date',
'until': until - relativedelta(days=1),
})
return detached_events
@api.model
def _detach_events(self, events):
events.write({
'recurrence_id': False,
'recurrency': False,
})
return events
def _write_events(self, values, dtstart=None):
"""
Write values on events in the recurrence.
:param values: event values
:param dstart: if provided, only write events starting from this point in time
"""
events = self._get_events_from(dtstart) if dtstart else self.calendar_event_ids
return events.with_context(no_mail_to_attendees=True, dont_notify=True).write(dict(values, recurrence_update='self_only'))
def _rrule_serialize(self):
"""
Compute rule string according to value type RECUR of iCalendar
:return: string containing recurring rule (empty if no rule)
"""
if self.interval <= 0:
raise UserError(_('The interval cannot be negative.'))
if self.end_type == 'count' and self.count <= 0:
raise UserError(_('The number of repetitions cannot be negative.'))
return str(self._get_rrule()) if self.rrule_type else ''
@api.model
def _rrule_parse(self, rule_str, date_start):
# LUL TODO clean this mess
data = {}
day_list = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
if 'Z' in rule_str and date_start and not date_start.tzinfo:
date_start = pytz.utc.localize(date_start)
rule = rrule.rrulestr(rule_str, dtstart=date_start)
data['rrule_type'] = freq_to_select(rule._freq)
data['count'] = rule._count
data['interval'] = rule._interval
data['until'] = rule._until
# Repeat weekly
if rule._byweekday:
for weekday in day_list:
data[weekday] = False # reset
for weekday_index in rule._byweekday:
weekday = rrule.weekday(weekday_index)
data[weekday_to_field(weekday.weekday)] = True
data['rrule_type'] = 'weekly'
# Repeat monthly by nweekday ((weekday, weeknumber), )
if rule._bynweekday:
data['weekday'] = day_list[list(rule._bynweekday)[0][0]].upper()
data['byday'] = str(list(rule._bynweekday)[0][1])
data['month_by'] = 'day'
data['rrule_type'] = 'monthly'
if rule._bymonthday:
data['day'] = list(rule._bymonthday)[0]
data['month_by'] = 'date'
data['rrule_type'] = 'monthly'
# Repeat yearly but for odoo it's monthly, take same information as monthly but interval is 12 times
if rule._bymonth:
data['interval'] *= 12
if data.get('until'):
data['end_type'] = 'end_date'
elif data.get('count'):
data['end_type'] = 'count'
else:
data['end_type'] = 'forever'
return data
def _get_lang_week_start(self):
lang = self.env['res.lang']._lang_get(self.env.user.lang)
week_start = int(lang.week_start) # lang.week_start ranges from '1' to '7'
return rrule.weekday(week_start - 1) # rrule expects an int from 0 to 6
def _get_start_of_period(self, dt):
if self.rrule_type == 'weekly':
week_start = self._get_lang_week_start()
start = dt + relativedelta(weekday=week_start(-1))
elif self.rrule_type == 'monthly':
start = dt + relativedelta(day=1)
else:
start = dt
# Comparaison of DST (to manage the case of going too far back in time).
# If we detect a change in the DST between the creation date of an event
# and the date used for the occurrence period, we use the creation date of the event.
# This is a hack to avoid duplication of events (for example on google calendar).
if isinstance(dt, datetime):
timezone = self._get_timezone()
dst_dt = timezone.localize(dt).dst()
dst_start = timezone.localize(start).dst()
if dst_dt != dst_start:
start = dt
return start
def _get_first_event(self, include_outliers=False):
if not self.calendar_event_ids:
return self.env['calendar.event']
events = self.calendar_event_ids.sorted('start')
if not include_outliers:
events -= self._get_outliers()
return events[:1]
def _get_outliers(self):
synced_events = self.env['calendar.event']
for recurrence in self:
if recurrence.calendar_event_ids:
start = min(recurrence.calendar_event_ids.mapped('start'))
starts = set(recurrence._get_occurrences(start))
synced_events |= recurrence.calendar_event_ids.filtered(lambda e: e.start in starts)
return self.calendar_event_ids - synced_events
def _range_calculation(self, event, duration):
""" Calculate the range of recurrence when applying the recurrence
The following issues are taken into account:
start of period is sometimes in the past (weekly or monthly rule).
We can easily filter these range values but then the count value may be wrong...
In that case, we just increase the count value, recompute the ranges and dismiss the useless values
"""
self.ensure_one()
original_count = self.end_type == 'count' and self.count
ranges = set(self._get_ranges(event.start, duration))
future_events = set((x, y) for x, y in ranges if x.date() >= event.start.date() and y.date() >= event.start.date())
if original_count and len(future_events) < original_count:
# Rise count number because some past values will be dismissed.
self.count = (2*original_count) - len(future_events)
ranges = set(self._get_ranges(event.start, duration))
# We set back the occurrence number to its original value
self.count = original_count
# Remove ranges of events occurring in the past
ranges = set((x, y) for x, y in ranges if x.date() >= event.start.date() and y.date() >= event.start.date())
return ranges
def _get_ranges(self, start, event_duration):
starts = self._get_occurrences(start)
return ((start, start + event_duration) for start in starts)
def _get_timezone(self):
return pytz.timezone(self.event_tz or self.env.context.get('tz') or 'UTC')
def _get_occurrences(self, dtstart):
"""
Get ocurrences of the rrule
:param dtstart: start of the recurrence
:return: iterable of datetimes
"""
self.ensure_one()
dtstart = self._get_start_of_period(dtstart)
if self._is_allday():
return self._get_rrule(dtstart=dtstart)
timezone = self._get_timezone()
# Localize the starting datetime to avoid missing the first occurrence
dtstart = pytz.utc.localize(dtstart).astimezone(timezone)
# dtstart is given as a naive datetime, but it actually represents a timezoned datetime
# (rrule package expects a naive datetime)
occurences = self._get_rrule(dtstart=dtstart.replace(tzinfo=None))
# Special timezoning is needed to handle DST (Daylight Saving Time) changes.
# Given the following recurrence:
# - monthly
# - 1st of each month
# - timezone US/Eastern (UTC−05:00)
# - at 6am US/Eastern = 11am UTC
# - from 2019/02/01 to 2019/05/01.
# The naive way would be to store:
# 2019/02/01 11:00 - 2019/03/01 11:00 - 2019/04/01 11:00 - 2019/05/01 11:00 (UTC)
#
# But a DST change occurs on 2019/03/10 in US/Eastern timezone. US/Eastern is now UTC−04:00.
# From this point in time, 11am (UTC) is actually converted to 7am (US/Eastern) instead of the expected 6am!
# What should be stored is:
# 2019/02/01 11:00 - 2019/03/01 11:00 - 2019/04/01 10:00 - 2019/05/01 10:00 (UTC)
# ***** *****
return (timezone.localize(occurrence, is_dst=False).astimezone(pytz.utc).replace(tzinfo=None) for occurrence in occurences)
def _get_events_from(self, dtstart):
return self.env['calendar.event'].search([
('id', 'in', self.calendar_event_ids.ids),
('start', '>=', dtstart)
])
def _get_week_days(self):
"""
:return: tuple of rrule weekdays for this recurrence.
"""
return tuple(
rrule.weekday(weekday_index)
for weekday_index, weekday in {
rrule.MO.weekday: self.mon,
rrule.TU.weekday: self.tue,
rrule.WE.weekday: self.wed,
rrule.TH.weekday: self.thu,
rrule.FR.weekday: self.fri,
rrule.SA.weekday: self.sat,
rrule.SU.weekday: self.sun,
}.items() if weekday
)
def _is_allday(self):
"""Returns whether a majority of events are allday or not (there might be some outlier events)
"""
score = sum(1 if e.allday else -1 for e in self.calendar_event_ids)
return score >= 0
def _get_rrule(self, dtstart=None):
self.ensure_one()
freq = self.rrule_type
rrule_params = dict(
dtstart=dtstart,
interval=self.interval,
)
if freq == 'monthly' and self.month_by == 'date': # e.g. every 15th of the month
rrule_params['bymonthday'] = self.day
elif freq == 'monthly' and self.month_by == 'day': # e.g. every 2nd Monday in the month
rrule_params['byweekday'] = getattr(rrule, RRULE_WEEKDAYS[self.weekday])(int(self.byday)) # e.g. MO(+2) for the second Monday of the month
elif freq == 'weekly':
weekdays = self._get_week_days()
if not weekdays:
raise UserError(_("You have to choose at least one day in the week"))
rrule_params['byweekday'] = weekdays
rrule_params['wkst'] = self._get_lang_week_start()
if self.end_type == 'count': # e.g. stop after X occurence
rrule_params['count'] = min(self.count, MAX_RECURRENT_EVENT)
elif self.end_type == 'forever':
rrule_params['count'] = MAX_RECURRENT_EVENT
elif self.end_type == 'end_date': # e.g. stop after 12/10/2020
rrule_params['until'] = datetime.combine(self.until, time.max)
return rrule.rrule(
freq_to_rrule(freq), **rrule_params
)
| 40.380414 | 21,442 |
1,988 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields, tools, _
from odoo.tools import is_html_empty
class MailActivityType(models.Model):
_inherit = "mail.activity.type"
category = fields.Selection(selection_add=[('meeting', 'Meeting')])
class MailActivity(models.Model):
_inherit = "mail.activity"
calendar_event_id = fields.Many2one('calendar.event', string="Calendar Meeting", ondelete='cascade')
def action_create_calendar_event(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("calendar.action_calendar_event")
action['context'] = {
'default_activity_type_id': self.activity_type_id.id,
'default_res_id': self.env.context.get('default_res_id'),
'default_res_model': self.env.context.get('default_res_model'),
'default_name': self.summary or self.res_name,
'default_description': self.note if not is_html_empty(self.note) else '',
'default_activity_ids': [(6, 0, self.ids)],
}
return action
def _action_done(self, feedback=False, attachment_ids=False):
events = self.mapped('calendar_event_id')
messages, activities = super(MailActivity, self)._action_done(feedback=feedback, attachment_ids=attachment_ids)
if feedback:
for event in events:
description = event.description
description = '%s<br />%s' % (
description if not tools.is_html_empty(description) else '',
_('Feedback: %(feedback)s', feedback=tools.plaintext2html(feedback)) if feedback else '',
)
event.write({'description': description})
return messages, activities
def unlink_w_meeting(self):
events = self.mapped('calendar_event_id')
res = self.unlink()
events.unlink()
return res
| 41.416667 | 1,988 |
56,583 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import math
import logging
from datetime import timedelta
from itertools import repeat
import pytz
from odoo import api, fields, models, Command
from odoo.osv.expression import AND
from odoo.addons.base.models.res_partner import _tz_get
from odoo.addons.calendar.models.calendar_attendee import Attendee
from odoo.addons.calendar.models.calendar_recurrence import (
weekday_to_field,
RRULE_TYPE_SELECTION,
END_TYPE_SELECTION,
MONTH_BY_SELECTION,
WEEKDAY_SELECTION,
BYDAY_SELECTION
)
from odoo.tools.translate import _
from odoo.tools.misc import get_lang
from odoo.tools import pycompat, html2plaintext, is_html_empty
from odoo.exceptions import UserError, ValidationError
_logger = logging.getLogger(__name__)
try:
import vobject
except ImportError:
_logger.warning("`vobject` Python module not found, iCal file generation disabled. Consider installing this module if you want to generate iCal files")
vobject = None
SORT_ALIASES = {
'start': 'sort_start',
'start_date': 'sort_start',
}
def get_weekday_occurence(date):
"""
:returns: ocurrence
>>> get_weekday_occurence(date(2019, 12, 17))
3 # third Tuesday of the month
>>> get_weekday_occurence(date(2019, 12, 25))
-1 # last Friday of the month
"""
occurence_in_month = math.ceil(date.day/7)
if occurence_in_month in {4, 5}: # fourth or fifth week on the month -> last
return -1
return occurence_in_month
class Meeting(models.Model):
_name = 'calendar.event'
_description = "Calendar Event"
_order = "start desc"
_inherit = ["mail.thread"]
@api.model
def default_get(self, fields):
# super default_model='crm.lead' for easier use in addons
if self.env.context.get('default_res_model') and not self.env.context.get('default_res_model_id'):
self = self.with_context(
default_res_model_id=self.env['ir.model']._get_id(self.env.context['default_res_model'])
)
defaults = super(Meeting, self).default_get(fields)
# support active_model / active_id as replacement of default_* if not already given
if 'res_model_id' not in defaults and 'res_model_id' in fields and \
self.env.context.get('active_model') and self.env.context['active_model'] != 'calendar.event':
defaults['res_model_id'] = self.env['ir.model']._get_id(self.env.context['active_model'])
defaults['res_model'] = self.env.context.get('active_model')
if 'res_id' not in defaults and 'res_id' in fields and \
defaults.get('res_model_id') and self.env.context.get('active_id'):
defaults['res_id'] = self.env.context['active_id']
return defaults
@api.model
def _default_partners(self):
""" When active_model is res.partner, the current partners should be attendees """
partners = self.env.user.partner_id
active_id = self._context.get('active_id')
if self._context.get('active_model') == 'res.partner' and active_id and active_id not in partners.ids:
partners |= self.env['res.partner'].browse(active_id)
return partners
# description
name = fields.Char('Meeting Subject', required=True)
description = fields.Html('Description')
user_id = fields.Many2one('res.users', 'Organizer', default=lambda self: self.env.user)
partner_id = fields.Many2one(
'res.partner', string='Scheduled by', related='user_id.partner_id', readonly=True)
location = fields.Char('Location', tracking=True, help="Location of Event")
videocall_location = fields.Char('Meeting URL')
# visibility
privacy = fields.Selection(
[('public', 'Public'),
('private', 'Private'),
('confidential', 'Only internal users')],
'Privacy', default='public', required=True,
help="People to whom this event will be visible.")
show_as = fields.Selection(
[('free', 'Available'),
('busy', 'Busy')], 'Show as', default='busy', required=True,
help="If the time is shown as 'busy', this event will be visible to other people with either the full \
information or simply 'busy' written depending on its privacy. Use this option to let other people know \
that you are unavailable during that period of time. \n If the event is shown as 'free', other users know \
that you are available during that period of time.")
is_highlighted = fields.Boolean(
compute='_compute_is_highlighted', string='Is the Event Highlighted')
is_organizer_alone = fields.Boolean(compute='_compute_is_organizer_alone', string="Is the Organizer Alone",
help="""Check if the organizer is alone in the event, i.e. if the organizer is the only one that hasn't declined
the event (only if the organizer is not the only attendee)""")
# filtering
active = fields.Boolean(
'Active', default=True,
tracking=True,
help="If the active field is set to false, it will allow you to hide the event alarm information without removing it.")
categ_ids = fields.Many2many(
'calendar.event.type', 'meeting_category_rel', 'event_id', 'type_id', 'Tags')
# timing
start = fields.Datetime(
'Start', required=True, tracking=True, default=fields.Date.today,
help="Start date of an event, without time for full days events")
stop = fields.Datetime(
'Stop', required=True, tracking=True, default=lambda self: fields.Datetime.today() + timedelta(hours=1),
compute='_compute_stop', readonly=False, store=True,
help="Stop date of an event, without time for full days events")
display_time = fields.Char('Event Time', compute='_compute_display_time')
allday = fields.Boolean('All Day', default=False)
start_date = fields.Date(
'Start Date', store=True, tracking=True,
compute='_compute_dates', inverse='_inverse_dates')
stop_date = fields.Date(
'End Date', store=True, tracking=True,
compute='_compute_dates', inverse='_inverse_dates')
duration = fields.Float('Duration', compute='_compute_duration', store=True, readonly=False)
# linked document
# LUL TODO use fields.Reference ?
res_id = fields.Integer('Document ID')
res_model_id = fields.Many2one('ir.model', 'Document Model', ondelete='cascade')
res_model = fields.Char(
'Document Model Name', related='res_model_id.model', readonly=True, store=True)
# messaging
activity_ids = fields.One2many('mail.activity', 'calendar_event_id', string='Activities')
# attendees
attendee_ids = fields.One2many(
'calendar.attendee', 'event_id', 'Participant')
attendee_status = fields.Selection(
Attendee.STATE_SELECTION, string='Attendee Status', compute='_compute_attendee')
partner_ids = fields.Many2many(
'res.partner', 'calendar_event_res_partner_rel',
string='Attendees', default=_default_partners)
# alarms
alarm_ids = fields.Many2many(
'calendar.alarm', 'calendar_alarm_calendar_event_rel',
string='Reminders', ondelete="restrict",
help="Notifications sent to all attendees to remind of the meeting.")
# RECURRENCE FIELD
recurrency = fields.Boolean('Recurrent')
recurrence_id = fields.Many2one(
'calendar.recurrence', string="Recurrence Rule", index=True)
follow_recurrence = fields.Boolean(default=False) # Indicates if an event follows the recurrence, i.e. is not an exception
recurrence_update = fields.Selection([
('self_only', "This event"),
('future_events', "This and following events"),
('all_events', "All events"),
], store=False, copy=False, default='self_only',
help="Choose what to do with other events in the recurrence. Updating All Events is not allowed when dates or time is modified")
# Those field are pseudo-related fields of recurrence_id.
# They can't be "real" related fields because it should work at record creation
# when recurrence_id is not created yet.
# If some of these fields are set and recurrence_id does not exists,
# a `calendar.recurrence.rule` will be dynamically created.
rrule = fields.Char('Recurrent Rule', compute='_compute_recurrence', readonly=False)
rrule_type = fields.Selection(RRULE_TYPE_SELECTION, string='Recurrence',
help="Let the event automatically repeat at that interval",
compute='_compute_recurrence', readonly=False)
event_tz = fields.Selection(
_tz_get, string='Timezone', compute='_compute_recurrence', readonly=False)
end_type = fields.Selection(
END_TYPE_SELECTION, string='Recurrence Termination',
compute='_compute_recurrence', readonly=False)
interval = fields.Integer(
string='Repeat Every', compute='_compute_recurrence', readonly=False,
help="Repeat every (Days/Week/Month/Year)")
count = fields.Integer(
string='Repeat', help="Repeat x times", compute='_compute_recurrence', readonly=False)
mon = fields.Boolean(compute='_compute_recurrence', readonly=False)
tue = fields.Boolean(compute='_compute_recurrence', readonly=False)
wed = fields.Boolean(compute='_compute_recurrence', readonly=False)
thu = fields.Boolean(compute='_compute_recurrence', readonly=False)
fri = fields.Boolean(compute='_compute_recurrence', readonly=False)
sat = fields.Boolean(compute='_compute_recurrence', readonly=False)
sun = fields.Boolean(compute='_compute_recurrence', readonly=False)
month_by = fields.Selection(
MONTH_BY_SELECTION, string='Option', compute='_compute_recurrence', readonly=False)
day = fields.Integer('Date of month', compute='_compute_recurrence', readonly=False)
weekday = fields.Selection(WEEKDAY_SELECTION, compute='_compute_recurrence', readonly=False)
byday = fields.Selection(BYDAY_SELECTION, compute='_compute_recurrence', readonly=False)
until = fields.Date(compute='_compute_recurrence', readonly=False)
# UI Fields.
display_description = fields.Boolean(compute='_compute_display_description')
def _compute_is_highlighted(self):
if self.env.context.get('active_model') == 'res.partner':
partner_id = self.env.context.get('active_id')
for event in self:
if event.partner_ids.filtered(lambda s: s.id == partner_id):
event.is_highlighted = True
else:
event.is_highlighted = False
else:
for event in self:
event.is_highlighted = False
@api.depends('partner_id', 'attendee_ids')
def _compute_is_organizer_alone(self):
"""
Check if the organizer of the event is the only one who has accepted the event.
It does not apply if the organizer is the only attendee of the event because it
would represent a personnal event.
The goal of this field is to highlight to the user that the others attendees are
not available for this event.
"""
for event in self:
organizer = event.attendee_ids.filtered(lambda a: a.partner_id == event.partner_id)
all_declined = not any((event.attendee_ids - organizer).filtered(lambda a: a.state != 'declined'))
event.is_organizer_alone = len(event.attendee_ids) > 1 and all_declined
def _compute_display_time(self):
for meeting in self:
meeting.display_time = self._get_display_time(meeting.start, meeting.stop, meeting.duration, meeting.allday)
@api.depends('allday', 'start', 'stop')
def _compute_dates(self):
""" Adapt the value of start_date(time)/stop_date(time)
according to start/stop fields and allday. Also, compute
the duration for not allday meeting ; otherwise the
duration is set to zero, since the meeting last all the day.
"""
for meeting in self:
if meeting.allday and meeting.start and meeting.stop:
meeting.start_date = meeting.start.date()
meeting.stop_date = meeting.stop.date()
else:
meeting.start_date = False
meeting.stop_date = False
@api.depends('stop', 'start')
def _compute_duration(self):
for event in self:
event.duration = self._get_duration(event.start, event.stop)
@api.depends('start', 'duration')
def _compute_stop(self):
# stop and duration fields both depends on the start field.
# But they also depends on each other.
# When start is updated, we want to update the stop datetime based on
# the *current* duration. In other words, we want: change start => keep the duration fixed and
# recompute stop accordingly.
# However, while computing stop, duration is marked to be recomputed. Calling `event.duration` would trigger
# its recomputation. To avoid this we manually mark the field as computed.
duration_field = self._fields['duration']
self.env.remove_to_compute(duration_field, self)
for event in self:
# Round the duration (in hours) to the minute to avoid weird situations where the event
# stops at 4:19:59, later displayed as 4:19.
event.stop = event.start and event.start + timedelta(minutes=round((event.duration or 1.0) * 60))
if event.allday:
event.stop -= timedelta(seconds=1)
def _inverse_dates(self):
""" This method is used to set the start and stop values of all day events.
The calendar view needs date_start and date_stop values to display correctly the allday events across
several days. As the user edit the {start,stop}_date fields when allday is true,
this inverse method is needed to update the start/stop value and have a relevant calendar view.
"""
for meeting in self:
if meeting.allday:
# Convention break:
# stop and start are NOT in UTC in allday event
# in this case, they actually represent a date
# because fullcalendar just drops times for full day events.
# i.e. Christmas is on 25/12 for everyone
# even if people don't celebrate it simultaneously
enddate = fields.Datetime.from_string(meeting.stop_date)
enddate = enddate.replace(hour=18)
startdate = fields.Datetime.from_string(meeting.start_date)
startdate = startdate.replace(hour=8) # Set 8 AM
meeting.write({
'start': startdate.replace(tzinfo=None),
'stop': enddate.replace(tzinfo=None)
})
def _compute_attendee(self):
for meeting in self:
attendee = meeting._find_attendee()
meeting.attendee_status = attendee.state if attendee else 'needsAction'
@api.constrains('start', 'stop', 'start_date', 'stop_date')
def _check_closing_date(self):
for meeting in self:
if not meeting.allday and meeting.start and meeting.stop and meeting.stop < meeting.start:
raise ValidationError(
_('The ending date and time cannot be earlier than the starting date and time.') + '\n' +
_("Meeting '%(name)s' starts '%(start_datetime)s' and ends '%(end_datetime)s'",
name=meeting.name,
start_datetime=meeting.start,
end_datetime=meeting.stop
)
)
if meeting.allday and meeting.start_date and meeting.stop_date and meeting.stop_date < meeting.start_date:
raise ValidationError(
_('The ending date cannot be earlier than the starting date.') + '\n' +
_("Meeting '%(name)s' starts '%(start_datetime)s' and ends '%(end_datetime)s'",
name=meeting.name,
start_datetime=meeting.start,
end_datetime=meeting.stop
)
)
@api.depends('recurrence_id', 'recurrency')
def _compute_recurrence(self):
recurrence_fields = self._get_recurrent_fields()
false_values = {field: False for field in recurrence_fields} # computes need to set a value
defaults = self.env['calendar.recurrence'].default_get(recurrence_fields)
default_rrule_values = self.recurrence_id.default_get(recurrence_fields)
for event in self:
if event.recurrency:
event.update(defaults) # default recurrence values are needed to correctly compute the recurrence params
event_values = event._get_recurrence_params()
rrule_values = {
field: event.recurrence_id[field]
for field in recurrence_fields
if event.recurrence_id[field]
}
rrule_values = rrule_values or default_rrule_values
event.update({**false_values, **event_values, **rrule_values})
else:
event.update(false_values)
@api.depends('description')
def _compute_display_description(self):
for event in self:
event.display_description = not is_html_empty(event.description)
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
# Prevent sending update notification when _inverse_dates is called
self = self.with_context(is_calendar_event_new=True)
vals_list = [ # Else bug with quick_create when we are filter on an other user
dict(vals, user_id=self.env.user.id) if not 'user_id' in vals else vals
for vals in vals_list
]
defaults = self.default_get(['activity_ids', 'res_model_id', 'res_id', 'user_id', 'res_model', 'partner_ids'])
meeting_activity_type = self.env['mail.activity.type'].search([('category', '=', 'meeting')], limit=1)
# get list of models ids and filter out None values directly
model_ids = list(filter(None, {values.get('res_model_id', defaults.get('res_model_id')) for values in vals_list}))
model_name = defaults.get('res_model')
valid_activity_model_ids = model_name and self.env[model_name].sudo().browse(model_ids).filtered(lambda m: 'activity_ids' in m).ids or []
if meeting_activity_type and not defaults.get('activity_ids'):
for values in vals_list:
# created from calendar: try to create an activity on the related record
if values.get('activity_ids'):
continue
res_model_id = values.get('res_model_id', defaults.get('res_model_id'))
res_id = values.get('res_id', defaults.get('res_id'))
user_id = values.get('user_id', defaults.get('user_id'))
if not res_model_id or not res_id:
continue
if res_model_id not in valid_activity_model_ids:
continue
activity_vals = {
'res_model_id': res_model_id,
'res_id': res_id,
'activity_type_id': meeting_activity_type.id,
}
if user_id:
activity_vals['user_id'] = user_id
values['activity_ids'] = [(0, 0, activity_vals)]
# Add commands to create attendees from partners (if present) if no attendee command
# is already given (coming from Google event for example).
# Automatically add the current partner when creating an event if there is none (happens when we quickcreate an event)
default_partners_ids = defaults.get('partner_ids') or ([(4, self.env.user.partner_id.id)])
vals_list = [
dict(vals, attendee_ids=self._attendees_values(vals.get('partner_ids', default_partners_ids)))
if not vals.get('attendee_ids')
else vals
for vals in vals_list
]
recurrence_fields = self._get_recurrent_fields()
recurring_vals = [vals for vals in vals_list if vals.get('recurrency')]
other_vals = [vals for vals in vals_list if not vals.get('recurrency')]
events = super().create(other_vals)
for vals in recurring_vals:
vals['follow_recurrence'] = True
recurring_events = super().create(recurring_vals)
events += recurring_events
for event, vals in zip(recurring_events, recurring_vals):
recurrence_values = {field: vals.pop(field) for field in recurrence_fields if field in vals}
if vals.get('recurrency'):
detached_events = event._apply_recurrence_values(recurrence_values)
detached_events.active = False
events.filtered(lambda event: event.start > fields.Datetime.now()).attendee_ids._send_mail_to_attendees(
self.env.ref('calendar.calendar_template_meeting_invitation', raise_if_not_found=False)
)
events._sync_activities(fields={f for vals in vals_list for f in vals.keys()})
if not self.env.context.get('dont_notify'):
events._setup_alarms()
return events.with_context(is_calendar_event_new=False)
def _compute_field_value(self, field):
if field.compute_sudo:
return super(Meeting, self.with_context(prefetch_fields=False))._compute_field_value(field)
return super()._compute_field_value(field)
def _read(self, fields):
if self.env.is_system():
super()._read(fields)
return
fields = set(fields)
private_fields = fields - self._get_public_fields()
if not private_fields:
super()._read(fields)
return
private_fields.add('partner_ids')
super()._read(fields | {'privacy', 'user_id', 'partner_ids'})
current_partner_id = self.env.user.partner_id
others_private_events = self.filtered(
lambda e: e.privacy == 'private' \
and e.user_id != self.env.user \
and current_partner_id not in e.partner_ids
)
if not others_private_events:
return
for field_name in private_fields:
field = self._fields[field_name]
replacement = field.convert_to_cache(
_('Busy') if field_name == 'name' else False,
others_private_events)
self.env.cache.update(others_private_events, field, repeat(replacement))
def write(self, values):
detached_events = self.env['calendar.event']
recurrence_update_setting = values.pop('recurrence_update', None)
update_recurrence = recurrence_update_setting in ('all_events', 'future_events') and len(self) == 1
break_recurrence = values.get('recurrency') is False
update_alarms = False
update_time = False
if 'partner_ids' in values:
values['attendee_ids'] = self._attendees_values(values['partner_ids'])
update_alarms = True
time_fields = self.env['calendar.event']._get_time_fields()
if any([values.get(key) for key in time_fields]) or 'alarm_ids' in values:
update_alarms = True
update_time = True
if (not recurrence_update_setting or recurrence_update_setting == 'self_only' and len(self) == 1) and 'follow_recurrence' not in values:
if any({field: values.get(field) for field in time_fields if field in values}):
values['follow_recurrence'] = False
previous_attendees = self.attendee_ids
recurrence_values = {field: values.pop(field) for field in self._get_recurrent_fields() if field in values}
if update_recurrence:
if break_recurrence:
# Update this event
detached_events |= self._break_recurrence(future=recurrence_update_setting == 'future_events')
else:
future_update_start = self.start if recurrence_update_setting == 'future_events' else None
time_values = {field: values.pop(field) for field in time_fields if field in values}
if recurrence_update_setting == 'all_events':
# Update all events: we create a new reccurrence and dismiss the existing events
self._rewrite_recurrence(values, time_values, recurrence_values)
else:
# Update future events
detached_events |= self._split_recurrence(time_values)
self.recurrence_id._write_events(values, dtstart=future_update_start)
else:
super().write(values)
self._sync_activities(fields=values.keys())
# We reapply recurrence for future events and when we add a rrule and 'recurrency' == True on the event
if recurrence_update_setting not in ['self_only', 'all_events'] and not break_recurrence:
detached_events |= self._apply_recurrence_values(recurrence_values, future=recurrence_update_setting == 'future_events')
(detached_events & self).active = False
(detached_events - self).with_context(archive_on_error=True).unlink()
# Notify attendees if there is an alarm on the modified event, or if there was an alarm
# that has just been removed, as it might have changed their next event notification
if not self.env.context.get('dont_notify') and update_alarms:
self._setup_alarms()
attendee_update_events = self.filtered(lambda ev: ev.user_id != self.env.user)
if update_time and attendee_update_events:
# Another user update the event time fields. It should not be auto accepted for the organizer.
# This prevent weird behavior when a user modified future events time fields and
# the base event of a recurrence is accepted by the organizer but not the following events
attendee_update_events.attendee_ids.filtered(lambda att: self.user_id.partner_id == att.partner_id).write({'state': 'needsAction'})
current_attendees = self.filtered('active').attendee_ids
if 'partner_ids' in values:
# we send to all partners and not only the new ones
(current_attendees - previous_attendees)._send_mail_to_attendees(
self.env.ref('calendar.calendar_template_meeting_invitation', raise_if_not_found=False)
)
if not self.env.context.get('is_calendar_event_new') and 'start' in values:
start_date = fields.Datetime.to_datetime(values.get('start'))
# Only notify on future events
if start_date and start_date >= fields.Datetime.now():
(current_attendees & previous_attendees).with_context(
calendar_template_ignore_recurrence=not update_recurrence
)._send_mail_to_attendees(
self.env.ref('calendar.calendar_template_meeting_changedate', raise_if_not_found=False)
)
return True
def name_get(self):
""" Hide private events' name for events which don't belong to the current user
"""
hidden = self.filtered(
lambda evt:
evt.privacy == 'private' and
evt.user_id.id != self.env.uid and
self.env.user.partner_id not in evt.partner_ids
)
shown = self - hidden
shown_names = super(Meeting, shown).name_get()
obfuscated_names = [(eid, _('Busy')) for eid in hidden.ids]
return shown_names + obfuscated_names
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
groupby = [groupby] if isinstance(groupby, str) else groupby
grouped_fields = set(group_field.split(':')[0] for group_field in groupby)
private_fields = grouped_fields - self._get_public_fields()
if not self.env.su and private_fields:
# display public and confidential events
domain = AND([domain, ['|', ('privacy', '!=', 'private'), ('user_id', '=', self.env.user.id)]])
self.env['bus.bus']._sendone(self.env.user.partner_id, 'simple_notification', {
'title': _('Private Event Excluded'),
'message': _('Grouping by %s is not allowed on private events.', ', '.join([self._fields[field_name].string for field_name in private_fields]))
})
return super(Meeting, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
return super(Meeting, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
def unlink(self):
# Get concerned attendees to notify them if there is an alarm on the unlinked events,
# as it might have changed their next event notification
events = self.filtered_domain([('alarm_ids', '!=', False)])
partner_ids = events.mapped('partner_ids').ids
# don't forget to update recurrences if there are some base events in the set to unlink,
# but after having removed the events ;-)
recurrences = self.env["calendar.recurrence"].search([
('base_event_id.id', 'in', [e.id for e in self])
])
result = super().unlink()
if recurrences:
recurrences._select_new_base_event()
# Notify the concerned attendees (must be done after removing the events)
self.env['calendar.alarm_manager']._notify_next_alarm(partner_ids)
return result
def copy(self, default=None):
"""When an event is copied, the attendees should be recreated to avoid sharing the same attendee records
between copies
"""
self.ensure_one()
if not default:
default = {}
# We need to make sure that the attendee_ids are recreated with new ids to avoid sharing attendees between events
# The copy should not have the same attendee status than the original event
default.update(partner_ids=[Command.set([])], attendee_ids=[Command.set([])])
copied_event = super().copy(default)
copied_event.write({'partner_ids': [(Command.set(self.partner_ids.ids))]})
return copied_event
def _attendees_values(self, partner_commands):
"""
:param partner_commands: ORM commands for partner_id field (0 and 1 commands not supported)
:return: associated attendee_ids ORM commands
"""
attendee_commands = []
removed_partner_ids = []
added_partner_ids = []
for command in partner_commands:
op = command[0]
if op in (2, 3): # Remove partner
removed_partner_ids += [command[1]]
elif op == 6: # Replace all
removed_partner_ids += set(self.partner_ids.ids) - set(command[2]) # Don't recreate attendee if partner already attend the event
added_partner_ids += set(command[2]) - set(self.partner_ids.ids)
elif op == 4:
added_partner_ids += [command[1]] if command[1] not in self.partner_ids.ids else []
# commands 0 and 1 not supported
if not self:
attendees_to_unlink = self.env['calendar.attendee']
else:
attendees_to_unlink = self.env['calendar.attendee'].search([
('event_id', 'in', self.ids),
('partner_id', 'in', removed_partner_ids),
])
attendee_commands += [[2, attendee.id] for attendee in attendees_to_unlink] # Removes and delete
attendee_commands += [
[0, 0, dict(partner_id=partner_id)]
for partner_id in added_partner_ids
]
return attendee_commands
# ------------------------------------------------------------
# ACTIONS
# ------------------------------------------------------------
def action_open_calendar_event(self):
if self.res_model and self.res_id:
return self.env[self.res_model].browse(self.res_id).get_formview_action()
return False
def action_sendmail(self):
email = self.env.user.email
if email:
for meeting in self:
meeting.attendee_ids._send_mail_to_attendees(
self.env.ref('calendar.calendar_template_meeting_invitation', raise_if_not_found=False)
)
return True
def action_open_composer(self):
if not self.partner_ids:
raise UserError(_("There are no attendees on these events"))
template_id = self.env['ir.model.data']._xmlid_to_res_id('calendar.calendar_template_meeting_update', raise_if_not_found=False)
# The mail is sent with datetime corresponding to the sending user TZ
composition_mode = self.env.context.get('composition_mode', 'comment')
compose_ctx = dict(
default_composition_mode=composition_mode,
default_model='calendar.event',
default_res_ids=self.ids,
default_use_template=bool(template_id),
default_template_id=template_id,
default_partner_ids=self.partner_ids.ids,
mail_tz=self.env.user.tz,
)
return {
'type': 'ir.actions.act_window',
'name': _('Contact Attendees'),
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(False, 'form')],
'view_id': False,
'target': 'new',
'context': compose_ctx,
}
def action_join_meeting(self, partner_id):
""" Method used when an existing user wants to join
"""
self.ensure_one()
partner = self.env['res.partner'].browse(partner_id)
if partner not in self.partner_ids:
self.write({'partner_ids': [(4, partner.id)]})
def action_mass_deletion(self, recurrence_update_setting):
self.ensure_one()
if recurrence_update_setting == 'all_events':
events = self.recurrence_id.calendar_event_ids
self.recurrence_id.unlink()
events.unlink()
elif recurrence_update_setting == 'future_events':
future_events = self.recurrence_id.calendar_event_ids.filtered(lambda ev: ev.start >= self.start)
future_events.unlink()
def action_mass_archive(self, recurrence_update_setting):
"""
The aim of this action purpose is to be called from sync calendar module when mass deletion is not possible.
"""
self.ensure_one()
if recurrence_update_setting == 'all_events':
self.recurrence_id.calendar_event_ids.write({'active': False})
elif recurrence_update_setting == 'future_events':
detached_events = self.recurrence_id._stop_at(self)
detached_events.write({'active': False})
# ------------------------------------------------------------
# MAILING
# ------------------------------------------------------------
def _get_attendee_emails(self):
""" Get comma-separated attendee email addresses. """
self.ensure_one()
return ",".join([e for e in self.attendee_ids.mapped("email") if e])
def _get_mail_tz(self):
self.ensure_one()
return self.event_tz or self.env.user.tz
def _sync_activities(self, fields):
# update activities
for event in self:
if event.activity_ids:
activity_values = {}
if 'name' in fields:
activity_values['summary'] = event.name
if 'description' in fields:
activity_values['note'] = event.description
if 'start' in fields:
# self.start is a datetime UTC *only when the event is not allday*
# activty.date_deadline is a date (No TZ, but should represent the day in which the user's TZ is)
# See 72254129dbaeae58d0a2055cba4e4a82cde495b7 for the same issue, but elsewhere
deadline = event.start
user_tz = self.env.context.get('tz')
if user_tz and not event.allday:
deadline = pytz.utc.localize(deadline)
deadline = deadline.astimezone(pytz.timezone(user_tz))
activity_values['date_deadline'] = deadline.date()
if 'user_id' in fields:
activity_values['user_id'] = event.user_id.id
if activity_values.keys():
event.activity_ids.write(activity_values)
# ------------------------------------------------------------
# ALARMS
# ------------------------------------------------------------
def _get_trigger_alarm_types(self):
return ['email']
def _setup_alarms(self):
""" Schedule cron triggers for future events """
cron = self.env.ref('calendar.ir_cron_scheduler_alarm').sudo()
alarm_types = self._get_trigger_alarm_types()
events_to_notify = self.env['calendar.event']
for event in self:
for alarm in (alarm for alarm in event.alarm_ids if alarm.alarm_type in alarm_types):
at = event.start - timedelta(minutes=alarm.duration_minutes)
if not cron.lastcall or at > cron.lastcall:
# Don't trigger for past alarms, they would be skipped by design
cron._trigger(at=at)
if any(alarm.alarm_type == 'notification' for alarm in event.alarm_ids):
# filter events before notifying attendees through calendar_alarm_manager
events_to_notify |= event.filtered(lambda ev: ev.alarm_ids and ev.stop >= fields.Datetime.now())
if events_to_notify:
self.env['calendar.alarm_manager']._notify_next_alarm(events_to_notify.partner_ids.ids)
# ------------------------------------------------------------
# RECURRENCY
# ------------------------------------------------------------
def _apply_recurrence_values(self, values, future=True):
"""Apply the new recurrence rules in `values`. Create a recurrence if it does not exist
and create all missing events according to the rrule.
If the changes are applied to future
events only, a new recurrence is created with the updated rrule.
:param values: new recurrence values to apply
:param future: rrule values are applied to future events only if True.
Rrule changes are applied to all events in the recurrence otherwise.
(ignored if no recurrence exists yet).
:return: events detached from the recurrence
"""
if not values:
return self.browse()
recurrence_vals = []
to_update = self.env['calendar.recurrence']
for event in self:
if not event.recurrence_id:
recurrence_vals += [dict(values, base_event_id=event.id, calendar_event_ids=[(4, event.id)])]
elif future:
to_update |= event.recurrence_id._split_from(event, values)
self.write({'recurrency': True, 'follow_recurrence': True})
to_update |= self.env['calendar.recurrence'].create(recurrence_vals)
return to_update._apply_recurrence()
def _get_recurrence_params(self):
if not self:
return {}
event_date = self._get_start_date()
weekday_field_name = weekday_to_field(event_date.weekday())
return {
weekday_field_name: True,
'weekday': weekday_field_name.upper(),
'byday': str(get_weekday_occurence(event_date)),
'day': event_date.day,
}
def _split_recurrence(self, time_values):
"""Apply time changes to events and update the recurrence accordingly.
:return: detached events
"""
self.ensure_one()
if not time_values:
return self.browse()
if self.follow_recurrence and self.recurrency:
previous_week_day_field = weekday_to_field(self._get_start_date().weekday())
else:
# When we try to change recurrence values of an event not following the recurrence, we get the parameters from
# the base_event
previous_week_day_field = weekday_to_field(self.recurrence_id.base_event_id._get_start_date().weekday())
self.write(time_values)
return self._apply_recurrence_values({
previous_week_day_field: False,
**self._get_recurrence_params(),
}, future=True)
def _break_recurrence(self, future=True):
"""Breaks the event's recurrence.
Stop the recurrence at the current event if `future` is True, leaving past events in the recurrence.
If `future` is False, all events in the recurrence are detached and the recurrence itself is unlinked.
:return: detached events excluding the current events
"""
recurrences_to_unlink = self.env['calendar.recurrence']
detached_events = self.env['calendar.event']
for event in self:
recurrence = event.recurrence_id
if future:
detached_events |= recurrence._stop_at(event)
else:
detached_events |= recurrence.calendar_event_ids
recurrence.calendar_event_ids.recurrence_id = False
recurrences_to_unlink |= recurrence
recurrences_to_unlink.with_context(archive_on_error=True).unlink()
return detached_events - self
def _rewrite_recurrence(self, values, time_values, recurrence_values):
""" Recreate the whole recurrence when all recurrent events must be moved
time_values corresponds to date times for one specific event. We need to update the base_event of the recurrence
and reapply the recurrence later. All exceptions are lost.
"""
self.ensure_one()
base_event = self.recurrence_id.base_event_id
if not base_event:
raise UserError(_("You can't update a recurrence without base event."))
[base_time_values] = self.recurrence_id.base_event_id.read(['start', 'stop', 'allday'])
update_dict = {}
start_update = fields.Datetime.to_datetime(time_values.get('start'))
stop_update = fields.Datetime.to_datetime(time_values.get('stop'))
# Convert the base_event_id hours according to new values: time shift
if start_update or stop_update:
if start_update:
start = base_time_values['start'] + (start_update - self.start)
stop = base_time_values['stop'] + (start_update - self.start)
start_date = base_time_values['start'].date() + (start_update.date() - self.start.date())
stop_date = base_time_values['stop'].date() + (start_update.date() - self.start.date())
update_dict.update({'start': start, 'start_date': start_date, 'stop': stop, 'stop_date': stop_date})
if stop_update:
if not start_update:
# Apply the same shift for start
start = base_time_values['start'] + (stop_update - self.stop)
start_date = base_time_values['start'].date() + (stop_update.date() - self.stop.date())
update_dict.update({'start': start, 'start_date': start_date})
stop = base_time_values['stop'] + (stop_update - self.stop)
stop_date = base_time_values['stop'].date() + (stop_update.date() - self.stop.date())
update_dict.update({'stop': stop, 'stop_date': stop_date})
time_values.update(update_dict)
if time_values or recurrence_values:
rec_fields = list(self._get_recurrent_fields())
[rec_vals] = base_event.read(rec_fields)
old_recurrence_values = {field: rec_vals.pop(field) for field in rec_fields if
field in rec_vals}
base_event.write({**values, **time_values})
# Delete all events except the base event and the currently modified
expandable_events = self.recurrence_id.calendar_event_ids - (self.recurrence_id.base_event_id + self)
self.recurrence_id.with_context(archive_on_error=True).unlink()
expandable_events.with_context(archive_on_error=True).unlink()
# Make sure to recreate a new recurrence. Needed to prevent sync issues
base_event.recurrence_id = False
# Recreate all events and the recurrence: override updated values
new_values = {
**old_recurrence_values,
**base_event._get_recurrence_params(),
**recurrence_values,
}
new_values.pop('rrule')
detached_events = base_event._apply_recurrence_values(new_values)
detached_events.write({'active': False})
# archive the current event if all the events were recreated
if self != self.recurrence_id.base_event_id and time_values:
self.active = False
else:
# Write on all events. Carefull, it could trigger a lot of noise to Google/Microsoft...
self.recurrence_id._write_events(values)
# ------------------------------------------------------------
# MANAGEMENT
# ------------------------------------------------------------
def change_attendee_status(self, status, recurrence_update_setting):
self.ensure_one()
if recurrence_update_setting == 'all_events':
events = self.recurrence_id.calendar_event_ids
elif recurrence_update_setting == 'future_events':
events = self.recurrence_id.calendar_event_ids.filtered(lambda ev: ev.start >= self.start)
else:
events = self
attendee = events.attendee_ids.filtered(lambda x: x.partner_id == self.env.user.partner_id)
if status == 'accepted':
return attendee.do_accept()
if status == 'declined':
return attendee.do_decline()
return attendee.do_tentative()
def find_partner_customer(self):
self.ensure_one()
return next(
(attendee.partner_id for attendee in self.attendee_ids.sorted('create_date')
if attendee.partner_id != self.user_id.partner_id),
self.env['calendar.attendee']
)
# ------------------------------------------------------------
# TOOLS
# ------------------------------------------------------------
def _find_attendee(self):
""" Return the first attendee where the user connected has been invited
or the attendee selected in the filter that is the owner
from all the meeting_ids in parameters.
"""
self.ensure_one()
my_attendee = self.attendee_ids.filtered(lambda att: att.partner_id == self.env.user.partner_id)
if my_attendee:
return my_attendee[:1]
event_checked_attendees = self.env['calendar.filters'].search([
('user_id', '=', self.env.user.id),
('partner_id', 'in', self.attendee_ids.partner_id.ids),
('partner_checked', '=', True)
]).mapped('partner_id')
if self.partner_id in event_checked_attendees and self.partner_id in self.attendee_ids.partner_id:
return self.attendee_ids.filtered(lambda attendee: attendee.partner_id == self.partner_id)[:1]
attendee = self.attendee_ids.filtered(lambda att: att.partner_id in event_checked_attendees and att.state != "needsAction")
return attendee[:1]
def _get_start_date(self):
"""Return the event starting date in the event's timezone.
If no starting time is assigned (yet), return today as default
:return: date
"""
if not self.start:
return fields.Date.today()
if self.recurrency and self.event_tz:
tz = pytz.timezone(self.event_tz)
# Ensure that all day events date are not calculated around midnight. TZ shift would potentially return bad date
start = self.start if not self.allday else self.start.replace(hour=12)
return pytz.utc.localize(start).astimezone(tz).date()
return self.start.date()
def _range(self):
self.ensure_one()
return (self.start, self.stop)
def get_display_time_tz(self, tz=False):
""" get the display_time of the meeting, forcing the timezone. This method is called from email template, to not use sudo(). """
self.ensure_one()
if tz:
self = self.with_context(tz=tz)
return self._get_display_time(self.start, self.stop, self.duration, self.allday)
def _get_ics_file(self):
""" Returns iCalendar file for the event invitation.
:returns a dict of .ics file content for each meeting
"""
result = {}
def ics_datetime(idate, allday=False):
if idate:
if allday:
return idate
return idate.replace(tzinfo=pytz.timezone('UTC'))
return False
if not vobject:
return result
for meeting in self:
cal = vobject.iCalendar()
event = cal.add('vevent')
if not meeting.start or not meeting.stop:
raise UserError(_("First you have to specify the date of the invitation."))
event.add('created').value = ics_datetime(fields.Datetime.now())
event.add('dtstart').value = ics_datetime(meeting.start, meeting.allday)
event.add('dtend').value = ics_datetime(meeting.stop, meeting.allday)
event.add('summary').value = meeting.name
if not is_html_empty(meeting.description):
if 'appointment_type_id' in meeting._fields and self.appointment_type_id:
# convert_online_event_desc_to_text method for correct data formatting in external calendars
event.add('description').value = self.convert_online_event_desc_to_text(meeting.description)
else:
event.add('description').value = html2plaintext(meeting.description)
if meeting.location:
event.add('location').value = meeting.location
if meeting.rrule:
event.add('rrule').value = meeting.rrule
if meeting.alarm_ids:
for alarm in meeting.alarm_ids:
valarm = event.add('valarm')
interval = alarm.interval
duration = alarm.duration
trigger = valarm.add('TRIGGER')
trigger.params['related'] = ["START"]
if interval == 'days':
delta = timedelta(days=duration)
elif interval == 'hours':
delta = timedelta(hours=duration)
elif interval == 'minutes':
delta = timedelta(minutes=duration)
trigger.value = delta
valarm.add('DESCRIPTION').value = alarm.name or u'Odoo'
for attendee in meeting.attendee_ids:
attendee_add = event.add('attendee')
attendee_add.value = u'MAILTO:' + (attendee.email or u'')
event.add('organizer').value = u'MAILTO:' + (meeting.user_id.email or u'')
result[meeting.id] = cal.serialize().encode('utf-8')
return result
def convert_online_event_desc_to_text(self, description):
"""
We can sync the calendar events with google calendar, iCal and Outlook, and we
also pass the event description along with other data. This description needs
to be in plaintext to be displayed properly in above platforms. Because online
events have fixed format for the description, this method removes some specific
html tags, and converts it into readable plaintext (to be used in external
calendars). Note that for regular (offline) events, we simply use the standard
`html2plaintext` method instead.
"""
desc_str = str(description)
tags_to_replace = ["<ul>", "</ul>", "<li>"]
for tag in tags_to_replace:
desc_str = desc_str.replace(tag, "")
desc_str = desc_str.replace("</li>", "<br/>")
return html2plaintext(desc_str)
@api.model
def _get_display_time(self, start, stop, zduration, zallday):
""" Return date and time (from to from) based on duration with timezone in string. Eg :
1) if user add duration for 2 hours, return : August-23-2013 at (04-30 To 06-30) (Europe/Brussels)
2) if event all day ,return : AllDay, July-31-2013
"""
timezone = self._context.get('tz') or self.env.user.partner_id.tz or 'UTC'
# get date/time format according to context
format_date, format_time = self._get_date_formats()
# convert date and time into user timezone
self_tz = self.with_context(tz=timezone)
date = fields.Datetime.context_timestamp(self_tz, fields.Datetime.from_string(start))
date_deadline = fields.Datetime.context_timestamp(self_tz, fields.Datetime.from_string(stop))
# convert into string the date and time, using user formats
to_text = pycompat.to_text
date_str = to_text(date.strftime(format_date))
time_str = to_text(date.strftime(format_time))
if zallday:
display_time = _("All Day, %(day)s", day=date_str)
elif zduration < 24:
duration = date + timedelta(minutes=round(zduration*60))
duration_time = to_text(duration.strftime(format_time))
display_time = _(
u"%(day)s at (%(start)s To %(end)s) (%(timezone)s)",
day=date_str,
start=time_str,
end=duration_time,
timezone=timezone,
)
else:
dd_date = to_text(date_deadline.strftime(format_date))
dd_time = to_text(date_deadline.strftime(format_time))
display_time = _(
u"%(date_start)s at %(time_start)s To\n %(date_end)s at %(time_end)s (%(timezone)s)",
date_start=date_str,
time_start=time_str,
date_end=dd_date,
time_end=dd_time,
timezone=timezone,
)
return display_time
def _get_duration(self, start, stop):
""" Get the duration value between the 2 given dates. """
if not start or not stop:
return 0
duration = (stop - start).total_seconds() / 3600
return round(duration, 2)
@api.model
def _get_date_formats(self):
""" get current date and time format, according to the context lang
:return: a tuple with (format date, format time)
"""
lang = get_lang(self.env)
return (lang.date_format, lang.time_format)
@api.model
def _get_recurrent_fields(self):
return {'byday', 'until', 'rrule_type', 'month_by', 'event_tz', 'rrule',
'interval', 'count', 'end_type', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat',
'sun', 'day', 'weekday'}
@api.model
def _get_time_fields(self):
return {'start', 'stop', 'start_date', 'stop_date'}
@api.model
def _get_custom_fields(self):
all_fields = self.fields_get(attributes=['manual'])
return {fname for fname in all_fields if all_fields[fname]['manual']}
@api.model
def _get_public_fields(self):
return self._get_recurrent_fields() | self._get_time_fields() | self._get_custom_fields() | {
'id', 'active', 'allday',
'duration', 'user_id', 'interval', 'partner_id',
'count', 'rrule', 'recurrence_id', 'show_as', 'privacy'}
| 48.947232 | 56,583 |
933 |
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 Contacts(models.Model):
_name = 'calendar.filters'
_description = 'Calendar Filters'
user_id = fields.Many2one('res.users', 'Me', required=True, default=lambda self: self.env.user)
partner_id = fields.Many2one('res.partner', 'Employee', required=True)
active = fields.Boolean('Active', default=True)
partner_checked = fields.Boolean('Checked', default=True,
help="This field is used to know if the partner is checked in the filter of the calendar view for the user_id.")
_sql_constraints = [
('user_id_partner_id_unique', 'UNIQUE(user_id, partner_id)', 'A user cannot have the same contact twice.')
]
@api.model
def unlink_from_partner_id(self, partner_id):
return self.search([('partner_id', '=', partner_id)]).unlink()
| 40.565217 | 933 |
2,087 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from odoo import api, fields, models, modules, _
from pytz import timezone, UTC
class Users(models.Model):
_inherit = 'res.users'
def _systray_get_calendar_event_domain(self):
tz = self.env.user.tz
start_dt = datetime.datetime.utcnow()
if tz:
start_date = timezone(tz).localize(start_dt).astimezone(UTC).date()
else:
start_date = datetime.date.today()
end_dt = datetime.datetime.combine(start_date, datetime.time.max)
if tz:
end_dt = timezone(tz).localize(end_dt).astimezone(UTC)
return ['&', '|',
'&',
'|',
['start', '>=', fields.Datetime.to_string(start_dt)],
['stop', '>=', fields.Datetime.to_string(start_dt)],
['start', '<=', fields.Datetime.to_string(end_dt)],
'&',
['allday', '=', True],
['start_date', '=', fields.Date.to_string(start_date)],
('attendee_ids.partner_id', '=', self.env.user.partner_id.id)]
@api.model
def systray_get_activities(self):
res = super(Users, self).systray_get_activities()
meetings_lines = self.env['calendar.event'].search_read(
self._systray_get_calendar_event_domain(),
['id', 'start', 'name', 'allday', 'attendee_status'],
order='start')
meetings_lines = [line for line in meetings_lines if line['attendee_status'] != 'declined']
if meetings_lines:
meeting_label = _("Today's Meetings")
meetings_systray = {
'type': 'meeting',
'name': meeting_label,
'model': 'calendar.event',
'icon': modules.module.get_module_icon(self.env['calendar.event']._original_module),
'meetings': meetings_lines,
}
res.insert(0, meetings_systray)
return res
| 37.945455 | 2,087 |
766 |
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 MailActivityMixin(models.AbstractModel):
_inherit = 'mail.activity.mixin'
activity_calendar_event_id = fields.Many2one(
'calendar.event', string="Next Activity Calendar Event",
compute='_compute_activity_calendar_event_id', groups="base.group_user")
@api.depends('activity_ids.calendar_event_id')
def _compute_activity_calendar_event_id(self):
"""This computes the calendar event of the next activity.
It evaluates to false if there is no such event."""
for record in self:
record.activity_calendar_event_id = record.activity_ids[:1].calendar_event_id
| 42.555556 | 766 |
4,324 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from odoo import api, fields, models
class Partner(models.Model):
_inherit = 'res.partner'
meeting_count = fields.Integer("# Meetings", compute='_compute_meeting_count')
meeting_ids = fields.Many2many('calendar.event', 'calendar_event_res_partner_rel', 'res_partner_id',
'calendar_event_id', string='Meetings', copy=False)
calendar_last_notif_ack = fields.Datetime(
'Last notification marked as read from base Calendar', default=fields.Datetime.now)
def _compute_meeting_count(self):
result = self._compute_meeting()
for p in self:
p.meeting_count = len(result.get(p.id, []))
def _compute_meeting(self):
if self.ids:
all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
event_id = self.env['calendar.event']._search([]) # ir.rules will be applied
subquery_string, subquery_params = event_id.select()
subquery = self.env.cr.mogrify(subquery_string, subquery_params).decode()
self.env.cr.execute("""
SELECT res_partner_id, calendar_event_id, count(1)
FROM calendar_event_res_partner_rel
WHERE res_partner_id IN %s AND calendar_event_id IN ({})
GROUP BY res_partner_id, calendar_event_id
""".format(subquery), [tuple(all_partners.ids)])
meeting_data = self.env.cr.fetchall()
# Create a dict {partner_id: event_ids} and fill with events linked to the partner
meetings = {p.id: set() for p in all_partners}
for m in meeting_data:
meetings[m[0]].add(m[1])
# Add the events linked to the children of the partner
all_partners.read(['parent_id'])
for p in all_partners:
partner = p
while partner:
if partner in self:
meetings[partner.id] |= meetings[p.id]
partner = partner.parent_id
return {p.id: list(meetings[p.id]) for p in self}
return {}
def get_attendee_detail(self, meeting_ids):
""" Return a list of dict of the given meetings with the attendees details
Used by:
- base_calendar.js : Many2ManyAttendee
- calendar_model.js (calendar.CalendarModel)
"""
attendees_details = []
meetings = self.env['calendar.event'].browse(meeting_ids)
meetings_attendees = meetings.mapped('attendee_ids')
for partner in self:
partner_info = partner.name_get()[0]
for attendee in meetings_attendees.filtered(lambda att: att.partner_id == partner):
attendee_is_organizer = self.env.user == attendee.event_id.user_id and attendee.partner_id == self.env.user.partner_id
attendees_details.append({
'id': partner_info[0],
'name': partner_info[1],
'status': attendee.state,
'event_id': attendee.event_id.id,
'attendee_id': attendee.id,
'is_alone': attendee.event_id.is_organizer_alone and attendee_is_organizer,
# attendees data is sorted according to this key in JS.
'is_organizer': 1 if attendee.partner_id == attendee.event_id.user_id.partner_id else 0,
})
return attendees_details
@api.model
def _set_calendar_last_notif_ack(self):
partner = self.env['res.users'].browse(self.env.context.get('uid', self.env.uid)).partner_id
partner.write({'calendar_last_notif_ack': datetime.now()})
def schedule_meeting(self):
self.ensure_one()
partner_ids = self.ids
partner_ids.append(self.env.user.partner_id.id)
action = self.env["ir.actions.actions"]._for_xml_id("calendar.action_calendar_event")
action['context'] = {
'default_partner_ids': partner_ids,
}
action['domain'] = ['|', ('id', 'in', self._compute_meeting()[self.id]), ('partner_ids', 'in', self.ids)]
return action
| 45.041667 | 4,324 |
3,037 |
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 Alarm(models.Model):
_name = 'calendar.alarm'
_description = 'Event Alarm'
_interval_selection = {'minutes': 'Minutes', 'hours': 'Hours', 'days': 'Days'}
name = fields.Char('Name', translate=True, required=True)
alarm_type = fields.Selection(
[('notification', 'Notification'), ('email', 'Email')],
string='Type', required=True, default='email')
duration = fields.Integer('Remind Before', required=True, default=1)
interval = fields.Selection(
list(_interval_selection.items()), 'Unit', required=True, default='hours')
duration_minutes = fields.Integer(
'Duration in minutes', store=True,
search='_search_duration_minutes', compute='_compute_duration_minutes',
help="Duration in minutes")
mail_template_id = fields.Many2one(
'mail.template', string="Email Template",
domain=[('model', 'in', ['calendar.attendee'])],
compute='_compute_mail_template_id', readonly=False, store=True,
help="Template used to render mail reminder content.")
body = fields.Text("Additional Message", help="Additional message that would be sent with the notification for the reminder")
@api.depends('interval', 'duration')
def _compute_duration_minutes(self):
for alarm in self:
if alarm.interval == "minutes":
alarm.duration_minutes = alarm.duration
elif alarm.interval == "hours":
alarm.duration_minutes = alarm.duration * 60
elif alarm.interval == "days":
alarm.duration_minutes = alarm.duration * 60 * 24
else:
alarm.duration_minutes = 0
@api.depends('alarm_type', 'mail_template_id')
def _compute_mail_template_id(self):
for alarm in self:
if alarm.alarm_type == 'email' and not alarm.mail_template_id:
alarm.mail_template_id = self.env['ir.model.data']._xmlid_to_res_id('calendar.calendar_template_meeting_reminder')
elif alarm.alarm_type != 'email' or not alarm.mail_template_id:
alarm.mail_template_id = False
def _search_duration_minutes(self, operator, value):
return [
'|', '|',
'&', ('interval', '=', 'minutes'), ('duration', operator, value),
'&', ('interval', '=', 'hours'), ('duration', operator, value / 60),
'&', ('interval', '=', 'days'), ('duration', operator, value / 60 / 24),
]
@api.onchange('duration', 'interval', 'alarm_type')
def _onchange_duration_interval(self):
display_interval = self._interval_selection.get(self.interval, '')
display_alarm_type = {
key: value for key, value in self._fields['alarm_type']._description_selection(self.env)
}[self.alarm_type]
self.name = "%s - %s %s" % (display_alarm_type, self.duration, display_interval)
| 46.723077 | 3,037 |
5,083 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.http as http
from odoo.http import request
from odoo.tools.misc import get_lang
class CalendarController(http.Controller):
# YTI Note: Keep id and kwargs only for retrocompatibility purpose
@http.route('/calendar/meeting/accept', type='http', auth="calendar")
def accept_meeting(self, token, id, **kwargs):
attendee = request.env['calendar.attendee'].sudo().search([
('access_token', '=', token),
('state', '!=', 'accepted')])
attendee.do_accept()
return self.view_meeting(token, id)
@http.route('/calendar/recurrence/accept', type='http', auth="calendar")
def accept_recurrence(self, token, id, **kwargs):
attendee = request.env['calendar.attendee'].sudo().search([
('access_token', '=', token),
('state', '!=', 'accepted')])
if attendee:
attendees = request.env['calendar.attendee'].sudo().search([
('event_id', 'in', attendee.event_id.recurrence_id.calendar_event_ids.ids),
('partner_id', '=', attendee.partner_id.id),
('state', '!=', 'accepted'),
])
attendees.do_accept()
return self.view_meeting(token, id)
@http.route('/calendar/meeting/decline', type='http', auth="calendar")
def decline_meeting(self, token, id, **kwargs):
attendee = request.env['calendar.attendee'].sudo().search([
('access_token', '=', token),
('state', '!=', 'declined')])
attendee.do_decline()
return self.view_meeting(token, id)
@http.route('/calendar/recurrence/decline', type='http', auth="calendar")
def decline_recurrence(self, token, id, **kwargs):
attendee = request.env['calendar.attendee'].sudo().search([
('access_token', '=', token),
('state', '!=', 'declined')])
if attendee:
attendees = request.env['calendar.attendee'].sudo().search([
('event_id', 'in', attendee.event_id.recurrence_id.calendar_event_ids.ids),
('partner_id', '=', attendee.partner_id.id),
('state', '!=', 'declined'),
])
attendees.do_decline()
return self.view_meeting(token, id)
@http.route('/calendar/meeting/view', type='http', auth="calendar")
def view_meeting(self, token, id, **kwargs):
attendee = request.env['calendar.attendee'].sudo().search([
('access_token', '=', token),
('event_id', '=', int(id))])
if not attendee:
return request.not_found()
timezone = attendee.partner_id.tz
lang = attendee.partner_id.lang or get_lang(request.env).code
event = request.env['calendar.event'].with_context(tz=timezone, lang=lang).sudo().browse(int(id))
company = event.user_id and event.user_id.company_id or event.create_uid.company_id
# If user is internal and logged, redirect to form view of event
# otherwise, display the simplifyed web page with event informations
if request.session.uid and request.env['res.users'].browse(request.session.uid).user_has_groups('base.group_user'):
return request.redirect('/web?db=%s#id=%s&view_type=form&model=calendar.event' % (request.env.cr.dbname, id))
# NOTE : we don't use request.render() since:
# - we need a template rendering which is not lazy, to render before cursor closing
# - we need to display the template in the language of the user (not possible with
# request.render())
response_content = request.env['ir.ui.view'].with_context(lang=lang)._render_template(
'calendar.invitation_page_anonymous', {
'company': company,
'event': event,
'attendee': attendee,
})
return request.make_response(response_content, headers=[('Content-Type', 'text/html')])
@http.route('/calendar/meeting/join', type='http', auth="user", website=True)
def calendar_join_meeting(self, token, **kwargs):
event = request.env['calendar.event'].sudo().search([
('access_token', '=', token)])
if not event:
return request.not_found()
event.action_join_meeting(request.env.user.partner_id.id)
attendee = request.env['calendar.attendee'].sudo().search([('partner_id', '=', request.env.user.partner_id.id), ('event_id', '=', event.id)])
return request.redirect('/calendar/meeting/view?token=%s&id=%s' % (attendee.access_token, event.id))
# Function used, in RPC to check every 5 minutes, if notification to do for an event or not
@http.route('/calendar/notify', type='json', auth="user")
def notify(self):
return request.env['calendar.alarm_manager'].get_next_notif()
@http.route('/calendar/notify_ack', type='json', auth="user")
def notify_ack(self):
return request.env['res.partner'].sudo()._set_calendar_last_notif_ack()
| 49.349515 | 5,083 |
502 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "IAP / Mail",
'summary': """Bridge between IAP and mail""",
'description': """Bridge between IAP and mail""",
'category': 'Hidden/Tools',
'version': '1.0',
'depends': [
'iap',
'mail',
],
'application': False,
'installable': True,
'auto_install': True,
'data': [
'data/mail_templates.xml',
],
'license': 'LGPL-3',
}
| 22.818182 | 502 |
640 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Purchase Requisition Stock',
'version': '1.2',
'category': 'Inventory/Purchase',
'sequence': 70,
'summary': '',
'description': "",
'depends': ['purchase_requisition', 'purchase_stock'],
'demo': [
'data/purchase_requisition_stock_demo.xml'
],
'data': [
'security/ir.model.access.csv',
'data/purchase_requisition_stock_data.xml',
'views/purchase_requisition_views.xml',
],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 27.826087 | 640 |
11,108 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields
from datetime import datetime
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.addons.purchase_requisition.tests.common import TestPurchaseRequisitionCommon
class TestPurchaseRequisitionStock(TestPurchaseRequisitionCommon):
def test_01_purchase_requisition_stock(self):
date_planned = fields.Datetime.now()
warehouse = self.env['stock.warehouse'].browse(self.ref('stock.warehouse0'))
self.env['procurement.group'].run([self.env['procurement.group'].Procurement(
self.product_13,
14,
self.env['uom.uom'].browse(self.ref('uom.product_uom_unit')),
warehouse.lot_stock_id,
'/',
'/',
self.env.company,
{
'warehouse_id': warehouse,
'date_planned': date_planned,
}
)])
# Check requisition details which created after run procurement.
line = self.env['purchase.requisition.line'].search([('product_id', '=', self.product_13.id), ('product_qty', '=', 14.0)])
requisition = line[0].requisition_id
self.assertEqual(requisition.date_end, date_planned, "End date does not correspond.")
self.assertEqual(len(requisition.line_ids), 1, "Requisition Lines should be one.")
self.assertEqual(line.product_uom_id.id, self.ref('uom.product_uom_unit'), "UOM is not correspond.")
# Give access rights of Purchase Requisition User to open requisition
# Set tender state to choose tendering line.
self.requisition1.with_user(self.user_purchase_requisition_user).action_in_progress()
self.requisition1.with_user(self.user_purchase_requisition_user).action_open()
# Vendor send one RFQ so I create a RfQ of that agreement.
PurchaseOrder = self.env['purchase.order']
purchase_order = PurchaseOrder.new({'partner_id': self.res_partner_1, 'requisition_id': self.requisition1.id})
purchase_order._onchange_requisition_id()
po_dict = purchase_order._convert_to_write({name: purchase_order[name] for name in purchase_order._cache})
self.po_requisition = PurchaseOrder.create(po_dict)
self.assertEqual(len(self.po_requisition.order_line), 1, 'Purchase order should have one line')
def test_02_purchase_requisition_stock(self):
"""Plays with the sequence of regular supplier infos and one created by blanket orders."""
# Product creation
unit = self.ref("uom.product_uom_unit")
warehouse1 = self.env.ref('stock.warehouse0')
route_buy = self.ref('purchase_stock.route_warehouse0_buy')
route_mto = warehouse1.mto_pull_id.route_id.id
vendor1 = self.env['res.partner'].create({'name': 'AAA', 'email': '[email protected]'})
vendor2 = self.env['res.partner'].create({'name': 'BBB', 'email': '[email protected]'})
supplier_info1 = self.env['product.supplierinfo'].create({
'name': vendor1.id,
'price': 50,
})
product_test = self.env['product.product'].create({
'name': 'Usb Keyboard',
'type': 'product',
'uom_id': unit,
'uom_po_id': unit,
'seller_ids': [(6, 0, [supplier_info1.id])],
'route_ids': [(6, 0, [route_buy, route_mto])]
})
# Stock picking
stock_location = self.env.ref('stock.stock_location_stock')
customer_location = self.env.ref('stock.stock_location_customers')
move1 = self.env['stock.move'].create({
'name': '10 in',
'procure_method': 'make_to_order',
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
'product_id': product_test.id,
'product_uom': unit,
'product_uom_qty': 10.0,
'price_unit': 10,
})
move1._action_confirm()
# Verification : there should be a purchase order created with the good price
purchase1 = self.env['purchase.order'].search([('partner_id', '=', vendor1.id)])
self.assertEqual(purchase1.order_line.price_unit, 50, 'The price on the purchase order is not the supplierinfo one')
# Blanket order creation
line1 = (0, 0, {'product_id': product_test.id, 'product_qty': 18, 'product_uom_id': product_test.uom_po_id.id, 'price_unit': 50})
requisition_type = self.env['purchase.requisition.type'].create({
'name': 'Blanket test',
'quantity_copy': 'none',
})
requisition_blanket = self.env['purchase.requisition'].create({
'line_ids': [line1],
'type_id': requisition_type.id,
'vendor_id': vendor2.id,
'currency_id': self.env.user.company_id.currency_id.id,
})
requisition_blanket.action_in_progress()
# Second stock move
move2 = self.env['stock.move'].create({
'name': '10 in',
'procure_method': 'make_to_order',
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
'product_id': product_test.id,
'product_uom': unit,
'product_uom_qty': 10.0,
'price_unit': 10
})
move2._action_confirm()
# As the supplier.info linked to the blanket order has the same price, the first one is stille used.
self.assertEqual(purchase1.order_line.product_qty, 20)
# Update the sequence of the blanket order's supplier info.
supplier_info1.sequence = 2
requisition_blanket.line_ids.supplier_info_ids.sequence = 1
# In [13]: [(x.sequence, x.min_qty, x.price, x.name.name) for x in supplier_info1 + requisition_blanket.line_ids.supplier_info_ids]
# Out[13]: [(2, 0.0, 50.0, 'AAA'), (1, 0.0, 50.0, 'BBB')]
# Second stock move
move3 = self.env['stock.move'].create({
'name': '10 in',
'procure_method': 'make_to_order',
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
'product_id': product_test.id,
'product_uom': unit,
'product_uom_qty': 10.0,
'price_unit': 10
})
move3._action_confirm()
# Verifications
purchase2 = self.env['purchase.order'].search([('partner_id', '=', vendor2.id), ('requisition_id', '=', requisition_blanket.id)])
self.assertEqual(len(purchase2), 1)
self.assertEqual(purchase2.order_line.price_unit, 50, 'The price on the purchase order is not the blanquet order one')
def test_03_purchase_requisition_stock(self):
""" Two blanket orders on different 'make to order' products must generate
two different purchase orders
"""
# Product creation
unit = self.ref("uom.product_uom_unit")
warehouse1 = self.env.ref('stock.warehouse0')
route_buy = self.ref('purchase_stock.route_warehouse0_buy')
route_mto = warehouse1.mto_pull_id.route_id.id
vendor1 = self.env['res.partner'].create({'name': 'AAA', 'email': '[email protected]'})
supplier_info1 = self.env['product.supplierinfo'].create({
'name': vendor1.id,
'price': 50,
})
product_1 = self.env['product.product'].create({
'name': 'product1',
'type': 'product',
'uom_id': unit,
'uom_po_id': unit,
'seller_ids': [(6, 0, [supplier_info1.id])],
'route_ids': [(6, 0, [route_buy, route_mto])]
})
product_2 = self.env['product.product'].create({
'name': 'product2',
'type': 'product',
'uom_id': unit,
'uom_po_id': unit,
'seller_ids': [(6, 0, [supplier_info1.id])],
'route_ids': [(6, 0, [route_buy, route_mto])]
})
# Blanket orders creation
requisition_type = self.env['purchase.requisition.type'].create({
'name': 'Blanket test',
'quantity_copy': 'none',
})
line1 = (0, 0, {'product_id': product_1.id, 'product_qty': 18, 'product_uom_id': product_1.uom_po_id.id, 'price_unit': 41})
line2 = (0, 0, {'product_id': product_2.id, 'product_qty': 18, 'product_uom_id': product_2.uom_po_id.id, 'price_unit': 42})
requisition_1 = self.env['purchase.requisition'].create({
'line_ids': [line1],
'type_id': requisition_type.id,
'vendor_id': vendor1.id,
'currency_id': self.env.user.company_id.currency_id.id,
})
requisition_2 = self.env['purchase.requisition'].create({
'line_ids': [line2],
'type_id': requisition_type.id,
'vendor_id': vendor1.id,
'currency_id': self.env.user.company_id.currency_id.id,
})
requisition_1.action_in_progress()
requisition_2.action_in_progress()
# Stock moves
stock_location = self.env.ref('stock.stock_location_stock')
customer_location = self.env.ref('stock.stock_location_customers')
move1 = self.env['stock.move'].create({
'name': '10 in',
'procure_method': 'make_to_order',
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
'product_id': product_1.id,
'product_uom': unit,
'product_uom_qty': 10.0,
'price_unit': 100,
})
move2 = self.env['stock.move'].create({
'name': '10 in',
'procure_method': 'make_to_order',
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
'product_id': product_2.id,
'product_uom': unit,
'product_uom_qty': 10.0,
'price_unit': 100,
})
move1._action_confirm()
move2._action_confirm()
# Verifications
POL1 = self.env['purchase.order.line'].search([('product_id', '=', product_1.id)]).order_id
POL2 = self.env['purchase.order.line'].search([('product_id', '=', product_2.id)]).order_id
self.assertFalse(POL1 == POL2, 'The two blanket orders should generate two purchase different purchase orders')
POL1.write({'order_line': [
(0, 0, {
'name': product_2.name,
'product_id': product_2.id,
'product_qty': 5.0,
'product_uom': product_2.uom_po_id.id,
'price_unit': 0,
'date_planned': datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),
})
]})
order_line = self.env['purchase.order.line'].search([
('product_id', '=', product_2.id),
('product_qty', '=', 5.0),
])
order_line._onchange_quantity()
self.assertEqual(order_line.price_unit, 50, 'The supplier info chosen should be the one without requisition id')
| 46.476987 | 11,108 |
453 |
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
@api.onchange('requisition_id')
def _onchange_requisition_id(self):
super(PurchaseOrder, self)._onchange_requisition_id()
if self.requisition_id:
self.picking_type_id = self.requisition_id.picking_type_id.id
| 32.357143 | 453 |
3,295 |
py
|
PYTHON
|
15.0
|
# -*- encoding: 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 StockRule(models.Model):
_inherit = 'stock.rule'
@api.model
def _run_buy(self, procurements):
requisitions_values_by_company = defaultdict(list)
other_procurements = []
for procurement, rule in procurements:
if procurement.product_id.purchase_requisition == 'tenders':
values = self.env['purchase.requisition']._prepare_tender_values(*procurement)
values['picking_type_id'] = rule.picking_type_id.id
requisitions_values_by_company[procurement.company_id.id].append(values)
else:
other_procurements.append((procurement, rule))
for company_id, requisitions_values in requisitions_values_by_company.items():
self.env['purchase.requisition'].sudo().with_company(company_id).create(requisitions_values)
return super(StockRule, self)._run_buy(other_procurements)
def _prepare_purchase_order(self, company_id, origins, values):
res = super(StockRule, self)._prepare_purchase_order(company_id, origins, values)
values = values[0]
res['partner_ref'] = values['supplier'].purchase_requisition_id.name
res['requisition_id'] = values['supplier'].purchase_requisition_id.id
if values['supplier'].purchase_requisition_id.currency_id:
res['currency_id'] = values['supplier'].purchase_requisition_id.currency_id.id
return res
def _make_po_get_domain(self, company_id, values, partner):
domain = super(StockRule, self)._make_po_get_domain(company_id, values, partner)
if 'supplier' in values and values['supplier'].purchase_requisition_id:
domain += (
('requisition_id', '=', values['supplier'].purchase_requisition_id.id),
)
return domain
class StockMove(models.Model):
_inherit = 'stock.move'
requisition_line_ids = fields.One2many('purchase.requisition.line', 'move_dest_id')
def _get_upstream_documents_and_responsibles(self, visited):
# People without purchase rights should be able to do this operation
requisition_lines_sudo = self.sudo().requisition_line_ids
if requisition_lines_sudo:
return [(requisition_line.requisition_id, requisition_line.requisition_id.user_id, visited) for requisition_line in requisition_lines_sudo if requisition_line.requisition_id.state not in ('done', 'cancel')]
else:
return super(StockMove, self)._get_upstream_documents_and_responsibles(visited)
class Orderpoint(models.Model):
_inherit = "stock.warehouse.orderpoint"
def _quantity_in_progress(self):
res = super(Orderpoint, self)._quantity_in_progress()
for op in self:
for pr in self.env['purchase.requisition'].search([('state', '=', 'draft'), ('origin', '=', op.name)]):
for prline in pr.line_ids.filtered(lambda l: l.product_id.id == op.product_id.id and not l.move_dest_id):
res[op.id] += prline.product_uom_id._compute_quantity(prline.product_qty, op.product_uom, round=False)
return res
| 48.455882 | 3,295 |
2,466 |
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class PurchaseRequisition(models.Model):
_inherit = 'purchase.requisition'
def _get_picking_in(self):
pick_in = self.env.ref('stock.picking_type_in', raise_if_not_found=False)
company = self.env.company
if not pick_in or not pick_in.sudo().active or pick_in.sudo().warehouse_id.company_id.id != company.id:
pick_in = self.env['stock.picking.type'].search(
[('warehouse_id.company_id', '=', company.id), ('code', '=', 'incoming')],
limit=1,
)
return pick_in
warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse', domain="[('company_id', '=', company_id)]")
picking_type_id = fields.Many2one('stock.picking.type', 'Operation Type', required=True, default=_get_picking_in, domain="['|',('warehouse_id', '=', False), ('warehouse_id.company_id', '=', company_id)]")
procurement_group_id = fields.Many2one('procurement.group', 'Procurement Group')
def _prepare_tender_values(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values):
return {
'origin': origin,
'date_end': values['date_planned'],
'user_id': False,
'warehouse_id': values.get('warehouse_id') and values['warehouse_id'].id or False,
'procurement_group_id': values.get('group_id') and values['group_id'].id or False,
'company_id': company_id.id,
'line_ids': [(0, 0, {
'product_id': product_id.id,
'product_uom_id': product_uom.id,
'product_qty': product_qty,
'product_description_variants': values.get('product_description_variants'),
'move_dest_id': values.get('move_dest_ids') and values['move_dest_ids'][0].id or False
})],
}
class PurchaseRequisitionLine(models.Model):
_inherit = "purchase.requisition.line"
move_dest_id = fields.Many2one('stock.move', 'Downstream Move')
def _prepare_purchase_order_line(self, name, product_qty=0.0, price_unit=0.0, taxes_ids=False):
res = super(PurchaseRequisitionLine, self)._prepare_purchase_order_line(name, product_qty, price_unit, taxes_ids)
res['move_dest_ids'] = self.move_dest_id and [(4, self.move_dest_id.id)] or []
return res
| 49.32 | 2,466 |
505 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Manufacturing Expiry',
'version': '1.0',
'category': 'Manufacturing/Manufacturing',
'summary': 'Manufacturing Expiry',
'description': """
Technical module.
""",
'depends': ['mrp', 'product_expiry'],
'data': [
'wizard/confirm_expiry_view.xml',
],
'installable': True,
'auto_install': True,
'application': False,
'license': 'LGPL-3',
}
| 25.25 | 505 |
4,596 |
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.stock.tests.common import TestStockCommon
from odoo.tests.common import Form
from odoo.exceptions import UserError
class TestStockProductionLot(TestStockCommon):
@classmethod
def setUpClass(cls):
super(TestStockProductionLot, cls).setUpClass()
# Creates a tracked product using expiration dates.
cls.product_apple = cls.ProductObj.create({
'name': 'Apple',
'type': 'product',
'tracking': 'lot',
'use_expiration_date': True,
'expiration_time': 10,
'use_time': 5,
'removal_time': 8,
'alert_time': 4,
})
# Creates an apple lot.
lot_form = Form(cls.LotObj)
lot_form.name = 'good-apple-lot'
lot_form.product_id = cls.product_apple
lot_form.company_id = cls.env.company
cls.lot_good_apple = lot_form.save()
# Creates an expired apple lot.
lot_form = Form(cls.LotObj)
lot_form.name = 'expired-apple-lot-01'
lot_form.product_id = cls.product_apple
lot_form.company_id = cls.env.company
cls.lot_expired_apple = lot_form.save()
lot_form = Form(cls.lot_expired_apple) # Edits the lot to make it expired.
lot_form.expiration_date = datetime.today() - timedelta(days=10)
cls.lot_expired_apple = lot_form.save()
# Creates a producible product and its BOM.
cls.product_apple_pie = cls.ProductObj.create({
'name': 'Apple Pie',
'type': 'product',
})
cls.bom_apple_pie = cls.env['mrp.bom'].create({
'product_id': cls.product_apple_pie.id,
'product_tmpl_id': cls.product_apple_pie.product_tmpl_id.id,
'product_uom_id': cls.uom_unit.id,
'product_qty': 1.0,
'consumption': 'flexible',
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_apple.id, 'product_qty': 3}),
]})
cls.location_stock = cls.env['stock.location'].browse(cls.stock_location)
# Creation of a routing
cls.workcenter = cls.env['mrp.workcenter'].create({
'name': 'Bakery',
'capacity': 2,
'time_start': 10,
'time_stop': 5,
'time_efficiency': 80,
})
def test_01_product_produce(self):
""" Checks user doesn't get a confirmation wizard when they produces with
no expired components. """
# Creates a Manufacturing Order...
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product_apple_pie
mo_form.bom_id = self.bom_apple_pie
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
# ... and tries to product with a non-expired lot as component.
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 3
ml.lot_id = self.lot_good_apple
details_operation_form.save()
res = mo.button_mark_done()
# Producing must not return a wizard in this case.
self.assertEqual(res, True)
def test_02_product_produce_using_expired(self):
""" Checks user gets a confirmation wizard when they produces with
expired components. """
# Creates a Manufacturing Order...
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product_apple_pie
mo_form.bom_id = self.bom_apple_pie
mo_form.product_qty = 1
mo = mo_form.save()
mo.action_confirm()
# ... and tries to product with an expired lot as component.
mo_form = Form(mo)
mo_form.qty_producing = 1
mo = mo_form.save()
details_operation_form = Form(mo.move_raw_ids[0], view=self.env.ref('stock.view_stock_move_operations'))
with details_operation_form.move_line_ids.new() as ml:
ml.qty_done = 3
ml.lot_id = self.lot_expired_apple
details_operation_form.save()
res = mo.button_mark_done()
# Producing must return a confirmation wizard.
self.assertNotEqual(res, None)
self.assertEqual(res['res_model'], 'expiry.picking.confirmation')
| 39.965217 | 4,596 |
1,830 |
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 ConfirmExpiry(models.TransientModel):
_inherit = 'expiry.picking.confirmation'
production_ids = fields.Many2many('mrp.production', readonly=True)
workorder_id = fields.Many2one('mrp.workorder', readonly=True)
@api.depends('lot_ids')
def _compute_descriptive_fields(self):
if self.production_ids or self.workorder_id:
# Shows expired lots only if we are more than one expired lot.
self.show_lots = len(self.lot_ids) > 1
if self.show_lots:
# For multiple expired lots, they are listed in the wizard view.
self.description = _(
"You are going to use some expired components."
"\nDo you confirm you want to proceed ?"
)
else:
# For one expired lot, its name is written in the wizard message.
self.description = _(
"You are going to use the component %(product_name)s, %(lot_name)s which is expired."
"\nDo you confirm you want to proceed ?",
product_name=self.lot_ids.product_id.display_name,
lot_name=self.lot_ids.name,
)
else:
super(ConfirmExpiry, self)._compute_descriptive_fields()
def confirm_produce(self):
ctx = dict(self._context, skip_expired=True)
ctx.pop('default_lot_ids')
return self.production_ids.with_context(ctx).button_mark_done()
def confirm_workorder(self):
ctx = dict(self._context, skip_expired=True)
ctx.pop('default_lot_ids')
return self.workorder_id.with_context(ctx).record_production()
| 41.590909 | 1,830 |
1,408 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
class MrpWorkorder(models.Model):
_inherit = 'mrp.production'
def _pre_button_mark_done(self):
confirm_expired_lots = self._check_expired_lots()
if confirm_expired_lots:
return confirm_expired_lots
return super()._pre_button_mark_done()
def _check_expired_lots(self):
# We use the 'skip_expired' context key to avoid to make the check when
# user already confirmed the wizard about using expired lots.
if self.env.context.get('skip_expired'):
return False
expired_lot_ids = self.move_raw_ids.move_line_ids.filtered(lambda ml: ml.lot_id.product_expiry_alert).lot_id.ids
if expired_lot_ids:
return {
'name': _('Confirmation'),
'type': 'ir.actions.act_window',
'res_model': 'expiry.picking.confirmation',
'view_mode': 'form',
'target': 'new',
'context': self._get_expired_context(expired_lot_ids),
}
def _get_expired_context(self, expired_lot_ids):
context = dict(self.env.context)
context.update({
'default_lot_ids': [(6, 0, expired_lot_ids)],
'default_production_ids': self.ids,
})
return context
| 37.052632 | 1,408 |
1,203 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name": "Philippines - Accounting",
"summary": """
This is the module to manage the accounting chart for The Philippines.
""",
"category": "Accounting/Localizations/Account Charts",
"version": "1.0",
"author": "Odoo PS",
"website": "https://www.odoo.com",
"depends": [
"account",
"base_vat",
"l10n_multilang",
],
"data": [
"data/account_chart_template_data.xml",
"data/account.account.template.csv",
"data/account_chart_template_post_data.xml",
"data/account_tax_group.xml",
"data/account_tax_template.xml",
"data/account_fiscal_position_template.xml",
"data/account_fiscal_position_tax_template.xml",
"data/account_chart_template_configure_data.xml",
"wizard/generate_2307_wizard_views.xml",
"views/account_move_views.xml",
"views/account_payment_views.xml",
"views/account_tax_views.xml",
"views/res_partner_views.xml",
"security/ir.model.access.csv",
],
"license": "LGPL-3",
"icon": "/base/static/img/country_flags/ph.png",
}
| 34.371429 | 1,203 |
3,826 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import io
import re
import xlwt
from odoo import fields, models
from odoo.tools.misc import format_date
COLUMN_HEADER_MAP = {
"Reporting_Month": "invoice_date",
"Vendor_TIN": "vat",
"branchCode": "branch_code",
"companyName": "company_name",
"surName": "last_name",
"firstName": "first_name",
"middleName": "middle_name",
"address": "address",
"nature": "product_name",
"ATC": "atc",
"income_payment": "price_subtotal",
"ewt_rate": "amount",
"tax_amount": "tax_amount",
}
class Generate2307Wizard(models.TransientModel):
_name = "l10n_ph_2307.wizard"
_description = "Exports 2307 data to a XLS file."
moves_to_export = fields.Many2many("account.move", string="Joural To Include")
generate_xls_file = fields.Binary(
"Generated file",
help="Technical field used to temporarily hold the generated XLS file before its downloaded."
)
def _write_single_row(self, worksheet, worksheet_row, values):
for index, field in enumerate(COLUMN_HEADER_MAP.values()):
worksheet.write(worksheet_row, index, label=values[field])
def _write_rows(self, worksheet, moves):
worksheet_row = 0
for move in moves:
worksheet_row += 1
partner = move.partner_id
partner_address_info = [partner.street, partner.street2, partner.city, partner.state_id.name, partner.country_id.name]
values = {
'invoice_date': format_date(self.env, move.invoice_date, date_format="MM/dd/yyyy"),
'vat': re.sub(r'\-', '', partner.vat)[:9] if partner.vat else '',
'branch_code': partner.branch_code or '000',
'company_name': partner.commercial_partner_id.name,
'first_name': partner.first_name or '',
'middle_name': partner.middle_name or '',
'last_name': partner.last_name or '',
'address': ', '.join([val for val in partner_address_info if val])
}
for invoice_line in move.invoice_line_ids.filtered(lambda l: not l.display_type):
for tax in invoice_line.tax_ids.filtered(lambda x: x.l10n_ph_atc):
values['product_name'] = re.sub(r'[\(\)]', '', invoice_line.product_id.name)
values['atc'] = tax.l10n_ph_atc
values['price_subtotal'] = invoice_line.price_subtotal
values['amount'] = tax.amount
values['tax_amount'] = tax._compute_amount(invoice_line.price_subtotal, invoice_line.price_unit)
self._write_single_row(worksheet, worksheet_row, values)
worksheet_row += 1
def action_generate(self):
""" Generate a xls format file for importing to
https://bir-excel-uploader.com/excel-file-to-bir-dat-format/#bir-form-2307-settings.
This website will then generate a BIR 2307 format excel file for uploading to the
PH government.
"""
self.ensure_one()
file_data = io.BytesIO()
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Form2307')
for index, col_header in enumerate(COLUMN_HEADER_MAP.keys()):
worksheet.write(0, index, label=col_header)
self._write_rows(worksheet, self.moves_to_export)
workbook.save(file_data)
file_data.seek(0)
self.generate_xls_file = base64.b64encode(file_data.read())
return {
"type": "ir.actions.act_url",
"target": "self",
"url": "/web/content?model=l10n_ph_2307.wizard&download=true&field=generate_xls_file&filename=Form_2307.xls&id={}".format(self.id),
}
| 41.139785 | 3,826 |
221 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class AccountTax(models.Model):
_inherit = "account.tax"
l10n_ph_atc = fields.Char("Philippines ATC")
| 24.555556 | 221 |
717 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
def action_open_l10n_ph_2307_wizard(self):
vendor_bills = self.filtered_domain([('move_type', '=', 'in_invoice')])
if vendor_bills:
wizard_action = self.env["ir.actions.act_window"]._for_xml_id("l10n_ph.view_l10n_ph_2307_wizard_act_window")
wizard_action.update({
'context': {'default_moves_to_export': vendor_bills.ids}
})
return wizard_action
else:
raise UserError(_('Only Vendor Bills are available.'))
| 37.736842 | 717 |
703 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, models
from odoo.exceptions import UserError
class AccountPayment(models.Model):
_inherit = "account.payment"
def action_open_l10n_ph_2307_wizard(self):
self.ensure_one()
if self.payment_type == 'outbound':
wizard_action = self.env["ir.actions.act_window"]._for_xml_id("l10n_ph.view_l10n_ph_2307_wizard_act_window")
wizard_action.update({
'context': {'default_moves_to_export': self.reconciled_bill_ids.ids}
})
return wizard_action
else:
raise UserError(_('Only Outbound Payment is available.'))
| 37 | 703 |
437 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class AccountTaxTemplate(models.Model):
_inherit = "account.tax.template"
l10n_ph_atc = fields.Char("Philippines ATC")
def _get_tax_vals(self, company, tax_template_to_tax):
val = super()._get_tax_vals(company, tax_template_to_tax)
val.update({"l10n_ph_atc": self.l10n_ph_atc})
return val
| 31.214286 | 437 |
930 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, api, models
class ResPartner(models.Model):
_inherit = "res.partner"
branch_code = fields.Char("Branch Code", default='000', compute='_compute_branch_code', store=True)
first_name = fields.Char("First Name")
middle_name = fields.Char("Middle Name")
last_name = fields.Char("Last Name")
@api.model
def _commercial_fields(self):
return super()._commercial_fields() + ['branch_code']
@api.depends('vat', 'country_id')
def _compute_branch_code(self):
for partner in self:
branch_code = '000'
if partner.country_id.code == 'PH' and partner.vat:
match = partner.__check_vat_ph_re.match(partner.vat)
branch_code = match and match.group(1) and match.group(1)[1:] or branch_code
partner.branch_code = branch_code
| 37.2 | 930 |
1,064 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Product Availability',
'category': 'Website/Website',
'summary': 'Manage product inventory & availability',
'description': """
Manage the inventory of your products and display their availability status in your eCommerce store.
In case of stockout, you can decide to block further sales or to keep selling.
A default behavior can be selected in the Website settings.
Then it can be made specific at the product level.
""",
'depends': [
'website_sale',
'sale_stock',
],
'data': [
'views/product_template_views.xml',
'views/res_config_settings_views.xml',
'views/website_sale_stock_templates.xml',
'views/stock_picking_views.xml'
],
'demo': [
'data/website_sale_stock_demo.xml',
],
'auto_install': True,
'assets': {
'web.assets_frontend': [
'website_sale_stock/static/src/js/**/*',
],
},
'license': 'LGPL-3',
}
| 31.294118 | 1,064 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.