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 |
|---|---|---|---|---|---|---|
24,444 | py | PYTHON | 15.0 | # Copyright 2019 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare, float_is_zero
class StockReturnRequest(models.Model):
_name = "stock.return.request"
_description = "Perform stock returns across pickings"
_inherit = ["mail.thread", "mail.activity.mixin"]
_order = "create_date desc"
name = fields.Char(
"Reference",
default=lambda self: _("New"),
copy=False,
readonly=True,
required=True,
)
partner_id = fields.Many2one(
comodel_name="res.partner",
readonly=True,
states={"draft": [("readonly", False)]},
)
return_type = fields.Selection(
selection=[
("supplier", "Return to Supplier"),
("customer", "Return from Customer"),
("internal", "Return to Internal location"),
],
required=True,
help="Supplier - Search for incoming moves from this supplier\n"
"Customer - Search for outgoing moves to this customer\n"
"Internal - Search for outgoing moves to this location.",
readonly=True,
states={"draft": [("readonly", False)]},
)
return_from_location = fields.Many2one(
comodel_name="stock.location",
string="Return from",
help="Return from this location",
required=True,
domain='[("usage", "=", "internal")]',
readonly=True,
states={"draft": [("readonly", False)]},
)
return_to_location = fields.Many2one(
comodel_name="stock.location",
string="Return to",
help="Return to this location",
required=True,
domain='[("usage", "=", "internal")]',
readonly=True,
states={"draft": [("readonly", False)]},
)
return_order = fields.Selection(
selection=[
("date desc, id desc", "Newer first"),
("date asc, id desc", "Older first"),
],
default="date desc, id desc",
required=True,
help="The returns will be performed searching moves in " "the given order.",
readonly=True,
states={"draft": [("readonly", False)]},
)
from_date = fields.Date(
string="Search moves up to this date",
)
picking_types = fields.Many2many(
comodel_name="stock.picking.type",
string="Operation types",
help="Restrict operation types to search for",
)
state = fields.Selection(
selection=[
("draft", "Open"),
("confirmed", "Confirmed"),
("done", "Done"),
("cancel", "Cancelled"),
],
default="draft",
readonly=True,
copy=False,
tracking=True,
)
returned_picking_ids = fields.One2many(
comodel_name="stock.picking",
inverse_name="stock_return_request_id",
string="Returned Pickings",
readonly=True,
copy=False,
)
to_refund = fields.Boolean(
readonly=True,
states={"draft": [("readonly", False)]},
)
show_to_refund = fields.Boolean(
compute="_compute_show_to_refund",
default=lambda self: "to_refund" in self.env["stock.move"]._fields,
readonly=True,
help="Whether to show it or not depending on the availability of"
"the stock_account module (so a bridge module is not necessary)",
)
line_ids = fields.One2many(
comodel_name="stock.return.request.line",
inverse_name="request_id",
string="Stock Return",
copy=True,
readonly=True,
states={"draft": [("readonly", False)]},
)
note = fields.Text(
string="Comments",
help="They will be visible on the report",
)
@api.onchange("return_type", "partner_id")
def onchange_locations(self):
"""UI helpers to determine locations"""
warehouse = self._default_warehouse_id()
if self.return_type == "supplier":
self.return_to_location = self.partner_id.property_stock_supplier
if self.return_from_location.usage != "internal":
self.return_from_location = warehouse.lot_stock_id.id
if self.return_type == "customer":
self.return_from_location = self.partner_id.property_stock_customer
if self.return_to_location.usage != "internal":
self.return_to_location = warehouse.lot_stock_id.id
if self.return_type == "internal":
self.partner_id = False
if self.return_to_location.usage != "internal":
self.return_to_location = warehouse.lot_stock_id.id
if self.return_from_location.usage != "internal":
self.return_from_location = warehouse.lot_stock_id.id
@api.model
def _default_warehouse_id(self):
warehouse = self.env["stock.warehouse"].search(
[
("company_id", "=", self.env.user.company_id.id),
],
limit=1,
)
return warehouse
def _compute_show_to_refund(self):
for one in self:
if "to_refund" not in self.env["stock.move"]._fields:
one.show_to_refund = False
continue
one.show_to_refund = True
def _prepare_return_picking(self, picking_dict, moves):
"""Extend to add more values if needed"""
picking_type = self.env["stock.picking.type"].browse(
picking_dict.get("picking_type_id")
)
return_picking_type = (
picking_type.return_picking_type_id or picking_type.return_picking_type_id
)
picking_dict.update(
{
"move_lines": [(6, 0, moves.ids)],
"move_line_ids": [(6, 0, moves.mapped("move_line_ids").ids)],
"picking_type_id": return_picking_type.id,
"state": "draft",
"origin": _("Return of %s") % picking_dict.get("origin"),
"location_id": self.return_from_location.id,
"location_dest_id": self.return_to_location.id,
"stock_return_request_id": self.id,
}
)
return picking_dict
def _create_picking(self, pickings, picking_moves):
"""Create return pickings with the proper moves"""
return_pickings = self.env["stock.picking"]
for picking in pickings:
picking_dict = picking.copy_data(
{
"origin": picking.name,
"printed": False,
}
)[0]
moves = picking_moves.filtered(
lambda x: x.origin_returned_move_id.picking_id == picking
)
new_picking = return_pickings.create(
self._prepare_return_picking(picking_dict, moves)
)
new_picking.message_post_with_view(
"mail.message_origin_link",
values={"self": new_picking, "origin": picking},
subtype_id=self.env.ref("mail.mt_note").id,
)
return_pickings += new_picking
return return_pickings
def _prepare_move_default_values(self, line, qty, move):
"""Extend this method to add values to return move"""
vals = {
"product_id": line.product_id.id,
"product_uom_qty": qty,
"product_uom": line.product_uom_id.id,
"state": "draft",
"location_id": line.request_id.return_from_location.id,
"location_dest_id": line.request_id.return_to_location.id,
"origin_returned_move_id": move.id,
"procure_method": "make_to_stock",
}
if self.show_to_refund:
vals["to_refund"] = line.request_id.to_refund
return vals
def _prepare_move_line_values(self, line, return_move, qty, quant=False):
"""Extend to add values to the move lines with lots"""
vals = {
"product_id": line.product_id.id,
"product_uom_id": line.product_uom_id.id,
"lot_id": line.lot_id.id,
"location_id": return_move.location_id.id,
"location_dest_id": return_move.location_dest_id._get_putaway_strategy(
line.product_id
).id
or return_move.location_dest_id.id,
"qty_done": qty,
}
if not quant:
return vals
if line.request_id.return_type in ["internal", "customer"]:
vals["location_dest_id"] = quant.location_id.id
else:
vals["location_id"] = quant.location_id.id
return vals
def action_confirm(self):
"""Wrapper for multi. Avoid recompute as it delays the pickings
creation"""
with self.env.norecompute():
for one in self:
one._action_confirm()
self.recompute()
def _action_confirm(self):
"""Get moves and then try to reserve quantities. Fail if the quantites
can't be assigned"""
self.ensure_one()
Quant = self.env["stock.quant"]
if not self.line_ids:
raise ValidationError(_("Add some products to return"))
returnable_moves = self.line_ids._get_returnable_move_ids()
return_moves = self.env["stock.move"]
failed_moves = []
done_moves = {}
for line in returnable_moves.keys():
for qty, move in returnable_moves[line]:
if move not in done_moves:
vals = self._prepare_move_default_values(line, qty, move)
return_move = move.copy(vals)
else:
return_move = done_moves[move]
return_move.product_uom_qty += qty
done_moves.setdefault(move, self.env["stock.move"])
done_moves[move] += return_move
if line.lot_id:
# We need to be deterministic with lots to avoid autoassign
# thus we create manually the line
return_move.with_context(skip_assign_move=True)._action_confirm()
# We try to reserve the stock manually so we ensure there's
# enough to make the return.
vals_list = []
if return_move.location_id.usage == "internal":
try:
quants = Quant._update_reserved_quantity(
line.product_id,
return_move.location_id,
qty,
lot_id=line.lot_id,
strict=False,
)
for q in quants:
vals_list.append(
(
0,
0,
self._prepare_move_line_values(
line, return_move, q[1], q[0]
),
)
)
except UserError:
failed_moves.append((line, return_move))
else:
vals_list.append(
(
0,
0,
self._prepare_move_line_values(line, return_move, qty),
)
)
return_move.write(
{
"move_line_ids": vals_list,
}
)
return_moves += return_move
line.returnable_move_ids += return_move
# If not lots, just try standard assign
else:
return_move._action_confirm()
# Force assign because the reservation method of picking type
# operation can be "manual" and the products would not be reserved
return_move._action_assign()
if return_move.state == "assigned":
return_move.quantity_done = qty
return_moves += return_move
line.returnable_move_ids += return_move
else:
failed_moves.append((line, return_move))
break
if failed_moves:
failed_moves_str = "\n".join(
[
"{}: {} {:.2f}".format(
x[0].product_id.display_name,
x[0].lot_id.name or "\t",
x[0].quantity,
)
for x in failed_moves
]
)
raise ValidationError(
_(
"It wasn't possible to assign stock for this returns:\n"
"{failed_moves_str}"
).format(failed_moves_str=failed_moves_str)
)
# Finish move traceability
for move in return_moves:
vals = {}
origin_move = move.origin_returned_move_id
move_orig_to_link = origin_move.move_dest_ids.mapped("returned_move_ids")
move_dest_to_link = origin_move.move_orig_ids.mapped("returned_move_ids")
vals["move_orig_ids"] = [(4, m.id) for m in move_orig_to_link | origin_move]
vals["move_dest_ids"] = [(4, m.id) for m in move_dest_to_link]
move.write(vals)
# Make return pickings and link to the proper moves.
origin_pickings = return_moves.mapped("origin_returned_move_id.picking_id")
self.returned_picking_ids = self._create_picking(origin_pickings, return_moves)
self.state = "confirmed"
def action_validate(self):
"""Wrapper for multi"""
for one in self:
one._action_validate()
def _action_validate(self):
self.returned_picking_ids._action_done()
self.state = "done"
def action_cancel_to_draft(self):
"""Set to draft again"""
self.filtered(lambda x: x.state == "cancel").write({"state": "draft"})
def action_cancel(self):
"""Cancel request and the associated pickings. We can set it to
draft again."""
self.filtered(lambda x: x.state == "draft").write({"state": "cancel"})
confirmed = self.filtered(lambda x: x.state == "confirmed")
for return_request in confirmed:
return_request.mapped("returned_picking_ids").action_cancel()
return_request.state = "cancel"
@api.model
def create(self, vals):
if "name" not in vals or vals["name"] == _("New"):
vals["name"] = self.env["ir.sequence"].next_by_code(
"stock.return.request"
) or _("New")
return super().create(vals)
def action_view_pickings(self):
"""Display returned pickings"""
xmlid = "stock.action_picking_tree_all"
action = self.env["ir.actions.act_window"]._for_xml_id(xmlid)
action["context"] = {}
pickings = self.mapped("returned_picking_ids")
if not pickings or len(pickings) > 1:
action["domain"] = "[('id', 'in', %s)]" % (pickings.ids)
elif len(pickings) == 1:
res = self.env.ref("stock.view_picking_form", False)
action["views"] = [(res and res.id or False, "form")]
action["res_id"] = pickings.id
return action
def do_print_return_request(self):
return self.env.ref(
"stock_return_request.action_report_stock_return_request"
).report_action(self)
class StockReturnRequestLine(models.Model):
_name = "stock.return.request.line"
_description = "Product to search for returns"
request_id = fields.Many2one(
comodel_name="stock.return.request",
string="Return Request",
ondelete="cascade",
required=True,
readonly=True,
)
product_id = fields.Many2one(
comodel_name="product.product",
string="Product",
required=True,
domain=[("type", "=", "product")],
)
product_uom_id = fields.Many2one(
comodel_name="uom.uom",
related="product_id.uom_id",
readonly=True,
)
tracking = fields.Selection(
related="product_id.tracking",
readonly=True,
)
lot_id = fields.Many2one(
comodel_name="stock.production.lot",
string="Lot / Serial",
)
quantity = fields.Float(
string="Quantiy to return",
digits="Product Unit of Measure",
required=True,
)
max_quantity = fields.Float(
string="Maximum available quantity",
digits="Product Unit of Measure",
readonly=True,
)
returnable_move_ids = fields.Many2many(
comodel_name="stock.move",
string="Returnable Move Lines",
copy=False,
readonly=True,
)
def _get_moves_domain(self):
"""Domain constructor for moves search"""
self.ensure_one()
domain = [
("state", "=", "done"),
("origin_returned_move_id", "=", False),
("qty_returnable", ">", 0),
("product_id", "=", self.product_id.id),
]
if not self.env.context.get("ignore_rr_lots"):
domain += [("move_line_ids.lot_id", "=", self.lot_id.id)]
if self.request_id.from_date:
domain += [("date", ">=", self.request_id.from_date)]
if self.request_id.picking_types:
domain += [
("picking_id.picking_type_id", "in", self.request_id.picking_types.ids)
]
return_type = self.request_id.return_type
if return_type != "internal":
domain += [
(
"picking_id.partner_id",
"child_of",
self.request_id.partner_id.commercial_partner_id.id,
)
]
# Search for movements coming delivered to that location
if return_type in ["internal", "customer"]:
domain += [
("location_dest_id", "=", self.request_id.return_from_location.id)
]
# Return to supplier. Search for moves that came from that location
else:
domain += [
("location_id", "child_of", self.request_id.return_to_location.id)
]
return domain
def _get_returnable_move_ids(self):
"""Gets returnable stock.moves for the given request conditions
:returns: a dict with request lines as keys containing a list of tuples
with qty returnable for a given move as the move itself
:rtype: dictionary
"""
moves_for_return = {}
stock_move_obj = self.env["stock.move"]
# Avoid lines with quantity to 0.0
for line in self.filtered("quantity"):
moves_for_return[line] = []
precision = line.product_uom_id.rounding
moves = stock_move_obj.search(
line._get_moves_domain(), order=line.request_id.return_order
)
# Add moves up to desired quantity
qty_to_complete = line.quantity
for move in moves:
qty_returned = 0
return_moves = move.returned_move_ids.filtered(
lambda x: x.state == "done"
)
# Don't count already returned
if return_moves:
qty_returned = -sum(
return_moves.mapped("move_line_ids")
.filtered(lambda x: x.lot_id == line.lot_id)
.mapped("qty_done")
)
quantity_done = sum(
move.mapped("move_line_ids")
.filtered(lambda x: x.lot_id == line.lot_id)
.mapped("qty_done")
)
qty_remaining = quantity_done - qty_returned
# We add the move to the list if there are units that haven't
# been returned
if float_compare(qty_remaining, 0.0, precision_rounding=precision) > 0:
qty_to_return = min(qty_to_complete, qty_remaining)
moves_for_return[line] += [(qty_to_return, move)]
qty_to_complete -= qty_to_return
if float_is_zero(qty_to_complete, precision_rounding=precision):
break
if qty_to_complete:
qty_found = line.quantity - qty_to_complete
raise ValidationError(
_(
"Not enough moves to return this product.\n"
"It wasn't possible to find enough moves to return "
"{line_quantity} {line_product_uom_id_name}"
"of {line_product_id_displayname}. A maximum of {qty_found} "
"can be returned."
).format(
line_quantity=line.quantity,
line_product_uom_id_name=line.product_uom_id.name,
line_product_id_displayname=line.product_id.display_name,
qty_found=qty_found,
)
)
return moves_for_return
@api.model
def create(self, values):
res = super().create(values)
existing = self.search(
[
("product_id", "=", res.product_id.id),
("request_id.state", "in", ["draft", "confirm"]),
(
"request_id.return_from_location",
"=",
res.request_id.return_from_location.id,
),
(
"request_id.return_to_location",
"=",
res.request_id.return_to_location.id,
),
(
"request_id.partner_id",
"child_of",
res.request_id.partner_id.commercial_partner_id.id,
),
("lot_id", "=", res.lot_id.id),
]
)
if len(existing) > 1:
raise UserError(
_(
"""
You cannot have two open Stock Return Requests with the same
product ({product_id}), locations ({return_from_location},
{return_to_location}) partner ({partner_id}) and lot.\n
Please first validate the first return request with this
product before creating a new one.
"""
).format(
product_id=res.product_id.display_name,
return_from_location=res.request_id.return_from_location.display_name,
return_to_location=res.request_id.return_to_location.display_name,
partner_id=res.request_id.partner_id.name,
)
)
return res
@api.onchange("product_id", "lot_id")
def onchange_product_id(self):
self.product_uom_id = self.product_id.uom_id
request = self.request_id
if request.return_type == "customer":
return
search_args = [
("location_id", "child_of", request.return_from_location.id),
("product_id", "=", self.product_id.id),
]
if self.lot_id:
search_args.append(("lot_id", "=", self.lot_id.id))
else:
search_args.append(("lot_id", "=", False))
res = self.env["stock.quant"].read_group(search_args, ["quantity"], [])
max_quantity = res[0]["quantity"]
self.max_quantity = max_quantity
def action_lot_suggestion(self):
return {
"name": _("Suggest Lot"),
"type": "ir.actions.act_window",
"res_model": "suggest.return.request.lot",
"view_type": "form",
"view_mode": "form",
"target": "new",
}
| 39.362319 | 24,444 |
622 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Stock Production Lot Traceability",
"summary": "Drill down/up the lots produced or consumed",
"version": "15.0.1.0.1",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"category": "Stock",
"depends": ["stock"],
"data": ["views/stock_production_lot.xml"],
}
| 38.8125 | 621 |
6,160 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import TransactionCase
class CommonStockLotTraceabilityCase(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.product1, cls.product2, cls.product3 = cls.env["product.product"].create(
[
{"name": "Product 1", "type": "product", "tracking": "lot"},
{"name": "Product 2", "type": "product", "tracking": "lot"},
{"name": "Product 3", "type": "product", "tracking": "lot"},
]
)
# Simulate a manufacture operation without any BoM nor mrp-like dependency
# In our example:
# - Product 1 is simply on stock
# - Product 2 is produced from Product 1
# - Product 3 is produced from Product 2
# - We have/produce two lots for each product
cls.product1_lot1, cls.product1_lot2 = cls.env["stock.production.lot"].create(
[
{
"name": "Product 1 Lot 1",
"product_id": cls.product1.id,
"company_id": cls.env.company.id,
},
{
"name": "Product 1 Lot 2",
"product_id": cls.product1.id,
"company_id": cls.env.company.id,
},
]
)
cls.product2_lot1, cls.product2_lot2 = cls.env["stock.production.lot"].create(
[
{
"name": "Product 2 Lot 1",
"product_id": cls.product2.id,
"company_id": cls.env.company.id,
},
{
"name": "Product 2 Lot 2",
"product_id": cls.product2.id,
"company_id": cls.env.company.id,
},
]
)
cls.product3_lot1, cls.product3_lot2 = cls.env["stock.production.lot"].create(
[
{
"name": "Product 3 Lot 1",
"product_id": cls.product3.id,
"company_id": cls.env.company.id,
},
{
"name": "Product 3 Lot 2",
"product_id": cls.product3.id,
"company_id": cls.env.company.id,
},
]
)
cls.location_supplier = cls.env.ref("stock.stock_location_suppliers")
cls.location_stock = cls.env.ref("stock.stock_location_stock")
cls._do_stock_move(
cls.product1,
cls.product1_lot1,
10,
cls.location_supplier,
cls.location_stock,
)
cls._do_stock_move(
cls.product1,
cls.product1_lot2,
10,
cls.location_supplier,
cls.location_stock,
)
# Product 2 Lot 1 manufactured from Product 1 Lot 1
cls._do_manufacture_move(
cls.product2,
cls.product2_lot1,
10,
[(cls.product1, cls.product1_lot1, 10)],
)
# Product 2 Lot 2 manufactured from Product 2 Lot 2
cls._do_manufacture_move(
cls.product2,
cls.product2_lot2,
10,
[(cls.product1, cls.product1_lot2, 10)],
)
# Product 3 Lot 1 manufactured from Product 2 Lot 1
cls._do_manufacture_move(
cls.product3,
cls.product3_lot1,
10,
[(cls.product2, cls.product2_lot1, 10)],
)
# Product 3 Lot 2 manufactured from Product 2 Lot 2
cls._do_manufacture_move(
cls.product3,
cls.product3_lot2,
10,
[(cls.product2, cls.product2_lot2, 10)],
)
@classmethod
def _do_stock_move(
cls, product, lot, qty, location_from, location_dest, validate=True
):
move = cls.env["stock.move"].create(
{
"name": product.name,
"product_id": product.id,
"product_uom_qty": qty,
"product_uom": product.uom_id.id,
"location_id": location_from.id,
"location_dest_id": location_dest.id,
"move_line_ids": [
(
0,
0,
{
"product_id": product.id,
"product_uom_id": product.uom_id.id,
"qty_done": qty,
"lot_id": lot.id,
"location_id": location_from.id,
"location_dest_id": location_dest.id,
},
)
],
}
)
if validate:
move._action_confirm()
move._action_done()
return move
@classmethod
def _do_manufacture_move(cls, product, lot, qty, consume_data, validate=True):
assert isinstance(consume_data, list)
# Consume data is a list of tuples (product, lot, qty)
consume_moves = cls.env["stock.move"]
for consume_product, consume_lot, consume_qty in consume_data:
consume_moves += cls._do_stock_move(
consume_product,
consume_lot,
consume_qty,
cls.location_stock,
product.property_stock_production,
validate=validate,
)
# Do the actual production
move = cls._do_stock_move(
product,
lot,
qty,
product.property_stock_production,
cls.location_stock,
validate=validate,
)
move.move_line_ids.consume_line_ids = [
(6, 0, consume_moves.mapped("move_line_ids").ids)
]
return move + consume_moves
| 35.80814 | 6,159 |
2,760 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from .common import CommonStockLotTraceabilityCase
class TestStockLotTraceability(CommonStockLotTraceabilityCase):
def test_produce_lots(self):
"""Test the Produced Lots/Serial Numbers field"""
self.assertEqual(
self.product1_lot1.produce_lot_ids, self.product2_lot1 + self.product3_lot1
)
self.assertEqual(self.product1_lot1.produce_lot_count, 2)
self.assertEqual(self.product2_lot1.produce_lot_ids, self.product3_lot1)
self.assertEqual(self.product2_lot1.produce_lot_count, 1)
self.assertFalse(self.product3_lot1.produce_lot_ids)
self.assertFalse(self.product3_lot1.produce_lot_count)
def test_consume_lots(self):
"""Test the Consumed Lots/Serial Numbers field"""
self.assertFalse(self.product1_lot1.consume_lot_ids)
self.assertFalse(self.product1_lot1.consume_lot_count)
self.assertEqual(self.product2_lot1.consume_lot_ids, self.product1_lot1)
self.assertEqual(self.product2_lot1.consume_lot_count, 1)
self.assertEqual(
self.product3_lot1.consume_lot_ids, self.product1_lot1 + self.product2_lot1
)
self.assertEqual(self.product3_lot1.consume_lot_count, 2)
def test_cache_invalidation(self):
"""Test that cache is invalidated when stock.move.line(s) are modified"""
self.assertEqual(
self.product1_lot1.produce_lot_ids, self.product2_lot1 + self.product3_lot1
)
self._do_stock_move(
self.product2,
self.product2_lot1,
1,
self.location_supplier,
self.location_stock,
)
new_moves = self._do_manufacture_move(
self.product3,
self.product3_lot2,
1,
[(self.product2, self.product2_lot1, 10)],
)
self.assertEqual(
self.product1_lot1.produce_lot_ids,
self.product2_lot1 + self.product3_lot1 + self.product3_lot2,
)
new_moves[0].move_line_ids.consume_line_ids = [(5,)]
self.assertEqual(
self.product1_lot1.produce_lot_ids, self.product2_lot1 + self.product3_lot1
)
def test_action_view_produce_lots(self):
"""Test that no error is raised when calling this action"""
self.assertIsInstance(self.product1_lot1.action_view_produce_lots(), dict)
def test_action_view_consume_lots(self):
"""Test that no error is raised when calling this action"""
self.assertIsInstance(self.product1_lot1.action_view_consume_lots(), dict)
| 43.109375 | 2,759 |
1,248 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
def write(self, vals):
# OVERRIDE to invalidate the cache of the lots' produce/consume fields,
# as they're computed from the move lines that consume/produce them.
self.env["stock.production.lot"].invalidate_cache(
[
"produce_lot_ids",
"consume_lot_ids",
"produce_lot_count",
"consume_lot_count",
]
)
return super().write(vals)
@api.model_create_multi
def create(self, vals_list):
# OVERRIDE to invalidate the cache of the lots' produce/consume fields,
# as they're computed from the move lines that consume/produce them.
self.env["stock.production.lot"].invalidate_cache(
[
"produce_lot_ids",
"consume_lot_ids",
"produce_lot_count",
"consume_lot_count",
]
)
return super().create(vals_list)
| 34.638889 | 1,247 |
7,837 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, fields, models
class StockProductionLot(models.Model):
_inherit = "stock.production.lot"
produce_lot_ids = fields.Many2many(
string="Produced Lots/Serial Numbers",
comodel_name="stock.production.lot",
compute="_compute_produce_lot_ids",
help="Lots that were directly or indirectly produced from this lot",
)
produce_lot_count = fields.Integer(
string="Produced Lots/Serial Numbers Count",
compute="_compute_produce_lot_ids",
)
consume_lot_ids = fields.Many2many(
string="Consumed Lots/Serial Numbers",
comodel_name="stock.production.lot",
compute="_compute_consume_lot_ids",
help="Lots that were directly or indirectly consumed to produce this lot",
)
consume_lot_count = fields.Integer(
string="Consumed Lots/Serial Numbers Count",
compute="_compute_consume_lot_ids",
)
def _compute_produce_lot_ids(self):
"""Compute the lots that were produced from this lot."""
data = {}
if self.ids:
self.env["stock.move.line"].flush(
["state", "lot_id", "produce_line_ids", "consume_line_ids"]
)
self.env.cr.execute(
"""
WITH RECURSIVE produce_lots AS (
SELECT
consume_line.lot_id AS lot_id,
consume_line.lot_id AS consume_lot_id,
produce_line.lot_id AS produce_lot_id
FROM stock_move_line_consume_rel rel
INNER JOIN stock_move_line
AS consume_line
ON rel.produce_line_id = consume_line.id
INNER JOIN stock_move_line
AS produce_line
ON rel.consume_line_id = produce_line.id
WHERE consume_line.lot_id IN %s
AND produce_line.lot_id IS NOT NULL
AND consume_line.state = 'done'
AND produce_line.state = 'done'
GROUP BY
consume_line.lot_id,
produce_line.lot_id
UNION
SELECT
produce_lots.lot_id AS lot_id,
consume_line.lot_id AS consume_lot_id,
produce_line.lot_id AS produce_lot_id
FROM stock_move_line_consume_rel rel
INNER JOIN stock_move_line
AS consume_line
ON rel.produce_line_id = consume_line.id
INNER JOIN stock_move_line
AS produce_line
ON rel.consume_line_id = produce_line.id
JOIN produce_lots
ON consume_line.lot_id = produce_lots.produce_lot_id
WHERE consume_line.lot_id IS NOT NULL
AND produce_line.lot_id IS NOT NULL
AND consume_line.state = 'done'
AND produce_line.state = 'done'
GROUP BY
consume_line.lot_id,
produce_line.lot_id,
produce_lots.lot_id
)
SELECT lot_id, ARRAY_AGG(produce_lot_id) AS produce_lot_ids
FROM produce_lots
GROUP BY lot_id
""",
(tuple(self.ids),),
)
data = dict(self.env.cr.fetchall())
for rec in self:
produce_lot_ids = data.get(rec.id, [])
rec.produce_lot_ids = [(6, 0, produce_lot_ids)]
rec.produce_lot_count = len(produce_lot_ids)
def _compute_consume_lot_ids(self):
"""Compute the lots that were consumed to produce this lot."""
data = {}
if self.ids:
self.env["stock.move.line"].flush(
["state", "lot_id", "produce_line_ids", "consume_line_ids"]
)
self.env.cr.execute(
"""
WITH RECURSIVE consume_lots AS (
SELECT
produce_line.lot_id AS lot_id,
produce_line.lot_id AS produce_lot_id,
consume_line.lot_id AS consume_lot_id
FROM stock_move_line_consume_rel rel
INNER JOIN stock_move_line
AS consume_line
ON rel.produce_line_id = consume_line.id
INNER JOIN stock_move_line
AS produce_line
ON rel.consume_line_id = produce_line.id
WHERE produce_line.lot_id IN %s
AND consume_line.lot_id IS NOT NULL
AND produce_line.state = 'done'
AND consume_line.state = 'done'
GROUP BY
produce_line.lot_id,
consume_line.lot_id
UNION
SELECT
consume_lots.lot_id AS lot_id,
produce_line.lot_id AS produce_lot_id,
consume_line.lot_id AS consume_lot_id
FROM stock_move_line_consume_rel rel
INNER JOIN stock_move_line
AS consume_line
ON rel.produce_line_id = consume_line.id
INNER JOIN stock_move_line
AS produce_line
ON rel.consume_line_id = produce_line.id
JOIN consume_Lots
ON produce_line.lot_id = consume_lots.consume_lot_id
WHERE consume_line.lot_id IS NOT NULL
AND produce_line.lot_id IS NOT NULL
AND consume_line.state = 'done'
AND produce_line.state = 'done'
GROUP BY
consume_line.lot_id,
produce_line.lot_id,
consume_lots.lot_id
)
SELECT lot_id, ARRAY_AGG(consume_lot_id) AS consume_lot_ids
FROM consume_lots
GROUP BY lot_id
""",
(tuple(self.ids),),
)
data = dict(self.env.cr.fetchall())
for rec in self:
consume_lot_ids = data.get(rec.id, [])
rec.consume_lot_ids = [(6, 0, consume_lot_ids)]
rec.consume_lot_count = len(consume_lot_ids)
def action_view_produce_lots(self):
action = self.env["ir.actions.act_window"]._for_xml_id(
"stock.action_production_lot_form"
)
action["context"] = {}
action["domain"] = [("id", "in", self.produce_lot_ids.ids)]
action["name"] = _("Produced Lots")
return action
def action_view_consume_lots(self):
action = self.env["ir.actions.act_window"]._for_xml_id(
"stock.action_production_lot_form"
)
action["context"] = {}
action["domain"] = [("id", "in", self.consume_lot_ids.ids)]
action["name"] = _("Consumed Lots")
return action
| 45.034483 | 7,836 |
553 | py | PYTHON | 15.0 | # Copyright 2020 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Stock Production Lot Active",
"summary": """
Allow to archive/unarchive a lot.""",
"version": "15.0.1.0.2",
"development_status": "Beta",
"license": "AGPL-3",
"author": "ACSONE SA/NV,Odoo Community Association (OCA)",
"maintainers": ["ThomasBinsfeld"],
"website": "https://github.com/OCA/stock-logistics-workflow",
"depends": ["stock"],
"data": ["views/stock_production_lot.xml"],
"demo": [],
}
| 32.529412 | 553 |
1,283 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestLotActive(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product = cls.env.ref("product.product_product_16")
cls.product.write({"tracking": "lot"})
cls.warehouse = cls.env.ref("stock.warehouse0")
def test_duplicate_inactive_lot(self):
self.env["stock.production.lot"].create(
{
"name": "stock_production_lot_active lot",
"product_id": self.product.id,
"company_id": self.warehouse.company_id.id,
"active": False,
}
)
# it should not be possible to create a new lot with the same name and company
# for the same product even when the first lot is inactive
with self.assertRaises(ValidationError):
self.env["stock.production.lot"].create(
{
"name": "stock_production_lot_active lot",
"product_id": self.product.id,
"company_id": self.warehouse.company_id.id,
"active": True,
}
)
| 37.735294 | 1,283 |
720 | py | PYTHON | 15.0 | # Copyright 2020 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class StockProductionLot(models.Model):
_inherit = "stock.production.lot"
active = fields.Boolean(default=True)
@api.constrains("name", "product_id", "company_id")
def _check_unique_lot(self):
"""Check that there is no other lot with the same name, company and product
To avoid allowing duplicate lot/company/name combinations when there is
another inactive entry we have to set the active_test flag to False.
"""
return super(
StockProductionLot, self.with_context(active_test=False)
)._check_unique_lot()
| 34.285714 | 720 |
641 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Stock lot product qty search",
"summary": "Allows to search on Quantity field of Lot/Serial Numbers",
"version": "15.0.1.0.0",
"development_status": "Alpha",
"category": "Inventory/Inventory",
"website": "https://github.com/OCA/stock-logistics-workflow",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["grindtildeath"],
"license": "AGPL-3",
"installable": True,
"depends": [
"stock",
],
"data": [
"views/stock_production_lot.xml",
],
}
| 32.05 | 641 |
2,930 | py | PYTHON | 15.0 | # Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.exceptions import UserError
from odoo.tests import TransactionCase
from odoo.tools import float_compare, float_is_zero
class TestSearchLotProductQty(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.uom_precision = cls.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
cls.existing_lots_qties = (
cls.env["stock.production.lot"]
.search([])
.read(["product_id", "product_qty"])
)
def test_search_with_product_qty(self):
lots_with_qties = self.env["stock.production.lot"].search(
[("product_qty", ">", 0)]
)
self.assertEqual(
lots_with_qties.ids,
[
exist_lot["id"]
for exist_lot in self.existing_lots_qties
if float_compare(
exist_lot["product_qty"], 0, precision_digits=self.uom_precision
)
> 0
],
)
def test_search_without_product_qty(self):
lots_with_qties = self.env["stock.production.lot"].search(
[("product_qty", "=", 0)]
)
self.assertEqual(
lots_with_qties.ids,
[
exist_lot["id"]
for exist_lot in self.existing_lots_qties
if float_is_zero(
exist_lot["product_qty"], precision_digits=self.uom_precision
)
],
)
def test_search_bigger_product_qty(self):
lots_with_qties = self.env["stock.production.lot"].search(
[("product_qty", ">", 50)]
)
self.assertEqual(
lots_with_qties.ids,
[
exist_lot["id"]
for exist_lot in self.existing_lots_qties
if float_compare(
exist_lot["product_qty"], 50, precision_digits=self.uom_precision
)
> 0
],
)
def test_search_smaller_product_qty(self):
lots_with_qties = self.env["stock.production.lot"].search(
[("product_qty", "<", 1)]
)
self.assertEqual(
lots_with_qties.ids,
[
exist_lot["id"]
for exist_lot in self.existing_lots_qties
if float_compare(
exist_lot["product_qty"], 1, precision_digits=self.uom_precision
)
< 0
],
)
def test_search_product_qty_args(self):
with self.assertRaises(UserError):
self.env["stock.production.lot"].search([("product_qty", "like", 1)])
with self.assertRaises(UserError):
self.env["stock.production.lot"].search([("product_qty", "=", "1")])
| 32.921348 | 2,930 |
2,720 | 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
from odoo.exceptions import UserError
from odoo.osv.expression import OR
from odoo.tools import float_compare, float_is_zero
from odoo.addons.stock.models.product import OPERATORS
class ProductionLot(models.Model):
_inherit = "stock.production.lot"
product_qty = fields.Float(search="_search_product_qty")
def _search_product_qty(self, operator, value):
if operator not in ("<", ">", "=", "!=", "<=", ">="):
raise UserError(_("Invalid domain operator %s", operator))
if not isinstance(value, (float, int)):
raise UserError(_("Invalid domain right operand %s", value))
# Check if we should include lots with a quantity of 0 in the results
uom_precision = self.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
include_without_qty = (
operator == "<"
and float_compare(value, 0, precision_digits=uom_precision) > 0
or operator == "<="
and float_compare(value, 0, precision_digits=uom_precision) >= 0
or operator == ">"
and float_compare(value, 0, precision_digits=uom_precision) < 0
or operator == ">="
and float_compare(value, 0, precision_digits=uom_precision) <= 0
or operator == "="
and float_is_zero(value, precision_digits=uom_precision)
or operator == "!="
and not float_is_zero(value, precision_digits=uom_precision)
)
locations_domain = OR(
[
[("usage", "=", "internal")],
[("usage", "=", "transit"), ("company_id", "!=", False)],
]
)
quants_locations = self.env["stock.location"].search(locations_domain)
grouped_quants = self.env["stock.quant"].read_group(
[("lot_id", "!=", False), ("location_id", "in", quants_locations.ids)],
["lot_id", "quantity"],
["lot_id"],
orderby="id",
)
lot_ids_with_quantity = {
group["lot_id"][0]: group["quantity"] for group in grouped_quants
}
if include_without_qty:
lot_ids_without_qty = self.search(
[("id", "not in", list(lot_ids_with_quantity.keys()))]
).ids
lot_ids_with_quantity.update({lot_id: 0 for lot_id in lot_ids_without_qty})
res_ids = [
lot_id
for lot_id, quantity in lot_ids_with_quantity.items()
if OPERATORS[operator](quantity, value)
]
return [("id", "in", res_ids)]
| 41.212121 | 2,720 |
574 | py | PYTHON | 15.0 | # copyright 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "HR Contract Reference",
"version": "15.0.1.0.0",
"category": "Generic Modules/Human Resources",
"author": "Michael Telahun Makonnen, "
"Fekete Mihai (Forest and Biomass Services Romania), "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"depends": ["hr_contract"],
"data": ["data/hr_contract_sequence.xml"],
"installable": True,
}
| 38.266667 | 574 |
541 | py | PYTHON | 15.0 | # Copyright 2020 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestContractReference(TransactionCase):
def setUp(self):
super(TestContractReference, self).setUp()
self.employee = self.env["hr.employee"].create({"name": "Emp"})
def test_contract_reference(self):
contract = self.env["hr.contract"].create(
{"employee_id": self.employee.id, "wage": 1000}
)
self.assertNotEqual(contract.name, "/")
| 33.8125 | 541 |
572 | py | PYTHON | 15.0 | # copyright 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class HrContract(models.Model):
_inherit = "hr.contract"
name = fields.Char(
"Contract Reference", required=False, readonly=True, copy=False, default="/"
)
@api.model
def create(self, vals):
if vals.get("name", "/") == "/":
vals["name"] = self.env["ir.sequence"].next_by_code("contract.ref")
return super(HrContract, self).create(vals)
| 31.777778 | 572 |
712 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "HR Course",
"summary": """
This module allows your to manage employee's training courses""",
"version": "15.0.1.1.1",
"license": "AGPL-3",
"author": "Creu Blanca,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": ["hr", "mail"],
"data": [
"security/course_security.xml",
"security/ir.model.access.csv",
"views/hr_course_category_views.xml",
"views/hr_course_views.xml",
"views/hr_course_schedule_views.xml",
"views/hr_employee_views.xml",
],
"demo": ["demo/hr_course.xml"],
}
| 32.363636 | 712 |
635 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade # pylint: disable=W7936
_models_renames = [
("hr.course", "hr.course.schedule"),
]
_column_renames = {
"hr_course_attendee": [("course_id", "course_schedule_id")],
}
_table_renames = [("hr_course", "hr_course_schedule")]
@openupgrade.migrate()
def migrate(env, version):
if openupgrade.table_exists(env.cr, "hr_course_schedule"):
return
openupgrade.rename_models(env.cr, _models_renames)
openupgrade.rename_tables(env.cr, _table_renames)
openupgrade.rename_columns(env.cr, _column_renames)
| 31.75 | 635 |
1,093 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade # pylint: disable=W7936
@openupgrade.migrate()
def migrate(env, version):
if openupgrade.column_exists(env.cr, "hr_course", "migration_course_id"):
return
openupgrade.logged_query(
env.cr,
"""
ALTER TABLE hr_course
ADD COLUMN migration_course_id integer""",
)
openupgrade.logged_query(
env.cr,
"""
INSERT INTO hr_course (
name,
category_id,
permanence,
permanence_time,
migration_course_id
)
SELECT name, category_id, permanence, permanence_time, id
FROM hr_course_schedule
""",
)
openupgrade.logged_query(
env.cr,
"""
UPDATE hr_course_schedule hcs
SET course_id = hc.id
FROM hr_course hc
WHERE hc.migration_course_id = hcs.id
""",
)
openupgrade.load_data(
env.cr, "hr_course", "migrations/14.0.2.0.0/noupdate_changes.xml"
)
| 26.658537 | 1,093 |
3,278 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import odoo.tests.common as common
from odoo.exceptions import ValidationError
class TestHrCourse(common.TransactionCase):
def setUp(self):
super(TestHrCourse, self).setUp()
self.course_categ = self.env["hr.course.category"].create(
{"name": "Category 1"}
)
self.employee1 = self.env["hr.employee"].create({"name": "Employee 1"})
self.employee2 = self.env["hr.employee"].create({"name": "Employee 2"})
self.course_id = self.env["hr.course"].create(
{
"name": "Course name",
"category_id": self.course_categ.id,
"permanence": True,
"permanence_time": "1 month",
}
)
self.course_schedule_id = self.env["hr.course.schedule"].create(
{
"name": "Convocatory",
"course_id": self.course_id.id,
"cost": 100,
"authorized_by": self.employee1.id,
"start_date": "2019-02-15",
"end_date": "2019-02-20",
}
)
def test_hr_course(self):
self.course_id.permanence = False
self.course_id._onchange_permanence()
self.assertFalse(self.course_id.permanence_time)
def test_hr_course_schedule(self):
with self.assertRaises(ValidationError):
self.course_schedule_id.write({"end_date": "2019-02-10"})
self.assertEqual(self.course_schedule_id.state, "draft")
self.course_schedule_id.cancel_course()
self.assertEqual(self.course_schedule_id.state, "cancelled")
self.course_schedule_id.back2draft()
self.course_schedule_id.draft2waiting()
self.assertEqual(self.course_schedule_id.state, "waiting_attendees")
self.course_schedule_id.attendant_ids = [
(6, 0, [self.employee1.id, self.employee2.id])
]
self.assertTrue(self.course_schedule_id.attendant_ids)
self.assertEqual(len(self.course_schedule_id.attendant_ids), 2)
self.course_schedule_id.waiting2inprogress()
self.assertEqual(self.course_schedule_id.state, "in_progress")
self.assertEqual(len(self.course_schedule_id.course_attendee_ids), 2)
self.course_schedule_id.attendant_ids = [(2, self.employee2.id, 0)]
self.course_schedule_id.waiting2inprogress()
self.assertEqual(len(self.course_schedule_id.attendant_ids), 1)
self.assertEqual(len(self.course_schedule_id.course_attendee_ids), 1)
self.employee1._compute_count_courses()
self.assertEqual(self.employee1.count_courses, 1)
self.employee1.action_view_course()
self.course_schedule_id.inprogress2validation()
self.assertEqual(self.course_schedule_id.state, "in_validation")
with self.assertRaises(ValidationError):
self.course_schedule_id.validation2complete()
self.course_schedule_id.all_passed()
self.assertEqual(
self.course_schedule_id.course_attendee_ids[0].result, "passed"
)
self.course_schedule_id.validation2complete()
self.assertEqual(self.course_schedule_id.state, "completed")
| 42.571429 | 3,278 |
704 | py | PYTHON | 15.0 | from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
count_courses = fields.Integer(
"Number of courses", compute="_compute_count_courses"
)
courses_ids = fields.One2many(
"hr.course.attendee",
"employee_id",
string="Courses",
readonly=True,
)
@api.depends("courses_ids")
def _compute_count_courses(self):
for r in self:
r.count_courses = len(r.courses_ids)
def action_view_course(self):
action = self.env.ref("hr_course.action_view_course")
result = action.read()[0]
result["domain"] = [("employee_id", "=", self.id)]
return result
| 26.074074 | 704 |
5,002 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class HrCourseSchedule(models.Model):
_name = "hr.course.schedule"
_description = "Course Schedule"
_inherit = "mail.thread"
name = fields.Char(required=True, tracking=True)
course_id = fields.Many2one("hr.course", string="Course", required=True)
start_date = fields.Date(
readonly=True,
states={"draft": [("readonly", False)]},
tracking=True,
)
end_date = fields.Date(
readonly=True,
states={"draft": [("readonly", False)]},
tracking=True,
)
currency_id = fields.Many2one(
"res.currency",
string="Currency",
default=lambda self: self.env.user.company_id.currency_id,
)
cost = fields.Monetary(string="Course Cost", required=True, tracking=True)
authorized_by = fields.Many2one(
comodel_name="hr.employee",
required=True,
readonly=True,
states={"draft": [("readonly", False)]},
tracking=True,
)
state = fields.Selection(
[
("draft", "Draft"),
("waiting_attendees", "Waiting attendees"),
("in_progress", "In progress"),
("in_validation", "In validation"),
("completed", "Completed"),
("cancelled", "Cancelled"),
],
required=True,
readonly=True,
default="draft",
tracking=True,
)
comment = fields.Text()
training_company_id = fields.Many2one("res.partner", string="Training company")
instructor_ids = fields.Many2many("res.partner", string="Instructor")
place = fields.Char()
attendant_ids = fields.Many2many(
"hr.employee",
readonly=True,
states={"waiting_attendees": [("readonly", False)]},
)
course_attendee_ids = fields.One2many(
"hr.course.attendee",
inverse_name="course_schedule_id",
readonly=True,
states={"in_validation": [("readonly", False)]},
)
note = fields.Text()
@api.constrains("start_date", "end_date")
def _check_start_end_dates(self):
self.ensure_one()
if self.start_date and self.end_date and (self.start_date > self.end_date):
raise ValidationError(
_("The start date cannot be later than the end date.")
)
def all_passed(self):
for attendee in self.course_attendee_ids:
attendee.result = "passed"
def _draft2waiting_values(self):
return {"state": "waiting_attendees"}
def _attendee_values(self, attendee):
return {"employee_id": attendee.id, "course_schedule_id": self.id}
def _waiting2inprogress_values(self):
attendants = []
employee_attendants = self.course_attendee_ids.mapped("employee_id")
for attendee in self.attendant_ids.filtered(
lambda r: r not in employee_attendants
):
attendants.append((0, 0, self._attendee_values(attendee)))
deleted_attendees = ""
for course_attendee in self.course_attendee_ids.filtered(
lambda r: r.employee_id not in self.attendant_ids
):
attendants += course_attendee._remove_from_course()
deleted_attendees += "- %s <br></br>" % course_attendee.employee_id.name
if deleted_attendees != "":
message = (
_("Employees removed from this course: <br></br>%s") % deleted_attendees
)
self.message_post(body=message)
return {"state": "in_progress", "course_attendee_ids": attendants}
def _inprogress2validation_values(self):
return {"state": "in_validation"}
def _validation2complete_values(self):
return {"state": "completed"}
def _back2draft_values(self):
return {"state": "draft"}
def _cancel_course_values(self):
return {"state": "cancelled"}
def draft2waiting(self):
for record in self:
record.write(record._draft2waiting_values())
def waiting2inprogress(self):
for record in self:
record.write(record._waiting2inprogress_values())
def inprogress2validation(self):
for record in self:
record.write(record._inprogress2validation_values())
def validation2complete(self):
for record in self:
if self.course_attendee_ids.filtered(
lambda r: r.result == "pending" and r.active
):
raise ValidationError(
_("You cannot complete the course with pending results")
)
else:
record.write(record._validation2complete_values())
def back2draft(self):
for record in self:
record.write(record._back2draft_values())
def cancel_course(self):
for record in self:
record.write(record._cancel_course_values())
| 33.125828 | 5,002 |
2,101 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class HRCourseAttendee(models.Model):
_name = "hr.course.attendee"
_description = "Course Attendee"
course_schedule_id = fields.Many2one(
"hr.course.schedule", ondelete="cascade", readonly=True, required=True
)
name = fields.Char(related="course_schedule_id.name", readonly=True)
employee_id = fields.Many2one("hr.employee", readonly=True)
course_start = fields.Date(related="course_schedule_id.start_date", readonly=True)
course_end = fields.Date(related="course_schedule_id.end_date", readonly=True)
state = fields.Selection(related="course_schedule_id.state", readonly=True)
result = fields.Selection(
[
("passed", "Passed"),
("failed", "Failed"),
("absent", "Absent"),
("pending", "Pending"),
],
default="pending",
)
active = fields.Boolean(default=True, readonly=True)
def _remove_from_course(self):
return [(1, self.id, {"active": False})]
class HrCourse(models.Model):
_name = "hr.course"
_description = "Course"
_inherit = "mail.thread"
name = fields.Char(required=True, tracking=True)
category_id = fields.Many2one(
"hr.course.category", string="Category", required=True
)
permanence = fields.Boolean(string="Has Permanence", default=False, tracking=True)
permanence_time = fields.Char(tracking=True)
content = fields.Html()
objective = fields.Html()
evaluation_criteria = fields.Html()
course_schedule_ids = fields.One2many(
"hr.course.schedule", inverse_name="course_id"
)
@api.onchange("permanence")
def _onchange_permanence(self):
self.permanence_time = False
class HRCourseCategory(models.Model):
_name = "hr.course.category"
_description = "Course Category"
name = fields.Char(string="Course category", required=True)
_sql_constraints = [("name_uniq", "unique (name)", "Category already exists !")]
| 31.358209 | 2,101 |
748 | py | PYTHON | 15.0 | # © 2012 Odoo Canada
# © 2015 Acysos S.L.
# © 2017 ForgeFlow S.L.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{
"name": "HR Worked Days From Timesheet",
"summary": "Adds a button to import worked days from timesheet.",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"category": "Generic Modules/Human Resources",
"author": "Savoir-faire Linux, Acysos S.L., ForgeFlow, "
"Serpent Consulting Services Pvt. Ltd.,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": [
"payroll",
"hr_timesheet_sheet",
],
"data": ["views/hr_payslip_view.xml"],
"installable": True,
}
| 32.391304 | 745 |
4,805 | py | PYTHON | 15.0 | # © 2012 Odoo Canada
# © 2015 Acysos S.L.
# © 2017 ForgeFlow S.L.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
import time
from odoo import fields
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class TestComputeWorkdays(TransactionCase):
def setUp(self):
super(TestComputeWorkdays, self).setUp()
self.company = self.env.ref("base.main_company")
self.user_admin = self.env.ref("base.partner_root")
self.timesheet_sheet = self.env["hr_timesheet.sheet"]
self.project_2 = self.env.ref("project.project_project_2")
hr_user_group = self.env.ref("hr.group_hr_user")
self.user_admin.user_id.groups_id = [(4, hr_user_group.id)]
# create user
user_dict = {
"name": "User 1",
"login": "tua@example.com",
"password": "base-test-passwd",
}
self.user_test = self.env["res.users"].create(user_dict)
user_dict2 = {
"name": "User 2",
"login": "user2@example.com",
"password": "base-test-passwd",
}
self.user_test2 = self.env["res.users"].create(user_dict2)
# create Employee
employee_dict = {
"name": "Employee 1",
"user_id": self.user_test.id,
"address_id": self.user_test.partner_id.id,
}
self.employee = self.env["hr.employee"].create(employee_dict)
employee_dict2 = {
"name": "Employee 2",
"user_id": self.user_test2.id,
"address_id": self.user_test.partner_id.id,
}
self.employee2 = self.env["hr.employee"].create(employee_dict2)
# create Contract
contract_dict = {
"name": "Contract 1",
"employee_id": self.employee.id,
"wage": 10.0,
}
self.contract = self.env["hr.contract"].create(contract_dict)
contract_dict2 = {
"name": "Contract 1",
"employee_id": self.employee.id,
"wage": 15.0,
}
self.contract2 = self.env["hr.contract"].create(contract_dict2)
self.timesheet_sheet = self.timesheet_sheet.create(
{
"date_start": fields.Date.to_date(time.strftime("%Y-%m-11")),
"date_end": fields.Date.to_date(time.strftime("%Y-%m-17")),
"name": "Employee 1",
"state": "new",
"employee_id": self.employee.id,
}
)
# I add 5 hours of work timesheet
self.timesheet_sheet.write(
{
"timesheet_ids": [
(
0,
0,
{
"project_id": self.project_2.id,
"date": fields.Date.to_date(time.strftime("%Y-%m-11")),
"name": "Develop UT for hr module(1)",
"user_id": self.user_test.id,
"unit_amount": 5.00,
},
)
]
}
)
self.timesheet_sheet.action_timesheet_confirm()
self.timesheet_sheet.sudo().with_user(self.user_admin.id).with_context(
mail_track_log_only=True
).action_timesheet_done()
def test_timesheet_import(self):
payslip_dict = {
"employee_id": self.employee.id,
"contract_id": self.contract.id,
"date_from": fields.Date.to_date(time.strftime("%Y-%m-01")),
"date_to": fields.Date.to_date(time.strftime("%Y-%m-21")),
}
payslip = self.env["hr.payslip"].create(payslip_dict)
payslip.import_worked_days()
self.assertEqual(payslip.worked_days_line_ids.number_of_hours, 5.0)
def test_check_contract_warning(self):
payslip_dict = {
"employee_id": self.employee.id,
"date_from": fields.Date.to_date(time.strftime("%Y-%m-01")),
"date_to": fields.Date.to_date(time.strftime("%Y-%m-21")),
}
payslip = self.env["hr.payslip"].create(payslip_dict)
with self.assertRaises(UserError):
payslip.import_worked_days()
def test_get_timesheet_for_employee_warning(self):
payslip_dict = {
"employee_id": self.employee2.id,
"contract_id": self.contract2.id,
"date_from": fields.Date.to_date(time.strftime("%Y-%m-01")),
"date_to": fields.Date.to_date(time.strftime("%Y-%m-21")),
}
payslip = self.env["hr.payslip"].create(payslip_dict)
with self.assertRaises(UserError):
payslip.import_worked_days()
| 35.308824 | 4,802 |
3,954 | py | PYTHON | 15.0 | # © 2012 Odoo Canada
# © 2015 Acysos S.L.
# © 2017 ForgeFlow S.L.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import _, api, models
from odoo.exceptions import UserError
class HrPayslip(models.Model):
_inherit = "hr.payslip"
@api.model
def prepare_worked_days(self, payslip, ts_sheet, date_from, date_to):
number_of_hours = 0
for ts in ts_sheet.timesheet_ids:
if date_from <= ts.date <= date_to:
number_of_hours += ts.unit_amount
# Get formatted date from the timesheet sheet
date_from_formatted = ts_sheet.date_start
number_of_days = (date_to - date_from).days
if number_of_hours > 0 and number_of_days > 0:
return {
"name": _("Timesheet %s") % date_from_formatted,
"number_of_hours": number_of_hours,
"number_of_days": number_of_days,
"contract_id": payslip.contract_id.id,
"code": "TS",
"imported_from_timesheet": True,
"timesheet_sheet_id": ts_sheet.id,
"payslip_id": payslip.id,
}
return False
def _timesheet_mapping(self, timesheet_sheets, payslip, date_from, date_to):
"""This function takes timesheet objects imported from the timesheet
module and creates a dict of worked days to be created in the payslip.
"""
# Create one worked days record for each timesheet sheet
for ts_sheet in timesheet_sheets:
worked_days_data = self.prepare_worked_days(
payslip, ts_sheet, date_from, date_to
)
if worked_days_data:
self.env["hr.payslip.worked_days"].create(worked_days_data)
def _check_contract(self):
"""Contract is not required field for payslips, yet it is for
payslips.worked_days."""
for payslip in self:
if not payslip.contract_id:
raise UserError(
_("Contract is not defined for one or more payslips."),
)
@api.model
def get_timesheets_from_employee(self, employee, date_from, date_to):
criteria = [
("date_start", ">=", date_from),
("date_end", "<=", date_to),
("state", "=", "done"),
("employee_id", "=", employee.id),
]
ts_model = self.env["hr_timesheet.sheet"]
timesheet_sheets = ts_model.search(criteria)
if not timesheet_sheets:
raise UserError(
_(
"Sorry, but there is no approved Timesheets for "
"the entire Payslip period for user {}"
).format(employee.name)
)
return timesheet_sheets
def import_worked_days(self):
"""This method retrieves the employee's timesheet for a payslip period
and creates worked days records from the imported timesheet
"""
self._check_contract()
for payslip in self:
date_from = payslip.date_from
date_to = payslip.date_to
# Delete old imported worked_days
# The reason to delete these records is that the user may make
# corrections to his timesheets and then reimport these.
self.env["hr.payslip.worked_days"].search(
[
("payslip_id", "=", payslip.id),
("imported_from_timesheet", "=", True),
]
).unlink()
# get timesheet sheets of employee
timesheet_sheets = self.get_timesheets_from_employee(
payslip.employee_id, date_from, date_to
)
# The reason to call this method is for other modules to modify it.
self._timesheet_mapping(timesheet_sheets, payslip, date_from, date_to)
| 39.51 | 3,951 |
479 | py | PYTHON | 15.0 | # © 2012 Odoo Canada
# © 2015 Acysos S.L.
# © 2017 ForgeFlow S.L.
# Copyright 2017 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class HrPayslipWorkedDays(models.Model):
_inherit = "hr.payslip.worked_days"
imported_from_timesheet = fields.Boolean(default=False)
timesheet_sheet_id = fields.Many2one(
string="Timesheet", comodel_name="hr_timesheet.sheet"
)
| 29.75 | 476 |
608 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "HR Branch",
"summary": "Allow define company branch for employee process",
"version": "15.0.1.0.0",
"development_status": "Mature",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "Vauxoo, Odoo Community Association (OCA)",
"maintainers": ["luistorresm"],
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": ["hr"],
"data": ["views/hr_department_views.xml", "views/hr_employee_views.xml"],
"demo": [],
"qweb": [],
}
| 33.777778 | 608 |
339 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrDepartment(models.Model):
_inherit = "hr.department"
branch_id = fields.Many2one(
"res.partner",
help="Indicate the department branch, to ensure that the "
"employees are assigned correctly",
)
| 26.076923 | 339 |
490 | py | PYTHON | 15.0 | # Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Employee Digitized Signature",
"version": "15.0.1.0.0",
"author": "Ecosoft, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"category": "Human Resources",
"license": "AGPL-3",
"depends": ["hr"],
"data": ["views/hr_employee_views.xml"],
"installable": True,
"maintainers": ["newtratip"],
}
| 32.666667 | 490 |
251 | py | PYTHON | 15.0 | # Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
signature = fields.Binary()
| 25.1 | 251 |
650 | py | PYTHON | 15.0 | # Copyright 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "HR Job Employee Categories",
"version": "15.0.1.0.0",
"category": "Generic Modules/Human Resources",
"summary": "Adds tags to employee through contract and job position",
"author": "Michael Telahun Makonnen <mmakonnen@gmail.com>, "
"Savoir-faire Linux, "
"Fekete Mihai (FBSR), "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"depends": ["hr_contract"],
"data": ["views/hr_view.xml"],
"installable": True,
}
| 36.111111 | 650 |
3,132 | py | PYTHON | 15.0 | # Copyright 2014 Savoir-faire Linux
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import common
class TestHrJobCategories(common.TransactionCase):
def setUp(self):
super(TestHrJobCategories, self).setUp()
self.employee_model = self.env["hr.employee"]
self.employee_categ_model = self.env["hr.employee.category"]
self.user_model = self.env["res.users"]
self.job_model = self.env["hr.job"]
self.contract_model = self.env["hr.contract"]
# Create a employee
self.employee_id_1 = self.employee_model.create({"name": "Employee 1"})
self.employee_id_2 = self.employee_model.create({"name": "Employee 2"})
# Create two employee categories
self.categ_id = self.employee_categ_model.create({"name": "Category 1"})
self.categ_2_id = self.employee_categ_model.create({"name": "Category 2"})
# Create two jobs
self.job_id = self.job_model.create(
{"name": "Job 1", "category_ids": [(6, 0, [self.categ_id.id])]}
)
self.job_2_id = self.job_model.create(
{"name": "Job 2", "category_ids": [(6, 0, [self.categ_2_id.id])]}
)
# Create one contract
self.contract_id = self.contract_model.create(
{"name": "Contract 1", "employee_id": self.employee_id_1.id, "wage": 50000}
)
def test_write_computes_with_normal_args(self):
"""
Test that write method on hr_contract computes without error
when the required data is given in parameter
Check if the job categories are written to the employee.
"""
# Check if job categories are written to the employee
self.contract_id.write({"job_id": self.job_id.id})
self.contract_id.refresh()
self.assertTrue(self.employee_id_1.category_ids)
self.assertTrue(
all(
x in self.employee_id_1.category_ids.ids
for x in self.job_id.category_ids.ids
)
)
self.contract_id.write({"job_id": False})
self.assertFalse(self.employee_id_1.category_ids)
# Check if job2 categories are written to the employee
self.contract_id.write({"job_id": self.job_2_id.id})
self.contract_id.flush()
self.assertTrue(
all(
x in self.employee_id_1.category_ids.ids
for x in self.job_2_id.category_ids.ids
)
)
self.contract_id.write({"employee_id": self.employee_id_2.id})
self.contract_id.write({"job_id": self.job_2_id.id})
# We need to force the job, as it is modified by a compute
self.employee_id_1.refresh()
self.employee_id_2.refresh()
self.assertFalse(self.employee_id_1.category_ids)
self.job_2_id.refresh()
self.assertTrue(
all(
x in self.employee_id_2.category_ids.ids
for x in self.job_2_id.category_ids.ids
)
)
self.contract_id.unlink()
self.assertFalse(self.employee_id_2.category_ids)
| 37.73494 | 3,132 |
1,588 | py | PYTHON | 15.0 | # Copyright 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class HRJob(models.Model):
_inherit = "hr.job"
category_ids = fields.Many2many(
"hr.employee.category",
"job_category_rel",
"job_id",
"category_id",
string="Associated Tags",
)
class HRContract(models.Model):
_inherit = "hr.contract"
def _tag_employees(self, job_id):
if job_id:
job = self.env["hr.job"].browse(job_id)
self.mapped("employee_id").write(
{"category_ids": [(6, 0, job.category_ids.ids)]}
)
else:
for contract in self:
categories = contract.job_id and contract.job_id.category_ids.ids or []
contract.employee_id.write({"category_ids": [(6, 0, categories)]})
@api.model
def create(self, vals):
res = super().create(vals)
if "job_id" in vals:
res._tag_employees(vals.get("job_id"))
return res
def write(self, vals):
if "employee_id" in vals:
self.mapped("employee_id").write({"category_ids": [(5,)]})
res = super().write(vals)
if "job_id" in vals or ("employee_id" in vals and vals["employee_id"]):
self._tag_employees(vals.get("job_id"))
return res
def unlink(self):
self.mapped("employee_id").write({"category_ids": [(5,)]})
return super().unlink()
| 29.407407 | 1,588 |
1,226 | py | PYTHON | 15.0 | from odoo import SUPERUSER_ID
from odoo.api import Environment
def post_init_hook(cr, _):
# This SQL statement is necessary to call _install_employee_lastnames() and
# set name fields correctly.
#
# After the installation, previously the dependency hr_employee_firstname
# splitting the name into two parts: firstname and lastname, so for this
# module to be able to process the new field lastmane2 it is necessary to
# reset the values to empty to be able to correctly set the three fields
# (firstname, lastname and lastname2).
#
# For example:
# After install hr_employee_fisrtname and before install hr_employee_lastnames:
# name = 'John Peterson Clinton'
# firstname = 'John'
# lastname = 'Peterson Clinton'
#
# After install hr_employee_lastnames:
# name = 'John Peterson Clinton'
# firstname = 'John'
# lastname = 'Peterson'
# lastname2 = 'Clinton'
cr.execute("UPDATE hr_employee SET firstname = NULL, lastname = NULL")
env = Environment(cr, SUPERUSER_ID, {})
env["hr.employee"]._install_employee_lastnames()
env["ir.config_parameter"].sudo().set_param("employee_names_order", "first_last")
| 42.275862 | 1,226 |
605 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "HR Employee First Name and Two Last Names",
"version": "15.0.1.0.0",
"author": "Vauxoo, Odoo Community Association (OCA)",
"maintainer": "Vauxoo",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"category": "Human Resources",
"summary": "Split Name in First Name, Father's Last Name and Mother's Last Name",
"depends": ["hr_employee_firstname"],
"data": ["views/hr_views.xml"],
"post_init_hook": "post_init_hook",
"demo": [],
"test": [],
"installable": True,
}
| 35.588235 | 605 |
6,562 | py | PYTHON | 15.0 | from odoo import exceptions
from odoo.tests.common import TransactionCase
class TestEmployeeLastnames(TransactionCase):
def setUp(self):
super(TestEmployeeLastnames, self).setUp()
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "first_last"
)
self.employee_model = self.env["hr.employee"]
# Create 3 employees to concatenate the firstname and lastnames
# in name_related
self.employee1_id = self.employee_model.create(
{"firstname": "Manuel", "lastname": "Fernandez", "lastname2": "Gonzalez"}
)
self.employee2_id = self.employee_model.create(
{"firstname": "Jean-Pierre", "lastname": "Carnaud"}
)
self.employee3_id = self.employee_model.create(
{"firstname": "Jenssens", "lastname": "Famke"}
)
# Create 3 employees for split the name_related to
# firstname and lastnames
self.employee10_id = self.employee_model.create(
{"name": "Manuel Fernandez Gonzalez"}
)
self.employee20_id = self.employee_model.create({"name": "Jean-Pierre Carnaud"})
self.employee30_id = self.employee_model.create({"name": "JenssensFamke"})
def test_get_name_lastnames(self):
"""Validate the _get_name_lastnames method is concatenating
the firstname and lastnames
"""
# Check for employee1
self.assertEqual(self.employee1_id.name, "Manuel Fernandez Gonzalez")
# Check for employee2
self.assertEqual(self.employee2_id.name, "Jean-Pierre Carnaud")
# Check for employee3
self.assertEqual(self.employee3_id.name, "Jenssens Famke")
def test_onchange(self):
"""Validate the _get_name_lastnames method is not failing"""
field_onchange = self.employee_model.new({})._onchange_spec()
self.assertEqual(field_onchange.get("firstname"), "1")
self.assertEqual(field_onchange.get("lastname"), "1")
values = {
"firstname": "Pedro",
"lastname": "Perez",
"lastname2": "Hernandez",
"name": "test employee",
}
for field in self.employee_model._fields:
if field not in values:
values[field] = False
# we work on a temporary record
new_record = self.employee_model.new(values)
updates = new_record.onchange(
values, ["firstname", "lastname", "lastname2"], field_onchange
)
values.update(updates.get("value", {}))
self.assertEqual(values["name"], "Pedro Perez Hernandez")
def test_auto_init_name(self):
"""Validate the create method if the name is split
in firstname and lastnames
"""
# Check for employee10
self.assertEqual(self.employee10_id.firstname, "Manuel")
self.assertEqual(self.employee10_id.lastname, "Fernandez")
self.assertEqual(self.employee10_id.lastname2, "Gonzalez")
# Check for employee20
self.assertEqual(self.employee20_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee20_id.lastname, "Carnaud")
self.assertEqual(self.employee20_id.lastname2, False)
# Check for employee30
self.assertEqual(self.employee30_id.firstname, False)
self.assertEqual(self.employee30_id.lastname, "JenssensFamke")
self.assertEqual(self.employee30_id.lastname2, False)
employee_without_name = self.employee_model
with self.assertRaises(exceptions.ValidationError):
employee_without_name = self.employee_model.create(
{"firstname": "", "lastname": ""}
)
self.assertEqual(employee_without_name, self.employee_model)
def test_change_name(self):
self.employee1_id.write({"name": "Pedro Martinez Torres"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Pedro")
self.assertEqual(self.employee1_id.lastname, "Martinez")
self.assertEqual(self.employee1_id.lastname2, "Torres")
def test_change_name_with_space(self):
self.employee1_id.write({"name": " Jean-Pierre Carnaud-Eyck"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee1_id.lastname, "Carnaud-Eyck")
self.assertEqual(self.employee1_id.lastname2, False)
def test_change_firstname(self):
self.employee1_id.write({"firstname": "Pedro"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Pedro Fernandez Gonzalez")
def test_change_lastname(self):
self.employee1_id.write({"lastname": "Lopez"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Manuel Lopez Gonzalez")
def test_change_firstname_and_lastnames(self):
self.employee1_id.write({"firstname": "Jean-Pierre", "lastname2": "Carnaud"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Jean-Pierre Fernandez Carnaud")
def test_change_lastname_with_set_last_first(self):
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "last_first"
)
self.employee1_id.write({"lastname": "Lopez"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Lopez Gonzalez Manuel")
def test_change_name_with_set_last_first(self):
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "last_first"
)
self.employee1_id.write({"name": "Martinez Torres Pedro"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Pedro")
self.assertEqual(self.employee1_id.lastname, "Martinez")
self.assertEqual(self.employee1_id.lastname2, "Torres")
self.employee1_id.write({"name": ""})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Pedro")
self.assertEqual(self.employee1_id.lastname, "Martinez")
self.assertEqual(self.employee1_id.lastname2, "Torres")
def test_change_lastname_with_set_last_first_comma(self):
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "last_first_comma"
)
self.employee1_id.write({"lastname": "Lopez"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Lopez Gonzalez, Manuel")
| 40.257669 | 6,562 |
5,813 | py | PYTHON | 15.0 | import logging
from odoo import api, models
from odoo.addons.hr_employee_firstname.models.hr_employee import UPDATE_PARTNER_FIELDS
_logger = logging.getLogger(__name__)
UPDATE_PARTNER_FIELDS += ["lastname2"]
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_name_lastnames(self, lastname, firstname, lastname2=None):
order = self._get_names_order()
names = list()
if order == "first_last":
if firstname:
names.append(firstname)
if lastname:
names.append(lastname)
if lastname2:
names.append(lastname2)
else:
if lastname:
names.append(lastname)
if lastname2:
names.append(lastname2)
if names and firstname and order == "last_first_comma":
names[-1] = names[-1] + ","
if firstname:
names.append(firstname)
return " ".join(names)
def _prepare_vals_on_create_firstname_lastname(self, vals):
values = vals.copy()
res = super(HrEmployee, self)._prepare_vals_on_create_firstname_lastname(values)
if any([field in vals for field in ("firstname", "lastname", "lastname2")]):
vals["name"] = self._get_name_lastnames(
vals.get("lastname"), vals.get("firstname"), vals.get("lastname2")
)
elif vals.get("name"):
name_splitted = self.split_name(vals["name"])
vals["firstname"] = name_splitted["firstname"]
vals["lastname"] = name_splitted["lastname"]
vals["lastname2"] = name_splitted["lastname2"]
return res
def _prepare_vals_on_write_firstname_lastname(self, vals):
values = vals.copy()
res = super(HrEmployee, self)._prepare_vals_on_write_firstname_lastname(values)
if any([field in vals for field in ("firstname", "lastname", "lastname2")]):
if "lastname" in vals:
lastname = vals["lastname"]
else:
lastname = self.lastname
if "firstname" in vals:
firstname = vals["firstname"]
else:
firstname = self.firstname
if "lastname2" in vals:
lastname2 = vals["lastname2"]
else:
lastname2 = self.lastname2
vals["name"] = self._get_name_lastnames(lastname, firstname, lastname2)
elif vals.get("name"):
name_splitted = self.split_name(vals["name"])
vals["lastname"] = name_splitted["lastname"]
vals["firstname"] = name_splitted["firstname"]
vals["lastname2"] = name_splitted["lastname2"]
return res
def _update_partner_firstname(self):
for employee in self:
partners = employee.mapped("user_id.partner_id")
partners |= employee.mapped("address_home_id")
partners.write(
{
"firstname": employee.firstname,
"lastname": employee.lastname,
"lastname2": employee.lastname2,
}
)
@api.model
def _get_inverse_name(self, name):
"""Compute the inverted name."""
result = {
"firstname": False,
"lastname": name or False,
"lastname2": False,
}
if not name:
return result
order = self._get_names_order()
result.update(super(HrEmployee, self)._get_inverse_name(name))
if order in ("first_last", "last_first_comma"):
parts = self._split_part("lastname", result)
if parts:
result.update({"lastname": parts[0], "lastname2": " ".join(parts[1:])})
else:
parts = self._split_part("firstname", result)
if parts:
result.update(
{"firstname": parts[-1], "lastname2": " ".join(parts[:-1])}
)
return result
def _split_part(self, name_part, name_split):
"""Split a given part of a name.
:param name_split: The parts of the name
:type dict
:param name_part: The part to split
:type str
"""
name = name_split.get(name_part, False)
parts = name.split(" ", 1) if name else []
if not name or len(parts) < 2:
return False
return parts
def _inverse_name(self):
"""Try to revert the effect of :method:`._compute_name`."""
for record in self:
parts = self._get_inverse_name(record.name)
record.write(
{
"lastname": parts["lastname"],
"firstname": parts["firstname"],
"lastname2": parts["lastname2"],
}
)
@api.model
def _install_employee_lastnames(self):
"""Save names correctly in the database.
Before installing the module, field ``name`` contains all full names.
When installing it, this method parses those names and saves them
correctly into the database. This can be called later too if needed.
"""
# Find records with empty firstname and lastnames
records = self.search([("firstname", "=", False), ("lastname", "=", False)])
# Force calculations there
records._inverse_name()
_logger.info("%d employees updated installing module.", len(records))
@api.onchange("firstname", "lastname", "lastname2")
def _onchange_firstname_lastname(self):
if self.firstname or self.lastname or self.lastname2:
self.name = self._get_name_lastnames(
self.lastname, self.firstname, self.lastname2
)
| 36.33125 | 5,813 |
243 | py | PYTHON | 15.0 | from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_inherit = "hr.employee.base"
firstname = fields.Char("First name")
lastname = fields.Char("Last name")
lastname2 = fields.Char("Second last name")
| 27 | 243 |
693 | py | PYTHON | 15.0 | # Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Employees study field",
"summary": "Structured study field for employees",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["hr"],
"data": [
"security/ir.model.access.csv",
"security/security.xml",
"views/hr_employee_view.xml",
"views/hr_study_views.xml",
],
"demo": ["demo/hr_study.xml"],
"installable": True,
"maintainers": ["victoralmau"],
}
| 32.904762 | 691 |
1,102 | py | PYTHON | 15.0 | # Copyright 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
from odoo.tests.common import users
class TestHrStudy(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.study = cls.env["hr.study"].create({"name": "Test study"})
cls.employee = cls.env["hr.employee"].create({"name": "Test employee"})
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
new_test_user(
cls.env,
login="test-hr_user",
groups="hr.group_hr_user",
context=ctx,
)
@users("test-hr_user")
def test_employee_onchange(self):
self.assertFalse(self.employee.study_field)
employee_form = Form(self.employee)
employee_form.study_id = self.study
employee_form.save()
self.assertEqual(self.employee.study_field, "Test study")
| 33.333333 | 1,100 |
395 | py | PYTHON | 15.0 | # Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrStudy(models.Model):
_name = "hr.study"
_description = "Study"
_order = "sequence, id"
sequence = fields.Integer(default=10)
name = fields.Char(required=True)
company_id = fields.Many2one(comodel_name="res.company")
| 28.071429 | 393 |
507 | py | PYTHON | 15.0 | # Copyright 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 HrEmployee(models.Model):
_inherit = "hr.employee"
study_id = fields.Many2one(
comodel_name="hr.study",
string="Study",
groups="hr.group_hr_user",
tracking=True,
)
@api.onchange("study_id")
def _onchange_study_id(self):
if self.study_id:
self.study_field = self.study_id.name
| 25.25 | 505 |
313 | py | PYTHON | 15.0 | # Copyright 2016-2019 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID
from odoo.api import Environment
def post_init_hook(cr, _):
env = Environment(cr, SUPERUSER_ID, {})
env["hr.employee"]._install_employee_firstname()
| 31.3 | 313 |
721 | py | PYTHON | 15.0 | # Copyright 2010-2014 Savoir-faire Linux (<http://www.savoirfairelinux.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "HR Employee First Name, Last Name",
"version": "15.0.1.0.0",
"author": "Savoir-faire Linux, "
"Fekete Mihai (Forest and Biomass Services Romania), "
"Onestein, "
"Odoo Community Association (OCA)",
"maintainer": "Savoir-faire Linux",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"category": "Human Resources",
"summary": "Adds First Name to Employee",
"depends": ["hr"],
"data": ["views/hr_view.xml", "views/base_config_view.xml"],
"post_init_hook": "post_init_hook",
"installable": True,
}
| 36.05 | 721 |
6,840 | py | PYTHON | 15.0 | # Copyright (C) 2014 Savoir-faire Linux. All Rights Reserved.
# Copyright 2016-2019 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import odoo
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestEmployeeFirstname(TransactionCase):
def setUp(self):
super().setUp()
# Create 3 employees to concatenate the firstname and lastname
# in name_related
self.employee1_id = self.env["hr.employee"].create(
{"firstname": "Jan", "lastname": "Van-Eyck"}
)
self.employee2_id = self.env["hr.employee"].create(
{"firstname": "Jean-Pierre", "lastname": "Carnaud"}
)
self.employee3_id = self.env["hr.employee"].create(
{"firstname": "Famke", "lastname": "Jenssens"}
)
# Create 3 employees for split the name_related to
# firstname and lastname
self.employee10_id = self.env["hr.employee"].create({"name": " Jan Van-Eyck"})
self.employee20_id = self.env["hr.employee"].create(
{"name": "Jean-Pierre Carnaud"}
)
self.employee30_id = self.env["hr.employee"].create({"name": "JenssensFamke"})
def test_get_name(self):
"""
Validate the _get_name method is concatenating
the firstname and lastname
"""
# Check for employee1
self.assertEqual(self.employee1_id.name, "Jan Van-Eyck")
# Check for employee2
self.assertEqual(self.employee2_id.name, "Jean-Pierre Carnaud")
# Check for employee3
self.assertEqual(self.employee3_id.name, "Famke Jenssens")
def test_onchange(self):
"""
Validate the get_name method is not failing
"""
field_onchange = self.env["hr.employee"].new({})._onchange_spec()
self.assertEqual(field_onchange.get("firstname"), "1")
self.assertEqual(field_onchange.get("lastname"), "1")
values = {
"firstname": "Antonio",
"lastname": "Esposito",
"name": "test employee",
}
for field in self.env["hr.employee"]._fields:
if field not in values:
values[field] = False
# we work on a temporary record
new_record = self.env["hr.employee"].new(values)
updates = new_record.onchange(values, ["firstname", "lastname"], field_onchange)
values.update(updates.get("value", {}))
self.assertEqual(values["name"], "Antonio Esposito")
def test_auto_init_name(self):
"""
Validate the create method if the name is split
in firstname and lastname
"""
# Check for employee10
self.assertEqual(self.employee10_id.firstname, "Jan")
self.assertEqual(self.employee10_id.lastname, "Van-Eyck")
# Check for employee20
self.assertEqual(self.employee20_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee20_id.lastname, "Carnaud")
# Check for employee30
self.assertEqual(self.employee30_id.firstname, False)
self.assertEqual(self.employee30_id.lastname, "JenssensFamke")
def test_change_name(self):
self.employee1_id.write({"name": "Jean-Pierre Carnaud-Eyck"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee1_id.lastname, "Carnaud-Eyck")
def test_change_name_with_space(self):
self.employee1_id.write({"name": " Jean-Pierre Carnaud-Eyck"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee1_id.lastname, "Carnaud-Eyck")
def test_change_firstname(self):
self.employee1_id.write({"firstname": "Jean-Pierre"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Jean-Pierre Van-Eyck")
def test_change_lastname(self):
self.employee1_id.write({"lastname": "Carnaud"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Jan Carnaud")
def test_change_firstname_and_lastname(self):
self.employee1_id.write({"firstname": "Jean-Pierre", "lastname": "Carnaud"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Jean-Pierre Carnaud")
def test_lastname_firstname(self):
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "last_first"
)
self.employee1_id.write({"name": "Carnaud-Eyck Jean-Pierre"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee1_id.lastname, "Carnaud-Eyck")
self.employee1_id.write({"name": " Carnaud-Eyck Jean-Pierre"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee1_id.lastname, "Carnaud-Eyck")
self.employee1_id.write({"firstname": "Jean-Pierre", "lastname": "Carnaud"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Carnaud Jean-Pierre")
@odoo.tests.tagged("-at_install", "post_install")
def test_update_name_post_install(self):
empl_demo = self.env.ref("hr.employee_admin")
self.assertEqual(empl_demo.firstname, "Mitchell")
self.assertEqual(empl_demo.lastname, "Admin")
def test_no_name(self):
self.env["hr.employee"].create({"firstname": "test"})
self.env["hr.employee"].create({"lastname": "test"})
self.env["hr.employee"].create({"name": "test"})
with self.assertRaises(ValidationError):
self.env["hr.employee"].create({})
def test_no_firstname_and_lastname(self):
with self.assertRaises(ValidationError):
self.employee1_id.write({"firstname": "", "lastname": ""})
def test_change_firstname_and_lastname_with_set_last_first_comma(self):
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "last_first_comma"
)
self.employee1_id.write({"firstname": "Jean-Pierre", "lastname": "Carnaud"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.name, "Carnaud, Jean-Pierre")
def test_change_name_with_space_with_set_last_first_comma(self):
self.env["ir.config_parameter"].sudo().set_param(
"employee_names_order", "last_first_comma"
)
self.employee1_id.write({"name": " Carnaud-Eyck, Jean-Pierre"})
self.employee1_id.refresh()
self.assertEqual(self.employee1_id.firstname, "Jean-Pierre")
self.assertEqual(self.employee1_id.lastname, "Carnaud-Eyck")
| 39.537572 | 6,840 |
6,580 | py | PYTHON | 15.0 | # Copyright 2010-2014 Savoir-faire Linux (<http://www.savoirfairelinux.com>)
# Copyright 2016-2019 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import _, api, models
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)
UPDATE_PARTNER_FIELDS = ["firstname", "lastname", "user_id", "address_home_id"]
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _names_order_default(self):
return "first_last"
@api.model
def _get_names_order(self):
"""Get names order configuration from system parameters.
You can override this method to read configuration from language,
country, company or other"""
return (
self.env["ir.config_parameter"]
.sudo()
.get_param("employee_names_order", self._names_order_default())
)
@api.model
def _get_name(self, lastname, firstname):
order = self._get_names_order()
if order == "last_first_comma":
return ", ".join(p for p in (lastname, firstname) if p)
elif order == "first_last":
return " ".join(p for p in (firstname, lastname) if p)
else:
return " ".join(p for p in (lastname, firstname) if p)
@api.onchange("firstname", "lastname")
def _onchange_firstname_lastname(self):
if self.firstname or self.lastname:
self.name = self._get_name(self.lastname, self.firstname)
@api.model
def _is_partner_firstname_installed(self):
return bool(
self.env["ir.module.module"]
.sudo()
.search([("name", "=", "partner_firstname"), ("state", "=", "installed")])
)
@api.model
def create(self, vals):
self._prepare_vals_on_create_firstname_lastname(vals)
res = super().create(vals)
if self._is_partner_firstname_installed():
res._update_partner_firstname()
return res
def write(self, vals):
self._prepare_vals_on_write_firstname_lastname(vals)
res = super().write(vals)
if self._is_partner_firstname_installed() and set(vals).intersection(
UPDATE_PARTNER_FIELDS
):
self._update_partner_firstname()
return res
def _prepare_vals_on_create_firstname_lastname(self, vals):
if vals.get("firstname") or vals.get("lastname"):
vals["name"] = self._get_name(vals.get("lastname"), vals.get("firstname"))
elif vals.get("name"):
vals["lastname"] = self.split_name(vals["name"])["lastname"]
vals["firstname"] = self.split_name(vals["name"])["firstname"]
else:
raise ValidationError(_("No name set."))
def _prepare_vals_on_write_firstname_lastname(self, vals):
if "firstname" in vals or "lastname" in vals:
if "lastname" in vals:
lastname = vals.get("lastname")
else:
lastname = self.lastname
if "firstname" in vals:
firstname = vals.get("firstname")
else:
firstname = self.firstname
vals["name"] = self._get_name(lastname, firstname)
elif vals.get("name"):
vals["lastname"] = self.split_name(vals["name"])["lastname"]
vals["firstname"] = self.split_name(vals["name"])["firstname"]
@api.model
def _get_whitespace_cleaned_name(self, name, comma=False):
"""Remove redundant whitespace from :param:`name`.
Removes leading, trailing and duplicated whitespace.
"""
try:
name = " ".join(name.split()) if name else name
except UnicodeDecodeError:
name = " ".join(name.decode("utf-8").split()) if name else name
if comma:
name = name.replace(" ,", ",").replace(", ", ",")
return name
@api.model
def _get_inverse_name(self, name):
"""Compute the inverted name.
This method can be easily overriden by other submodules.
You can also override this method to change the order of name's
attributes
When this method is called, :attr:`~.name` already has unified and
trimmed whitespace.
"""
order = self._get_names_order()
# Remove redundant spaces
name = self._get_whitespace_cleaned_name(
name, comma=(order == "last_first_comma")
)
parts = name.split("," if order == "last_first_comma" else " ", 1)
if len(parts) > 1:
if order == "first_last":
parts = [" ".join(parts[1:]), parts[0]]
else:
parts = [parts[0], " ".join(parts[1:])]
else:
while len(parts) < 2:
parts.append(False)
return {"lastname": parts[0], "firstname": parts[1]}
@api.model
def split_name(self, name):
clean_name = " ".join(name.split(None)) if name else name
return self._get_inverse_name(clean_name)
def _inverse_name(self):
"""Try to revert the effect of :meth:`._compute_name`."""
for record in self:
parts = self._get_inverse_name(record.name)
record.lastname = parts["lastname"]
record.firstname = parts["firstname"]
@api.model
def _install_employee_firstname(self):
"""Save names correctly in the database.
Before installing the module, field ``name`` contains all full names.
When installing it, this method parses those names and saves them
correctly into the database. This can be called later too if needed.
"""
# Find records with empty firstname and lastname
records = self.search([("firstname", "=", False), ("lastname", "=", False)])
# Force calculations there
records._inverse_name()
_logger.info("%d employees updated installing module.", len(records))
def _update_partner_firstname(self):
for employee in self:
partners = employee.mapped("user_id.partner_id")
partners |= employee.mapped("address_home_id")
partners.write(
{"firstname": employee.firstname, "lastname": employee.lastname}
)
@api.constrains("firstname", "lastname")
def _check_name(self):
"""Ensure at least one name is set."""
for record in self:
if not (record.firstname or record.lastname):
raise ValidationError(_("No name set."))
| 36.759777 | 6,580 |
932 | py | PYTHON | 15.0 | # Copyright 2015 Antiun Ingenieria S.L. - Antonio Espinosa
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from odoo import fields, models
_logger = logging.getLogger(__name__)
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
employee_names_order = fields.Selection(
selection="_employee_names_order_selection",
help="Order to compose employee fullname",
config_parameter="employee_names_order",
default=lambda a: a._employee_names_order_default(),
required=True,
)
def _employee_names_order_selection(self):
return [
("last_first", "Lastname Firstname"),
("last_first_comma", "Lastname, Firstname"),
("first_last", "Firstname Lastname"),
]
def _employee_names_order_default(self):
return self.env["hr.employee"]._names_order_default()
| 31.066667 | 932 |
172 | py | PYTHON | 15.0 | from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_inherit = "hr.employee.base"
firstname = fields.Char()
lastname = fields.Char()
| 21.5 | 172 |
518 | py | PYTHON | 15.0 | # Copyright (C) 2015 Salton Massally (<smassally@idtlabs.sl>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Employee Age",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Salton Massally <smassally@idtlabs.sl>, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"category": "Human Resources",
"summary": "Age field for employee",
"depends": ["hr"],
"data": ["views/hr_employee.xml"],
"installable": True,
}
| 32.375 | 518 |
604 | py | PYTHON | 15.0 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import common
class TestHrEmployee(common.TransactionCase):
def setUp(self):
super().setUp()
self.employee_admin = self.env.ref("hr.employee_admin")
self.employee_admin.write({"birthday": "1990-05-15"})
def test_compute_age(self):
self.employee_admin._compute_age()
age = relativedelta(fields.Date.today(), self.employee_admin.birthday).years
self.assertEqual(self.employee_admin.age, age)
| 33.555556 | 604 |
574 | py | PYTHON | 15.0 | # Copyright (C) 2015 Salton Massally (<smassally@idtlabs.sl>).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
age = fields.Integer(compute="_compute_age")
@api.depends("birthday")
def _compute_age(self):
for record in self:
age = 0
if record.birthday:
age = relativedelta(fields.Date.today(), record.birthday).years
record.age = age
| 30.210526 | 574 |
1,224 | py | PYTHON | 15.0 | # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "HR Org Chart Overview",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "ForgeFlow S.L., Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "Organizational Chart Overview",
"depends": ["hr"],
"data": ["views/hr_views.xml"],
"qweb": ["static/src/xml/hr_org_chart_overview.xml"],
"assets": {
"web.assets_backend": [
"/hr_org_chart_overview/static/src/js/hr_org_chart_overview.js",
"/hr_org_chart_overview/static/src/lib/orgchart/html2canvas.min.js",
"/hr_org_chart_overview/static/src/lib/orgchart/jspdf.min.js",
"/hr_org_chart_overview/static/src/lib/orgchart/jquery.orgchart.js",
"/hr_org_chart_overview/static/src/lib/orgchart/jquery.orgchart.css",
"/hr_org_chart_overview/static/src/scss/hr_org_chart_style.scss",
],
"web.assets_qweb": [
"hr_org_chart_overview/static/src/xml/**/*",
],
},
}
| 40.8 | 1,224 |
2,909 | py | PYTHON | 15.0 | # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, models
from odoo.exceptions import ValidationError
org_chart_classes = {
0: "level-0",
1: "level-1",
2: "level-2",
3: "level-3",
4: "level-4",
}
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.constrains("parent_id")
def _check_parent_id(self):
if not self._check_recursion():
raise ValidationError(_("You cannot assign manager recursively."))
def _get_employee_domain(self, parent_id):
company = self.env.company
domain = ["|", ("company_id", "=", False), ("company_id", "=", company.id)]
if not parent_id:
domain.extend([("parent_id", "=", False), ("child_ids", "!=", False)])
else:
domain.append(("parent_id", "=", parent_id))
return domain
def _get_employee_data(self, level=0):
return {
"id": self.id,
"name": self.name,
"title": self.job_id.name,
"className": org_chart_classes[level],
"image": self.env["ir.attachment"]
.sudo()
.search(
[
("res_model", "=", "hr.employee"),
("res_id", "=", self.id),
("res_field", "=", "image_512"),
],
limit=1,
)
.datas,
}
@api.model
def _get_children_data(self, child_ids, level):
children = []
for employee in child_ids:
data = employee._get_employee_data(level)
employee_child_ids = self.search(self._get_employee_domain(employee.id))
if employee_child_ids:
data.update(
{
"children": self._get_children_data(
employee_child_ids, (level + 1) % 5
)
}
)
children.append(data)
return children
@api.model
def get_organization_data(self):
# First get employee with no manager
domain = self._get_employee_domain(False)
data = {"id": None, "name": "", "title": "", "children": []}
top_employees = self.search(domain)
for top_employee in top_employees:
child_data = top_employee._get_employee_data()
# If any child we fetch data recursively for childs of top employee
top_employee_child_ids = self.search(
self._get_employee_domain(top_employee.id)
)
if top_employee_child_ids:
child_data.update(
{"children": self._get_children_data(top_employee_child_ids, 1)}
)
data.get("children").append(child_data)
return data
| 34.223529 | 2,909 |
560 | py | PYTHON | 15.0 | # Copyright 2020 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Employee external Partner",
"summary": "Associate an external Partner to Employee",
"version": "15.0.1.0.0",
"category": "Human Resources",
"author": "Stefano Consolaro Associazione PNLUG - Gruppo Odoo, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"license": "AGPL-3",
"depends": ["hr"],
"data": ["views/hr_employee.xml"],
}
| 37.333333 | 560 |
725 | py | PYTHON | 15.0 | # Copyright 2020 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class EmployeePartner(models.Model):
"""
Add administrative Partner reference to Employee
"""
_inherit = "hr.employee"
# set employee as external
is_external = fields.Boolean(
"Is an external Employee",
default=False,
groups="hr.group_hr_user",
)
# Partner reference
hr_external_partner_id = fields.Many2one(
"res.partner",
"External Partner",
groups="hr.group_hr_user",
help="Partner that administrate Employee that works in the Company",
)
| 27.884615 | 725 |
604 | py | PYTHON | 15.0 | # Copyright (C) 2018 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": "HR Employee SSN & SIN",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "View/edit employee's SSN & SIN fields",
"depends": ["hr"],
"data": ["views/hr_employee_views.xml"],
}
| 35.529412 | 604 |
100 | py | PYTHON | 15.0 | import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
2,123 | py | PYTHON | 15.0 | import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-hr",
description="Meta package for oca-hr Odoo addons",
version=version,
install_requires=[
'odoo-addon-hr_branch>=15.0dev,<15.1dev',
'odoo-addon-hr_contract_employee_calendar_planning>=15.0dev,<15.1dev',
'odoo-addon-hr_contract_multi_job>=15.0dev,<15.1dev',
'odoo-addon-hr_contract_reference>=15.0dev,<15.1dev',
'odoo-addon-hr_course>=15.0dev,<15.1dev',
'odoo-addon-hr_department_code>=15.0dev,<15.1dev',
'odoo-addon-hr_emergency_contact>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_age>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_birth_name>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_calendar_planning>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_digitized_signature>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_document>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_firstname>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_id>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_lastnames>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_medical_examination>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_partner_external>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_phone_extension>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_relative>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_service>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_service_contract>=15.0dev,<15.1dev',
'odoo-addon-hr_employee_ssn>=15.0dev,<15.1dev',
'odoo-addon-hr_holidays_settings>=15.0dev,<15.1dev',
'odoo-addon-hr_job_category>=15.0dev,<15.1dev',
'odoo-addon-hr_org_chart_overview>=15.0dev,<15.1dev',
'odoo-addon-hr_personal_equipment_request>=15.0dev,<15.1dev',
'odoo-addon-hr_study>=15.0dev,<15.1dev',
'odoo-addon-hr_worked_days_from_timesheet>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 47.177778 | 2,123 |
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 |
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 |
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 |
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 |
721 | py | PYTHON | 15.0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Hr Personal Equipment Request",
"summary": """
This addon allows to manage employee personal equipment""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Creu Blanca,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": ["product", "hr", "mail"],
"data": [
"security/hr_personal_equipment_request_security.xml",
"security/ir.model.access.csv",
"views/product_template.xml",
"views/hr_personal_equipment.xml",
"views/hr_personal_equipment_request.xml",
"views/hr_employee.xml",
],
}
| 34.333333 | 721 |
5,370 | py | PYTHON | 15.0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import TransactionCase
class TestHRPersonalEquipmentRequest(TransactionCase):
def setUp(self):
super().setUp()
self.product_personal_equipment_1 = self.env["product.template"].create(
{
"name": "Product Test Personal Equipment 1",
"is_personal_equipment": True,
"uom_id": self.env.ref("uom.product_uom_unit").id,
}
)
self.product_personal_equipment_2 = self.env["product.template"].create(
{
"name": "Product Test Personal Equipment 2",
"is_personal_equipment": True,
"uom_id": self.env.ref("uom.product_uom_unit").id,
}
)
self.user = (
self.env["res.users"]
.sudo()
.create(
{
"name": "Test User",
"login": "user@test.com",
"email": "user@test.com",
"groups_id": [
(4, self.env.ref("base.group_user").id),
(4, self.env.ref("hr.group_hr_user").id),
],
}
)
)
self.employee = self.env["hr.employee"].create(
{"name": "Employee Test", "user_id": self.user.id}
)
lines = [
{
"name": "Personal Equipment 1",
"product_id": self.product_personal_equipment_1.product_variant_id.id,
"quantity": 3,
},
{
"name": "Personal Equipment 2",
"product_id": self.product_personal_equipment_2.product_variant_id.id,
"quantity": 2,
},
]
self.personal_equipment_request = (
self.env["hr.personal.equipment.request"]
.with_user(self.user.id)
.create(
{
"name": "Personal Equipment Request Test",
"line_ids": [(0, 0, line) for line in lines],
}
)
)
def test_request_compute_name(self):
self.assertTrue(self.personal_equipment_request.name)
self.assertEqual(
self.personal_equipment_request.name,
"Personal Equipment Request by Employee Test",
)
def test_accept_request(self):
self.assertEqual(self.personal_equipment_request.state, "draft")
self.assertEqual(self.personal_equipment_request.line_ids[0].state, "draft")
self.personal_equipment_request.accept_request()
self.assertEqual(self.personal_equipment_request.state, "accepted")
self.assertEqual(self.personal_equipment_request.line_ids[0].state, "accepted")
def test_cancel_request(self):
self.assertEqual(self.personal_equipment_request.state, "draft")
self.assertEqual(self.personal_equipment_request.line_ids[0].state, "draft")
self.personal_equipment_request.cancel_request()
self.assertEqual(self.personal_equipment_request.state, "cancelled")
self.assertEqual(self.personal_equipment_request.line_ids[0].state, "cancelled")
def test_allocation_compute_name(self):
self.assertEqual(
self.personal_equipment_request.line_ids[0].name,
"Product Test Personal Equipment 1 to Employee Test",
)
def test_onchange_uom_id(self):
self.assertFalse(self.personal_equipment_request.line_ids[0].product_uom_id)
self.personal_equipment_request.line_ids[0]._onchange_uom_id()
self.assertTrue(self.personal_equipment_request.line_ids[0].product_uom_id)
self.assertEqual(
self.personal_equipment_request.line_ids[0].product_uom_id,
self.product_personal_equipment_1.uom_id,
)
def test_validate_allocation(self):
self.personal_equipment_request.accept_request()
allocation = self.personal_equipment_request.line_ids[0]
self.assertEqual(allocation.state, "accepted")
allocation.validate_allocation()
self.assertEqual(allocation.state, "valid")
def test_expire_allocation(self):
self.personal_equipment_request.accept_request()
allocation = self.personal_equipment_request.line_ids[0]
allocation.validate_allocation()
self.assertEqual(allocation.state, "valid")
self.assertFalse(allocation.expiry_date)
allocation.expire_allocation()
self.assertEqual(allocation.state, "expired")
self.assertTrue(allocation.expiry_date)
def test_action_open_equipment_request(self):
action = self.employee.action_open_equipment_request()
self.assertEqual(action["res_model"], "hr.personal.equipment.request")
self.assertEqual(self.employee.equipment_request_count, 1)
def test_action_open_personal_equipment(self):
action = self.employee.action_open_personal_equipment()
self.assertEqual(action["res_model"], "hr.personal.equipment")
self.assertEqual(self.employee.personal_equipment_count, 0)
self.personal_equipment_request.accept_request()
self.personal_equipment_request.refresh()
self.assertEqual(self.employee.personal_equipment_count, 2)
| 40.992366 | 5,370 |
2,660 | py | PYTHON | 15.0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.fields import Date
class HrPersonalEquipment(models.Model):
_name = "hr.personal.equipment"
_description = "Adds personal equipment information and allocation"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char(compute="_compute_name")
product_id = fields.Many2one(
comodel_name="product.product",
required=True,
domain=[("is_personal_equipment", "=", True)],
)
employee_id = fields.Many2one(
comodel_name="hr.employee",
related="equipment_request_id.employee_id",
store=True,
)
state = fields.Selection(
[
("draft", "Draft"),
("accepted", "Accepted"),
("valid", "Valid"),
("expired", "Expired"),
("cancelled", "Cancelled"),
],
default="draft",
tracking=True,
)
start_date = fields.Date()
expiry_date = fields.Date()
equipment_request_id = fields.Many2one(
comodel_name="hr.personal.equipment.request", required=True, ondelete="cascade"
)
quantity = fields.Integer(default=1)
product_uom_id = fields.Many2one("uom.uom", "Unit of Measure")
@api.onchange("product_id")
def _onchange_uom_id(self):
if self.product_id:
self.product_uom_id = self.product_id.uom_id
return {
"domain": {
"product_uom_id": [
("category_id", "=", self.product_uom_id.category_id.id)
]
}
}
@api.depends("product_id", "employee_id")
def _compute_name(self):
for rec in self:
if rec.product_id.name and rec.employee_id.name:
rec.name = "{} to {}".format(rec.product_id.name, rec.employee_id.name)
else:
rec.name = False
def _validate_allocation_vals(self):
return {
"state": "valid",
"start_date": fields.Date.context_today(self)
if not self.start_date
else self.start_date,
}
def validate_allocation(self):
for rec in self:
rec.write(rec._validate_allocation_vals())
def expire_allocation(self):
for rec in self:
rec.state = "expired"
if not rec.expiry_date:
rec.expiry_date = Date.today()
def _accept_request_vals(self):
return {"state": "accepted"}
def _accept_request(self):
for rec in self:
rec.write(rec._accept_request_vals())
| 30.574713 | 2,660 |
314 | py | PYTHON | 15.0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
is_personal_equipment = fields.Boolean(
default=False, string="Is Employee Personal Equipment"
)
| 24.153846 | 314 |
2,226 | py | PYTHON | 15.0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class HrPersonalEquipmentRequest(models.Model):
_name = "hr.personal.equipment.request"
_description = "This model allows to create a personal equipment request"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char(compute="_compute_name")
employee_id = fields.Many2one(
comodel_name="hr.employee",
string="Employee",
required=True,
default=lambda self: self._default_employee_id(),
)
line_ids = fields.One2many(
string="Personal Equipment",
comodel_name="hr.personal.equipment",
inverse_name="equipment_request_id",
copy=True,
)
allocations_count = fields.Integer(compute="_compute_allocation_count")
state = fields.Selection(
[("draft", "Draft"), ("accepted", "Accepted"), ("cancelled", "Cancelled")],
default="draft",
tracking=True,
)
observations = fields.Text()
def _default_employee_id(self):
return self.env.user.employee_ids[:1]
@api.depends("employee_id")
def _compute_name(self):
for rec in self:
rec.name = _("Personal Equipment Request by %s") % rec.employee_id.name
def accept_request(self):
for rec in self:
rec.write(rec._accept_request_vals())
rec.line_ids._accept_request()
def _accept_request_vals(self):
return {"state": "accepted"}
def cancel_request(self):
for rec in self:
rec.state = "cancelled"
rec.line_ids.update({"state": "cancelled"})
def _compute_equipment_request_count(self):
self.equipment_request_count = len(self.equipment_request_ids)
def _compute_allocation_count(self):
self.allocations_count = len(self.line_ids)
def action_open_personal_equipment(self):
self.ensure_one()
return {
"name": _("Allocations"),
"type": "ir.actions.act_window",
"res_model": "hr.personal.equipment",
"view_mode": "tree,form",
"domain": [("id", "in", self.line_ids.ids)],
}
| 31.352113 | 2,226 |
1,781 | py | PYTHON | 15.0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
equipment_request_ids = fields.One2many(
comodel_name="hr.personal.equipment.request",
inverse_name="employee_id",
)
personal_equipment_ids = fields.One2many(
comodel_name="hr.personal.equipment",
inverse_name="employee_id",
domain=[("state", "not in", ["draft", "cancelled"])],
)
equipment_request_count = fields.Integer(
compute="_compute_equipment_request_count",
)
personal_equipment_count = fields.Integer(
compute="_compute_personal_equipment_count"
)
def _compute_equipment_request_count(self):
self.equipment_request_count = len(self.equipment_request_ids)
def _compute_personal_equipment_count(self):
self.personal_equipment_count = len(self.personal_equipment_ids)
def action_open_equipment_request(self):
self.ensure_one()
return {
"name": _("Equipment Request"),
"type": "ir.actions.act_window",
"res_model": "hr.personal.equipment.request",
"view_mode": "tree,form",
"context": {"group_by": "state"},
"domain": [("id", "in", self.equipment_request_ids.ids)],
}
def action_open_personal_equipment(self):
self.ensure_one()
return {
"name": _("Personal Equipment"),
"type": "ir.actions.act_window",
"res_model": "hr.personal.equipment",
"context": {"group_by": "state"},
"view_mode": "tree,form",
"domain": [("id", "in", self.personal_equipment_ids.ids)],
}
| 31.803571 | 1,781 |
697 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Hr Employee Medical Examination",
"summary": """
Adds information about employee's medical examinations""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Creu Blanca,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/hr",
"depends": ["hr"],
"data": [
"views/hr_employee_medical_examination_views.xml",
"wizards/wizard_generate_medical_examination.xml",
"views/hr_employee_views.xml",
"security/ir.model.access.csv",
"security/hr_employee_medical_examination_security.xml",
],
}
| 34.85 | 697 |
2,207 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestHrEmployeeMedicalExamination(TransactionCase):
def setUp(self):
super(TestHrEmployeeMedicalExamination, self).setUp()
self.department = self.env["hr.department"].create({"name": "Department"})
self.job = self.env["hr.job"].create({"name": "Job"})
self.employee1 = self.env["hr.employee"].create(
{
"name": "Employee 1",
"job_id": self.job.id,
"department_id": self.department.id,
}
)
self.examination = self.env["hr.employee.medical.examination"].create(
{"name": "Dummy Exam to test domain", "employee_id": self.employee1.id}
)
self.wizard = self.env["wizard.generate.medical.examination"].create(
{"name": "Examination 2019"}
)
def test_hr_employee_medical_examination(self):
self.assertFalse(self.wizard.employee_ids)
self.wizard.write({"job_id": self.job.id, "department_id": self.department.id})
self.wizard.populate()
self.assertEqual(len(self.wizard.employee_ids), 1)
result = self.wizard.create_medical_examinations()
examination = self.env["hr.employee.medical.examination"].search(
result["domain"]
)
self.assertTrue(examination)
self.assertEqual(1, len(examination))
self.assertEqual(examination.name, "Examination 2019 on Employee 1")
self.assertEqual(self.employee1.medical_examination_count, 2)
self.assertTrue(self.employee1.can_see_examinations_button)
examination.write({"date": "2018-05-05"})
examination._onchange_date()
self.assertEqual(examination.year, "2018")
examination.to_done()
self.assertEqual(examination.state, "done")
examination.to_cancelled()
self.assertEqual(examination.state, "cancelled")
examination.to_rejected()
self.assertEqual(examination.state, "rejected")
examination.back_to_pending()
self.assertEqual(examination.state, "pending")
| 39.410714 | 2,207 |
1,623 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import datetime
from odoo import api, fields, models
class HrEmployeeMedicalExamination(models.Model):
_name = "hr.employee.medical.examination"
_description = "Hr Employee Medical Examination"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char(
required=True,
tracking=True,
)
state = fields.Selection(
selection=[
("pending", "Pending"),
("done", "Done"),
("cancelled", "Cancelled"),
("rejected", "Rejected"),
],
default="pending",
readonly=True,
tracking=True,
)
date = fields.Date(
string="Examination Date",
tracking=True,
)
result = fields.Selection(
selection=[("failed", "Failed"), ("passed", "Passed")],
tracking=True,
)
employee_id = fields.Many2one(
"hr.employee",
string="Employee",
required=True,
tracking=True,
)
year = fields.Char(default=lambda r: str(datetime.date.today().year))
note = fields.Text(tracking=True)
@api.onchange("date")
def _onchange_date(self):
for record in self:
if record.date:
record.year = str(record.date.year)
def back_to_pending(self):
self.write({"state": "pending"})
def to_done(self):
self.write({"state": "done"})
def to_cancelled(self):
self.write({"state": "cancelled"})
def to_rejected(self):
self.write({"state": "rejected"})
| 23.867647 | 1,623 |
1,031 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
medical_examination_ids = fields.One2many(
comodel_name="hr.employee.medical.examination",
inverse_name="employee_id",
)
medical_examination_count = fields.Integer(
compute="_compute_medical_examination_count",
)
can_see_examinations_button = fields.Boolean(
compute="_compute_can_see_examinations_button",
)
@api.depends("medical_examination_ids")
def _compute_medical_examination_count(self):
for record in self:
record.medical_examination_count = len(record.medical_examination_ids)
def _compute_can_see_examinations_button(self):
for record in self:
record.can_see_examinations_button = (
self.env.uid == record.user_id.id
or self.env.user.has_group("hr.group_hr_manager")
)
| 30.323529 | 1,031 |
2,463 | py | PYTHON | 15.0 | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import date
from odoo import _, fields, models
class WizardGenerateMedicalExamination(models.TransientModel):
_name = "wizard.generate.medical.examination"
_description = "Generation wizard for medical examinations"
name = fields.Char(required=True, string="Examination Name")
year = fields.Char(
default=lambda r: str(date.today().year),
)
employee_ids = fields.Many2many(comodel_name="hr.employee", string="Employees")
department_id = fields.Many2one(
comodel_name="hr.department",
string="Department",
)
job_id = fields.Many2one(
comodel_name="hr.job",
string="Job",
)
def _prepare_employee_domain(self):
res = []
if self.job_id:
res.append(("job_id", "=", self.job_id.id))
if self.department_id:
res.append(("department_id", "child_of", self.department_id.id))
return res
def populate(self):
domain = self._prepare_employee_domain()
employees = self.env["hr.employee"].search(domain)
self.employee_ids = employees
action = {
"name": _("Generate Medical Examinations"),
"type": "ir.actions.act_window",
"res_model": "wizard.generate.medical.examination",
"view_mode": "form",
"target": "new",
"res_id": self.id,
"context": self._context,
}
return action
def _create_examination_vals(self, employee):
return {
"name": _("%(name)s on %(employee)s")
% {
"name": self.name,
"employee": employee.name,
},
"employee_id": employee.id,
"year": self.year,
}
def create_medical_examinations(self):
exams = self.env["hr.employee.medical.examination"]
for form in self:
for employee in form.employee_ids:
exams |= self.env["hr.employee.medical.examination"].create(
form._create_examination_vals(employee)
)
action = self.env.ref(
"hr_employee_medical_examination.hr_employee"
"_medical_examination_act_window",
False,
)
result = action.read()[0]
result["domain"] = [("id", "in", exams.ids)]
return result
| 31.987013 | 2,463 |
806 | py | PYTHON | 15.0 | # Copyright (C) 2018 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": "HR Employee Relatives",
"version": "15.0.1.0.0",
"category": "Human Resources",
"website": "https://github.com/OCA/hr",
"author": "CorporateHub, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"application": False,
"summary": "Allows storing information about employee's family",
"depends": ["hr"],
"external_dependencies": {"python": ["dateutil"]},
"data": [
"data/data_relative_relation.xml",
"security/ir.model.access.csv",
"views/hr_employee.xml",
"views/hr_employee_relative.xml",
],
}
| 35.043478 | 806 |
1,817 | py | PYTHON | 15.0 | # Copyright (C) 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo.tests import Form, common
_ns = "hr_employee_relative"
class TestHrEmployeeRelatives(common.TransactionCase):
def setUp(self):
super().setUp()
self.Employee = self.env["hr.employee"]
self.EmployeeRelative = self.env["hr.employee.relative"]
def test_age_calculation(self):
employee = self.Employee.create(
{
"name": "Employee",
"relative_ids": [
(
0,
0,
{
"relation_id": self.env.ref(_ns + ".relation_sibling").id,
"partner_id": self.env.ref("base.res_partner_1").id,
"name": "Relative",
"date_of_birth": datetime.now() + relativedelta(years=-42),
},
)
],
}
)
relative = self.EmployeeRelative.browse(employee.relative_ids[0].id)
self.assertEqual(int(relative.age), 42)
# onchange partner
ctx = {
"active_ids": [relative.id],
"active_id": relative.id,
"active_model": "hr.employee.relative",
}
self.assertEqual(relative.name, "Relative")
with Form(self.EmployeeRelative.with_context(**ctx)) as f:
f.partner_id = self.env.ref("base.res_partner_2")
f.relation_id = self.env.ref(_ns + ".relation_sibling")
relative = f.save()
self.assertEqual(relative.name, relative.partner_id.display_name)
| 36.34 | 1,817 |
1,437 | py | PYTHON | 15.0 | # Copyright (C) 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class HrEmployeeRelative(models.Model):
_name = "hr.employee.relative"
_description = "HR Employee Relative"
employee_id = fields.Many2one(string="Employee", comodel_name="hr.employee")
relation_id = fields.Many2one(
"hr.employee.relative.relation", string="Relation", required=True
)
name = fields.Char(required=True)
partner_id = fields.Many2one(
"res.partner",
string="Partner",
domain=["&", ("is_company", "=", False), ("type", "=", "contact")],
)
gender = fields.Selection(
selection=[("male", "Male"), ("female", "Female"), ("other", "Other")],
)
date_of_birth = fields.Date(string="Date of Birth")
age = fields.Float(compute="_compute_age")
job = fields.Char()
phone_number = fields.Char()
notes = fields.Text()
@api.depends("date_of_birth")
def _compute_age(self):
for record in self:
age = relativedelta(datetime.now(), record.date_of_birth)
record.age = age.years + (age.months / 12)
@api.onchange("partner_id")
def _onchange_partner_id(self):
if self.partner_id:
self.name = self.partner_id.display_name
| 31.933333 | 1,437 |
380 | py | PYTHON | 15.0 | # Copyright (C) 2018 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrEmployeeRelativeRelation(models.Model):
_name = "hr.employee.relative.relation"
_description = "HR Employee Relative Relation"
name = fields.Char(string="Relation", required=True, translate=True)
| 34.545455 | 380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.