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
|
---|---|---|---|---|---|---|
2,651 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Carlos Dauden <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from ast import literal_eval
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
sale_contract_count = fields.Integer(
string="Sale Contracts",
compute="_compute_contract_count",
)
purchase_contract_count = fields.Integer(
string="Purchase Contracts",
compute="_compute_contract_count",
)
contract_ids = fields.One2many(
comodel_name="contract.contract",
inverse_name="partner_id",
string="Contracts",
)
def _get_partner_contract_domain(self):
return [("partner_id", "child_of", self.ids)]
def _compute_contract_count(self):
contract_model = self.env["contract.contract"]
fetch_data = contract_model.read_group(
self._get_partner_contract_domain(),
["partner_id", "contract_type"],
["partner_id", "contract_type"],
lazy=False,
)
result = [
[data["partner_id"][0], data["contract_type"], data["__count"]]
for data in fetch_data
]
for partner in self:
partner_child_ids = partner.child_ids.ids + partner.ids
partner.sale_contract_count = sum(
r[2] for r in result if r[0] in partner_child_ids and r[1] == "sale"
)
partner.purchase_contract_count = sum(
r[2] for r in result if r[0] in partner_child_ids and r[1] == "purchase"
)
def act_show_contract(self):
"""This opens contract view
@return: the contract view
"""
self.ensure_one()
contract_type = self._context.get("contract_type")
res = self._get_act_window_contract_xml(contract_type)
action_context = {k: v for k, v in self.env.context.items() if k != "group_by"}
action_context["default_partner_id"] = self.id
action_context["default_pricelist_id"] = self.property_product_pricelist.id
res["context"] = action_context
res["domain"] = (
literal_eval(res["domain"]) + self._get_partner_contract_domain()
)
return res
def _get_act_window_contract_xml(self, contract_type):
if contract_type == "purchase":
return self.env["ir.actions.act_window"]._for_xml_id(
"contract.action_supplier_contract"
)
else:
return self.env["ir.actions.act_window"]._for_xml_id(
"contract.action_customer_contract"
)
| 35.346667 | 2,651 |
11,126 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import itertools
from collections import namedtuple
from odoo.fields import Date
Criteria = namedtuple(
"Criteria",
[
"when", # Contract line relatively to today (BEFORE, IN, AFTER)
"has_date_end", # Is date_end set on contract line (bool)
"has_last_date_invoiced", # Is last_date_invoiced set on contract line
"is_auto_renew", # Is is_auto_renew set on contract line (bool)
"has_successor", # Is contract line has_successor (bool)
"predecessor_has_successor",
# Is contract line predecessor has successor (bool)
# In almost of the cases
# contract_line.predecessor.successor == contract_line
# But at cancel action,
# contract_line.predecessor.successor == False
# This is to permit plan_successor on predecessor
# If contract_line.predecessor.successor != False
# and contract_line is canceled, we don't allow uncancel
# else we re-link contract_line and its predecessor
"canceled", # Is contract line canceled (bool)
],
)
Allowed = namedtuple(
"Allowed",
["plan_successor", "stop_plan_successor", "stop", "cancel", "uncancel"],
)
def _expand_none(criteria):
variations = []
for attribute, value in criteria._asdict().items():
if value is None:
if attribute == "when":
variations.append(["BEFORE", "IN", "AFTER"])
else:
variations.append([True, False])
else:
variations.append([value])
return itertools.product(*variations)
def _add(matrix, criteria, allowed):
"""Expand None values to True/False combination"""
for c in _expand_none(criteria):
matrix[c] = allowed
CRITERIA_ALLOWED_DICT = {
Criteria(
when="BEFORE",
has_date_end=True,
has_last_date_invoiced=False,
is_auto_renew=True,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=True,
has_last_date_invoiced=False,
is_auto_renew=False,
has_successor=True,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=True,
has_last_date_invoiced=False,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=True,
stop_plan_successor=True,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=False,
has_last_date_invoiced=False,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=True,
has_last_date_invoiced=False,
is_auto_renew=True,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=True,
has_last_date_invoiced=False,
is_auto_renew=False,
has_successor=True,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=True,
has_last_date_invoiced=False,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=True,
stop_plan_successor=True,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=False,
has_last_date_invoiced=False,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=True,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=True,
has_last_date_invoiced=True,
is_auto_renew=True,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=True,
has_last_date_invoiced=True,
is_auto_renew=False,
has_successor=True,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=True,
has_last_date_invoiced=True,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=True,
stop_plan_successor=True,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="BEFORE",
has_date_end=False,
has_last_date_invoiced=True,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=True,
has_last_date_invoiced=True,
is_auto_renew=True,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=True,
has_last_date_invoiced=True,
is_auto_renew=False,
has_successor=True,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=True,
has_last_date_invoiced=True,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=True,
stop_plan_successor=True,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="IN",
has_date_end=False,
has_last_date_invoiced=True,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=True,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="AFTER",
has_date_end=True,
has_last_date_invoiced=None,
is_auto_renew=True,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when="AFTER",
has_date_end=True,
has_last_date_invoiced=None,
is_auto_renew=False,
has_successor=True,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=False,
cancel=False,
uncancel=False,
),
Criteria(
when="AFTER",
has_date_end=True,
has_last_date_invoiced=None,
is_auto_renew=False,
has_successor=False,
predecessor_has_successor=None,
canceled=False,
): Allowed(
plan_successor=True,
stop_plan_successor=False,
stop=True,
cancel=False,
uncancel=False,
),
Criteria(
when=None,
has_date_end=None,
has_last_date_invoiced=None,
is_auto_renew=None,
has_successor=None,
predecessor_has_successor=False,
canceled=True,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=False,
cancel=False,
uncancel=True,
),
Criteria(
when=None,
has_date_end=None,
has_last_date_invoiced=None,
is_auto_renew=None,
has_successor=None,
predecessor_has_successor=True,
canceled=True,
): Allowed(
plan_successor=False,
stop_plan_successor=False,
stop=False,
cancel=False,
uncancel=False,
),
}
criteria_allowed_dict = {}
for c in CRITERIA_ALLOWED_DICT:
_add(criteria_allowed_dict, c, CRITERIA_ALLOWED_DICT[c])
def compute_when(date_start, date_end):
today = Date.today()
if today < date_start:
return "BEFORE"
if date_end and today > date_end:
return "AFTER"
return "IN"
def compute_criteria(
date_start,
date_end,
has_last_date_invoiced,
is_auto_renew,
successor_contract_line_id,
predecessor_contract_line_id,
is_canceled,
):
return Criteria(
when=compute_when(date_start, date_end),
has_date_end=bool(date_end),
has_last_date_invoiced=bool(has_last_date_invoiced),
is_auto_renew=is_auto_renew,
has_successor=bool(successor_contract_line_id),
predecessor_has_successor=bool(
predecessor_contract_line_id.successor_contract_line_id
),
canceled=is_canceled,
)
def get_allowed(
date_start,
date_end,
has_last_date_invoiced,
is_auto_renew,
successor_contract_line_id,
predecessor_contract_line_id,
is_canceled,
):
criteria = compute_criteria(
date_start,
date_end,
has_last_date_invoiced,
is_auto_renew,
successor_contract_line_id,
predecessor_contract_line_id,
is_canceled,
)
if criteria in criteria_allowed_dict:
return criteria_allowed_dict[criteria]
return False
| 25.934732 | 11,126 |
455 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractTag(models.Model):
_name = "contract.tag"
_description = "Contract Tag"
name = fields.Char(required=True)
company_id = fields.Many2one(
"res.company",
string="Company",
default=lambda self: self.env.company.id,
)
color = fields.Integer("Color Index", default=0)
| 25.277778 | 455 |
1,667 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractLineWizard(models.TransientModel):
_name = "contract.line.wizard"
_description = "Contract Line Wizard"
date_start = fields.Date()
date_end = fields.Date()
recurring_next_date = fields.Date(string="Next Invoice Date")
is_auto_renew = fields.Boolean(default=False)
manual_renew_needed = fields.Boolean(
default=False,
help="This flag is used to make a difference between a definitive stop"
"and temporary one for which a user is not able to plan a"
"successor in advance",
)
contract_line_id = fields.Many2one(
comodel_name="contract.line",
string="Contract Line",
required=True,
index=True,
ondelete="cascade",
)
def stop(self):
for wizard in self:
wizard.contract_line_id.stop(
wizard.date_end, manual_renew_needed=wizard.manual_renew_needed
)
return True
def plan_successor(self):
for wizard in self:
wizard.contract_line_id.plan_successor(
wizard.date_start, wizard.date_end, wizard.is_auto_renew
)
return True
def stop_plan_successor(self):
for wizard in self:
wizard.contract_line_id.stop_plan_successor(
wizard.date_start, wizard.date_end, wizard.is_auto_renew
)
return True
def uncancel(self):
for wizard in self:
wizard.contract_line_id.uncancel(wizard.recurring_next_date)
return True
| 30.87037 | 1,667 |
2,963 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import (
AccessDenied,
AccessError,
MissingError,
UserError,
ValidationError,
)
class ContractManuallyCreateInvoice(models.TransientModel):
_name = "contract.manually.create.invoice"
_description = "Contract Manually Create Invoice Wizard"
invoice_date = fields.Date(required=True)
contract_to_invoice_count = fields.Integer(
compute="_compute_contract_to_invoice_ids"
)
contract_to_invoice_ids = fields.Many2many(
comodel_name="contract.contract",
compute="_compute_contract_to_invoice_ids",
)
contract_type = fields.Selection(
selection=[("sale", "Customer"), ("purchase", "Supplier")],
default="sale",
required=True,
)
@api.depends("invoice_date")
def _compute_contract_to_invoice_ids(self):
if not self.invoice_date:
# trick to show no invoice when no date has been entered yet
contract_to_invoice_domain = [("id", "=", False)]
else:
contract_to_invoice_domain = self.env[
"contract.contract"
]._get_contracts_to_invoice_domain(self.invoice_date)
self.contract_to_invoice_ids = self.env["contract.contract"].search(
contract_to_invoice_domain + [("contract_type", "=", self.contract_type)]
)
self.contract_to_invoice_count = len(self.contract_to_invoice_ids)
def action_show_contract_to_invoice(self):
self.ensure_one()
return {
"type": "ir.actions.act_window",
"name": _("Contracts to invoice"),
"res_model": "contract.contract",
"domain": [("id", "in", self.contract_to_invoice_ids.ids)],
"view_mode": "tree,form",
"context": self.env.context,
}
def create_invoice(self):
self.ensure_one()
invoices = self.env["account.move"]
for contract in self.contract_to_invoice_ids:
try:
invoices |= contract.recurring_create_invoice()
except (
AccessDenied,
AccessError,
MissingError,
UserError,
ValidationError,
) as oe:
raise UserError(
_(
"Failed to process the contract %(name)s [id: %(id)s]:\n%(ue)s",
name=contract.name,
id=contract.id,
ue=repr(oe),
)
) from oe
return {
"type": "ir.actions.act_window",
"name": _("Invoices"),
"res_model": "account.move",
"domain": [("id", "in", invoices.ids)],
"view_mode": "tree,form",
"context": self.env.context,
}
| 34.057471 | 2,963 |
1,159 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractContractTerminate(models.TransientModel):
_name = "contract.contract.terminate"
_description = "Terminate Contract Wizard"
contract_id = fields.Many2one(
comodel_name="contract.contract",
string="Contract",
required=True,
ondelete="cascade",
)
terminate_reason_id = fields.Many2one(
comodel_name="contract.terminate.reason",
string="Termination Reason",
required=True,
ondelete="cascade",
)
terminate_comment = fields.Text(string="Termination Comment")
terminate_date = fields.Date(string="Termination Date", required=True)
terminate_comment_required = fields.Boolean(
related="terminate_reason_id.terminate_comment_required"
)
def terminate_contract(self):
for wizard in self:
wizard.contract_id._terminate_contract(
wizard.terminate_reason_id,
wizard.terminate_comment,
wizard.terminate_date,
)
return True
| 31.324324 | 1,159 |
3,946 |
py
|
PYTHON
|
15.0
|
# Copyright 2020-2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, http
from odoo.exceptions import AccessError, MissingError
from odoo.http import request
from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager
class PortalContract(CustomerPortal):
def _prepare_home_portal_values(self, counters):
values = super()._prepare_home_portal_values(counters)
if "contract_count" in counters:
contract_model = request.env["contract.contract"]
contract_count = (
contract_model.search_count([])
if contract_model.check_access_rights("read", raise_exception=False)
else 0
)
values["contract_count"] = contract_count
return values
def _contract_get_page_view_values(self, contract, access_token, **kwargs):
values = {
"page_name": "Contracts",
"contract": contract,
}
return self._get_page_view_values(
contract, access_token, values, "my_contracts_history", False, **kwargs
)
def _get_filter_domain(self, kw):
return []
@http.route(
["/my/contracts", "/my/contracts/page/<int:page>"],
type="http",
auth="user",
website=True,
)
def portal_my_contracts(
self, page=1, date_begin=None, date_end=None, sortby=None, **kw
):
values = self._prepare_portal_layout_values()
contract_obj = request.env["contract.contract"]
# Avoid error if the user does not have access.
if not contract_obj.check_access_rights("read", raise_exception=False):
return request.redirect("/my")
domain = self._get_filter_domain(kw)
searchbar_sortings = {
"date": {"label": _("Date"), "order": "recurring_next_date desc"},
"name": {"label": _("Name"), "order": "name desc"},
"code": {"label": _("Reference"), "order": "code desc"},
}
# default sort by order
if not sortby:
sortby = "date"
order = searchbar_sortings[sortby]["order"]
# count for pager
contract_count = contract_obj.search_count(domain)
# pager
pager = portal_pager(
url="/my/contracts",
url_args={
"date_begin": date_begin,
"date_end": date_end,
"sortby": sortby,
},
total=contract_count,
page=page,
step=self._items_per_page,
)
# content according to pager and archive selected
contracts = contract_obj.search(
domain, order=order, limit=self._items_per_page, offset=pager["offset"]
)
request.session["my_contracts_history"] = contracts.ids[:100]
values.update(
{
"date": date_begin,
"contracts": contracts,
"page_name": "Contracts",
"pager": pager,
"default_url": "/my/contracts",
"searchbar_sortings": searchbar_sortings,
"sortby": sortby,
}
)
return request.render("contract.portal_my_contracts", values)
@http.route(
["/my/contracts/<int:contract_contract_id>"],
type="http",
auth="public",
website=True,
)
def portal_my_contract_detail(self, contract_contract_id, access_token=None, **kw):
try:
contract_sudo = self._document_check_access(
"contract.contract", contract_contract_id, access_token
)
except (AccessError, MissingError):
return request.redirect("/my")
values = self._contract_get_page_view_values(contract_sudo, access_token, **kw)
return request.render("contract.portal_contract_page", values)
| 37.207547 | 3,944 |
805 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antiun Ingenieria S.L. - Antonio Espinosa
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from odoo import SUPERUSER_ID, api
_logger = logging.getLogger(__name__)
def post_init_hook(cr, registry):
"""Copy payment mode from partner to the new field at contract."""
env = api.Environment(cr, SUPERUSER_ID, {})
m_contract = env["contract.contract"]
contracts = m_contract.search([("payment_mode_id", "=", False)])
if contracts:
_logger.info("Setting payment mode: %d contracts" % len(contracts))
for contract in contracts:
payment_mode = contract.partner_id.customer_payment_mode_id
if payment_mode:
contract.payment_mode_id = payment_mode.id
_logger.info("Setting payment mode: Done")
| 36.590909 | 805 |
921 |
py
|
PYTHON
|
15.0
|
# Copyright 2015 Domatix (<www.domatix.com>)
# Copyright 2016 Antiun Ingenieria S.L. - Antonio Espinosa
# Copyright 2017 Tecnativa - David Vidal
# Copyright 2017 Tecnativa - Carlos Dauden <[email protected]>
# Copyright 2017-2018 Tecnativa - Vicent Cubells <[email protected]>
# Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Contract Payment Mode",
"summary": "Payment mode in contracts and their invoices",
"version": "15.0.1.1.1",
"author": "Domatix, " "Tecnativa, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/contract",
"depends": ["contract", "account_payment_partner"],
"category": "Sales Management",
"license": "AGPL-3",
"data": ["views/contract_view.xml"],
"post_init_hook": "post_init_hook",
"installable": True,
"auto_install": True,
}
| 41.863636 | 921 |
4,735 |
py
|
PYTHON
|
15.0
|
# Copyright 2015 Antiun Ingenieria S.L. - Antonio Espinosa
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2017 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest.mock import patch
import odoo.tests
from odoo.tests import tagged
from odoo.addons.account.models.account_payment_method import AccountPaymentMethod
from ..hooks import post_init_hook
@tagged("post_install", "-at_install")
class TestContractPaymentInit(odoo.tests.HttpCase):
def setUp(self):
super().setUp()
Method_get_payment_method_information = (
AccountPaymentMethod._get_payment_method_information
)
def _get_payment_method_information(self):
res = Method_get_payment_method_information(self)
res["Test"] = {"mode": "multi", "domain": [("type", "=", "bank")]}
return res
with patch.object(
AccountPaymentMethod,
"_get_payment_method_information",
_get_payment_method_information,
):
self.payment_method = self.env["account.payment.method"].create(
{
"name": "Test Payment Method",
"code": "Test",
"payment_type": "inbound",
}
)
self.payment_mode = self.env["account.payment.mode"].create(
{
"name": "Test payment mode",
"active": True,
"payment_method_id": self.payment_method.id,
"bank_account_link": "variable",
}
)
self.partner = self.env["res.partner"].create(
{
"name": "Test contract partner",
"customer_payment_mode_id": self.payment_mode,
}
)
self.product = self.env["product.product"].create(
{
"name": "Custom Service",
"type": "service",
"uom_id": self.env.ref("uom.product_uom_hour").id,
"uom_po_id": self.env.ref("uom.product_uom_hour").id,
"sale_ok": True,
}
)
self.contract = self.env["contract.contract"].create(
{"name": "Maintenance of Servers", "partner_id": self.partner.id}
)
company = self.env.ref("base.main_company")
self.journal = self.env["account.journal"].create(
{
"name": "Sale Journal - Test",
"code": "HRTSJ",
"type": "sale",
"company_id": company.id,
}
)
def test_post_init_hook(self):
contract = self.env["contract.contract"].create(
{
"name": "Test contract",
"partner_id": self.partner.id,
"payment_mode_id": self.payment_mode.id,
}
)
self.assertEqual(contract.payment_mode_id, self.payment_mode)
contract.payment_mode_id = False
self.assertEqual(contract.payment_mode_id.id, False)
post_init_hook(self.cr, self.env)
self.assertEqual(contract.payment_mode_id, self.payment_mode)
def test_contract_and_invoices(self):
self.contract.write({"partner_id": self.partner.id})
self.contract.on_change_partner_id()
self.assertEqual(
self.contract.payment_mode_id,
self.contract.partner_id.customer_payment_mode_id,
)
self.contract.write(
{
"line_recurrence": True,
"contract_type": "sale",
"recurring_interval": 1,
"recurring_rule_type": "monthly",
"date_start": "2018-01-15",
"contract_line_ids": [
(
0,
0,
{
"product_id": self.product.id,
"name": "Database Administration 25",
"quantity": 2.0,
"uom_id": self.product.uom_id.id,
"price_unit": 200.0,
},
)
],
}
)
self.contract.recurring_create_invoice()
new_invoice = self.contract._get_related_invoices()
self.assertTrue(new_invoice)
self.assertEqual(new_invoice.partner_id, self.contract.partner_id)
self.assertEqual(new_invoice.payment_mode_id, self.contract.payment_mode_id)
self.assertEqual(len(new_invoice.ids), 1)
self.contract.recurring_create_invoice()
self.assertEqual(self.contract.payment_mode_id, new_invoice.payment_mode_id)
| 36.145038 | 4,735 |
967 |
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class ContractContract(models.Model):
_inherit = "contract.contract"
payment_mode_id = fields.Many2one(
comodel_name="account.payment.mode",
string="Payment Mode",
domain=[("payment_type", "=", "inbound")],
index=True,
)
@api.onchange("partner_id")
def on_change_partner_id(self):
partner = self.with_company(self.company_id).partner_id
if self.contract_type == "purchase":
self.payment_mode_id = partner.supplier_payment_mode_id.id
else:
self.payment_mode_id = partner.customer_payment_mode_id.id
def _prepare_invoice(self, date_invoice, journal=None):
invoice_vals, move_form = super()._prepare_invoice(
date_invoice=date_invoice, journal=journal
)
if self.payment_mode_id:
invoice_vals["payment_mode_id"] = self.payment_mode_id.id
return invoice_vals, move_form
| 34.535714 | 967 |
819 |
py
|
PYTHON
|
15.0
|
# Copyright 2016-2019 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Variable quantity in contract recurrent invoicing",
"version": "15.0.1.0.0",
"category": "Contract Management",
"license": "AGPL-3",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/contract",
"depends": ["contract"],
"data": [
"security/ir.model.access.csv",
"views/abstract_contract_line.xml",
"views/contract_line_formula.xml",
"views/contract_line_views.xml",
"views/contract_template.xml",
"views/contract.xml",
"views/contract_portal_templates.xml",
],
"installable": True,
}
| 34.125 | 819 |
2,976 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import exceptions
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
@tagged("post_install", "-at_install")
class TestContractVariableQuantity(TransactionCase):
def setUp(self):
super().setUp()
self.partner = self.env["res.partner"].create({"name": "Test partner"})
self.product = self.env["product.product"].create({"name": "Test product"})
self.contract = self.env["contract.contract"].create(
{
"name": "Test Contract",
"partner_id": self.partner.id,
"pricelist_id": self.partner.property_product_pricelist.id,
}
)
self.formula = self.env["contract.line.qty.formula"].create(
{
"name": "Test formula",
# For testing each of the possible variables
"code": 'env["res.users"]\n'
'context.get("lang")\n'
"user.id\n"
"line.qty_type\n"
"contract.id\n"
"quantity\n"
"period_first_date\n"
"period_last_date\n"
"invoice_date\n"
"result = 12",
}
)
self.contract_line = self.env["contract.line"].create(
{
"contract_id": self.contract.id,
"product_id": self.product.id,
"name": "Test",
"qty_type": "variable",
"qty_formula_id": self.formula.id,
"quantity": 1,
"uom_id": self.product.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2016-02-15",
"recurring_next_date": "2016-02-29",
}
)
def test_check_invalid_code(self):
with self.assertRaises(exceptions.ValidationError):
self.formula.code = "sdsds"
def test_check_no_return_value(self):
with self.assertRaises(exceptions.ValidationError):
self.formula.code = "user.id"
def test_check_variable_quantity(self):
self.contract.recurring_create_invoice()
invoice = self.contract._get_related_invoices()
self.assertEqual(invoice.invoice_line_ids[0].quantity, 12)
def test_check_skip_zero_qty(self):
self.formula.code = "result=0"
self.contract.skip_zero_qty = True
invoice = self.contract.recurring_create_invoice()
self.assertFalse(invoice.invoice_line_ids)
self.contract.skip_zero_qty = False
invoice = self.contract.recurring_create_invoice()
self.assertAlmostEqual(invoice.invoice_line_ids[0].quantity, 0.0)
| 38.153846 | 2,976 |
639 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractAbstractContractLine(models.AbstractModel):
_inherit = "contract.abstract.contract.line"
qty_type = fields.Selection(
selection=[("fixed", "Fixed quantity"), ("variable", "Variable quantity")],
required=True,
default="fixed",
string="Qty. type",
)
qty_formula_id = fields.Many2one(
comodel_name="contract.line.qty.formula", string="Qty. formula"
)
| 31.95 | 639 |
1,873 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
from odoo.tools import float_is_zero
from odoo.tools.safe_eval import safe_eval
class AccountAnalyticInvoiceLine(models.Model):
_inherit = "contract.line"
def _get_quantity_to_invoice(
self, period_first_date, period_last_date, invoice_date
):
quantity = super()._get_quantity_to_invoice(
period_first_date, period_last_date, invoice_date
)
if not period_first_date or not period_last_date or not invoice_date:
return quantity
if self.qty_type == "variable":
eval_context = {
"env": self.env,
"context": self.env.context,
"user": self.env.user,
"line": self,
"quantity": quantity,
"period_first_date": period_first_date,
"period_last_date": period_last_date,
"invoice_date": invoice_date,
"contract": self.contract_id,
}
safe_eval(
self.qty_formula_id.code.strip(),
eval_context,
mode="exec",
nocopy=True,
) # nocopy for returning result
quantity = eval_context.get("result", 0)
return quantity
def _prepare_invoice_line(self, move_form):
vals = super()._prepare_invoice_line(move_form)
if (
"quantity" in vals
and self.contract_id.skip_zero_qty
and float_is_zero(
vals["quantity"],
self.env["decimal.precision"].precision_get("Product Unit of Measure"),
)
):
vals = {}
return vals
| 34.685185 | 1,873 |
1,377 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
from odoo.tools.safe_eval import safe_eval
class ContractLineFormula(models.Model):
_name = "contract.line.qty.formula"
_description = "Contract Line Formula"
name = fields.Char(required=True, translate=True)
code = fields.Text(required=True, default="result = 0")
@api.constrains("code")
def _check_code(self):
eval_context = {
"env": self.env,
"context": self.env.context,
"user": self.env.user,
"line": self.env["contract.line"],
"contract": self.env["contract.contract"],
"invoice": self.env["account.move"],
"quantity": 0,
"period_first_date": False,
"period_last_date": False,
"invoice_date": False,
}
try:
safe_eval(self.code.strip(), eval_context, mode="exec", nocopy=True)
except Exception as e:
raise exceptions.ValidationError(
_("Error evaluating code.\nDetails: %s") % e
) from e
if "result" not in eval_context:
raise exceptions.ValidationError(_("No valid result returned."))
| 36.236842 | 1,377 |
450 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Pedro M. Baeza
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractContract(models.Model):
_inherit = "contract.contract"
skip_zero_qty = fields.Boolean(
string="Skip Zero Qty Lines",
help="If checked, contract lines with 0 qty don't create invoice line",
)
| 30 | 450 |
579 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Pesol (<http://pesol.es>)
# Copyright 2017 Angel Moya <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html)
{
"name": "Contracts Management - Recurring Sales",
"version": "15.0.1.0.3",
"category": "Contract Management",
"license": "AGPL-3",
"author": "ACSONE SA/NV, PESOL, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/contract",
"depends": ["contract_sale"],
"data": [
"data/contract_cron.xml",
"views/contract.xml",
],
"installable": True,
}
| 30.473684 | 579 |
6,847 |
py
|
PYTHON
|
15.0
|
# © 2016 Carlos Dauden <[email protected]>
# Copyright 2017 Pesol (<http://pesol.es>)
# Copyright 2017 Angel Moya <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
from .common import ContractSaleCommon, to_date
class TestContractSale(ContractSaleCommon, TransactionCase):
def test_check_discount(self):
with self.assertRaises(ValidationError):
self.contract_line.write({"discount": 120})
def test_contract(self):
recurring_next_date = to_date("2020-02-15")
self.assertAlmostEqual(self.contract_line.price_subtotal, 50.0)
self.contract_line.price_unit = 100.0
self.contract.partner_id = self.partner.id
self.contract.recurring_create_sale()
self.sale_monthly = self.contract._get_related_sales()
self.assertTrue(self.sale_monthly)
self.assertEqual(self.contract_line.recurring_next_date, recurring_next_date)
self.order_line = self.sale_monthly.order_line[0]
self.assertTrue(self.order_line.tax_id)
self.assertAlmostEqual(self.order_line.price_subtotal, 50.0)
self.assertEqual(self.contract.user_id, self.sale_monthly.user_id)
def test_contract_autoconfirm(self):
recurring_next_date = to_date("2020-02-15")
self.contract.sale_autoconfirm = True
self.assertAlmostEqual(self.contract_line.price_subtotal, 50.0)
self.contract_line.price_unit = 100.0
self.contract.partner_id = self.partner.id
self.contract.recurring_create_sale()
self.sale_monthly = self.contract._get_related_sales()
self.assertTrue(self.sale_monthly)
self.assertEqual(self.contract_line.recurring_next_date, recurring_next_date)
self.order_line = self.sale_monthly.order_line[0]
self.assertTrue(self.order_line.tax_id)
self.assertAlmostEqual(self.order_line.price_subtotal, 50.0)
self.assertEqual(self.contract.user_id, self.sale_monthly.user_id)
def test_onchange_contract_template_id(self):
"""It should change the contract values to match the template."""
self.contract.contract_template_id = False
self.contract._onchange_contract_template_id()
self.contract.contract_template_id = self.template
self.contract._onchange_contract_template_id()
res = {
"contract_type": "sale",
"contract_line_ids": [
(
0,
0,
{
"product_id": self.product_1.id,
"name": "Test Contract Template",
"quantity": 1,
"uom_id": self.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "yearly",
"recurring_interval": 1,
},
)
],
}
del self.template_vals["name"]
self.assertDictEqual(res, self.template_vals)
def test_contract_count_sale(self):
self.contract.recurring_create_sale()
self.contract.recurring_create_sale()
self.contract.recurring_create_sale()
self.contract._compute_sale_count()
self.assertEqual(self.contract.sale_count, 3)
def test_contract_count_sale_2(self):
orders = self.env["sale.order"]
orders |= self.contract.recurring_create_sale()
orders |= self.contract.recurring_create_sale()
orders |= self.contract.recurring_create_sale()
action = self.contract.action_show_sales()
self.assertEqual(set(action["domain"][0][2]), set(orders.ids))
def test_cron_recurring_create_sale(self):
self.contract_line.date_start = "2020-01-01"
self.contract_line.recurring_invoicing_type = "post-paid"
self.contract_line.date_end = "2020-03-15"
self.contract_line._onchange_is_auto_renew()
# If we do not recompute recurring_next_date
# then it maintains it's 'old' value.
# TODO: Research that
recurring_next_date = self.contract_line.recurring_next_date
self.assertGreaterEqual(recurring_next_date, self.contract_line.date_start)
contracts = self.contract2
for _i in range(10):
contracts |= self.contract.copy({"generation_type": "sale"})
self.env["contract.contract"]._cron_recurring_create(create_type="sale")
order_lines = self.env["sale.order.line"].search(
[("contract_line_id", "in", contracts.mapped("contract_line_ids").ids)]
)
self.assertEqual(
len(contracts.mapped("contract_line_ids")),
len(order_lines),
)
def test_contract_sale_analytic_payment_term_fiscal_position(self):
# Call onchange in order to retrieve
# payment term and fiscal position
self.contract._onchange_partner_id()
orders = self.env["sale.order"].browse()
orders |= self.contract.recurring_create_sale()
self.assertEqual(self.analytic_account, orders.mapped("analytic_account_id"))
self.assertEqual(self.payment_term_id, orders.mapped("payment_term_id"))
self.assertEqual(self.fiscal_position_id, orders.mapped("fiscal_position_id"))
def test_recurring_method_retrieval(self):
self.assertNotEqual(
self.contract._get_recurring_create_func(create_type="sale"),
self.contract._get_recurring_create_func(create_type="invoice"),
)
def test__prepare_recurring_sales_values_no_date_ref(self):
self.contract.recurring_next_date = False
self.assertEqual(self.contract._prepare_recurring_sales_values(), [])
def test__prepare_recurring_sales_values_no_contract_lines(self):
a_contract_with_no_lines = self.env["contract.contract"].create(
{
"name": "No lines Contract",
"partner_id": self.partner.id,
"generation_type": "sale",
"date_start": "2020-01-15",
}
)
self.assertEqual(a_contract_with_no_lines._prepare_recurring_sales_values(), [])
def test__prepare_sale_line_vals_with_order_id(self):
order = self.contract.recurring_create_sale()[0]
recurring_next_date = self.contract.recurring_next_date
date_start = self.contract.date_start
date_end = self.contract.date_end
dates = [date_start, date_end, recurring_next_date]
for line in self.contract._get_lines_to_invoice(recurring_next_date):
line_vals = line._prepare_sale_line_vals(dates, order)
self.assertEqual(line_vals["order_id"], order.id)
| 45.64 | 6,846 |
2,605 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from freezegun.api import freeze_time
from odoo import fields
from odoo.tests import Form
from odoo.tests.common import TransactionCase
from .common import ContractSaleCommon
today = "2020-01-15"
class TestContractSale(ContractSaleCommon, TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.contract_obj = cls.env["contract.contract"]
@classmethod
def _create_contract(cls):
cls.contract = cls.contract.create(
{
"name": "Test Contract",
"partner_id": cls.partner.id,
}
)
with Form(cls.contract) as contract_form:
contract_form.partner_id = cls.partner
contract_form.generation_type = "sale"
contract_form.group_id = cls.analytic_account
cls.contract = contract_form.save()
def test_contract_next_date(self):
"""
Change recurrence to weekly
Check the recurring next date value on lines
"""
with freeze_time(today):
self._create_contract()
self.contract.recurring_rule_type = "weekly"
with freeze_time(today):
with Form(self.contract) as contract_form:
with contract_form.contract_line_ids.new() as line_form:
line_form.product_id = self.product_1
line_form.name = "Services from #START# to #END#"
line_form.quantity = 1
line_form.price_unit = 100.0
line_form.discount = 50
line_form.recurring_rule_type = "weekly"
with freeze_time(today):
with Form(self.contract) as contract_form:
with contract_form.contract_line_ids.new() as line_form:
line_form.product_id = self.product_1
line_form.name = "Services from #START# to #END#"
line_form.quantity = 2
line_form.price_unit = 50.0
line_form.recurring_rule_type = "weekly"
self.assertEqual(
fields.Date.to_date("2020-01-15"), self.contract.recurring_next_date
)
self.contract.recurring_create_sale()
self.assertEqual(
fields.Date.to_date("2020-01-22"), self.contract.recurring_next_date
)
self.contract.recurring_create_sale()
self.assertEqual(
fields.Date.to_date("2020-01-29"), self.contract.recurring_next_date
)
| 35.684932 | 2,605 |
5,412 |
py
|
PYTHON
|
15.0
|
# © 2016 Carlos Dauden <[email protected]>
# Copyright 2017 Pesol (<http://pesol.es>)
# Copyright 2017 Angel Moya <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from freezegun import freeze_time
from odoo import fields
from odoo.tests import Form
def to_date(date):
return fields.Date.to_date(date)
class ContractSaleCommon:
# Use case : Prepare some data for current test case
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.analytic_account = cls.env["account.analytic.account"].create(
{
"name": "Contracts",
}
)
cls.payment_term_id = cls.env.ref(
"account.account_payment_term_end_following_month"
)
cls.fiscal_position_id = cls.env["account.fiscal.position"].create(
{"name": "Contracts"}
)
contract_date = "2020-01-15"
cls.pricelist = cls.env["product.pricelist"].create(
{
"name": "pricelist for contract test",
}
)
cls.partner = cls.env["res.partner"].create(
{
"name": "partner test contract",
"property_product_pricelist": cls.pricelist.id,
"property_payment_term_id": cls.payment_term_id.id,
"property_account_position_id": cls.fiscal_position_id.id,
}
)
cls.product_1 = cls.env.ref("product.product_product_1")
cls.product_1.taxes_id += cls.env["account.tax"].search(
[("type_tax_use", "=", "sale")], limit=1
)
cls.product_1.description_sale = "Test description sale"
cls.line_template_vals = {
"product_id": cls.product_1.id,
"name": "Test Contract Template",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "yearly",
"recurring_interval": 1,
}
cls.template_vals = {
"name": "Test Contract Template",
"contract_type": "sale",
"contract_line_ids": [
(0, 0, cls.line_template_vals),
],
}
cls.template = cls.env["contract.template"].create(cls.template_vals)
# For being sure of the applied price
cls.env["product.pricelist.item"].create(
{
"pricelist_id": cls.partner.property_product_pricelist.id,
"product_id": cls.product_1.id,
"compute_price": "formula",
"base": "list_price",
}
)
cls.contract = cls.env["contract.contract"].create(
{
"name": "Test Contract",
"partner_id": cls.partner.id,
"pricelist_id": cls.partner.property_product_pricelist.id,
"generation_type": "sale",
"sale_autoconfirm": False,
"group_id": cls.analytic_account.id,
"date_start": "2020-01-15",
}
)
cls.line_vals = {
"name": "Services from #START# to #END#",
"quantity": 1,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2020-01-01",
"recurring_next_date": "2020-01-15",
}
with Form(cls.contract) as contract_form, freeze_time(contract_date):
contract_form.contract_template_id = cls.template
with contract_form.contract_line_ids.new() as line_form:
line_form.product_id = cls.product_1
line_form.name = "Services from #START# to #END#"
line_form.quantity = 1
line_form.price_unit = 100.0
line_form.discount = 50
line_form.recurring_rule_type = "monthly"
line_form.recurring_interval = 1
line_form.date_start = "2020-01-15"
line_form.recurring_next_date = "2020-01-15"
cls.contract_line = cls.contract.contract_line_ids[1]
cls.contract2 = cls.env["contract.contract"].create(
{
"name": "Test Contract 2",
"generation_type": "sale",
"partner_id": cls.partner.id,
"pricelist_id": cls.partner.property_product_pricelist.id,
"contract_type": "purchase",
"contract_line_ids": [
(
0,
0,
{
"product_id": cls.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2018-02-15",
"recurring_next_date": "2018-02-22",
},
)
],
}
)
| 38.65 | 5,411 |
832 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
contract_auto_confirm = fields.Boolean(
compute="_compute_contract_auto_confirm",
help="This is a technical field in order to know if the order should"
"be automatically confirmed if generated by contract.",
)
def _compute_contract_auto_confirm(self):
sale_auto_confirm = self.filtered(
lambda sale: any(
line.contract_line_id.contract_id.sale_autoconfirm
for line in sale.order_line
)
)
sale_auto_confirm.contract_auto_confirm = True
(self - sale_auto_confirm).contract_auto_confirm = False
| 34.666667 | 832 |
319 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
contract_line_id = fields.Many2one(
"contract.line", string="Contract Line", index=True
)
| 26.583333 | 319 |
1,944 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class ContractLine(models.Model):
_inherit = "contract.line"
def _prepare_sale_line_vals(self, dates, order_id=False):
sale_line_vals = {
"product_id": self.product_id.id,
"product_uom_qty": self._get_quantity_to_invoice(*dates),
"product_uom": self.uom_id.id,
"discount": self.discount,
"contract_line_id": self.id,
"display_type": self.display_type,
}
if order_id:
sale_line_vals["order_id"] = order_id.id
return sale_line_vals
def _prepare_sale_line(self, order_id=False, sale_values=False):
self.ensure_one()
dates = self._get_period_to_invoice(
self.last_date_invoiced, self.recurring_next_date
)
sale_line_vals = self._prepare_sale_line_vals(dates, order_id=order_id)
order_line = (
self.env["sale.order.line"]
.with_company(self.contract_id.company_id.id)
.new(sale_line_vals)
)
if sale_values and not order_id:
sale = (
self.env["sale.order"]
.with_company(self.contract_id.company_id.id)
.new(sale_values)
)
order_line.order_id = sale
# Get other order line values from product onchange
order_line.product_id_change()
sale_line_vals = order_line._convert_to_write(order_line._cache)
# Insert markers
name = self._insert_markers(dates[0], dates[1])
sale_line_vals.update(
{
"sequence": self.sequence,
"name": name,
"analytic_tag_ids": [(6, 0, self.analytic_tag_ids.ids)],
"price_unit": self.price_unit,
}
)
return sale_line_vals
| 35.345455 | 1,944 |
501 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Pesol (<http://pesol.es>)
# Copyright 2017 Angel Moya <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ContractAbstractContract(models.AbstractModel):
_inherit = "contract.abstract.contract"
sale_autoconfirm = fields.Boolean()
@api.model
def _selection_generation_type(self):
res = super()._selection_generation_type()
res.append(("sale", "Sale"))
return res
| 29.470588 | 501 |
5,273 |
py
|
PYTHON
|
15.0
|
# © 2004-2010 OpenERP SA
# © 2014 Angel Moya <[email protected]>
# © 2015 Pedro M. Baeza <[email protected]>
# © 2016 Carlos Dauden <[email protected]>
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2017 Pesol (<http://pesol.es>)
# Copyright 2017 Angel Moya <[email protected]>
# Copyright 2018 Therp BV <https://therp.nl>.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class ContractContract(models.Model):
_inherit = "contract.contract"
sale_count = fields.Integer(compute="_compute_sale_count")
def _prepare_sale(self, date_ref):
self.ensure_one()
sale = self.env["sale.order"].new(
{
"partner_id": self.partner_id,
"date_order": fields.Date.to_string(date_ref),
"origin": self.name,
"company_id": self.company_id.id,
"user_id": self.partner_id.user_id.id,
"analytic_account_id": self.group_id.id,
}
)
if self.payment_term_id:
sale.payment_term_id = self.payment_term_id.id
if self.fiscal_position_id:
sale.fiscal_position_id = self.fiscal_position_id.id
# Get other sale values from partner onchange
sale.onchange_partner_id()
return sale._convert_to_write(sale._cache)
def _get_related_sales(self):
self.ensure_one()
sales = (
self.env["sale.order.line"]
.search([("contract_line_id", "in", self.contract_line_ids.ids)])
.mapped("order_id")
)
return sales
def _compute_sale_count(self):
for rec in self:
rec.sale_count = len(rec._get_related_sales())
def action_show_sales(self):
self.ensure_one()
tree_view = self.env.ref("sale.view_order_tree", raise_if_not_found=False)
form_view = self.env.ref("sale.view_order_form", raise_if_not_found=False)
action = {
"type": "ir.actions.act_window",
"name": "Sales Orders",
"res_model": "sale.order",
"view_type": "form",
"view_mode": "tree,kanban,form,calendar,pivot,graph,activity",
"domain": [("id", "in", self._get_related_sales().ids)],
}
if tree_view and form_view:
action["views"] = [(tree_view.id, "tree"), (form_view.id, "form")]
return action
def recurring_create_sale(self):
"""
This method triggers the creation of the next sale order of the
contracts even if their next sale order date is in the future.
"""
sales = self._recurring_create_sale()
for sale_rec in sales:
self.message_post(
body=_(
"Contract manually sale order: "
'<a href="#" data-oe-model="%(model)s" data-oe-id="%(id)s">'
"Sale Order"
"</a>"
)
% {"model": sale_rec._name, "id": sale_rec.id}
)
return sales
def _prepare_recurring_sales_values(self, date_ref=False):
"""
This method builds the list of sales values to create, based on
the lines to sale of the contracts in self.
!!! The date of next invoice (recurring_next_date) is updated here !!!
:return: list of dictionaries (invoices values)
"""
sales_values = []
for contract in self:
if not date_ref:
date_ref = contract.recurring_next_date
if not date_ref:
# this use case is possible when recurring_create_invoice is
# called for a finished contract
continue
contract_lines = contract._get_lines_to_invoice(date_ref)
if not contract_lines:
continue
sale_values = contract._prepare_sale(date_ref)
for line in contract_lines:
sale_values.setdefault("order_line", [])
invoice_line_values = line._prepare_sale_line(
sale_values=sale_values,
)
if invoice_line_values:
sale_values["order_line"].append((0, 0, invoice_line_values))
sales_values.append(sale_values)
contract_lines._update_recurring_next_date()
return sales_values
def _recurring_create_sale(self, date_ref=False):
sales_values = self._prepare_recurring_sales_values(date_ref)
sale_orders = self.env["sale.order"].create(sales_values)
sale_orders_to_confirm = sale_orders.filtered(
lambda sale: sale.contract_auto_confirm
)
sale_orders_to_confirm.action_confirm()
self._compute_recurring_next_date()
return sale_orders
@api.model
def _get_recurring_create_func(self, create_type="invoice"):
res = super()._get_recurring_create_func(create_type=create_type)
if create_type == "sale":
return self.__class__._recurring_create_sale
return res
@api.model
def cron_recurring_create_sale(self, date_ref=None):
return self._cron_recurring_create(date_ref, create_type="sale")
| 39.02963 | 5,269 |
764 |
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-contract",
description="Meta package for oca-contract Odoo addons",
version=version,
install_requires=[
'odoo-addon-agreement_rebate_partner_company_group>=15.0dev,<15.1dev',
'odoo-addon-contract>=15.0dev,<15.1dev',
'odoo-addon-contract_payment_mode>=15.0dev,<15.1dev',
'odoo-addon-contract_sale>=15.0dev,<15.1dev',
'odoo-addon-contract_sale_generation>=15.0dev,<15.1dev',
'odoo-addon-contract_variable_quantity>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 33.217391 | 764 |
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 |
627 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Dauden
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Agreement Rebate Partner Company Group",
"summary": "Rebate agreements applied to all company group members",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "Contract",
"website": "https://github.com/OCA/contract",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["agreement_rebate", "base_partner_company_group"],
}
| 39.1875 | 627 |
1,897 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.addons.agreement_rebate.tests.test_agreement_rebate import TestAgreementRebate
class TestAgreementRebatePartnerCompanyGroup(TestAgreementRebate):
def setUp(self):
super().setUp()
self.Partner = self.env["res.partner"]
self.partner_group = self.Partner.create(
{"name": "partner test rebate group", "ref": "TST-G01"}
)
self.partner_member_1 = self.Partner.create(
{
"name": "partner test rebate member 1",
"ref": "TST-M001",
"company_group_id": self.partner_group.id,
}
)
self.partner_member_2 = self.Partner.create(
{
"name": "partner test rebate member 2",
"ref": "TST-M002",
"company_group_id": self.partner_group.id,
}
)
self.invoice_member_1 = self.create_invoice(self.partner_member_1)
self.invoice_member_2 = self.create_invoice(self.partner_member_2)
def test_create_settlement_wo_filters_global_company_group(self):
"""Global rebate without filters apply to all company group members"""
# Total by invoice: 3800 amount invoiced
# 2 invoice members: 3800 * 2 = 7600
# Global rebate without filters
agreement_global = self.create_agreements_rebate("global", self.partner_group)
agreement_global.rebate_line_ids = False
settlement_wiz = self.create_settlement_wizard(agreement_global)
settlements = self.get_settlements_from_action(
settlement_wiz.action_create_settlement()
)
self.assertEqual(len(settlements), 1)
self.assertEqual(settlements.amount_invoiced, 7600)
self.assertEqual(settlements.amount_rebate, 760)
| 42.155556 | 1,897 |
866 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class AgreementSettlementCreateWiz(models.TransientModel):
_inherit = "agreement.settlement.create.wiz"
def _partner_domain(self, agreement):
if not agreement.partner_id.company_group_member_ids:
return super()._partner_domain(agreement)
# Try replace only child_of part in original domain
orig_domain = ("partner_id", "child_of", agreement.partner_id.ids)
domain = super()._partner_domain(agreement)
pos = 0
if orig_domain in domain:
pos = domain.index(orig_domain)
domain.remove(orig_domain)
domain.insert(
pos, ("partner_id", "in", agreement.partner_id.company_group_member_ids.ids)
)
return domain
| 37.652174 | 866 |
915 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Jairo Llopis
# Copyright 2021 Tecnativa - Víctor Martínez
# Copyright 2021 Tecnativa - Pedro M. Baeza
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "eCommerce product attachments",
"summary": "Let visitors download attachments from a product page",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, Odoo Community Association (OCA)",
"maintainers": ["Yajo"],
"license": "LGPL-3",
"installable": True,
"depends": ["website_sale"],
"data": [
"templates/product_template.xml",
"views/ir_attachment.xml",
"views/product_template.xml",
],
"assets": {
"web.assets_tests": [
"website_sale_product_attachment/static/tests/tours/website_tour.js",
]
},
}
| 33.814815 | 913 |
569 |
py
|
PYTHON
|
15.0
|
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
# Copyright 2021 Tecnativa - Víctor Martínez
from odoo.tests import common
class TestWebsiteSaleProductAttachmentTourl(common.HttpCase):
def setUp(self):
super().setUp()
attachment = self.env.ref("website.library_image_11")
product = self.env.ref("product.product_product_4_product_template")
product.website_attachment_ids = [(6, 0, [attachment.id])]
def test_tour(self):
self.start_tour("/shop", "website_sale_product_attachment_tour", login="demo")
| 37.8 | 567 |
735 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Jairo Llopis
# Copyright 2021 Tecnativa - Pedro M. Baeza
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import fields, models
class IrAttachment(models.Model):
_inherit = "ir.attachment"
attached_in_product_tmpl_ids = fields.Many2many(
string="Attached in products",
comodel_name="product.template",
help="Attachment publicly downladable from eCommerce pages "
"in these product templates.",
)
website_name = fields.Char(
string="Name in e-commerce",
help="The name of the download that will be displayed on the e-commerce "
"product page. If not filled, the filename will be shown by default.",
)
| 35 | 735 |
1,722 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Jairo Llopis
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models
from odoo.addons.website.models import ir_http
class ProductTemplate(models.Model):
_inherit = "product.template"
website_attachment_ids = fields.Many2many(
string="Website attachments",
comodel_name="ir.attachment",
context={"default_public": True, "hide_attachment_products": True},
domain=lambda self, *args, **kwargs: (
self._domain_website_attachment_ids(*args, **kwargs)
),
help="Files publicly downloadable from the product eCommerce page.",
)
@api.model
def _domain_website_attachment_ids(self):
"""Get domain for website attachments."""
domain = [
# Only use public attachments
("public", "=", True),
# Exclude Odoo asset files to avoid confusing the user
"!",
("name", "=ilike", "%.assets%.js"),
"!",
("name", "=ilike", "%.assets%.css"),
"!",
("name", "=ilike", "web_editor%"),
"!",
("name", "=ilike", "/web/content/%.assets%.js"),
"!",
("name", "=ilike", "/web/content/%.assets%.css"),
"!",
("name", "=ilike", r"/web/content/%/web\_editor.summernote%.js"),
"!",
("name", "=ilike", r"/web/content/%/web\_editor.summernote%.css"),
]
# Filter by website domain in frontend
if ir_http.get_request_website():
website = self.env["website"].get_current_website()
domain += website.website_domain()
return domain
| 35.875 | 1,722 |
1,227 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Website Sale Product Minimal Price",
"summary": "Display minimal price for products that has variants",
"version": "15.0.1.0.0",
"development_status": "Production/Stable",
"maintainers": ["sergio-teruel"],
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["website_sale"],
"data": ["views/templates.xml"],
"assets": {
"web.assets_frontend": [
"/web/static/src/legacy/js/fields/field_utils.js",
"/website_sale_product_minimal_price/static/src/js"
"/website_sale_product_minimal_price.js",
"/website_sale_product_minimal_price/static/src/js"
"/website_sale_product_price_scale.js",
],
"web.assets_tests": [
"/website_sale_product_minimal_price/static/src/js/tour.js",
"/website_sale_product_minimal_price/static/src/js"
"/test_product_with_no_prices_tour.js",
],
},
}
| 39.580645 | 1,227 |
3,532 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import tagged
from odoo.tests.common import HttpCase
@tagged("post_install", "-at_install")
class WebsiteSaleProductMinimalPriceHttpCase(HttpCase):
def setUp(self):
super().setUp()
# Create and select a pricelist
# to make tests pass no matter what l10n package is enabled
self.website = self.env["website"].get_current_website()
pricelist = self.env["product.pricelist"].create(
{
"name": "website_sale_product_minimal_price public",
"currency_id": self.env.company.currency_id.id,
"selectable": True,
"sequence": 1,
"website_id": self.website.id,
}
)
self.env.ref("base.user_admin").property_product_pricelist = pricelist
# Models
ProductAttribute = self.env["product.attribute"]
ProductAttributeValue = self.env["product.attribute.value"]
ProductTmplAttributeValue = self.env["product.template.attribute.value"]
self.product_attribute = ProductAttribute.create(
{"name": "Test", "create_variant": "always"}
)
self.product_attribute_value_test_1 = ProductAttributeValue.create(
{"name": "Test v1", "attribute_id": self.product_attribute.id}
)
self.product_attribute_value_test_2 = ProductAttributeValue.create(
{"name": "Test v2", "attribute_id": self.product_attribute.id}
)
self.product_template = self.env["product.template"].create(
{
"name": "My product test with various prices",
"is_published": True,
"type": "consu",
"list_price": 100.0,
"website_id": self.website.id,
"website_sequence": 1,
"attribute_line_ids": [
(
0,
0,
{
"attribute_id": self.product_attribute.id,
"value_ids": [
(4, self.product_attribute_value_test_1.id),
(4, self.product_attribute_value_test_2.id),
],
},
),
],
}
)
product_tmpl_att_value = ProductTmplAttributeValue.search(
[
("product_tmpl_id", "=", self.product_template.id),
("attribute_id", "=", self.product_attribute.id),
(
"product_attribute_value_id",
"=",
self.product_attribute_value_test_1.id,
),
]
)
product_tmpl_att_value.price_extra = 50.0
product_tmpl_att_value = ProductTmplAttributeValue.search(
[
("product_tmpl_id", "=", self.product_template.id),
("attribute_id", "=", self.product_attribute.id),
(
"product_attribute_value_id",
"=",
self.product_attribute_value_test_2.id,
),
]
)
product_tmpl_att_value.price_extra = 25.0
def test_ui_website(self):
"""Test frontend tour."""
self.start_tour("/shop", "website_sale_product_minimal_price", login="admin")
| 40.597701 | 3,532 |
4,038 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import tagged
from odoo.tests.common import HttpCase
@tagged("post_install", "-at_install")
class TestProductWithNoPrices(HttpCase):
"""With this test we are checking that the minimal price is set
when the product has not a price defined and the price of
variants depend on a subpricelist.
"""
def setUp(self):
super().setUp()
ProductAttribute = self.env["product.attribute"]
ProductAttributeValue = self.env["product.attribute.value"]
self.category = self.env["product.category"].create({"name": "Test category"})
self.product_attribute = ProductAttribute.create(
{"name": "Test", "create_variant": "always"}
)
self.product_attribute_value_test_1 = ProductAttributeValue.create(
{"name": "Test v1", "attribute_id": self.product_attribute.id}
)
self.product_attribute_value_test_2 = ProductAttributeValue.create(
{"name": "Test v2", "attribute_id": self.product_attribute.id}
)
self.product_template = self.env["product.template"].create(
{
"name": "My product test with no prices",
"is_published": True,
"type": "consu",
"website_sequence": 1,
"categ_id": self.category.id,
"attribute_line_ids": [
(
0,
0,
{
"attribute_id": self.product_attribute.id,
"value_ids": [
(4, self.product_attribute_value_test_1.id),
(4, self.product_attribute_value_test_2.id),
],
},
),
],
}
)
self.variant_1 = self.product_template.product_variant_ids[0]
self.variant_2 = self.product_template.product_variant_ids[1]
self.pricelist_aux = self.env["product.pricelist"].create(
{
"name": "Test pricelist Aux",
"selectable": True,
"item_ids": [
(
0,
0,
{
"applied_on": "0_product_variant",
"product_id": self.variant_1.id,
"compute_price": "fixed",
"fixed_price": 10,
},
),
(
0,
0,
{
"applied_on": "0_product_variant",
"product_id": self.variant_2.id,
"compute_price": "fixed",
"fixed_price": 11,
},
),
],
}
)
self.pricelist_main = self.env["product.pricelist"].create(
{
"name": "Test pricelist Main",
"selectable": True,
"item_ids": [
(
0,
0,
{
"applied_on": "2_product_category",
"categ_id": self.category.id,
"compute_price": "formula",
"base": "pricelist",
"base_pricelist_id": self.pricelist_aux.id,
},
)
],
}
)
user = self.env.ref("base.user_admin")
user.property_product_pricelist = self.pricelist_main
def test_ui_website(self):
"""Test frontend tour."""
self.start_tour("/", "test_product_with_no_prices", login="admin")
| 38.826923 | 4,038 |
5,167 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Sergio Teruel
# Copyright 2020 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class ProductTemplate(models.Model):
_inherit = "product.template"
def _get_product_subpricelists(self, pricelist_id):
return pricelist_id.item_ids.filtered(
lambda i: (
i.applied_on == "3_global"
or (
i.applied_on == "2_product_category" and i.categ_id == self.categ_id
)
or (i.applied_on == "1_product" and i.product_tmpl_id == self)
or (
i.applied_on == "0_product_variant"
and i.product_id in self.product_variant_ids
)
)
and i.compute_price == "formula"
and i.base == "pricelist"
).mapped("base_pricelist_id")
def _get_variants_from_pricelist(self, pricelist_ids):
return pricelist_ids.mapped("item_ids").filtered(
lambda i: i.product_id in self.product_variant_ids
)
def _get_pricelist_variant_items(self, pricelist_id):
res = self._get_variants_from_pricelist(pricelist_id)
next_pricelists = self._get_product_subpricelists(pricelist_id)
res |= self._get_variants_from_pricelist(next_pricelists)
visited_pricelists = pricelist_id
while next_pricelists:
pricelist = next_pricelists[0]
if pricelist not in visited_pricelists:
res |= self._get_variants_from_pricelist(pricelist)
next_pricelists |= self._get_product_subpricelists(pricelist)
next_pricelists -= pricelist
visited_pricelists |= pricelist
else:
next_pricelists -= pricelist
return res
def _get_cheapest_info(self, pricelist):
"""Helper method for getting the variant with lowest price."""
# TODO: Cache this method for getting better performance
self.ensure_one()
min_price = 99999999
product_id = False
add_qty = 0
has_distinct_price = False
# Variants with extra price
variants_extra_price = self.product_variant_ids.filtered("price_extra")
variants_without_extra_price = self.product_variant_ids - variants_extra_price
# Avoid compute prices when pricelist has not item variants defined
variant_items = self._get_pricelist_variant_items(pricelist)
if variant_items:
# Take into account only the variants defined in pricelist and one
# variant not defined to compute prices defined at template or
# category level. Maybe there is any definition on template that
# has cheaper price.
variants = variant_items.mapped("product_id")
products = variants + (self.product_variant_ids - variants)[:1]
else:
products = variants_without_extra_price[:1]
products |= variants_extra_price
for product in products:
for qty in [1, 99999999]:
product_price = product.with_context(
quantity=qty, pricelist=pricelist.id
).price
if product_price != min_price and min_price != 99999999:
# Mark if there are different prices iterating over
# variants and comparing qty 1 and maximum qty
has_distinct_price = True
if product_price < min_price:
min_price = product_price
add_qty = qty
product_id = product.id
return product_id, add_qty, has_distinct_price
def _get_first_possible_combination(
self, parent_combination=None, necessary_values=None
):
"""Get the cheaper product combination for the website view."""
res = super()._get_first_possible_combination(
parent_combination=parent_combination, necessary_values=necessary_values
)
context = self.env.context
if (
context.get("website_id")
and context.get("pricelist")
and self.product_variant_count > 1
):
# It only makes sense to change the default one when there are
# more than one variants and we know the pricelist
pricelist = self.env["product.pricelist"].browse(context["pricelist"])
product_id = self._get_cheapest_info(pricelist)[0]
product = self.env["product.product"].browse(product_id)
# Rebuild the combination in the expected order
res = self.env["product.template.attribute.value"]
for line in product.valid_product_template_attribute_line_ids:
value = product.product_template_attribute_value_ids.filtered(
lambda x: x in line.product_template_value_ids
)
if not value:
value = line.product_template_value_ids[:1]
res += value
return res
| 45.324561 | 5,167 |
3,636 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import http
from odoo.http import request
from odoo.addons.sale.controllers.variant import VariantController
class WebsiteSaleVariantController(VariantController):
@http.route(
["/sale/get_combination_info_minimal_price"],
type="json",
auth="public",
methods=["POST"],
website=True,
)
def get_combination_info_minimal_price(self, product_template_ids, **kw):
"""Special route to use website logic in get_combination_info override.
This route is called in JS by appending _website to the base route.
"""
res = []
templates = request.env["product.template"].sudo().browse(product_template_ids)
pricelist = request.env["website"].get_current_website().get_current_pricelist()
for template in templates.filtered(lambda t: t.is_published):
product_id, add_qty, has_distinct_price = template._get_cheapest_info(
pricelist
)
combination = template._get_combination_info(
product_id=product_id, add_qty=add_qty, pricelist=pricelist
)
res.append(
{
"id": template.id,
"price": combination.get("price"),
"distinct_prices": has_distinct_price,
"currency": {
"position": template.currency_id.position,
"symbol": template.currency_id.symbol,
},
}
)
return res
@http.route(
["/sale/get_combination_info_pricelist_atributes"],
type="json",
auth="public",
website=True,
)
def get_combination_info_pricelist_atributes(self, product_id, **kwargs):
"""Special route to use website logic in get_combination_info override.
This route is called in JS by appending _website to the base route.
"""
pricelist = request.env["website"].get_current_website().get_current_pricelist()
product = (
request.env["product.product"]
.browse(product_id)
.with_context(pricelist=pricelist.id)
)
# Getting all min_quantity of the current product to compute the possible
# price scale.
qty_list = request.env["product.pricelist.item"].search(
[
"|",
("product_id", "=", product.id),
"|",
("product_tmpl_id", "=", product.product_tmpl_id.id),
(
"categ_id",
"in",
list(map(int, product.categ_id.parent_path.split("/")[0:-1])),
),
("min_quantity", ">", 0),
]
)
qty_list = sorted(set(qty_list.mapped("min_quantity")))
res = []
last_price = product.with_context(quantity=0).price
for min_qty in qty_list:
new_price = product.with_context(quantity=min_qty).price
if new_price != last_price:
res.append(
{
"min_qty": min_qty,
"price": new_price,
"currency": {
"position": product.currency_id.position,
"symbol": product.currency_id.symbol,
},
}
)
last_price = new_price
return (res, product.uom_name)
| 38.680851 | 3,636 |
493 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Display product reference in e-commerce",
"version": "15.0.1.0.0",
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["website_sale"],
"data": ["views/website_sale_views.xml"],
}
| 35.214286 | 493 |
574 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Website Sale Comparison Hide Price",
"version": "15.0.1.0.0",
"category": "Website",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/e-commerce",
"license": "AGPL-3",
"summary": "Hide product prices on the shop",
"depends": ["website_sale_hide_price", "website_sale_comparison"],
"data": ["views/website_sale_template.xml"],
"installable": True,
"auto_install": True,
}
| 38.266667 | 574 |
983 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Jairo Llopis - Tecnativa
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Alternative (un)taxed prices display on eCommerce",
"summary": "Display prices with(out) taxes in eCommerce, complementing normal mode",
"version": "15.0.1.1.0",
"development_status": "Production/Stable",
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, Odoo Community Association (OCA)",
"maintainers": ["Yajo"],
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": ["website_sale"],
"data": ["templates/product.xml"],
"assets": {
"web.assets_frontend": [
"/website_sale_b2x_alt_price/static/src/js/product_configurator_mixin.esm.js",
],
"web.assets_tests": [
"/website_sale_b2x_alt_price/static/tours/b2b.js",
"/website_sale_b2x_alt_price/static/tours/b2c.js",
],
},
}
| 37.807692 | 983 |
6,684 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Jairo Llopis - Tecnativa
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo.tests.common import Form, HttpCase
class UICase(HttpCase):
def setUp(self):
super().setUp()
# Create and select a pricelist
# to make tests pass no matter what l10n package is enabled
website = self.env["website"].get_current_website()
pricelist = self.env["product.pricelist"].create(
{
"name": "website_sale_b2x_alt_price public",
"currency_id": website.user_id.company_id.currency_id.id,
"selectable": True,
}
)
website.user_id.property_product_pricelist = pricelist
admin = self.env.ref("base.user_admin")
admin.property_product_pricelist = pricelist
# Create some demo taxes
self.tax_group_22 = self.env["account.tax.group"].create(
{"name": "Tax group 22%"}
)
self.tax_22_sale = self.env["account.tax"].create(
{
"amount_type": "percent",
"amount": 22,
"description": "22%",
"name": "Tax sale 22%",
"tax_group_id": self.tax_group_22.id,
"type_tax_use": "sale",
}
)
self.tax_22_purchase = self.env["account.tax"].create(
{
"amount_type": "percent",
"amount": 22,
"description": "22%",
"name": "Tax purchase 22%",
"tax_group_id": self.tax_group_22.id,
"type_tax_use": "purchase",
}
)
# Create one product without taxes
self.training_accounting = self.env["product.template"].create(
{
"name": "Training on accounting - website_sale_b2x_alt_price",
"list_price": 100,
"type": "service",
"website_published": True,
"uom_id": self.ref("uom.product_uom_unit"),
"uom_po_id": self.ref("uom.product_uom_unit"),
"taxes_id": [(5, 0, 0)],
"supplier_taxes_id": [(5, 0, 0)],
}
)
# One product with taxes
self.pen = self.env["product.template"].create(
{
"name": "Pen - website_sale_b2x_alt_price",
"list_price": 5,
"type": "consu",
"website_published": True,
"uom_id": self.ref("uom.product_uom_unit"),
"uom_po_id": self.ref("uom.product_uom_unit"),
"description_sale": "Best. Pen. Ever.",
"taxes_id": [(6, 0, [self.tax_22_sale.id])],
"supplier_taxes_id": [(6, 0, [self.tax_22_purchase.id])],
}
)
# One product with taxes and variants
self.notebook = self.env["product.template"].create(
{
"name": "Notebook - website_sale_b2x_alt_price",
"list_price": 3,
"type": "consu",
"website_published": True,
"uom_id": self.ref("uom.product_uom_unit"),
"uom_po_id": self.ref("uom.product_uom_unit"),
"description_sale": "Best. Notebook. Ever.",
"taxes_id": [(6, 0, [self.tax_22_sale.id])],
"supplier_taxes_id": [(6, 0, [self.tax_22_purchase.id])],
}
)
self.sheet_size = self.env["product.attribute"].create(
{"name": "Sheet size", "create_variant": "always"}
)
self.sheet_size_a4 = self.env["product.attribute.value"].create(
{"name": "A4", "attribute_id": self.sheet_size.id, "sequence": 20}
)
self.sheet_size_a5 = self.env["product.attribute.value"].create(
{"name": "A5", "attribute_id": self.sheet_size.id, "sequence": 10}
)
self.notebook_attline = self.env["product.template.attribute.line"].create(
{
"product_tmpl_id": self.notebook.id,
"attribute_id": self.sheet_size.id,
"value_ids": [(6, 0, [self.sheet_size_a4.id, self.sheet_size_a5.id])],
}
)
self.notebook_size_a4 = self.notebook_attline.product_template_value_ids[1]
self.notebook_size_a5 = self.notebook_attline.product_template_value_ids[0]
self.notebook_a4 = self.notebook._get_variant_for_combination(
self.notebook_size_a4
)
self.notebook_a4.write(
{"default_code": "NB_A4", "product_tmpl_id": self.notebook.id}
)
self.notebook_a5 = self.notebook._get_variant_for_combination(
self.notebook_size_a5
)
self.notebook_a5.write(
{"default_code": "NB_A5", "product_tmpl_id": self.notebook.id}
)
# A4 notebook is slightly more expensive
self.notebook_a4.product_template_attribute_value_ids.price_extra = 0.5
# Create a pricelist selectable from website with 10% discount
self.discount_pricelist = self.env["product.pricelist"].create(
{
"name": "website_sale_b2x_alt_price discounted",
"discount_policy": "without_discount",
"selectable": True,
"item_ids": [
(
0,
0,
{
"applied_on": "3_global",
"compute_price": "percentage",
"percent_price": 10,
},
),
],
}
)
def _switch_tax_mode(self, mode):
assert mode in {"tax_excluded", "tax_included"}
config = Form(self.env["res.config.settings"])
config.show_line_subtotals_tax_selection = mode
config.group_product_pricelist = True
config.product_pricelist_setting = "advanced"
config.group_discount_per_so_line = True
config = config.save()
config.execute()
def test_ui_website_b2b(self):
"""Test frontend b2b tour."""
self._switch_tax_mode("tax_excluded")
self.start_tour(
"/shop?search=website_sale_b2x_alt_price",
"website_sale_b2x_alt_price_b2b",
login="admin",
)
def test_ui_website_b2c(self):
"""Test frontend b2c tour."""
self._switch_tax_mode("tax_included")
self.start_tour(
"/shop?search=website_sale_b2x_alt_price",
"website_sale_b2x_alt_price_b2c",
login="admin",
)
| 40.26506 | 6,684 |
2,548 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Jairo Llopis - Tecnativa
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import models
class ProductTemplate(models.Model):
_inherit = "product.template"
def _get_combination_info(
self,
combination=False,
product_id=False,
add_qty=1,
pricelist=False,
parent_combination=False,
only_template=False,
):
"""Include alternative (un)taxed amount."""
combination_info = super()._get_combination_info(
combination=combination,
product_id=product_id,
add_qty=add_qty,
pricelist=pricelist,
parent_combination=parent_combination,
only_template=only_template,
)
website = self.env["website"].get_current_website(fallback=False)
if not website:
return combination_info
partner = self.env.user.partner_id
company_id = website.company_id
pricelist = pricelist or website.get_current_pricelist()
product = (
self.env["product.product"].browse(combination_info["product_id"]) or self
)
# The list_price is always the price of one.
quantity_1 = 1
# Obtain the inverse field of the normal b2b/b2c behavior
alt_field = (
"total_included"
if self.env.user.has_group("account.group_show_line_subtotals_tax_excluded")
else "total_excluded"
)
# Obtain taxes that apply to the product and context
taxes = partner.property_account_position_id.map_tax(
product.sudo().taxes_id.filtered(lambda x: x.company_id == company_id)
).with_context(force_price_include=alt_field == "total_excluded")
# Obtain alt prices
# TODO Cache upstream calls to compute_all() and get results from there
alt_list_price = alt_price = taxes.compute_all(
combination_info["price"],
pricelist.currency_id,
quantity_1,
product,
partner,
)[alt_field]
if combination_info.get("has_discounted_price"):
alt_list_price = taxes.compute_all(
combination_info["list_price"],
pricelist.currency_id,
quantity_1,
product,
partner,
)[alt_field]
combination_info.update(
alt_price=alt_price, alt_list_price=alt_list_price, alt_field=alt_field
)
return combination_info
| 36.927536 | 2,548 |
840 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Website Sale Product Cart Quantity",
"summary": "Allows to add to cart from product items a custom quantity.",
"version": "15.0.1.0.0",
"website": "https://github.com/OCA/e-commerce",
"maintainers": ["CarlosRoca13"],
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["website_sale"],
"data": ["views/templates.xml"],
"assets": {
"web.assets_frontend": [
"/website_sale_product_item_cart_custom_qty/static/src/scss/add_to_cart.scss"
],
"web.assets_tests": [
"/website_sale_product_item_cart_custom_qty/static/src/js/tour.js"
],
},
}
| 36.521739 | 840 |
699 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import HttpCase, tagged
@tagged("post_install", "-at_install")
class TestWebsiteSaleProductItemCartCustomQty(HttpCase):
def setUp(self):
super().setUp()
view = self.env.ref("website_sale.products_add_to_cart")
view.active = True
self.env["product.template"].create(
{"name": "Test Product", "is_published": True, "website_sequence": 1}
)
def test_ui_website(self):
"""Test frontend tour."""
self.start_tour(
"/shop", "website_sale_product_item_cart_custom_qty", login="admin"
)
| 34.95 | 699 |
674 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Google Tag Manager Enhanced Conversions",
"summary": "Add support for Google Tag Manager Enhanced Conversions",
"version": "15.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"category": "eCommerce",
"website": "https://github.com/OCA/e-commerce",
"depends": ["website_sale", "website_google_tag_manager"],
"data": ["views/res_config_settings_view.xml", "views/website_templates.xml"],
"images": ["static/description/website_google_tag_manager.png"],
}
| 44.933333 | 674 |
378 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
google_tag_manager_enhanced_conversions = fields.Boolean(
related="website_id.google_tag_manager_enhanced_conversions", readonly=False
)
| 34.363636 | 378 |
540 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Website(models.Model):
_inherit = "website"
google_tag_manager_enhanced_conversions = fields.Boolean(
string="Enhanced Conversions",
help="This will provide the necessary data in the confirmation page that GTM "
"needs to gather in order to be able to use Enhanced Conversions. The "
"template can be edited if more info is needed in the future.",
)
| 38.571429 | 540 |
574 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Alexandre D. Díaz
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Website Sale Attribute Filter Order",
"version": "15.0.1.0.0",
"category": "Website",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/e-commerce",
"license": "LGPL-3",
"summary": "Move active checkbox options to the first place of the list",
"depends": ["website_sale"],
"data": ["templates/website_sale.xml"],
"installable": True,
"maintainers": ["Tardo"],
}
| 38.2 | 573 |
795 |
py
|
PYTHON
|
15.0
|
# Copyright 2015 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright 2017 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "e-commerce required VAT",
"summary": "VAT number required in checkout form",
"version": "15.0.1.0.0",
"category": "Website",
"author": "Agile Business Group, Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/e-commerce",
"license": "AGPL-3",
"depends": ["website_sale", "base_vat"],
"data": ["views/templates.xml"],
"installable": True,
"auto_install": False,
"assets": {
"web.assets_tests": [
"website_sale_vat_required/static/src/js/website_sale_vat_required.tour.js",
],
},
}
| 36.136364 | 795 |
567 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import HttpCase
class TestWebsiteSaleVatRequired(HttpCase):
def test_website_sale_vat_required(self):
self.env.user.partner_id.vat = False
self.browser_js(
url_path="/",
code="odoo.__DEBUG__.services['web_tour.tour']" ".run('shop_buy_product')",
ready="odoo.__DEBUG__.services['web_tour.tour']"
".tours.shop_buy_product.ready",
login="admin",
)
| 37.8 | 567 |
475 |
py
|
PYTHON
|
15.0
|
# Copyright 2015 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright 2017 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.addons.website_sale.controllers.main import WebsiteSale
class WebsiteSale(WebsiteSale):
def _get_mandatory_fields_billing(self, country_id=False):
result = super()._get_mandatory_fields_billing(country_id)
result.append("vat")
return result
| 39.583333 | 475 |
979 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Alexandre Díaz - Tecnativa S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import SUPERUSER_ID, api
from odoo.tools import config
def post_init_hook(cr, registry):
# This is here to not broke the tests. The idea:
# - XML changes in website are made using 'customize_show=True'
# - When Odoo is running in testing mode, we disable our changes
# - When run our test, we enable the changes and test it. (see test file)
#
# For the user it has no impact (only more customizable options in the website)
# For CI/CD avoids problems testing modules that removes/positioning elements
# that other modules uses in their tests.
if config["test_enable"] or config["test_file"]:
env = api.Environment(cr, SUPERUSER_ID, {})
env.ref("website_sale_suggest_create_account.cart").active = False
env.ref("website_sale_suggest_create_account.short_cart_summary").active = False
| 51.473684 | 978 |
744 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2015 Antiun Ingeniería, S.L.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
{
"name": "Suggest to create user account when buying",
"summary": "Suggest users to create an account when buying in the website",
"version": "15.0.1.0.1",
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, LasLabs, Odoo Community Association (OCA)",
"license": "LGPL-3",
"installable": True,
"depends": ["website_sale"],
"data": ["views/website_sale.xml"],
"assets": {
"web.assets_tests": [
"website_sale_suggest_create_account/static/tests/tours/checkout.js",
],
},
"post_init_hook": "post_init_hook",
}
| 37.15 | 743 |
911 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Alexandre Díaz - Tecnativa S.L.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import odoo.tests
@odoo.tests.tagged("post_install", "-at_install")
class TestUi(odoo.tests.HttpCase):
def test_01_shop_buy(self):
# Ensure that 'vat' is not empty for compatibility with
# website_sale_vat_required module
portal_user = self.env.ref("base.demo_user0")
if not portal_user.partner_id.vat:
portal_user.partner_id.vat = "BE1234567"
current_website = self.env["website"].get_current_website()
current_website.auth_signup_uninvited = "b2b"
self.env.ref("website_sale_suggest_create_account.cart").active = True
self.env.ref(
"website_sale_suggest_create_account.short_cart_summary"
).active = True
self.start_tour("/shop", "shop_buy_checkout_suggest_account_website")
| 45.5 | 910 |
911 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Sergio Teruel <[email protected]>
# Copyright 2017 David Vidal <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Website Sale Checkout Skip Payment",
"summary": "Skip payment for logged users in checkout process",
"version": "15.0.1.2.0",
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": ["website_sale"],
"data": [
"views/website_sale_skip_payment.xml",
"views/website_sale_template.xml",
"views/partner_view.xml",
"views/res_config_settings_views.xml",
],
"assets": {
"web.assets_frontend": [
"website_sale_checkout_skip_payment/static/src/js/*.js",
],
},
}
| 33.740741 | 911 |
1,247 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from unittest.mock import Mock, patch
from odoo.tests.common import HttpCase
class WebsiteSaleHttpCase(HttpCase):
def setUp(self):
super().setUp()
# Active skip payment for Mitchel Admin
self.partner = self.env.ref("base.partner_admin")
self.partner.with_context(**{"res_partner_search_mode": "customer"}).write(
{"skip_website_checkout_payment": True}
)
def test_checkout_skip_payment(self):
website = self.env.ref("website.website2")
with patch(
"odoo.addons.website_sale_checkout_skip_payment.models.website.request",
new=Mock(),
) as request:
request.session.uid = False
self.assertFalse(website.checkout_skip_payment)
def test_ui_website(self):
"""Test frontend tour."""
tour = (
"odoo.__DEBUG__.services['web_tour.tour']",
"website_sale_checkout_skip_payment",
)
self.browser_js(
url_path="/shop",
code="%s.run('%s')" % tour,
ready="%s.tours['%s'].ready" % tour,
login="admin",
)
| 33.702703 | 1,247 |
391 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
website_sale_checkout_skip_message = fields.Text(
"Website Sale Checkout Skip Message",
related="website_id.website_sale_checkout_skip_message",
readonly=False,
)
| 30.076923 | 391 |
864 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Sergio Teruel <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import fields, models
from odoo.http import request
class Website(models.Model):
_inherit = "website"
website_sale_checkout_skip_message = fields.Text(
string="Website Sale SKip Message",
required=True,
default="Our team will check your order and send you payment information soon.",
)
checkout_skip_payment = fields.Boolean(compute="_compute_checkout_skip_payment")
def _compute_checkout_skip_payment(self):
for rec in self:
if request.session.uid:
rec.checkout_skip_payment = (
request.env.user.partner_id.skip_website_checkout_payment
)
else:
rec.checkout_skip_payment = False
| 34.56 | 864 |
288 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Sergio Teruel <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
skip_website_checkout_payment = fields.Boolean(default=False)
| 28.8 | 288 |
1,701 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Sergio Teruel <[email protected]>
# Copyright 2017 David Vidal <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import http
from odoo.http import request
from odoo.addons.payment.controllers.portal import PaymentPortal
from odoo.addons.website_sale.controllers.main import WebsiteSale
class CheckoutSkipPaymentWebsite(WebsiteSale):
@http.route()
def shop_payment_get_status(self, sale_order_id, **post):
# When skip payment step, the transaction not exists so only render
# the waiting message in ajax json call
if not request.website.checkout_skip_payment:
return super().shop_payment_get_status(sale_order_id, **post)
return {
"recall": True,
"message": request.website._render(
"website_sale_checkout_skip_payment.order_state_message"
),
}
class CheckoutSkipPayment(PaymentPortal):
@http.route()
def payment_confirm(self, tx_id, access_token, **kwargs):
if not request.website.checkout_skip_payment:
return super().payment_confirm(tx_id, access_token, **kwargs)
order = (
request.env["sale.order"]
.sudo()
.browse(request.session.get("sale_last_order_id"))
)
order.action_confirm()
try:
order._send_order_confirmation_mail()
except Exception:
return request.render(
"website_sale_checkout_skip_payment.confirmation_order_error"
)
request.website.sale_reset()
return request.render("website_sale.confirmation", {"order": order})
| 37.8 | 1,701 |
974 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-Today GRAP (http://www.grap.coop).
# @author Sylvain LE GAL <https://twitter.com/legalsylvain>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Product Multi Links (Template)",
"version": "15.0.1.0.0",
"category": "Generic Modules",
"author": "GRAP, ACSONE SA/NV, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/e-commerce",
"license": "AGPL-3",
"depends": ["sale"],
"data": [
"data/product_template_link_type.xml",
"security/product_template_link_type.xml",
"views/product_template_link_type.xml",
"security/ir.model.access.csv",
"views/action.xml",
"views/product_template_view.xml",
"views/product_template_link_view.xml",
"views/menu.xml",
"wizards/product_template_linker.xml",
],
"demo": ["demo/product_template_link_type.xml", "demo/product_template_link.xml"],
"installable": True,
}
| 37.461538 | 974 |
4,645 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestProductTemplateLink(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(
context=dict(
cls.env.context,
tracking_disable=True,
# compatibility flag when you run tests on a db
# where `product_variant_multi_link` is installed.
_product_variant_link_bypass_check=True,
)
)
cls.ProductTemplateLink = cls.env["product.template.link"]
cls.product_product_1 = cls.env.ref("product.product_product_1")
cls.product_product_2 = cls.env.ref("product.product_product_2")
cls.link_type = cls.env.ref(
"product_template_multi_link.product_template_link_type_cross_selling"
)
def test_01(self):
"""
Data:
- 2 publication templates
Test Case:
- Try to create 2 links of same type
Expected result:
- ValidationError is raised
"""
link1 = self.ProductTemplateLink.create(
{
"left_product_tmpl_id": self.product_product_1.id,
"right_product_tmpl_id": self.product_product_2.id,
"type_id": self.link_type.id,
}
)
with self.assertRaises(ValidationError), self.env.cr.savepoint():
link1.copy()
# create the same link but inverse ids
with self.assertRaises(ValidationError), self.env.cr.savepoint():
self.ProductTemplateLink.create(
{
"left_product_tmpl_id": self.product_product_2.id,
"right_product_tmpl_id": self.product_product_1.id,
"type_id": self.link_type.id,
}
)
def test_02(self):
"""
Data:
- 1 publication templates
Test Case:
- Try to create 1 link between the same product
Expected result:
- ValidationError is raised
"""
with self.assertRaises(ValidationError), self.env.cr.savepoint():
self.ProductTemplateLink.create(
{
"left_product_tmpl_id": self.product_product_1.id,
"right_product_tmpl_id": self.product_product_1.id,
"type_id": self.link_type.id,
}
)
def test_03(self):
"""
Data:
- 2 publication templates
Test Case:
- Create 1 link between the 2 products
Expected result:
- The link is visible from the 2 products
"""
link1 = self.ProductTemplateLink.create(
{
"left_product_tmpl_id": self.product_product_1.id,
"right_product_tmpl_id": self.product_product_2.id,
"type_id": self.link_type.id,
}
)
self.assertEqual(link1, self.product_product_1.product_template_link_ids)
self.assertEqual(link1, self.product_product_2.product_template_link_ids)
def test_04(self):
"""
Data:
- 2 publication templates
Test Case:
1 Create 1 link between the 2 products
2 Unlik the link
Expected result:
1 The link is visible from the 2 products
2 No link remains between the 2 products
This test check the cache invalidation of the computed fields on the
product.template
"""
link1 = self.ProductTemplateLink.create(
{
"left_product_tmpl_id": self.product_product_1.id,
"right_product_tmpl_id": self.product_product_2.id,
"type_id": self.link_type.id,
}
)
self.assertEqual(link1, self.product_product_1.product_template_link_ids)
self.assertEqual(link1, self.product_product_2.product_template_link_ids)
self.assertEqual(1, self.product_product_1.product_template_link_count)
self.assertEqual(1, self.product_product_2.product_template_link_count)
link1.unlink()
self.assertFalse(self.product_product_1.product_template_link_ids)
self.assertFalse(self.product_product_2.product_template_link_ids)
self.assertEqual(0, self.product_product_1.product_template_link_count)
self.assertEqual(0, self.product_product_2.product_template_link_count)
| 36.865079 | 4,645 |
9,700 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from psycopg2 import IntegrityError
from odoo.tests import TransactionCase
from odoo.tools import mute_logger
class TestProductTemplateLinkType(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.LinkType = cls.env["product.template.link.type"]
cls.link_type_cross_selling = cls.env.ref(
"product_template_multi_link.product_template_link_type_cross_selling"
)
cls.link_type_range = cls.env.ref(
"product_template_multi_link.product_template_link_type_demo_range"
)
cls.symmetric_link_without_code = cls.LinkType.create(
{"name": "symmetric_link_without_code"}
)
cls.symmetric_link_with_code = cls.LinkType.create(
{
"name": "symmetric_link_with_code-name",
"code": "symmetric_link_with_code-code",
}
)
cls.asymmetric_link_without_inverse_code = cls.LinkType.create(
{
"is_symmetric": False,
"name": "asymmetric_link_without_code-name",
"inverse_name": "asymmetric_link_without_code-inverse_name",
}
)
cls.asymmetric_link_with_inverse_code = cls.LinkType.create(
{
"is_symmetric": False,
"name": "asymmetric_link_with_code-name",
"inverse_name": "asymmetric_link_with_code-inverse_name",
"inverse_code": "asymmetric_link_with_code-inverse_code",
}
)
def test_0(self):
"""
Data:
None
Test case:
Create a link type by providing only the name
Expected Result:
by default link is symmetric
inverse_name is computed
inverse_name is equal to name
code is false (not provided)
inverse_code is false
"""
link_type = self.LinkType.create({"name": "my type"})
self.assertTrue(link_type.is_symmetric)
self.assertTrue(link_type.name)
self.assertEqual(link_type.name, link_type.inverse_name)
self.assertFalse(link_type.code)
self.assertFalse(link_type.inverse_code)
def test_1(self):
"""
Data:
None
Test case:
Create a link type by providing only the name and the code
Expected Result:
by default link is symmetric
inverse_name is computed
inverse_name is equal to name
inverse_code is computed
inverse_code is equal to code
"""
link_type = self.LinkType.create({"name": "my type", "code": "my-code"})
self.assertTrue(link_type.is_symmetric)
self.assertEqual(link_type.name, "my type")
self.assertEqual(link_type.code, "my-code")
self.assertEqual(link_type.name, link_type.inverse_name)
self.assertEqual(link_type.code, link_type.inverse_code)
@mute_logger("odoo.sql_db")
def test_2(self):
"""
Data:
None
Test case:
Create a link type without providing the name
Expected Result:
Exception is raised
"""
with self.assertRaises(IntegrityError), self.env.cr.savepoint():
self.LinkType.create(
{
"inverse_name": "my type",
"is_symmetric": False,
"code": "my_code",
"inverse_code": "my_inverse_code",
}
)
def test_3(self):
"""
Data:
An existing symmetric link type
Test case:
Update the name
Expected Result:
inverse_name is still equal to name
"""
self.assertEqual(
self.link_type_cross_selling.name, self.link_type_cross_selling.inverse_name
)
self.link_type_cross_selling.write({"name": "new name"})
self.assertEqual(self.link_type_cross_selling.name, "new name")
self.assertEqual(
self.link_type_cross_selling.name, self.link_type_cross_selling.inverse_name
)
def test_4(self):
"""
Data:
An existing symmetric link type
Test case:
Update the code
Expected Result:
inverse_code is still equal to code
"""
self.assertEqual(
self.link_type_cross_selling.code, self.link_type_cross_selling.inverse_code
)
self.link_type_cross_selling.write({"code": "new-code"})
self.assertEqual(self.link_type_cross_selling.code, "new-code")
self.assertEqual(
self.link_type_cross_selling.code, self.link_type_cross_selling.inverse_code
)
def test_5(self):
"""
Data:
An existing symmetric link type
Test case:
Update the inverse_name
Update the inverse_code
Expected Result:
inverse_name and inverse_code are not updated
"""
self.assertEqual(
self.link_type_cross_selling.name, self.link_type_cross_selling.inverse_name
)
self.assertEqual(
self.link_type_cross_selling.code, self.link_type_cross_selling.inverse_code
)
inverse_name = self.link_type_cross_selling.inverse_name
inverse_code = self.link_type_cross_selling.inverse_code
self.link_type_cross_selling.write(
{
"inverse_name": "new " + inverse_name,
"inverse_code": "new " + inverse_code,
}
)
self.assertEqual(self.link_type_cross_selling.inverse_name, inverse_name)
self.assertEqual(self.link_type_cross_selling.inverse_code, inverse_code)
def test_6(self):
"""
Data:
An existing symmetric link type
Test case:
Update the inverse_name with name != inverse_name,
code != inverse_code and make it asymmetric
Expected Result:
inverse_name is no more equal to name and
the code is not more equald to inverse_code
"""
self.assertEqual(
self.link_type_cross_selling.name, self.link_type_cross_selling.inverse_name
)
self.assertEqual(
self.link_type_cross_selling.code, self.link_type_cross_selling.inverse_code
)
self.link_type_cross_selling.write(
{
"is_symmetric": False,
"inverse_name": "new inverse name",
"inverse_code": "new inverse code",
}
)
self.assertEqual(self.link_type_cross_selling.inverse_name, "new inverse name")
self.assertEqual(self.link_type_cross_selling.inverse_code, "new inverse code")
def test_7(self):
"""
Data:
An existing asymmetric link with inverse_code != code
and inverse_name != name
Test case:
1 Make it symmetric
Expected Result:
invsere_code=code and inverse_name=name
"""
self.assertFalse(self.link_type_range.is_symmetric)
self.assertNotEqual(
self.link_type_range.name, self.link_type_range.inverse_name
)
self.assertNotEqual(
self.link_type_range.code, self.link_type_range.inverse_code
)
self.link_type_range.write({"is_symmetric": True})
self.assertEqual(self.link_type_range.name, self.link_type_range.inverse_name)
self.assertEqual(self.link_type_range.code, self.link_type_range.inverse_code)
@mute_logger("odoo.sql_db")
def test_8(self):
"""
Data:
symmetric link type without code
symmetric link with code
asymmetric link type without inverse_code
asymmetric link type with inverse_code
Test case:
1 create a new link type with the same name without code
1 create a new link type with the same name
1 create a new link type with the same code
1 create a new link type with the same inverse_name
Expected Result:
Intergrity Error
"""
with self.assertRaises(IntegrityError), self.env.cr.savepoint():
self.LinkType.create({"name": self.symmetric_link_without_code.name})
with self.assertRaises(IntegrityError), self.env.cr.savepoint():
self.LinkType.create(
{
"name": self.symmetric_link_with_code.name + "test_8",
"code": self.symmetric_link_with_code.code,
}
)
with self.assertRaises(IntegrityError), self.env.cr.savepoint():
inverse_name = self.asymmetric_link_without_inverse_code.inverse_name
self.LinkType.create(
{
"name": self.asymmetric_link_without_inverse_code.name + "test_8",
"inverse_name": inverse_name,
}
)
with self.assertRaises(IntegrityError), self.env.cr.savepoint():
self.LinkType.create(
{
"name": self.asymmetric_link_with_inverse_code.name + "test_8",
"inverse_name": self.asymmetric_link_with_inverse_code.inverse_name
+ "test_8",
"inverse_code": self.asymmetric_link_with_inverse_code.inverse_code,
}
)
| 37.022901 | 9,700 |
5,115 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestProductTemplateLinker(TransactionCase):
"""
Tests for product.template.linker
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.wizard_obj = cls.env["product.template.linker"]
cls.product_link_obj = cls.env["product.template.link"]
cls.cross_sell = cls.env.ref(
"product_template_multi_link.product_template_link_type_cross_selling"
)
cls.up_sell = cls.env.ref(
"product_template_multi_link.product_template_link_type_up_selling"
)
cls.product1 = cls.env.ref("product.product_product_25").product_tmpl_id
cls.product2 = cls.env.ref("product.product_product_5").product_tmpl_id
cls.product3 = cls.env.ref("product.product_product_27").product_tmpl_id
cls.products = cls.product1 | cls.product2 | cls.product3
cls.products.mapped("product_template_link_ids").unlink()
def _launch_wizard(self, products, operation_type, link_type=None):
"""
:param products: product.template recordset
:return: product.template.linker recordset
"""
link_type = link_type or self.env["product.template.link.type"].browse()
values = {
"operation_type": operation_type,
"type_id": link_type.id,
"product_ids": [(6, False, products.ids)],
}
return self.wizard_obj.create(values)
def _test_link_created(self, links, link_type):
for link in links:
source_product = link.left_product_tmpl_id
linked_products = source_product.product_template_link_ids
full_links = (
linked_products.mapped("left_product_tmpl_id")
| linked_products.mapped("right_product_tmpl_id")
) - source_product
expected_products_linked = self.products - source_product
self.assertEqual(set(expected_products_linked.ids), set(full_links.ids))
self.assertEqual(link_type, link.type_id)
def test_wizard_link_cross_sell(self):
link_type = self.cross_sell
wizard = self._launch_wizard(
self.products, operation_type="link", link_type=link_type
)
links = wizard.action_apply_link()
self._test_link_created(links, link_type)
def test_wizard_link_up_sell(self):
link_type = self.up_sell
wizard = self._launch_wizard(
self.products, operation_type="link", link_type=link_type
)
links = wizard.action_apply_link()
self._test_link_created(links, link_type)
def test_wizard_link_duplicate1(self):
link_type = self.up_sell
wizard = self._launch_wizard(
self.products, operation_type="link", link_type=link_type
)
self.product_link_obj.create(
{
"left_product_tmpl_id": self.product1.id,
"right_product_tmpl_id": self.product2.id,
"type_id": link_type.id,
}
)
links = wizard.action_apply_link()
self._test_link_created(links, link_type)
# Ensure no duplicates
link = self.product1.product_template_link_ids.filtered(
lambda l: l.right_product_tmpl_id == self.product2
)
self.assertEqual(1, len(link))
def test_wizard_link_duplicate2(self):
link_type = self.cross_sell
wizard = self._launch_wizard(
self.products, operation_type="link", link_type=link_type
)
self.product_link_obj.create(
{
"left_product_tmpl_id": self.product1.id,
"right_product_tmpl_id": self.product2.id,
"type_id": self.up_sell.id,
}
)
links = wizard.action_apply_link()
self._test_link_created(links, link_type)
# Ensure no duplicates
link = self.product1.product_template_link_ids.filtered(
lambda l: l.right_product_tmpl_id == self.product2
or l.left_product_tmpl_id == self.product2
)
# 2 because we have up_sell and cross_sell
self.assertEqual(2, len(link))
def test_wizard_unlink(self):
wizard = self._launch_wizard(self.products, operation_type="unlink")
self.product_link_obj.create(
{
"left_product_tmpl_id": self.product1.id,
"right_product_tmpl_id": self.product2.id,
"type_id": self.up_sell.id,
}
)
self.product_link_obj.create(
{
"left_product_tmpl_id": self.product1.id,
"right_product_tmpl_id": self.product3.id,
"type_id": self.cross_sell.id,
}
)
wizard.action_apply_unlink()
self.assertFalse(self.product1.product_template_link_ids)
| 39.346154 | 5,115 |
3,627 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ProductTemplateLinkType(models.Model):
_name = "product.template.link.type"
_description = "Product Template Link Type"
name = fields.Char(required=True, translate=True)
inverse_name = fields.Char(
compute="_compute_inverse_name",
inverse="_inverse_inverse_name",
readonly=False,
store=True,
translate=True,
)
manual_inverse_name = fields.Char()
is_symmetric = fields.Boolean(
help="The relation meaning is the same from each side of the relation",
default=True,
)
code = fields.Char(
"Technical code",
help="This code allows to provide a technical code to external"
"systems identifying this link type",
)
inverse_code = fields.Char(
"Technical code (inverse)",
compute="_compute_inverse_code",
inverse="_inverse_inverse_code",
readonly=False,
store=True,
help="This code allows to provide a technical code to external"
"systems identifying this link type",
)
manual_inverse_code = fields.Char()
_sql_constraints = [
("name_uniq", "unique (name)", "Link type name already exists !"),
(
"inverse_name_uniq",
"unique (inverse_name)",
"Link type inverse name already exists !",
),
(
"code_uniq",
"EXCLUDE (code WITH =) WHERE (code is not null)",
"Link code already exists !",
),
(
"inverse_code_uniq",
"EXCLUDE (inverse_code WITH =) WHERE (inverse_code is not null)",
"Link inverse code already exists !",
),
]
display_name = fields.Char(compute="_compute_display_name")
def _inverse_inverse_name(self):
for record in self:
record.manual_inverse_name = record.inverse_name
def _inverse_inverse_code(self):
for record in self:
record.manual_inverse_code = record.inverse_code
@api.depends("name", "inverse_name")
def _compute_display_name(self):
for record in self:
display_name = record.name
if not record.is_symmetric:
display_name = "{} / {}".format(record.inverse_name, record.name)
record.display_name = display_name
@api.depends("name", "is_symmetric")
def _compute_inverse_name(self):
for record in self:
if record.is_symmetric:
record.inverse_name = record.name
else:
record.inverse_name = record.manual_inverse_name
@api.depends("code", "is_symmetric")
def _compute_inverse_code(self):
for record in self:
if record.is_symmetric:
record.inverse_code = record.code
else:
record.inverse_code = record.manual_inverse_code
def write(self, vals):
if not self:
return True
r = True
for record in self:
is_symmetric = vals.get("is_symmetric", record.is_symmetric)
v = vals.copy()
if is_symmetric:
v.pop("inverse_code", None)
v.pop("inverse_name", None)
r = super(ProductTemplateLinkType, record).write(v)
return r
def get_by_code(self, code):
"""Get link matching given code.
Just a shortcut for a search that can be done very often.
"""
return self.search([("code", "=", code)], limit=1)
| 32.675676 | 3,627 |
3,684 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-Today GRAP (http://www.grap.coop).
# @author Sylvain LE GAL <https://twitter.com/legalsylvain>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from collections import defaultdict
from odoo import _, api, fields, models
from odoo.exceptions import AccessError
class ProductTemplate(models.Model):
_inherit = "product.template"
product_template_link_ids = fields.One2many(
string="Product Links",
comodel_name="product.template.link",
compute="_compute_product_link_ids",
)
product_template_link_count = fields.Integer(
string="Product Links Count", compute="_compute_product_template_link_count"
)
def _compute_product_link_ids(self):
link_model = self.env["product.template.link"]
domain = [
"|",
("left_product_tmpl_id", "in", self.ids),
("right_product_tmpl_id", "in", self.ids),
]
links = link_model.search(domain)
links_by_product_id = defaultdict(set)
for link in links:
links_by_product_id[link.left_product_tmpl_id.id].add(link.id)
links_by_product_id[link.right_product_tmpl_id.id].add(link.id)
for record in self:
record.product_template_link_ids = self.env["product.template.link"].browse(
list(links_by_product_id[record.id])
)
@api.depends("product_template_link_ids")
def _compute_product_template_link_count(self):
link_model = self.env["product.template.link"]
# Set product_template_link_qty to 0 if user has no access on the model
try:
link_model.check_access_rights("read")
except AccessError:
for rec in self:
rec.product_template_link_count = 0
return
domain = [
"|",
("left_product_tmpl_id", "in", self.ids),
("right_product_tmpl_id", "in", self.ids),
]
res_1 = link_model.read_group(
domain=domain,
fields=["left_product_tmpl_id"],
groupby=["left_product_tmpl_id"],
)
res_2 = link_model.read_group(
domain=domain,
fields=["right_product_tmpl_id"],
groupby=["right_product_tmpl_id"],
)
link_dict = {}
for dic in res_1:
link_id = dic["left_product_tmpl_id"][0]
link_dict.setdefault(link_id, 0)
link_dict[link_id] += dic["left_product_tmpl_id_count"]
for dic in res_2:
link_id = dic["right_product_tmpl_id"][0]
link_dict.setdefault(link_id, 0)
link_dict[link_id] += dic["right_product_tmpl_id_count"]
for rec in self:
rec.product_template_link_count = link_dict.get(rec.id, 0)
def show_product_template_links(self):
self.ensure_one()
return {
"name": _("Product links"),
"type": "ir.actions.act_window",
"view_mode": "tree,form",
"res_model": "product.template.link",
"domain": [
"|",
("left_product_tmpl_id", "=", self.id),
("right_product_tmpl_id", "=", self.id),
],
"context": {
"search_default_groupby_type": True,
"default_left_product_tmpl_id": self.id,
},
}
def get_links_by_code(self, code):
"""Get all active active links maching code for current product."""
self.ensure_one()
return self.product_template_link_ids.filtered(
lambda r: r.type_id.code == code and r.is_link_active
)
| 35.085714 | 3,684 |
5,698 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-Today GRAP (http://www.grap.coop).
# @author Sylvain LE GAL <https://twitter.com/legalsylvain>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from contextlib import contextmanager
from psycopg2.extensions import AsIs
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ProductTemplateLink(models.Model):
_name = "product.template.link"
_order = "left_product_tmpl_id, right_product_tmpl_id"
_description = "Product link"
left_product_tmpl_id = fields.Many2one(
string="Source Product",
comodel_name="product.template",
required=True,
ondelete="cascade",
index=True,
)
right_product_tmpl_id = fields.Many2one(
string="Linked Product",
comodel_name="product.template",
required=True,
ondelete="cascade",
index=True,
)
type_id = fields.Many2one(
string="Link type",
comodel_name="product.template.link.type",
required=True,
ondelete="restrict",
index=True,
)
link_type_name = fields.Char(related="type_id.name") # left to right
link_type_inverse_name = fields.Char(
related="type_id.inverse_name"
) # right to left
is_link_active = fields.Boolean(compute="_compute_is_link_active")
def _compute_is_link_active(self):
# Hook here to define your own logic
for record in self:
record.is_link_active = True
@api.constrains("left_product_tmpl_id", "right_product_tmpl_id", "type_id")
def _check_products(self):
"""Verify links between products.
Check whether:
- the two products are different
- there is only one link between the same two templates for the same type
:raise: ValidationError if not ok
"""
self.flush() # flush required since the method uses plain sql
if any(rec._check_product_not_different() for rec in self):
raise ValidationError(
_("You can only create a link between 2 different products")
)
products = self.mapped("left_product_tmpl_id") + self.mapped(
"right_product_tmpl_id"
)
query, query_args = self._check_products_query(products)
self.env.cr.execute(query, query_args)
res = self.env.cr.fetchall()
is_duplicate_by_link_id = dict(res)
if True in is_duplicate_by_link_id.values():
ids = [k for k, v in is_duplicate_by_link_id.items() if v]
descrs = "\n ".join(
[link._duplicate_link_error_msg() for link in self.browse(ids)]
)
raise ValidationError(
_(
"Only one link with the same type is allowed between 2 "
"products. \n %s"
)
% descrs
)
def _check_product_not_different(self):
return self.left_product_tmpl_id == self.right_product_tmpl_id
def _check_products_query(self, products):
query = """
SELECT
id,
l2.duplicate or l3.duplicate
FROM (
SELECT
{main_select_columns}
FROM
%s
WHERE
left_product_tmpl_id in %s
AND right_product_tmpl_id in %s
) as l1
LEFT JOIN LATERAL (
SELECT
TRUE as duplicate
FROM
%s
WHERE
{l2_join_where_clause}
) l2 ON TRUE
LEFT JOIN LATERAL (
SELECT
TRUE as duplicate
FROM
%s
WHERE
{l3_join_where_clause}
) l3 ON TRUE
""".format(
**self._check_products_query_params()
)
query_args = (
AsIs(self._table),
tuple(products.ids),
tuple(products.ids),
AsIs(self._table),
AsIs(self._table),
)
return query, query_args
def _check_products_query_params(self):
return dict(
main_select_columns="""
id,
left_product_tmpl_id,
right_product_tmpl_id,
type_id
""",
l2_join_where_clause="""
right_product_tmpl_id = l1.left_product_tmpl_id
AND left_product_tmpl_id = l1.right_product_tmpl_id
AND type_id = l1.type_id
""",
l3_join_where_clause="""
left_product_tmpl_id = l1.left_product_tmpl_id
AND right_product_tmpl_id = l1.right_product_tmpl_id
AND type_id = l1.type_id
AND id != l1.id
""",
)
def _duplicate_link_error_msg(self):
return "{} <-> {} / {} <-> {}".format(
self.left_product_tmpl_id.name,
self.link_type_name,
self.link_type_inverse_name,
self.right_product_tmpl_id.name,
)
@contextmanager
def _invalidate_links_on_product_template(self):
yield
self._invalidate_links()
def _invalidate_links(self):
self.env["product.template"].invalidate_cache(["product_template_link_ids"])
@api.model_create_multi
def create(self, vals_list):
with self._invalidate_links_on_product_template():
return super().create(vals_list)
def write(self, vals):
with self._invalidate_links_on_product_template():
return super().write(vals)
| 32.747126 | 5,698 |
3,632 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class ProductTemplateLinker(models.TransientModel):
"""
Wizard used to link product template together in one shot
"""
_name = "product.template.linker"
_description = "Product template linker wizard"
operation_type = fields.Selection(
selection=[
("unlink", "Remove existing links"),
("link", "Link these products"),
],
string="Operation",
required=True,
help="Remove existing links: will remove every existing link "
"on each selected products;\n"
"Link these products: will link all selected "
"products together.",
)
product_ids = fields.Many2many(
comodel_name="product.template",
string="Products",
)
type_id = fields.Many2one(
string="Link type",
comodel_name="product.template.link.type",
ondelete="restrict",
)
@api.model
def default_get(self, fields_list):
"""Inherit default_get to auto-fill product_ids with current context
:param fields_list: list of str
:return: dict
"""
result = super().default_get(fields_list)
ctx = self.env.context
active_ids = ctx.get("active_ids", ctx.get("active_id", []))
products = []
if ctx.get("active_model") == self.product_ids._name and active_ids:
products = [(6, False, list(active_ids))]
result.update(
{
"product_ids": products,
}
)
return result
def action_apply(self):
if self.operation_type == "link":
self.action_apply_link()
elif self.operation_type == "unlink":
self.action_apply_unlink()
return {}
def action_apply_unlink(self):
"""Remove links from products.
:return: product.template.link recordset
"""
self.product_ids.mapped("product_template_link_ids").unlink()
return self.env["product.template.link"].browse()
def action_apply_link(self):
"""Add link to products.
:return: product.template.link recordset
"""
links = self.env["product.template.link"].browse()
for product in self.product_ids:
existing_links = product.product_template_link_ids.filtered(
lambda l: l.type_id == self.type_id
)
linked_products = existing_links.mapped(
"left_product_tmpl_id"
) | existing_links.mapped("right_product_tmpl_id")
products_to_link = self.product_ids - linked_products - product
links |= self._create_link(product, products_to_link)
return links
def _create_link(self, product_source, target_products):
"""Create the link between given product source and target products.
:param product_source: product.template recordset
:param target_products: product.template recordset
:return: product.template.link recordset
"""
self.ensure_one()
prod_link_obj = self.env["product.template.link"]
product_links = prod_link_obj.browse()
for target_product in target_products:
values = {
"left_product_tmpl_id": product_source.id,
"right_product_tmpl_id": target_product.id,
"type_id": self.type_id.id,
}
product_links |= prod_link_obj.create(values)
return product_links
| 34.590476 | 3,632 |
897 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Website Sale Hide Price",
"version": "15.0.1.3.0",
"category": "Website",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/e-commerce",
"license": "AGPL-3",
"summary": "Hide product prices on the shop",
"depends": ["website_sale"],
"data": [
"data/product_snippet_template_data.xml",
"views/partner_view.xml",
"views/product_template_views.xml",
"views/res_config_settings_views.xml",
"views/website_sale_template.xml",
],
"qweb": ["static/src/xml/website_sale_templates.xml"],
"installable": True,
"assets": {
"web.assets_frontend": [
"/website_sale_hide_price/static/src/js/website_sale_hide_price.js"
]
},
}
| 34.5 | 897 |
1,892 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
website_hide_price = fields.Boolean(string="Hide prices on website")
website_hide_price_message = fields.Text(
string="Hidden price message",
help="When the price is hidden on the website we can give the customer"
"some tips on how to find it out.",
translate=True,
)
def _get_combination_info(
self,
combination=False,
product_id=False,
add_qty=1,
pricelist=False,
parent_combination=False,
only_template=False,
):
combination_info = super()._get_combination_info(
combination=combination,
product_id=product_id,
add_qty=add_qty,
pricelist=pricelist,
parent_combination=parent_combination,
only_template=only_template,
)
combination_info.update(
{
"website_hide_price": self.website_hide_price,
"website_hide_price_message": self.website_hide_price_message,
}
)
return combination_info
def _search_render_results(self, fetch_fields, mapping, icon, limit):
"""Hide price on the search bar results"""
results_data = super()._search_render_results(
fetch_fields, mapping, icon, limit
)
for product, data in zip(self, results_data):
if product.website_hide_price:
data.update(
{
"price": "<span>%s</span>"
% (product.website_hide_price_message or ""),
"list_price": "",
}
)
return results_data
| 33.785714 | 1,892 |
374 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - David Vidal
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
website_hide_price_default_message = fields.Char(
related="website_id.website_hide_price_default_message",
readonly=False,
)
| 31.166667 | 374 |
712 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
from odoo.http import request
class Website(models.Model):
_inherit = "website"
website_show_price = fields.Boolean(compute="_compute_website_show_price")
website_hide_price_default_message = fields.Char(
string="Default Hidden price message",
help="When the price is hidden on the website we can give the customer"
"some tips on how to find it out.",
translate=True,
)
def _compute_website_show_price(self):
for rec in self:
rec.website_show_price = request.env.user.partner_id.website_show_price
| 33.904762 | 712 |
288 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
website_show_price = fields.Boolean(string="Show prices on website", default=True)
| 32 | 288 |
802 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Sergio Teruel <[email protected]>
# Copyright 2016-2017 Jairo Llopis <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Website Sale Checkout Country VAT",
"summary": "Autocomplete VAT in checkout process",
"version": "15.0.1.0.0",
"category": "Website",
"website": "https://github.com/OCA/e-commerce",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": ["base_vat", "website_sale", "website_snippet_country_dropdown"],
"data": ["views/templates.xml"],
"assets": {
"web.assets_frontend": [
"/website_sale_checkout_country_vat/static/src/js/dropdown.js"
]
},
}
| 36.454545 | 802 |
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 |
3,112 |
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-e-commerce",
description="Meta package for oca-e-commerce Odoo addons",
version=version,
install_requires=[
'odoo-addon-product_template_multi_link>=15.0dev,<15.1dev',
'odoo-addon-website_sale_b2x_alt_price>=15.0dev,<15.1dev',
'odoo-addon-website_sale_cart_expire>=15.0dev,<15.1dev',
'odoo-addon-website_sale_checkout_country_vat>=15.0dev,<15.1dev',
'odoo-addon-website_sale_checkout_skip_payment>=15.0dev,<15.1dev',
'odoo-addon-website_sale_comparison_hide_price>=15.0dev,<15.1dev',
'odoo-addon-website_sale_google_tag_manager>=15.0dev,<15.1dev',
'odoo-addon-website_sale_hide_empty_category>=15.0dev,<15.1dev',
'odoo-addon-website_sale_hide_price>=15.0dev,<15.1dev',
'odoo-addon-website_sale_invoice_address>=15.0dev,<15.1dev',
'odoo-addon-website_sale_order_type>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_assortment>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_attachment>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_attribute_filter_category>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_attribute_filter_collapse>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_attribute_filter_order>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_attribute_value_filter_existing>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_brand>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_description>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_detail_attribute_image>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_detail_attribute_value_image>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_item_cart_custom_qty>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_minimal_price>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_reference_displayed>=15.0dev,<15.1dev',
'odoo-addon-website_sale_product_sort>=15.0dev,<15.1dev',
'odoo-addon-website_sale_require_legal>=15.0dev,<15.1dev',
'odoo-addon-website_sale_require_login>=15.0dev,<15.1dev',
'odoo-addon-website_sale_secondary_unit>=15.0dev,<15.1dev',
'odoo-addon-website_sale_stock_available>=15.0dev,<15.1dev',
'odoo-addon-website_sale_stock_list_preview>=15.0dev,<15.1dev',
'odoo-addon-website_sale_stock_provisioning_date>=15.0dev,<15.1dev',
'odoo-addon-website_sale_suggest_create_account>=15.0dev,<15.1dev',
'odoo-addon-website_sale_tax_toggle>=15.0dev,<15.1dev',
'odoo-addon-website_sale_vat_required>=15.0dev,<15.1dev',
'odoo-addon-website_sale_wishlist_archive_cron>=15.0dev,<15.1dev',
'odoo-addon-website_sale_wishlist_keep>=15.0dev,<15.1dev',
'odoo-addon-website_snippet_product_category>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 57.62963 | 3,112 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.