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 |
|---|---|---|---|---|---|---|
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
726 | py | PYTHON | 15.0 | # Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Project Stock",
"version": "15.0.1.0.4",
"category": "Project Management",
"website": "https://github.com/OCA/project",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["project", "stock"],
"installable": True,
"data": [
"views/project_project_view.xml",
"views/project_task_type_view.xml",
"views/stock_move_view.xml",
"views/project_task_view.xml",
],
"demo": [
"demo/stock_picking_type_data.xml",
"demo/project_data.xml",
],
"maintainers": ["victoralmau"],
}
| 31.478261 | 724 |
401 | py | PYTHON | 15.0 | # Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
_table_renamed = [
(
"account_analytic_tag_project_task_rel",
"account_analytic_tag_project_task_stock_rel",
),
]
@openupgrade.migrate()
def migrate(env, version):
openupgrade.rename_tables(env.cr, _table_renamed)
| 24.9375 | 399 |
12,263 | py | PYTHON | 15.0 | # Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.tests import Form
from odoo.tests.common import users
from .common import TestProjectStockBase
class TestProjectStock(TestProjectStockBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._create_stock_quant(cls, cls.product_a, cls.location, 2)
cls._create_stock_quant(cls, cls.product_b, cls.location, 1)
cls._create_stock_quant(cls, cls.product_c, cls.location, 1)
cls.task = cls._create_task(cls, [(cls.product_a, 2), (cls.product_b, 1)])
cls.move_product_a = cls.task.move_ids.filtered(
lambda x: x.product_id == cls.product_a
)
cls.move_product_b = cls.task.move_ids.filtered(
lambda x: x.product_id == cls.product_b
)
cls.env.ref("base.user_admin").write(
{
"groups_id": [
(4, cls.env.ref("analytic.group_analytic_accounting").id),
(4, cls.env.ref("analytic.group_analytic_tags").id),
],
}
)
def _create_stock_quant(self, product, location, qty):
self.env["stock.quant"].create(
{"product_id": product.id, "location_id": location.id, "quantity": qty}
)
def test_project_task_misc(self):
self.assertTrue(self.task.group_id)
self.assertEqual(self.task.picking_type_id, self.picking_type)
self.assertEqual(self.task.location_id, self.location)
self.assertEqual(self.task.location_dest_id, self.location_dest)
self.assertEqual(self.move_product_a.name, self.task.name)
self.assertEqual(self.move_product_a.group_id, self.task.group_id)
self.assertEqual(self.move_product_a.reference, self.task.name)
self.assertEqual(self.move_product_a.location_id, self.location)
self.assertEqual(self.move_product_a.location_dest_id, self.location_dest)
self.assertEqual(self.move_product_a.picking_type_id, self.picking_type)
self.assertEqual(self.move_product_a.raw_material_task_id, self.task)
self.assertEqual(self.move_product_b.group_id, self.task.group_id)
self.assertEqual(self.move_product_b.location_id, self.location)
self.assertEqual(self.move_product_b.location_dest_id, self.location_dest)
self.assertEqual(self.move_product_b.picking_type_id, self.picking_type)
self.assertEqual(self.move_product_b.raw_material_task_id, self.task)
def _test_task_analytic_lines_from_task(self, amount):
self.task = self.env["project.task"].browse(self.task.id)
# Prevent error when hr_timesheet addon is installed.
stock_analytic_lines = self.task.sudo().stock_analytic_line_ids
self.assertEqual(len(stock_analytic_lines), 2)
self.assertEqual(sum(stock_analytic_lines.mapped("unit_amount")), 3)
self.assertEqual(sum(stock_analytic_lines.mapped("amount")), amount)
self.assertEqual(
self.task.stock_analytic_tag_ids,
stock_analytic_lines.mapped("tag_ids"),
)
self.assertIn(
self.analytic_account,
stock_analytic_lines.mapped("account_id"),
)
# Prevent incoherence when hr_timesheet addon is installed.
if "project_id" in self.task.stock_analytic_line_ids._fields:
self.assertFalse(self.task.stock_analytic_line_ids.project_id)
def test_project_task_without_analytic_account(self):
self.task = self.env["project.task"].browse(self.task.id)
# Prevent error when hr_timesheet addon is installed.
if "allow_timesheets" in self.task.project_id._fields:
self.task.project_id.allow_timesheets = False
self.task.project_id.analytic_account_id = False
self.task.write({"stage_id": self.stage_done.id})
self.task.action_done()
self.assertFalse(self.task.stock_analytic_line_ids)
@users("manager-user")
def test_project_task_without_analytic_account_manager_user(self):
self.test_project_task_without_analytic_account()
def test_project_task_analytic_lines_without_tags(self):
self.task = self.env["project.task"].browse(self.task.id)
self.task.write({"stage_id": self.stage_done.id})
self.task.action_done()
self._test_task_analytic_lines_from_task(-40)
self.assertEqual(
fields.first(self.task.stock_analytic_line_ids).date,
fields.Date.from_string("1990-01-01"),
)
@users("manager-user")
def test_project_task_analytic_lines_without_tags_manager_user(self):
self.test_project_task_analytic_lines_without_tags()
def test_project_task_analytic_lines_with_tag_1(self):
self.task = self.env["project.task"].browse(self.task.id)
self.task.write(
{
"stock_analytic_date": "1991-01-01",
"stock_analytic_tag_ids": self.analytic_tag_1.ids,
}
)
self.task.write({"stage_id": self.stage_done.id})
self.task.action_done()
self._test_task_analytic_lines_from_task(-40)
self.assertEqual(
fields.first(self.task.stock_analytic_line_ids).date,
fields.Date.from_string("1991-01-01"),
)
@users("manager-user")
def test_project_task_analytic_lines_with_tag_1_manager_user(self):
self.test_project_task_analytic_lines_with_tag_1()
def test_project_task_analytic_lines_with_tag_2(self):
self.task = self.env["project.task"].browse(self.task.id)
self.task.project_id.stock_analytic_date = False
self.task.write({"stock_analytic_tag_ids": self.analytic_tag_2.ids})
self.task.write({"stage_id": self.stage_done.id})
self.task.action_done()
self._test_task_analytic_lines_from_task(-20)
self.assertEqual(
fields.first(self.task.stock_analytic_line_ids).date, fields.date.today()
)
@users("manager-user")
def test_project_task_analytic_lines_with_tag_2_manager_user(self):
self.test_project_task_analytic_lines_with_tag_2()
def test_project_task_process_done(self):
self.task = self.env["project.task"].browse(self.task.id)
self.assertEqual(self.move_product_a.state, "draft")
self.assertEqual(self.move_product_b.state, "draft")
# Change task stage (auto-confirm + auto-assign)
self.task.write({"stage_id": self.stage_done.id})
self.assertEqual(self.move_product_a.state, "assigned")
self.assertEqual(self.move_product_b.state, "assigned")
self.assertEqual(self.move_product_a.reserved_availability, 2)
self.assertEqual(self.move_product_b.reserved_availability, 1)
self.assertTrue(self.task.stock_moves_is_locked)
self.task.action_toggle_stock_moves_is_locked()
self.assertFalse(self.task.stock_moves_is_locked)
# Add new stock_move
self.task.write({"stage_id": self.stage_in_progress.id})
task_form = Form(self.task)
with task_form.move_ids.new() as move_form:
move_form.product_id = self.product_c
move_form.product_uom_qty = 1
task_form.save()
move_product_c = self.task.move_ids.filtered(
lambda x: x.product_id == self.product_c
)
self.assertEqual(move_product_c.group_id, self.task.group_id)
self.assertEqual(move_product_c.state, "draft")
self.task.action_assign()
self.assertEqual(move_product_c.state, "assigned")
self.task.write({"stage_id": self.stage_done.id})
# action_done
self.task.action_done()
self.assertEqual(self.move_product_a.state, "done")
self.assertEqual(self.move_product_b.state, "done")
self.assertEqual(self.move_product_a.quantity_done, 2)
self.assertEqual(self.move_product_b.quantity_done, 1)
self.assertEqual(move_product_c.quantity_done, 1)
@users("basic-user")
def test_project_task_process_done_basic_user(self):
self.test_project_task_process_done()
def test_project_task_process_cancel(self):
self.task = self.env["project.task"].browse(self.task.id)
self.assertEqual(self.move_product_a.state, "draft")
self.assertEqual(self.move_product_b.state, "draft")
# Change task stage
self.task.write({"stage_id": self.stage_done.id})
self.assertEqual(self.move_product_a.state, "assigned")
self.assertEqual(self.move_product_b.state, "assigned")
# action_done
self.task.action_done()
self.assertEqual(self.move_product_a.state, "done")
self.assertEqual(self.move_product_b.state, "done")
self.assertEqual(self.move_product_a.quantity_done, 2)
self.assertEqual(self.move_product_b.quantity_done, 1)
self.assertTrue(self.task.sudo().stock_analytic_line_ids)
# action_cancel
self.task.action_cancel()
self.assertEqual(self.move_product_a.state, "done")
self.assertEqual(self.move_product_b.state, "done")
self.assertEqual(self.move_product_a.quantity_done, 0)
self.assertEqual(self.move_product_b.quantity_done, 0)
self.assertFalse(self.task.stock_analytic_line_ids)
quant_a = self.product_a.stock_quant_ids.filtered(
lambda x: x.location_id == self.location
)
quant_b = self.product_b.stock_quant_ids.filtered(
lambda x: x.location_id == self.location
)
quant_c = self.product_c.stock_quant_ids.filtered(
lambda x: x.location_id == self.location
)
self.assertEqual(quant_a.quantity, 2)
self.assertEqual(quant_b.quantity, 1)
self.assertEqual(quant_c.quantity, 1)
@users("manager-user")
def test_project_task_process_cancel_manager_user(self):
self.test_project_task_process_cancel()
def test_project_task_process_unreserve(self):
self.task = self.env["project.task"].browse(self.task.id)
self.assertEqual(self.move_product_a.state, "draft")
self.assertEqual(self.move_product_b.state, "draft")
# Change task stage (auto-confirm + auto-assign)
self.task.write({"stage_id": self.stage_done.id})
self.assertTrue(self.move_product_a.move_line_ids)
self.assertEqual(self.move_product_a.move_line_ids.task_id, self.task)
self.assertEqual(self.move_product_a.state, "assigned")
self.assertEqual(self.move_product_b.state, "assigned")
self.assertEqual(self.move_product_a.reserved_availability, 2)
self.assertEqual(self.move_product_b.reserved_availability, 1)
self.assertTrue(self.task.unreserve_visible)
# button_unreserve
self.task.button_unreserve()
self.assertEqual(self.move_product_a.state, "confirmed")
self.assertEqual(self.move_product_b.state, "confirmed")
self.assertEqual(self.move_product_a.reserved_availability, 0)
self.assertEqual(self.move_product_b.reserved_availability, 0)
self.assertFalse(self.task.unreserve_visible)
@users("basic-user")
def test_project_task_process_unreserve_basic_user(self):
self.test_project_task_process_unreserve()
def test_project_task_action_cancel(self):
self.assertTrue(self.env["project.task"].browse(self.task.id).action_cancel())
@users("basic-user")
def test_project_task_action_cancel_basic_user(self):
self.test_project_task_action_cancel()
def test_project_task_action_done(self):
self.task = self.env["project.task"].browse(self.task.id)
self.task.write({"stage_id": self.stage_done.id})
self.task.action_done()
self.assertTrue(self.task.sudo().stock_analytic_line_ids)
@users("basic-user")
def test_project_task_action_done_basic_user(self):
self.test_project_task_action_done()
def test_project_task_unlink(self):
self.assertTrue(self.env["project.task"].browse(self.task.id).unlink())
@users("basic-user")
def test_project_task_unlink_basic_user(self):
self.test_project_task_unlink()
| 46.443182 | 12,261 |
4,253 | py | PYTHON | 15.0 | # Copyright 2022-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import Form, common, new_test_user
class TestProjectStockBase(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product_a = cls.env["product.product"].create(
{"name": "Test product A", "detailed_type": "product", "standard_price": 10}
)
cls.product_b = cls.env["product.product"].create(
{"name": "Test product B", "detailed_type": "product", "standard_price": 20}
)
cls.product_c = cls.env["product.product"].create(
{"name": "Test product C", "detailed_type": "product", "standard_price": 0}
)
cls.picking_type = cls.env.ref("project_stock.stock_picking_type_tm_test")
cls.location = cls.picking_type.default_location_src_id
cls.location_dest = cls.picking_type.default_location_dest_id
cls.analytic_account = cls.env["account.analytic.account"].create(
{"name": "Test account"}
)
cls.analytic_tag_1 = cls.env["account.analytic.tag"].create(
{
"name": "Test tag 1",
"active_analytic_distribution": True,
"analytic_distribution_ids": [
(0, 0, {"account_id": cls.analytic_account.id, "percentage": 100}),
],
}
)
analytic_account_2 = cls.analytic_account.copy({"name": "Test account 2"})
cls.analytic_tag_2 = cls.env["account.analytic.tag"].create(
{
"name": "Test tag 2",
"active_analytic_distribution": True,
"analytic_distribution_ids": [
(0, 0, {"account_id": cls.analytic_account.id, "percentage": 50}),
(0, 0, {"account_id": analytic_account_2.id, "percentage": 50}),
],
}
)
cls.project = cls.env.ref("project_stock.project_project_tm_test")
cls.project.analytic_account_id = cls.analytic_account
cls.stage_in_progress = cls.env.ref("project.project_stage_1")
cls.stage_done = cls.env.ref("project.project_stage_2")
group_stock_user = "stock.group_stock_user"
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
new_test_user(
cls.env,
login="basic-user",
groups="project.group_project_user,%s" % group_stock_user,
context=ctx,
)
new_test_user(
cls.env,
login="manager-user",
groups="project.group_project_manager,%s,analytic.group_analytic_accounting"
% group_stock_user,
context=ctx,
)
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
new_test_user(
cls.env,
login="project-task-user",
groups="project.group_project_user,stock.group_stock_user",
context=ctx,
)
def _prepare_context_task(self):
return {
"default_project_id": self.project.id,
"default_stage_id": self.stage_in_progress.id,
# We need to set default values according to compute store fields
"default_location_id": self.project.location_id.id,
"default_location_dest_id": self.project.location_dest_id.id,
"default_picking_type_id": self.project.picking_type_id.id,
}
def _create_task(self, products):
task_form = Form(
self.env["project.task"].with_context(**self._prepare_context_task(self))
)
task_form.name = "Test task"
# Save task to use default_get() correctlly in stock.moves
task_form.save()
for product in products:
with task_form.move_ids.new() as move_form:
move_form.product_id = product[0]
move_form.product_uom_qty = product[1]
return task_form.save()
| 41.271845 | 4,251 |
1,122 | py | PYTHON | 15.0 | # Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import api, fields, models
class StockMove(models.Model):
_inherit = "stock.scrap"
task_id = fields.Many2one(
comodel_name="project.task", string="Task", check_company=True
)
@api.onchange("task_id")
def _onchange_task_id(self):
if self.task_id:
self.location_id = self.task_id.move_raw_ids.filtered(
lambda x: x.state not in ("done", "cancel")
) and (self.task_id.location_src_id.id or self.task_id.location_dest_id.id)
def _prepare_move_values(self):
vals = super()._prepare_move_values()
if self.task_id:
vals["origin"] = vals["origin"] or self.task_id.name
vals.update({"raw_material_task_id": self.task_id.id})
return vals
def _get_origin_moves(self):
return super()._get_origin_moves() or (
self.task_id
and self.task_id.move_raw_ids.filtered(
lambda x: x.product_id == self.product_id
)
)
| 33.939394 | 1,120 |
4,803 | py | PYTHON | 15.0 | # Copyright 2022-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import api, fields, models
class StockMove(models.Model):
_inherit = "stock.move"
task_id = fields.Many2one(
comodel_name="project.task",
string="Related Task",
check_company=True,
)
raw_material_task_id = fields.Many2one(
comodel_name="project.task", string="Task for material", check_company=True
)
@api.onchange("product_id")
def _onchange_product_id(self):
"""It is necessary to overwrite the name to prevent set product name
from being auto-defined."""
res = super()._onchange_product_id()
if self.raw_material_task_id:
self.name = self.raw_material_task_id.name
return res
def _prepare_analytic_line_from_task(self):
product = self.product_id
company_id = self.env.company
task = self.task_id or self.raw_material_task_id
analytic_account = (
task.stock_analytic_account_id or task.project_id.analytic_account_id
)
if not analytic_account:
return False
res = {
"date": (
task.stock_analytic_date
or task.project_id.stock_analytic_date
or fields.date.today()
),
"name": task.name + ": " + product.name,
"unit_amount": self.quantity_done,
"account_id": analytic_account.id,
"user_id": self._uid,
"product_uom_id": self.product_uom.id,
"company_id": analytic_account.company_id.id or self.env.company.id,
"partner_id": task.partner_id.id or task.project_id.partner_id.id or False,
"stock_task_id": task.id,
}
amount_unit = product.with_context(uom=self.product_uom.id).price_compute(
"standard_price"
)[product.id]
amount = amount_unit * self.quantity_done or 0.0
result = round(amount, company_id.currency_id.decimal_places) * -1
vals = {"amount": result}
analytic_line_fields = self.env["account.analytic.line"]._fields
# Extra fields added in account addon
if "ref" in analytic_line_fields:
vals["ref"] = task.name
if "product_id" in analytic_line_fields:
vals["product_id"] = product.id
# Prevent incoherence when hr_timesheet addon is installed.
if "project_id" in analytic_line_fields:
vals["project_id"] = False
# tags + distributions
if task.stock_analytic_tag_ids:
vals["tag_ids"] = [(6, 0, task.stock_analytic_tag_ids.ids)]
new_amount = 0
distributions = self.env["account.analytic.distribution"].search(
[
("account_id", "=", analytic_account.id),
("tag_id", "in", task.stock_analytic_tag_ids.ids),
("percentage", ">", 0),
]
)
for distribution in distributions:
new_amount -= (amount / 100) * distribution.percentage
vals["amount"] = new_amount
res.update(vals)
return res
@api.model
def default_get(self, fields_list):
defaults = super().default_get(fields_list)
if self.env.context.get("default_raw_material_task_id"):
task = self.env["project.task"].browse(
self.env.context.get("default_raw_material_task_id")
)
task._set_procurement_group_id() # Define group_id only if necessary
defaults.update(
{
"group_id": task.group_id.id,
"location_id": (
task.location_id.id or task.project_id.location_id.id
),
"location_dest_id": (
task.location_dest_id.id or task.project_id.location_dest_id.id
),
"picking_type_id": (
task.picking_type_id.id or task.project_id.picking_type_id.id
),
}
)
return defaults
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
task_id = fields.Many2one(
comodel_name="project.task",
string="Task",
compute="_compute_task_id",
store=True,
)
@api.depends("move_id.raw_material_task_id", "move_id.task_id")
def _compute_task_id(self):
for item in self:
task = (
item.move_id.raw_material_task_id
if item.move_id.raw_material_task_id
else item.move_id.task_id
)
item.task_id = task if task else False
| 38.103175 | 4,801 |
10,204 | py | PYTHON | 15.0 | # Copyright 2022-2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class ProjectTask(models.Model):
_inherit = "project.task"
scrap_ids = fields.One2many(
comodel_name="stock.scrap", inverse_name="task_id", string="Scraps"
)
scrap_count = fields.Integer(
compute="_compute_scrap_move_count", string="Scrap Move"
)
move_ids = fields.One2many(
comodel_name="stock.move",
inverse_name="raw_material_task_id",
string="Stock Moves",
copy=False,
domain=[("scrapped", "=", False)],
)
use_stock_moves = fields.Boolean(related="stage_id.use_stock_moves")
done_stock_moves = fields.Boolean(related="stage_id.done_stock_moves")
stock_moves_is_locked = fields.Boolean(default=True)
allow_moves_action_confirm = fields.Boolean(
compute="_compute_allow_moves_action_confirm"
)
allow_moves_action_assign = fields.Boolean(
compute="_compute_allow_moves_action_assign"
)
stock_state = fields.Selection(
selection=[
("pending", "Pending"),
("confirmed", "Confirmed"),
("assigned", "Assigned"),
("done", "Done"),
("cancel", "Cancel"),
],
compute="_compute_stock_state",
)
picking_type_id = fields.Many2one(
comodel_name="stock.picking.type",
string="Operation Type",
readonly=False,
domain="[('company_id', '=', company_id)]",
index=True,
check_company=True,
)
location_id = fields.Many2one(
comodel_name="stock.location",
string="Source Location",
readonly=False,
index=True,
check_company=True,
)
location_dest_id = fields.Many2one(
comodel_name="stock.location",
string="Destination Location",
readonly=False,
index=True,
check_company=True,
)
stock_analytic_date = fields.Date(string="Analytic date")
unreserve_visible = fields.Boolean(
string="Allowed to Unreserve Inventory",
compute="_compute_unreserve_visible",
help="Technical field to check when we can unreserve",
)
stock_analytic_account_id = fields.Many2one(
comodel_name="account.analytic.account",
string="Move Analytic Account",
help="Move created will be assigned to this analytic account",
)
stock_analytic_tag_ids = fields.Many2many(
comodel_name="account.analytic.tag",
relation="account_analytic_tag_project_task_stock_rel",
column1="project_task_id",
column2="account_analytic_tag_id",
string="Move Analytic Tags",
)
stock_analytic_line_ids = fields.One2many(
comodel_name="account.analytic.line",
inverse_name="stock_task_id",
string="Analytic Lines",
)
group_id = fields.Many2one(
comodel_name="procurement.group",
)
def _compute_scrap_move_count(self):
data = self.env["stock.scrap"].read_group(
[("task_id", "in", self.ids)], ["task_id"], ["task_id"]
)
count_data = {item["task_id"][0]: item["task_id_count"] for item in data}
for item in self:
item.scrap_count = count_data.get(item.id, 0)
@api.depends("move_ids", "move_ids.state")
def _compute_allow_moves_action_confirm(self):
for item in self:
item.allow_moves_action_confirm = any(
move.state == "draft" for move in item.move_ids
)
@api.depends("move_ids", "move_ids.state")
def _compute_allow_moves_action_assign(self):
for item in self:
item.allow_moves_action_assign = any(
move.state in ("confirmed", "partially_available")
for move in item.move_ids
)
@api.depends("move_ids", "move_ids.state")
def _compute_stock_state(self):
for task in self:
task.stock_state = "pending"
if task.move_ids:
states = task.mapped("move_ids.state")
for state in ("confirmed", "assigned", "done", "cancel"):
if state in states:
task.stock_state = state
break
@api.depends("move_ids", "move_ids.quantity_done")
def _compute_unreserve_visible(self):
for item in self:
already_reserved = item.mapped("move_ids.move_line_ids")
any_quantity_done = any([m.quantity_done > 0 for m in item.move_ids])
item.unreserve_visible = not any_quantity_done and already_reserved
def _set_procurement_group_id(self):
"""We use this method to auto-set group_id always and use it in other addons."""
self.ensure_one()
if not self.group_id:
self.group_id = self.env["procurement.group"].create(
self._prepare_procurement_group_vals()
)
@api.onchange("picking_type_id")
def _onchange_picking_type_id(self):
self.location_id = self.picking_type_id.default_location_src_id.id
self.location_dest_id = self.picking_type_id.default_location_dest_id.id
def _check_tasks_with_pending_moves(self):
if self.move_ids and "assigned" in self.mapped("move_ids.state"):
raise UserError(
_("It is not possible to change this with reserved movements in tasks.")
)
def _update_moves_info(self):
for item in self:
item._check_tasks_with_pending_moves()
picking_type = item.picking_type_id or item.project_id.picking_type_id
location = item.location_id or item.project_id.location_id
location_dest = item.location_dest_id or item.project_id.location_dest_id
moves = item.move_ids.filtered(
lambda x: x.state not in ("cancel", "done")
and (x.location_id != location or x.location_dest_id != location_dest)
)
moves.update(
{
"warehouse_id": location.warehouse_id.id,
"location_id": location.id,
"location_dest_id": location_dest.id,
"picking_type_id": picking_type.id,
}
)
self.action_assign()
@api.model
def _prepare_procurement_group_vals(self):
return {"name": "Task-ID: %s" % self.id}
def action_confirm(self):
self.mapped("move_ids")._action_confirm()
def action_assign(self):
self.action_confirm()
self.mapped("move_ids")._action_assign()
def button_scrap(self):
self.ensure_one()
move_items = self.move_ids.filtered(lambda x: x.state not in ("done", "cancel"))
return {
"name": _("Scrap"),
"view_mode": "form",
"res_model": "stock.scrap",
"view_id": self.env.ref("stock.stock_scrap_form_view2").id,
"type": "ir.actions.act_window",
"context": {
"default_task_id": self.id,
"product_ids": move_items.mapped("product_id").ids,
"default_company_id": self.company_id.id,
},
"target": "new",
}
def do_unreserve(self):
for item in self:
item.move_ids.filtered(
lambda x: x.state not in ("done", "cancel")
)._do_unreserve()
return True
def button_unreserve(self):
self.ensure_one()
self.do_unreserve()
return True
def action_cancel(self):
"""Cancel the stock moves and remove the analytic lines created from
stock moves when cancelling the task.
"""
self.mapped("move_ids.move_line_ids").write({"qty_done": 0})
# Use sudo to avoid error for users with no access to analytic
self.sudo().stock_analytic_line_ids.unlink()
self.stock_moves_is_locked = True
return True
def action_toggle_stock_moves_is_locked(self):
self.ensure_one()
self.stock_moves_is_locked = not self.stock_moves_is_locked
return True
def action_done(self):
for move in self.mapped("move_ids"):
move.quantity_done = move.reserved_availability
self.mapped("move_ids")._action_done()
# Use sudo to avoid error for users with no access to analytic
analytic_line_model = self.env["account.analytic.line"].sudo()
for move in self.move_ids.filtered(lambda x: x.state == "done"):
vals = move._prepare_analytic_line_from_task()
if vals:
analytic_line_model.create(vals)
def action_see_move_scrap(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_stock_scrap")
action["domain"] = [("task_id", "=", self.id)]
action["context"] = dict(self._context, default_origin=self.name)
return action
def write(self, vals):
res = super().write(vals)
if "stage_id" in vals:
stage = self.env["project.task.type"].browse(vals.get("stage_id"))
if stage.done_stock_moves:
# Avoid permissions error if the user does not have access to stock.
self.sudo().action_assign()
# Update info
field_names = ("location_id", "location_dest_id")
if any(vals.get(field) for field in field_names):
self._update_moves_info()
return res
def unlink(self):
# Use sudo to avoid error to users with no access to analytic
# related to hr_timesheet addon
return super(ProjectTask, self.sudo()).unlink()
class ProjectTaskType(models.Model):
_inherit = "project.task.type"
use_stock_moves = fields.Boolean(
help="If you mark this check, when a task goes to this state, "
"it will use stock moves",
)
done_stock_moves = fields.Boolean(
help="If you check this box, when a task is in this state, you will not "
"be able to add more stock moves but they can be viewed."
)
| 37.369963 | 10,202 |
1,594 | py | PYTHON | 15.0 | # Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import api, fields, models
class ProjectProject(models.Model):
_inherit = "project.project"
picking_type_id = fields.Many2one(
comodel_name="stock.picking.type",
string="Operation Type",
readonly=False,
domain="[('company_id', '=', company_id)]",
index=True,
check_company=True,
)
location_id = fields.Many2one(
comodel_name="stock.location",
string="Source Location",
readonly=False,
check_company=True,
index=True,
help="Default location from which materials are consumed.",
)
location_dest_id = fields.Many2one(
comodel_name="stock.location",
string="Destination Location",
readonly=False,
index=True,
check_company=True,
help="Default location to which materials are consumed.",
)
stock_analytic_date = fields.Date(string="Analytic date")
@api.onchange("picking_type_id")
def _onchange_picking_type_id(self):
self.location_id = self.picking_type_id.default_location_src_id.id
self.location_dest_id = self.picking_type_id.default_location_dest_id.id
def write(self, vals):
"""Update location information on pending moves when changed."""
res = super().write(vals)
field_names = ("location_id", "location_dest_id")
if any(vals.get(field) for field in field_names):
self.task_ids._update_moves_info()
return res
| 34.608696 | 1,592 |
844 | py | PYTHON | 15.0 | # Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class AccountAnalyticLine(models.Model):
_inherit = "account.analytic.line"
stock_task_id = fields.Many2one(
comodel_name="project.task", string="Project Task", ondelete="cascade"
)
def _timesheet_postprocess_values(self, values):
"""When hr_timesheet addon is installed, in the create() and write() methods,
the amount is recalculated according to the employee cost.
We need to force that in the records related to stock tasks the price is not
updated."""
res = super()._timesheet_postprocess_values(values)
for key in self.filtered(lambda x: x.stock_task_id).ids:
res[key].pop("amount", None)
return res
| 40.095238 | 842 |
450 | py | PYTHON | 15.0 | # Copyright 2016-2017 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
def post_init_hook(cr, registry):
"""Put the date with 00:00:00 as the date_time for the line."""
cr.execute(
"""UPDATE account_analytic_line
SET date_time = to_timestamp(date || ' 00:00:00',
'YYYY/MM/DD HH24:MI:SS')
WHERE date(date_time) != date
"""
)
| 34.615385 | 450 |
1,005 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa - Antonio Espinosa
# Copyright 2016 Tecnativa - Sergio Teruel
# Copyright 2016-2018 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Ernesto Tejeda
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Project timesheet time control",
"version": "15.0.1.1.1",
"category": "Project",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"maintainers": ["ernestotejeda"],
"website": "https://github.com/OCA/project",
"depends": [
"hr_timesheet_task_domain",
"hr_timesheet_task_stage",
"web_ir_actions_act_multi",
"web_ir_actions_act_view_reload",
],
"data": [
"security/ir.model.access.csv",
"views/account_analytic_line_view.xml",
"views/project_project_view.xml",
"views/project_task_view.xml",
"wizards/hr_timesheet_switch_view.xml",
],
"license": "AGPL-3",
"installable": True,
"post_init_hook": "post_init_hook",
}
| 33.5 | 1,005 |
13,178 | py | PYTHON | 15.0 | # Copyright 2016-2018 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0
from datetime import date, datetime, timedelta
from odoo import exceptions
from odoo.tests import Form, common
from odoo.tools.float_utils import float_compare
class TestProjectTimesheetTimeControl(common.TransactionCase):
def setUp(self):
super().setUp()
admin = self.browse_ref("base.user_admin")
# Stop any timer running
self.env["account.analytic.line"].search(
[
("date_time", "!=", False),
("user_id", "=", admin.id),
("project_id.allow_timesheets", "=", True),
("unit_amount", "=", 0),
]
).button_end_work()
admin.groups_id |= self.browse_ref("hr_timesheet.group_hr_timesheet_user")
self.uid = admin.id
self.other_employee = self.env["hr.employee"].create({"name": "Somebody else"})
self.project = self.env["project.project"].create(
{"name": "Test project", "allow_timesheets": True}
)
self.project_without_timesheets = self.env["project.project"].create(
{"name": "Test project", "allow_timesheets": False}
)
self.analytic_account = self.project.analytic_account_id
self.task = self.env["project.task"].create(
{"name": "Test task", "project_id": self.project.id}
)
self.line = self.env["account.analytic.line"].create(
{
"date_time": datetime.now() - timedelta(hours=1),
"task_id": self.task.id,
"project_id": self.project.id,
"account_id": self.analytic_account.id,
"name": "Test line",
}
)
def _create_wizard(self, action, active_record):
"""Create a new hr.timesheet.switch wizard in the specified context.
:param dict action: Action definition that creates the wizard.
:param active_record: Record being browsed when creating the wizard.
"""
self.assertEqual(action["res_model"], "hr.timesheet.switch")
self.assertEqual(action["target"], "new")
self.assertEqual(action["type"], "ir.actions.act_window")
self.assertEqual(action["view_mode"], "form")
self.assertEqual(action["view_type"], "form")
wiz_form = Form(
active_record.env[action["res_model"]].with_context(
active_id=active_record.id,
active_ids=active_record.ids,
active_model=active_record._name,
**action.get("context", {}),
)
)
return wiz_form.save()
def test_aal_from_other_employee_no_button(self):
"""Lines from other employees have no resume/stop button."""
self.line.employee_id = self.other_employee
self.assertFalse(self.line.show_time_control)
def test_create_analytic_line(self):
line = self._create_analytic_line(datetime(2016, 3, 24, 3), tz="EST")
self.assertEqual(line.date, date(2016, 3, 23))
def test_create_analytic_line_with_string_datetime(self):
line = self._create_analytic_line("2016-03-24 03:00:00", tz="EST")
self.assertEqual(line.date, date(2016, 3, 23))
def test_write_analytic_line(self):
line = self._create_analytic_line(datetime.now())
line.with_context(tz="EST").date_time = "2016-03-24 03:00:00"
self.assertEqual(line.date, date(2016, 3, 23))
def test_write_analytic_line_with_string_datetime(self):
line = self._create_analytic_line(datetime.now())
line.with_context(tz="EST").date_time = datetime(2016, 3, 24, 3)
self.assertEqual(line.date, date(2016, 3, 23))
def _create_analytic_line(self, datetime_, tz=None):
return (
self.env["account.analytic.line"]
.with_context(tz=tz)
.create(
{
"date_time": datetime_,
"project_id": self.project.id,
"name": "Test line",
}
)
)
def test_aal_time_control_flow(self):
"""Test account.analytic.line time controls."""
# Duration == 0, stop the timer
self.assertFalse(self.line.unit_amount)
self.assertEqual(self.line.show_time_control, "stop")
self.line.button_end_work()
# Duration > 0, cannot stop it
self.assertTrue(self.line.unit_amount)
with self.assertRaises(exceptions.UserError):
self.line.button_end_work()
# Open a new running AAL without wizard
running_timer = self.line.copy({"unit_amount": False})
# Use resume wizard
self.line.invalidate_cache()
self.assertEqual(self.line.show_time_control, "resume")
resume_action = self.line.button_resume_work()
wizard = self._create_wizard(resume_action, self.line)
self.assertLessEqual(wizard.date_time, datetime.now())
self.assertEqual(wizard.analytic_line_id, self.line)
self.assertEqual(wizard.name, self.line.name)
self.assertEqual(wizard.project_id, self.line.project_id)
self.assertEqual(wizard.running_timer_id, running_timer)
self.assertEqual(wizard.task_id, self.line.task_id)
# Changing start time changes expected duration
wizard.date_time = running_timer.date_time + timedelta(minutes=30)
self.assertEqual(wizard.running_timer_duration, 0.5)
wizard.date_time = running_timer.date_time + timedelta(hours=2)
self.assertEqual(wizard.running_timer_duration, 2)
# Stop old timer, start new one
new_act = wizard.with_context(show_created_timer=True).action_switch()
new_line = self.env[new_act["res_model"]].browse(new_act["res_id"])
self.assertEqual(
new_line.date_time, running_timer.date_time + timedelta(hours=2)
)
self.assertEqual(new_line.employee_id, running_timer.employee_id)
self.assertEqual(new_line.project_id, running_timer.project_id)
self.assertEqual(new_line.task_id, running_timer.task_id)
self.assertEqual(new_line.unit_amount, 0)
self.assertEqual(running_timer.unit_amount, 2)
def test_aal_without_start_resume_button(self):
"""If a line has no start date, can only resume it."""
self.assertEqual(self.line.show_time_control, "stop")
self.line.date_time = False
self.line.invalidate_cache()
self.assertEqual(self.line.show_time_control, "resume")
def test_error_multiple_running_timers(self):
"""If there are multiple running timers, I don't know which to stop."""
self.line.copy({})
self.line.copy({})
self.line.button_end_work()
resume_action = self.line.button_resume_work()
with self.assertRaises(exceptions.UserError):
self._create_wizard(resume_action, self.line)
def test_project_time_control_flow(self):
"""Test project.project time controls."""
# Resuming a project will try to find lines without task
line_without_task = self.line.copy(
{"task_id": False, "project_id": self.project.id, "name": "No task here"}
)
self.assertFalse(line_without_task.unit_amount)
# Multiple running lines found, no buttons
self.assertFalse(self.project.show_time_control)
# Stop line without task, now we see stop button
line_without_task.button_end_work()
self.project.invalidate_cache()
self.assertEqual(self.project.show_time_control, "stop")
self.project.button_end_work()
# No more running lines, cannot stop again
with self.assertRaises(exceptions.UserError):
self.project.button_end_work()
# All lines stopped, start new one
self.project.invalidate_cache()
self.assertEqual(self.project.show_time_control, "start")
start_action = self.project.button_start_work()
wizard = self._create_wizard(start_action, self.project)
self.assertLessEqual(wizard.date_time, datetime.now())
self.assertEqual(
wizard.analytic_line_id.account_id, self.project.analytic_account_id
)
self.assertEqual(wizard.name, "No task here")
self.assertEqual(wizard.project_id, self.project)
self.assertFalse(wizard.running_timer_id, self.line)
self.assertFalse(wizard.task_id)
new_act = wizard.with_context(show_created_timer=True).action_switch()
new_line = self.env[new_act["res_model"]].browse(new_act["res_id"])
self.assertEqual(new_line.employee_id, self.env.user.employee_ids)
self.assertEqual(new_line.project_id, self.project)
self.assertFalse(new_line.task_id)
self.assertEqual(new_line.unit_amount, 0)
self.assertTrue(self.line.unit_amount)
# Projects without timesheets show no buttons
self.assertFalse(self.project_without_timesheets.show_time_control)
def test_task_time_control_flow(self):
"""Test project.task time controls."""
# Running line found, stop the timer
self.assertEqual(self.task.show_time_control, "stop")
self.task.button_end_work()
# No more running lines, cannot stop again
with self.assertRaises(exceptions.UserError):
self.task.button_end_work()
# All lines stopped, start new one
self.task.invalidate_cache()
self.assertEqual(self.task.show_time_control, "start")
start_action = self.task.button_start_work()
wizard = self._create_wizard(start_action, self.task)
self.assertLessEqual(wizard.date_time, datetime.now())
self.assertEqual(
wizard.analytic_line_id.account_id, self.task.project_id.analytic_account_id
)
self.assertEqual(wizard.name, self.line.name)
self.assertEqual(wizard.project_id, self.task.project_id)
self.assertEqual(wizard.task_id, self.task)
new_act = wizard.with_context(show_created_timer=True).action_switch()
new_line = self.env[new_act["res_model"]].browse(new_act["res_id"])
self.assertEqual(new_line.employee_id, self.env.user.employee_ids)
self.assertEqual(new_line.project_id, self.project)
self.assertEqual(new_line.task_id, self.task)
self.assertEqual(new_line.unit_amount, 0)
self.assertTrue(self.line.unit_amount)
def test_wizard_standalone(self):
"""Standalone wizard usage works properly."""
# It detects the running timer
wizard = self.env["hr.timesheet.switch"].create(
{"name": "Standalone 1", "project_id": self.project.id}
)
self.assertEqual(wizard.running_timer_id, self.line)
self.assertTrue(wizard.running_timer_duration)
new_act = wizard.with_context(show_created_timer=True).action_switch()
new_line = self.env[new_act["res_model"]].browse(new_act["res_id"])
self.assertEqual(new_line.name, "Standalone 1")
self.assertEqual(new_line.project_id, self.project)
# It also works if there is no running timer
new_line.button_end_work()
wizard = (
self.env["hr.timesheet.switch"]
.with_context(active_model="unknown", active_id=1)
.create({"name": "Standalone 2", "project_id": self.project.id})
)
self.assertFalse(wizard.running_timer_id)
self.assertFalse(wizard.running_timer_duration)
new_act = wizard.action_switch()
self.assertEqual(
new_act,
{
"type": "ir.actions.act_multi",
"actions": [
{"type": "ir.actions.act_window_close"},
{"type": "ir.actions.act_view_reload"},
],
},
)
new_line = self.env["account.analytic.line"].search(
[
("name", "=", "Standalone 2"),
("project_id", "=", self.project.id),
("unit_amount", "=", 0),
("employee_id", "=", self.line.employee_id.id),
]
)
self.assertEqual(len(new_line), 1)
def test_start_end_time(self):
line = self.line.copy(
{"task_id": False, "project_id": self.project.id, "name": "No task here"}
)
line.date_time = datetime(2020, 8, 1, 10, 0, 0)
line.unit_amount = 2.0
self.assertTrue(line.date_time_end == datetime(2020, 8, 1, 12, 0, 0))
line.date_time_end = datetime(2020, 8, 1, 15, 0, 0)
self.assertFalse(float_compare(line.unit_amount, 5.0, precision_digits=2))
def test_non_timesheet_analytic_line(self):
line = self.env["account.analytic.line"].create(
{
"project_id": self.project.id,
"account_id": self.analytic_account.id,
"name": "Test non-timesheet line",
"product_uom_id": self.env.ref("uom.product_uom_gram").id,
}
)
line.unit_amount = 500.0
self.assertFalse(line.date_time_end)
| 45.441379 | 13,178 |
2,807 | py | PYTHON | 15.0 | # Copyright 2019 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class HrTimesheetTimeControlMixin(models.AbstractModel):
_name = "hr.timesheet.time_control.mixin"
_description = "Mixin for records related with timesheet lines"
show_time_control = fields.Selection(
selection=[("start", "Start"), ("stop", "Stop")],
compute="_compute_show_time_control",
help="Indicate which time control button to show, if any.",
)
@api.model
def _relation_with_timesheet_line(self):
"""Name of the field that relates this model with AAL."""
raise NotImplementedError
@api.model
def _timesheet_running_domain(self):
"""Domain to find running timesheet lines."""
return self.env["account.analytic.line"]._running_domain() + [
(self._relation_with_timesheet_line(), "in", self.ids),
]
def _compute_show_time_control(self):
"""Decide which time control button to show, if any."""
related_field = self._relation_with_timesheet_line()
grouped = self.env["account.analytic.line"].read_group(
domain=self._timesheet_running_domain(),
fields=["id"],
groupby=[related_field],
)
lines_per_record = {
group[related_field][0]: group["%s_count" % related_field]
for group in grouped
}
button_per_lines = {0: "start", 1: "stop"}
for record in self:
record.show_time_control = button_per_lines.get(
lines_per_record.get(record.id, 0),
False,
)
def button_start_work(self):
"""Create a new record starting now, with a running timer."""
related_field = self._relation_with_timesheet_line()
return {
"context": {"default_%s" % related_field: self.id},
"name": _("Start work"),
"res_model": "hr.timesheet.switch",
"target": "new",
"type": "ir.actions.act_window",
"view_mode": "form",
"view_type": "form",
}
def button_end_work(self):
running_lines = self.env["account.analytic.line"].search(
self._timesheet_running_domain(),
)
if not running_lines:
model = self.env["ir.model"].sudo().search([("model", "=", self._name)])
message = _(
"No running timer found in %(model)s %(record)s. "
"Refresh the page and check again."
)
raise UserError(
message % {"model": model.name, "record": self.display_name}
)
return running_lines.button_end_work()
| 37.426667 | 2,807 |
985 | py | PYTHON | 15.0 | # Copyright 2019 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class ProjectTask(models.Model):
_name = "project.task"
_inherit = ["project.task", "hr.timesheet.time_control.mixin"]
@api.model
def _relation_with_timesheet_line(self):
return "task_id"
@api.depends(
"project_id.allow_timesheets",
"timesheet_ids.employee_id",
"timesheet_ids.unit_amount",
)
def _compute_show_time_control(self):
result = super()._compute_show_time_control()
for task in self:
# Never show button if timesheets are not allowed in project
if not task.project_id.allow_timesheets:
task.show_time_control = False
return result
def button_start_work(self):
result = super().button_start_work()
result["context"].update({"default_project_id": self.project_id.id})
return result
| 31.774194 | 985 |
957 | py | PYTHON | 15.0 | # Copyright 2019 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class ProjectProject(models.Model):
_name = "project.project"
_inherit = ["project.project", "hr.timesheet.time_control.mixin"]
@api.model
def _relation_with_timesheet_line(self):
return "project_id"
@api.depends("allow_timesheets")
def _compute_show_time_control(self):
result = super()._compute_show_time_control()
for project in self:
# Never show button if timesheets are not allowed in project
if not project.allow_timesheets:
project.show_time_control = False
return result
def button_start_work(self):
result = super().button_start_work()
# When triggering from project is usually to start timer without task
result["context"].update({"default_task_id": False})
return result
| 34.178571 | 957 |
4,380 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa - Antonio Espinosa
# Copyright 2016 Tecnativa - Sergio Teruel
# Copyright 2016-2018 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class AccountAnalyticLine(models.Model):
_inherit = "account.analytic.line"
_order = "date_time desc"
date_time = fields.Datetime(
string="Start Time", default=fields.Datetime.now, copy=False
)
date_time_end = fields.Datetime(
string="End Time",
compute="_compute_date_time_end",
inverse="_inverse_date_time_end",
)
show_time_control = fields.Selection(
selection=[("resume", "Resume"), ("stop", "Stop")],
compute="_compute_show_time_control",
help="Indicate which time control button to show, if any.",
)
@api.depends("date_time", "unit_amount", "product_uom_id")
def _compute_date_time_end(self):
hour_uom = self.env.ref("uom.product_uom_hour")
for record in self:
if (
record.product_uom_id == hour_uom
and record.date_time
and record.unit_amount
):
record.date_time_end = record.date_time + relativedelta(
hours=record.unit_amount
)
else:
record.date_time_end = record.date_time_end
def _inverse_date_time_end(self):
hour_uom = self.env.ref("uom.product_uom_hour")
for record in self.filtered(lambda x: x.date_time and x.date_time_end):
if record.product_uom_id == hour_uom:
record.unit_amount = (
record.date_time_end - record.date_time
).seconds / 3600
@api.model
def _eval_date(self, vals):
if vals.get("date_time"):
return dict(vals, date=self._convert_datetime_to_date(vals["date_time"]))
return vals
def _convert_datetime_to_date(self, datetime_):
if isinstance(datetime_, str):
datetime_ = fields.Datetime.from_string(datetime_)
return fields.Date.context_today(self, datetime_)
@api.model
def _running_domain(self):
"""Domain to find running timesheet lines."""
return [
("date_time", "!=", False),
("user_id", "=", self.env.user.id),
("project_id.allow_timesheets", "=", True),
("unit_amount", "=", 0),
]
@api.model
def _duration(self, start, end):
"""Compute float duration between start and end."""
try:
return (end - start).total_seconds() / 3600
except TypeError:
return 0
@api.depends("employee_id", "unit_amount")
def _compute_show_time_control(self):
"""Decide when to show time controls."""
for one in self:
if one.employee_id not in self.env.user.employee_ids:
one.show_time_control = False
elif one.unit_amount or not one.date_time:
one.show_time_control = "resume"
else:
one.show_time_control = "stop"
@api.model_create_multi
def create(self, vals_list):
return super().create(list(map(self._eval_date, vals_list)))
def write(self, vals):
return super().write(self._eval_date(vals))
def button_resume_work(self):
"""Create a new record starting now, with a running timer."""
return {
"name": _("Resume work"),
"res_model": "hr.timesheet.switch",
"target": "new",
"type": "ir.actions.act_window",
"view_mode": "form",
"view_type": "form",
}
def button_end_work(self):
end = fields.Datetime.to_datetime(
self.env.context.get("stop_dt", datetime.now())
)
for line in self:
if line.unit_amount:
raise UserError(
_(
"Cannot stop timer %d because it is not running. "
"Refresh the page and check again."
)
% line.id
)
line.unit_amount = line._duration(line.date_time, end)
return True
| 34.488189 | 4,380 |
7,781 | py | PYTHON | 15.0 | # Copyright 2019 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.osv import expression
class HrTimesheetSwitch(models.TransientModel):
_name = "hr.timesheet.switch"
_description = "Helper to quickly switch between timesheet lines"
def _domain_project_id(self):
domain = [("allow_timesheets", "=", True)]
if not self.user_has_groups("hr_timesheet.group_timesheet_manager"):
return expression.AND(
[
domain,
[
"|",
("privacy_visibility", "!=", "followers"),
("message_partner_ids", "in", [self.env.user.partner_id.id]),
],
]
)
return domain
analytic_line_id = fields.Many2one(
comodel_name="account.analytic.line", string="Origin line"
)
name = fields.Char(string="Description", required=True)
date_time = fields.Datetime(
string="Start Time", default=fields.Datetime.now, required=True
)
date_time_end = fields.Datetime(string="End Time")
task_id = fields.Many2one(
comodel_name="project.task",
string="Task",
compute="_compute_task_id",
store=True,
readonly=False,
index=True,
domain="""
[
('company_id', '=', company_id),
('project_id.allow_timesheets', '=', True),
('project_id', '=?', project_id)
]
""",
)
project_id = fields.Many2one(
comodel_name="project.project",
string="Project",
compute="_compute_project_id",
store=True,
readonly=False,
domain=_domain_project_id,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
required=True,
readonly=True,
default=lambda self: self.env.company,
)
running_timer_id = fields.Many2one(
comodel_name="account.analytic.line",
string="Previous timer",
ondelete="cascade",
readonly=True,
default=lambda self: self._default_running_timer_id(),
help="This timer is running and will be stopped",
)
running_timer_start = fields.Datetime(
string="Previous timer start",
related="running_timer_id.date_time",
readonly=True,
)
running_timer_duration = fields.Float(
string="Previous timer duration",
compute="_compute_running_timer_duration",
help="When the previous timer is stopped, it will save this duration.",
)
@api.depends("task_id", "task_id.project_id")
def _compute_project_id(self):
for line in self.filtered(lambda line: not line.project_id):
line.project_id = line.task_id.project_id
@api.depends("project_id")
def _compute_task_id(self):
for line in self.filtered(lambda line: not line.project_id):
line.task_id = False
@api.model
def _default_running_timer_id(self, employee=None):
"""Obtain running timer."""
employee = employee or self.env.user.employee_ids
# Find running work
running = self.env["account.analytic.line"].search(
[
("date_time", "!=", False),
("employee_id", "in", employee.ids),
("id", "not in", self.env.context.get("resuming_lines", [])),
("project_id", "!=", False),
("unit_amount", "=", 0),
]
)
if len(running) > 1:
raise UserError(
_(
"%d running timers found. Cannot know which one to stop. "
"Please stop them manually."
)
% len(running)
)
return running
@api.depends("date_time", "running_timer_id")
def _compute_running_timer_duration(self):
"""Compute duration of running timer when stopped."""
for one in self:
one.running_timer_duration = 0.0
if one.running_timer_id:
one.running_timer_duration = one.running_timer_id._duration(
one.running_timer_id.date_time,
one.date_time,
)
@api.model
def _closest_suggestion(self):
"""Find most similar account.analytic.line record."""
context = self.env.context
model = "account.analytic.line"
domain = [("employee_id", "in", self.env.user.employee_ids.ids)]
if context.get("active_model") == model:
return self.env[model].browse(context["active_id"])
elif context.get("active_model") == "project.task":
domain.append(("task_id", "=", context["active_id"]))
elif context.get("active_model") == "project.project":
domain += [
("project_id", "=", context["active_id"]),
("task_id", "=", False),
]
else:
return self.env[model]
return self.env["account.analytic.line"].search(
domain,
order="date_time DESC",
limit=1,
)
def _prepare_default_values(self, account_analytic_line):
return {
"analytic_line_id": account_analytic_line.id,
"name": account_analytic_line.name,
"project_id": account_analytic_line.project_id.id,
"task_id": account_analytic_line.task_id.id,
}
@api.model
def default_get(self, fields_list):
"""Return defaults depending on the context where it is called."""
result = super().default_get(fields_list)
inherited = self._closest_suggestion()
if inherited:
result.update(self._prepare_default_values(inherited))
return result
def _prepare_copy_values(self, record):
"""Return the values that will be overwritten in new timesheet entry."""
return {
"name": record.name,
"date_time": record.date_time,
"date_time_end": record.date_time_end,
"project_id": record.project_id.id,
"task_id": record.task_id.id,
"unit_amount": 0,
}
def action_switch(self):
"""Stop old timer, start new one."""
self.ensure_one()
# Stop old timer
self.with_context(
resuming_lines=self.ids,
stop_dt=self.date_time,
).running_timer_id.button_end_work()
# Start new timer
if self.analytic_line_id:
new = self.analytic_line_id.copy(self._prepare_copy_values(self))
else:
fields = self.env["account.analytic.line"]._fields.keys()
vals = self.env["account.analytic.line"].default_get(fields)
vals.update(self._prepare_copy_values(self))
new = self.env["account.analytic.line"].create(vals)
# Display created timer record if requested
if self.env.context.get("show_created_timer"):
form_view = self.env.ref("hr_timesheet.hr_timesheet_line_form")
return {
"res_id": new.id,
"res_model": new._name,
"type": "ir.actions.act_window",
"view_mode": "form",
"view_type": "form",
"views": [(form_view.id, "form")],
}
# Close wizard and reload view
return {
"type": "ir.actions.act_multi",
"actions": [
{"type": "ir.actions.act_window_close"},
{"type": "ir.actions.act_view_reload"},
],
}
| 36.190698 | 7,781 |
648 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Project Template & Milestone",
"summary": """Adds function to copy of milestones when creating
a project from template""",
"author": "Patrick Wilson, Odoo Community Association (OCA),"
"Open Source Integrators",
"website": "https://github.com/OCA/project",
"category": "Project Management",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["project_template", "project_milestone"],
"application": False,
"auto_install": True,
"development_status": "Beta",
"maintainers": ["patrickrwilson"],
}
| 36 | 648 |
3,140 | py | PYTHON | 15.0 | # Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# Copyright (C) 2021 Open Source Integrators
# Copyright (C) 2021 Serpent Consulting Services
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import common
class TestProjectTemplate(common.TransactionCase):
def setUp(self):
super().setUp()
self.test_customer = self.env["res.partner"].create({"name": "TestCustomer"})
# Create project with 2 milestones
self.test_project = self.env["project.project"].create(
{
"name": "TestProject",
"alias_name": "test_alias",
"partner_id": self.test_customer.id,
}
)
self.test_milestone_1 = self.env["project.milestone"].create(
{"name": "Test_Milestone_1", "project_id": self.test_project.id}
)
self.test_milestone_2 = self.env["project.milestone"].create(
{"name": "Test_Milestone_2", "project_id": self.test_project.id}
)
# Create 2 tasks for milestone 1
self.env["project.task"].create(
{
"name": "TestTask_1",
"project_id": self.test_project.id,
"milestone_id": self.test_milestone_1.id,
}
)
self.env["project.task"].create(
{
"name": "TestTask_2",
"project_id": self.test_project.id,
"milestone_id": self.test_milestone_1.id,
}
)
# Create 1 tasks for milestone 2
self.env["project.task"].create(
{
"name": "TestTask_3",
"project_id": self.test_project.id,
"milestone_id": self.test_milestone_2.id,
}
)
# TEST 01: Create project from template and verify milestones & tasks
def test_create_project_from_template(self):
# Set Project Template
project_01 = self.test_project
project_01.is_template = True
project_01.on_change_is_template()
# Create new Project from Template
project_01.create_project_from_template()
new_project = self.env["project.project"].search(
[("name", "=", "TestProject (COPY)")]
)
# Verify that the project was created successfully
self.assertEqual(len(new_project), 1)
# Verify that the Milestones were created successfully
self.assertEqual(len(new_project.milestone_ids), 2)
# Verify that the tasks were created successfully with milestones
task_milestone_1_ids = self.env["project.task"].search(
[
("milestone_id.name", "=", "Test_Milestone_1"),
("project_id", "=", new_project.id),
]
)
self.assertEqual(len(task_milestone_1_ids), 2)
task_milestone_2_ids = self.env["project.task"].search(
[
("milestone_id.name", "=", "Test_Milestone_2"),
("project_id", "=", new_project.id),
]
)
self.assertEqual(len(task_milestone_2_ids), 1)
| 35.681818 | 3,140 |
957 | py | PYTHON | 15.0 | # Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# Copyright (C) 2021 Open Source Integrators
# Copyright (C) 2021 Serpent Consulting Services
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class ProjectTemplate(models.Model):
_inherit = "project.project"
def create_project_from_template(self):
self.ensure_one()
res = super().create_project_from_template()
project = self.browse(res["res_id"])
for milestone in self.milestone_ids:
milestone.copy(default={"project_id": project.id})
# LINK THE NEWLY CREATED TASKS TO THE NEWLY CREATED MILESTONES
for new_task_record in project.task_ids:
for new_milestone_record in project.milestone_ids:
if new_task_record.milestone_id.name == new_milestone_record.name:
new_task_record.milestone_id = new_milestone_record.id
return res
| 41.608696 | 957 |
639 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Project Forecast Lines Bokeh Chart",
"summary": "Project Forecast Lines Bokeh Chart",
"version": "15.0.1.0.2",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Project",
"website": "https://github.com/OCA/project",
"depends": ["project_forecast_line", "web_widget_bokeh_chart"],
"data": [
"security/ir.model.access.csv",
"report/forecast_line_reporting_views.xml",
],
"development_status": "Alpha",
"installable": True,
}
| 35.5 | 639 |
8,504 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import json
# pylint: disable=W7936
from bokeh import palettes
from bokeh.embed import components
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
from odoo.tools import date_utils
class ForecastLineReporting(models.TransientModel):
_name = "forecast.line.reporting"
_description = "Forecast reporting wizard"
bokeh_chart = fields.Text(compute="_compute_bokeh_chart")
date_from = fields.Date(default=fields.Date.today)
nb_months = fields.Integer(default=2)
granularity = fields.Selection(
[("day", "Day"), ("week", "Week"), ("month", "Month")],
default=lambda r: r.env.company.forecast_line_granularity,
required=True,
)
employee_ids = fields.Many2many("hr.employee")
project_ids = fields.Many2many(
"project.project",
help="Setting this will automatically add "
"all employees assigned to tasks on the project",
)
@api.onchange("project_ids")
def onchange_project_ids(self):
if self.project_ids:
self.employee_ids |= self.project_ids.mapped(
"task_ids.user_ids.employee_ids"
)
@api.depends("date_from", "nb_months", "employee_ids", "granularity", "project_ids")
def _compute_bokeh_chart(self):
"""compute the chart to be displayed"""
# the current implementation shows 1 chart per selected employee over
# the next nb_month months with the selected granularity. For each
# employee, the chart displays the consolidated_forecast field
# grouped by project on which the employee is planned for a given
# period.
plots = self._build_plots()
grid = column(*plots)
script, div = components(grid, wrap_script=False)
self.bokeh_chart = json.dumps({"div": div, "script": script})
def _prepare_bokeh_chart_data(self):
"""compute the data that will be plotted.
:return: a tuple with 2 elements: (projects list, plot_data
dictionary).
The plot data dictionary is nested dictionary defined as follows:
{
employee: {
project: {
date: forecast
for dates with a forecast on that project
}
for all projects scheduled on employee
}
for all selected employees
}
"""
end_date = self.date_from + relativedelta(months=self.nb_months)
domain = [
("date_from", ">=", self.date_from),
("date_to", "<=", end_date),
]
if self.employee_ids:
if self.project_ids:
domain += [
"|",
"&",
("employee_id", "=", False),
("project_id", "in", self.project_ids.ids),
("employee_id", "in", self.employee_ids.ids),
]
else:
domain += [("employee_id", "in", self.employee_ids.ids)]
else:
domain.append(("employee_id", "=", False))
groups = [
"date_from:%s" % self.granularity,
"employee_id",
"project_id",
]
groupdata = self.env["forecast.line"].read_group(
domain, ["consolidated_forecast"], groups, lazy=False
)
employees = set()
projects = set()
data_project = {}
data_overload = {}
for d in groupdata:
employee = d.get("employee_id")
if employee:
employee = employee[1]._value
else:
employee = _("Not assigned to an employee")
employees.add(employee)
if employee not in data_project:
data_project[employee] = {}
data_overload[employee] = {}
forecast = d["consolidated_forecast"]
date = d["__range"]["date_from"]["from"]
project = d.get("project_id")
if project:
project = project[1]._value
data = data_project
elif forecast >= 0:
project = _("Available")
data = data_project
else:
project = _("Overload")
data = data_overload
projects.add(project)
if project not in data[employee]:
data[employee][project] = {}
x_key = date
data[employee][project][x_key] = forecast
employees = list(employees)
employees.sort()
if _("Not assigned to an employee") in employees:
# make sure it is the last one
employees.remove(_("Not assigned to an employee"))
employees.append(_("Not assigned to an employee"))
projects = list(projects)
projects.sort()
for name in [_("Available"), _("Overload")]:
if name in projects:
# make sure these two get in the first tow positions
projects.remove(name)
projects.insert(0, name)
return employees, projects, data_project, data_overload
def _get_time_range(self):
end_date = self.date_from + relativedelta(months=self.nb_months)
dates = []
granularity = self.granularity
date = self.date_from
delta = date_utils.get_timedelta(1, granularity)
while date < end_date:
dates.append(date.strftime("%Y-%m-%d"))
date += delta
return dates
def _build_empty_plot(self, height=300, width=1024):
dates = self._get_time_range()
p = figure(height=height, width=width, x_range=FactorRange(*dates))
p.title.text = _("Nothing to plot. Select some employees")
return [p]
def _get_palette(self, projects):
"""return a dictionary mapping project names to colors"""
if len(projects) <= 20:
project_colors = palettes.Category20[max(len(projects), 3)][: len(projects)]
else:
step = len(palettes.Turbo256) // len(projects)
project_colors = palettes.Turbo256[::step][: len(projects)]
return dict(zip(projects, project_colors))
def _build_plots(self, height=300, width=1024):
employees, projects, data, data_overload = self._prepare_bokeh_chart_data()
if not data:
return self._build_empty_plot(height, width)
project_color_map = self._get_palette(projects)
dates = self._get_time_range()
plots = []
for employee in employees:
plot_data = {"dates": dates}
plot_data_overload = {"dates": dates}
for project in data[employee]:
forecast = data[employee][project]
plot_data[project] = [forecast.get(date, 0) for date in dates]
for project in data_overload[employee]:
forecast = data_overload[employee][project]
plot_data_overload[project] = [forecast.get(date, 0) for date in dates]
plot_projects = [
p
for p in projects
if p in data[employee] or p in data_overload[employee]
]
source = ColumnDataSource(data=plot_data)
source_overload = ColumnDataSource(data=plot_data_overload)
p = figure(
x_range=FactorRange(*dates),
height=max(height, len(plot_projects) * 30),
width=width,
)
for src in (source, source_overload):
p.vbar_stack(
plot_projects,
x="dates",
source=src,
width=0.4,
alpha=0.5,
color=[project_color_map[p] for p in plot_projects],
legend_label=[
(proj_name if len(proj_name) < 20 else proj_name[:19] + "…")
for proj_name in plot_projects
],
)
p.xaxis.major_label_orientation = "vertical"
p.title.text = employee
p.legend.click_policy = "mute"
p.add_layout(p.legend[0], "right")
plots.append(p)
return plots
| 38.297297 | 8,502 |
746 | py | PYTHON | 15.0 | # Copyright 2018 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Project Timeline - Timesheet",
"summary": "Shows the progress of tasks on the timeline view.",
"author": "Onestein, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/project",
"category": "Project Management",
"version": "15.0.1.0.0",
"depends": ["project_timeline", "hr_timesheet"],
"data": ["views/project_task_view.xml"],
"assets": {
"web.assets_backend": [
"/project_timeline_hr_timesheet/static/src/scss/project_timeline_hr_timesheet.scss"
]
},
"installable": True,
"auto_install": True,
}
| 35.52381 | 746 |
578 | py | PYTHON | 15.0 | # Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Projects List View",
"version": "15.0.2.0.0",
"category": "Project",
"website": "https://github.com/OCA/project",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "Projects list view",
"depends": ["project"],
"data": ["views/project_project.xml"],
}
| 34 | 578 |
1,057 | py | PYTHON | 15.0 | # Copyright 2023 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID, api
def uninstall_hook(cr, registry):
"""Restore project.project_project_manager_rule"""
env = api.Environment(cr, SUPERUSER_ID, {})
# Removing the 'group_full_project_manager' group before renaming the original
# 'Project: Administrator' group (project.group_project_manager) to 'Administrator'
# in order to avoid getting a SQL constraint error:
# 'duplicate key value violates unique constraint "res_groups_name_uniq'"
env.ref(
"project_administrator_restricted_visibility.group_full_project_manager"
).unlink()
# Rename the original 'Project: Administrator' access group back to 'Administrator'
# and reassign the access rule for projects that it previously had.
env.ref("project.group_project_manager").write(
{
"name": "Administrator",
"rule_groups": [(4, env.ref("project.project_project_manager_rule").id)],
}
)
| 45.956522 | 1,057 |
479 | py | PYTHON | 15.0 | {
"name": "Project Administrator Restricted Visibility",
"version": "15.0.1.0.0",
"summary": "Adds a 'Project Administrator' access group "
"with restricted visibility to 'Projects'",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"license": "AGPL-3",
"category": "Project",
"depends": ["project"],
"data": ["security/project_security.xml"],
"uninstall_hook": "uninstall_hook",
}
| 36.846154 | 479 |
1,909 | py | PYTHON | 15.0 | # Copyright 2023 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase, new_test_user, users
class TestAccountPaymentTermSecurity(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.project_obj = cls.env["project.project"]
cls.user_admin = cls.env.ref("base.user_admin")
cls.user_user_padmin = new_test_user(
cls.env,
login="project-user",
groups="project.group_project_user",
)
cls.user_restrcited_padmin = new_test_user(
cls.env,
login="restricted-project-admin",
groups="project.group_project_manager",
)
cls.user_full_padmin = new_test_user(
cls.env,
login="project-admin",
groups="project_administrator_restricted_visibility.group_full_project_manager",
)
cls.restricted_project = cls.env["project.project"].create(
{
"name": "Restricted project",
"privacy_visibility": "followers",
"user_id": cls.user_admin.id,
"message_partner_ids": [(6, 0, cls.user_admin.ids)],
}
)
@users("restricted-project-admin", "project-admin")
def test_create_new_project(self):
"""'Restricted project administrator' can create
projects like a 'Project administrator'.
"""
self.project_obj.create({"name": "Another project"})
@users("restricted-project-admin", "project-user")
def test_cant_see_restricted_projects(self):
"""'Restricted project administrator' has the same project restriction
as the 'Project user'.
"""
all_project = self.env["project.project"].search([])
self.assertNotIn(self.restricted_project, all_project)
| 38.959184 | 1,909 |
698 | py | PYTHON | 15.0 | # Copyright 2016-2020 Onestein (<http://www.onestein.eu>)
# Copyright 2020 Tecnativa - Manuel Calero
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Project Task Dependencies",
"version": "15.0.1.0.0",
"category": "Project",
"website": "https://github.com/OCA/project",
"summary": "Enables to define dependencies (other tasks) of a task",
"author": "Onestein,Odoo Community Association (OCA)",
"license": "AGPL-3",
"development_status": "Production/Stable",
"maintainers": ["astirpe"],
"depends": ["project"],
"external_dependencies": {"python": ["openupgradelib"]},
"installable": True,
"auto_install": False,
}
| 36.736842 | 698 |
632 | py | PYTHON | 15.0 | from openupgradelib import openupgrade
xml_ids = ["project_task_form"]
@openupgrade.migrate()
def migrate(env, version):
openupgrade.delete_records_safely_by_xml_id(env, xml_ids)
env.cr.execute(
"""
INSERT INTO task_dependencies_rel(task_id, depends_on_id)
SELECT task_id, dependency_task_id FROM project_task_dependency_task_rel;
"""
)
env.cr.execute(
"""
UPDATE project_project SET allow_task_dependencies=true
WHERE id in (SELECT project_id FROM project_task WHERE id in (SELECT task_id
FROM project_task_dependency_task_rel));
"""
)
| 30.095238 | 632 |
1,066 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa <vicent.cubells@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID, api
def pre_init_hook(cr):
"""
With this pre-init-hook we want to avoid error when creating the UNIQUE
code constraint when the module is installed and before the post-init-hook
is launched.
"""
cr.execute("ALTER TABLE project_task ADD COLUMN code character varying;")
cr.execute("UPDATE project_task SET code = id;")
def post_init_hook(cr, registry):
"""
This post-init-hook will update all existing task assigning them the
corresponding sequence code.
"""
env = api.Environment(cr, SUPERUSER_ID, dict())
task_obj = env["project.task"]
sequence_obj = env["ir.sequence"]
tasks = task_obj.search([], order="id")
for task_id in tasks.ids:
cr.execute(
"UPDATE project_task SET code = %s WHERE id = %s;",
(
sequence_obj.next_by_code("project.task"),
task_id,
),
)
| 32.30303 | 1,066 |
650 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa <vicent.cubells@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sequential Code for Tasks",
"version": "15.0.1.0.4",
"category": "Project Management",
"author": "OdooMRP team, "
"AvanzOSC, "
"Tecnativa, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"license": "AGPL-3",
"depends": [
"project",
],
"data": [
"data/task_sequence.xml",
"views/project_view.xml",
],
"installable": True,
"pre_init_hook": "pre_init_hook",
"post_init_hook": "post_init_hook",
}
| 27.083333 | 650 |
1,529 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa <vicent.cubells@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import odoo.tests.common as common
class TestProjectTaskCode(common.TransactionCase):
def setUp(self):
super().setUp()
self.project_task_model = self.env["project.task"]
self.ir_sequence_model = self.env["ir.sequence"]
self.task_sequence = self.env.ref("project_task_code.sequence_task")
self.project_task = self.env.ref("project.project_task_1")
def test_old_task_code_assign(self):
project_tasks = self.project_task_model.search([])
for project_task in project_tasks:
self.assertNotEqual(project_task.code, "/")
def test_new_task_code_assign(self):
number_next = self.task_sequence.number_next_actual
code = self.task_sequence.get_next_char(number_next)
project_task = self.project_task_model.create(
{
"name": "Testing task code",
}
)
self.assertNotEqual(project_task.code, "/")
self.assertEqual(project_task.code, code)
def test_name_get(self):
number_next = self.task_sequence.number_next_actual
code = self.task_sequence.get_next_char(number_next)
project_task = self.project_task_model.create(
{
"name": "Task Testing Get Name",
}
)
result = project_task.name_get()
self.assertEqual(result[0][1], "[%s] Task Testing Get Name" % code)
| 38.225 | 1,529 |
1,225 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa <vicent.cubells@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class ProjectTask(models.Model):
_inherit = "project.task"
code = fields.Char(
string="Task Number",
required=True,
default="/",
readonly=True,
copy=False,
)
_sql_constraints = [
("project_task_unique_code", "UNIQUE (code)", _("The code must be unique!")),
]
@api.model_create_multi
def create(self, vals_list):
new_list = []
for vals in vals_list:
if vals.get("code", "/") == "/":
new_vals = dict(
vals,
code=self.env["ir.sequence"].next_by_code("project.task") or "/",
)
else:
new_vals = vals
new_list.append(new_vals)
return super().create(new_list)
def name_get(self):
result = super().name_get()
new_result = []
for task in result:
rec = self.browse(task[0])
name = "[{}] {}".format(rec.code, task[1])
new_result.append((rec.id, name))
return new_result
| 27.840909 | 1,225 |
753 | py | PYTHON | 15.0 | # Copyright 2012 - 2013 Daniel Reis
# Copyright 2015 - Antiun Ingeniería S.L. - Sergio Teruel
# Copyright 2016 - Tecnativa - Vicent Cubells
# Copyright 2017 - Tecnativa - David Vidal
# Copyright 2018 - Brain-tec AG - Carlos Jesus Cebrian
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl-3.0).
{
"name": "Project Task Material",
"summary": "Record products spent in a Task",
"version": "15.0.1.0.0",
"category": "Project Management",
"author": "Daniel Reis," "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"license": "AGPL-3",
"installable": True,
"depends": ["project", "product"],
"data": ["security/ir.model.access.csv", "views/project_view.xml"],
}
| 41.777778 | 752 |
1,836 | py | PYTHON | 15.0 | # Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2018 - Brain-tec AG - Carlos Jesus Cebrian
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl-3.0).
from odoo.exceptions import ValidationError
from .common import TestProjectCases
class ProjectTaskMaterial(TestProjectCases):
def test_manager_add_task_material_wrong(self):
"""
TEST CASE 1
The user is adding some materials in the task
with different wrong values
"""
try:
# Material with `quantity = 0.0`
self.action.write(
{
"material_ids": [
(0, 0, {"product_id": self.product.id, "quantity": 0.0})
]
}
)
except ValidationError as err:
self.assertEqual(
str(err.args[0]),
"Quantity of material consumed must be greater than 0.",
)
try:
# Material with `negative quantity`
self.action.write(
{
"material_ids": [
(0, 0, {"product_id": self.product.id, "quantity": -10.0})
]
}
)
except ValidationError as err:
self.assertEqual(
str(err.args[0]),
"Quantity of material consumed must be greater than 0.",
)
def test_manager_add_task_material_right(self):
"""
TEST CASE 2
The user is adding some materials in the task
with right values
"""
# Material with `quantity = 1.0`
self.action.write(
{"material_ids": [(0, 0, {"product_id": self.product.id, "quantity": 4.0})]}
)
self.assertEqual(len(self.task.material_ids.ids), 1)
| 31.118644 | 1,836 |
1,141 | py | PYTHON | 15.0 | # Copyright 2018 - Brain-tec AG - Carlos Jesus Cebrian
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl-3.0).
from odoo.tests.common import TransactionCase
class TestProjectCases(TransactionCase):
"""Prepare data to test the module."""
def setUp(self):
"""Create user, task, project as well as refre action of the user."""
super(TestProjectCases, self).setUp()
# Create new User
# Add it to the `project user` group
self.project_user = self.env["res.users"].create(
{
"company_id": self.env.ref("base.main_company").id,
"name": "Carlos Project User",
"login": "cpu",
"email": "cpu@yourcompany.com",
"groups_id": [(6, 0, [self.ref("project.group_project_user")])],
}
)
# Refer to a task assigned to the project user
self.task = self.env.ref("project.project_task_2")
self.product = self.env.ref("product.consu_delivery_03")
# Refer to a action from the user created
self.action = self.task.with_user(self.project_user.id)
| 36.806452 | 1,141 |
1,336 | py | PYTHON | 15.0 | # Copyright 2012 - 2013 Daniel Reis
# Copyright 2015 - Antiun Ingeniería S.L. - Sergio Teruel
# Copyright 2016 - Tecnativa - Vicent Cubells
# Copyright 2018 - Brain-tec AG - Carlos Jesus Cebrian
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl-3.0).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class Task(models.Model):
"""Added Material Used in the Project Task."""
_inherit = "project.task"
material_ids = fields.One2many(
comodel_name="project.task.material",
inverse_name="task_id",
string="Material Used",
)
class ProjectTaskMaterial(models.Model):
"""Added Product and Quantity in the Task Material Used."""
_name = "project.task.material"
_description = "Task Material Used"
task_id = fields.Many2one(
comodel_name="project.task", string="Task", ondelete="cascade", required=True
)
product_id = fields.Many2one(
comodel_name="product.product", string="Product", required=True
)
quantity = fields.Float()
@api.constrains("quantity")
def _check_quantity(self):
for material in self:
if not material.quantity > 0.0:
raise ValidationError(
_("Quantity of material consumed must be greater than 0.")
)
| 31.046512 | 1,335 |
589 | py | PYTHON | 15.0 | # Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
{
"name": "Project Templates",
"summary": """Project Templates""",
"author": "Patrick Wilson, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"category": "Project Management",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["project"],
"data": ["views/project.xml"],
"application": False,
"development_status": "Beta",
"maintainers": ["patrickrwilson"],
}
| 34.647059 | 589 |
2,390 | py | PYTHON | 15.0 | # Copyright 2019 Patrick Wilson <patrickraymondwilson@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import common
class TestProjectTemplate(common.TransactionCase):
def setUp(self):
super().setUp()
self.test_customer = self.env["res.partner"].create({"name": "TestCustomer"})
self.test_project = self.env["project.project"].create(
{
"name": "TestProject",
"alias_name": "test_alias",
"partner_id": self.test_customer.id,
}
)
self.env["project.task"].create(
{"name": "TestTask", "project_id": self.test_project.id}
)
# TEST 01: Set project to be a template and test name change
def test_on_change_is_template(self):
# Test when changing project to a template
project_01 = self.test_project
project_01.is_template = True
project_01.on_change_is_template()
self.assertEqual(project_01.name, "TestProject (TEMPLATE)")
# Test when changing template back to project
project_01.is_template = False
project_01.on_change_is_template()
self.assertEqual(project_01.name, "TestProject")
# TEST 02: Create project from template
def test_create_project_from_template(self):
# Set Project Template
project_01 = self.test_project
project_01.is_template = True
project_01.on_change_is_template()
# Create new Project from Template
project_01.create_project_from_template()
new_project = self.env["project.project"].search(
[("name", "=", "TestProject (COPY)")]
)
self.assertEqual(len(new_project), 1)
# TEST 03: Create project from template using non-standard name
def test_create_project_from_template_non_standard_name(self):
# Set Project Template
project_01 = self.test_project
project_01.is_template = True
project_01.on_change_is_template()
# Change the name of project template
project_01.name = "TestProject(TEST)"
# Create new Project from Template
project_01.create_project_from_template()
new_project = self.env["project.project"].search(
[("name", "=", "TestProject(TEST) (COPY)")]
)
self.assertEqual(len(new_project), 1)
| 37.936508 | 2,390 |
2,102 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class Project(models.Model):
_inherit = "project.project"
is_template = fields.Boolean(copy=False)
# CREATE A PROJECT FROM A TEMPLATE AND OPEN THE NEWLY CREATED PROJECT
def create_project_from_template(self):
if " (TEMPLATE)" in self.name:
new_name = self.name.replace(" (TEMPLATE)", " (COPY)")
else:
new_name = self.name + " (COPY)"
new_project = self.copy(
default={"name": new_name, "active": True, "alias_name": False}
)
# SINCE THE END DATE DOESN'T COPY OVER ON TASKS
# (Even when changed to copy=true), POPULATE END DATES ON THE TASK
for new_task_record in new_project.task_ids:
for old_task_record in self.task_ids:
if new_task_record.name == old_task_record.name:
new_task_record.date_end = old_task_record.date_end
# OPEN THE NEWLY CREATED PROJECT FORM
return {
"view_type": "form",
"view_mode": "form",
"res_model": "project.project",
"target": "current",
"res_id": new_project.id,
"type": "ir.actions.act_window",
}
# ADD "(TEMPLATE)" TO THE NAME WHEN PROJECT IS MARKED AS A TEMPLATE
@api.onchange("is_template")
def on_change_is_template(self):
# Add "(TEMPLATE)" to the Name if is_template == true
# if self.name is needed for creating projects via configuration menu
if self.name:
if self.is_template:
if "(TEMPLATE)" not in self.name:
self.name = self.name + " (TEMPLATE)"
if self.user_id:
self.user_id = False
if self.partner_id:
self.partner_id = False
if self.alias_name:
self.alias_name = False
else:
if " (TEMPLATE)" in self.name:
self.name = self.name.replace(" (TEMPLATE)", "")
| 38.218182 | 2,102 |
883 | py | PYTHON | 15.0 | import logging
from odoo.api import SUPERUSER_ID, Environment
logger = logging.getLogger(__name__)
def pre_init_hook(cr):
env = Environment(cr, SUPERUSER_ID, {})
# avoid crashing installation because of having same complete_wbs_code
for aa in (
env["account.analytic.account"]
.with_context(active_test=False)
.search([("code", "=", False)])
):
aa._write(
{"code": env["ir.sequence"].next_by_code("account.analytic.account.code")}
)
logger.info("Assigning default code to existing analytic accounts")
projects = (
env["project.project"]
.with_context(active_test=False)
.search([("analytic_account_id", "=", False)])
)
projects._create_analytic_account()
projects.filtered(lambda p: not p.active).mapped("analytic_account_id").write(
{"active": False}
)
| 30.448276 | 883 |
911 | py | PYTHON | 15.0 | # Copyright 2017-19 Eficent Business and IT Consulting Services S.L.
# Copyright 2017 Luxim d.o.o.
# Copyright 2017 Matmoz d.o.o.
# Copyright 2017 Deneroteam.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Project Work Breakdown Structure",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Matmoz d.o.o., "
"Luxim d.o.o., "
"Deneroteam, "
"Eficent, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"depends": [
"account_analytic_parent",
"account_analytic_sequence",
"hr_timesheet",
],
"summary": "Apply Work Breakdown Structure",
"data": [
"view/account_analytic_account_view.xml",
"view/project_project_view.xml",
],
"pre_init_hook": "pre_init_hook",
"installable": True,
}
| 31.413793 | 911 |
5,583 | py | PYTHON | 15.0 | # Copyright 2017-19 Eficent Business and IT Consulting Services S.L.
# Copyright 2017 Luxim d.o.o.
# Copyright 2017 Matmoz d.o.o.
# Copyright 2017 Deneroteam.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import ValidationError
from odoo.tests import common
class TestProjectWbs(common.TransactionCase):
def setUp(self):
super(TestProjectWbs, self).setUp()
self.project_project = self.env["project.project"]
self.project = self.project_project.create(
{"name": "Test project", "code": "0001"}
)
self.parent_account = self.project.analytic_account_id
self.project_son = self.project_project.create(
{
"name": "Test project son",
"code": "01",
"parent_id": self.parent_account.id,
}
)
self.son_account = self.project_son.analytic_account_id
self.project_grand_son = self.project_project.create(
{
"name": "Test project grand son",
"code": "02",
"parent_id": self.son_account.id,
}
)
self.grand_son_account = self.project_grand_son.analytic_account_id
self.project2 = self.project_project.create(
{"name": "Test project 2", "code": "03"}
)
self.account2 = self.project2.analytic_account_id
self.analytic_account = self.env["account.analytic.account"].create(
{
"name": "Test analytic account",
}
)
def test_get_name_and_code(self):
project = self.project_project.create({"name": "Project", "code": "1001"})
project.name_get()
project_account = self.project.analytic_account_id
project_account.name_get()
def test_get_project_wbs(self):
accounts = self.project._get_project_wbs()
self.assertEqual(len(accounts), 3, "wrong children number")
def test_wbs_code(self):
self.assertEqual(self.project.complete_wbs_code, "[0001]", "Incorrect WBS code")
self.assertEqual(
self.project_son.complete_wbs_code, "[0001 / 01]", "Incorrect WBS code"
)
self.assertEqual(
self.project_grand_son.complete_wbs_code,
"[0001 / 01 / 02]",
"Incorrect WBS code",
)
def test_get_child_accounts(self):
res = self.env["account.analytic.account"].get_child_accounts()
self.assertEqual(res, {}, "Should get nothing")
res = self.parent_account.get_child_accounts()
for has_parent in res.keys():
self.assertEqual(res[has_parent], True, "Wrong child accounts")
def test_view_context(self):
res = self.project_project.with_context(
default_parent_id=self.project.id
)._resolve_analytic_account_id_from_context()
self.assertEqual(res, self.project.id, "Wrong Parent Project from context")
res = self.project_project._resolve_analytic_account_id_from_context()
self.assertEqual(res, None, "Should not be anything in context")
def test_indent_calc(self):
self.son_account._wbs_indent_calc()
self.assertEqual(self.son_account.wbs_indent, ">", "Wrong Indent")
def test_open_window(self):
res = self.project_son.action_open_parent_tree_view()
self.assertEqual(
res["domain"][0][2][0], self.project.id, "Parent not showing in view"
)
res = self.project_grand_son.action_open_child_tree_view()
self.assertEqual(res["domain"][0][2], [], "Lowest element have no child")
res = self.project.action_open_child_kanban_view()
self.assertEqual(
res["domain"][0][2][0], self.project_son.id, "Son not showing in view"
)
res = self.project_son.action_open_child_kanban_view()
self.assertEqual(
res["domain"][0][2][0],
self.project_grand_son.id,
"Grand son not showing in kanban view",
)
res = self.project_son.action_open_parent_kanban_view()
self.assertEqual(
res["domain"][0][2][0], self.project.id, "Parent not showing in kanban view"
)
res = self.project.action_open_view_project_form()
self.assertEqual(res["res_id"], self.project.id, "Wrong project form view")
def test_onchange_parent(self):
self.project2.write({"parent_id": self.parent_account.id})
self.project2.on_change_parent()
child_in = self.project2 in self.project.project_child_complete_ids
self.assertTrue(child_in, "Child not added")
def test_duplicate(self):
seq_id = self.env["ir.sequence"].search(
[("code", "=", "account.analytic.account.code")]
)
next_val = seq_id.number_next_actual
copy_project = self.project.copy()
self.assertTrue(str(next_val) in copy_project.analytic_account_id.code)
next_val = seq_id.number_next_actual
with self.assertRaises(ValidationError):
copy_analytic = self.parent_account.copy()
self.assertTrue(str(next_val) in copy_analytic.analytic_account_id.code)
self.analytic_account.copy()
def test_project_analytic_id(self):
self.grand_son_account.account_class = "deliverable"
self.grand_son_account._compute_project_analytic_id()
self.assertEqual(
self.grand_son_account.project_analytic_id.id, self.son_account.id
)
| 41.051471 | 5,583 |
7,314 | py | PYTHON | 15.0 | # Copyright 2017-19 Eficent Business and IT Consulting Services S.L.
# Copyright 2017 Luxim d.o.o.
# Copyright 2017 Matmoz d.o.o.
# Copyright 2017 Deneroteam.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class AccountAnalyticAccount(models.Model):
_inherit = "account.analytic.account"
_order = "complete_wbs_code"
def get_child_accounts(self):
result = {}
if not self.ids:
return result
for curr_id in self.ids:
result[curr_id] = True
# Now add the children
self.env.cr.execute(
"""
WITH RECURSIVE children AS (
SELECT parent_id, id
FROM account_analytic_account
WHERE parent_id IN %s
UNION ALL
SELECT a.parent_id, a.id
FROM account_analytic_account a
JOIN children b ON(a.parent_id = b.id)
)
SELECT * FROM children order by parent_id
""",
(tuple(self.ids),),
)
res = self.env.cr.fetchall()
for _x, y in res:
result[y] = True
return result
def write(self, vals):
res = super(AccountAnalyticAccount, self).write(vals)
if vals.get("parent_id"):
for account in self.browse(self.get_child_accounts().keys()):
account._complete_wbs_code_calc()
account._complete_wbs_name_calc()
if "active" in vals:
for account in self:
account.project_ids.filtered(
lambda p: p.active != account.active
).write({"active": account.active})
return res
@api.depends("code")
def _complete_wbs_code_calc(self):
for account in self:
data = []
acc = account
while acc:
if acc.code:
data.insert(0, acc.code)
acc = acc.parent_id
if data:
if len(data) >= 2:
data = " / ".join(data)
else:
data = data[0]
data = "[" + data + "]"
account.complete_wbs_code = data or ""
@api.depends("name")
def _complete_wbs_name_calc(self):
for account in self:
data = []
acc = account
while acc:
if acc.name:
data.insert(0, acc.name)
acc = acc.parent_id
if data:
if len(data) >= 2:
data = " / ".join(data)
else:
data = data[0]
account.complete_wbs_name = data or ""
def _wbs_indent_calc(self):
for account in self:
data = []
acc = account
while acc:
if acc.name and acc.parent_id:
data.insert(0, ">")
acc = acc.parent_id
if data:
if len(data) >= 2:
data = "".join(data) # pragma: no cover
else:
data = data[0]
account.wbs_indent = data or ""
@api.depends("account_class", "parent_id")
def _compute_project_analytic_id(self):
for analytic in self:
if analytic.parent_id:
current = analytic.parent_id
else:
current = analytic
while current.id:
if current.account_class == "project":
analytic.project_analytic_id = current
break
current = current.parent_id
@api.model
def _default_parent(self):
return self.env.context.get("parent_id", None)
@api.model
def _default_partner(self):
return self.env.context.get("partner_id", None)
@api.model
def _default_user(self):
return self.env.context.get("user_id", self.env.user)
wbs_indent = fields.Char(compute=_wbs_indent_calc, string="Level")
complete_wbs_code = fields.Char(
compute=_complete_wbs_code_calc,
string="Full WBS Code",
help="The full WBS code describes the full path of this component "
"within the project WBS hierarchy",
store=True,
)
code = fields.Char(copy=False)
complete_wbs_name = fields.Char(
compute=_complete_wbs_name_calc,
string="Full WBS path",
help="Full path in the WBS hierarchy",
store=True,
)
project_ids = fields.One2many(
comodel_name="project.project",
inverse_name="analytic_account_id",
string="Projects",
)
project_analytic_id = fields.Many2one(
"account.analytic.account",
compute=_compute_project_analytic_id,
string="Root Analytic Account",
store=True,
)
user_id = fields.Many2one(
"res.users",
"Project Manager",
tracking=True,
default=_default_user,
)
manager_id = fields.Many2one("res.users", "Manager", tracking=True)
account_class = fields.Selection(
[
("project", "Project"),
("phase", "Phase"),
("deliverable", "Deliverable"),
("work_package", "Work Package"),
],
"Class",
default="project",
help="The classification allows you to create a proper project "
"Work Breakdown Structure",
)
parent_id = fields.Many2one(
default=_default_parent, string="Parent Analytic Account"
)
partner_id = fields.Many2one(default=_default_partner)
def copy(self, default=None):
if self.mapped("project_ids"):
raise ValidationError(
_("Duplicate the project instead of the " "Analytic Account")
)
default = {}
default["code"] = self.env["ir.sequence"].next_by_code(
"account.analytic.account.code"
)
return super(AccountAnalyticAccount, self).copy(default)
@api.depends("code")
def code_get(self):
res = []
for account in self:
data = []
acc = account
while acc:
if acc.code:
data.insert(0, acc.code)
else:
data.insert(0, "") # pragma: no cover
acc = acc.parent_id
data = " / ".join(data)
res.append((account.id, data))
return res
@api.depends("name")
def name_get(self):
res = []
for account in self:
data = []
acc = account
while acc:
if acc.name:
data.insert(0, acc.name)
else:
data.insert(0, "") # pragma: no cover
acc = acc.parent_id
data = "/".join(data)
res2 = account.code_get()
if res2 and res2[0][1]:
data = "[" + res2[0][1] + "] " + data
res.append((account.id, data))
return res
_sql_constraints = [
(
"analytic_unique_wbs_code",
"UNIQUE (complete_wbs_code)",
_("The full wbs code must be unique!"),
),
]
| 30.731092 | 7,314 |
11,642 | py | PYTHON | 15.0 | # Copyright 2017-19 Eficent Business and IT Consulting Services S.L.
# Copyright 2017 Luxim d.o.o.
# Copyright 2017 Matmoz d.o.o.
# Copyright 2017 Deneroteam.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
class Project(models.Model):
_inherit = "project.project"
_description = "WBS element"
_order = "complete_wbs_code"
analytic_account_id = fields.Many2one(
"account.analytic.account",
"Analytic Account",
required=True,
ondelete="restrict",
index=True,
)
def _get_project_analytic_wbs(self):
result = {}
self.env.cr.execute(
"""
WITH RECURSIVE children AS (
SELECT p.id as ppid, p.id as pid, a.id, a.parent_id
FROM account_analytic_account a
INNER JOIN project_project p
ON a.id = p.analytic_account_id
WHERE p.id IN %s
UNION ALL
SELECT b.ppid as ppid, p.id as pid, a.id, a.parent_id
FROM account_analytic_account a
INNER JOIN project_project p
ON a.id = p.analytic_account_id
JOIN children b ON(a.parent_id = b.id)
)
SELECT * FROM children order by ppid
""",
(tuple(self.ids),),
)
res = self.env.cr.fetchall()
for r in res:
if r[0] in result:
result[r[0]][r[1]] = r[2]
else:
result[r[0]] = {r[1]: r[2]}
return result
def _get_project_wbs(self):
result = []
projects_data = self._get_project_analytic_wbs()
for ppid in projects_data.values():
result.extend(ppid.keys())
return result
@api.depends("name")
def name_get(self):
res = []
for project_item in self:
data = []
proj = project_item
if proj and proj.name:
data.insert(0, proj.name)
else:
data.insert(0, "") # pragma: no cover
acc = proj.analytic_account_id.parent_id
while acc:
if acc and acc.name:
data.insert(0, acc.name)
else:
data.insert(0, "") # pragma: no cover
acc = acc.parent_id
data = "/".join(data)
res2 = project_item.code_get()
if res2 and res2[0][1]:
data = "[" + res2[0][1] + "] " + data
res.append((project_item.id, data))
return res
@api.depends("analytic_account_id.code")
def code_get(self):
res = []
for project_item in self:
data = []
proj = project_item
if proj.analytic_account_id.code:
data.insert(0, proj.analytic_account_id.code)
else:
data.insert(0, "") # pragma: no cover
acc = proj.analytic_account_id.parent_id
while acc:
if acc.code:
data.insert(0, acc.code)
else:
data.insert(0, "") # pragma: no cover
acc = acc.parent_id
data = "/".join(data)
res.append((project_item.id, data))
return res
@api.depends("analytic_account_id.parent_id")
def _compute_child(self):
for project_item in self:
child_ids = False
if project_item.analytic_account_id:
child_ids = self.env["project.project"].search(
[
(
"analytic_account_id.parent_id",
"=",
project_item.analytic_account_id.id,
)
]
)
project_item.project_child_complete_ids = child_ids
@api.depends("project_child_complete_ids")
def _compute_has_child(self):
for project_item in self:
project_item.has_project_child_complete_ids = (
len(project_item.project_child_complete_ids.ids) > 0
)
def _resolve_analytic_account_id_from_context(self):
"""
Returns ID of parent analytic account based on the value of
'default_parent_id'
context key, or None if it cannot be resolved to a single
account.analytic.account
"""
context = self.env.context or {}
if isinstance(context.get("default_parent_id"), int):
return context["default_parent_id"]
return None
def prepare_analytics_vals(self, vals):
return {
"name": vals.get("name", _("Unknown Analytic Account")),
"company_id": vals.get("company_id", self.env.user.company_id.id),
"partner_id": vals.get("partner_id"),
"active": True,
}
def update_project_from_analytic_vals(self, vals):
new_vals = vals
if "parent_id" in vals and not vals["parent_id"]:
# it means it comes from a form
parent = self.env["account.analytic.account"].browse(
self._context.get("default_parent_id", False)
)
if parent:
account_analytic = self.env["account.analytic.account"].browse(
vals.get("analytic_account_id", False)
)
new_vals.update(
{
"parent_id": parent.id,
"code": account_analytic.code,
"project_analytic_id": parent.project_analytic_id.id,
"account_class": parent.account_class,
}
)
return new_vals
parent_id = fields.Many2one(
related="analytic_account_id.parent_id",
readonly=False,
)
child_ids = fields.One2many(
related="analytic_account_id.child_ids",
readonly=False,
)
project_child_complete_ids = fields.Many2many(
comodel_name="project.project",
string="Project Hierarchy",
compute="_compute_child",
)
has_project_child_complete_ids = fields.Boolean(
compute="_compute_has_child",
)
wbs_indent = fields.Char(
related="analytic_account_id.wbs_indent",
readonly=False,
)
complete_wbs_code = fields.Char(
related="analytic_account_id.complete_wbs_code",
string="WBS Code",
store=True,
readonly=False,
)
code = fields.Char(
related="analytic_account_id.code",
readonly=False,
)
complete_wbs_name = fields.Char(
related="analytic_account_id.complete_wbs_name",
readonly=False,
)
project_analytic_id = fields.Many2one(
related="analytic_account_id.project_analytic_id", readonly=True, store=True
)
account_class = fields.Selection(
related="analytic_account_id.account_class",
store=True,
default="project",
readonly=False,
)
@api.model
def create(self, vals):
analytic_vals = self.prepare_analytics_vals(vals)
if "analytic_account_id" not in vals:
aa = self.env["account.analytic.account"].create(analytic_vals)
vals.update({"analytic_account_id": aa.id})
if not vals.get("code"):
vals.update({"code": aa.code})
vals = self.update_project_from_analytic_vals(vals)
res = super(Project, self).create(vals)
return res
@api.model
def action_open_child_view(self, act_window):
"""
:return dict: dictionary value for created view
"""
res = self.env["ir.actions.act_window"]._for_xml_id(act_window)
domain = []
project_ids = []
child_project_ids = self.env["project.project"].search(
[("analytic_account_id.parent_id", "=", self.analytic_account_id.id)]
)
for child_project_id in child_project_ids:
project_ids.append(child_project_id.id)
res["context"] = {
"default_parent_id": (
self.analytic_account_id and self.analytic_account_id.id or False
),
"default_partner_id": (self.partner_id and self.partner_id.id or False),
"default_user_id": (self.user_id and self.user_id.id or False),
}
domain.append(("id", "in", project_ids))
res.update({"display_name": self.name, "domain": domain, "nodestroy": False})
return res
def action_open_child_tree_view(self):
self.ensure_one()
return self.action_open_child_view("project_wbs.open_view_project_wbs")
def action_open_child_kanban_view(self):
self.ensure_one()
return self.action_open_child_view("project_wbs.open_view_wbs_kanban")
def action_open_parent_tree_view(self):
"""
:return dict: dictionary value for created view
"""
self.ensure_one()
domain = []
analytic_account_ids = []
res = self.env["ir.actions.act_window"]._for_xml_id(
"project_wbs.open_view_project_wbs"
)
if self.analytic_account_id.parent_id:
for parent_project_id in self.env["project.project"].search(
[("analytic_account_id", "=", self.analytic_account_id.parent_id.id)]
):
analytic_account_ids.append(parent_project_id.id)
if analytic_account_ids:
domain.append(("id", "in", analytic_account_ids))
res.update({"domain": domain, "nodestroy": False})
res["display_name"] = self.name
return res
def write(self, vals):
res = super(Project, self).write(vals)
if "parent_id" in vals:
for account in self.env["account.analytic.account"].browse(
self.analytic_account_id.get_child_accounts().keys()
):
account._complete_wbs_code_calc()
account._complete_wbs_name_calc()
if "active" in vals and vals["active"]:
for project in self.filtered(lambda p: not p.analytic_account_id.active):
project.analytic_account_id.active = True
return res
def action_open_parent_kanban_view(self):
"""
:return dict: dictionary value for created view
"""
self.ensure_one()
domain = []
analytic_account_ids = []
res = self.env["ir.actions.act_window"]._for_xml_id(
"project_wbs.open_view_wbs_kanban"
)
if self.analytic_account_id.parent_id:
for parent_project_id in self.env["project.project"].search(
[("analytic_account_id", "=", self.analytic_account_id.parent_id.id)]
):
analytic_account_ids.append(parent_project_id.id)
if analytic_account_ids:
domain.append(("id", "in", analytic_account_ids))
res.update({"domain": domain, "nodestroy": False})
return res
@api.onchange("parent_id")
def on_change_parent(self):
self.analytic_account_id._onchange_parent_id()
def action_open_view_project_form(self):
view = {
"name": _("Details"),
"view_mode": "form,tree,kanban",
"res_model": "project.project",
"view_id": False,
"type": "ir.actions.act_window",
"target": "current",
"res_id": self.id,
"context": self.env.context,
}
return view
| 34.960961 | 11,642 |
425 | py | PYTHON | 15.0 | # Copyright 2017-2020 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
def uninstall_hook(cr, registry): # pragma: no cover
# Convert priority from High and Very High to Normal
# to avoid inconsistency after the module is uninstalled
cr.execute(
"UPDATE project_task SET priority = '1' "
"WHERE priority like '2' or priority like '3'"
)
| 38.636364 | 425 |
647 | py | PYTHON | 15.0 | # Copyright 2016-2020 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Project Task Add Very High",
"summary": "Adds extra options 'High' and 'Very High' on tasks",
"version": "15.0.1.0.0",
"development_status": "Production/Stable",
"author": "Onestein, Odoo Community Association (OCA)",
"maintainers": ["astirpe"],
"license": "AGPL-3",
"category": "Project",
"website": "https://github.com/OCA/project",
"depends": ["project"],
"data": ["views/project_task_view.xml"],
"installable": True,
"uninstall_hook": "uninstall_hook",
}
| 35.944444 | 647 |
306 | py | PYTHON | 15.0 | # Copyright 2016-2020 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProjectTask(models.Model):
_inherit = "project.task"
priority = fields.Selection(selection_add=[("2", "High"), ("3", "Very High")])
| 30.6 | 306 |
697 | py | PYTHON | 15.0 | # Copyright (C) 2019 - TODAY, Patrick Wilson
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Project - Stock Request",
"summary": "Create stock requests from a projects and project tasks",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Pavlov Media, Odoo Community Association (OCA)",
"category": "Project",
"website": "https://github.com/OCA/project",
"depends": [
"stock_request",
"project",
],
"data": [
"views/project_views.xml",
"views/project_task_views.xml",
"views/stock_request_order_views.xml",
"security/ir.model.access.csv",
],
"installable": True,
}
| 30.304348 | 697 |
412 | py | PYTHON | 15.0 | # Copyright (C) 2019 - TODAY, Patrick Wilson
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class StockRequestOrder(models.Model):
_inherit = "stock.request.order"
project_id = fields.Many2one("project.project", string="Project", tracking=True)
project_task_id = fields.Many2one(
"project.task", string="Project Task", tracking=True
)
| 31.692308 | 412 |
341 | py | PYTHON | 15.0 | # Copyright (C) 2019 - TODAY, Patrick Wilson
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProjectTask(models.Model):
_inherit = "project.task"
stock_request_order_ids = fields.One2many(
"stock.request.order", "project_task_id", string="Stock Request Orders"
)
| 28.416667 | 341 |
335 | py | PYTHON | 15.0 | # Copyright (C) 2019 - TODAY, Patrick Wilson
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Project(models.Model):
_inherit = "project.project"
stock_request_order_ids = fields.One2many(
"stock.request.order", "project_id", string="Stock Request Orders"
)
| 27.916667 | 335 |
586 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "Project - Create Purchase Orders with Analytic Account",
"version": "15.0.1.0.1",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainer": "Camptocamp",
"license": "AGPL-3",
"category": "Project",
"complexity": "easy",
"depends": ["project_purchase", "purchase_analytic_global"],
"website": "https://github.com/OCA/project",
"data": [],
"installable": True,
"auto_install": False,
"maintainers": ["yankinmax"],
}
| 32.555556 | 586 |
1,743 | py | PYTHON | 15.0 | # Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from datetime import date
from odoo.tests.common import Form, TransactionCase
class TestProjectPurchaseAnalyticGlobal(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.Project = cls.env["project.project"]
cls.AnalyticAccount = cls.env["account.analytic.account"]
cls.Partner = cls.env["res.partner"]
cls.PurchaseOrder = cls.env["purchase.order"]
cls.partner1 = cls.Partner.create({"name": "Partner1"})
cls.analytic_account1 = cls.AnalyticAccount.create(
{"name": "Analytic Account 1"}
)
cls.product = cls.env.ref("product.product_product_4")
cls.project1 = cls.Project.create(
{
"name": "Project1",
"analytic_account_id": cls.analytic_account1.id,
}
)
def test_analytic_account(self):
action = self.project1.action_open_project_purchase_orders()
self.PurchaseOrder = self.PurchaseOrder.with_context(**action["context"])
purchase_order = self.PurchaseOrder.create({"partner_id": self.partner1.id})
purchase_form = Form(purchase_order)
with purchase_form.order_line.new() as line_form:
line_form.product_id = self.product
line_form.name = self.product.name
line_form.product_qty = 10
line_form.price_unit = 20
line_form.product_uom = self.product.uom_id
line_form.date_planned = date.today()
purchase_form.save()
self.assertEqual(
purchase_order.account_analytic_id, self.project1.analytic_account_id
)
| 39.613636 | 1,743 |
606 | py | PYTHON | 15.0 | # Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import api, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.depends("product_id", "date_order")
def _compute_account_analytic_id(self):
# prevent standard account_analytic_id computation
# if order is created from project with smart button
# providing account_analytic_id in context
if self.env.context.get("default_account_analytic_id"):
return True
return super()._compute_account_analytic_id()
| 35.647059 | 606 |
819 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import models
class Project(models.Model):
_inherit = "project.project"
def action_open_project_purchase_orders(self):
action_window = super().action_open_project_purchase_orders()
purchase_orders = self.env["purchase.order"].search(action_window["domain"])
action_window.update(
{
"context": {
"create": True,
"default_account_analytic_id": self.analytic_account_id.id,
}
}
)
if len(purchase_orders) == 1:
action_window.update({"views": [[False, "tree"], [False, "form"]]})
action_window.update({"res_id": None})
return action_window
| 34.125 | 819 |
1,249 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Project Forecast Lines",
"summary": "Project Forecast Lines",
"version": "15.0.1.3.1",
"author": "Camptocamp SA, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Project",
"website": "https://github.com/OCA/project",
"depends": ["sale_timesheet", "sale_project", "hr_holidays"],
"data": [
"security/forecast_line_security.xml",
"security/ir.model.access.csv",
"views/sale_order_views.xml",
"views/hr_employee_views.xml",
"views/forecast_line_views.xml",
"views/forecast_role_views.xml",
"views/product_views.xml",
"views/project_task_views.xml",
"views/project_project_stage_views.xml",
"views/res_config_settings_views.xml",
"data/ir_cron.xml",
"data/project_data.xml",
],
"demo": [
"demo/res_users.xml",
"demo/forecast_role.xml",
"demo/hr_job.xml",
"demo/hr_employee.xml",
"demo/product.xml",
"demo/project.xml",
"demo/sale.xml",
],
"installable": True,
"development_status": "Alpha",
"application": True,
}
| 32.868421 | 1,249 |
43,609 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import date
from freezegun import freeze_time
from odoo.tests.common import Form, TransactionCase, tagged
@tagged("-at_install", "post_install")
class BaseForecastLineTest(TransactionCase):
@classmethod
@freeze_time("2022-01-01")
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.ResUsers = cls.env["res.users"]
cls.ResPartner = cls.env["res.partner"]
cls.HrEmployee = cls.env["hr.employee"]
cls.HrEmployeeForecastRole = cls.env["hr.employee.forecast.role"]
cls.role_model = cls.HrEmployeeForecastRole._name
ProductProduct = cls.env["product.product"]
cls.env.company.write(
{
"forecast_line_granularity": "month",
"forecast_line_horizon": 6, # months
}
)
cls.role_developer = cls.env["forecast.role"].create({"name": "developer"})
cls.role_consultant = cls.env["forecast.role"].create({"name": "consultant"})
cls.role_pm = cls.env["forecast.role"].create({"name": "project manager"})
cls.employee_dev = cls.HrEmployee.create({"name": "John Dev"})
cls.user_consultant = cls.ResUsers.create(
{"name": "John Consultant", "login": "jc@example.com"}
)
cls.employee_consultant = cls.HrEmployee.create(
{"name": "John Consultant", "user_id": cls.user_consultant.id}
)
cls.user_pm = cls.ResUsers.create(
{"name": "John Peem", "login": "jp@example.com"}
)
cls.employee_pm = cls.HrEmployee.create(
{"name": "John Peem", "user_id": cls.user_pm.id}
)
cls.dev_employee_forecast_role = cls.HrEmployeeForecastRole.create(
{
"employee_id": cls.employee_dev.id,
"role_id": cls.role_developer.id,
"date_start": "2022-01-01",
"sequence": 1,
}
)
cls.consult_employee_forecast_role = cls.HrEmployeeForecastRole.create(
{
"employee_id": cls.employee_consultant.id,
"role_id": cls.role_consultant.id,
"date_start": "2022-01-01",
"sequence": 1,
}
)
cls.pm_employee_forecast_role = cls.HrEmployeeForecastRole.create(
{
"employee_id": cls.employee_pm.id,
"role_id": cls.role_pm.id,
"date_start": "2022-01-01",
"sequence": 1,
}
)
cls.product_dev_tm = ProductProduct.create(
{
"name": "development time and material",
"detailed_type": "service",
"service_tracking": "task_in_project",
"price": 95,
"standard_price": 75,
"forecast_role_id": cls.role_developer.id,
"uom_id": cls.env.ref("uom.product_uom_hour").id,
"uom_po_id": cls.env.ref("uom.product_uom_hour").id,
}
)
cls.product_consultant_tm = ProductProduct.create(
{
"name": "consultant time and material",
"detailed_type": "service",
"service_tracking": "task_in_project",
"price": 100,
"standard_price": 80,
"forecast_role_id": cls.role_consultant.id,
"uom_id": cls.env.ref("uom.product_uom_hour").id,
"uom_po_id": cls.env.ref("uom.product_uom_hour").id,
}
)
cls.product_pm_tm = ProductProduct.create(
{
"name": "pm time and material",
"detailed_type": "service",
"service_tracking": "task_in_project",
"price": 120,
"standard_price": 100,
"forecast_role_id": cls.role_consultant.id,
"uom_id": cls.env.ref("uom.product_uom_hour").id,
"uom_po_id": cls.env.ref("uom.product_uom_hour").id,
}
)
cls.customer = cls.ResPartner.create({"name": "Some Customer"})
class TestForecastLineEmployee(BaseForecastLineTest):
def test_employee_main_role(self):
self.HrEmployeeForecastRole.create(
{
"employee_id": self.employee_consultant.id,
"role_id": self.role_developer.id,
"date_start": "2021-01-01",
"date_end": "2021-12-31",
"sequence": 0,
}
)
self.assertEqual(self.employee_consultant.main_role_id, self.role_consultant)
def test_employee_job_role(self):
job = self.env["hr.job"].create(
{"name": "Developer", "role_id": self.role_developer.id}
)
employee = self.env["hr.employee"].create(
{"name": "John Dev", "job_id": job.id}
)
self.assertEqual(employee.main_role_id, self.role_developer)
self.assertEqual(len(employee.role_ids), 1)
self.assertEqual(employee.role_ids.rate, 100)
def test_employee_job_role_change(self):
job1 = self.env["hr.job"].create(
{"name": "Consultant", "role_id": self.role_consultant.id}
)
job2 = self.env["hr.job"].create(
{"name": "Developer", "role_id": self.role_developer.id}
)
employee = self.env["hr.employee"].create(
{"name": "John Dev", "job_id": job2.id}
)
employee.job_id = job1
self.assertEqual(employee.main_role_id, self.role_consultant)
self.assertEqual(len(employee.role_ids), 1)
self.assertEqual(employee.role_ids.rate, 100)
@freeze_time("2022-01-01")
def test_employee_forecast(self):
lines = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("forecast_role_id", "=", self.role_consultant.id),
("res_model", "=", self.role_model),
]
)
self.assertEqual(len(lines), 6) # 6 months horizon
self.assertEqual(
lines.mapped("forecast_hours"),
# number of working days in the first 6 months of 2022, no vacations
[21.0 * 8, 20.0 * 8, 23.0 * 8, 21.0 * 8, 22.0 * 8, 22.0 * 8],
)
res_ids = self.consult_employee_forecast_role.ids
self.consult_employee_forecast_role.unlink()
to_remove_lines = self.env["forecast.line"].search(
[("res_id", "in", res_ids), ("res_model", "=", "hr.employee.forecast.role")]
)
self.assertFalse(to_remove_lines.exists())
@freeze_time("2022-01-01")
def test_employee_forecast_unlink(self):
roles = self.employee_consultant.role_ids
lines = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("forecast_role_id", "=", self.role_consultant.id),
("res_model", "=", self.role_model),
]
)
roles.unlink()
self.assertFalse(lines.exists())
@freeze_time("2022-01-01")
def test_employee_forecast_change_roles(self):
# employee becomes 50% consultant, 50% PM on Feb 1st
roles = self.employee_consultant.role_ids
roles.write({"date_end": "2022-01-31"})
self.env["base"].flush()
lines = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("forecast_role_id", "=", self.role_consultant.id),
("res_model", "=", self.role_model),
]
)
self.assertEqual(len(lines), 1) # 100% consultant role now ends on 31/01
self.assertEqual(lines.forecast_hours, 21.0 * 8)
self.HrEmployeeForecastRole.create(
[
{
"employee_id": self.employee_consultant.id,
"role_id": self.role_consultant.id,
"date_start": "2022-02-01",
"sequence": 1,
"rate": 50,
},
{
"employee_id": self.employee_consultant.id,
"role_id": self.role_pm.id,
"date_start": "2022-02-01",
"sequence": 2,
"rate": 50,
},
]
)
self.env["base"].flush()
lines = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("forecast_role_id", "=", self.role_consultant.id),
]
)
self.assertEqual(len(lines), 6) # 6 months horizon
self.assertEqual(
lines.mapped("forecast_hours"),
# number of days in the first 6 months of 2022
[
21.0 * 8,
20.0 * 8 / 2,
23.0 * 8 / 2,
21.0 * 8 / 2,
22.0 * 8 / 2,
22.0 * 8 / 2,
],
)
res_ids = self.consult_employee_forecast_role.ids
self.consult_employee_forecast_role.unlink()
to_remove_lines = self.env["forecast.line"].search(
[("res_id", "in", res_ids), ("res_model", "=", "hr.employee.forecast.role")]
)
self.assertFalse(to_remove_lines.exists())
@freeze_time("2022-01-01 12:00:00")
def test_forecast_with_calendar(self):
calendar = self.employee_dev.resource_calendar_id
self.env["resource.calendar.leaves"].create(
{
"name": "Easter monday",
"calendar_id": calendar.id,
"date_from": "2022-04-18 00:00:00",
"date_to": "2022-04-19 00:00:00", # Easter
"time_type": "leave",
}
)
self.env["base"].flush()
lines = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_dev.id),
("forecast_role_id", "=", self.role_developer.id),
("res_model", "=", self.role_model),
]
)
self.assertEqual(len(lines), 6) # 6 months horizon
self.assertEqual(
lines.mapped("forecast_hours"),
# number of days in the first 6 months of 2022, minus easter in April
[21.0 * 8, 20.0 * 8, 23.0 * 8, (21.0 - 1) * 8, 22.0 * 8, 22.0 * 8],
)
res_ids = self.dev_employee_forecast_role.ids
self.dev_employee_forecast_role.unlink()
to_remove_lines = self.env["forecast.line"].search(
[("res_id", "in", res_ids), ("res_model", "=", "hr.employee.forecast.role")]
)
self.assertFalse(to_remove_lines.exists())
class TestForecastLineSales(BaseForecastLineTest):
def _create_sale(
self, default_forecast_date_start, default_forecast_date_end, uom_qty=10
):
with Form(self.env["sale.order"]) as form:
form.partner_id = self.customer
form.date_order = "2022-01-10 08:00:00"
form.default_forecast_date_start = default_forecast_date_start
form.default_forecast_date_end = default_forecast_date_end
with form.order_line.new() as line:
line.product_id = self.product_dev_tm
line.product_uom_qty = uom_qty # 1 FTE sold
line.product_uom = self.env.ref("uom.product_uom_day")
so = form.save()
return so
@freeze_time("2022-01-01")
def test_draft_sale_order_creates_negative_forecast_forecast(self):
so = self._create_sale("2022-02-07", "2022-02-20")
line = so.order_line[0]
self.assertEqual(line.forecast_date_start, date(2022, 2, 7))
self.assertEqual(line.forecast_date_end, date(2022, 2, 20))
forecast_lines = self.env["forecast.line"].search(
[
("sale_line_id", "=", line.id),
("res_model", "=", "sale.order.line"),
]
)
self.assertEqual(len(forecast_lines), 1) # 10 days on 2022-02-01 to 2022-02-10
self.assertEqual(forecast_lines.type, "forecast")
self.assertEqual(
forecast_lines.forecast_role_id,
self.product_dev_tm.forecast_role_id,
)
self.assertEqual(forecast_lines.forecast_hours, -10 * 8)
self.assertEqual(forecast_lines.cost, -10 * 8 * 75)
self.assertEqual(forecast_lines.date_from, date(2022, 2, 1))
self.assertEqual(forecast_lines.date_to, date(2022, 2, 28))
@freeze_time("2022-01-01")
def test_sale_line_unlink(self):
so = self._create_sale("2022-02-07", "2022-02-20")
line = so.order_line[0]
forecast_lines = self.env["forecast.line"].search(
[
("sale_line_id", "=", line.id),
("res_model", "=", "sale.order.line"),
]
)
line.unlink()
self.assertFalse(forecast_lines.exists())
@freeze_time("2022-01-01")
def test_draft_sale_order_without_dates_no_forecast(self):
"""a draft sale order with no dates on the line does not create forecast"""
so = self._create_sale("2022-02-07", False)
line = so.order_line[0]
self.assertEqual(line.forecast_date_start, date(2022, 2, 7))
self.assertEqual(line.forecast_date_end, False)
forecast_lines = self.env["forecast.line"].search(
[
("sale_line_id", "=", line.id),
("res_model", "=", "sale.order.line"),
]
)
self.assertFalse(forecast_lines)
@freeze_time("2022-01-01")
def test_draft_sale_order_forecast_spread(self):
so = self._create_sale("2022-02-07", "2022-04-17", uom_qty=100)
line = so.order_line[0]
self.assertEqual(line.forecast_date_start, date(2022, 2, 7))
self.assertEqual(line.forecast_date_end, date(2022, 4, 17))
forecast_lines = self.env["forecast.line"].search(
[
("sale_line_id", "=", line.id),
("res_model", "=", "sale.order.line"),
]
)
self.assertEqual(len(forecast_lines), 3)
daily_ratio = 2 * 8 # 2 FTE * 8h days
self.assertAlmostEqual(
forecast_lines[0].forecast_hours,
-1 * daily_ratio * 16, # 16 worked days between 2022 Feb 7 and Feb 28
)
self.assertAlmostEqual(
forecast_lines[1].forecast_hours,
-1 * daily_ratio * 23, # 23 worked days in march 2022
)
self.assertAlmostEqual(
forecast_lines[2].forecast_hours,
-1 * daily_ratio * 11, # 11 worked day between april 1 and 17 2022
)
self.assertEqual(
forecast_lines.mapped("date_from"),
[date(2022, 2, 1), date(2022, 3, 1), date(2022, 4, 1)],
)
self.assertEqual(
forecast_lines.mapped("date_to"),
[date(2022, 2, 28), date(2022, 3, 31), date(2022, 4, 30)],
)
@freeze_time("2022-01-01")
def test_confirm_order_sale_order_no_forecast_line(self):
so = self._create_sale("2022-02-14", "2022-04-14", uom_qty=60)
so.action_confirm()
line = so.order_line[0]
forecast_lines = self.env["forecast.line"].search(
[
("sale_line_id", "=", line.id),
("res_model", "=", "sale.order.line"),
]
)
self.assertFalse(forecast_lines)
@freeze_time("2022-01-01")
def test_confirm_order_sale_order_create_project_task_with_forecast_line(self):
so = self._create_sale("2022-02-14", "2022-04-17", uom_qty=45 * 2) # 2 FTE
so.action_confirm()
line = so.order_line[0]
task = self.env["project.task"].search([("sale_line_id", "=", line.id)])
forecast_lines = self.env["forecast.line"].search(
[("res_id", "=", task.id), ("res_model", "=", "project.task")]
)
self.assertEqual(len(forecast_lines), 3)
self.assertEqual(forecast_lines.mapped("forecast_role_id"), self.role_developer)
daily_ratio = 8 * 2 # 2 FTE
self.assertAlmostEqual(
forecast_lines[0].forecast_hours,
-1 * daily_ratio * 11, # 11 working days on 2022-02-14 -> 2022-02-28
)
self.assertAlmostEqual(
forecast_lines[1].forecast_hours,
-1 * daily_ratio * 23, # 23 working days on 2022-03-01 -> 2022-03-31
)
self.assertAlmostEqual(
forecast_lines[2].forecast_hours,
-1 * daily_ratio * 11, # 11 working days on 2022-04-01 -> 2022-04-17
)
class TestForecastLineTimesheet(BaseForecastLineTest):
def test_timesheet_forecast_lines(self):
with freeze_time("2022-01-01"):
with Form(self.env["sale.order"]) as form:
form.partner_id = self.customer
form.date_order = "2022-01-10 08:00:00"
form.default_forecast_date_start = "2022-02-14"
form.default_forecast_date_end = "2022-04-17"
with form.order_line.new() as line:
line.product_id = self.product_dev_tm
line.product_uom_qty = (
45 * 2
) # 45 working days in the period, sell 2 FTE
line.product_uom = self.env.ref("uom.product_uom_day")
so = form.save()
so.action_confirm()
with freeze_time("2022-02-14"):
line = so.order_line[0]
task = self.env["project.task"].search([("sale_line_id", "=", line.id)])
# timesheet 1d
self.env["account.analytic.line"].create(
{
"employee_id": self.employee_dev.id,
"task_id": task.id,
"project_id": task.project_id.id,
"unit_amount": 8,
}
)
task.flush()
forecast_lines = self.env["forecast.line"].search(
[("res_id", "=", task.id), ("res_model", "=", "project.task")]
)
self.assertEqual(len(forecast_lines), 3)
daily_ratio = (45 * 2 - 1) * 8 / 45
self.assertAlmostEqual(
forecast_lines[0].forecast_hours, -1 * daily_ratio * 11
)
self.assertAlmostEqual(
forecast_lines[1].forecast_hours, -1 * daily_ratio * 23
)
self.assertAlmostEqual(
forecast_lines[2].forecast_hours, -1 * daily_ratio * 11
)
self.assertEqual(
forecast_lines.mapped("date_from"),
[date(2022, 2, 1), date(2022, 3, 1), date(2022, 4, 1)],
)
self.assertEqual(
forecast_lines.mapped("date_to"),
[date(2022, 2, 28), date(2022, 3, 31), date(2022, 4, 30)],
)
def test_timesheet_forecast_lines_cron(self):
"""check recomputation of forecast lines of tasks even if we don"t TS"""
self.test_timesheet_forecast_lines()
with freeze_time("2022-03-10"):
self.env["forecast.line"]._cron_recompute_all()
forecast_lines = self.env["forecast.line"].search(
[("res_model", "=", "project.task")]
)
self.assertEqual(len(forecast_lines), 2)
daily_ratio = (
8
* (45 * 2 - 1)
/ 27 # 27 worked days between 2022-03-10 and 2022-04-17
)
self.assertAlmostEqual(
forecast_lines[0].forecast_hours,
-1
* daily_ratio
* 16, # 16 worked days between 2022-03-10 and 2022-03-31
)
self.assertAlmostEqual(
forecast_lines[1].forecast_hours,
-1
* daily_ratio
* 11, # 11 worked days between 2022-04-01 and 2022-04-17
)
self.assertEqual(
forecast_lines.mapped("date_from"),
[date(2022, 3, 1), date(2022, 4, 1)],
)
self.assertEqual(
forecast_lines.mapped("date_to"),
[date(2022, 3, 31), date(2022, 4, 30)],
)
class TestForecastLineProjectReschedule(BaseForecastLineTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
# for this test, we use a daily granularity
cls.env.company.write(
{
"forecast_line_granularity": "day",
"forecast_line_horizon": 2, # months
}
)
ProjectProject = cls.env["project.project"]
ProjectTask = cls.env["project.task"]
project = ProjectProject.create({"name": "TestProjectReschedule"})
# set project in stage "in progress" to get confirmed forecast
project.stage_id = cls.env.ref("project.project_project_stage_1")
with freeze_time("2022-02-01 12:00:00"):
cls.task = ProjectTask.create(
{
"name": "TaskReschedule",
"project_id": project.id,
"forecast_role_id": cls.role_consultant.id,
"forecast_date_planned_start": "2022-02-14",
"forecast_date_planned_end": "2022-02-15",
"planned_hours": 16,
}
)
# flush needed here to trigger the recomputation with the correct
# frozen time (otherwise it is called by the test runner before the
# tests, outside of the context manager.
cls.task.flush()
@freeze_time("2022-02-01 12:00:00")
def test_task_unlink(self):
task_forecast = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.task.unlink()
self.assertFalse(task_forecast.exists())
@freeze_time("2022-02-01 12:00:00")
def test_task_forecast_line_reschedule_employee(self):
"""changing the employee will create new lines"""
self.task.user_ids = self.user_consultant
task_forecast = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(task_forecast.mapped("employee_id"), self.employee_consultant)
self.task.user_ids = self.user_pm
self.task.flush()
task_forecast_after = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertNotEqual(task_forecast.ids, task_forecast_after.ids)
self.assertEqual(task_forecast_after.mapped("employee_id"), self.employee_pm)
@freeze_time("2022-02-01 12:00:00")
def test_task_forecast_line_reschedule_dates(self):
"""changing the dates will keep the lines which did not change dates"""
task_forecast = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(task_forecast[0].date_from.strftime("%Y-%m-%d"), "2022-02-14")
self.assertEqual(task_forecast[1].date_from.strftime("%Y-%m-%d"), "2022-02-15")
self.task.write(
{
"forecast_date_planned_start": "2022-02-15",
"forecast_date_planned_end": "2022-02-16",
}
)
self.task.flush()
task_forecast_after = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(
task_forecast_after[0].date_from.strftime("%Y-%m-%d"), "2022-02-15"
)
self.assertEqual(
task_forecast_after[1].date_from.strftime("%Y-%m-%d"), "2022-02-16"
)
self.assertEqual(task_forecast.ids[1], task_forecast_after.ids[0])
self.assertNotEqual(task_forecast.ids[0], task_forecast_after.ids[1])
@freeze_time("2022-02-01 12:00:00")
def test_task_forecast_line_reschedule_time(self):
"""changing the remaining time will keep the forecast lines"""
self.task.user_ids = self.user_consultant
self.task.flush()
task_forecast = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(task_forecast.mapped("forecast_hours"), [-8, -8])
self.task.write({"planned_hours": 24})
self.task.flush()
task_forecast_after = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(task_forecast_after.mapped("forecast_hours"), [-12, -12])
self.assertEqual(task_forecast.ids, task_forecast_after.ids)
@freeze_time("2022-02-01 12:00:00")
def test_task_forecast_line_reschedule_time_no_employee(self):
"""changing the remaining time will keep the forecast lines, even when no
employee assigned"""
self.task.flush()
task_forecast = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(task_forecast.mapped("forecast_hours"), [-8, -8])
self.task.write({"planned_hours": 24})
self.task.flush()
task_forecast_after = self.env["forecast.line"].search(
[("task_id", "=", self.task.id)]
)
self.assertEqual(task_forecast_after.mapped("forecast_hours"), [-12, -12])
self.assertEqual(task_forecast.ids, task_forecast_after.ids)
class TestForecastLineProject(BaseForecastLineTest):
@classmethod
@freeze_time("2022-01-01")
def setUpClass(cls):
super().setUpClass()
# for this test, we use a daily granularity
cls.env.company.write(
{
"forecast_line_granularity": "day",
"forecast_line_horizon": 2, # months
}
)
def _get_employee_forecast(self):
employee_forecast = self.env["forecast.line"].search(
[("employee_id", "=", self.employee_consultant.id)]
)
# we can take first line to check as forecast values are equal
forecast_consultant = employee_forecast.filtered(
lambda l: l.res_model == self.role_model
and l.forecast_role_id == self.role_consultant
)[0]
forecast_pm = employee_forecast.filtered(
lambda l: l.res_model == self.role_model
and l.forecast_role_id == self.role_pm
)[0]
return forecast_consultant, forecast_pm
@freeze_time("2022-02-14 12:00:00")
def test_task_forecast_lines_consolidated_forecast(self):
# set the consultant employee to 75% consultant and 25% PM
self.HrEmployeeForecastRole.create(
{
"employee_id": self.employee_consultant.id,
"role_id": self.role_pm.id,
"date_start": "2022-01-01",
"rate": 25,
"sequence": 1,
}
)
consultant_role = self.HrEmployeeForecastRole.search(
[
("employee_id", "=", self.employee_consultant.id),
("role_id", "=", self.role_consultant.id),
]
)
consultant_role.rate = 75
ProjectProject = self.env["project.project"]
ProjectTask = self.env["project.task"]
# Create 2 project and 2 tasks with role consultant with 8h planned on
# 1 day, assigned to the consultant
#
# Projet 1 is in TODO (not confirmed forecast)
project_1 = ProjectProject.create({"name": "TestProject1"})
# set project in stage "to do" to get forecast
project_1.stage_id = self.env.ref("project.project_project_stage_0")
project_1.flush()
task_values = {
"project_id": project_1.id,
"forecast_role_id": self.role_consultant.id,
"forecast_date_planned_start": "2022-02-14",
"forecast_date_planned_end": "2022-02-14",
"planned_hours": 8,
}
task_values.update({"name": "Task1"})
task_1 = ProjectTask.create(task_values)
task_1.user_ids = self.user_consultant
task_values.update({"name": "Task2"})
task_2 = ProjectTask.create(task_values)
task_2.user_ids = self.user_consultant
# Project 2 is in stage "in rogress" to get forecast
project_2 = ProjectProject.create({"name": "TestProject2"})
project_2.stage_id = self.env.ref("project.project_project_stage_1")
project_2.flush()
task_values.update({"project_id": project_2.id, "name": "Task3"})
task_3 = ProjectTask.create(task_values)
task_3.user_ids = self.user_consultant
task_values.update({"name": "Task4"})
task_4 = ProjectTask.create(task_values)
task_4.user_ids = self.user_consultant
# check forecast lines
forecast = self.env["forecast.line"].search(
[("task_id", "in", (task_1.id, task_2.id, task_3.id, task_4.id))]
)
self.assertEqual(len(forecast), 4)
self.assertEqual(
forecast.mapped("forecast_hours"),
[
-8.0,
]
* 4,
)
# consolidated forecast is in days of 8 hours
self.assertEqual(forecast.mapped("consolidated_forecast"), [1.0] * 4)
self.assertEqual(
forecast.filtered(lambda r: r.type == "forecast").mapped(
"confirmed_consolidated_forecast"
),
[0.0] * 2,
)
self.assertEqual(
forecast.filtered(lambda r: r.type == "confirmed").mapped(
"confirmed_consolidated_forecast"
),
[1.0] * 2,
)
forecast_consultant, forecast_pm = self._get_employee_forecast()
self.assertEqual(forecast_consultant.forecast_hours, 6.0)
self.assertAlmostEqual(
forecast_consultant.consolidated_forecast, 1.0 * 75 / 100 - 4
)
self.assertAlmostEqual(
forecast_consultant.confirmed_consolidated_forecast, 1.0 * 75 / 100 - 2
)
self.assertEqual(forecast_pm.forecast_hours, 2.0)
self.assertAlmostEqual(forecast_pm.consolidated_forecast, 0.25)
self.assertAlmostEqual(forecast_pm.confirmed_consolidated_forecast, 0.25)
res_ids = project_1.task_ids.ids
project_1.task_ids.unlink()
to_remove_lines = self.env["forecast.line"].search(
[("res_id", "in", res_ids), ("res_model", "=", "project.task")]
)
self.assertFalse(to_remove_lines.exists())
@freeze_time("2022-01-01 12:00:00")
def test_forecast_with_holidays(self):
self.test_task_forecast_lines_consolidated_forecast()
with Form(self.env["hr.leave"]) as form:
form.employee_id = self.employee_consultant
form.holiday_status_id = self.env.ref("hr_holidays.holiday_status_unpaid")
form.request_date_from = "2022-02-14"
form.request_date_to = "2022-02-15"
form.request_hour_from = "8"
form.request_hour_to = "18"
leave_request = form.save()
# validating the leave request will recompute the forecast lines for
# the employee capactities (actually delete the existing ones and
# create new ones -> we check that the project task lines are
# automatically related to the new newly created employee role lines.
leave_request.action_validate()
leave_request.flush()
forecast_lines = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("res_model", "=", self.role_model),
("date_from", ">=", "2022-02-14"),
("date_to", "<=", "2022-02-15"),
]
)
# 1 line per role per day -> 4 lines
self.assertEqual(len(forecast_lines), 2 * 2)
forecast_lines_consultant = forecast_lines.filtered(
lambda r: r.forecast_role_id == self.role_consultant
)
# both new lines have now a capacity of 0 (employee is on holidays)
self.assertEqual(forecast_lines_consultant[0].forecast_hours, 0)
self.assertEqual(forecast_lines_consultant[1].forecast_hours, 0)
# first line has a negative consolidated forecast (because of the task)
self.assertEqual(forecast_lines_consultant[0].consolidated_forecast, 0 - 2)
self.assertEqual(forecast_lines_consultant[1].consolidated_forecast, -0)
def test_task_forecast_lines_consolidated_forecast_overallocation(self):
ProjectProject = self.env["project.project"]
ProjectTask = self.env["project.task"]
with freeze_time("2022-01-01"):
employee_forecast = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("date_from", "=", "2022-02-14"),
]
)
self.assertEqual(len(employee_forecast), 1)
project = ProjectProject.create({"name": "TestProject"})
# set project in stage "in progress" to get confirmed forecast
project.stage_id = self.env.ref("project.project_project_stage_1")
project.flush()
task = ProjectTask.create(
{
"name": "Task1",
"project_id": project.id,
"forecast_role_id": self.role_consultant.id,
"forecast_date_planned_start": "2022-02-14",
"forecast_date_planned_end": "2022-02-14",
"planned_hours": 8,
}
)
task.remaining_hours = 10
task.user_ids = self.user_consultant
forecast = self.env["forecast.line"].search([("task_id", "=", task.id)])
self.assertEqual(len(forecast), 1)
# using assertEqual on purpose here
self.assertEqual(forecast.forecast_hours, -10.0)
self.assertEqual(forecast.consolidated_forecast, 1.25)
self.assertEqual(forecast.confirmed_consolidated_forecast, 1.25)
self.assertEqual(
forecast.employee_resource_forecast_line_id.consolidated_forecast,
-0.25,
)
self.assertEqual(
forecast.employee_resource_forecast_line_id.confirmed_consolidated_forecast,
-0.25,
)
def test_task_forecast_lines_consolidated_forecast_overallocation_multiple_tasks(
self,
):
ProjectProject = self.env["project.project"]
ProjectTask = self.env["project.task"]
with freeze_time("2022-01-01"):
employee_forecast = self.env["forecast.line"].search(
[
("employee_id", "=", self.employee_consultant.id),
("date_from", "=", "2022-02-14"),
]
)
self.assertEqual(len(employee_forecast), 1)
project = ProjectProject.create({"name": "TestProject"})
# set project in stage "in progress" to get confirmed forecast
project.stage_id = self.env.ref("project.project_project_stage_1")
project.flush()
task1 = ProjectTask.create(
{
"name": "Task1",
"project_id": project.id,
"forecast_role_id": self.role_consultant.id,
"forecast_date_planned_start": "2022-02-14",
"forecast_date_planned_end": "2022-02-14",
"planned_hours": 8,
}
)
task1.remaining_hours = 10
task1.user_ids = self.user_consultant
forecast1 = self.env["forecast.line"].search([("task_id", "=", task1.id)])
self.assertEqual(len(forecast1), 1)
task2 = ProjectTask.create(
{
"name": "Task2",
"project_id": project.id,
"forecast_role_id": self.role_consultant.id,
"forecast_date_planned_start": "2022-02-14",
"forecast_date_planned_end": "2022-02-14",
"planned_hours": 4,
}
)
task2.remaining_hours = 4
task2.user_ids = self.user_consultant
forecast2 = self.env["forecast.line"].search([("task_id", "=", task2.id)])
# using assertEqual on purpose here
self.assertEqual(
forecast1.employee_resource_forecast_line_id,
forecast2.employee_resource_forecast_line_id,
)
self.assertAlmostEqual(
forecast1.employee_resource_forecast_line_id.consolidated_forecast,
-0.75,
)
self.assertAlmostEqual(
forecast1.employee_resource_forecast_line_id.confirmed_consolidated_forecast,
-0.75,
)
@freeze_time("2022-01-03 12:00:00")
def test_task_forecast_lines_employee_different_roles(self):
"""
Test forecast lines when employee has different roles.
Employee has 2 forecast_role_id: consultant 75% and project manager 25%,
working 8h per day (standard calendar).
Create a task with forecast role consultant, with remaining time = 8h
and a scheduled period starting and ending on the same day (today for instance).
Assign this task to the user.
Expected: for the user, on today, 3 forecast lines.
res_model forecast_role_id forecast_hours consolidated_forecast
project.task consultant -8 1 (in days)
hr.employee.forecast.role consultant 6 -0.25 (in days)
hr.employee.forecast.role project manager 2 0.25 (in days)
"""
ProjectProject = self.env["project.project"]
ProjectTask = self.env["project.task"]
self.HrEmployeeForecastRole.create(
{
"employee_id": self.employee_consultant.id,
"role_id": self.role_pm.id,
"date_start": "2022-01-01",
"rate": 25,
"sequence": 1,
}
)
consultant_role = self.HrEmployeeForecastRole.search(
[
("employee_id", "=", self.employee_consultant.id),
("role_id", "=", self.role_consultant.id),
]
)
consultant_role.rate = 75
project = ProjectProject.create({"name": "TestProjectDiffRoles"})
# set project in stage "in progress" to get confirmed forecast
project.stage_id = self.env.ref("project.project_project_stage_1")
project.flush()
task = ProjectTask.create(
{
"name": "TaskDiffRoles",
"project_id": project.id,
"forecast_role_id": self.role_consultant.id,
"forecast_date_planned_start": date.today(),
"forecast_date_planned_end": date.today(),
"planned_hours": 8,
}
)
task.user_ids = self.user_consultant
task_forecast = self.env["forecast.line"].search([("task_id", "=", task.id)])
self.assertEqual(len(task_forecast), 1)
# using assertEqual on purpose here
self.assertEqual(task_forecast.forecast_hours, -8.0)
self.assertEqual(task_forecast.consolidated_forecast, 1.0)
self.assertEqual(task_forecast.confirmed_consolidated_forecast, 1.0)
forecast_consultant, forecast_pm = self._get_employee_forecast()
self.assertEqual(forecast_consultant.forecast_hours, 6.0)
self.assertAlmostEqual(forecast_consultant.consolidated_forecast, -0.25)
self.assertAlmostEqual(
forecast_consultant.confirmed_consolidated_forecast, -0.25
)
self.assertEqual(forecast_pm.forecast_hours, 2.0)
self.assertAlmostEqual(forecast_pm.consolidated_forecast, 0.25)
self.assertAlmostEqual(forecast_pm.confirmed_consolidated_forecast, 0.25)
@freeze_time("2022-01-03 12:00:00")
def test_task_forecast_lines_employee_main_role(self):
"""
Test forecast lines when employee has different roles
and different from employee's role is assigned to the task.
Employee has 2 forecast_role_id: consultant 75% and project manager 25%,
working 8h per day (standard calendar).
Create a task with forecast role developer, with remaining time = 8h
and a scheduled period starting and ending on the same day (today for instance).
Assign this task to the user.
Expected: for the user, on today, 3 forecast lines.
res_model forecast_role_id forecast_hours consolidated_forecast
project.task consultant -8 1 (in days)
hr.employee.forecast.role consultant 6 -0.25 (in days)
hr.employee.forecast.role project manager 2 0.25 (in days)
"""
ProjectProject = self.env["project.project"]
ProjectTask = self.env["project.task"]
self.HrEmployeeForecastRole.create(
{
"employee_id": self.employee_consultant.id,
"role_id": self.role_pm.id,
"date_start": "2022-01-01",
"rate": 25,
"sequence": 1,
}
)
consultant_role = self.HrEmployeeForecastRole.search(
[
("employee_id", "=", self.employee_consultant.id),
("role_id", "=", self.role_consultant.id),
]
)
consultant_role.rate = 75
project = ProjectProject.create({"name": "TestProjectDiffRoles"})
# set project in stage "in progress" to get confirmed forecast
project.stage_id = self.env.ref("project.project_project_stage_1")
project.flush()
task = ProjectTask.create(
{
"name": "TaskDiffRoles",
"project_id": project.id,
"forecast_role_id": self.role_developer.id,
"forecast_date_planned_start": date.today(),
"forecast_date_planned_end": date.today(),
"planned_hours": 8,
}
)
task.user_ids = self.user_consultant
task_forecast = self.env["forecast.line"].search([("task_id", "=", task.id)])
self.assertEqual(len(task_forecast), 1)
# using assertEqual on purpose here
self.assertEqual(task_forecast.forecast_hours, -8.0)
self.assertEqual(task_forecast.consolidated_forecast, 1.0)
self.assertEqual(task_forecast.confirmed_consolidated_forecast, 1.0)
forecast_consultant, forecast_pm = self._get_employee_forecast()
self.assertEqual(forecast_consultant.forecast_hours, 6.0)
self.assertAlmostEqual(forecast_consultant.consolidated_forecast, -0.25)
self.assertAlmostEqual(
forecast_consultant.confirmed_consolidated_forecast, -0.25
)
self.assertEqual(forecast_pm.forecast_hours, 2.0)
self.assertAlmostEqual(forecast_pm.consolidated_forecast, 0.25)
self.assertAlmostEqual(forecast_pm.confirmed_consolidated_forecast, 0.25)
| 42.462512 | 43,609 |
3,255 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import _, api, fields, models
_logger = logging.getLogger(__name__)
class HrLeave(models.Model):
_name = "hr.leave"
_inherit = ["hr.leave", "forecast.line.mixin"]
@api.model_create_multi
def create(self, vals_list):
leaves = super().create(vals_list)
leaves._update_forecast_lines()
return leaves
def write(self, values):
res = super().write(values)
self._update_forecast_lines()
return res
def _update_forecast_lines(self):
forecast_vals = []
ForecastLine = self.env["forecast.line"].sudo()
# XXX try to be smarter and only unlink those needing unlinking, update the others
ForecastLine.search(
[("res_id", "in", self.ids), ("res_model", "=", self._name)]
).unlink()
leaves = self.filtered_domain([("state", "!=", "refuse")])
# we need to use sudo here, because forecast line creation
# requires access to fields declared on hr.employee
# we don't want to restrict them with `groups="hr.group_hr_user"`
# as this will require giving access to employee app,
# which isn't wanted on some projects
# for more details see here: .../addons/hr/models/hr_employee.py#L22
for leave in leaves.sudo():
if not leave.employee_id.main_role_id:
_logger.warning(
"No forecast role for employee %s (%s)",
leave.employee_id.name,
leave.employee_id,
)
continue
if leave.state == "validate":
# will be handled by the resource.calendar.leaves
continue
else:
forecast_type = "forecast"
forecast_vals += ForecastLine._prepare_forecast_lines(
name=_("Leave"),
date_from=leave.date_from.date(),
date_to=leave.date_to.date(),
ttype=forecast_type,
forecast_hours=ForecastLine.convert_days_to_hours(
-1 * leave.number_of_days
),
unit_cost=leave.employee_id.timesheet_cost,
forecast_role_id=leave.employee_id.main_role_id.id,
hr_leave_id=leave.id,
employee_id=leave.employee_id.id,
res_model=self._name,
res_id=leave.id,
)
return ForecastLine.create(forecast_vals)
@api.model
def _recompute_forecast_lines(self, force_company_id=None):
today = fields.Date.context_today(self)
if force_company_id:
companies = self.env["res.company"].browse(force_company_id)
else:
companies = self.env["res.company"].search([])
for company in companies:
to_update = self.with_company(company).search(
[
("date_to", ">=", today),
("employee_company_id", "=", company.id),
]
)
to_update._update_forecast_lines()
# XXX: leave request should create forcast negative forecast?
| 37.848837 | 3,255 |
1,046 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
default_forecast_date_start = fields.Date()
default_forecast_date_end = fields.Date()
# XXX rewrite this based on a trigger field on so lines
def action_cancel(self):
res = super().action_cancel()
self.filtered(lambda r: r.state == "cancel").mapped(
"order_line"
)._update_forecast_lines()
return res
def action_confirm(self):
res = super().action_confirm()
self.filtered(lambda r: r.state == "sale").mapped(
"order_line"
)._update_forecast_lines()
return res
def write(self, values):
res = super().write(values)
if self and "project_id" in values:
self.env["forecast.line"].sudo().search(
[("sale_id", "in", self.ids)]
).write({"project_id": values["project_id"]})
return res
| 31.69697 | 1,046 |
1,689 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import api, models
class ResourceCalendarLeaves(models.Model):
_name = "resource.calendar.leaves"
_inherit = ["resource.calendar.leaves", "forecast.line.mixin"]
@api.model_create_multi
def create(self, vals_list):
recs = super().create(vals_list)
recs._update_forecast_lines()
return recs
def write(self, values):
res = super().write(values)
self._update_forecast_lines()
return res
def _get_resource_roles(self):
resources = self.mapped("resource_id")
if resources:
employees = self.env["hr.employee"].search([("id", "in", resources.ids)])
else:
employees = self.env["hr.employee"].search(
[("company_id", "in", self.mapped("company_id").ids)]
)
roles = self.env["hr.employee.forecast.role"].search(
[("employee_id", "in", employees.ids)]
)
return roles
def _update_forecast_lines(self):
roles = self._get_resource_roles()
if self:
date_start = min(self.mapped("date_from")).date() - relativedelta(days=1)
date_to = max(self.mapped("date_to")).date() + relativedelta(days=1)
else:
date_start = date_to = None
roles.with_context(
date_start=date_start, date_to=date_to
)._update_forecast_lines()
def unlink(self):
roles = self._get_resource_roles()
res = super().unlink()
roles._update_forecast_lines()
return res
| 33.117647 | 1,689 |
19,521 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from datetime import datetime, time
import pytz
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
from odoo.tools import date_utils, mute_logger
_logger = logging.getLogger(__name__)
class ForecastLine(models.Model):
"""
we generate 1 forecast line per period defined on the current company (day, week, month).
"""
_name = "forecast.line"
_order = "date_from, employee_id, project_id"
_description = "Forecast"
name = fields.Char(required=True)
date_from = fields.Date(
required=True, help="Date of the period start for this line"
)
date_to = fields.Date(required=True)
forecast_role_id = fields.Many2one(
"forecast.role",
string="Forecast role",
required=True,
index=True,
ondelete="restrict",
)
employee_id = fields.Many2one("hr.employee", string="Employee", ondelete="cascade")
employee_forecast_role_id = fields.Many2one(
"hr.employee.forecast.role", string="Employee Forecast Role", ondelete="cascade"
)
project_id = fields.Many2one(
"project.project", index=True, string="Project", ondelete="cascade"
)
task_id = fields.Many2one(
"project.task", index=True, string="Task", ondelete="cascade"
)
sale_id = fields.Many2one(
"sale.order",
related="sale_line_id.order_id",
store=True,
index=True,
string="Sale",
)
sale_line_id = fields.Many2one(
"sale.order.line", index=True, string="Sale line", ondelete="cascade"
)
hr_leave_id = fields.Many2one(
"hr.leave", index=True, string="Leave", ondelete="cascade"
)
forecast_hours = fields.Float(
"Forecast",
help="Forecast (in hours). Forecast is positive for resources which add forecast, "
"such as employees, and negative for things which consume forecast, such as "
"holidays, sales, or tasks.",
)
cost = fields.Monetary(
help="Cost, in company currency. Cost is positive for things which add forecast, "
"such as employees and negative for things which consume forecast such as "
"holidays, sales, or tasks. ",
)
consolidated_forecast = fields.Float(
help="Consolidated forecast for lines of all types consumed",
digits=(12, 5),
store=True,
compute="_compute_consolidated_forecast",
)
confirmed_consolidated_forecast = fields.Float(
string="Confirmed lines consolidated forecast",
help="Consolidated forecast for lines of type confirmed",
digits=(12, 5),
store=True,
compute="_compute_consolidated_forecast",
)
currency_id = fields.Many2one(related="company_id.currency_id", store=True)
company_id = fields.Many2one(
"res.company", required=True, default=lambda s: s.env.company
)
type = fields.Selection(
[("forecast", "Forecast"), ("confirmed", "Confirmed")],
required=True,
default="forecast",
)
res_model = fields.Char(string="Model", index=True)
res_id = fields.Integer(string="Record ID", index=True)
employee_resource_forecast_line_id = fields.Many2one(
"forecast.line",
store=True,
index=True,
compute="_compute_employee_forecast_line_id",
ondelete="set null",
help="technical field giving the name of the resource "
"(model=hr.employee.forecast.role) line for that employee and that period",
)
employee_resource_consumption_ids = fields.One2many(
"forecast.line", "employee_resource_forecast_line_id"
)
def write(self, vals):
# avoid retriggering the costly recomputation of
# employee_forecast_line_id when updating the lines during
# recomputation if the values have not changed for the trigger fields
if len(self) == 1:
for key in ("date_from", "type", "res_model"):
if key in vals and self[key] == vals[key]:
del vals[key]
if "employee_id" in vals and self["employee_id"].id == vals["employee_id"]:
del vals["employee_id"]
if vals:
return super().write(vals)
else:
return True
@api.depends("employee_id", "date_from", "type", "res_model")
def _compute_employee_forecast_line_id(self):
employees = self.mapped("employee_id")
main_roles = employees.mapped("main_role_id")
date_froms = self.mapped("date_from")
date_tos = self.mapped("date_to")
forecast_roles = self.mapped("forecast_role_id") | main_roles
if employees:
lines = self.search(
[
("employee_id", "in", employees.ids),
("forecast_role_id", "in", forecast_roles.ids),
("res_model", "=", "hr.employee.forecast.role"),
("date_from", ">=", min(date_froms)),
("date_to", "<=", max(date_tos)),
("type", "=", "confirmed"),
]
)
else:
lines = self.env["forecast.line"]
capacities = {}
for line in lines:
employee_id = line.employee_id
date_from = line.date_from
forecast_role_id = line.forecast_role_id
capacities[(employee_id.id, date_from, forecast_role_id.id)] = line.id
for rec in self:
if (
rec.type in ("forecast", "confirmed")
and rec.res_model != "hr.employee.forecast.role"
):
resource_forecast_line = capacities.get(
(rec.employee_id.id, rec.date_from, rec.forecast_role_id.id), False
)
if resource_forecast_line:
rec.employee_resource_forecast_line_id = resource_forecast_line
else:
# if we didn't find a forecast line with a matching role
# we get forecast line with the main role of the employee
main_role_id = rec.employee_id.main_role_id
rec.employee_resource_forecast_line_id = capacities.get(
(rec.employee_id.id, rec.date_from, main_role_id.id), False
)
else:
rec.employee_resource_forecast_line_id = False
def _get_grouped_line_values(self):
data = {}
grouped_line_result = self.env["forecast.line"].read_group(
[("employee_resource_forecast_line_id", "in", self.ids)],
fields=["forecast_hours"],
groupby=["employee_resource_forecast_line_id", "type"],
lazy=False,
)
for d in grouped_line_result:
line_id = d["employee_resource_forecast_line_id"][0]
if line_id not in data:
data[line_id] = {"confirmed": 0, "forecast": 0}
data[line_id][d["type"]] += d["forecast_hours"]
return data
@api.model
def _get_consolidation_uom(self):
"""
Returns the unit of measure used for the consolidated forecast.
The default is days.
"""
return self.env.ref("uom.product_uom_day")
def _convert_hours_to_days(self, hours):
to_convert_uom = self._get_consolidation_uom()
project_time_mode_id = self.company_id.project_time_mode_id
return project_time_mode_id._compute_quantity(
hours, to_convert_uom, round=False
)
@api.depends("employee_resource_consumption_ids.forecast_hours", "forecast_hours")
def _compute_consolidated_forecast(self):
grouped_lines_values = self._get_grouped_line_values()
for rec in self:
if rec.res_model != "hr.employee.forecast.role":
rec.consolidated_forecast = (
self._convert_hours_to_days(rec.forecast_hours) * -1
)
if rec.type == "confirmed":
rec.confirmed_consolidated_forecast = rec.consolidated_forecast
else:
rec.confirmed_consolidated_forecast = 0.0
else:
resource_forecast = grouped_lines_values.get(rec.id, 0)
confirmed = (
resource_forecast.get("confirmed", 0) if resource_forecast else 0
)
unconfirmed = (
confirmed + resource_forecast.get("forecast", 0)
if resource_forecast
else 0
)
rec.consolidated_forecast = self._convert_hours_to_days(
rec.forecast_hours + unconfirmed
)
rec.confirmed_consolidated_forecast = self._convert_hours_to_days(
rec.forecast_hours + confirmed
)
def _update_forecast_lines(
self,
name,
date_from,
date_to,
ttype,
forecast_hours,
unit_cost,
res_model,
res_id=0,
**kwargs
):
"""this method is called on a recordset, it will update it so that all the
lines in the set are correct, removing the ones which need removing and
creating the missing ones. Updates lines, and return a list of dict to pass to
create"""
values = self._prepare_forecast_lines(
name,
date_from,
date_to,
ttype,
forecast_hours,
unit_cost,
res_model=res_model,
res_id=res_id,
**kwargs
)
to_create = []
self_by_start_date = {r.date_from: r for r in self}
updated = []
for vals in values:
start_date = vals["date_from"]
rec = self_by_start_date.pop(start_date, None)
if rec is None:
to_create.append(vals)
else:
rec.write(vals)
updated.append(rec.id)
_logger.debug("updated lines %s", updated)
to_remove = self.browse([r.id for r in self_by_start_date.values()])
to_remove.unlink()
_logger.debug("removed lines %s", to_remove.ids)
_logger.debug("%d records to create", len(to_create))
return to_create
def _prepare_forecast_lines(
self,
name,
date_from,
date_to,
ttype,
forecast_hours,
unit_cost,
res_model="",
res_id=0,
**kwargs
):
common_value_dict = {
"company_id": self.env.company.id,
"name": name,
"type": ttype,
"forecast_role_id": kwargs.get("forecast_role_id", False),
"employee_id": kwargs.get("employee_id", False),
"project_id": kwargs.get("project_id", False),
"task_id": kwargs.get("task_id", False),
"sale_line_id": kwargs.get("sale_line_id", False),
"hr_leave_id": kwargs.get("hr_leave_id", False),
"employee_forecast_role_id": kwargs.get("employee_forecast_role_id", False),
"res_model": res_model,
"res_id": res_id,
}
forecast_line_vals = []
if common_value_dict["employee_id"]:
resource = (
self.env["hr.employee"]
.browse(common_value_dict["employee_id"])
.resource_id
)
calendar = resource.calendar_id
else:
resource = self.env["resource.resource"]
calendar = self.env.company.resource_calendar_id
for updates in self._split_per_period(
date_from, date_to, forecast_hours, unit_cost, resource, calendar
):
values = common_value_dict.copy()
values.update(updates)
forecast_line_vals.append(values)
return forecast_line_vals
def _company_horizon_end(self):
company = self.env.company
today = fields.Date.context_today(self)
horizon_end = today + relativedelta(months=company.forecast_line_horizon)
return horizon_end
def _compute_horizon(self, date_from, date_to):
today = fields.Date.context_today(self)
horizon_end = self._company_horizon_end()
# the date_to passed as argument is "included". We want to be able to
# reason with this date "excluded" when doing substractions to compute
# a number of days -> add 1d
date_to += relativedelta(days=1)
horiz_date_from = max(date_from, today)
horiz_date_to = min(date_to, horizon_end)
return horiz_date_from, horiz_date_to, date_to
def _split_per_period(
self, date_from, date_to, forecast_hours, unit_cost, resource, calendar
):
company = self.env.company
granularity = company.forecast_line_granularity
delta = date_utils.get_timedelta(1, granularity)
horiz_date_from, horiz_date_to, date_to = self._compute_horizon(
date_from, date_to
)
curr_date = date_utils.start_of(horiz_date_from, granularity)
if horiz_date_to <= horiz_date_from:
return
whole_period_forecast = self._number_of_hours(
horiz_date_from, horiz_date_to, resource, calendar
)
if whole_period_forecast == 0:
# the resource if completely off during the period -> we cannot
# plan the forecast in the period. We put the whole forecast on the
# day after the period.
# TODO future improvement: dump this on the
# first day when the employee is not on holiday
_logger.warning(
"resource %s has 0 forecast on period %s -> %s",
resource,
horiz_date_from,
horiz_date_to,
)
yield {
"date_from": horiz_date_to,
"date_to": horiz_date_to + delta - relativedelta(days=1),
"forecast_hours": forecast_hours,
"cost": forecast_hours * unit_cost,
}
return
daily_forecast = forecast_hours / whole_period_forecast
if daily_forecast == 0:
return
while curr_date < horiz_date_to:
next_date = curr_date + delta
# XXX fix periods which are not entirely in the horizon
# (min max trick on the numerator of the division)
period_forecast = self._number_of_hours(
max(curr_date, date_from),
min(next_date, date_to),
resource,
calendar,
)
# note we do create lines even if the period_forecast is 0, as this
# ensures that consolidated capacity can be computed: if there is
# no line for a day when the employee does not work, but for some
# reason there is a need on that day, we need the 0 capacity line
# to compute the negative consolidated capacity.
period_forecast *= daily_forecast
period_cost = period_forecast * unit_cost
updates = {
"date_from": curr_date,
"date_to": next_date - relativedelta(days=1),
"forecast_hours": period_forecast,
"cost": period_cost,
}
yield updates
curr_date = next_date
@api.model
def _cron_recompute_all(self, force_company_id=None, force_delete=False):
today = fields.Date.context_today(self)
ForecastLine = self.env["forecast.line"].sudo()
if force_company_id:
companies = self.env["res.company"].browse(force_company_id)
else:
companies = self.env["res.company"].search([])
for company in companies:
ForecastLine = ForecastLine.with_company(company)
limit_date = date_utils.start_of(today, company.forecast_line_granularity)
if force_delete:
stale_forecast_lines = ForecastLine.search(
[
("company_id", "=", company.id),
]
)
else:
stale_forecast_lines = ForecastLine.search(
[
("date_from", "<", limit_date),
("company_id", "=", company.id),
]
)
stale_forecast_lines.unlink()
# always start with forecast role to ensure we can compute the
# employee_resource_forecast_line_id field
self.env["hr.employee.forecast.role"]._recompute_forecast_lines(
force_company_id=force_company_id
)
self.env["sale.order.line"]._recompute_forecast_lines(
force_company_id=force_company_id
)
self.env["hr.leave"]._recompute_forecast_lines(
force_company_id=force_company_id
)
self.env["project.task"]._recompute_forecast_lines(
force_company_id=force_company_id
)
# fix weird issue where the employee_resource_forecast_line_id seems to
# not be always computed
ForecastLine.search([])._compute_employee_forecast_line_id()
@api.model
def convert_days_to_hours(self, days):
uom_day = self.env.ref("uom.product_uom_day")
uom_hour = self.env.ref("uom.product_uom_hour")
return uom_day._compute_quantity(days, uom_hour)
@api.model
def _number_of_hours(
self, date_from, date_to, resource, calendar, force_granularity=False
):
if force_granularity:
company = self.env.company
granularity = company.forecast_line_granularity
date_from = date_utils.start_of(date_from, granularity)
date_to = date_utils.end_of(date_to, granularity) + relativedelta(days=1)
tzinfo = pytz.timezone(calendar.tz)
start_dt = tzinfo.localize(datetime.combine(date_from, time(0)))
end_dt = tzinfo.localize(datetime.combine(date_to, time(0)))
intervals = calendar._work_intervals_batch(
start_dt, end_dt, resources=resource
)[resource.id]
nb_hours = sum(
(stop - start).total_seconds() / 3600 for start, stop, meta in intervals
)
return nb_hours
def unlink(self):
# we routinely unlink forecast lines, let's not fill the logs with this
with mute_logger("odoo.models.unlink"):
return super().unlink()
@api.model_create_multi
@api.returns("self", lambda value: value.id)
def create(self, vals_list):
records = super().create(vals_list)
employee_role_lines = records.filtered(
lambda r: r.res_model == "hr.employee.forecast.role"
)
if employee_role_lines:
# check for existing records which could have the new lines as
# employee_resource_forecast_line_id
other_lines = self.search(
[
("employee_resource_forecast_line_id", "=", False),
(
"employee_id",
"in",
employee_role_lines.mapped("employee_id").ids,
),
]
)
other_lines._compute_employee_forecast_line_id()
return records
| 39.596349 | 19,521 |
410 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProjectProjectStage(models.Model):
_inherit = "project.project.stage"
forecast_line_type = fields.Selection(
[("forecast", "Forecast"), ("confirmed", "Confirmed")],
help="type of forecast lines created by the tasks of projects in that stage",
)
| 34.166667 | 410 |
5,170 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class SaleOrderLine(models.Model):
_name = "sale.order.line"
_inherit = ["sale.order.line", "forecast.line.mixin"]
forecast_date_start = fields.Date()
forecast_date_end = fields.Date()
@api.model_create_multi
def create(self, vals_list):
lines = super().create(vals_list)
lines._update_forecast_lines()
return lines
def _update_forecast_lines(self):
forecast_vals = []
ForecastLine = self.env["forecast.line"].sudo()
# XXX try to be smarter and only unlink those needing unlinking, update the others
ForecastLine.search(
[("res_id", "in", self.ids), ("res_model", "=", self._name)]
).unlink()
for line in self:
if not line.product_id.forecast_role_id:
continue
elif line.state in ("cancel", "sale"):
# no forecast line for confirmed sales -> this is handled by projects and tasks
continue
elif not (line.forecast_date_end and line.forecast_date_start):
_logger.info(
"sale line with forecast product but no dates -> ignoring %s",
line.id,
)
continue
else:
forecast_type = "forecast"
uom = line.product_uom
quantity_hours = uom._compute_quantity(
line.product_uom_qty, self.env.ref("uom.product_uom_hour")
)
forecast_vals += ForecastLine._prepare_forecast_lines(
name=line.name,
date_from=line.forecast_date_start,
date_to=line.forecast_date_end,
ttype=forecast_type,
forecast_hours=-1 * quantity_hours,
unit_cost=line.product_id.standard_price, # XXX currency + unit conversion
forecast_role_id=line.product_id.forecast_role_id.id,
sale_line_id=line.id,
project_id=line.project_id.id,
res_model="sale.order.line",
res_id=line.id,
)
return ForecastLine.create(forecast_vals)
@api.model
def _recompute_forecast_lines(self, force_company_id=None):
today = fields.Date.context_today(self)
if force_company_id:
companies = self.env["res.company"].browse(force_company_id)
else:
companies = self.env["res.company"].search([])
for company in companies:
to_update = self.with_company(company).search(
[
("forecast_date_end", ">=", today),
("company_id", "=", company.id),
]
)
to_update._update_forecast_lines()
def _update_forecast_lines_trigger_fields(self):
return [
"state",
"product_uom_qty",
"forecast_date_start",
"forecast_date_end",
"product_id",
"name",
]
def _write(self, values):
res = super()._write(values)
trigger_fields = self._update_forecast_lines_trigger_fields()
if any(field in values for field in trigger_fields):
self._update_forecast_lines()
return res
@api.onchange("product_id")
def product_id_change(self):
res = super().product_id_change()
for line in self:
if not line.product_id.forecast_role_id:
line.forecast_date_start = False
line.forecast_date_end = False
else:
if (
not line.forecast_date_start
and line.order_id.default_forecast_date_start
):
line.forecast_date_start = line.order_id.default_forecast_date_start
if (
not line.forecast_date_end
and line.order_id.default_forecast_date_end
):
line.forecast_date_end = line.order_id.default_forecast_date_end
return res
def _timesheet_create_task_prepare_values(self, project):
values = super()._timesheet_create_task_prepare_values(project)
values.update(
{
"forecast_role_id": self.product_id.forecast_role_id.id,
"forecast_date_planned_end": self.forecast_date_end,
"forecast_date_planned_start": self.forecast_date_start,
}
)
return values
def _timesheet_create_project(self):
project = super()._timesheet_create_project()
if self.product_id.project_template_id and self.product_id.forecast_role_id:
project.tasks.write(
{
"forecast_role_id": self.product_id.forecast_role_id.id,
"date_end": self.forecast_date_end,
"date_planned_start": self.forecast_date_start,
}
)
return project
| 37.737226 | 5,170 |
550 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class ForecastLineModelMixin(models.Model):
_name = "forecast.line.mixin"
_description = "mixin for models which generate forecast lines"
def _get_forecast_lines(self, domain=None):
self.ensure_one()
base_domain = [("res.model", "=", self._name), ("res_id", "=", self.id)]
if domain is not None:
base_domain += domain
return self.env["forecast.line"].search(base_domain)
| 36.666667 | 550 |
279 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
forecast_role_id = fields.Many2one("forecast.role", ondelete="restrict")
| 31 | 279 |
316 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ForecastRole(models.Model):
_name = "forecast.role"
_description = "Employee role for task matching"
name = fields.Char(required=True)
description = fields.Text()
| 28.727273 | 316 |
876 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
forecast_line_granularity = fields.Selection(
[("day", "Day"), ("week", "Week"), ("month", "Month")],
default="month",
help="Periodicity of the forecast that will be generated",
)
forecast_line_horizon = fields.Integer(
help="Number of month for the forecast planning", default=12
)
def write(self, values):
res = super().write(values)
if "forecast_line_granularity" in values or "forecast_line_horizon" in values:
for company in self:
self.env["forecast.line"]._cron_recompute_all(
force_company_id=company.id, force_delete=True
)
return res
| 35.04 | 876 |
6,293 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class HrJob(models.Model):
_inherit = "hr.job"
role_id = fields.Many2one("forecast.role", ondelete="restrict")
class HrEmployee(models.Model):
_inherit = "hr.employee"
role_ids = fields.One2many("hr.employee.forecast.role", "employee_id")
main_role_id = fields.Many2one(
"forecast.role", compute="_compute_main_role_id", ondelete="restrict"
)
def _compute_main_role_id(self):
# can"t store as it depends on current date
today = fields.Date.context_today(self)
for rec in self:
rec.main_role_id = rec.role_ids.filtered(
lambda r: r.date_start <= today and (r.date_end >= today)
if r.date_end
else True
)[:1].role_id
def write(self, values):
values = self._check_job_role(values)
return super().write(values)
@api.model_create_multi
@api.returns("self", lambda value: value.id)
def create(self, values):
values = [self._check_job_role(val) for val in values]
return super().create(values)
def _check_job_role(self, values):
"""helper method
ensures that you get a role when you set a job with a role"""
new_job_id = values.get("job_id")
if new_job_id:
job = self.env["hr.job"].browse(new_job_id)
if job.role_id and "role_ids" not in values:
values = values.copy()
values["role_ids"] = [
fields.Command.clear(),
fields.Command.create({"role_id": job.role_id.id}),
]
return values
class HrEmployeeForecastRole(models.Model):
_name = "hr.employee.forecast.role"
_inherit = "forecast.line.mixin"
_description = "Employee forecast role"
_order = "employee_id, date_start, sequence, rate DESC, id"
employee_id = fields.Many2one("hr.employee", required=True, ondelete="cascade")
role_id = fields.Many2one("forecast.role", required=True)
date_start = fields.Date(required=True, default=fields.Date.today)
date_end = fields.Date()
rate = fields.Integer(default=100)
sequence = fields.Integer()
company_id = fields.Many2one(related="employee_id.company_id", store=True)
# TODO:
# ensure sum of rate = 100
@api.model_create_multi
def create(self, vals_list):
recs = super().create(vals_list)
recs._update_forecast_lines()
return recs
def write(self, values):
res = super().write(values)
self._update_forecast_lines()
return res
def _update_forecast_lines(self):
today = fields.Date.context_today(self)
leave_date_start = self.env.context.get("date_start")
leave_date_to = self.env.context.get("date_to")
ForecastLine = self.env["forecast.line"].sudo()
if not self:
return ForecastLine
leaves = self.env["hr.leave"].search(
[
("employee_id", "in", self.mapped("employee_id").ids),
("state", "!=", "cancel"),
("date_to", ">=", min(self.mapped("date_start"))),
]
)
leaves._update_forecast_lines()
forecast_vals = []
ForecastLine.search(
[
("res_id", "in", self.ids),
("res_model", "=", self._name),
("date_from", "<", today),
]
).unlink()
horizon_end = ForecastLine._company_horizon_end()
for rec in self:
if rec.date_end:
date_end = rec.date_end
ForecastLine.search(
[
("res_id", "=", rec.id),
("res_model", "=", self._name),
("date_to", ">=", date_end),
]
).unlink()
else:
date_end = horizon_end - relativedelta(days=1)
if leave_date_to is not None:
date_end = min(leave_date_to, date_end)
date_start = max(rec.date_start, today)
if leave_date_start is not None:
date_start = max(date_start, leave_date_start)
resource = rec.employee_id.resource_id
calendar = resource.calendar_id
forecast = ForecastLine._number_of_hours(
date_start, date_end, resource, calendar, force_granularity=True
)
forecast_lines = ForecastLine.search(
[
("res_model", "=", self._name),
("res_id", "in", rec.ids),
("date_from", "<=", date_end),
("date_to", ">=", date_start),
]
)
forecast_vals += forecast_lines._update_forecast_lines(
name="Employee %s as %s (%d%%)"
% (rec.employee_id.name, rec.role_id.name, rec.rate),
date_from=date_start,
date_to=date_end,
forecast_hours=forecast * rec.rate / 100.0,
unit_cost=rec.employee_id.timesheet_cost, # XXX to check
ttype="confirmed",
forecast_role_id=rec.role_id.id,
employee_id=rec.employee_id.id,
employee_forecast_role_id=rec.id,
res_model=self._name,
res_id=rec.id,
)
return ForecastLine.create(forecast_vals)
@api.model
def _recompute_forecast_lines(self, force_company_id=None):
today = fields.Date.context_today(self)
if force_company_id:
companies = self.env["res.company"].browse(force_company_id)
else:
companies = self.env["res.company"].search([])
for company in companies:
to_update = self.with_company(company).search(
[
"|",
("date_end", "=", False),
("date_end", ">=", today),
("company_id", "=", company.id),
]
)
to_update._update_forecast_lines()
| 36.587209 | 6,293 |
9,118 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
import random
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class ProjectTask(models.Model):
_name = "project.task"
_inherit = ["project.task", "forecast.line.mixin"]
forecast_role_id = fields.Many2one("forecast.role", ondelete="restrict")
forecast_date_planned_start = fields.Date("Planned start date")
forecast_date_planned_end = fields.Date("Planned end date")
forecast_recomputation_trigger = fields.Float(
compute="_compute_forecast_recomputation_trigger",
store=True,
help="Technical field used to trigger the forecast recomputation",
)
@api.model_create_multi
def create(self, vals_list):
# compatibility with fields from project_enterprise
for vals in vals_list:
if vals.get("planned_date_begin"):
vals["forecast_date_planned_start"] = vals["planned_date_begin"]
if vals.get("planned_date_end"):
vals["forecast_date_planned_end"] = vals["planned_date_end"]
tasks = super().create(vals_list)
# tasks._update_forecast_lines()
return tasks
def _update_forecast_lines_trigger_fields(self):
return [
# "sale_order_line_id",
"forecast_role_id",
"forecast_date_planned_start",
"forecast_date_planned_end",
# "remaining_hours",
"name",
# "planned_time",
"user_ids",
"project_id.stage_id",
"project_id.stage_id.forecast_line_type",
]
@api.depends(_update_forecast_lines_trigger_fields)
def _compute_forecast_recomputation_trigger(self):
value = random.random()
for rec in self:
rec.forecast_recomputation_trigger = value
def write(self, values):
# compatibility with fields from project_enterprise
if "planned_date_begin" in values:
values["forecast_date_planned_start"] = values["planned_date_begin"]
if "planned_date_end" in values:
values["forecast_date_planned_end"] = values["planned_date_end"]
return super().write(values)
def _write(self, values):
res = super()._write(values)
if "forecast_recomputation_trigger" in values:
self._update_forecast_lines()
elif "remaining_hours" in values:
self._quick_update_forecast_lines()
return res
@api.onchange("user_ids")
def onchange_user_ids(self):
for task in self:
if not task.user_ids:
continue
if task.forecast_role_id:
continue
employees = task.mapped("user_ids.employee_id")
for employee in employees:
if employee.main_role_id:
task.forecast_role_id = employee.main_role_id
break
def _get_task_employees(self):
return self.with_context(active_test=False).mapped("user_ids.employee_id")
def _quick_update_forecast_lines(self):
# called when only the remaining hours have changed. In this case, we
# can only update the forecast lines by applying a ratio
ForecastLine = self.env["forecast.line"].sudo()
for task in self:
forecast_lines = ForecastLine.search(
[("res_model", "=", self._name), ("res_id", "=", task.id)]
)
total_forecast = sum(forecast_lines.mapped("forecast_hours"))
if not forecast_lines or total_forecast:
# no existing forecast lines, try to generate some using the
# normal flow
task._update_forecast_lines()
continue
ratio = task.remaining_hours / total_forecast
for line in forecast_lines:
line.forecast_hours *= ratio
def _should_have_forecast(self):
self.ensure_one()
if not self.forecast_role_id:
_logger.info("skip task %s: no forecast role", self)
return False
elif self.project_id.stage_id:
forecast_type = self.project_id.stage_id.forecast_line_type
if not forecast_type:
_logger.info("skip task %s: no forecast for project state", self)
return False
elif self.sale_line_id:
sale_state = self.sale_line_id.state
if sale_state == "cancel":
_logger.info("skip task %s: cancelled sale", self)
return False
elif sale_state == "sale":
return True
else:
# TODO have forecast quantity if the sale is in Draft and we
# are not generating forecast lines from SO
_logger.info("skip task %s: draft sale")
return False
if not self.forecast_date_planned_start or not self.forecast_date_planned_end:
_logger.info("skip task %s: no planned dates", self)
return False
if not self.remaining_hours:
_logger.info("skip task %s: no remaining hours", self)
return False
if self.remaining_hours < 0:
_logger.info("skip task %s: negative remaining hours", self)
return False
return True
def _update_forecast_lines(self):
_logger.debug("update forecast lines %s", self)
today = fields.Date.context_today(self)
forecast_vals = []
ForecastLine = self.env["forecast.line"].sudo()
task_with_lines_to_clean = []
for task in self:
if not task._should_have_forecast():
task_with_lines_to_clean.append(task.id)
continue
if task.project_id.stage_id:
forecast_type = task.project_id.stage_id.forecast_line_type
elif task.sale_line_id:
if task.sale_line_id.state == "sale":
forecast_type = "confirmed"
else:
forecast_type = "forecast"
date_start = max(today, task.forecast_date_planned_start)
date_end = max(today, task.forecast_date_planned_end)
employee_ids = task._get_task_employees().ids
if not employee_ids:
employee_ids = [False]
_logger.debug(
"compute forecast for task %s: %s to %s %sh",
task,
date_start,
date_end,
task.remaining_hours,
)
forecast_hours = task.remaining_hours / len(employee_ids)
# remove lines for employees which are no longer assigned to the task
ForecastLine.search(
[
("res_model", "=", self._name),
("res_id", "=", task.id),
("employee_id", "not in", tuple(employee_ids)),
]
).unlink()
for employee_id in employee_ids:
employee_lines = ForecastLine.search(
[
("res_model", "=", self._name),
("res_id", "=", task.id),
("employee_id", "=", employee_id),
]
)
forecast_vals += employee_lines._update_forecast_lines(
name=task.name,
date_from=date_start,
date_to=date_end,
ttype=forecast_type,
forecast_hours=-1 * forecast_hours,
# XXX currency + unit conversion
unit_cost=task.sale_line_id.product_id.standard_price,
forecast_role_id=task.forecast_role_id.id,
sale_line_id=task.sale_line_id.id,
task_id=task.id,
project_id=task.project_id.id,
employee_id=employee_id,
res_model=self._name,
res_id=task.id,
)
if task_with_lines_to_clean:
to_clean = ForecastLine.search(
[
("res_model", "=", self._name),
("res_id", "in", tuple(task_with_lines_to_clean)),
]
)
if to_clean:
to_clean.unlink()
lines = ForecastLine.create(forecast_vals)
return lines
@api.model
def _recompute_forecast_lines(self, force_company_id=None):
today = fields.Date.context_today(self)
if force_company_id:
companies = self.env["res.company"].browse(force_company_id)
else:
companies = self.env["res.company"].search([])
for company in companies:
to_update = self.with_company(company).search(
[
("forecast_date_planned_end", ">=", today),
("company_id", "=", company.id),
]
)
to_update._update_forecast_lines()
| 39.816594 | 9,118 |
641 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
forecast_line_granularity = fields.Selection(
related="company_id.forecast_line_granularity", readonly=False
)
forecast_line_horizon = fields.Integer(
related="company_id.forecast_line_horizon", readonly=False
)
group_forecast_line_on_quotation = fields.Boolean(
"Forecast Line on Quotations",
implied_group="project_forecast_line.group_forecast_line_on_quotation",
)
| 33.736842 | 641 |
539 | py | PYTHON | 15.0 | # Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Project HR",
"summary": "Link HR with project",
"development_status": "Production/Stable",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"depends": ["project", "hr"],
"data": ["views/project_task_views.xml", "views/project_project_views.xml"],
"maintainers": ["pedrobaeza"],
}
| 35.933333 | 539 |
392 | py | PYTHON | 15.0 | # Copyright 2023 Tecnativa - Pilar Vargas
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
# Convert m2o to m2m in 'project.task'
openupgrade.m2o_to_x2m(
env.cr,
env["project.task"],
"project_task",
"employee_ids",
"employee_id",
)
| 24.5 | 392 |
4,708 | py | PYTHON | 15.0 | # Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
_logger = logging.getLogger(__name__)
class TestProjectHr(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
user_group_employee = cls.env.ref("base.group_user")
user_group_project_user = cls.env.ref("project.group_project_user")
# Test users to use through the various tests
Users = cls.env["res.users"].with_context(no_reset_password=True)
cls.user1 = Users.create(
{
"name": "Test User1",
"login": "user1",
"password": "user1",
"email": "user1.projecthr@example.com",
"groups_id": [
(6, 0, [user_group_employee.id, user_group_project_user.id])
],
}
)
cls.user2 = Users.create(
{
"name": "Test User2",
"login": "user2",
"password": "user2",
"email": "user2.projecthr@example.com",
"groups_id": [
(6, 0, [user_group_employee.id, user_group_project_user.id])
],
}
)
cls.hr_category = cls.env["hr.employee.category"].create(
{"name": "Test employee category"}
)
cls.hr_category_2 = cls.env["hr.employee.category"].create(
{"name": "Test employee category 2"}
)
cls.hr_category_3 = cls.env["hr.employee.category"].create(
{"name": "Test employee category 3"}
)
cls.employee = cls.env["hr.employee"].create(
{
"name": "Test employee",
"user_id": cls.user1.id,
"category_ids": [(6, 0, cls.hr_category.ids)],
}
)
cls.project = cls.env["project.project"].create(
{"name": "Test project", "hr_category_ids": [(4, cls.hr_category.id)]}
)
cls.task = cls.env["project.task"].create(
{
"name": "Test task",
"project_id": cls.project.id,
"hr_category_ids": [(4, cls.hr_category.id)],
"user_ids": [(6, 0, [cls.user1.id])],
}
)
def test_user(self):
self.assertEqual(self.user1.hr_category_ids, self.hr_category)
self.employee.category_ids = [(4, self.hr_category_2.id)]
self.assertEqual(
self.user1.hr_category_ids, self.hr_category + self.hr_category_2
)
# Check if need invalidate cache
self.employee.category_ids = [(4, self.hr_category_3.id)]
self.assertEqual(
self.user1.hr_category_ids,
self.hr_category + self.hr_category_2 + self.hr_category_3,
)
def test_task(self):
# check computed values on task
self.assertEqual(self.task.employee_ids, self.employee)
self.assertEqual(self.task.allowed_hr_category_ids, self.hr_category)
self.assertEqual(self.task.allowed_assigned_user_ids, self.user1)
self.project.hr_category_ids = [(4, self.hr_category_2.id)]
self.assertEqual(
self.task.allowed_hr_category_ids, self.hr_category + self.hr_category_2
)
self.env["hr.employee"].create(
{
"name": "Test employee 2",
"user_id": self.user2.id,
"category_ids": [(6, 0, self.hr_category.ids)],
}
)
self.assertEqual(self.task.allowed_assigned_user_ids, self.user1 + self.user2)
# Test _check_employee_category_user constraint
with self.assertRaises(ValidationError):
self.task.hr_category_ids = [(4, self.hr_category_2.id)]
# Test _check_employee_category_project constraint
self.project.hr_category_ids = [(4, self.hr_category_2.id)]
with self.assertRaises(ValidationError):
self.task.hr_category_ids = [(4, self.hr_category_2.id)]
# add employee to category hr_category_3
self.employee.category_ids = [(4, self.hr_category_3.id)]
# test assign a category no in project categories
with self.assertRaises(ValidationError):
self.task.hr_category_ids = [(4, self.hr_category_3.id)]
def test_task_project_wo_categories(self):
self.project.hr_category_ids = False
self.assertTrue(self.task.allowed_hr_category_ids)
# This operation shouldn't give error
self.task.hr_category_ids = [(4, self.hr_category.id)]
| 39.563025 | 4,708 |
403 | py | PYTHON | 15.0 | # Copyright 2019 Tecnativa - Victor M.M. Torres
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def create(self, vals):
employee = super().create(vals)
if employee.category_ids:
self.env["project.task"].invalidate_cache()
return employee
| 26.866667 | 403 |
800 | py | PYTHON | 15.0 | # Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResUsers(models.Model):
_inherit = "res.users"
hr_category_ids = fields.Many2many(
comodel_name="hr.employee.category",
string="HR categories",
compute="_compute_hr_category_ids",
help="Technical field for computing dynamically employee categories "
"linked to the user in the current company.",
)
@api.depends("company_id", "employee_ids", "employee_ids.category_ids")
def _compute_hr_category_ids(self):
for user in self:
user.hr_category_ids = user.employee_ids.filtered(
lambda x: x.company_id == user.company_id
)[:1].category_ids
| 34.782609 | 800 |
3,892 | py | PYTHON | 15.0 | # Copyright 2018 Tecnativa - Pedro M. Baeza
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class ProjectTask(models.Model):
_inherit = "project.task"
employee_ids = fields.Many2many(
comodel_name="hr.employee",
string="Linked employee",
compute="_compute_employee_ids",
store=True,
)
hr_category_ids = fields.Many2many(
comodel_name="hr.employee.category",
string="Employee Categories",
domain="[('id', 'in', allowed_hr_category_ids)]",
help="Here you can select the employee category suitable to perform "
"this task, limiting the selectable users to be assigned to "
"those that belongs to that category.",
)
allowed_hr_category_ids = fields.Many2many(
comodel_name="hr.employee.category",
string="Allowed HR categories",
compute="_compute_allowed_hr_category_ids",
help="Technical field for computing allowed employee categories "
"according categories at project level.",
)
# This field could have been named allowed_user_ids but a field with
# that name already exists in the Odoo core 'project' module
allowed_assigned_user_ids = fields.Many2many(
comodel_name="res.users",
string="Allowed users",
compute="_compute_allowed_assigned_user_ids",
help="Technical field for computing allowed users according employee "
"category.",
)
@api.depends("user_ids", "company_id")
def _compute_employee_ids(self):
for task in self.filtered("user_ids"):
task.employee_ids = task.user_ids.employee_ids.filtered(
lambda x: x.company_id == task.company_id
)
@api.depends("project_id", "project_id.hr_category_ids")
def _compute_allowed_hr_category_ids(self):
hr_category_obj = self.env["hr.employee.category"]
for task in self:
if task.project_id.hr_category_ids:
task.allowed_hr_category_ids = task.project_id.hr_category_ids
else:
task.allowed_hr_category_ids = hr_category_obj.search([])
@api.depends("hr_category_ids", "company_id")
def _compute_allowed_assigned_user_ids(self):
user_obj = self.env["res.users"]
for task in self:
domain = []
if task.hr_category_ids:
domain = [
("employee_ids.company_id", "=", task.company_id.id),
("employee_ids.category_ids", "in", task.hr_category_ids.ids),
]
task.allowed_assigned_user_ids = user_obj.search(domain)
@api.constrains("hr_category_ids", "user_ids")
def _check_employee_category_user(self):
"""Check user's employee belong to the selected category."""
for task in self.filtered(lambda x: x.hr_category_ids and x.user_ids):
if any(
x not in task.employee_ids.category_ids for x in task.hr_category_ids
):
raise exceptions.ValidationError(
_(
"You can't assign a user not belonging to the selected "
"employee category."
)
)
@api.constrains("hr_category_ids", "project_id")
def _check_employee_category_project(self):
for task in self.filtered("hr_category_ids"):
if task.project_id.hr_category_ids and bool(
task.hr_category_ids - task.project_id.hr_category_ids
):
raise exceptions.ValidationError(
_(
"You can't assign a category that is not allowed at "
"project level."
)
)
| 40.968421 | 3,892 |
466 | py | PYTHON | 15.0 | # Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProjectProject(models.Model):
_inherit = "project.project"
hr_category_ids = fields.Many2many(
comodel_name="hr.employee.category",
string="Employee Categories",
help="Here you can link the project to several employee categories, "
"that will be the allowed in tasks.",
)
| 31.066667 | 466 |
843 | py | PYTHON | 15.0 | # Copyright 2018-2019 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020-2022 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Project Roles",
"version": "15.0.1.0.1",
"category": "Project",
"website": "https://github.com/OCA/project",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "Project role-based roster",
"depends": ["project", "mail"],
"data": [
"security/ir.model.access.csv",
"security/project_role.xml",
"views/project_assignment.xml",
"views/project_project.xml",
"views/project_role.xml",
"views/res_config_settings.xml",
],
"maintainers": ["alexey-pelykh"],
}
| 33.72 | 843 |
11,149 | py | PYTHON | 15.0 | # Copyright 2018-2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from unittest import mock
from psycopg2 import IntegrityError
from odoo.exceptions import UserError, ValidationError
from odoo.tests import common
from odoo.tools.misc import mute_logger
_module_ns = "odoo.addons.project_role"
_project_role_class = _module_ns + ".models.project_role.ProjectRole"
class TestProjectRole(common.TransactionCase):
def setUp(self):
super().setUp()
self.ResUsers = self.env["res.users"]
self.Company = self.env["res.company"]
self.Project = self.env["project.project"]
self.Role = self.env["project.role"]
self.Assignment = self.env["project.assignment"]
self.company_id = self.env.user.company_id
def test_create_assignment(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
project = self.Project.create({"name": "Project"})
role = self.Role.create({"name": "Role"})
self.Assignment.create(
{"project_id": project.id, "role_id": role.id, "user_id": user.id}
)
self.assertEqual(self.Role.get_available_roles(user, project).ids, role.ids)
def test_no_duplicate_assignment(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
project = self.Project.create({"name": "Project"})
role = self.Role.create({"name": "Role"})
self.Assignment.create(
{"project_id": project.id, "role_id": role.id, "user_id": user.id}
)
with self.assertRaises(IntegrityError), mute_logger("odoo.sql_db"):
self.Assignment.create(
{"project_id": project.id, "role_id": role.id, "user_id": user.id}
)
def test_restrict_assign(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
project = self.Project.create({"name": "Project"})
role = self.Role.create({"name": "Role"})
company_1 = self.Company.create({"name": "Company #1"})
with mock.patch(
_project_role_class + ".can_assign",
return_value=False,
):
with self.assertRaises(ValidationError):
self.Assignment.create(
{"project_id": project.id, "role_id": role.id, "user_id": user.id}
)
with self.assertRaises(ValidationError):
self.Assignment.create(
{"role_id": role.id, "user_id": user.id, "company_id": company_1.id}
)
with self.assertRaises(ValidationError):
self.Assignment.create(
{
"company_id": self.company_id.id,
"role_id": role.id,
"user_id": user.id,
}
)
def test_multicompany_roles(self):
company_1 = self.Company.create({"name": "Company #1"})
self.Role.create({"name": "Role", "company_id": company_1.id})
company_2 = self.Company.create({"name": "Company #2"})
self.Role.create({"name": "Role", "company_id": company_2.id})
def test_unique_crosscompany_role(self):
self.Role.create({"name": "Role", "company_id": False})
with self.assertRaises(ValidationError):
self.Role.create({"name": "Role"})
def test_nonconflicting_crosscompany_role(self):
self.Role.create({"name": "Role"})
with self.assertRaises(ValidationError):
self.Role.create({"name": "Role", "company_id": False})
def test_child_role(self):
parent_role = self.Role.create({"name": "Parent Role"})
child_role = self.Role.create(
{"name": "Child Role", "parent_id": parent_role.id}
)
self.assertTrue(child_role.complete_name, "Parent Role / Child Role")
with self.assertRaises(UserError):
parent_role.parent_id = child_role
child_role.active = False
parent_role.active = False
with self.assertRaises(ValidationError):
child_role.active = True
def test_companywide_assignments_1(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role = self.Role.create({"name": "Role"})
self.Assignment.create({"role_id": role.id, "user_id": user.id})
with self.assertRaises(IntegrityError), mute_logger("odoo.sql_db"):
self.Assignment.create({"role_id": role.id, "user_id": user.id})
def test_companywide_assignments_2(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role_1 = self.Role.create({"name": "Role 1"})
role_2 = self.Role.create({"name": "Role 2"})
project = self.Project.create({"name": "Project"})
self.Assignment.create({"role_id": role_1.id, "user_id": user.id})
with self.assertRaises(ValidationError):
self.Assignment.create(
{"role_id": role_1.id, "user_id": user.id, "project_id": project.id}
)
self.Assignment.create({"role_id": role_2.id, "user_id": user.id})
def test_companywide_assignments_3(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role_1 = self.Role.create({"name": "Role 1"})
role_2 = self.Role.create({"name": "Role 2"})
self.Assignment.create({"role_id": role_1.id, "user_id": user.id})
self.Assignment.create({"role_id": role_2.id, "user_id": user.id})
def test_crosscompany_assignments_1(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role = self.Role.create({"name": "Role", "company_id": False})
self.Assignment.create(
{"role_id": role.id, "user_id": user.id, "company_id": False}
)
with self.assertRaises(ValidationError):
self.Assignment.with_context(
company_id=self.company_id.id,
).create({"role_id": role.id, "user_id": user.id})
def test_crosscompany_assignments_2(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role = self.Role.create({"name": "Role", "company_id": False})
project = self.Project.create({"name": "Project"})
self.Assignment.create(
{"role_id": role.id, "user_id": user.id, "company_id": False}
)
with self.assertRaises(ValidationError):
self.Assignment.with_context(
company_id=self.company_id.id,
).create({"role_id": role.id, "user_id": user.id, "project_id": project.id})
def test_crosscompany_assignments_3(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role_1 = self.Role.create({"name": "Role 1", "company_id": False})
role_2 = self.Role.create({"name": "Role 2", "company_id": False})
self.Assignment.create(
{"role_id": role_1.id, "user_id": user.id, "company_id": False}
)
self.Assignment.with_context(
company_id=self.company_id.id,
).create({"role_id": role_2.id, "user_id": user.id})
def test_no_project(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
self.Role.create({"name": "Role"})
self.assertFalse(self.Role.get_available_roles(user, False))
def test_inherit_assignments(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role = self.Role.create({"name": "Role"})
project = self.Project.create(
{"name": "Project", "limit_role_to_assignments": True}
)
self.Assignment.create({"role_id": role.id, "user_id": user.id})
self.assertEqual(self.Role.get_available_roles(user, project).ids, role.ids)
project.inherit_assignments = False
self.assertFalse(self.Role.get_available_roles(user, project))
def test_limit_role_to_assignments(self):
user = self.ResUsers.sudo().create(
{
"name": "User",
"login": "user",
"email": "user@example.com",
"company_id": self.company_id.id,
}
)
role = self.Role.create({"name": "Role"})
project = self.Project.create({"name": "Project"})
self.assertEqual(self.Role.get_available_roles(user, project).ids, role.ids)
project.inherit_assignments = False
self.assertEqual(self.Role.get_available_roles(user, project).ids, role.ids)
def test_defaults(self):
company = self.Company.create(
{
"name": "Company",
"project_inherit_assignments": False,
"project_limit_role_to_assignments": True,
}
)
project = self.Project.create({"name": "Project", "company_id": company.id})
self.Role.create({"name": "Role"})
self.assertEqual(project.company_id.id, company.id)
self.assertEqual(
project.inherit_assignments, company.project_inherit_assignments
)
self.assertEqual(
project.limit_role_to_assignments, company.project_limit_role_to_assignments
)
| 35.733974 | 11,149 |
483 | py | PYTHON | 15.0 | # Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
project_inherit_assignments = fields.Boolean(
string="Projects Inherit Assignments",
default=True,
)
project_limit_role_to_assignments = fields.Boolean(
string="Limit Project Role to Assignments",
default=False,
)
| 28.411765 | 483 |
533 | py | PYTHON | 15.0 | # Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
project_inherit_assignments = fields.Boolean(
related="company_id.project_inherit_assignments",
readonly=False,
)
project_limit_role_to_assignments = fields.Boolean(
related="company_id.project_limit_role_to_assignments",
readonly=False,
)
| 31.352941 | 533 |
1,711 | py | PYTHON | 15.0 | # Copyright 2018-2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ProjectProject(models.Model):
_inherit = "project.project"
assignment_ids = fields.One2many(
string="Project Assignments",
comodel_name="project.assignment",
inverse_name="project_id",
tracking=True,
)
inherit_assignments = fields.Boolean(
default=lambda self: self._default_inherit_assignments(),
)
limit_role_to_assignments = fields.Boolean(
default=lambda self: self._default_limit_role_to_assignments(),
)
@api.model
def _default_inherit_assignments(self):
company = self.env["res.company"].browse(
self._context.get("company_id", self.env.user.company_id.id)
)
return company.project_inherit_assignments
@api.model
def _default_limit_role_to_assignments(self):
company = self.env["res.company"].browse(
self._context.get("company_id", self.env.user.company_id.id)
)
return company.project_limit_role_to_assignments
@api.model
def create(self, values):
company = None
if "company_id" in values:
company = self.env["res.company"].browse(values["company_id"])
if company and "inherit_assignments" not in values:
values["inherit_assignments"] = company.project_inherit_assignments
if company and "limit_role_to_assignments" not in values:
values[
"limit_role_to_assignments"
] = company.project_limit_role_to_assignments
return super().create(values)
| 33.54902 | 1,711 |
4,351 | py | PYTHON | 15.0 | # Copyright 2018-2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.tools.translate import html_translate
class ProjectRole(models.Model):
_name = "project.role"
_description = "Project Role"
_parent_name = "parent_id"
_parent_store = True
_rec_name = "complete_name"
_order = "complete_name"
active = fields.Boolean(
default=True,
)
parent_path = fields.Char(
index=True,
)
parent_id = fields.Many2one(
string="Parent Role",
comodel_name="project.role",
index=True,
ondelete="cascade",
)
child_ids = fields.One2many(
string="Child Roles",
comodel_name="project.role",
inverse_name="parent_id",
copy=True,
)
complete_name = fields.Char(
compute="_compute_complete_name", store=True, recursive=True
)
name = fields.Char(
translate=True,
required=True,
)
description = fields.Html(
translate=html_translate,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
ondelete="cascade",
)
_sql_constraints = [
(
"name_company_uniq",
"UNIQUE (name, company_id)",
"Role with such name already exists in the company!",
),
(
"name_nocompany_uniq",
("EXCLUDE (name WITH =) WHERE (" " company_id IS NULL" ")"),
"Shared role with such name already exists!",
),
]
@api.constrains("name")
def _check_name(self):
for role in self:
if self.search(
[
("company_id", "=" if role.company_id else "!=", False),
("name", "=", role.name),
],
limit=1,
):
raise ValidationError(
_('Role "%s" conflicts with another role due to same name.')
% (role.name,)
)
@api.depends("name", "parent_id.complete_name")
def _compute_complete_name(self):
for role in self:
if role.parent_id:
role.complete_name = _("%(parent)s / %(own)s") % {
"parent": role.parent_id.complete_name,
"own": role.name,
}
else:
role.complete_name = role.name
@api.constrains("active")
def _check_active(self):
for role in self:
if (
role.active
and role.parent_id
and role.parent_id not in self
and not role.parent_id.active
):
raise ValidationError(
_("Please activate first parent role %s")
% (role.parent_id.complete_name,)
)
def can_assign(self, user_id, project_id):
"""Extension point to check if user can be assigned to this role"""
self.ensure_one()
return self.active
@api.model
def get_available_roles(self, user_id, project_id):
"""
Get domain on roles that can be assumed by given user on a specific
project, depending on company and project assignments configuration.
"""
if not user_id or not project_id:
return self
if not project_id.limit_role_to_assignments:
if project_id.inherit_assignments:
domain = [("company_id", "in", [False, user_id.company_id.id])]
else:
domain = [("company_id", "=", user_id.company_id.id)]
return self.search(domain)
domain = [("user_id", "=", user_id.id)]
if project_id.inherit_assignments:
domain += [
("project_id", "in", [False, project_id.id]),
("company_id", "in", [False, user_id.company_id.id]),
]
else:
domain += [
("project_id", "=", project_id.id),
("company_id", "=", user_id.company_id.id),
]
return self.env["project.assignment"].search(domain).mapped("role_id")
| 31.759124 | 4,351 |
5,256 | py | PYTHON | 15.0 | # Copyright 2018-2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ProjectAssignment(models.Model):
_name = "project.assignment"
_description = "Project Assignment"
_inherit = ["mail.thread"]
active = fields.Boolean(
default=True,
)
name = fields.Char(
compute="_compute_name",
store=True,
index=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
ondelete="cascade",
)
project_id = fields.Many2one(
comodel_name="project.project",
string="Project",
ondelete="cascade",
)
role_id = fields.Many2one(
comodel_name="project.role",
string="Role",
required=True,
ondelete="restrict",
)
user_id = fields.Many2one(
comodel_name="res.users",
string="User",
required=True,
ondelete="restrict",
)
_sql_constraints = [
(
"project_role_user_uniq",
"UNIQUE (project_id, role_id, user_id)",
"User may be assigned per role only once within a project!",
),
(
"company_role_user_uniq",
(
"EXCLUDE ("
" company_id WITH =, role_id WITH =, user_id WITH ="
") WHERE ("
" project_id IS NULL"
")"
),
"User may be assigned per role only once within a company!",
),
(
"nocompany_role_user_uniq",
(
"EXCLUDE (role_id WITH =, user_id WITH =) WHERE ("
" project_id IS NULL AND company_id IS NULL"
")"
),
"User may be assigned per role only once!",
),
]
@api.depends(
"company_id.name",
"project_id.name",
"role_id.name",
"user_id.name",
)
def _compute_name(self):
for assignment in self:
if assignment.project_id:
assignment.name = _("%(USER)s as %(ROLE)s on %(PROJECT)s") % {
"USER": assignment.user_id.name,
"ROLE": assignment.role_id.name,
"PROJECT": assignment.project_id.name,
}
elif assignment.company_id:
assignment.name = _("%(USER)s as %(ROLE)s in %(PROJECT)s") % {
"USER": assignment.user_id.name,
"ROLE": assignment.role_id.name,
"PROJECT": assignment.company_id.name,
}
else:
assignment.name = _("%(USER)s as %(ROLE)s") % {
"USER": assignment.user_id.name,
"ROLE": assignment.role_id.name,
}
def _get_conflicting_domain(self):
self.ensure_one()
return (
[
("id", "!=", self.id),
("role_id", "=", self.role_id.id),
("user_id", "=", self.user_id.id),
]
+ (
[("company_id", "in", [False, self.company_id.id])]
if self.company_id
else []
)
+ (
[("project_id", "in", [False, self.project_id.id])]
if self.project_id
else []
)
)
@api.constrains("company_id", "project_id", "role_id", "user_id")
def _check(self):
"""
Check if assignment conflicts with any already-existing assignment and
if specific role can be assigned at all (extension hook).
"""
for assignment in self:
conflicting_assignment = self.search(
assignment._get_conflicting_domain(),
limit=1,
)
if conflicting_assignment:
raise ValidationError(
_(
"Assignment %(ASSIGNMENT)s conflicts with another assignment: "
"%(OTHER_ASSIGNMENT)s"
)
% {
"ASSIGNMENT": assignment.name,
"OTHER_ASSIGNMENT": conflicting_assignment.name,
}
)
if not assignment.role_id.can_assign(
assignment.user_id, assignment.project_id
):
if assignment.project_id:
error = _(
"User %(USER)s can not be assigned to role %(ROLE)s on %(PROJECT)s."
) % {
"USER": assignment.user_id.name,
"ROLE": assignment.role_id.name,
"PROJECT": assignment.project_id.name,
}
else:
error = _("User %(USER)s can not be assigned to role %(ROLE)s.") % {
"USER": assignment.user_id.name,
"ROLE": assignment.role_id.name,
}
raise ValidationError(error)
| 33.477707 | 5,256 |
561 | py | PYTHON | 15.0 | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
{
"name": "Project Duplicate subtask",
"version": "15.0.1.0.0",
"category": "Project",
"website": "https://github.com/OCA/project",
"summary": "The module adds an action to duplicate tasks with the child subtasks",
"author": "Forgeflow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["project"],
"data": ["views/project_duplicate_action.xml"],
"installable": True,
"auto_install": False,
}
| 35.0625 | 561 |
1,891 | py | PYTHON | 15.0 | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
super().setUp()
self.project1 = self.env["project.project"].create({"name": "Project 1"})
self.task1 = self.env["project.task"].create(
{"name": "name1", "project_id": self.project1.id}
)
self.subtask1 = self.env["project.task"].create(
{"name": "2", "project_id": self.project1.id, "parent_id": self.task1.id}
)
self.subtask2 = self.env["project.task"].create(
{"name": "3", "project_id": self.project1.id, "parent_id": self.task1.id}
)
def test_check_subtasks(self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been created"
)
def test_check_subtasks_of_substasks(self):
self.sub_subtask1_1 = self.env["project.task"].create(
{"name": "4", "project_id": self.project1.id, "parent_id": self.subtask1.id}
)
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been created"
)
new_subtask = self.env["project.task"].search(
[
("name", "=", self.subtask1.name + " (copy)"),
]
)
self.assertEqual(
len(new_subtask.child_ids), 1, "One subtask should have been created"
)
| 37.078431 | 1,891 |
1,361 | py | PYTHON | 15.0 | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import models
class ProjectTask(models.Model):
_inherit = "project.task"
def action_duplicate_subtasks(self):
action = self.env.ref("project.action_view_task")
result = action.read()[0]
task_created = self.env["project.task"]
for task in self:
new_task = task.copy()
task_created |= new_task
if task.child_ids:
def duplicate_childs(task, new_task):
if task.child_ids:
for child in task.child_ids:
new_subtask = child.copy()
new_subtask.write({"parent_id": new_task.id})
duplicate_childs(child, new_subtask)
duplicate_childs(task, new_task)
if len(task_created) == 1:
res = self.env.ref("project.view_task_form2")
result["views"] = [(res and res.id or False, "form")]
result["res_id"] = new_task.id
action["context"] = {
"form_view_initial_mode": "edit",
"force_detailed_view": "true",
}
else:
result["domain"] = "[('id', 'in', " + str(task_created.ids) + ")]"
return result
| 34.897436 | 1,361 |
554 | py | PYTHON | 15.0 | # Copyright 2014 Daniel Reis
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Add State field to Project Stages",
"version": "15.0.1.0.1",
"category": "Project Management",
"summary": "Restore State attribute removed from Project Stages in 8.0",
"author": "Daniel Reis, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/project",
"license": "AGPL-3",
"installable": True,
"depends": ["project"],
"data": ["security/ir.model.access.csv", "views/project_view.xml"],
}
| 36.933333 | 554 |
445 | py | PYTHON | 15.0 | # Copyright 2014 Daniel Reis
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models
_TASK_STATE = [
("draft", "New"),
("open", "In Progress"),
("pending", "Pending"),
("done", "Done"),
("cancelled", "Cancelled"),
]
class ProjectTaskType(models.Model):
"""Added state in the Project Task Type."""
_inherit = "project.task.type"
state = fields.Selection(_TASK_STATE)
| 22.25 | 445 |
304 | py | PYTHON | 15.0 | # Copyright 2014 Daniel Reis
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models
class ProjectTask(models.Model):
"""Added state in the Project Task."""
_inherit = "project.task"
state = fields.Selection(related="stage_id.state", store=True)
| 25.333333 | 304 |
1,032 | py | PYTHON | 15.0 | # Copyright 2021 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Point of Sale Event Sessions",
"summary": "Sell event sessions from Point of Sale",
"author": "Moka Tourisme, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"category": "Marketing",
"version": "15.0.3.0.0",
"license": "AGPL-3",
"maintainers": ["ivantodorovich"],
"depends": ["pos_event_sale", "event_sale_session"],
"data": [
"reports/report_pos_order.xml",
"views/event_session.xml",
],
"assets": {
"point_of_sale.assets": [
"pos_event_sale_session/static/src/js/**/*.js",
],
"web.assets_qweb": [
"pos_event_sale_session/static/src/xml/**/*.xml",
],
"web.assets_tests": [
"pos_event_sale_session/static/tests/tours/**/*",
],
},
"auto_install": True,
}
| 33.258065 | 1,031 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.