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
|
|---|---|---|---|---|---|---|
8,688
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.fields import Command
from odoo.exceptions import ValidationError
from odoo.tests import tagged
from odoo.addons.project.tests.test_project_base import TestProjectCommon
from datetime import date
@tagged('-at_install', 'post_install')
class TestTaskDependencies(TestProjectCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.project_pigs.write({
'allow_task_dependencies': True,
})
cls.task_3 = cls.env['project.task'].with_context({'mail_create_nolog': True}).create({
'name': 'Pigs UserTask 2',
'user_ids': cls.user_projectuser,
'project_id': cls.project_pigs.id,
})
def flush_tracking(self):
""" Force the creation of tracking values. """
self.env['base'].flush()
self.cr.precommit.run()
def test_task_dependencies(self):
""" Test the task dependencies feature
Test Case:
=========
1) Add task2 as dependency in task1
2) Checks if the task1 has the task in depend_on_ids field.
"""
self.assertEqual(len(self.task_1.depend_on_ids), 0, "The task 1 should not have any dependency.")
self.task_1.write({
'depend_on_ids': [Command.link(self.task_2.id)],
})
self.assertEqual(len(self.task_1.depend_on_ids), 1, "The task 1 should have a dependency.")
self.task_1.write({
'depend_on_ids': [Command.link(self.task_3.id)],
})
self.assertEqual(len(self.task_1.depend_on_ids), 2, "The task 1 should have two dependencies.")
def test_cyclic_dependencies(self):
""" Test the cyclic dependencies
Test Case:
=========
1) Check initial setting on three tasks
2) Add task2 as dependency in task1
3) Add task3 as dependency in task2
4) Add task1 as dependency in task3 and check a validation error is raised
5) Add task1 as dependency in task2 and check a validation error is raised
"""
# 1) Check initial setting on three tasks
self.assertTrue(
len(self.task_1.depend_on_ids) == len(self.task_2.depend_on_ids) == len(self.task_3.depend_on_ids) == 0,
"The three tasks should depend on no tasks.")
self.assertTrue(self.task_1.allow_task_dependencies, 'The task dependencies feature should be enable.')
self.assertTrue(self.task_2.allow_task_dependencies, 'The task dependencies feature should be enable.')
self.assertTrue(self.task_3.allow_task_dependencies, 'The task dependencies feature should be enable.')
# 2) Add task2 as dependency in task1
self.task_1.write({
'depend_on_ids': [Command.link(self.task_2.id)],
})
self.assertEqual(len(self.task_1.depend_on_ids), 1, 'The task 1 should have one dependency.')
# 3) Add task3 as dependency in task2
self.task_2.write({
'depend_on_ids': [Command.link(self.task_3.id)],
})
self.assertEqual(len(self.task_2.depend_on_ids), 1, "The task 2 should have one dependency.")
# 4) Add task1 as dependency in task3 and check a validation error is raised
with self.assertRaises(ValidationError), self.cr.savepoint():
self.task_3.write({
'depend_on_ids': [Command.link(self.task_1.id)],
})
self.assertEqual(len(self.task_3.depend_on_ids), 0, "The dependency should not be added in the task 3 because of a cyclic dependency.")
# 5) Add task1 as dependency in task2 and check a validation error is raised
with self.assertRaises(ValidationError), self.cr.savepoint():
self.task_2.write({
'depend_on_ids': [Command.link(self.task_1.id)],
})
self.assertEqual(len(self.task_2.depend_on_ids), 1, "The number of dependencies should no change in the task 2 because of a cyclic dependency.")
def test_tracking_dependencies(self):
# Enable the company setting
self.env['res.config.settings'].create({
'group_project_task_dependencies': True
}).execute()
# `depend_on_ids` is tracked
self.task_1.with_context(mail_notrack=True).write({
'depend_on_ids': [Command.link(self.task_2.id)]
})
self.cr.precommit.clear()
# Check that changing a dependency tracked field in task_2 logs a message in task_1.
self.task_2.write({'date_deadline': date(1983, 3, 1)}) # + 1 message in task_1 and task_2
self.flush_tracking()
self.assertEqual(len(self.task_1.message_ids), 1,
'Changing the deadline on task 2 should have logged a message in task 1.')
# Check that changing a dependency tracked field in task_1 does not log a message in task_2.
self.task_1.date_deadline = date(2020, 1, 2) # + 1 message in task_1
self.flush_tracking()
self.assertEqual(len(self.task_2.message_ids), 1,
'Changing the deadline on task 1 should not have logged a message in task 2.')
# Check that changing a field that is not tracked at all on task 2 does not impact task 1.
self.task_2.color = 100 # no new message
self.flush_tracking()
self.assertEqual(len(self.task_1.message_ids), 2,
'Changing the color on task 2 should not have logged a message in task 1 since it is not tracked.')
# Check that changing multiple fields does not log more than one message.
self.task_2.write({
'date_deadline': date(2020, 1, 1),
'kanban_state': 'blocked',
}) # + 1 message in task_1 and task_2
self.flush_tracking()
self.assertEqual(len(self.task_1.message_ids), 3,
'Changing multiple fields on task 2 should only log one message in task 1.')
def test_task_dependencies_settings_change(self):
def set_task_dependencies_setting(enabled):
features_config = self.env["res.config.settings"].create({'group_project_task_dependencies': enabled})
features_config.execute()
self.project_pigs.write({
'allow_task_dependencies': False,
})
# As the the Project General Setting group_project_task_dependencies needs to be toggled in order
# to be applied on the existing projects we need to force it so that it does not depends on anything
# (like demo data for instance)
set_task_dependencies_setting(False)
set_task_dependencies_setting(True)
self.assertTrue(self.project_pigs.allow_task_dependencies, "Projects allow_task_dependencies should follow group_project_task_dependencies setting changes")
self.project_chickens = self.env['project.project'].create({
'name': 'My Chicken Project'
})
self.assertTrue(self.project_chickens.allow_task_dependencies, "New Projects allow_task_dependencies should default to group_project_task_dependencies")
set_task_dependencies_setting(False)
self.assertFalse(self.project_pigs.allow_task_dependencies, "Projects allow_task_dependencies should follow group_project_task_dependencies setting changes")
self.project_ducks = self.env['project.project'].create({
'name': 'My Ducks Project'
})
self.assertFalse(self.project_ducks.allow_task_dependencies, "New Projects allow_task_dependencies should default to group_project_task_dependencies")
def test_duplicate_project_with_task_dependencies(self):
self.project_pigs.allow_task_dependencies = True
self.task_1.depend_on_ids = self.task_2
pigs_copy = self.project_pigs.copy()
task1_copy = pigs_copy.task_ids.filtered(lambda t: t.name == 'Pigs UserTask')
task2_copy = pigs_copy.task_ids.filtered(lambda t: t.name == 'Pigs ManagerTask')
self.assertEqual(len(task1_copy), 1, "Should only contain 1 copy of UserTask")
self.assertEqual(len(task2_copy), 1, "Should only contain 1 copy of ManagerTask")
self.assertEqual(task1_copy.depend_on_ids.ids, [task2_copy.id],
"Copy should only create a relation between both copy if they are both part of the project")
task1_copy.depend_on_ids = self.task_1
pigs_copy_copy = pigs_copy.copy()
task1_copy_copy = pigs_copy_copy.task_ids.filtered(lambda t: t.name == 'Pigs UserTask')
self.assertEqual(task1_copy_copy.depend_on_ids.ids, [self.task_1.id],
"Copy should not alter the relation if the other task is in a different project")
| 47.217391
| 8,688
|
13,923
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import Command
from odoo.addons.project.tests.test_project_base import TestProjectCommon
from odoo.tests import tagged
from odoo.tests.common import Form
@tagged('-at_install', 'post_install')
class TestProjectSubtasks(TestProjectCommon):
def test_task_display_project_with_default_form(self):
"""
Create a task in the default task form should take the project set in the form or the default project in the context
"""
with Form(self.env['project.task'].with_context({'tracking_disable': True})) as task_form:
task_form.name = 'Test Task 1'
task_form.project_id = self.project_pigs
task = task_form.save()
self.assertEqual(task.project_id, self.project_pigs, "The project should be assigned.")
self.assertEqual(task.display_project_id, task.project_id, "The display project of a first layer task should be assigned to project_id.")
with Form(self.env['project.task'].with_context({'tracking_disable': True, 'default_project_id': self.project_pigs.id})) as task_form:
task_form.name = 'Test Task 2'
task = task_form.save()
self.assertEqual(task.project_id, self.project_pigs, "The project should be assigned from the default project.")
self.assertEqual(task.display_project_id, task.project_id, "The display project of a first layer task should be assigned to project_id.")
def test_task_display_project_with_task_form2(self):
"""
Create a task in the task form 2 should take the project set in the form or the default project in the context
"""
with Form(self.env['project.task'].with_context({'tracking_disable': True}), view="project.view_task_form2") as task_form:
task_form.name = 'Test Task 1'
task_form.project_id = self.project_pigs
task = task_form.save()
self.assertEqual(task.project_id, self.project_pigs, "The project should be assigned.")
self.assertEqual(task.display_project_id, task.project_id, "The display project of a first layer task should be assigned to project_id.")
with Form(self.env['project.task'].with_context({'tracking_disable': True, 'default_project_id': self.project_pigs.id}), view="project.view_task_form2") as task_form:
task_form.name = 'Test Task 2'
task = task_form.save()
self.assertEqual(task.project_id, self.project_pigs, "The project should be assigned from the default project.")
self.assertEqual(task.display_project_id, task.project_id, "The display project of a first layer task should be assigned to project_id.")
def test_task_display_project_with_quick_create_task_form(self):
"""
Create a task in the quick create form should take the default project in the context
"""
with Form(self.env['project.task'].with_context({'tracking_disable': True, 'default_project_id': self.project_pigs.id}), view="project.quick_create_task_form") as task_form:
task_form.name = 'Test Task 2'
task = task_form.save()
self.assertEqual(task.project_id, self.project_pigs, "The project should be assigned from the default project.")
self.assertEqual(task.display_project_id, task.project_id, "The display project of a first layer task should be assigned to project_id.")
def test_task_display_project_with_any_task_form(self):
"""
Create a task in any form should take the default project in the context
"""
form_views = self.env['ir.ui.view'].search([('model', '=', 'project.task'), ('type', '=', 'form')])
for form_view in form_views:
with Form(self.env['project.task'].with_context({'tracking_disable': True, 'default_project_id': self.project_pigs.id}), view=form_view) as task_form:
task_form.name = 'Test Task 1'
task = task_form.save()
self.assertEqual(task.project_id, self.project_pigs, "The project should be assigned from the default project, form_view name : %s." % form_view.name)
self.assertEqual(task.display_project_id, task.project_id, "The display project of a first layer task should be assigned to project_id, form_view name : %s." % form_view.name)
def test_subtask_display_project(self):
"""
1) Create a subtask
- Should have the same project as its parent
- Shouldn't have a display project set.
2) Set display project on subtask
- Should not change parent project
- Should change the subtask project
- Display project should be correct
3) Reset the display project to False
- Should make the project equal to parent project
- Display project should be correct
4) Change parent task project
- Should make the subtask project follow parent project
- Display project should stay false
5) Set display project on subtask and change parent task project
- Should make the subtask project follow new display project id
- Display project should be correct
6) Remove parent task:
- The project id should remain unchanged
- The display project id should follow the project id
7) Remove display project id then parent id:
- The project id should be the one from the parent :
- Since the display project id was removed, the project id is updated to the parent one
- The display project id should follow the project id
"""
# 1)
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask 1'
self.assertEqual(self.task_1.child_ids.project_id, self.project_pigs, "The project should be assigned from the default project.")
self.assertFalse(self.task_1.child_ids.display_project_id, "The display project of a sub task should be false to project_id.")
# 2)
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.edit(0) as subtask_form:
subtask_form.display_project_id = self.project_goats
self.assertEqual(self.task_1.project_id, self.project_pigs, "Changing the project of a subtask should not change parent project")
self.assertEqual(self.task_1.child_ids.display_project_id, self.project_goats, "Display Project of the task should be well assigned")
self.assertEqual(self.task_1.child_ids.project_id, self.project_goats, "Changing display project id on a subtask should change project id")
# 3)
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.edit(0) as subtask_form:
subtask_form.display_project_id = self.env['project.project']
self.assertFalse(self.task_1.child_ids.display_project_id, "Display Project of the task should be well assigned, to False")
self.assertEqual(self.task_1.child_ids.project_id, self.project_pigs, "Resetting display project to False on a subtask should change project id to parent project id")
# 4)
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
task_form.project_id = self.project_goats
self.assertEqual(self.task_1.project_id, self.project_goats, "Parent project should change.")
self.assertFalse(self.task_1.child_ids.display_project_id, "Display Project of the task should be False")
self.assertEqual(self.task_1.child_ids.project_id, self.project_goats, "Resetting display project to False on a subtask should follow project of its parent")
# 5)
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.edit(0) as subtask_form:
subtask_form.display_project_id = self.project_goats
task_form.project_id = self.project_pigs
self.assertEqual(self.task_1.project_id, self.project_pigs, "Parent project should change back.")
self.assertEqual(self.task_1.child_ids.display_project_id, self.project_goats, "Display Project of the task should be well assigned")
self.assertEqual(self.task_1.child_ids.project_id, self.project_goats, "Changing display project id on a subtask should change project id")
# 6)
with Form(self.task_1.child_ids.with_context({'tracking_disable': True})) as subtask_form:
subtask_form.parent_id = self.env['project.task']
orphan_subtask = subtask_form.save()
self.assertEqual(orphan_subtask.display_project_id, self.project_goats, "Display Project of the task should be well assigned")
self.assertEqual(orphan_subtask.project_id, self.project_goats, "Changing display project id on a subtask should change project id")
self.assertFalse(orphan_subtask.parent_id, "Parent should be false")
# 7)
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask 1'
subtask_form.display_project_id = self.project_goats
with Form(self.task_1.child_ids.with_context({'tracking_disable': True})) as subtask_form:
subtask_form.display_project_id = self.env['project.project']
subtask_form.parent_id = self.env['project.task']
orphan_subtask = subtask_form.save()
self.assertEqual(orphan_subtask.project_id, self.project_pigs, "Removing parent should not change project")
self.assertEqual(orphan_subtask.display_project_id, self.project_pigs, "Removing parent should make the display project set as project.")
def test_subtask_stage(self):
"""
The stage of the new child must be the default one of the project
"""
stage_a = self.env['project.task.type'].create({'name': 'a', 'sequence': 1})
stage_b = self.env['project.task.type'].create({'name': 'b', 'sequence': 10})
self.project_pigs.type_ids |= stage_a
self.project_pigs.type_ids |= stage_b
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask 1'
self.assertEqual(self.task_1.child_ids.stage_id, stage_a, "The stage of the child task should be the default one of the project.")
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
task_form.stage_id = stage_b
self.assertEqual(self.task_1.child_ids.stage_id, stage_a, "The stage of the child task should remain the same while changing parent task stage.")
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
task_form.child_ids.remove(0)
with task_form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask 2'
self.assertEqual(self.task_1.child_ids.stage_id, stage_a, "The stage of the child task should be the default one of the project even if parent stage id is different.")
with Form(self.task_1.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.edit(0) as subtask_form:
subtask_form.display_project_id = self.project_goats
self.assertEqual(self.task_1.child_ids.stage_id.name, "New", "The stage of the child task should be the default one of the display project id, once set.")
def test_copy_project_with_subtasks(self):
""" Test that when copying a project, the subtasks are copied correctly. """
self.env['project.task'].with_context({'mail_create_nolog': True}).create({
'name': 'Parent Task',
'project_id': self.project_goats.id,
'child_ids': [
Command.create({'name': 'child 1'}),
Command.create({'name': 'child 2', 'display_project_id': self.project_goats.id}),
Command.create({'name': 'child 3 with subtask', 'child_ids': [Command.create({'name': 'child 4'})]}),
Command.create({'name': 'child archived', 'active': False}),
],
})
task_count_with_subtasks_including_archived_in_project_goats = self.project_goats.with_context(
active_test=False).task_count_with_subtasks
self.project_goats._compute_task_count() # recompute without archived tasks and subtasks
task_count_in_project_goats = self.project_goats.task_count
project_goats_duplicated = self.project_goats.copy()
self.project_pigs._compute_task_count() # retrigger since a new task should be added in the project after the duplication of Project Goats
subtask_with_display_project_id = project_goats_duplicated.tasks.filtered(lambda t: t.name == 'child 2')
self.assertEqual(subtask_with_display_project_id.display_project_id, project_goats_duplicated, "The display project id of the subtask should be the duplicated project.")
self.assertEqual(
project_goats_duplicated.with_context(active_test=False).task_count_with_subtasks,
task_count_with_subtasks_including_archived_in_project_goats,
'The number of duplicated tasks (subtasks included) should be equal to the number of all task of both projects')
self.assertEqual(self.project_goats.task_count, task_count_in_project_goats,
'The number of tasks should be the same before and after the duplication of this project.')
| 59.755365
| 13,923
|
16,397
|
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.osv import expression
from odoo.exceptions import AccessError
from odoo.tests import tagged
from odoo.tests.common import Form
from .test_project_base import TestProjectCommon
class TestProjectSharingCommon(TestProjectCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
project_sharing_stages_vals_list = [
(0, 0, {'name': 'To Do', 'sequence': 1}),
(0, 0, {'name': 'Done', 'sequence': 10, 'fold': True, 'rating_template_id': cls.env.ref('project.rating_project_request_email_template').id}),
]
cls.partner_portal = cls.env['res.partner'].create({
'name': 'Chell Gladys',
'email': 'chell@gladys.portal',
'company_id': False,
'user_ids': [Command.link(cls.user_portal.id)]})
cls.project_cows = cls.env['project.project'].with_context({'mail_create_nolog': True}).create({
'name': 'Cows',
'privacy_visibility': 'portal',
'alias_name': 'project+cows',
'type_ids': project_sharing_stages_vals_list,
})
cls.project_portal = cls.env['project.project'].with_context({'mail_create_nolog': True}).create({
'name': 'Portal',
'privacy_visibility': 'portal',
'alias_name': 'project+portal',
'partner_id': cls.user_portal.partner_id.id,
'type_ids': project_sharing_stages_vals_list,
})
cls.task_cow = cls.env['project.task'].with_context({'mail_create_nolog': True}).create({
'name': 'Cow UserTask',
'user_ids': cls.user_projectuser,
'project_id': cls.project_cows.id,
})
cls.task_portal = cls.env['project.task'].with_context({'mail_create_nolog': True}).create({
'name': 'Portal UserTask',
'user_ids': cls.user_projectuser,
'project_id': cls.project_portal.id,
})
cls.project_sharing_form_view_xml_id = 'project.project_sharing_project_task_view_form'
def get_project_sharing_form_view(self, record, with_user=None):
return Form(
record.with_user(with_user or self.env.user),
view=self.project_sharing_form_view_xml_id
)
@tagged('project_sharing')
class TestProjectSharing(TestProjectSharingCommon):
def test_project_share_wizard(self):
""" Test Project Share Wizard
Test Cases:
==========
1) Create the wizard record
2) Check if no access rights are given to a portal user
3) Add access rights to a portal user
"""
project_share_wizard = self.env['project.share.wizard'].create({
'res_model': 'project.project',
'res_id': self.project_portal.id,
'access_mode': 'edit',
})
self.assertFalse(project_share_wizard.partner_ids, 'No collaborator should be in the wizard.')
self.assertFalse(self.project_portal.with_user(self.user_portal)._check_project_sharing_access(), 'The portal user should not have accessed in project sharing views.')
project_share_wizard.write({'partner_ids': [Command.link(self.user_portal.partner_id.id)]})
project_share_wizard.action_send_mail()
self.assertEqual(len(self.project_portal.collaborator_ids), 1, 'The access right added in project share wizard should be added in the project when the user confirm the access in the wizard.')
self.assertDictEqual({
'partner_id': self.project_portal.collaborator_ids.partner_id,
'project_id': self.project_portal.collaborator_ids.project_id,
}, {
'partner_id': self.user_portal.partner_id,
'project_id': self.project_portal,
}, 'The access rights added should be the read access for the portal project for Chell Gladys.')
self.assertTrue(self.project_portal.with_user(self.user_portal)._check_project_sharing_access(), 'The portal user should have read access to the portal project with project sharing feature.')
def test_project_sharing_access(self):
""" Check if the different user types can access to project sharing feature as expected. """
with self.assertRaises(AccessError, msg='The public user should not have any access to project sharing feature of the portal project.'):
self.project_portal.with_user(self.user_public)._check_project_sharing_access()
self.assertTrue(self.project_portal.with_user(self.user_projectuser)._check_project_sharing_access(), 'The internal user should have all accesses to project sharing feature of the portal project.')
self.assertFalse(self.project_portal.with_user(self.user_portal)._check_project_sharing_access(), 'The portal user should not have any access to project sharing feature of the portal project.')
self.project_portal.write({'collaborator_ids': [Command.create({'partner_id': self.user_portal.partner_id.id})]})
self.assertTrue(self.project_portal.with_user(self.user_portal)._check_project_sharing_access(), 'The portal user can access to project sharing feature of the portal project.')
def test_create_task_in_project_sharing(self):
""" Test when portal user creates a task in project sharing views.
Test Cases:
==========
1) Give the 'read' access mode to a portal user in a project and try to create task with this user.
2) Give the 'comment' access mode to a portal user in a project and try to create task with this user.
3) Give the 'edit' access mode to a portal user in a project and try to create task with this user.
3.1) Try to change the project of the new task with this user.
"""
# 1) Give the 'read' access mode to a portal user in a project and try to create task with this user.
with self.assertRaises(AccessError, msg="Should not accept the portal user create a task in the project when he has not the edit access right."):
with self.get_project_sharing_form_view(self.env['project.task'].with_context({'tracking_disable': True, 'default_project_id': self.project_portal.id}), self.user_portal) as form:
form.name = 'Test'
task = form.save()
self.project_portal.write({
'collaborator_ids': [
Command.create({'partner_id': self.user_portal.partner_id.id}),
],
})
with self.get_project_sharing_form_view(self.env['project.task'].with_context({'tracking_disable': True, 'default_project_id': self.project_portal.id}), self.user_portal) as form:
form.name = 'Test'
task = form.save()
self.assertEqual(task.name, 'Test')
self.assertEqual(task.project_id, self.project_portal)
self.assertFalse(task.portal_user_names)
# 3.1) Try to change the project of the new task with this user.
with self.assertRaises(AssertionError, msg="Should not accept the portal user changes the project of the task."):
form.project_id = self.project_cows
task = form.save()
def test_edit_task_in_project_sharing(self):
""" Test when portal user creates a task in project sharing views.
Test Cases:
==========
1) Give the 'read' access mode to a portal user in a project and try to edit task with this user.
2) Give the 'comment' access mode to a portal user in a project and try to edit task with this user.
3) Give the 'edit' access mode to a portal user in a project and try to create task with this user.
3.1) Try to change the project of the new task with this user.
3.2) Create a sub-task
3.3) Create a second sub-task
"""
# 1) Give the 'read' access mode to a portal user in a project and try to create task with this user.
with self.assertRaises(AccessError, msg="Should not accept the portal user create a task in the project when he has not the edit access right."):
with self.get_project_sharing_form_view(self.task_cow.with_context({'tracking_disable': True, 'default_project_id': self.project_cows.id}), self.user_portal) as form:
form.name = 'Test'
task = form.save()
project_share_wizard = self.env['project.share.wizard'].create({
'access_mode': 'edit',
'res_model': 'project.project',
'res_id': self.project_cows.id,
'partner_ids': [
Command.link(self.user_portal.partner_id.id),
],
})
project_share_wizard.action_send_mail()
with self.get_project_sharing_form_view(self.task_cow.with_context({'tracking_disable': True, 'default_project_id': self.project_cows.id, 'uid': self.user_portal.id}), self.user_portal) as form:
form.name = 'Test'
task = form.save()
self.assertEqual(task.name, 'Test')
self.assertEqual(task.project_id, self.project_cows)
# 3.1) Try to change the project of the new task with this user.
with self.assertRaises(AssertionError, msg="Should not accept the portal user changes the project of the task."):
with self.get_project_sharing_form_view(task, self.user_portal) as form:
form.project_id = self.project_portal
# 3.2) Create a sub-task
with self.get_project_sharing_form_view(task, self.user_portal) as form:
with form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask'
with self.assertRaises(AssertionError, msg="Should not accept the portal user changes the project of the task."):
subtask_form.display_project_id = self.project_portal
self.assertEqual(task.child_ids.name, 'Test Subtask')
self.assertEqual(task.child_ids.project_id, self.project_cows)
self.assertFalse(task.child_ids.portal_user_names, 'by default no user should be assigned to a subtask created by the portal user.')
self.assertFalse(task.child_ids.user_ids, 'No user should be assigned to the new subtask.')
task2 = self.env['project.task'] \
.with_context({
'tracking_disable': True,
'default_project_id': self.project_cows.id,
'default_user_ids': [Command.set(self.user_portal.ids)],
}) \
.with_user(self.user_portal) \
.create({'name': 'Test'})
self.assertFalse(task2.portal_user_names, 'the portal user should not be assigned when the portal user creates a task into the project shared.')
# 3.3) Create a second sub-task
with self.get_project_sharing_form_view(task, self.user_portal) as form:
with form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask'
self.assertEqual(len(task.child_ids), 2, 'Check 2 subtasks has correctly been created by the user portal.')
def test_portal_user_cannot_see_all_assignees(self):
""" Test when the portal sees a task he cannot see all the assignees.
Because of a ir.rule in res.partner filters the assignees, the portal
can only see the assignees in the same company than him.
Test Cases:
==========
1) add many assignees in a task
2) check the portal user can read no assignee in this task. Should have an AccessError exception
"""
self.task_cow.write({'user_ids': [Command.link(self.user_projectmanager.id)]})
with self.assertRaises(AccessError, msg="Should not accept the portal user to access to a task he does not follow it and its project."):
self.task_cow.with_user(self.user_portal).read(['portal_user_names'])
self.assertEqual(len(self.task_cow.user_ids), 2, '2 users should be assigned in this task.')
project_share_wizard = self.env['project.share.wizard'].create({
'access_mode': 'edit',
'res_model': 'project.project',
'res_id': self.project_cows.id,
'partner_ids': [
Command.link(self.user_portal.partner_id.id),
],
})
project_share_wizard.action_send_mail()
self.assertFalse(self.task_cow.with_user(self.user_portal).user_ids, 'the portal user should see no assigness in the task.')
task_portal_read = self.task_cow.with_user(self.user_portal).read(['portal_user_names'])
self.assertEqual(self.task_cow.portal_user_names, task_portal_read[0]['portal_user_names'], 'the portal user should see assignees name in the task via the `portal_user_names` field.')
def test_portal_user_can_change_stage_with_rating(self):
""" Test portal user can change the stage of task to a stage with rating template email
The user should be able to change the stage and the email should be sent as expected
if a email template is set in `rating_template_id` field in the new stage.
"""
self.project_portal.write({
'rating_active': True,
'rating_status': 'stage',
'collaborator_ids': [
Command.create({'partner_id': self.user_portal.partner_id.id}),
],
})
self.task_portal.with_user(self.user_portal).write({'stage_id': self.project_portal.type_ids[-1].id})
def test_orm_method_with_true_false_domain(self):
""" Test orm method overriden in project for project sharing works with TRUE_LEAF/FALSE_LEAF
Test Case
=========
1) Share a project in edit mode for portal user
2) Search the portal task contained in the project shared by using a domain with TRUE_LEAF
3) Check the task is found with the `search` method
4) filter the task with `TRUE_DOMAIN` and check if the task is always returned by `filtered_domain` method
5) filter the task with `FALSE_DOMAIN` and check if no task is returned by `filtered_domain` method
6) Search the task with `FALSE_LEAF` and check no task is found with `search` method
7) Call `read_group` method with `TRUE_LEAF` in the domain and check if the task is found
8) Call `read_group` method with `FALSE_LEAF` in the domain and check if no task is found
"""
domain = [('id', '=', self.task_portal.id)]
self.project_portal.write({
'collaborator_ids': [Command.create({
'partner_id': self.user_portal.partner_id.id,
})],
})
task = self.env['project.task'].with_user(self.user_portal).search(
expression.AND([
expression.TRUE_DOMAIN,
domain,
])
)
self.assertTrue(task, 'The task should be found.')
self.assertEqual(task, task.filtered_domain(expression.TRUE_DOMAIN), 'The task found should be kept since the domain is truly')
self.assertFalse(task.filtered_domain(expression.FALSE_DOMAIN), 'The task should not be found since the domain is falsy')
task = self.env['project.task'].with_user(self.user_portal).search(
expression.AND([
expression.FALSE_DOMAIN,
domain,
]),
)
self.assertFalse(task, 'No task should be found since the domain contained a falsy tuple.')
task_read_group = self.env['project.task'].read_group(
expression.AND([expression.TRUE_DOMAIN, domain]),
['id'],
[],
)
self.assertEqual(task_read_group[0]['__count'], 1, 'The task should be found with the read_group method containing a truly tuple.')
self.assertEqual(task_read_group[0]['id'], self.task_portal.id, 'The task should be found with the read_group method containing a truly tuple.')
task_read_group = self.env['project.task'].read_group(
expression.AND([expression.FALSE_DOMAIN, domain]),
['id'],
[],
)
self.assertFalse(task_read_group[0]['__count'], 'No result should found with the read_group since the domain is falsy.')
| 55.39527
| 16,397
|
5,951
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import tagged, HttpCase
from .test_project_base import TestProjectCommon
@tagged('-at_install', 'post_install', 'personal_stages')
class TestPersonalStages(TestProjectCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user_stages = cls.env['project.task.type'].search([('user_id', '=', cls.user_projectuser.id)])
cls.manager_stages = cls.env['project.task.type'].search([('user_id', '=', cls.user_projectmanager.id)])
def test_personal_stage_base(self):
# Project User is assigned to task_1 he should be able to see a personal stage
self.task_1.with_user(self.user_projectuser)._compute_personal_stage_id()
self.assertTrue(self.task_1.with_user(self.user_projectuser).personal_stage_type_id,
'Project User is assigned to task 1, he should have a personal stage assigned.')
self.task_1.with_user(self.user_projectmanager)._compute_personal_stage_id()
self.assertFalse(self.env['project.task'].browse(self.task_1.id).with_user(self.user_projectmanager).personal_stage_type_id,
'Project Manager is not assigned to task 1, he should not have a personal stage assigned.')
# Now assign a second user to our task_1
self.task_1.user_ids += self.user_projectmanager
self.assertTrue(self.task_1.with_user(self.user_projectmanager).personal_stage_type_id,
'Project Manager has now been assigned to task 1 and should have a personal stage assigned.')
self.task_1.with_user(self.user_projectmanager)._compute_personal_stage_id()
task_1_manager_stage = self.task_1.with_user(self.user_projectmanager).personal_stage_type_id
self.task_1.with_user(self.user_projectuser)._compute_personal_stage_id()
self.task_1.with_user(self.user_projectuser).personal_stage_type_id = self.user_stages[1]
self.assertEqual(self.task_1.with_user(self.user_projectuser).personal_stage_type_id, self.user_stages[1],
'Assigning another personal stage to the task should have changed it for user 1.')
self.task_1.with_user(self.user_projectmanager)._compute_personal_stage_id()
self.assertEqual(self.task_1.with_user(self.user_projectmanager).personal_stage_type_id, task_1_manager_stage,
'Modifying the personal stage of Project User should not have affected the personal stage of Project Manager.')
self.task_2.with_user(self.user_projectmanager).personal_stage_type_id = self.manager_stages[1]
self.assertEqual(self.task_1.with_user(self.user_projectmanager).personal_stage_type_id, task_1_manager_stage,
'Modifying the personal stage on task 2 for Project Manager should not have affected the stage on task 1.')
def test_personal_stage_search(self):
self.task_2.user_ids += self.user_projectuser
# Make sure both personal stages are different
self.task_1.with_user(self.user_projectuser).personal_stage_type_id = self.user_stages[0]
self.task_2.with_user(self.user_projectuser).personal_stage_type_id = self.user_stages[1]
tasks = self.env['project.task'].with_user(self.user_projectuser).search([('personal_stage_type_id', '=', self.user_stages[0].id)])
self.assertTrue(tasks, 'The search result should not be empty.')
for task in tasks:
self.assertEqual(task.personal_stage_type_id, self.user_stages[0],
'The search should only have returned task that are in the inbox personal stage.')
def test_personal_stage_read_group(self):
self.task_1.user_ids += self.user_projectmanager
self.task_1.with_user(self.user_projectmanager).personal_stage_type_id = self.manager_stages[1]
#Makes sure the personal stage for project manager is saved in the database
self.env['project.task'].flush()
read_group_user = self.env['project.task'].with_user(self.user_projectuser).read_group(
[('user_ids', '=', self.user_projectuser.id)], fields=['sequence:avg'], groupby=['personal_stage_type_ids'])
# Check that the result is at least a bit coherent
self.assertEqual(len(self.user_stages), len(read_group_user),
'read_group should return %d groups' % len(self.user_stages))
# User has only one task assigned the sum of all counts should be 1
total = 0
for group in read_group_user:
total += group['personal_stage_type_ids_count']
self.assertEqual(1, total,
'read_group should not have returned more tasks than the user is assigned to.')
read_group_manager = self.env['project.task'].with_user(self.user_projectmanager).read_group(
[('user_ids', '=', self.user_projectmanager.id)], fields=['sequence:avg'], groupby=['personal_stage_type_ids'])
self.assertEqual(len(self.manager_stages), len(read_group_manager),
'read_group should return %d groups' % len(self.user_stages))
total = 0
total_stage_0 = 0
total_stage_1 = 0
for group in read_group_manager:
total += group['personal_stage_type_ids_count']
# Check that we have a task in both stages
if group['personal_stage_type_ids'][0] == self.manager_stages[0].id:
total_stage_0 += 1
elif group['personal_stage_type_ids'][0] == self.manager_stages[1].id:
total_stage_1 += 1
self.assertEqual(2, total,
'read_group should not have returned more tasks than the user is assigned to.')
self.assertEqual(1, total_stage_0)
self.assertEqual(1, total_stage_1)
@tagged('-at_install', 'post_install')
class TestPersonalStageTour(HttpCase, TestProjectCommon):
def test_personal_stage_tour(self):
# Test customizing personal stages as a project user
self.start_tour('/web', 'personal_stage_tour', login="armandel")
| 60.72449
| 5,951
|
2,644
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import Command
from odoo.tests import HttpCase, tagged
@tagged('post_install', '-at_install')
class TestProjectSharingUi(HttpCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
user = cls.env['res.users'].with_context({'no_reset_password': True, 'mail_create_nolog': True}).create({
'name': 'Georges',
'login': 'georges1',
'password': 'georges1',
'email': 'georges@project.portal',
'signature': 'SignGeorges',
'notification_type': 'email',
'groups_id': [Command.set([cls.env.ref('base.group_portal').id])],
})
cls.partner_portal = cls.env['res.partner'].with_context({'mail_create_nolog': True}).create({
'name': 'Georges',
'email': 'georges@project.portal',
'company_id': False,
'user_ids': [user.id],
})
cls.project_portal = cls.env['project.project'].with_context({'mail_create_nolog': True}).create({
'name': 'Project Sharing',
'privacy_visibility': 'portal',
'alias_name': 'project+sharing',
'partner_id': cls.partner_portal.id,
'type_ids': [
Command.create({'name': 'To Do', 'sequence': 1}),
Command.create({'name': 'Done', 'sequence': 10})
],
})
def test_01_project_sharing(self):
""" Test Project Sharing UI with an internal user """
self.start_tour("/web", 'project_sharing_tour', login="admin")
def test_02_project_sharing(self):
""" Test project sharing ui with a portal user.
The additional data created here are the data created in the first test with the tour js.
Since a problem to logout Mitchell Admin to log in as Georges user, this test is created
to launch a tour with portal user.
"""
project_share_wizard = self.env['project.share.wizard'].create({
'access_mode': 'edit',
'res_model': 'project.project',
'res_id': self.project_portal.id,
'partner_ids': [
Command.link(self.partner_portal.id),
],
})
project_share_wizard.action_send_mail()
self.project_portal.write({
'task_ids': [Command.create({
'name': "Test Project Sharing",
'stage_id': self.project_portal.type_ids.filtered(lambda stage: stage.sequence == 10)[:1].id,
})],
})
self.start_tour("/my/projects", 'portal_project_sharing_tour', login='georges1')
| 38.882353
| 2,644
|
5,575
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase
from odoo.exceptions import UserError
class TestProjectCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestProjectCommon, cls).setUpClass()
user_group_employee = cls.env.ref('base.group_user')
user_group_project_user = cls.env.ref('project.group_project_user')
user_group_project_manager = cls.env.ref('project.group_project_manager')
cls.partner_1 = cls.env['res.partner'].create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com'})
cls.partner_2 = cls.env['res.partner'].create({
'name': 'Valid Poilvache',
'email': 'valid.other@gmail.com'})
cls.partner_3 = cls.env['res.partner'].create({
'name': 'Valid Poilboeuf',
'email': 'valid.poilboeuf@gmail.com'})
# Test users to use through the various tests
Users = cls.env['res.users'].with_context({'no_reset_password': True})
cls.user_public = Users.create({
'name': 'Bert Tartignole',
'login': 'bert',
'email': 'b.t@example.com',
'signature': 'SignBert',
'notification_type': 'email',
'groups_id': [(6, 0, [cls.env.ref('base.group_public').id])]})
cls.user_portal = Users.create({
'name': 'Chell Gladys',
'login': 'chell',
'email': 'chell@gladys.portal',
'signature': 'SignChell',
'notification_type': 'email',
'groups_id': [(6, 0, [cls.env.ref('base.group_portal').id])]})
cls.user_projectuser = Users.create({
'name': 'Armande ProjectUser',
'login': 'armandel',
'password': 'armandel',
'email': 'armande.projectuser@example.com',
'groups_id': [(6, 0, [user_group_employee.id, user_group_project_user.id])]
})
cls.user_projectmanager = Users.create({
'name': 'Bastien ProjectManager',
'login': 'bastien',
'email': 'bastien.projectmanager@example.com',
'groups_id': [(6, 0, [user_group_employee.id, user_group_project_manager.id])]})
# Test 'Pigs' project
cls.project_pigs = cls.env['project.project'].with_context({'mail_create_nolog': True}).create({
'name': 'Pigs',
'privacy_visibility': 'employees',
'alias_name': 'project+pigs',
'partner_id': cls.partner_1.id})
# Already-existing tasks in Pigs
cls.task_1 = cls.env['project.task'].with_context({'mail_create_nolog': True}).create({
'name': 'Pigs UserTask',
'user_ids': cls.user_projectuser,
'project_id': cls.project_pigs.id})
cls.task_2 = cls.env['project.task'].with_context({'mail_create_nolog': True}).create({
'name': 'Pigs ManagerTask',
'user_ids': cls.user_projectmanager,
'project_id': cls.project_pigs.id})
# Test 'Goats' project, same as 'Pigs', but with 2 stages
cls.project_goats = cls.env['project.project'].with_context({'mail_create_nolog': True}).create({
'name': 'Goats',
'privacy_visibility': 'followers',
'alias_name': 'project+goats',
'partner_id': cls.partner_1.id,
'type_ids': [
(0, 0, {
'name': 'New',
'sequence': 1,
}),
(0, 0, {
'name': 'Won',
'sequence': 10,
})]
})
def format_and_process(self, template, to='groups@example.com, other@gmail.com', subject='Frogs',
extra='', email_from='Sylvie Lelitre <test.sylvie.lelitre@agrolait.com>',
cc='', msg_id='<1198923581.41972151344608186760.JavaMail@agrolait.com>',
model=None, target_model='project.task', target_field='name'):
self.assertFalse(self.env[target_model].search([(target_field, '=', subject)]))
mail = template.format(to=to, subject=subject, cc=cc, extra=extra, email_from=email_from, msg_id=msg_id)
self.env['mail.thread'].message_process(model, mail)
return self.env[target_model].search([(target_field, '=', subject)])
def test_delete_project_with_tasks(self):
"""User should never be able to delete a project with tasks"""
with self.assertRaises(UserError):
self.project_pigs.unlink()
# click on the archive button
self.project_pigs.write({'active': False})
with self.assertRaises(UserError):
self.project_pigs.unlink()
def test_auto_assign_stages_when_importing_tasks(self):
self.assertFalse(self.project_pigs.type_ids)
self.assertEqual(len(self.project_goats.type_ids), 2)
first_stage = self.project_goats.type_ids[0]
self.env['project.task']._load_records_create([{
'name': 'First Task',
'project_id': self.project_pigs.id,
'stage_id': first_stage.id,
}])
self.assertEqual(self.project_pigs.type_ids, first_stage)
self.env['project.task']._load_records_create([
{
'name': 'task',
'project_id': self.project_pigs.id,
'stage_id': stage.id,
} for stage in self.project_goats.type_ids
])
self.assertEqual(self.project_pigs.type_ids, self.project_goats.type_ids)
| 44.246032
| 5,575
|
1,496
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import tagged
from odoo.addons.project.tests.test_project_base import TestProjectCommon
@tagged('-at_install', 'post_install')
class TestTaskTracking(TestProjectCommon):
def flush_tracking(self):
""" Force the creation of tracking values. """
self.env['base'].flush()
self.cr.precommit.run()
def test_many2many_tracking(self):
# Basic test
# Assign new user
self.cr.precommit.clear()
self.task_1.user_ids += self.user_projectmanager
self.flush_tracking()
self.assertEqual(len(self.task_1.message_ids), 1,
"Assigning a new user should log a message.")
# No change
self.task_1.user_ids += self.user_projectmanager
self.flush_tracking()
self.assertEqual(len(self.task_1.message_ids), 1,
"Assigning an already assigned user should not log a message.")
# Removing assigness
self.task_1.user_ids = False
self.flush_tracking()
self.assertEqual(len(self.task_1.message_ids), 2,
"Removing both assignees should only log one message.")
def test_many2many_tracking_context(self):
# Test that the many2many tracking does not throw an error when using
# default values for fields that exists both on tasks and on messages
# Using an invalid value for this test
self.task_1.with_context(default_parent_id=-1).user_ids += self.user_projectmanager
| 38.358974
| 1,496
|
249
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import HttpCase, tagged
@tagged('post_install', '-at_install')
class TestProjectUpdateUi(HttpCase):
def test_01_project_tour(self):
self.start_tour("/web", 'project_update_tour', login="admin")
| 27.666667
| 249
|
2,384
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.project.tests.test_access_rights import TestProjectPortalCommon
from odoo.exceptions import AccessError
from odoo.tools import mute_logger
class TestPortalProject(TestProjectPortalCommon):
@mute_logger('odoo.addons.base.models.ir_model')
def test_portal_project_access_rights(self):
pigs = self.project_pigs
pigs.write({'privacy_visibility': 'portal'})
# Do: Alfred reads project -> ok (employee ok public)
pigs.with_user(self.user_projectuser).read(['user_id'])
# Test: all project tasks visible
tasks = self.env['project.task'].with_user(self.user_projectuser).search([('project_id', '=', pigs.id)])
self.assertEqual(tasks, self.task_1 | self.task_2 | self.task_3 | self.task_4 | self.task_5 | self.task_6,
'access rights: project user should see all tasks of a portal project')
# Do: Bert reads project -> crash, no group
self.assertRaises(AccessError, pigs.with_user(self.user_noone).read, ['user_id'])
# Test: no project task searchable
self.assertRaises(AccessError, self.env['project.task'].with_user(self.user_noone).search, [('project_id', '=', pigs.id)])
# Data: task follower
pigs.with_user(self.user_projectmanager).message_subscribe(partner_ids=[self.user_portal.partner_id.id])
self.task_1.with_user(self.user_projectuser).message_subscribe(partner_ids=[self.user_portal.partner_id.id])
self.task_3.with_user(self.user_projectuser).message_subscribe(partner_ids=[self.user_portal.partner_id.id])
# Do: Chell reads project -> ok (portal ok public)
pigs.with_user(self.user_portal).read(['user_id'])
# Do: Donovan reads project -> ko (public ko portal)
self.assertRaises(AccessError, pigs.with_user(self.user_public).read, ['user_id'])
# Test: no access right to project.task
self.assertRaises(AccessError, self.env['project.task'].with_user(self.user_public).search, [])
# Data: task follower cleaning
self.task_1.with_user(self.user_projectuser).message_unsubscribe(partner_ids=[self.user_portal.partner_id.id])
self.task_3.with_user(self.user_projectuser).message_unsubscribe(partner_ids=[self.user_portal.partner_id.id])
| 61.128205
| 2,384
|
8,049
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from freezegun import freeze_time
from datetime import datetime
from odoo import Command
from odoo.tests.common import TransactionCase
class TestBurndownChart(TransactionCase):
def set_create_date(self, table, res_id, create_date):
self.env.cr.execute("UPDATE {} SET create_date=%s WHERE id=%s".format(table), (create_date, res_id))
def test_burndown_chart(self):
current_year = datetime.now().year
create_date = datetime(current_year - 1, 1, 1)
kanban_state_vals = {
"legend_blocked": 'Blocked',
"legend_done": 'Ready',
"legend_normal": 'In Progress'
}
Stage = self.env['project.task.type']
todo_stage = Stage.create({
'sequence': 1,
'name': 'TODO',
**kanban_state_vals,
})
self.set_create_date('project_task_type', todo_stage.id, create_date)
in_progress_stage = Stage.create({
'sequence': 10,
'name': 'In Progress',
**kanban_state_vals,
})
self.set_create_date('project_task_type', in_progress_stage.id, create_date)
testing_stage = Stage.create({
'sequence': 20,
'name': 'Testing',
**kanban_state_vals,
})
self.set_create_date('project_task_type', testing_stage.id, create_date)
done_stage = Stage.create({
'sequence': 30,
'name': 'Done',
**kanban_state_vals,
})
self.set_create_date('project_task_type', done_stage.id, create_date)
stages = todo_stage + in_progress_stage + testing_stage + done_stage
project = self.env['project.project'].create({
'name': 'Burndown Chart Test',
'privacy_visibility': 'employees',
'alias_name': 'project+burndown_chart',
'type_ids': [Command.link(stage_id) for stage_id in stages.ids],
})
self.set_create_date('project_project', project.id, create_date)
project.invalidate_cache()
task_a = self.env['project.task'].create({
'name': 'Task A',
'priority': 0,
'project_id': project.id,
'stage_id': todo_stage.id,
})
self.set_create_date('project_task', task_a.id, create_date)
task_b = task_a.copy({
'name': 'Task B',
})
self.set_create_date('project_task', task_b.id, create_date)
task_c = task_a.copy({
'name': 'Task C',
})
self.set_create_date('project_task', task_c.id, create_date)
task_d = task_a.copy({
'name': 'Task D',
})
self.set_create_date('project_task', task_d.id, create_date)
task_e = task_a.copy({
'name': 'Task E',
})
self.set_create_date('project_task', task_e.id, create_date)
# Create a new task to check if a task without changing its stage is taken into account
task_f = self.env['project.task'].create({
'name': 'Task F',
'priority': 0,
'project_id': project.id,
'stage_id': todo_stage.id,
})
self.set_create_date('project_task', task_f.id, datetime(current_year - 1, 12, 20))
# Precommit to have the records in db and allow to rollback at the end of test
self.env.cr.flush()
with freeze_time('%s-02-10' % (current_year - 1)):
(task_a + task_b).write({'stage_id': in_progress_stage.id})
self.env.cr.flush()
with freeze_time('%s-02-20' % (current_year - 1)):
task_c.write({'stage_id': in_progress_stage.id})
self.env.cr.flush()
with freeze_time('%s-03-15' % (current_year - 1)):
(task_d + task_e).write({'stage_id': in_progress_stage.id})
self.env.cr.flush()
with freeze_time('%s-04-10' % (current_year - 1)):
(task_a + task_b).write({'stage_id': testing_stage.id})
self.env.cr.flush()
with freeze_time('%s-05-12' % (current_year - 1)):
task_c.write({'stage_id': testing_stage.id})
self.env.cr.flush()
with freeze_time('%s-06-25' % (current_year - 1)):
task_d.write({'stage_id': testing_stage.id})
self.env.cr.flush()
with freeze_time('%s-07-25' % (current_year - 1)):
task_e.write({'stage_id': testing_stage.id})
self.env.cr.flush()
with freeze_time('%s-08-01' % (current_year - 1)):
task_a.write({'stage_id': done_stage.id})
self.env.cr.flush()
with freeze_time('%s-09-10' % (current_year - 1)):
task_b.write({'stage_id': done_stage.id})
self.env.cr.flush()
with freeze_time('%s-10-05' % (current_year - 1)):
task_c.write({'stage_id': done_stage.id})
self.env.cr.flush()
with freeze_time('%s-11-25' % (current_year - 1)):
task_d.write({'stage_id': done_stage.id})
self.env.cr.flush()
with freeze_time('%s-12-12' % (current_year - 1)):
task_e.write({'stage_id': done_stage.id})
self.env.cr.flush()
read_group_result = self.env['project.task.burndown.chart.report'].with_context(fill_temporal=True).read_group([('project_id', '=', project.id), ('display_project_id', '!=', False)], ['date', 'stage_id', 'nb_tasks'], ['date:month', 'stage_id'], lazy=False)
read_group_result_dict = {(res['date:month'], res['stage_id'][0]): res['nb_tasks'] for res in read_group_result}
stages_dict = {stage.id: stage.name for stage in stages}
expected_dict = {
('January %s' % (current_year - 1), todo_stage.id): 5,
('February %s' % (current_year - 1), todo_stage.id): 2,
('February %s' % (current_year - 1), in_progress_stage.id): 3,
('March %s' % (current_year - 1), in_progress_stage.id): 5,
('April %s' % (current_year - 1), in_progress_stage.id): 3,
('April %s' % (current_year - 1), testing_stage.id): 2,
('May %s' % (current_year - 1), in_progress_stage.id): 2,
('May %s' % (current_year - 1), testing_stage.id): 3,
('June %s' % (current_year - 1), in_progress_stage.id): 1,
('June %s' % (current_year - 1), testing_stage.id): 4,
('July %s' % (current_year - 1), testing_stage.id): 5,
('August %s' % (current_year - 1), testing_stage.id): 4,
('August %s' % (current_year - 1), done_stage.id): 1,
('September %s' % (current_year - 1), testing_stage.id): 3,
('September %s' % (current_year - 1), done_stage.id): 2,
('October %s' % (current_year - 1), testing_stage.id): 2,
('October %s' % (current_year - 1), done_stage.id): 3,
('November %s' % (current_year - 1), testing_stage.id): 1,
('November %s' % (current_year - 1), done_stage.id): 4,
('December %s' % (current_year - 1), done_stage.id): 5,
('December %s' % (current_year - 1), todo_stage.id): 1,
('January %s' % (current_year), done_stage.id): 5,
('January %s' % (current_year), todo_stage.id): 1,
}
for (month, stage_id), nb_tasks in read_group_result_dict.items():
# when we don't found any record in the dict then we are in the current_year
# and the number of tasks should always be 5 in Done stage and 1 in Todo Stage
# since we have created the last task without changing its stage.
expected_nb_tasks = expected_dict.get((month, stage_id), 5 if stage_id != todo_stage.id else 1)
self.assertEqual(
nb_tasks,
expected_nb_tasks,
'In %s, the number of tasks should be equal to %s in %s stage.' % (month, expected_nb_tasks, stages_dict.get(stage_id, 'Unknown'))
)
| 45.219101
| 8,049
|
2,351
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import logging
from .test_project_base import TestProjectCommon
_logger = logging.getLogger(__name__)
class TestProjectConfig(TestProjectCommon):
"""Test module configuration and its effects on projects."""
@classmethod
def setUpClass(cls):
super(TestProjectConfig, cls).setUpClass()
cls.Project = cls.env["project.project"]
cls.Settings = cls.env["res.config.settings"]
cls.features = (
# Pairs of associated (config_flag, project_flag)
("group_subtask_project", "allow_subtasks"),
("group_project_recurring_tasks", "allow_recurring_tasks"),
("group_project_rating", "rating_active"),
)
# Start with a known value on feature flags to ensure validity of tests
cls._set_feature_status(is_enabled=False)
@classmethod
def _set_feature_status(cls, is_enabled):
"""Set enabled/disabled status of all optional features in the
project app config to is_enabled (boolean).
"""
features_config = cls.Settings.create(
{feature[0]: is_enabled for feature in cls.features})
features_config.execute()
def test_existing_projects_enable_features(self):
"""Check that *existing* projects have features enabled when
the user enables them in the module configuration.
"""
self._set_feature_status(is_enabled=True)
for config_flag, project_flag in self.features:
self.assertTrue(
self.project_pigs[project_flag],
"Existing project failed to adopt activation of "
f"{config_flag}/{project_flag} feature")
def test_new_projects_enable_features(self):
"""Check that after the user enables features in the module
configuration, *newly created* projects have those features
enabled as well.
"""
self._set_feature_status(is_enabled=True)
project_cows = self.Project.create({
"name": "Cows",
"partner_id": self.partner_1.id})
for config_flag, project_flag in self.features:
self.assertTrue(
project_cows[project_flag],
f"Newly created project failed to adopt activation of "
f"{config_flag}/{project_flag} feature")
| 38.540984
| 2,351
|
4,803
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.exceptions import AccessError
from odoo.tests import tagged
from odoo.tests.common import users
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.project.tests.test_project_base import TestProjectCommon
@tagged('-at_install', 'post_install')
class TestProjectUpdateAccessRights(TestProjectCommon):
@classmethod
def setUpClass(cls):
super(TestProjectUpdateAccessRights, cls).setUpClass()
cls.project_update_1 = cls.env['project.update'].create({
'name': "Test Project Update",
'project_id': cls.project_pigs.id,
'status': 'on_track',
})
cls.project_milestone = cls.env['project.milestone'].create({
'name': 'Test Projec Milestone',
'project_id': cls.project_pigs.id,
})
cls.base_user = mail_new_test_user(cls.env, 'Base user', groups='base.group_user')
cls.project_user = mail_new_test_user(cls.env, 'Project user', groups='project.group_project_user')
cls.project_manager = mail_new_test_user(cls.env, 'Project admin', groups='project.group_project_manager')
cls.portal_user = mail_new_test_user(cls.env, 'Portal user', groups='base.group_portal')
@users('Project user', 'Project admin', 'Base user')
def test_project_update_user_can_read(self):
self.project_update_1.with_user(self.env.user).name
@users('Base user')
def test_project_update_user_no_write(self):
with self.assertRaises(AccessError, msg="%s should not be able to write in the project update" % self.env.user.name):
self.project_update_1.with_user(self.env.user).name = "Test write"
@users('Project admin')
def test_project_update_admin_can_write(self):
self.project_update_1.with_user(self.env.user).name = "Test write"
@users('Base user')
def test_project_update_user_no_unlink(self):
with self.assertRaises(AccessError, msg="%s should not be able to unlink in the project update" % self.env.user.name):
self.project_update_1.with_user(self.env.user).unlink()
@users('Project admin')
def test_project_update_admin_unlink(self):
self.project_update_1.with_user(self.env.user).unlink()
@users('Portal user')
def test_project_update_portal_user_no_read(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to read in the project update"):
self.project_update_1.with_user(self.env.user).name
@users('Portal user')
def test_project_update_portal_user_no_write(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to write in the project update"):
self.project_update_1.with_user(self.env.user).name = 'Test write'
@users('Portal user')
def test_project_update_portal_user_no_create(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to create in the project update model"):
self.env['project.update'].with_user(self.env.user).create({
'name': 'Test Create with portal user',
'project_id': self.project_pigs.id,
'state': 'on_track',
})
@users('Portal user')
def test_project_update_portal_user_no_unlink(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to unlink in the project update"):
self.project_update_1.with_user(self.env.user).unlink()
@users('Portal user')
def test_project_milestone_portal_user_no_read(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to read in the project update"):
self.project_milestone.with_user(self.env.user).name
@users('Portal user')
def test_project_milestone_portal_user_no_write(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to write in the project update"):
self.project_milestone.with_user(self.env.user).name = 'Test write'
@users('Portal user')
def test_project_milestone_portal_user_no_create(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to create in the project update model"):
self.env['project.update'].with_user(self.env.user).create({
'name': 'Test Create with portal user',
'project_id': self.project_pigs.id,
})
@users('Portal user')
def test_project_milestone_portal_user_no_unlink(self):
with self.assertRaises(AccessError, msg=f"{self.env.user.name} should not be able to unlink in the project update"):
self.project_milestone.with_user(self.env.user).unlink()
| 50.03125
| 4,803
|
27,338
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests.common import TransactionCase, Form
from odoo.exceptions import ValidationError
from odoo import fields
from datetime import date, datetime
from dateutil.rrule import MO, TU, WE, TH, FR, SA, SU
from freezegun import freeze_time
class TestProjectrecurrence(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestProjectrecurrence, cls).setUpClass()
cls.env.user.groups_id += cls.env.ref('project.group_project_recurring_tasks')
cls.stage_a = cls.env['project.task.type'].create({'name': 'a'})
cls.stage_b = cls.env['project.task.type'].create({'name': 'b'})
cls.project_recurring = cls.env['project.project'].with_context({'mail_create_nolog': True}).create({
'name': 'Recurring',
'allow_recurring_tasks': True,
'type_ids': [
(4, cls.stage_a.id),
(4, cls.stage_b.id),
]
})
def set_task_create_date(self, task_id, create_date):
self.env.cr.execute("UPDATE project_task SET create_date=%s WHERE id=%s", (create_date, task_id))
def test_recurrence_simple(self):
with freeze_time("2020-02-01"):
with Form(self.env['project.task']) as form:
form.name = 'test recurring task'
form.project_id = self.project_recurring
form.recurring_task = True
form.repeat_interval = 5
form.repeat_unit = 'month'
form.repeat_type = 'after'
form.repeat_number = 10
form.repeat_on_month = 'date'
form.repeat_day = '31'
task = form.save()
self.assertTrue(bool(task.recurrence_id), 'should create a recurrence')
task.write(dict(repeat_interval=2, repeat_number=11))
self.assertEqual(task.recurrence_id.repeat_interval, 2, 'recurrence should be updated')
self.assertEqual(task.recurrence_id.repeat_number, 11, 'recurrence should be updated')
self.assertEqual(task.recurrence_id.recurrence_left, 11)
self.assertEqual(task.recurrence_id.next_recurrence_date, date(2020, 2, 29))
task.recurring_task = False
self.assertFalse(bool(task.recurrence_id), 'the recurrence should be deleted')
def test_recurrence_cron_repeat_after(self):
domain = [('project_id', '=', self.project_recurring.id)]
with freeze_time("2020-01-01"):
form = Form(self.env['project.task'])
form.name = 'test recurring task'
form.description = 'my super recurring task bla bla bla'
form.project_id = self.project_recurring
form.date_deadline = datetime(2020, 2, 1)
form.recurring_task = True
form.repeat_interval = 1
form.repeat_unit = 'month'
form.repeat_type = 'after'
form.repeat_number = 2
form.repeat_on_month = 'date'
form.repeat_day = '15'
task = form.save()
task.planned_hours = 2
self.assertEqual(task.recurrence_id.next_recurrence_date, date(2020, 1, 15))
self.assertEqual(self.env['project.task'].search_count(domain), 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 1, 'no extra task should be created')
self.assertEqual(task.recurrence_id.recurrence_left, 2)
with freeze_time("2020-01-15"):
self.assertEqual(self.env['project.task'].search_count(domain), 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 2)
self.assertEqual(task.recurrence_id.recurrence_left, 1)
with freeze_time("2020-02-15"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
self.assertEqual(task.recurrence_id.recurrence_left, 0)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
self.assertEqual(task.recurrence_id.recurrence_left, 0)
tasks = self.env['project.task'].search(domain)
self.assertEqual(len(tasks), 3)
self.assertTrue(bool(tasks[2].date_deadline))
self.assertFalse(tasks[1].date_deadline, "Deadline should not be copied")
for f in self.env['project.task.recurrence']._get_recurring_fields():
self.assertTrue(tasks[0][f] == tasks[1][f] == tasks[2][f], "Field %s should have been copied" % f)
def test_recurrence_cron_repeat_until(self):
domain = [('project_id', '=', self.project_recurring.id)]
with freeze_time("2020-01-01"):
form = Form(self.env['project.task'])
form.name = 'test recurring task'
form.description = 'my super recurring task bla bla bla'
form.project_id = self.project_recurring
form.date_deadline = datetime(2020, 2, 1)
form.recurring_task = True
form.repeat_interval = 1
form.repeat_unit = 'month'
form.repeat_type = 'until'
form.repeat_until = date(2020, 2, 20)
form.repeat_on_month = 'date'
form.repeat_day = '15'
task = form.save()
task.planned_hours = 2
self.assertEqual(task.recurrence_id.next_recurrence_date, date(2020, 1, 15))
self.assertEqual(self.env['project.task'].search_count(domain), 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 1, 'no extra task should be created')
with freeze_time("2020-01-15"):
self.assertEqual(self.env['project.task'].search_count(domain), 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 2)
with freeze_time("2020-02-15"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
tasks = self.env['project.task'].search(domain)
self.assertEqual(len(tasks), 3)
self.assertTrue(bool(tasks[2].date_deadline))
self.assertFalse(tasks[1].date_deadline, "Deadline should not be copied")
for f in self.env['project.task.recurrence']._get_recurring_fields():
self.assertTrue(tasks[0][f] == tasks[1][f] == tasks[2][f], "Field %s should have been copied" % f)
def test_recurrence_cron_repeat_forever(self):
domain = [('project_id', '=', self.project_recurring.id)]
with freeze_time("2020-01-01"):
form = Form(self.env['project.task'])
form.name = 'test recurring task'
form.description = 'my super recurring task bla bla bla'
form.project_id = self.project_recurring
form.date_deadline = datetime(2020, 2, 1)
form.recurring_task = True
form.repeat_interval = 1
form.repeat_unit = 'month'
form.repeat_type = 'forever'
form.repeat_on_month = 'date'
form.repeat_day = '15'
task = form.save()
task.planned_hours = 2
self.assertEqual(task.recurrence_id.next_recurrence_date, date(2020, 1, 15))
self.assertEqual(self.env['project.task'].search_count(domain), 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 1, 'no extra task should be created')
with freeze_time("2020-01-15"):
self.assertEqual(self.env['project.task'].search_count(domain), 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 2)
with freeze_time("2020-02-15"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
with freeze_time("2020-02-16"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
with freeze_time("2020-02-17"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
with freeze_time("2020-02-17"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 3)
with freeze_time("2020-03-15"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 4)
tasks = self.env['project.task'].search(domain)
self.assertEqual(len(tasks), 4)
self.assertTrue(bool(tasks[3].date_deadline))
self.assertFalse(tasks[1].date_deadline, "Deadline should not be copied")
for f in self.env['project.task.recurrence']._get_recurring_fields():
self.assertTrue(
tasks[0][f] == tasks[1][f] == tasks[2][f] == tasks[3][f],
"Field %s should have been copied" % f)
def test_recurrence_update_task(self):
with freeze_time("2020-01-01"):
task = self.env['project.task'].create({
'name': 'test recurring task',
'project_id': self.project_recurring.id,
'recurring_task': True,
'repeat_interval': 1,
'repeat_unit': 'week',
'repeat_type': 'after',
'repeat_number': 2,
'mon': True,
})
with freeze_time("2020-01-06"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
with freeze_time("2020-01-13"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
task_c, task_b, task_a = self.env['project.task'].search([('project_id', '=', self.project_recurring.id)])
self.set_task_create_date(task_a.id, datetime(2020, 1, 1))
self.set_task_create_date(task_b.id, datetime(2020, 1, 6))
self.set_task_create_date(task_c.id, datetime(2020, 1, 13))
(task_a+task_b+task_c).invalidate_cache()
task_c.write({
'name': 'my super updated task',
'recurrence_update': 'all',
})
self.assertEqual(task_a.name, 'my super updated task')
self.assertEqual(task_b.name, 'my super updated task')
self.assertEqual(task_c.name, 'my super updated task')
task_a.write({
'name': 'don\'t you dare change my title',
'recurrence_update': 'this',
})
self.assertEqual(task_a.name, 'don\'t you dare change my title')
self.assertEqual(task_b.name, 'my super updated task')
self.assertEqual(task_c.name, 'my super updated task')
task_b.write({
'description': 'hello!',
'recurrence_update': 'subsequent',
})
self.assertEqual(task_a.description, False)
self.assertEqual(task_b.description, '<p>hello!</p>')
self.assertEqual(task_c.description, '<p>hello!</p>')
def test_recurrence_fields_visibility(self):
form = Form(self.env['project.task'])
form.name = 'test recurring task'
form.project_id = self.project_recurring
form.recurring_task = True
form.repeat_unit = 'week'
self.assertTrue(form.repeat_show_dow)
self.assertFalse(form.repeat_show_day)
self.assertFalse(form.repeat_show_week)
self.assertFalse(form.repeat_show_month)
form.repeat_unit = 'month'
form.repeat_on_month = 'date'
self.assertFalse(form.repeat_show_dow)
self.assertTrue(form.repeat_show_day)
self.assertFalse(form.repeat_show_week)
self.assertFalse(form.repeat_show_month)
form.repeat_unit = 'month'
form.repeat_on_month = 'day'
self.assertFalse(form.repeat_show_dow)
self.assertFalse(form.repeat_show_day)
self.assertTrue(form.repeat_show_week)
self.assertFalse(form.repeat_show_month)
form.repeat_unit = 'year'
form.repeat_on_year = 'date'
self.assertFalse(form.repeat_show_dow)
self.assertTrue(form.repeat_show_day)
self.assertFalse(form.repeat_show_week)
self.assertTrue(form.repeat_show_month)
form.repeat_unit = 'year'
form.repeat_on_year = 'day'
self.assertFalse(form.repeat_show_dow)
self.assertFalse(form.repeat_show_day)
self.assertTrue(form.repeat_show_week)
self.assertTrue(form.repeat_show_month)
form.recurring_task = False
self.assertFalse(form.repeat_show_dow)
self.assertFalse(form.repeat_show_day)
self.assertFalse(form.repeat_show_week)
self.assertFalse(form.repeat_show_month)
def test_recurrence_week_day(self):
with self.assertRaises(ValidationError), self.cr.savepoint():
self.env['project.task'].create({
'name': 'test recurring task',
'project_id': self.project_recurring.id,
'recurring_task': True,
'repeat_interval': 1,
'repeat_unit': 'week',
'repeat_type': 'after',
'repeat_number': 2,
'mon': False,
'tue': False,
'wed': False,
'thu': False,
'fri': False,
'sat': False,
'sun': False,
})
def test_recurrence_next_dates_week(self):
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2020, 1, 1),
repeat_interval=1,
repeat_unit='week',
repeat_type=False,
repeat_until=False,
repeat_on_month=False,
repeat_on_year=False,
weekdays=False,
repeat_day=False,
repeat_week=False,
repeat_month=False,
count=5)
self.assertEqual(dates[0], datetime(2020, 1, 6, 0, 0))
self.assertEqual(dates[1], datetime(2020, 1, 13, 0, 0))
self.assertEqual(dates[2], datetime(2020, 1, 20, 0, 0))
self.assertEqual(dates[3], datetime(2020, 1, 27, 0, 0))
self.assertEqual(dates[4], datetime(2020, 2, 3, 0, 0))
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2020, 1, 1),
repeat_interval=3,
repeat_unit='week',
repeat_type='until',
repeat_until=date(2020, 2, 1),
repeat_on_month=False,
repeat_on_year=False,
weekdays=[MO, FR],
repeat_day=False,
repeat_week=False,
repeat_month=False,
count=100)
self.assertEqual(len(dates), 3)
self.assertEqual(dates[0], datetime(2020, 1, 3, 0, 0))
self.assertEqual(dates[1], datetime(2020, 1, 20, 0, 0))
self.assertEqual(dates[2], datetime(2020, 1, 24, 0, 0))
def test_recurrence_next_dates_month(self):
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2020, 1, 15),
repeat_interval=1,
repeat_unit='month',
repeat_type=False, # Forever
repeat_until=False,
repeat_on_month='date',
repeat_on_year=False,
weekdays=False,
repeat_day=31,
repeat_week=False,
repeat_month=False,
count=12)
# should take the last day of each month
self.assertEqual(dates[0], date(2020, 1, 31))
self.assertEqual(dates[1], date(2020, 2, 29))
self.assertEqual(dates[2], date(2020, 3, 31))
self.assertEqual(dates[3], date(2020, 4, 30))
self.assertEqual(dates[4], date(2020, 5, 31))
self.assertEqual(dates[5], date(2020, 6, 30))
self.assertEqual(dates[6], date(2020, 7, 31))
self.assertEqual(dates[7], date(2020, 8, 31))
self.assertEqual(dates[8], date(2020, 9, 30))
self.assertEqual(dates[9], date(2020, 10, 31))
self.assertEqual(dates[10], date(2020, 11, 30))
self.assertEqual(dates[11], date(2020, 12, 31))
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2020, 2, 20),
repeat_interval=3,
repeat_unit='month',
repeat_type=False, # Forever
repeat_until=False,
repeat_on_month='date',
repeat_on_year=False,
weekdays=False,
repeat_day=29,
repeat_week=False,
repeat_month=False,
count=5)
self.assertEqual(dates[0], date(2020, 2, 29))
self.assertEqual(dates[1], date(2020, 5, 29))
self.assertEqual(dates[2], date(2020, 8, 29))
self.assertEqual(dates[3], date(2020, 11, 29))
self.assertEqual(dates[4], date(2021, 2, 28))
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2020, 1, 10),
repeat_interval=1,
repeat_unit='month',
repeat_type='until',
repeat_until=datetime(2020, 5, 31),
repeat_on_month='day',
repeat_on_year=False,
weekdays=[SA(4), ], # 4th Saturday
repeat_day=29,
repeat_week=False,
repeat_month=False,
count=6)
self.assertEqual(len(dates), 5)
self.assertEqual(dates[0], datetime(2020, 1, 25))
self.assertEqual(dates[1], datetime(2020, 2, 22))
self.assertEqual(dates[2], datetime(2020, 3, 28))
self.assertEqual(dates[3], datetime(2020, 4, 25))
self.assertEqual(dates[4], datetime(2020, 5, 23))
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=datetime(2020, 1, 10),
repeat_interval=6, # twice a year
repeat_unit='month',
repeat_type='until',
repeat_until=datetime(2021, 1, 11),
repeat_on_month='date',
repeat_on_year=False,
weekdays=[TH(+1)],
repeat_day='3', # the 3rd of the month
repeat_week=False,
repeat_month=False,
count=1)
self.assertEqual(len(dates), 2)
self.assertEqual(dates[0], datetime(2020, 7, 3))
self.assertEqual(dates[1], datetime(2021, 1, 3))
# Should generate a date at the last day of the current month
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2022, 2, 26),
repeat_interval=1,
repeat_unit='month',
repeat_type='until',
repeat_until=date(2022, 2, 28),
repeat_on_month='date',
repeat_on_year=False,
weekdays=False,
repeat_day=31,
repeat_week=False,
repeat_month=False,
count=5)
self.assertEqual(len(dates), 1)
self.assertEqual(dates[0], date(2022, 2, 28))
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2022, 11, 26),
repeat_interval=3,
repeat_unit='month',
repeat_type='until',
repeat_until=date(2024, 2, 29),
repeat_on_month='date',
repeat_on_year=False,
weekdays=False,
repeat_day=25,
repeat_week=False,
repeat_month=False,
count=5)
self.assertEqual(len(dates), 5)
self.assertEqual(dates[0], date(2023, 2, 25))
self.assertEqual(dates[1], date(2023, 5, 25))
self.assertEqual(dates[2], date(2023, 8, 25))
self.assertEqual(dates[3], date(2023, 11, 25))
self.assertEqual(dates[4], date(2024, 2, 25))
# Use the exact same parameters than the previous test but with a repeat_day that is not passed yet
# So we generate an additional date in the current month
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2022, 11, 26),
repeat_interval=3,
repeat_unit='month',
repeat_type='until',
repeat_until=date(2024, 2, 29),
repeat_on_month='date',
repeat_on_year=False,
weekdays=False,
repeat_day=31,
repeat_week=False,
repeat_month=False,
count=5)
self.assertEqual(len(dates), 6)
self.assertEqual(dates[0], date(2022, 11, 30))
self.assertEqual(dates[1], date(2023, 2, 28))
self.assertEqual(dates[2], date(2023, 5, 31))
self.assertEqual(dates[3], date(2023, 8, 31))
self.assertEqual(dates[4], date(2023, 11, 30))
self.assertEqual(dates[5], date(2024, 2, 29))
def test_recurrence_next_dates_year(self):
dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date_start=date(2020, 12, 1),
repeat_interval=1,
repeat_unit='year',
repeat_type='until',
repeat_until=datetime(2026, 1, 1),
repeat_on_month=False,
repeat_on_year='date',
weekdays=False,
repeat_day=31,
repeat_week=False,
repeat_month='november',
count=10)
self.assertEqual(len(dates), 5)
self.assertEqual(dates[0], datetime(2021, 11, 30))
self.assertEqual(dates[1], datetime(2022, 11, 30))
self.assertEqual(dates[2], datetime(2023, 11, 30))
self.assertEqual(dates[3], datetime(2024, 11, 30))
self.assertEqual(dates[4], datetime(2025, 11, 30))
def test_recurrence_cron_repeat_after_subtasks(self):
def get_task_and_subtask_counts(domain):
tasks = self.env['project.task'].search(domain)
return tasks, len(tasks), len(tasks.filtered('parent_id'))
parent_task = self.env['project.task'].create({
'name': 'Parent Task',
'project_id': self.project_recurring.id
})
domain = [('project_id', '=', self.project_recurring.id)]
with Form(parent_task.with_context({'tracking_disable': True})) as task_form:
with task_form.child_ids.new() as subtask_form:
subtask_form.name = 'Test Subtask 1'
with freeze_time("2020-01-01"):
with Form(parent_task.child_ids.with_context({'tracking_disable': True})) as form:
form.description = 'my super recurring task bla bla bla'
form.date_deadline = datetime(2020, 2, 1)
form.display_project_id = parent_task.project_id
form.recurring_task = True
form.repeat_interval = 1
form.repeat_unit = 'month'
form.repeat_type = 'after'
form.repeat_number = 2
form.repeat_on_month = 'date'
form.repeat_day = '15'
subtask = form.save()
subtask.planned_hours = 2
self.assertEqual(subtask.recurrence_id.next_recurrence_date, date(2020, 1, 15))
project_tasks, project_task_count, project_subtask_count = get_task_and_subtask_counts(domain)
self.assertEqual(project_task_count, 2)
self.assertEqual(project_subtask_count, 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
self.assertEqual(self.env['project.task'].search_count(domain), 2, 'no extra task should be created')
self.assertEqual(subtask.recurrence_id.recurrence_left, 2)
for task in project_tasks:
self.assertEqual(task.display_project_id, parent_task.project_id, "All tasks should have a display project id set")
with freeze_time("2020-01-15"):
project_tasks, project_task_count, project_subtask_count = get_task_and_subtask_counts(domain)
self.assertEqual(project_task_count, 2)
self.assertEqual(project_subtask_count, 1)
self.env['project.task.recurrence']._cron_create_recurring_tasks()
project_tasks, project_task_count, project_subtask_count = get_task_and_subtask_counts(domain)
self.assertEqual(project_task_count, 3)
self.assertEqual(project_subtask_count, 2)
self.assertEqual(subtask.recurrence_id.recurrence_left, 1)
for task in project_tasks:
self.assertEqual(task.display_project_id, parent_task.project_id, "All tasks should have a display project id set")
with freeze_time("2020-02-15"):
self.env['project.task.recurrence']._cron_create_recurring_tasks()
project_tasks, project_task_count, project_subtask_count = get_task_and_subtask_counts(domain)
self.assertEqual(project_task_count, 4)
self.assertEqual(project_subtask_count, 3)
self.assertEqual(subtask.recurrence_id.recurrence_left, 0)
for task in project_tasks:
self.assertEqual(task.display_project_id, parent_task.project_id, "All tasks should have a display project id set")
self.env['project.task.recurrence']._cron_create_recurring_tasks()
_, project_task_count, project_subtask_count = get_task_and_subtask_counts(domain)
self.assertEqual(project_task_count, 4)
self.assertEqual(project_subtask_count, 3)
self.assertEqual(subtask.recurrence_id.recurrence_left, 0)
tasks = self.env['project.task'].search(domain)
self.assertEqual(len(tasks), 4)
self.assertTrue(bool(tasks[2].date_deadline))
self.assertFalse(tasks[1].date_deadline, "Deadline should not be copied")
for f in self.env['project.task.recurrence']._get_recurring_fields():
self.assertTrue(tasks[0][f] == tasks[1][f] == tasks[2][f], "Field %s should have been copied" % f)
def test_compute_recurrence_message_with_lang_not_set(self):
task = self.env['project.task'].create({
'name': 'Test task with user language not set',
'project_id': self.project_recurring.id,
'recurring_task': True,
'repeat_interval': 1,
'repeat_unit': 'week',
'repeat_type': 'after',
'repeat_number': 2,
'mon': True,
})
self.env.user.lang = None
task._compute_recurrence_message()
| 43.324881
| 27,338
|
4,602
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import tagged
from odoo.tests.common import Form
from odoo.addons.project.tests.test_project_base import TestProjectCommon
@tagged('-at_install', 'post_install')
class TestProjectUpdate(TestProjectCommon):
def test_project_update_form(self):
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 1"
milestone_form.deadline = fields.Date.today()
try:
with Form(self.env['project.update'].with_context({'default_project_id': self.project_pigs.id})) as update_form:
update_form.name = "Test"
update_form.progress = 65
update = update_form.save()
except Exception as e:
raise AssertionError("Error raised unexpectedly while filling the project update form ! Exception : " + e.args[0])
self.assertEqual(update.user_id, self.env.user, "The author is the user who created the update.")
self.assertNotEqual(len(update.description), 0, "The description should not be empty.")
self.assertTrue("Activities" in update.description, "The description should contain 'Activities'.")
self.assertEqual(update.status, 'on_track', "The status should be the default one.")
with Form(self.env['project.update'].with_context({'default_project_id': self.project_pigs.id})) as update_form:
update_form.name = "Test 2"
update = update_form.save()
self.assertEqual(update.progress, 65, "The default progress is the one from the previous update by default")
def test_project_update_description(self):
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 1"
milestone_form.deadline = fields.Date.today()
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 2"
milestone_form.deadline = fields.Date.today()
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 3"
milestone_form.deadline = fields.Date.today() + relativedelta(years=2)
template_values = self.env['project.update']._get_template_values(self.project_pigs)
self.assertEqual(len(template_values['milestones']['list']), 2, "Milestone list length should be equal to 2")
self.assertEqual(len(template_values['milestones']['created']), 3, "Milestone created length tasks should be equal to 3")
def test_project_update_panel(self):
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 1"
milestone_form.deadline = fields.Date.today() + relativedelta(years=-1)
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 2"
milestone_form.deadline = fields.Date.today() + relativedelta(years=-1)
milestone_form.is_reached = True
with Form(self.env['project.milestone'].with_context({'default_project_id': self.project_pigs.id})) as milestone_form:
milestone_form.name = "Test 3"
milestone_form.deadline = fields.Date.today() + relativedelta(years=2)
panel_data = self.project_pigs.get_panel_data()
self.assertEqual(len(panel_data['milestones']['data']), 3, "Panel data should contain 'milestone' entry")
self.assertFalse(panel_data['milestones']['data'][0]['is_deadline_exceeded'], "Milestone is achieved")
self.assertTrue(panel_data['milestones']['data'][1]['is_deadline_exceeded'], "Milestone is exceeded")
self.assertTrue(panel_data['milestones']['data'][0]['is_reached'], "Milestone is done")
self.assertFalse(panel_data['milestones']['data'][1]['is_reached'], "Milestone isn't done")
# sorting
self.assertEqual(panel_data['milestones']['data'][0]['name'], "Test 2", "Sorting isn't correct")
self.assertEqual(panel_data['milestones']['data'][1]['name'], "Test 1", "Sorting isn't correct")
self.assertEqual(panel_data['milestones']['data'][2]['name'], "Test 3", "Sorting isn't correct")
| 61.36
| 4,602
|
12,789
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from odoo.tests.common import TransactionCase, Form
from odoo.exceptions import AccessError, UserError
class TestMultiCompanyCommon(TransactionCase):
@classmethod
def setUpMultiCompany(cls):
# create companies
cls.company_a = cls.env['res.company'].create({
'name': 'Company A'
})
cls.company_b = cls.env['res.company'].create({
'name': 'Company B'
})
# shared customers
cls.partner_1 = cls.env['res.partner'].create({
'name': 'Valid Lelitre',
'email': 'valid.lelitre@agrolait.com',
'company_id': False,
})
cls.partner_2 = cls.env['res.partner'].create({
'name': 'Valid Poilvache',
'email': 'valid.other@gmail.com',
'company_id': False,
})
# users to use through the various tests
user_group_employee = cls.env.ref('base.group_user')
Users = cls.env['res.users'].with_context({'no_reset_password': True})
cls.user_employee_company_a = Users.create({
'name': 'Employee Company A',
'login': 'employee-a',
'email': 'employee@companya.com',
'company_id': cls.company_a.id,
'company_ids': [(6, 0, [cls.company_a.id])],
'groups_id': [(6, 0, [user_group_employee.id])]
})
cls.user_manager_company_a = Users.create({
'name': 'Manager Company A',
'login': 'manager-a',
'email': 'manager@companya.com',
'company_id': cls.company_a.id,
'company_ids': [(6, 0, [cls.company_a.id])],
'groups_id': [(6, 0, [user_group_employee.id])]
})
cls.user_employee_company_b = Users.create({
'name': 'Employee Company B',
'login': 'employee-b',
'email': 'employee@companyb.com',
'company_id': cls.company_b.id,
'company_ids': [(6, 0, [cls.company_b.id])],
'groups_id': [(6, 0, [user_group_employee.id])]
})
cls.user_manager_company_b = Users.create({
'name': 'Manager Company B',
'login': 'manager-b',
'email': 'manager@companyb.com',
'company_id': cls.company_b.id,
'company_ids': [(6, 0, [cls.company_b.id])],
'groups_id': [(6, 0, [user_group_employee.id])]
})
@contextmanager
def sudo(self, login):
old_uid = self.uid
try:
user = self.env['res.users'].sudo().search([('login', '=', login)])
# switch user
self.uid = user.id
self.env = self.env(user=self.uid)
yield
finally:
# back
self.uid = old_uid
self.env = self.env(user=self.uid)
@contextmanager
def allow_companies(self, company_ids):
""" The current user will be allowed in each given companies (like he can sees all of them in the company switcher and they are all checked) """
old_allow_company_ids = self.env.user.company_ids.ids
current_user = self.env.user
try:
current_user.write({'company_ids': company_ids})
context = dict(self.env.context, allowed_company_ids=company_ids)
self.env = self.env(user=current_user, context=context)
yield
finally:
# back
current_user.write({'company_ids': old_allow_company_ids})
context = dict(self.env.context, allowed_company_ids=old_allow_company_ids)
self.env = self.env(user=current_user, context=context)
@contextmanager
def switch_company(self, company):
""" Change the company in which the current user is logged """
old_companies = self.env.context.get('allowed_company_ids', [])
try:
# switch company in context
new_companies = list(old_companies)
if company.id not in new_companies:
new_companies = [company.id] + new_companies
else:
new_companies.insert(0, new_companies.pop(new_companies.index(company.id)))
context = dict(self.env.context, allowed_company_ids=new_companies)
self.env = self.env(context=context)
yield
finally:
# back
context = dict(self.env.context, allowed_company_ids=old_companies)
self.env = self.env(context=context)
class TestMultiCompanyProject(TestMultiCompanyCommon):
@classmethod
def setUpClass(cls):
super(TestMultiCompanyProject, cls).setUpClass()
cls.setUpMultiCompany()
user_group_project_user = cls.env.ref('project.group_project_user')
user_group_project_manager = cls.env.ref('project.group_project_manager')
# setup users
cls.user_employee_company_a.write({
'groups_id': [(4, user_group_project_user.id)]
})
cls.user_manager_company_a.write({
'groups_id': [(4, user_group_project_manager.id)]
})
cls.user_employee_company_b.write({
'groups_id': [(4, user_group_project_user.id)]
})
cls.user_manager_company_b.write({
'groups_id': [(4, user_group_project_manager.id)]
})
# create project in both companies
Project = cls.env['project.project'].with_context({'mail_create_nolog': True, 'tracking_disable': True})
cls.project_company_a = Project.create({
'name': 'Project Company A',
'alias_name': 'project+companya',
'partner_id': cls.partner_1.id,
'company_id': cls.company_a.id,
'type_ids': [
(0, 0, {
'name': 'New',
'sequence': 1,
}),
(0, 0, {
'name': 'Won',
'sequence': 10,
})
]
})
cls.project_company_b = Project.create({
'name': 'Project Company B',
'alias_name': 'project+companyb',
'partner_id': cls.partner_1.id,
'company_id': cls.company_b.id,
'type_ids': [
(0, 0, {
'name': 'New',
'sequence': 1,
}),
(0, 0, {
'name': 'Won',
'sequence': 10,
})
]
})
# already-existing tasks in company A and B
Task = cls.env['project.task'].with_context({'mail_create_nolog': True, 'tracking_disable': True})
cls.task_1 = Task.create({
'name': 'Task 1 in Project A',
'user_ids': cls.user_employee_company_a,
'project_id': cls.project_company_a.id
})
cls.task_2 = Task.create({
'name': 'Task 2 in Project B',
'user_ids': cls.user_employee_company_b,
'project_id': cls.project_company_b.id
})
def test_create_project(self):
""" Check project creation in multiple companies """
with self.sudo('manager-a'):
project = self.env['project.project'].with_context({'tracking_disable': True}).create({
'name': 'Project Company A',
'partner_id': self.partner_1.id,
})
self.assertEqual(project.company_id, self.env.user.company_id, "A newly created project should be in the current user company")
with self.switch_company(self.company_b):
with self.assertRaises(AccessError, msg="Manager can not create project in a company in which he is not allowed"):
project = self.env['project.project'].with_context({'tracking_disable': True}).create({
'name': 'Project Company B',
'partner_id': self.partner_1.id,
'company_id': self.company_b.id
})
# when allowed in other company, can create a project in another company (different from the one in which you are logged)
with self.allow_companies([self.company_a.id, self.company_b.id]):
project = self.env['project.project'].with_context({'tracking_disable': True}).create({
'name': 'Project Company B',
'partner_id': self.partner_1.id,
'company_id': self.company_b.id
})
def test_generate_analytic_account(self):
""" Check the analytic account generation, company propagation """
with self.sudo('manager-b'):
with self.allow_companies([self.company_a.id, self.company_b.id]):
self.project_company_a._create_analytic_account()
self.assertEqual(self.project_company_a.company_id, self.project_company_a.analytic_account_id.company_id, "The analytic account created from a project should be in the same company")
def test_create_task(self):
with self.sudo('employee-a'):
# create task, set project; the onchange will set the correct company
with Form(self.env['project.task'].with_context({'tracking_disable': True})) as task_form:
task_form.name = 'Test Task in company A'
task_form.project_id = self.project_company_a
task = task_form.save()
self.assertEqual(task.company_id, self.project_company_a.company_id, "The company of the task should be the one from its project.")
def test_move_task(self):
with self.sudo('employee-a'):
with self.allow_companies([self.company_a.id, self.company_b.id]):
with Form(self.task_1) as task_form:
task_form.project_id = self.project_company_b
task = task_form.save()
self.assertEqual(task.company_id, self.company_b, "The company of the task should be the one from its project.")
with Form(self.task_1) as task_form:
task_form.project_id = self.project_company_a
task = task_form.save()
self.assertEqual(task.company_id, self.company_a, "Moving a task should change its company.")
def test_create_subtask(self):
with self.sudo('employee-a'):
with self.allow_companies([self.company_a.id, self.company_b.id]):
# create subtask, set parent; the onchange will set the correct company and subtask project
with Form(self.env['project.task'].with_context({'tracking_disable': True, 'default_parent_id': self.task_1.id, 'default_project_id': self.project_company_b.id})) as task_form:
task_form.name = 'Test Subtask in company B'
task = task_form.save()
self.assertEqual(task.company_id, self.project_company_b.company_id, "The company of the subtask should be the one from its project, and not from its parent.")
# set parent on existing orphan task; the onchange will set the correct company and subtask project
self.task_2.write({'project_id': False})
with Form(self.task_2) as task_form:
task_form.name = 'Test Task 2 becomes child of Task 1 (other company)'
task_form.parent_id = self.task_1
task = task_form.save()
self.assertEqual(task.company_id, task.project_id.company_id, "The company of the orphan subtask should be the one from its project.")
def test_cross_subtask_project(self):
# set up default subtask project
self.project_company_a.write({'allow_subtasks': True})
with self.sudo('employee-a'):
with self.allow_companies([self.company_a.id, self.company_b.id]):
with Form(self.env['project.task'].with_context({'tracking_disable': True})) as task_form:
task_form.name = 'Test Subtask in company B'
task_form.parent_id = self.task_1
task = task_form.save()
self.assertEqual(task.project_id, self.task_1.project_id, "The default project of a subtask should be the default subtask project of the project from the mother task")
self.assertEqual(task.company_id, task.project_id.company_id, "The company of the orphan subtask should be the one from its project.")
self.assertEqual(self.task_1.child_ids.ids, [task.id])
with self.sudo('employee-a'):
with self.assertRaises(AccessError):
with Form(task) as task_form:
task_form.name = "Testing changing name in a company I can not read/write"
| 44.716783
| 12,789
|
1,798
|
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 ProjectShareWizard(models.TransientModel):
_name = 'project.share.wizard'
_inherit = 'portal.share'
_description = 'Project Sharing'
@api.model
def default_get(self, fields):
result = super().default_get(fields)
if not result.get('access_mode'):
result.update(
access_mode='read',
display_access_mode=True,
)
return result
@api.model
def _selection_target_model(self):
project_model = self.env['ir.model']._get('project.project')
return [(project_model.model, project_model.name)]
access_mode = fields.Selection([('read', 'Readonly'), ('edit', 'Edit')])
display_access_mode = fields.Boolean()
@api.depends('res_model', 'res_id')
def _compute_resource_ref(self):
for wizard in self:
if wizard.res_model and wizard.res_model == 'project.project':
wizard.resource_ref = '%s,%s' % (wizard.res_model, wizard.res_id or 0)
else:
wizard.resource_ref = None
def action_send_mail(self):
self.ensure_one()
if self.access_mode == 'edit':
portal_partners = self.partner_ids.filtered('user_ids')
note = self._get_note()
self.resource_ref._add_collaborators(self.partner_ids)
self._send_public_link(note, portal_partners)
self._send_signup_link(note, partners=self.partner_ids - portal_partners)
self.resource_ref.message_subscribe(partner_ids=self.partner_ids.ids)
return {'type': 'ir.actions.act_window_close'}
return super().action_send_mail()
| 37.458333
| 1,798
|
2,925
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
import ast
class ProjectTaskTypeDelete(models.TransientModel):
_name = 'project.task.type.delete.wizard'
_description = 'Project Stage Delete Wizard'
project_ids = fields.Many2many('project.project', domain="['|', ('active', '=', False), ('active', '=', True)]", string='Projects', ondelete='cascade')
stage_ids = fields.Many2many('project.task.type', string='Stages To Delete', ondelete='cascade')
tasks_count = fields.Integer('Number of Tasks', compute='_compute_tasks_count')
stages_active = fields.Boolean(compute='_compute_stages_active')
@api.depends('project_ids')
def _compute_tasks_count(self):
for wizard in self:
wizard.tasks_count = self.with_context(active_test=False).env['project.task'].search_count([('stage_id', 'in', wizard.stage_ids.ids)])
@api.depends('stage_ids')
def _compute_stages_active(self):
for wizard in self:
wizard.stages_active = all(wizard.stage_ids.mapped('active'))
def action_archive(self):
if len(self.project_ids) <= 1:
return self.action_confirm()
return {
'name': _('Confirmation'),
'view_mode': 'form',
'res_model': 'project.task.type.delete.wizard',
'views': [(self.env.ref('project.view_project_task_type_delete_confirmation_wizard').id, 'form')],
'type': 'ir.actions.act_window',
'res_id': self.id,
'target': 'new',
'context': self.env.context,
}
def action_confirm(self):
tasks = self.with_context(active_test=False).env['project.task'].search([('stage_id', 'in', self.stage_ids.ids)])
tasks.write({'active': False})
self.stage_ids.write({'active': False})
return self._get_action()
def action_unlink(self):
self.stage_ids.unlink()
return self._get_action()
def _get_action(self):
project_id = self.env.context.get('default_project_id')
if project_id:
action = self.env["ir.actions.actions"]._for_xml_id("project.action_view_task")
action['domain'] = [('project_id', '=', project_id)]
action['context'] = str({
'pivot_row_groupby': ['user_ids'],
'default_project_id': project_id,
})
elif self.env.context.get('stage_view'):
action = self.env["ir.actions.actions"]._for_xml_id("project.open_task_type_form")
else:
action = self.env["ir.actions.actions"]._for_xml_id("project.action_view_all_task")
context = dict(ast.literal_eval(action.get('context')), active_test=True)
action['context'] = context
action['target'] = 'main'
return action
| 40.625
| 2,925
|
1,081
|
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 ProjectDelete(models.TransientModel):
_name = 'project.delete.wizard'
_description = 'Project Delete Wizard'
project_ids = fields.Many2many('project.project', string='Projects')
task_count = fields.Integer(compute='_compute_task_count')
projects_archived = fields.Boolean(compute='_compute_projects_archived')
def _compute_projects_archived(self):
for wizard in self.with_context(active_test=False):
wizard.projects_archived = all(not p.active for p in wizard.project_ids)
def _compute_task_count(self):
for wizard in self:
wizard.task_count = sum(wizard.with_context(active_test=False).project_ids.mapped('task_count'))
def action_archive(self):
self.project_ids.write({'active': False})
def confirm_delete(self):
self.with_context(active_test=False).project_ids.unlink()
return self.env["project.project"]._action_open_all_projects()
| 38.607143
| 1,081
|
1,321
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.exceptions import AccessError
class Digest(models.Model):
_inherit = 'digest.digest'
kpi_project_task_opened = fields.Boolean('Open Tasks')
kpi_project_task_opened_value = fields.Integer(compute='_compute_project_task_opened_value')
def _compute_project_task_opened_value(self):
if not self.env.user.has_group('project.group_project_user'):
raise AccessError(_("Do not have access, skip this data for user's digest email"))
for record in self:
start, end, company = record._get_kpi_compute_parameters()
record.kpi_project_task_opened_value = self.env['project.task'].search_count([
('stage_id.fold', '=', False),
('create_date', '>=', start),
('create_date', '<', end),
('company_id', '=', company.id),
('display_project_id', '!=', False),
])
def _compute_kpis_actions(self, company, user):
res = super(Digest, self)._compute_kpis_actions(company, user)
res['kpi_project_task_opened'] = 'project.open_view_project_all&menu_id=%s' % self.env.ref('project.menu_main_pm').id
return res
| 44.033333
| 1,321
|
7,116
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from werkzeug.urls import url_encode
from odoo import api, fields, models
from odoo.osv import expression
from odoo.tools import formatLang
STATUS_COLOR = {
'on_track': 20, # green / success
'at_risk': 2, # orange
'off_track': 23, # red / danger
'on_hold': 4, # light blue
False: 0, # default grey -- for studio
}
class ProjectUpdate(models.Model):
_name = 'project.update'
_description = 'Project Update'
_order = 'date desc'
_inherit = ['mail.thread.cc', 'mail.activity.mixin']
def default_get(self, fields):
result = super().default_get(fields)
if 'project_id' in fields and not result.get('project_id'):
result['project_id'] = self.env.context.get('active_id')
if result.get('project_id'):
project = self.env['project.project'].browse(result['project_id'])
if 'progress' in fields and not result.get('progress'):
result['progress'] = project.last_update_id.progress
if 'description' in fields and not result.get('description'):
result['description'] = self._build_description(project)
if 'status' in fields and not result.get('status'):
result['status'] = project.last_update_status
return result
name = fields.Char("Title", required=True, tracking=True)
status = fields.Selection(selection=[
('on_track', 'On Track'),
('at_risk', 'At Risk'),
('off_track', 'Off Track'),
('on_hold', 'On Hold')
], required=True, tracking=True)
color = fields.Integer(compute='_compute_color')
progress = fields.Integer(tracking=True)
progress_percentage = fields.Float(compute='_compute_progress_percentage')
user_id = fields.Many2one('res.users', string='Author', required=True, default=lambda self: self.env.user)
description = fields.Html()
date = fields.Date(default=fields.Date.context_today, tracking=True)
project_id = fields.Many2one('project.project', required=True)
name_cropped = fields.Char(compute="_compute_name_cropped")
@api.depends('status')
def _compute_color(self):
for update in self:
update.color = STATUS_COLOR[update.status]
@api.depends('progress')
def _compute_progress_percentage(self):
for u in self:
u.progress_percentage = u.progress / 100
@api.depends('name')
def _compute_name_cropped(self):
for u in self:
u.name_cropped = (u.name[:57] + '...') if len(u.name) > 60 else u.name
# ---------------------------------
# ORM Override
# ---------------------------------
@api.model
def create(self, vals):
update = super().create(vals)
update.project_id.sudo().last_update_id = update
return update
def unlink(self):
projects = self.project_id
res = super().unlink()
for project in projects:
project.last_update_id = self.search([('project_id', "=", project.id)], order="date desc", limit=1)
return res
# ---------------------------------
# Build default description
# ---------------------------------
@api.model
def _build_description(self, project):
template = self.env.ref('project.project_update_default_description')
return template._render(self._get_template_values(project), engine='ir.qweb')
@api.model
def _get_template_values(self, project):
milestones = self._get_milestone_values(project)
return {
'user': self.env.user,
'project': project,
'show_activities': milestones['show_section'],
'milestones': milestones,
'format_lang': lambda value, digits: formatLang(self.env, value, digits=digits),
}
@api.model
def _get_milestone_values(self, project):
Milestone = self.env['project.milestone']
list_milestones = Milestone.search(
[('project_id', '=', project.id),
'|', ('deadline', '<', fields.Date.context_today(self) + relativedelta(years=1)), ('deadline', '=', False)])._get_data_list()
updated_milestones = self._get_last_updated_milestone(project)
domain = [('project_id', '=', project.id)]
if project.last_update_id.create_date:
domain = expression.AND([domain, [('create_date', '>', project.last_update_id.create_date)]])
created_milestones = Milestone.search(domain)._get_data_list()
return {
'show_section': (list_milestones or updated_milestones or created_milestones) and True or False,
'list': list_milestones,
'updated': updated_milestones,
'last_update_date': project.last_update_id.create_date or None,
'created': created_milestones,
}
@api.model
def _get_last_updated_milestone(self, project):
query = """
SELECT DISTINCT pm.id as milestone_id,
pm.deadline as deadline,
FIRST_VALUE(old_value_datetime::date) OVER w_partition as old_value,
pm.deadline as new_value
FROM mail_message mm
INNER JOIN mail_tracking_value mtv
ON mm.id = mtv.mail_message_id
INNER JOIN ir_model_fields imf
ON mtv.field = imf.id
AND imf.model = 'project.milestone'
AND imf.name = 'deadline'
INNER JOIN project_milestone pm
ON mm.res_id = pm.id
WHERE mm.model = 'project.milestone'
AND mm.message_type = 'notification'
AND pm.project_id = %(project_id)s
"""
if project.last_update_id.create_date:
query = query + "AND mm.date > %(last_update_date)s"
query = query + """
WINDOW w_partition AS (
PARTITION BY pm.id
ORDER BY mm.date ASC
)
ORDER BY pm.deadline ASC
LIMIT 1;
"""
query_params = {'project_id': project.id}
if project.last_update_id.create_date:
query_params['last_update_date'] = project.last_update_id.create_date
self.env.cr.execute(query, query_params)
results = self.env.cr.dictfetchall()
mapped_result = {res['milestone_id']: {'new_value': res['new_value'], 'old_value': res['old_value']} for res in results}
milestones = self.env['project.milestone'].search([('id', 'in', list(mapped_result.keys()))])
return [{
**milestone._get_data(),
'new_value': mapped_result[milestone.id]['new_value'],
'old_value': mapped_result[milestone.id]['old_value'],
} for milestone in milestones]
| 42.86747
| 7,116
|
2,842
|
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 ProjectCollaborator(models.Model):
_name = 'project.collaborator'
_description = 'Collaborators in project shared'
project_id = fields.Many2one('project.project', 'Project Shared', domain=[('privacy_visibility', '=', 'portal')], required=True, readonly=True)
partner_id = fields.Many2one('res.partner', 'Collaborator', required=True, readonly=True)
_sql_constraints = [
('unique_collaborator', 'UNIQUE(project_id, partner_id)', 'A collaborator cannot be selected more than once in the project sharing access. Please remove duplicate(s) and try again.'),
]
def name_get(self):
collaborator_search_read = self.search_read([('id', 'in', self.ids)], ['id', 'project_id', 'partner_id'])
return [(collaborator['id'], '%s - %s' % (collaborator['project_id'][1], collaborator['partner_id'][1])) for collaborator in collaborator_search_read]
@api.model_create_multi
def create(self, vals_list):
collaborator = self.env['project.collaborator'].search([], limit=1)
project_collaborators = super().create(vals_list)
if not collaborator:
self._toggle_project_sharing_portal_rules(True)
return project_collaborators
def unlink(self):
res = super().unlink()
# Check if it remains at least a collaborator in all shared projects.
collaborator = self.env['project.collaborator'].search([], limit=1)
if not collaborator: # then disable the project sharing feature
self._toggle_project_sharing_portal_rules(False)
return res
@api.model
def _toggle_project_sharing_portal_rules(self, active):
""" Enable/disable project sharing feature
When the first collaborator is added in the model then we need to enable the feature.
In the inverse case, if no collaborator is stored in the model then we disable the feature.
To enable/disable the feature, we just need to enable/disable the ir.model.access and ir.rule
added to portal user that we do not want to give when we know the project sharing is unused.
:param active: contains boolean value, True to enable the project sharing feature, otherwise we disable the feature.
"""
access_project_sharing_portal = self.env.ref('project.access_project_sharing_task_portal').sudo()
if access_project_sharing_portal.active != active:
access_project_sharing_portal.write({'active': active})
task_portal_ir_rule = self.env.ref('project.project_task_rule_portal_project_sharing').sudo()
if task_portal_ir_rule.active != active:
task_portal_ir_rule.write({'active': active})
| 51.672727
| 2,842
|
730
|
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 ProjectProjectStage(models.Model):
_name = 'project.project.stage'
_description = 'Project Stage'
_order = 'sequence, id'
active = fields.Boolean(default=True)
sequence = fields.Integer(default=50)
name = fields.Char(required=True, translate=True)
mail_template_id = fields.Many2one('mail.template', string='Email Template', domain=[('model', '=', 'project.project')],
help="If set, an email will be sent to the customer when the project reaches this step.")
fold = fields.Boolean('Folded in Kanban', help="This stage is folded in the kanban view.")
| 45.625
| 730
|
420
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class IrUiMenu(models.Model):
_inherit = 'ir.ui.menu'
def _load_menus_blacklist(self):
res = super()._load_menus_blacklist()
if self.env.user.has_group('project.group_project_stages'):
res.append(self.env.ref('project.menu_projects').id)
return res
| 30
| 420
|
12,579
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.exceptions import ValidationError
from calendar import monthrange
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, rruleset, DAILY, WEEKLY, MONTHLY, YEARLY, MO, TU, WE, TH, FR, SA, SU
MONTHS = {
'january': 31,
'february': 28,
'march': 31,
'april': 30,
'may': 31,
'june': 30,
'july': 31,
'august': 31,
'september': 30,
'october': 31,
'november': 30,
'december': 31,
}
DAYS = {
'mon': MO,
'tue': TU,
'wed': WE,
'thu': TH,
'fri': FR,
'sat': SA,
'sun': SU,
}
WEEKS = {
'first': 1,
'second': 2,
'third': 3,
'last': 4,
}
class ProjectTaskRecurrence(models.Model):
_name = 'project.task.recurrence'
_description = 'Task Recurrence'
task_ids = fields.One2many('project.task', 'recurrence_id', copy=False)
next_recurrence_date = fields.Date()
recurrence_left = fields.Integer(string="Number of Tasks Left to Create", copy=False)
repeat_interval = fields.Integer(string='Repeat Every', default=1)
repeat_unit = fields.Selection([
('day', 'Days'),
('week', 'Weeks'),
('month', 'Months'),
('year', 'Years'),
], default='week')
repeat_type = fields.Selection([
('forever', 'Forever'),
('until', 'End Date'),
('after', 'Number of Repetitions'),
], default="forever", string="Until")
repeat_until = fields.Date(string="End Date")
repeat_number = fields.Integer(string="Repetitions")
repeat_on_month = fields.Selection([
('date', 'Date of the Month'),
('day', 'Day of the Month'),
])
repeat_on_year = fields.Selection([
('date', 'Date of the Year'),
('day', 'Day of the Year'),
])
mon = fields.Boolean(string="Mon")
tue = fields.Boolean(string="Tue")
wed = fields.Boolean(string="Wed")
thu = fields.Boolean(string="Thu")
fri = fields.Boolean(string="Fri")
sat = fields.Boolean(string="Sat")
sun = fields.Boolean(string="Sun")
repeat_day = fields.Selection([
(str(i), str(i)) for i in range(1, 32)
])
repeat_week = fields.Selection([
('first', 'First'),
('second', 'Second'),
('third', 'Third'),
('last', 'Last'),
])
repeat_weekday = fields.Selection([
('mon', 'Monday'),
('tue', 'Tuesday'),
('wed', 'Wednesday'),
('thu', 'Thursday'),
('fri', 'Friday'),
('sat', 'Saturday'),
('sun', 'Sunday'),
], string='Day Of The Week', readonly=False)
repeat_month = fields.Selection([
('january', 'January'),
('february', 'February'),
('march', 'March'),
('april', 'April'),
('may', 'May'),
('june', 'June'),
('july', 'July'),
('august', 'August'),
('september', 'September'),
('october', 'October'),
('november', 'November'),
('december', 'December'),
])
@api.constrains('repeat_unit', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
def _check_recurrence_days(self):
for project in self.filtered(lambda p: p.repeat_unit == 'week'):
if not any([project.mon, project.tue, project.wed, project.thu, project.fri, project.sat, project.sun]):
raise ValidationError('You should select a least one day')
@api.constrains('repeat_interval')
def _check_repeat_interval(self):
if self.filtered(lambda t: t.repeat_interval <= 0):
raise ValidationError('The interval should be greater than 0')
@api.constrains('repeat_number', 'repeat_type')
def _check_repeat_number(self):
if self.filtered(lambda t: t.repeat_type == 'after' and t.repeat_number <= 0):
raise ValidationError('Should repeat at least once')
@api.constrains('repeat_type', 'repeat_until')
def _check_repeat_until_date(self):
today = fields.Date.today()
if self.filtered(lambda t: t.repeat_type == 'until' and t.repeat_until < today):
raise ValidationError('The end date should be in the future')
@api.constrains('repeat_unit', 'repeat_on_month', 'repeat_day', 'repeat_type', 'repeat_until')
def _check_repeat_until_month(self):
if self.filtered(lambda r: r.repeat_type == 'until' and r.repeat_unit == 'month' and r.repeat_until and r.repeat_on_month == 'date'
and int(r.repeat_day) > r.repeat_until.day and monthrange(r.repeat_until.year, r.repeat_until.month)[1] != r.repeat_until.day):
raise ValidationError('The end date should be after the day of the month or the last day of the month')
@api.model
def _get_recurring_fields(self):
return ['message_partner_ids', 'company_id', 'description', 'displayed_image_id', 'email_cc',
'parent_id', 'partner_email', 'partner_id', 'partner_phone', 'planned_hours',
'project_id', 'display_project_id', 'project_privacy_visibility', 'sequence', 'tag_ids', 'recurrence_id',
'name', 'recurring_task', 'analytic_account_id']
def _get_weekdays(self, n=1):
self.ensure_one()
if self.repeat_unit == 'week':
return [fn(n) for day, fn in DAYS.items() if self[day]]
return [DAYS.get(self.repeat_weekday)(n)]
@api.model
def _get_next_recurring_dates(self, date_start, repeat_interval, repeat_unit, repeat_type, repeat_until, repeat_on_month, repeat_on_year, weekdays, repeat_day, repeat_week, repeat_month, **kwargs):
count = kwargs.get('count', 1)
rrule_kwargs = {'interval': repeat_interval or 1, 'dtstart': date_start}
repeat_day = int(repeat_day)
start = False
dates = []
if repeat_type == 'until':
rrule_kwargs['until'] = repeat_until if repeat_until else fields.Date.today()
else:
rrule_kwargs['count'] = count
if repeat_unit == 'week'\
or (repeat_unit == 'month' and repeat_on_month == 'day')\
or (repeat_unit == 'year' and repeat_on_year == 'day'):
rrule_kwargs['byweekday'] = weekdays
if repeat_unit == 'day':
rrule_kwargs['freq'] = DAILY
elif repeat_unit == 'month':
rrule_kwargs['freq'] = MONTHLY
if repeat_on_month == 'date':
start = date_start - relativedelta(days=1)
start = start.replace(day=min(repeat_day, monthrange(start.year, start.month)[1]))
if start < date_start:
# Ensure the next recurrence is in the future
start += relativedelta(months=repeat_interval)
start = start.replace(day=min(repeat_day, monthrange(start.year, start.month)[1]))
can_generate_date = (lambda: start <= repeat_until) if repeat_type == 'until' else (lambda: len(dates) < count)
while can_generate_date():
dates.append(start)
start += relativedelta(months=repeat_interval)
start = start.replace(day=min(repeat_day, monthrange(start.year, start.month)[1]))
return dates
elif repeat_unit == 'year':
rrule_kwargs['freq'] = YEARLY
month = list(MONTHS.keys()).index(repeat_month) + 1 if repeat_month else date_start.month
repeat_month = repeat_month or list(MONTHS.keys())[month - 1]
rrule_kwargs['bymonth'] = month
if repeat_on_year == 'date':
rrule_kwargs['bymonthday'] = min(repeat_day, MONTHS.get(repeat_month))
rrule_kwargs['bymonth'] = month
else:
rrule_kwargs['freq'] = WEEKLY
rules = rrule(**rrule_kwargs)
return list(rules) if rules else []
def _new_task_values(self, task):
self.ensure_one()
fields_to_copy = self._get_recurring_fields()
task_values = task.read(fields_to_copy).pop()
create_values = {
field: value[0] if isinstance(value, tuple) else value for field, value in task_values.items()
}
create_values['stage_id'] = task.project_id.type_ids[0].id if task.project_id.type_ids else task.stage_id.id
create_values['user_ids'] = False
return create_values
def _create_subtasks(self, task, new_task, depth=3):
if depth == 0 or not task.child_ids:
return
children = []
child_recurrence = []
# copy the subtasks of the original task
for child in task.child_ids:
if child.recurrence_id and child.recurrence_id.id in child_recurrence:
# The subtask has been generated by another subtask in the childs
# This subtasks is skipped as it will be meant to be a copy of the first
# task of the recurrence we just created.
continue
child_values = self._new_task_values(child)
child_values['parent_id'] = new_task.id
if child.recurrence_id:
# The subtask has a recurrence, the recurrence is thus copied rather than used
# with raw reference in order to decouple the recurrence of the initial subtask
# from the recurrence of the copied subtask which will live its own life and generate
# subsequent tasks.
child_recurrence += [child.recurrence_id.id]
child_values['recurrence_id'] = child.recurrence_id.copy().id
if child.child_ids and depth > 1:
# If child has childs in the following layer and we will have to copy layer, we have to
# first create the new_child record in order to have a new parent_id reference for the
# "grandchildren" tasks
new_child = self.env['project.task'].sudo().create(child_values)
self._create_subtasks(child, new_child, depth=depth - 1)
else:
children.append(child_values)
children_tasks = self.env['project.task'].sudo().create(children)
def _create_next_task(self):
for recurrence in self:
task = max(recurrence.sudo().task_ids, key=lambda t: t.id)
create_values = recurrence._new_task_values(task)
new_task = self.env['project.task'].sudo().create(create_values)
recurrence._create_subtasks(task, new_task, depth=3)
def _set_next_recurrence_date(self):
today = fields.Date.today()
tomorrow = today + relativedelta(days=1)
for recurrence in self.filtered(
lambda r:
r.repeat_type == 'after' and r.recurrence_left >= 0
or r.repeat_type == 'until' and r.repeat_until >= today
or r.repeat_type == 'forever'
):
if recurrence.repeat_type == 'after' and recurrence.recurrence_left == 0:
recurrence.next_recurrence_date = False
else:
next_date = self._get_next_recurring_dates(tomorrow, recurrence.repeat_interval, recurrence.repeat_unit, recurrence.repeat_type, recurrence.repeat_until, recurrence.repeat_on_month, recurrence.repeat_on_year, recurrence._get_weekdays(), recurrence.repeat_day, recurrence.repeat_week, recurrence.repeat_month, count=1)
recurrence.next_recurrence_date = next_date[0] if next_date else False
@api.model
def _cron_create_recurring_tasks(self):
if not self.env.user.has_group('project.group_project_recurring_tasks'):
return
today = fields.Date.today()
recurring_today = self.search([('next_recurrence_date', '<=', today)])
recurring_today._create_next_task()
for recurrence in recurring_today.filtered(lambda r: r.repeat_type == 'after'):
recurrence.recurrence_left -= 1
recurring_today._set_next_recurrence_date()
@api.model
def create(self, vals):
if vals.get('repeat_number'):
vals['recurrence_left'] = vals.get('repeat_number')
res = super(ProjectTaskRecurrence, self).create(vals)
res._set_next_recurrence_date()
return res
def write(self, vals):
if vals.get('repeat_number'):
vals['recurrence_left'] = vals.get('repeat_number')
res = super(ProjectTaskRecurrence, self).write(vals)
if 'next_recurrence_date' not in vals:
self._set_next_recurrence_date()
return res
| 42.353535
| 12,579
|
783
|
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 ProjectTaskStagePersonal(models.Model):
_name = 'project.task.stage.personal'
_description = 'Personal Task Stage'
_table = 'project_task_user_rel'
_rec_name = 'stage_id'
task_id = fields.Many2one('project.task', required=True, ondelete='cascade', index=True)
user_id = fields.Many2one('res.users', required=True, ondelete='cascade', index=True)
stage_id = fields.Many2one('project.task.type', domain="[('user_id', '=', user_id)]", ondelete='restrict')
_sql_constraints = [
('project_personal_stage_unique', 'UNIQUE (task_id, user_id)', 'A task can only have a single personal stage per user.'),
]
| 43.5
| 783
|
3,073
|
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'
module_project_forecast = fields.Boolean(string="Planning")
module_hr_timesheet = fields.Boolean(string="Task Logs")
group_subtask_project = fields.Boolean("Sub-tasks", implied_group="project.group_subtask_project")
group_project_rating = fields.Boolean("Customer Ratings", implied_group='project.group_project_rating')
group_project_stages = fields.Boolean("Project Stages", implied_group="project.group_project_stages")
group_project_recurring_tasks = fields.Boolean("Recurring Tasks", implied_group="project.group_project_recurring_tasks")
group_project_task_dependencies = fields.Boolean("Task Dependencies", implied_group="project.group_project_task_dependencies")
@api.model
def _get_basic_project_domain(self):
return []
def set_values(self):
# Ensure that settings on existing projects match the above fields
projects = self.env["project.project"].search([])
basic_projects = projects.filtered_domain(self._get_basic_project_domain())
features = {
# key: (config_flag, is_global), value: project_flag
("group_project_rating", True): "rating_active",
("group_project_recurring_tasks", True): "allow_recurring_tasks",
("group_subtask_project", False): "allow_subtasks",
("group_project_task_dependencies", False): "allow_task_dependencies",
}
for (config_flag, is_global), project_flag in features.items():
config_flag_global = f"project.{config_flag}"
config_feature_enabled = self[config_flag]
if self.user_has_groups(config_flag_global) != config_feature_enabled:
if config_feature_enabled and not is_global:
basic_projects[project_flag] = config_feature_enabled
else:
projects[project_flag] = config_feature_enabled
# Hide the task dependency changes subtype when the dependency setting is disabled
task_dep_change_subtype_id = self.env.ref('project.mt_task_dependency_change')
project_task_dep_change_subtype_id = self.env.ref('project.mt_project_task_dependency_change')
if task_dep_change_subtype_id.hidden != (not self['group_project_task_dependencies']):
task_dep_change_subtype_id.hidden = not self['group_project_task_dependencies']
project_task_dep_change_subtype_id.hidden = not self['group_project_task_dependencies']
# Hide Project Stage Changed mail subtype according to the settings
project_stage_change_mail_type = self.env.ref('project.mt_project_stage_change')
if project_stage_change_mail_type.hidden == self['group_project_stages']:
project_stage_change_mail_type.hidden = not self['group_project_stages']
super(ResConfigSettings, self).set_values()
| 55.872727
| 3,073
|
276
|
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 AccountAnalyticTag(models.Model):
_inherit = 'account.analytic.tag'
task_ids = fields.Many2many('project.task', string='Tasks')
| 30.666667
| 276
|
2,255
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class AccountAnalyticAccount(models.Model):
_inherit = 'account.analytic.account'
_description = 'Analytic Account'
project_ids = fields.One2many('project.project', 'analytic_account_id', string='Projects')
project_count = fields.Integer("Project Count", compute='_compute_project_count')
@api.depends('project_ids')
def _compute_project_count(self):
project_data = self.env['project.project'].read_group([('analytic_account_id', 'in', self.ids)], ['analytic_account_id'], ['analytic_account_id'])
mapping = {m['analytic_account_id'][0]: m['analytic_account_id_count'] for m in project_data}
for account in self:
account.project_count = mapping.get(account.id, 0)
@api.constrains('company_id')
def _check_company_id(self):
for record in self:
if record.company_id and not all(record.company_id == c for c in record.project_ids.mapped('company_id')):
raise UserError(_('You cannot change the company of an analytic account if it is related to a project.'))
@api.ondelete(at_uninstall=False)
def _unlink_except_existing_tasks(self):
projects = self.env['project.project'].search([('analytic_account_id', 'in', self.ids)])
has_tasks = self.env['project.task'].search_count([('project_id', 'in', projects.ids)])
if has_tasks:
raise UserError(_('Please remove existing tasks in the project linked to the accounts you want to delete.'))
def action_view_projects(self):
kanban_view_id = self.env.ref('project.view_project_kanban').id
result = {
"type": "ir.actions.act_window",
"res_model": "project.project",
"views": [[kanban_view_id, "kanban"], [False, "form"]],
"domain": [['analytic_account_id', '=', self.id]],
"context": {"create": False},
"name": "Projects",
}
if len(self.project_ids) == 1:
result['views'] = [(False, "form")]
result['res_id'] = self.project_ids.id
return result
| 46.979167
| 2,255
|
1,996
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.tools import email_normalize
class ResPartner(models.Model):
""" Inherits partner and adds Tasks information in the partner form """
_inherit = 'res.partner'
task_ids = fields.One2many('project.task', 'partner_id', string='Tasks')
task_count = fields.Integer(compute='_compute_task_count', string='# Tasks')
def _compute_task_count(self):
# retrieve all children partners and prefetch 'parent_id' on them
all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)])
all_partners.read(['parent_id'])
task_data = self.env['project.task'].read_group(
domain=[('partner_id', 'in', all_partners.ids)],
fields=['partner_id'], groupby=['partner_id']
)
self.task_count = 0
for group in task_data:
partner = self.browse(group['partner_id'][0])
while partner:
if partner in self:
partner.task_count += group['partner_id_count']
partner = partner.parent_id
# Deprecated: remove me in MASTER
def _create_portal_users(self):
partners_without_user = self.filtered(lambda partner: not partner.user_ids)
if not partners_without_user:
return self.env['res.users']
created_users = self.env['res.users']
for partner in partners_without_user:
created_users += self.env['res.users'].with_context(no_reset_password=True).sudo()._create_user_from_template({
'email': email_normalize(partner.email),
'login': email_normalize(partner.email),
'partner_id': partner.id,
'company_id': self.env.company.id,
'company_ids': [(6, 0, self.env.company.ids)],
'active': True,
})
return created_users
| 41.583333
| 1,996
|
2,134
|
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 ProjectMilestone(models.Model):
_name = 'project.milestone'
_description = "Project Milestone"
_inherit = ['mail.thread']
_order = 'deadline, is_reached desc, name'
def _get_default_project_id(self):
return self.env.context.get('default_project_id') or self.env.context.get('active_id')
name = fields.Char(required=True)
project_id = fields.Many2one('project.project', required=True, default=_get_default_project_id)
deadline = fields.Date(tracking=True)
is_reached = fields.Boolean(string="Reached", default=False)
reached_date = fields.Date(compute='_compute_reached_date', store=True)
# computed non-stored fields
is_deadline_exceeded = fields.Boolean(compute="_compute_is_deadline_exceeded")
is_deadline_future = fields.Boolean(compute="_compute_is_deadline_future")
@api.depends('is_reached')
def _compute_reached_date(self):
for ms in self:
ms.reached_date = ms.is_reached and fields.Date.context_today(self)
@api.depends('is_reached', 'deadline')
def _compute_is_deadline_exceeded(self):
today = fields.Date.context_today(self)
for ms in self:
ms.is_deadline_exceeded = not ms.is_reached and ms.deadline and ms.deadline < today
@api.depends('deadline')
def _compute_is_deadline_future(self):
for ms in self:
ms.is_deadline_future = ms.deadline and ms.deadline > fields.Date.context_today(self)
def toggle_is_reached(self, is_reached):
self.ensure_one()
self.update({'is_reached': is_reached})
return self._get_data()
@api.model
def _get_fields_to_export(self):
return ['id', 'name', 'deadline', 'is_reached', 'reached_date', 'is_deadline_exceeded', 'is_deadline_future']
def _get_data(self):
self.ensure_one()
return {field: self[field] for field in self._get_fields_to_export()}
def _get_data_list(self):
return [ms._get_data() for ms in self]
| 38.8
| 2,134
|
114,886
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import json
from collections import defaultdict
from datetime import timedelta, datetime
from random import randint
from odoo import api, Command, fields, models, tools, SUPERUSER_ID, _, _lt
from odoo.addons.web_editor.controllers.main import handle_history_divergence
from odoo.exceptions import UserError, ValidationError, AccessError
from odoo.tools import format_amount
from odoo.osv.expression import OR, TRUE_LEAF, FALSE_LEAF
from .project_task_recurrence import DAYS, WEEKS
from .project_update import STATUS_COLOR
from odoo.tools.misc import get_lang
PROJECT_TASK_READABLE_FIELDS = {
'id',
'active',
'description',
'priority',
'kanban_state_label',
'project_id',
'display_project_id',
'color',
'partner_is_company',
'commercial_partner_id',
'allow_subtasks',
'subtask_count',
'child_text',
'is_closed',
'email_from',
'create_date',
'write_date',
'company_id',
'displayed_image_id',
'display_name',
'portal_user_names',
'legend_normal',
'legend_blocked',
'legend_done',
'user_ids',
}
PROJECT_TASK_WRITABLE_FIELDS = {
'name',
'partner_id',
'date_deadline',
'tag_ids',
'sequence',
'stage_id',
'kanban_state',
'child_ids',
'parent_id',
'priority',
}
class ProjectTaskType(models.Model):
_name = 'project.task.type'
_description = 'Task Stage'
_order = 'sequence, id'
def _get_default_project_ids(self):
default_project_id = self.env.context.get('default_project_id')
return [default_project_id] if default_project_id else None
active = fields.Boolean('Active', default=True)
name = fields.Char(string='Name', required=True, translate=True)
description = fields.Text(translate=True)
sequence = fields.Integer(default=1)
project_ids = fields.Many2many('project.project', 'project_task_type_rel', 'type_id', 'project_id', string='Projects',
default=lambda self: self._get_default_project_ids())
legend_blocked = fields.Char(
'Red Kanban Label', default=lambda s: _('Blocked'), translate=True, required=True,
help='Override the default value displayed for the blocked state for kanban selection when the task or issue is in that stage.')
legend_done = fields.Char(
'Green Kanban Label', default=lambda s: _('Ready'), translate=True, required=True,
help='Override the default value displayed for the done state for kanban selection when the task or issue is in that stage.')
legend_normal = fields.Char(
'Grey Kanban Label', default=lambda s: _('In Progress'), translate=True, required=True,
help='Override the default value displayed for the normal state for kanban selection when the task or issue is in that stage.')
mail_template_id = fields.Many2one(
'mail.template',
string='Email Template',
domain=[('model', '=', 'project.task')],
help="If set, an email will be sent to the customer when the task or issue reaches this step.")
fold = fields.Boolean(string='Folded in Kanban',
help='This stage is folded in the kanban view when there are no records in that stage to display.')
rating_template_id = fields.Many2one(
'mail.template',
string='Rating Email Template',
domain=[('model', '=', 'project.task')],
help="If set and if the project's rating configuration is 'Rating when changing stage', then an email will be sent to the customer when the task reaches this step.")
auto_validation_kanban_state = fields.Boolean('Automatic kanban status', default=False,
help="Automatically modify the kanban state when the customer replies to the feedback for this stage.\n"
" * Good feedback from the customer will update the kanban state to 'ready for the new stage' (green bullet).\n"
" * Neutral or bad feedback will set the kanban state to 'blocked' (red bullet).\n")
is_closed = fields.Boolean('Closing Stage', help="Tasks in this stage are considered as closed.")
disabled_rating_warning = fields.Text(compute='_compute_disabled_rating_warning')
user_id = fields.Many2one('res.users', 'Stage Owner', index=True)
def unlink_wizard(self, stage_view=False):
self = self.with_context(active_test=False)
# retrieves all the projects with a least 1 task in that stage
# a task can be in a stage even if the project is not assigned to the stage
readgroup = self.with_context(active_test=False).env['project.task'].read_group([('stage_id', 'in', self.ids)], ['project_id'], ['project_id'])
project_ids = list(set([project['project_id'][0] for project in readgroup] + self.project_ids.ids))
wizard = self.with_context(project_ids=project_ids).env['project.task.type.delete.wizard'].create({
'project_ids': project_ids,
'stage_ids': self.ids
})
context = dict(self.env.context)
context['stage_view'] = stage_view
return {
'name': _('Delete Stage'),
'view_mode': 'form',
'res_model': 'project.task.type.delete.wizard',
'views': [(self.env.ref('project.view_project_task_type_delete_wizard').id, 'form')],
'type': 'ir.actions.act_window',
'res_id': wizard.id,
'target': 'new',
'context': context,
}
def write(self, vals):
if 'active' in vals and not vals['active']:
self.env['project.task'].search([('stage_id', 'in', self.ids)]).write({'active': False})
return super(ProjectTaskType, self).write(vals)
@api.depends('project_ids', 'project_ids.rating_active')
def _compute_disabled_rating_warning(self):
for stage in self:
disabled_projects = stage.project_ids.filtered(lambda p: not p.rating_active)
if disabled_projects:
stage.disabled_rating_warning = '\n'.join('- %s' % p.name for p in disabled_projects)
else:
stage.disabled_rating_warning = False
@api.constrains('user_id', 'project_ids')
def _check_personal_stage_not_linked_to_projects(self):
if any(stage.user_id and stage.project_ids for stage in self):
raise UserError(_('A personal stage cannot be linked to a project because it is only visible to its corresponding user.'))
def remove_personal_stage(self):
"""
Remove a personal stage, tasks using that stage will move to the first
stage with a lower priority if it exists higher if not.
This method will not allow to delete the last personal stage.
Having no personal_stage_type_id makes the task not appear when grouping by personal stage.
"""
self.ensure_one()
assert self.user_id == self.env.user or self.env.su
users_personal_stages = self.env['project.task.type']\
.search([('user_id', '=', self.user_id.id)], order='sequence DESC')
if len(users_personal_stages) == 1:
raise ValidationError(_("You should at least have one personal stage. Create a new stage to which the tasks can be transferred after this one is deleted."))
# Find the most suitable stage, they are already sorted by sequence
new_stage = self.env['project.task.type']
for stage in users_personal_stages:
if stage == self:
continue
if stage.sequence > self.sequence:
new_stage = stage
elif stage.sequence <= self.sequence:
new_stage = stage
break
self.env['project.task.stage.personal'].search([('stage_id', '=', self.id)]).write({
'stage_id': new_stage.id,
})
self.unlink()
class Project(models.Model):
_name = "project.project"
_description = "Project"
_inherit = ['portal.mixin', 'mail.alias.mixin', 'mail.thread', 'mail.activity.mixin', 'rating.parent.mixin']
_order = "sequence, name, id"
_rating_satisfaction_days = False # takes all existing ratings
_check_company_auto = True
def _compute_attached_docs_count(self):
self.env.cr.execute(
"""
WITH docs AS (
SELECT res_id as id, count(*) as count
FROM ir_attachment
WHERE res_model = 'project.project'
AND res_id IN %(project_ids)s
GROUP BY res_id
UNION ALL
SELECT t.project_id as id, count(*) as count
FROM ir_attachment a
JOIN project_task t ON a.res_model = 'project.task' AND a.res_id = t.id
WHERE t.project_id IN %(project_ids)s
GROUP BY t.project_id
)
SELECT id, sum(count)
FROM docs
GROUP BY id
""",
{"project_ids": tuple(self.ids)}
)
docs_count = dict(self.env.cr.fetchall())
for project in self:
project.doc_count = docs_count.get(project.id, 0)
def _compute_task_count(self):
task_data = self.env['project.task'].read_group(
[('project_id', 'in', self.ids),
'|',
('stage_id.fold', '=', False),
('stage_id', '=', False)],
['project_id', 'display_project_id:count'], ['project_id'])
result_wo_subtask = defaultdict(int)
result_with_subtasks = defaultdict(int)
for data in task_data:
result_wo_subtask[data['project_id'][0]] += data['display_project_id']
result_with_subtasks[data['project_id'][0]] += data['project_id_count']
for project in self:
project.task_count = result_wo_subtask[project.id]
project.task_count_with_subtasks = result_with_subtasks[project.id]
def attachment_tree_view(self):
action = self.env['ir.actions.act_window']._for_xml_id('base.action_attachment')
action['domain'] = str([
'|',
'&',
('res_model', '=', 'project.project'),
('res_id', 'in', self.ids),
'&',
('res_model', '=', 'project.task'),
('res_id', 'in', self.task_ids.ids)
])
action['context'] = "{'default_res_model': '%s','default_res_id': %d}" % (self._name, self.id)
return action
def _default_stage_id(self):
# Since project stages are order by sequence first, this should fetch the one with the lowest sequence number.
return self.env['project.project.stage'].search([], limit=1)
def _compute_is_favorite(self):
for project in self:
project.is_favorite = self.env.user in project.favorite_user_ids
def _inverse_is_favorite(self):
favorite_projects = not_fav_projects = self.env['project.project'].sudo()
for project in self:
if self.env.user in project.favorite_user_ids:
favorite_projects |= project
else:
not_fav_projects |= project
# Project User has no write access for project.
not_fav_projects.write({'favorite_user_ids': [(4, self.env.uid)]})
favorite_projects.write({'favorite_user_ids': [(3, self.env.uid)]})
def _get_default_favorite_user_ids(self):
return [(6, 0, [self.env.uid])]
@api.model
def _read_group_stage_ids(self, stages, domain, order):
return self.env['project.project.stage'].search([], order=order)
name = fields.Char("Name", index=True, required=True, tracking=True, translate=True)
description = fields.Html()
active = fields.Boolean(default=True,
help="If the active field is set to False, it will allow you to hide the project without removing it.")
sequence = fields.Integer(default=10, help="Gives the sequence order when displaying a list of Projects.")
partner_id = fields.Many2one('res.partner', string='Customer', auto_join=True, tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
partner_email = fields.Char(
compute='_compute_partner_email', inverse='_inverse_partner_email',
string='Email', readonly=False, store=True, copy=False)
partner_phone = fields.Char(
compute='_compute_partner_phone', inverse='_inverse_partner_phone',
string="Phone", readonly=False, store=True, copy=False)
commercial_partner_id = fields.Many2one(related="partner_id.commercial_partner_id")
company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company)
currency_id = fields.Many2one('res.currency', related="company_id.currency_id", string="Currency", readonly=True)
analytic_account_id = fields.Many2one('account.analytic.account', string="Analytic Account", copy=False, ondelete='set null',
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", check_company=True,
help="Analytic account to which this project is linked for financial management. "
"Use an analytic account to record cost and revenue on your project.")
analytic_account_balance = fields.Monetary(related="analytic_account_id.balance")
favorite_user_ids = fields.Many2many(
'res.users', 'project_favorite_user_rel', 'project_id', 'user_id',
default=_get_default_favorite_user_ids,
string='Members')
is_favorite = fields.Boolean(compute='_compute_is_favorite', inverse='_inverse_is_favorite',
string='Show Project on Dashboard',
help="Whether this project should be displayed on your dashboard.")
label_tasks = fields.Char(string='Use Tasks as', default='Tasks', help="Label used for the tasks of the project.", translate=True)
tasks = fields.One2many('project.task', 'project_id', string="Task Activities")
resource_calendar_id = fields.Many2one(
'resource.calendar', string='Working Time',
related='company_id.resource_calendar_id')
type_ids = fields.Many2many('project.task.type', 'project_task_type_rel', 'project_id', 'type_id', string='Tasks Stages')
task_count = fields.Integer(compute='_compute_task_count', string="Task Count")
task_count_with_subtasks = fields.Integer(compute='_compute_task_count')
task_ids = fields.One2many('project.task', 'project_id', string='Tasks',
domain=['|', ('stage_id.fold', '=', False), ('stage_id', '=', False)])
color = fields.Integer(string='Color Index')
user_id = fields.Many2one('res.users', string='Project Manager', default=lambda self: self.env.user, tracking=True)
alias_enabled = fields.Boolean(string='Use Email Alias', compute='_compute_alias_enabled', readonly=False)
alias_id = fields.Many2one('mail.alias', string='Alias', ondelete="restrict", required=True,
help="Internal email associated with this project. Incoming emails are automatically synchronized "
"with Tasks (or optionally Issues if the Issue Tracker module is installed).")
alias_value = fields.Char(string='Alias email', compute='_compute_alias_value')
privacy_visibility = fields.Selection([
('followers', 'Invited employees'),
('employees', 'All employees'),
('portal', 'Invited portal users and all employees'),
],
string='Visibility', required=True,
default='portal',
help="People to whom this project and its tasks will be visible.\n\n"
"- Invited internal users: when following a project, internal users will get access to all of its tasks without distinction. "
"Otherwise, they will only get access to the specific tasks they are following.\n "
"A user with the project > administrator access right level can still access this project and its tasks, even if they are not explicitly part of the followers.\n\n"
"- All internal users: all internal users can access the project and all of its tasks without distinction.\n\n"
"- Invited portal users and all internal users: all internal users can access the project and all of its tasks without distinction.\n"
"When following a project, portal users will get access to all of its tasks without distinction. Otherwise, they will only get access to the specific tasks they are following.\n\n"
"When a project is shared in read-only, the portal user is redirected to their portal. They can view the tasks, but not edit them.\n"
"When a project is shared in edit, the portal user is redirected to the kanban and list views of the tasks. They can modify a selected number of fields on the tasks.\n\n"
"In any case, an internal user with no project access rights can still access a task, "
"provided that they are given the corresponding URL (and that they are part of the followers if the project is private).")
doc_count = fields.Integer(compute='_compute_attached_docs_count', string="Number of documents attached")
date_start = fields.Date(string='Start Date')
date = fields.Date(string='Expiration Date', index=True, tracking=True)
allow_subtasks = fields.Boolean('Sub-tasks', default=lambda self: self.env.user.has_group('project.group_subtask_project'))
allow_recurring_tasks = fields.Boolean('Recurring Tasks', default=lambda self: self.env.user.has_group('project.group_project_recurring_tasks'))
allow_task_dependencies = fields.Boolean('Task Dependencies', default=lambda self: self.env.user.has_group('project.group_project_task_dependencies'))
tag_ids = fields.Many2many('project.tags', relation='project_project_project_tags_rel', string='Tags')
# Project Sharing fields
collaborator_ids = fields.One2many('project.collaborator', 'project_id', string='Collaborators', copy=False)
collaborator_count = fields.Integer('# Collaborators', compute='_compute_collaborator_count', compute_sudo=True)
# rating fields
rating_request_deadline = fields.Datetime(compute='_compute_rating_request_deadline', store=True)
rating_active = fields.Boolean('Customer Ratings', default=lambda self: self.env.user.has_group('project.group_project_rating'))
rating_status = fields.Selection(
[('stage', 'Rating when changing stage'),
('periodic', 'Periodic rating')
], 'Customer Ratings Status', default="stage", required=True,
help="How to get customer feedback?\n"
"- Rating when changing stage: an email will be sent when a task is pulled to another stage.\n"
"- Periodic rating: an email will be sent periodically.\n\n"
"Don't forget to set up the email templates on the stages for which you want to get customer feedback.")
rating_status_period = fields.Selection([
('daily', 'Daily'),
('weekly', 'Weekly'),
('bimonthly', 'Twice a Month'),
('monthly', 'Once a Month'),
('quarterly', 'Quarterly'),
('yearly', 'Yearly')], 'Rating Frequency', required=True, default='monthly')
# Not `required` since this is an option to enable in project settings.
stage_id = fields.Many2one('project.project.stage', string='Stage', ondelete='restrict', groups="project.group_project_stages",
tracking=True, index=True, copy=False, default=_default_stage_id, group_expand='_read_group_stage_ids')
update_ids = fields.One2many('project.update', 'project_id')
last_update_id = fields.Many2one('project.update', string='Last Update', copy=False)
last_update_status = fields.Selection(selection=[
('on_track', 'On Track'),
('at_risk', 'At Risk'),
('off_track', 'Off Track'),
('on_hold', 'On Hold')
], default='on_track', compute='_compute_last_update_status', store=True)
last_update_color = fields.Integer(compute='_compute_last_update_color')
milestone_ids = fields.One2many('project.milestone', 'project_id')
milestone_count = fields.Integer(compute='_compute_milestone_count')
_sql_constraints = [
('project_date_greater', 'check(date >= date_start)', 'Error! Project start date must be before project end date.')
]
@api.depends('partner_id.email')
def _compute_partner_email(self):
for project in self:
if project.partner_id and project.partner_id.email != project.partner_email:
project.partner_email = project.partner_id.email
def _inverse_partner_email(self):
for project in self:
if project.partner_id and project.partner_email != project.partner_id.email:
project.partner_id.email = project.partner_email
@api.depends('partner_id.phone')
def _compute_partner_phone(self):
for project in self:
if project.partner_id and project.partner_phone != project.partner_id.phone:
project.partner_phone = project.partner_id.phone
def _inverse_partner_phone(self):
for project in self:
if project.partner_id and project.partner_phone != project.partner_id.phone:
project.partner_id.phone = project.partner_phone
@api.onchange('alias_enabled')
def _onchange_alias_name(self):
if not self.alias_enabled:
self.alias_name = False
def _compute_alias_enabled(self):
for project in self:
project.alias_enabled = project.alias_domain and project.alias_id.alias_name
def _compute_access_url(self):
super(Project, self)._compute_access_url()
for project in self:
project.access_url = '/my/project/%s' % project.id
def _compute_access_warning(self):
super(Project, self)._compute_access_warning()
for project in self.filtered(lambda x: x.privacy_visibility != 'portal'):
project.access_warning = _(
"The project cannot be shared with the recipient(s) because the privacy of the project is too restricted. Set the privacy to 'Visible by following customers' in order to make it accessible by the recipient(s).")
@api.depends('rating_status', 'rating_status_period')
def _compute_rating_request_deadline(self):
periods = {'daily': 1, 'weekly': 7, 'bimonthly': 15, 'monthly': 30, 'quarterly': 90, 'yearly': 365}
for project in self:
project.rating_request_deadline = fields.datetime.now() + timedelta(days=periods.get(project.rating_status_period, 0))
@api.depends('last_update_id.status')
def _compute_last_update_status(self):
for project in self:
project.last_update_status = project.last_update_id.status or 'on_track'
@api.depends('last_update_status')
def _compute_last_update_color(self):
for project in self:
project.last_update_color = STATUS_COLOR[project.last_update_status]
@api.depends('milestone_ids')
def _compute_milestone_count(self):
read_group = self.env['project.milestone'].read_group([('project_id', 'in', self.ids)], ['project_id'], ['project_id'])
mapped_count = {group['project_id'][0]: group['project_id_count'] for group in read_group}
for project in self:
project.milestone_count = mapped_count.get(project.id, 0)
@api.depends('alias_name', 'alias_domain')
def _compute_alias_value(self):
for project in self:
if not project.alias_name or not project.alias_domain:
project.alias_value = ''
else:
project.alias_value = "%s@%s" % (project.alias_name, project.alias_domain)
@api.depends('collaborator_ids', 'privacy_visibility')
def _compute_collaborator_count(self):
project_sharings = self.filtered(lambda project: project.privacy_visibility == 'portal')
collaborator_read_group = self.env['project.collaborator'].read_group(
[('project_id', 'in', project_sharings.ids)],
['project_id'],
['project_id'],
)
collaborator_count_by_project = {res['project_id'][0]: res['project_id_count'] for res in collaborator_read_group}
for project in self:
project.collaborator_count = collaborator_count_by_project.get(project.id, 0)
@api.model
def _map_tasks_default_valeus(self, task, project):
""" get the default value for the copied task on project duplication """
return {
'stage_id': task.stage_id.id,
'name': task.name,
'company_id': project.company_id.id,
}
def map_tasks(self, new_project_id):
""" copy and map tasks from old to new project """
self.ensure_one()
project = self.browse(new_project_id)
tasks = self.env['project.task']
# We want to copy archived task, but do not propagate an active_test context key
task_ids = self.env['project.task'].with_context(active_test=False).search([('project_id', '=', self.id)], order='parent_id').ids
old_to_new_tasks = {}
all_tasks = self.env['project.task'].browse(task_ids)
for task in all_tasks:
# preserve task name and stage, normally altered during copy
defaults = self._map_tasks_default_valeus(task, project)
if task.parent_id:
# set the parent to the duplicated task
parent_id = old_to_new_tasks.get(task.parent_id.id, False)
defaults['parent_id'] = parent_id
if not parent_id or task.display_project_id:
defaults['project_id'] = project.id if task.display_project_id == self else False
defaults['display_project_id'] = project.id if task.display_project_id == self else False
elif task.display_project_id == self:
defaults['project_id'] = project.id
defaults['display_project_id'] = project.id
new_task = task.copy(defaults)
# If child are created before parent (ex sub_sub_tasks)
new_child_ids = [old_to_new_tasks[child.id] for child in task.child_ids if child.id in old_to_new_tasks]
tasks.browse(new_child_ids).write({'parent_id': new_task.id})
old_to_new_tasks[task.id] = new_task.id
if task.allow_task_dependencies:
depend_on_ids = [t.id if t not in all_tasks else old_to_new_tasks.get(t.id, None) for t in
task.depend_on_ids]
new_task.write({'depend_on_ids': [Command.link(tid) for tid in depend_on_ids if tid]})
dependent_ids = [t.id if t not in all_tasks else old_to_new_tasks.get(t.id, None) for t in
task.dependent_ids]
new_task.write({'dependent_ids': [Command.link(tid) for tid in dependent_ids if tid]})
tasks += new_task
return project.write({'tasks': [(6, 0, tasks.ids)]})
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
if default is None:
default = {}
if not default.get('name'):
default['name'] = _("%s (copy)") % (self.name)
project = super(Project, self).copy(default)
for follower in self.message_follower_ids:
project.message_subscribe(partner_ids=follower.partner_id.ids, subtype_ids=follower.subtype_ids.ids)
if 'tasks' not in default:
self.map_tasks(project.id)
return project
@api.model
def create(self, vals):
# Prevent double project creation
self = self.with_context(mail_create_nosubscribe=True)
project = super(Project, self).create(vals)
if project.privacy_visibility == 'portal' and project.partner_id:
project.message_subscribe(project.partner_id.ids)
return project
def write(self, vals):
# directly compute is_favorite to dodge allow write access right
if 'is_favorite' in vals:
vals.pop('is_favorite')
self._fields['is_favorite'].determine_inverse(self)
res = super(Project, self).write(vals) if vals else True
if 'allow_recurring_tasks' in vals and not vals.get('allow_recurring_tasks'):
self.env['project.task'].search([('project_id', 'in', self.ids), ('recurring_task', '=', True)]).write({'recurring_task': False})
if 'active' in vals:
# archiving/unarchiving a project does it on its tasks, too
self.with_context(active_test=False).mapped('tasks').write({'active': vals['active']})
if vals.get('partner_id') or vals.get('privacy_visibility'):
for project in self.filtered(lambda project: project.privacy_visibility == 'portal'):
project.message_subscribe(project.partner_id.ids)
if vals.get('privacy_visibility'):
self._change_privacy_visibility()
if 'name' in vals and self.analytic_account_id:
projects_read_group = self.env['project.project'].read_group(
[('analytic_account_id', 'in', self.analytic_account_id.ids)],
['analytic_account_id'],
['analytic_account_id']
)
analytic_account_to_update = self.env['account.analytic.account'].browse([
res['analytic_account_id'][0]
for res in projects_read_group
if res['analytic_account_id'] and res['analytic_account_id_count'] == 1
])
analytic_account_to_update.write({'name': self.name})
return res
def action_unlink(self):
wizard = self.env['project.delete.wizard'].create({
'project_ids': self.ids
})
return {
'name': _('Confirmation'),
'view_mode': 'form',
'res_model': 'project.delete.wizard',
'views': [(self.env.ref('project.project_delete_wizard_form').id, 'form')],
'type': 'ir.actions.act_window',
'res_id': wizard.id,
'target': 'new',
'context': self.env.context,
}
@api.ondelete(at_uninstall=False)
def _unlink_except_contains_tasks(self):
# Check project is empty
for project in self.with_context(active_test=False):
if project.tasks:
raise UserError(_('You cannot delete a project containing tasks. You can either archive it or first delete all of its tasks.'))
def unlink(self):
# Delete the empty related analytic account
analytic_accounts_to_delete = self.env['account.analytic.account']
for project in self:
if project.analytic_account_id and not project.analytic_account_id.line_ids:
analytic_accounts_to_delete |= project.analytic_account_id
result = super(Project, self).unlink()
analytic_accounts_to_delete.unlink()
return result
def message_subscribe(self, partner_ids=None, subtype_ids=None):
"""
Subscribe to all existing active tasks when subscribing to a project
"""
res = super(Project, self).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids)
project_subtypes = self.env['mail.message.subtype'].browse(subtype_ids) if subtype_ids else None
task_subtypes = (project_subtypes.mapped('parent_id') | project_subtypes.filtered(lambda sub: sub.internal or sub.default)).ids if project_subtypes else None
if not subtype_ids or task_subtypes:
self.mapped('tasks').message_subscribe(
partner_ids=partner_ids, subtype_ids=task_subtypes)
return res
def message_unsubscribe(self, partner_ids=None):
""" Unsubscribe from all tasks when unsubscribing from a project """
self.mapped('tasks').message_unsubscribe(partner_ids=partner_ids)
return super(Project, self).message_unsubscribe(partner_ids=partner_ids)
def _alias_get_creation_values(self):
values = super(Project, self)._alias_get_creation_values()
values['alias_model_id'] = self.env['ir.model']._get('project.task').id
if self.id:
values['alias_defaults'] = defaults = ast.literal_eval(self.alias_defaults or "{}")
defaults['project_id'] = self.id
return values
# ---------------------------------------------------
# Mail gateway
# ---------------------------------------------------
def _track_template(self, changes):
res = super()._track_template(changes)
project = self[0]
if self.user_has_groups('project.group_project_stages') and 'stage_id' in changes and project.stage_id.mail_template_id:
res['stage_id'] = (project.stage_id.mail_template_id, {
'auto_delete_message': True,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
'email_layout_xmlid': 'mail.mail_notification_light',
})
return res
def _track_subtype(self, init_values):
self.ensure_one()
if 'stage_id' in init_values:
return self.env.ref('project.mt_project_stage_change')
return super()._track_subtype(init_values)
def _mail_get_message_subtypes(self):
res = super()._mail_get_message_subtypes()
if len(self) == 1:
dependency_subtype = self.env.ref('project.mt_project_task_dependency_change')
if not self.allow_task_dependencies and dependency_subtype in res:
res -= dependency_subtype
return res
# ---------------------------------------------------
# Actions
# ---------------------------------------------------
def toggle_favorite(self):
favorite_projects = not_fav_projects = self.env['project.project'].sudo()
for project in self:
if self.env.user in project.favorite_user_ids:
favorite_projects |= project
else:
not_fav_projects |= project
# Project User has no write access for project.
not_fav_projects.write({'favorite_user_ids': [(4, self.env.uid)]})
favorite_projects.write({'favorite_user_ids': [(3, self.env.uid)]})
def action_view_tasks(self):
action = self.with_context(active_id=self.id, active_ids=self.ids) \
.env.ref('project.act_project_project_2_project_task_all') \
.sudo().read()[0]
action['display_name'] = self.name
return action
def action_view_all_rating(self):
""" return the action to see all the rating of the project and activate default filters"""
action = self.env['ir.actions.act_window']._for_xml_id('project.rating_rating_action_view_project_rating')
action['name'] = _('Ratings of %s') % (self.name,)
action_context = ast.literal_eval(action['context']) if action['context'] else {}
action_context.update(self._context)
action_context['search_default_parent_res_name'] = self.name
action_context.pop('group_by', None)
return dict(action, context=action_context)
def action_view_tasks_analysis(self):
""" return the action to see the tasks analysis report of the project """
action = self.env['ir.actions.act_window']._for_xml_id('project.action_project_task_user_tree')
action_context = ast.literal_eval(action['context']) if action['context'] else {}
action_context['search_default_project_id'] = self.id
return dict(action, context=action_context)
@api.model
def _action_open_all_projects(self):
action = self.env['ir.actions.act_window']._for_xml_id(
'project.open_view_project_all' if not self.user_has_groups('project.group_project_stages') else
'project.open_view_project_all_group_stage')
return action
def action_view_analytic_account_entries(self):
self.ensure_one()
return {
'res_model': 'account.analytic.line',
'type': 'ir.actions.act_window',
'name': _("Gross Margin"),
'domain': [('account_id', '=', self.analytic_account_id.id)],
'views': [(self.env.ref('analytic.view_account_analytic_line_tree').id, 'list'),
(self.env.ref('analytic.view_account_analytic_line_form').id, 'form'),
(self.env.ref('analytic.view_account_analytic_line_graph').id, 'graph'),
(self.env.ref('analytic.view_account_analytic_line_pivot').id, 'pivot')],
'view_mode': 'tree,form,graph,pivot',
'context': {'search_default_group_date': 1, 'default_account_id': self.analytic_account_id.id}
}
def action_view_kanban_project(self):
# [XBO] TODO: remove me in master
return
# ---------------------------------------------
# PROJECT UPDATES
# ---------------------------------------------
def get_last_update_or_default(self):
self.ensure_one()
labels = dict(self._fields['last_update_status']._description_selection(self.env))
return {
'status': labels[self.last_update_status],
'color': self.last_update_color,
}
def get_panel_data(self):
self.ensure_one()
return {
'user': self._get_user_values(),
'tasks_analysis': self._get_tasks_analysis(),
'milestones': self._get_milestones(),
'buttons': sorted(self._get_stat_buttons(), key=lambda k: k['sequence']),
}
def _get_user_values(self):
return {
'is_project_user': self.user_has_groups('project.group_project_user'),
}
def _get_tasks_analysis(self):
# Deprecated
return {
'data': [],
}
def _get_milestones(self):
self.ensure_one()
return {
'data': self.milestone_ids._get_data_list(),
}
def _get_stat_buttons(self):
self.ensure_one()
buttons = [{
'icon': 'tasks',
'text': _lt('Tasks'),
'number': self.task_count,
'action_type': 'action',
'action': 'project.act_project_project_2_project_task_all',
'additional_context': json.dumps({
'active_id': self.id,
}),
'show': True,
'sequence': 2,
}]
if self.user_has_groups('project.group_project_rating'):
buttons.append({
'icon': 'smile-o',
'text': _lt('Customer Satisfaction'),
'number': '%s %%' % (self.rating_percentage_satisfaction),
'action_type': 'object',
'action': 'action_view_all_rating',
'show': self.rating_active and self.rating_percentage_satisfaction > -1,
'sequence': 5,
})
if self.user_has_groups('project.group_project_manager'):
buttons.append({
'icon': 'area-chart',
'text': _lt('Burndown Chart'),
'action_type': 'action',
'action': 'project.action_project_task_burndown_chart_report',
'additional_context': json.dumps({
'active_id': self.id,
}),
'show': True,
'sequence': 7,
})
buttons.append({
'icon': 'users',
'text': _lt('Collaborators'),
'number': self.collaborator_count,
'action_type': 'action',
'action': 'project.project_collaborator_action',
'additional_context': json.dumps({
'active_id': self.id,
}),
'show': True,
'sequence': 23,
})
if self.user_has_groups('analytic.group_analytic_accounting'):
buttons.append({
'icon': 'usd',
'text': _lt('Gross Margin'),
'number': format_amount(self.env, self.analytic_account_balance, self.company_id.currency_id),
'action_type': 'object',
'action': 'action_view_analytic_account_entries',
'show': bool(self.analytic_account_id),
'sequence': 18,
})
return buttons
def _get_tasks_analysis_counts(self, created=False, updated=False):
# Deprecated
return {}
# ---------------------------------------------------
# Business Methods
# ---------------------------------------------------
@api.model
def _create_analytic_account_from_values(self, values):
analytic_account = self.env['account.analytic.account'].create({
'name': values.get('name', _('Unknown Analytic Account')),
'company_id': values.get('company_id') or self.env.company.id,
'partner_id': values.get('partner_id'),
'active': True,
})
return analytic_account
def _create_analytic_account(self):
for project in self:
analytic_account = self.env['account.analytic.account'].create({
'name': project.name,
'company_id': project.company_id.id,
'partner_id': project.partner_id.id,
'active': True,
})
project.write({'analytic_account_id': analytic_account.id})
# ---------------------------------------------------
# Rating business
# ---------------------------------------------------
# This method should be called once a day by the scheduler
@api.model
def _send_rating_all(self):
projects = self.search([
('rating_active', '=', True),
('rating_status', '=', 'periodic'),
('rating_request_deadline', '<=', fields.Datetime.now())
])
for project in projects:
project.task_ids._send_task_rating_mail()
project._compute_rating_request_deadline()
self.env.cr.commit()
# ---------------------------------------------------
# Privacy
# ---------------------------------------------------
def _change_privacy_visibility(self):
"""
Unsubscribe non-internal users from the project and tasks if the project privacy visibility
goes to a value different than 'portal'
"""
for project in self.filtered(lambda p: p.privacy_visibility != 'portal'):
portal_users = project.message_partner_ids.user_ids.filtered('share')
project.message_unsubscribe(partner_ids=portal_users.partner_id.ids)
project.mapped('tasks')._change_project_privacy_visibility()
# ---------------------------------------------------
# Project sharing
# ---------------------------------------------------
def _check_project_sharing_access(self):
self.ensure_one()
if self.privacy_visibility != 'portal':
return False
if self.env.user.has_group('base.group_portal'):
return self.env['project.collaborator'].search([('project_id', '=', self.sudo().id), ('partner_id', '=', self.env.user.partner_id.id)])
return self.env.user.has_group('base.group_user')
def _add_collaborators(self, partners):
self.ensure_one()
user_group_id = self.env['ir.model.data']._xmlid_to_res_id('base.group_user')
all_collaborators = self.collaborator_ids.partner_id
new_collaborators = partners.filtered(
lambda partner:
partner not in all_collaborators
and (not partner.user_ids or user_group_id not in partner.user_ids[0].groups_id.ids)
)
if not new_collaborators:
# Then we have nothing to do
return
self.write({'collaborator_ids': [
Command.create({
'partner_id': collaborator.id,
}) for collaborator in new_collaborators],
})
class Task(models.Model):
_name = "project.task"
_description = "Task"
_date_name = "date_assign"
_inherit = ['portal.mixin', 'mail.thread.cc', 'mail.activity.mixin', 'rating.mixin']
_mail_post_access = 'read'
_order = "priority desc, sequence, id desc"
_check_company_auto = True
@api.model
def _get_default_partner_id(self, project=None, parent=None):
if parent and parent.partner_id:
return parent.partner_id.id
if project and project.partner_id:
return project.partner_id.id
return False
def _get_default_stage_id(self):
""" Gives default stage_id """
project_id = self.env.context.get('default_project_id')
if not project_id:
return False
return self.stage_find(project_id, [('fold', '=', False), ('is_closed', '=', False)])
@api.model
def _default_company_id(self):
if self._context.get('default_project_id'):
return self.env['project.project'].browse(self._context['default_project_id']).company_id
return self.env.company
@api.model
def _read_group_stage_ids(self, stages, domain, order):
search_domain = [('id', 'in', stages.ids)]
if 'default_project_id' in self.env.context:
search_domain = ['|', ('project_ids', '=', self.env.context['default_project_id'])] + search_domain
stage_ids = stages._search(search_domain, order=order, access_rights_uid=SUPERUSER_ID)
return stages.browse(stage_ids)
@api.model
def _read_group_personal_stage_type_ids(self, stages, domain, order):
return stages.search(['|', ('id', 'in', stages.ids), ('user_id', '=', self.env.user.id)])
active = fields.Boolean(default=True)
name = fields.Char(string='Title', tracking=True, required=True, index=True)
description = fields.Html(string='Description', sanitize_attributes=False)
priority = fields.Selection([
('0', 'Normal'),
('1', 'Important'),
], default='0', index=True, string="Starred", tracking=True)
sequence = fields.Integer(string='Sequence', index=True, default=10,
help="Gives the sequence order when displaying a list of tasks.")
stage_id = fields.Many2one('project.task.type', string='Stage', compute='_compute_stage_id',
store=True, readonly=False, ondelete='restrict', tracking=True, index=True,
default=_get_default_stage_id, group_expand='_read_group_stage_ids',
domain="[('project_ids', '=', project_id)]", copy=False, task_dependency_tracking=True)
tag_ids = fields.Many2many('project.tags', string='Tags')
kanban_state = fields.Selection([
('normal', 'In Progress'),
('done', 'Ready'),
('blocked', 'Blocked')], string='Status',
copy=False, default='normal', required=True)
kanban_state_label = fields.Char(compute='_compute_kanban_state_label', string='Kanban State Label', tracking=True, task_dependency_tracking=True)
create_date = fields.Datetime("Created On", readonly=True, index=True)
write_date = fields.Datetime("Last Updated On", readonly=True, index=True)
date_end = fields.Datetime(string='Ending Date', index=True, copy=False)
date_assign = fields.Datetime(string='Assigning Date', index=True, copy=False, readonly=True)
date_deadline = fields.Date(string='Deadline', index=True, copy=False, tracking=True, task_dependency_tracking=True)
date_last_stage_update = fields.Datetime(string='Last Stage Update',
index=True,
copy=False,
readonly=True)
project_id = fields.Many2one('project.project', string='Project',
compute='_compute_project_id', recursive=True, store=True, readonly=False,
index=True, tracking=True, check_company=True, change_default=True)
# Defines in which project the task will be displayed / taken into account in statistics.
# Example: 1 task A with 1 subtask B in project P
# A -> project_id=P, display_project_id=P
# B -> project_id=P (to inherit from ACL/security rules), display_project_id=False
display_project_id = fields.Many2one('project.project', index=True)
planned_hours = fields.Float("Initially Planned Hours", help='Time planned to achieve this task (including its sub-tasks).', tracking=True)
subtask_planned_hours = fields.Float("Sub-tasks Planned Hours", compute='_compute_subtask_planned_hours',
help="Sum of the time planned of all the sub-tasks linked to this task. Usually less than or equal to the initially planned time of this task.")
# Tracking of this field is done in the write function
user_ids = fields.Many2many('res.users', relation='project_task_user_rel', column1='task_id', column2='user_id',
string='Assignees', default=lambda self: not self.env.user.share and self.env.user, context={'active_test': False}, tracking=True)
# User names displayed in project sharing views
portal_user_names = fields.Char(compute='_compute_portal_user_names', compute_sudo=True, search='_search_portal_user_names')
# Second Many2many containing the actual personal stage for the current user
# See project_task_stage_personal.py for the model defininition
personal_stage_type_ids = fields.Many2many('project.task.type', 'project_task_user_rel', column1='task_id', column2='stage_id',
ondelete='restrict', group_expand='_read_group_personal_stage_type_ids', copy=False,
domain="[('user_id', '=', user.id)]", depends=['user_ids'], string='Personal Stage')
# Personal Stage computed from the user
personal_stage_id = fields.Many2one('project.task.stage.personal', string='Personal Stage State', compute_sudo=False,
compute='_compute_personal_stage_id', help="The current user's personal stage.")
# This field is actually a related field on personal_stage_id.stage_id
# However due to the fact that personal_stage_id is computed, the orm throws out errors
# saying the field cannot be searched.
personal_stage_type_id = fields.Many2one('project.task.type', string='Personal User Stage',
compute='_compute_personal_stage_type_id', inverse='_inverse_personal_stage_type_id', store=False,
search='_search_personal_stage_type_id',
help="The current user's personal task stage.")
partner_id = fields.Many2one('res.partner',
string='Customer',
compute='_compute_partner_id', recursive=True, store=True, readonly=False, tracking=True,
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
partner_is_company = fields.Boolean(related='partner_id.is_company', readonly=True)
commercial_partner_id = fields.Many2one(related='partner_id.commercial_partner_id')
partner_email = fields.Char(
compute='_compute_partner_email', inverse='_inverse_partner_email',
string='Email', readonly=False, store=True, copy=False)
partner_phone = fields.Char(
compute='_compute_partner_phone', inverse='_inverse_partner_phone',
string="Phone", readonly=False, store=True, copy=False)
partner_city = fields.Char(related='partner_id.city', readonly=False)
manager_id = fields.Many2one('res.users', string='Project Manager', related='project_id.user_id', readonly=True)
company_id = fields.Many2one(
'res.company', string='Company', compute='_compute_company_id', store=True, readonly=False,
required=True, copy=True, default=_default_company_id)
color = fields.Integer(string='Color Index')
attachment_ids = fields.One2many('ir.attachment', compute='_compute_attachment_ids', string="Main Attachments",
help="Attachments that don't come from a message.")
# In the domain of displayed_image_id, we couln't use attachment_ids because a one2many is represented as a list of commands so we used res_model & res_id
displayed_image_id = fields.Many2one('ir.attachment', domain="[('res_model', '=', 'project.task'), ('res_id', '=', id), ('mimetype', 'ilike', 'image')]", string='Cover Image')
legend_blocked = fields.Char(related='stage_id.legend_blocked', string='Kanban Blocked Explanation', readonly=True, related_sudo=False)
legend_done = fields.Char(related='stage_id.legend_done', string='Kanban Valid Explanation', readonly=True, related_sudo=False)
legend_normal = fields.Char(related='stage_id.legend_normal', string='Kanban Ongoing Explanation', readonly=True, related_sudo=False)
is_closed = fields.Boolean(related="stage_id.is_closed", string="Closing Stage", readonly=True, related_sudo=False)
parent_id = fields.Many2one('project.task', string='Parent Task', index=True)
child_ids = fields.One2many('project.task', 'parent_id', string="Sub-tasks")
child_text = fields.Char(compute="_compute_child_text")
allow_subtasks = fields.Boolean(string="Allow Sub-tasks", related="project_id.allow_subtasks", readonly=True)
subtask_count = fields.Integer("Sub-task Count", compute='_compute_subtask_count')
email_from = fields.Char(string='Email From', help="These people will receive email.", index=True,
compute='_compute_email_from', recursive=True, store=True, readonly=False, copy=False)
project_privacy_visibility = fields.Selection(related='project_id.privacy_visibility', string="Project Visibility")
# Computed field about working time elapsed between record creation and assignation/closing.
working_hours_open = fields.Float(compute='_compute_elapsed', string='Working Hours to Assign', digits=(16, 2), store=True, group_operator="avg")
working_hours_close = fields.Float(compute='_compute_elapsed', string='Working Hours to Close', digits=(16, 2), store=True, group_operator="avg")
working_days_open = fields.Float(compute='_compute_elapsed', string='Working Days to Assign', store=True, group_operator="avg")
working_days_close = fields.Float(compute='_compute_elapsed', string='Working Days to Close', store=True, group_operator="avg")
# customer portal: include comment and incoming emails in communication history
website_message_ids = fields.One2many(domain=lambda self: [('model', '=', self._name), ('message_type', 'in', ['email', 'comment'])])
is_private = fields.Boolean(compute='_compute_is_private')
# Task Dependencies fields
allow_task_dependencies = fields.Boolean(related='project_id.allow_task_dependencies')
# Tracking of this field is done in the write function
depend_on_ids = fields.Many2many('project.task', relation="task_dependencies_rel", column1="task_id",
column2="depends_on_id", string="Blocked By", tracking=True, copy=False,
domain="[('allow_task_dependencies', '=', True), ('id', '!=', id)]")
dependent_ids = fields.Many2many('project.task', relation="task_dependencies_rel", column1="depends_on_id",
column2="task_id", string="Block", copy=False,
domain="[('allow_task_dependencies', '=', True), ('id', '!=', id)]")
dependent_tasks_count = fields.Integer(string="Dependent Tasks", compute='_compute_dependent_tasks_count')
# recurrence fields
allow_recurring_tasks = fields.Boolean(related='project_id.allow_recurring_tasks')
recurring_task = fields.Boolean(string="Recurrent")
recurring_count = fields.Integer(string="Tasks in Recurrence", compute='_compute_recurring_count')
recurrence_id = fields.Many2one('project.task.recurrence', copy=False)
recurrence_update = fields.Selection([
('this', 'This task'),
('subsequent', 'This and following tasks'),
('all', 'All tasks'),
], default='this', store=False)
recurrence_message = fields.Char(string='Next Recurrencies', compute='_compute_recurrence_message')
repeat_interval = fields.Integer(string='Repeat Every', default=1, compute='_compute_repeat', readonly=False)
repeat_unit = fields.Selection([
('day', 'Days'),
('week', 'Weeks'),
('month', 'Months'),
('year', 'Years'),
], default='week', compute='_compute_repeat', readonly=False)
repeat_type = fields.Selection([
('forever', 'Forever'),
('until', 'End Date'),
('after', 'Number of Repetitions'),
], default="forever", string="Until", compute='_compute_repeat', readonly=False)
repeat_until = fields.Date(string="End Date", compute='_compute_repeat', readonly=False)
repeat_number = fields.Integer(string="Repetitions", default=1, compute='_compute_repeat', readonly=False)
repeat_on_month = fields.Selection([
('date', 'Date of the Month'),
('day', 'Day of the Month'),
], default='date', compute='_compute_repeat', readonly=False)
repeat_on_year = fields.Selection([
('date', 'Date of the Year'),
('day', 'Day of the Year'),
], default='date', compute='_compute_repeat', readonly=False)
mon = fields.Boolean(string="Mon", compute='_compute_repeat', readonly=False)
tue = fields.Boolean(string="Tue", compute='_compute_repeat', readonly=False)
wed = fields.Boolean(string="Wed", compute='_compute_repeat', readonly=False)
thu = fields.Boolean(string="Thu", compute='_compute_repeat', readonly=False)
fri = fields.Boolean(string="Fri", compute='_compute_repeat', readonly=False)
sat = fields.Boolean(string="Sat", compute='_compute_repeat', readonly=False)
sun = fields.Boolean(string="Sun", compute='_compute_repeat', readonly=False)
repeat_day = fields.Selection([
(str(i), str(i)) for i in range(1, 32)
], compute='_compute_repeat', readonly=False)
repeat_week = fields.Selection([
('first', 'First'),
('second', 'Second'),
('third', 'Third'),
('last', 'Last'),
], default='first', compute='_compute_repeat', readonly=False)
repeat_weekday = fields.Selection([
('mon', 'Monday'),
('tue', 'Tuesday'),
('wed', 'Wednesday'),
('thu', 'Thursday'),
('fri', 'Friday'),
('sat', 'Saturday'),
('sun', 'Sunday'),
], string='Day Of The Week', compute='_compute_repeat', readonly=False)
repeat_month = fields.Selection([
('january', 'January'),
('february', 'February'),
('march', 'March'),
('april', 'April'),
('may', 'May'),
('june', 'June'),
('july', 'July'),
('august', 'August'),
('september', 'September'),
('october', 'October'),
('november', 'November'),
('december', 'December'),
], compute='_compute_repeat', readonly=False)
repeat_show_dow = fields.Boolean(compute='_compute_repeat_visibility')
repeat_show_day = fields.Boolean(compute='_compute_repeat_visibility')
repeat_show_week = fields.Boolean(compute='_compute_repeat_visibility')
repeat_show_month = fields.Boolean(compute='_compute_repeat_visibility')
# Account analytic
analytic_account_id = fields.Many2one('account.analytic.account', ondelete='set null',
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", check_company=True,
help="Analytic account to which this task is linked for financial management. "
"Use an analytic account to record cost and revenue on your task. "
"If empty, the analytic account of the project will be used.")
project_analytic_account_id = fields.Many2one('account.analytic.account', string='Project Analytic Account', related='project_id.analytic_account_id')
analytic_tag_ids = fields.Many2many('account.analytic.tag',
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", check_company=True)
@property
def SELF_READABLE_FIELDS(self):
return PROJECT_TASK_READABLE_FIELDS | self.SELF_WRITABLE_FIELDS
@property
def SELF_WRITABLE_FIELDS(self):
return PROJECT_TASK_WRITABLE_FIELDS
@api.depends('project_id', 'parent_id')
def _compute_is_private(self):
# Modify accordingly, this field is used to display the lock on the task's kanban card
for task in self:
task.is_private = not task.project_id and not task.parent_id
@api.depends_context('uid')
@api.depends('user_ids')
def _compute_personal_stage_id(self):
# An user may only access his own 'personal stage' and there can only be one pair (user, task_id)
personal_stages = self.env['project.task.stage.personal'].search([('user_id', '=', self.env.uid), ('task_id', 'in', self.ids)])
self.personal_stage_id = False
for personal_stage in personal_stages:
personal_stage.task_id.personal_stage_id = personal_stage
@api.depends('personal_stage_id')
def _compute_personal_stage_type_id(self):
for task in self:
task.personal_stage_type_id = task.personal_stage_id.stage_id
def _inverse_personal_stage_type_id(self):
for task in self:
task.personal_stage_id.stage_id = task.personal_stage_type_id
@api.model
def _search_personal_stage_type_id(self, operator, value):
return [('personal_stage_type_ids', operator, value)]
@api.model
def _get_default_personal_stage_create_vals(self, user_id):
return [
{'sequence': 1, 'name': _('Inbox'), 'user_id': user_id, 'fold': False},
{'sequence': 2, 'name': _('Today'), 'user_id': user_id, 'fold': False},
{'sequence': 3, 'name': _('This Week'), 'user_id': user_id, 'fold': False},
{'sequence': 4, 'name': _('This Month'), 'user_id': user_id, 'fold': False},
{'sequence': 5, 'name': _('Later'), 'user_id': user_id, 'fold': False},
{'sequence': 6, 'name': _('Done'), 'user_id': user_id, 'fold': True},
{'sequence': 7, 'name': _('Canceled'), 'user_id': user_id, 'fold': True},
]
def _populate_missing_personal_stages(self):
# Assign the default personal stage for those that are missing
personal_stages_without_stage = self.env['project.task.stage.personal'].sudo().search([('task_id', 'in', self.ids), ('stage_id', '=', False)])
if personal_stages_without_stage:
user_ids = personal_stages_without_stage.user_id
personal_stage_by_user = defaultdict(lambda: self.env['project.task.stage.personal'])
for personal_stage in personal_stages_without_stage:
personal_stage_by_user[personal_stage.user_id] |= personal_stage
for user_id in user_ids:
stage = self.env['project.task.type'].sudo().search([('user_id', '=', user_id.id)], limit=1)
# In the case no stages have been found, we create the default stages for the user
if not stage:
stages = self.env['project.task.type'].sudo().with_context(lang=user_id.partner_id.lang, default_project_ids=False).create(
self.with_context(lang=user_id.partner_id.lang)._get_default_personal_stage_create_vals(user_id.id)
)
stage = stages[0]
personal_stage_by_user[user_id].sudo().write({'stage_id': stage.id})
@api.constrains('depend_on_ids')
def _check_no_cyclic_dependencies(self):
if not self._check_m2m_recursion('depend_on_ids'):
raise ValidationError(_("You cannot create cyclic dependency."))
@api.model
def _get_recurrence_fields(self):
return ['repeat_interval', 'repeat_unit', 'repeat_type', 'repeat_until', 'repeat_number',
'repeat_on_month', 'repeat_on_year', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat',
'sun', 'repeat_day', 'repeat_week', 'repeat_month', 'repeat_weekday']
@api.depends('recurring_task', 'repeat_unit', 'repeat_on_month', 'repeat_on_year')
def _compute_repeat_visibility(self):
for task in self:
task.repeat_show_day = task.recurring_task and (task.repeat_unit == 'month' and task.repeat_on_month == 'date') or (task.repeat_unit == 'year' and task.repeat_on_year == 'date')
task.repeat_show_week = task.recurring_task and (task.repeat_unit == 'month' and task.repeat_on_month == 'day') or (task.repeat_unit == 'year' and task.repeat_on_year == 'day')
task.repeat_show_dow = task.recurring_task and task.repeat_unit == 'week'
task.repeat_show_month = task.recurring_task and task.repeat_unit == 'year'
@api.depends('recurring_task')
def _compute_repeat(self):
rec_fields = self._get_recurrence_fields()
defaults = self.default_get(rec_fields)
for task in self:
for f in rec_fields:
if task.recurrence_id:
task[f] = task.recurrence_id[f]
else:
if task.recurring_task:
task[f] = defaults.get(f)
else:
task[f] = False
def _get_weekdays(self, n=1):
self.ensure_one()
if self.repeat_unit == 'week':
return [fn(n) for day, fn in DAYS.items() if self[day]]
return [DAYS.get(self.repeat_weekday)(n)]
def _get_recurrence_start_date(self):
return fields.Date.today()
@api.depends(
'recurring_task', 'repeat_interval', 'repeat_unit', 'repeat_type', 'repeat_until',
'repeat_number', 'repeat_on_month', 'repeat_on_year', 'mon', 'tue', 'wed', 'thu', 'fri',
'sat', 'sun', 'repeat_day', 'repeat_week', 'repeat_month', 'repeat_weekday')
def _compute_recurrence_message(self):
self.recurrence_message = False
for task in self.filtered(lambda t: t.recurring_task and t._is_recurrence_valid()):
date = task._get_recurrence_start_date()
recurrence_left = task.recurrence_id.recurrence_left if task.recurrence_id else task.repeat_number
number_occurrences = min(5, recurrence_left if task.repeat_type == 'after' else 5)
delta = task.repeat_interval if task.repeat_unit == 'day' else 1
recurring_dates = self.env['project.task.recurrence']._get_next_recurring_dates(
date + timedelta(days=delta),
task.repeat_interval,
task.repeat_unit,
task.repeat_type,
task.repeat_until,
task.repeat_on_month,
task.repeat_on_year,
task._get_weekdays(WEEKS.get(task.repeat_week)),
task.repeat_day,
task.repeat_week,
task.repeat_month,
count=number_occurrences)
date_format = self.env['res.lang']._lang_get(self.env.user.lang).date_format or get_lang(self.env).date_format
if recurrence_left == 0:
recurrence_title = _('There are no more occurrences.')
else:
recurrence_title = _('Next Occurrences:')
task.recurrence_message = '<p><span class="fa fa-check-circle"></span> %s</p><ul>' % recurrence_title
task.recurrence_message += ''.join(['<li>%s</li>' % date.strftime(date_format) for date in recurring_dates[:5]])
if task.repeat_type == 'after' and recurrence_left > 5 or task.repeat_type == 'forever' or len(recurring_dates) > 5:
task.recurrence_message += '<li>...</li>'
task.recurrence_message += '</ul>'
if task.repeat_type == 'until':
task.recurrence_message += _('<p><em>Number of tasks: %(tasks_count)s</em></p>') % {'tasks_count': len(recurring_dates)}
def _is_recurrence_valid(self):
self.ensure_one()
return self.repeat_interval > 0 and\
(not self.repeat_show_dow or self._get_weekdays()) and\
(self.repeat_type != 'after' or self.repeat_number) and\
(self.repeat_type != 'until' or self.repeat_until and self.repeat_until > fields.Date.today())
@api.depends('recurrence_id')
def _compute_recurring_count(self):
self.recurring_count = 0
recurring_tasks = self.filtered(lambda l: l.recurrence_id)
count = self.env['project.task'].read_group([('recurrence_id', 'in', recurring_tasks.recurrence_id.ids)], ['id'], 'recurrence_id')
tasks_count = {c.get('recurrence_id')[0]: c.get('recurrence_id_count') for c in count}
for task in recurring_tasks:
task.recurring_count = tasks_count.get(task.recurrence_id.id, 0)
@api.depends('dependent_ids')
def _compute_dependent_tasks_count(self):
tasks_with_dependency = self.filtered('allow_task_dependencies')
(self - tasks_with_dependency).dependent_tasks_count = 0
if tasks_with_dependency:
group_dependent = self.env['project.task'].read_group([
('depend_on_ids', 'in', tasks_with_dependency.ids),
], ['depend_on_ids'], ['depend_on_ids'])
dependent_tasks_count_dict = {
group['depend_on_ids'][0]: group['depend_on_ids_count']
for group in group_dependent
}
for task in tasks_with_dependency:
task.dependent_tasks_count = dependent_tasks_count_dict.get(task.id, 0)
@api.depends('partner_id.email')
def _compute_partner_email(self):
for task in self:
if task.partner_id and task.partner_id.email != task.partner_email:
task.partner_email = task.partner_id.email
def _inverse_partner_email(self):
for task in self:
if task.partner_id and task.partner_email != task.partner_id.email:
task.partner_id.email = task.partner_email
@api.depends('partner_id.phone')
def _compute_partner_phone(self):
for task in self:
if task.partner_id and task.partner_phone != task.partner_id.phone:
task.partner_phone = task.partner_id.phone
def _inverse_partner_phone(self):
for task in self:
if task.partner_id and task.partner_phone != task.partner_id.phone:
task.partner_id.phone = task.partner_phone
@api.constrains('parent_id')
def _check_parent_id(self):
if not self._check_recursion():
raise ValidationError(_('Error! You cannot create a recursive hierarchy of tasks.'))
def _compute_attachment_ids(self):
for task in self:
attachment_ids = self.env['ir.attachment'].search([('res_id', '=', task.id), ('res_model', '=', 'project.task')]).ids
message_attachment_ids = task.mapped('message_ids.attachment_ids').ids # from mail_thread
task.attachment_ids = [(6, 0, list(set(attachment_ids) - set(message_attachment_ids)))]
@api.depends('create_date', 'date_end', 'date_assign')
def _compute_elapsed(self):
task_linked_to_calendar = self.filtered(
lambda task: task.project_id.resource_calendar_id and task.create_date
)
for task in task_linked_to_calendar:
dt_create_date = fields.Datetime.from_string(task.create_date)
if task.date_assign:
dt_date_assign = fields.Datetime.from_string(task.date_assign)
duration_data = task.project_id.resource_calendar_id.get_work_duration_data(dt_create_date, dt_date_assign, compute_leaves=True)
task.working_hours_open = duration_data['hours']
task.working_days_open = duration_data['days']
else:
task.working_hours_open = 0.0
task.working_days_open = 0.0
if task.date_end:
dt_date_end = fields.Datetime.from_string(task.date_end)
duration_data = task.project_id.resource_calendar_id.get_work_duration_data(dt_create_date, dt_date_end, compute_leaves=True)
task.working_hours_close = duration_data['hours']
task.working_days_close = duration_data['days']
else:
task.working_hours_close = 0.0
task.working_days_close = 0.0
(self - task_linked_to_calendar).update(dict.fromkeys(
['working_hours_open', 'working_hours_close', 'working_days_open', 'working_days_close'], 0.0))
@api.depends('stage_id', 'kanban_state')
def _compute_kanban_state_label(self):
for task in self:
if task.kanban_state == 'normal':
task.kanban_state_label = task.legend_normal
elif task.kanban_state == 'blocked':
task.kanban_state_label = task.legend_blocked
else:
task.kanban_state_label = task.legend_done
def _compute_access_url(self):
super(Task, self)._compute_access_url()
for task in self:
task.access_url = '/my/task/%s' % task.id
def _compute_access_warning(self):
super(Task, self)._compute_access_warning()
for task in self.filtered(lambda x: x.project_id.privacy_visibility != 'portal'):
task.access_warning = _(
"The task cannot be shared with the recipient(s) because the privacy of the project is too restricted. Set the privacy of the project to 'Visible by following customers' in order to make it accessible by the recipient(s).")
@api.depends('child_ids.planned_hours')
def _compute_subtask_planned_hours(self):
for task in self:
task.subtask_planned_hours = sum(child_task.planned_hours + child_task.subtask_planned_hours for child_task in task.child_ids)
@api.depends('child_ids')
def _compute_child_text(self):
for task in self:
if not task.subtask_count:
task.child_text = False
elif task.subtask_count == 1:
task.child_text = _("(+ 1 task)")
else:
task.child_text = _("(+ %(child_count)s tasks)", child_count=task.subtask_count)
@api.depends('child_ids')
def _compute_subtask_count(self):
for task in self:
task.subtask_count = len(task._get_all_subtasks())
@api.onchange('company_id')
def _onchange_task_company(self):
if self.project_id.company_id != self.company_id:
self.project_id = False
@api.depends('project_id.company_id')
def _compute_company_id(self):
for task in self.filtered(lambda task: task.project_id):
task.company_id = task.project_id.company_id
@api.depends('project_id')
def _compute_stage_id(self):
for task in self:
if task.project_id:
if task.project_id not in task.stage_id.project_ids:
task.stage_id = task.stage_find(task.project_id.id, [
('fold', '=', False), ('is_closed', '=', False)])
else:
task.stage_id = False
@api.depends('user_ids')
def _compute_portal_user_names(self):
""" This compute method allows to see all the names of assigned users to each task contained in `self`.
When we are in the project sharing feature, the `user_ids` contains only the users if we are a portal user.
That is, only the users in the same company of the current user.
So this compute method is a related of `user_ids.name` but with more records that the portal user
can normally see.
(In other words, this compute is only used in project sharing views to see all assignees for each task)
"""
if self.ids:
# fetch 'user_ids' in superuser mode (and override value in cache
# browse is useful to avoid miscache because of the newIds contained in self
self.browse(self.ids)._read(['user_ids'])
for task in self.with_context(prefetch_fields=False):
task.portal_user_names = ', '.join(task.user_ids.mapped('name'))
def _search_portal_user_names(self, operator, value):
if operator != 'ilike' and not isinstance(value, str):
raise ValidationError('Not Implemented.')
query = """
SELECT task_user.task_id
FROM project_task_user_rel task_user
INNER JOIN res_users users ON task_user.user_id = users.id
INNER JOIN res_partner partners ON partners.id = users.partner_id
WHERE partners.name ILIKE %s
"""
return [('id', 'inselect', (query, [f'%{value}%']))]
@api.constrains('recurring_task')
def _check_recurring_task(self):
# Deprecated method
# TODO : Remove me in master
return
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
if default is None:
default = {}
if not default.get('name'):
default['name'] = _("%s (copy)", self.name)
if self.recurrence_id:
default['recurrence_id'] = self.recurrence_id.copy().id
return super(Task, self).copy(default)
@api.model
def get_empty_list_help(self, help):
tname = _("task")
project_id = self.env.context.get('default_project_id', False)
if project_id:
name = self.env['project.project'].browse(project_id).label_tasks
if name: tname = name.lower()
self = self.with_context(
empty_list_help_id=self.env.context.get('default_project_id'),
empty_list_help_model='project.project',
empty_list_help_document_name=tname,
)
return super(Task, self).get_empty_list_help(help)
def _valid_field_parameter(self, field, name):
# If the field has `task_dependency_tracking` on we track the changes made in the dependent task on the parent task
return name == 'task_dependency_tracking' or super()._valid_field_parameter(field, name)
@tools.ormcache('self.env.uid', 'self.env.su')
def _get_depends_tracked_fields(self):
""" Returns the set of tracked field names for the current model.
Those fields are the ones tracked in the parent task when using task dependencies.
See :meth:`mail.models.MailThread._get_tracked_fields`"""
fields = {name for name, field in self._fields.items() if getattr(field, 'task_dependency_tracking', None)}
return fields and set(self.fields_get(fields))
# ----------------------------------------
# Case management
# ----------------------------------------
def stage_find(self, section_id, domain=[], order='sequence, id'):
""" Override of the base.stage method
Parameter of the stage search taken from the lead:
- section_id: if set, stages must belong to this section or
be a default stage; if not set, stages must be default
stages
"""
# collect all section_ids
section_ids = []
if section_id:
section_ids.append(section_id)
section_ids.extend(self.mapped('project_id').ids)
search_domain = []
if section_ids:
search_domain = [('|')] * (len(section_ids) - 1)
for section_id in section_ids:
search_domain.append(('project_ids', '=', section_id))
search_domain += list(domain)
# perform search, return the first found
return self.env['project.task.type'].search(search_domain, order=order, limit=1).id
# ------------------------------------------------
# CRUD overrides
# ------------------------------------------------
@api.model
def fields_get(self, allfields=None, attributes=None):
fields = super().fields_get(allfields=allfields, attributes=attributes)
if not self.env.user.has_group('base.group_portal'):
return fields
readable_fields = self.SELF_READABLE_FIELDS
public_fields = {field_name: description for field_name, description in fields.items() if field_name in readable_fields}
writable_fields = self.SELF_WRITABLE_FIELDS
for field_name, description in public_fields.items():
if field_name not in writable_fields and not description.get('readonly', False):
# If the field is not in Writable fields and it is not readonly then we force the readonly to True
description['readonly'] = True
return public_fields
@api.model
def default_get(self, default_fields):
vals = super(Task, self).default_get(default_fields)
days = list(DAYS.keys())
week_start = fields.Datetime.today().weekday()
if all(d in default_fields for d in days):
vals[days[week_start]] = True
if 'repeat_day' in default_fields:
vals['repeat_day'] = str(fields.Datetime.today().day)
if 'repeat_month' in default_fields:
vals['repeat_month'] = self._fields.get('repeat_month').selection[fields.Datetime.today().month - 1][0]
if 'repeat_until' in default_fields:
vals['repeat_until'] = fields.Date.today() + timedelta(days=7)
if 'repeat_weekday' in default_fields:
vals['repeat_weekday'] = self._fields.get('repeat_weekday').selection[week_start][0]
if 'partner_id' in vals and not vals['partner_id']:
# if the default_partner_id=False or no default_partner_id then we search the partner based on the project and parent
project_id = vals.get('project_id')
parent_id = vals.get('parent_id', self.env.context.get('default_parent_id'))
if project_id or parent_id:
partner_id = self._get_default_partner_id(
project_id and self.env['project.project'].browse(project_id),
parent_id and self.env['project.task'].browse(parent_id)
)
if partner_id:
vals['partner_id'] = partner_id
return vals
def _ensure_fields_are_accessible(self, fields, operation='read', check_group_user=True):
"""" ensure all fields are accessible by the current user
This method checks if the portal user can access to all fields given in parameter.
By default, it checks if the current user is a portal user and then checks if all fields are accessible for this user.
:param fields: list of fields to check if the current user can access.
:param operation: contains either 'read' to check readable fields or 'write' to check writable fields.
:param check_group_user: contains boolean value.
- True, if the method has to check if the current user is a portal one.
- False if we are sure the user is a portal user,
"""
assert operation in ('read', 'write'), 'Invalid operation'
if fields and (not check_group_user or self.env.user.has_group('base.group_portal')) and not self.env.su:
unauthorized_fields = set(fields) - (self.SELF_READABLE_FIELDS if operation == 'read' else self.SELF_WRITABLE_FIELDS)
if unauthorized_fields:
if operation == 'read':
error_message = _('You cannot read %s fields in task.', ', '.join(unauthorized_fields))
else:
error_message = _('You cannot write on %s fields in task.', ', '.join(unauthorized_fields))
raise AccessError(error_message)
def read(self, fields=None, load='_classic_read'):
self._ensure_fields_are_accessible(fields)
return super(Task, self).read(fields=fields, load=load)
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
fields_list = ([f.split(':')[0] for f in fields] or [])
if groupby:
fields_groupby = [groupby] if isinstance(groupby, str) else groupby
# only take field name when having ':' e.g 'date_deadline:week' => 'date_deadline'
fields_list += [f.split(':')[0] for f in fields_groupby]
if domain:
fields_list += [term[0].split('.')[0] for term in domain if isinstance(term, (tuple, list)) and term not in [TRUE_LEAF, FALSE_LEAF]]
self._ensure_fields_are_accessible(fields_list)
return super(Task, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
fields_list = {term[0] for term in args if isinstance(term, (tuple, list)) and term not in [TRUE_LEAF, FALSE_LEAF]}
self._ensure_fields_are_accessible(fields_list)
return super(Task, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
def mapped(self, func):
# Note: This will protect the filtered method too
if func and isinstance(func, str):
fields_list = func.split('.')
self._ensure_fields_are_accessible(fields_list)
return super(Task, self).mapped(func)
def filtered_domain(self, domain):
fields_list = [term[0] for term in domain if isinstance(term, (tuple, list)) and term not in [TRUE_LEAF, FALSE_LEAF]]
self._ensure_fields_are_accessible(fields_list)
return super(Task, self).filtered_domain(domain)
def copy_data(self, default=None):
defaults = super().copy_data(default=default)
if self.env.user.has_group('project.group_project_user'):
return defaults
return [{k: v for k, v in default.items() if k in self.SELF_READABLE_FIELDS} for default in defaults]
@api.model
def _ensure_portal_user_can_write(self, fields):
for field in fields:
if field not in self.SELF_WRITABLE_FIELDS:
raise AccessError(_('You have not write access of %s field.') % field)
def _load_records_create(self, vals_list):
projects_with_recurrence = self.env['project.project'].search([('allow_recurring_tasks', '=', True)])
for vals in vals_list:
if vals.get('recurring_task'):
if vals.get('project_id') in projects_with_recurrence.ids and not vals.get('recurrence_id'):
default_val = self.default_get(self._get_recurrence_fields())
vals.update(**default_val)
else:
for field_name in self._get_recurrence_fields() + ['recurring_task']:
vals.pop(field_name, None)
tasks = super()._load_records_create(vals_list)
stage_ids_per_project = defaultdict(list)
for task in tasks:
if task.stage_id and task.stage_id not in task.project_id.type_ids and task.stage_id.id not in stage_ids_per_project[task.project_id]:
stage_ids_per_project[task.project_id].append(task.stage_id.id)
for project, stage_ids in stage_ids_per_project.items():
project.write({'type_ids': [Command.link(stage_id) for stage_id in stage_ids]})
return tasks
@api.model_create_multi
def create(self, vals_list):
is_portal_user = self.env.user.has_group('base.group_portal')
if is_portal_user:
self.check_access_rights('create')
default_stage = dict()
for vals in vals_list:
if is_portal_user:
self._ensure_fields_are_accessible(vals.keys(), operation='write', check_group_user=False)
project_id = vals.get('project_id') or self.env.context.get('default_project_id')
if not vals.get('parent_id'):
# 1) We must initialize display_project_id to follow project_id if there is no parent_id
vals['display_project_id'] = project_id
if project_id and not "company_id" in vals:
vals["company_id"] = self.env["project.project"].browse(
project_id
).company_id.id or self.env.company.id
if project_id and "stage_id" not in vals:
# 1) Allows keeping the batch creation of tasks
# 2) Ensure the defaults are correct (and computed once by project),
# by using default get (instead of _get_default_stage_id or _stage_find),
if project_id not in default_stage:
default_stage[project_id] = self.with_context(
default_project_id=project_id
).default_get(['stage_id']).get('stage_id')
vals["stage_id"] = default_stage[project_id]
# user_ids change: update date_assign
if vals.get('user_ids'):
vals['date_assign'] = fields.Datetime.now()
# Stage change: Update date_end if folded stage and date_last_stage_update
if vals.get('stage_id'):
vals.update(self.update_date_end(vals['stage_id']))
vals['date_last_stage_update'] = fields.Datetime.now()
# recurrence
rec_fields = vals.keys() & self._get_recurrence_fields()
if rec_fields and vals.get('recurring_task') is True:
rec_values = {rec_field: vals[rec_field] for rec_field in rec_fields}
rec_values['next_recurrence_date'] = fields.Datetime.today()
recurrence = self.env['project.task.recurrence'].create(rec_values)
vals['recurrence_id'] = recurrence.id
# The sudo is required for a portal user as the record creation
# requires the read access on other models, as mail.template
# in order to compute the field tracking
was_in_sudo = self.env.su
if is_portal_user:
ctx = {
key: value for key, value in self.env.context.items()
if key == 'default_project_id' \
or not key.startswith('default_') \
or key[8:] in self.SELF_WRITABLE_FIELDS
}
self = self.with_context(ctx).sudo()
tasks = super(Task, self).create(vals_list)
tasks._populate_missing_personal_stages()
self._task_message_auto_subscribe_notify({task: task.user_ids - self.env.user for task in tasks})
# in case we were already in sudo, we don't check the rights.
if is_portal_user and not was_in_sudo:
# since we use sudo to create tasks, we need to check
# if the portal user could really create the tasks based on the ir rule.
tasks.with_user(self.env.user).check_access_rule('create')
for task in tasks:
if task.project_id.privacy_visibility == 'portal':
task._portal_ensure_token()
return tasks
def write(self, vals):
if len(self) == 1:
handle_history_divergence(self, 'description', vals)
portal_can_write = False
if self.env.user.has_group('base.group_portal') and not self.env.su:
# Check if all fields in vals are in SELF_WRITABLE_FIELDS
self._ensure_fields_are_accessible(vals.keys(), operation='write', check_group_user=False)
self.check_access_rights('write')
self.check_access_rule('write')
portal_can_write = True
now = fields.Datetime.now()
if 'parent_id' in vals and vals['parent_id'] in self.ids:
raise UserError(_("Sorry. You can't set a task as its parent task."))
if 'active' in vals and not vals.get('active') and any(self.mapped('recurrence_id')):
# TODO: show a dialog to stop the recurrence
raise UserError(_('You cannot archive recurring tasks. Please disable the recurrence first.'))
if 'recurrence_id' in vals and vals.get('recurrence_id') and any(not task.active for task in self):
raise UserError(_('Archived tasks cannot be recurring. Please unarchive the task first.'))
# stage change: update date_last_stage_update
if 'stage_id' in vals:
vals.update(self.update_date_end(vals['stage_id']))
vals['date_last_stage_update'] = now
# reset kanban state when changing stage
if 'kanban_state' not in vals:
vals['kanban_state'] = 'normal'
# user_ids change: update date_assign
if vals.get('user_ids') and 'date_assign' not in vals:
vals['date_assign'] = now
# recurrence fields
rec_fields = vals.keys() & self._get_recurrence_fields()
if rec_fields:
rec_values = {rec_field: vals[rec_field] for rec_field in rec_fields}
for task in self:
if task.recurrence_id:
task.recurrence_id.write(rec_values)
elif vals.get('recurring_task'):
rec_values['next_recurrence_date'] = fields.Datetime.today()
recurrence = self.env['project.task.recurrence'].create(rec_values)
task.recurrence_id = recurrence.id
if 'recurring_task' in vals and not vals.get('recurring_task'):
self.recurrence_id.unlink()
tasks = self
recurrence_update = vals.pop('recurrence_update', 'this')
if recurrence_update != 'this':
recurrence_domain = []
if recurrence_update == 'subsequent':
for task in self:
recurrence_domain = OR([recurrence_domain, ['&', ('recurrence_id', '=', task.recurrence_id.id), ('create_date', '>=', task.create_date)]])
else:
recurrence_domain = [('recurrence_id', 'in', self.recurrence_id.ids)]
tasks |= self.env['project.task'].search(recurrence_domain)
# The sudo is required for a portal user as the record update
# requires the write access on others models, as rating.rating
# in order to keep the same name than the task.
if portal_can_write:
tasks = tasks.sudo()
# Track user_ids to send assignment notifications
old_user_ids = {t: t.user_ids for t in self}
result = super(Task, tasks).write(vals)
self._task_message_auto_subscribe_notify({task: task.user_ids - old_user_ids[task] - self.env.user for task in self})
if 'user_ids' in vals:
tasks._populate_missing_personal_stages()
# rating on stage
if 'stage_id' in vals and vals.get('stage_id'):
tasks.filtered(lambda x: x.project_id.rating_active and x.project_id.rating_status == 'stage')._send_task_rating_mail(force_send=True)
for task in self:
if task.display_project_id != task.project_id and not task.parent_id:
# We must make the display_project_id follow the project_id if no parent_id set
task.display_project_id = task.project_id
return result
def update_date_end(self, stage_id):
project_task_type = self.env['project.task.type'].browse(stage_id)
if project_task_type.fold or project_task_type.is_closed:
return {'date_end': fields.Datetime.now()}
return {'date_end': False}
@api.ondelete(at_uninstall=False)
def _unlink_except_recurring(self):
if any(self.mapped('recurrence_id')):
# TODO: show a dialog to stop the recurrence
raise UserError(_('You cannot delete recurring tasks. Please disable the recurrence first.'))
# ---------------------------------------------------
# Subtasks
# ---------------------------------------------------
@api.depends('parent_id', 'project_id', 'display_project_id')
def _compute_partner_id(self):
""" Compute the partner_id when the tasks have no partner_id.
Use the project partner_id if any, or else the parent task partner_id.
"""
for task in self.filtered(lambda task: not task.partner_id):
# When the task has a parent task, the display_project_id can be False or the project choose by the user for this task.
project = task.display_project_id if task.parent_id and task.display_project_id else task.project_id
task.partner_id = self._get_default_partner_id(project, task.parent_id)
@api.depends('partner_id.email', 'parent_id.email_from')
def _compute_email_from(self):
for task in self:
task.email_from = task.partner_id.email or ((task.partner_id or task.parent_id) and task.email_from) or task.parent_id.email_from
@api.depends('parent_id.project_id', 'display_project_id')
def _compute_project_id(self):
for task in self:
if task.parent_id:
task.project_id = task.display_project_id or task.parent_id.project_id
# ---------------------------------------------------
# Mail gateway
# ---------------------------------------------------
@api.model
def _task_message_auto_subscribe_notify(self, users_per_task):
# Utility method to send assignation notification upon writing/creation.
template_id = self.env['ir.model.data']._xmlid_to_res_id('project.project_message_user_assigned', raise_if_not_found=False)
if not template_id:
return
view = self.env['ir.ui.view'].browse(template_id)
task_model_description = self.env['ir.model']._get(self._name).display_name
for task, users in users_per_task.items():
if not users:
continue
values = {
'object': task,
'model_description': task_model_description,
'access_link': task._notify_get_action_link('view'),
}
for user in users:
values.update(assignee_name=user.sudo().name)
assignation_msg = view._render(values, engine='ir.qweb', minimal_qcontext=True)
assignation_msg = self.env['mail.render.mixin']._replace_local_links(assignation_msg)
task.message_notify(
subject=_('You have been assigned to %s', task.display_name),
body=assignation_msg,
partner_ids=user.partner_id.ids,
record_name=task.display_name,
email_layout_xmlid='mail.mail_notification_light',
model_description=task_model_description,
)
def _message_auto_subscribe_followers(self, updated_values, default_subtype_ids):
if 'user_ids' not in updated_values:
return []
# Since the changes to user_ids becoming a m2m, the default implementation of this function
# could not work anymore, override the function to keep the functionality.
new_followers = []
# Normalize input to tuple of ids
value = self._fields['user_ids'].convert_to_cache(updated_values.get('user_ids', []), self.env['project.task'], validate=False)
users = self.env['res.users'].browse(value)
for user in users:
try:
if user.partner_id:
# The you have been assigned notification is handled separately
new_followers.append((user.partner_id.id, default_subtype_ids, False))
except:
pass
return new_followers
def _mail_track(self, tracked_fields, initial_values):
changes, tracking_value_ids = super()._mail_track(tracked_fields, initial_values)
# Many2many tracking
if len(changes) > len(tracking_value_ids):
for changed_field in changes:
if tracked_fields[changed_field]['type'] in ['one2many', 'many2many']:
field = self.env['ir.model.fields']._get(self._name, changed_field)
vals = {
'field': field.id,
'field_desc': field.field_description,
'field_type': field.ttype,
'tracking_sequence': field.tracking,
'old_value_char': ', '.join(initial_values[changed_field].mapped('name')),
'new_value_char': ', '.join(self[changed_field].mapped('name')),
}
tracking_value_ids.append(Command.create(vals))
# Track changes on depending tasks
depends_tracked_fields = self._get_depends_tracked_fields()
depends_changes = changes & depends_tracked_fields
if depends_changes and self.allow_task_dependencies and self.user_has_groups('project.group_project_task_dependencies'):
parent_ids = self.dependent_ids
if parent_ids:
fields_to_ids = self.env['ir.model.fields']._get_ids('project.task')
field_ids = [fields_to_ids.get(name) for name in depends_changes]
depends_tracking_value_ids = [
tracking_values for tracking_values in tracking_value_ids
if tracking_values[2]['field'] in field_ids
]
subtype = self.env['ir.model.data']._xmlid_to_res_id('project.mt_task_dependency_change')
# We want to include the original subtype message coming from the child task
# for example when the stage changes the message in the chatter starts with 'Stage Changed'
child_subtype = self._track_subtype(dict((col_name, initial_values[col_name]) for col_name in changes))
child_subtype_info = child_subtype.description or child_subtype.name if child_subtype else False
# NOTE: the subtype does not have a description on purpose, otherwise the description would be put
# at the end of the message instead of at the top, we use the name here
body = self.env['ir.qweb']._render('project.task_track_depending_tasks', {
'child': self,
'child_subtype': child_subtype_info,
})
for p in parent_ids:
p.message_post(body=body, subtype_id=subtype, tracking_value_ids=depends_tracking_value_ids)
return changes, tracking_value_ids
def _track_template(self, changes):
res = super(Task, self)._track_template(changes)
test_task = self[0]
if 'stage_id' in changes and test_task.stage_id.mail_template_id:
res['stage_id'] = (test_task.stage_id.mail_template_id, {
'auto_delete_message': True,
'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
'email_layout_xmlid': 'mail.mail_notification_light'
})
return res
def _creation_subtype(self):
return self.env.ref('project.mt_task_new')
def _track_subtype(self, init_values):
self.ensure_one()
if 'kanban_state_label' in init_values and self.kanban_state == 'blocked':
return self.env.ref('project.mt_task_blocked')
elif 'kanban_state_label' in init_values and self.kanban_state == 'done':
return self.env.ref('project.mt_task_ready')
elif 'stage_id' in init_values:
return self.env.ref('project.mt_task_stage')
return super(Task, self)._track_subtype(init_values)
def _mail_get_message_subtypes(self):
res = super()._mail_get_message_subtypes()
if len(self) == 1:
dependency_subtype = self.env.ref('project.mt_task_dependency_change')
if ((self.project_id and not self.project_id.allow_task_dependencies)\
or (not self.project_id and not self.user_has_groups('project.group_project_task_dependencies')))\
and dependency_subtype in res:
res -= dependency_subtype
return res
def _notify_get_groups(self, msg_vals=None):
""" Handle project users and managers recipients that can assign
tasks and create new one directly from notification emails. Also give
access button to portal users and portal customers. If they are notified
they should probably have access to the document. """
groups = super(Task, self)._notify_get_groups(msg_vals=msg_vals)
local_msg_vals = dict(msg_vals or {})
self.ensure_one()
project_user_group_id = self.env.ref('project.group_project_user').id
new_group = ('group_project_user', lambda pdata: pdata['type'] == 'user' and project_user_group_id in pdata['groups'], {})
groups = [new_group] + groups
if self.project_privacy_visibility == 'portal':
groups.insert(0, (
'allowed_portal_users',
lambda pdata: pdata['type'] == 'portal',
{}
))
portal_privacy = self.project_id.privacy_visibility == 'portal'
for group_name, group_method, group_data in groups:
if group_name in ('customer', 'user') or group_name == 'portal_customer' and not portal_privacy:
group_data['has_button_access'] = False
elif group_name == 'portal_customer' and portal_privacy:
group_data['has_button_access'] = True
return groups
def _notify_get_reply_to(self, default=None, records=None, company=None, doc_names=None):
""" Override to set alias of tasks to their project if any. """
aliases = self.sudo().mapped('project_id')._notify_get_reply_to(default=default, records=None, company=company, doc_names=None)
res = {task.id: aliases.get(task.project_id.id) for task in self}
leftover = self.filtered(lambda rec: not rec.project_id)
if leftover:
res.update(super(Task, leftover)._notify_get_reply_to(default=default, records=None, company=company, doc_names=doc_names))
return res
def email_split(self, msg):
email_list = tools.email_split((msg.get('to') or '') + ',' + (msg.get('cc') or ''))
# check left-part is not already an alias
aliases = self.mapped('project_id.alias_name')
return [x for x in email_list if x.split('@')[0] not in aliases]
@api.model
def message_new(self, msg, custom_values=None):
""" Overrides mail_thread message_new that is called by the mailgateway
through message_process.
This override updates the document according to the email.
"""
# remove default author when going through the mail gateway. Indeed we
# do not want to explicitly set user_id to False; however we do not
# want the gateway user to be responsible if no other responsible is
# found.
create_context = dict(self.env.context or {})
create_context['default_user_ids'] = False
if custom_values is None:
custom_values = {}
defaults = {
'name': msg.get('subject') or _("No Subject"),
'email_from': msg.get('from'),
'planned_hours': 0.0,
'partner_id': msg.get('author_id')
}
defaults.update(custom_values)
task = super(Task, self.with_context(create_context)).message_new(msg, custom_values=defaults)
email_list = task.email_split(msg)
partner_ids = [p.id for p in self.env['mail.thread']._mail_find_partner_from_emails(email_list, records=task, force_create=False) if p]
task.message_subscribe(partner_ids)
return task
def message_update(self, msg, update_vals=None):
""" Override to update the task according to the email. """
email_list = self.email_split(msg)
partner_ids = [p.id for p in self.env['mail.thread']._mail_find_partner_from_emails(email_list, records=self, force_create=False) if p]
self.message_subscribe(partner_ids)
return super(Task, self).message_update(msg, update_vals=update_vals)
def _message_get_suggested_recipients(self):
recipients = super(Task, self)._message_get_suggested_recipients()
for task in self:
if task.partner_id:
reason = _('Customer Email') if task.partner_id.email else _('Customer')
task._message_add_suggested_recipient(recipients, partner=task.partner_id, reason=reason)
elif task.email_from:
task._message_add_suggested_recipient(recipients, email=task.email_from, reason=_('Customer Email'))
return recipients
def _notify_email_header_dict(self):
headers = super(Task, self)._notify_email_header_dict()
if self.project_id:
current_objects = [h for h in headers.get('X-Odoo-Objects', '').split(',') if h]
current_objects.insert(0, 'project.project-%s, ' % self.project_id.id)
headers['X-Odoo-Objects'] = ','.join(current_objects)
if self.tag_ids:
headers['X-Odoo-Tags'] = ','.join(self.tag_ids.mapped('name'))
return headers
def _message_post_after_hook(self, message, msg_vals):
if message.attachment_ids and not self.displayed_image_id:
image_attachments = message.attachment_ids.filtered(lambda a: a.mimetype == 'image')
if image_attachments:
self.displayed_image_id = image_attachments[0]
if self.email_from and not self.partner_id:
# we consider that posting a message with a specified recipient (not a follower, a specific one)
# on a document without customer means that it was created through the chatter using
# suggested recipients. This heuristic allows to avoid ugly hacks in JS.
new_partner = message.partner_ids.filtered(lambda partner: partner.email == self.email_from)
if new_partner:
self.search([
('partner_id', '=', False),
('email_from', '=', new_partner.email),
('stage_id.fold', '=', False)]).write({'partner_id': new_partner.id})
return super(Task, self)._message_post_after_hook(message, msg_vals)
def action_assign_to_me(self):
self.write({'user_ids': [(4, self.env.user.id)]})
def action_unassign_me(self):
self.write({'user_ids': [Command.unlink(self.env.uid)]})
# If depth == 1, return only direct children
# If depth == 3, return children to third generation
# If depth <= 0, return all children without depth limit
def _get_all_subtasks(self, depth=0):
children = self.mapped('child_ids')
if not children:
return self.env['project.task']
if depth == 1:
return children
return children + children._get_all_subtasks(depth - 1)
def action_open_parent_task(self):
return {
'name': _('Parent Task'),
'view_mode': 'form',
'res_model': 'project.task',
'res_id': self.parent_id.id,
'type': 'ir.actions.act_window',
'context': self._context
}
# ------------
# Actions
# ------------
def action_open_task(self):
return {
'view_mode': 'form',
'res_model': 'project.task',
'res_id': self.id,
'type': 'ir.actions.act_window',
'context': self._context
}
def action_dependent_tasks(self):
self.ensure_one()
action = {
'res_model': 'project.task',
'type': 'ir.actions.act_window',
'context': {**self._context, 'default_depend_on_ids': [Command.link(self.id)], 'show_project_update': False},
'domain': [('depend_on_ids', '=', self.id)],
}
if self.dependent_tasks_count == 1:
action['view_mode'] = 'form'
action['res_id'] = self.dependent_ids.id
action['views'] = [(False, 'form')]
else:
action['name'] = _('Dependent Tasks')
action['view_mode'] = 'tree,form,kanban,calendar,pivot,graph,activity'
return action
def action_recurring_tasks(self):
return {
'name': 'Tasks in Recurrence',
'type': 'ir.actions.act_window',
'res_model': 'project.task',
'view_mode': 'tree,form,kanban,calendar,pivot,graph,activity',
'domain': [('recurrence_id', 'in', self.recurrence_id.ids)],
}
def action_stop_recurrence(self):
tasks = self.env['project.task'].with_context(active_test=False).search([('recurrence_id', 'in', self.recurrence_id.ids)])
tasks.write({'recurring_task': False})
self.recurrence_id.unlink()
def action_continue_recurrence(self):
self.recurrence_id = False
self.recurring_task = False
# ---------------------------------------------------
# Rating business
# ---------------------------------------------------
def _send_task_rating_mail(self, force_send=False):
for task in self:
rating_template = task.stage_id.rating_template_id
if rating_template:
task.rating_send_request(rating_template, lang=task.partner_id.lang, force_send=force_send)
def rating_get_partner_id(self):
res = super(Task, self).rating_get_partner_id()
if not res and self.project_id.partner_id:
return self.project_id.partner_id
return res
def rating_apply(self, rate, token=None, feedback=None, subtype_xmlid=None):
return super(Task, self).rating_apply(rate, token=token, feedback=feedback, subtype_xmlid="project.mt_task_rating")
def _rating_get_parent_field_name(self):
return 'project_id'
def rating_get_rated_partner_id(self):
""" Overwrite since we have user_ids and not user_id """
tasks_with_one_user = self.filtered(lambda task: len(task.user_ids) == 1 and task.user_ids.partner_id)
return tasks_with_one_user.user_ids.partner_id or self.env['res.partner']
# ---------------------------------------------------
# Privacy
# ---------------------------------------------------
def _change_project_privacy_visibility(self):
for task in self.filtered(lambda t: t.project_privacy_visibility != 'portal'):
portal_users = task.message_partner_ids.user_ids.filtered('share')
task.message_unsubscribe(partner_ids=portal_users.partner_id.ids)
# ---------------------------------------------------
# Analytic accounting
# ---------------------------------------------------
def _get_task_analytic_account_id(self):
self.ensure_one()
return self.analytic_account_id or self.project_analytic_account_id
class ProjectTags(models.Model):
""" Tags of project's tasks """
_name = "project.tags"
_description = "Project Tags"
def _get_default_color(self):
return randint(1, 11)
name = fields.Char('Name', required=True)
color = fields.Integer(string='Color', default=_get_default_color)
_sql_constraints = [
('name_uniq', 'unique (name)', "Tag name already exists!"),
]
| 50.81203
| 114,886
|
7,290
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from psycopg2 import sql
from odoo import api, fields, models, tools
from odoo.osv import expression
from odoo.tools import OrderedSet
class ReportProjectTaskBurndownChart(models.Model):
_name = 'project.task.burndown.chart.report'
_description = 'Burndown Chart'
_auto = False
_order = 'date'
project_id = fields.Many2one('project.project', readonly=True)
display_project_id = fields.Many2one('project.project', readonly=True)
stage_id = fields.Many2one('project.task.type', readonly=True)
date = fields.Datetime('Date', readonly=True)
user_ids = fields.Many2many('res.users', relation='project_task_user_rel', column1='task_id', column2='user_id',
string='Assignees', readonly=True)
date_assign = fields.Datetime(string='Assignment Date', readonly=True)
date_deadline = fields.Date(string='Deadline', readonly=True)
partner_id = fields.Many2one('res.partner', string='Customer', readonly=True)
nb_tasks = fields.Integer('# of Tasks', readonly=True, group_operator="sum")
date_group_by = fields.Selection(
[
('day', 'By Day'),
('month', 'By Month'),
('quarter', 'By quarter'),
('year', 'By Year')
], string="Date Group By", readonly=True)
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
date_group_bys = []
groupby = [groupby] if isinstance(groupby, str) else list(OrderedSet(groupby))
for gb in groupby:
if gb.startswith('date:'):
date_group_bys.append(gb.split(':')[-1])
date_domains = []
for gb in date_group_bys:
date_domains = expression.OR([date_domains, [('date_group_by', '=', gb)]])
domain = expression.AND([domain, date_domains])
res = super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
return res
def init(self):
query = """
WITH all_moves_stage_task AS (
-- Here we compute all previous stage in tracking values
-- We're missing the last reached stage
-- And the tasks without any stage change (which, by definition, are at the last stage)
SELECT pt.project_id,
pt.id as task_id,
pt.display_project_id,
COALESCE(LAG(mm.date) OVER (PARTITION BY mm.res_id ORDER BY mm.id), pt.create_date) as date_begin,
mm.date as date_end,
mtv.old_value_integer as stage_id,
pt.date_assign,
pt.date_deadline,
pt.partner_id
FROM project_task pt
JOIN mail_message mm ON mm.res_id = pt.id
AND mm.message_type = 'notification'
AND mm.model = 'project.task'
JOIN mail_tracking_value mtv ON mm.id = mtv.mail_message_id
JOIN ir_model_fields imf ON mtv.field = imf.id
AND imf.model = 'project.task'
AND imf.name = 'stage_id'
JOIN project_task_type_rel pttr ON pttr.type_id = mtv.old_value_integer
AND pttr.project_id = pt.project_id
WHERE pt.active
--We compute the last reached stage
UNION ALL
SELECT pt.project_id,
pt.id as task_id,
pt.display_project_id,
COALESCE(md.date, pt.create_date) as date_begin,
(CURRENT_DATE + interval '1 month')::date as date_end,
pt.stage_id,
pt.date_assign,
pt.date_deadline,
pt.partner_id
FROM project_task pt
LEFT JOIN LATERAL (SELECT mm.date
FROM mail_message mm
JOIN mail_tracking_value mtv ON mm.id = mtv.mail_message_id
JOIN ir_model_fields imf ON mtv.field = imf.id
AND imf.model = 'project.task'
AND imf.name = 'stage_id'
WHERE mm.res_id = pt.id
AND mm.message_type = 'notification'
AND mm.model = 'project.task'
ORDER BY mm.id DESC
FETCH FIRST ROW ONLY) md ON TRUE
WHERE pt.active
)
SELECT (task_id*10^7 + 10^6 + to_char(d, 'YYMMDD')::integer)::bigint as id,
project_id,
task_id,
display_project_id,
stage_id,
d as date,
date_assign,
date_deadline,
partner_id,
'day' AS date_group_by,
1 AS nb_tasks
FROM all_moves_stage_task t
JOIN LATERAL generate_series(t.date_begin, t.date_end-interval '1 day', '1 day') d ON TRUE
UNION ALL
SELECT (task_id*10^7 + 2*10^6 + to_char(d, 'YYMMDD')::integer)::bigint as id,
project_id,
task_id,
display_project_id,
stage_id,
date_trunc('week', d) as date,
date_assign,
date_deadline,
partner_id,
'week' AS date_group_by,
1 AS nb_tasks
FROM all_moves_stage_task t
JOIN LATERAL generate_series(t.date_begin, t.date_end, '1 week') d ON TRUE
WHERE date_trunc('week', t.date_begin) <= date_trunc('week', d)
AND date_trunc('week', t.date_end) > date_trunc('week', d)
UNION ALL
SELECT (task_id*10^7 + 3*10^6 + to_char(d, 'YYMMDD')::integer)::bigint as id,
project_id,
task_id,
display_project_id,
stage_id,
date_trunc('month', d) as date,
date_assign,
date_deadline,
partner_id,
'month' AS date_group_by,
1 AS nb_tasks
FROM all_moves_stage_task t
JOIN LATERAL generate_series(t.date_begin, t.date_end, '1 month') d ON TRUE
WHERE date_trunc('month', t.date_begin) <= date_trunc('month', d)
AND date_trunc('month', t.date_end) > date_trunc('month', d)
UNION ALL
SELECT (task_id*10^7 + 4*10^6 + to_char(d, 'YYMMDD')::integer)::bigint as id,
project_id,
task_id,
display_project_id,
stage_id,
date_trunc('quarter', d) as date,
date_assign,
date_deadline,
partner_id,
'quarter' AS date_group_by,
1 AS nb_tasks
FROM all_moves_stage_task t
JOIN LATERAL generate_series(t.date_begin, t.date_end, '3 month') d ON TRUE
WHERE date_trunc('quarter', t.date_begin) <= date_trunc('quarter', d)
AND date_trunc('quarter', t.date_end) > date_trunc('quarter', d)
UNION ALL
SELECT (task_id*10^7 + 5*10^6 + to_char(d, 'YYMMDD')::integer)::bigint as id,
project_id,
task_id,
display_project_id,
stage_id,
date_trunc('year', d) as date,
date_assign,
date_deadline,
partner_id,
'year' AS date_group_by,
1 AS nb_tasks
FROM all_moves_stage_task t
JOIN LATERAL generate_series(t.date_begin, t.date_end, '1 year') d ON TRUE
WHERE date_trunc('year', t.date_begin) <= date_trunc('year', d)
AND date_trunc('year', t.date_end) > date_trunc('year', d)
"""
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute(
sql.SQL("CREATE or REPLACE VIEW {} as ({})").format(
sql.Identifier(self._table),
sql.SQL(query)
)
)
| 37.005076
| 7,290
|
4,916
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, tools
class ReportProjectTaskUser(models.Model):
_name = "report.project.task.user"
_description = "Tasks Analysis"
_order = 'name desc, project_id'
_auto = False
name = fields.Char(string='Task', readonly=True)
user_ids = fields.Many2many('res.users', relation='project_task_user_rel', column1='task_id', column2='user_id',
string='Assignees', readonly=True)
create_date = fields.Datetime("Create Date", readonly=True)
date_assign = fields.Datetime(string='Assignment Date', readonly=True)
date_end = fields.Datetime(string='Ending Date', readonly=True)
date_deadline = fields.Date(string='Deadline', readonly=True)
date_last_stage_update = fields.Datetime(string='Last Stage Update', readonly=True)
project_id = fields.Many2one('project.project', string='Project', readonly=True)
working_days_close = fields.Float(string='Working Days to Close',
digits=(16,2), readonly=True, group_operator="avg",
help="Number of Working Days to close the task")
working_days_open = fields.Float(string='Working Days to Assign',
digits=(16,2), readonly=True, group_operator="avg",
help="Number of Working Days to open the task")
delay_endings_days = fields.Float(string='Days to Deadline', digits=(16, 2), group_operator="avg", readonly=True)
nbr = fields.Integer('# of Tasks', readonly=True) # TDE FIXME master: rename into nbr_tasks
working_hours_open = fields.Float(string='Working Hours to Assign', digits=(16, 2), readonly=True, group_operator="avg", help="Number of Working Hours to open the task")
working_hours_close = fields.Float(string='Working Hours to Close', digits=(16, 2), readonly=True, group_operator="avg", help="Number of Working Hours to close the task")
rating_last_value = fields.Float('Rating Value (/5)', group_operator="avg", readonly=True, groups="project.group_project_rating")
priority = fields.Selection([
('0', 'Low'),
('1', 'Normal'),
('2', 'High')
], readonly=True, string="Priority")
state = fields.Selection([
('normal', 'In Progress'),
('blocked', 'Blocked'),
('done', 'Ready for Next Stage')
], string='Kanban State', readonly=True)
company_id = fields.Many2one('res.company', string='Company', readonly=True)
partner_id = fields.Many2one('res.partner', string='Customer', readonly=True)
stage_id = fields.Many2one('project.task.type', string='Stage', readonly=True)
task_id = fields.Many2one('project.task', string='Tasks', readonly=True)
def _select(self):
select_str = """
SELECT
(select 1 ) AS nbr,
t.id as id,
t.id as task_id,
t.create_date as create_date,
t.date_assign as date_assign,
t.date_end as date_end,
t.date_last_stage_update as date_last_stage_update,
t.date_deadline as date_deadline,
t.project_id,
t.priority,
t.name as name,
t.company_id,
t.partner_id,
t.stage_id as stage_id,
t.kanban_state as state,
NULLIF(t.rating_last_value, 0) as rating_last_value,
t.working_days_close as working_days_close,
t.working_days_open as working_days_open,
t.working_hours_open as working_hours_open,
t.working_hours_close as working_hours_close,
(extract('epoch' from (t.date_deadline-(now() at time zone 'UTC'))))/(3600*24) as delay_endings_days
"""
return select_str
def _group_by(self):
group_by_str = """
GROUP BY
t.id,
t.create_date,
t.write_date,
t.date_assign,
t.date_end,
t.date_deadline,
t.date_last_stage_update,
t.project_id,
t.priority,
t.name,
t.company_id,
t.partner_id,
t.stage_id
"""
return group_by_str
def init(self):
tools.drop_view_if_exists(self._cr, self._table)
self._cr.execute("""
CREATE view %s as
%s
FROM project_task t
LEFT JOIN project_task_user_rel tu on t.id=tu.task_id
WHERE t.active = 'true'
AND t.project_id IS NOT NULL
%s
""" % (self._table, self._select(), self._group_by()))
| 47.269231
| 4,916
|
21,800
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import OrderedDict
from operator import itemgetter
from markupsafe import Markup
from odoo import conf, http, _
from odoo.exceptions import AccessError, MissingError
from odoo.http import request
from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager
from odoo.tools import groupby as groupbyelem
from odoo.osv.expression import OR, AND
from odoo.addons.web.controllers.main import HomeStaticTemplateHelpers
class ProjectCustomerPortal(CustomerPortal):
def _prepare_home_portal_values(self, counters):
values = super()._prepare_home_portal_values(counters)
if 'project_count' in counters:
values['project_count'] = request.env['project.project'].search_count([]) \
if request.env['project.project'].check_access_rights('read', raise_exception=False) else 0
if 'task_count' in counters:
values['task_count'] = request.env['project.task'].search_count([('project_id', '!=', False)]) \
if request.env['project.task'].check_access_rights('read', raise_exception=False) else 0
return values
# ------------------------------------------------------------
# My Project
# ------------------------------------------------------------
def _project_get_page_view_values(self, project, access_token, page=1, date_begin=None, date_end=None, sortby=None, search=None, search_in='content', groupby=None, **kwargs):
# TODO: refactor this because most of this code is duplicated from portal_my_tasks method
values = self._prepare_portal_layout_values()
searchbar_sortings = self._task_get_searchbar_sortings()
searchbar_inputs = self._task_get_searchbar_inputs()
searchbar_groupby = self._task_get_searchbar_groupby()
# default sort by value
if not sortby:
sortby = 'date'
order = searchbar_sortings[sortby]['order']
# default filter by value
domain = [('project_id', '=', project.id)]
# default group by value
if not groupby:
groupby = 'project'
if date_begin and date_end:
domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
# search
if search and search_in:
domain += self._task_get_search_domain(search_in, search)
Task = request.env['project.task']
if access_token:
Task = Task.sudo()
elif not request.env.user._is_public():
domain = AND([domain, request.env['ir.rule']._compute_domain(Task._name, 'read')])
Task = Task.sudo()
# task count
task_count = Task.search_count(domain)
# pager
url = "/my/project/%s" % project.id
pager = portal_pager(
url=url,
url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'groupby': groupby, 'search_in': search_in, 'search': search, 'access_token': access_token},
total=task_count,
page=page,
step=self._items_per_page
)
# content according to pager and archive selected
order = self._task_get_order(order, groupby)
tasks = Task.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])
request.session['my_project_tasks_history'] = tasks.ids[:100]
groupby_mapping = self._task_get_groupby_mapping()
group = groupby_mapping.get(groupby)
if group:
grouped_tasks = [Task.concat(*g) for k, g in groupbyelem(tasks, itemgetter(group))]
else:
grouped_tasks = [tasks]
values.update(
date=date_begin,
date_end=date_end,
grouped_tasks=grouped_tasks,
page_name='project',
default_url=url,
pager=pager,
searchbar_sortings=searchbar_sortings,
searchbar_groupby=searchbar_groupby,
searchbar_inputs=searchbar_inputs,
search_in=search_in,
search=search,
sortby=sortby,
groupby=groupby,
project=project,
)
return self._get_page_view_values(project, access_token, values, 'my_projects_history', False, **kwargs)
@http.route(['/my/projects', '/my/projects/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_projects(self, page=1, date_begin=None, date_end=None, sortby=None, **kw):
values = self._prepare_portal_layout_values()
Project = request.env['project.project']
domain = []
searchbar_sortings = {
'date': {'label': _('Newest'), 'order': 'create_date desc'},
'name': {'label': _('Name'), 'order': 'name'},
}
if not sortby:
sortby = 'date'
order = searchbar_sortings[sortby]['order']
if date_begin and date_end:
domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
# projects count
project_count = Project.search_count(domain)
# pager
pager = portal_pager(
url="/my/projects",
url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby},
total=project_count,
page=page,
step=self._items_per_page
)
# content according to pager and archive selected
projects = Project.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])
request.session['my_projects_history'] = projects.ids[:100]
values.update({
'date': date_begin,
'date_end': date_end,
'projects': projects,
'page_name': 'project',
'default_url': '/my/projects',
'pager': pager,
'searchbar_sortings': searchbar_sortings,
'sortby': sortby
})
return request.render("project.portal_my_projects", values)
@http.route(['/my/project/<int:project_id>', '/my/project/<int:project_id>/page/<int:page>'], type='http', auth="public", website=True)
def portal_my_project(self, project_id=None, access_token=None, page=1, date_begin=None, date_end=None, sortby=None, search=None, search_in='content', groupby=None, **kw):
try:
project_sudo = self._document_check_access('project.project', project_id, access_token)
except (AccessError, MissingError):
return request.redirect('/my')
if project_sudo.collaborator_count and project_sudo.with_user(request.env.user)._check_project_sharing_access():
return request.render("project.project_sharing_portal", {'project_id': project_id})
project_sudo = project_sudo if access_token else project_sudo.with_user(request.env.user)
values = self._project_get_page_view_values(project_sudo, access_token, page, date_begin, date_end, sortby, search, search_in, groupby, **kw)
values['task_url'] = 'project/%s/task' % project_id
return request.render("project.portal_my_project", values)
def _prepare_project_sharing_session_info(self, project):
session_info = request.env['ir.http'].session_info()
user_context = request.session.get_context() if request.session.uid else {}
mods = conf.server_wide_modules or []
qweb_checksum = HomeStaticTemplateHelpers.get_qweb_templates_checksum(debug=request.session.debug, bundle="project.assets_qweb")
if request.env.lang:
lang = request.env.lang
session_info['user_context']['lang'] = lang
# Update Cache
user_context['lang'] = lang
lang = user_context.get("lang")
translation_hash = request.env['ir.translation'].get_web_translations_hash(mods, lang)
cache_hashes = {
"qweb": qweb_checksum,
"translations": translation_hash,
}
project_company = project.company_id
session_info.update(
cache_hashes=cache_hashes,
action_name='project.project_sharing_project_task_action',
project_id=project.id,
user_companies={
'current_company': project_company.id,
'allowed_companies': {
project_company.id: {
'id': project_company.id,
'name': project_company.name,
},
},
},
# FIXME: See if we prefer to give only the currency that the portal user just need to see the correct information in project sharing
currencies=request.env['ir.http'].get_currencies(),
)
return session_info
@http.route("/my/project/<int:project_id>/project_sharing", type="http", auth="user", methods=['GET'])
def render_project_backend_view(self, project_id):
project = request.env['project.project'].sudo().browse(project_id)
if not project.exists() or not project.with_user(request.env.user)._check_project_sharing_access():
return request.not_found()
return request.render(
'project.project_sharing_embed',
{'session_info': self._prepare_project_sharing_session_info(project)},
)
@http.route('/my/project/<int:project_id>/task/<int:task_id>', type='http', auth='public', website=True)
def portal_my_project_task(self, project_id=None, task_id=None, access_token=None, **kw):
try:
project_sudo = self._document_check_access('project.project', project_id, access_token)
except (AccessError, MissingError):
return request.redirect('/my')
Task = request.env['project.task']
if access_token:
Task = Task.sudo()
task_sudo = Task.search([('project_id', '=', project_id), ('id', '=', task_id)], limit=1).sudo()
task_sudo.attachment_ids.generate_access_token()
values = self._task_get_page_view_values(task_sudo, access_token, project=project_sudo, **kw)
values['project'] = project_sudo
return request.render("project.portal_my_task", values)
# ------------------------------------------------------------
# My Task
# ------------------------------------------------------------
def _task_get_page_view_values(self, task, access_token, **kwargs):
project = kwargs.get('project')
if project:
project_accessible = True
page_name = 'project_task'
history = 'my_project_tasks_history'
else:
page_name = 'task'
history = 'my_tasks_history'
try:
project_accessible = bool(task.project_id.id and self._document_check_access('project.project', task.project_id.id))
except (AccessError, MissingError):
project_accessible = False
values = {
'page_name': page_name,
'task': task,
'user': request.env.user,
'project_accessible': project_accessible,
}
values = self._get_page_view_values(task, access_token, values, history, False, **kwargs)
if project:
history = request.session.get('my_project_tasks_history', [])
try:
current_task_index = history.index(task.id)
except ValueError:
return values
total_task = len(history)
task_url = f"{task.project_id.access_url}/task/%s?model=project.project&res_id={values['user'].id}&access_token={access_token}"
values['prev_record'] = current_task_index != 0 and task_url % history[current_task_index - 1]
values['next_record'] = current_task_index < total_task - 1 and task_url % history[current_task_index + 1]
return values
def _task_get_searchbar_sortings(self):
return {
'date': {'label': _('Newest'), 'order': 'create_date desc', 'sequence': 1},
'name': {'label': _('Title'), 'order': 'name', 'sequence': 2},
'project': {'label': _('Project'), 'order': 'project_id, stage_id', 'sequence': 3},
'users': {'label': _('Assignees'), 'order': 'user_ids', 'sequence': 4},
'stage': {'label': _('Stage'), 'order': 'stage_id, project_id', 'sequence': 5},
'status': {'label': _('Status'), 'order': 'kanban_state', 'sequence': 6},
'priority': {'label': _('Priority'), 'order': 'priority desc', 'sequence': 7},
'date_deadline': {'label': _('Deadline'), 'order': 'date_deadline asc', 'sequence': 8},
'update': {'label': _('Last Stage Update'), 'order': 'date_last_stage_update desc', 'sequence': 10},
}
def _task_get_searchbar_groupby(self):
values = {
'none': {'input': 'none', 'label': _('None'), 'order': 1},
'project': {'input': 'project', 'label': _('Project'), 'order': 2},
'stage': {'input': 'stage', 'label': _('Stage'), 'order': 4},
'status': {'input': 'status', 'label': _('Status'), 'order': 5},
'priority': {'input': 'priority', 'label': _('Priority'), 'order': 6},
'customer': {'input': 'customer', 'label': _('Customer'), 'order': 9},
}
return dict(sorted(values.items(), key=lambda item: item[1]["order"]))
def _task_get_groupby_mapping(self):
return {
'project': 'project_id',
'stage': 'stage_id',
'customer': 'partner_id',
'priority': 'priority',
'status': 'kanban_state',
}
def _task_get_order(self, order, groupby):
groupby_mapping = self._task_get_groupby_mapping()
field_name = groupby_mapping.get(groupby, '')
if not field_name:
return order
return '%s, %s' % (field_name, order)
def _task_get_searchbar_inputs(self):
values = {
'all': {'input': 'all', 'label': _('Search in All'), 'order': 1},
'content': {'input': 'content', 'label': Markup(_('Search <span class="nolabel"> (in Content)</span>')), 'order': 1},
'ref': {'input': 'ref', 'label': _('Search in Ref'), 'order': 1},
'project': {'input': 'project', 'label': _('Search in Project'), 'order': 2},
'users': {'input': 'users', 'label': _('Search in Assignees'), 'order': 3},
'stage': {'input': 'stage', 'label': _('Search in Stages'), 'order': 4},
'status': {'input': 'status', 'label': _('Search in Status'), 'order': 5},
'priority': {'input': 'priority', 'label': _('Search in Priority'), 'order': 6},
'message': {'input': 'message', 'label': _('Search in Messages'), 'order': 10},
}
return dict(sorted(values.items(), key=lambda item: item[1]["order"]))
def _task_get_search_domain(self, search_in, search):
search_domain = []
if search_in in ('content', 'all'):
search_domain.append([('name', 'ilike', search)])
search_domain.append([('description', 'ilike', search)])
if search_in in ('customer', 'all'):
search_domain.append([('partner_id', 'ilike', search)])
if search_in in ('message', 'all'):
search_domain.append([('message_ids.body', 'ilike', search)])
if search_in in ('stage', 'all'):
search_domain.append([('stage_id', 'ilike', search)])
if search_in in ('project', 'all'):
search_domain.append([('project_id', 'ilike', search)])
if search_in in ('ref', 'all'):
search_domain.append([('id', 'ilike', search)])
if search_in in ('users', 'all'):
user_ids = request.env['res.users'].sudo().search([('name', 'ilike', search)])
search_domain.append([('user_ids', 'in', user_ids.ids)])
if search_in in ('priority', 'all'):
search_domain.append([('priority', 'ilike', search == 'normal' and '0' or '1')])
if search_in in ('status', 'all'):
search_domain.append([
('kanban_state', 'ilike', 'normal' if search == 'In Progress' else 'done' if search == 'Ready' else 'blocked' if search == 'Blocked' else search)
])
return OR(search_domain)
@http.route(['/my/tasks', '/my/tasks/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_tasks(self, page=1, date_begin=None, date_end=None, sortby=None, filterby=None, search=None, search_in='content', groupby=None, **kw):
values = self._prepare_portal_layout_values()
searchbar_sortings = self._task_get_searchbar_sortings()
searchbar_sortings = dict(sorted(self._task_get_searchbar_sortings().items(),
key=lambda item: item[1]["sequence"]))
searchbar_filters = {
'all': {'label': _('All'), 'domain': [('project_id', '!=', False)]},
}
searchbar_inputs = self._task_get_searchbar_inputs()
searchbar_groupby = self._task_get_searchbar_groupby()
# extends filterby criteria with project the customer has access to
projects = request.env['project.project'].search([])
for project in projects:
searchbar_filters.update({
str(project.id): {'label': project.name, 'domain': [('project_id', '=', project.id)]}
})
# extends filterby criteria with project (criteria name is the project id)
# Note: portal users can't view projects they don't follow
project_groups = request.env['project.task'].read_group([('project_id', 'not in', projects.ids)],
['project_id'], ['project_id'])
for group in project_groups:
proj_id = group['project_id'][0] if group['project_id'] else False
proj_name = group['project_id'][1] if group['project_id'] else _('Others')
searchbar_filters.update({
str(proj_id): {'label': proj_name, 'domain': [('project_id', '=', proj_id)]}
})
# default sort by value
if not sortby:
sortby = 'date'
order = searchbar_sortings[sortby]['order']
# default filter by value
if not filterby:
filterby = 'all'
domain = searchbar_filters.get(filterby, searchbar_filters.get('all'))['domain']
# default group by value
if not groupby:
groupby = 'project'
if date_begin and date_end:
domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
# search
if search and search_in:
domain += self._task_get_search_domain(search_in, search)
TaskSudo = request.env['project.task'].sudo()
domain = AND([domain, request.env['ir.rule']._compute_domain(TaskSudo._name, 'read')])
# task count
task_count = TaskSudo.search_count(domain)
# pager
pager = portal_pager(
url="/my/tasks",
url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'filterby': filterby, 'groupby': groupby, 'search_in': search_in, 'search': search},
total=task_count,
page=page,
step=self._items_per_page
)
# content according to pager and archive selected
order = self._task_get_order(order, groupby)
tasks = TaskSudo.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])
request.session['my_tasks_history'] = tasks.ids[:100]
groupby_mapping = self._task_get_groupby_mapping()
group = groupby_mapping.get(groupby)
if group:
grouped_tasks = [request.env['project.task'].concat(*g) for k, g in groupbyelem(tasks, itemgetter(group))]
else:
grouped_tasks = [tasks]
task_states = dict(request.env['project.task']._fields['kanban_state']._description_selection(request.env))
if sortby == 'status':
if groupby == 'none' and grouped_tasks:
grouped_tasks[0] = grouped_tasks[0].sorted(lambda tasks: task_states.get(tasks.kanban_state))
else:
grouped_tasks.sort(key=lambda tasks: task_states.get(tasks[0].kanban_state))
values.update({
'date': date_begin,
'date_end': date_end,
'grouped_tasks': grouped_tasks,
'page_name': 'task',
'default_url': '/my/tasks',
'task_url': 'task',
'pager': pager,
'searchbar_sortings': searchbar_sortings,
'searchbar_groupby': searchbar_groupby,
'searchbar_inputs': searchbar_inputs,
'search_in': search_in,
'search': search,
'sortby': sortby,
'groupby': groupby,
'searchbar_filters': OrderedDict(sorted(searchbar_filters.items())),
'filterby': filterby,
})
return request.render("project.portal_my_tasks", values)
@http.route(['/my/task/<int:task_id>'], type='http', auth="public", website=True)
def portal_my_task(self, task_id, access_token=None, **kw):
try:
task_sudo = self._document_check_access('project.task', task_id, access_token)
except (AccessError, MissingError):
return request.redirect('/my')
# ensure attachment are accessible with access token inside template
for attachment in task_sudo.attachment_ids:
attachment.generate_access_token()
values = self._task_get_page_view_values(task_sudo, access_token, **kw)
return request.render("project.portal_my_task", values)
| 46.88172
| 21,800
|
5,541
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.exceptions import Forbidden
from odoo.http import request, route
from odoo.addons.portal.controllers.mail import PortalChatter
from .portal import ProjectCustomerPortal
class ProjectSharingChatter(PortalChatter):
def _check_project_access_and_get_token(self, project_id, res_model, res_id, token):
""" Check if the chatter in project sharing can be accessed
If the portal user is in the project sharing, then we do not have the access token of the task
but we can have the one of the project (if the user accessed to the project sharing views via the shared link).
So, we need to check if the chatter is for a task and if the res_id is a task
in the project shared. Then, if we had the project token and this one is the one in the project
then we return the token of the task to continue the portal chatter process.
If we do not have any token, then we need to check if the portal user is a follower of the project shared.
If it is the case, then we give the access token of the task.
"""
project_sudo = ProjectCustomerPortal._document_check_access(self, 'project.project', project_id, token)
can_access = project_sudo and res_model == 'project.task' and project_sudo.with_user(request.env.user)._check_project_sharing_access()
task = None
if can_access:
task = request.env['project.task'].sudo().search([('id', '=', res_id), ('project_id', '=', project_sudo.id)])
if not can_access or not task:
raise Forbidden()
return task[task._mail_post_token_field]
# ============================================================ #
# Note concerning the methods portal_chatter_(init/post/fetch)
# ============================================================ #
#
# When the project is shared to a portal user with the edit rights,
# he has the read/write access to the related tasks. So it could be
# possible to call directly the message_post method on a task.
#
# This change is considered as safe, as we only willingly expose
# records, for some assumed fields only, and this feature is
# optional and opt-in. (like the public employee model for example).
# It doesn't allow portal users to access other models, like
# a timesheet or an invoice.
#
# It could seem odd to use those routes, and converting the project
# access token into the task access token, as the user has actually
# access to the records.
#
# However, it has been decided that it was the less hacky way to
# achieve this, as:
#
# - We're reusing the existing routes, that convert all the data
# into valid arguments for the methods we use (message_post, ...).
# That way, we don't have to reinvent the wheel, duplicating code
# from mail/portal that surely will lead too desynchronization
# and inconsistencies over the time.
#
# - We don't define new routes, to do the exact same things than portal,
# considering that the portal user can use message_post for example
# because he has access to the record.
# Let's suppose that we remove this in a future development, those
# new routes won't be valid anymore.
#
# - We could have reused the mail widgets, as we already reuse the
# form/list/kanban views, etc. However, we only want to display
# the messages and allow to post. We don't need the next activities
# the followers system, etc. This required to override most of the
# mail.thread basic methods, without being sure that this would
# work with other installed applications or customizations
@route()
def portal_chatter_init(self, res_model, res_id, domain=False, limit=False, **kwargs):
project_sharing_id = kwargs.get('project_sharing_id')
if project_sharing_id:
# if there is a token in `kwargs` then it should be the access_token of the project shared
token = self._check_project_access_and_get_token(project_sharing_id, res_model, res_id, kwargs.get('token'))
if token:
del kwargs['project_sharing_id']
kwargs['token'] = token
return super().portal_chatter_init(res_model, res_id, domain=domain, limit=limit, **kwargs)
@route()
def portal_chatter_post(self, res_model, res_id, message, attachment_ids=None, attachment_tokens=None, **kw):
project_sharing_id = kw.get('project_sharing_id')
if project_sharing_id:
token = self._check_project_access_and_get_token(project_sharing_id, res_model, res_id, kw.get('token'))
if token:
del kw['project_sharing_id']
kw['token'] = token
return super().portal_chatter_post(res_model, res_id, message, attachment_ids=attachment_ids, attachment_tokens=attachment_tokens, **kw)
@route()
def portal_message_fetch(self, res_model, res_id, domain=False, limit=10, offset=0, **kw):
project_sharing_id = kw.get('project_sharing_id')
if project_sharing_id:
token = self._check_project_access_and_get_token(project_sharing_id, res_model, res_id, kw.get('token'))
if token:
kw['token'] = token
return super().portal_message_fetch(res_model, res_id, domain=domain, limit=limit, offset=offset, **kw)
| 54.861386
| 5,541
|
901
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Algeria - Accounting',
'version': '1.0',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the module to manage the accounting chart for Algeria in Odoo.
======================================================================
This module applies to companies based in Algeria.
""",
'author': 'Osis',
'depends': ['account', 'l10n_multilang'],
'data': [
'data/account_chart_template_data.xml',
'data/account.account.template.csv',
'data/account_chart_template_post_data.xml',
'data/account_tax_data.xml',
'data/account_fiscal_position_template_data.xml',
'data/account_chart_template_configuration_data.xml',
'report/account_move_report.xml',
],
'license': 'LGPL-3',
}
| 36.04
| 901
|
419
|
py
|
PYTHON
|
15.0
|
from odoo import api, models, fields
class AccountMove(models.Model):
_inherit = 'account.move'
amount_total_words = fields.Char("Amount total in words", compute="_compute_amount_total_words")
@api.depends('amount_total', 'currency_id')
def _compute_amount_total_words(self):
for record in self:
record.amount_total_words = record.currency_id.amount_to_text(record.amount_total)
| 34.916667
| 419
|
699
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "Website Sale Stock Product Configurator",
'summary': """
Bridge module for website_sale_stock / sale_product_configurator""",
'description': """
Bridge module to make the website e-commerce stock management compatible with the product configurator
""",
'category': 'Hidden',
'version': '1.0',
'depends': ['website_sale_stock', 'sale_product_configurator'],
'auto_install': True,
'data': [
'views/product_configurator_templates.xml',
],
'assets' : {
'web.assets_tests': [
'website_sale_stock_product_configurator/static/tests/**/*',
]
},
'license': 'LGPL-3',
}
| 31.772727
| 699
|
2,252
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import tagged
from odoo.addons.sale_product_configurator.tests.common import TestProductConfiguratorCommon
from odoo.addons.base.tests.common import HttpCaseWithUserPortal
@tagged('post_install', '-at_install')
class TestWebsiteSaleStockProductConfigurator(TestProductConfiguratorCommon, HttpCaseWithUserPortal):
def test_01_stock_message_update_after_close_with_optional_products(self):
product_product_with_options = self.env['product.product'].create({
'name': 'Product With Optional (TEST)',
'standard_price': 500.0,
'list_price': 750.0,
'optional_product_ids': [(4, self.product_product_conf_chair.id)],
'website_published': True,
'show_availability': True,
'available_threshold': 5000,
'allow_out_of_stock_order': False,
'type':'product',
})
self.product_product_conf_chair.website_published = True
self.env['stock.quant'].create({
'product_id': product_product_with_options.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'quantity': 30.0,
})
self.start_tour("/", 'website_sale_stock_message_after_close_onfigurator_modal_with_optional_products', login="admin")
def test_02_stock_message_update_after_close_without_optional_products(self):
product_product_without_options = self.env['product.product'].create({
'name': 'Product Without Optional (TEST)',
'standard_price': 500.0,
'list_price': 750.0,
'website_published': True,
'show_availability': True,
'available_threshold': 5000,
'allow_out_of_stock_order': False,
'detailed_type':'product',
})
self.env['stock.quant'].create({
'product_id': product_product_without_options.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'quantity': 30.0,
})
self.start_tour("/", 'website_sale_stock_message_after_close_onfigurator_modal_without_optional_products', login="admin")
| 47.914894
| 2,252
|
839
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Timesheet when on Time Off',
'version': '1.0',
'category': 'Human Resources',
'summary': 'Schedule timesheet when on time off',
'description': """
Bridge module to integrate leaves in timesheet
================================================
This module allows to automatically log timesheets when employees are
on leaves. Project and task can be configured company-wide.
""",
'depends': ['hr_timesheet', 'hr_holidays'],
'data': [
'views/res_config_settings_views.xml',
'views/hr_holidays_views.xml',
'security/ir.model.access.csv',
],
'demo': [],
'installable': True,
'auto_install': True,
'post_init_hook': 'post_init',
'license': 'LGPL-3',
}
| 29.964286
| 839
|
9,293
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from datetime import datetime, timedelta
from freezegun import freeze_time
from odoo import Command
from odoo.tests import common
class TestTimesheetGlobalTimeOff(common.TransactionCase):
def setUp(self):
super(TestTimesheetGlobalTimeOff, self).setUp()
# Creates 1 test company and a calendar for employees that
# work part time. Then creates an employee per calendar (one
# for the standard calendar and one for the one we created)
self.test_company = self.env['res.company'].create({
'name': 'My Test Company',
})
attendance_ids = [
Command.create({'name': 'Monday Morning', 'dayofweek': '0', 'hour_from': 9, 'hour_to': 12, 'day_period': 'morning'}),
Command.create({'name': 'Monday Afternoon', 'dayofweek': '0', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}),
Command.create({'name': 'Tuesday Morning', 'dayofweek': '1', 'hour_from': 9, 'hour_to': 12, 'day_period': 'morning'}),
Command.create({'name': 'Tuesday Afternoon', 'dayofweek': '1', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}),
Command.create({'name': 'Thursday Morning', 'dayofweek': '3', 'hour_from': 9, 'hour_to': 12, 'day_period': 'morning'}),
Command.create({'name': 'Thursday Afternoon', 'dayofweek': '3', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'}),
Command.create({'name': 'Friday Morning', 'dayofweek': '4', 'hour_from': 9, 'hour_to': 12, 'day_period': 'morning'}),
Command.create({'name': 'Friday Afternoon', 'dayofweek': '4', 'hour_from': 13, 'hour_to': 16, 'day_period': 'afternoon'})
]
self.part_time_calendar = self.env['resource.calendar'].create({
'name': 'Part Time Calendar',
'company_id': self.test_company.id,
'hours_per_day': 6,
'attendance_ids': attendance_ids,
})
self.full_time_employee = self.env['hr.employee'].create({
'name': 'John Doe',
'company_id': self.test_company.id,
'resource_calendar_id': self.test_company.resource_calendar_id.id,
})
self.full_time_employee_2 = self.env['hr.employee'].create({
'name': 'John Smith',
'company_id': self.test_company.id,
'resource_calendar_id': self.test_company.resource_calendar_id.id,
})
self.part_time_employee = self.env['hr.employee'].create({
'name': 'Jane Doe',
'company_id': self.test_company.id,
'resource_calendar_id': self.part_time_calendar.id,
})
# This tests that timesheets are created for every employee with the same calendar
# when a global time off is created.
# This also tests that timesheets are deleted when global time off is deleted.
def test_timesheet_creation_and_deletion_for_time_off(self):
leave_start_datetime = datetime(2021, 1, 4, 7, 0, 0, 0) # This is a monday
leave_end_datetime = datetime(2021, 1, 8, 18, 0, 0, 0) # This is a friday
global_time_off = self.env['resource.calendar.leaves'].create({
'name': 'Test',
'calendar_id': self.test_company.resource_calendar_id.id,
'date_from': leave_start_datetime,
'date_to': leave_end_datetime,
})
# 5 Timesheets should have been created for full_time_employee and full_time_employee_2
# but none for part_time_employee
leave_task = self.test_company.leave_timesheet_task_id
timesheets_by_employee = defaultdict(lambda: self.env['account.analytic.line'])
for timesheet in leave_task.timesheet_ids:
timesheets_by_employee[timesheet.employee_id] |= timesheet
self.assertFalse(timesheets_by_employee.get(self.part_time_employee, False))
self.assertEqual(len(timesheets_by_employee.get(self.full_time_employee)), 5)
self.assertEqual(len(timesheets_by_employee.get(self.full_time_employee_2)), 5)
# The standard calendar is for 8 hours/day from 8 to 12 and from 13 to 17.
# So we need to check that the timesheets don't have more than 8 hours per day.
self.assertEqual(leave_task.effective_hours, 80)
# Now we delete the global time off. The timesheets should be deleted too.
global_time_off.unlink()
self.assertFalse(leave_task.timesheet_ids.ids)
@freeze_time('2022-01-01 08:00:00')
def test_timesheet_creation_and_deletion_on_employee_archive(self):
""" Test the timesheets linked to the global time off in the future when the employee is archived """
today = datetime.today()
leave_start_datetime = today + timedelta(days=-today.weekday(), weeks=1) # Next monday
leave_end_datetime = leave_start_datetime + timedelta(days=5) # Next friday
self.env['resource.calendar.leaves'].create({
'name': 'Test',
'calendar_id': self.test_company.resource_calendar_id.id,
'date_from': leave_start_datetime,
'date_to': leave_end_datetime,
})
# 5 Timesheets should have been created for full_time_employee
timesheets_full_time_employee = self.env['account.analytic.line'].search([('employee_id', '=', self.full_time_employee.id)])
self.assertEqual(len(timesheets_full_time_employee), 5)
# All timesheets should have been deleted for full_time_employee when he is archived
self.full_time_employee.active = False
timesheets_full_time_employee = self.env['account.analytic.line'].search([('employee_id', '=', self.full_time_employee.id)])
self.assertEqual(len(timesheets_full_time_employee), 0)
# 5 Timesheets should have been created for full_time_employee when he is unarchived
self.full_time_employee.active = True
timesheets_full_time_employee = self.env['account.analytic.line'].search([('employee_id', '=', self.full_time_employee.id)])
self.assertEqual(len(timesheets_full_time_employee), 5)
# This tests that no timesheet are created for days when the employee is not supposed to work
def test_no_timesheet_on_off_days(self):
leave_start_datetime = datetime(2021, 1, 4, 7, 0, 0, 0) # This is a monday
leave_end_datetime = datetime(2021, 1, 8, 18, 0, 0, 0) # This is a friday
day_off = datetime(2021, 1, 6, 0, 0, 0) # part_time_employee does not work on wednesday
self.env['resource.calendar.leaves'].create({
'name': 'Test',
'calendar_id': self.part_time_calendar.id,
'date_from': leave_start_datetime,
'date_to': leave_end_datetime,
})
# The total number of hours for the timesheet created should be equal to the
# hours_per_day of the calendar
leave_task = self.test_company.leave_timesheet_task_id
self.assertEqual(leave_task.effective_hours, 4 * self.part_time_calendar.hours_per_day)
# No timesheet should have been created on the day off
timesheet = self.env['account.analytic.line'].search([('date', '=', day_off), ('task_id', '=', leave_task.id)])
self.assertFalse(timesheet.id)
# This tests that timesheets are created/deleted for every employee with the same calendar
# when a global time off has a calendar_id set/remove
def test_timesheet_creation_and_deletion_for_calendar_set_and_remove(self):
leave_start_datetime = datetime(2021, 1, 4, 7, 0, 0, 0) # This is a monday
leave_end_datetime = datetime(2021, 1, 8, 18, 0, 0, 0) # This is a friday
global_time_off = self.env['resource.calendar.leaves'].create({
'name': 'Test',
'calendar_id': self.test_company.resource_calendar_id.id,
'date_from': leave_start_datetime,
'date_to': leave_end_datetime,
})
# 5 Timesheets should have been created for full_time_employee and full_time_employee_2
# but none for part_time_employee
leave_task = self.test_company.leave_timesheet_task_id
# Now we delete the calendar_id. The timesheets should be deleted too.
global_time_off.calendar_id = False
self.assertFalse(leave_task.timesheet_ids.ids)
# Now we reset the calendar_id. The timesheets should be created and have the right value.
global_time_off.calendar_id = self.test_company.resource_calendar_id.id
timesheets_by_employee = defaultdict(lambda: self.env['account.analytic.line'])
for timesheet in leave_task.timesheet_ids:
timesheets_by_employee[timesheet.employee_id] |= timesheet
self.assertFalse(timesheets_by_employee.get(self.part_time_employee, False))
self.assertEqual(len(timesheets_by_employee.get(self.full_time_employee)), 5)
self.assertEqual(len(timesheets_by_employee.get(self.full_time_employee_2)), 5)
# The standard calendar is for 8 hours/day from 8 to 12 and from 13 to 17.
# So we need to check that the timesheets don't have more than 8 hours per day.
self.assertEqual(leave_task.effective_hours, 80)
| 52.502825
| 9,293
|
6,353
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import fields, SUPERUSER_ID
from odoo.tests import common, new_test_user
from odoo.addons.hr_timesheet.tests.test_timesheet import TestCommonTimesheet
import time
class TestTimesheetHolidaysCreate(common.TransactionCase):
def test_status_create(self):
"""Ensure that when a status is created, it fullfills the project and task constrains"""
status = self.env['hr.leave.type'].create({
'name': 'A nice Leave Type',
'requires_allocation': 'no'
})
company = self.env.company
self.assertEqual(status.timesheet_project_id, company.internal_project_id, 'The default project linked to the status should be the same as the company')
self.assertEqual(status.timesheet_task_id, company.leave_timesheet_task_id, 'The default task linked to the status should be the same as the company')
def test_company_create(self):
main_company = self.env.ref('base.main_company')
user = new_test_user(self.env, login='fru',
groups='base.group_user,base.group_erp_manager,base.group_partner_manager',
company_id=main_company.id,
company_ids=[(6, 0, main_company.ids)])
Company = self.env['res.company']
Company = Company.with_user(user)
Company = Company.with_company(main_company)
company = Company.create({'name': "Wall Company"})
self.assertEqual(company.internal_project_id.sudo().company_id, company, "It should have created a project for the company")
class TestTimesheetHolidays(TestCommonTimesheet):
def setUp(self):
super(TestTimesheetHolidays, self).setUp()
self.employee_working_calendar = self.empl_employee.resource_calendar_id
# leave dates : from next monday to next wednesday (to avoid crashing tests on weekend, when
# there is no work days in working calendar)
# NOTE: second and millisecond can add a working days
self.leave_start_datetime = datetime(2018, 2, 5, 7, 0, 0, 0) # this is monday
self.leave_end_datetime = self.leave_start_datetime + relativedelta(days=3)
# all company have those internal project/task (created by default)
self.internal_project = self.env.company.internal_project_id
self.internal_task_leaves = self.env.company.leave_timesheet_task_id
self.hr_leave_type_with_ts = self.env['hr.leave.type'].create({
'name': 'Leave Type with timesheet generation',
'requires_allocation': 'no',
'timesheet_generate': True,
'timesheet_project_id': self.internal_project.id,
'timesheet_task_id': self.internal_task_leaves.id,
})
self.hr_leave_type_no_ts = self.env['hr.leave.type'].create({
'name': 'Leave Type without timesheet generation',
'requires_allocation': 'no',
'timesheet_generate': False,
'timesheet_project_id': False,
'timesheet_task_id': False,
})
# HR Officer allocates some leaves to the employee 1
self.Requests = self.env['hr.leave'].with_context(mail_create_nolog=True, mail_notrack=True)
self.Allocations = self.env['hr.leave.allocation'].with_context(mail_create_nolog=True, mail_notrack=True)
self.hr_leave_allocation_with_ts = self.Allocations.sudo().create({
'name': 'Days for limited category with timesheet',
'employee_id': self.empl_employee.id,
'holiday_status_id': self.hr_leave_type_with_ts.id,
'number_of_days': 10,
'state': 'confirm',
'date_from': time.strftime('%Y-01-01'),
'date_to': time.strftime('%Y-12-31'),
})
self.hr_leave_allocation_with_ts.action_validate()
self.hr_leave_allocation_no_ts = self.Allocations.sudo().create({
'name': 'Days for limited category without timesheet',
'employee_id': self.empl_employee.id,
'holiday_status_id': self.hr_leave_type_no_ts.id,
'number_of_days': 10,
'state': 'confirm',
'date_from': time.strftime('%Y-01-01'),
'date_to': time.strftime('%Y-12-31'),
})
self.hr_leave_allocation_no_ts.action_validate()
def test_validate_with_timesheet(self):
# employee creates a leave request
number_of_days = (self.leave_end_datetime - self.leave_start_datetime).days
holiday = self.Requests.with_user(self.user_employee).create({
'name': 'Leave 1',
'employee_id': self.empl_employee.id,
'holiday_status_id': self.hr_leave_type_with_ts.id,
'date_from': self.leave_start_datetime,
'date_to': self.leave_end_datetime,
'number_of_days': number_of_days,
})
holiday.with_user(SUPERUSER_ID).action_validate()
self.assertEqual(len(holiday.timesheet_ids), number_of_days, 'Number of generated timesheets should be the same as the leave duration (1 per day between %s and %s)' % (fields.Datetime.to_string(self.leave_start_datetime), fields.Datetime.to_string(self.leave_end_datetime)))
# manager refuse the leave
holiday.with_user(SUPERUSER_ID).action_refuse()
self.assertEqual(len(holiday.timesheet_ids), 0, 'Number of linked timesheets should be zero, since the leave is refused.')
def test_validate_without_timesheet(self):
# employee creates a leave request
number_of_days = (self.leave_end_datetime - self.leave_start_datetime).days
holiday = self.Requests.with_user(self.user_employee).create({
'name': 'Leave 1',
'employee_id': self.empl_employee.id,
'holiday_status_id': self.hr_leave_type_no_ts.id,
'date_from': self.leave_start_datetime,
'date_to': self.leave_end_datetime,
'number_of_days': number_of_days,
})
holiday.with_user(SUPERUSER_ID).action_validate()
self.assertEqual(len(holiday.timesheet_ids), 0, 'Number of generated timesheets should be zero since the leave type does not generate timesheet')
| 51.233871
| 6,353
|
8,871
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from pytz import timezone, utc
from odoo import api, fields, models, _
class ResourceCalendarLeaves(models.Model):
_inherit = "resource.calendar.leaves"
timesheet_ids = fields.One2many('account.analytic.line', 'global_leave_id', string="Analytic Lines")
def _work_time_per_day(self):
""" Get work time per day based on the calendar and its attendances
1) Gets all calendars with their characteristics (i.e.
(a) the leaves in it,
(b) the resources which have a leave,
(c) the oldest and
(d) the latest leave dates
) for leaves in self.
2) Search the attendances based on the characteristics retrieved for each calendar.
The attendances found are the ones between the date_from of the oldest leave
and the date_to of the most recent leave.
3) Create a dict as result of this method containing:
{
leave: {
max(date_start of work hours, date_start of the leave):
the duration in days of the work including the leave
}
}
"""
leaves_read_group = self.env['resource.calendar.leaves'].read_group(
[('id', 'in', self.ids)],
['calendar_id', 'ids:array_agg(id)', 'resource_ids:array_agg(resource_id)', 'min_date_from:min(date_from)', 'max_date_to:max(date_to)'],
['calendar_id'],
)
# dict of keys: calendar_id
# and values : { 'date_from': datetime, 'date_to': datetime, resources: self.env['resource.resource'] }
cal_attendance_intervals_dict = {
res['calendar_id'][0]: {
'date_from': utc.localize(res['min_date_from']),
'date_to': utc.localize(res['max_date_to']),
'resources': self.env['resource.resource'].browse(res['resource_ids'] if res['resource_ids'] and res['resource_ids'][0] else []),
'leaves': self.env['resource.calendar.leaves'].browse(res['ids']),
} for res in leaves_read_group
}
# to easily find the calendar with its id.
calendars_dict = {calendar.id: calendar for calendar in self.calendar_id}
# dict of keys: leave.id
# and values: a dict of keys: date
# and values: number of days
results = defaultdict(lambda: defaultdict(float))
for calendar_id, cal_attendance_intervals_params_entry in cal_attendance_intervals_dict.items():
calendar = calendars_dict[calendar_id]
work_hours_intervals = calendar._attendance_intervals_batch(
cal_attendance_intervals_params_entry['date_from'],
cal_attendance_intervals_params_entry['date_to'],
cal_attendance_intervals_params_entry['resources'],
tz=timezone(calendar.tz)
)
for leave in cal_attendance_intervals_params_entry['leaves']:
work_hours_data = work_hours_intervals[leave.resource_id.id]
for date_from, date_to, dummy in work_hours_data:
if date_to > utc.localize(leave.date_from) and date_from < utc.localize(leave.date_to):
tmp_start = max(date_from, utc.localize(leave.date_from))
tmp_end = min(date_to, utc.localize(leave.date_to))
results[leave.id][tmp_start.date()] += (tmp_end - tmp_start).total_seconds() / 3600
results[leave.id] = sorted(results[leave.id].items())
return results
def _timesheet_create_lines(self):
""" Create timesheet leaves for each employee using the same calendar containing in self.calendar_id
If the employee has already a time off in the same day then no timesheet should be created.
"""
work_hours_data = self._work_time_per_day()
employees_groups = self.env['hr.employee'].read_group(
[('resource_calendar_id', 'in', self.calendar_id.ids)],
['resource_calendar_id', 'ids:array_agg(id)'],
['resource_calendar_id'])
mapped_employee = {
employee['resource_calendar_id'][0]: self.env['hr.employee'].browse(employee['ids'])
for employee in employees_groups
}
employee_ids_set = set()
employee_ids_set.update(*[line['ids'] for line in employees_groups])
min_date = max_date = None
for values in work_hours_data.values():
for d, dummy in values:
if not min_date and not max_date:
min_date = max_date = d
elif d < min_date:
min_date = d
elif d > max_date:
max_date = d
holidays_read_group = self.env['hr.leave'].read_group([
('employee_id', 'in', list(employee_ids_set)),
('date_from', '<=', max_date),
('date_to', '>=', min_date),
('state', 'not in', ('cancel', 'refuse')),
], ['date_from_list:array_agg(date_from)', 'date_to_list:array_agg(date_to)', 'employee_id'], ['employee_id'])
holidays_by_employee = {
line['employee_id'][0]: [
(date_from.date(), date_to.date()) for date_from, date_to in zip(line['date_from_list'], line['date_to_list'])
] for line in holidays_read_group
}
vals_list = []
for leave in self:
for employee in mapped_employee.get(leave.calendar_id.id, self.env['hr.employee']):
holidays = holidays_by_employee.get(employee.id)
work_hours_list = work_hours_data[leave.id]
for index, (day_date, work_hours_count) in enumerate(work_hours_list):
if not holidays or all(not (date_from <= day_date and date_to >= day_date) for date_from, date_to in holidays):
vals_list.append(
leave._timesheet_prepare_line_values(
index,
employee,
work_hours_list,
day_date,
work_hours_count
)
)
return self.env['account.analytic.line'].sudo().create(vals_list)
def _timesheet_prepare_line_values(self, index, employee_id, work_hours_data, day_date, work_hours_count):
self.ensure_one()
return {
'name': _("Time Off (%s/%s)", index + 1, len(work_hours_data)),
'project_id': employee_id.company_id.internal_project_id.id,
'task_id': employee_id.company_id.leave_timesheet_task_id.id,
'account_id': employee_id.company_id.internal_project_id.analytic_account_id.id,
'unit_amount': work_hours_count,
'user_id': employee_id.user_id.id,
'date': day_date,
'global_leave_id': self.id,
'employee_id': employee_id.id,
'company_id': employee_id.company_id.id,
}
@api.model_create_multi
def create(self, vals_list):
results = super(ResourceCalendarLeaves, self).create(vals_list)
results_with_leave_timesheet = results.filtered(lambda r: not r.resource_id.id and r.calendar_id.company_id.internal_project_id and r.calendar_id.company_id.leave_timesheet_task_id)
results_with_leave_timesheet and results_with_leave_timesheet._timesheet_create_lines()
return results
def write(self, vals):
date_from, date_to, calendar_id = vals.get('date_from'), vals.get('date_to'), vals.get('calendar_id')
global_time_off_updated = self.env['resource.calendar.leaves']
if date_from or date_to or 'calendar_id' in vals:
global_time_off_updated = self.filtered(lambda r: (date_from is not None and r.date_from != date_from) or (date_to is not None and r.date_to != date_to) or (calendar_id is not None and r.calendar_id.id != calendar_id))
timesheets = global_time_off_updated.sudo().timesheet_ids
if timesheets:
timesheets.write({'global_leave_id': False})
timesheets.unlink()
result = super(ResourceCalendarLeaves, self).write(vals)
if global_time_off_updated:
global_time_offs_with_leave_timesheet = global_time_off_updated.filtered(lambda r: not r.resource_id and r.calendar_id.company_id.internal_project_id and r.calendar_id.company_id.leave_timesheet_task_id)
global_time_offs_with_leave_timesheet.sudo()._timesheet_create_lines()
return result
| 53.439759
| 8,871
|
706
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
holiday_id = fields.Many2one("hr.leave", string='Leave Request', copy=False)
global_leave_id = fields.Many2one("resource.calendar.leaves", string="Global Time Off", ondelete='cascade')
@api.ondelete(at_uninstall=False)
def _unlink_except_linked_leave(self):
if any(line.holiday_id for line in self):
raise UserError(_('You cannot delete timesheets linked to time off. Please, cancel the time off instead.'))
| 41.529412
| 706
|
2,873
|
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 Company(models.Model):
_inherit = 'res.company'
leave_timesheet_task_id = fields.Many2one(
'project.task', string="Time Off Task",
domain="[('project_id', '=', internal_project_id)]")
def init(self):
type_ids = [(4, self.env.ref('hr_timesheet.internal_project_default_stage').id)]
companies = self.search(['|', ('internal_project_id', '=', False), ('leave_timesheet_task_id', '=', False)])
internal_projects_by_company_dict = None
Project = self.env['project.project']
for company in companies:
company = company.with_company(company)
if not company.internal_project_id:
if not internal_projects_by_company_dict:
internal_projects_by_company_read = Project.search_read([
('name', '=', _('Internal')),
('allow_timesheets', '=', True),
('company_id', 'in', companies.ids),
], ['company_id', 'id'])
internal_projects_by_company_dict = {res['company_id'][0]: res['id'] for res in internal_projects_by_company_read}
project_id = internal_projects_by_company_dict.get(company.id, False)
if not project_id:
project_id = Project.create({
'name': _('Internal'),
'allow_timesheets': True,
'company_id': company.id,
'type_ids': type_ids,
}).id
company.write({'internal_project_id': project_id})
if not company.leave_timesheet_task_id:
task = company.env['project.task'].create({
'name': _('Time Off'),
'project_id': company.internal_project_id.id,
'active': True,
'company_id': company.id,
})
company.write({
'leave_timesheet_task_id': task.id,
})
def _create_internal_project_task(self):
projects = super()._create_internal_project_task()
for project in projects:
company = project.company_id
company = company.with_company(company)
if not company.leave_timesheet_task_id:
task = company.env['project.task'].sudo().create({
'name': _('Time Off'),
'project_id': company.internal_project_id.id,
'active': True,
'company_id': company.id,
})
company.write({
'leave_timesheet_task_id': task.id,
})
return projects
| 44.890625
| 2,873
|
2,293
|
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 Employee(models.Model):
_inherit = 'hr.employee'
@api.model
def create(self, vals):
employees = super(Employee, self).create(vals)
# We need to create timesheet entries for the global time off that are already created
# and are planned for after this employee creation date
self._create_future_public_holidays_timesheets(employees)
return employees
def write(self, vals):
result = super(Employee, self).write(vals)
if 'active' in vals:
if vals.get('active'):
# Create future holiday timesheets
self._create_future_public_holidays_timesheets(self)
else:
# Delete future holiday timesheets
future_timesheets = self.env['account.analytic.line'].sudo().search([('global_leave_id', '!=', False), ('date', '>=', fields.date.today()), ('employee_id', 'in', self.ids)])
future_timesheets.write({'global_leave_id': False})
future_timesheets.unlink()
return result
def _create_future_public_holidays_timesheets(self, employees):
lines_vals = []
for employee in employees:
if not employee.active:
continue
# First we look for the global time off that are already planned after today
global_leaves = employee.resource_calendar_id.global_leave_ids.filtered(lambda l: l.date_from >= fields.Datetime.today())
work_hours_data = global_leaves._work_time_per_day()
for global_time_off in global_leaves:
for index, (day_date, work_hours_count) in enumerate(work_hours_data[global_time_off.id]):
lines_vals.append(
global_time_off._timesheet_prepare_line_values(
index,
employee,
work_hours_data[global_time_off.id],
day_date,
work_hours_count
)
)
return self.env['account.analytic.line'].sudo().create(lines_vals)
| 44.096154
| 2,293
|
1,090
|
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'
internal_project_id = fields.Many2one(
related='company_id.internal_project_id', required=True, string="Internal Project",
domain="[('company_id', '=', company_id)]", readonly=False)
leave_timesheet_task_id = fields.Many2one(
related='company_id.leave_timesheet_task_id', string="Time Off Task", readonly=False,
domain="[('company_id', '=', company_id), ('project_id', '=?', internal_project_id)]")
@api.onchange('internal_project_id')
def _onchange_timesheet_project_id(self):
if self.internal_project_id != self.leave_timesheet_task_id.project_id:
self.leave_timesheet_task_id = False
@api.onchange('leave_timesheet_task_id')
def _onchange_timesheet_task_id(self):
if self.leave_timesheet_task_id:
self.internal_project_id = self.leave_timesheet_task_id.project_id
| 43.6
| 1,090
|
5,611
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class HolidaysType(models.Model):
_inherit = "hr.leave.type"
def _default_project_id(self):
company = self.company_id if self.company_id else self.env.company
return company.internal_project_id.id
def _default_task_id(self):
company = self.company_id if self.company_id else self.env.company
return company.leave_timesheet_task_id.id
timesheet_generate = fields.Boolean(
'Generate Timesheet', compute='_compute_timesheet_generate', store=True, readonly=False,
help="If checked, when validating a time off, timesheet will be generated in the Vacation Project of the company.")
timesheet_project_id = fields.Many2one('project.project', string="Project", default=_default_project_id, domain="[('company_id', '=', company_id)]", help="The project will contain the timesheet generated when a time off is validated.")
timesheet_task_id = fields.Many2one(
'project.task', string="Task", compute='_compute_timesheet_task_id',
store=True, readonly=False, default=_default_task_id,
domain="[('project_id', '=', timesheet_project_id),"
"('company_id', '=', company_id)]")
@api.depends('timesheet_task_id', 'timesheet_project_id')
def _compute_timesheet_generate(self):
for leave_type in self:
leave_type.timesheet_generate = leave_type.timesheet_task_id and leave_type.timesheet_project_id
@api.depends('timesheet_project_id')
def _compute_timesheet_task_id(self):
for leave_type in self:
company = leave_type.company_id if leave_type.company_id else self.env.company
default_task_id = company.leave_timesheet_task_id
if default_task_id and default_task_id.project_id == leave_type.timesheet_project_id:
leave_type.timesheet_task_id = default_task_id
else:
leave_type.timesheet_task_id = False
@api.constrains('timesheet_generate', 'timesheet_project_id', 'timesheet_task_id')
def _check_timesheet_generate(self):
for holiday_status in self:
if holiday_status.timesheet_generate:
if not holiday_status.timesheet_project_id or not holiday_status.timesheet_task_id:
raise ValidationError(_("Both the internal project and task are required to "
"generate a timesheet for the time off %s. If you don't want a timesheet, you should "
"leave the internal project and task empty.") % (holiday_status.name))
class Holidays(models.Model):
_inherit = "hr.leave"
timesheet_ids = fields.One2many('account.analytic.line', 'holiday_id', string="Analytic Lines")
def _validate_leave_request(self):
""" Timesheet will be generated on leave validation only if a timesheet_project_id and a
timesheet_task_id are set on the corresponding leave type. The generated timesheet will
be attached to this project/task.
"""
holidays = self.filtered(
lambda l: l.holiday_type == 'employee' and
l.holiday_status_id.timesheet_project_id and
l.holiday_status_id.timesheet_task_id and
l.holiday_status_id.timesheet_project_id.sudo().company_id == (l.holiday_status_id.company_id or self.env.company))
# Unlink previous timesheets do avoid doublon (shouldn't happen on the interface but meh)
old_timesheets = holidays.sudo().timesheet_ids
if old_timesheets:
old_timesheets.holiday_id = False
old_timesheets.unlink()
# create the timesheet on the vacation project
holidays._timesheet_create_lines()
return super()._validate_leave_request()
def _timesheet_create_lines(self):
vals_list = []
for leave in self:
if not leave.employee_id:
continue
work_hours_data = leave.employee_id.list_work_time_per_day(
leave.date_from,
leave.date_to)
for index, (day_date, work_hours_count) in enumerate(work_hours_data):
vals_list.append(leave._timesheet_prepare_line_values(index, work_hours_data, day_date, work_hours_count))
return self.env['account.analytic.line'].sudo().create(vals_list)
def _timesheet_prepare_line_values(self, index, work_hours_data, day_date, work_hours_count):
self.ensure_one()
return {
'name': _("Time Off (%s/%s)", index + 1, len(work_hours_data)),
'project_id': self.holiday_status_id.timesheet_project_id.id,
'task_id': self.holiday_status_id.timesheet_task_id.id,
'account_id': self.holiday_status_id.timesheet_project_id.analytic_account_id.id,
'unit_amount': work_hours_count,
'user_id': self.employee_id.user_id.id,
'date': day_date,
'holiday_id': self.id,
'employee_id': self.employee_id.id,
'company_id': self.holiday_status_id.timesheet_task_id.company_id.id or self.holiday_status_id.timesheet_project_id.company_id.id,
}
def action_refuse(self):
""" Remove the timesheets linked to the refused holidays """
result = super(Holidays, self).action_refuse()
timesheets = self.sudo().mapped('timesheet_ids')
timesheets.write({'holiday_id': False})
timesheets.unlink()
return result
| 48.791304
| 5,611
|
671
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Test - Base Automation',
'version': '1.0',
'category': 'Hidden',
'sequence': 9877,
'summary': 'Base Automation Tests: Ensure Flow Robustness',
'description': """This module contains tests related to base automation. Those are
present in a separate module as it contains models used only to perform
tests independently to functional aspects of other models.""",
'depends': ['base_automation'],
'data': [
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'license': 'LGPL-3',
}
| 33.55
| 671
|
21,846
|
py
|
PYTHON
|
15.0
|
# # -*- coding: utf-8 -*-
# # Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
import sys
from odoo.addons.base.tests.common import TransactionCaseWithUserDemo
from odoo.tests import common, tagged
from odoo.exceptions import AccessError
@tagged('post_install', '-at_install')
class BaseAutomationTest(TransactionCaseWithUserDemo):
def setUp(self):
super(BaseAutomationTest, self).setUp()
self.user_root = self.env.ref('base.user_root')
self.user_admin = self.env.ref('base.user_admin')
self.test_mail_template_automation = self.env['mail.template'].create({
'name': 'Template Automation',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'body_html': """<div>Email automation</div>""",
})
self.res_partner_1 = self.env['res.partner'].create({'name': 'My Partner'})
self.env['base.automation'].create([
{
'name': 'Base Automation: test rule on create',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'state': 'code',
'code': "records.write({'user_id': %s})" % (self.user_demo.id),
'trigger': 'on_create',
'active': True,
'filter_domain': "[('state', '=', 'draft')]",
}, {
'name': 'Base Automation: test rule on write',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'state': 'code',
'code': "records.write({'user_id': %s})" % (self.user_demo.id),
'trigger': 'on_write',
'active': True,
'filter_domain': "[('state', '=', 'done')]",
'filter_pre_domain': "[('state', '=', 'open')]",
}, {
'name': 'Base Automation: test rule on recompute',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'state': 'code',
'code': "records.write({'user_id': %s})" % (self.user_demo.id),
'trigger': 'on_write',
'active': True,
'filter_domain': "[('employee', '=', True)]",
}, {
'name': 'Base Automation: test recursive rule',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'state': 'code',
'code': """
record = model.browse(env.context['active_id'])
if 'partner_id' in env.context['old_values'][record.id]:
record.write({'state': 'draft'})""",
'trigger': 'on_write',
'active': True,
}, {
'name': 'Base Automation: test rule on secondary model',
'model_id': self.env.ref('test_base_automation.model_base_automation_line_test').id,
'state': 'code',
'code': "records.write({'user_id': %s})" % (self.user_demo.id),
'trigger': 'on_create',
'active': True,
}, {
'name': 'Base Automation: test rule on write check context',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'state': 'code',
'code': """
record = model.browse(env.context['active_id'])
if 'user_id' in env.context['old_values'][record.id]:
record.write({'is_assigned_to_admin': (record.user_id.id == 1)})""",
'trigger': 'on_write',
'active': True,
}, {
'name': 'Base Automation: test rule with trigger',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'trigger_field_ids': [(4, self.env.ref('test_base_automation.field_base_automation_lead_test__state').id)],
'state': 'code',
'code': """
record = model.browse(env.context['active_id'])
record['name'] = record.name + 'X'""",
'trigger': 'on_write',
'active': True,
}, {
'name': 'Base Automation: test send an email',
'model_id': self.env.ref('test_base_automation.model_base_automation_lead_test').id,
'template_id': self.test_mail_template_automation.id,
'trigger_field_ids': [(4, self.env.ref('test_base_automation.field_base_automation_lead_test__deadline').id)],
'state': 'email',
'code': """
record = model.browse(env.context['active_id'])
record['name'] = record.name + 'X'""",
'trigger': 'on_write',
'active': True,
'filter_domain': "[('deadline', '!=', False)]",
'filter_pre_domain': "[('deadline', '=', False)]",
}
])
def tearDown(self):
super().tearDown()
self.env['base.automation']._unregister_hook()
def create_lead(self, **kwargs):
vals = {
'name': "Lead Test",
'user_id': self.user_root.id,
}
vals.update(kwargs)
return self.env['base.automation.lead.test'].create(vals)
def test_00_check_to_state_open_pre(self):
"""
Check that a new record (with state = open) doesn't change its responsible
when there is a precondition filter which check that the state is open.
"""
lead = self.create_lead(state='open')
self.assertEqual(lead.state, 'open')
self.assertEqual(lead.user_id, self.user_root, "Responsible should not change on creation of Lead with state 'open'.")
def test_01_check_to_state_draft_post(self):
"""
Check that a new record changes its responsible when there is a postcondition
filter which check that the state is draft.
"""
lead = self.create_lead()
self.assertEqual(lead.state, 'draft', "Lead state should be 'draft'")
self.assertEqual(lead.user_id, self.user_demo, "Responsible should be change on creation of Lead with state 'draft'.")
def test_02_check_from_draft_to_done_with_steps(self):
"""
A new record is created and goes from states 'open' to 'done' via the
other states (open, pending and cancel). We have a rule with:
- precondition: the record is in "open"
- postcondition: that the record is "done".
If the state goes from 'open' to 'done' the responsible is changed.
If those two conditions aren't verified, the responsible remains the same.
"""
lead = self.create_lead(state='open')
self.assertEqual(lead.state, 'open', "Lead state should be 'open'")
self.assertEqual(lead.user_id, self.user_root, "Responsible should not change on creation of Lead with state 'open'.")
# change state to pending and check that responsible has not changed
lead.write({'state': 'pending'})
self.assertEqual(lead.state, 'pending', "Lead state should be 'pending'")
self.assertEqual(lead.user_id, self.user_root, "Responsible should not change on creation of Lead with state from 'draft' to 'open'.")
# change state to done and check that responsible has not changed
lead.write({'state': 'done'})
self.assertEqual(lead.state, 'done', "Lead state should be 'done'")
self.assertEqual(lead.user_id, self.user_root, "Responsible should not chang on creation of Lead with state from 'pending' to 'done'.")
def test_03_check_from_draft_to_done_without_steps(self):
"""
A new record is created and goes from states 'open' to 'done' via the
other states (open, pending and cancel). We have a rule with:
- precondition: the record is in "open"
- postcondition: that the record is "done".
If the state goes from 'open' to 'done' the responsible is changed.
If those two conditions aren't verified, the responsible remains the same.
"""
lead = self.create_lead(state='open')
self.assertEqual(lead.state, 'open', "Lead state should be 'open'")
self.assertEqual(lead.user_id, self.user_root, "Responsible should not change on creation of Lead with state 'open'.")
# change state to done and check that responsible has changed
lead.write({'state': 'done'})
self.assertEqual(lead.state, 'done', "Lead state should be 'done'")
self.assertEqual(lead.user_id, self.user_demo, "Responsible should be change on write of Lead with state from 'open' to 'done'.")
def test_10_recomputed_field(self):
"""
Check that a rule is executed whenever a field is recomputed after a
change on another model.
"""
partner = self.res_partner_1
partner.write({'employee': False})
lead = self.create_lead(state='open', partner_id=partner.id)
self.assertFalse(lead.employee, "Customer field should updated to False")
self.assertEqual(lead.user_id, self.user_root, "Responsible should not change on creation of Lead with state from 'draft' to 'open'.")
# change partner, recompute on lead should trigger the rule
partner.write({'employee': True})
lead.flush()
self.assertTrue(lead.employee, "Customer field should updated to True")
self.assertEqual(lead.user_id, self.user_demo, "Responsible should be change on write of Lead when Customer becomes True.")
def test_11_recomputed_field(self):
"""
Check that a rule is executed whenever a field is recomputed and the
context contains the target field
"""
partner = self.res_partner_1
lead = self.create_lead(state='draft', partner_id=partner.id)
self.assertFalse(lead.deadline, 'There should not be a deadline defined')
# change priority and user; this triggers deadline recomputation, and
# the server action should set the boolean field to True
lead.write({'priority': True, 'user_id': self.user_root.id})
self.assertTrue(lead.deadline, 'Deadline should be defined')
self.assertTrue(lead.is_assigned_to_admin, 'Lead should be assigned to admin')
def test_11b_recomputed_field(self):
mail_automation = self.env['base.automation'].search([('name', '=', 'Base Automation: test send an email')])
send_mail_count = 0
def _patched_get_actions(*args, **kwargs):
obj = args[0]
if '__action_done' not in obj._context:
obj = obj.with_context(__action_done={})
return mail_automation.with_env(obj.env)
def _patched_send_mail(*args, **kwargs):
nonlocal send_mail_count
send_mail_count += 1
patchers = [
patch('odoo.addons.base_automation.models.base_automation.BaseAutomation._get_actions', _patched_get_actions),
patch('odoo.addons.mail.models.mail_template.MailTemplate.send_mail', _patched_send_mail),
]
patchers[0].start()
lead = self.create_lead()
self.assertFalse(lead.priority)
self.assertFalse(lead.deadline)
patchers[1].start()
lead.write({'priority': True})
self.assertTrue(lead.priority)
self.assertTrue(lead.deadline)
for patcher in patchers:
patcher.stop()
self.assertEqual(send_mail_count, 1)
def test_12_recursive(self):
""" Check that a rule is executed recursively by a secondary change. """
lead = self.create_lead(state='open')
self.assertEqual(lead.state, 'open')
self.assertEqual(lead.user_id, self.user_root)
# change partner; this should trigger the rule that modifies the state
partner = self.res_partner_1
lead.write({'partner_id': partner.id})
self.assertEqual(lead.state, 'draft')
def test_20_direct_line(self):
"""
Check that a rule is executed after creating a line record.
"""
line = self.env['base.automation.line.test'].create({'name': "Line"})
self.assertEqual(line.user_id, self.user_demo)
def test_20_indirect_line(self):
"""
Check that creating a lead with a line executes rules on both records.
"""
lead = self.create_lead(line_ids=[(0, 0, {'name': "Line"})])
self.assertEqual(lead.state, 'draft', "Lead state should be 'draft'")
self.assertEqual(lead.user_id, self.user_demo, "Responsible should change on creation of Lead test line.")
self.assertEqual(len(lead.line_ids), 1, "New test line is not created")
self.assertEqual(lead.line_ids.user_id, self.user_demo, "Responsible should be change on creation of Lead test line.")
def test_21_trigger_fields(self):
"""
Check that the rule with trigger is executed only once per pertinent update.
"""
lead = self.create_lead(name="X")
lead.priority = True
partner1 = self.res_partner_1
lead.partner_id = partner1.id
self.assertEqual(lead.name, 'X', "No update until now.")
lead.state = 'open'
self.assertEqual(lead.name, 'XX', "One update should have happened.")
lead.state = 'done'
self.assertEqual(lead.name, 'XXX', "One update should have happened.")
lead.state = 'done'
self.assertEqual(lead.name, 'XXX', "No update should have happened.")
lead.state = 'cancel'
self.assertEqual(lead.name, 'XXXX', "One update should have happened.")
# change the rule to trigger on partner_id
rule = self.env['base.automation'].search([('name', '=', 'Base Automation: test rule with trigger')])
rule.write({'trigger_field_ids': [(6, 0, [self.env.ref('test_base_automation.field_base_automation_lead_test__partner_id').id])]})
partner2 = self.env['res.partner'].create({'name': 'A new partner'})
lead.name = 'X'
lead.state = 'open'
self.assertEqual(lead.name, 'X', "No update should have happened.")
lead.partner_id = partner2
self.assertEqual(lead.name, 'XX', "One update should have happened.")
lead.partner_id = partner2
self.assertEqual(lead.name, 'XX', "No update should have happened.")
lead.partner_id = partner1
self.assertEqual(lead.name, 'XXX', "One update should have happened.")
def test_30_modelwithoutaccess(self):
"""
Ensure a domain on a M2O without user access doesn't fail.
We create a base automation with a filter on a model the user haven't access to
- create a group
- restrict acl to this group and set only admin in it
- create base.automation with a filter
- create a record in the restricted model in admin
- create a record in the non restricted model in demo
"""
Model = self.env['base.automation.link.test']
Comodel = self.env['base.automation.linked.test']
access = self.env.ref("test_base_automation.access_base_automation_linked_test")
access.group_id = self.env['res.groups'].create({
'name': "Access to base.automation.linked.test",
"users": [(6, 0, [self.user_admin.id,])]
})
# sanity check: user demo has no access to the comodel of 'linked_id'
with self.assertRaises(AccessError):
Comodel.with_user(self.user_demo).check_access_rights('read')
# check base automation with filter that performs Comodel.search()
self.env['base.automation'].create({
'name': 'test no access',
'model_id': self.env['ir.model']._get_id("base.automation.link.test"),
'trigger': 'on_create_or_write',
'filter_pre_domain': "[('linked_id.another_field', '=', 'something')]",
'state': 'code',
'active': True,
'code': "action = [rec.name for rec in records]"
})
Comodel.create([
{'name': 'a first record', 'another_field': 'something'},
{'name': 'another record', 'another_field': 'something different'},
])
rec1 = Model.create({'name': 'a record'})
rec1.write({'name': 'a first record'})
rec2 = Model.with_user(self.user_demo).create({'name': 'another record'})
rec2.write({'name': 'another value'})
# check base automation with filter that performs Comodel.name_search()
self.env['base.automation'].create({
'name': 'test no name access',
'model_id': self.env['ir.model']._get_id("base.automation.link.test"),
'trigger': 'on_create_or_write',
'filter_pre_domain': "[('linked_id', '=', 'whatever')]",
'state': 'code',
'active': True,
'code': "action = [rec.name for rec in records]"
})
rec3 = Model.create({'name': 'a random record'})
rec3.write({'name': 'a first record'})
rec4 = Model.with_user(self.user_demo).create({'name': 'again another record'})
rec4.write({'name': 'another value'})
@common.tagged('post_install', '-at_install')
class TestCompute(common.TransactionCase):
def test_inversion(self):
""" If a stored field B depends on A, an update to the trigger for A
should trigger the recomputaton of A, then B.
However if a search() is performed during the computation of A
??? and _order is affected ??? a flush will be triggered, forcing the
computation of B, based on the previous A.
This happens if a rule has has a non-empty filter_pre_domain, even if
it's an empty list (``'[]'`` as opposed to ``False``).
"""
company1 = self.env['res.partner'].create({
'name': "Gorofy",
'is_company': True,
})
company2 = self.env['res.partner'].create({
'name': "Awiclo",
'is_company': True
})
r = self.env['res.partner'].create({
'name': 'Bob',
'is_company': False,
'parent_id': company1.id
})
self.assertEqual(r.display_name, 'Gorofy, Bob')
r.parent_id = company2
self.assertEqual(r.display_name, 'Awiclo, Bob')
self.env['base.automation'].create({
'name': "test rule",
'filter_pre_domain': False,
'trigger': 'on_create_or_write',
'state': 'code', # no-op action
'model_id': self.env.ref('base.model_res_partner').id,
})
r.parent_id = company1
self.assertEqual(r.display_name, 'Gorofy, Bob')
self.env['base.automation'].create({
'name': "test rule",
'filter_pre_domain': '[]',
'trigger': 'on_create_or_write',
'state': 'code', # no-op action
'model_id': self.env.ref('base.model_res_partner').id,
})
r.parent_id = company2
self.assertEqual(r.display_name, 'Awiclo, Bob')
def test_recursion(self):
project = self.env['test_base_automation.project'].create({})
# this action is executed every time a task is assigned to project
self.env['base.automation'].create({
'name': 'dummy',
'model_id': self.env['ir.model']._get_id('test_base_automation.task'),
'state': 'code',
'trigger': 'on_create_or_write',
'filter_domain': repr([('project_id', '=', project.id)]),
})
# create one task in project with 10 subtasks; all the subtasks are
# automatically assigned to project, too
task = self.env['test_base_automation.task'].create({'project_id': project.id})
subtasks = task.create([{'parent_id': task.id} for _ in range(10)])
subtasks.flush()
# This test checks what happens when a stored recursive computed field
# is marked to compute on many records, and automated actions are
# triggered depending on that field. In this case, we trigger the
# recomputation of 'project_id' on 'subtasks' by deleting their parent
# task.
#
# An issue occurs when the domain of automated actions is evaluated by
# method search(), because the latter flushes the fields to search on,
# which are also the ones being recomputed. Combined with the fact
# that recursive fields are not computed in batch, this leads to a huge
# amount of recursive calls between the automated action and flush().
#
# The execution of task.unlink() looks like this:
# - mark 'project_id' to compute on subtasks
# - delete task
# - flush()
# - recompute 'project_id' on subtask1
# - call compute on subtask1
# - in action, search([('id', 'in', subtask1.ids), ('project_id', '=', pid)])
# - flush(['id', 'project_id'])
# - recompute 'project_id' on subtask2
# - call compute on subtask2
# - in action search([('id', 'in', subtask2.ids), ('project_id', '=', pid)])
# - flush(['id', 'project_id'])
# - recompute 'project_id' on subtask3
# - call compute on subtask3
# - in action, search([('id', 'in', subtask3.ids), ('project_id', '=', pid)])
# - flush(['id', 'project_id'])
# - recompute 'project_id' on subtask4
# ...
limit = sys.getrecursionlimit()
try:
sys.setrecursionlimit(100)
task.unlink()
finally:
sys.setrecursionlimit(limit)
| 47.183585
| 21,846
|
3,284
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil import relativedelta
from odoo import fields, models, api
class LeadTest(models.Model):
_name = "base.automation.lead.test"
_description = "Automated Rule Test"
name = fields.Char(string='Subject', required=True, index=True)
user_id = fields.Many2one('res.users', string='Responsible')
state = fields.Selection([('draft', 'New'), ('cancel', 'Cancelled'), ('open', 'In Progress'),
('pending', 'Pending'), ('done', 'Closed')],
string="Status", readonly=True, default='draft')
active = fields.Boolean(default=True)
partner_id = fields.Many2one('res.partner', string='Partner')
date_action_last = fields.Datetime(string='Last Action', readonly=True)
employee = fields.Boolean(compute='_compute_employee_deadline', store=True)
line_ids = fields.One2many('base.automation.line.test', 'lead_id')
priority = fields.Boolean()
deadline = fields.Boolean(compute='_compute_employee_deadline', store=True)
is_assigned_to_admin = fields.Boolean(string='Assigned to admin user')
@api.depends('partner_id.employee', 'priority')
def _compute_employee_deadline(self):
# this method computes two fields on purpose; don't split it
for record in self:
record.employee = record.partner_id.employee
if not record.priority:
record.deadline = False
else:
record.deadline = record.create_date + relativedelta.relativedelta(days=3)
def write(self, vals):
result = super().write(vals)
# force recomputation of field 'deadline' via 'employee': the action
# based on 'deadline' must be triggered
self.mapped('employee')
return result
class LineTest(models.Model):
_name = "base.automation.line.test"
_description = "Automated Rule Line Test"
name = fields.Char()
lead_id = fields.Many2one('base.automation.lead.test', ondelete='cascade')
user_id = fields.Many2one('res.users')
class ModelWithAccess(models.Model):
_name = "base.automation.link.test"
_description = "Automated Rule Link Test"
name = fields.Char()
linked_id = fields.Many2one('base.automation.linked.test', ondelete='cascade')
class ModelWithoutAccess(models.Model):
_name = "base.automation.linked.test"
_description = "Automated Rule Linked Test"
name = fields.Char()
another_field = fields.Char()
class Project(models.Model):
_name = _description = 'test_base_automation.project'
name = fields.Char()
task_ids = fields.One2many('test_base_automation.task', 'project_id')
class Task(models.Model):
_name = _description = 'test_base_automation.task'
name = fields.Char()
parent_id = fields.Many2one('test_base_automation.task')
project_id = fields.Many2one(
'test_base_automation.project',
compute='_compute_project_id', recursive=True, store=True, readonly=False,
)
@api.depends('parent_id.project_id')
def _compute_project_id(self):
for task in self:
if not task.project_id:
task.project_id = task.parent_id.project_id
| 36.087912
| 3,284
|
676
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "website_sale_delivery_mondialrelay",
'summary': """ Let's choose Point Relais® on your ecommerce """,
'description': """
This module allow your customer to choose a Point Relais® and use it as shipping address.
""",
'category': 'Website/Website',
'version': '0.1',
'depends': ['website_sale_delivery', 'delivery_mondialrelay'],
'data': [
'views/templates.xml',
],
'assets': {
'web.assets_frontend': [
'website_sale_delivery_mondialrelay/static/src/js/website_sale_delivery_mondialrelay.js',
],
},
'license': 'LGPL-3',
'auto_install': True,
}
| 30.636364
| 674
|
701
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class WebsiteMondialRelay(models.Model):
_inherit = 'website'
def _prepare_sale_order_values(self, partner, pricelist):
self.ensure_one()
values = super()._prepare_sale_order_values(partner, pricelist)
# never use Mondial Relay shipping address as default.
shipping_address = self.env['res.partner'].browse(values['partner_shipping_id'])
if shipping_address.id != values['partner_invoice_id'] and shipping_address.is_mondialrelay:
values['partner_shipping_id'] = values['partner_invoice_id']
return values
| 41.235294
| 701
|
3,925
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import http, _
from odoo.addons.website_sale.controllers.main import WebsiteSale, PaymentPortal
from odoo.addons.website_sale_delivery.controllers.main import WebsiteSaleDelivery
from odoo.exceptions import AccessDenied, ValidationError, UserError
from odoo.http import request
class MondialRelay(http.Controller):
@http.route(['/website_sale_delivery_mondialrelay/update_shipping'], type='json', auth="public", website=True)
def mondial_relay_update_shipping(self, **data):
order = request.website.sale_get_order()
if order.partner_id == request.website.user_id.sudo().partner_id:
raise AccessDenied('Customer of the order cannot be the public user at this step.')
if order.carrier_id.country_ids:
country_is_allowed = data['Pays'][:2].upper() in order.carrier_id.country_ids.mapped(lambda c: c.code.upper())
assert country_is_allowed, _("%s is not allowed for this delivery carrier.", data['Pays'])
partner_shipping = order.partner_id.sudo()._mondialrelay_search_or_create({
'id': data['ID'],
'name': data['Nom'],
'street': data['Adresse1'],
'street2': data['Adresse2'],
'zip': data['CP'],
'city': data['Ville'],
'country_code': data['Pays'][:2].lower(),
})
if order.partner_shipping_id != partner_shipping:
order.partner_shipping_id = partner_shipping
order.onchange_partner_shipping_id()
return {
'address': request.env['ir.qweb']._render('website_sale.address_on_payment', {
'order': order,
'only_services': order and order.only_services,
}),
'new_partner_shipping_id': order.partner_shipping_id.id,
}
class WebsiteSaleMondialrelay(WebsiteSale):
@http.route()
def address(self, **kw):
res = super().address(**kw)
Partner_sudo = request.env['res.partner'].sudo()
partner_id = res.qcontext.get('partner_id', 0)
if partner_id > 0 and Partner_sudo.browse(partner_id).is_mondialrelay:
raise UserError(_('You cannot edit the address of a Point Relais®.'))
return res
class WebsiteSaleDeliveryMondialrelay(WebsiteSaleDelivery):
def _update_website_sale_delivery_return(self, order, **post):
res = super()._update_website_sale_delivery_return(order, **post)
if order.carrier_id.is_mondialrelay:
res['mondial_relay'] = {
'brand': order.carrier_id.mondialrelay_brand,
'col_liv_mod': order.carrier_id.mondialrelay_packagetype,
'partner_zip': order.partner_shipping_id.zip,
'partner_country_code': order.partner_shipping_id.country_id.code.upper(),
'allowed_countries': ','.join(order.carrier_id.country_ids.mapped('code')).upper(),
}
if order.partner_shipping_id.is_mondialrelay:
res['mondial_relay']['current'] = '%s-%s' % (
res['mondial_relay']['partner_country_code'],
order.partner_shipping_id.ref.lstrip('MR#'),
)
return res
class PaymentPortalMondialRelay(PaymentPortal):
@http.route()
def shop_payment_transaction(self, *args, **kwargs):
order = request.website.sale_get_order()
if order.partner_shipping_id.is_mondialrelay and order.carrier_id and not order.carrier_id.is_mondialrelay and order.delivery_set:
raise ValidationError(_('Point Relais® can only be used with the delivery method Mondial Relay.'))
elif not order.partner_shipping_id.is_mondialrelay and order.carrier_id.is_mondialrelay:
raise ValidationError(_('Delivery method Mondial Relay can only ship to Point Relais®.'))
return super().shop_payment_transaction(*args, **kwargs)
| 45.08046
| 3,922
|
1,136
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2009 P. Christeas <p_christ@hol.gr>. All Rights Reserved
{
'name': 'Greece - Accounting',
'author': 'P. Christeas, OpenERP SA.',
'website': 'http://openerp.hellug.gr/',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the base module to manage the accounting chart for Greece.
==================================================================
Greek accounting chart and localization.
""",
'depends': [
'account',
'base_iban',
'base_vat',
],
'data': [ 'data/account_type_data.xml',
'data/l10n_gr_chart_data.xml',
'data/account.account.template.csv',
'data/account_chart_template_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_report_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_configure_data.xml'
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 32.457143
| 1,136
|
1,020
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name" : "Norway - Accounting",
"version" : "2.1",
"author" : "Rolv Råen",
'category': 'Accounting/Localizations/Account Charts',
"description": """This is the module to manage the accounting chart for Norway in Odoo.
Updated for Odoo 9 by Bringsvor Consulting AS <www.bringsvor.com>
""",
"depends" : [
"account",
"base_iban",
"base_vat",
],
"data": ['data/l10n_no_chart_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_report_data.xml',
'data/account.account.template.csv',
'data/account_tax_data.xml',
'data/account_chart_template_data.xml',
'views/res_partner_views.xml',
'views/res_company_views.xml',
],
'demo': [
'demo/demo_company.xml',
],
'post_init_hook': '_preserve_tag_on_taxes',
'license': 'LGPL-3',
}
| 31.84375
| 1,019
|
250
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
update_taxes_from_templates(cr, 'l10n_no.no_chart_template')
| 41.666667
| 250
|
291
|
py
|
PYTHON
|
15.0
|
from openerp.modules.registry import RegistryManager
def migrate(cr, version):
registry = RegistryManager.get(cr.dbname)
from openerp.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable
migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_no')
| 41.571429
| 291
|
1,034
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from stdnum import luhn
class AccountMove(models.Model):
_inherit = "account.move"
def _get_invoice_reference_no_invoice(self):
""" This computes the reference based on the Odoo format.
We calculat reference using invoice number and
partner id and added control digit at last.
"""
return self._get_kid_number()
def _get_invoice_reference_no_partner(self):
""" This computes the reference based on the Odoo format.
We calculat reference using invoice number and
partner id and added control digit at last.
"""
return self._get_kid_number()
def _get_kid_number(self):
self.ensure_one()
invoice_name = ''.join([i for i in self.name if i.isdigit()]).zfill(7)
ref = (str(self.partner_id.id).zfill(7)[-7:] + invoice_name[-7:])
return ref + luhn.calc_check_digit(ref)
| 35.655172
| 1,034
|
378
|
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 AccountJournal(models.Model):
_inherit = 'account.journal'
invoice_reference_model = fields.Selection(selection_add=[
('no', 'Norway')
], ondelete={'no': lambda recs: recs.write({'invoice_reference_model': 'odoo'})})
| 31.5
| 378
|
222
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
from odoo import fields, models
class ResCompany(models.Model):
_inherit = 'res.company'
l10n_no_bronnoysund_number = fields.Char(related='partner_id.l10n_no_bronnoysund_number', readonly=False)
| 27.75
| 222
|
234
|
py
|
PYTHON
|
15.0
|
# coding: utf-8
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
l10n_no_bronnoysund_number = fields.Char(string='Register of Legal Entities (Brønnøysund Register Center)', size=9)
| 29
| 232
|
1,414
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2010-2011 BAAMTU SARL (<http://www.baamtu.sn>).
# contact: leadsn@baamtu.com
{
'name' : 'OHADA - Accounting',
'author' : 'Baamtu Senegal',
'category': 'Accounting/Localizations/Account Charts',
'icon': '/l10n_syscohada/static/description/icon.jpeg',
'description': """
This module implements the accounting chart for OHADA area.
===========================================================
It allows any company or association to manage its financial accounting.
Countries that use OHADA are the following:
-------------------------------------------
Benin, Burkina Faso, Cameroon, Central African Republic, Comoros, Congo,
Ivory Coast, Gabon, Guinea, Guinea Bissau, Equatorial Guinea, Mali, Niger,
Democratic Republic of the Congo, Senegal, Chad, Togo.
""",
'website': 'http://www.baamtu.com',
'depends' : [
'account',
],
'data': [
'data/menuitem_data.xml',
'data/account_tax_group_data.xml',
'data/l10n_syscohada_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_syscohada_chart_post_data.xml',
'data/account_tax_template_data.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 32.883721
| 1,414
|
1,265
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Mail Group",
'summary': "Manage your mailing lists",
'description': """
Manage your mailing lists from Odoo.
""",
'version': '1.0',
'depends': [
'mail',
'portal',
],
'auto_install': False,
'data': [
'data/ir_cron_data.xml',
'data/mail_templates.xml',
'data/mail_template_data.xml',
'data/res_groups.xml',
'security/ir.model.access.csv',
'security/mail_group_security.xml',
'wizard/mail_group_message_reject_views.xml',
'views/mail_group_member_views.xml',
'views/mail_group_message_views.xml',
'views/mail_group_moderation_views.xml',
'views/mail_group_views.xml',
'views/mail_group_menus.xml',
'views/portal_templates.xml',
],
'demo': [
'data/mail_group_demo.xml',
],
'assets': {
'web.assets_frontend': [
'mail_group/static/src/css/mail_group.scss',
'mail_group/static/src/js/*',
],
'web.assets_backend': [
'mail_group/static/src/css/mail_group_backend.scss',
],
},
'license': 'LGPL-3',
}
| 28.75
| 1,265
|
3,172
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command, tools
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.test_mail.tests.common import TestMailCommon
class TestMailListCommon(TestMailCommon):
@classmethod
def setUpClass(cls):
super(TestMailListCommon, cls).setUpClass()
# Test credentials / from
cls.email_from_unknown = tools.formataddr(("Bob Lafrite", "bob.email@test.example.com"))
cls.user_employee_2 = mail_new_test_user(
cls.env, login='employee_2',
company_id=cls.company_admin.id,
email='employee_2@test.com',
groups='base.group_user',
name='Albertine Another Employee',
)
# Test group: members, moderation
cls.test_group = cls.env['mail.group'].create({
'access_mode': 'public',
'alias_name': 'test.mail.group',
'moderation': True,
'moderator_ids': [Command.link(cls.user_employee.id)],
'name': 'Test group',
})
cls.moderation = cls.env['mail.group.moderation'].create({
'mail_group_id': cls.test_group.id,
'email': 'banned_member@test.com',
'status': 'ban',
})
cls.test_group_member_1 = cls.env['mail.group.member'].create({
'email': '"Member 1" <member_1@test.com>',
'mail_group_id': cls.test_group.id,
})
cls.test_group_member_2 = cls.env['mail.group.member'].create({
'email': 'member_2@test.com',
'mail_group_id': cls.test_group.id,
})
cls.test_group_member_3_banned = cls.env['mail.group.member'].create({
'email': '"Banned Member" <banned_member@test.com>',
'mail_group_id': cls.test_group.id,
})
cls.test_group_member_4_emp = cls.env['mail.group.member'].create({
'partner_id': cls.partner_employee.id,
'mail_group_id': cls.test_group.id,
})
cls.test_group_valid_members = cls.test_group_member_1 + cls.test_group_member_2 + cls.test_group_member_4_emp
cls._init_mail_gateway()
# Create some messages
cls.test_group_msg_1_pending = cls.env['mail.group.message'].create({
'subject': 'Test message pending',
'mail_group_id': cls.test_group.id,
'moderation_status': 'pending_moderation',
'email_from': '"Bob" <bob@test.com>',
})
cls.test_group_msg_2_accepted = cls.env['mail.group.message'].create({
'subject': 'Test message accepted',
'mail_group_id': cls.test_group.id,
'moderation_status': 'accepted',
'email_from': '"Alice" <alice@test.com>',
})
cls.test_group_msg_3_rejected = cls.env['mail.group.message'].create({
'subject': 'Test message rejected',
'mail_group_id': cls.test_group.id,
'moderation_status': 'rejected',
'email_from': '"Alice" <alice@test.com>',
})
cls.user_portal = cls._create_portal_user()
| 39.65
| 3,172
|
8,201
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail_group.tests.common import TestMailListCommon
from odoo.addons.mail_group.tests.data import GROUP_TEMPLATE
from odoo.exceptions import AccessError
from odoo.tools import mute_logger
class TestMailGroupMessage(TestMailListCommon):
def test_batch_send(self):
"""Test that when someone sends an email to a large group that it is
delivered exactly to those people"""
self.test_group.write({
'access_mode': 'members',
'alias_contact': 'followers',
'moderation': False,
})
self.test_group.member_ids.unlink()
for num in range(42):
self.env['mail.group.member'].create({
'email': f'emu-{num}@example.com',
'mail_group_id': self.test_group.id,
})
self.assertEqual(len(self.test_group.member_ids), 42)
# force a batch split with a low limit
self.env['ir.config_parameter'].sudo().set_param('mail.session.batch.size', 10)
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.test_group.member_ids[0].email,
self.test_group.alias_id.display_name,
subject='Never Surrender', msg_id='<glory.to.the.hypnotoad@localhost>', target_model='mail.group')
message = self.env['mail.group.message'].search([('mail_message_id.message_id', '=', '<glory.to.the.hypnotoad@localhost>')])
self.assertEqual(message.subject, 'Never Surrender', 'Should have created a <mail.group.message>')
mails = self.env['mail.mail'].search([('mail_message_id', '=', message.mail_message_id.id)])
# 42 -1 as the sender doesn't get an email
self.assertEqual(len(mails), 41, 'Should have send one and only one email per recipient')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message')
def test_email_duplicated(self):
""" Test gateway does not accept two times same incoming email """
self.test_group.write({'moderation': False})
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='Test subject', msg_id='<test.message.id@localhost>', target_model='mail.group')
message = self.env['mail.group.message'].search([('mail_message_id.message_id', '=', '<test.message.id@localhost>')])
self.assertEqual(message.subject, 'Test subject', 'Should have created a <mail.group.message>')
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='Another subject', msg_id='<test.message.id@localhost>', target_model='mail.group')
new_message = self.env['mail.group.message'].search([('mail_message_id.message_id', '=', '<test.message.id@localhost>')])
self.assertEqual(new_message, message)
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message')
def test_email_not_sent_to_author(self):
"""Test that when someone sends an email the group process does not send
it back to the original author."""
self.test_group.write({'moderation': False})
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.test_group_member_1.email,
self.test_group.alias_id.display_name,
subject='Test subject', target_model='mail.group')
mails = self.env['mail.mail'].search([('subject', '=', 'Test subject')])
self.assertEqual(len(mails), len(self.test_group.member_ids) - 1)
self.assertNotIn(self.test_group_member_1.email, mails.mapped('email_to'), 'Should not have send the email to the original author')
@mute_logger('odoo.addons.base.models.ir_rule')
def test_mail_group_message_security_groups(self):
user_group = self.env.ref('base.group_partner_manager')
self.test_group.access_group_id = user_group
self.test_group.access_mode = 'groups'
# Message pending
with self.assertRaises(AccessError, msg='Portal should not have access to pending messages'):
self.test_group_msg_1_pending.with_user(self.user_portal).check_access_rule('read')
self.user_portal.groups_id |= user_group
with self.assertRaises(AccessError, msg='Non moderator should have access to only accepted message'):
self.test_group_msg_1_pending.with_user(self.user_portal).check_access_rule('read')
self.test_group_msg_1_pending.invalidate_cache()
self.assertEqual(self.test_group_msg_1_pending.with_user(self.user_employee).moderation_status, 'pending_moderation',
msg='Moderators should have access to pending message')
# Message accepted
self.test_group_msg_2_accepted.invalidate_cache()
self.assertEqual(self.test_group_msg_2_accepted.with_user(self.user_portal).moderation_status, 'accepted',
msg='Portal should have access to accepted messages')
self.user_portal.groups_id -= user_group
with self.assertRaises(AccessError, msg='User not in the group should not have access to accepted message'):
self.test_group_msg_2_accepted.with_user(self.user_portal).check_access_rule('read')
@mute_logger('odoo.addons.base.models.ir_rule')
def test_mail_group_message_security_public(self):
self.test_group.access_mode = 'public'
# Message pending
with self.assertRaises(AccessError, msg='Portal should not have access to pending messages'):
self.test_group_msg_1_pending.with_user(self.user_portal).check_access_rule('read')
with self.assertRaises(AccessError, msg='Non moderator should have access to only accepted message'):
self.test_group_msg_1_pending.with_user(self.user_employee_2).check_access_rule('read')
self.test_group_msg_1_pending.invalidate_cache()
self.assertEqual(self.test_group_msg_1_pending.with_user(self.user_employee).moderation_status, 'pending_moderation',
msg='Moderators should have access to pending message')
# Message rejected
with self.assertRaises(AccessError, msg='Portal should not have access to pending messages'):
self.test_group_msg_1_pending.with_user(self.user_portal).check_access_rule('read')
# Message accepted
self.assertEqual(self.test_group_msg_2_accepted.with_user(self.user_portal).moderation_status, 'accepted',
msg='Portal should have access to accepted messages')
self.test_group_msg_3_rejected.invalidate_cache()
self.assertEqual(self.test_group_msg_1_pending.with_user(self.user_admin).moderation_status, 'pending_moderation',
msg='Mail Group Administrator should have access to all messages')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message')
def test_email_empty_from(self):
"""Test that when someone sends an email the group process does not send
it back to the original author."""
self.test_group.write({
'access_mode': 'members',
'alias_contact': 'followers',
'moderation': False,
})
# new member without email
self.env['mail.group.member'].create({
'email': '',
'mail_group_id': self.test_group.id,
})
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, "Foo",
self.test_group.alias_id.display_name,
subject='Test subject', target_model='mail.group')
mails = self.env['mail.mail'].search([('subject', '=', 'Test subject')])
self.assertEqual(len(mails), 0, "Email should not be delivered when no email is specified")
| 51.25625
| 8,201
|
20,232
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from psycopg2 import IntegrityError
from odoo import Command, tools
from odoo.addons.mail_group.tests.data import GROUP_TEMPLATE
from odoo.addons.mail_group.tests.common import TestMailListCommon
from odoo.exceptions import AccessError
from odoo.tests.common import tagged, users
from odoo.tools import mute_logger
@tagged('mail_group_moderation')
class TestMailGroupModeration(TestMailListCommon):
@classmethod
def setUpClass(cls):
super(TestMailGroupModeration, cls).setUpClass()
cls.test_group_2 = cls.env['mail.group'].create({
'access_mode': 'members',
'alias_name': 'test.mail.group.2',
'moderation': True,
'moderator_ids': [Command.link(cls.user_employee.id)],
'name': 'Test group 2',
})
@mute_logger('odoo.sql_db')
@users('employee')
def test_constraints(self):
mail_group = self.env['mail.group'].browse(self.test_group.ids)
with self.assertRaises(IntegrityError):
moderation = self.env['mail.group.moderation'].create({
'mail_group_id': mail_group.id,
'email': 'banned_member@test.com',
'status': 'ban',
})
moderation.flush()
@mute_logger('odoo.models.unlink', 'odoo.addons.mail_group.models.mail_group_message')
@users('employee')
def test_moderation_rule_api(self):
""" Test moderation rule creation / update through API """
mail_group = self.env['mail.group'].browse(self.test_group.ids)
mail_group_2 = self.env['mail.group'].browse(self.test_group_2.ids)
self.assertEqual(
set(mail_group.moderation_rule_ids.mapped('email')),
set(['banned_member@test.com'])
)
moderation_1, moderation_2, moderation_3 = self.env['mail.group.moderation'].create([{
'email': 'std@test.com',
'status': 'allow',
'mail_group_id': mail_group.id,
}, {
'email': 'xss@test.com',
'status': 'ban',
'mail_group_id': mail_group.id,
}, {
'email': 'xss@test.com',
'status': 'ban',
'mail_group_id': mail_group_2.id,
}])
self.assertEqual(
set(mail_group.moderation_rule_ids.mapped('email')),
set(['banned_member@test.com', 'std@test.com', 'xss@test.com'])
)
message_1, message_2, message_3 = self.env['mail.group.message'].create([{
'email_from': '"Boum" <sTd@teST.com>',
'mail_group_id': mail_group.id,
}, {
'email_from': '"xSs" <xss@teST.com>',
'mail_group_id': mail_group.id,
}, {
'email_from': '"Bob" <bob@teST.com>',
'mail_group_id': mail_group.id,
}])
# status 'bouh' does not exist
with self.assertRaises(ValueError):
(message_1 | message_2 | message_3)._create_moderation_rule('bouh')
(message_1 | message_2 | message_3)._create_moderation_rule('allow')
self.assertEqual(len(mail_group.moderation_rule_ids), 4, "Should have created only one moderation rule")
self.assertEqual(
set(mail_group.moderation_rule_ids.mapped('email')),
set(['banned_member@test.com', 'std@test.com', 'xss@test.com', 'bob@test.com'])
)
self.assertEqual(moderation_1.status, 'allow')
self.assertEqual(moderation_2.status, 'allow', 'Should have write on the existing moderation rule')
self.assertEqual(moderation_3.status, 'ban', 'Should not have changed moderation of the other group')
new_moderation = mail_group.moderation_rule_ids.filtered(lambda rule: rule.email == 'bob@test.com')
self.assertEqual(new_moderation.status, 'allow', 'Should have created the moderation with the right status')
@users('employee')
def test_moderation_rule_email_normalize(self):
""" Test emails are automatically normalized """
rule = self.env['mail.group.moderation'].create({
'mail_group_id': self.test_group.id,
'email': '"Bob" <bob@test.com>',
'status': 'ban',
})
self.assertEqual(rule.email, 'bob@test.com')
rule.email = '"Alice" <alice@test.com>'
self.assertEqual(rule.email, 'alice@test.com')
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model')
def test_moderation_rule_security(self):
with self.assertRaises(AccessError, msg='Portal should not have access to moderation rules'):
self.env['mail.group.moderation'].with_user(self.user_portal).browse(self.moderation.ids).email
self.test_group.write({
'moderator_ids': [(4, self.user_admin.id), (3, self.user_employee.id)]
})
with self.assertRaises(AccessError, msg='Non moderators should not have access to moderation rules'):
self.env['mail.group.moderation'].with_user(self.user_employee).browse(self.moderation.ids).email
self.assertEqual(
self.env['mail.group.moderation'].with_user(self.user_admin).browse(self.moderation.ids).email,
'banned_member@test.com',
msg='Moderators should have access to moderation rules')
@tagged('mail_group_moderation')
class TestModeration(TestMailListCommon):
@classmethod
def setUpClass(cls):
super(TestModeration, cls).setUpClass()
# Test group: members, moderation
cls.test_group_2 = cls.env['mail.group'].create({
'access_mode': 'members',
'alias_name': 'test.mail.group.2',
'moderation': True,
'moderator_ids': [Command.link(cls.user_employee.id)],
'name': 'Test group 2',
})
cls.test_group_2_member_emp = cls.env['mail.group.member'].create({
'partner_id': cls.user_employee_2.partner_id.id,
'email': cls.user_employee_2.email,
'mail_group_id': cls.test_group_2.id,
})
# Existing messages on group 2
cls.test_group_2_msg_1_pending = cls.env['mail.group.message'].create({
'email_from': cls.email_from_unknown,
'subject': 'Group 2 Pending',
'mail_group_id': cls.test_group_2.id,
'moderation_status': 'pending_moderation',
})
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message')
@users('employee')
def test_moderation_flow_accept(self):
""" Unknown email sends email on moderated group, test accept """
mail_group = self.env['mail.group'].browse(self.test_group.ids)
self.assertEqual(len(mail_group.mail_group_message_ids), 3)
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='Old email', target_model='mail.group')
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='New email', target_model='mail.group')
# find messages
self.assertEqual(len(mail_group.mail_group_message_ids), 5)
old_email_message = mail_group.mail_group_message_ids[-2]
new_email_message = mail_group.mail_group_message_ids[-1]
# check message content
self.assertEqual(old_email_message.moderation_status, 'pending_moderation')
self.assertEqual(old_email_message.subject, 'Old email')
self.assertEqual(new_email_message.moderation_status, 'pending_moderation')
self.assertEqual(new_email_message.subject, 'New email')
# accept email without any moderation rule
with self.mock_mail_gateway():
new_email_message.action_moderate_accept()
self.assertEqual(len(self._new_mails), 4)
for email in self.test_group_valid_members.mapped('email'):
self.assertMailMailWEmails([email], 'outgoing',
content="This should be posted on a mail.group. Or not.",
fields_values={
'email_from': self.email_from_unknown,
'subject': 'New email',
},
mail_message=new_email_message.mail_message_id)
self.assertEqual(new_email_message.moderation_status, 'accepted', 'Should have accepted the message')
self.assertEqual(old_email_message.moderation_status, 'pending_moderation', 'Should not have touched other message of the same author')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message', 'odoo.models.unlink')
@users('employee')
def test_moderation_flow_allow(self):
""" Unknown email sends email on moderated group, test allow """
mail_group = self.test_group
mail_group_2_as2 = self.env['mail.group'].with_user(self.user_employee_2).browse(self.test_group_2.ids)
self.assertEqual(len(mail_group.mail_group_message_ids), 3)
group_2_message_count = len(mail_group_2_as2.mail_group_message_ids)
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='Old email', target_model='mail.group')
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='New email', target_model='mail.group')
# find messages
self.assertEqual(len(mail_group.mail_group_message_ids), 5)
old_email_message = mail_group.mail_group_message_ids[-2]
new_email_message = mail_group.mail_group_message_ids[-1]
# check message content
self.assertEqual(old_email_message.email_from, self.email_from_unknown)
self.assertEqual(old_email_message.moderation_status, 'pending_moderation')
self.assertEqual(old_email_message.subject, 'Old email')
self.assertEqual(new_email_message.email_from, self.email_from_unknown)
self.assertEqual(new_email_message.moderation_status, 'pending_moderation')
self.assertEqual(new_email_message.subject, 'New email')
# Create a moderation rule to always accept this email address
with self.mock_mail_gateway():
new_email_message.action_moderate_allow()
self.assertEqual(new_email_message.moderation_status, 'accepted', 'Should have accepted the message')
self.assertEqual(old_email_message.moderation_status, 'accepted', 'Should have accepted the old message of the same author')
# Test that the moderation rule has been created
new_rule = self.env['mail.group.moderation'].search([
('status', '=', 'allow'),
('email', '=', tools.email_normalize(self.email_from_unknown))
])
self.assertEqual(len(new_rule), 1, 'Should have created a moderation rule')
# Check emails have been sent
self.assertEqual(len(self._new_mails), 8)
for email in self.test_group_valid_members.mapped('email'):
self.assertMailMailWEmails([email], 'outgoing',
content="This should be posted on a mail.group. Or not.",
fields_values={
'email_from': self.email_from_unknown,
'subject': 'New email',
},
mail_message=new_email_message.mail_message_id)
self.assertMailMailWEmails([email], 'outgoing',
content="This should be posted on a mail.group. Or not.",
fields_values={
'email_from': self.email_from_unknown,
'subject': 'Old email',
},
mail_message=old_email_message.mail_message_id)
# Send a second email with the same FROM, but with a different name
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE,
tools.formataddr(("Another Name", "bob.email@test.example.com")),
self.test_group.alias_id.display_name,
subject='Another email', target_model='mail.group')
# find messages
self.assertEqual(len(mail_group.mail_group_message_ids), 6)
new_email_message = mail_group.mail_group_message_ids[-1]
self.assertEqual(new_email_message.email_from, tools.formataddr(("Another Name", "bob.email@test.example.com")))
self.assertEqual(new_email_message.moderation_status, 'accepted', msg='Should have automatically accepted the email')
self.assertEqual(new_email_message.subject, 'Another email')
self.assertEqual(
self.test_group_2_msg_1_pending.moderation_status, 'pending_moderation',
'Should not have accepted message in the other group')
self.assertEqual(
len(mail_group_2_as2.mail_group_message_ids), group_2_message_count,
'Should never have created message in the other group')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message', 'odoo.models.unlink')
@users('employee')
def test_moderation_flow_ban(self):
""" Unknown email sends email on moderated group, test ban """
mail_group = self.env['mail.group'].browse(self.test_group.ids)
self.assertEqual(len(mail_group.mail_group_message_ids), 3)
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='Old email', target_model='mail.group')
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='New email', target_model='mail.group')
# find messages
self.assertEqual(len(mail_group.mail_group_message_ids), 5)
old_email_message = mail_group.mail_group_message_ids[-2]
new_email_message = mail_group.mail_group_message_ids[-1]
# ban and check moderation rule has been
with self.mock_mail_gateway():
new_email_message.action_moderate_ban()
self.assertEqual(old_email_message.moderation_status, 'rejected')
self.assertEqual(new_email_message.moderation_status, 'rejected')
# Test that the moderation rule has been created
new_rule = self.env['mail.group.moderation'].search([
('status', '=', 'ban'),
('email', '=', tools.email_normalize(self.email_from_unknown))
])
self.assertEqual(len(new_rule), 1, 'Should have created a moderation rule')
# Check no mail.mail has been sent
self.assertEqual(len(self._new_mails), 0, 'Should not have send emails')
# Send a second email with the same FROM, but with a different name
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE,
tools.formataddr(("Another Name", "bob.email@test.example.com")),
self.test_group.alias_id.display_name,
subject='Another email', target_model='mail.group')
# find messages
self.assertEqual(len(mail_group.mail_group_message_ids), 6)
new_email_message = mail_group.mail_group_message_ids[-1]
self.assertEqual(new_email_message.moderation_status, 'rejected', 'Should have automatically rejected the email')
# Check no mail.mail has been sent
self.assertEqual(len(self._new_mails), 0, 'Should not have send emails')
@mute_logger('odoo.addons.mail.models.mail_thread', 'odoo.addons.mail_group.models.mail_group_message', 'odoo.models.unlink')
@users('employee')
def test_moderation_flow_reject(self):
""" Unknown email sends email on moderated group, test reject """
mail_group = self.env['mail.group'].browse(self.test_group.ids)
self.assertEqual(len(mail_group.mail_group_message_ids), 3)
with self.mock_mail_gateway():
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='Old email', target_model='mail.group')
self.format_and_process(
GROUP_TEMPLATE, self.email_from_unknown, self.test_group.alias_id.display_name,
subject='New email', target_model='mail.group')
# find messages
self.assertEqual(len(mail_group.mail_group_message_ids), 5)
old_email_message = mail_group.mail_group_message_ids[-2]
new_email_message = mail_group.mail_group_message_ids[-1]
# reject without moderation rule
with self.mock_mail_gateway():
new_email_message.action_moderate_reject_with_comment('Test Rejected', 'Bad email')
self.assertEqual(new_email_message.moderation_status, 'rejected', 'Should have rejected the message')
self.assertEqual(old_email_message.moderation_status, 'pending_moderation', 'Should not have rejected old message')
self.assertEqual(len(self._new_mails), 1, 'Should have sent the reject email')
self.assertMailMailWEmails([self.email_from_unknown], 'outgoing',
content="This should be posted on a mail.group. Or not.",
fields_values={
'email_from': self.user_employee.email_formatted,
'subject': 'Test Rejected',
})
@mute_logger('odoo.addons.mail_group.models.mail_group')
@users('employee')
def test_moderation_send_guidelines(self):
""" Test sending guidelines """
mail_group = self.env['mail.group'].browse(self.test_group.ids)
mail_group.write({
'moderation_guidelines': True,
'moderation_guidelines_msg': 'Test guidelines group',
})
with self.mock_mail_gateway():
mail_group.action_send_guidelines()
self.assertEqual(len(self._new_mails), 3)
for email in self.test_group_valid_members.mapped('email'):
self.assertMailMailWEmails([email], 'outgoing',
content="Test guidelines group",
fields_values={
'email_from': self.env.company.email_formatted,
'subject': 'Guidelines of group %s' % mail_group.name,
})
@mute_logger('odoo.addons.mail_group.models.mail_group')
@users('employee')
def test_moderation_send_guidelines_on_new_member(self):
""" Test sending guidelines when having a new members """
mail_group = self.env['mail.group'].browse(self.test_group.ids)
mail_group.write({
'moderation_guidelines': True,
'moderation_guidelines_msg': 'Test guidelines group',
})
with self.mock_mail_gateway():
mail_group._join_group('"New Member" <new.member@test.com>')
self.assertEqual(len(self._new_mails), 1)
self.assertMailMailWEmails(['"New Member" <new.member@test.com>'], 'outgoing',
content="Test guidelines group",
fields_values={
'email_from': self.env.company.email_formatted,
'subject': 'Guidelines of group %s' % mail_group.name,
})
| 48.634615
| 20,232
|
1,292
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
GROUP_TEMPLATE = """Return-Path: <whatever-2a840@postmaster.twitter.com>
To: {to}
cc: {cc}
Received: by mail1.openerp.com (Postfix, from userid 10002)
id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)
From: {email_from}
Subject: {subject}
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_Part_4200734_24778174.1344608186754"
Date: Fri, 10 Aug 2012 14:16:26 +0000
Message-ID: {msg_id}
{extra}
------=_Part_4200734_24778174.1344608186754
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
This should be posted on a mail.group. Or not.
--
Sylvie
------=_Part_4200734_24778174.1344608186754
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>=20
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8" />
</head>=20
<body style=3D"margin: 0; padding: 0; background: #ffffff;-webkit-text-size-adjust: 100%;">=20
<p>This should be posted on a mail.group. Or not.</p>
<p>--<br/>
Sylvie
<p>
</body>
</html>
------=_Part_4200734_24778174.1344608186754--
"""
| 29.363636
| 1,292
|
11,863
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.mail_group.tests.common import TestMailListCommon
from odoo.exceptions import ValidationError, AccessError
from odoo.tests.common import users
from odoo.tools import mute_logger, append_content_to_html
class TestMailGroup(TestMailListCommon):
def test_clean_email_body(self):
template = self.env.ref('mail_group.mail_group_footer')
footer = template._render({'group_url': 'Test remove footer'}, engine='ir.qweb', minimal_qcontext=True)
body = append_content_to_html("<div>Test email body</div>", footer, plaintext=False)
result = self.env['mail.group']._clean_email_body(body)
self.assertIn('Test email body', result, 'Should have kept the original email body')
self.assertNotIn('Test remove footer', result, 'Should have removed the mailing list footer')
self.assertNotIn('o_mg_message_footer', result, 'Should have removed the entire HTML element')
def test_constraint_valid_email(self):
mail_group = self.env['mail.group'].with_user(self.user_employee).browse(self.test_group.ids)
user_without_email = mail_new_test_user(
self.env, login='user_employee_nomail',
company_id=self.company_admin.id,
email=False,
groups='base.group_user',
name='User without email',
)
with self.assertRaises(ValidationError, msg="Moderators must have an email"):
mail_group.moderator_ids |= user_without_email
def test_find_member(self):
"""Test the priority to retrieve a member of a mail group from a partner_id
and an email address.
When a partner is given for the search, return in priority
- The member whose partner match the given partner
- The member without partner but whose email match the given email
When no partner is given for the search, return in priority
- A member whose email match the given email and has no partner
- A member whose email match the given email and has partner
"""
member_1 = self.test_group_member_1
email = member_1.email_normalized
partner_2 = self.user_portal.partner_id
partner_2.email = '"Bob" <%s>' % email
member_2 = self.env['mail.group.member'].create({
'partner_id': partner_2.id,
'mail_group_id': self.test_group.id,
})
partner_3 = self.partner_root
partner_3.email = '"Bob" <%s>' % email
member_3 = self.env['mail.group.member'].create({
'partner_id': partner_3.id,
'mail_group_id': self.test_group.id,
})
self.env['mail.group.member'].create({
'email': "Alice",
'mail_group_id': self.test_group.id,
})
member = self.test_group._find_member(email)
self.assertEqual(member, member_1, 'When no partner is provided, return the member without partner in priority')
member = self.test_group._find_member(email, partner_2.id)
self.assertEqual(member, member_2, 'Should return the member with the right partner')
member = self.test_group._find_member(email, partner_3.id)
self.assertEqual(member, member_3, 'Should return the member with the right partner')
member_2.unlink()
member = self.test_group._find_member(email, partner_2.id)
self.assertEqual(member, member_1, 'Should return the member without partner')
member_1.unlink()
member = self.test_group._find_member(email, partner_2.id)
self.assertFalse(member, 'Should not return any member because the only one with the same email has a different partner')
member = self.test_group._find_member('', None)
self.assertEqual(member, None, 'When no email nor partner is provided, return nobody')
def test_find_member_for_alias(self):
"""Test the matching of a mail_group.members, when 2 users have the same partner email, and
that the first user was subscribed."""
user = self.user_portal
user2 = mail_new_test_user(self.env, login='login_2', email=user.email)
member = self.env['mail.group.member'].create({
# subscribe with the first user
'partner_id': user.partner_id.id,
'mail_group_id': self.test_group.id,
})
self.assertEqual(member.email, user.email)
# In case of matching, function return a falsy value.
# Should not return string (exception) if at least one members have the same email, whatever
# the partner (author_id) that could match this email.
msg_dict = {
# send mail with the second user
'author_id': user2.partner_id.id,
'email_from': user2.email,
}
self.test_group.alias_id.alias_contact = 'followers'
self.assertFalse(self.test_group._alias_get_error_message({}, msg_dict, self.test_group.alias_id))
@users('employee')
def test_join_group(self):
mail_group = self.env['mail.group'].browse(self.test_group.ids)
self.assertEqual(len(mail_group.member_ids), 4)
mail_group._join_group('"Jack" <jack@test.com>')
self.assertEqual(len(mail_group.member_ids), 5)
self.assertTrue(mail_group._find_member('"Test" <jack@test.com>'))
mail_group._join_group('"Jack the developer" <jack@test.com>')
self.assertEqual(len(mail_group.member_ids), 5, 'Should not have added the duplicated email')
# Join a group with a different email than the partner
portal_partner = self.user_portal.partner_id
mail_group._join_group('"Bob" <email_different_than_partner@test.com>', portal_partner.id)
self.assertEqual(len(mail_group.member_ids), 6, 'Should have added the new member')
member = mail_group._find_member('email_different_than_partner@test.com', portal_partner.id)
self.assertTrue(member)
self.assertEqual(member.partner_id, portal_partner, 'Should have set the partner')
self.assertEqual(member.email, portal_partner.email, 'Should have force the email to the email of the partner')
self.assertEqual(member.email_normalized, portal_partner.email_normalized)
portal_partner.email = 'new_portal_email@example.com'
self.assertEqual(member.email, 'new_portal_email@example.com', 'Should have change the email of the partner')
self.assertEqual(member.email_normalized, 'new_portal_email@example.com')
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model')
@users('employee')
def test_mail_group_access_mode_groups(self):
test_group = self.env.ref('base.group_partner_manager')
mail_group = self.env['mail.group'].browse(self.test_group.ids)
mail_group.write({
'access_group_id': test_group.id,
'access_mode': 'groups',
})
with self.assertRaises(AccessError):
mail_group.with_user(self.user_portal).check_access_rule('read')
public_user = self.env.ref('base.public_user')
with self.assertRaises(AccessError):
mail_group.with_user(public_user).check_access_rule('read')
with self.assertRaises(AccessError):
mail_group.with_user(self.user_employee_2).check_access_rule('read')
# Add the group to the user
self.user_employee_2.groups_id |= test_group
mail_group.with_user(self.user_employee_2).check_access_rule('read')
with self.assertRaises(AccessError, msg='Only moderator / responsible and admin can write on the group'):
mail_group.with_user(self.user_employee_2).check_access_rule('write')
# Remove the group of the user BUT add it in the moderators list
self.user_employee_2.groups_id -= test_group
mail_group.moderator_ids |= self.user_employee_2
mail_group.with_user(self.user_employee_2).check_access_rule('read')
mail_group.with_user(self.user_employee_2).check_access_rule('write')
# Test with public user
mail_group.access_group_id = self.env.ref('base.group_public')
mail_group.with_user(public_user).check_access_rule('read')
mail_group.with_user(public_user).check_access_rights('read')
with self.assertRaises(AccessError):
mail_group.with_user(public_user).check_access_rule('write')
mail_group.with_user(public_user).check_access_rights('write')
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model')
@users('employee')
def test_mail_group_access_mode_public(self):
mail_group = self.env['mail.group'].browse(self.test_group.ids)
mail_group.access_mode = 'public'
public_user = self.env.ref('base.public_user')
mail_group.with_user(public_user).check_access_rule('read')
with self.assertRaises(AccessError):
mail_group.with_user(public_user).check_access_rights('write')
mail_group.with_user(self.user_employee_2).check_access_rule('read')
with self.assertRaises(AccessError, msg='Only moderator / responsible and admin can write on the group'):
mail_group.with_user(self.user_employee_2).check_access_rule('write')
mail_group.moderator_ids |= self.user_employee_2
mail_group.with_user(self.user_employee_2).check_access_rule('write')
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model')
@users('employee')
def test_mail_group_access_mode_members(self):
mail_group = self.env['mail.group'].browse(self.test_group.ids)
mail_group.access_mode = 'members'
partner = self.user_employee_2.partner_id
self.assertNotIn(partner, mail_group.member_partner_ids)
with self.assertRaises(AccessError, msg='Non-member should not have access to the group'):
mail_group.with_user(self.user_employee_2).check_access_rule('read')
public_user = self.env.ref('base.public_user')
with self.assertRaises(AccessError, msg='Non-member should not have access to the group'):
mail_group.with_user(public_user).check_access_rule('read')
mail_group.write({'member_ids': [(0, 0, {
'partner_id': partner.id,
})]})
self.assertIn(partner, mail_group.member_partner_ids)
# Now that portal is in the member list he should have access
mail_group.with_user(self.user_employee_2).check_access_rule('read')
with self.assertRaises(AccessError, msg='Only moderator / responsible and admin can write on the group'):
mail_group.with_user(self.user_employee_2).check_access_rule('write')
mail_group.moderator_ids |= self.user_employee_2
mail_group.with_user(self.user_employee_2).check_access_rule('write')
@mute_logger('odoo.addons.base.models.ir_rule', 'odoo.addons.base.models.ir_model')
@users('employee')
def test_mail_group_member_security(self):
member = self.env['mail.group.member'].browse(self.test_group_member_1.ids)
self.assertEqual(member.email, '"Member 1" <member_1@test.com>', msg='Moderators should have access to members')
with self.assertRaises(AccessError, msg='Portal should not have access to members'):
member.with_user(self.user_portal).check_access_rule('read')
member.with_user(self.user_portal).check_access_rights('read')
with self.assertRaises(AccessError, msg='Non moderators should not have access to member'):
member.with_user(self.user_portal).check_access_rule('read')
member.with_user(self.user_portal).check_access_rights('read')
| 49.844538
| 11,863
|
1,892
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools, _
class MailGroupMessageReject(models.TransientModel):
_name = 'mail.group.message.reject'
_description = 'Reject Group Message'
subject = fields.Char('Subject', store=True, readonly=False, compute='_compute_subject')
body = fields.Html('Contents', default='', sanitize_style=True)
email_from_normalized = fields.Char('Email From', related='mail_group_message_id.email_from_normalized')
mail_group_message_id = fields.Many2one('mail.group.message', string="Message", required=True, readonly=True)
action = fields.Selection([('reject', 'Reject'), ('ban', 'Ban')], string='Action', required=True)
send_email = fields.Boolean('Send Email', help='Send an email to the author of the message', compute='_compute_send_email')
@api.depends('mail_group_message_id')
def _compute_subject(self):
for wizard in self:
wizard.subject = _('Re: %s', wizard.mail_group_message_id.subject or '')
@api.depends('body')
def _compute_send_email(self):
for wizard in self:
wizard.send_email = not tools.is_html_empty(wizard.body)
def action_send_mail(self):
self.ensure_one()
# Reject
if self.action == 'reject' and self.send_email:
self.mail_group_message_id.action_moderate_reject_with_comment(self.subject, self.body)
elif self.action == 'reject' and not self.send_email:
self.mail_group_message_id.action_moderate_reject()
# Ban
elif self.action == 'ban' and self.send_email:
self.mail_group_message_id.action_moderate_ban_with_comment(self.subject, self.body)
elif self.action == 'ban' and not self.send_email:
self.mail_group_message_id.action_moderate_ban()
| 45.047619
| 1,892
|
1,470
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, fields, models
from odoo.tools import email_normalize
_logger = logging.getLogger(__name__)
class MailGroupMember(models.Model):
"""Models a group member that can be either an email address either a full partner."""
_name = 'mail.group.member'
_description = 'Mailing List Member'
_rec_name = 'email'
email = fields.Char(string='Email', compute='_compute_email', readonly=False, store=True)
email_normalized = fields.Char(
string='Normalized Email', compute='_compute_email_normalized',
index=True, store=True)
mail_group_id = fields.Many2one('mail.group', string='Group', required=True, ondelete='cascade')
partner_id = fields.Many2one('res.partner', 'Partner', ondelete='cascade')
_sql_constraints = [(
'unique_partner',
'UNIQUE(partner_id, mail_group_id)',
'This partner is already subscribed to the group',
)]
@api.depends('partner_id.email')
def _compute_email(self):
for member in self:
if member.partner_id:
member.email = member.partner_id.email
elif not member.email:
member.email = False
@api.depends('email')
def _compute_email_normalized(self):
for moderation in self:
moderation.email_normalized = email_normalize(moderation.email)
| 35
| 1,470
|
31,587
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import lxml
from ast import literal_eval
from datetime import datetime
from dateutil import relativedelta
from werkzeug import urls
from odoo import _, api, fields, models, tools
from odoo.addons.http_routing.models.ir_http import slug
from odoo.exceptions import ValidationError, UserError
from odoo.osv import expression
from odoo.tools import email_normalize, hmac, generate_tracking_message_id
_logger = logging.getLogger(__name__)
# TODO remove me master
GROUP_SEND_BATCH_SIZE = 500
class MailGroup(models.Model):
"""This model represents a mailing list.
Users send emails to an alias to create new group messages or reply to existing
group messages. Moderation can be activated on groups. In that case email have to
be validated or rejected.
"""
_name = 'mail.group'
_description = 'Mail Group'
# TDE CHECK: use blaclist mixin
_inherit = ['mail.alias.mixin']
_order = 'create_date DESC, id DESC'
@api.model
def default_get(self, fields):
res = super(MailGroup, self).default_get(fields)
if not res.get('alias_contact') and (not fields or 'alias_contact' in fields):
res['alias_contact'] = 'everyone' if res.get('access_mode') == 'public' else 'followers'
return res
active = fields.Boolean('Active', default=True)
name = fields.Char('Name', required=True, translate=True)
alias_name = fields.Char('Alias Name', copy=False, related='alias_id.alias_name', readonly=False)
alias_fullname = fields.Char('Alias Full Name', compute='_compute_alias_fullname')
description = fields.Text('Description')
image_128 = fields.Image('Image', max_width=128, max_height=128)
# Messages
mail_group_message_ids = fields.One2many('mail.group.message', 'mail_group_id', string='Pending Messages')
mail_group_message_last_month_count = fields.Integer('Messages Per Month', compute='_compute_mail_group_message_last_month_count')
mail_group_message_count = fields.Integer('Messages Count', help='Number of message in this group', compute='_compute_mail_group_message_count')
mail_group_message_moderation_count = fields.Integer('Pending Messages Count', help='Messages that need an action', compute='_compute_mail_group_message_moderation_count')
# Members
is_member = fields.Boolean('Is Member', compute='_compute_is_member')
member_ids = fields.One2many('mail.group.member', 'mail_group_id', string='Members')
member_partner_ids = fields.Many2many('res.partner', string='Partners Member', compute='_compute_member_partner_ids', search='_search_member_partner_ids')
member_count = fields.Integer('Members Count', compute='_compute_member_count')
# Moderation
is_moderator = fields.Boolean(string='Moderator', help='Current user is a moderator of the group', compute='_compute_is_moderator')
moderation = fields.Boolean(string='Moderate this group')
moderation_rule_count = fields.Integer(string='Moderated emails count', compute='_compute_moderation_rule_count')
moderation_rule_ids = fields.One2many('mail.group.moderation', 'mail_group_id', string='Moderated Emails')
moderator_ids = fields.Many2many('res.users', 'mail_group_moderator_rel', string='Moderators',
domain=lambda self: [('groups_id', 'in', self.env.ref('base.group_user').id)])
moderation_notify = fields.Boolean(
string='Automatic notification',
help='People receive an automatic notification about their message being waiting for moderation.')
moderation_notify_msg = fields.Html(string='Notification message')
moderation_guidelines = fields.Boolean(
string='Send guidelines to new subscribers',
help='Newcomers on this moderated group will automatically receive the guidelines.')
moderation_guidelines_msg = fields.Html(string='Guidelines')
# ACLs
access_mode = fields.Selection([
('public', 'Everyone'),
('members', 'Members only'),
('groups', 'Selected group of users'),
], string='Privacy', required=True, default='public')
access_group_id = fields.Many2one('res.groups', string='Authorized Group',
default=lambda self: self.env.ref('base.group_user'))
# UI
can_manage_group = fields.Boolean('Can Manage', help='Can manage the members', compute='_compute_can_manage_group')
@api.depends('alias_name', 'alias_domain')
def _compute_alias_fullname(self):
for group in self:
if group.alias_name and group.alias_domain:
group.alias_fullname = f'{group.alias_name}@{group.alias_domain}'
else:
group.alias_fullname = group.alias_name
@api.depends('mail_group_message_ids.create_date', 'mail_group_message_ids.moderation_status')
def _compute_mail_group_message_last_month_count(self):
month_date = datetime.today() - relativedelta.relativedelta(months=1)
messages_data = self.env['mail.group.message'].read_group([
('mail_group_id', 'in', self.ids),
('create_date', '>=', fields.Datetime.to_string(month_date)),
('moderation_status', '=', 'accepted'),
], ['mail_group_id'], ['mail_group_id'])
# { mail_discusison_id: number_of_mail_group_message_last_month_count }
messages_data = {
message['mail_group_id'][0]: message['mail_group_id_count']
for message in messages_data
}
for group in self:
group.mail_group_message_last_month_count = messages_data.get(group.id, 0)
@api.depends('mail_group_message_ids')
def _compute_mail_group_message_count(self):
if not self:
self.mail_group_message_count = 0
return
results = self.env['mail.group.message'].read_group(
[('mail_group_id', 'in', self.ids)],
['mail_group_id'],
['mail_group_id'],
)
result_per_group = {
result['mail_group_id'][0]: result['mail_group_id_count']
for result in results
}
for group in self:
group.mail_group_message_count = result_per_group.get(group.id, 0)
@api.depends('mail_group_message_ids.moderation_status')
def _compute_mail_group_message_moderation_count(self):
results = self.env['mail.group.message'].read_group(
[('mail_group_id', 'in', self.ids), ('moderation_status', '=', 'pending_moderation')],
['mail_group_id'],
['mail_group_id'],
)
result_per_group = {
result['mail_group_id'][0]: result['mail_group_id_count']
for result in results
}
for group in self:
group.mail_group_message_moderation_count = result_per_group.get(group.id, 0)
@api.depends('member_ids')
def _compute_member_count(self):
for group in self:
group.member_count = len(group.member_ids)
@api.depends_context('uid')
def _compute_is_member(self):
if not self or self.env.user._is_public():
self.is_member = False
return
# SUDO to bypass the ACL rules
members = self.env['mail.group.member'].sudo().search([
('partner_id', '=', self.env.user.partner_id.id),
('mail_group_id', 'in', self.ids),
])
is_member = {member.mail_group_id.id: True for member in members}
for group in self:
group.is_member = is_member.get(group.id, False)
@api.depends('member_ids')
def _compute_member_partner_ids(self):
for group in self:
group.member_partner_ids = group.member_ids.partner_id
def _search_member_partner_ids(self, operator, operand):
return [(
'member_ids',
'in',
self.env['mail.group.member'].sudo()._search([
('partner_id', operator, operand)
])
)]
@api.depends('moderator_ids')
@api.depends_context('uid')
def _compute_is_moderator(self):
for group in self:
group.is_moderator = self.env.user.id in group.moderator_ids.ids
@api.depends('moderation_rule_ids')
def _compute_moderation_rule_count(self):
for group in self:
group.moderation_rule_count = len(group.moderation_rule_ids)
@api.depends('is_moderator')
@api.depends_context('uid')
def _compute_can_manage_group(self):
is_admin = self.env.user.has_group('mail_group.group_mail_group_manager') or self.env.su
for group in self:
group.can_manage_group = is_admin or group.is_moderator
@api.onchange('access_mode')
def _onchange_access_mode(self):
if self.access_mode == 'public':
self.alias_contact = 'everyone'
else:
self.alias_contact = 'followers'
@api.onchange('moderation')
def _onchange_moderation(self):
if self.moderation and self.env.user not in self.moderator_ids:
self.moderator_ids |= self.env.user
# CONSTRAINTS
@api.constrains('moderator_ids')
def _check_moderator_email(self):
if any(not moderator.email for group in self for moderator in group.moderator_ids):
raise ValidationError(_('Moderators must have an email address.'))
@api.constrains('moderation_notify', 'moderation_notify_msg')
def _check_moderation_notify(self):
if any(group.moderation_notify and not group.moderation_notify_msg for group in self):
raise ValidationError(_('The notification message is missing.'))
@api.constrains('moderation_guidelines', 'moderation_guidelines_msg')
def _check_moderation_guidelines(self):
if any(group.moderation_guidelines and not group.moderation_guidelines_msg for group in self):
raise ValidationError(_('The guidelines description is missing.'))
@api.constrains('moderator_ids', 'moderation')
def _check_moderator_existence(self):
if any(not group.moderator_ids for group in self if group.moderation):
raise ValidationError(_('Moderated group must have moderators.'))
@api.constrains('access_mode', 'access_group_id')
def _check_access_mode(self):
if any(group.access_mode == 'groups' and not group.access_group_id for group in self):
raise ValidationError(_('The "Authorized Group" is missing.'))
def _alias_get_creation_values(self):
"""Return the default values for the automatically created alias."""
values = super(MailGroup, self)._alias_get_creation_values()
values['alias_model_id'] = self.env['ir.model']._get('mail.group').id
values['alias_force_thread_id'] = self.id
values['alias_defaults'] = literal_eval(self.alias_defaults or '{}')
return values
# ------------------------------------------------------------
# MAILING
# ------------------------------------------------------------
def _alias_get_error_message(self, message, message_dict, alias):
self.ensure_one()
if alias.alias_contact == 'followers':
# Members only
if not self._find_member(message_dict.get('email_from')):
return _('Only members can send email to the mailing list.')
# Skip the verification because the partner is in the member list
return
return super(MailGroup, self)._alias_get_error_message(message, message_dict, alias)
@api.model
def message_new(self, msg_dict, custom_values=None):
"""Add the method to make the mail gateway flow work with this model."""
return
@api.model
def message_update(self, msg_dict, update_vals=None):
"""Add the method to make the mail gateway flow work with this model."""
return
@api.returns('mail.message', lambda value: value.id)
def message_post(self, body='', subject=None, email_from=None, author_id=None, **kwargs):
""" Custom posting process. This model does not inherit from ``mail.thread``
but uses the mail gateway so few methods should be defined.
This custom posting process works as follow
* create a ``mail.message`` based on incoming email;
* create linked ``mail.group.message`` that encapsulates message in a
format used in mail groups;
* apply moderation rules;
:return message: newly-created mail.message
"""
self.ensure_one()
# First create the <mail.message>
Mailthread = self.env['mail.thread']
values = dict((key, val) for key, val in kwargs.items() if key in self.env['mail.message']._fields)
author_id, email_from = Mailthread._message_compute_author(author_id, email_from, raise_exception=True)
values.update({
'author_id': author_id,
'body': self._clean_email_body(body),
'email_from': email_from,
'model': self._name,
'partner_ids': [],
'res_id': self.id,
'subject': subject,
})
# Force the "reply-to" to make the mail group flow work
values['reply_to'] = self.env['mail.message']._get_reply_to(values)
# ensure message ID so that replies go to the right thread
if not values.get('message_id'):
values['message_id'] = generate_tracking_message_id('%s-mail.group' % self.id)
attachments = kwargs.get('attachments') or []
attachment_ids = kwargs.get('attachment_ids') or []
attachement_values = Mailthread._message_post_process_attachments(attachments, attachment_ids, values)
values.update(attachement_values)
mail_message = Mailthread._message_create(values)
# Find the <mail.group.message> parent
group_message_parent_id = False
if mail_message.parent_id:
group_message_parent = self.env['mail.group.message'].search(
[('mail_message_id', '=', mail_message.parent_id.id)])
group_message_parent_id = group_message_parent.id if group_message_parent else False
moderation_status = 'pending_moderation' if self.moderation else 'accepted'
# Create the group message associated
group_message = self.env['mail.group.message'].create({
'mail_group_id': self.id,
'mail_message_id': mail_message.id,
'moderation_status': moderation_status,
'group_message_parent_id': group_message_parent_id,
})
# Check the moderation rule to determine if we should accept or reject the email
email_normalized = email_normalize(email_from)
moderation_rule = self.env['mail.group.moderation'].search([
('mail_group_id', '=', self.id),
('email', '=', email_normalized),
], limit=1)
if not self.moderation:
self._notify_members(group_message)
elif moderation_rule and moderation_rule.status == 'allow':
group_message.action_moderate_accept()
elif moderation_rule and moderation_rule.status == 'ban':
group_message.action_moderate_reject()
elif self.moderation_notify:
self.env['mail.mail'].sudo().create({
'author_id': self.env.user.partner_id.id,
'auto_delete': True,
'body_html': group_message.mail_group_id.moderation_notify_msg,
'email_from': self.env.user.company_id.catchall_formatted or self.env.user.company_id.email_formatted,
'email_to': email_from,
'subject': 'Re: %s' % (subject or ''),
'state': 'outgoing'
})
return mail_message
def action_send_guidelines(self, members=None):
""" Send guidelines to given members. """
self.ensure_one()
if not self.env.is_admin() and not self.is_moderator:
raise UserError(_('Only an administrator or a moderator can send guidelines to group members.'))
if not self.moderation_guidelines_msg:
raise UserError(_('The guidelines description is empty.'))
template = self.env.ref('mail_group.mail_template_guidelines', raise_if_not_found=False)
if not template:
raise UserError(_('Template "mail_group.mail_template_guidelines" was not found. No email has been sent. Please contact an administrator to fix this issue.'))
banned_emails = self.env['mail.group.moderation'].sudo().search([
('status', '=', 'ban'),
('mail_group_id', '=', self.id),
]).mapped('email')
if members is None:
members = self.member_ids
members = members.filtered(lambda member: member.email_normalized not in banned_emails)
for member in members:
company = member.partner_id.company_id or self.env.company
template.send_mail(
member.id,
email_values={
'author_id': self.env.user.partner_id.id,
'email_from': company.email_formatted or company.catchall_formatted,
'reply_to': company.email_formatted or company.catchall_formatted,
},
)
_logger.info('Send guidelines to %i members', len(members))
def _notify_members(self, message):
"""Send the given message to all members of the mail group (except the author)."""
self.ensure_one()
if message.mail_group_id != self:
raise UserError(_('The group of the message do not match.'))
if not message.mail_message_id.reply_to:
_logger.error('The alias or the catchall domain is missing, group might not work properly.')
base_url = self.get_base_url()
body = self.env['mail.render.mixin']._replace_local_links(message.body)
access_token = self._generate_group_access_token()
# Email added in a dict to be sure to send only once the email to each address
member_emails = {
email_normalize(member.email): member.email
for member in self.member_ids
}
batch_size = int(self.env['ir.config_parameter'].sudo().get_param('mail.session.batch.size', GROUP_SEND_BATCH_SIZE))
for batch_email_member in tools.split_every(batch_size, member_emails.items()):
mail_values = []
for email_member_normalized, email_member in batch_email_member:
if email_member_normalized == message.email_from_normalized:
# Do not send the email to his author
continue
# SMTP headers related to the subscription
email_url_encoded = urls.url_quote(email_member)
headers = {
** self._notify_email_header_dict(),
'List-Archive': f'<{base_url}/groups/{slug(self)}>',
'List-Subscribe': f'<{base_url}/groups?email={email_url_encoded}>',
'List-Unsubscribe': f'<{base_url}/groups?unsubscribe&email={email_url_encoded}>',
'Precedence': 'list',
'X-Auto-Response-Suppress': 'OOF', # avoid out-of-office replies from MS Exchange
}
if self.alias_name and self.alias_domain:
headers.update({
'List-Id': f'<{self.alias_name}.{self.alias_domain}>',
'List-Post': f'<mailto:{self.alias_name}@{self.alias_domain}>',
'X-Forge-To': f'"{self.name}" <{self.alias_name}@{self.alias_domain}>',
})
if message.mail_message_id.parent_id:
headers['In-Reply-To'] = message.mail_message_id.parent_id.message_id
# Add the footer (member specific) in the body
template_values = {
'mailto': f'{self.alias_name}@{self.alias_domain}',
'group_url': f'{base_url}/groups/{slug(self)}',
'unsub_label': f'{base_url}/groups?unsubscribe',
'unsub_url': f'{base_url}/groups?unsubscribe&group_id={self.id}&token={access_token}&email={email_url_encoded}',
}
template = self.env.ref('mail_group.mail_group_footer')
footer = template._render(template_values, engine='ir.qweb', minimal_qcontext=True)
member_body = tools.append_content_to_html(body, footer, plaintext=False)
mail_values.append({
'auto_delete': True,
'attachment_ids': message.attachment_ids.ids,
'body_html': member_body,
'email_from': message.email_from,
'email_to': email_member,
'headers': json.dumps(headers),
'mail_message_id': message.mail_message_id.id,
'message_id': message.mail_message_id.message_id,
'model': 'mail.group',
'reply_to': message.mail_message_id.reply_to,
'res_id': self.id,
'subject': message.subject,
})
if mail_values:
self.env['mail.mail'].sudo().create(mail_values)
@api.model
def _cron_notify_moderators(self):
moderated_groups = self.env['mail.group'].search([('moderation', '=', True)])
return moderated_groups._notify_moderators()
def _notify_moderators(self):
"""Push a notification (Inbox / Email) to the moderators whose an action is waiting."""
template = self.env.ref('mail_group.mail_group_notify_moderation', raise_if_not_found=False)
if not template:
_logger.warning('Template "mail_group.mail_group_notify_moderation" was not found. Cannot send reminder notifications.')
return
results = self.env['mail.group.message'].read_group(
[('mail_group_id', 'in', self.ids), ('moderation_status', '=', 'pending_moderation')],
['mail_group_id'],
['mail_group_id'],
)
groups = self.browse([result['mail_group_id'][0] for result in results])
for group in groups:
moderators_to_notify = group.moderator_ids
MailThread = self.env['mail.thread'].with_context(mail_notify_author=True)
for moderator in moderators_to_notify:
body = template._render({
'moderator': moderator,
'group': group,
}, engine='ir.qweb', minimal_qcontext=True)
email_from = moderator.company_id.catchall_formatted or moderator.company_id.email_formatted
MailThread.message_notify(
partner_ids=moderator.partner_id.ids,
subject=_('Messages are pending moderation'),
body=body,
email_from=email_from,
model='mail.group',
res_id=group.id,
)
@api.model
def _clean_email_body(self, body_html):
"""When we receive an email, we want to clean it before storing it in the database."""
tree = lxml.html.fromstring(body_html or '')
# Remove the mailing footer
xpath_footer = ".//div[contains(@id, 'o_mg_message_footer')]"
for parent_footer in tree.xpath(xpath_footer + "/.."):
for footer in parent_footer.xpath(xpath_footer):
parent_footer.remove(footer)
return lxml.etree.tostring(tree, encoding='utf-8').decode()
# ------------------------------------------------------------
# MEMBERSHIP
# ------------------------------------------------------------
def action_join(self):
self.check_access_rights('read')
self.check_access_rule('read')
partner = self.env.user.partner_id
self.sudo()._join_group(partner.email, partner.id)
_logger.info('"%s" (#%s) joined mail.group "%s" (#%s)', partner.name, partner.id, self.name, self.id)
def action_leave(self):
self.check_access_rights('read')
self.check_access_rule('read')
partner = self.env.user.partner_id
self.sudo()._leave_group(partner.email, partner.id)
_logger.info('"%s" (#%s) leaved mail.group "%s" (#%s)', partner.name, partner.id, self.name, self.id)
def _join_group(self, email, partner_id=None):
self.ensure_one()
if partner_id:
partner = self.env['res.partner'].browse(partner_id).exists()
if not partner:
raise ValidationError(_('The partner can not be found.'))
email = partner.email
existing_member = self._find_member(email, partner_id)
if existing_member:
# Update the information of the partner to force the synchronization
# If one the the value is not up to date (e.g. if our email is subscribed
# but our partner was not set)
existing_member.write({
'email': email,
'partner_id': partner_id,
})
return
member = self.env['mail.group.member'].create({
'partner_id': partner_id,
'email': email,
'mail_group_id': self.id,
})
if self.moderation_guidelines:
# Automatically send the guidelines to the new member
self.action_send_guidelines(member)
def _leave_group(self, email, partner_id=None, all_members=False):
"""Remove the given email / partner from the group.
If the "all_members" parameter is set to True, remove all members with the given
email address (multiple members might have the same email address).
Otherwise, remove the most appropriate.
"""
self.ensure_one()
if all_members and not partner_id:
self.env['mail.group.member'].search([
('mail_group_id', '=', self.id),
('email_normalized', '=', email_normalize(email)),
]).unlink()
else:
member = self._find_member(email, partner_id)
if member:
member.unlink()
def _send_subscribe_confirmation_email(self, email):
"""Send an email to the given address to subscribe / unsubscribe to the mailing list."""
self.ensure_one()
confirm_action_url = self._generate_action_url(email, 'subscribe')
template = self.env.ref('mail_group.mail_template_list_subscribe')
template.with_context(token_url=confirm_action_url).send_mail(
self.id,
force_send=True,
email_values={
'author_id': self.create_uid.partner_id.id,
'auto_delete': True,
'email_from': self.env.company.email_formatted,
'email_to': email,
'message_type': 'user_notification',
},
notif_layout='mail.mail_notification_light',
)
_logger.info('Subscription email sent to %s.', email)
def _send_unsubscribe_confirmation_email(self, email):
"""Send an email to the given address to subscribe / unsubscribe to the mailing list."""
self.ensure_one()
confirm_action_url = self._generate_action_url(email, 'unsubscribe')
template = self.env.ref('mail_group.mail_template_list_unsubscribe')
template.with_context(token_url=confirm_action_url).send_mail(
self.id,
force_send=True,
email_values={
'author_id': self.create_uid.partner_id.id,
'auto_delete': True,
'email_from': self.env.company.email_formatted,
'email_to': email,
'message_type': 'user_notification',
},
notif_layout='mail.mail_notification_light',
)
_logger.info('Unsubscription email sent to %s.', email)
def _generate_action_url(self, email, action):
"""Generate the confirmation URL to subscribe / unsubscribe from the mailing list."""
if action not in ['subscribe', 'unsubscribe']:
raise ValueError(_('Invalid action for URL generation (%s)', action))
self.ensure_one()
confirm_action_url = '/group/%s-confirm?%s' % (
action,
urls.url_encode({
'group_id': self.id,
'email': email,
'token': self._generate_action_token(email, action),
})
)
base_url = self.get_base_url()
confirm_action_url = urls.url_join(base_url, confirm_action_url)
return confirm_action_url
def _generate_action_token(self, email, action):
"""Generate an action token to be able to subscribe / unsubscribe from the mailing list."""
if action not in ['subscribe', 'unsubscribe']:
raise ValueError(_('Invalid action for URL generation (%s)', action))
self.ensure_one()
email_normalized = email_normalize(email)
if not email_normalized:
raise UserError(_('Email %s is invalid', email))
data = (self.id, email_normalized, action)
return hmac(self.env(su=True), 'mail_group-email-subscription', data)
def _generate_group_access_token(self):
"""Generate an action token to be able to subscribe / unsubscribe from the mailing list."""
self.ensure_one()
return hmac(self.env(su=True), 'mail_group-access-token-portal', self.id)
def _find_member(self, email, partner_id=None):
"""Return the <mail.group.member> corresponding to the given email address."""
self.ensure_one()
result = self._find_members(email, partner_id)
return result.get(self.id)
def _find_members(self, email, partner_id):
"""Get all the members record corresponding to the email / partner_id.
Can be called in batch and return a dictionary
{'group_id': <mail.group.member>}
Multiple members might have the same email address, but with different partner
because there's no unique constraint on the email field of the <res.partner>
model.
When a partner is given for the search, return in priority
- The member whose partner match the given partner
- The member without partner but whose email match the given email
When no partner is given for the search, return in priority
- A member whose email match the given email and has no partner
- A member whose email match the given email and has partner
"""
order = 'partner_id ASC'
if not email_normalize(email):
# empty email should match nobody
return {}
domain = [('email_normalized', '=', email_normalize(email))]
if partner_id:
domain = expression.OR([
expression.AND([
[('partner_id', '=', False)],
domain,
]),
[('partner_id', '=', partner_id)],
])
order = 'partner_id DESC'
domain = expression.AND([domain, [('mail_group_id', 'in', self.ids)]])
members_data = self.env['mail.group.member'].sudo().search(domain, order=order)
return {
member.mail_group_id.id: member
for member in members_data
}
| 44.177622
| 31,587
|
10,365
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import _, api, fields, models
from odoo.exceptions import AccessError, UserError
from odoo.osv import expression
from odoo.tools import email_normalize, append_content_to_html, ustr
_logger = logging.getLogger(__name__)
class MailGroupMessage(models.Model):
"""Emails belonging to a discussion group.
Those are build on <mail.message> with additional information related to specific
features of <mail.group> like better parent / children management and moderation.
"""
_name = 'mail.group.message'
_description = 'Mailing List Message'
_rec_name = 'subject'
_order = 'create_date DESC'
# <mail.message> fields, can not be done with inherits because it will impact
# the performance of the <mail.message> model (different cache, so the ORM will need
# to do one more SQL query to be able to update the <mail.group.message> cache)
attachment_ids = fields.Many2many(related='mail_message_id.attachment_ids', readonly=False)
author_id = fields.Many2one(related='mail_message_id.author_id', readonly=False)
email_from = fields.Char(related='mail_message_id.email_from', readonly=False)
email_from_normalized = fields.Char('Normalized From', compute='_compute_email_from_normalized', store=True)
body = fields.Html(related='mail_message_id.body', readonly=False)
subject = fields.Char(related='mail_message_id.subject', readonly=False)
# Thread
mail_group_id = fields.Many2one(
'mail.group', string='Group',
required=True, ondelete='cascade')
mail_message_id = fields.Many2one('mail.message', 'Mail Message', required=True, ondelete='cascade', index=True, copy=False)
# Parent and children
group_message_parent_id = fields.Many2one(
'mail.group.message', string='Parent', store=True)
group_message_child_ids = fields.One2many('mail.group.message', 'group_message_parent_id', string='Childs')
# Moderation
author_moderation = fields.Selection([('ban', 'Banned'), ('allow', 'Whitelisted')], string='Author Moderation Status',
compute='_compute_author_moderation')
is_group_moderated = fields.Boolean('Is Group Moderated', related='mail_group_id.moderation')
moderation_status = fields.Selection(
[('pending_moderation', 'Pending Moderation'),
('accepted', 'Accepted'),
('rejected', 'Rejected')],
string='Status', index=True, copy=False,
required=True, default='pending_moderation')
moderator_id = fields.Many2one('res.users', string='Moderated By')
@api.depends('email_from')
def _compute_email_from_normalized(self):
for message in self:
message.email_from_normalized = email_normalize(message.email_from)
@api.depends('email_from_normalized', 'mail_group_id')
def _compute_author_moderation(self):
moderations = self.env['mail.group.moderation'].search([
('mail_group_id', 'in', self.mail_group_id.ids),
])
all_emails = set(self.mapped('email_from_normalized'))
moderations = {
(moderation.mail_group_id, moderation.email): moderation.status
for moderation in moderations
if moderation.email in all_emails
}
for message in self:
message.author_moderation = moderations.get((message.mail_group_id, message.email_from_normalized), False)
@api.constrains('mail_message_id')
def _constrains_mail_message_id(self):
for message in self:
if message.mail_message_id.model != 'mail.group':
raise AccessError(_(
'Group message can only be linked to mail group. Current model is %s.',
message.mail_message_id.model,
))
if message.mail_message_id.res_id != message.mail_group_id.id:
raise AccessError(_('The record of the message should be the group.'))
@api.model_create_multi
def create(self, values_list):
for vals in values_list:
if not vals.get('mail_message_id'):
vals.update({
'res_id': vals.get('mail_group_id'),
'model': 'mail.group',
})
vals['mail_message_id'] = self.env['mail.message'].sudo().create({
field: vals.pop(field)
for field in self.env['mail.message']._fields
if field in vals
}).id
return super(MailGroupMessage, self).create(values_list)
def copy(self, default=None):
default = dict(default or {})
default['mail_message_id'] = self.mail_message_id.copy().id
return super(MailGroupMessage, self).copy(default)
# --------------------------------------------------
# MODERATION API
# --------------------------------------------------
def action_moderate_accept(self):
"""Accept the incoming email.
Will send the incoming email to all members of the group.
"""
self._assert_moderable()
self.write({
'moderation_status': 'accepted',
'moderator_id': self.env.uid,
})
# Send the email to the members of the group
for message in self:
message.mail_group_id._notify_members(message)
def action_moderate_reject_with_comment(self, reject_subject, reject_comment):
self._assert_moderable()
if reject_subject or reject_comment:
self._moderate_send_reject_email(reject_subject, reject_comment)
self.action_moderate_reject()
def action_moderate_reject(self):
self._assert_moderable()
self.write({
'moderation_status': 'rejected',
'moderator_id': self.env.uid,
})
def action_moderate_allow(self):
self._create_moderation_rule('allow')
# Accept all emails of the same authors
same_author = self._get_pending_same_author_same_group()
same_author.action_moderate_accept()
def action_moderate_ban(self):
self._create_moderation_rule('ban')
# Reject all emails of the same author
same_author = self._get_pending_same_author_same_group()
same_author.action_moderate_reject()
def action_moderate_ban_with_comment(self, ban_subject, ban_comment):
self._create_moderation_rule('ban')
if ban_subject or ban_comment:
self._moderate_send_reject_email(ban_subject, ban_comment)
# Reject all emails of the same author
same_author = self._get_pending_same_author_same_group()
same_author.action_moderate_reject()
def _get_pending_same_author_same_group(self):
"""Return the pending messages of the same authors in the same groups."""
return self.search(
expression.AND([
expression.OR([
[
('mail_group_id', '=', message.mail_group_id.id),
('email_from_normalized', '=', message.email_from_normalized),
] for message in self
]),
[('moderation_status', '=', 'pending_moderation')],
])
)
def _create_moderation_rule(self, status):
"""Create a moderation rule <mail.group.moderation> with the given status.
Update existing moderation rule for the same email address if found,
otherwise create a new rule.
"""
if status not in ('ban', 'allow'):
raise ValueError(_('Wrong status (%s)', status))
for message in self:
if not email_normalize(message.email_from):
raise UserError(_('The email "%s" is not valid.', message.email_from))
existing_moderation = self.env['mail.group.moderation'].search(
expression.OR([
[
('email', '=', email_normalize(message.email_from)),
('mail_group_id', '=', message.mail_group_id.id)
] for message in self
])
)
existing_moderation.status = status
# Add the value in a set to create only 1 moderation rule per (email_normalized, group)
moderation_to_create = {
(email_normalize(message.email_from), message.mail_group_id.id)
for message in self
if email_normalize(message.email_from) not in existing_moderation.mapped('email')
}
self.env['mail.group.moderation'].create([
{
'email': email,
'mail_group_id': mail_group_id,
'status': status,
} for email, mail_group_id in moderation_to_create])
def _assert_moderable(self):
"""Raise an error if one of the current message can not be moderated.
A <mail.group.message> can only be moderated
if it's moderation status is "pending_moderation".
"""
non_moderable_messages = self.filtered_domain([
('moderation_status', '!=', 'pending_moderation'),
])
if non_moderable_messages:
if len(self) == 1:
raise UserError(_('This message can not be moderated'))
raise UserError(_(
'Those messages can not be moderated: %s.',
', '.join(non_moderable_messages.mapped('subject')),
))
def _moderate_send_reject_email(self, subject, comment):
for message in self:
if not message.email_from:
continue
body_html = append_content_to_html('<div>%s</div>' % ustr(comment), message.body, plaintext=False)
body_html = self.env['mail.render.mixin']._replace_local_links(body_html)
self.env['mail.mail'].sudo().create({
'author_id': self.env.user.partner_id.id,
'auto_delete': True,
'body_html': body_html,
'email_from': self.env.user.email_formatted or self.env.company.catchall_formatted,
'email_to': message.email_from,
'references': message.mail_message_id.message_id,
'subject': subject,
'state': 'outgoing',
})
| 42.306122
| 10,365
|
1,663
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
from odoo.exceptions import UserError
from odoo.tools import email_normalize
class MailGroupModeration(models.Model):
"""Represent the moderation rules for an email address in a group."""
_name = 'mail.group.moderation'
_description = 'Mailing List black/white list'
email = fields.Char(string='Email', required=True)
status = fields.Selection(
[('allow', 'Always Allow'), ('ban', 'Permanent Ban')],
string='Status', required=True, default='ban')
mail_group_id = fields.Many2one('mail.group', string='Group', required=True, ondelete='cascade')
_sql_constraints = [(
'mail_group_email_uniq',
'UNIQUE(mail_group_id, email)',
'You can create only one rule for a given email address in a group.',
)]
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
email_normalized = email_normalize(values.get('email'))
if not email_normalized:
raise UserError(_('Invalid email address %r', values.get('email')))
values['email'] = email_normalized
return super(MailGroupModeration, self).create(vals_list)
def write(self, values):
if 'email' in values:
email_normalized = email_normalize(values['email'])
if not email_normalized:
raise UserError(_('Invalid email address %r', values.get('email')))
values['email'] = email_normalized
return super(MailGroupModeration, self).write(values)
| 40.560976
| 1,663
|
15,034
|
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, fields, tools
from odoo.addons.http_routing.models.ir_http import slug
from odoo.addons.portal.controllers.portal import pager as portal_pager
from odoo.exceptions import AccessError
from odoo.http import request
from odoo.osv import expression
class PortalMailGroup(http.Controller):
_thread_per_page = 20
_replies_per_page = 5
def _get_website_domain(self):
# Base group domain in addition to the security access rules
# Do not show rejected message on the portal view even for admin
return [('moderation_status', '!=', 'rejected')]
def _get_archives(self, group_id):
"""Return the different date range and message count for the group messages."""
domain = expression.AND([self._get_website_domain(), [('mail_group_id', '=', group_id)]])
results = request.env['mail.group.message']._read_group_raw(
domain,
['subject', 'create_date'],
groupby=['create_date'], orderby='create_date')
date_groups = []
for result in results:
(dates_range, label) = result['create_date']
start, end = dates_range.split('/')
date_groups.append({
'date': label,
'date_begin': fields.Date.to_string(fields.Date.to_date(start)),
'date_end': fields.Date.to_string(fields.Date.to_date(end)),
'messages_count': result['create_date_count'],
})
thread_domain = expression.AND([domain, [('group_message_parent_id', '=', False)]])
threads_count = request.env['mail.group.message'].search_count(thread_domain)
return {
'threads_count': threads_count,
'threads_time_data': date_groups,
}
# ------------------------------------------------------------
# MAIN PAGE
# ------------------------------------------------------------
@http.route('/groups', type='http', auth='public', sitemap=True, website=True)
def groups_index(self, email='', **kw):
"""View of the group lists. Allow the users to subscribe and unsubscribe."""
if kw.get('group_id') and kw.get('token'):
group_id = int(kw.get('group_id'))
token = kw.get('token')
group = request.env['mail.group'].browse(group_id).exists().sudo()
if not group:
raise werkzeug.exceptions.NotFound()
if token != group._generate_group_access_token():
raise werkzeug.exceptions.NotFound()
mail_groups = group
else:
mail_groups = request.env['mail.group'].search([]).sudo()
if not request.env.user._is_public():
# Force the email if the user is logged
email_normalized = request.env.user.email_normalized
partner_id = request.env.user.partner_id.id
else:
email_normalized = tools.email_normalize(email)
partner_id = None
members_data = mail_groups._find_members(email_normalized, partner_id)
return request.render('mail_group.mail_groups', {
'mail_groups': [{
'group': group,
'is_member': bool(members_data.get(group.id, False)),
} for group in mail_groups],
'email': email_normalized,
'is_mail_group_manager': request.env.user.has_group('mail_group.group_mail_group_manager'),
})
# ------------------------------------------------------------
# THREAD DISPLAY / MANAGEMENT
# ------------------------------------------------------------
@http.route([
'/groups/<model("mail.group"):group>',
'/groups/<model("mail.group"):group>/page/<int:page>',
], type='http', auth='public', sitemap=True, website=True)
def group_view_messages(self, group, page=1, mode='thread', date_begin=None, date_end=None, **post):
GroupMessage = request.env['mail.group.message']
domain = expression.AND([self._get_website_domain(), [('mail_group_id', '=', group.id)]])
if mode == 'thread':
domain = expression.AND([domain, [('group_message_parent_id', '=', False)]])
if date_begin and date_end:
domain = expression.AND([domain, [('create_date', '>', date_begin), ('create_date', '<=', date_end)]])
# SUDO after the search to apply access rules but be able to read attachments
messages_sudo = GroupMessage.search(
domain, limit=self._thread_per_page,
offset=(page - 1) * self._thread_per_page).sudo()
pager = portal_pager(
url=f'/groups/{slug(group)}',
total=GroupMessage.search_count(domain),
page=page,
step=self._thread_per_page,
scope=5,
url_args={'date_begin': date_begin, 'date_end': date_end, 'mode': mode}
)
self._generate_attachments_access_token(messages_sudo)
return request.render('mail_group.group_messages', {
'page_name': 'groups',
'group': group,
'messages': messages_sudo,
'archives': self._get_archives(group.id),
'date_begin': date_begin,
'date_end': date_end,
'pager': pager,
'replies_per_page': self._replies_per_page,
'mode': mode,
})
@http.route('/groups/<model("mail.group"):group>/<model("mail.group.message"):message>',
type='http', auth='public', sitemap=True, website=True)
def group_view_message(self, group, message, mode='thread', date_begin=None, date_end=None, **post):
if group != message.mail_group_id:
raise werkzeug.exceptions.NotFound()
GroupMessage = request.env['mail.group.message']
base_domain = expression.AND([
self._get_website_domain(),
[('mail_group_id', '=', group.id),
('group_message_parent_id', '=', message.group_message_parent_id.id)],
])
next_message = GroupMessage.search(
expression.AND([base_domain, [('id', '>', message.id)]]),
order='id ASC', limit=1)
prev_message = GroupMessage.search(
expression.AND([base_domain, [('id', '<', message.id)]]),
order='id DESC', limit=1)
message_sudo = message.sudo()
self._generate_attachments_access_token(message_sudo)
values = {
'page_name': 'groups',
'message': message_sudo,
'group': group,
'mode': mode,
'archives': self._get_archives(group.id),
'date_begin': date_begin,
'date_end': date_end,
'replies_per_page': self._replies_per_page,
'next_message': next_message,
'prev_message': prev_message,
}
return request.render('mail_group.group_message', values)
@http.route('/groups/<model("mail.group"):group>/<model("mail.group.message"):message>/get_replies',
type='json', auth='public', methods=['POST'], website=True)
def group_message_get_replies(self, group, message, last_displayed_id, **post):
if group != message.mail_group_id:
raise werkzeug.exceptions.NotFound()
replies_domain = expression.AND([
self._get_website_domain(),
[('id', '>', int(last_displayed_id)), ('group_message_parent_id', '=', message.id)],
])
# SUDO after the search to apply access rules but be able to read attachments
replies_sudo = request.env['mail.group.message'].search(replies_domain, limit=self._replies_per_page).sudo()
message_count = request.env['mail.group.message'].search_count(replies_domain)
if not replies_sudo:
return
message_sudo = message.sudo()
self._generate_attachments_access_token(message_sudo | replies_sudo)
values = {
'group': group,
'parent_message': message_sudo,
'messages': replies_sudo,
'msg_more_count': message_count - self._replies_per_page,
'replies_per_page': self._replies_per_page,
}
return request.env.ref('mail_group.messages_short')._render(values, engine='ir.qweb')
# ------------------------------------------------------------
# SUBSCRIPTION
# ------------------------------------------------------------
@http.route('/group/subscribe', type='json', auth='public', website=True)
def group_subscribe(self, group_id=0, email=None, token=None, **kw):
"""Subscribe the current logged user or the given email address to the mailing list.
If the user is logged, the action is automatically done.
But if the user is not logged (public user) an email will be send with a token
to confirm the action.
:param group_id: Id of the group
:param email: Email to add in the member list
:param token: An access token to bypass the <mail.group> access rule
:return:
'added'
if the member was added in the mailing list
'email_sent'
if we send a confirmation email
'is_already_member'
if we try to subscribe but we are already member
"""
group_sudo, is_member, partner_id = self._group_subscription_get_group(group_id, email, token)
if is_member:
return 'is_already_member'
if not request.env.user._is_public():
# For logged user, automatically join / leave without sending a confirmation email
group_sudo._join_group(request.env.user.email, partner_id)
return 'added'
# For non-logged user, send an email with a token to confirm the action
group_sudo._send_subscribe_confirmation_email(email)
return 'email_sent'
@http.route('/group/unsubscribe', type='json', auth='public', website=True)
def group_unsubscribe(self, group_id=0, email=None, token=None, **kw):
"""Unsubscribe the current logged user or the given email address to the mailing list.
If the user is logged, the action is automatically done.
But if the user is not logged (public user) an email will be send with a token
to confirm the action.
:param group_id: Id of the group
:param email: Email to add in the member list
:param token: An access token to bypass the <mail.group> access rule
:return:
'removed'
if the member was removed from the mailing list
'email_sent'
if we send a confirmation email
'is_not_member'
if we try to unsubscribe but we are not member
"""
group_sudo, is_member, partner_id = self._group_subscription_get_group(group_id, email, token)
if not is_member:
return 'is_not_member'
if not request.env.user._is_public():
# For logged user, automatically join / leave without sending a confirmation email
group_sudo._leave_group(request.env.user.email, partner_id)
return 'removed'
# For non-logged user, send an email with a token to confirm the action
group_sudo._send_unsubscribe_confirmation_email(email)
return 'email_sent'
def _group_subscription_get_group(self, group_id, email, token):
"""Check the given token and return,
:return:
- The group sudo-ed
- True if the email is member of the group
- The partner of the current user
:raise NotFound: if the given token is not valid
"""
group = request.env['mail.group'].browse(int(group_id)).exists()
if not group:
raise werkzeug.exceptions.NotFound()
# SUDO to have access to field of the many2one
group_sudo = group.sudo()
if token and token != group_sudo._generate_group_access_token():
raise werkzeug.exceptions.NotFound()
elif not token:
try:
# Check that the current user has access to the group
group.check_access_rights('read')
group.check_access_rule('read')
except AccessError:
raise werkzeug.exceptions.NotFound()
partner_id = None
if not request.env.user._is_public():
partner_id = request.env.user.partner_id.id
is_member = bool(group_sudo._find_member(email, partner_id))
return group_sudo, is_member, partner_id
@http.route('/group/subscribe-confirm', type='http', auth='public', website=True)
def group_subscribe_confirm(self, group_id, email, token, **kw):
"""Confirm the subscribe / unsubscribe action which was sent by email."""
group = self._group_subscription_confirm_get_group(group_id, email, token, 'subscribe')
if not group:
return request.render('mail_group.invalid_token_subscription')
partners = request.env['mail.thread'].sudo()._mail_find_partner_from_emails([email])
partner_id = partners[0].id if partners else None
group._join_group(email, partner_id)
return request.render('mail_group.confirmation_subscription', {
'group': group,
'email': email,
'subscribing': True,
})
@http.route('/group/unsubscribe-confirm', type='http', auth='public', website=True)
def group_unsubscribe_confirm(self, group_id, email, token, **kw):
"""Confirm the subscribe / unsubscribe action which was sent by email."""
group = self._group_subscription_confirm_get_group(group_id, email, token, 'unsubscribe')
if not group:
return request.render('mail_group.invalid_token_subscription')
group._leave_group(email, all_members=True)
return request.render('mail_group.confirmation_subscription', {
'group': group,
'email': email,
'subscribing': False,
})
def _group_subscription_confirm_get_group(self, group_id, email, token, action):
"""Retrieve the group and check the token use to perform the given action."""
if not group_id or not email or not token:
return False
# Here we can SUDO because the token will be checked
group = request.env['mail.group'].browse(int(group_id)).exists().sudo()
if not group:
raise werkzeug.exceptions.NotFound()
excepted_token = group._generate_action_token(email, action)
return group if token == excepted_token else False
def _generate_attachments_access_token(self, messages):
for message in messages:
if message.attachment_ids:
message.attachment_ids.generate_access_token()
self._generate_attachments_access_token(message.group_message_child_ids)
| 41.645429
| 15,034
|
949
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'In-App Purchases',
'category': 'Hidden/Tools',
'version': '1.1',
'summary': 'Basic models and helpers to support In-App purchases.',
'description': """
This module provides standard tools (account model, context manager and helpers)
to support In-App purchases inside Odoo. """,
'depends': [
'web',
'base_setup'
],
'data': [
'security/ir.model.access.csv',
'security/ir_rule.xml',
'views/iap_views.xml',
'views/res_config_settings.xml',
],
'auto_install': True,
'assets': {
'web.assets_backend': [
'iap/static/src/js/**/*',
],
'web.tests_assets': [
'iap/static/tests/**/*',
],
'web.assets_qweb': [
'iap/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 27.114286
| 949
|
9,488
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import contextlib
import logging
import json
import requests
import uuid
from unittest.mock import patch
from odoo import exceptions, _
from odoo.tests.common import BaseCase
from odoo.tools import pycompat
_logger = logging.getLogger(__name__)
DEFAULT_ENDPOINT = 'https://iap.odoo.com'
# We need to mock iap_jsonrpc during tests as we don't want to perform real calls to RPC endpoints
def iap_jsonrpc_mocked(*args, **kwargs):
raise exceptions.AccessError("Unavailable during tests.")
iap_patch = patch('odoo.addons.iap.tools.iap_tools.iap_jsonrpc', iap_jsonrpc_mocked)
def setUp(self):
old_setup_func(self)
iap_patch.start()
self.addCleanup(iap_patch.stop)
old_setup_func = BaseCase.setUp
BaseCase.setUp = setUp
#----------------------------------------------------------
# Tools globals
#----------------------------------------------------------
_MAIL_DOMAIN_BLACKLIST = set([
# Top 100 email providers on SaaS at 2020-10
'gmail.com', 'hotmail.com', 'yahoo.com', 'qq.com', 'outlook.com', '163.com', 'yahoo.fr', 'live.com', 'hotmail.fr', 'icloud.com', '126.com',
'me.com', 'free.fr', 'ymail.com', 'msn.com', 'mail.com', 'orange.fr', 'aol.com', 'wanadoo.fr', 'live.fr', 'mail.ru', 'yahoo.co.in',
'rediffmail.com', 'hku.hk', 'googlemail.com', 'gmx.de', 'sina.com', 'skynet.be', 'laposte.net', 'yahoo.co.uk', 'yahoo.co.id', 'web.de',
'gmail.com ', 'outlook.fr', 'telenet.be', 'yahoo.es', 'naver.com', 'hotmail.co.uk', 'gmai.com', 'foxmail.com', 'hku.hku', 'bluewin.ch',
'sfr.fr', 'libero.it', 'mac.com', 'rocketmail.com', 'protonmail.com', 'gmx.com', 'gamil.com', 'hotmail.es', 'gmx.net', 'comcast.net',
'yahoo.com.mx', 'linkedin.com', 'yahoo.com.br', 'yahoo.in', 'yahoo.ca', 't-online.de', '139.com', 'yandex.ru', 'yahoo.com.hk','yahoo.de',
'yeah.net', 'yandex.com', 'nwytg.net', 'neuf.fr', 'yahoo.com.ar', 'outlook.es', 'abv.bg', 'aliyun.com', 'yahoo.com.tw', 'ukr.net', 'live.nl',
'wp.pl', 'hotmail.it', 'live.com.mx', 'zoho.com', 'live.co.uk', 'sohu.com', 'twoomail.com', 'yahoo.com.sg', 'odoo.com', 'yahoo.com.vn',
'windowslive.com', 'gmail', 'vols.utk.edu', 'email.com', 'tiscali.it', 'yahoo.it', 'gmx.ch', 'trbvm.com', 'nwytg.com', 'mvrht.com', 'nyit.edu',
'o2.pl', 'live.cn', 'gmial.com', 'seznam.cz', 'live.be', 'videotron.ca', 'gmil.com', 'live.ca', 'hotmail.de', 'sbcglobal.net', 'connect.hku.hk',
'yahoo.com.au', 'att.net', 'live.in', 'btinternet.com', 'gmx.fr', 'voila.fr', 'shaw.ca', 'prodigy.net.mx', 'vip.qq.com', 'yahoo.com.ph',
'bigpond.com', '7thcomputing.com', 'freenet.de', 'alice.it', 'esi.dz',
'bk.ru', 'mail.odoo.com', 'gmail.con', 'fiu.edu', 'gmal.com', 'useemlikefun.com', 'google.com', 'trbvn.com', 'yopmail.com', 'ya.ru',
'hotmail.co.th', 'arcor.de', 'hotmail.ca', '21cn.com', 'live.de', 'outlook.de', 'gmailcom', 'unal.edu.co', 'tom.com', 'yahoo.gr',
'gmx.at', 'inbox.lv', 'ziggo.nl', 'xs4all.nl', 'sapo.pt', 'live.com.au', 'nate.com', 'online.de', 'sina.cn', 'gmail.co', 'rogers.com',
'mailinator.com', 'cox.net', 'hotmail.be', 'verizon.net', 'yahoo.co.jp', 'usa.com', 'consultant.com', 'hotmai.com', '189.cn',
'sky.com', 'eezee-it.com', 'opayq.com', 'maildrop.cc', 'home.nl', 'virgilio.it', 'outlook.be', 'hanmail.net', 'uol.com.br', 'hec.ca',
'terra.com.br', 'inbox.ru', 'tin.it', 'list.ru', 'hotmail.com ', 'safecoms.com', 'smile.fr', 'sprintit.fi', 'uniminuto.edu.co',
'bol.com.br', 'bellsouth.net', 'nirmauni.ac.in', 'ldc.edu.in', 'ig.com.br', 'engineer.com', 'scarlet.be', 'inbox.com', 'gmaill.com',
'freemail.hu', 'live.it', 'blackwaretech.com', 'byom.de', 'dispostable.com', 'dayrep.com', 'aim.com', 'prixgen.com', 'gmail.om',
'asterisk-tech.mn', 'in.com', 'aliceadsl.fr', 'lycos.com', 'topnet.tn', 'teleworm.us', 'kedgebs.com', 'supinfo.com', 'posteo.de',
'yahoo.com ', 'op.pl', 'gmail.fr', 'grr.la', 'oci.fr', 'aselcis.com', 'optusnet.com.au', 'mailcatch.com', 'rambler.ru', 'protonmail.ch',
'prisme.ch', 'bbox.fr', 'orbitalu.com', 'netcourrier.com', 'iinet.net.au',
# Dummy entries
'example.com',
])
# List of country codes for which we should offer state filtering when mining new leads.
# See crm.iap.lead.mining.request#_compute_available_state_ids() or task-2471703 for more details.
_STATES_FILTER_COUNTRIES_WHITELIST = set([
'AR', 'AU', 'BR', 'CA', 'IN', 'MY', 'MX', 'NZ', 'AE', 'US'
])
#----------------------------------------------------------
# Helpers for both clients and proxy
#----------------------------------------------------------
def iap_get_endpoint(env):
url = env['ir.config_parameter'].sudo().get_param('iap.endpoint', DEFAULT_ENDPOINT)
return url
#----------------------------------------------------------
# Helpers for clients
#----------------------------------------------------------
class InsufficientCreditError(Exception):
pass
def iap_jsonrpc(url, method='call', params=None, timeout=15):
"""
Calls the provided JSON-RPC endpoint, unwraps the result and
returns JSON-RPC errors as exceptions.
"""
payload = {
'jsonrpc': '2.0',
'method': method,
'params': params,
'id': uuid.uuid4().hex,
}
_logger.info('iap jsonrpc %s', url)
try:
req = requests.post(url, json=payload, timeout=timeout)
req.raise_for_status()
response = req.json()
if 'error' in response:
name = response['error']['data'].get('name').rpartition('.')[-1]
message = response['error']['data'].get('message')
if name == 'InsufficientCreditError':
e_class = InsufficientCreditError
elif name == 'AccessError':
e_class = exceptions.AccessError
elif name == 'UserError':
e_class = exceptions.UserError
else:
raise requests.exceptions.ConnectionError()
e = e_class(message)
e.data = response['error']['data']
raise e
return response.get('result')
except (ValueError, requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.Timeout, requests.exceptions.HTTPError) as e:
raise exceptions.AccessError(
_('The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was %s', url)
)
#----------------------------------------------------------
# Helpers for proxy
#----------------------------------------------------------
class IapTransaction(object):
def __init__(self):
self.credit = None
def iap_authorize(env, key, account_token, credit, dbuuid=False, description=None, credit_template=None, ttl=4320):
endpoint = iap_get_endpoint(env)
params = {
'account_token': account_token,
'credit': credit,
'key': key,
'description': description,
'ttl': ttl,
}
if dbuuid:
params.update({'dbuuid': dbuuid})
try:
transaction_token = iap_jsonrpc(endpoint + '/iap/1/authorize', params=params)
except InsufficientCreditError as e:
if credit_template:
arguments = json.loads(e.args[0])
arguments['body'] = pycompat.to_text(env['ir.qweb']._render(credit_template))
e.args = (json.dumps(arguments),)
raise e
return transaction_token
def iap_cancel(env, transaction_token, key):
endpoint = iap_get_endpoint(env)
params = {
'token': transaction_token,
'key': key,
}
r = iap_jsonrpc(endpoint + '/iap/1/cancel', params=params)
return r
def iap_capture(env, transaction_token, key, credit):
endpoint = iap_get_endpoint(env)
params = {
'token': transaction_token,
'key': key,
'credit_to_capture': credit,
}
r = iap_jsonrpc(endpoint + '/iap/1/capture', params=params)
return r
@contextlib.contextmanager
def iap_charge(env, key, account_token, credit, dbuuid=False, description=None, credit_template=None, ttl=4320):
"""
Account charge context manager: takes a hold for ``credit``
amount before executing the body, then captures it if there
is no error, or cancels it if the body generates an exception.
:param str key: service identifier
:param str account_token: user identifier
:param int credit: cost of the body's operation
:param description: a description of the purpose of the charge,
the user will be able to see it in their
dashboard
:type description: str
:param credit_template: a QWeb template to render and show to the
user if their account does not have enough
credits for the requested operation
:param int ttl: transaction time to live in hours.
If the credit are not captured when the transaction
expires, the transaction is canceled
:type credit_template: str
"""
transaction_token = iap_authorize(env, key, account_token, credit, dbuuid, description, credit_template, ttl)
try:
transaction = IapTransaction()
transaction.credit = credit
yield transaction
except Exception as e:
r = iap_cancel(env,transaction_token, key)
raise e
else:
r = iap_capture(env,transaction_token, key, transaction.credit)
| 44.544601
| 9,488
|
362
|
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
class TestIAP(TransactionCase):
def test_get_account(self):
account = self.env["iap.account"].get("random_service_name")
self.assertTrue(account.account_token, "Must be able to read the field")
| 36.2
| 362
|
5,725
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from unittest.mock import patch
from odoo import exceptions
from odoo.addons.iap.tools import iap_tools
from odoo.addons.iap.models.iap_enrich_api import IapEnrichAPI
from odoo.tests import common
class MockIAPEnrich(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(MockIAPEnrich, cls).setUpClass()
cls._init_iap_mock()
@contextmanager
def mockIAPEnrichGateway(self, default_data=None, email_data=None, sim_error=None, failing_emails=None):
def _contact_iap(local_endpoint, params):
sim_result = {
'name': 'Simulator INC',
'location': 'Simulator Street',
'city': 'SimCity',
'postal_code': '9876',
'country_code': 'BE',
'clearbit_id': 'idontknow',
'phone_numbers': ['+3269001122', '+32456001122'],
'twitter': 'testtwitter',
'facebook': 'testfacebook',
}
if default_data:
sim_result.update(default_data)
# mock single sms sending
if local_endpoint == '/iap/clearbit/1/lead_enrichment_email':
result = {}
for lead_id, email in params['domains'].items():
if sim_error and sim_error == 'credit':
raise iap_tools.InsufficientCreditError('InsufficientCreditError')
elif sim_error and sim_error == 'jsonrpc_exception':
raise exceptions.AccessError(
'The url that this service requested returned an error. Please contact the author of the app. The url it tried to contact was ' + local_endpoint
)
result[str(lead_id)] = dict(sim_result)
if email_data and email_data.get(email):
result[str(lead_id)].update(email_data[email])
return result
try:
with patch.object(IapEnrichAPI, '_contact_iap', side_effect=_contact_iap) as contact_iap_mock:
yield
finally:
pass
@classmethod
def _init_iap_mock(cls):
cls.base_de = cls.env.ref('base.de')
cls.de_state_st = cls.env['res.country.state'].create({
'name': 'DE ST State',
'code': 'st',
'country_id': cls.base_de.id
})
cls.base_be = cls.env.ref('base.be')
cls.be_state_bw = cls.env['res.country.state'].create({
'name': 'Béwééé dis',
'code': 'bw',
'country_id': cls.base_be.id
})
def _get_iap_company_data(self, base_name, service=None, add_values=None):
return {
'domain': '%s.de' % base_name,
'clearbit_id': '123_ClearbitID_%s' % base_name,
# Company Info
'name': '%s GmbH' % base_name,
'legal_name': '%s GmbH legal_name' % base_name,
'description': '%s GmbH description' % base_name,
'founded_year': '1930',
'logo': 'https://logo.clearbit.com/%slogo.com' % base_name,
'company_type': 'private',
# Contacts
'phone_numbers': ['+4930499193937', '+4930653376208'],
'email': [
'info@%s.example.com' % base_name,
'info2@%s.example.com' % base_name
],
# Timezone
'timezone': 'Europe/Berlin',
'timezone_url': 'https://time.is/Berlin',
# Social
'facebook': "%s Facebook Handle" % base_name,
'linkedin': "%s Linkedin Handle" % base_name,
'crunchbase': "organization/%s" % base_name,
# Twitter
'twitter': '%s Twitter Handle' % base_name,
'twitter_bio': '%s Twitter Bio' % base_name,
'twitter_followers': 1250,
'twitter_location': 'Berlin',
# Metrics
'estimated_annual_revenue': '1000000',
'employees': 3.14,
'market_cap': 6.28,
'raised': 15000,
'annual_revenue': 1000000,
# Category
'sector': '%s sector' % base_name,
'sector_primary': '%s sector_primary' % base_name,
'industry': '%s industry' % base_name,
'industry_group': '%s industry_group' % base_name,
'sub_industry': '%s sub_industry' % base_name,
'tag': ['Automation', 'Construction'],
'tech': ['3d_cart', 'nginx'],
# Site
'website_title': '%s Website Title' % base_name,
# GEO Data
'location': 'Mennrather Str. 123456',
'street_number': '123456',
'street_name': 'Mennrather Str.',
'sub_premise': 'sub premise',
'postal_code': '41179',
'city': 'Mönchengladbach',
'state_code': self.de_state_st.code,
'state_name': self.de_state_st.name,
'country_code': self.base_de.code,
'country_name': self.base_de.name,
}
def _get_iap_contact_data(self, base_name, service=None, add_values=None):
people_data = []
for index in range(2):
payload = {
'full_name': 'Contact %s %s' % (base_name, index),
'email': 'test.contact.%s@%s.example.com' % (index, base_name),
'phone': '+49 30 548406496',
'seniority': 'manager',
'title': 'Doing stuff',
'role': 'health_professional',
}
people_data.append(payload)
return people_data
| 37.880795
| 5,720
|
1,541
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
from odoo.addons.iap.tools import iap_tools
class IapEnrichAPI(models.AbstractModel):
_name = 'iap.enrich.api'
_description = 'IAP Lead Enrichment API'
_DEFAULT_ENDPOINT = 'https://iap-services.odoo.com'
@api.model
def _contact_iap(self, local_endpoint, params):
account = self.env['iap.account'].get('reveal')
dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
params['account_token'] = account.account_token
params['dbuuid'] = dbuuid
base_url = self.env['ir.config_parameter'].sudo().get_param('enrich.endpoint', self._DEFAULT_ENDPOINT)
return iap_tools.iap_jsonrpc(base_url + local_endpoint, params=params, timeout=300)
@api.model
def _request_enrich(self, lead_emails):
""" Contact endpoint to get enrichment data.
:param lead_emails: dict{lead_id: email}
:return: dict{lead_id: company data or False}
:raise: several errors, notably
* InsufficientCreditError: {
"credit": 4.0,
"service_name": "reveal",
"base_url": "https://iap.odoo.com/iap/1/credit",
"message": "You don't have enough credits on your account to use this service."
}
"""
params = {
'domains': lead_emails,
}
return self._contact_iap('/iap/clearbit/1/lead_enrichment_email', params=params)
| 39.512821
| 1,541
|
403
|
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 ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
@api.model
def _redirect_to_iap_account(self):
return {
'type': 'ir.actions.act_url',
'url': self.env['iap.account'].get_account_url(),
}
| 26.866667
| 403
|
5,450
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import uuid
import werkzeug.urls
from odoo import api, fields, models
from odoo.addons.iap.tools import iap_tools
_logger = logging.getLogger(__name__)
DEFAULT_ENDPOINT = 'https://iap.odoo.com'
class IapAccount(models.Model):
_name = 'iap.account'
_rec_name = 'service_name'
_description = 'IAP Account'
service_name = fields.Char()
account_token = fields.Char(default=lambda s: uuid.uuid4().hex)
company_ids = fields.Many2many('res.company')
@api.model
def get(self, service_name, force_create=True):
domain = [
('service_name', '=', service_name),
'|',
('company_ids', 'in', self.env.companies.ids),
('company_ids', '=', False)
]
accounts = self.search(domain, order='id desc')
accounts_without_token = accounts.filtered(lambda acc: not acc.account_token)
if accounts_without_token:
with self.pool.cursor() as cr:
# In case of a further error that will rollback the database, we should
# use a different SQL cursor to avoid undo the accounts deletion.
# Flush the pending operations to avoid a deadlock.
self.flush()
IapAccount = self.with_env(self.env(cr=cr))
# Need to use sudo because regular users do not have delete right
IapAccount.search(domain + [('account_token', '=', False)]).sudo().unlink()
accounts = accounts - accounts_without_token
if not accounts:
with self.pool.cursor() as cr:
# Since the account did not exist yet, we will encounter a NoCreditError,
# which is going to rollback the database and undo the account creation,
# preventing the process to continue any further.
# Flush the pending operations to avoid a deadlock.
self.flush()
IapAccount = self.with_env(self.env(cr=cr))
account = IapAccount.search(domain, order='id desc', limit=1)
if not account:
if not force_create:
return account
account = IapAccount.create({'service_name': service_name})
# fetch 'account_token' into cache with this cursor,
# as self's cursor cannot see this account
account_token = account.account_token
account = self.browse(account.id)
self.env.cache.set(account, IapAccount._fields['account_token'], account_token)
return account
accounts_with_company = accounts.filtered(lambda acc: acc.company_ids)
if accounts_with_company:
return accounts_with_company[0]
return accounts[0]
@api.model
def get_credits_url(self, service_name, base_url='', credit=0, trial=False):
""" Called notably by ajax crash manager, buy more widget, partner_autocomplete, sanilmail. """
dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid')
if not base_url:
endpoint = iap_tools.iap_get_endpoint(self.env)
route = '/iap/1/credit'
base_url = endpoint + route
account_token = self.get(service_name).account_token
d = {
'dbuuid': dbuuid,
'service_name': service_name,
'account_token': account_token,
'credit': credit,
}
if trial:
d.update({'trial': trial})
return '%s?%s' % (base_url, werkzeug.urls.url_encode(d))
@api.model
def get_account_url(self):
""" Called only by res settings """
route = '/iap/services'
endpoint = iap_tools.iap_get_endpoint(self.env)
d = {'dbuuid': self.env['ir.config_parameter'].sudo().get_param('database.uuid')}
return '%s?%s' % (endpoint + route, werkzeug.urls.url_encode(d))
@api.model
def get_config_account_url(self):
""" Called notably by ajax partner_autocomplete. """
account = self.env['iap.account'].get('partner_autocomplete')
action = self.env.ref('iap.iap_account_action')
menu = self.env.ref('iap.iap_account_menu')
no_one = self.user_has_groups('base.group_no_one')
if account:
url = "/web#id=%s&action=%s&model=iap.account&view_type=form&menu_id=%s" % (account.id, action.id, menu.id)
else:
url = "/web#action=%s&model=iap.account&view_type=form&menu_id=%s" % (action.id, menu.id)
return no_one and url
@api.model
def get_credits(self, service_name):
account = self.get(service_name, force_create=False)
credit = 0
if account:
route = '/iap/1/balance'
endpoint = iap_tools.iap_get_endpoint(self.env)
url = endpoint + route
params = {
'dbuuid': self.env['ir.config_parameter'].sudo().get_param('database.uuid'),
'account_token': account.account_token,
'service_name': service_name,
}
try:
credit = iap_tools.iap_jsonrpc(url=url, params=params)
except Exception as e:
_logger.info('Get credit error : %s', str(e))
credit = -1
return credit
| 41.287879
| 5,450
|
988
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'United Arab Emirates - Accounting',
'author': 'Tech Receptives',
'category': 'Accounting/Localizations/Account Charts',
'description': """
United Arab Emirates accounting chart and localization.
=======================================================
""",
'depends': ['base', 'account'],
'data': [
'data/l10n_ae_data.xml',
'data/l10n_ae_chart_data.xml',
'data/account.account.template.csv',
'data/account_tax_group_data.xml',
'data/l10n_ae_chart_post_data.xml',
'data/account_tax_report_data.xml',
'data/account_tax_template_data.xml',
'data/fiscal_templates_data.xml',
'data/account_chart_template_data.xml',
'views/report_invoice_templates.xml',
'views/account_move.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 34.068966
| 988
|
501
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
l10n_ae_vat_amount = fields.Monetary(compute='_compute_vat_amount', string='VAT Amount')
@api.depends('price_subtotal', 'price_total')
def _compute_vat_amount(self):
for record in self:
record.l10n_ae_vat_amount = record.price_total - record.price_subtotal
| 35.785714
| 501
|
2,505
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):
""" If UAE chart, we add 2 new journals TA and IFRS"""
if self == self.env.ref('l10n_ae.uae_chart_template_standard'):
if not journals_dict:
journals_dict = []
journals_dict.extend(
[{"name": "Tax Adjustments", "company_id": company.id, "code": "TA", "type": "general", "sequence": 1,
"favorite": True},
{"name": "IFRS 16", "company_id": company.id, "code": "IFRS", "type": "general", "favorite": True,
"sequence": 10}])
return super()._prepare_all_journals(acc_template_ref, company, journals_dict=journals_dict)
def _load_template(self, company, code_digits=None, account_ref=None, taxes_ref=None):
account_ref, taxes_ref = super(AccountChartTemplate, self)._load_template(company=company,
code_digits=code_digits,
account_ref=account_ref,
taxes_ref=taxes_ref)
if self == self.env.ref('l10n_ae.uae_chart_template_standard'):
ifrs_journal = self.env['account.journal'].search(
[('company_id', '=', company.id), ('code', '=', 'IFRS')]).id
if ifrs_journal:
ifrs_account_ids = [self.env.ref('l10n_ae.uae_account_100101').id,
self.env.ref('l10n_ae.uae_account_100102').id,
self.env.ref('l10n_ae.uae_account_400070').id]
ifrs_accounts = self.env['account.account'].browse([account_ref.get(id) for id in ifrs_account_ids])
for account in ifrs_accounts:
account.allowed_journal_ids = [(4, ifrs_journal, 0)]
self.env.ref('l10n_ae.ae_tax_group_5').write(
{'property_tax_payable_account_id': account_ref.get(self.env.ref('l10n_ae.uae_account_202003').id),
'property_tax_receivable_account_id': account_ref.get(self.env.ref('l10n_ae.uae_account_100103').id)})
return account_ref, taxes_ref
| 64.230769
| 2,505
|
437
|
py
|
PYTHON
|
15.0
|
{
'name': "TOTPortal",
'category': 'Hidden',
'depends': ['portal', 'auth_totp'],
'auto_install': True,
'data': [
'security/security.xml',
'views/templates.xml',
],
'assets': {
'web.assets_frontend': [
'auth_totp_portal/static/src/**/*',
],
'web.assets_tests': [
'auth_totp_portal/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 23
| 437
|
1,711
|
py
|
PYTHON
|
15.0
|
import time
from passlib.totp import TOTP
from odoo import http
from odoo.tests import tagged, HttpCase
from odoo.addons.auth_totp.controllers.home import Home
@tagged('post_install', '-at_install')
class TestTOTPortal(HttpCase):
"""
Largely replicates TestTOTP
"""
def test_totp(self):
totp = None
# test endpoint as doing totp on the client side is not really an option
# (needs sha1 and hmac + BE packing of 64b integers)
def totp_hook(self, secret=None):
nonlocal totp
if totp is None:
totp = TOTP(secret)
if secret:
return totp.generate().token
else:
# on check, take advantage of window because previous token has been
# "burned" so we can't generate the same, but tour is so fast
# we're pretty certainly within the same 30s
return totp.generate(time.time() + 30).token
# because not preprocessed by ControllerType metaclass
totp_hook.routing_type = 'json'
# patch Home to add test endpoint
Home.totp_hook = http.route('/totphook', type='json', auth='none')(totp_hook)
self.env['ir.http']._clear_routing_map()
# remove endpoint and destroy routing map
@self.addCleanup
def _cleanup():
del Home.totp_hook
self.env['ir.http']._clear_routing_map()
self.start_tour('/my/security', 'totportal_tour_setup', login='portal')
# also disables totp otherwise we can't re-login
self.start_tour('/', 'totportal_login_enabled', login=None)
self.start_tour('/', 'totportal_login_disabled', login=None)
| 38.886364
| 1,711
|
374
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class Users(models.Model):
_inherit = 'res.users'
def get_totp_invite_url(self):
if not self.has_group('base.group_user'):
return '/my/security'
else:
return super(Users, self).get_totp_invite_url()
| 26.714286
| 374
|
1,120
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
"name" : "Mongolia - Accounting",
"version" : "1.0",
'category': 'Accounting/Localizations/Account Charts',
"author" : "BumanIT LLC, Odoo S.A.",
"description": """
This is the module to manage the accounting chart for Mongolia.
===============================================================
* the Mongolia Official Chart of Accounts,
* the Tax Code Chart for Mongolia
* the main taxes used in Mongolia
Financial requirement contributor: Baskhuu Lodoikhuu. BumanIT LLC
""",
"depends": ['account'],
'data': [
'data/account_chart_template_data.xml',
'data/account.account.tag.csv',
'data/account.account.template.csv',
'data/account.tax.group.csv',
'data/account_tax_template_data.xml',
'data/account_fiscal_position_template_data.xml',
'data/account.chart.template.csv',
'data/account_chart_template_configuration_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 32.941176
| 1,120
|
596
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Indian - Stock Report(GST)',
'icon': '/l10n_in/static/description/icon.png',
'version': '1.0',
'description': """GST Stock Report""",
'category': 'Accounting/Localizations',
'depends': [
'l10n_in',
'stock',
],
'data': [
'views/report_stockpicking_operations.xml',
],
'demo': [
'data/product_demo.xml',
],
'installable': True,
'application': False,
'auto_install': True,
'license': 'LGPL-3',
}
| 24.833333
| 596
|
335
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class StockPicking(models.Model):
_inherit = 'stock.picking'
def _should_generate_commercial_invoice(self):
super(StockPicking, self)._should_generate_commercial_invoice()
return True
| 27.916667
| 335
|
1,794
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Vantiv Payment Services',
'version': '1.0',
'category': 'Sales/Point of Sale',
'sequence': 6,
'summary': 'Credit card support for Point Of Sale',
'description': """
Allow credit card POS payments
==============================
This module allows customers to pay for their orders with credit
cards. The transactions are processed by Vantiv (developed by Wells
Fargo Bank). A Vantiv merchant account is necessary. It allows the
following:
* Fast payment by just swiping a credit card while on the payment screen
* Combining of cash payments and credit card payments
* Cashback
* Supported cards: Visa, MasterCard, American Express, Discover
""",
'depends': ['web', 'barcodes', 'point_of_sale'],
'data': [
'data/pos_mercury_data.xml',
'security/ir.model.access.csv',
'views/pos_mercury_views.xml',
'views/pos_mercury_transaction_templates.xml',
'views/pos_config_setting_views.xml',
],
'demo': [
'data/pos_mercury_demo.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'point_of_sale.assets': [
'pos_mercury/static/src/js/pos_mercury.js',
'pos_mercury/static/src/js/OrderReceipt.js',
'pos_mercury/static/src/js/PaymentScreen.js',
'pos_mercury/static/src/js/PaymentScreenPaymentLines.js',
'pos_mercury/static/src/js/PaymentTransactionPopup.js',
'pos_mercury/static/src/js/ProductScreen.js',
'pos_mercury/static/src/css/pos_mercury.css',
],
'web.assets_qweb': [
'pos_mercury/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 34.5
| 1,794
|
4,206
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, timedelta
import requests
from html import unescape
from markupsafe import Markup
from odoo import models, api, service
from odoo.tools.translate import _
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, misc
class MercuryTransaction(models.Model):
_name = 'pos_mercury.mercury_transaction'
_description = 'Point of Sale Vantiv Transaction'
def _get_pos_session(self):
pos_session = self.env['pos.session'].search([('state', '=', 'opened'), ('user_id', '=', self.env.uid)], limit=1)
if not pos_session:
raise UserError(_("No opened point of sale session for user %s found.", self.env.user.name))
pos_session.login()
return pos_session
def _get_pos_mercury_config_id(self, config, payment_method_id):
payment_method = config.current_session_id.payment_method_ids.filtered(lambda pm: pm.id == payment_method_id)
if payment_method and payment_method.pos_mercury_config_id:
return payment_method.pos_mercury_config_id
else:
raise UserError(_("No Vantiv configuration associated with the payment method."))
def _setup_request(self, data):
# todo: in master make the client include the pos.session id and use that
pos_session = self._get_pos_session()
config = pos_session.config_id
pos_mercury_config = self._get_pos_mercury_config_id(config, data['payment_method_id'])
data['operator_id'] = pos_session.user_id.login
data['merchant_id'] = pos_mercury_config.sudo().merchant_id
data['merchant_pwd'] = pos_mercury_config.sudo().merchant_pwd
data['memo'] = "Odoo " + service.common.exp_version()['server_version']
def _do_request(self, template, data):
if not data['merchant_id'] or not data['merchant_pwd']:
return "not setup"
# transaction is str()'ed so it's escaped inside of <mer:tran>
xml_transaction = Markup('''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mer="http://www.mercurypay.com">
<soapenv:Header/>
<soapenv:Body>
<mer:CreditTransaction>
<mer:tran>{transaction}</mer:tran>
<mer:pw>{password}</mer:pw>
</mer:CreditTransaction>
</soapenv:Body>
</soapenv:Envelope>''').format(transaction=str(self.env.ref(template)._render(data)), password=data['merchant_pwd'])
response = ''
headers = {
'Content-Type': 'text/xml',
'SOAPAction': 'http://www.mercurypay.com/CreditTransaction',
}
url = 'https://w1.mercurypay.com/ws/ws.asmx'
if self.env['ir.config_parameter'].sudo().get_param('pos_mercury.enable_test_env'):
url = 'https://w1.mercurycert.net/ws/ws.asmx'
try:
r = requests.post(url, data=xml_transaction, headers=headers, timeout=65)
r.raise_for_status()
response = unescape(r.content.decode())
except Exception:
response = "timeout"
return response
def _do_reversal_or_voidsale(self, data, is_voidsale):
try:
self._setup_request(data)
except UserError:
return "internal error"
data['is_voidsale'] = is_voidsale
response = self._do_request('pos_mercury.mercury_voidsale', data)
return response
@api.model
def do_payment(self, data):
try:
self._setup_request(data)
except UserError:
return "internal error"
response = self._do_request('pos_mercury.mercury_transaction', data)
return response
@api.model
def do_reversal(self, data):
return self._do_reversal_or_voidsale(data, False)
@api.model
def do_voidsale(self, data):
return self._do_reversal_or_voidsale(data, True)
def do_return(self, data):
try:
self._setup_request(data)
except UserError:
return "internal error"
response = self._do_request('pos_mercury.mercury_return', data)
return response
| 34.760331
| 4,206
|
3,501
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import models, fields, api, _
from odoo.tools.float_utils import float_compare
_logger = logging.getLogger(__name__)
class BarcodeRule(models.Model):
_inherit = 'barcode.rule'
type = fields.Selection(selection_add=[
('credit', 'Credit Card')
], ondelete={'credit': 'set default'})
class PosMercuryConfiguration(models.Model):
_name = 'pos_mercury.configuration'
_description = 'Point of Sale Vantiv Configuration'
name = fields.Char(required=True, help='Name of this Vantiv configuration')
merchant_id = fields.Char(string='Merchant ID', required=True, help='ID of the merchant to authenticate him on the payment provider server')
merchant_pwd = fields.Char(string='Merchant Password', required=True, help='Password of the merchant to authenticate him on the payment provider server')
class PoSPayment(models.Model):
_inherit = "pos.payment"
mercury_card_number = fields.Char(string='Card Number', help='The last 4 numbers of the card used to pay')
mercury_prefixed_card_number = fields.Char(string='Card Number Prefix', compute='_compute_prefixed_card_number', help='The card number used for the payment.')
mercury_card_brand = fields.Char(string='Card Brand', help='The brand of the payment card (e.g. Visa, AMEX, ...)')
mercury_card_owner_name = fields.Char(string='Card Owner Name', help='The name of the card owner')
mercury_ref_no = fields.Char(string='Vantiv reference number', help='Payment reference number from Vantiv Pay')
mercury_record_no = fields.Char(string='Vantiv record number', help='Payment record number from Vantiv Pay')
mercury_invoice_no = fields.Char(string='Vantiv invoice number', help='Invoice number from Vantiv Pay')
def _compute_prefixed_card_number(self):
for line in self:
if line.mercury_card_number:
line.mercury_prefixed_card_number = "********" + line.mercury_card_number
else:
line.mercury_prefixed_card_number = ""
class PoSPaymentMethod(models.Model):
_inherit = 'pos.payment.method'
pos_mercury_config_id = fields.Many2one('pos_mercury.configuration', string='Vantiv Credentials', help='The configuration of Vantiv used for this journal')
def _get_payment_terminal_selection(self):
return super(PoSPaymentMethod, self)._get_payment_terminal_selection() + [('mercury', 'Vantiv')]
@api.onchange('use_payment_terminal')
def _onchange_use_payment_terminal(self):
super(PoSPaymentMethod, self)._onchange_use_payment_terminal()
if self.use_payment_terminal != 'mercury':
self.pos_mercury_config_id = False
class PosOrder(models.Model):
_inherit = "pos.order"
@api.model
def _payment_fields(self, order, ui_paymentline):
fields = super(PosOrder, self)._payment_fields(order, ui_paymentline)
fields.update({
'mercury_card_number': ui_paymentline.get('mercury_card_number'),
'mercury_card_brand': ui_paymentline.get('mercury_card_brand'),
'mercury_card_owner_name': ui_paymentline.get('mercury_card_owner_name'),
'mercury_ref_no': ui_paymentline.get('mercury_ref_no'),
'mercury_record_no': ui_paymentline.get('mercury_record_no'),
'mercury_invoice_no': ui_paymentline.get('mercury_invoice_no')
})
return fields
| 44.884615
| 3,501
|
388
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Finland - Sale',
'version': '1.0',
'description': """Finland Sale""",
'category': 'Localization',
'depends': [
'l10n_fi',
'sale',
],
'installable': True,
'application': False,
'auto_install': True,
'license': 'LGPL-3',
}
| 22.823529
| 388
|
1,719
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import re
from odoo import api, models, _
from odoo.exceptions import UserError
class SaleOrder(models.Model):
_inherit = "sale.order"
def write(self, values):
# We compute the l10n_fi/SaleOrder.reference from itself the same way
# we compute the l10n_fi/AccountMove.invoice_payment_ref from its name.
reference = values.get('reference', False)
if reference:
values['reference'] = self.compute_payment_reference_finnish(reference)
return super().write(values)
@api.model
def number2numeric(self, number):
so_number = re.sub(r'\D', '', number)
if so_number == '' or so_number is False:
raise UserError(_('Reference must contain numeric characters'))
# Make sure the base number is 3...19 characters long
if len(so_number) < 3:
so_number = ('11' + so_number)[-3:]
elif len(so_number) > 19:
so_number = so_number[:19]
return so_number
@api.model
def get_finnish_check_digit(self, base_number):
# Multiply digits from end to beginning with 7, 3 and 1 and
# calculate the sum of the products
total = sum((7, 3, 1)[idx % 3] * int(val) for idx, val in
enumerate(base_number[::-1]))
# Subtract the sum from the next decade. 10 = 0
return str((10 - (total % 10)) % 10)
@api.model
def compute_payment_reference_finnish(self, number):
# Drop all non-numeric characters
so_number = self.number2numeric(number)
# Calculate the Finnish check digit
check_digit = self.get_finnish_check_digit(so_number)
return so_number + check_digit
| 36.574468
| 1,719
|
908
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Phone Numbers Validation',
'version': '2.1',
'summary': 'Validate and format phone numbers',
'sequence': '9999',
'category': 'Hidden',
'description': """
Phone Numbers Validation
========================
This module adds the feature of validation and formatting phone numbers
according to a destination country.
It also adds phone blacklist management through a specific model storing
blacklisted phone numbers.
It adds mail.thread.phone mixin that handles sanitation and blacklist of
records numbers. """,
'data': [
'security/ir.model.access.csv',
'views/phone_blacklist_views.xml',
'wizard/phone_blacklist_remove_view.xml',
],
'depends': [
'base',
'mail',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 27.515152
| 908
|
4,940
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _
from odoo.exceptions import UserError
import logging
_logger = logging.getLogger(__name__)
_phonenumbers_lib_warning = False
try:
import phonenumbers
def phone_parse(number, country_code):
try:
phone_nbr = phonenumbers.parse(number, region=country_code or None, keep_raw_input=True)
except phonenumbers.phonenumberutil.NumberParseException as e:
raise UserError(_('Unable to parse %(phone)s: %(error)s', phone=number, error=str(e)))
if not phonenumbers.is_possible_number(phone_nbr):
raise UserError(_('Impossible number %s: probably invalid number of digits.', number))
if not phonenumbers.is_valid_number(phone_nbr):
raise UserError(_('Invalid number %s: probably incorrect prefix.', number))
return phone_nbr
def phone_format(number, country_code, country_phone_code, force_format='INTERNATIONAL', raise_exception=True):
""" Format the given phone number according to the localisation and international options.
:param number: number to convert
:param country_code: the ISO country code in two chars
:type country_code: str
:param country_phone_code: country dial in codes, defined by the ITU-T (Ex: 32 for Belgium)
:type country_phone_code: int
:param force_format: stringified version of format globals (see
https://github.com/daviddrysdale/python-phonenumbers/blob/dev/python/phonenumbers/phonenumberutil.py)
'E164' = 0
'INTERNATIONAL' = 1
'NATIONAL' = 2
'RFC3966' = 3
:type force_format: str
:rtype: str
"""
try:
phone_nbr = phone_parse(number, country_code)
except (phonenumbers.phonenumberutil.NumberParseException, UserError) as e:
if raise_exception:
raise
else:
return number
if force_format == 'E164':
phone_fmt = phonenumbers.PhoneNumberFormat.E164
elif force_format == 'RFC3966':
phone_fmt = phonenumbers.PhoneNumberFormat.RFC3966
elif force_format == 'INTERNATIONAL' or phone_nbr.country_code != country_phone_code:
phone_fmt = phonenumbers.PhoneNumberFormat.INTERNATIONAL
else:
phone_fmt = phonenumbers.PhoneNumberFormat.NATIONAL
return phonenumbers.format_number(phone_nbr, phone_fmt)
except ImportError:
def phone_parse(number, country_code):
return False
def phone_format(number, country_code, country_phone_code, force_format='INTERNATIONAL', raise_exception=True):
global _phonenumbers_lib_warning
if not _phonenumbers_lib_warning:
_logger.info(
"The `phonenumbers` Python module is not installed, contact numbers will not be "
"verified. Please install the `phonenumbers` Python module."
)
_phonenumbers_lib_warning = True
return number
def phone_sanitize_numbers(numbers, country_code, country_phone_code, force_format='E164'):
""" Given a list of numbers, return parsezd and sanitized information
:return dict: {number: {
'sanitized': sanitized and formated number or False (if cannot format)
'code': 'empty' (number was a void string), 'invalid' (error) or False (sanitize ok)
'msg': error message when 'invalid'
}}
"""
if not isinstance(numbers, (list)):
raise NotImplementedError()
result = dict.fromkeys(numbers, False)
for number in numbers:
if not number:
result[number] = {'sanitized': False, 'code': 'empty', 'msg': False}
continue
try:
stripped = number.strip()
sanitized = phone_format(
stripped, country_code, country_phone_code,
force_format=force_format, raise_exception=True)
except Exception as e:
result[number] = {'sanitized': False, 'code': 'invalid', 'msg': str(e)}
else:
result[number] = {'sanitized': sanitized, 'code': False, 'msg': False}
return result
def phone_sanitize_numbers_w_record(numbers, record, country=False, record_country_fname='country_id', force_format='E164'):
if not isinstance(numbers, (list)):
raise NotImplementedError()
if not country:
if record and record_country_fname and hasattr(record, record_country_fname) and record[record_country_fname]:
country = record[record_country_fname]
elif record:
country = record.env.company.country_id
country_code = country.code if country else None
country_phone_code = country.phone_code if country else None
return phone_sanitize_numbers(numbers, country_code, country_phone_code, force_format=force_format)
| 42.586207
| 4,940
|
1,913
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
try:
import phonenumbers
except ImportError:
phonenumbers = None
from odoo.tests.common import BaseCase
from odoo.tools.parse_version import parse_version
from odoo.addons.phone_validation.lib import phonenumbers_patch
class TestPhonenumbersPatch(BaseCase):
def test_region_CI_monkey_patch(self):
"""Test if the patch is apply on the good version of the lib
And test some phonenumbers"""
if not phonenumbers:
self.skipTest('Cannot test without phonenumbers module installed.')
# MONKEY PATCHING phonemetadata of Ivory Coast if phonenumbers is too old
if parse_version('7.6.1') <= parse_version(phonenumbers.__version__) < parse_version('8.12.32'):
# check that _local_load_region is set to `odoo.addons.phone_validation.lib.phonenumbers_patch._local_load_region`
# check that you can load a new ivory coast phone number without error
parsed_phonenumber_1 = phonenumbers.parse("20 25/35-51 ", region="CI", keep_raw_input=True)
self.assertEqual(parsed_phonenumber_1.national_number, 20253551, "The national part of the phonenumber should be 22522586")
self.assertEqual(parsed_phonenumber_1.country_code, 225, "The country code of Ivory Coast is 225")
parsed_phonenumber_2 = phonenumbers.parse("+225 22 52 25 86 ", region="CI", keep_raw_input=True)
self.assertEqual(parsed_phonenumber_2.national_number, 22522586, "The national part of the phonenumber should be 22522586")
self.assertEqual(parsed_phonenumber_2.country_code, 225, "The country code of Ivory Coast is 225")
else:
self.assertFalse(hasattr(phonenumbers_patch, '_local_load_region'),
"The code should not be monkey patched with phonenumbers > 8.12.32.")
| 59.78125
| 1,913
|
802
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.phone_validation.tools import phone_validation
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.tests.common import BaseCase
@tagged('phone_validation')
class TestPhonenumbers(BaseCase):
def test_country_code_falsy(self):
self.assertEqual(
phone_validation.phone_format('0456998877', 'BE', '32', force_format='E164'),
'+32456998877'
)
# no country code -> UserError, no internal traceback
with self.assertRaises(UserError):
self.assertEqual(
phone_validation.phone_format('0456998877', None, '32', force_format='E164'),
'+32456998877'
)
| 34.869565
| 802
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.