size
int64 0
304k
| ext
stringclasses 1
value | lang
stringclasses 1
value | branch
stringclasses 1
value | content
stringlengths 0
304k
| avg_line_length
float64 0
238
| max_line_length
int64 0
304k
|
|---|---|---|---|---|---|---|
1,102
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import registry, SUPERUSER_ID
from odoo.api import Environment
from odoo.addons.bus.controllers import main
from odoo.fields import Datetime
from odoo.http import Controller, request, route
class BusController(main.BusController):
@route('/longpolling/poll', type="json", auth="public")
def poll(self, channels, last, options=None):
if request.env.user.has_group('base.group_user'):
ip_address = request.httprequest.remote_addr
users_log = request.env['res.users.log'].search_count([
('create_uid', '=', request.env.user.id),
('ip', '=', ip_address),
('create_date', '>=', Datetime.to_string(Datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)))])
if not users_log:
with registry(request.env.cr.dbname).cursor() as cr:
env = Environment(cr, request.env.user.id, {})
env['res.users.log'].create({'ip': ip_address})
return super(BusController, self).poll(channels, last, options=options)
| 45.916667
| 1,102
|
545
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Website Events CRM',
'version': '1.0',
'category': 'Website/Website',
'website': 'https://www.odoo.com/app/events',
'description': "Allow per-order lead creation mode",
'depends': ['event_crm', 'website_event'],
'data': [
'views/event_lead_rule_views.xml',
],
'demo': [
'data/event_crm_demo.xml',
],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 27.25
| 545
|
1,052
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Indonesian - Accounting',
'version': '1.0',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the latest Indonesian Odoo localisation necessary to run Odoo accounting for SMEs with:
=================================================================================================
- generic Indonesian chart of accounts
- tax structure""",
'author': 'vitraining.com',
'website': 'http://www.vitraining.com',
'depends': ['account', 'base_iban', 'base_vat', 'l10n_multilang'],
'data': [
'data/account_chart_template_data.xml',
'data/account.account.template.csv',
'data/account_chart_template_post_data.xml',
'data/account_tax_template_data.xml',
'data/account_chart_template_configuration_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'post_init_hook': 'load_translations',
'license': 'LGPL-3',
}
| 37.571429
| 1,052
|
592
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'PayuLatam Payment Acquirer',
'version': '2.0',
'category': 'Accounting/Payment Acquirers',
'sequence': 370,
'summary': 'Payment Acquirer: PayuLatam Implementation',
'description': """Payulatam payment acquirer""",
'depends': ['payment'],
'data': [
'views/payment_views.xml',
'views/payment_payulatam_templates.xml',
'data/payment_acquirer_data.xml',
],
'application': True,
'uninstall_hook': 'uninstall_hook',
'license': 'LGPL-3',
}
| 31.157895
| 592
|
10,384
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from freezegun import freeze_time
from odoo.exceptions import ValidationError
from odoo.fields import Command
from odoo.tests import tagged
from odoo.tests.common import HttpCase
from odoo.tools import mute_logger
from .common import PayULatamCommon
from ..controllers.main import PayuLatamController
from ..models.payment_acquirer import SUPPORTED_CURRENCIES
@tagged('post_install', '-at_install')
class PayULatamTest(PayULatamCommon, HttpCase):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super(PayULatamTest, cls).setUpClass(chart_template_ref=chart_template_ref)
# typical data posted by payulatam after client has successfully paid
cls.payulatam_post_confirmation_approved_data = {
'currency': cls.currency.name,
'reference_sale': cls.reference,
'response_message_pol': 'APPROVED',
'sign': '6b4728ddb01317af58f92b8accdb4a42',
'state_pol': '4',
'transaction_id': '7008bc34-8258-4857-b866-7d4d7982bd73',
'value': str(cls.amount)
}
cls.payulatam_post_confirmation_approved_data_webhook = cls.payulatam_post_confirmation_approved_data.copy()
cls.payulatam_post_confirmation_approved_data_webhook["sign"] = 'e227f90e64808320953dbbcb5ee96c9f'
def test_compatibility_with_supported_currencies(self):
""" Test that the PayULatam acquirer is compatible with all supported currencies. """
for supported_currency_code in SUPPORTED_CURRENCIES:
supported_currency = self._prepare_currency(supported_currency_code)
compatible_acquirers = self.env['payment.acquirer']._get_compatible_acquirers(
self.company.id, self.partner.id, currency_id=supported_currency.id,
)
self.assertIn(self.payulatam, compatible_acquirers)
def test_incompatibility_with_unsupported_currency(self):
""" Test that the PayULatam acquirer is not compatible with an unsupported currency. """
compatible_acquirers = self.env['payment.acquirer']._get_compatible_acquirers(
self.company.id, self.partner.id, currency_id=self.currency_euro.id,
)
self.assertNotIn(self.payulatam, compatible_acquirers)
@freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior
def test_reference_is_singularized(self):
""" Test singularization of reference prefixes. """
reference = self.env['payment.transaction']._compute_reference(self.payulatam.provider)
self.assertEqual(
reference, 'tx-20111102120021', "transaction reference was not correctly singularized"
)
@freeze_time('2011-11-02 12:00:21') # Freeze time for consistent singularization behavior
def test_reference_is_computed_based_on_document_name(self):
""" Test computation of reference prefixes based on the provided invoice. """
invoice = self.env['account.move'].create({})
reference = self.env['payment.transaction']._compute_reference(
self.payulatam.provider, invoice_ids=[Command.set([invoice.id])]
)
self.assertEqual(reference, 'MISC/2011/11/0001-20111102120021')
def test_redirect_form_values(self):
""" Test the values of the redirect form inputs. """
tx = self.create_transaction(flow='redirect')
with mute_logger('odoo.addons.payment.models.payment_transaction'):
processing_values = tx._get_processing_values()
form_info = self._extract_values_from_html_form(processing_values['redirect_form_html'])
expected_values = {
'merchantId': 'dummy',
'accountId': 'dummy',
'description': self.reference,
'referenceCode': self.reference,
'amount': str(self.amount),
'currency': self.currency.name,
'tax': str(0),
'taxReturnBase': str(0),
'buyerEmail': self.partner.email,
'buyerFullName': self.partner.name,
'responseUrl': self._build_url(PayuLatamController._return_url),
'confirmationUrl': self._build_url(PayuLatamController._webhook_url),
'test': str(1), # testing is always performed in test mode
}
expected_values['signature'] = self.payulatam._payulatam_generate_sign(
expected_values, incoming=False
)
self.assertEqual(
form_info['action'], 'https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/'
)
self.assertDictEqual(form_info['inputs'], expected_values)
def test_feedback_processing(self):
# typical data posted by payulatam after client has successfully paid
payulatam_post_data = {
'installmentsNumber': '1',
'lapPaymentMethod': 'VISA',
'description': self.reference,
'currency': self.currency.name,
'extra2': '',
'lng': 'es',
'transactionState': '7',
'polPaymentMethod': '211',
'pseCycle': '',
'pseBank': '',
'referenceCode': self.reference,
'reference_pol': '844164756',
'signature': 'f3ea3a7414a56d8153c425ab7e2f69d7', # Update me
'pseReference3': '',
'buyerEmail': 'admin@yourcompany.example.com',
'lapResponseCode': 'PENDING_TRANSACTION_CONFIRMATION',
'pseReference2': '',
'cus': '',
'orderLanguage': 'es',
'TX_VALUE': str(self.amount),
'risk': '',
'trazabilityCode': '',
'extra3': '',
'pseReference1': '',
'polTransactionState': '14',
'polResponseCode': '25',
'merchant_name': 'Test PayU Test comercio',
'merchant_url': 'http://pruebaslapv.xtrweb.com',
'extra1': '/shop/payment/validate',
'message': 'PENDING',
'lapPaymentMethodType': 'CARD',
'polPaymentMethodType': '7',
'telephone': '7512354',
'merchantId': 'dummy',
'transactionId': 'b232989a-4aa8-42d1-bace-153236eee791',
'authorizationCode': '',
'lapTransactionState': 'PENDING',
'TX_TAX': '.00',
'merchant_address': 'Av 123 Calle 12'
}
# should raise error about unknown tx
with self.assertRaises(ValidationError):
self.env['payment.transaction']._handle_feedback_data('payulatam', payulatam_post_data)
tx = self.create_transaction(flow='redirect')
# Validate the transaction ('pending' state)
self.env['payment.transaction']._handle_feedback_data('payulatam', payulatam_post_data)
self.assertEqual(tx.state, 'pending', 'Payulatam: wrong state after receiving a valid pending notification')
self.assertEqual(tx.state_message, payulatam_post_data['message'], 'Payulatam: wrong state message after receiving a valid pending notification')
self.assertEqual(tx.acquirer_reference, 'b232989a-4aa8-42d1-bace-153236eee791', 'Payulatam: wrong txn_id after receiving a valid pending notification')
# Reset the transaction
tx.write({
'state': 'draft',
'acquirer_reference': False})
# Validate the transaction ('approved' state)
payulatam_post_data['lapTransactionState'] = 'APPROVED'
self.env['payment.transaction']._handle_feedback_data('payulatam', payulatam_post_data)
self.assertEqual(tx.state, 'done', 'Payulatam: wrong state after receiving a valid pending notification')
self.assertEqual(tx.acquirer_reference, 'b232989a-4aa8-42d1-bace-153236eee791', 'Payulatam: wrong txn_id after receiving a valid pending notification')
@mute_logger('odoo.addons.payment_payulatam.controllers.main')
def test_confirmation_webhook_approved(self):
tx = self.create_transaction(flow='redirect')
self.assertEqual(tx.state, 'draft')
res = self.url_open(PayuLatamController._webhook_url,
self.payulatam_post_confirmation_approved_data_webhook)
self.assertEqual(res.status_code, 200, 'Should be OK')
self.assertEqual(res.text, '', "Body should be empty")
self.assertEqual(tx.state, 'done')
@mute_logger('odoo.addons.payment_payulatam.controllers.main')
def test_confirmation_webhook_approved_bad_signature(self):
tx = self.create_transaction(flow='redirect')
self.assertEqual(tx.state, 'draft')
post_data = self.payulatam_post_confirmation_approved_data
post_data['sign'] = "wrong signature"
res = self.url_open(PayuLatamController._webhook_url,
post_data)
self.assertEqual(res.status_code, 200, 'Should be OK')
self.assertEqual(tx.state, 'draft')
@mute_logger('odoo.addons.payment_payulatam.controllers.main')
def test_confirmation_webhook_declined(self):
tx = self.create_transaction(flow='redirect')
self.assertEqual(tx.state, 'draft')
post_data = self.payulatam_post_confirmation_approved_data
post_data['state_pol'] = '6'
post_data['response_message_pol'] = 'DECLINED'
post_data['sign'] = '28a1a45b1362a4096cf71357204e0256'
res = self.url_open(PayuLatamController._webhook_url,
post_data)
self.assertEqual(res.status_code, 200, 'Should be OK')
self.assertEqual(res.text, '', "Body should be empty")
self.assertEqual(tx.state, 'cancel')
@mute_logger('odoo.addons.payment_payulatam.controllers.main')
def test_confirmation_webhook_expired(self):
tx = self.create_transaction(flow='redirect')
self.assertEqual(tx.state, 'draft')
post_data = self.payulatam_post_confirmation_approved_data
post_data['state_pol'] = '5'
post_data['response_message_pol'] = 'EXPIRED'
post_data['sign'] = '4d43432f81d68c046a14d44fa7e235da'
res = self.url_open(PayuLatamController._webhook_url,
post_data)
self.assertEqual(res.status_code, 200, 'Should be OK')
self.assertEqual(res.text, '', "Body should be empty")
self.assertEqual(tx.state, 'cancel')
| 47.2
| 10,384
|
642
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.payment.tests.common import PaymentCommon
class PayULatamCommon(PaymentCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.payulatam = cls._prepare_acquirer('payulatam', update_values={
'payulatam_account_id': 'dummy',
'payulatam_merchant_id': 'dummy',
'payulatam_api_key': 'dummy',
})
# Override default values
cls.acquirer = cls.payulatam
cls.currency = cls.currency_euro
| 32.1
| 642
|
6,935
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from werkzeug import urls
from odoo import _, api, models
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_repr
from odoo.addons.payment import utils as payment_utils
from odoo.addons.payment_payulatam.controllers.main import PayuLatamController
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
@api.model
def _compute_reference(self, provider, prefix=None, separator='-', **kwargs):
""" Override of payment to ensure that PayU Latam requirements for references are satisfied.
PayU Latam requirements for transaction are as follows:
- References must be unique at provider level for a given merchant account.
This is satisfied by singularizing the prefix with the current datetime. If two
transactions are created simultaneously, `_compute_reference` ensures the uniqueness of
references by suffixing a sequence number.
:param str provider: The provider of the acquirer handling the transaction
:param str prefix: The custom prefix used to compute the full reference
:param str separator: The custom separator used to separate the prefix from the suffix
:return: The unique reference for the transaction
:rtype: str
"""
if provider == 'payulatam':
if not prefix:
# If no prefix is provided, it could mean that a module has passed a kwarg intended
# for the `_compute_reference_prefix` method, as it is only called if the prefix is
# empty. We call it manually here because singularizing the prefix would generate a
# default value if it was empty, hence preventing the method from ever being called
# and the transaction from received a reference named after the related document.
prefix = self.sudo()._compute_reference_prefix(
provider, separator, **kwargs
) or None
prefix = payment_utils.singularize_reference_prefix(prefix=prefix, separator=separator)
return super()._compute_reference(provider, prefix=prefix, separator=separator, **kwargs)
def _get_specific_rendering_values(self, processing_values):
""" Override of payment to return Payulatam-specific rendering values.
Note: self.ensure_one() from `_get_processing_values`
:param dict processing_values: The generic and specific processing values of the transaction
:return: The dict of acquirer-specific processing values
:rtype: dict
"""
res = super()._get_specific_rendering_values(processing_values)
if self.provider != 'payulatam':
return res
api_url = 'https://checkout.payulatam.com/ppp-web-gateway-payu/' \
if self.acquirer_id.state == 'enabled' \
else 'https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/'
payulatam_values = {
'merchantId': self.acquirer_id.payulatam_merchant_id,
'referenceCode': self.reference,
'description': self.reference,
'amount': float_repr(processing_values['amount'], self.currency_id.decimal_places or 2),
'tax': 0,
'taxReturnBase': 0,
'currency': self.currency_id.name,
'accountId': self.acquirer_id.payulatam_account_id,
'buyerFullName': self.partner_name,
'buyerEmail': self.partner_email,
'responseUrl': urls.url_join(self.get_base_url(), PayuLatamController._return_url),
'confirmationUrl': urls.url_join(self.get_base_url(), PayuLatamController._webhook_url),
'api_url': api_url,
}
if self.acquirer_id.state != 'enabled':
payulatam_values['test'] = 1
payulatam_values['signature'] = self.acquirer_id._payulatam_generate_sign(
payulatam_values, incoming=False
)
return payulatam_values
@api.model
def _get_tx_from_feedback_data(self, provider, data):
""" Override of payment to find the transaction based on Payulatam data.
:param str provider: The provider of the acquirer that handled the transaction
:param dict data: The feedback data sent by the provider
:return: The transaction if found
:rtype: recordset of `payment.transaction`
:raise: ValidationError if inconsistent data were received
:raise: ValidationError if the data match no transaction
:raise: ValidationError if the signature can not be verified
"""
tx = super()._get_tx_from_feedback_data(provider, data)
if provider != 'payulatam':
return tx
reference = data.get('referenceCode')
sign = data.get('signature')
if not reference or not sign:
raise ValidationError(
"PayU Latam: " + _(
"Received data with missing reference (%(ref)s) or sign (%(sign)s).",
ref=reference, sign=sign
)
)
tx = self.search([('reference', '=', reference), ('provider', '=', 'payulatam')])
if not tx:
raise ValidationError(
"PayU Latam: " + _("No transaction found matching reference %s.", reference)
)
# Verify signature
sign_check = tx.acquirer_id._payulatam_generate_sign(data, incoming=True)
if sign_check != sign:
raise ValidationError(
"PayU Latam: " + _(
"Invalid sign: received %(sign)s, computed %(check)s.",
sign=sign, check=sign_check
)
)
return tx
def _process_feedback_data(self, data):
""" Override of payment to process the transaction based on Payulatam data.
Note: self.ensure_one()
:param dict data: The feedback data sent by the provider
:return: None
"""
super()._process_feedback_data(data)
if self.provider != 'payulatam':
return
self.acquirer_reference = data.get('transactionId')
status = data.get('lapTransactionState')
state_message = data.get('message')
if status == 'PENDING':
self._set_pending(state_message=state_message)
elif status == 'APPROVED':
self._set_done(state_message=state_message)
elif status in ('EXPIRED', 'DECLINED'):
self._set_canceled(state_message=state_message)
else:
_logger.warning(
"received unrecognized payment state %s for transaction with reference %s",
status, self.reference
)
self._set_error("PayU Latam: " + _("Invalid payment status."))
| 43.892405
| 6,935
|
432
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class AccountPaymentMethod(models.Model):
_inherit = 'account.payment.method'
@api.model
def _get_payment_method_information(self):
res = super()._get_payment_method_information()
res['payulatam'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]}
return res
| 30.857143
| 432
|
4,094
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from hashlib import md5
from odoo import api, fields, models
from odoo.tools.float_utils import float_split, float_repr
SUPPORTED_CURRENCIES = ('ARS', 'BRL', 'CLP', 'COP', 'MXN', 'PEN', 'USD')
class PaymentAcquirer(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(
selection_add=[('payulatam', 'PayU Latam')], ondelete={'payulatam': 'set default'})
payulatam_merchant_id = fields.Char(
string="PayU Latam Merchant ID",
help="The ID solely used to identify the account with PayULatam",
required_if_provider='payulatam')
payulatam_account_id = fields.Char(
string="PayU Latam Account ID",
help="The ID solely used to identify the country-dependent shop with PayULatam",
required_if_provider='payulatam')
payulatam_api_key = fields.Char(
string="PayU Latam API Key", required_if_provider='payulatam',
groups='base.group_system')
@api.model
def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs):
""" Override of payment to unlist PayU Latam acquirers for unsupported currencies. """
acquirers = super()._get_compatible_acquirers(*args, currency_id=currency_id, **kwargs)
currency = self.env['res.currency'].browse(currency_id).exists()
if currency and currency.name not in SUPPORTED_CURRENCIES:
acquirers = acquirers.filtered(lambda a: a.provider != 'payulatam')
return acquirers
def _payulatam_generate_sign(self, values, incoming=True):
""" Generate the signature for incoming or outgoing communications.
:param dict values: The values used to generate the signature
:param bool incoming: Whether the signature must be generated for an incoming (PayU Latam to
Odoo) or outgoing (Odoo to PayU Latam) communication.
:return: The signature
:rtype: str
"""
if incoming:
# "Confirmation" and "Response" pages have a different way to calculate what they call the `new_value`
if self.env.context.get('payulatam_is_confirmation_page'):
# https://developers.payulatam.com/latam/en/docs/integrations/webcheckout-integration/confirmation-page.html#signature-validation
# For confirmation page, PayU Latam round to the first digit if the second one is a zero
# to generate their signature.
# e.g:
# 150.00 -> 150.0
# 150.26 -> 150.26
# This happens to be Python 3's default behavior when casting to `float`.
new_value = "%d.%d" % float_split(float(values.get('TX_VALUE')), 2)
else:
# https://developers.payulatam.com/latam/en/docs/integrations/webcheckout-integration/response-page.html#signature-validation
# PayU Latam use the "Round half to even" rounding method
# to generate their signature. This happens to be Python 3's
# default rounding method.
new_value = float_repr(float(values.get('TX_VALUE')), 1)
data_string = '~'.join([
self.payulatam_api_key,
self.payulatam_merchant_id,
values['referenceCode'],
new_value,
values['currency'],
values.get('transactionState'),
])
else:
data_string = '~'.join([
self.payulatam_api_key,
self.payulatam_merchant_id,
values['referenceCode'],
float_repr(float(values['amount']), 2),
values['currency'],
])
return md5(data_string.encode('utf-8')).hexdigest()
def _get_default_payment_method_id(self):
self.ensure_one()
if self.provider != 'payulatam':
return super()._get_default_payment_method_id()
return self.env.ref('payment_payulatam.payment_method_payulatam').id
| 47.057471
| 4,094
|
2,162
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
from odoo import http
from odoo.exceptions import ValidationError
from odoo.http import request
_logger = logging.getLogger(__name__)
class PayuLatamController(http.Controller):
_return_url = '/payment/payulatam/return'
_webhook_url = '/payment/payulatam/webhook'
@http.route(_return_url, type='http', auth='public', methods=['GET'])
def payulatam_return(self, **data):
_logger.info("entering _handle_feedback_data with data:\n%s", pprint.pformat(data))
request.env['payment.transaction'].sudo()._handle_feedback_data('payulatam', data)
return request.redirect('/payment/status')
@http.route(_webhook_url, type='http', auth='public', methods=['POST'], csrf=False)
def payulatam_webhook(self, **data):
_logger.info("handling confirmation from PayU Latam with data:\n%s", pprint.pformat(data))
state_pol = data.get('state_pol')
if state_pol == '4':
lapTransactionState = 'APPROVED'
elif state_pol == '6':
lapTransactionState = 'DECLINED'
elif state_pol == '5':
lapTransactionState = 'EXPIRED'
else:
lapTransactionState = f'INVALID state_pol {state_pol}'
data = {
'signature': data.get('sign'),
'TX_VALUE': data.get('value'),
'currency': data.get('currency'),
'referenceCode': data.get('reference_sale'),
'transactionId': data.get('transaction_id'),
'transactionState': data.get('state_pol'),
'message': data.get('response_message_pol'),
'lapTransactionState': lapTransactionState,
}
try:
request.env['payment.transaction'].sudo().with_context(payulatam_is_confirmation_page=True)\
._handle_feedback_data('payulatam', data)
except ValidationError:
_logger.exception(
'An error occurred while handling the confirmation from PayU with data:\n%s',
pprint.pformat(data))
return http.Response(status=200)
| 40.037037
| 2,162
|
1,136
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Accounting - MRP',
'version': '1.0',
'category': 'Manufacturing/Manufacturing',
'summary': 'Analytic accounting in Manufacturing',
'description': """
Analytic Accounting in MRP
==========================
* Cost structure report
Also, allows to compute the cost of the product based on its BoM, using the costs of its components and work center operations.
It adds a button on the product itself but also an action in the list view of the products.
If the automated inventory valuation is active, the necessary accounting entries will be created.
""",
'website': 'https://www.odoo.com/app/manufacturing',
'depends': ['mrp', 'stock_account'],
"data": [
'security/ir.model.access.csv',
"views/product_views.xml",
"views/mrp_bom_views.xml",
"views/mrp_production_views.xml",
"views/analytic_account_views.xml",
],
'demo': [
'data/mrp_account_demo.xml',
],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 32.457143
| 1,136
|
11,880
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
from odoo.tests import Form
class TestAnalyticAccount(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env.user.write({'groups_id': [(4, cls.env.ref('analytic.group_analytic_accounting').id),]})
cls.analytic_account = cls.env['account.analytic.account'].create({'name': 'test_analytic_account'})
cls.workcenter = cls.env['mrp.workcenter'].create({
'name': 'Workcenter',
'capacity': 1,
'time_efficiency': 100,
'costs_hour': 10,
})
cls.product = cls.env['product.product'].create({
'name': 'Product',
'type': 'product',
'standard_price': 233.0,
})
cls.component = cls.env['product.product'].create({
'name': 'Component',
'type': 'product',
'standard_price': 10.0,
})
cls.bom = cls.env['mrp.bom'].create({
'product_id': cls.product.id,
'product_tmpl_id': cls.product.product_tmpl_id.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.component.id, 'product_qty': 1.0}),
],
'operation_ids': [
(0, 0, {'name': 'work work', 'workcenter_id': cls.workcenter.id, 'time_cycle': 15, 'sequence': 1}),
]})
def test_mo_analytic(self):
"""Test the amount on analytic line will change when consumed qty of the
component changed.
"""
# create a mo
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product
mo_form.bom_id = self.bom
mo_form.product_qty = 10.0
mo_form.analytic_account_id = self.analytic_account
mo = mo_form.save()
mo.action_confirm()
self.assertEqual(mo.state, 'confirmed')
self.assertEqual(len(mo.move_raw_ids.analytic_account_line_id), 0)
# increase qty_producing to 5.0
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo_form.save()
self.assertEqual(mo.state, 'progress')
self.assertEqual(mo.move_raw_ids.analytic_account_line_id.amount, -50.0)
# increase qty_producing to 10.0
mo_form = Form(mo)
mo_form.qty_producing = 10.0
mo_form.save()
# Hack to bypass test doing strange things
mo._set_qty_producing()
mo.workorder_ids.button_finish()
self.assertEqual(mo.state, 'to_close')
self.assertEqual(mo.move_raw_ids.analytic_account_line_id.amount, -100.0)
# mark as done
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
self.assertEqual(mo.move_raw_ids.analytic_account_line_id.amount, -100.0)
def test_mo_analytic_backorder(self):
"""Test the analytic lines are correctly posted when backorder.
"""
# create a mo
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product
mo_form.bom_id = self.bom
mo_form.product_qty = 10.0
mo_form.analytic_account_id = self.analytic_account
mo = mo_form.save()
mo.action_confirm()
self.assertEqual(mo.state, 'confirmed')
self.assertEqual(len(mo.move_raw_ids.analytic_account_line_id), 0)
# increase qty_producing to 5.0
mo_form = Form(mo)
mo_form.qty_producing = 5.0
mo_form.save()
self.assertEqual(mo.state, 'progress')
self.assertEqual(mo.move_raw_ids.analytic_account_line_id.amount, -50.0)
backorder_wizard_dict = mo.button_mark_done()
Form(self.env[(backorder_wizard_dict.get('res_model'))].with_context(backorder_wizard_dict['context'])).save().action_backorder()
self.assertEqual(mo.state, 'done')
self.assertEqual(mo.move_raw_ids.analytic_account_line_id.amount, -50.0)
def test_workcenter_same_analytic_account(self):
"""Test when workcenter and MO are using the same analytic account, no
duplicated lines will be post.
"""
# set wc analytic account to be the same of the one on the bom
self.workcenter.costs_hour_account_id = self.analytic_account
# create a mo
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product
mo_form.bom_id = self.bom
mo_form.product_qty = 10.0
mo_form.analytic_account_id = self.analytic_account
mo = mo_form.save()
mo.action_confirm()
self.assertEqual(len(mo.workorder_ids.wc_analytic_account_line_id), 0)
# change duration to 60
with mo_form.workorder_ids.edit(0) as line_edit:
line_edit.duration = 60.0
mo_form.save()
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.amount, -10.0)
self.assertEqual(len(mo.workorder_ids.wc_analytic_account_line_id), 0)
# change duration to 120
with mo_form.workorder_ids.edit(0) as line_edit:
line_edit.duration = 120.0
mo_form.save()
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.amount, -20.0)
self.assertEqual(len(mo.workorder_ids.wc_analytic_account_line_id), 0)
# mark as done
mo_form.qty_producing = 10.0
mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.amount, -20.0)
self.assertEqual(len(mo.workorder_ids.wc_analytic_account_line_id), 0)
def test_workcenter_different_analytic_account(self):
"""Test when workcenter and MO are using the same analytic account, no
duplicated lines will be post.
"""
# set wc analytic account to be different from the one on the bom
wc_analytic_account = self.env['account.analytic.account'].create({'name': 'wc_analytic_account'})
self.workcenter.costs_hour_account_id = wc_analytic_account
# create a mo
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product
mo_form.bom_id = self.bom
mo_form.product_qty = 10.0
mo_form.analytic_account_id = self.analytic_account
mo = mo_form.save()
mo.action_confirm()
self.assertEqual(len(mo.workorder_ids.wc_analytic_account_line_id), 0)
# change duration to 60
with mo_form.workorder_ids.edit(0) as line_edit:
line_edit.duration = 60.0
mo_form.save()
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.amount, -10.0)
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.account_id, self.analytic_account)
self.assertEqual(mo.workorder_ids.wc_analytic_account_line_id.amount, -10.0)
self.assertEqual(mo.workorder_ids.wc_analytic_account_line_id.account_id, wc_analytic_account)
# change duration to 120
with mo_form.workorder_ids.edit(0) as line_edit:
line_edit.duration = 120.0
mo_form.save()
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.amount, -20.0)
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.account_id, self.analytic_account)
self.assertEqual(mo.workorder_ids.wc_analytic_account_line_id.amount, -20.0)
self.assertEqual(mo.workorder_ids.wc_analytic_account_line_id.account_id, wc_analytic_account)
# mark as done
mo_form.qty_producing = 10.0
mo_form.save()
mo.button_mark_done()
self.assertEqual(mo.state, 'done')
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.amount, -20.0)
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.account_id, self.analytic_account)
self.assertEqual(mo.workorder_ids.wc_analytic_account_line_id.amount, -20.0)
self.assertEqual(mo.workorder_ids.wc_analytic_account_line_id.account_id, wc_analytic_account)
def test_changing_mo_analytic_account(self):
""" Check if the MO account analytic lines are correctly updated
after the change of the MO account analytic.
"""
# create a mo
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = self.product
mo_form.bom_id = self.bom
mo_form.product_qty = 1
mo_form.analytic_account_id = self.analytic_account
mo = mo_form.save()
mo.action_confirm()
self.assertEqual(mo.state, 'confirmed')
self.assertEqual(len(mo.move_raw_ids.analytic_account_line_id), 0)
self.assertEqual(len(mo.workorder_ids.mo_analytic_account_line_id), 0)
# Change duration to 60
with mo_form.workorder_ids.edit(0) as line_edit:
line_edit.duration = 60.0
mo_form.save()
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.account_id, self.analytic_account)
# Mark as done
wizard_dict = mo.button_mark_done()
Form(self.env[(wizard_dict.get('res_model'))].with_context(wizard_dict['context'])).save().process()
self.assertEqual(mo.state, 'done')
self.assertEqual(len(mo.move_raw_ids.analytic_account_line_id), 1)
# Create a new analytic account
new_analytic_account = self.env['account.analytic.account'].create({'name': 'test_analytic_account_2'})
# Change the MO analytic account
mo.analytic_account_id = new_analytic_account
self.assertEqual(mo.move_raw_ids.analytic_account_line_id.account_id.id, new_analytic_account.id)
self.assertEqual(mo.workorder_ids.mo_analytic_account_line_id.account_id.id, new_analytic_account.id)
#Get the MO analytic account lines
mo_analytic_account_raw_lines = mo.move_raw_ids.analytic_account_line_id
mo_analytic_account_wc_lines = mo.workorder_ids.mo_analytic_account_line_id
mo.analytic_account_id = False
# Check that the MO analytic account lines are deleted
self.assertEqual(len(mo.move_raw_ids.analytic_account_line_id), 0)
self.assertEqual(len(mo.workorder_ids.mo_analytic_account_line_id), 0)
self.assertFalse(mo_analytic_account_raw_lines.exists())
self.assertFalse(mo_analytic_account_wc_lines.exists())
# Check that the AA lines are recreated correctly if we delete the AA, save the MO, and assign a new one
mo.analytic_account_id = self.analytic_account
self.assertEqual(len(mo.move_raw_ids.analytic_account_line_id), 1)
self.assertEqual(len(mo.workorder_ids.mo_analytic_account_line_id), 1)
def test_add_wo_analytic_no_company(self):
"""Test the addition of work orders to a MO linked to
an analytic account that has no company associated
"""
# Create an analytic account and remove the company
analytic_account_no_company = self.env['account.analytic.account'].create({
'name': 'test_analytic_account_no_company',
})
analytic_account_no_company.company_id = False
# Create a mo linked to an analytic account with no associated company
mo_no_company = self.env['mrp.production'].create({
'product_id': self.product.id,
'analytic_account_id': analytic_account_no_company.id,
'product_uom_id': self.bom.product_uom_id.id,
})
mo_no_c_form = Form(mo_no_company)
self.env['mrp.workorder'].create({
'name': 'Work_order',
'workcenter_id': self.workcenter.id,
'product_uom_id': self.bom.product_uom_id.id,
'production_id': mo_no_c_form.id,
})
mo_no_c_form.save()
self.assertTrue(mo_no_company.workorder_ids)
| 44.830189
| 11,880
|
15,278
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mrp.tests.common import TestMrpCommon
from odoo.addons.stock_account.tests.test_account_move import TestAccountMove
from odoo.tests import Form, tagged
class TestMrpAccount(TestMrpCommon):
@classmethod
def setUpClass(cls):
super(TestMrpAccount, cls).setUpClass()
cls.source_location_id = cls.stock_location_14.id
cls.warehouse = cls.env.ref('stock.warehouse0')
# setting up alternative workcenters
cls.wc_alt_1 = cls.env['mrp.workcenter'].create({
'name': 'Nuclear Workcenter bis',
'capacity': 3,
'time_start': 9,
'time_stop': 5,
'time_efficiency': 80,
})
cls.wc_alt_2 = cls.env['mrp.workcenter'].create({
'name': 'Nuclear Workcenter ter',
'capacity': 1,
'time_start': 10,
'time_stop': 5,
'time_efficiency': 85,
})
cls.product_4.uom_id = cls.uom_unit
cls.planning_bom = cls.env['mrp.bom'].create({
'product_id': cls.product_4.id,
'product_tmpl_id': cls.product_4.product_tmpl_id.id,
'product_uom_id': cls.uom_unit.id,
'product_qty': 4.0,
'consumption': 'flexible',
'operation_ids': [
(0, 0, {'name': 'Gift Wrap Maching', 'workcenter_id': cls.workcenter_1.id, 'time_cycle': 15, 'sequence': 1}),
],
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.product_2.id, 'product_qty': 2}),
(0, 0, {'product_id': cls.product_1.id, 'product_qty': 4})
]})
cls.dining_table = cls.env['product.product'].create({
'name': 'Table (MTO)',
'type': 'product',
'tracking': 'serial',
})
cls.product_table_sheet = cls.env['product.product'].create({
'name': 'Table Top',
'type': 'product',
'tracking': 'serial',
})
cls.product_table_leg = cls.env['product.product'].create({
'name': 'Table Leg',
'type': 'product',
'tracking': 'lot',
})
cls.product_bolt = cls.env['product.product'].create({
'name': 'Bolt',
'type': 'product',
})
cls.product_screw = cls.env['product.product'].create({
'name': 'Screw',
'type': 'product',
})
cls.mrp_workcenter = cls.env['mrp.workcenter'].create({
'name': 'Assembly Line 1',
'resource_calendar_id': cls.env.ref('resource.resource_calendar_std').id,
})
cls.mrp_bom_desk = cls.env['mrp.bom'].create({
'product_tmpl_id': cls.dining_table.product_tmpl_id.id,
'product_uom_id': cls.env.ref('uom.product_uom_unit').id,
'sequence': 3,
'consumption': 'flexible',
'operation_ids': [
(0, 0, {'workcenter_id': cls.mrp_workcenter.id, 'name': 'Manual Assembly'}),
],
})
cls.mrp_bom_desk.write({
'bom_line_ids': [
(0, 0, {
'product_id': cls.product_table_sheet.id,
'product_qty': 1,
'product_uom_id': cls.env.ref('uom.product_uom_unit').id,
'sequence': 1,
'operation_id': cls.mrp_bom_desk.operation_ids.id}),
(0, 0, {
'product_id': cls.product_table_leg.id,
'product_qty': 4,
'product_uom_id': cls.env.ref('uom.product_uom_unit').id,
'sequence': 2,
'operation_id': cls.mrp_bom_desk.operation_ids.id}),
(0, 0, {
'product_id': cls.product_bolt.id,
'product_qty': 4,
'product_uom_id': cls.env.ref('uom.product_uom_unit').id,
'sequence': 3,
'operation_id': cls.mrp_bom_desk.operation_ids.id}),
(0, 0, {
'product_id': cls.product_screw.id,
'product_qty': 10,
'product_uom_id': cls.env.ref('uom.product_uom_unit').id,
'sequence': 4,
'operation_id': cls.mrp_bom_desk.operation_ids.id}),
]
})
cls.mrp_workcenter_1 = cls.env['mrp.workcenter'].create({
'name': 'Drill Station 1',
'resource_calendar_id': cls.env.ref('resource.resource_calendar_std').id,
})
cls.mrp_workcenter_3 = cls.env['mrp.workcenter'].create({
'name': 'Assembly Line 1',
'resource_calendar_id': cls.env.ref('resource.resource_calendar_std').id,
})
cls.categ_standard = cls.env['product.category'].create({
'name': 'STANDARD',
'property_cost_method': 'standard'
})
cls.categ_real = cls.env['product.category'].create({
'name': 'REAL',
'property_cost_method': 'fifo'
})
cls.categ_average = cls.env['product.category'].create({
'name': 'AVERAGE',
'property_cost_method': 'average'
})
cls.dining_table.categ_id = cls.categ_real.id
cls.product_table_sheet.categ_id = cls.categ_real.id
cls.product_table_leg.categ_id = cls.categ_average.id
cls.product_bolt.categ_id = cls.categ_standard.id
cls.product_screw.categ_id = cls.categ_standard.id
cls.env['stock.move'].search([('product_id', 'in', [cls.product_bolt.id, cls.product_screw.id])])._do_unreserve()
(cls.product_bolt + cls.product_screw).write({'type': 'product'})
cls.dining_table.tracking = 'none'
def test_00_production_order_with_accounting(self):
self.product_table_sheet.standard_price = 20.0
self.product_table_leg.standard_price = 15.0
self.product_bolt.standard_price = 10.0
self.product_screw.standard_price = 0.1
self.product_table_leg.tracking = 'none'
self.product_table_sheet.tracking = 'none'
# Inventory Product Table
quants = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_table_sheet.id, # tracking serial
'inventory_quantity': 20,
'location_id': self.source_location_id,
})
quants |= self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_table_leg.id, # tracking lot
'inventory_quantity': 20,
'location_id': self.source_location_id,
})
quants |= self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_bolt.id,
'inventory_quantity': 20,
'location_id': self.source_location_id,
})
quants |= self.env['stock.quant'].create({
'product_id': self.product_screw.id,
'inventory_quantity': 200000,
'location_id': self.source_location_id,
})
quants.action_apply_inventory()
bom = self.mrp_bom_desk.copy()
bom.operation_ids = False
production_table_form = Form(self.env['mrp.production'])
production_table_form.product_id = self.dining_table
production_table_form.bom_id = bom
production_table_form.product_qty = 1
production_table = production_table_form.save()
production_table.extra_cost = 20
production_table.action_confirm()
mo_form = Form(production_table)
mo_form.qty_producing = 1
production_table = mo_form.save()
production_table._post_inventory()
move_value = production_table.move_finished_ids.filtered(lambda x: x.state == "done").stock_valuation_layer_ids.value
# 1 table head at 20 + 4 table leg at 15 + 4 bolt at 10 + 10 screw at 10 + 1*20 (extra cost)
self.assertEqual(move_value, 141, 'Thing should have the correct price')
@tagged("post_install", "-at_install")
class TestMrpAccountMove(TestAccountMove):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product_B = cls.env["product.product"].create(
{
"name": "Product B",
"type": "product",
"default_code": "prda",
"categ_id": cls.auto_categ.id,
"taxes_id": [(5, 0, 0)],
"supplier_taxes_id": [(5, 0, 0)],
"lst_price": 100.0,
"standard_price": 10.0,
"property_account_income_id": cls.company_data["default_account_revenue"].id,
"property_account_expense_id": cls.company_data["default_account_expense"].id,
}
)
cls.bom = cls.env['mrp.bom'].create({
'product_id': cls.product_A.id,
'product_tmpl_id': cls.product_A.product_tmpl_id.id,
'product_qty': 1.0,
'bom_line_ids': [
(0, 0, {'product_id': cls.product_B.id, 'product_qty': 1}),
]})
def test_unbuild_account_00(self):
"""Test when after unbuild, the journal entries are the reversal of the
journal entries created when produce the product.
"""
# build
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_A
production_form.bom_id = self.bom
production_form.product_qty = 1
production = production_form.save()
production.action_confirm()
mo_form = Form(production)
mo_form.qty_producing = 1
production = mo_form.save()
production._post_inventory()
production.button_mark_done()
# finished product move
productA_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product A'), ('credit', '=', 0)])
productA_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product A'), ('debit', '=', 0)])
self.assertEqual(productA_debit_line.account_id, self.stock_valuation_account)
self.assertEqual(productA_credit_line.account_id, self.stock_input_account)
# component move
productB_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product B'), ('credit', '=', 0)])
productB_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product B'), ('debit', '=', 0)])
self.assertEqual(productB_debit_line.account_id, self.stock_output_account)
self.assertEqual(productB_credit_line.account_id, self.stock_valuation_account)
# unbuild
res_dict = production.button_unbuild()
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.action_validate()
# finished product move
productA_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product A'), ('credit', '=', 0)])
productA_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product A'), ('debit', '=', 0)])
self.assertEqual(productA_debit_line.account_id, self.stock_input_account)
self.assertEqual(productA_credit_line.account_id, self.stock_valuation_account)
# component move
productB_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product B'), ('credit', '=', 0)])
productB_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product B'), ('debit', '=', 0)])
self.assertEqual(productB_debit_line.account_id, self.stock_valuation_account)
self.assertEqual(productB_credit_line.account_id, self.stock_output_account)
def test_unbuild_account_01(self):
"""Test when production location has its valuation accounts. After unbuild,
the journal entries are the reversal of the journal entries created when
produce the product.
"""
# set accounts for production location
production_location = self.product_A.property_stock_production
wip_incoming_account = self.env['account.account'].create({
'name': 'wip incoming',
'code': '000001',
'user_type_id': self.env.ref('account.data_account_type_current_assets').id,
})
wip_outgoing_account = self.env['account.account'].create({
'name': 'wip outgoing',
'code': '000002',
'user_type_id': self.env.ref('account.data_account_type_current_assets').id,
})
production_location.write({
'valuation_in_account_id': wip_incoming_account.id,
'valuation_out_account_id': wip_outgoing_account.id,
})
# build
production_form = Form(self.env['mrp.production'])
production_form.product_id = self.product_A
production_form.bom_id = self.bom
production_form.product_qty = 1
production = production_form.save()
production.action_confirm()
mo_form = Form(production)
mo_form.qty_producing = 1
production = mo_form.save()
production._post_inventory()
production.button_mark_done()
# finished product move
productA_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product A'), ('credit', '=', 0)])
productA_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product A'), ('debit', '=', 0)])
self.assertEqual(productA_debit_line.account_id, self.stock_valuation_account)
self.assertEqual(productA_credit_line.account_id, wip_outgoing_account)
# component move
productB_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product B'), ('credit', '=', 0)])
productB_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'MO%Product B'), ('debit', '=', 0)])
self.assertEqual(productB_debit_line.account_id, wip_incoming_account)
self.assertEqual(productB_credit_line.account_id, self.stock_valuation_account)
# unbuild
res_dict = production.button_unbuild()
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.action_validate()
productA_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product A'), ('credit', '=', 0)])
productA_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product A'), ('debit', '=', 0)])
self.assertEqual(productA_debit_line.account_id, wip_outgoing_account)
self.assertEqual(productA_credit_line.account_id, self.stock_valuation_account)
# component move
productB_debit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product B'), ('credit', '=', 0)])
productB_credit_line = self.env['account.move.line'].search([('ref', 'ilike', 'UB%Product B'), ('debit', '=', 0)])
self.assertEqual(productB_debit_line.account_id, self.stock_valuation_account)
self.assertEqual(productB_credit_line.account_id, wip_incoming_account)
| 47.447205
| 15,278
|
10,804
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests import common, Form
from odoo.tools.float_utils import float_round, float_compare
class TestBomPrice(common.TransactionCase):
def _create_product(self, name, price):
return self.Product.create({
'name': name,
'type': 'product',
'standard_price': price,
})
def setUp(self):
super(TestBomPrice, self).setUp()
self.Product = self.env['product.product']
self.Bom = self.env['mrp.bom']
# Products.
self.dining_table = self._create_product('Dining Table', 1000)
self.table_head = self._create_product('Table Head', 300)
self.screw = self._create_product('Screw', 10)
self.leg = self._create_product('Leg', 25)
self.glass = self._create_product('Glass', 100)
# Unit of Measure.
self.unit = self.env.ref("uom.product_uom_unit")
self.dozen = self.env.ref("uom.product_uom_dozen")
# Bills Of Materials.
# -------------------------------------------------------------------------------
# Cost of BoM (Dining Table 1 Unit)
# Component Cost = Table Head 1 Unit * 300 = 300 (468.75 from it's components)
# Screw 5 Unit * 10 = 50
# Leg 4 Unit * 25 = 100
# Glass 1 Unit * 100 = 100
# Total = 550 [718.75 if components of Table Head considered] (for 1 Unit)
# -------------------------------------------------------------------------------
bom_form = Form(self.Bom)
bom_form.product_id = self.dining_table
bom_form.product_tmpl_id = self.dining_table.product_tmpl_id
bom_form.product_qty = 1.0
bom_form.product_uom_id = self.unit
bom_form.type = 'normal'
with bom_form.bom_line_ids.new() as line:
line.product_id = self.table_head
line.product_qty = 1
with bom_form.bom_line_ids.new() as line:
line.product_id = self.screw
line.product_qty = 5
with bom_form.bom_line_ids.new() as line:
line.product_id = self.leg
line.product_qty = 4
with bom_form.bom_line_ids.new() as line:
line.product_id = self.glass
line.product_qty = 1
self.bom_1 = bom_form.save()
# Table Head's components.
self.plywood_sheet = self._create_product('Plywood Sheet', 200)
self.bolt = self._create_product('Bolt', 10)
self.colour = self._create_product('Colour', 100)
self.corner_slide = self._create_product('Corner Slide', 25)
# -----------------------------------------------------------------
# Cost of BoM (Table Head 1 Dozen)
# Component Cost = Plywood Sheet 12 Unit * 200 = 2400
# Bolt 60 Unit * 10 = 600
# Colour 12 Unit * 100 = 1200
# Corner Slide 57 Unit * 25 = 1425
# Total = 5625
# 1 Unit price (5625/12) = 468.75
# -----------------------------------------------------------------
bom_form2 = Form(self.Bom)
bom_form2.product_id = self.table_head
bom_form2.product_tmpl_id = self.table_head.product_tmpl_id
bom_form2.product_qty = 1.0
bom_form2.product_uom_id = self.dozen
bom_form2.type = 'phantom'
with bom_form2.bom_line_ids.new() as line:
line.product_id = self.plywood_sheet
line.product_qty = 12
with bom_form2.bom_line_ids.new() as line:
line.product_id = self.bolt
line.product_qty = 60
with bom_form2.bom_line_ids.new() as line:
line.product_id = self.colour
line.product_qty = 12
with bom_form2.bom_line_ids.new() as line:
line.product_id = self.corner_slide
line.product_qty = 57
self.bom_2 = bom_form2.save()
def test_00_compute_price(self):
"""Test multi-level BoM cost"""
self.assertEqual(self.dining_table.standard_price, 1000, "Initial price of the Product should be 1000")
self.dining_table.button_bom_cost()
self.assertEqual(self.dining_table.standard_price, 550, "After computing price from BoM price should be 550")
def test_01_compute_price_operation_cost(self):
"""Test calcuation of bom cost with operations."""
workcenter_from1 = Form(self.env['mrp.workcenter'])
workcenter_from1.name = 'Workcenter'
workcenter_from1.time_efficiency = 80
workcenter_from1.capacity = 2
workcenter_from1.oee_target = 100
workcenter_from1.time_start = 15
workcenter_from1.time_stop = 15
workcenter_from1.costs_hour = 100
workcenter_1 = workcenter_from1.save()
self.bom_1.write({
'operation_ids': [
(0, 0, {
'name': 'Cutting',
'workcenter_id': workcenter_1.id,
'time_mode': 'manual',
'time_cycle_manual': 20,
'sequence': 1,
}),
(0, 0, {
'name': 'Drilling',
'workcenter_id': workcenter_1.id,
'time_mode': 'manual',
'time_cycle_manual': 25,
'sequence': 2,
}),
(0, 0, {
'name': 'Fitting',
'workcenter_id': workcenter_1.id,
'time_mode': 'manual',
'time_cycle_manual': 30,
'sequence': 3,
}),
],
}),
self.bom_2.write({
'operation_ids': [
(0, 0, {
'name': 'Cutting',
'workcenter_id': workcenter_1.id,
'time_mode': 'manual',
'time_cycle_manual': 20,
'sequence': 1,
}),
(0, 0, {
'name': 'Drilling',
'workcenter_id': workcenter_1.id,
'time_mode': 'manual',
'time_cycle_manual': 25,
'sequence': 2,
}),
(0, 0, {
'name': 'Fitting',
'workcenter_id': workcenter_1.id,
'time_mode': 'manual',
'time_cycle_manual': 30,
'sequence': 3,
}),
],
}),
# -----------------------------------------------------------------
# Dinning Table Operation Cost(1 Unit)
# -----------------------------------------------------------------
# Operation cost calculate for 1 units
# Cutting (15 + 15 + (20 * 100/80) / 60) * 100 = 91.67
# Drilling (15 + 15 + (25 * 100/80) / 60) * 100 = 102.08
# Fitting (15 + 15 + (30 * 100/80) / 60) * 100 = 112.50
# ----------------------------------------
# Operation Cost 1 unit = 306.25
# -----------------------------------------------------------------
# --------------------------------------------------------------------------
# Table Head Operation Cost (1 Dozen)
# --------------------------------------------------------------------------
# Operation cost calculate for 1 dozens
# Cutting (15 + 15 + (20 * 1 * 100/80) / 60) * 100 = 91.67
# Drilling (15 + 15 + (25 * 1 * 100/80) / 60) * 100 = 102.08
# Fitting (15 + 15 + (30 * 1 * 100/80) / 60) * 100 = 112.50
# ----------------------------------------
# Operation Cost 1 dozen (306.25 per dozen) and 25.52 for 1 Unit
# --------------------------------------------------------------------------
self.assertEqual(self.dining_table.standard_price, 1000, "Initial price of the Product should be 1000")
self.dining_table.button_bom_cost()
# Total cost of Dining Table = (550) + Total cost of operations (306.25) = 856.25
self.assertEqual(float_round(self.dining_table.standard_price, precision_digits=2), 856.25, "After computing price from BoM price should be 856.25")
self.Product.browse([self.dining_table.id, self.table_head.id]).action_bom_cost()
# Total cost of Dining Table = (718.75) + Total cost of all operations (306.25 + 25.52) = 1050.52
self.assertEqual(float_compare(self.dining_table.standard_price, 1050.52, precision_digits=2), 0, "After computing price from BoM price should be 1050.52")
def test_02_compute_byproduct_price(self):
"""Test BoM cost when byproducts with cost share"""
# byproduct
scrap_wood = self._create_product('Scrap Wood', 30)
# different byproduct line uoms => 20 total units with a total of 75% of cost share
self.bom_1.write({
'byproduct_ids': [
(0, 0, {
'product_id': scrap_wood.id,
'product_uom_id': self.unit.id,
'product_qty': 8,
'bom_id': self.bom_1.id,
'cost_share': 25,
}),
(0, 0, {
'product_id': scrap_wood.id,
'product_uom_id': self.dozen.id,
'product_qty': 1,
'bom_id': self.bom_1.id,
'cost_share': 50,
}),
],
}),
# Cost Breakdown.
# -------------------------------------------------------------------------------
# Total Cost of BoM = 550 [718.75 if components of Table Head considered] (for 1 Unit)
# Dining Table 1 Unit = 1 - (25 + 50) / 100 * 550 = 0.25 * 550 = 137.5
# Scrap Wood 1 Unit = (25 + 50) / 100 * 550 / (8 units + 12 units) = 20.625
# -------------------------------------------------------------------------------
self.assertEqual(self.dining_table.standard_price, 1000, "Initial price of the Product should be 1000")
self.assertEqual(scrap_wood.standard_price, 30, "Initial price of the By-Product should be 30")
self.dining_table.button_bom_cost()
self.assertEqual(self.dining_table.standard_price, 137.5, "After computing price from BoM price should be 137.5")
scrap_wood.button_bom_cost()
self.assertEqual(scrap_wood.standard_price, 20.63, "After computing price from BoM price should be 20.63")
| 45.016667
| 10,804
|
15,377
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
""" Implementation of "INVENTORY VALUATION TESTS (With valuation layers)" spreadsheet. """
from odoo.addons.stock_account.tests.test_stockvaluationlayer import TestStockValuationCommon
from odoo.tests import Form
class TestMrpValuationCommon(TestStockValuationCommon):
@classmethod
def setUpClass(cls):
super(TestMrpValuationCommon, cls).setUpClass()
cls.component_category = cls.env['product.category'].create(
{'name': 'category2'}
)
cls.component = cls.env['product.product'].create({
'name': 'component1',
'type': 'product',
'categ_id': cls.component_category.id,
})
cls.bom = cls.env['mrp.bom'].create({
'product_id': cls.product1.id,
'product_tmpl_id': cls.product1.product_tmpl_id.id,
'product_uom_id': cls.uom_unit.id,
'product_qty': 1.0,
'type': 'normal',
'bom_line_ids': [
(0, 0, {'product_id': cls.component.id, 'product_qty': 1})
]})
def _make_mo(self, bom, quantity=1):
mo_form = Form(self.env['mrp.production'])
mo_form.product_id = bom.product_id
mo_form.bom_id = bom
mo_form.product_qty = quantity
mo = mo_form.save()
mo.action_confirm()
return mo
def _produce(self, mo, quantity=0):
mo_form = Form(mo)
if not quantity:
quantity = mo.product_qty - mo.qty_produced
mo_form.qty_producing += quantity
mo = mo_form.save()
class TestMrpValuationStandard(TestMrpValuationCommon):
def test_fifo_fifo_1(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo = mo.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(self.component.value_svl, 20)
self.assertEqual(self.product1.value_svl, 10)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
def test_fifo_fifo_2(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self._make_out_move(self.product1, 1)
self.assertEqual(self.product1.value_svl, 15)
def test_fifo_byproduct(self):
""" Check that a MO byproduct with a cost share calculates correct svl """
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
# add byproduct
byproduct_cost_share = 10
byproduct = self.env['product.product'].create({
'name': 'byproduct',
'type': 'product',
'categ_id': self.product1.product_tmpl_id.categ_id.id,
})
self.bom.write({
'byproduct_ids': [(0, 0, {'product_id': byproduct.id, 'product_uom_id': self.uom_unit.id, 'product_qty': 1, 'cost_share': byproduct_cost_share})]
})
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo = mo.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(self.component.value_svl, 20)
self.assertEqual(self.product1.value_svl, 10 * (100 - byproduct_cost_share) / 100)
self.assertEqual(byproduct.value_svl, 10 * byproduct_cost_share / 100)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self.assertEqual(byproduct.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30 * (100 - byproduct_cost_share) / 100)
self.assertEqual(byproduct.value_svl, 30 * byproduct_cost_share / 100)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self.assertEqual(byproduct.quantity_svl, 2)
def test_fifo_avco_1(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
action = mo.button_mark_done()
backorder = Form(self.env['mrp.production.backorder'].with_context(**action['context']))
backorder.save().action_backorder()
mo = mo.procurement_group_id.mrp_production_ids[-1]
self.assertEqual(self.component.value_svl, 20)
self.assertEqual(self.product1.value_svl, 10)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
def test_fifo_avco_2(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self._make_out_move(self.product1, 1)
self.assertEqual(self.product1.value_svl, 15)
def test_fifo_std_1(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.standard_price = 8.8
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
mo._post_inventory()
self.assertEqual(self.component.value_svl, 20)
self.assertEqual(self.product1.value_svl, 8.8)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 8.8 * 2)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
def test_fifo_std_2(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'fifo'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.standard_price = 8.8
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 8.8 * 2)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self._make_out_move(self.product1, 1)
self.assertEqual(self.product1.value_svl, 8.8)
def test_std_avco_1(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self.component.standard_price = 8.8
self._make_in_move(self.component, 1)
self._make_in_move(self.component, 1)
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
mo._post_inventory()
self.assertEqual(self.component.value_svl, 8.8)
self.assertEqual(self.product1.value_svl, 8.8)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 8.8 * 2)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
def test_std_avco_2(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self.component.standard_price = 8.8
self._make_in_move(self.component, 1)
self._make_in_move(self.component, 1)
mo = self._make_mo(self.bom, 2)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 8.8 * 2)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self._make_out_move(self.product1, 1)
self.assertEqual(self.product1.value_svl, 8.8)
def test_std_std_1(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.component.standard_price = 8.8
self.product1.standard_price = 7.2
self._make_in_move(self.component, 1)
self._make_in_move(self.component, 1)
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
mo._post_inventory()
self.assertEqual(self.component.value_svl, 8.8)
self.assertEqual(self.product1.value_svl, 7.2)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 7.2 * 2)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
def test_std_std_2(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'standard'
self.component.standard_price = 8.8
self.product1.standard_price = 7.2
self._make_in_move(self.component, 1)
self._make_in_move(self.component, 1)
mo = self._make_mo(self.bom, 2)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 7.2 * 2)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self._make_out_move(self.product1, 1)
self.assertEqual(self.product1.value_svl, 7.2)
def test_avco_avco_1(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'average'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo, 1)
mo._post_inventory()
self.assertEqual(self.component.value_svl, 15)
self.assertEqual(self.product1.value_svl, 15)
self.assertEqual(self.component.quantity_svl, 1)
self.assertEqual(self.product1.quantity_svl, 1)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
def test_avco_avco_2(self):
self.component.product_tmpl_id.categ_id.property_cost_method = 'average'
self.product1.product_tmpl_id.categ_id.property_cost_method = 'average'
self._make_in_move(self.component, 1, 10)
self._make_in_move(self.component, 1, 20)
mo = self._make_mo(self.bom, 2)
self._produce(mo)
mo.button_mark_done()
self.assertEqual(self.component.value_svl, 0)
self.assertEqual(self.product1.value_svl, 30)
self.assertEqual(self.component.quantity_svl, 0)
self.assertEqual(self.product1.quantity_svl, 2)
self._make_out_move(self.product1, 1)
self.assertEqual(self.product1.value_svl, 15)
def test_validate_draft_kit(self):
"""
Create a draft receipt, add a kit to its move lines and directly
validate it. From client side, such a behaviour is possible with
the Barcode app.
"""
self.component.product_tmpl_id.categ_id.property_cost_method = 'average'
self.product1.type = 'consu'
self.bom.type = 'phantom'
self.component.standard_price = 1424
receipt = self.env['stock.picking'].create({
'location_id': self.customer_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': self.picking_type_in.id,
'move_line_ids': [(0, 0, {
'product_id': self.product1.id,
'qty_done': 1,
'product_uom_id': self.product1.uom_id.id,
'location_id': self.customer_location.id,
'location_dest_id': self.stock_location.id,
})]
})
receipt.button_validate()
self.assertEqual(receipt.state, 'done')
self.assertRecordValues(receipt.move_lines, [
{'product_id': self.component.id, 'quantity_done': 1, 'state': 'done'},
])
self.assertEqual(self.component.qty_available, 1)
self.assertEqual(self.component.value_svl, 1424)
| 43.934286
| 15,377
|
1,255
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from collections import defaultdict
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def _get_invoiced_qty_per_product(self):
# Replace the kit-type products with their components
qties = defaultdict(float)
res = super()._get_invoiced_qty_per_product()
invoiced_products = self.env['product.product'].concat(*res.keys())
bom_kits = self.env['mrp.bom']._bom_find(invoiced_products, company_id=self.company_id[:1].id, bom_type='phantom')
for product, qty in res.items():
bom_kit = bom_kits[product]
if bom_kit:
invoiced_qty = product.uom_id._compute_quantity(qty, bom_kit.product_uom_id, round=False)
factor = invoiced_qty / bom_kit.product_qty
dummy, bom_sub_lines = bom_kit.explode(product, factor)
for bom_line, bom_line_data in bom_sub_lines:
qties[bom_line.product_id] += bom_line.product_uom_id._compute_quantity(bom_line_data['qty'], bom_line.product_id.uom_id)
else:
qties[product] += qty
return qties
| 44.821429
| 1,255
|
1,716
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, models
class StockMove(models.Model):
_inherit = "stock.move"
def _filter_anglo_saxon_moves(self, product):
res = super(StockMove, self)._filter_anglo_saxon_moves(product)
res += self.filtered(lambda m: m.bom_line_id.bom_id.product_tmpl_id.id == product.product_tmpl_id.id)
return res
def _generate_analytic_lines_data(self, unit_amount, amount):
vals = super()._generate_analytic_lines_data(unit_amount, amount)
if self.raw_material_production_id.analytic_account_id:
vals['name'] = _('[Raw] %s', self.product_id.display_name)
vals['ref'] = self.raw_material_production_id.display_name
vals['category'] = 'manufacturing_order'
return vals
def _get_analytic_account(self):
account = self.raw_material_production_id.analytic_account_id
if account:
return account
return super()._get_analytic_account()
def _get_src_account(self, accounts_data):
if not self.unbuild_id:
return super()._get_src_account(accounts_data)
else:
return self.location_dest_id.valuation_out_account_id.id or accounts_data['stock_input'].id
def _get_dest_account(self, accounts_data):
if not self.unbuild_id:
return super()._get_dest_account(accounts_data)
else:
return self.location_id.valuation_in_account_id.id or accounts_data['stock_output'].id
def _is_returned(self, valued_type):
if self.unbuild_id:
return True
return super()._is_returned(valued_type)
| 39
| 1,716
|
5,314
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.tools import float_round, groupby
class ProductTemplate(models.Model):
_name = 'product.template'
_inherit = 'product.template'
def action_bom_cost(self):
templates = self.filtered(lambda t: t.product_variant_count == 1 and t.bom_count > 0)
if templates:
return templates.mapped('product_variant_id').action_bom_cost()
def button_bom_cost(self):
templates = self.filtered(lambda t: t.product_variant_count == 1 and t.bom_count > 0)
if templates:
return templates.mapped('product_variant_id').button_bom_cost()
class ProductProduct(models.Model):
_name = 'product.product'
_inherit = 'product.product'
_description = 'Product'
def button_bom_cost(self):
self.ensure_one()
self._set_price_from_bom()
def action_bom_cost(self):
boms_to_recompute = self.env['mrp.bom'].search(['|', ('product_id', 'in', self.ids), '&', ('product_id', '=', False), ('product_tmpl_id', 'in', self.mapped('product_tmpl_id').ids)])
for product in self:
product._set_price_from_bom(boms_to_recompute)
def _set_price_from_bom(self, boms_to_recompute=False):
self.ensure_one()
bom = self.env['mrp.bom']._bom_find(self)[self]
if bom:
self.standard_price = self._compute_bom_price(bom, boms_to_recompute=boms_to_recompute)
else:
bom = self.env['mrp.bom'].search([('byproduct_ids.product_id', '=', self.id)], order='sequence, product_id, id', limit=1)
if bom:
price = self._compute_bom_price(bom, boms_to_recompute=boms_to_recompute, byproduct_bom=True)
if price:
self.standard_price = price
def _compute_average_price(self, qty_invoiced, qty_to_invoice, stock_moves):
self.ensure_one()
if stock_moves.product_id == self:
return super()._compute_average_price(qty_invoiced, qty_to_invoice, stock_moves)
bom = self.env['mrp.bom']._bom_find(self, company_id=stock_moves.company_id.id, bom_type='phantom')[self]
if not bom:
return super()._compute_average_price(qty_invoiced, qty_to_invoice, stock_moves)
value = 0
dummy, bom_lines = bom.explode(self, 1)
bom_lines = {line: data for line, data in bom_lines}
for bom_line, moves_list in groupby(stock_moves.filtered(lambda sm: sm.state != 'cancel'), lambda sm: sm.bom_line_id):
if bom_line not in bom_lines:
for move in moves_list:
value += move.product_qty * move.product_id._compute_average_price(qty_invoiced * move.product_qty, qty_to_invoice * move.product_qty, move)
continue
line_qty = bom_line.product_uom_id._compute_quantity(bom_lines[bom_line]['qty'], bom_line.product_id.uom_id)
moves = self.env['stock.move'].concat(*moves_list)
value += line_qty * bom_line.product_id._compute_average_price(qty_invoiced * line_qty, qty_to_invoice * line_qty, moves)
return value
def _compute_bom_price(self, bom, boms_to_recompute=False, byproduct_bom=False):
self.ensure_one()
if not bom:
return 0
if not boms_to_recompute:
boms_to_recompute = []
total = 0
for opt in bom.operation_ids:
if opt._skip_operation_line(self):
continue
duration_expected = (
opt.workcenter_id.time_start +
opt.workcenter_id.time_stop +
opt.time_cycle * 100 / opt.workcenter_id.time_efficiency)
total += (duration_expected / 60) * opt.workcenter_id.costs_hour
for line in bom.bom_line_ids:
if line._skip_bom_line(self):
continue
# Compute recursive if line has `child_line_ids`
if line.child_bom_id and line.child_bom_id in boms_to_recompute:
child_total = line.product_id._compute_bom_price(line.child_bom_id, boms_to_recompute=boms_to_recompute)
total += line.product_id.uom_id._compute_price(child_total, line.product_uom_id) * line.product_qty
else:
total += line.product_id.uom_id._compute_price(line.product_id.standard_price, line.product_uom_id) * line.product_qty
if byproduct_bom:
byproduct_lines = bom.byproduct_ids.filtered(lambda b: b.product_id == self and b.cost_share != 0)
product_uom_qty = 0
for line in byproduct_lines:
product_uom_qty += line.product_uom_id._compute_quantity(line.product_qty, self.uom_id, round=False)
byproduct_cost_share = sum(byproduct_lines.mapped('cost_share'))
if byproduct_cost_share and product_uom_qty:
return total * byproduct_cost_share / 100 / product_uom_qty
else:
byproduct_cost_share = sum(bom.byproduct_ids.mapped('cost_share'))
if byproduct_cost_share:
total *= float_round(1 - byproduct_cost_share / 100, precision_rounding=0.0001)
return bom.product_uom_id._compute_price(total / bom.product_qty, self.uom_id)
| 49.203704
| 5,314
|
612
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class StockRule(models.Model):
_inherit = 'stock.rule'
def _prepare_mo_vals(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom):
res = super()._prepare_mo_vals(product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom)
if not bom.analytic_account_id and values.get('analytic_account_id'):
res['analytic_account_id'] = values.get('analytic_account_id').id
return res
| 43.714286
| 612
|
6,228
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from odoo import api, fields, models, _
from odoo.tools import float_is_zero, float_round
class MrpProductionWorkcenterLineTime(models.Model):
_inherit = 'mrp.workcenter.productivity'
cost_already_recorded = fields.Boolean('Cost Recorded', help="Technical field automatically checked when a ongoing production posts journal entries for its costs. This way, we can record one production's cost multiple times and only consider new entries in the work centers time lines.")
class MrpProduction(models.Model):
_inherit = 'mrp.production'
extra_cost = fields.Float(copy=False, help='Extra cost per produced unit')
show_valuation = fields.Boolean(compute='_compute_show_valuation')
analytic_account_id = fields.Many2one(
'account.analytic.account', 'Analytic Account', copy=True,
help="Analytic account in which cost and revenue entries will take\
place for financial management of the manufacturing order.",
compute='_compute_analytic_account_id', store=True, readonly=False)
def _compute_show_valuation(self):
for order in self:
order.show_valuation = any(m.state == 'done' for m in order.move_finished_ids)
@api.depends('bom_id')
def _compute_analytic_account_id(self):
if self.bom_id.analytic_account_id:
self.analytic_account_id = self.bom_id.analytic_account_id
def write(self, vals):
origin_analytic_account = {production: production.analytic_account_id for production in self}
res = super().write(vals)
for production in self:
if vals.get('name'):
production.move_raw_ids.analytic_account_line_id.ref = production.display_name
for workorder in production.workorder_ids:
workorder.mo_analytic_account_line_id.ref = production.display_name
workorder.mo_analytic_account_line_id.name = _("[WC] %s", workorder.display_name)
if 'analytic_account_id' in vals and production.state != 'draft':
if vals['analytic_account_id'] and origin_analytic_account[production]:
# Link the account analytic lines to the new AA
production.move_raw_ids.analytic_account_line_id.write({'account_id': vals['analytic_account_id']})
production.workorder_ids.mo_analytic_account_line_id.write({'account_id': vals['analytic_account_id']})
elif vals['analytic_account_id'] and not origin_analytic_account[production]:
# Create the account analytic lines if no AA is set in the MO
production.move_raw_ids._account_analytic_entry_move()
production.workorder_ids._create_or_update_analytic_entry()
else:
production.move_raw_ids.analytic_account_line_id.unlink()
production.workorder_ids.mo_analytic_account_line_id.unlink()
return res
def action_view_stock_valuation_layers(self):
self.ensure_one()
domain = [('id', 'in', (self.move_raw_ids + self.move_finished_ids + self.scrap_ids.move_id).stock_valuation_layer_ids.ids)]
action = self.env["ir.actions.actions"]._for_xml_id("stock_account.stock_valuation_layer_action")
context = literal_eval(action['context'])
context.update(self.env.context)
context['no_at_date'] = True
context['search_default_group_by_product_id'] = False
return dict(action, domain=domain, context=context)
def action_view_analytic_account(self):
self.ensure_one()
return {
"type": "ir.actions.act_window",
"res_model": "account.analytic.account",
'res_id': self.analytic_account_id.id,
"context": {"create": False},
"name": _("Analytic Account"),
'view_mode': 'form',
}
def _cal_price(self, consumed_moves):
"""Set a price unit on the finished move according to `consumed_moves`.
"""
super(MrpProduction, self)._cal_price(consumed_moves)
work_center_cost = 0
finished_move = self.move_finished_ids.filtered(
lambda x: x.product_id == self.product_id and x.state not in ('done', 'cancel') and x.quantity_done > 0)
if finished_move:
finished_move.ensure_one()
for work_order in self.workorder_ids:
time_lines = work_order.time_ids.filtered(
lambda x: x.date_end and not x.cost_already_recorded)
duration = sum(time_lines.mapped('duration'))
time_lines.write({'cost_already_recorded': True})
work_center_cost += (duration / 60.0) * \
work_order.workcenter_id.costs_hour
qty_done = finished_move.product_uom._compute_quantity(
finished_move.quantity_done, finished_move.product_id.uom_id)
extra_cost = self.extra_cost * qty_done
total_cost = - sum(consumed_moves.sudo().stock_valuation_layer_ids.mapped('value')) + work_center_cost + extra_cost
byproduct_moves = self.move_byproduct_ids.filtered(lambda m: m.state not in ('done', 'cancel') and m.quantity_done > 0)
byproduct_cost_share = 0
for byproduct in byproduct_moves:
if byproduct.cost_share == 0:
continue
byproduct_cost_share += byproduct.cost_share
if byproduct.product_id.cost_method in ('fifo', 'average'):
byproduct.price_unit = total_cost * byproduct.cost_share / 100 / byproduct.product_uom._compute_quantity(byproduct.quantity_done, byproduct.product_id.uom_id)
if finished_move.product_id.cost_method in ('fifo', 'average'):
finished_move.price_unit = total_cost * float_round(1 - byproduct_cost_share / 100, precision_rounding=0.0001) / qty_done
return True
def _get_backorder_mo_vals(self):
res = super()._get_backorder_mo_vals()
res['extra_cost'] = self.extra_cost
return res
| 54.156522
| 6,228
|
3,803
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
from odoo.tools import float_is_zero
class MrpWorkorder(models.Model):
_inherit = 'mrp.workorder'
mo_analytic_account_line_id = fields.Many2one('account.analytic.line', copy=False)
wc_analytic_account_line_id = fields.Many2one('account.analytic.line', copy=False)
def _compute_duration(self):
res = super()._compute_duration()
self._create_or_update_analytic_entry()
return res
def _set_duration(self):
res = super()._set_duration()
self._create_or_update_analytic_entry()
return res
def action_cancel(self):
(self.mo_analytic_account_line_id | self.wc_analytic_account_line_id).unlink()
return super().action_cancel()
def _prepare_analytic_line_values(self, account, unit_amount, amount):
self.ensure_one()
return {
'name': _("[WC] %s", self.display_name),
'amount': amount,
'account_id': account.id,
'unit_amount': unit_amount,
'product_id': self.product_id.id,
'product_uom_id': self.env.ref('uom.product_uom_hour').id,
'company_id': self.company_id.id,
'ref': self.production_id.name,
'category': 'manufacturing_order',
}
def _create_or_update_analytic_entry(self):
wo_to_link_mo_analytic_line = self.env['mrp.workorder']
wo_to_link_wc_analytic_line = self.env['mrp.workorder']
mo_analytic_line_vals_list = []
wc_analytic_line_vals_list = []
for wo in self.filtered(lambda wo: wo.production_id.analytic_account_id or wo.workcenter_id.costs_hour_account_id):
hours = wo.duration / 60.0
value = -hours * wo.workcenter_id.costs_hour
mo_account = wo.production_id.analytic_account_id
wc_account = wo.workcenter_id.costs_hour_account_id
if mo_account:
mo_currency = mo_account.currency_id or wo.company_id.currency_id
is_zero = float_is_zero(value, precision_rounding=mo_currency.rounding)
if wo.mo_analytic_account_line_id:
wo.mo_analytic_account_line_id.write({
'unit_amount': hours,
'amount': value if not is_zero else 0,
})
elif not is_zero:
wo_to_link_mo_analytic_line += wo
mo_analytic_line_vals_list.append(wo._prepare_analytic_line_values(mo_account, hours, value))
if wc_account and wc_account != mo_account:
is_zero = float_is_zero(value, precision_rounding=wc_account.currency_id.rounding)
if wo.wc_analytic_account_line_id:
wo.wc_analytic_account_line_id.write({
'unit_amount': hours,
'amount': value if not is_zero else 0,
})
elif not is_zero:
wo_to_link_wc_analytic_line += wo
wc_analytic_line_vals_list.append(wo._prepare_analytic_line_values(wc_account, hours, value))
analytic_lines = self.env['account.analytic.line'].sudo().create(mo_analytic_line_vals_list + wc_analytic_line_vals_list)
mo_analytic_lines, wc_analytic_lines = analytic_lines[:len(wo_to_link_mo_analytic_line)], analytic_lines[len(wo_to_link_mo_analytic_line):]
for wo, analytic_line in zip(wo_to_link_mo_analytic_line, mo_analytic_lines):
wo.mo_analytic_account_line_id = analytic_line
for wo, analytic_line in zip(wo_to_link_wc_analytic_line, wc_analytic_lines):
wo.wc_analytic_account_line_id = analytic_line
| 48.75641
| 3,803
|
3,104
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class AccountAnalyticAccount(models.Model):
_inherit = 'account.analytic.account'
_description = 'Analytic Account'
production_ids = fields.One2many('mrp.production', 'analytic_account_id', string='Manufacturing Orders')
production_count = fields.Integer("Manufacturing Orders Count", compute='_compute_production_count')
bom_ids = fields.One2many('mrp.bom', 'analytic_account_id', string='Bills of Materials')
bom_count = fields.Integer("BoM Count", compute='_compute_bom_count')
workcenter_ids = fields.One2many('mrp.workcenter', 'costs_hour_account_id', string='Workcenters')
workorder_count = fields.Integer("Work Order Count", compute='_compute_workorder_count')
@api.depends('production_ids')
def _compute_production_count(self):
for account in self:
account.production_count = len(account.production_ids)
@api.depends('bom_ids')
def _compute_bom_count(self):
for account in self:
account.bom_count = len(account.bom_ids)
@api.depends('workcenter_ids.order_ids', 'production_ids.workorder_ids')
def _compute_workorder_count(self):
for account in self:
account.workorder_count = len(account.workcenter_ids.order_ids | account.production_ids.workorder_ids)
def action_view_mrp_production(self):
self.ensure_one()
result = {
"type": "ir.actions.act_window",
"res_model": "mrp.production",
"domain": [['id', 'in', self.production_ids.ids]],
"name": _("Manufacturing Orders"),
'view_mode': 'tree,form',
"context": {'default_analytic_account_id': self.id},
}
if len(self.production_ids) == 1:
result['view_mode'] = 'form'
result['res_id'] = self.production_ids.id
return result
def action_view_mrp_bom(self):
self.ensure_one()
result = {
"type": "ir.actions.act_window",
"res_model": "mrp.bom",
"domain": [['id', 'in', self.bom_ids.ids]],
"name": _("Bills of Materials"),
'view_mode': 'tree,form',
"context": {'default_analytic_account_id': self.id},
}
if self.bom_count == 1:
result['view_mode'] = 'form'
result['res_id'] = self.bom_ids.id
return result
def action_view_workorder(self):
self.ensure_one()
result = {
"type": "ir.actions.act_window",
"res_model": "mrp.workorder",
"domain": [['id', 'in', (self.workcenter_ids.order_ids | self.production_ids.workorder_ids).ids]],
"context": {"create": False},
"name": _("Work Orders"),
'view_mode': 'tree',
}
return result
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
category = fields.Selection(selection_add=[('manufacturing_order', 'Manufacturing Order')])
| 39.291139
| 3,104
|
448
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class MrpBom(models.Model):
_inherit = 'mrp.bom'
analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account', company_dependent=True, copy=True,
help="Analytic account in which cost and revenue entries will take place for financial management of the manufacturing order.")
| 44.8
| 448
|
413
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class MrpWorkcenter(models.Model):
_inherit = 'mrp.workcenter'
costs_hour_account_id = fields.Many2one(
'account.analytic.account', string='Analytic Account',
help="Fill this only if you want automatic analytic accounting entries on production orders.")
| 34.416667
| 413
|
777
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Coupon",
'summary': "Use discount coupons in different sales channels.",
'description': """Integrate coupon mechanism in orders.""",
'category': 'Sales',
'version': '1.0',
'depends': ['account'],
'data': [
'wizard/coupon_generate_views.xml',
'security/ir.model.access.csv',
'security/coupon_security.xml',
'views/coupon_views.xml',
'views/coupon_program_views.xml',
'report/coupon_report.xml',
'report/coupon_report_templates.xml',
'data/expire_coupon_cron.xml',
],
'demo': [
'demo/coupon_demo.xml',
],
'installable': True,
'license': 'LGPL-3',
}
| 31.08
| 777
|
2,693
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import _, api, fields, models
import ast
from odoo.osv import expression
class CouponGenerate(models.TransientModel):
_name = 'coupon.generate.wizard'
_description = 'Generate Coupon'
nbr_coupons = fields.Integer(string="Number of Coupons", help="Number of coupons", default=1)
generation_type = fields.Selection([
('nbr_coupon', 'Number of Coupons'),
('nbr_customer', 'Number of Selected Customers')
], default='nbr_coupon')
partners_domain = fields.Char(string="Customer", default='[]')
has_partner_email = fields.Boolean(compute='_compute_has_partner_email')
template_id = fields.Many2one('mail.template', 'Use template', domain="[('model', '=', 'coupon.coupon')]")
def generate_coupon(self):
"""Generates the number of coupons entered in wizard field nbr_coupons
"""
program = self.env['coupon.program'].browse(self.env.context.get('active_id'))
vals = {'program_id': program.id}
if self.generation_type == 'nbr_coupon' and self.nbr_coupons > 0:
for count in range(0, self.nbr_coupons):
self.env['coupon.coupon'].create(vals)
if self.generation_type == 'nbr_customer' and self.partners_domain:
for partner in self.env['res.partner'].search(ast.literal_eval(self.partners_domain)):
vals.update({'partner_id': partner.id, 'state': 'sent' if partner.email else 'new'})
coupon = self.env['coupon.coupon'].create(vals)
context = dict(lang=partner.lang)
subject = _('%s, a coupon has been generated for you') % (partner.name)
del context
if self.template_id:
email_values = {'email_from': self.env.user.email or '', 'subject': subject}
self.template_id.send_mail(coupon.id, email_values=email_values, notif_layout='mail.mail_notification_light')
@api.depends('partners_domain')
def _compute_has_partner_email(self):
for record in self:
partners_domain = ast.literal_eval(record.partners_domain)
if partners_domain == [['', '=', 1]]:
# The field name is not clear. It actually means "all partners have email".
# If domain is not set, we don't want to show the warning "there is a partner without email".
# So, we explicitly set value to True
record.has_partner_email = True
continue
domain = expression.AND([partners_domain, [('email', '=', False)]])
record.has_partner_email = self.env['res.partner'].search_count(domain) == 0
| 48.963636
| 2,693
|
1,789
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class CouponRule(models.Model):
_name = 'coupon.rule'
_description = "Coupon Rule"
rule_date_from = fields.Datetime(string="Start Date", help="Coupon program start date")
rule_date_to = fields.Datetime(string="End Date", help="Coupon program end date")
rule_partners_domain = fields.Char(string="Based on Customers", help="Coupon program will work for selected customers only")
rule_products_domain = fields.Char(string="Based on Products", default=[['sale_ok', '=', True]], help="On Purchase of selected product, reward will be given")
rule_min_quantity = fields.Integer(string="Minimum Quantity", default=1,
help="Minimum required product quantity to get the reward")
rule_minimum_amount = fields.Float(default=0.0, help="Minimum required amount to get the reward")
rule_minimum_amount_tax_inclusion = fields.Selection([
('tax_included', 'Tax Included'),
('tax_excluded', 'Tax Excluded')], default="tax_excluded")
_sql_constraints = [
('check_coupon_rule_dates', 'check(rule_date_from < rule_date_to)', 'The start date must be before the end date!'),
]
@api.constrains('rule_minimum_amount')
def _check_rule_minimum_amount(self):
if self.filtered(lambda applicability: applicability.rule_minimum_amount < 0):
raise ValidationError(_('Minimum purchased amount should be greater than 0'))
@api.constrains('rule_min_quantity')
def _check_rule_min_quantity(self):
if not self.rule_min_quantity > 0:
raise ValidationError(_('Minimum quantity should be greater than 0'))
| 51.114286
| 1,789
|
4,852
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from uuid import uuid4
class Coupon(models.Model):
_name = 'coupon.coupon'
_description = "Coupon"
_rec_name = 'code'
@api.model
def _generate_code(self):
"""Generate a 20 char long pseudo-random string of digits for barcode
generation.
A decimal serialisation is longer than a hexadecimal one *but* it
generates a more compact barcode (Code128C rather than Code128A).
Generate 8 bytes (64 bits) barcodes as 16 bytes barcodes are not
compatible with all scanners.
"""
return str(uuid4())[:22]
code = fields.Char(default=lambda self: self._generate_code(), required=True, readonly=True)
expiration_date = fields.Date('Expiration Date', compute='_compute_expiration_date')
state = fields.Selection([
('reserved', 'Pending'),
('new', 'Valid'),
('sent', 'Sent'),
('used', 'Used'),
('expired', 'Expired'),
('cancel', 'Cancelled')
], required=True, default='new')
partner_id = fields.Many2one('res.partner', "For Customer")
program_id = fields.Many2one('coupon.program', "Program")
discount_line_product_id = fields.Many2one('product.product', related='program_id.discount_line_product_id', readonly=False,
help='Product used in the sales order to apply the discount.')
_sql_constraints = [
('unique_coupon_code', 'unique(code)', 'The coupon code must be unique!'),
]
@api.depends('create_date', 'program_id.validity_duration')
def _compute_expiration_date(self):
self.expiration_date = 0
for coupon in self.filtered(lambda x: x.program_id.validity_duration > 0):
coupon.expiration_date = (coupon.create_date + relativedelta(days=coupon.program_id.validity_duration)).date()
def _get_default_template(self):
return False
def action_coupon_send(self):
""" Open a window to compose an email, with the edi invoice template
message loaded by default
"""
self.ensure_one()
default_template = self._get_default_template()
compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)
ctx = dict(
default_model='coupon.coupon',
default_res_id=self.id,
default_use_template=bool(default_template),
default_template_id=default_template and default_template.id,
default_composition_mode='comment',
custom_layout='mail.mail_notification_light',
mark_coupon_as_sent=True,
force_email=True,
)
return {
'name': _('Compose Email'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form.id, 'form')],
'view_id': compose_form.id,
'target': 'new',
'context': ctx,
}
def action_coupon_cancel(self):
self.state = 'cancel'
def cron_expire_coupon(self):
self._cr.execute("""
SELECT C.id FROM COUPON_COUPON as C
INNER JOIN COUPON_PROGRAM as P ON C.program_id = P.id
WHERE C.STATE in ('reserved', 'new', 'sent')
AND P.validity_duration > 0
AND C.create_date + interval '1 day' * P.validity_duration < now()""")
expired_ids = [res[0] for res in self._cr.fetchall()]
self.browse(expired_ids).write({'state': 'expired'})
def _check_coupon_code(self, order_date, partner_id, **kwargs):
""" Check the validity of this single coupon.
:param order_date Date:
:param partner_id int | boolean:
"""
self.ensure_one()
message = {}
if self.state == 'used':
message = {'error': _('This coupon has already been used (%s).') % (self.code)}
elif self.state == 'reserved':
message = {'error': _('This coupon %s exists but the origin sales order is not validated yet.') % (self.code)}
elif self.state == 'cancel':
message = {'error': _('This coupon has been cancelled (%s).') % (self.code)}
elif self.state == 'expired' or (self.expiration_date and self.expiration_date < order_date):
message = {'error': _('This coupon is expired (%s).') % (self.code)}
elif not self.program_id.active:
message = {'error': _('The coupon program for %s is in draft or closed state') % (self.code)}
elif self.partner_id and self.partner_id.id != partner_id:
message = {'error': _('Invalid partner.')}
return message
| 41.470085
| 4,852
|
641
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailComposeMessage(models.TransientModel):
_inherit = 'mail.compose.message'
def _action_send_mail(self, **kwargs):
for wizard in self:
if self._context.get('mark_coupon_as_sent') and wizard.model == 'coupon.coupon' and wizard.partner_ids:
# Mark coupon as sent in sudo, as helpdesk users don't have the right to write on coupons
self.env[wizard.model].sudo().browse(wizard.res_id).state = 'sent'
return super()._action_send_mail(**kwargs)
| 42.733333
| 641
|
801
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
from odoo.exceptions import UserError
class ProductProduct(models.Model):
_inherit = 'product.product'
@api.ondelete(at_uninstall=False)
def _unlink_except_linked_with_coupon_program(self):
'''
This methods prevents deleting Reward line product that is linked
with Coupon/Promotion
:return:
'''
coupon_prog_count = self.env['coupon.program'].sudo().with_context(active_test=False).search_count([('discount_line_product_id', 'in', self.ids)])
if coupon_prog_count > 0:
raise UserError(_("You cannot delete a product that is linked with Coupon or Promotion program. Archive it instead."))
| 42.157895
| 801
|
8,532
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
import ast
class CouponProgram(models.Model):
_name = 'coupon.program'
_description = "Coupon Program"
_inherits = {'coupon.rule': 'rule_id', 'coupon.reward': 'reward_id'}
# We should apply 'discount' promotion first to avoid offering free product when we should not.
# Eg: If the discount lower the SO total below the required threshold
# Note: This is only revelant when programs have the same sequence (which they have by default)
_order = "sequence, reward_type"
name = fields.Char(required=True, translate=True)
active = fields.Boolean('Active', default=True, help="A program is available for the customers when active")
rule_id = fields.Many2one('coupon.rule', string="Coupon Rule", ondelete='restrict', required=True)
reward_id = fields.Many2one('coupon.reward', string="Reward", ondelete='restrict', required=True, copy=False)
sequence = fields.Integer(copy=False,
help="Coupon program will be applied based on given sequence if multiple programs are " +
"defined on same condition(For minimum amount)")
maximum_use_number = fields.Integer(help="Maximum number of sales orders in which reward can be provided")
program_type = fields.Selection([
('promotion_program', 'Promotional Program'),
('coupon_program', 'Coupon Program'),
],
help="""A promotional program can be either a limited promotional offer without code (applied automatically)
or with a code (displayed on a magazine for example) that may generate a discount on the current
order or create a coupon for a next order.
A coupon program generates coupons with a code that can be used to generate a discount on the current
order or create a coupon for a next order.""")
promo_code_usage = fields.Selection([
('no_code_needed', 'Automatically Applied'),
('code_needed', 'Use a code')],
help="Automatically Applied - No code is required, if the program rules are met, the reward is applied (Except the global discount or the free shipping rewards which are not cumulative)\n" +
"Use a code - If the program rules are met, a valid code is mandatory for the reward to be applied\n")
promo_code = fields.Char('Promotion Code', copy=False,
help="A promotion code is a code that is associated with a marketing discount. For example, a retailer might tell frequent customers to enter the promotion code 'THX001' to receive a 10%% discount on their whole order.")
promo_applicability = fields.Selection([
('on_current_order', 'Apply On Current Order'),
('on_next_order', 'Send a Coupon')],
default='on_current_order', string="Applicability")
coupon_ids = fields.One2many('coupon.coupon', 'program_id', string="Generated Coupons", copy=False)
coupon_count = fields.Integer(compute='_compute_coupon_count')
company_id = fields.Many2one('res.company', string="Company", required=True, default=lambda self: self.env.company)
currency_id = fields.Many2one(string="Currency", related='company_id.currency_id', readonly=True)
validity_duration = fields.Integer(default=30,
help="Validity duration for a coupon after its generation")
total_order_count = fields.Integer("Total Order Count", compute="_compute_total_order_count")
@api.constrains('promo_code')
def _check_promo_code_constraint(self):
""" Program code must be unique """
for program in self.filtered(lambda p: p.promo_code):
domain = [('id', '!=', program.id), ('promo_code', '=', program.promo_code)]
if self.search(domain):
raise ValidationError(_('The program code must be unique!'))
@api.depends('coupon_ids')
def _compute_coupon_count(self):
coupon_data = self.env['coupon.coupon'].read_group([('program_id', 'in', self.ids)], ['program_id'], ['program_id'])
mapped_data = dict([(m['program_id'][0], m['program_id_count']) for m in coupon_data])
for program in self:
program.coupon_count = mapped_data.get(program.id, 0)
@api.onchange('promo_code_usage')
def _onchange_promo_code_usage(self):
if self.promo_code_usage == 'no_code_needed':
self.promo_code = False
@api.onchange('reward_product_id')
def _onchange_reward_product_id(self):
if self.reward_product_id:
self.reward_product_uom_id = self.reward_product_id.uom_id
@api.onchange('discount_type')
def _onchange_discount_type(self):
if self.discount_type == 'fixed_amount':
self.discount_apply_on = 'on_order'
@api.model
def create(self, vals):
program = super(CouponProgram, self).create(vals)
if not vals.get('discount_line_product_id', False):
values = program._get_discount_product_values()
discount_line_product_id = self.env['product.product'].create(values)
program.write({'discount_line_product_id': discount_line_product_id.id})
return program
def write(self, vals):
res = super(CouponProgram, self).write(vals)
if not self:
return res
reward_fields = [
'reward_type', 'reward_product_id', 'discount_type', 'discount_percentage',
'discount_apply_on', 'discount_specific_product_ids', 'discount_fixed_amount'
]
if any(field in reward_fields for field in vals):
for program in self:
program.discount_line_product_id.write({'name': program.reward_id.display_name})
return res
@api.ondelete(at_uninstall=False)
def _unlink_except_active(self):
if self.filtered('active'):
raise UserError(_('You can not delete a program in active state'))
def unlink(self):
# get reference to rule and reward
rule = self.rule_id
reward = self.reward_id
# unlink the program
super(CouponProgram, self).unlink()
# then unlink the rule and reward
rule.unlink()
reward.unlink()
return True
def toggle_active(self):
super(CouponProgram, self).toggle_active()
for program in self:
program.discount_line_product_id.active = program.active
coupons = self.filtered(lambda p: not p.active and p.promo_code_usage == 'code_needed').mapped('coupon_ids')
coupons.filtered(lambda x: x.state != 'used').write({'state': 'expired'})
def _compute_program_amount(self, field, currency_to):
self.ensure_one()
return self.currency_id._convert(self[field], currency_to, self.company_id, fields.Date.today())
def _is_valid_partner(self, partner):
if self.rule_partners_domain and self.rule_partners_domain != '[]':
domain = ast.literal_eval(self.rule_partners_domain) + [('id', '=', partner.id)]
return bool(self.env['res.partner'].search_count(domain))
else:
return True
def _get_valid_products(self, products):
"""Get valid products for the program.
:param products: records of product.product
:return: valid products recordset
"""
if self.rule_products_domain and self.rule_products_domain != "[]":
domain = ast.literal_eval(self.rule_products_domain)
return products.filtered_domain(domain)
return products
def _generate_coupons(self, partner_id):
'''Generate coupons that can be used in the next order for the given partner_id.'''
generated_coupons = self.env['coupon.coupon']
for program in self:
generated_coupons |= self.env['coupon.coupon'].create({
'program_id': program.id,
'partner_id': partner_id,
})
return generated_coupons
def _compute_total_order_count(self):
for program in self:
program.total_order_count = 0
def _get_discount_product_values(self):
return {
'name': self.reward_id.display_name,
'type': 'service',
'taxes_id': False,
'supplier_taxes_id': False,
'sale_ok': False,
'purchase_ok': False,
'lst_price': 0, #Do not set a high value to avoid issue with coupon code
}
| 48.477273
| 8,532
|
5,085
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class CouponReward(models.Model):
_name = 'coupon.reward'
_description = "Coupon Reward"
_rec_name = 'reward_description'
# VFE FIXME multi company
"""Rewards are not restricted to a company...
You could have a reward_product_id limited to a specific company A.
But still use this reward as reward of a program of company B...
"""
reward_description = fields.Char('Reward Description')
reward_type = fields.Selection([
('discount', 'Discount'),
('product', 'Free Product'),
], string='Reward Type', default='discount',
help="Discount - Reward will be provided as discount.\n" +
"Free Product - Free product will be provide as reward \n" +
"Free Shipping - Free shipping will be provided as reward (Need delivery module)")
# Product Reward
reward_product_id = fields.Many2one('product.product', string="Free Product",
help="Reward Product")
reward_product_quantity = fields.Integer(string="Quantity", default=1, help="Reward product quantity")
# Discount Reward
discount_type = fields.Selection([
('percentage', 'Percentage'),
('fixed_amount', 'Fixed Amount')], default="percentage",
help="Percentage - Entered percentage discount will be provided\n" +
"Amount - Entered fixed amount discount will be provided")
discount_percentage = fields.Float(string="Discount", default=10,
help='The discount in percentage, between 1 and 100')
discount_apply_on = fields.Selection([
('on_order', 'On Order'),
('cheapest_product', 'On Cheapest Product'),
('specific_products', 'On Specific Products')], default="on_order",
help="On Order - Discount on whole order\n" +
"Cheapest product - Discount on cheapest product of the order\n" +
"Specific products - Discount on selected specific products")
discount_specific_product_ids = fields.Many2many('product.product', string="Products",
help="Products that will be discounted if the discount is applied on specific products")
discount_max_amount = fields.Float(default=0,
help="Maximum amount of discount that can be provided")
discount_fixed_amount = fields.Float(string="Fixed Amount", help='The discount in fixed amount')
reward_product_uom_id = fields.Many2one(related='reward_product_id.product_tmpl_id.uom_id', string='Unit of Measure', readonly=True)
discount_line_product_id = fields.Many2one('product.product', string='Reward Line Product', copy=False,
help="Product used in the sales order to apply the discount. Each coupon program has its own reward product for reporting purpose")
@api.constrains('discount_percentage')
def _check_discount_percentage(self):
if self.filtered(lambda reward: reward.discount_type == 'percentage' and (reward.discount_percentage < 0 or reward.discount_percentage > 100)):
raise ValidationError(_('Discount percentage should be between 1-100'))
def name_get(self):
"""
Returns a complete description of the reward
"""
result = []
for reward in self:
reward_string = ""
if reward.reward_type == 'product':
reward_string = _("Free Product - %s", reward.reward_product_id.name)
elif reward.reward_type == 'discount':
if reward.discount_type == 'percentage':
reward_percentage = str(reward.discount_percentage)
if reward.discount_apply_on == 'on_order':
reward_string = _("%s%% discount on total amount", reward_percentage)
elif reward.discount_apply_on == 'specific_products':
if len(reward.discount_specific_product_ids) > 1:
reward_string = _("%s%% discount on products", reward_percentage)
else:
reward_string = _(
"%(percentage)s%% discount on %(product_name)s",
percentage=reward_percentage,
product_name=reward.discount_specific_product_ids.name
)
elif reward.discount_apply_on == 'cheapest_product':
reward_string = _("%s%% discount on cheapest product", reward_percentage)
elif reward.discount_type == 'fixed_amount':
program = self.env['coupon.program'].search([('reward_id', '=', reward.id)])
reward_string = _(
"%(amount)s %(currency)s discount on total amount",
amount=reward.discount_fixed_amount,
currency=program.currency_id.name
)
result.append((reward.id, reward_string))
return result
| 55.271739
| 5,085
|
535
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class CouponReport(models.AbstractModel):
_name = 'report.coupon.report_coupon'
_description = 'Sales Coupon Report'
@api.model
def _get_report_values(self, docids, data=None):
docs = self.env['coupon.coupon'].browse(docids)
return {
'doc_ids': docs.ids,
'doc_model': 'coupon.coupon',
'data': data,
'docs': docs,
}
| 28.157895
| 535
|
372
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': "Sale Stock Margin",
'category': 'Sales/Sales',
'summary': '',
'description': 'Once the delivery is validated, update the cost on the SO to have an exact margin computation.',
'version': '0.1',
'depends': ['sale_stock', 'sale_margin'],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 31
| 372
|
13,045
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields
from odoo.tests import Form, tagged
from odoo.addons.stock_account.tests.test_stockvaluationlayer import TestStockValuationCommon
@tagged('post_install', '-at_install')
class TestSaleStockMargin(TestStockValuationCommon):
@classmethod
def setUpClass(cls):
super(TestSaleStockMargin, cls).setUpClass()
cls.pricelist = cls.env['product.pricelist'].create({'name': 'Simple Pricelist'})
cls.env['res.currency.rate'].search([]).unlink()
#########
# UTILS #
#########
def _create_sale_order(self):
return self.env['sale.order'].create({
'name': 'Sale order',
'partner_id': self.env.ref('base.partner_admin').id,
'partner_invoice_id': self.env.ref('base.partner_admin').id,
'pricelist_id': self.pricelist.id,
})
def _create_sale_order_line(self, sale_order, product, quantity, price_unit=0):
return self.env['sale.order.line'].create({
'name': 'Sale order',
'order_id': sale_order.id,
'price_unit': price_unit,
'product_id': product.id,
'product_uom_qty': quantity,
'product_uom': self.env.ref('uom.product_uom_unit').id,
})
def _create_product(self):
product_template = self.env['product.template'].create({
'name': 'Super product',
'type': 'product',
})
product_template.categ_id.property_cost_method = 'fifo'
return product_template.product_variant_ids
#########
# TESTS #
#########
def test_sale_stock_margin_1(self):
sale_order = self._create_sale_order()
product = self._create_product()
self._make_in_move(product, 2, 35)
self._make_out_move(product, 1)
order_line = self._create_sale_order_line(sale_order, product, 1, 50)
sale_order.action_confirm()
self.assertEqual(order_line.purchase_price, 35)
self.assertEqual(sale_order.margin, 15)
sale_order.picking_ids.move_lines.quantity_done = 1
sale_order.picking_ids.button_validate()
self.assertEqual(order_line.purchase_price, 35)
self.assertEqual(order_line.margin, 15)
self.assertEqual(sale_order.margin, 15)
def test_sale_stock_margin_2(self):
sale_order = self._create_sale_order()
product = self._create_product()
self._make_in_move(product, 2, 32)
self._make_in_move(product, 5, 17)
self._make_out_move(product, 1)
order_line = self._create_sale_order_line(sale_order, product, 2, 50)
sale_order.action_confirm()
self.assertEqual(order_line.purchase_price, 32)
self.assertAlmostEqual(sale_order.margin, 36)
sale_order.picking_ids.move_lines.quantity_done = 2
sale_order.picking_ids.button_validate()
self.assertAlmostEqual(order_line.purchase_price, 24.5)
self.assertAlmostEqual(order_line.margin, 51)
self.assertAlmostEqual(sale_order.margin, 51)
def test_sale_stock_margin_3(self):
sale_order = self._create_sale_order()
product = self._create_product()
self._make_in_move(product, 2, 10)
self._make_out_move(product, 1)
order_line = self._create_sale_order_line(sale_order, product, 2, 20)
sale_order.action_confirm()
self.assertEqual(order_line.purchase_price, 10)
self.assertAlmostEqual(sale_order.margin, 20)
sale_order.picking_ids.move_lines.quantity_done = 1
sale_order.picking_ids.button_validate()
self.assertAlmostEqual(order_line.purchase_price, 10)
self.assertAlmostEqual(order_line.margin, 20)
self.assertAlmostEqual(sale_order.margin, 20)
def test_sale_stock_margin_4(self):
sale_order = self._create_sale_order()
product = self._create_product()
self._make_in_move(product, 2, 10)
self._make_in_move(product, 1, 20)
self._make_out_move(product, 1)
order_line = self._create_sale_order_line(sale_order, product, 2, 20)
sale_order.action_confirm()
self.assertEqual(order_line.purchase_price, 10)
self.assertAlmostEqual(sale_order.margin, 20)
sale_order.picking_ids.move_lines.quantity_done = 1
res = sale_order.picking_ids.button_validate()
Form(self.env[res['res_model']].with_context(res['context'])).save().process()
self.assertAlmostEqual(order_line.purchase_price, 15)
self.assertAlmostEqual(order_line.margin, 10)
self.assertAlmostEqual(sale_order.margin, 10)
def test_sale_stock_margin_5(self):
sale_order = self._create_sale_order()
product_1 = self._create_product()
product_2 = self._create_product()
self._make_in_move(product_1, 2, 35)
self._make_in_move(product_1, 1, 51)
self._make_out_move(product_1, 1)
self._make_in_move(product_2, 2, 17)
self._make_in_move(product_2, 1, 11)
self._make_out_move(product_2, 1)
order_line_1 = self._create_sale_order_line(sale_order, product_1, 2, 60)
order_line_2 = self._create_sale_order_line(sale_order, product_2, 4, 20)
sale_order.action_confirm()
self.assertAlmostEqual(order_line_1.purchase_price, 35)
self.assertAlmostEqual(order_line_2.purchase_price, 17)
self.assertAlmostEqual(order_line_1.margin, 25 * 2)
self.assertAlmostEqual(order_line_2.margin, 3 * 4)
self.assertAlmostEqual(sale_order.margin, 62)
sale_order.picking_ids.move_lines[0].quantity_done = 2
sale_order.picking_ids.move_lines[1].quantity_done = 3
res = sale_order.picking_ids.button_validate()
Form(self.env[res['res_model']].with_context(res['context'])).save().process()
self.assertAlmostEqual(order_line_1.purchase_price, 43) # (35 + 51) / 2
self.assertAlmostEqual(order_line_2.purchase_price, 12.5) # (17 + 11 + 11 + 11) / 4
self.assertAlmostEqual(order_line_1.margin, 34) # (60 - 43) * 2
self.assertAlmostEqual(order_line_2.margin, 30) # (20 - 12.5) * 4
self.assertAlmostEqual(sale_order.margin, 64)
def test_sale_stock_margin_6(self):
""" Test that the purchase price doesn't change when there is a service product in the SO"""
service = self.env['product.product'].create({
'name': 'Service',
'type': 'service',
'list_price': 100.0,
'standard_price': 50.0})
self.product1.list_price = 80.0
self.product1.standard_price = 40.0
sale_order = self._create_sale_order()
order_line_1 = self._create_sale_order_line(sale_order, service, 1, 100)
order_line_2 = self._create_sale_order_line(sale_order, self.product1, 1, 80)
self.assertEqual(order_line_1.purchase_price, 50, "Sales order line cost should be 50.00")
self.assertEqual(order_line_2.purchase_price, 40, "Sales order line cost should be 40.00")
self.assertEqual(order_line_1.margin, 50, "Sales order line profit should be 50.00")
self.assertEqual(order_line_2.margin, 40, "Sales order line profit should be 40.00")
self.assertEqual(sale_order.margin, 90, "Sales order profit should be 90.00")
# Change the purchase price of the service product.
order_line_1.purchase_price = 100.0
self.assertEqual(order_line_1.purchase_price, 100, "Sales order line cost should be 100.00")
# Confirm the sales order.
sale_order.action_confirm()
self.assertEqual(order_line_1.purchase_price, 100, "Sales order line cost should be 100.00")
self.assertEqual(order_line_2.purchase_price, 40, "Sales order line cost should be 40.00")
def test_so_and_multicurrency(self):
ResCurrencyRate = self.env['res.currency.rate']
company_currency = self.env.company.currency_id
other_currency = self.env.ref('base.EUR') if company_currency == self.env.ref('base.USD') else self.env.ref('base.USD')
date = fields.Date.today()
ResCurrencyRate.create({'currency_id': company_currency.id, 'rate': 1, 'name': date})
other_currency_rate = ResCurrencyRate.search([('name', '=', date), ('currency_id', '=', other_currency.id)])
if other_currency_rate:
other_currency_rate.rate = 2
else:
ResCurrencyRate.create({'currency_id': other_currency.id, 'rate': 2, 'name': date})
so = self._create_sale_order()
so.pricelist_id = self.env['product.pricelist'].create({
'name': 'Super Pricelist',
'currency_id': other_currency.id,
})
product = self._create_product()
product.standard_price = 100
product.list_price = 200
so_form = Form(so)
with so_form.order_line.new() as line:
line.product_id = product
so = so_form.save()
so_line = so.order_line
self.assertEqual(so_line.purchase_price, 200)
self.assertEqual(so_line.price_unit, 400)
so.action_confirm()
self.assertEqual(so_line.purchase_price, 200)
self.assertEqual(so_line.price_unit, 400)
def test_so_and_multicompany(self):
""" In a multicompany environnement, when the user is on company C01 and confirms a SO that
belongs to a second company C02, this test ensures that the computations will be based on
C02's data"""
main_company = self.env['res.company']._get_main_company()
main_company_currency = main_company.currency_id
new_company_currency = self.env.ref('base.EUR') if main_company_currency == self.env.ref('base.USD') else self.env.ref('base.USD')
date = fields.Date.today()
self.env['res.currency.rate'].create([
{'currency_id': main_company_currency.id, 'rate': 1, 'name': date, 'company_id': False},
{'currency_id': new_company_currency.id, 'rate': 3, 'name': date, 'company_id': False},
])
new_company = self.env['res.company'].create({
'name': 'Super Company',
'currency_id': new_company_currency.id,
})
self.env.user.company_id = new_company.id
self.pricelist.currency_id = new_company_currency.id
product = self._create_product()
incoming_picking_type = self.env['stock.picking.type'].search([('company_id', '=', new_company.id), ('code', '=', 'incoming')], limit=1)
production_location = self.env['stock.location'].search([('company_id', '=', new_company.id), ('usage', '=', 'production')])
picking = self.env['stock.picking'].create({
'picking_type_id': incoming_picking_type.id,
'location_id': production_location.id,
'location_dest_id': incoming_picking_type.default_location_dest_id.id,
})
self.env['stock.move'].create({
'name': 'Incoming Product',
'product_id': product.id,
'location_id': production_location.id,
'location_dest_id': incoming_picking_type.default_location_dest_id.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1,
'price_unit': 100,
'picking_type_id': incoming_picking_type.id,
'picking_id': picking.id,
})
picking.action_confirm()
res_dict = picking.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
self.pricelist.currency_id = new_company_currency.id
partner = self.env['res.partner'].create({'name': 'Super Partner'})
so = self.env['sale.order'].create({
'name': 'Sale order',
'partner_id': partner.id,
'partner_invoice_id': partner.id,
'pricelist_id': self.pricelist.id,
})
sol = self._create_sale_order_line(so, product, 1, price_unit=200)
self.env.user.company_id = main_company.id
so.action_confirm()
self.assertEqual(sol.purchase_price, 100)
self.assertEqual(sol.margin, 100)
def test_purchase_price_changes(self):
so = self._create_sale_order()
product = self._create_product()
product.categ_id.property_cost_method = 'standard'
product.standard_price = 20
self._create_sale_order_line(so, product, 1, product.list_price)
so_form = Form(so)
with so_form.order_line.edit(0) as line:
line.purchase_price = 15
so = so_form.save()
email_act = so.action_quotation_send()
email_ctx = email_act.get('context', {})
so.with_context(**email_ctx).message_post_with_template(email_ctx.get('default_template_id'))
self.assertEqual(so.state, 'sent')
self.assertEqual(so.order_line[0].purchase_price, 15)
| 41.281646
| 13,045
|
1,446
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
@api.depends('move_ids', 'move_ids.stock_valuation_layer_ids', 'move_ids.picking_id.state')
def _compute_purchase_price(self):
lines_without_moves = self.browse()
for line in self:
product = line.product_id.with_company(line.company_id)
if not line.move_ids:
lines_without_moves |= line
elif product.categ_id.property_cost_method != 'standard':
purch_price = product._compute_average_price(0, line.product_uom_qty, line.move_ids)
if line.product_uom and line.product_uom != product.uom_id:
purch_price = product.uom_id._compute_price(purch_price, line.product_uom)
to_cur = line.currency_id or line.order_id.currency_id
line.purchase_price = product.cost_currency_id._convert(
from_amount=purch_price,
to_currency=to_cur,
company=line.company_id or self.env.company,
date=line.order_id.date_order or fields.Date.today(),
round=False,
) if to_cur and purch_price else purch_price
return super(SaleOrderLine, lines_without_moves)._compute_purchase_price()
| 49.862069
| 1,446
|
429
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Import/Export invoices with generic UBL',
'description': '''
Support for Export/Import in UBL format (2.1).
''',
'version': '1.0',
'category': 'Accounting/Accounting',
'depends': ['account_edi'],
'data': [
'data/ubl_templates.xml',
'data/account_edi_data.xml',
],
'installable': True,
'application': False,
'license': 'LGPL-3',
}
| 25.235294
| 429
|
12,730
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields
from odoo.tools import float_repr, html2plaintext
from odoo.tests.common import Form
from pathlib import PureWindowsPath
import base64
import logging
import markupsafe
_logger = logging.getLogger(__name__)
class AccountEdiFormat(models.Model):
_inherit = 'account.edi.format'
####################################################
# Helpers
####################################################
def _is_ubl(self, filename, tree):
return tree.tag == '{urn:oasis:names:specification:ubl:schema:xsd:Invoice-2}Invoice'
####################################################
# Import
####################################################
def _create_invoice_from_ubl(self, tree):
invoice = self.env['account.move']
journal = invoice._get_default_journal()
move_type = 'out_invoice' if journal.type == 'sale' else 'in_invoice'
element = tree.find('.//{*}InvoiceTypeCode')
if element is not None and element.text == '381':
move_type = 'in_refund' if move_type == 'in_invoice' else 'out_refund'
invoice = invoice.with_context(default_move_type=move_type, default_journal_id=journal.id)
return self._import_ubl(tree, invoice)
def _update_invoice_from_ubl(self, tree, invoice):
invoice = invoice.with_context(default_move_type=invoice.move_type, default_journal_id=invoice.journal_id.id)
return self._import_ubl(tree, invoice)
def _import_ubl(self, tree, invoice):
""" Decodes an UBL invoice into an invoice.
:param tree: the UBL tree to decode.
:param invoice: the invoice to update or an empty recordset.
:returns: the invoice where the UBL data was imported.
"""
def _get_ubl_namespaces():
''' If the namespace is declared with xmlns='...', the namespaces map contains the 'None' key that causes an
TypeError: empty namespace prefix is not supported in XPath
Then, we need to remap arbitrarily this key.
:param tree: An instance of etree.
:return: The namespaces map without 'None' key.
'''
namespaces = tree.nsmap
namespaces['inv'] = namespaces.pop(None)
return namespaces
namespaces = _get_ubl_namespaces()
def _find_value(xpath, element=tree):
return self._find_value(xpath, element, namespaces)
with Form(invoice) as invoice_form:
# Reference
elements = tree.xpath('//cbc:ID', namespaces=namespaces)
if elements:
invoice_form.ref = elements[0].text
elements = tree.xpath('//cbc:InstructionID', namespaces=namespaces)
if elements:
invoice_form.payment_reference = elements[0].text
# Dates
elements = tree.xpath('//cbc:IssueDate', namespaces=namespaces)
if elements:
invoice_form.invoice_date = elements[0].text
elements = tree.xpath('//cbc:PaymentDueDate', namespaces=namespaces)
if elements:
invoice_form.invoice_date_due = elements[0].text
# allow both cbc:PaymentDueDate and cbc:DueDate
elements = tree.xpath('//cbc:DueDate', namespaces=namespaces)
invoice_form.invoice_date_due = invoice_form.invoice_date_due or elements and elements[0].text
# Currency
currency = self._retrieve_currency(_find_value('//cbc:DocumentCurrencyCode'))
if currency and currency.active:
invoice_form.currency_id = currency
# Incoterm
elements = tree.xpath('//cbc:TransportExecutionTerms/cac:DeliveryTerms/cbc:ID', namespaces=namespaces)
if elements:
invoice_form.invoice_incoterm_id = self.env['account.incoterms'].search([('code', '=', elements[0].text)], limit=1)
# Partner
counterpart = 'Customer' if invoice_form.move_type in ('out_invoice', 'out_refund') else 'Supplier'
invoice_form.partner_id = self._retrieve_partner(
name=_find_value(f'//cac:Accounting{counterpart}Party/cac:Party//cbc:Name'),
phone=_find_value(f'//cac:Accounting{counterpart}Party/cac:Party//cbc:Telephone'),
mail=_find_value(f'//cac:Accounting{counterpart}Party/cac:Party//cbc:ElectronicMail'),
vat=_find_value(f'//cac:Accounting{counterpart}Party/cac:Party//cbc:CompanyID'),
)
# Lines
lines_elements = tree.xpath('//cac:InvoiceLine', namespaces=namespaces)
for eline in lines_elements:
with invoice_form.invoice_line_ids.new() as invoice_line_form:
# Product
invoice_line_form.product_id = self._retrieve_product(
default_code=_find_value('cac:Item/cac:SellersItemIdentification/cbc:ID', eline),
name=_find_value('cac:Item/cbc:Name', eline),
barcode=_find_value('cac:Item/cac:StandardItemIdentification/cbc:ID[@schemeID=\'0160\']', eline)
)
# Quantity
elements = eline.xpath('cbc:InvoicedQuantity', namespaces=namespaces)
quantity = elements and float(elements[0].text) or 1.0
invoice_line_form.quantity = quantity
# Price Unit
elements = eline.xpath('cac:Price/cbc:PriceAmount', namespaces=namespaces)
price_unit = elements and float(elements[0].text) or 0.0
elements = eline.xpath('cbc:LineExtensionAmount', namespaces=namespaces)
line_extension_amount = elements and float(elements[0].text) or 0.0
invoice_line_form.price_unit = price_unit or line_extension_amount / invoice_line_form.quantity or 0.0
# Name
elements = eline.xpath('cac:Item/cbc:Description', namespaces=namespaces)
if elements and elements[0].text:
invoice_line_form.name = elements[0].text
invoice_line_form.name = invoice_line_form.name.replace('%month%', str(fields.Date.to_date(invoice_form.invoice_date).month)) # TODO: full name in locale
invoice_line_form.name = invoice_line_form.name.replace('%year%', str(fields.Date.to_date(invoice_form.invoice_date).year))
else:
partner_name = _find_value('//cac:AccountingSupplierParty/cac:Party//cbc:Name')
invoice_line_form.name = "%s (%s)" % (partner_name or '', invoice_form.invoice_date)
# Taxes
tax_element = eline.xpath('cac:TaxTotal/cac:TaxSubtotal', namespaces=namespaces)
invoice_line_form.tax_ids.clear()
for eline in tax_element:
tax = self._retrieve_tax(
amount=_find_value('cbc:Percent', eline),
type_tax_use=invoice_form.journal_id.type
)
if tax:
invoice_line_form.tax_ids.add(tax)
invoice = invoice_form.save()
# Regenerate PDF
attachments = self.env['ir.attachment']
elements = tree.xpath('//cac:AdditionalDocumentReference', namespaces=namespaces)
for element in elements:
attachment_name = element.xpath('cbc:ID', namespaces=namespaces)
attachment_data = element.xpath('cac:Attachment//cbc:EmbeddedDocumentBinaryObject', namespaces=namespaces)
if attachment_name and attachment_data:
text = attachment_data[0].text
# Normalize the name of the file : some e-fff emitters put the full path of the file
# (Windows or Linux style) and/or the name of the xml instead of the pdf.
# Get only the filename with a pdf extension.
name = PureWindowsPath(attachment_name[0].text).stem + '.pdf'
attachments |= self.env['ir.attachment'].create({
'name': name,
'res_id': invoice.id,
'res_model': 'account.move',
'datas': text + '=' * (len(text) % 3), # Fix incorrect padding
'type': 'binary',
'mimetype': 'application/pdf',
})
if attachments:
invoice.with_context(no_new_invoice=True).message_post(attachment_ids=attachments.ids)
return invoice
####################################################
# Export
####################################################
def _get_ubl_values(self, invoice):
''' Get the necessary values to generate the XML. These values will be used in the qweb template when
rendering. Needed values differ depending on the implementation of the UBL, as (sub)template can be overriden
or called dynamically.
:returns: a dictionary with the value used in the template has key and the value as value.
'''
def format_monetary(amount):
# Format the monetary values to avoid trailing decimals (e.g. 90.85000000000001).
return float_repr(amount, invoice.currency_id.decimal_places)
return {
**invoice._prepare_edi_vals_to_export(),
'tax_details': invoice._prepare_edi_tax_details(),
'ubl_version': 2.1,
'type_code': 380 if invoice.move_type == 'out_invoice' else 381,
'payment_means_code': 42 if invoice.journal_id.bank_account_id else 31,
'bank_account': invoice.partner_bank_id,
'note': html2plaintext(invoice.narration) if invoice.narration else False,
'format_monetary': format_monetary,
'customer_vals': {'partner': invoice.commercial_partner_id},
'supplier_vals': {'partner': invoice.company_id.partner_id.commercial_partner_id},
}
def _export_ubl(self, invoice):
self.ensure_one()
# Create file content.
xml_content = markupsafe.Markup("<?xml version='1.0' encoding='UTF-8'?>")
xml_content += self.env.ref('account_edi_ubl.export_ubl_invoice')._render(self._get_ubl_values(invoice))
xml_name = '%s_ubl_2_1.xml' % (invoice.name.replace('/', '_'))
return self.env['ir.attachment'].create({
'name': xml_name,
'raw': xml_content.encode(),
'res_model': 'account.move',
'res_id': invoice.id,
'mimetype': 'application/xml'
})
####################################################
# Account.edi.format override
####################################################
def _create_invoice_from_xml_tree(self, filename, tree, journal=None):
# OVERRIDE
self.ensure_one()
if self.code == 'ubl_2_1' and self._is_ubl(filename, tree) and not self._is_account_edi_ubl_cii_available():
return self._create_invoice_from_ubl(tree)
return super()._create_invoice_from_xml_tree(filename, tree, journal=journal)
def _update_invoice_from_xml_tree(self, filename, tree, invoice):
# OVERRIDE
self.ensure_one()
if self.code == 'ubl_2_1' and self._is_ubl(filename, tree) and not self._is_account_edi_ubl_cii_available():
return self._update_invoice_from_ubl(tree, invoice)
return super()._update_invoice_from_xml_tree(filename, tree, invoice)
def _is_compatible_with_journal(self, journal):
# OVERRIDE
self.ensure_one()
if self.code != 'ubl_2_1':
return super()._is_compatible_with_journal(journal)
return journal.type == 'sale'
def _is_enabled_by_default_on_journal(self, journal):
# OVERRIDE
# UBL is disabled by default to prevent conflict with other implementations of UBL.
self.ensure_one()
if self.code != 'ubl_2_1':
return super()._is_enabled_by_default_on_journal(journal)
return False
def _post_invoice_edi(self, invoices):
# OVERRIDE
self.ensure_one()
if self.code != 'ubl_2_1' or self._is_account_edi_ubl_cii_available():
return super()._post_invoice_edi(invoices)
res = {}
for invoice in invoices:
attachment = self._export_ubl(invoice)
res[invoice] = {'success': True, 'attachment': attachment}
return res
| 48.587786
| 12,730
|
2,089
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Products & Pricelists',
'version': '1.2',
'category': 'Sales/Sales',
'depends': ['base', 'mail', 'uom'],
'description': """
This is the base module for managing products and pricelists in Odoo.
========================================================================
Products support variants, different pricing methods, vendors information,
make to stock/order, different units of measure, packaging and properties.
Pricelists support:
-------------------
* Multiple-level of discount (by product, category, quantities)
* Compute price based on different criteria:
* Other pricelist
* Cost price
* List price
* Vendor price
Pricelists preferences by product and/or partners.
Print product labels with barcode.
""",
'data': [
'data/product_data.xml',
'security/product_security.xml',
'security/ir.model.access.csv',
'wizard/product_label_layout_views.xml',
'views/res_config_settings_views.xml',
'views/product_attribute_views.xml',
'views/product_views.xml',
'views/product_template_views.xml',
'views/product_pricelist_views.xml',
'views/res_partner_views.xml',
'report/product_reports.xml',
'report/product_product_templates.xml',
'report/product_template_templates.xml',
'report/product_packaging.xml',
'report/product_pricelist_report_templates.xml',
],
'demo': [
'data/product_demo.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'web.assets_backend': [
'product/static/src/js/**/*',
],
'web.report_assets_common': [
'product/static/src/scss/report_label_sheet.scss',
],
'web.qunit_suite_tests': [
'product/static/tests/**/*',
],
'web.assets_qweb': [
'product/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 31.651515
| 2,089
|
5,023
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.tools import populate
from datetime import timedelta, date
class Pricelist(models.Model):
_inherit = "product.pricelist"
_populate_sizes = {"small": 20, "medium": 100, "large": 1_500}
_populate_dependencies = ["res.company"]
def _populate(self, size):
# Reflect the settings with data created
self.env['res.config.settings'].create({
'group_product_pricelist': True, # Activate pricelist
'group_sale_pricelist': True, # Activate advanced pricelist
}).execute()
return super()._populate(size)
def _populate_factories(self):
company_ids = self.env.registry.populated_models["res.company"]
return [
("company_id", populate.iterate(company_ids + [False for i in range(len(company_ids))])),
("name", populate.constant('product_pricelist_{counter}')),
("currency_id", populate.randomize(self.env["res.currency"].search([("active", "=", True)]).ids)),
("sequence", populate.randomize([False] + [i for i in range(1, 101)])),
("discount_policy", populate.randomize(["with_discount", "without_discount"])),
("active", populate.randomize([True, False], [0.8, 0.2])),
]
class PricelistItem(models.Model):
_inherit = "product.pricelist.item"
_populate_sizes = {"small": 500, "medium": 5_000, "large": 50_000}
_populate_dependencies = ["product.product", "product.template", "product.pricelist"]
def _populate_factories(self):
pricelist_ids = self.env.registry.populated_models["product.pricelist"]
product_ids = self.env.registry.populated_models["product.product"]
p_tmpl_ids = self.env.registry.populated_models["product.template"]
categ_ids = self.env.registry.populated_models["product.category"]
def get_target_info(iterator, field_name, model_name):
random = populate.Random("pricelist_target")
for values in iterator:
# If product population is updated to consider multi company
# the company of product would have to be considered
# for product_id & product_tmpl_id
applied_on = values["applied_on"]
if applied_on == "0_product_variant":
values["product_id"] = random.choice(product_ids)
elif applied_on == "1_product":
values["product_tmpl_id"] = random.choice(p_tmpl_ids)
elif applied_on == "2_product_category":
values["categ_id"] = random.choice(categ_ids)
yield values
def get_prices(iterator, field_name, model_name):
random = populate.Random("pricelist_prices")
for values in iterator:
# Fixed price, percentage, formula
compute_price = values["compute_price"]
if compute_price == "fixed":
# base = "list_price" = default
# fixed_price
values["fixed_price"] = random.randint(1, 1000)
elif compute_price == "percentage":
# base = "list_price" = default
# percent_price
values["percent_price"] = random.randint(1, 100)
else: # formula
# pricelist base not considered atm.
values["base"] = random.choice(["list_price", "standard_price"])
values["price_discount"] = random.randint(0, 100)
# price_min_margin, price_max_margin
# price_round ??? price_discount, price_surcharge
yield values
now = date.today()
def get_date_start(values, counter, random):
if random.random() > 0.5: # 50 % of chance to have validation dates
return now + timedelta(days=random.randint(-20, 20))
else:
False
def get_date_end(values, counter, random):
if values['date_start']: # 50 % of chance to have validation dates
return values['date_start'] + timedelta(days=random.randint(5, 100))
else:
False
return [
("pricelist_id", populate.randomize(pricelist_ids)),
("applied_on", populate.randomize(
["3_global", "2_product_category", "1_product", "0_product_variant"],
[5, 3, 2, 1],
)),
("compute_price", populate.randomize(
["fixed", "percentage", "formula"],
[5, 3, 1],
)),
("_price", get_prices),
("_target", get_target_info),
("min_quantity", populate.randint(0, 50)),
("date_start", populate.compute(get_date_start)),
("date_end", populate.compute(get_date_end)),
]
| 44.451327
| 5,023
|
7,948
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from collections import defaultdict
from functools import reduce
from odoo import models
from odoo.tools import populate
_logger = logging.getLogger(__name__)
class ProductAttribute(models.Model):
_inherit = "product.attribute"
_populate_sizes = {"small": 20, "medium": 150, "large": 750}
def _populate(self, size):
# Reflect the settings with data created
self.env['res.config.settings'].create({
'group_product_variant': True, # Activate variant
}).execute()
return super()._populate(size)
def _populate_factories(self):
return [
("name", populate.constant('PA_{counter}')),
("sequence", populate.randomize([False] + [i for i in range(1, 101)])),
("create_variant", populate.randomize(["always", "dynamic", "no_variant"])),
]
class ProductAttributeValue(models.Model):
_inherit = "product.attribute.value"
_populate_dependencies = ["product.attribute"]
_populate_sizes = {"small": 100, "medium": 1_000, "large": 10_000}
def _populate_factories(self):
attribute_ids = self.env.registry.populated_models["product.attribute"]
return [
("name", populate.constant('PAV_{counter}')),
("sequence", populate.randomize([False] + [i for i in range(1, 101)])),
("attribute_id", populate.randomize(attribute_ids)),
]
class ProductTemplate(models.Model):
_inherit = "product.template"
_populate_sizes = {"small": 150, "medium": 5_000, "large": 50_000}
_populate_dependencies = ["product.attribute.value", "product.category"]
def _populate(self, size):
res = super()._populate(size)
def set_barcode_variant(sample_ratio):
random = populate.Random('barcode_product_template')
product_variants_ids = res.product_variant_ids.ids
product_variants_ids = random.sample(product_variants_ids, int(len(product_variants_ids) * sample_ratio))
product_variants = self.env['product.product'].browse(product_variants_ids)
_logger.info('Set barcode on product variants (%s)', len(product_variants))
for product in product_variants:
product.barcode = "BARCODE-PT-%s" % product.id
set_barcode_variant(0.85)
return res
def _populate_factories(self):
attribute_ids = self.env.registry.populated_models["product.attribute"]
attribute_ids_by_types = defaultdict(list)
attributes = self.env["product.attribute"].browse(attribute_ids)
for attr in attributes:
attribute_ids_by_types[attr.create_variant].append(attr.id)
def get_attributes(values, counter, random):
if random.random() < 0.20: # 20 % chance to have no attributes
return False
attributes_qty = random.choices(
[1, 2, 3, 4, 5, 6, 8, 10],
[10, 9, 8, 7, 6, 4, 1, 0.5],
)[0]
attr_line_vals = []
attribute_used_ids = attribute_ids
if random.random() < 0.20: # 20 % chance of using only always attributes (to test when product has lot of variant)
attribute_used_ids = attribute_ids_by_types["always"]
no_variant = False
values_count = [0 for i in range(attributes_qty)]
def will_exceed(i):
return not no_variant and reduce((lambda x, y: (x or 1) * (y or 1)), values_count[i:] + [values_count[i] + 1] + values_count[:i]) > 1000
for i in range(attributes_qty):
if will_exceed(i):
return attr_line_vals
attr_id = random.choice(attribute_used_ids)
attr = self.env["product.attribute"].browse(attr_id)
if attr.create_variant == "dynamic":
no_variant = True
if not attr.value_ids:
# attribute without any value
continue
nb_values = len(attr.value_ids)
vals_qty = random.randrange(nb_values) + 1
value_ids = set()
for __ in range(vals_qty):
# Ensure that we wouldn't have > 1k variants with the generated attributes combination
if will_exceed(i):
break
random_value_id = attr.value_ids[random.randrange(nb_values)].id
if random_value_id not in value_ids:
values_count[i] += 1
value_ids.add(random_value_id)
attr_line_vals.append((0, 0, {
"attribute_id": attr_id,
"value_ids": [(6, 0, list(value_ids))],
}))
return attr_line_vals
return [
("name", populate.constant('product_template_name_{counter}')),
("description", populate.constant('product_template_description_{counter}')),
("default_code", populate.constant('PT-{counter}')),
("attribute_line_ids", populate.compute(get_attributes)),
] + self.env['product.product']._populate_get_product_factories()
class ProductTemplateAttributeExclusion(models.Model):
_inherit = "product.template.attribute.exclusion"
_populate_dependencies = ["product.template"]
_populate_sizes = {"small": 200, "medium": 1_000, "large": 5_000}
def _populate_factories(self):
p_tmpl_ids = self.env.registry.populated_models["product.template"]
configurable_templates = self.env["product.template"].search([
('id', 'in', p_tmpl_ids),
('has_configurable_attributes', '=', True),
])
tmpl_ids_possible = []
multi_values_attribute_lines_by_tmpl = {}
for template in configurable_templates:
multi_values_attribute_lines = template.attribute_line_ids.filtered(
lambda l: len(l.value_ids) > 1
)
if len(multi_values_attribute_lines) < 2:
continue
tmpl_ids_possible.append(template.id)
multi_values_attribute_lines_by_tmpl[template.id] = multi_values_attribute_lines
def get_product_template_attribute_value_id(values, counter, random):
return random.choice(multi_values_attribute_lines_by_tmpl[values['product_tmpl_id']].product_template_value_ids.ids)
def get_value_ids(values, counter, random):
attr_val = self.env['product.template.attribute.value'].browse(values['product_template_attribute_value_id']).attribute_line_id
remaining_lines = multi_values_attribute_lines_by_tmpl[values['product_tmpl_id']] - attr_val
return [(
# TODO: multiple values
6, 0, [random.choice(remaining_lines.product_template_value_ids).id]
)]
return [
("product_tmpl_id", populate.randomize(tmpl_ids_possible)),
("product_template_attribute_value_id", populate.compute(get_product_template_attribute_value_id)),
("value_ids", populate.compute(get_value_ids)),
]
class ProductTemplateAttributeValue(models.Model):
_inherit = "product.template.attribute.value"
_populate_dependencies = ["product.template"]
def _populate(self, size):
p_tmpl_ids = self.env.registry.populated_models["product.template"]
ptavs = self.search([('product_tmpl_id', 'in', p_tmpl_ids)])
# ptavs are automatically created when specifying attribute lines on product templates.
rand = populate.Random("ptav_extra_price_generator")
for ptav in ptavs:
if rand.random() < 0.50: # 50% of having a extra price
ptav.price_extra = rand.randrange(500) * rand.random()
return ptavs
| 42.502674
| 7,948
|
4,994
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import collections
from odoo import models
from odoo.tools import populate
from odoo.addons.stock.populate.stock import COMPANY_NB_WITH_STOCK
_logger = logging.getLogger(__name__)
class ProductCategory(models.Model):
_inherit = "product.category"
_populate_sizes = {"small": 50, "medium": 500, "large": 5_000}
def _populate_factories(self):
return [("name", populate.constant('PC_{counter}'))]
def _populate(self, size):
categories = super()._populate(size)
# Set parent/child relation
self._populate_set_parents(categories, size)
return categories
def _populate_set_parents(self, categories, size):
_logger.info('Set parent/child relation of product categories')
parent_ids = []
rand = populate.Random('product.category+parent_generator')
for category in categories:
if rand.random() < 0.25:
parent_ids.append(category.id)
categories -= self.browse(parent_ids) # Avoid recursion in parent-child relations.
parent_childs = collections.defaultdict(lambda: self.env['product.category'])
for category in categories:
if rand.random() < 0.25: # 1/4 of remaining categories have a parent.
parent_childs[rand.choice(parent_ids)] |= category
for count, (parent, children) in enumerate(parent_childs.items()):
if (count + 1) % 1000 == 0:
_logger.info('Setting parent: %s/%s', count + 1, len(parent_childs))
children.write({'parent_id': parent})
class ProductProduct(models.Model):
_inherit = "product.product"
_populate_sizes = {"small": 150, "medium": 5_000, "large": 50_000}
_populate_dependencies = ["product.category"]
def _populate_get_types(self):
return ["consu", "service"], [2, 1]
def _populate_get_product_factories(self):
category_ids = self.env.registry.populated_models["product.category"]
types, types_distribution = self._populate_get_types()
def get_rand_float(values, counter, random):
return random.randrange(0, 1500) * random.random()
# TODO sale & purchase uoms
return [
("sequence", populate.randomize([False] + [i for i in range(1, 101)])),
("active", populate.randomize([True, False], [0.8, 0.2])),
("type", populate.randomize(types, types_distribution)),
("categ_id", populate.randomize(category_ids)),
("list_price", populate.compute(get_rand_float)),
("standard_price", populate.compute(get_rand_float)),
]
def _populate_factories(self):
return [
("name", populate.constant('product_product_name_{counter}')),
("description", populate.constant('product_product_description_{counter}')),
("default_code", populate.constant('PP-{counter}')),
("barcode", populate.constant('BARCODE-PP-{counter}')),
] + self._populate_get_product_factories()
class SupplierInfo(models.Model):
_inherit = 'product.supplierinfo'
_populate_sizes = {'small': 450, 'medium': 15_000, 'large': 180_000}
_populate_dependencies = ['res.partner', 'product.product', 'product.template']
def _populate_factories(self):
random = populate.Random('product_with_supplierinfo')
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK] + [False]
partner_ids = self.env.registry.populated_models['res.partner']
product_templates_ids = self.env['product.product'].browse(self.env.registry.populated_models['product.product']).product_tmpl_id.ids
product_templates_ids += self.env.registry.populated_models['product.template']
product_templates_ids = random.sample(product_templates_ids, int(len(product_templates_ids) * 0.95))
def get_company_id(values, counter, random):
partner = self.env['res.partner'].browse(values['name'])
if partner.company_id:
return partner.company_id.id
return random.choice(company_ids)
def get_delay(values, counter, random):
# 5 % with huge delay (between 5 month and 6 month), otherwise between 1 and 10 days
if random.random() > 0.95:
return random.randint(150, 210)
return random.randint(1, 10)
return [
('name', populate.randomize(partner_ids)),
('company_id', populate.compute(get_company_id)),
('product_tmpl_id', populate.iterate(product_templates_ids)),
('product_name', populate.constant("SI-{counter}")),
('sequence', populate.randint(1, 10)),
('min_qty', populate.randint(0, 10)),
('price', populate.randint(10, 100)),
('delay', populate.compute(get_delay)),
]
| 43.051724
| 4,994
|
3,035
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestSeller(TransactionCase):
def setUp(self):
super(TestSeller, self).setUp()
self.product_service = self.env['product.product'].create({
'name': 'Virtual Home Staging',
})
self.product_service.default_code = 'DEFCODE'
self.product_consu = self.env['product.product'].create({
'name': 'Boudin',
'type': 'consu',
})
self.product_consu.default_code = 'DEFCODE'
self.asustec = self.env['res.partner'].create({'name': 'Wood Corner'})
self.camptocamp = self.env['res.partner'].create({'name': 'Azure Interior'})
def test_10_sellers(self):
self.product_service.write({'seller_ids': [
(0, 0, {'name': self.asustec.id, 'product_code': 'ASUCODE'}),
(0, 0, {'name': self.camptocamp.id, 'product_code': 'C2CCODE'}),
]})
default_code = self.product_service.code
self.assertEqual("DEFCODE", default_code, "Default code not used in product name")
context_code = self.product_service\
.with_context(partner_id=self.camptocamp.id)\
.code
self.assertEqual('C2CCODE', context_code, "Partner's code not used in product name with context set")
def test_20_sellers_company(self):
company_a = self.env.company
company_b = self.env['res.company'].create({
'name': 'Saucisson Inc.',
})
self.product_consu.write({'seller_ids': [
(0, 0, {'name': self.asustec.id, 'product_code': 'A', 'company_id': company_a.id}),
(0, 0, {'name': self.asustec.id, 'product_code': 'B', 'company_id': company_b.id}),
(0, 0, {'name': self.asustec.id, 'product_code': 'NO', 'company_id': False}),
]})
names = self.product_consu.with_context(
partner_id=self.asustec.id,
).name_get()
ref = set([x[1] for x in names])
self.assertEqual(len(names), 3, "3 vendor references should have been found")
self.assertEqual(ref, {'[A] Boudin', '[B] Boudin', '[NO] Boudin'}, "Incorrect vendor reference list")
names = self.product_consu.with_context(
partner_id=self.asustec.id,
company_id=company_a.id,
).name_get()
ref = set([x[1] for x in names])
self.assertEqual(len(names), 2, "2 vendor references should have been found")
self.assertEqual(ref, {'[A] Boudin', '[NO] Boudin'}, "Incorrect vendor reference list")
names = self.product_consu.with_context(
partner_id=self.asustec.id,
company_id=company_b.id,
).name_get()
ref = set([x[1] for x in names])
self.assertEqual(len(names), 2, "2 vendor references should have been found")
self.assertEqual(ref, {'[B] Boudin', '[NO] Boudin'}, "Incorrect vendor reference list")
| 45.298507
| 3,035
|
63,776
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from collections import OrderedDict
from datetime import datetime, timedelta
import io
import unittest.mock
from PIL import Image
from . import common
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase, Form
class TestVariantsSearch(TransactionCase):
def setUp(self):
res = super(TestVariantsSearch, self).setUp()
self.size_attr = self.env['product.attribute'].create({'name': 'Size'})
self.size_attr_value_s = self.env['product.attribute.value'].create({'name': 'S', 'attribute_id': self.size_attr.id})
self.size_attr_value_m = self.env['product.attribute.value'].create({'name': 'M', 'attribute_id': self.size_attr.id})
self.size_attr_value_l = self.env['product.attribute.value'].create({'name': 'L', 'attribute_id': self.size_attr.id})
self.product_shirt_template = self.env['product.template'].create({
'name': 'Shirt',
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(6, 0, [self.size_attr_value_l.id])],
})]
})
return res
def test_attribute_line_search(self):
search_not_to_be_found = self.env['product.template'].search(
[('attribute_line_ids', '=', 'M')]
)
self.assertNotIn(self.product_shirt_template, search_not_to_be_found,
'Shirt should not be found searching M')
search_attribute = self.env['product.template'].search(
[('attribute_line_ids', '=', 'Size')]
)
self.assertIn(self.product_shirt_template, search_attribute,
'Shirt should be found searching Size')
search_value = self.env['product.template'].search(
[('attribute_line_ids', '=', 'L')]
)
self.assertIn(self.product_shirt_template, search_value,
'Shirt should be found searching L')
def test_name_search(self):
self.product_slip_template = self.env['product.template'].create({
'name': 'Slip',
})
res = self.env['product.product'].name_search('Shirt', [], 'not ilike', None)
res_ids = [r[0] for r in res]
self.assertIn(self.product_slip_template.product_variant_ids.id, res_ids,
'Slip should be found searching \'not ilike\'')
class TestVariants(common.TestProductCommon):
def setUp(self):
res = super(TestVariants, self).setUp()
self.size_attr = self.env['product.attribute'].create({'name': 'Size'})
self.size_attr_value_s = self.env['product.attribute.value'].create({'name': 'S', 'attribute_id': self.size_attr.id})
self.size_attr_value_m = self.env['product.attribute.value'].create({'name': 'M', 'attribute_id': self.size_attr.id})
self.size_attr_value_l = self.env['product.attribute.value'].create({'name': 'L', 'attribute_id': self.size_attr.id})
return res
def test_variants_is_product_variant(self):
template = self.product_7_template
variants = template.product_variant_ids
self.assertFalse(template.is_product_variant,
'Product template is not a variant')
self.assertEqual({True}, set(v.is_product_variant for v in variants),
'Product variants are variants')
def test_variants_creation_mono(self):
test_template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(4, self.size_attr_value_s.id)],
})]
})
# produced variants: one variant, because mono value
self.assertEqual(len(test_template.product_variant_ids), 1)
self.assertEqual(test_template.product_variant_ids.product_template_attribute_value_ids.product_attribute_value_id, self.size_attr_value_s)
def test_variants_creation_mono_double(self):
test_template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v2.id)],
}), (0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(4, self.size_attr_value_s.id)],
})]
})
# produced variants: one variant, because only 1 combination is possible
self.assertEqual(len(test_template.product_variant_ids), 1)
self.assertEqual(test_template.product_variant_ids.product_template_attribute_value_ids.product_attribute_value_id, self.size_attr_value_s + self.prod_attr1_v2)
def test_variants_creation_mono_multi(self):
test_template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v2.id)],
}), (0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(4, self.size_attr_value_s.id), (4, self.size_attr_value_m.id)],
})]
})
sofa_attr1_v2 = test_template.attribute_line_ids[0].product_template_value_ids[0]
sofa_size_s = test_template.attribute_line_ids[1].product_template_value_ids[0]
sofa_size_m = test_template.attribute_line_ids[1].product_template_value_ids[1]
# produced variants: two variants, simple matrix
self.assertEqual(len(test_template.product_variant_ids), 2)
for ptav in sofa_size_s + sofa_size_m:
products = self.env['product.product'].search([
('product_tmpl_id', '=', test_template.id),
('product_template_attribute_value_ids', 'in', ptav.id),
('product_template_attribute_value_ids', 'in', sofa_attr1_v2.id)
])
self.assertEqual(len(products), 1)
def test_variants_creation_matrix(self):
test_template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v1.id), (4, self.prod_attr1_v2.id)],
}), (0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(4, self.size_attr_value_s.id), (4, self.size_attr_value_m.id), (4, self.size_attr_value_l.id)],
})]
})
sofa_attr1_v1 = test_template.attribute_line_ids[0].product_template_value_ids[0]
sofa_attr1_v2 = test_template.attribute_line_ids[0].product_template_value_ids[1]
sofa_size_s = test_template.attribute_line_ids[1].product_template_value_ids[0]
sofa_size_m = test_template.attribute_line_ids[1].product_template_value_ids[1]
sofa_size_l = test_template.attribute_line_ids[1].product_template_value_ids[2]
# produced variants: value matrix : 2x3 values
self.assertEqual(len(test_template.product_variant_ids), 6)
for value_1 in sofa_attr1_v1 + sofa_attr1_v2:
for value_2 in sofa_size_s + sofa_size_m + sofa_size_l:
products = self.env['product.product'].search([
('product_tmpl_id', '=', test_template.id),
('product_template_attribute_value_ids', 'in', value_1.id),
('product_template_attribute_value_ids', 'in', value_2.id)
])
self.assertEqual(len(products), 1)
def test_variants_creation_multi_update(self):
test_template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v1.id), (4, self.prod_attr1_v2.id)],
}), (0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(4, self.size_attr_value_s.id), (4, self.size_attr_value_m.id)],
})]
})
size_attribute_line = test_template.attribute_line_ids.filtered(lambda line: line.attribute_id == self.size_attr)
test_template.write({
'attribute_line_ids': [(1, size_attribute_line.id, {
'value_ids': [(4, self.size_attr_value_l.id)],
})]
})
def test_variants_copy(self):
template = self.env['product.template'].create({
'name': 'Test Copy',
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size_attr.id,
'value_ids': [(4, self.size_attr_value_s.id), (4, self.size_attr_value_m.id)],
})]
})
self.assertEqual(len(template.product_variant_ids), 2)
self.assertEqual(template.name, 'Test Copy')
# test copy of template
template_copy = template.copy()
self.assertEqual(template.name, 'Test Copy')
self.assertEqual(template_copy.name, 'Test Copy (copy)')
self.assertEqual(len(template_copy.product_variant_ids), 2)
# test copy of variant (actually just copying template)
variant_copy = template_copy.product_variant_ids[0].copy()
self.assertEqual(template.name, 'Test Copy')
self.assertEqual(template_copy.name, 'Test Copy (copy)')
self.assertEqual(variant_copy.name, 'Test Copy (copy) (copy)')
self.assertEqual(len(variant_copy.product_variant_ids), 2)
def test_dynamic_variants_copy(self):
self.color_attr = self.env['product.attribute'].create({'name': 'Color', 'create_variant': 'dynamic'})
self.color_attr_value_r = self.env['product.attribute.value'].create({'name': 'Red', 'attribute_id': self.color_attr.id})
self.color_attr_value_b = self.env['product.attribute.value'].create({'name': 'Blue', 'attribute_id': self.color_attr.id})
# test copy of variant with dynamic attribute
template_dyn = self.env['product.template'].create({
'name': 'Test Dynamical',
'attribute_line_ids': [(0, 0, {
'attribute_id': self.color_attr.id,
'value_ids': [(4, self.color_attr_value_r.id), (4, self.color_attr_value_b.id)],
})]
})
self.assertEqual(len(template_dyn.product_variant_ids), 0)
self.assertEqual(template_dyn.name, 'Test Dynamical')
variant_dyn = template_dyn._create_product_variant(template_dyn._get_first_possible_combination())
self.assertEqual(len(template_dyn.product_variant_ids), 1)
variant_dyn_copy = variant_dyn.copy()
template_dyn_copy = variant_dyn_copy.product_tmpl_id
self.assertEqual(len(template_dyn_copy.product_variant_ids), 1)
self.assertEqual(template_dyn_copy.name, 'Test Dynamical (copy)')
def test_standard_price(self):
""" Ensure template values are correctly (re)computed depending on the context """
one_variant_product = self.product_1
self.assertEqual(one_variant_product.product_variant_count, 1)
company_a = self.env.company
company_b = self.env['res.company'].create({'name': 'CB', 'currency_id': self.env.ref('base.VEF').id})
self.assertEqual(one_variant_product.cost_currency_id, company_a.currency_id)
self.assertEqual(one_variant_product.with_company(company_b).cost_currency_id, company_b.currency_id)
one_variant_template = one_variant_product.product_tmpl_id
self.assertEqual(one_variant_product.standard_price, one_variant_template.standard_price)
one_variant_product.with_company(company_b).standard_price = 500.0
self.assertEqual(
one_variant_product.with_company(company_b).standard_price,
one_variant_template.with_company(company_b).standard_price
)
self.assertEqual(
500.0,
one_variant_template.with_company(company_b).standard_price
)
def test_archive_variant(self):
template = self.env['product.template'].create({
'name': 'template'
})
self.assertEqual(len(template.product_variant_ids), 1)
template.write({
'attribute_line_ids': [(0, False, {
'attribute_id': self.size_attr.id,
'value_ids': [
(4, self.size_attr.value_ids[0].id, self.size_attr_value_s),
(4, self.size_attr.value_ids[1].id, self.size_attr_value_m)
],
})]
})
self.assertEqual(len(template.product_variant_ids), 2)
variant_1 = template.product_variant_ids[0]
variant_1.toggle_active()
self.assertFalse(variant_1.active)
self.assertEqual(len(template.product_variant_ids), 1)
self.assertEqual(len(template.with_context(
active_test=False).product_variant_ids), 2)
variant_1.toggle_active()
self.assertTrue(variant_1.active)
self.assertTrue(template.active)
def test_template_barcode(self):
template = self.env['product.template'].create({
'name': 'template',
'barcode': 'test',
})
self.assertEqual(len(template.product_variant_ids), 1)
self.assertEqual(template.barcode, 'test')
template.product_variant_ids.action_archive()
self.assertFalse(template.active)
template.invalidate_cache(['barcode'])
self.assertEqual(template.barcode, 'test')
template.product_variant_ids.action_unarchive()
template.action_unarchive()
template.write({
'attribute_line_ids': [(0, False, {
'attribute_id': self.size_attr.id,
'value_ids': [
(4, self.size_attr.value_ids[0].id, self.size_attr_value_s),
(4, self.size_attr.value_ids[1].id, self.size_attr_value_m)
],
})]
})
self.assertFalse(template.barcode) # 2 active variants --> no barcode on template
variant_1 = template.product_variant_ids[0]
variant_2 = template.product_variant_ids[1]
variant_1.barcode = 'v1_barcode'
variant_2.barcode = 'v2_barcode'
variant_1.action_archive()
template.invalidate_cache(['barcode'])
self.assertEqual(template.barcode, variant_2.barcode) # 1 active variant --> barcode on template
variant_1.action_unarchive()
template.invalidate_cache(['barcode'])
self.assertFalse(template.barcode) # 2 active variants --> no barcode on template
def test_archive_all_variants(self):
template = self.env['product.template'].create({
'name': 'template'
})
self.assertEqual(len(template.product_variant_ids), 1)
template.write({
'attribute_line_ids': [(0, False, {
'attribute_id': self.size_attr.id,
'value_ids': [
(4, self.size_attr.value_ids[0].id, self.size_attr_value_s),
(4, self.size_attr.value_ids[1].id, self.size_attr_value_m)
],
})]
})
self.assertEqual(len(template.product_variant_ids), 2)
variant_1 = template.product_variant_ids[0]
variant_2 = template.product_variant_ids[1]
template.product_variant_ids.toggle_active()
self.assertFalse(variant_1.active, 'Should archive all variants')
self.assertFalse(template.active, 'Should archive related template')
variant_1.toggle_active()
self.assertTrue(variant_1.active, 'Should activate variant')
self.assertFalse(variant_2.active, 'Should not re-activate other variant')
self.assertTrue(template.active, 'Should re-activate template')
class TestVariantsNoCreate(common.TestProductCommon):
def setUp(self):
super(TestVariantsNoCreate, self).setUp()
self.size = self.env['product.attribute'].create({
'name': 'Size',
'create_variant': 'no_variant',
'value_ids': [(0, 0, {'name': 'S'}), (0, 0, {'name': 'M'}), (0, 0, {'name': 'L'})],
})
self.size_S = self.size.value_ids[0]
self.size_M = self.size.value_ids[1]
self.size_L = self.size.value_ids[2]
def test_create_mono(self):
""" create a product with a 'nocreate' attribute with a single value """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size.id,
'value_ids': [(4, self.size_S.id)],
})],
})
self.assertEqual(len(template.product_variant_ids), 1)
self.assertFalse(template.product_variant_ids.product_template_attribute_value_ids)
def test_update_mono(self):
""" modify a product with a 'nocreate' attribute with a single value """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
})
self.assertEqual(len(template.product_variant_ids), 1)
template.write({
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size.id,
'value_ids': [(4, self.size_S.id)],
})],
})
self.assertEqual(len(template.product_variant_ids), 1)
self.assertFalse(template.product_variant_ids.product_template_attribute_value_ids)
def test_create_multi(self):
""" create a product with a 'nocreate' attribute with several values """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size.id,
'value_ids': [(6, 0, self.size.value_ids.ids)],
})],
})
self.assertEqual(len(template.product_variant_ids), 1)
self.assertFalse(template.product_variant_ids.product_template_attribute_value_ids)
def test_update_multi(self):
""" modify a product with a 'nocreate' attribute with several values """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
})
self.assertEqual(len(template.product_variant_ids), 1)
template.write({
'attribute_line_ids': [(0, 0, {
'attribute_id': self.size.id,
'value_ids': [(6, 0, self.size.value_ids.ids)],
})],
})
self.assertEqual(len(template.product_variant_ids), 1)
self.assertFalse(template.product_variant_ids.product_template_attribute_value_ids)
def test_create_mixed_mono(self):
""" create a product with regular and 'nocreate' attributes """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [
(0, 0, { # no variants for this one
'attribute_id': self.size.id,
'value_ids': [(4, self.size_S.id)],
}),
(0, 0, { # two variants for this one
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v1.id), (4, self.prod_attr1_v2.id)],
}),
],
})
self.assertEqual(len(template.product_variant_ids), 2)
self.assertEqual(
{variant.product_template_attribute_value_ids.product_attribute_value_id for variant in template.product_variant_ids},
{self.prod_attr1_v1, self.prod_attr1_v2},
)
def test_update_mixed_mono(self):
""" modify a product with regular and 'nocreate' attributes """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
})
self.assertEqual(len(template.product_variant_ids), 1)
template.write({
'attribute_line_ids': [
(0, 0, { # no variants for this one
'attribute_id': self.size.id,
'value_ids': [(4, self.size_S.id)],
}),
(0, 0, { # two variants for this one
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v1.id), (4, self.prod_attr1_v2.id)],
}),
],
})
self.assertEqual(len(template.product_variant_ids), 2)
self.assertEqual(
{variant.product_template_attribute_value_ids.product_attribute_value_id for variant in template.product_variant_ids},
{self.prod_attr1_v1, self.prod_attr1_v2},
)
def test_create_mixed_multi(self):
""" create a product with regular and 'nocreate' attributes """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [
(0, 0, { # no variants for this one
'attribute_id': self.size.id,
'value_ids': [(6, 0, self.size.value_ids.ids)],
}),
(0, 0, { # two variants for this one
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v1.id), (4, self.prod_attr1_v2.id)],
}),
],
})
self.assertEqual(len(template.product_variant_ids), 2)
self.assertEqual(
{variant.product_template_attribute_value_ids.product_attribute_value_id for variant in template.product_variant_ids},
{self.prod_attr1_v1, self.prod_attr1_v2},
)
def test_update_mixed_multi(self):
""" modify a product with regular and 'nocreate' attributes """
template = self.env['product.template'].create({
'name': 'Sofa',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
})
self.assertEqual(len(template.product_variant_ids), 1)
template.write({
'attribute_line_ids': [
(0, 0, { # no variants for this one
'attribute_id': self.size.id,
'value_ids': [(6, 0, self.size.value_ids.ids)],
}),
(0, 0, { # two variants for this one
'attribute_id': self.prod_att_1.id,
'value_ids': [(4, self.prod_attr1_v1.id), (4, self.prod_attr1_v2.id)],
}),
],
})
self.assertEqual(len(template.product_variant_ids), 2)
self.assertEqual(
{variant.product_template_attribute_value_ids.product_attribute_value_id for variant in template.product_variant_ids},
{self.prod_attr1_v1, self.prod_attr1_v2},
)
def test_update_variant_with_nocreate(self):
""" update variants with a 'nocreate' value on variant """
template = self.env['product.template'].create({
'name': 'Sofax',
'uom_id': self.uom_unit.id,
'uom_po_id': self.uom_unit.id,
'attribute_line_ids': [
(0, 0, { # one variant for this one
'attribute_id': self.prod_att_1.id,
'value_ids': [(6, 0, self.prod_attr1_v1.ids)],
}),
],
})
self.assertEqual(len(template.product_variant_ids), 1)
template.attribute_line_ids = [(0, 0, {
'attribute_id': self.size.id,
'value_ids': [(6, 0, self.size_S.ids)],
})]
self.assertEqual(len(template.product_variant_ids), 1)
# no_variant attribute should not appear on the variant
self.assertNotIn(self.size_S, template.product_variant_ids.product_template_attribute_value_ids.product_attribute_value_id)
class TestVariantsManyAttributes(common.TestAttributesCommon):
def test_01_create_no_variant(self):
toto = self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
self.assertEqual(len(toto.attribute_line_ids.mapped('attribute_id')), 10)
self.assertEqual(len(toto.attribute_line_ids.mapped('value_ids')), 100)
self.assertEqual(len(toto.product_variant_ids), 1)
def test_02_create_dynamic(self):
self.attributes.write({'create_variant': 'dynamic'})
toto = self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
self.assertEqual(len(toto.attribute_line_ids.mapped('attribute_id')), 10)
self.assertEqual(len(toto.attribute_line_ids.mapped('value_ids')), 100)
self.assertEqual(len(toto.product_variant_ids), 0)
def test_03_create_always(self):
self.attributes.write({'create_variant': 'always'})
with self.assertRaises(UserError):
self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
def test_04_create_no_variant_dynamic(self):
self.attributes[:5].write({'create_variant': 'dynamic'})
toto = self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
self.assertEqual(len(toto.attribute_line_ids.mapped('attribute_id')), 10)
self.assertEqual(len(toto.attribute_line_ids.mapped('value_ids')), 100)
self.assertEqual(len(toto.product_variant_ids), 0)
def test_05_create_no_variant_always(self):
self.attributes[:2].write({'create_variant': 'always'})
toto = self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
self.assertEqual(len(toto.attribute_line_ids.mapped('attribute_id')), 10)
self.assertEqual(len(toto.attribute_line_ids.mapped('value_ids')), 100)
self.assertEqual(len(toto.product_variant_ids), 100)
def test_06_create_dynamic_always(self):
self.attributes[:5].write({'create_variant': 'dynamic'})
self.attributes[5:].write({'create_variant': 'always'})
toto = self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
self.assertEqual(len(toto.attribute_line_ids.mapped('attribute_id')), 10)
self.assertEqual(len(toto.attribute_line_ids.mapped('value_ids')), 100)
self.assertEqual(len(toto.product_variant_ids), 0)
def test_07_create_no_create_dynamic_always(self):
self.attributes[3:6].write({'create_variant': 'dynamic'})
self.attributes[6:].write({'create_variant': 'always'})
toto = self.env['product.template'].create({
'name': 'Toto',
'attribute_line_ids': [(0, 0, {
'attribute_id': attribute.id,
'value_ids': [(6, 0, attribute.value_ids.ids)],
}) for attribute in self.attributes],
})
self.assertEqual(len(toto.attribute_line_ids.mapped('attribute_id')), 10)
self.assertEqual(len(toto.attribute_line_ids.mapped('value_ids')), 100)
self.assertEqual(len(toto.product_variant_ids), 0)
class TestVariantsImages(common.TestProductCommon):
def setUp(self):
res = super(TestVariantsImages, self).setUp()
self.colors = OrderedDict([('none', ''), ('red', '#FF0000'), ('green', '#00FF00'), ('blue', '#0000FF')])
self.images = {}
product_attribute = self.env['product.attribute'].create({'name': 'Color'})
self.template = self.env['product.template'].create({
'name': 'template',
})
color_values = self.env['product.attribute.value'].create([{
'name': color,
'attribute_id': product_attribute.id,
'sequence': i,
} for i, color in enumerate(self.colors)])
ptal = self.env['product.template.attribute.line'].create({
'attribute_id': product_attribute.id,
'product_tmpl_id': self.template.id,
'value_ids': [(6, 0, color_values.ids)],
})
for color_value in ptal.product_template_value_ids[1:]:
f = io.BytesIO()
Image.new('RGB', (800, 500), self.colors[color_value.name]).save(f, 'PNG')
f.seek(0)
self.images.update({color_value.name: base64.b64encode(f.read())})
self.template._get_variant_for_combination(color_value).write({
'image_variant_1920': self.images[color_value.name],
})
# the first one has no image
self.variants = self.template.product_variant_ids
return res
def test_variant_images(self):
"""Check that on variant, the image used is the image_variant_1920 if set,
and defaults to the template image otherwise.
"""
# Pretend setup happened in an older transaction by updating on the SQL layer and making sure it gets reloaded
# Using _write() instead of write() because write() only allows updating log access fields at boot time
before = self.env.cr.now() - timedelta(seconds=1)
self.template._write({
'create_date': before,
'write_date': before,
})
self.variants._write({
'create_date': before,
'write_date': before,
})
self.template.invalidate_cache(['create_date', 'write_date'], self.template.ids)
self.variants.invalidate_cache(['create_date', 'write_date'], self.variants.ids)
f = io.BytesIO()
Image.new('RGB', (800, 500), '#000000').save(f, 'PNG')
f.seek(0)
image_black = base64.b64encode(f.read())
images = self.variants.mapped('image_1920')
self.assertEqual(len(set(images)), 4)
variant_no_image = self.variants[0]
old_last_update = variant_no_image['__last_update']
self.assertFalse(variant_no_image.image_1920)
self.template.image_1920 = image_black
self.template.write({'write_date': datetime.now()})
new_last_update = variant_no_image['__last_update']
# the first has no image variant, all the others do
self.assertFalse(variant_no_image.image_variant_1920)
self.assertTrue(all(images[1:]))
# template image is the same as this one, since it has no image variant
self.assertEqual(variant_no_image.image_1920, self.template.image_1920)
# having changed the template image should not have changed these
self.assertEqual(images[1:], self.variants.mapped('image_1920')[1:])
# last update changed for the variant without image
self.assertLess(old_last_update, new_last_update)
def test_update_images_with_archived_variants(self):
"""Update images after variants have been archived"""
self.variants[1:].write({'active': False})
self.variants[0].image_1920 = self.images['red']
self.assertEqual(self.template.image_1920, self.images['red'])
self.assertEqual(self.variants[0].image_variant_1920, False)
self.assertEqual(self.variants[0].image_1920, self.images['red'])
class TestVariantsArchive(common.TestProductCommon):
"""Once a variant is used on orders/invoices, etc, they can't be unlinked.
As a result, updating attributes on a product template would simply
archive the variants instead. We make sure that at each update, we have
the correct active and inactive records.
In these tests, we use the commands sent by the JS framework to the ORM
when using the interface.
"""
def setUp(self):
res = super(TestVariantsArchive, self).setUp()
self.pa_color = self.env['product.attribute'].create({'name': "color", 'sequence': 1})
color_values = self.env['product.attribute.value'].create([{
'name': n,
'sequence': i,
'attribute_id': self.pa_color.id,
} for i, n in enumerate(['white', 'black'])])
self.pav_color_white = color_values[0]
self.pav_color_black = color_values[1]
self.pa_size = self.env['product.attribute'].create({'name': "size", 'sequence': 2})
size_values = self.env['product.attribute.value'].create([{
'name': n,
'sequence': i,
'attribute_id': self.pa_size.id,
} for i, n in enumerate(['s', 'm'])])
self.pav_size_s = size_values[0]
self.pav_size_m = size_values[1]
self.template = self.env['product.template'].create({
'name': 'consume product',
'attribute_line_ids': self._get_add_all_attributes_command(),
})
self._update_color_vars(self.template.attribute_line_ids[0])
self._update_size_vars(self.template.attribute_line_ids[1])
return res
def test_01_update_variant_unlink(self):
"""Variants are not used anywhere, so removing an attribute line would
unlink the variants and create new ones. Nothing too fancy here.
"""
variants_2x2 = self.template.product_variant_ids
self._assert_2color_x_2size()
# Remove the size line, corresponding variants will be removed too since
# they are used nowhere. Since we only kept color, we should have as many
# variants as it has values.
self._remove_ptal_size()
self._assert_2color_x_0size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
# We re-add the line we just removed, so we should get new variants.
self._add_ptal_size_s_m()
self._assert_2color_x_2size()
self.assertFalse(self.template.product_variant_ids & variants_2x2)
def test_02_update_variant_archive_1_value(self):
"""We do the same operations on the template as in the previous test,
except we simulate that the variants can't be unlinked.
It follows that variants should be archived instead, so the results
should all be different from previous test.
In this test we have a line that has only one possible value:
this is handled differently than the case where we have more than
one value, since it does not add new variants.
"""
self._remove_ptal_size()
self._add_ptal_size_s()
# create a patch to make as if one variant was undeletable
# (e.g. present in a field with ondelete=restrict)
Product = self.env['product.product']
def unlink(self):
raise Exception('just')
Product._patch_method('unlink', unlink)
variants_2x1 = self.template.product_variant_ids
self._assert_2color_x_1size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
# Remove the size line, which is the one with only one possible value.
# Variants should be kept, just the single value removed from them.
self._remove_ptal_size()
self.assertEqual(variants_2x1, self.template.product_variant_ids)
self._assert_2color_x_0size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
# Add the line just removed, so it is added back to the variants.
self._add_ptal_size_s()
self.assertEqual(variants_2x1, self.template.product_variant_ids)
self._assert_2color_x_1size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
Product._revert_method('unlink')
def test_02_update_variant_archive_2_value(self):
"""We do the same operations on the template as in the previous tests,
except we simulate that the variants can't be unlinked.
It follows that variants should be archived instead, so the results
should all be different from previous test.
"""
Product = self.env['product.product']
def unlink(slef):
raise Exception('just')
Product._patch_method('unlink', unlink)
variants_2x2 = self.template.product_variant_ids
self._assert_2color_x_2size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
# CASE remove one attribute line (going from 2*2 to 2*1)
# Since they can't be unlinked, existing variants should be archived.
self._remove_ptal_size()
variants_2x0 = self.template.product_variant_ids
self._assert_2color_x_0size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x2)
self._assert_2color_x_2size(archived_variants)
# Add the line just removed, so get back the previous variants.
# Since they can't be unlinked, existing variants should be archived.
self._add_ptal_size_s_m()
self.assertEqual(self.template.product_variant_ids, variants_2x2)
self._assert_2color_x_2size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x0)
self._assert_2color_x_0size(archived_variants)
# we redo the whole remove/read to check
self._remove_ptal_size()
self.assertEqual(self.template.product_variant_ids, variants_2x0)
self._assert_2color_x_0size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x2)
self._assert_2color_x_2size(archived_variants)
self._add_ptal_size_s_m()
self.assertEqual(self.template.product_variant_ids, variants_2x2)
self._assert_2color_x_2size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x0)
self._assert_2color_x_0size(archived_variants)
self._remove_ptal_size()
self.assertEqual(self.template.product_variant_ids, variants_2x0)
self._assert_2color_x_0size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x2)
self._assert_2color_x_2size(archived_variants)
# This time we only add one of the two attributes we've been removing.
# This is a single value line, so the value is simply added to existing
# variants.
self._add_ptal_size_s()
self.assertEqual(self.template.product_variant_ids, variants_2x0)
self._assert_2color_x_1size()
self.assertEqual(archived_variants, variants_2x2)
self._assert_2color_x_2size(archived_variants)
Product._revert_method('unlink')
def test_03_update_variant_archive_3_value(self):
self._remove_ptal_size()
self._add_ptal_size_s()
Product = self.env['product.product']
def unlink(slef):
raise Exception('just')
Product._patch_method('unlink', unlink)
self._assert_2color_x_1size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
variants_2x1 = self.template.product_variant_ids
# CASE: remove single value line, no variant change
self._remove_ptal_size()
self.assertEqual(self.template.product_variant_ids, variants_2x1)
self._assert_2color_x_0size()
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
# CASE: empty combination, this generates a new variant
self.template.write({'attribute_line_ids': [(2, self.ptal_color.id)]})
self._assert_0color_x_0size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x1)
self._assert_2color_x_0size(archived_variants) # single value are removed
variant_0x0 = self.template.product_variant_ids
# CASE: add single value on empty
self._add_ptal_size_s()
self.assertEqual(self.template.product_variant_ids, variant_0x0)
self._assert_0color_x_1size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x1)
self._assert_2color_x_0size(archived_variants) # single value are removed
# CASE: empty again
self._remove_ptal_size()
self.assertEqual(self.template.product_variant_ids, variant_0x0)
self._assert_0color_x_0size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x1)
self._assert_2color_x_0size(archived_variants) # single value are removed
# CASE: re-add everything
self.template.write({
'attribute_line_ids': self._get_add_all_attributes_command(),
})
self._update_color_vars(self.template.attribute_line_ids[0])
self._update_size_vars(self.template.attribute_line_ids[1])
self._assert_2color_x_2size()
archived_variants = self._get_archived_variants()
self.assertEqual(archived_variants, variants_2x1 + variant_0x0)
Product._revert_method('unlink')
def test_04_from_to_single_values(self):
Product = self.env['product.product']
def unlink(slef):
raise Exception('just')
Product._patch_method('unlink', unlink)
# CASE: remove one value, line becoming single value
variants_2x2 = self.template.product_variant_ids
self.ptal_size.write({'value_ids': [(3, self.pav_size_m.id)]})
self._assert_2color_x_1size()
self.assertEqual(self.template.product_variant_ids, variants_2x2[0] + variants_2x2[2])
archived_variants = self._get_archived_variants()
self._assert_2color_x_1size(archived_variants, ptav=self.ptav_size_m)
self.assertEqual(archived_variants, variants_2x2[1] + variants_2x2[3])
# CASE: add back the value
self.ptal_size.write({'value_ids': [(4, self.pav_size_m.id)]})
self._assert_2color_x_2size()
self.assertEqual(self.template.product_variant_ids, variants_2x2)
archived_variants = self._get_archived_variants()
self.assertFalse(archived_variants)
# CASE: remove one value, line becoming single value, and then remove
# the remaining value
self.ptal_size.write({'value_ids': [(3, self.pav_size_m.id)]})
self._remove_ptal_size()
self._assert_2color_x_0size()
self.assertFalse(self.template.product_variant_ids & variants_2x2)
archived_variants = self._get_archived_variants()
self._assert_2color_x_2size(archived_variants)
self.assertEqual(archived_variants, variants_2x2)
variants_2x0 = self.template.product_variant_ids
# CASE: add back the values
self._add_ptal_size_s_m()
self._assert_2color_x_2size()
self.assertEqual(self.template.product_variant_ids, variants_2x2)
archived_variants = self._get_archived_variants()
self._assert_2color_x_0size(archived_variants)
self.assertEqual(archived_variants, variants_2x0)
Product._revert_method('unlink')
def test_name_search_dynamic_attributes(self):
dynamic_attr = self.env['product.attribute'].create({
'name': 'Dynamic',
'create_variant': 'dynamic',
'value_ids': [(0, False, {'name': 'ValueDynamic'})],
})
template = self.env['product.template'].create({
'name': 'cimanyd',
'attribute_line_ids': [(0, False, {
'attribute_id': dynamic_attr.id,
'value_ids': [(4, dynamic_attr.value_ids[0].id, False)],
})]
})
self.assertEqual(len(template.product_variant_ids), 0)
name_searched = self.env['product.template'].name_search(name='cima')
self.assertIn(template.id, [ng[0] for ng in name_searched])
def test_uom_update_variant(self):
""" Changing the uom on the template do not behave the same
as changing on the product product."""
units = self.env.ref('uom.product_uom_unit')
cm = self.env.ref('uom.product_uom_cm')
template = self.env['product.template'].create({
'name': 'kardon'
})
template_form = Form(template)
template_form.uom_id = cm
self.assertEqual(template_form.uom_po_id, cm)
template = template_form.save()
variant_form = Form(template.product_variant_ids)
variant_form.uom_id = units
self.assertEqual(variant_form.uom_po_id, units)
variant = variant_form.save()
self.assertEqual(variant.uom_po_id, units)
self.assertEqual(template.uom_po_id, units)
def test_dynamic_attributes_archiving(self):
Product = self.env['product.product']
ProductAttribute = self.env['product.attribute']
ProductAttributeValue = self.env['product.attribute.value']
# Patch unlink method to force archiving instead deleting
def unlink(self):
self.active = False
Product._patch_method('unlink', unlink)
# Creating attributes
pa_color = ProductAttribute.create({'sequence': 1, 'name': 'color', 'create_variant': 'dynamic'})
color_values = ProductAttributeValue.create([{
'name': n,
'sequence': i,
'attribute_id': pa_color.id,
} for i, n in enumerate(['white', 'black'])])
pav_color_white = color_values[0]
pav_color_black = color_values[1]
pa_size = ProductAttribute.create({'sequence': 2, 'name': 'size', 'create_variant': 'dynamic'})
size_values = ProductAttributeValue.create([{
'name': n,
'sequence': i,
'attribute_id': pa_size.id,
} for i, n in enumerate(['s', 'm'])])
pav_size_s = size_values[0]
pav_size_m = size_values[1]
pa_material = ProductAttribute.create({'sequence': 3, 'name': 'material', 'create_variant': 'no_variant'})
material_values = ProductAttributeValue.create([{
'name': 'Wood',
'sequence': 1,
'attribute_id': pa_material.id,
}])
pav_material_wood = material_values[0]
# Define a template with only color attribute & white value
template = self.env['product.template'].create({
'name': 'test product',
'attribute_line_ids': [(0, 0, {
'attribute_id': pa_color.id,
'value_ids': [(6, 0, [pav_color_white.id])],
})],
})
# Create a variant (because of dynamic attribute)
ptav_white = self.env['product.template.attribute.value'].search([
('attribute_line_id', '=', template.attribute_line_ids.id),
('product_attribute_value_id', '=', pav_color_white.id)
])
product_white = template._create_product_variant(ptav_white)
# Adding a new value to an existing attribute should not archive the variant
template.write({
'attribute_line_ids': [(1, template.attribute_line_ids[0].id, {
'attribute_id': pa_color.id,
'value_ids': [(4, pav_color_black.id, False)],
})]
})
self.assertTrue(product_white.active)
# Removing an attribute value should archive the product using it
template.write({
'attribute_line_ids': [(1, template.attribute_line_ids[0].id, {
'value_ids': [(3, pav_color_white.id, 0)],
})]
})
self.assertFalse(product_white.active)
self.assertFalse(template._is_combination_possible_by_config(
combination=product_white.product_template_attribute_value_ids,
ignore_no_variant=True,
))
# Creating a product with the same attributes for testing duplicates
product_white_duplicate = Product.create({
'product_tmpl_id': template.id,
'product_template_attribute_value_ids': [(6, 0, [ptav_white.id])],
'active': False,
})
# Reset archiving for the next assert
template.write({
'attribute_line_ids': [(1, template.attribute_line_ids[0].id, {
'value_ids': [(4, pav_color_white.id, 0)],
})]
})
self.assertTrue(product_white.active)
self.assertFalse(product_white_duplicate.active)
# Adding a new attribute should archive the old variant
template.write({
'attribute_line_ids': [(0, 0, {
'attribute_id': pa_size.id,
'value_ids': [(6, 0, [pav_size_s.id, pav_size_m.id])],
})]
})
self.assertFalse(product_white.active)
# Reset archiving for the next assert
template.write({
'attribute_line_ids': [(3, template.attribute_line_ids[1].id, 0)]
})
self.assertTrue(product_white.active)
# Adding a no_variant attribute should not archive the product
template.write({
'attribute_line_ids': [(0, 0, {
'attribute_id': pa_material.id,
'value_ids': [(6, 0, [pav_material_wood.id])],
})]
})
self.assertTrue(product_white.active)
Product._revert_method('unlink')
def test_set_barcode(self):
tmpl = self.product_0.product_tmpl_id
tmpl.barcode = '123'
self.assertEqual(tmpl.barcode, '123')
self.assertEqual(self.product_0.barcode, '123')
tmpl.toggle_active()
tmpl.barcode = '456'
tmpl.invalidate_cache(fnames=['barcode'], ids=tmpl.ids)
self.assertEqual(tmpl.barcode, '456')
self.assertEqual(self.product_0.barcode, '456')
def _update_color_vars(self, ptal):
self.ptal_color = ptal
self.assertEqual(self.ptal_color.attribute_id, self.pa_color)
self.ptav_color_white = self.ptal_color.product_template_value_ids[0]
self.assertEqual(self.ptav_color_white.product_attribute_value_id, self.pav_color_white)
self.ptav_color_black = self.ptal_color.product_template_value_ids[1]
self.assertEqual(self.ptav_color_black.product_attribute_value_id, self.pav_color_black)
def _update_size_vars(self, ptal):
self.ptal_size = ptal
self.assertEqual(self.ptal_size.attribute_id, self.pa_size)
self.ptav_size_s = self.ptal_size.product_template_value_ids[0]
self.assertEqual(self.ptav_size_s.product_attribute_value_id, self.pav_size_s)
if len(self.ptal_size.product_template_value_ids) > 1:
self.ptav_size_m = self.ptal_size.product_template_value_ids[1]
self.assertEqual(self.ptav_size_m.product_attribute_value_id, self.pav_size_m)
def _get_add_all_attributes_command(self):
return [(0, 0, {
'attribute_id': pa.id,
'value_ids': [(6, 0, pa.value_ids.ids)],
}) for pa in self.pa_color + self.pa_size]
def _get_archived_variants(self):
# Change context to also get archived values when reading them from the
# variants.
return self.env['product.product'].with_context(active_test=False).search([
('active', '=', False),
('product_tmpl_id', '=', self.template.id)
])
def _remove_ptal_size(self):
self.template.write({'attribute_line_ids': [(2, self.ptal_size.id)]})
def _add_ptal_size_s_m(self):
self.template.write({
'attribute_line_ids': [(0, 0, {
'attribute_id': self.pa_size.id,
'value_ids': [(6, 0, (self.pav_size_s + self.pav_size_m).ids)],
})],
})
self._update_size_vars(self.template.attribute_line_ids[-1])
def _add_ptal_size_s(self):
self.template.write({
'attribute_line_ids': [(0, 0, {
'attribute_id': self.pa_size.id,
'value_ids': [(6, 0, self.pav_size_s.ids)],
})],
})
self._update_size_vars(self.template.attribute_line_ids[-1])
def _get_combinations_names(self, combinations):
return ' | '.join([','.join(c.mapped('name')) for c in combinations])
def _assert_required_combinations(self, variants, required_values):
actual_values = [v.product_template_attribute_value_ids for v in variants]
self.assertEqual(set(required_values), set(actual_values),
"\nRequired: %s\nActual: %s" % (self._get_combinations_names(required_values), self._get_combinations_names(actual_values)))
def _assert_2color_x_2size(self, variants=None):
"""Assert the full matrix 2 color x 2 size"""
variants = variants or self.template.product_variant_ids
self.assertEqual(len(variants), 4)
self._assert_required_combinations(variants, required_values=[
self.ptav_color_white + self.ptav_size_s,
self.ptav_color_white + self.ptav_size_m,
self.ptav_color_black + self.ptav_size_s,
self.ptav_color_black + self.ptav_size_m,
])
def _assert_2color_x_1size(self, variants=None, ptav=None):
"""Assert the matrix 2 color x 1 size"""
variants = variants or self.template.product_variant_ids
self.assertEqual(len(variants), 2)
self._assert_required_combinations(variants, required_values=[
self.ptav_color_white + (ptav or self.ptav_size_s),
self.ptav_color_black + (ptav or self.ptav_size_s),
])
def _assert_2color_x_0size(self, variants=None):
"""Assert the matrix 2 color x no size"""
variants = variants or self.template.product_variant_ids
self.assertEqual(len(variants), 2)
self._assert_required_combinations(variants, required_values=[
self.ptav_color_white,
self.ptav_color_black,
])
def _assert_0color_x_1size(self, variants=None):
"""Assert the matrix no color x 1 size"""
variants = variants or self.template.product_variant_ids
self.assertEqual(len(variants), 1)
self.assertEqual(variants[0].product_template_attribute_value_ids, self.ptav_size_s)
def _assert_0color_x_0size(self, variants=None):
"""Assert the matrix no color x no size"""
variants = variants or self.template.product_variant_ids
self.assertEqual(len(variants), 1)
self.assertFalse(variants[0].product_template_attribute_value_ids)
class TestVariantWrite(TransactionCase):
def test_active_one2many(self):
template = self.env['product.template'].create({'name': 'Foo', 'description': 'Foo'})
self.assertEqual(len(template.product_variant_ids), 1)
# check the consistency of one2many field product_variant_ids w.r.t. active variants
variant1 = template.product_variant_ids
variant2 = self.env['product.product'].create({'product_tmpl_id': template.id})
self.assertEqual(template.product_variant_ids, variant1 + variant2)
variant2.active = False
self.assertEqual(template.product_variant_ids, variant1)
variant2.active = True
self.assertEqual(template.product_variant_ids, variant1 + variant2)
variant1.active = False
self.assertEqual(template.product_variant_ids, variant2)
def test_write_inherited_field(self):
product = self.env['product.product'].create({'name': 'Foo', 'sequence': 1})
self.assertEqual(product.name, 'Foo')
self.assertEqual(product.sequence, 1)
self.env['product.pricelist'].create({
'name': 'Foo',
'item_ids': [(0, 0, {'product_id': product.id, 'fixed_price': 1})],
})
# patch template.write to modify pricelist items, which causes some
# cache invalidation
Template = self.registry['product.template']
Template_write = Template.write
def write(self, vals):
result = Template_write(self, vals)
items = self.env['product.pricelist.item'].search([('product_id', '=', product.id)])
items.fixed_price = 2
return result
with unittest.mock.patch.object(Template, 'write', write):
# change both 'name' and 'sequence': due to some programmed cache
# invalidation, the second field may not be properly assigned
product.write({'name': 'Bar', 'sequence': 2})
self.assertEqual(product.name, 'Bar')
self.assertEqual(product.sequence, 2)
class TestVariantsExclusion(common.TestProductCommon):
def setUp(self):
res = super(TestVariantsExclusion, self).setUp()
self.smartphone = self.env['product.template'].create({
'name': 'Smartphone',
})
self.size_attr = self.env['product.attribute'].create({'name': 'Size'})
self.size_attr_value_s = self.env['product.attribute.value'].create({'name': 'S', 'attribute_id': self.size_attr.id})
self.size_attr_value_xl = self.env['product.attribute.value'].create({'name': 'XL', 'attribute_id': self.size_attr.id})
self.storage_attr = self.env['product.attribute'].create({'name': 'Storage'})
self.storage_attr_value_128 = self.env['product.attribute.value'].create({'name': '128', 'attribute_id': self.storage_attr.id})
self.storage_attr_value_256 = self.env['product.attribute.value'].create({'name': '256', 'attribute_id': self.storage_attr.id})
# add attributes to product
self.smartphone_size_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.smartphone.id,
'attribute_id': self.size_attr.id,
'value_ids': [(6, 0, [self.size_attr_value_s.id, self.size_attr_value_xl.id])],
})
self.smartphone_storage_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.smartphone.id,
'attribute_id': self.storage_attr.id,
'value_ids': [(6, 0, [self.storage_attr_value_128.id, self.storage_attr_value_256.id])],
})
def get_ptav(model, att):
return model.valid_product_template_attribute_line_ids.filtered(
lambda l: l.attribute_id == att.attribute_id
).product_template_value_ids.filtered(
lambda v: v.product_attribute_value_id == att
)
self.smartphone_s = get_ptav(self.smartphone, self.size_attr_value_s)
self.smartphone_256 = get_ptav(self.smartphone, self.storage_attr_value_256)
self.smartphone_128 = get_ptav(self.smartphone, self.storage_attr_value_128)
return res
def test_variants_1_exclusion(self):
# Create one exclusion for Smartphone S
self.smartphone_s.write({
'exclude_for': [(0, 0, {
'product_tmpl_id': self.smartphone.id,
'value_ids': [(6, 0, [self.smartphone_256.id])]
})]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 3, 'With exclusion {s: [256]}, the smartphone should have 3 active different variants')
# Delete exclusion
self.smartphone_s.write({
'exclude_for': [(2, self.smartphone_s.exclude_for.id, 0)]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 4, 'With no exclusion, the smartphone should have 4 active different variants')
def test_variants_2_exclusions_same_line(self):
# Create two exclusions for Smartphone S on the same line
self.smartphone_s.write({
'exclude_for': [(0, 0, {
'product_tmpl_id': self.smartphone.id,
'value_ids': [(6, 0, [self.smartphone_128.id, self.smartphone_256.id])]
})]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 2, 'With exclusion {s: [128, 256]}, the smartphone should have 2 active different variants')
# Delete one exclusion of the line
self.smartphone_s.write({
'exclude_for': [(1, self.smartphone_s.exclude_for.id, {
'product_tmpl_id': self.smartphone.id,
'value_ids': [(6, 0, [self.smartphone_128.id])]
})]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 3, 'With exclusion {s: [128]}, the smartphone should have 3 active different variants')
# Delete exclusion
self.smartphone_s.write({
'exclude_for': [(2, self.smartphone_s.exclude_for.id, 0)]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 4, 'With no exclusion, the smartphone should have 4 active different variants')
def test_variants_2_exclusions_different_lines(self):
# add 1 exclusion
self.smartphone_s.write({
'exclude_for': [(0, 0, {
'product_tmpl_id': self.smartphone.id,
'value_ids': [(6, 0, [self.smartphone_128.id])]
})]
})
# add 1 exclusion on a different line
self.smartphone_s.write({
'exclude_for': [(0, 0, {
'product_tmpl_id': self.smartphone.id,
'value_ids': [(6, 0, [self.smartphone_256.id])]
})]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 2, 'With exclusion {s: [128, 256]}, the smartphone should have 2 active different variants')
# delete one exclusion line
self.smartphone_s.write({
'exclude_for': [(2, self.smartphone_s.exclude_for.ids[0], 0)]
})
self.assertEqual(len(self.smartphone.product_variant_ids), 3, 'With one exclusion, the smartphone should have 3 active different variants')
| 44.412256
| 63,776
|
5,063
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestPricelist(TransactionCase):
def setUp(self):
super(TestPricelist, self).setUp()
self.datacard = self.env['product.product'].create({'name': 'Office Lamp'})
self.usb_adapter = self.env['product.product'].create({'name': 'Office Chair'})
self.uom_ton = self.env.ref('uom.product_uom_ton')
self.uom_unit_id = self.ref('uom.product_uom_unit')
self.uom_dozen_id = self.ref('uom.product_uom_dozen')
self.uom_kgm_id = self.ref('uom.product_uom_kgm')
self.public_pricelist = self.env.ref('product.list0')
self.sale_pricelist_id = self.env['product.pricelist'].create({
'name': 'Sale pricelist',
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'list_price', # based on public price
'price_discount': 10,
'product_id': self.usb_adapter.id,
'applied_on': '0_product_variant',
}), (0, 0, {
'compute_price': 'formula',
'base': 'list_price', # based on public price
'price_surcharge': -0.5,
'product_id': self.datacard.id,
'applied_on': '0_product_variant',
})]
})
def test_10_discount(self):
# Make sure the price using a pricelist is the same than without after
# applying the computation manually
context = {}
public_context = dict(context, pricelist=self.public_pricelist.id)
pricelist_context = dict(context, pricelist=self.sale_pricelist_id.id)
usb_adapter_without_pricelist = self.usb_adapter.with_context(public_context)
usb_adapter_with_pricelist = self.usb_adapter.with_context(pricelist_context)
self.assertEqual(usb_adapter_with_pricelist.price, usb_adapter_without_pricelist.price*0.9)
datacard_without_pricelist = self.datacard.with_context(public_context)
datacard_with_pricelist = self.datacard.with_context(pricelist_context)
self.assertEqual(datacard_with_pricelist.price, datacard_without_pricelist.price-0.5)
# Make sure that changing the unit of measure does not break the unit
# price (after converting)
unit_context = dict(context, pricelist=self.sale_pricelist_id.id, uom=self.uom_unit_id)
dozen_context = dict(context, pricelist=self.sale_pricelist_id.id, uom=self.uom_dozen_id)
usb_adapter_unit = self.usb_adapter.with_context(unit_context)
usb_adapter_dozen = self.usb_adapter.with_context(dozen_context)
self.assertAlmostEqual(usb_adapter_unit.price*12, usb_adapter_dozen.price)
datacard_unit = self.datacard.with_context(unit_context)
datacard_dozen = self.datacard.with_context(dozen_context)
# price_surcharge applies to product default UoM, here "Units", so surcharge will be multiplied
self.assertAlmostEqual(datacard_unit.price*12, datacard_dozen.price)
def test_20_pricelist_uom(self):
# Verify that the pricelist rules are correctly using the product's default UoM
# as reference, and return a result according to the target UoM (as specific in the context)
kg, tonne = self.uom_kgm_id, self.uom_ton.id
tonne_price = 100
# make sure 'tonne' resolves down to 1 'kg'.
self.uom_ton.write({'rounding': 0.001})
# setup product stored in 'tonnes', with a discounted pricelist for qty > 3 tonnes
spam_id = self.env['product.product'].create({
'name': '1 tonne of spam',
'uom_id': self.uom_ton.id,
'uom_po_id': self.uom_ton.id,
'list_price': tonne_price,
'type': 'consu'
})
self.env['product.pricelist.item'].create({
'pricelist_id': self.public_pricelist.id,
'applied_on': '0_product_variant',
'compute_price': 'formula',
'base': 'list_price', # based on public price
'min_quantity': 3, # min = 3 tonnes
'price_surcharge': -10, # -10 EUR / tonne
'product_id': spam_id.id
})
pricelist = self.public_pricelist
def test_unit_price(qty, uom, expected_unit_price):
spam = spam_id.with_context({'uom': uom})
unit_price = pricelist.with_context({'uom': uom}).get_product_price(spam, qty, False)
self.assertAlmostEqual(unit_price, expected_unit_price, msg='Computed unit price is wrong')
# Test prices - they are *per unit*, the quantity is only here to match the pricelist rules!
test_unit_price(2, kg, tonne_price / 1000.0)
test_unit_price(2000, kg, tonne_price / 1000.0)
test_unit_price(3500, kg, (tonne_price - 10) / 1000.0)
test_unit_price(2, tonne, tonne_price)
test_unit_price(3, tonne, tonne_price - 10)
| 48.219048
| 5,063
|
4,616
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import common
class TestProductCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestProductCommon, cls).setUpClass()
# Customer related data
cls.partner_1 = cls.env['res.partner'].create({
'name': 'Julia Agrolait',
'email': 'julia@agrolait.example.com',
})
# Product environment related data
Uom = cls.env['uom.uom']
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.uom_dozen = cls.env.ref('uom.product_uom_dozen')
cls.uom_dunit = Uom.create({
'name': 'DeciUnit',
'category_id': cls.uom_unit.category_id.id,
'factor_inv': 0.1,
'factor': 10.0,
'uom_type': 'smaller',
'rounding': 0.001})
cls.uom_weight = cls.env.ref('uom.product_uom_kgm')
Product = cls.env['product.product']
cls.product_0 = Product.create({
'name': 'Work',
'type': 'service',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
cls.product_1 = Product.create({
'name': 'Courage',
'type': 'consu',
'default_code': 'PROD-1',
'uom_id': cls.uom_dunit.id,
'uom_po_id': cls.uom_dunit.id})
cls.product_2 = Product.create({
'name': 'Wood',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
cls.product_3 = Product.create({
'name': 'Stone',
'uom_id': cls.uom_dozen.id,
'uom_po_id': cls.uom_dozen.id})
cls.product_4 = Product.create({
'name': 'Stick',
'uom_id': cls.uom_dozen.id,
'uom_po_id': cls.uom_dozen.id})
cls.product_5 = Product.create({
'name': 'Stone Tools',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
cls.product_6 = Product.create({
'name': 'Door',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
cls.prod_att_1 = cls.env['product.attribute'].create({'name': 'Color'})
cls.prod_attr1_v1 = cls.env['product.attribute.value'].create({'name': 'red', 'attribute_id': cls.prod_att_1.id, 'sequence': 1})
cls.prod_attr1_v2 = cls.env['product.attribute.value'].create({'name': 'blue', 'attribute_id': cls.prod_att_1.id, 'sequence': 2})
cls.prod_attr1_v3 = cls.env['product.attribute.value'].create({'name': 'green', 'attribute_id': cls.prod_att_1.id, 'sequence': 3})
cls.product_7_template = cls.env['product.template'].create({
'name': 'Sofa',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id,
'attribute_line_ids': [(0, 0, {
'attribute_id': cls.prod_att_1.id,
'value_ids': [(6, 0, [cls.prod_attr1_v1.id, cls.prod_attr1_v2.id, cls.prod_attr1_v3.id])]
})]
})
cls.product_7_attr1_v1 = cls.product_7_template.attribute_line_ids[0].product_template_value_ids[0]
cls.product_7_attr1_v2 = cls.product_7_template.attribute_line_ids[0].product_template_value_ids[1]
cls.product_7_attr1_v3 = cls.product_7_template.attribute_line_ids[0].product_template_value_ids[2]
cls.product_7_1 = cls.product_7_template._get_variant_for_combination(cls.product_7_attr1_v1)
cls.product_7_2 = cls.product_7_template._get_variant_for_combination(cls.product_7_attr1_v2)
cls.product_7_3 = cls.product_7_template._get_variant_for_combination(cls.product_7_attr1_v3)
cls.product_8 = Product.create({
'name': 'House',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
cls.product_9 = Product.create({
'name': 'Paper',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
cls.product_10 = Product.create({
'name': 'Stone',
'uom_id': cls.uom_unit.id,
'uom_po_id': cls.uom_unit.id})
class TestAttributesCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestAttributesCommon, cls).setUpClass()
# create 10 attributes with 10 values each
cls.att_names = "ABCDEFGHIJ"
cls.attributes = cls.env['product.attribute'].create([{
'name': name,
'create_variant': 'no_variant',
'value_ids': [(0, 0, {'name': n}) for n in range(10)]
} for name in cls.att_names
])
| 39.118644
| 4,616
|
13,007
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
import time
from odoo.tests.common import TransactionCase
from odoo.tools import float_compare, test_reports
class TestProductPricelist(TransactionCase):
def setUp(self):
super(TestProductPricelist, self).setUp()
self.ProductPricelist = self.env['product.pricelist']
self.res_partner_4 = self.env['res.partner'].create({'name': 'Ready Mat'})
self.res_partner_1 = self.env['res.partner'].create({'name': 'Wood Corner'})
self.category_5_id = self.env['product.category'].create({
'name': 'Office Furniture',
'parent_id': self.env.ref('product.product_category_1').id
}).id
self.computer_SC234 = self.env['product.product'].create({
'name': 'Desk Combination',
'categ_id': self.category_5_id,
})
self.ipad_retina_display = self.env['product.product'].create({
'name': 'Customizable Desk',
})
self.custom_computer_kit = self.env['product.product'].create({
'name': 'Corner Desk Right Sit',
'categ_id': self.category_5_id,
})
self.ipad_mini = self.env['product.product'].create({
'name': 'Large Cabinet',
'categ_id': self.category_5_id,
'standard_price': 800.0,
})
self.monitor = self.env['product.product'].create({
'name': 'Super nice monitor',
'categ_id': self.category_5_id,
'list_price': 1000.0,
})
self.env['product.supplierinfo'].create([
{
'name': self.res_partner_1.id,
'product_tmpl_id': self.ipad_mini.product_tmpl_id.id,
'delay': 3,
'min_qty': 1,
'price': 750,
}, {
'name': self.res_partner_4.id,
'product_tmpl_id': self.ipad_mini.product_tmpl_id.id,
'delay': 3,
'min_qty': 1,
'price': 790,
}, {
'name': self.res_partner_4.id,
'product_tmpl_id': self.ipad_mini.product_tmpl_id.id,
'delay': 3,
'min_qty': 3,
'price': 785,
}, {
'name': self.res_partner_4.id,
'product_tmpl_id': self.monitor.product_tmpl_id.id,
'delay': 3,
'min_qty': 3,
'price': 100,
}
])
self.apple_in_ear_headphones = self.env['product.product'].create({
'name': 'Storage Box',
'categ_id': self.category_5_id,
})
self.laptop_E5023 = self.env['product.product'].create({
'name': 'Office Chair',
'categ_id': self.category_5_id,
})
self.laptop_S3450 = self.env['product.product'].create({
'name': 'Acoustic Bloc Screens',
'categ_id': self.category_5_id,
})
self.uom_unit_id = self.ref('uom.product_uom_unit')
self.list0 = self.ref('product.list0')
self.new_currency = self.env['res.currency'].create({
'name': 'Wonderful Currency',
'symbol': ':)',
'rate_ids': [(0, 0, {'rate': 10, 'name': time.strftime('%Y-%m-%d')})],
})
self.ipad_retina_display.write({'uom_id': self.uom_unit_id, 'categ_id': self.category_5_id})
self.customer_pricelist = self.ProductPricelist.create({
'name': 'Customer Pricelist',
'item_ids': [(0, 0, {
'name': 'Default pricelist',
'compute_price': 'formula',
'base': 'pricelist',
'base_pricelist_id': self.list0
}), (0, 0, {
'name': '10% Discount on Assemble Computer',
'applied_on': '1_product',
'product_tmpl_id': self.ipad_retina_display.product_tmpl_id.id,
'compute_price': 'formula',
'base': 'list_price',
'price_discount': 10
}), (0, 0, {
'name': '1 surchange on Laptop',
'applied_on': '1_product',
'product_tmpl_id': self.laptop_E5023.product_tmpl_id.id,
'compute_price': 'formula',
'base': 'list_price',
'price_surcharge': 1
}), (0, 0, {
'name': '5% Discount on all Computer related products',
'applied_on': '2_product_category',
'min_quantity': 2,
'compute_price': 'formula',
'base': 'list_price',
'categ_id': self.category_5_id,
'price_discount': 5
}), (0, 0, {
'name': '30% Discount on all products',
'applied_on': '3_global',
'date_start': '2011-12-27',
'date_end': '2011-12-31',
'compute_price': 'formula',
'price_discount': 30,
'base': 'list_price'
}), (0, 0, {
'name': 'Fixed on all products',
'applied_on': '1_product',
'product_tmpl_id': self.monitor.product_tmpl_id.id,
'date_start': '2020-04-06 09:00:00',
'date_end': '2020-04-09 12:00:00',
'compute_price': 'formula',
'price_discount': 50,
'base': 'list_price'
})]
})
def test_10_calculation_price_of_products_pricelist(self):
"""Test calculation of product price based on pricelist"""
# I check sale price of Customizable Desk
context = {}
context.update({'pricelist': self.customer_pricelist.id, 'quantity': 1})
ipad_retina_display = self.ipad_retina_display.with_context(context)
msg = "Wrong sale price: Customizable Desk. should be %s instead of %s" % (ipad_retina_display.price, (ipad_retina_display.lst_price-ipad_retina_display.lst_price*(0.10)))
self.assertEqual(float_compare(ipad_retina_display.price, (ipad_retina_display.lst_price-ipad_retina_display.lst_price*(0.10)), precision_digits=2), 0, msg)
# I check sale price of Laptop.
laptop_E5023 = self.laptop_E5023.with_context(context)
msg = "Wrong sale price: Laptop. should be %s instead of %s" % (laptop_E5023.price, (laptop_E5023.lst_price + 1))
self.assertEqual(float_compare(laptop_E5023.price, laptop_E5023.lst_price + 1, precision_digits=2), 0, msg)
# I check sale price of IT component.
apple_headphones = self.apple_in_ear_headphones.with_context(context)
msg = "Wrong sale price: IT component. should be %s instead of %s" % (apple_headphones.price, apple_headphones.lst_price)
self.assertEqual(float_compare(apple_headphones.price, apple_headphones.lst_price, precision_digits=2), 0, msg)
# I check sale price of IT component if more than 3 Unit.
context.update({'quantity': 5})
laptop_S3450 = self.laptop_S3450.with_context(context)
msg = "Wrong sale price: IT component if more than 3 Unit. should be %s instead of %s" % (laptop_S3450.price, (laptop_S3450.lst_price-laptop_S3450.lst_price*(0.05)))
self.assertEqual(float_compare(laptop_S3450.price, laptop_S3450.lst_price-laptop_S3450.lst_price*(0.05), precision_digits=2), 0, msg)
# I check sale price of LCD Monitor.
context.update({'quantity': 1})
ipad_mini = self.ipad_mini.with_context(context)
msg = "Wrong sale price: LCD Monitor. should be %s instead of %s" % (ipad_mini.price, ipad_mini.lst_price)
self.assertEqual(float_compare(ipad_mini.price, ipad_mini.lst_price, precision_digits=2), 0, msg)
# I check sale price of LCD Monitor on end of year.
context.update({'quantity': 1, 'date': '2011-12-31'})
ipad_mini = self.ipad_mini.with_context(context)
msg = "Wrong sale price: LCD Monitor on end of year. should be %s instead of %s" % (ipad_mini.price, ipad_mini.lst_price-ipad_mini.lst_price*(0.30))
self.assertEqual(float_compare(ipad_mini.price, ipad_mini.lst_price-ipad_mini.lst_price*(0.30), precision_digits=2), 0, msg)
# I check cost price of LCD Monitor.
context.update({'quantity': 1, 'date': False, 'partner_id': self.res_partner_4.id})
ipad_mini = self.ipad_mini.with_context(context)
partner = self.res_partner_4.with_context(context)
msg = "Wrong cost price: LCD Monitor. should be 790 instead of %s" % ipad_mini._select_seller(partner_id=partner, quantity=1.0).price
self.assertEqual(float_compare(ipad_mini._select_seller(partner_id=partner, quantity=1.0).price, 790, precision_digits=2), 0, msg)
# I check cost price of LCD Monitor if more than 3 Unit.
context.update({'quantity': 3})
ipad_mini = self.ipad_mini.with_context(context)
partner = self.res_partner_4.with_context(context)
msg = "Wrong cost price: LCD Monitor if more than 3 Unit.should be 785 instead of %s" % ipad_mini._select_seller(partner_id=partner, quantity=3.0).price
self.assertEqual(float_compare(ipad_mini._select_seller(partner_id=partner, quantity=3.0).price, 785, precision_digits=2), 0, msg)
# Check if the pricelist is applied at precise datetime
context.update({'quantity': 1, 'date': datetime.strptime('2020-04-05 08:00:00', '%Y-%m-%d %H:%M:%S')})
monitor = self.monitor.with_context(context)
partner = self.res_partner_4.with_context(context)
msg = "Wrong cost price: LCD Monitor. should be 1000 instead of %s" % monitor._select_seller(
partner_id=partner, quantity=1.0).price
self.assertEqual(
float_compare(monitor.price, monitor.lst_price, precision_digits=2), 0,
msg)
context.update({'quantity': 1, 'date': datetime.strptime('2020-04-06 10:00:00', '%Y-%m-%d %H:%M:%S')})
monitor = self.monitor.with_context(context)
msg = "Wrong cost price: LCD Monitor. should be 500 instead of %s" % monitor._select_seller(
partner_id=partner, quantity=1.0).price
self.assertEqual(
float_compare(monitor.price, monitor.lst_price/2, precision_digits=2), 0,
msg)
def test_20_price_different_currency_pricelist(self):
pricelist = self.ProductPricelist.create({
'name': 'Currency Pricelist',
'currency_id': self.new_currency.id,
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'list_price',
'price_surcharge': 100
})]
})
product = self.monitor.with_context({
'pricelist': pricelist.id, 'quantity': 1
})
# product price use the currency of the pricelist
self.assertEqual(product.price, 10100)
def test_21_price_diff_cur_min_margin_pricelist(self):
pricelist = self.ProductPricelist.create({
'name': 'Currency with Margin Pricelist',
'currency_id': self.new_currency.id,
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'list_price',
'price_min_margin': 10,
'price_max_margin': 100,
})]
})
product = self.monitor.with_context({
'pricelist': pricelist.id, 'quantity': 1
})
# product price use the currency of the pricelist
self.assertEqual(product.price, 10010)
def test_22_price_diff_cur_max_margin_pricelist(self):
pricelist = self.ProductPricelist.create({
'name': 'Currency with Margin Pricelist',
'currency_id': self.new_currency.id,
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'list_price',
'price_surcharge': 100,
'price_max_margin': 90
})]
})
product = self.monitor.with_context({
'pricelist': pricelist.id, 'quantity': 1
})
# product price use the currency of the pricelist
self.assertEqual(product.price, 10090)
def test_23_diff_curr_rounding(self):
""" Make sure rounding is applied after the currency conversion"""
pricelist = self.ProductPricelist.create({
'name': 'Currency Pricelist',
'currency_id': self.new_currency.id,
'item_ids': [(0, 0, {
'compute_price': 'formula',
'base': 'list_price',
'price_discount': 42.328745867,
'price_round': 1.00,
})]
})
product = self.computer_SC234
product.lst_price = 450.0
product = product.with_context({
'pricelist': pricelist.id, 'quantity': 1
})
self.assertEqual(product.price, 2595)
| 46.453571
| 13,007
|
35,218
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from psycopg2 import IntegrityError
from odoo.exceptions import UserError, ValidationError
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
from odoo.tools import mute_logger
class TestProductAttributeValueCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestProductAttributeValueCommon, cls).setUpClass()
cls.computer = cls.env['product.template'].create({
'name': 'Super Computer',
'price': 2000,
})
cls._add_ssd_attribute()
cls._add_ram_attribute()
cls._add_hdd_attribute()
cls.computer_case = cls.env['product.template'].create({
'name': 'Super Computer Case'
})
cls._add_size_attribute()
@classmethod
def _add_ssd_attribute(cls):
cls.ssd_attribute = cls.env['product.attribute'].create({'name': 'Memory', 'sequence': 1})
cls.ssd_256 = cls.env['product.attribute.value'].create({
'name': '256 GB',
'attribute_id': cls.ssd_attribute.id,
'sequence': 1,
})
cls.ssd_512 = cls.env['product.attribute.value'].create({
'name': '512 GB',
'attribute_id': cls.ssd_attribute.id,
'sequence': 2,
})
cls._add_ssd_attribute_line()
@classmethod
def _add_ssd_attribute_line(cls):
cls.computer_ssd_attribute_lines = cls.env['product.template.attribute.line'].create({
'product_tmpl_id': cls.computer.id,
'attribute_id': cls.ssd_attribute.id,
'value_ids': [(6, 0, [cls.ssd_256.id, cls.ssd_512.id])],
})
cls.computer_ssd_attribute_lines.product_template_value_ids[0].price_extra = 200
cls.computer_ssd_attribute_lines.product_template_value_ids[1].price_extra = 400
@classmethod
def _add_ram_attribute(cls):
cls.ram_attribute = cls.env['product.attribute'].create({'name': 'RAM', 'sequence': 2})
cls.ram_8 = cls.env['product.attribute.value'].create({
'name': '8 GB',
'attribute_id': cls.ram_attribute.id,
'sequence': 1,
})
cls.ram_16 = cls.env['product.attribute.value'].create({
'name': '16 GB',
'attribute_id': cls.ram_attribute.id,
'sequence': 2,
})
cls.ram_32 = cls.env['product.attribute.value'].create({
'name': '32 GB',
'attribute_id': cls.ram_attribute.id,
'sequence': 3,
})
cls.computer_ram_attribute_lines = cls.env['product.template.attribute.line'].create({
'product_tmpl_id': cls.computer.id,
'attribute_id': cls.ram_attribute.id,
'value_ids': [(6, 0, [cls.ram_8.id, cls.ram_16.id, cls.ram_32.id])],
})
cls.computer_ram_attribute_lines.product_template_value_ids[0].price_extra = 20
cls.computer_ram_attribute_lines.product_template_value_ids[1].price_extra = 40
cls.computer_ram_attribute_lines.product_template_value_ids[2].price_extra = 80
@classmethod
def _add_hdd_attribute(cls):
cls.hdd_attribute = cls.env['product.attribute'].create({'name': 'HDD', 'sequence': 3})
cls.hdd_1 = cls.env['product.attribute.value'].create({
'name': '1 To',
'attribute_id': cls.hdd_attribute.id,
'sequence': 1,
})
cls.hdd_2 = cls.env['product.attribute.value'].create({
'name': '2 To',
'attribute_id': cls.hdd_attribute.id,
'sequence': 2,
})
cls.hdd_4 = cls.env['product.attribute.value'].create({
'name': '4 To',
'attribute_id': cls.hdd_attribute.id,
'sequence': 3,
})
cls._add_hdd_attribute_line()
@classmethod
def _add_hdd_attribute_line(cls):
cls.computer_hdd_attribute_lines = cls.env['product.template.attribute.line'].create({
'product_tmpl_id': cls.computer.id,
'attribute_id': cls.hdd_attribute.id,
'value_ids': [(6, 0, [cls.hdd_1.id, cls.hdd_2.id, cls.hdd_4.id])],
})
cls.computer_hdd_attribute_lines.product_template_value_ids[0].price_extra = 2
cls.computer_hdd_attribute_lines.product_template_value_ids[1].price_extra = 4
cls.computer_hdd_attribute_lines.product_template_value_ids[2].price_extra = 8
def _add_ram_exclude_for(self):
self._get_product_value_id(self.computer_ram_attribute_lines, self.ram_16).update({
'exclude_for': [(0, 0, {
'product_tmpl_id': self.computer.id,
'value_ids': [(6, 0, [self._get_product_value_id(self.computer_hdd_attribute_lines, self.hdd_1).id])]
})]
})
@classmethod
def _add_size_attribute(cls):
cls.size_attribute = cls.env['product.attribute'].create({'name': 'Size', 'sequence': 4})
cls.size_m = cls.env['product.attribute.value'].create({
'name': 'M',
'attribute_id': cls.size_attribute.id,
'sequence': 1,
})
cls.size_l = cls.env['product.attribute.value'].create({
'name': 'L',
'attribute_id': cls.size_attribute.id,
'sequence': 2,
})
cls.size_xl = cls.env['product.attribute.value'].create({
'name': 'XL',
'attribute_id': cls.size_attribute.id,
'sequence': 3,
})
cls.computer_case_size_attribute_lines = cls.env['product.template.attribute.line'].create({
'product_tmpl_id': cls.computer_case.id,
'attribute_id': cls.size_attribute.id,
'value_ids': [(6, 0, [cls.size_m.id, cls.size_l.id, cls.size_xl.id])],
})
def _get_product_value_id(self, product_template_attribute_lines, product_attribute_value):
return product_template_attribute_lines.product_template_value_ids.filtered(
lambda product_value_id: product_value_id.product_attribute_value_id == product_attribute_value)[0]
def _get_product_template_attribute_value(self, product_attribute_value, model=False):
"""
Return the `product.template.attribute.value` matching
`product_attribute_value` for self.
:param: recordset of one product.attribute.value
:return: recordset of one product.template.attribute.value if found
else empty
"""
if not model:
model = self.computer
return model.valid_product_template_attribute_line_ids.filtered(
lambda l: l.attribute_id == product_attribute_value.attribute_id
).product_template_value_ids.filtered(
lambda v: v.product_attribute_value_id == product_attribute_value
)
def _add_exclude(self, m1, m2, product_template=False):
m1.update({
'exclude_for': [(0, 0, {
'product_tmpl_id': (product_template or self.computer).id,
'value_ids': [(6, 0, [m2.id])]
})]
})
@tagged('post_install', '-at_install')
class TestProductAttributeValueConfig(TestProductAttributeValueCommon):
def test_product_template_attribute_values_creation(self):
self.assertEqual(len(self.computer_ssd_attribute_lines.product_template_value_ids), 2,
'Product attribute values (ssd) were not automatically created')
self.assertEqual(len(self.computer_ram_attribute_lines.product_template_value_ids), 3,
'Product attribute values (ram) were not automatically created')
self.assertEqual(len(self.computer_hdd_attribute_lines.product_template_value_ids), 3,
'Product attribute values (hdd) were not automatically created')
self.assertEqual(len(self.computer_case_size_attribute_lines.product_template_value_ids), 3,
'Product attribute values (size) were not automatically created')
def test_get_variant_for_combination(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
# completely defined variant
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
ok_variant = self.computer._get_variant_for_combination(combination)
self.assertEqual(ok_variant.product_template_attribute_value_ids, combination)
# over defined variant
combination = computer_ssd_256 + computer_ram_8 + computer_ram_16 + computer_hdd_1
variant = self.computer._get_variant_for_combination(combination)
self.assertEqual(len(variant), 0)
# under defined variant
combination = computer_ssd_256 + computer_ram_8
variant = self.computer._get_variant_for_combination(combination)
self.assertFalse(variant)
def test_product_filtered_exclude_for(self):
"""
Super Computer has 18 variants total (2 ssd * 3 ram * 3 hdd)
RAM 16 excludes HDD 1, that matches 2 variants:
- SSD 256 RAM 16 HDD 1
- SSD 512 RAM 16 HDD 1
=> There has to be 16 variants left when filtered
"""
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ssd_512 = self._get_product_template_attribute_value(self.ssd_512)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self.assertEqual(len(self.computer._get_possible_variants()), 18)
self._add_ram_exclude_for()
self.assertEqual(len(self.computer._get_possible_variants()), 16)
self.assertTrue(self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)._is_variant_possible())
self.assertFalse(self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_16 + computer_hdd_1))
self.assertFalse(self.computer._get_variant_for_combination(computer_ssd_512 + computer_ram_16 + computer_hdd_1))
def test_children_product_filtered_exclude_for(self):
"""
Super Computer Case has 3 variants total (3 size)
Reference product Computer with HDD 4 excludes Size M
The following variant will be excluded:
- Size M
=> There has to be 2 variants left when filtered
"""
computer_hdd_4 = self._get_product_template_attribute_value(self.hdd_4)
computer_size_m = self._get_product_template_attribute_value(self.size_m, self.computer_case)
self._add_exclude(computer_hdd_4, computer_size_m, self.computer_case)
self.assertEqual(len(self.computer_case._get_possible_variants(computer_hdd_4)), 2)
self.assertFalse(self.computer_case._get_variant_for_combination(computer_size_m)._is_variant_possible(computer_hdd_4))
def test_is_combination_possible(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: basic
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: ram 16 excluding hdd1
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_16 + computer_hdd_1))
# CASE: under defined combination
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_16))
# CASE: no combination, no variant, just return the only variant
mouse = self.env['product.template'].create({'name': 'Mouse'})
self.assertTrue(mouse._is_combination_possible(self.env['product.template.attribute.value']))
# prep work for the last part of the test
color_attribute = self.env['product.attribute'].create({'name': 'Color'})
color_red = self.env['product.attribute.value'].create({
'name': 'Red',
'attribute_id': color_attribute.id,
})
color_green = self.env['product.attribute.value'].create({
'name': 'Green',
'attribute_id': color_attribute.id,
})
self.env['product.template.attribute.line'].create({
'product_tmpl_id': mouse.id,
'attribute_id': color_attribute.id,
'value_ids': [(6, 0, [color_red.id, color_green.id])],
})
mouse_color_red = self._get_product_template_attribute_value(color_red, mouse)
mouse_color_green = self._get_product_template_attribute_value(color_green, mouse)
self._add_exclude(computer_ssd_256, mouse_color_green, mouse)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
# CASE: wrong attributes (mouse_color_red not on computer)
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_16 + mouse_color_red))
# CASE: parent ok
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1, mouse_color_red))
self.assertTrue(mouse._is_combination_possible(mouse_color_red, computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: parent exclusion but good direction (parent is directional)
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1, mouse_color_green))
# CASE: parent exclusion and wrong direction (parent is directional)
self.assertFalse(mouse._is_combination_possible(mouse_color_green, computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: deleted combination
variant.unlink()
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: if multiple variants exist for the same combination and at least
# one of them is not archived, the combination is possible
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
self.env['product.product'].create({
'product_tmpl_id': self.computer.id,
'product_template_attribute_value_ids': [(6, 0, combination.ids)],
'active': False,
})
self.env['product.product'].create({
'product_tmpl_id': self.computer.id,
'product_template_attribute_value_ids': [(6, 0, combination.ids)],
'active': True,
})
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
def test_get_first_possible_combination(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ssd_512 = self._get_product_template_attribute_value(self.ssd_512)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_ram_32 = self._get_product_template_attribute_value(self.ram_32)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
computer_hdd_4 = self._get_product_template_attribute_value(self.hdd_4)
self._add_exclude(computer_ram_16, computer_hdd_1)
# Basic case: test all iterations of generator
gen = self.computer._get_possible_combinations()
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_2)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_4)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_16 + computer_hdd_2)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_16 + computer_hdd_4)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_2)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_4)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_2)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_4)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_16 + computer_hdd_2)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_16 + computer_hdd_4)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_2)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_4)
self.assertIsNone(next(gen, None))
# Give priority to ram_16 but it is not allowed by hdd_1 so it should return hhd_2 instead
# Test invalidate_cache on product.attribute.value write
computer_ram_16.product_attribute_value_id.sequence = -1
self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_16 + computer_hdd_2)
# Move down the ram, so it will try to change the ram instead of the hdd
# Test invalidate_cache on product.attribute write
self.ram_attribute.sequence = 10
self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
# Give priority to ram_32 and is allowed with the rest so it should return it
self.ram_attribute.sequence = 2
computer_ram_16.product_attribute_value_id.sequence = 2
computer_ram_32.product_attribute_value_id.sequence = -1
self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_32 + computer_hdd_1)
# Give priority to ram_16 but now it is not allowing any hdd so it should return ram_8 instead
computer_ram_32.product_attribute_value_id.sequence = 3
computer_ram_16.product_attribute_value_id.sequence = -1
self._add_exclude(computer_ram_16, computer_hdd_2)
self._add_exclude(computer_ram_16, computer_hdd_4)
self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
# Only the last combination is possible
computer_ram_16.product_attribute_value_id.sequence = 2
self._add_exclude(computer_ram_8, computer_hdd_1)
self._add_exclude(computer_ram_8, computer_hdd_2)
self._add_exclude(computer_ram_8, computer_hdd_4)
self._add_exclude(computer_ram_32, computer_hdd_1)
self._add_exclude(computer_ram_32, computer_hdd_2)
self._add_exclude(computer_ram_32, computer_ssd_256)
self.assertEqual(self.computer._get_first_possible_combination(), computer_ssd_512 + computer_ram_32 + computer_hdd_4)
# Not possible to add an exclusion when only one variant is left -> it deletes the product template associated to it
with self.assertRaises(UserError), self.cr.savepoint():
self._add_exclude(computer_ram_32, computer_hdd_4)
# If an exclusion rule deletes all variants at once it does not delete the template.
# Here we can test `_get_first_possible_combination` with a product template with no variants
# Deletes all exclusions
for exclusion in computer_ram_32.exclude_for:
computer_ram_32.write({
'exclude_for': [(2, exclusion.id, 0)]
})
# Activates all exclusions at once
computer_ram_32.write({
'exclude_for': [(0, computer_ram_32.exclude_for.id, {
'product_tmpl_id': self.computer.id,
'value_ids': [(6, 0, [computer_hdd_1.id, computer_hdd_2.id, computer_hdd_4.id, computer_ssd_256.id, computer_ssd_512.id])]
})]
})
self.assertEqual(self.computer._get_first_possible_combination(), self.env['product.template.attribute.value'])
gen = self.computer._get_possible_combinations()
self.assertIsNone(next(gen, None))
# Testing parent case
mouse = self.env['product.template'].create({'name': 'Mouse'})
self.assertTrue(mouse._is_combination_possible(self.env['product.template.attribute.value']))
# prep work for the last part of the test
color_attribute = self.env['product.attribute'].create({'name': 'Color'})
color_red = self.env['product.attribute.value'].create({
'name': 'Red',
'attribute_id': color_attribute.id,
})
color_green = self.env['product.attribute.value'].create({
'name': 'Green',
'attribute_id': color_attribute.id,
})
self.env['product.template.attribute.line'].create({
'product_tmpl_id': mouse.id,
'attribute_id': color_attribute.id,
'value_ids': [(6, 0, [color_red.id, color_green.id])],
})
mouse_color_red = self._get_product_template_attribute_value(color_red, mouse)
mouse_color_green = self._get_product_template_attribute_value(color_green, mouse)
self._add_exclude(computer_ssd_256, mouse_color_red, mouse)
self.assertEqual(mouse._get_first_possible_combination(parent_combination=computer_ssd_256 + computer_ram_8 + computer_hdd_1), mouse_color_green)
# Test to see if several attribute_line for same attribute is well handled
color_blue = self.env['product.attribute.value'].create({
'name': 'Blue',
'attribute_id': color_attribute.id,
})
color_yellow = self.env['product.attribute.value'].create({
'name': 'Yellow',
'attribute_id': color_attribute.id,
})
self.env['product.template.attribute.line'].create({
'product_tmpl_id': mouse.id,
'attribute_id': color_attribute.id,
'value_ids': [(6, 0, [color_blue.id, color_yellow.id])],
})
mouse_color_yellow = self._get_product_template_attribute_value(color_yellow, mouse)
self.assertEqual(mouse._get_first_possible_combination(necessary_values=mouse_color_yellow), mouse_color_red + mouse_color_yellow)
# Making sure it's not extremely slow (has to discard invalid combinations early !)
product_template = self.env['product.template'].create({
'name': 'many combinations',
})
for i in range(10):
# create the attributes
product_attribute = self.env['product.attribute'].create({
'name': "att %s" % i,
'create_variant': 'dynamic',
'sequence': i,
})
for j in range(50):
# create the attribute values
value = self.env['product.attribute.value'].create([{
'name': "val %s" % j,
'attribute_id': product_attribute.id,
'sequence': j,
}])
# set attribute and attribute values on the template
self.env['product.template.attribute.line'].create([{
'attribute_id': product_attribute.id,
'product_tmpl_id': product_template.id,
'value_ids': [(6, 0, product_attribute.value_ids.ids)]
}])
self._add_exclude(
self._get_product_template_attribute_value(product_template.attribute_line_ids[1].value_ids[0],
model=product_template),
self._get_product_template_attribute_value(product_template.attribute_line_ids[0].value_ids[0],
model=product_template),
product_template)
self._add_exclude(
self._get_product_template_attribute_value(product_template.attribute_line_ids[0].value_ids[0],
model=product_template),
self._get_product_template_attribute_value(product_template.attribute_line_ids[1].value_ids[1],
model=product_template),
product_template)
combination = self.env['product.template.attribute.value']
for idx, ptal in enumerate(product_template.attribute_line_ids):
if idx != 1:
value = ptal.product_template_value_ids[0]
else:
value = ptal.product_template_value_ids[2]
combination += value
started_at = time.time()
self.assertEqual(product_template._get_first_possible_combination(), combination)
elapsed = time.time() - started_at
# It should be about instantaneous, 0.5 to avoid false positives
self.assertLess(elapsed, 0.5)
def test_get_closest_possible_combinations(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ssd_512 = self._get_product_template_attribute_value(self.ssd_512)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_ram_32 = self._get_product_template_attribute_value(self.ram_32)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
computer_hdd_4 = self._get_product_template_attribute_value(self.hdd_4)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE nothing special (test 2 iterations)
gen = self.computer._get_closest_possible_combinations(None)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_2)
# CASE contains computer_hdd_1 (test all iterations)
gen = self.computer._get_closest_possible_combinations(computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_8 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_256 + computer_ram_32 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_8 + computer_hdd_1)
self.assertEqual(next(gen), computer_ssd_512 + computer_ram_32 + computer_hdd_1)
self.assertIsNone(next(gen, None))
# CASE contains computer_hdd_2
self.assertEqual(self.computer._get_closest_possible_combination(computer_hdd_2),
computer_ssd_256 + computer_ram_8 + computer_hdd_2)
# CASE contains computer_hdd_2, computer_ram_16
self.assertEqual(self.computer._get_closest_possible_combination(computer_hdd_2 + computer_ram_16),
computer_ssd_256 + computer_ram_16 + computer_hdd_2)
# CASE invalid combination (excluded):
self.assertEqual(self.computer._get_closest_possible_combination(computer_hdd_1 + computer_ram_16),
computer_ssd_256 + computer_ram_8 + computer_hdd_1)
# CASE invalid combination (too much):
self.assertEqual(self.computer._get_closest_possible_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_4 + computer_hdd_2),
computer_ssd_256 + computer_ram_8 + computer_hdd_4)
# Make sure this is not extremely slow:
product_template = self.env['product.template'].create({
'name': 'many combinations',
})
for i in range(10):
# create the attributes
product_attribute = self.env['product.attribute'].create({
'name': "att %s" % i,
'create_variant': 'dynamic',
'sequence': i,
})
for j in range(10):
# create the attribute values
self.env['product.attribute.value'].create([{
'name': "val %s/%s" % (i, j),
'attribute_id': product_attribute.id,
'sequence': j,
}])
# set attribute and attribute values on the template
self.env['product.template.attribute.line'].create([{
'attribute_id': product_attribute.id,
'product_tmpl_id': product_template.id,
'value_ids': [(6, 0, product_attribute.value_ids.ids)]
}])
# Get a value in the middle for each attribute to make sure it would
# take time to reach it (if looping one by one like before the fix).
combination = self.env['product.template.attribute.value']
for ptal in product_template.attribute_line_ids:
combination += ptal.product_template_value_ids[5]
started_at = time.time()
self.assertEqual(product_template._get_closest_possible_combination(combination), combination)
elapsed = time.time() - started_at
# It should take around 10ms, but to avoid false positives we check an
# higher value. Before the fix it would take hours.
self.assertLess(elapsed, 0.5)
def test_clear_caches(self):
"""The goal of this test is to make sure the cache is invalidated when
it should be."""
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
# CASE: initial result of _get_variant_for_combination
variant = self.computer._get_variant_for_combination(combination)
self.assertTrue(variant)
# CASE: clear_caches in product.product unlink
variant.unlink()
self.assertFalse(self.computer._get_variant_for_combination(combination))
# CASE: clear_caches in product.product create
variant = self.env['product.product'].create({
'product_tmpl_id': self.computer.id,
'product_template_attribute_value_ids': [(6, 0, combination.ids)],
})
self.assertEqual(variant, self.computer._get_variant_for_combination(combination))
# CASE: clear_caches in product.product write
variant.product_template_attribute_value_ids = False
self.assertFalse(self.computer._get_variant_id_for_combination(combination))
def test_constraints(self):
"""The goal of this test is to make sure constraints are correct."""
with self.assertRaises(UserError, msg="can't change variants creation mode of attribute used on product"):
self.ram_attribute.create_variant = 'no_variant'
with self.assertRaises(UserError, msg="can't delete attribute used on product"):
self.ram_attribute.unlink()
with self.assertRaises(UserError, msg="can't change the attribute of an value used on product"):
self.ram_32.attribute_id = self.hdd_attribute.id
with self.assertRaises(UserError, msg="can't delete value used on product"):
self.ram_32.unlink()
with self.assertRaises(ValidationError, msg="can't have attribute without value on product"):
self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer_case.id,
'attribute_id': self.hdd_attribute.id,
'value_ids': [(6, 0, [])],
})
with self.assertRaises(ValidationError, msg="value attribute must match line attribute"):
self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer_case.id,
'attribute_id': self.ram_attribute.id,
'value_ids': [(6, 0, [self.ssd_256.id])],
})
with self.assertRaises(UserError, msg="can't change the attribute of an attribute line"):
self.computer_ssd_attribute_lines.attribute_id = self.hdd_attribute.id
with self.assertRaises(UserError, msg="can't change the product of an attribute line"):
self.computer_ssd_attribute_lines.product_tmpl_id = self.computer_case.id
with self.assertRaises(UserError, msg="can't change the value of a product template attribute value"):
self.computer_ram_attribute_lines.product_template_value_ids[0].product_attribute_value_id = self.hdd_1
with self.assertRaises(UserError, msg="can't change the product of a product template attribute value"):
self.computer_ram_attribute_lines.product_template_value_ids[0].product_tmpl_id = self.computer_case.id
with mute_logger('odoo.sql_db'), self.assertRaises(IntegrityError, msg="can't have two values with the same name for the same attribute"):
self.env['product.attribute.value'].create({
'name': '32 GB',
'attribute_id': self.ram_attribute.id,
})
def test_inactive_related_product_update(self):
"""
Create a product and give it a product attribute then archive it, delete the product attribute,
unarchive the product and check that the product is not related to the product attribute.
"""
product_attribut = self.env['product.attribute'].create({
'name': 'PA',
'sequence': 1,
'create_variant': 'no_variant',
})
a1 = self.env['product.attribute.value'].create({
'name': 'pa_value',
'attribute_id': product_attribut.id,
'sequence': 1,
})
product = self.env['product.template'].create({
'name': 'P1',
'type': 'consu',
'attribute_line_ids': [(0, 0, {
'attribute_id': product_attribut.id,
'value_ids': [(6, 0, [a1.id])],
})]
})
self.assertEqual(product_attribut.number_related_products, 1, 'The product attribute must have an associated product')
product.action_archive()
self.assertFalse(product.active, 'The product should be archived.')
product.write({'attribute_line_ids': [[5, 0, 0]]})
product.action_unarchive()
self.assertTrue(product.active, 'The product should be unarchived.')
self.assertEqual(product_attribut.number_related_products, 0, 'The product attribute must not have an associated product')
| 50.455587
| 35,218
|
1,229
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestName(TransactionCase):
def setUp(self):
super().setUp()
self.product_name = 'Product Test Name'
self.product_code = 'PTN'
self.product = self.env['product.product'].create({
'name': self.product_name,
'default_code': self.product_code,
})
def test_10_product_name(self):
display_name = self.product.display_name
self.assertEqual(display_name, "[%s] %s" % (self.product_code, self.product_name),
"Code should be preprended the the name as the context is not preventing it.")
display_name = self.product.with_context(display_default_code=False).display_name
self.assertEqual(display_name, self.product_name,
"Code should not be preprended to the name as context should prevent it.")
def test_default_code_and_negative_operator(self):
res = self.env['product.template'].name_search(name='PTN', operator='not ilike')
res_ids = [r[0] for r in res]
self.assertNotIn(self.product.id, res_ids)
| 42.37931
| 1,229
|
2,882
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class ProductLabelLayout(models.TransientModel):
_name = 'product.label.layout'
_description = 'Choose the sheet layout to print the labels'
print_format = fields.Selection([
('dymo', 'Dymo'),
('2x7xprice', '2 x 7 with price'),
('4x7xprice', '4 x 7 with price'),
('4x12', '4 x 12'),
('4x12xprice', '4 x 12 with price')], string="Format", default='2x7xprice', required=True)
custom_quantity = fields.Integer('Quantity', default=1, required=True)
product_ids = fields.Many2many('product.product')
product_tmpl_ids = fields.Many2many('product.template')
extra_html = fields.Html('Extra Content', default='')
rows = fields.Integer(compute='_compute_dimensions')
columns = fields.Integer(compute='_compute_dimensions')
@api.depends('print_format')
def _compute_dimensions(self):
for wizard in self:
if 'x' in wizard.print_format:
columns, rows = wizard.print_format.split('x')[:2]
wizard.columns = int(columns)
wizard.rows = int(rows)
else:
wizard.columns, wizard.rows = 1, 1
def _prepare_report_data(self):
if self.custom_quantity <= 0:
raise UserError(_('You need to set a positive quantity.'))
# Get layout grid
if self.print_format == 'dymo':
xml_id = 'product.report_product_template_label_dymo'
elif 'x' in self.print_format:
xml_id = 'product.report_product_template_label'
else:
xml_id = ''
active_model = ''
if self.product_tmpl_ids:
products = self.product_tmpl_ids.ids
active_model = 'product.template'
elif self.product_ids:
products = self.product_ids.ids
active_model = 'product.product'
else:
raise UserError(_("No product to print, if the product is archived please unarchive it before printing its label."))
# Build data to pass to the report
data = {
'active_model': active_model,
'quantity_by_product': {p: self.custom_quantity for p in products},
'layout_wizard': self.id,
'price_included': 'xprice' in self.print_format,
}
return xml_id, data
def process(self):
self.ensure_one()
xml_id, data = self._prepare_report_data()
if not xml_id:
raise UserError(_('Unable to find report template for %s format', self.print_format))
report_action = self.env.ref(xml_id).report_action(None, data=data)
report_action.update({'close_on_report_download': True})
return report_action
| 38.945946
| 2,882
|
34,395
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from itertools import chain
from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import format_datetime
from odoo.tools.misc import formatLang, get_lang
class Pricelist(models.Model):
_name = "product.pricelist"
_description = "Pricelist"
_order = "sequence asc, id desc"
def _get_default_currency_id(self):
return self.env.company.currency_id.id
name = fields.Char('Pricelist Name', required=True, translate=True)
active = fields.Boolean('Active', default=True, help="If unchecked, it will allow you to hide the pricelist without removing it.")
item_ids = fields.One2many(
'product.pricelist.item', 'pricelist_id', 'Pricelist Rules',
copy=True)
currency_id = fields.Many2one('res.currency', 'Currency', default=_get_default_currency_id, required=True)
company_id = fields.Many2one('res.company', 'Company')
sequence = fields.Integer(default=16)
country_group_ids = fields.Many2many('res.country.group', 'res_country_group_pricelist_rel',
'pricelist_id', 'res_country_group_id', string='Country Groups')
discount_policy = fields.Selection([
('with_discount', 'Discount included in the price'),
('without_discount', 'Show public price & discount to the customer')],
default='with_discount', required=True)
def name_get(self):
return [(pricelist.id, '%s (%s)' % (pricelist.name, pricelist.currency_id.name)) for pricelist in self]
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if name and operator == '=' and not args:
# search on the name of the pricelist and its currency, opposite of name_get(),
# Used by the magic context filter in the product search view.
query_args = {'name': name, 'limit': limit, 'lang': get_lang(self.env).code}
query = """SELECT p.id
FROM ((
SELECT pr.id, pr.name
FROM product_pricelist pr JOIN
res_currency cur ON
(pr.currency_id = cur.id)
WHERE pr.name || ' (' || cur.name || ')' = %(name)s
)
UNION (
SELECT tr.res_id as id, tr.value as name
FROM ir_translation tr JOIN
product_pricelist pr ON (
pr.id = tr.res_id AND
tr.type = 'model' AND
tr.name = 'product.pricelist,name' AND
tr.lang = %(lang)s
) JOIN
res_currency cur ON
(pr.currency_id = cur.id)
WHERE tr.value || ' (' || cur.name || ')' = %(name)s
)
) p
ORDER BY p.name"""
if limit:
query += " LIMIT %(limit)s"
self._cr.execute(query, query_args)
ids = [r[0] for r in self._cr.fetchall()]
# regular search() to apply ACLs - may limit results below limit in some cases
pricelist_ids = self._search([('id', 'in', ids)], limit=limit, access_rights_uid=name_get_uid)
if pricelist_ids:
return pricelist_ids
return super(Pricelist, self)._name_search(name, args, operator=operator, limit=limit, name_get_uid=name_get_uid)
def _compute_price_rule_multi(self, products_qty_partner, date=False, uom_id=False):
""" Low-level method - Multi pricelist, multi products
Returns: dict{product_id: dict{pricelist_id: (price, suitable_rule)} }"""
if not self.ids:
pricelists = self.search([])
else:
pricelists = self
results = {}
for pricelist in pricelists:
subres = pricelist._compute_price_rule(products_qty_partner, date=date, uom_id=uom_id)
for product_id, price in subres.items():
results.setdefault(product_id, {})
results[product_id][pricelist.id] = price
return results
def _compute_price_rule_get_items(self, products_qty_partner, date, uom_id, prod_tmpl_ids, prod_ids, categ_ids):
self.ensure_one()
# Load all rules
self.env['product.pricelist.item'].flush(['price', 'currency_id', 'company_id', 'active'])
self.env.cr.execute(
"""
SELECT
item.id
FROM
product_pricelist_item AS item
LEFT JOIN product_category AS categ ON item.categ_id = categ.id
WHERE
(item.product_tmpl_id IS NULL OR item.product_tmpl_id = any(%s))
AND (item.product_id IS NULL OR item.product_id = any(%s))
AND (item.categ_id IS NULL OR item.categ_id = any(%s))
AND (item.pricelist_id = %s)
AND (item.date_start IS NULL OR item.date_start<=%s)
AND (item.date_end IS NULL OR item.date_end>=%s)
AND (item.active = TRUE)
ORDER BY
item.applied_on, item.min_quantity desc, categ.complete_name desc, item.id desc
""",
(prod_tmpl_ids, prod_ids, categ_ids, self.id, date, date))
# NOTE: if you change `order by` on that query, make sure it matches
# _order from model to avoid inconstencies and undeterministic issues.
item_ids = [x[0] for x in self.env.cr.fetchall()]
return self.env['product.pricelist.item'].browse(item_ids)
def _compute_price_rule(self, products_qty_partner, date=False, uom_id=False):
""" Low-level method - Mono pricelist, multi products
Returns: dict{product_id: (price, suitable_rule) for the given pricelist}
Date in context can be a date, datetime, ...
:param products_qty_partner: list of typles products, quantity, partner
:param datetime date: validity date
:param ID uom_id: intermediate unit of measure
"""
self.ensure_one()
if not date:
date = self._context.get('date') or fields.Datetime.now()
if not uom_id and self._context.get('uom'):
uom_id = self._context['uom']
if uom_id:
# rebrowse with uom if given
products = [item[0].with_context(uom=uom_id) for item in products_qty_partner]
products_qty_partner = [(products[index], data_struct[1], data_struct[2]) for index, data_struct in enumerate(products_qty_partner)]
else:
products = [item[0] for item in products_qty_partner]
if not products:
return {}
categ_ids = {}
for p in products:
categ = p.categ_id
while categ:
categ_ids[categ.id] = True
categ = categ.parent_id
categ_ids = list(categ_ids)
is_product_template = products[0]._name == "product.template"
if is_product_template:
prod_tmpl_ids = [tmpl.id for tmpl in products]
# all variants of all products
prod_ids = [p.id for p in
list(chain.from_iterable([t.product_variant_ids for t in products]))]
else:
prod_ids = [product.id for product in products]
prod_tmpl_ids = [product.product_tmpl_id.id for product in products]
items = self._compute_price_rule_get_items(products_qty_partner, date, uom_id, prod_tmpl_ids, prod_ids, categ_ids)
results = {}
for product, qty, partner in products_qty_partner:
results[product.id] = 0.0
suitable_rule = False
# Final unit price is computed according to `qty` in the `qty_uom_id` UoM.
# An intermediary unit price may be computed according to a different UoM, in
# which case the price_uom_id contains that UoM.
# The final price will be converted to match `qty_uom_id`.
qty_uom_id = self._context.get('uom') or product.uom_id.id
qty_in_product_uom = qty
if qty_uom_id != product.uom_id.id:
try:
qty_in_product_uom = self.env['uom.uom'].browse([self._context['uom']])._compute_quantity(qty, product.uom_id)
except UserError:
# Ignored - incompatible UoM in context, use default product UoM
pass
# if Public user try to access standard price from website sale, need to call price_compute.
# TDE SURPRISE: product can actually be a template
price = product.price_compute('list_price')[product.id]
price_uom = self.env['uom.uom'].browse([qty_uom_id])
for rule in items:
if not rule._is_applicable_for(product, qty_in_product_uom):
continue
if rule.base == 'pricelist' and rule.base_pricelist_id:
price = rule.base_pricelist_id._compute_price_rule([(product, qty, partner)], date, uom_id)[product.id][0] # TDE: 0 = price, 1 = rule
src_currency = rule.base_pricelist_id.currency_id
else:
# if base option is public price take sale price else cost price of product
# price_compute returns the price in the context UoM, i.e. qty_uom_id
price = product.price_compute(rule.base)[product.id]
if rule.base == 'standard_price':
src_currency = product.cost_currency_id
else:
src_currency = product.currency_id
if src_currency != self.currency_id:
price = src_currency._convert(
price, self.currency_id, self.env.company, date, round=False)
if price is not False:
price = rule._compute_price(price, price_uom, product, quantity=qty, partner=partner)
suitable_rule = rule
break
if not suitable_rule:
cur = product.currency_id
price = cur._convert(price, self.currency_id, self.env.company, date, round=False)
results[product.id] = (price, suitable_rule and suitable_rule.id or False)
return results
# New methods: product based
def get_products_price(self, products, quantities, partners, date=False, uom_id=False):
""" For a given pricelist, return price for products
Returns: dict{product_id: product price}, in the given pricelist """
self.ensure_one()
return {
product_id: res_tuple[0]
for product_id, res_tuple in self._compute_price_rule(
list(zip(products, quantities, partners)),
date=date,
uom_id=uom_id
).items()
}
def get_product_price(self, product, quantity, partner, date=False, uom_id=False):
""" For a given pricelist, return price for a given product """
self.ensure_one()
return self._compute_price_rule([(product, quantity, partner)], date=date, uom_id=uom_id)[product.id][0]
def get_product_price_rule(self, product, quantity, partner, date=False, uom_id=False):
""" For a given pricelist, return price and rule for a given product """
self.ensure_one()
return self._compute_price_rule([(product, quantity, partner)], date=date, uom_id=uom_id)[product.id]
def price_get(self, prod_id, qty, partner=None):
""" Multi pricelist, mono product - returns price per pricelist """
return {key: price[0] for key, price in self.price_rule_get(prod_id, qty, partner=partner).items()}
def price_rule_get_multi(self, products_by_qty_by_partner):
""" Multi pricelist, multi product - return tuple """
return self._compute_price_rule_multi(products_by_qty_by_partner)
def price_rule_get(self, prod_id, qty, partner=None):
""" Multi pricelist, mono product - return tuple """
product = self.env['product.product'].browse([prod_id])
return self._compute_price_rule_multi([(product, qty, partner)])[prod_id]
@api.model
def _price_get_multi(self, pricelist, products_by_qty_by_partner):
""" Mono pricelist, multi product - return price per product """
return pricelist.get_products_price(
list(zip(**products_by_qty_by_partner)))
def _get_partner_pricelist_multi_search_domain_hook(self, company_id):
return [
('active', '=', True),
('company_id', 'in', [company_id, False]),
]
def _get_partner_pricelist_multi_filter_hook(self):
return self.filtered('active')
def _get_partner_pricelist_multi(self, partner_ids, company_id=None):
""" Retrieve the applicable pricelist for given partners in a given company.
It will return the first found pricelist in this order:
First, the pricelist of the specific property (res_id set), this one
is created when saving a pricelist on the partner form view.
Else, it will return the pricelist of the partner country group
Else, it will return the generic property (res_id not set), this one
is created on the company creation.
Else, it will return the first available pricelist
:param company_id: if passed, used for looking up properties,
instead of current user's company
:return: a dict {partner_id: pricelist}
"""
# `partner_ids` might be ID from inactive uers. We should use active_test
# as we will do a search() later (real case for website public user).
Partner = self.env['res.partner'].with_context(active_test=False)
company_id = company_id or self.env.company.id
Property = self.env['ir.property'].with_company(company_id)
Pricelist = self.env['product.pricelist']
pl_domain = self._get_partner_pricelist_multi_search_domain_hook(company_id)
# if no specific property, try to find a fitting pricelist
result = Property._get_multi('property_product_pricelist', Partner._name, partner_ids)
remaining_partner_ids = [pid for pid, val in result.items() if not val or
not val._get_partner_pricelist_multi_filter_hook()]
if remaining_partner_ids:
# get fallback pricelist when no pricelist for a given country
pl_fallback = (
Pricelist.search(pl_domain + [('country_group_ids', '=', False)], limit=1) or
Property._get('property_product_pricelist', 'res.partner') or
Pricelist.search(pl_domain, limit=1)
)
# group partners by country, and find a pricelist for each country
domain = [('id', 'in', remaining_partner_ids)]
groups = Partner.read_group(domain, ['country_id'], ['country_id'])
for group in groups:
country_id = group['country_id'] and group['country_id'][0]
pl = Pricelist.search(pl_domain + [('country_group_ids.country_ids', '=', country_id)], limit=1)
pl = pl or pl_fallback
for pid in Partner.search(group['__domain']).ids:
result[pid] = pl
return result
@api.model
def get_import_templates(self):
return [{
'label': _('Import Template for Pricelists'),
'template': '/product/static/xls/product_pricelist.xls'
}]
@api.ondelete(at_uninstall=False)
def _unlink_except_used_as_rule_base(self):
linked_items = self.env['product.pricelist.item'].sudo().with_context(active_test=False).search([
('base', '=', 'pricelist'),
('base_pricelist_id', 'in', self.ids),
('pricelist_id', 'not in', self.ids),
])
if linked_items:
raise UserError(_(
'You cannot delete those pricelist(s):\n(%s)\n, they are used in other pricelist(s):\n%s',
'\n'.join(linked_items.base_pricelist_id.mapped('display_name')),
'\n'.join(linked_items.pricelist_id.mapped('display_name'))
))
class ResCountryGroup(models.Model):
_inherit = 'res.country.group'
pricelist_ids = fields.Many2many('product.pricelist', 'res_country_group_pricelist_rel',
'res_country_group_id', 'pricelist_id', string='Pricelists')
class PricelistItem(models.Model):
_name = "product.pricelist.item"
_description = "Pricelist Rule"
_order = "applied_on, min_quantity desc, categ_id desc, id desc"
_check_company_auto = True
# NOTE: if you change _order on this model, make sure it matches the SQL
# query built in _compute_price_rule() above in this file to avoid
# inconstencies and undeterministic issues.
def _default_pricelist_id(self):
return self.env['product.pricelist'].search([
'|', ('company_id', '=', False),
('company_id', '=', self.env.company.id)], limit=1)
product_tmpl_id = fields.Many2one(
'product.template', 'Product', ondelete='cascade', check_company=True,
help="Specify a template if this rule only applies to one product template. Keep empty otherwise.")
product_id = fields.Many2one(
'product.product', 'Product Variant', ondelete='cascade', check_company=True,
help="Specify a product if this rule only applies to one product. Keep empty otherwise.")
categ_id = fields.Many2one(
'product.category', 'Product Category', ondelete='cascade',
help="Specify a product category if this rule only applies to products belonging to this category or its children categories. Keep empty otherwise.")
min_quantity = fields.Float(
'Min. Quantity', default=0, digits="Product Unit Of Measure",
help="For the rule to apply, bought/sold quantity must be greater "
"than or equal to the minimum quantity specified in this field.\n"
"Expressed in the default unit of measure of the product.")
applied_on = fields.Selection([
('3_global', 'All Products'),
('2_product_category', 'Product Category'),
('1_product', 'Product'),
('0_product_variant', 'Product Variant')], "Apply On",
default='3_global', required=True,
help='Pricelist Item applicable on selected option')
base = fields.Selection([
('list_price', 'Sales Price'),
('standard_price', 'Cost'),
('pricelist', 'Other Pricelist')], "Based on",
default='list_price', required=True,
help='Base price for computation.\n'
'Sales Price: The base price will be the Sales Price.\n'
'Cost Price : The base price will be the cost price.\n'
'Other Pricelist : Computation of the base price based on another Pricelist.')
base_pricelist_id = fields.Many2one('product.pricelist', 'Other Pricelist', check_company=True)
pricelist_id = fields.Many2one('product.pricelist', 'Pricelist', index=True, ondelete='cascade', required=True, default=_default_pricelist_id)
price_surcharge = fields.Float(
'Price Surcharge', digits='Product Price',
help='Specify the fixed amount to add or subtract(if negative) to the amount calculated with the discount.')
price_discount = fields.Float(
'Price Discount', default=0, digits=(16, 2),
help="You can apply a mark-up by setting a negative discount.")
price_round = fields.Float(
'Price Rounding', digits='Product Price',
help="Sets the price so that it is a multiple of this value.\n"
"Rounding is applied after the discount and before the surcharge.\n"
"To have prices that end in 9.99, set rounding 10, surcharge -0.01")
price_min_margin = fields.Float(
'Min. Price Margin', digits='Product Price',
help='Specify the minimum amount of margin over the base price.')
price_max_margin = fields.Float(
'Max. Price Margin', digits='Product Price',
help='Specify the maximum amount of margin over the base price.')
company_id = fields.Many2one(
'res.company', 'Company',
readonly=True, related='pricelist_id.company_id', store=True)
currency_id = fields.Many2one(
'res.currency', 'Currency',
readonly=True, related='pricelist_id.currency_id', store=True)
active = fields.Boolean(
readonly=True, related="pricelist_id.active", store=True)
date_start = fields.Datetime('Start Date', help="Starting datetime for the pricelist item validation\n"
"The displayed value depends on the timezone set in your preferences.")
date_end = fields.Datetime('End Date', help="Ending datetime for the pricelist item validation\n"
"The displayed value depends on the timezone set in your preferences.")
compute_price = fields.Selection([
('fixed', 'Fixed Price'),
('percentage', 'Discount'),
('formula', 'Formula')], index=True, default='fixed', required=True)
fixed_price = fields.Float('Fixed Price', digits='Product Price')
percent_price = fields.Float(
'Percentage Price',
help="You can apply a mark-up by setting a negative discount.")
# functional fields used for usability purposes
name = fields.Char(
'Name', compute='_get_pricelist_item_name_price',
help="Explicit rule name for this pricelist line.")
price = fields.Char(
'Price', compute='_get_pricelist_item_name_price',
help="Explicit rule name for this pricelist line.")
rule_tip = fields.Char(compute='_compute_rule_tip')
@api.constrains('base_pricelist_id', 'pricelist_id', 'base')
def _check_recursion(self):
if any(item.base == 'pricelist' and item.pricelist_id and item.pricelist_id == item.base_pricelist_id for item in self):
raise ValidationError(_('You cannot assign the Main Pricelist as Other Pricelist in PriceList Item'))
@api.constrains('date_start', 'date_end')
def _check_date_range(self):
for item in self:
if item.date_start and item.date_end and item.date_start >= item.date_end:
raise ValidationError(_('%s : end date (%s) should be greater than start date (%s)', item.display_name, format_datetime(self.env, item.date_end), format_datetime(self.env, item.date_start)))
return True
@api.constrains('price_min_margin', 'price_max_margin')
def _check_margin(self):
if any(item.price_min_margin > item.price_max_margin for item in self):
raise ValidationError(_('The minimum margin should be lower than the maximum margin.'))
@api.constrains('product_id', 'product_tmpl_id', 'categ_id')
def _check_product_consistency(self):
for item in self:
if item.applied_on == "2_product_category" and not item.categ_id:
raise ValidationError(_("Please specify the category for which this rule should be applied"))
elif item.applied_on == "1_product" and not item.product_tmpl_id:
raise ValidationError(_("Please specify the product for which this rule should be applied"))
elif item.applied_on == "0_product_variant" and not item.product_id:
raise ValidationError(_("Please specify the product variant for which this rule should be applied"))
@api.depends('applied_on', 'categ_id', 'product_tmpl_id', 'product_id', 'compute_price', 'fixed_price', \
'pricelist_id', 'percent_price', 'price_discount', 'price_surcharge')
def _get_pricelist_item_name_price(self):
for item in self:
if item.categ_id and item.applied_on == '2_product_category':
item.name = _("Category: %s") % (item.categ_id.display_name)
elif item.product_tmpl_id and item.applied_on == '1_product':
item.name = _("Product: %s") % (item.product_tmpl_id.display_name)
elif item.product_id and item.applied_on == '0_product_variant':
item.name = _("Variant: %s") % (item.product_id.with_context(display_default_code=False).display_name)
else:
item.name = _("All Products")
if item.compute_price == 'fixed':
item.price = formatLang(item.env, item.fixed_price, monetary=True, dp="Product Price", currency_obj=item.currency_id)
elif item.compute_price == 'percentage':
item.price = _("%s %% discount", item.percent_price)
else:
item.price = _("%(percentage)s %% discount and %(price)s surcharge", percentage=item.price_discount, price=item.price_surcharge)
@api.depends_context('lang')
@api.depends('compute_price', 'price_discount', 'price_surcharge', 'base', 'price_round')
def _compute_rule_tip(self):
base_selection_vals = {elem[0]: elem[1] for elem in self._fields['base']._description_selection(self.env)}
self.rule_tip = False
for item in self:
if item.compute_price != 'formula':
continue
base_amount = 100
discount_factor = (100 - item.price_discount) / 100
discounted_price = base_amount * discount_factor
if item.price_round:
discounted_price = tools.float_round(discounted_price, precision_rounding=item.price_round)
surcharge = tools.format_amount(item.env, item.price_surcharge, item.currency_id)
item.rule_tip = _(
"%(base)s with a %(discount)s %% discount and %(surcharge)s extra fee\n"
"Example: %(amount)s * %(discount_charge)s + %(price_surcharge)s → %(total_amount)s",
base=base_selection_vals[item.base],
discount=item.price_discount,
surcharge=surcharge,
amount=tools.format_amount(item.env, 100, item.currency_id),
discount_charge=discount_factor,
price_surcharge=surcharge,
total_amount=tools.format_amount(
item.env, discounted_price + item.price_surcharge, item.currency_id),
)
@api.onchange('compute_price')
def _onchange_compute_price(self):
if self.compute_price != 'fixed':
self.fixed_price = 0.0
if self.compute_price != 'percentage':
self.percent_price = 0.0
if self.compute_price != 'formula':
self.update({
'base': 'list_price',
'price_discount': 0.0,
'price_surcharge': 0.0,
'price_round': 0.0,
'price_min_margin': 0.0,
'price_max_margin': 0.0,
})
@api.onchange('product_id')
def _onchange_product_id(self):
has_product_id = self.filtered('product_id')
for item in has_product_id:
item.product_tmpl_id = item.product_id.product_tmpl_id
if self.env.context.get('default_applied_on', False) == '1_product':
# If a product variant is specified, apply on variants instead
# Reset if product variant is removed
has_product_id.update({'applied_on': '0_product_variant'})
(self - has_product_id).update({'applied_on': '1_product'})
@api.onchange('product_tmpl_id')
def _onchange_product_tmpl_id(self):
has_tmpl_id = self.filtered('product_tmpl_id')
for item in has_tmpl_id:
if item.product_id and item.product_id.product_tmpl_id != item.product_tmpl_id:
item.product_id = None
@api.onchange('product_id', 'product_tmpl_id', 'categ_id')
def _onchane_rule_content(self):
if not self.user_has_groups('product.group_sale_pricelist') and not self.env.context.get('default_applied_on', False):
# If advanced pricelists are disabled (applied_on field is not visible)
# AND we aren't coming from a specific product template/variant.
variants_rules = self.filtered('product_id')
template_rules = (self-variants_rules).filtered('product_tmpl_id')
variants_rules.update({'applied_on': '0_product_variant'})
template_rules.update({'applied_on': '1_product'})
(self-variants_rules-template_rules).update({'applied_on': '3_global'})
@api.onchange('price_round')
def _onchange_price_round(self):
if any(item.price_round and item.price_round < 0.0 for item in self):
raise ValidationError(_("The rounding method must be strictly positive."))
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if values.get('applied_on', False):
# Ensure item consistency for later searches.
applied_on = values['applied_on']
if applied_on == '3_global':
values.update(dict(product_id=None, product_tmpl_id=None, categ_id=None))
elif applied_on == '2_product_category':
values.update(dict(product_id=None, product_tmpl_id=None))
elif applied_on == '1_product':
values.update(dict(product_id=None, categ_id=None))
elif applied_on == '0_product_variant':
values.update(dict(categ_id=None))
return super(PricelistItem, self).create(vals_list)
def write(self, values):
if values.get('applied_on', False):
# Ensure item consistency for later searches.
applied_on = values['applied_on']
if applied_on == '3_global':
values.update(dict(product_id=None, product_tmpl_id=None, categ_id=None))
elif applied_on == '2_product_category':
values.update(dict(product_id=None, product_tmpl_id=None))
elif applied_on == '1_product':
values.update(dict(product_id=None, categ_id=None))
elif applied_on == '0_product_variant':
values.update(dict(categ_id=None))
res = super(PricelistItem, self).write(values)
# When the pricelist changes we need the product.template price
# to be invalided and recomputed.
self.env['product.template'].invalidate_cache(['price'])
self.env['product.product'].invalidate_cache(['price'])
return res
def toggle_active(self):
raise ValidationError(_("You cannot disable a pricelist rule, please delete it or archive its pricelist instead."))
def _is_applicable_for(self, product, qty_in_product_uom):
"""Check whether the current rule is valid for the given product & qty.
Note: self.ensure_one()
:param product: product record (product.product/product.template)
:param float qty_in_product_uom: quantity, expressed in product UoM
:returns: Whether rules is valid or not
:rtype: bool
"""
self.ensure_one()
product.ensure_one()
res = True
is_product_template = product._name == 'product.template'
if self.min_quantity and qty_in_product_uom < self.min_quantity:
res = False
elif self.applied_on == "2_product_category":
if (
product.categ_id != self.categ_id
and not product.categ_id.parent_path.startswith(self.categ_id.parent_path)
):
res = False
else:
# Applied on a specific product template/variant
if is_product_template:
if self.applied_on == "1_product" and product.id != self.product_tmpl_id.id:
res = False
elif self.applied_on == "0_product_variant" and not (
product.product_variant_count == 1
and product.product_variant_id.id == self.product_id.id
):
# product self acceptable on template if has only one variant
res = False
else:
if self.applied_on == "1_product" and product.product_tmpl_id.id != self.product_tmpl_id.id:
res = False
elif self.applied_on == "0_product_variant" and product.id != self.product_id.id:
res = False
return res
def _compute_price(self, price, price_uom, product, quantity=1.0, partner=False):
"""Compute the unit price of a product in the context of a pricelist application.
The unused parameters are there to make the full context available for overrides.
"""
self.ensure_one()
convert_to_price_uom = (lambda price: product.uom_id._compute_price(price, price_uom))
if self.compute_price == 'fixed':
price = convert_to_price_uom(self.fixed_price)
elif self.compute_price == 'percentage':
price = (price - (price * (self.percent_price / 100))) or 0.0
else:
# complete formula
price_limit = price
price = (price - (price * (self.price_discount / 100))) or 0.0
if self.price_round:
price = tools.float_round(price, precision_rounding=self.price_round)
if self.price_surcharge:
price += convert_to_price_uom(self.price_surcharge)
if self.price_min_margin:
price_min_margin = convert_to_price_uom(self.price_min_margin)
price = max(price, price_limit + price_min_margin)
if self.price_max_margin:
price_max_margin = convert_to_price_uom(self.price_max_margin)
price = min(price, price_limit + price_max_margin)
return price
| 50.877219
| 34,393
|
65,918
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import itertools
import logging
from collections import defaultdict
from odoo import api, fields, models, tools, _, SUPERUSER_ID
from odoo.exceptions import ValidationError, RedirectWarning, UserError
from odoo.osv import expression
_logger = logging.getLogger(__name__)
class ProductTemplate(models.Model):
_name = "product.template"
_inherit = ['mail.thread', 'mail.activity.mixin', 'image.mixin']
_description = "Product Template"
_order = "priority desc, name"
@tools.ormcache()
def _get_default_category_id(self):
# Deletion forbidden (at least through unlink)
return self.env.ref('product.product_category_all')
@tools.ormcache()
def _get_default_uom_id(self):
# Deletion forbidden (at least through unlink)
return self.env.ref('uom.product_uom_unit')
def _get_default_uom_po_id(self):
return self.default_get(['uom_id']).get('uom_id') or self._get_default_uom_id()
def _read_group_categ_id(self, categories, domain, order):
category_ids = self.env.context.get('default_categ_id')
if not category_ids and self.env.context.get('group_expand'):
category_ids = categories._search([], order=order, access_rights_uid=SUPERUSER_ID)
return categories.browse(category_ids)
name = fields.Char('Name', index=True, required=True, translate=True)
sequence = fields.Integer('Sequence', default=1, help='Gives the sequence order when displaying a product list')
description = fields.Html(
'Description', translate=True)
description_purchase = fields.Text(
'Purchase Description', translate=True)
description_sale = fields.Text(
'Sales Description', translate=True,
help="A description of the Product that you want to communicate to your customers. "
"This description will be copied to every Sales Order, Delivery Order and Customer Invoice/Credit Note")
detailed_type = fields.Selection([
('consu', 'Consumable'),
('service', 'Service')], string='Product Type', default='consu', required=True,
help='A storable product is a product for which you manage stock. The Inventory app has to be installed.\n'
'A consumable product is a product for which stock is not managed.\n'
'A service is a non-material product you provide.')
type = fields.Selection(
selection=[
('consu', 'Consumable'),
('service', 'Service')
],
compute='_compute_type',
store=True,
readonly=False,
)
categ_id = fields.Many2one(
'product.category', 'Product Category',
change_default=True, default=_get_default_category_id, group_expand='_read_group_categ_id',
required=True, help="Select category for the current product")
currency_id = fields.Many2one(
'res.currency', 'Currency', compute='_compute_currency_id')
cost_currency_id = fields.Many2one(
'res.currency', 'Cost Currency', compute='_compute_cost_currency_id')
# price fields
# price: total template price, context dependent (partner, pricelist, quantity)
price = fields.Float(
'Price', compute='_compute_template_price', inverse='_set_template_price',
digits='Product Price')
# list_price: catalog price, user defined
list_price = fields.Float(
'Sales Price', default=1.0,
digits='Product Price',
help="Price at which the product is sold to customers.",
)
standard_price = fields.Float(
'Cost', compute='_compute_standard_price',
inverse='_set_standard_price', search='_search_standard_price',
digits='Product Price', groups="base.group_user",
help="""In Standard Price & AVCO: value of the product (automatically computed in AVCO).
In FIFO: value of the next unit that will leave the stock (automatically computed).
Used to value the product when the purchase cost is not known (e.g. inventory adjustment).
Used to compute margins on sale orders.""")
volume = fields.Float(
'Volume', compute='_compute_volume', inverse='_set_volume', digits='Volume', store=True)
volume_uom_name = fields.Char(string='Volume unit of measure label', compute='_compute_volume_uom_name')
weight = fields.Float(
'Weight', compute='_compute_weight', digits='Stock Weight',
inverse='_set_weight', store=True)
weight_uom_name = fields.Char(string='Weight unit of measure label', compute='_compute_weight_uom_name')
sale_ok = fields.Boolean('Can be Sold', default=True)
purchase_ok = fields.Boolean('Can be Purchased', default=True)
pricelist_id = fields.Many2one(
'product.pricelist', 'Pricelist', store=False,
help='Technical field. Used for searching on pricelists, not stored in database.')
uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
default=_get_default_uom_id, required=True,
help="Default unit of measure used for all stock operations.")
uom_name = fields.Char(string='Unit of Measure Name', related='uom_id.name', readonly=True)
uom_po_id = fields.Many2one(
'uom.uom', 'Purchase UoM',
default=_get_default_uom_po_id, required=True,
help="Default unit of measure used for purchase orders. It must be in the same category as the default unit of measure.")
company_id = fields.Many2one(
'res.company', 'Company', index=1)
packaging_ids = fields.One2many(
'product.packaging', string="Product Packages", compute="_compute_packaging_ids", inverse="_set_packaging_ids",
help="Gives the different ways to package the same product.")
seller_ids = fields.One2many('product.supplierinfo', 'product_tmpl_id', 'Vendors', depends_context=('company',), help="Define vendor pricelists.")
variant_seller_ids = fields.One2many('product.supplierinfo', 'product_tmpl_id')
active = fields.Boolean('Active', default=True, help="If unchecked, it will allow you to hide the product without removing it.")
color = fields.Integer('Color Index')
is_product_variant = fields.Boolean(string='Is a product variant', compute='_compute_is_product_variant')
attribute_line_ids = fields.One2many('product.template.attribute.line', 'product_tmpl_id', 'Product Attributes', copy=True)
valid_product_template_attribute_line_ids = fields.Many2many('product.template.attribute.line',
compute="_compute_valid_product_template_attribute_line_ids", string='Valid Product Attribute Lines', help="Technical compute")
product_variant_ids = fields.One2many('product.product', 'product_tmpl_id', 'Products', required=True)
# performance: product_variant_id provides prefetching on the first product variant only
product_variant_id = fields.Many2one('product.product', 'Product', compute='_compute_product_variant_id')
product_variant_count = fields.Integer(
'# Product Variants', compute='_compute_product_variant_count')
# related to display product product information if is_product_variant
barcode = fields.Char('Barcode', compute='_compute_barcode', inverse='_set_barcode', search='_search_barcode')
default_code = fields.Char(
'Internal Reference', compute='_compute_default_code',
inverse='_set_default_code', store=True)
pricelist_item_count = fields.Integer("Number of price rules", compute="_compute_item_count")
can_image_1024_be_zoomed = fields.Boolean("Can Image 1024 be zoomed", compute='_compute_can_image_1024_be_zoomed', store=True)
has_configurable_attributes = fields.Boolean("Is a configurable product", compute='_compute_has_configurable_attributes', store=True)
product_tooltip = fields.Char(compute='_compute_product_tooltip')
priority = fields.Selection([
('0', 'Normal'),
('1', 'Favorite'),
], default='0', string="Favorite")
def _compute_item_count(self):
for template in self:
# Pricelist item count counts the rules applicable on current template or on its variants.
template.pricelist_item_count = template.env['product.pricelist.item'].search_count([
'|', ('product_tmpl_id', '=', template.id), ('product_id', 'in', template.product_variant_ids.ids)])
@api.depends('image_1920', 'image_1024')
def _compute_can_image_1024_be_zoomed(self):
for template in self:
template.can_image_1024_be_zoomed = template.image_1920 and tools.is_image_size_above(template.image_1920, template.image_1024)
@api.depends('attribute_line_ids', 'attribute_line_ids.value_ids', 'attribute_line_ids.attribute_id.create_variant')
def _compute_has_configurable_attributes(self):
"""A product is considered configurable if:
- It has dynamic attributes
- It has any attribute line with at least 2 attribute values configured
"""
for product in self:
product.has_configurable_attributes = product.has_dynamic_attributes() or any(len(ptal.value_ids) >= 2 for ptal in product.attribute_line_ids)
@api.depends('product_variant_ids')
def _compute_product_variant_id(self):
for p in self:
p.product_variant_id = p.product_variant_ids[:1].id
@api.depends('company_id')
def _compute_currency_id(self):
main_company = self.env['res.company']._get_main_company()
for template in self:
template.currency_id = template.company_id.sudo().currency_id.id or main_company.currency_id.id
@api.depends_context('company')
def _compute_cost_currency_id(self):
self.cost_currency_id = self.env.company.currency_id.id
def _compute_template_price(self):
prices = self._compute_template_price_no_inverse()
for template in self:
template.price = prices.get(template.id, 0.0)
def _compute_template_price_no_inverse(self):
"""The _compute_template_price writes the 'list_price' field with an inverse method
This method allows computing the price without writing the 'list_price'
"""
prices = {}
pricelist_id_or_name = self._context.get('pricelist')
if pricelist_id_or_name:
pricelist = None
partner = self.env.context.get('partner')
quantity = self.env.context.get('quantity', 1.0)
# Support context pricelists specified as list, display_name or ID for compatibility
if isinstance(pricelist_id_or_name, list):
pricelist_id_or_name = pricelist_id_or_name[0]
if isinstance(pricelist_id_or_name, str):
pricelist_data = self.env['product.pricelist'].name_search(pricelist_id_or_name, operator='=', limit=1)
if pricelist_data:
pricelist = self.env['product.pricelist'].browse(pricelist_data[0][0])
elif isinstance(pricelist_id_or_name, int):
pricelist = self.env['product.pricelist'].browse(pricelist_id_or_name)
if pricelist:
quantities = [quantity] * len(self)
partners = [partner] * len(self)
prices = pricelist.get_products_price(self, quantities, partners)
return prices
def _set_template_price(self):
if self._context.get('uom'):
for template in self:
value = self.env['uom.uom'].browse(self._context['uom'])._compute_price(template.price, template.uom_id)
template.write({'list_price': value})
else:
self.write({'list_price': self.price})
@api.depends_context('company')
@api.depends('product_variant_ids', 'product_variant_ids.standard_price')
def _compute_standard_price(self):
# Depends on force_company context because standard_price is company_dependent
# on the product_product
unique_variants = self.filtered(lambda template: len(template.product_variant_ids) == 1)
for template in unique_variants:
template.standard_price = template.product_variant_ids.standard_price
for template in (self - unique_variants):
template.standard_price = 0.0
def _set_standard_price(self):
for template in self:
if len(template.product_variant_ids) == 1:
template.product_variant_ids.standard_price = template.standard_price
def _search_standard_price(self, operator, value):
products = self.env['product.product'].search([('standard_price', operator, value)], limit=None)
return [('id', 'in', products.mapped('product_tmpl_id').ids)]
@api.depends('product_variant_ids', 'product_variant_ids.volume')
def _compute_volume(self):
unique_variants = self.filtered(lambda template: len(template.product_variant_ids) == 1)
for template in unique_variants:
template.volume = template.product_variant_ids.volume
for template in (self - unique_variants):
template.volume = 0.0
def _set_volume(self):
for template in self:
if len(template.product_variant_ids) == 1:
template.product_variant_ids.volume = template.volume
@api.depends('product_variant_ids', 'product_variant_ids.weight')
def _compute_weight(self):
unique_variants = self.filtered(lambda template: len(template.product_variant_ids) == 1)
for template in unique_variants:
template.weight = template.product_variant_ids.weight
for template in (self - unique_variants):
template.weight = 0.0
def _compute_is_product_variant(self):
self.is_product_variant = False
@api.depends('product_variant_ids.barcode')
def _compute_barcode(self):
self.barcode = False
for template in self:
# TODO master: update product_variant_count depends and use it instead
variant_count = len(template.product_variant_ids)
if variant_count == 1:
template.barcode = template.product_variant_ids.barcode
elif variant_count == 0:
archived_variants = template.with_context(active_test=False).product_variant_ids
if len(archived_variants) == 1:
template.barcode = archived_variants.barcode
def _search_barcode(self, operator, value):
query = self.with_context(active_test=False)._search([('product_variant_ids.barcode', operator, value)])
return [('id', 'in', query)]
def _set_barcode(self):
variant_count = len(self.product_variant_ids)
if variant_count == 1:
self.product_variant_ids.barcode = self.barcode
elif variant_count == 0:
archived_variants = self.with_context(active_test=False).product_variant_ids
if len(archived_variants) == 1:
archived_variants.barcode = self.barcode
@api.model
def _get_weight_uom_id_from_ir_config_parameter(self):
""" Get the unit of measure to interpret the `weight` field. By default, we considerer
that weights are expressed in kilograms. Users can configure to express them in pounds
by adding an ir.config_parameter record with "product.product_weight_in_lbs" as key
and "1" as value.
"""
product_weight_in_lbs_param = self.env['ir.config_parameter'].sudo().get_param('product.weight_in_lbs')
if product_weight_in_lbs_param == '1':
return self.env.ref('uom.product_uom_lb')
else:
return self.env.ref('uom.product_uom_kgm')
@api.model
def _get_length_uom_id_from_ir_config_parameter(self):
""" Get the unit of measure to interpret the `length`, 'width', 'height' field.
By default, we considerer that length are expressed in millimeters. Users can configure
to express them in feet by adding an ir.config_parameter record with "product.volume_in_cubic_feet"
as key and "1" as value.
"""
product_length_in_feet_param = self.env['ir.config_parameter'].sudo().get_param('product.volume_in_cubic_feet')
if product_length_in_feet_param == '1':
return self.env.ref('uom.product_uom_foot')
else:
return self.env.ref('uom.product_uom_millimeter')
@api.model
def _get_volume_uom_id_from_ir_config_parameter(self):
""" Get the unit of measure to interpret the `volume` field. By default, we consider
that volumes are expressed in cubic meters. Users can configure to express them in cubic feet
by adding an ir.config_parameter record with "product.volume_in_cubic_feet" as key
and "1" as value.
"""
product_length_in_feet_param = self.env['ir.config_parameter'].sudo().get_param('product.volume_in_cubic_feet')
if product_length_in_feet_param == '1':
return self.env.ref('uom.product_uom_cubic_foot')
else:
return self.env.ref('uom.product_uom_cubic_meter')
@api.model
def _get_weight_uom_name_from_ir_config_parameter(self):
return self._get_weight_uom_id_from_ir_config_parameter().display_name
@api.model
def _get_length_uom_name_from_ir_config_parameter(self):
return self._get_length_uom_id_from_ir_config_parameter().display_name
@api.model
def _get_volume_uom_name_from_ir_config_parameter(self):
return self._get_volume_uom_id_from_ir_config_parameter().display_name
def _compute_weight_uom_name(self):
self.weight_uom_name = self._get_weight_uom_name_from_ir_config_parameter()
def _compute_volume_uom_name(self):
self.volume_uom_name = self._get_volume_uom_name_from_ir_config_parameter()
def _set_weight(self):
for template in self:
if len(template.product_variant_ids) == 1:
template.product_variant_ids.weight = template.weight
@api.depends('product_variant_ids.product_tmpl_id')
def _compute_product_variant_count(self):
for template in self:
template.product_variant_count = len(template.product_variant_ids)
@api.onchange('default_code')
def _onchange_default_code(self):
if not self.default_code:
return
domain = [('default_code', '=', self.default_code)]
if self.id.origin:
domain.append(('id', '!=', self.id.origin))
if self.env['product.template'].search(domain, limit=1):
return {'warning': {
'title': _("Note:"),
'message': _("The Internal Reference '%s' already exists.", self.default_code),
}}
@api.depends('product_variant_ids', 'product_variant_ids.default_code')
def _compute_default_code(self):
unique_variants = self.filtered(lambda template: len(template.product_variant_ids) == 1)
for template in unique_variants:
template.default_code = template.product_variant_ids.default_code
for template in (self - unique_variants):
template.default_code = False
def _set_default_code(self):
for template in self:
if len(template.product_variant_ids) == 1:
template.product_variant_ids.default_code = template.default_code
@api.depends('product_variant_ids', 'product_variant_ids.packaging_ids')
def _compute_packaging_ids(self):
for p in self:
if len(p.product_variant_ids) == 1:
p.packaging_ids = p.product_variant_ids.packaging_ids
else:
p.packaging_ids = False
def _set_packaging_ids(self):
for p in self:
if len(p.product_variant_ids) == 1:
p.product_variant_ids.packaging_ids = p.packaging_ids
@api.depends('type')
def _compute_product_tooltip(self):
for record in self:
if record.type == 'consu':
record.product_tooltip = _(
"Consumables are physical products for which you don't manage the inventory "
"level: they are always available."
)
else:
record.product_tooltip = ""
def _detailed_type_mapping(self):
return {}
@api.depends('detailed_type')
def _compute_type(self):
type_mapping = self._detailed_type_mapping()
for record in self:
record.type = type_mapping.get(record.detailed_type, record.detailed_type)
@api.constrains('type', 'detailed_type')
def _constrains_detailed_type(self):
type_mapping = self._detailed_type_mapping()
for record in self:
if record.type != type_mapping.get(record.detailed_type, record.detailed_type):
raise ValidationError(_("The Type of this product doesn't match the Detailed Type"))
@api.constrains('uom_id', 'uom_po_id')
def _check_uom(self):
if any(template.uom_id and template.uom_po_id and template.uom_id.category_id != template.uom_po_id.category_id for template in self):
raise ValidationError(_('The default Unit of Measure and the purchase Unit of Measure must be in the same category.'))
@api.onchange('uom_id')
def _onchange_uom_id(self):
if self.uom_id:
self.uom_po_id = self.uom_id.id
@api.onchange('uom_po_id')
def _onchange_uom(self):
if self.uom_id and self.uom_po_id and self.uom_id.category_id != self.uom_po_id.category_id:
self.uom_po_id = self.uom_id
@api.onchange('type')
def _onchange_type(self):
# Do nothing but needed for inheritance
return {}
def _sanitize_vals(self, vals):
"""Sanitize vales for writing/creating product templates and variants.
Values need to be sanitized to keep values synchronized, and to be able to preprocess the
vals in extensions of create/write.
:param vals: create/write values dictionary
"""
if 'type' in vals and 'detailed_type' not in vals:
if vals['type'] not in self.mapped('type'):
vals['detailed_type'] = vals['type']
if 'detailed_type' in vals and 'type' not in vals:
type_mapping = self._detailed_type_mapping()
vals['type'] = type_mapping.get(vals['detailed_type'], vals['detailed_type'])
@api.model_create_multi
def create(self, vals_list):
''' Store the initial standard price in order to be able to retrieve the cost of a product template for a given date'''
for vals in vals_list:
self._sanitize_vals(vals)
templates = super(ProductTemplate, self).create(vals_list)
if "create_product_product" not in self._context:
templates._create_variant_ids()
# This is needed to set given values to first variant after creation
for template, vals in zip(templates, vals_list):
related_vals = {}
if vals.get('barcode'):
related_vals['barcode'] = vals['barcode']
if vals.get('default_code'):
related_vals['default_code'] = vals['default_code']
if vals.get('standard_price'):
related_vals['standard_price'] = vals['standard_price']
if vals.get('volume'):
related_vals['volume'] = vals['volume']
if vals.get('weight'):
related_vals['weight'] = vals['weight']
# Please do forward port
if vals.get('packaging_ids'):
related_vals['packaging_ids'] = vals['packaging_ids']
if related_vals:
template.write(related_vals)
return templates
def write(self, vals):
self._sanitize_vals(vals)
if 'uom_id' in vals or 'uom_po_id' in vals:
uom_id = self.env['uom.uom'].browse(vals.get('uom_id')) or self.uom_id
uom_po_id = self.env['uom.uom'].browse(vals.get('uom_po_id')) or self.uom_po_id
if uom_id and uom_po_id and uom_id.category_id != uom_po_id.category_id:
vals['uom_po_id'] = uom_id.id
res = super(ProductTemplate, self).write(vals)
if 'attribute_line_ids' in vals or (vals.get('active') and len(self.product_variant_ids) == 0):
self._create_variant_ids()
if 'active' in vals and not vals.get('active'):
self.with_context(active_test=False).mapped('product_variant_ids').write({'active': vals.get('active')})
if 'image_1920' in vals:
self.env['product.product'].invalidate_cache(fnames=[
'image_1920',
'image_1024',
'image_512',
'image_256',
'image_128',
'can_image_1024_be_zoomed',
])
# Touch all products that will fall back on the template field
# This is done because __last_update is used to compute the 'unique' SHA in image URLs
# for making sure that images are not retrieved from the browser cache after a change
# Performance discussion outcome:
# Actually touch all variants to avoid using filtered on the image_variant_1920 field
self.product_variant_ids.write({})
return res
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
# TDE FIXME: should probably be copy_data
self.ensure_one()
if default is None:
default = {}
if 'name' not in default:
default['name'] = _("%s (copy)", self.name)
return super(ProductTemplate, self).copy(default=default)
def name_get(self):
# Prefetch the fields used by the `name_get`, so `browse` doesn't fetch other fields
self.browse(self.ids).read(['name', 'default_code'])
return [(template.id, '%s%s' % (template.default_code and '[%s] ' % template.default_code or '', template.name))
for template in self]
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
# Only use the product.product heuristics if there is a search term and the domain
# does not specify a match on `product.template` IDs.
if not name or any(term[0] == 'id' for term in (args or [])):
return super(ProductTemplate, self)._name_search(name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
Product = self.env['product.product']
templates = self.browse([])
while True:
domain = templates and [('product_tmpl_id', 'not in', templates.ids)] or []
args = args if args is not None else []
# Product._name_search has default value limit=100
# So, we either use that value or override it to None to fetch all products at once
kwargs = {} if limit else {'limit': None}
products_ids = Product._name_search(name, args+domain, operator=operator, name_get_uid=name_get_uid, **kwargs)
products = Product.browse(products_ids)
new_templates = products.mapped('product_tmpl_id')
if new_templates & templates:
"""Product._name_search can bypass the domain we passed (search on supplier info).
If this happens, an infinite loop will occur."""
break
templates |= new_templates
if (not products) or (limit and (len(templates) > limit)):
break
searched_ids = set(templates.ids)
# some product.templates do not have product.products yet (dynamic variants configuration),
# we need to add the base _name_search to the results
# FIXME awa: this is really not performant at all but after discussing with the team
# we don't see another way to do it
tmpl_without_variant_ids = []
if not limit or len(searched_ids) < limit:
tmpl_without_variant_ids = self.env['product.template'].search(
[('id', 'not in', self.env['product.template']._search([('product_variant_ids.active', '=', True)]))]
)
if tmpl_without_variant_ids:
domain = expression.AND([args or [], [('id', 'in', tmpl_without_variant_ids.ids)]])
searched_ids |= set(super(ProductTemplate, self)._name_search(
name,
args=domain,
operator=operator,
limit=limit,
name_get_uid=name_get_uid))
# re-apply product.template order + name_get
return super(ProductTemplate, self)._name_search(
'', args=[('id', 'in', list(searched_ids))],
operator='ilike', limit=limit, name_get_uid=name_get_uid)
def action_open_label_layout(self):
action = self.env['ir.actions.act_window']._for_xml_id('product.action_open_label_layout')
action['context'] = {'default_product_tmpl_ids': self.ids}
return action
def open_pricelist_rules(self):
self.ensure_one()
domain = ['|',
('product_tmpl_id', '=', self.id),
('product_id', 'in', self.product_variant_ids.ids)]
return {
'name': _('Price Rules'),
'view_mode': 'tree,form',
'views': [(self.env.ref('product.product_pricelist_item_tree_view_from_product').id, 'tree'), (False, 'form')],
'res_model': 'product.pricelist.item',
'type': 'ir.actions.act_window',
'target': 'current',
'domain': domain,
'context': {
'default_product_tmpl_id': self.id,
'default_applied_on': '1_product',
'product_without_variants': self.product_variant_count == 1,
},
}
def price_compute(self, price_type, uom=False, currency=False, company=None):
# TDE FIXME: delegate to template or not ? fields are reencoded here ...
# compatibility about context keys used a bit everywhere in the code
if not uom and self._context.get('uom'):
uom = self.env['uom.uom'].browse(self._context['uom'])
if not currency and self._context.get('currency'):
currency = self.env['res.currency'].browse(self._context['currency'])
templates = self
if price_type == 'standard_price':
# standard_price field can only be seen by users in base.group_user
# Thus, in order to compute the sale price from the cost for users not in this group
# We fetch the standard price as the superuser
templates = self.with_company(company).sudo()
if not company:
company = self.env.company
date = self.env.context.get('date') or fields.Date.today()
prices = dict.fromkeys(self.ids, 0.0)
for template in templates:
prices[template.id] = template[price_type] or 0.0
# yes, there can be attribute values for product template if it's not a variant YET
# (see field product.attribute create_variant)
if price_type == 'list_price' and self._context.get('current_attributes_price_extra'):
# we have a list of price_extra that comes from the attribute values, we need to sum all that
prices[template.id] += sum(self._context.get('current_attributes_price_extra'))
if uom:
prices[template.id] = template.uom_id._compute_price(prices[template.id], uom)
# Convert from current user company currency to asked one
# This is right cause a field cannot be in more than one currency
if currency:
prices[template.id] = template.currency_id._convert(prices[template.id], currency, company, date)
return prices
def _create_variant_ids(self):
self.flush()
Product = self.env["product.product"]
variants_to_create = []
variants_to_activate = Product
variants_to_unlink = Product
for tmpl_id in self:
lines_without_no_variants = tmpl_id.valid_product_template_attribute_line_ids._without_no_variant_attributes()
all_variants = tmpl_id.with_context(active_test=False).product_variant_ids.sorted(lambda p: (p.active, -p.id))
current_variants_to_create = []
current_variants_to_activate = Product
# adding an attribute with only one value should not recreate product
# write this attribute on every product to make sure we don't lose them
single_value_lines = lines_without_no_variants.filtered(lambda ptal: len(ptal.product_template_value_ids._only_active()) == 1)
if single_value_lines:
for variant in all_variants:
combination = variant.product_template_attribute_value_ids | single_value_lines.product_template_value_ids._only_active()
# Do not add single value if the resulting combination would
# be invalid anyway.
if (
len(combination) == len(lines_without_no_variants) and
combination.attribute_line_id == lines_without_no_variants
):
variant.product_template_attribute_value_ids = combination
# Set containing existing `product.template.attribute.value` combination
existing_variants = {
variant.product_template_attribute_value_ids: variant for variant in all_variants
}
# Determine which product variants need to be created based on the attribute
# configuration. If any attribute is set to generate variants dynamically, skip the
# process.
# Technical note: if there is no attribute, a variant is still created because
# 'not any([])' and 'set([]) not in set([])' are True.
if not tmpl_id.has_dynamic_attributes():
# Iterator containing all possible `product.template.attribute.value` combination
# The iterator is used to avoid MemoryError in case of a huge number of combination.
all_combinations = itertools.product(*[
ptal.product_template_value_ids._only_active() for ptal in lines_without_no_variants
])
# For each possible variant, create if it doesn't exist yet.
for combination_tuple in all_combinations:
combination = self.env['product.template.attribute.value'].concat(*combination_tuple)
is_combination_possible = tmpl_id._is_combination_possible_by_config(combination, ignore_no_variant=True)
if not is_combination_possible:
continue
if combination in existing_variants:
current_variants_to_activate += existing_variants[combination]
else:
current_variants_to_create.append(tmpl_id._prepare_variant_values(combination))
if len(current_variants_to_create) > 1000:
raise UserError(_(
'The number of variants to generate is too high. '
'You should either not generate variants for each combination or generate them on demand from the sales order. '
'To do so, open the form view of attributes and change the mode of *Create Variants*.'))
variants_to_create += current_variants_to_create
variants_to_activate += current_variants_to_activate
else:
for variant in existing_variants.values():
is_combination_possible = self._is_combination_possible_by_config(
combination=variant.product_template_attribute_value_ids,
ignore_no_variant=True,
)
if is_combination_possible:
current_variants_to_activate += variant
variants_to_activate += current_variants_to_activate
variants_to_unlink += all_variants - current_variants_to_activate
if variants_to_activate:
variants_to_activate.write({'active': True})
if variants_to_create:
Product.create(variants_to_create)
if variants_to_unlink:
variants_to_unlink._unlink_or_archive()
# prevent change if exclusion deleted template by deleting last variant
if self.exists() != self:
raise UserError(_("This configuration of product attributes, values, and exclusions would lead to no possible variant. Please archive or delete your product directly if intended."))
# prefetched o2m have to be reloaded (because of active_test)
# (eg. product.template: product_variant_ids)
# We can't rely on existing invalidate_cache because of the savepoint
# in _unlink_or_archive.
self.flush()
self.invalidate_cache()
return True
def _prepare_variant_values(self, combination):
self.ensure_one()
return {
'product_tmpl_id': self.id,
'product_template_attribute_value_ids': [(6, 0, combination.ids)],
'active': self.active
}
def has_dynamic_attributes(self):
"""Return whether this `product.template` has at least one dynamic
attribute.
:return: True if at least one dynamic attribute, False otherwise
:rtype: bool
"""
self.ensure_one()
return any(a.create_variant == 'dynamic' for a in self.valid_product_template_attribute_line_ids.attribute_id)
@api.depends('attribute_line_ids.value_ids')
def _compute_valid_product_template_attribute_line_ids(self):
"""A product template attribute line is considered valid if it has at
least one possible value.
Those with only one value are considered valid, even though they should
not appear on the configurator itself (unless they have an is_custom
value to input), indeed single value attributes can be used to filter
products among others based on that attribute/value.
"""
for record in self:
record.valid_product_template_attribute_line_ids = record.attribute_line_ids.filtered(lambda ptal: ptal.value_ids)
def _get_possible_variants(self, parent_combination=None):
"""Return the existing variants that are possible.
For dynamic attributes, it will only return the variants that have been
created already.
If there are a lot of variants, this method might be slow. Even if there
aren't too many variants, for performance reasons, do not call this
method in a loop over the product templates.
Therefore this method has a very restricted reasonable use case and you
should strongly consider doing things differently if you consider using
this method.
:param parent_combination: combination from which `self` is an
optional or accessory product.
:type parent_combination: recordset `product.template.attribute.value`
:return: the existing variants that are possible.
:rtype: recordset of `product.product`
"""
self.ensure_one()
return self.product_variant_ids.filtered(lambda p: p._is_variant_possible(parent_combination))
def _get_attribute_exclusions(self, parent_combination=None, parent_name=None):
"""Return the list of attribute exclusions of a product.
:param parent_combination: the combination from which
`self` is an optional or accessory product. Indeed exclusions
rules on one product can concern another product.
:type parent_combination: recordset `product.template.attribute.value`
:param parent_name: the name of the parent product combination.
:type parent_name: str
:return: dict of exclusions
- exclusions: from this product itself
- parent_combination: ids of the given parent_combination
- parent_exclusions: from the parent_combination
- parent_product_name: the name of the parent product if any, used in the interface
to explain why some combinations are not available.
(e.g: Not available with Customizable Desk (Legs: Steel))
- mapped_attribute_names: the name of every attribute values based on their id,
used to explain in the interface why that combination is not available
(e.g: Not available with Color: Black)
"""
self.ensure_one()
parent_combination = parent_combination or self.env['product.template.attribute.value']
return {
'exclusions': self._complete_inverse_exclusions(self._get_own_attribute_exclusions()),
'parent_exclusions': self._get_parent_attribute_exclusions(parent_combination),
'parent_combination': parent_combination.ids,
'parent_product_name': parent_name,
'mapped_attribute_names': self._get_mapped_attribute_names(parent_combination),
}
@api.model
def _complete_inverse_exclusions(self, exclusions):
"""Will complete the dictionnary of exclusions with their respective inverse
e.g: Black excludes XL and L
-> XL excludes Black
-> L excludes Black"""
result = dict(exclusions)
for key, value in exclusions.items():
for exclusion in value:
if exclusion in result and key not in result[exclusion]:
result[exclusion].append(key)
else:
result[exclusion] = [key]
return result
def _get_own_attribute_exclusions(self):
"""Get exclusions coming from the current template.
Dictionnary, each product template attribute value is a key, and for each of them
the value is an array with the other ptav that they exclude (empty if no exclusion).
"""
self.ensure_one()
product_template_attribute_values = self.valid_product_template_attribute_line_ids.product_template_value_ids
return {
ptav.id: [
value_id
for filter_line in ptav.exclude_for.filtered(
lambda filter_line: filter_line.product_tmpl_id == self
) for value_id in filter_line.value_ids.ids
]
for ptav in product_template_attribute_values
}
def _get_parent_attribute_exclusions(self, parent_combination):
"""Get exclusions coming from the parent combination.
Dictionnary, each parent's ptav is a key, and for each of them the value is
an array with the other ptav that are excluded because of the parent.
"""
self.ensure_one()
if not parent_combination:
return {}
result = {}
for product_attribute_value in parent_combination:
for filter_line in product_attribute_value.exclude_for.filtered(
lambda filter_line: filter_line.product_tmpl_id == self
):
# Some exclusions don't have attribute value. This means that the template is not
# compatible with the parent combination. If such an exclusion is found, it means that all
# attribute values are excluded.
if filter_line.value_ids:
result[product_attribute_value.id] = filter_line.value_ids.ids
else:
result[product_attribute_value.id] = filter_line.product_tmpl_id.mapped('attribute_line_ids.product_template_value_ids').ids
return result
def _get_mapped_attribute_names(self, parent_combination=None):
""" The name of every attribute values based on their id,
used to explain in the interface why that combination is not available
(e.g: Not available with Color: Black).
It contains both attribute value names from this product and from
the parent combination if provided.
"""
self.ensure_one()
all_product_attribute_values = self.valid_product_template_attribute_line_ids.product_template_value_ids
if parent_combination:
all_product_attribute_values |= parent_combination
return {
attribute_value.id: attribute_value.display_name
for attribute_value in all_product_attribute_values
}
def _is_combination_possible_by_config(self, combination, ignore_no_variant=False):
"""Return whether the given combination is possible according to the config of attributes on the template
:param combination: the combination to check for possibility
:type combination: recordset `product.template.attribute.value`
:param ignore_no_variant: whether no_variant attributes should be ignored
:type ignore_no_variant: bool
:return: wether the given combination is possible according to the config of attributes on the template
:rtype: bool
"""
self.ensure_one()
attribute_lines = self.valid_product_template_attribute_line_ids
if ignore_no_variant:
attribute_lines = attribute_lines._without_no_variant_attributes()
if len(combination) != len(attribute_lines):
# number of attribute values passed is different than the
# configuration of attributes on the template
return False
if attribute_lines != combination.attribute_line_id:
# combination has different attributes than the ones configured on the template
return False
if not (attribute_lines.product_template_value_ids._only_active() >= combination):
# combination has different values than the ones configured on the template
return False
exclusions = self._get_own_attribute_exclusions()
if exclusions:
# exclude if the current value is in an exclusion,
# and the value excluding it is also in the combination
for ptav in combination:
for exclusion in exclusions.get(ptav.id):
if exclusion in combination.ids:
return False
return True
def _is_combination_possible(self, combination, parent_combination=None, ignore_no_variant=False):
"""
The combination is possible if it is not excluded by any rule
coming from the current template, not excluded by any rule from the
parent_combination (if given), and there should not be any archived
variant with the exact same combination.
If the template does not have any dynamic attribute, the combination
is also not possible if the matching variant has been deleted.
Moreover the attributes of the combination must excatly match the
attributes allowed on the template.
:param combination: the combination to check for possibility
:type combination: recordset `product.template.attribute.value`
:param ignore_no_variant: whether no_variant attributes should be ignored
:type ignore_no_variant: bool
:param parent_combination: combination from which `self` is an
optional or accessory product.
:type parent_combination: recordset `product.template.attribute.value`
:return: whether the combination is possible
:rtype: bool
"""
self.ensure_one()
if not self._is_combination_possible_by_config(combination, ignore_no_variant):
return False
variant = self._get_variant_for_combination(combination)
if self.has_dynamic_attributes():
if variant and not variant.active:
# dynamic and the variant has been archived
return False
else:
if not variant or not variant.active:
# not dynamic, the variant has been archived or deleted
return False
parent_exclusions = self._get_parent_attribute_exclusions(parent_combination)
if parent_exclusions:
# parent_exclusion are mapped by ptav but here we don't need to know
# where the exclusion comes from so we loop directly on the dict values
for exclusions_values in parent_exclusions.values():
for exclusion in exclusions_values:
if exclusion in combination.ids:
return False
return True
def _get_variant_for_combination(self, combination):
"""Get the variant matching the combination.
All of the values in combination must be present in the variant, and the
variant should not have more attributes. Ignore the attributes that are
not supposed to create variants.
:param combination: recordset of `product.template.attribute.value`
:return: the variant if found, else empty
:rtype: recordset `product.product`
"""
self.ensure_one()
filtered_combination = combination._without_no_variant_attributes()
return self.env['product.product'].browse(self._get_variant_id_for_combination(filtered_combination))
def _create_product_variant(self, combination, log_warning=False):
""" Create if necessary and possible and return the product variant
matching the given combination for this template.
It is possible to create only if the template has dynamic attributes
and the combination itself is possible.
If we are in this case and the variant already exists but it is
archived, it is activated instead of being created again.
:param combination: the combination for which to get or create variant.
The combination must contain all necessary attributes, including
those of type no_variant. Indeed even though those attributes won't
be included in the variant if newly created, they are needed when
checking if the combination is possible.
:type combination: recordset of `product.template.attribute.value`
:param log_warning: whether a warning should be logged on fail
:type log_warning: bool
:return: the product variant matching the combination or none
:rtype: recordset of `product.product`
"""
self.ensure_one()
Product = self.env['product.product']
product_variant = self._get_variant_for_combination(combination)
if product_variant:
if not product_variant.active and self.has_dynamic_attributes() and self._is_combination_possible(combination):
product_variant.active = True
return product_variant
if not self.has_dynamic_attributes():
if log_warning:
_logger.warning('The user #%s tried to create a variant for the non-dynamic product %s.' % (self.env.user.id, self.id))
return Product
if not self._is_combination_possible(combination):
if log_warning:
_logger.warning('The user #%s tried to create an invalid variant for the product %s.' % (self.env.user.id, self.id))
return Product
return Product.sudo().create({
'product_tmpl_id': self.id,
'product_template_attribute_value_ids': [(6, 0, combination._without_no_variant_attributes().ids)]
})
def _create_first_product_variant(self, log_warning=False):
"""Create if necessary and possible and return the first product
variant for this template.
:param log_warning: whether a warning should be logged on fail
:type log_warning: bool
:return: the first product variant or none
:rtype: recordset of `product.product`
"""
return self._create_product_variant(self._get_first_possible_combination(), log_warning)
@tools.ormcache('self.id', 'frozenset(filtered_combination.ids)')
def _get_variant_id_for_combination(self, filtered_combination):
"""See `_get_variant_for_combination`. This method returns an ID
so it can be cached.
Use sudo because the same result should be cached for all users.
"""
self.ensure_one()
domain = [('product_tmpl_id', '=', self.id)]
combination_indices_ids = filtered_combination._ids2str()
if combination_indices_ids:
domain = expression.AND([domain, [('combination_indices', '=', combination_indices_ids)]])
else:
domain = expression.AND([domain, [('combination_indices', 'in', ['', False])]])
return self.env['product.product'].sudo().with_context(active_test=False).search(domain, order='active DESC', limit=1).id
@tools.ormcache('self.id')
def _get_first_possible_variant_id(self):
"""See `_create_first_product_variant`. This method returns an ID
so it can be cached."""
self.ensure_one()
return self._create_first_product_variant().id
def _get_first_possible_combination(self, parent_combination=None, necessary_values=None):
"""See `_get_possible_combinations` (one iteration).
This method return the same result (empty recordset) if no
combination is possible at all which would be considered a negative
result, or if there are no attribute lines on the template in which
case the "empty combination" is actually a possible combination.
Therefore the result of this method when empty should be tested
with `_is_combination_possible` if it's important to know if the
resulting empty combination is actually possible or not.
"""
return next(self._get_possible_combinations(parent_combination, necessary_values), self.env['product.template.attribute.value'])
def _cartesian_product(self, product_template_attribute_values_per_line, parent_combination):
"""
Generate all possible combination for attributes values (aka cartesian product).
It is equivalent to itertools.product except it skips invalid partial combinations before they are complete.
Imagine the cartesian product of 'A', 'CD' and range(1_000_000) and let's say that 'A' and 'C' are incompatible.
If you use itertools.product or any normal cartesian product, you'll need to filter out of the final result
the 1_000_000 combinations that start with 'A' and 'C' . Instead, This implementation will test if 'A' and 'C' are
compatible before even considering range(1_000_000), skip it and and continue with combinations that start
with 'A' and 'D'.
It's necessary for performance reason because filtering out invalid combinations from standard Cartesian product
can be extremely slow
:param product_template_attribute_values_per_line: the values we want all the possibles combinations of.
One list of values by attribute line
:return: a generator of product template attribute value
"""
if not product_template_attribute_values_per_line:
return
all_exclusions = {self.env['product.template.attribute.value'].browse(k):
self.env['product.template.attribute.value'].browse(v) for k, v in
self._get_own_attribute_exclusions().items()}
# The following dict uses product template attribute values as keys
# 0 means the value is acceptable, greater than 0 means it's rejected, it cannot be negative
# Bear in mind that several values can reject the same value and the latter can only be included in the
# considered combination if no value rejects it.
# This dictionary counts how many times each value is rejected.
# Each time a value is included in the considered combination, the values it rejects are incremented
# When a value is discarded from the considered combination, the values it rejects are decremented
current_exclusions = defaultdict(int)
for exclusion in self._get_parent_attribute_exclusions(parent_combination):
current_exclusions[self.env['product.template.attribute.value'].browse(exclusion)] += 1
partial_combination = self.env['product.template.attribute.value']
# The following list reflects product_template_attribute_values_per_line
# For each line, instead of a list of values, it contains the index of the selected value
# -1 means no value has been picked for the line in the current (partial) combination
value_index_per_line = [-1] * len(product_template_attribute_values_per_line)
# determines which line line we're working on
line_index = 0
while True:
current_line_values = product_template_attribute_values_per_line[line_index]
current_ptav_index = value_index_per_line[line_index]
current_ptav = current_line_values[current_ptav_index]
# removing exclusions from current_ptav as we're removing it from partial_combination
if current_ptav_index >= 0:
for ptav_to_include_back in all_exclusions[current_ptav]:
current_exclusions[ptav_to_include_back] -= 1
partial_combination -= current_ptav
if current_ptav_index < len(current_line_values) - 1:
# go to next value of current line
value_index_per_line[line_index] += 1
current_line_values = product_template_attribute_values_per_line[line_index]
current_ptav_index = value_index_per_line[line_index]
current_ptav = current_line_values[current_ptav_index]
elif line_index != 0:
# reset current line, and then go to previous line
value_index_per_line[line_index] = - 1
line_index -= 1
continue
else:
# we're done if we must reset first line
break
# adding exclusions from current_ptav as we're incorporating it in partial_combination
for ptav_to_exclude in all_exclusions[current_ptav]:
current_exclusions[ptav_to_exclude] += 1
partial_combination += current_ptav
# test if included values excludes current value or if current value exclude included values
if current_exclusions[current_ptav] or \
any(intersection in partial_combination for intersection in all_exclusions[current_ptav]):
continue
if line_index == len(product_template_attribute_values_per_line) - 1:
# submit combination if we're on the last line
yield partial_combination
else:
# else we go to the next line
line_index += 1
def _get_possible_combinations(self, parent_combination=None, necessary_values=None):
"""Generator returning combinations that are possible, following the
sequence of attributes and values.
See `_is_combination_possible` for what is a possible combination.
When encountering an impossible combination, try to change the value
of attributes by starting with the further regarding their sequences.
Ignore attributes that have no values.
:param parent_combination: combination from which `self` is an
optional or accessory product.
:type parent_combination: recordset `product.template.attribute.value`
:param necessary_values: values that must be in the returned combination
:type necessary_values: recordset of `product.template.attribute.value`
:return: the possible combinations
:rtype: generator of recordset of `product.template.attribute.value`
"""
self.ensure_one()
if not self.active:
return _("The product template is archived so no combination is possible.")
necessary_values = necessary_values or self.env['product.template.attribute.value']
necessary_attribute_lines = necessary_values.mapped('attribute_line_id')
attribute_lines = self.valid_product_template_attribute_line_ids.filtered(lambda ptal: ptal not in necessary_attribute_lines)
if not attribute_lines and self._is_combination_possible(necessary_values, parent_combination):
yield necessary_values
product_template_attribute_values_per_line = [
ptal.product_template_value_ids._only_active()
for ptal in attribute_lines
]
for partial_combination in self._cartesian_product(product_template_attribute_values_per_line, parent_combination):
combination = partial_combination + necessary_values
if self._is_combination_possible(combination, parent_combination):
yield combination
return _("There are no remaining possible combination.")
def _get_closest_possible_combination(self, combination):
"""See `_get_closest_possible_combinations` (one iteration).
This method return the same result (empty recordset) if no
combination is possible at all which would be considered a negative
result, or if there are no attribute lines on the template in which
case the "empty combination" is actually a possible combination.
Therefore the result of this method when empty should be tested
with `_is_combination_possible` if it's important to know if the
resulting empty combination is actually possible or not.
"""
return next(self._get_closest_possible_combinations(combination), self.env['product.template.attribute.value'])
def _get_closest_possible_combinations(self, combination):
"""Generator returning the possible combinations that are the closest to
the given combination.
If the given combination is incomplete, try to complete it.
If the given combination is invalid, try to remove values from it before
completing it.
:param combination: the values to include if they are possible
:type combination: recordset `product.template.attribute.value`
:return: the possible combinations that are including as much
elements as possible from the given combination.
:rtype: generator of recordset of product.template.attribute.value
"""
while True:
res = self._get_possible_combinations(necessary_values=combination)
try:
# If there is at least one result for the given combination
# we consider that combination set, and we yield all the
# possible combinations for it.
yield(next(res))
for cur in res:
yield(cur)
return _("There are no remaining closest combination.")
except StopIteration:
# There are no results for the given combination, we try to
# progressively remove values from it.
if not combination:
return _("There are no possible combination.")
combination = combination[:-1]
def _get_current_company(self, **kwargs):
"""Get the most appropriate company for this product.
If the company is set on the product, directly return it. Otherwise,
fallback to a contextual company.
:param kwargs: kwargs forwarded to the fallback method.
:return: the most appropriate company for this product
:rtype: recordset of one `res.company`
"""
self.ensure_one()
return self.company_id or self._get_current_company_fallback(**kwargs)
def _get_current_company_fallback(self, **kwargs):
"""Fallback to get the most appropriate company for this product.
This should only be called from `_get_current_company` but is defined
separately to allow override.
The final fallback will be the current user's company.
:return: the fallback company for this product
:rtype: recordset of one `res.company`
"""
self.ensure_one()
return self.env.company
def _get_placeholder_filename(self, field):
image_fields = ['image_%s' % size for size in [1920, 1024, 512, 256, 128]]
if field in image_fields:
return 'product/static/img/placeholder.png'
return super()._get_placeholder_filename(field)
def get_single_product_variant(self):
""" Method used by the product configurator to check if the product is configurable or not.
We need to open the product configurator if the product:
- is configurable (see has_configurable_attributes)
- has optional products (method is extended in sale to return optional products info)
"""
self.ensure_one()
if self.product_variant_count == 1 and not self.has_configurable_attributes:
return {
'product_id': self.product_variant_id.id,
}
return {}
@api.model
def get_empty_list_help(self, help):
self = self.with_context(
empty_list_help_document_name=_("product"),
)
return super(ProductTemplate, self).get_empty_list_help(help)
@api.model
def get_import_templates(self):
return [{
'label': _('Import Template for Products'),
'template': '/product/static/xls/product_template.xls'
}]
| 48.326979
| 65,918
|
3,112
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
class ResCompany(models.Model):
_inherit = "res.company"
@api.model_create_multi
def create(self, vals_list):
companies = super(ResCompany, self).create(vals_list)
ProductPricelist = self.env['product.pricelist']
for new_company in companies:
pricelist = ProductPricelist.search([
('currency_id', '=', new_company.currency_id.id),
('company_id', '=', False)
], limit=1)
if not pricelist:
params = {'currency': new_company.currency_id.name}
pricelist = ProductPricelist.create({
'name': _("Default %(currency)s pricelist") % params,
'currency_id': new_company.currency_id.id,
})
self.env['ir.property']._set_default(
'property_product_pricelist',
'res.partner',
pricelist,
new_company,
)
return companies
def write(self, values):
# When we modify the currency of the company, we reflect the change on the list0 pricelist, if
# that pricelist is not used by another company. Otherwise, we create a new pricelist for the
# given currency.
ProductPricelist = self.env['product.pricelist']
currency_id = values.get('currency_id')
main_pricelist = self.env.ref('product.list0', False)
if currency_id and main_pricelist:
nb_companies = self.search_count([])
for company in self:
existing_pricelist = ProductPricelist.search(
[('company_id', 'in', (False, company.id)),
('currency_id', 'in', (currency_id, company.currency_id.id))])
if existing_pricelist and any(currency_id == x.currency_id.id for x in existing_pricelist):
continue
if currency_id == company.currency_id.id:
continue
currency_match = main_pricelist.currency_id == company.currency_id
company_match = (main_pricelist.company_id == company or
(main_pricelist.company_id.id is False and nb_companies == 1))
if currency_match and company_match:
main_pricelist.write({'currency_id': currency_id})
else:
params = {'currency': self.env['res.currency'].browse(currency_id).name}
pricelist = ProductPricelist.create({
'name': _("Default %(currency)s pricelist") % params,
'currency_id': currency_id,
})
self.env['ir.property']._set_default(
'property_product_pricelist',
'res.partner',
pricelist,
company,
)
return super(ResCompany, self).write(values)
| 46.447761
| 3,112
|
492
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class ResCurrency(models.Model):
_inherit = 'res.currency'
def _activate_group_multi_currency(self):
# for Sale/ POS - Multi currency flows require pricelists
super()._activate_group_multi_currency()
group_user = self.env.ref('base.group_user').sudo()
group_user._apply_group(self.env.ref('product.group_product_pricelist'))
| 35.142857
| 492
|
796
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
class UoM(models.Model):
_inherit = 'uom.uom'
@api.onchange('rounding')
def _onchange_rounding(self):
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
if self.rounding < 1.0 / 10.0**precision:
return {'warning': {
'title': _('Warning!'),
'message': _(
"This rounding precision is higher than the Decimal Accuracy"
" (%s digits).\nThis may cause inconsistencies in computations.\n"
"Please set a precision between %s and 1."
) % (precision, 1.0 / 10.0**precision),
}}
| 37.904762
| 796
|
44,338
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import re
from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
from odoo.tools import float_compare, float_round
_logger = logging.getLogger(__name__)
class ProductCategory(models.Model):
_name = "product.category"
_description = "Product Category"
_parent_name = "parent_id"
_parent_store = True
_rec_name = 'complete_name'
_order = 'complete_name'
name = fields.Char('Name', index=True, required=True)
complete_name = fields.Char(
'Complete Name', compute='_compute_complete_name', recursive=True,
store=True)
parent_id = fields.Many2one('product.category', 'Parent Category', index=True, ondelete='cascade')
parent_path = fields.Char(index=True)
child_id = fields.One2many('product.category', 'parent_id', 'Child Categories')
product_count = fields.Integer(
'# Products', compute='_compute_product_count',
help="The number of products under this category (Does not consider the children categories)")
@api.depends('name', 'parent_id.complete_name')
def _compute_complete_name(self):
for category in self:
if category.parent_id:
category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)
else:
category.complete_name = category.name
def _compute_product_count(self):
read_group_res = self.env['product.template'].read_group([('categ_id', 'child_of', self.ids)], ['categ_id'], ['categ_id'])
group_data = dict((data['categ_id'][0], data['categ_id_count']) for data in read_group_res)
for categ in self:
product_count = 0
for sub_categ_id in categ.search([('id', 'child_of', categ.ids)]).ids:
product_count += group_data.get(sub_categ_id, 0)
categ.product_count = product_count
@api.constrains('parent_id')
def _check_category_recursion(self):
if not self._check_recursion():
raise ValidationError(_('You cannot create recursive categories.'))
@api.model
def name_create(self, name):
return self.create({'name': name}).name_get()[0]
def name_get(self):
if not self.env.context.get('hierarchical_naming', True):
return [(record.id, record.name) for record in self]
return super().name_get()
@api.ondelete(at_uninstall=False)
def _unlink_except_default_category(self):
main_category = self.env.ref('product.product_category_all')
if main_category in self:
raise UserError(_("You cannot delete this product category, it is the default generic category."))
expense_category = self.env.ref('product.cat_expense', raise_if_not_found=False)
if expense_category and expense_category in self:
raise UserError(_("You cannot delete the %s product category.", expense_category.name))
class ProductProduct(models.Model):
_name = "product.product"
_description = "Product"
_inherits = {'product.template': 'product_tmpl_id'}
_inherit = ['mail.thread', 'mail.activity.mixin']
_order = 'priority desc, default_code, name, id'
# price: total price, context dependent (partner, pricelist, quantity)
price = fields.Float(
'Price', compute='_compute_product_price',
digits='Product Price', inverse='_set_product_price')
# price_extra: catalog extra value only, sum of variant extra attributes
price_extra = fields.Float(
'Variant Price Extra', compute='_compute_product_price_extra',
digits='Product Price',
help="This is the sum of the extra price of all attributes")
# lst_price: catalog value + extra, context dependent (uom)
lst_price = fields.Float(
'Sales Price', compute='_compute_product_lst_price',
digits='Product Price', inverse='_set_product_lst_price',
help="The sale price is managed from the product template. Click on the 'Configure Variants' button to set the extra attribute prices.")
default_code = fields.Char('Internal Reference', index=True)
code = fields.Char('Reference', compute='_compute_product_code')
partner_ref = fields.Char('Customer Ref', compute='_compute_partner_ref')
active = fields.Boolean(
'Active', default=True,
help="If unchecked, it will allow you to hide the product without removing it.")
product_tmpl_id = fields.Many2one(
'product.template', 'Product Template',
auto_join=True, index=True, ondelete="cascade", required=True)
barcode = fields.Char(
'Barcode', copy=False,
help="International Article Number used for product identification.")
product_template_attribute_value_ids = fields.Many2many('product.template.attribute.value', relation='product_variant_combination', string="Attribute Values", ondelete='restrict')
product_template_variant_value_ids = fields.Many2many('product.template.attribute.value', relation='product_variant_combination',
domain=[('attribute_line_id.value_count', '>', 1)], string="Variant Values", ondelete='restrict')
combination_indices = fields.Char(compute='_compute_combination_indices', store=True, index=True)
is_product_variant = fields.Boolean(compute='_compute_is_product_variant')
standard_price = fields.Float(
'Cost', company_dependent=True,
digits='Product Price',
groups="base.group_user",
help="""In Standard Price & AVCO: value of the product (automatically computed in AVCO).
In FIFO: value of the next unit that will leave the stock (automatically computed).
Used to value the product when the purchase cost is not known (e.g. inventory adjustment).
Used to compute margins on sale orders.""")
volume = fields.Float('Volume', digits='Volume')
weight = fields.Float('Weight', digits='Stock Weight')
pricelist_item_count = fields.Integer("Number of price rules", compute="_compute_variant_item_count")
packaging_ids = fields.One2many(
'product.packaging', 'product_id', 'Product Packages',
help="Gives the different ways to package the same product.")
# all image fields are base64 encoded and PIL-supported
# all image_variant fields are technical and should not be displayed to the user
image_variant_1920 = fields.Image("Variant Image", max_width=1920, max_height=1920)
# resized fields stored (as attachment) for performance
image_variant_1024 = fields.Image("Variant Image 1024", related="image_variant_1920", max_width=1024, max_height=1024, store=True)
image_variant_512 = fields.Image("Variant Image 512", related="image_variant_1920", max_width=512, max_height=512, store=True)
image_variant_256 = fields.Image("Variant Image 256", related="image_variant_1920", max_width=256, max_height=256, store=True)
image_variant_128 = fields.Image("Variant Image 128", related="image_variant_1920", max_width=128, max_height=128, store=True)
can_image_variant_1024_be_zoomed = fields.Boolean("Can Variant Image 1024 be zoomed", compute='_compute_can_image_variant_1024_be_zoomed', store=True)
# Computed fields that are used to create a fallback to the template if
# necessary, it's recommended to display those fields to the user.
image_1920 = fields.Image("Image", compute='_compute_image_1920', inverse='_set_image_1920')
image_1024 = fields.Image("Image 1024", compute='_compute_image_1024')
image_512 = fields.Image("Image 512", compute='_compute_image_512')
image_256 = fields.Image("Image 256", compute='_compute_image_256')
image_128 = fields.Image("Image 128", compute='_compute_image_128')
can_image_1024_be_zoomed = fields.Boolean("Can Image 1024 be zoomed", compute='_compute_can_image_1024_be_zoomed')
@api.depends('image_variant_1920', 'image_variant_1024')
def _compute_can_image_variant_1024_be_zoomed(self):
for record in self:
record.can_image_variant_1024_be_zoomed = record.image_variant_1920 and tools.is_image_size_above(record.image_variant_1920, record.image_variant_1024)
def _set_template_field(self, template_field, variant_field):
for record in self:
if (
# We are trying to remove a field from the variant even though it is already
# not set on the variant, remove it from the template instead.
(not record[template_field] and not record[variant_field])
# We are trying to add a field to the variant, but the template field is
# not set, write on the template instead.
or (record[template_field] and not record.product_tmpl_id[template_field])
# There is only one variant, always write on the template.
or self.search_count([
('product_tmpl_id', '=', record.product_tmpl_id.id),
('active', '=', True),
]) <= 1
):
record[variant_field] = False
record.product_tmpl_id[template_field] = record[template_field]
else:
record[variant_field] = record[template_field]
def _compute_image_1920(self):
"""Get the image from the template if no image is set on the variant."""
for record in self:
record.image_1920 = record.image_variant_1920 or record.product_tmpl_id.image_1920
def _set_image_1920(self):
return self._set_template_field('image_1920', 'image_variant_1920')
@api.depends("create_date", "write_date", "product_tmpl_id.create_date", "product_tmpl_id.write_date")
def compute_concurrency_field_with_access(self):
# Intentionally not calling super() to involve all fields explicitly
for record in self:
record[self.CONCURRENCY_CHECK_FIELD] = max(filter(None, (
record.product_tmpl_id.write_date or record.product_tmpl_id.create_date,
record.write_date or record.create_date or fields.Datetime.now(),
)))
def _compute_image_1024(self):
"""Get the image from the template if no image is set on the variant."""
for record in self:
record.image_1024 = record.image_variant_1024 or record.product_tmpl_id.image_1024
def _compute_image_512(self):
"""Get the image from the template if no image is set on the variant."""
for record in self:
record.image_512 = record.image_variant_512 or record.product_tmpl_id.image_512
def _compute_image_256(self):
"""Get the image from the template if no image is set on the variant."""
for record in self:
record.image_256 = record.image_variant_256 or record.product_tmpl_id.image_256
def _compute_image_128(self):
"""Get the image from the template if no image is set on the variant."""
for record in self:
record.image_128 = record.image_variant_128 or record.product_tmpl_id.image_128
def _compute_can_image_1024_be_zoomed(self):
"""Get the image from the template if no image is set on the variant."""
for record in self:
record.can_image_1024_be_zoomed = record.can_image_variant_1024_be_zoomed if record.image_variant_1920 else record.product_tmpl_id.can_image_1024_be_zoomed
def _get_placeholder_filename(self, field):
image_fields = ['image_%s' % size for size in [1920, 1024, 512, 256, 128]]
if field in image_fields:
return 'product/static/img/placeholder.png'
return super()._get_placeholder_filename(field)
def init(self):
"""Ensure there is at most one active variant for each combination.
There could be no variant for a combination if using dynamic attributes.
"""
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS product_product_combination_unique ON %s (product_tmpl_id, combination_indices) WHERE active is true"
% self._table)
_sql_constraints = [
('barcode_uniq', 'unique(barcode)', "A barcode can only be assigned to one product !"),
]
def _get_invoice_policy(self):
return False
@api.depends('product_template_attribute_value_ids')
def _compute_combination_indices(self):
for product in self:
product.combination_indices = product.product_template_attribute_value_ids._ids2str()
def _compute_is_product_variant(self):
self.is_product_variant = True
@api.depends_context('pricelist', 'partner', 'quantity', 'uom', 'date', 'no_variant_attributes_price_extra')
def _compute_product_price(self):
prices = {}
pricelist_id_or_name = self._context.get('pricelist')
if pricelist_id_or_name:
pricelist = None
partner = self.env.context.get('partner', False)
quantity = self.env.context.get('quantity', 1.0)
# Support context pricelists specified as list, display_name or ID for compatibility
if isinstance(pricelist_id_or_name, list):
pricelist_id_or_name = pricelist_id_or_name[0]
if isinstance(pricelist_id_or_name, str):
pricelist_name_search = self.env['product.pricelist'].name_search(pricelist_id_or_name, operator='=', limit=1)
if pricelist_name_search:
pricelist = self.env['product.pricelist'].browse([pricelist_name_search[0][0]])
elif isinstance(pricelist_id_or_name, int):
pricelist = self.env['product.pricelist'].browse(pricelist_id_or_name)
if pricelist:
quantities = [quantity] * len(self)
partners = [partner] * len(self)
prices = pricelist.get_products_price(self, quantities, partners)
for product in self:
product.price = prices.get(product.id, 0.0)
def _set_product_price(self):
for product in self:
if self._context.get('uom'):
value = self.env['uom.uom'].browse(self._context['uom'])._compute_price(product.price, product.uom_id)
else:
value = product.price
value -= product.price_extra
product.write({'list_price': value})
@api.onchange('lst_price')
def _set_product_lst_price(self):
for product in self:
if self._context.get('uom'):
value = self.env['uom.uom'].browse(self._context['uom'])._compute_price(product.lst_price, product.uom_id)
else:
value = product.lst_price
value -= product.price_extra
product.write({'list_price': value})
def _compute_product_price_extra(self):
for product in self:
product.price_extra = sum(product.product_template_attribute_value_ids.mapped('price_extra'))
@api.depends('list_price', 'price_extra')
@api.depends_context('uom')
def _compute_product_lst_price(self):
to_uom = None
if 'uom' in self._context:
to_uom = self.env['uom.uom'].browse(self._context['uom'])
for product in self:
if to_uom:
list_price = product.uom_id._compute_price(product.list_price, to_uom)
else:
list_price = product.list_price
product.lst_price = list_price + product.price_extra
@api.depends_context('partner_id')
def _compute_product_code(self):
for product in self:
for supplier_info in product.seller_ids:
if supplier_info.name.id == product._context.get('partner_id'):
product.code = supplier_info.product_code or product.default_code
break
else:
product.code = product.default_code
@api.depends_context('partner_id')
def _compute_partner_ref(self):
for product in self:
for supplier_info in product.seller_ids:
if supplier_info.name.id == product._context.get('partner_id'):
product_name = supplier_info.product_name or product.default_code or product.name
product.partner_ref = '%s%s' % (product.code and '[%s] ' % product.code or '', product_name)
break
else:
product.partner_ref = product.display_name
def _compute_variant_item_count(self):
for product in self:
domain = ['|',
'&', ('product_tmpl_id', '=', product.product_tmpl_id.id), ('applied_on', '=', '1_product'),
'&', ('product_id', '=', product.id), ('applied_on', '=', '0_product_variant')]
product.pricelist_item_count = self.env['product.pricelist.item'].search_count(domain)
@api.onchange('uom_id')
def _onchange_uom_id(self):
if self.uom_id:
self.uom_po_id = self.uom_id.id
@api.onchange('uom_po_id')
def _onchange_uom(self):
if self.uom_id and self.uom_po_id and self.uom_id.category_id != self.uom_po_id.category_id:
self.uom_po_id = self.uom_id
@api.onchange('default_code')
def _onchange_default_code(self):
if not self.default_code:
return
domain = [('default_code', '=', self.default_code)]
if self.id.origin:
domain.append(('id', '!=', self.id.origin))
if self.env['product.product'].search(domain, limit=1):
return {'warning': {
'title': _("Note:"),
'message': _("The Internal Reference '%s' already exists.", self.default_code),
}}
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
self.product_tmpl_id._sanitize_vals(vals)
products = super(ProductProduct, self.with_context(create_product_product=True)).create(vals_list)
# `_get_variant_id_for_combination` depends on existing variants
self.clear_caches()
return products
def write(self, values):
self.product_tmpl_id._sanitize_vals(values)
res = super(ProductProduct, self).write(values)
if 'product_template_attribute_value_ids' in values:
# `_get_variant_id_for_combination` depends on `product_template_attribute_value_ids`
self.clear_caches()
elif 'active' in values:
# `_get_first_possible_variant_id` depends on variants active state
self.clear_caches()
return res
def unlink(self):
unlink_products = self.env['product.product']
unlink_templates = self.env['product.template']
for product in self:
# If there is an image set on the variant and no image set on the
# template, move the image to the template.
if product.image_variant_1920 and not product.product_tmpl_id.image_1920:
product.product_tmpl_id.image_1920 = product.image_variant_1920
# Check if product still exists, in case it has been unlinked by unlinking its template
if not product.exists():
continue
# Check if the product is last product of this template...
other_products = self.search([('product_tmpl_id', '=', product.product_tmpl_id.id), ('id', '!=', product.id)])
# ... and do not delete product template if it's configured to be created "on demand"
if not other_products and not product.product_tmpl_id.has_dynamic_attributes():
unlink_templates |= product.product_tmpl_id
unlink_products |= product
res = super(ProductProduct, unlink_products).unlink()
# delete templates after calling super, as deleting template could lead to deleting
# products due to ondelete='cascade'
unlink_templates.unlink()
# `_get_variant_id_for_combination` depends on existing variants
self.clear_caches()
return res
def _filter_to_unlink(self, check_access=True):
return self
def _unlink_or_archive(self, check_access=True):
"""Unlink or archive products.
Try in batch as much as possible because it is much faster.
Use dichotomy when an exception occurs.
"""
# Avoid access errors in case the products is shared amongst companies
# but the underlying objects are not. If unlink fails because of an
# AccessError (e.g. while recomputing fields), the 'write' call will
# fail as well for the same reason since the field has been set to
# recompute.
if check_access:
self.check_access_rights('unlink')
self.check_access_rule('unlink')
self.check_access_rights('write')
self.check_access_rule('write')
self = self.sudo()
to_unlink = self._filter_to_unlink()
to_archive = self - to_unlink
to_archive.write({'active': False})
self = to_unlink
try:
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
self.unlink()
except Exception:
# We catch all kind of exceptions to be sure that the operation
# doesn't fail.
if len(self) > 1:
self[:len(self) // 2]._unlink_or_archive(check_access=False)
self[len(self) // 2:]._unlink_or_archive(check_access=False)
else:
if self.active:
# Note: this can still fail if something is preventing
# from archiving.
# This is the case from existing stock reordering rules.
self.write({'active': False})
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
"""Variants are generated depending on the configuration of attributes
and values on the template, so copying them does not make sense.
For convenience the template is copied instead and its first variant is
returned.
"""
# copy variant is disabled in https://github.com/odoo/odoo/pull/38303
# this returns the first possible combination of variant to make it
# works for now, need to be fixed to return product_variant_id if it's
# possible in the future
template = self.product_tmpl_id.copy(default=default)
return template.product_variant_id or template._create_first_product_variant()
@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
# TDE FIXME: strange
if self._context.get('search_default_categ_id'):
args.append((('categ_id', 'child_of', self._context['search_default_categ_id'])))
return super(ProductProduct, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
@api.depends_context('display_default_code', 'seller_id')
def _compute_display_name(self):
# `display_name` is calling `name_get()`` which is overidden on product
# to depend on `display_default_code` and `seller_id`
return super()._compute_display_name()
def name_get(self):
# TDE: this could be cleaned a bit I think
def _name_get(d):
name = d.get('name', '')
code = self._context.get('display_default_code', True) and d.get('default_code', False) or False
if code:
name = '[%s] %s' % (code,name)
return (d['id'], name)
partner_id = self._context.get('partner_id')
if partner_id:
partner_ids = [partner_id, self.env['res.partner'].browse(partner_id).commercial_partner_id.id]
else:
partner_ids = []
company_id = self.env.context.get('company_id')
# all user don't have access to seller and partner
# check access and use superuser
self.check_access_rights("read")
self.check_access_rule("read")
result = []
# Prefetch the fields used by the `name_get`, so `browse` doesn't fetch other fields
# Use `load=False` to not call `name_get` for the `product_tmpl_id`
self.sudo().read(['name', 'default_code', 'product_tmpl_id'], load=False)
product_template_ids = self.sudo().mapped('product_tmpl_id').ids
if partner_ids:
supplier_info = self.env['product.supplierinfo'].sudo().search([
('product_tmpl_id', 'in', product_template_ids),
('name', 'in', partner_ids),
])
# Prefetch the fields used by the `name_get`, so `browse` doesn't fetch other fields
# Use `load=False` to not call `name_get` for the `product_tmpl_id` and `product_id`
supplier_info.sudo().read(['product_tmpl_id', 'product_id', 'product_name', 'product_code'], load=False)
supplier_info_by_template = {}
for r in supplier_info:
supplier_info_by_template.setdefault(r.product_tmpl_id, []).append(r)
for product in self.sudo():
variant = product.product_template_attribute_value_ids._get_combination_name()
name = variant and "%s (%s)" % (product.name, variant) or product.name
sellers = self.env['product.supplierinfo'].sudo().browse(self.env.context.get('seller_id')) or []
if not sellers and partner_ids:
product_supplier_info = supplier_info_by_template.get(product.product_tmpl_id, [])
sellers = [x for x in product_supplier_info if x.product_id and x.product_id == product]
if not sellers:
sellers = [x for x in product_supplier_info if not x.product_id]
# Filter out sellers based on the company. This is done afterwards for a better
# code readability. At this point, only a few sellers should remain, so it should
# not be a performance issue.
if company_id:
sellers = [x for x in sellers if x.company_id.id in [company_id, False]]
if sellers:
for s in sellers:
seller_variant = s.product_name and (
variant and "%s (%s)" % (s.product_name, variant) or s.product_name
) or False
mydict = {
'id': product.id,
'name': seller_variant or name,
'default_code': s.product_code or product.default_code,
}
temp = _name_get(mydict)
if temp not in result:
result.append(temp)
else:
mydict = {
'id': product.id,
'name': name,
'default_code': product.default_code,
}
result.append(_name_get(mydict))
return result
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if not args:
args = []
if name:
positive_operators = ['=', 'ilike', '=ilike', 'like', '=like']
product_ids = []
if operator in positive_operators:
product_ids = list(self._search([('default_code', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid))
if not product_ids:
product_ids = list(self._search([('barcode', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid))
if not product_ids and operator not in expression.NEGATIVE_TERM_OPERATORS:
# Do not merge the 2 next lines into one single search, SQL search performance would be abysmal
# on a database with thousands of matching products, due to the huge merge+unique needed for the
# OR operator (and given the fact that the 'name' lookup results come from the ir.translation table
# Performing a quick memory merge of ids in Python will give much better performance
product_ids = list(self._search(args + [('default_code', operator, name)], limit=limit))
if not limit or len(product_ids) < limit:
# we may underrun the limit because of dupes in the results, that's fine
limit2 = (limit - len(product_ids)) if limit else False
product2_ids = self._search(args + [('name', operator, name), ('id', 'not in', product_ids)], limit=limit2, access_rights_uid=name_get_uid)
product_ids.extend(product2_ids)
elif not product_ids and operator in expression.NEGATIVE_TERM_OPERATORS:
domain = expression.OR([
['&', ('default_code', operator, name), ('name', operator, name)],
['&', ('default_code', '=', False), ('name', operator, name)],
])
domain = expression.AND([args, domain])
product_ids = list(self._search(domain, limit=limit, access_rights_uid=name_get_uid))
if not product_ids and operator in positive_operators:
ptrn = re.compile('(\[(.*?)\])')
res = ptrn.search(name)
if res:
product_ids = list(self._search([('default_code', '=', res.group(2))] + args, limit=limit, access_rights_uid=name_get_uid))
# still no results, partner in context: search on supplier info as last hope to find something
if not product_ids and self._context.get('partner_id'):
suppliers_ids = self.env['product.supplierinfo']._search([
('name', '=', self._context.get('partner_id')),
'|',
('product_code', operator, name),
('product_name', operator, name)], access_rights_uid=name_get_uid)
if suppliers_ids:
product_ids = self._search([('product_tmpl_id.seller_ids', 'in', suppliers_ids)], limit=limit, access_rights_uid=name_get_uid)
else:
product_ids = self._search(args, limit=limit, access_rights_uid=name_get_uid)
return product_ids
@api.model
def view_header_get(self, view_id, view_type):
if self._context.get('categ_id'):
return _(
'Products: %(category)s',
category=self.env['product.category'].browse(self.env.context['categ_id']).name,
)
return super().view_header_get(view_id, view_type)
def action_open_label_layout(self):
action = self.env['ir.actions.act_window']._for_xml_id('product.action_open_label_layout')
action['context'] = {'default_product_ids': self.ids}
return action
def open_pricelist_rules(self):
self.ensure_one()
domain = ['|',
'&', ('product_tmpl_id', '=', self.product_tmpl_id.id), ('applied_on', '=', '1_product'),
'&', ('product_id', '=', self.id), ('applied_on', '=', '0_product_variant')]
return {
'name': _('Price Rules'),
'view_mode': 'tree,form',
'views': [(self.env.ref('product.product_pricelist_item_tree_view_from_product').id, 'tree'), (False, 'form')],
'res_model': 'product.pricelist.item',
'type': 'ir.actions.act_window',
'target': 'current',
'domain': domain,
'context': {
'default_product_id': self.id,
'default_applied_on': '0_product_variant',
}
}
def open_product_template(self):
""" Utility method used to add an "Open Template" button in product views """
self.ensure_one()
return {'type': 'ir.actions.act_window',
'res_model': 'product.template',
'view_mode': 'form',
'res_id': self.product_tmpl_id.id,
'target': 'new'}
def _prepare_sellers(self, params=False):
return self.seller_ids.filtered(lambda s: s.name.active).sorted(lambda s: (s.sequence, -s.min_qty, s.price, s.id))
def _select_seller(self, partner_id=False, quantity=0.0, date=None, uom_id=False, params=False):
self.ensure_one()
if date is None:
date = fields.Date.context_today(self)
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
res = self.env['product.supplierinfo']
sellers = self._prepare_sellers(params)
sellers = sellers.filtered(lambda s: not s.company_id or s.company_id.id == self.env.company.id)
for seller in sellers:
# Set quantity in UoM of seller
quantity_uom_seller = quantity
if quantity_uom_seller and uom_id and uom_id != seller.product_uom:
quantity_uom_seller = uom_id._compute_quantity(quantity_uom_seller, seller.product_uom)
if seller.date_start and seller.date_start > date:
continue
if seller.date_end and seller.date_end < date:
continue
if partner_id and seller.name not in [partner_id, partner_id.parent_id]:
continue
if quantity is not None and float_compare(quantity_uom_seller, seller.min_qty, precision_digits=precision) == -1:
continue
if seller.product_id and seller.product_id != self:
continue
if not res or res.name == seller.name:
res |= seller
return res.sorted('price')[:1]
def price_compute(self, price_type, uom=False, currency=False, company=None):
# TDE FIXME: delegate to template or not ? fields are reencoded here ...
# compatibility about context keys used a bit everywhere in the code
if not uom and self._context.get('uom'):
uom = self.env['uom.uom'].browse(self._context['uom'])
if not currency and self._context.get('currency'):
currency = self.env['res.currency'].browse(self._context['currency'])
products = self
if price_type == 'standard_price':
# standard_price field can only be seen by users in base.group_user
# Thus, in order to compute the sale price from the cost for users not in this group
# We fetch the standard price as the superuser
products = self.with_company(company or self.env.company).sudo()
prices = dict.fromkeys(self.ids, 0.0)
for product in products:
prices[product.id] = product[price_type] or 0.0
if price_type == 'list_price':
prices[product.id] += product.price_extra
# we need to add the price from the attributes that do not generate variants
# (see field product.attribute create_variant)
if self._context.get('no_variant_attributes_price_extra'):
# we have a list of price_extra that comes from the attribute values, we need to sum all that
prices[product.id] += sum(self._context.get('no_variant_attributes_price_extra'))
if uom:
prices[product.id] = product.uom_id._compute_price(prices[product.id], uom)
# Convert from current user company currency to asked one
# This is right cause a field cannot be in more than one currency
if currency:
company = company or self.env.company
prices[product.id] = product.currency_id._convert(
prices[product.id], currency, company, fields.Date.today())
return prices
@api.model
def get_empty_list_help(self, help):
self = self.with_context(
empty_list_help_document_name=_("product"),
)
return super(ProductProduct, self).get_empty_list_help(help)
def get_product_multiline_description_sale(self):
""" Compute a multiline description of this product, in the context of sales
(do not use for purchases or other display reasons that don't intend to use "description_sale").
It will often be used as the default description of a sale order line referencing this product.
"""
name = self.display_name
if self.description_sale:
name += '\n' + self.description_sale
return name
def _is_variant_possible(self, parent_combination=None):
"""Return whether the variant is possible based on its own combination,
and optionally a parent combination.
See `_is_combination_possible` for more information.
:param parent_combination: combination from which `self` is an
optional or accessory product.
:type parent_combination: recordset `product.template.attribute.value`
:return: ẁhether the variant is possible based on its own combination
:rtype: bool
"""
self.ensure_one()
return self.product_tmpl_id._is_combination_possible(self.product_template_attribute_value_ids, parent_combination=parent_combination, ignore_no_variant=True)
def toggle_active(self):
""" Archiving related product.template if there is not any more active product.product
(and vice versa, unarchiving the related product template if there is now an active product.product) """
result = super().toggle_active()
# We deactivate product templates which are active with no active variants.
tmpl_to_deactivate = self.filtered(lambda product: (product.product_tmpl_id.active
and not product.product_tmpl_id.product_variant_ids)).mapped('product_tmpl_id')
# We activate product templates which are inactive with active variants.
tmpl_to_activate = self.filtered(lambda product: (not product.product_tmpl_id.active
and product.product_tmpl_id.product_variant_ids)).mapped('product_tmpl_id')
(tmpl_to_deactivate + tmpl_to_activate).toggle_active()
return result
class ProductPackaging(models.Model):
_name = "product.packaging"
_description = "Product Packaging"
_order = 'product_id, sequence, id'
_check_company_auto = True
name = fields.Char('Product Packaging', required=True)
sequence = fields.Integer('Sequence', default=1, help="The first in the sequence is the default one.")
product_id = fields.Many2one('product.product', string='Product', check_company=True)
qty = fields.Float('Contained Quantity', default=1, digits='Product Unit of Measure', help="Quantity of products contained in the packaging.")
barcode = fields.Char('Barcode', copy=False, help="Barcode used for packaging identification. Scan this packaging barcode from a transfer in the Barcode app to move all the contained units")
product_uom_id = fields.Many2one('uom.uom', related='product_id.uom_id', readonly=True)
company_id = fields.Many2one('res.company', 'Company', index=True)
_sql_constraints = [
('positive_qty', 'CHECK(qty > 0)', 'Contained Quantity should be positive.')
]
def _check_qty(self, product_qty, uom_id, rounding_method="HALF-UP"):
"""Check if product_qty in given uom is a multiple of the packaging qty.
If not, rounding the product_qty to closest multiple of the packaging qty
according to the rounding_method "UP", "HALF-UP or "DOWN".
"""
self.ensure_one()
default_uom = self.product_id.uom_id
packaging_qty = default_uom._compute_quantity(self.qty, uom_id)
# We do not use the modulo operator to check if qty is a mltiple of q. Indeed the quantity
# per package might be a float, leading to incorrect results. For example:
# 8 % 1.6 = 1.5999999999999996
# 5.4 % 1.8 = 2.220446049250313e-16
if product_qty and packaging_qty:
rounded_qty = float_round(product_qty / packaging_qty, precision_rounding=1.0,
rounding_method=rounding_method) * packaging_qty
return rounded_qty if float_compare(rounded_qty, product_qty, precision_rounding=default_uom.rounding) else product_qty
return product_qty
def _find_suitable_product_packaging(self, product_qty, uom_id):
""" try find in `self` if a packaging's qty in given uom is a divisor of
the given product_qty. If so, return the one with greatest divisor.
"""
packagings = self.sorted(lambda p: p.qty, reverse=True)
for packaging in packagings:
new_qty = packaging._check_qty(product_qty, uom_id)
if new_qty == product_qty:
return packaging
return self.env['product.packaging']
class SupplierInfo(models.Model):
_name = "product.supplierinfo"
_description = "Supplier Pricelist"
_order = 'sequence, min_qty DESC, price, id'
name = fields.Many2one(
'res.partner', 'Vendor',
ondelete='cascade', required=True,
help="Vendor of this product", check_company=True)
product_name = fields.Char(
'Vendor Product Name',
help="This vendor's product name will be used when printing a request for quotation. Keep empty to use the internal one.")
product_code = fields.Char(
'Vendor Product Code',
help="This vendor's product code will be used when printing a request for quotation. Keep empty to use the internal one.")
sequence = fields.Integer(
'Sequence', default=1, help="Assigns the priority to the list of product vendor.")
product_uom = fields.Many2one(
'uom.uom', 'Unit of Measure',
related='product_tmpl_id.uom_po_id',
help="This comes from the product form.")
min_qty = fields.Float(
'Quantity', default=0.0, required=True, digits="Product Unit Of Measure",
help="The quantity to purchase from this vendor to benefit from the price, expressed in the vendor Product Unit of Measure if not any, in the default unit of measure of the product otherwise.")
price = fields.Float(
'Price', default=0.0, digits='Product Price',
required=True, help="The price to purchase a product")
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company.id, index=1)
currency_id = fields.Many2one(
'res.currency', 'Currency',
default=lambda self: self.env.company.currency_id.id,
required=True)
date_start = fields.Date('Start Date', help="Start date for this vendor price")
date_end = fields.Date('End Date', help="End date for this vendor price")
product_id = fields.Many2one(
'product.product', 'Product Variant', check_company=True,
help="If not set, the vendor price will apply to all variants of this product.")
product_tmpl_id = fields.Many2one(
'product.template', 'Product Template', check_company=True,
index=True, ondelete='cascade')
product_variant_count = fields.Integer('Variant Count', related='product_tmpl_id.product_variant_count')
delay = fields.Integer(
'Delivery Lead Time', default=1, required=True,
help="Lead time in days between the confirmation of the purchase order and the receipt of the products in your warehouse. Used by the scheduler for automatic computation of the purchase order planning.")
@api.model
def get_import_templates(self):
return [{
'label': _('Import Template for Vendor Pricelists'),
'template': '/product/static/xls/product_supplierinfo.xls'
}]
@api.constrains('product_id', 'product_tmpl_id')
def _check_product_variant(self):
for supplier in self:
if supplier.product_id and supplier.product_tmpl_id and supplier.product_id.product_tmpl_id != supplier.product_tmpl_id:
raise ValidationError(_('The product variant must be a variant of the product template.'))
| 50.668571
| 44,335
|
4,192
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
group_discount_per_so_line = fields.Boolean("Discounts", implied_group='product.group_discount_per_so_line')
group_uom = fields.Boolean("Units of Measure", implied_group='uom.group_uom')
group_product_variant = fields.Boolean("Variants", implied_group='product.group_product_variant')
module_sale_product_configurator = fields.Boolean("Product Configurator")
module_sale_product_matrix = fields.Boolean("Sales Grid Entry")
group_stock_packaging = fields.Boolean('Product Packagings',
implied_group='product.group_stock_packaging')
group_product_pricelist = fields.Boolean("Pricelists",
implied_group='product.group_product_pricelist')
group_sale_pricelist = fields.Boolean("Advanced Pricelists",
implied_group='product.group_sale_pricelist',
help="""Allows to manage different prices based on rules per category of customers.
Example: 10% for retailers, promotion of 5 EUR on this product, etc.""")
product_pricelist_setting = fields.Selection([
('basic', 'Multiple prices per product'),
('advanced', 'Advanced price rules (discounts, formulas)')
], default='basic', string="Pricelists Method", config_parameter='product.product_pricelist_setting',
help="Multiple prices: Pricelists with fixed price rules by product,\nAdvanced rules: enables advanced price rules for pricelists.")
product_weight_in_lbs = fields.Selection([
('0', 'Kilograms'),
('1', 'Pounds'),
], 'Weight unit of measure', config_parameter='product.weight_in_lbs', default='0')
product_volume_volume_in_cubic_feet = fields.Selection([
('0', 'Cubic Meters'),
('1', 'Cubic Feet'),
], 'Volume unit of measure', config_parameter='product.volume_in_cubic_feet', default='0')
@api.onchange('group_product_variant')
def _onchange_group_product_variant(self):
"""The product Configurator requires the product variants activated.
If the user disables the product variants -> disable the product configurator as well"""
if self.module_sale_product_configurator and not self.group_product_variant:
self.module_sale_product_configurator = False
if self.module_sale_product_matrix and not self.group_product_variant:
self.module_sale_product_matrix = False
@api.onchange('module_sale_product_configurator')
def _onchange_module_sale_product_configurator(self):
"""The product Configurator requires the product variants activated
If the user enables the product configurator -> enable the product variants as well"""
if self.module_sale_product_configurator and not self.group_product_variant:
self.group_product_variant = True
@api.onchange('group_product_pricelist')
def _onchange_group_sale_pricelist(self):
if not self.group_product_pricelist and self.group_sale_pricelist:
self.group_sale_pricelist = False
@api.onchange('product_pricelist_setting')
def _onchange_product_pricelist_setting(self):
if self.product_pricelist_setting == 'basic':
self.group_sale_pricelist = False
else:
self.group_sale_pricelist = True
def set_values(self):
super(ResConfigSettings, self).set_values()
if not self.group_discount_per_so_line:
pl = self.env['product.pricelist'].search([('discount_policy', '=', 'without_discount')])
pl.write({'discount_policy': 'with_discount'})
@api.onchange('module_sale_product_matrix')
def _onchange_module_module_sale_product_matrix(self):
"""The product Grid Configurator requires the product Configurator activated
If the user enables the Grid Configurator -> enable the product Configurator as well"""
if self.module_sale_product_matrix and not self.module_sale_product_configurator:
self.module_sale_product_configurator = True
| 55.157895
| 4,192
|
32,808
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from random import randint
from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
class ProductAttribute(models.Model):
_name = "product.attribute"
_description = "Product Attribute"
# if you change this _order, keep it in sync with the method
# `_sort_key_attribute_value` in `product.template`
_order = 'sequence, id'
name = fields.Char('Attribute', required=True, translate=True)
value_ids = fields.One2many('product.attribute.value', 'attribute_id', 'Values', copy=True)
sequence = fields.Integer('Sequence', help="Determine the display order", index=True)
attribute_line_ids = fields.One2many('product.template.attribute.line', 'attribute_id', 'Lines')
create_variant = fields.Selection([
('always', 'Instantly'),
('dynamic', 'Dynamically'),
('no_variant', 'Never (option)')],
default='always',
string="Variants Creation Mode",
help="""- Instantly: All possible variants are created as soon as the attribute and its values are added to a product.
- Dynamically: Each variant is created only when its corresponding attributes and values are added to a sales order.
- Never: Variants are never created for the attribute.
Note: the variants creation mode cannot be changed once the attribute is used on at least one product.""",
required=True)
number_related_products = fields.Integer(compute='_compute_number_related_products')
product_tmpl_ids = fields.Many2many('product.template', string="Related Products", compute='_compute_products', store=True)
display_type = fields.Selection([
('radio', 'Radio'),
('pills', 'Pills'),
('select', 'Select'),
('color', 'Color')], default='radio', required=True, help="The display type used in the Product Configurator.")
@api.depends('product_tmpl_ids')
def _compute_number_related_products(self):
for pa in self:
pa.number_related_products = len(pa.product_tmpl_ids)
@api.depends('attribute_line_ids.active', 'attribute_line_ids.product_tmpl_id')
def _compute_products(self):
for pa in self:
pa.with_context(active_test=False).product_tmpl_ids = pa.attribute_line_ids.product_tmpl_id
def _without_no_variant_attributes(self):
return self.filtered(lambda pa: pa.create_variant != 'no_variant')
def write(self, vals):
"""Override to make sure attribute type can't be changed if it's used on
a product template.
This is important to prevent because changing the type would make
existing combinations invalid without recomputing them, and recomputing
them might take too long and we don't want to change products without
the user knowing about it."""
if 'create_variant' in vals:
for pa in self:
if vals['create_variant'] != pa.create_variant and pa.number_related_products:
raise UserError(
_("You cannot change the Variants Creation Mode of the attribute %s because it is used on the following products:\n%s") %
(pa.display_name, ", ".join(pa.product_tmpl_ids.mapped('display_name')))
)
invalidate_cache = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self)
res = super(ProductAttribute, self).write(vals)
if invalidate_cache:
# prefetched o2m have to be resequenced
# (eg. product.template: attribute_line_ids)
self.flush()
self.invalidate_cache()
return res
@api.ondelete(at_uninstall=False)
def _unlink_except_used_on_product(self):
for pa in self:
if pa.number_related_products:
raise UserError(
_("You cannot delete the attribute %s because it is used on the following products:\n%s") %
(pa.display_name, ", ".join(pa.product_tmpl_ids.mapped('display_name')))
)
def action_open_related_products(self):
return {
'type': 'ir.actions.act_window',
'name': _("Related Products"),
'res_model': 'product.template',
'view_mode': 'tree,form',
'domain': [('id', 'in', self.product_tmpl_ids.ids)],
}
class ProductAttributeValue(models.Model):
_name = "product.attribute.value"
# if you change this _order, keep it in sync with the method
# `_sort_key_variant` in `product.template'
_order = 'attribute_id, sequence, id'
_description = 'Attribute Value'
def _get_default_color(self):
return randint(1, 11)
name = fields.Char(string='Value', required=True, translate=True)
sequence = fields.Integer(string='Sequence', help="Determine the display order", index=True)
attribute_id = fields.Many2one('product.attribute', string="Attribute", ondelete='cascade', required=True, index=True,
help="The attribute cannot be changed once the value is used on at least one product.")
pav_attribute_line_ids = fields.Many2many('product.template.attribute.line', string="Lines",
relation='product_attribute_value_product_template_attribute_line_rel', copy=False)
is_used_on_products = fields.Boolean('Used on Products', compute='_compute_is_used_on_products')
is_custom = fields.Boolean('Is custom value', help="Allow users to input custom values for this attribute value")
html_color = fields.Char(
string='Color',
help="Here you can set a specific HTML color index (e.g. #ff0000) to display the color if the attribute type is 'Color'.")
display_type = fields.Selection(related='attribute_id.display_type', readonly=True)
color = fields.Integer('Color Index', default=_get_default_color)
_sql_constraints = [
('value_company_uniq', 'unique (name, attribute_id)', "You cannot create two values with the same name for the same attribute.")
]
@api.depends('pav_attribute_line_ids')
def _compute_is_used_on_products(self):
for pav in self:
pav.is_used_on_products = bool(pav.pav_attribute_line_ids)
def name_get(self):
"""Override because in general the name of the value is confusing if it
is displayed without the name of the corresponding attribute.
Eg. on product list & kanban views, on BOM form view
However during variant set up (on the product template form) the name of
the attribute is already on each line so there is no need to repeat it
on every value.
"""
if not self._context.get('show_attribute', True):
return super(ProductAttributeValue, self).name_get()
return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]
def write(self, values):
if 'attribute_id' in values:
for pav in self:
if pav.attribute_id.id != values['attribute_id'] and pav.is_used_on_products:
raise UserError(
_("You cannot change the attribute of the value %s because it is used on the following products:%s") %
(pav.display_name, ", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')))
)
invalidate_cache = 'sequence' in values and any(record.sequence != values['sequence'] for record in self)
res = super(ProductAttributeValue, self).write(values)
if invalidate_cache:
# prefetched o2m have to be resequenced
# (eg. product.template.attribute.line: value_ids)
self.flush()
self.invalidate_cache()
return res
@api.ondelete(at_uninstall=False)
def _unlink_except_used_on_product(self):
for pav in self:
if pav.is_used_on_products:
raise UserError(
_("You cannot delete the value %s because it is used on the following products:"
"\n%s\n If the value has been associated to a product in the past, you will "
"not be able to delete it.") %
(pav.display_name, ", ".join(
pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')
))
)
linked_products = pav.env['product.template.attribute.value'].search(
[('product_attribute_value_id', '=', pav.id)]
).with_context(active_test=False).ptav_product_variant_ids
unlinkable_products = linked_products._filter_to_unlink()
if linked_products != unlinkable_products:
raise UserError(_(
"You cannot delete value %s because it was used in some products.",
pav.display_name
))
def _without_no_variant_attributes(self):
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
class ProductTemplateAttributeLine(models.Model):
"""Attributes available on product.template with their selected values in a m2m.
Used as a configuration model to generate the appropriate product.template.attribute.value"""
_name = "product.template.attribute.line"
_rec_name = 'attribute_id'
_description = 'Product Template Attribute Line'
_order = 'attribute_id, id'
active = fields.Boolean(default=True)
product_tmpl_id = fields.Many2one('product.template', string="Product Template", ondelete='cascade', required=True, index=True)
attribute_id = fields.Many2one('product.attribute', string="Attribute", ondelete='restrict', required=True, index=True)
value_ids = fields.Many2many('product.attribute.value', string="Values", domain="[('attribute_id', '=', attribute_id)]",
relation='product_attribute_value_product_template_attribute_line_rel', ondelete='restrict')
value_count = fields.Integer(compute='_compute_value_count', store=True, readonly=True)
product_template_value_ids = fields.One2many('product.template.attribute.value', 'attribute_line_id', string="Product Attribute Values")
@api.depends('value_ids')
def _compute_value_count(self):
for record in self:
record.value_count = len(record.value_ids)
@api.onchange('attribute_id')
def _onchange_attribute_id(self):
self.value_ids = self.value_ids.filtered(lambda pav: pav.attribute_id == self.attribute_id)
@api.constrains('active', 'value_ids', 'attribute_id')
def _check_valid_values(self):
for ptal in self:
if ptal.active and not ptal.value_ids:
raise ValidationError(
_("The attribute %s must have at least one value for the product %s.") %
(ptal.attribute_id.display_name, ptal.product_tmpl_id.display_name)
)
for pav in ptal.value_ids:
if pav.attribute_id != ptal.attribute_id:
raise ValidationError(
_("On the product %s you cannot associate the value %s with the attribute %s because they do not match.") %
(ptal.product_tmpl_id.display_name, pav.display_name, ptal.attribute_id.display_name)
)
return True
@api.model_create_multi
def create(self, vals_list):
"""Override to:
- Activate archived lines having the same configuration (if they exist)
instead of creating new lines.
- Set up related values and related variants.
Reactivating existing lines allows to re-use existing variants when
possible, keeping their configuration and avoiding duplication.
"""
create_values = []
activated_lines = self.env['product.template.attribute.line']
for value in vals_list:
vals = dict(value, active=value.get('active', True))
# While not ideal for peformance, this search has to be done at each
# step to exclude the lines that might have been activated at a
# previous step. Since `vals_list` will likely be a small list in
# all use cases, this is an acceptable trade-off.
archived_ptal = self.search([
('active', '=', False),
('product_tmpl_id', '=', vals.pop('product_tmpl_id', 0)),
('attribute_id', '=', vals.pop('attribute_id', 0)),
], limit=1)
if archived_ptal:
# Write given `vals` in addition of `active` to ensure
# `value_ids` or other fields passed to `create` are saved too,
# but change the context to avoid updating the values and the
# variants until all the expected lines are created/updated.
archived_ptal.with_context(update_product_template_attribute_values=False).write(vals)
activated_lines += archived_ptal
else:
create_values.append(value)
res = activated_lines + super(ProductTemplateAttributeLine, self).create(create_values)
res._update_product_template_attribute_values()
return res
def write(self, values):
"""Override to:
- Add constraints to prevent doing changes that are not supported such
as modifying the template or the attribute of existing lines.
- Clean up related values and related variants when archiving or when
updating `value_ids`.
"""
if 'product_tmpl_id' in values:
for ptal in self:
if ptal.product_tmpl_id.id != values['product_tmpl_id']:
raise UserError(
_("You cannot move the attribute %s from the product %s to the product %s.") %
(ptal.attribute_id.display_name, ptal.product_tmpl_id.display_name, values['product_tmpl_id'])
)
if 'attribute_id' in values:
for ptal in self:
if ptal.attribute_id.id != values['attribute_id']:
raise UserError(
_("On the product %s you cannot transform the attribute %s into the attribute %s.") %
(ptal.product_tmpl_id.display_name, ptal.attribute_id.display_name, values['attribute_id'])
)
# Remove all values while archiving to make sure the line is clean if it
# is ever activated again.
if not values.get('active', True):
values['value_ids'] = [(5, 0, 0)]
res = super(ProductTemplateAttributeLine, self).write(values)
if 'active' in values:
self.flush()
self.env['product.template'].invalidate_cache(fnames=['attribute_line_ids'])
# If coming from `create`, no need to update the values and the variants
# before all lines are created.
if self.env.context.get('update_product_template_attribute_values', True):
self._update_product_template_attribute_values()
return res
def unlink(self):
"""Override to:
- Archive the line if unlink is not possible.
- Clean up related values and related variants.
Archiving is typically needed when the line has values that can't be
deleted because they are referenced elsewhere (on a variant that can't
be deleted, on a sales order line, ...).
"""
# Try to remove the values first to remove some potentially blocking
# references, which typically works:
# - For single value lines because the values are directly removed from
# the variants.
# - For values that are present on variants that can be deleted.
self.product_template_value_ids._only_active().unlink()
# Keep a reference to the related templates before the deletion.
templates = self.product_tmpl_id
# Now delete or archive the lines.
ptal_to_archive = self.env['product.template.attribute.line']
for ptal in self:
try:
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
super(ProductTemplateAttributeLine, ptal).unlink()
except Exception:
# We catch all kind of exceptions to be sure that the operation
# doesn't fail.
ptal_to_archive += ptal
ptal_to_archive.write({'active': False})
# For archived lines `_update_product_template_attribute_values` is
# implicitly called during the `write` above, but for products that used
# unlinked lines `_create_variant_ids` has to be called manually.
(templates - ptal_to_archive.product_tmpl_id)._create_variant_ids()
return True
def _update_product_template_attribute_values(self):
"""Create or unlink `product.template.attribute.value` for each line in
`self` based on `value_ids`.
The goal is to delete all values that are not in `value_ids`, to
activate those in `value_ids` that are currently archived, and to create
those in `value_ids` that didn't exist.
This is a trick for the form view and for performance in general,
because we don't want to generate in advance all possible values for all
templates, but only those that will be selected.
"""
ProductTemplateAttributeValue = self.env['product.template.attribute.value']
ptav_to_create = []
ptav_to_unlink = ProductTemplateAttributeValue
for ptal in self:
ptav_to_activate = ProductTemplateAttributeValue
remaining_pav = ptal.value_ids
for ptav in ptal.product_template_value_ids:
if ptav.product_attribute_value_id not in remaining_pav:
# Remove values that existed but don't exist anymore, but
# ignore those that are already archived because if they are
# archived it means they could not be deleted previously.
if ptav.ptav_active:
ptav_to_unlink += ptav
else:
# Activate corresponding values that are currently archived.
remaining_pav -= ptav.product_attribute_value_id
if not ptav.ptav_active:
ptav_to_activate += ptav
for pav in remaining_pav:
# The previous loop searched for archived values that belonged to
# the current line, but if the line was deleted and another line
# was recreated for the same attribute, we need to expand the
# search to those with matching `attribute_id`.
# While not ideal for peformance, this search has to be done at
# each step to exclude the values that might have been activated
# at a previous step. Since `remaining_pav` will likely be a
# small list in all use cases, this is an acceptable trade-off.
ptav = ProductTemplateAttributeValue.search([
('ptav_active', '=', False),
('product_tmpl_id', '=', ptal.product_tmpl_id.id),
('attribute_id', '=', ptal.attribute_id.id),
('product_attribute_value_id', '=', pav.id),
], limit=1)
if ptav:
ptav.write({'ptav_active': True, 'attribute_line_id': ptal.id})
# If the value was marked for deletion, now keep it.
ptav_to_unlink -= ptav
else:
# create values that didn't exist yet
ptav_to_create.append({
'product_attribute_value_id': pav.id,
'attribute_line_id': ptal.id
})
# Handle active at each step in case a following line might want to
# re-use a value that was archived at a previous step.
ptav_to_activate.write({'ptav_active': True})
ptav_to_unlink.write({'ptav_active': False})
if ptav_to_unlink:
ptav_to_unlink.unlink()
ProductTemplateAttributeValue.create(ptav_to_create)
self.product_tmpl_id._create_variant_ids()
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
# TDE FIXME: currently overriding the domain; however as it includes a
# search on a m2o and one on a m2m, probably this will quickly become
# difficult to compute - check if performance optimization is required
if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
args = args or []
domain = ['|', ('attribute_id', operator, name), ('value_ids', operator, name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
return super(ProductTemplateAttributeLine, self)._name_search(name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
def _without_no_variant_attributes(self):
return self.filtered(lambda ptal: ptal.attribute_id.create_variant != 'no_variant')
def action_open_attribute_values(self):
return {
'type': 'ir.actions.act_window',
'name': _("Product Variant Values"),
'res_model': 'product.template.attribute.value',
'view_mode': 'tree,form',
'domain': [('id', 'in', self.product_template_value_ids.ids)],
'views': [
(self.env.ref('product.product_template_attribute_value_view_tree').id, 'list'),
(self.env.ref('product.product_template_attribute_value_view_form').id, 'form'),
],
'context': {
'search_default_active': 1,
},
}
class ProductTemplateAttributeValue(models.Model):
"""Materialized relationship between attribute values
and product template generated by the product.template.attribute.line"""
_name = "product.template.attribute.value"
_description = "Product Template Attribute Value"
_order = 'attribute_line_id, product_attribute_value_id, id'
def _get_default_color(self):
return randint(1, 11)
# Not just `active` because we always want to show the values except in
# specific case, as opposed to `active_test`.
ptav_active = fields.Boolean("Active", default=True)
name = fields.Char('Value', related="product_attribute_value_id.name")
# defining fields: the product template attribute line and the product attribute value
product_attribute_value_id = fields.Many2one(
'product.attribute.value', string='Attribute Value',
required=True, ondelete='cascade', index=True)
attribute_line_id = fields.Many2one('product.template.attribute.line', required=True, ondelete='cascade', index=True)
# configuration fields: the price_extra and the exclusion rules
price_extra = fields.Float(
string="Value Price Extra",
default=0.0,
digits='Product Price',
help="Extra price for the variant with this attribute value on sale price. eg. 200 price extra, 1000 + 200 = 1200.")
currency_id = fields.Many2one(related='attribute_line_id.product_tmpl_id.currency_id')
exclude_for = fields.One2many(
'product.template.attribute.exclusion',
'product_template_attribute_value_id',
string="Exclude for",
help="Make this attribute value not compatible with "
"other values of the product or some attribute values of optional and accessory products.")
# related fields: product template and product attribute
product_tmpl_id = fields.Many2one('product.template', string="Product Template", related='attribute_line_id.product_tmpl_id', store=True, index=True)
attribute_id = fields.Many2one('product.attribute', string="Attribute", related='attribute_line_id.attribute_id', store=True, index=True)
ptav_product_variant_ids = fields.Many2many('product.product', relation='product_variant_combination', string="Related Variants", readonly=True)
html_color = fields.Char('HTML Color Index', related="product_attribute_value_id.html_color")
is_custom = fields.Boolean('Is custom value', related="product_attribute_value_id.is_custom")
display_type = fields.Selection(related='product_attribute_value_id.display_type', readonly=True)
color = fields.Integer('Color', default=_get_default_color)
_sql_constraints = [
('attribute_value_unique', 'unique(attribute_line_id, product_attribute_value_id)', "Each value should be defined only once per attribute per product."),
]
@api.constrains('attribute_line_id', 'product_attribute_value_id')
def _check_valid_values(self):
for ptav in self:
if ptav.product_attribute_value_id not in ptav.attribute_line_id.value_ids:
raise ValidationError(
_("The value %s is not defined for the attribute %s on the product %s.") %
(ptav.product_attribute_value_id.display_name, ptav.attribute_id.display_name, ptav.product_tmpl_id.display_name)
)
@api.model_create_multi
def create(self, vals_list):
if any('ptav_product_variant_ids' in v for v in vals_list):
# Force write on this relation from `product.product` to properly
# trigger `_compute_combination_indices`.
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
return super(ProductTemplateAttributeValue, self).create(vals_list)
def write(self, values):
if 'ptav_product_variant_ids' in values:
# Force write on this relation from `product.product` to properly
# trigger `_compute_combination_indices`.
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
pav_in_values = 'product_attribute_value_id' in values
product_in_values = 'product_tmpl_id' in values
if pav_in_values or product_in_values:
for ptav in self:
if pav_in_values and ptav.product_attribute_value_id.id != values['product_attribute_value_id']:
raise UserError(
_("You cannot change the value of the value %s set on product %s.") %
(ptav.display_name, ptav.product_tmpl_id.display_name)
)
if product_in_values and ptav.product_tmpl_id.id != values['product_tmpl_id']:
raise UserError(
_("You cannot change the product of the value %s set on product %s.") %
(ptav.display_name, ptav.product_tmpl_id.display_name)
)
res = super(ProductTemplateAttributeValue, self).write(values)
if 'exclude_for' in values:
self.product_tmpl_id._create_variant_ids()
return res
def unlink(self):
"""Override to:
- Clean up the variants that use any of the values in self:
- Remove the value from the variant if the value belonged to an
attribute line with only one value.
- Unlink or archive all related variants.
- Archive the value if unlink is not possible.
Archiving is typically needed when the value is referenced elsewhere
(on a variant that can't be deleted, on a sales order line, ...).
"""
# Directly remove the values from the variants for lines that had single
# value (counting also the values that are archived).
single_values = self.filtered(lambda ptav: len(ptav.attribute_line_id.product_template_value_ids) == 1)
for ptav in single_values:
ptav.ptav_product_variant_ids.write({'product_template_attribute_value_ids': [(3, ptav.id, 0)]})
# Try to remove the variants before deleting to potentially remove some
# blocking references.
self.ptav_product_variant_ids._unlink_or_archive()
# Now delete or archive the values.
ptav_to_archive = self.env['product.template.attribute.value']
for ptav in self:
try:
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
super(ProductTemplateAttributeValue, ptav).unlink()
except Exception:
# We catch all kind of exceptions to be sure that the operation
# doesn't fail.
ptav_to_archive += ptav
ptav_to_archive.write({'ptav_active': False})
return True
def name_get(self):
"""Override because in general the name of the value is confusing if it
is displayed without the name of the corresponding attribute.
Eg. on exclusion rules form
"""
return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]
def _only_active(self):
return self.filtered(lambda ptav: ptav.ptav_active)
def _without_no_variant_attributes(self):
return self.filtered(lambda ptav: ptav.attribute_id.create_variant != 'no_variant')
def _ids2str(self):
return ','.join([str(i) for i in sorted(self.ids)])
def _get_combination_name(self):
"""Exclude values from single value lines or from no_variant attributes."""
ptavs = self._without_no_variant_attributes().with_prefetch(self._prefetch_ids)
ptavs = ptavs._filter_single_value_lines().with_prefetch(self._prefetch_ids)
return ", ".join([ptav.name for ptav in ptavs])
def _filter_single_value_lines(self):
"""Return `self` with values from single value lines filtered out
depending on the active state of all the values in `self`.
If any value in `self` is archived, archived values are also taken into
account when checking for single values.
This allows to display the correct name for archived variants.
If all values in `self` are active, only active values are taken into
account when checking for single values.
This allows to display the correct name for active combinations.
"""
only_active = all(ptav.ptav_active for ptav in self)
return self.filtered(lambda ptav: not ptav._is_from_single_value_line(only_active))
def _is_from_single_value_line(self, only_active=True):
"""Return whether `self` is from a single value line, counting also
archived values if `only_active` is False.
"""
self.ensure_one()
all_values = self.attribute_line_id.product_template_value_ids
if only_active:
all_values = all_values._only_active()
return len(all_values) == 1
class ProductTemplateAttributeExclusion(models.Model):
_name = "product.template.attribute.exclusion"
_description = 'Product Template Attribute Exclusion'
_order = 'product_tmpl_id, id'
product_template_attribute_value_id = fields.Many2one(
'product.template.attribute.value', string="Attribute Value", ondelete='cascade', index=True)
product_tmpl_id = fields.Many2one(
'product.template', string='Product Template', ondelete='cascade', required=True, index=True)
value_ids = fields.Many2many(
'product.template.attribute.value', relation="product_attr_exclusion_value_ids_rel",
string='Attribute Values', domain="[('product_tmpl_id', '=', product_tmpl_id), ('ptav_active', '=', True)]")
class ProductAttributeCustomValue(models.Model):
_name = "product.attribute.custom.value"
_description = 'Product Attribute Custom Value'
_order = 'custom_product_template_attribute_value_id, id'
name = fields.Char("Name", compute='_compute_name')
custom_product_template_attribute_value_id = fields.Many2one('product.template.attribute.value', string="Attribute Value", required=True, ondelete='restrict')
custom_value = fields.Char("Custom Value")
@api.depends('custom_product_template_attribute_value_id.name', 'custom_value')
def _compute_name(self):
for record in self:
name = (record.custom_value or '').strip()
if record.custom_product_template_attribute_value_id.display_name:
name = "%s: %s" % (record.custom_product_template_attribute_value_id.display_name, name)
record.name = name
| 51.829384
| 32,808
|
2,135
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class Partner(models.Model):
_name = 'res.partner'
_inherit = 'res.partner'
# NOT A REAL PROPERTY !!!!
property_product_pricelist = fields.Many2one(
'product.pricelist', 'Pricelist', compute='_compute_product_pricelist',
inverse="_inverse_product_pricelist", company_dependent=False,
domain=lambda self: [('company_id', 'in', (self.env.company.id, False))],
help="This pricelist will be used, instead of the default one, for sales to the current partner")
@api.depends('country_id')
@api.depends_context('company')
def _compute_product_pricelist(self):
company = self.env.company.id
res = self.env['product.pricelist']._get_partner_pricelist_multi(self.ids, company_id=company)
for p in self:
p.property_product_pricelist = res.get(p.id)
def _inverse_product_pricelist(self):
for partner in self:
pls = self.env['product.pricelist'].search(
[('country_group_ids.country_ids.code', '=', partner.country_id and partner.country_id.code or False)],
limit=1
)
default_for_country = pls and pls[0]
actual = self.env['ir.property']._get('property_product_pricelist', 'res.partner', 'res.partner,%s' % partner.id)
# update at each change country, and so erase old pricelist
if partner.property_product_pricelist or (actual and default_for_country and default_for_country.id != actual.id):
# keep the company of the current user before sudo
self.env['ir.property']._set_multi(
'property_product_pricelist',
partner._name,
{partner.id: partner.property_product_pricelist or default_for_country.id},
default_value=default_for_country.id
)
def _commercial_fields(self):
return super(Partner, self)._commercial_fields() + ['property_product_pricelist']
| 47.444444
| 2,135
|
1,836
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, tools, _
from odoo.exceptions import ValidationError
class DecimalPrecision(models.Model):
_inherit = 'decimal.precision'
@api.constrains('digits')
def _check_main_currency_rounding(self):
if any(precision.name == 'Account' and
tools.float_compare(self.env.company.currency_id.rounding, 10 ** - precision.digits, precision_digits=6) == -1
for precision in self):
raise ValidationError(_("You cannot define the decimal precision of 'Account' as greater than the rounding factor of the company's main currency"))
return True
@api.onchange('digits')
def _onchange_digits(self):
if self.name != "Product Unit of Measure": # precision_get() relies on this name
return
# We are changing the precision of UOM fields; check whether the
# precision is equal or higher than existing units of measure.
rounding = 1.0 / 10.0**self.digits
dangerous_uom = self.env['uom.uom'].search([('rounding', '<', rounding)])
if dangerous_uom:
uom_descriptions = [
" - %s (id=%s, precision=%s)" % (uom.name, uom.id, uom.rounding)
for uom in dangerous_uom
]
return {'warning': {
'title': _('Warning!'),
'message': _(
"You are setting a Decimal Accuracy less precise than the UOMs:\n"
"%s\n"
"This may cause inconsistencies in computations.\n"
"Please increase the rounding of those units of measure, or the digits of this Decimal Accuracy."
) % ('\n'.join(uom_descriptions)),
}}
| 45.9
| 1,836
|
2,505
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class ProductPricelistReport(models.AbstractModel):
_name = 'report.product.report_pricelist'
_description = 'Pricelist Report'
def _get_report_values(self, docids, data):
return self._get_report_data(data, 'pdf')
@api.model
def get_html(self, data):
render_values = self._get_report_data(data, 'html')
return self.env.ref('product.report_pricelist_page')._render(render_values)
def _get_report_data(self, data, report_type='html'):
quantities = data.get('quantities', [1])
data_pricelist_id = data.get('pricelist_id')
pricelist_id = data_pricelist_id and int(data_pricelist_id)
pricelist = self.env['product.pricelist'].browse(pricelist_id).exists()
if not pricelist:
pricelist = self.env['product.pricelist'].search([], limit=1)
active_model = data.get('active_model', 'product.template')
active_ids = data.get('active_ids') or []
is_product_tmpl = active_model == 'product.template'
ProductClass = self.env[active_model]
products = ProductClass.browse(active_ids) if active_ids else ProductClass.search([('sale_ok', '=', True)])
products_data = [
self._get_product_data(is_product_tmpl, product, pricelist, quantities)
for product in products
]
return {
'is_html_type': report_type == 'html',
'is_product_tmpl': is_product_tmpl,
'is_visible_title': data.get('is_visible_title', False) and bool(data['is_visible_title']),
'pricelist': pricelist,
'products': products_data,
'quantities': quantities,
}
def _get_product_data(self, is_product_tmpl, product, pricelist, quantities):
data = {
'id': product.id,
'name': is_product_tmpl and product.name or product.display_name,
'price': dict.fromkeys(quantities, 0.0),
'uom': product.uom_id.name,
}
for qty in quantities:
data['price'][qty] = pricelist.get_product_price(product, qty, False)
if is_product_tmpl and product.product_variant_count > 1:
data['variants'] = [
self._get_product_data(False, variant, pricelist, quantities)
for variant in product.product_variant_ids
]
return data
| 39.140625
| 2,505
|
2,349
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import _, models
from odoo.exceptions import UserError
def _prepare_data(env, data):
# change product ids by actual product object to get access to fields in xml template
# we needed to pass ids because reports only accepts native python types (int, float, strings, ...)
if data.get('active_model') == 'product.template':
Product = env['product.template'].with_context(display_default_code=False)
elif data.get('active_model') == 'product.product':
Product = env['product.product'].with_context(display_default_code=False)
else:
raise UserError(_('Product model not defined, Please contact your administrator.'))
total = 0
quantity_by_product = defaultdict(list)
for p, q in data.get('quantity_by_product').items():
product = Product.browse(int(p))
quantity_by_product[product].append((product.barcode, q))
total += q
if data.get('custom_barcodes'):
# we expect custom barcodes format as: {product: [(barcode, qty_of_barcode)]}
for product, barcodes_qtys in data.get('custom_barcodes').items():
quantity_by_product[Product.browse(int(product))] += (barcodes_qtys)
total += sum(qty for _, qty in barcodes_qtys)
layout_wizard = env['product.label.layout'].browse(data.get('layout_wizard'))
if not layout_wizard:
return {}
return {
'quantity': quantity_by_product,
'rows': layout_wizard.rows,
'columns': layout_wizard.columns,
'page_numbers': (total - 1) // (layout_wizard.rows * layout_wizard.columns) + 1,
'price_included': data.get('price_included'),
'extra_html': layout_wizard.extra_html,
}
class ReportProductTemplateLabel(models.AbstractModel):
_name = 'report.product.report_producttemplatelabel'
_description = 'Product Label Report'
def _get_report_values(self, docids, data):
return _prepare_data(self.env, data)
class ReportProductTemplateLabelDymo(models.AbstractModel):
_name = 'report.product.report_producttemplatelabel_dymo'
_description = 'Product Label Report'
def _get_report_values(self, docids, data):
return _prepare_data(self.env, data)
| 41.946429
| 2,349
|
647
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Website Partner',
'category': 'Hidden',
'summary': 'Partner module for website',
'version': '0.1',
'description': """
This is a base module. It holds website-related stuff for Contact model (res.partner).
""",
'depends': ['website'],
'data': [
'views/res_partner_views.xml',
'views/website_partner_templates.xml',
'data/website_partner_data.xml',
],
'demo': ['data/website_partner_demo.xml'],
'installable': True,
'auto_install': False,
'license': 'LGPL-3',
}
| 29.409091
| 647
|
698
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models
from odoo.addons.http_routing.models.ir_http import slug
from odoo.tools.translate import html_translate
class WebsiteResPartner(models.Model):
_name = 'res.partner'
_inherit = ['res.partner', 'website.seo.metadata']
website_description = fields.Html('Website Partner Full Description', strip_style=True, translate=html_translate)
website_short_description = fields.Text('Website Partner Short Description', translate=True)
def _compute_website_url(self):
super(WebsiteResPartner, self)._compute_website_url()
for partner in self:
partner.website_url = "/partners/%s" % slug(partner)
| 38.777778
| 698
|
1,017
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import http
from odoo.addons.http_routing.models.ir_http import unslug
from odoo.http import request
class WebsitePartnerPage(http.Controller):
# Do not use semantic controller due to SUPERUSER_ID
@http.route(['/partners/<partner_id>'], type='http', auth="public", website=True)
def partners_detail(self, partner_id, **post):
_, partner_id = unslug(partner_id)
if partner_id:
partner_sudo = request.env['res.partner'].sudo().browse(partner_id)
is_website_publisher = request.env['res.users'].has_group('website.group_website_publisher')
if partner_sudo.exists() and (partner_sudo.website_published or is_website_publisher):
values = {
'main_object': partner_sudo,
'partner': partner_sudo,
'edit_page': False
}
return request.render("website_partner.partner_page", values)
return request.not_found()
| 42.375
| 1,017
|
1,944
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2011 Thamini S.à.R.L (<http://www.thamini.com>)
# Copyright (C) 2011 ADN Consultants S.à.R.L (<http://www.adn-luxembourg.com>)
# Copyright (C) 2014 ACSONE SA/NV (<http://acsone.eu>)
{
'name': 'Luxembourg - Accounting',
'version': '2.1',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the base module to manage the accounting chart for Luxembourg.
======================================================================
* the Luxembourg Official Chart of Accounts (law of June 2009 + 2015 chart and Taxes),
* the Tax Code Chart for Luxembourg
* the main taxes used in Luxembourg
* default fiscal position for local, intracom, extracom
Notes:
* the 2015 chart of taxes is implemented to a large extent,
see the first sheet of tax.xls for details of coverage
* to update the chart of tax template, update tax.xls and run tax2csv.py
""",
'author': 'OpenERP SA, ADN, ACSONE SA/NV',
'depends': [
'account',
'base_iban',
'base_vat',
'l10n_multilang',
],
'data': [
# basic accounting data
'data/l10n_lu_chart_data.xml',
'data/account.account.template.csv',
'data/account.group.template.csv',
'data/account_tax_report_line.xml',
'data/account.tax.group.csv',
'data/account_tax_template_2015.xml',
'data/account.fiscal.position.template-2011.csv',
'data/account.fiscal.position.tax.template-2015.csv',
'data/account_reconcile_model_template_data.xml',
# configuration wizard, views, reports...
'data/account.chart.template.csv',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'post_init_hook': '_post_init_hook',
'license': 'LGPL-3',
}
| 36.641509
| 1,942
|
248
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
update_taxes_from_templates(cr, 'l10n_lu.lu_2011_chart_1')
| 41.333333
| 248
|
685
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
@api.model
def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):
journal_data = super(AccountChartTemplate, self)._prepare_all_journals(
acc_template_ref, company, journals_dict)
for journal in journal_data:
if journal['type'] in ('sale', 'purchase') and company.account_fiscal_country_id.code == "LU":
journal.update({'refund_sequence': True})
return journal_data
| 40.294118
| 685
|
7,727
|
py
|
PYTHON
|
15.0
|
from collections import OrderedDict
import xlrd
from odoo.tools import pycompat
def _is_true(s):
return s not in ('F', 'False', 0, '', None, False)
class LuxTaxGenerator:
def __init__(self, filename):
self.workbook = xlrd.open_workbook('tax.xls')
self.sheet_info = \
self.workbook.sheet_by_name('INFO')
self.sheet_taxes = \
self.workbook.sheet_by_name('TAXES')
self.sheet_tax_codes = \
self.workbook.sheet_by_name('TAX.CODES')
self.sheet_fiscal_pos_map = \
self.workbook.sheet_by_name('FISCAL.POSITION.MAPPINGS')
self.suffix = self.sheet_info.cell_value(4, 2)
def iter_tax_codes(self):
keys = [c.value for c in self.sheet_tax_codes.row(0)]
yield keys
for i in range(1, self.sheet_tax_codes.nrows):
row = (c.value for c in self.sheet_tax_codes.row(i))
d = OrderedDict(zip(keys, row))
d['sign'] = int(d['sign'])
d['sequence'] = int(d['sequence'])
yield d
def iter_taxes(self):
keys = [c.value for c in self.sheet_taxes.row(0)]
yield keys
for i in range(1, self.sheet_taxes.nrows):
row = (c.value for c in self.sheet_taxes.row(i))
yield OrderedDict(zip(keys, row))
def iter_fiscal_pos_map(self):
keys = [c.value for c in self.sheet_fiscal_pos_map.row(0)]
yield keys
for i in range(1, self.sheet_fiscal_pos_map.nrows):
row = (c.value for c in self.sheet_fiscal_pos_map.row(i))
yield OrderedDict(zip(keys, row))
def tax_codes_to_csv(self):
writer = pycompat.csv_writer(open('account.tax.code.template-%s.csv' %
self.suffix, 'wb'))
tax_codes_iterator = self.iter_tax_codes()
keys = next(tax_codes_iterator)
writer.writerow(keys)
# write structure tax codes
tax_codes = {} # code: id
for row in tax_codes_iterator:
tax_code = row['code']
if tax_code in tax_codes:
raise RuntimeError('duplicate tax code %s' % tax_code)
tax_codes[tax_code] = row['id']
writer.writerow([pycompat.to_text(v) for v in row.values()])
# read taxes and add leaf tax codes
new_tax_codes = {} # id: parent_code
def add_new_tax_code(tax_code_id, new_name, new_parent_code):
if not tax_code_id:
return
name, parent_code = new_tax_codes.get(tax_code_id, (None, None))
if parent_code and parent_code != new_parent_code:
raise RuntimeError('tax code "%s" already exist with '
'parent %s while trying to add it with '
'parent %s' %
(tax_code_id, parent_code, new_parent_code))
else:
new_tax_codes[tax_code_id] = (new_name, new_parent_code)
taxes_iterator = self.iter_taxes()
next(taxes_iterator)
for row in taxes_iterator:
if not _is_true(row['active']):
continue
if row['child_depend'] and row['amount'] != 1:
raise RuntimeError('amount must be one if child_depend '
'for %s' % row['id'])
# base parent
base_code = row['BASE_CODE']
if not base_code or base_code == '/':
base_code = 'NA'
if base_code not in tax_codes:
raise RuntimeError('undefined tax code %s' % base_code)
if base_code != 'NA':
if row['child_depend']:
raise RuntimeError('base code specified '
'with child_depend for %s' % row['id'])
if not row['child_depend']:
# ... in lux, we have the same code for invoice and refund
if base_code != 'NA':
assert row['base_code_id:id'], 'missing base_code_id for %s' % row['id']
assert row['ref_base_code_id:id'] == row['base_code_id:id']
add_new_tax_code(row['base_code_id:id'],
'Base - ' + row['name'],
base_code)
# tax parent
tax_code = row['TAX_CODE']
if not tax_code or tax_code == '/':
tax_code = 'NA'
if tax_code not in tax_codes:
raise RuntimeError('undefined tax code %s' % tax_code)
if tax_code == 'NA':
if row['amount'] and not row['child_depend']:
raise RuntimeError('TAX_CODE not specified '
'for non-zero tax %s' % row['id'])
if row['tax_code_id:id']:
raise RuntimeError('tax_code_id specified '
'for tax %s' % row['id'])
else:
if row['child_depend']:
raise RuntimeError('TAX_CODE specified '
'with child_depend for %s' % row['id'])
if not row['amount']:
raise RuntimeError('TAX_CODE specified '
'for zero tax %s' % row['id'])
if not row['tax_code_id:id']:
raise RuntimeError('tax_code_id not specified '
'for tax %s' % row['id'])
if not row['child_depend'] and row['amount']:
# ... in lux, we have the same code for invoice and refund
assert row['tax_code_id:id'], 'missing tax_code_id for %s' % row['id']
assert row['ref_tax_code_id:id'] == row['tax_code_id:id']
add_new_tax_code(row['tax_code_id:id'],
'Taxe - ' + row['name'],
tax_code)
for tax_code_id in sorted(new_tax_codes):
name, parent_code = new_tax_codes[tax_code_id]
writer.writerow([
tax_code_id,
u'lu_tct_m' + parent_code,
tax_code_id.replace('lu_tax_code_template_', u''),
u'1',
u'',
pycompat.to_text(name),
u''
])
def taxes_to_csv(self):
writer = pycompat.csv_writer(open('account.tax.template-%s.csv' %
self.suffix, 'wb'))
taxes_iterator = self.iter_taxes()
keys = next(taxes_iterator)
writer.writerow(keys[3:] + ['sequence'])
seq = 100
for row in sorted(taxes_iterator, key=lambda r: r['description']):
if not _is_true(row['active']):
continue
seq += 1
if row['parent_id:id']:
cur_seq = seq + 1000
else:
cur_seq = seq
writer.writerow([
pycompat.to_text(v)
for v in list(row.values())[3:]
] + [cur_seq])
def fiscal_pos_map_to_csv(self):
writer = pycompat.csv_writer(open('account.fiscal.'
'position.tax.template-%s.csv' %
self.suffix, 'wb'))
fiscal_pos_map_iterator = self.iter_fiscal_pos_map()
keys = next(fiscal_pos_map_iterator)
writer.writerow(keys)
for row in fiscal_pos_map_iterator:
writer.writerow([pycompat.to_text(s) for s in row.values()])
if __name__ == '__main__':
o = LuxTaxGenerator('tax.xls')
o.tax_codes_to_csv()
o.taxes_to_csv()
o.fiscal_pos_map_to_csv()
| 42.224044
| 7,727
|
671
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Netherlands - E-Invoicing (NLCIUS 1.0.3)',
'icon': '/l10n_nl/static/description/icon.png',
'version': '0.1',
'category': 'Accounting/Localizations/EDI',
'summary': 'E-Invoicing, Universal Business Language (NLCIUS 1.0.3), nlc',
'description': """
NLCIUS is the Dutch implementation of EN 16931 norm. Both for UBL and UN / CEFACT XML CII.
""",
'depends': ['l10n_nl', 'account_edi_ubl_bis3'],
'data': [
'data/account_edi_data.xml',
'data/nlcius_template.xml',
],
'post_init_hook': '_post_init_hook',
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 33.55
| 671
|
11,195
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account_edi.tests.common import AccountEdiTestCommon
from odoo.tests import tagged
from freezegun import freeze_time
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestUBL(AccountEdiTestCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_nl.l10nnl_chart_template', edi_format_ref='l10n_nl_edi.edi_nlcius_1'):
super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref)
if cls.env['ir.module.module'].search(
[('name', '=', 'account_edi_ubl_cii'), ('state', '=', 'installed')],
limit=1,
):
cls.skipTest(cls, "NLCIUS Tests skipped because account_edi_ubl_cii is installed.")
cls.company_data['company'].partner_id.write({
'street': 'Archefstraat 42',
'zip': '1000',
'city': 'Amsterdam',
'country_id': cls.env.ref('base.nl').id,
'l10n_nl_kvk': '82777822',
'vat': 'NL000099998B57',
})
cls.partner_a.write({
'l10n_nl_kvk': '77777677',
'country_id': cls.env.ref('base.be').id,
'vat': 'BE0477472701',
})
bank_account = cls.env['res.partner.bank'].create({
'acc_number': 'BE93999574162167',
'partner_id': cls.partner_a.id,
})
cls.tax_sale_b.write({
'amount': 15
})
cls.invoice = cls.env['account.move'].create({
'partner_id': cls.partner_a.id,
'move_type': 'out_invoice',
'partner_bank_id': bank_account.id,
'invoice_date_due': '2020-12-16',
'invoice_line_ids': [
(0, 0, {
'product_id': cls.product_a.id,
'quantity': 150,
'price_unit': 250,
'discount': 10,
'tax_ids': [(6, 0, cls.tax_sale_a.ids)],
}),
(0, 0, {
'product_id': cls.product_b.id,
'quantity': 12,
'price_unit': 100,
'tax_ids': [(6, 0, cls.tax_sale_b.ids)],
}),
]
})
cls.expected_invoice_values = '''
<Invoice xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2">
<cbc:CustomizationID>urn:cen.eu:en16931:2017#compliant#urn:fdc:nen.nl:nlcius:v1.0</cbc:CustomizationID>
<cbc:ProfileID>urn:fdc:peppol.eu:2017:poacc:billing:01:1.0</cbc:ProfileID>
<cbc:ID>INV/2020/00001</cbc:ID>
<cbc:IssueDate>2020-12-16</cbc:IssueDate>
<cbc:DueDate>2020-12-16</cbc:DueDate>
<cbc:InvoiceTypeCode>380</cbc:InvoiceTypeCode>
<cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode>
<cbc:BuyerReference>partner_a</cbc:BuyerReference>
<cac:AccountingSupplierParty>
<cac:Party>
<cbc:EndpointID schemeID="0106">82777822</cbc:EndpointID>
<cac:PartyIdentification>
<cbc:ID>82777822</cbc:ID>
</cac:PartyIdentification>
<cac:PartyName>
<cbc:Name>company_1_data</cbc:Name>
</cac:PartyName>
<cac:PostalAddress>
<cbc:StreetName>Archefstraat 42</cbc:StreetName>
<cbc:CityName>Amsterdam</cbc:CityName>
<cbc:PostalZone>1000</cbc:PostalZone>
<cac:Country>
<cbc:IdentificationCode>NL</cbc:IdentificationCode>
</cac:Country>
</cac:PostalAddress>
<cac:PartyTaxScheme>
<cbc:CompanyID>NL000099998B57</cbc:CompanyID>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:PartyTaxScheme>
<cac:PartyLegalEntity>
<cbc:RegistrationName>company_1_data</cbc:RegistrationName>
<cbc:CompanyID schemeID="0106">82777822</cbc:CompanyID>
</cac:PartyLegalEntity>
<cac:Contact>
<cbc:Name>company_1_data</cbc:Name>
</cac:Contact>
</cac:Party>
</cac:AccountingSupplierParty>
<cac:AccountingCustomerParty>
<cac:Party>
<cbc:EndpointID schemeID="9925">BE0477472701</cbc:EndpointID>
<cac:PartyName>
<cbc:Name>partner_a</cbc:Name>
</cac:PartyName>
<cac:PostalAddress>
<cac:Country>
<cbc:IdentificationCode>BE</cbc:IdentificationCode>
</cac:Country>
</cac:PostalAddress>
<cac:PartyTaxScheme>
<cbc:CompanyID>BE0477472701</cbc:CompanyID>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:PartyTaxScheme>
<cac:PartyLegalEntity>
<cbc:RegistrationName>partner_a</cbc:RegistrationName>
</cac:PartyLegalEntity>
<cac:Contact>
<cbc:Name>partner_a</cbc:Name>
</cac:Contact>
</cac:Party>
</cac:AccountingCustomerParty>
<cac:PaymentMeans>
<cbc:PaymentMeansCode>30</cbc:PaymentMeansCode>
<cac:PayeeFinancialAccount>
<cbc:ID>BE93 9995 7416 2167</cbc:ID>
</cac:PayeeFinancialAccount>
</cac:PaymentMeans>
<cac:TaxTotal>
<cbc:TaxAmount currencyID="EUR">7267.50</cbc:TaxAmount>
<cac:TaxSubtotal>
<cbc:TaxableAmount currencyID="EUR">33750.00</cbc:TaxableAmount>
<cbc:TaxAmount currencyID="EUR">7087.50</cbc:TaxAmount>
<cac:TaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>21.0</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:TaxCategory>
</cac:TaxSubtotal>
<cac:TaxSubtotal>
<cbc:TaxableAmount currencyID="EUR">1200.00</cbc:TaxableAmount>
<cbc:TaxAmount currencyID="EUR">180.00</cbc:TaxAmount>
<cac:TaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>15.0</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:TaxCategory>
</cac:TaxSubtotal>
</cac:TaxTotal>
<cac:LegalMonetaryTotal>
<cbc:LineExtensionAmount currencyID="EUR">34950.00</cbc:LineExtensionAmount>
<cbc:TaxExclusiveAmount currencyID="EUR">34950.00</cbc:TaxExclusiveAmount>
<cbc:TaxInclusiveAmount currencyID="EUR">42217.50</cbc:TaxInclusiveAmount>
<cbc:PrepaidAmount currencyID="EUR">0.00</cbc:PrepaidAmount>
<cbc:PayableAmount currencyID="EUR">42217.50</cbc:PayableAmount>
</cac:LegalMonetaryTotal>
<cac:InvoiceLine>
<cbc:ID>1</cbc:ID>
<cbc:Note>Discount (10.0 %)</cbc:Note>
<cbc:InvoicedQuantity unitCode="ZZ">150.0</cbc:InvoicedQuantity>
<cbc:LineExtensionAmount currencyID="EUR">33750.00</cbc:LineExtensionAmount>
<cac:Item>
<cbc:Description>product_a</cbc:Description>
<cbc:Name>product_a</cbc:Name>
<cac:ClassifiedTaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>21.0</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:ClassifiedTaxCategory>
</cac:Item>
<cac:Price>
<cbc:PriceAmount currencyID="EUR">225.00</cbc:PriceAmount>
<cbc:BaseQuantity>150.0</cbc:BaseQuantity>
</cac:Price>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>2</cbc:ID>
<cbc:InvoicedQuantity unitCode="ZZ">12.0</cbc:InvoicedQuantity>
<cbc:LineExtensionAmount currencyID="EUR">1200.00</cbc:LineExtensionAmount>
<cac:Item>
<cbc:Description>product_b</cbc:Description>
<cbc:Name>product_b</cbc:Name>
<cac:ClassifiedTaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>15.0</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:ClassifiedTaxCategory>
</cac:Item>
<cac:Price>
<cbc:PriceAmount currencyID="EUR">100.00</cbc:PriceAmount>
<cbc:BaseQuantity>12.0</cbc:BaseQuantity>
</cac:Price>
</cac:InvoiceLine>
</Invoice>
'''
def test_nlcius_import(self):
invoice = self.env['account.move'].with_context(default_move_type='in_invoice').create({})
invoice_count = len(self.env['account.move'].search([]))
self.update_invoice_from_file('l10n_nl_edi', 'test_xml_file', 'nlcius_test.xml', invoice)
self.assertEqual(len(self.env['account.move'].search([])), invoice_count)
self.assertEqual(invoice.amount_total, 387.2)
self.assertEqual(invoice.amount_tax, 67.2)
self.assertEqual(invoice.partner_id, self.partner_a)
@freeze_time('2020-12-16')
def test_nlcius_export(self):
self.assert_generated_file_equal(self.invoice, self.expected_invoice_values)
| 49.317181
| 11,195
|
7,058
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import markupsafe
from odoo.addons.account_edi_ubl_bis3.models.account_edi_format import COUNTRY_EAS
from odoo import models, _
class AccountEdiFormat(models.Model):
_inherit = 'account.edi.format'
####################################################
# Import
####################################################
def _is_ubl(self, filename, tree):
""" OVERRIDE so that the generic ubl parser does not parse BIS3 any longer.
"""
is_ubl = super()._is_ubl(filename, tree)
return is_ubl and not self._is_nlcius(filename, tree)
def _is_nlcius(self, filename, tree):
profile_id = tree.find('./{*}ProfileID')
customization_id = tree.find('./{*}CustomizationID')
return tree.tag == '{urn:oasis:names:specification:ubl:schema:xsd:Invoice-2}Invoice' and \
profile_id is not None and 'peppol' in profile_id.text and \
customization_id is not None and 'nlcius' in customization_id.text
def _bis3_get_extra_partner_domains(self, tree):
if self.code == 'nlcius_1':
endpoint = tree.find('./{*}AccountingSupplierParty/{*}Party/{*}EndpointID')
if endpoint is not None:
scheme = endpoint.attrib['schemeID']
if scheme == '0106' and endpoint.text:
return [('l10n_nl_kvk', '=', endpoint.text)]
elif scheme == '0190' and endpoint.text:
return [('l10n_nl_oin', '=', endpoint.text)]
return super()._bis3_get_extra_partner_domains(tree)
####################################################
# Export
####################################################
def _get_nlcius_values(self, invoice):
values = super()._get_bis3_values(invoice)
values.update({
'customization_id': 'urn:cen.eu:en16931:2017#compliant#urn:fdc:nen.nl:nlcius:v1.0',
'payment_means_code': 30,
})
for partner_vals in (values['customer_vals'], values['supplier_vals']):
partner = partner_vals['partner']
endpoint = partner.l10n_nl_oin or partner.l10n_nl_kvk
if partner.country_code == 'NL' and endpoint:
scheme = '0190' if partner.l10n_nl_oin else '0106'
partner_vals.update({
'bis3_endpoint': endpoint,
'bis3_endpoint_scheme': scheme,
'legal_entity': endpoint,
'legal_entity_scheme': scheme,
'partner_identification': endpoint,
})
return values
def _export_nlcius(self, invoice):
self.ensure_one()
# Create file content.
xml_content = markupsafe.Markup("<?xml version='1.0' encoding='UTF-8'?>")
xml_content += self.env.ref('l10n_nl_edi.export_nlcius_invoice')._render(self._get_nlcius_values(invoice))
vat = invoice.company_id.partner_id.commercial_partner_id.vat
xml_name = 'nlcius-%s%s%s.xml' % (vat or '', '-' if vat else '', invoice.name.replace('/', '_'))
return self.env['ir.attachment'].create({
'name': xml_name,
'raw': xml_content.encode(),
'res_model': 'account.move',
'res_id': invoice.id,
'mimetype': 'application/xml'
})
####################################################
# Account.edi.format override
####################################################
def _check_move_configuration(self, invoice):
errors = super()._check_move_configuration(invoice)
if self.code != 'nlcius_1' or self._is_account_edi_ubl_cii_available():
return errors
supplier = invoice.company_id.partner_id.commercial_partner_id
if not supplier.street or not supplier.zip or not supplier.city:
errors.append(_("The supplier's address must include street, zip and city (%s).", supplier.display_name))
if supplier.country_code == 'NL' and not supplier.l10n_nl_kvk and not supplier.l10n_nl_oin:
errors.append(_("The supplier %s must have a KvK-nummer or OIN.", supplier.display_name))
if not supplier.vat:
errors.append(_("Please define a VAT number for '%s'.", supplier.display_name))
customer = invoice.commercial_partner_id
if customer.country_code == 'NL' and (not customer.street or not customer.zip or not customer.city):
errors.append(_("Customer's address must include street, zip and city (%s).", customer.display_name))
if customer.country_code == 'NL' and not customer.l10n_nl_kvk and not customer.l10n_nl_oin:
errors.append(_("The customer %s must have a KvK-nummer or OIN.", customer.display_name))
if not invoice.partner_bank_id:
errors.append(_("The supplier %s must have a bank account.", supplier.display_name))
if invoice.invoice_line_ids.filtered(lambda l: not (l.product_id.name or l.name)):
errors.append(_('Each invoice line must have a product or a label.'))
if invoice.invoice_line_ids.tax_ids.invoice_repartition_line_ids.filtered(lambda r: r.use_in_tax_closing) and \
not supplier.vat:
errors.append(_("When vat is present, the supplier must have a vat number."))
return errors
def _is_compatible_with_journal(self, journal):
self.ensure_one()
if self.code != 'nlcius_1' or self._is_account_edi_ubl_cii_available():
return super()._is_compatible_with_journal(journal)
return journal.type == 'sale' and journal.country_code == 'NL'
def _post_invoice_edi(self, invoices):
self.ensure_one()
if self.code != 'nlcius_1' or self._is_account_edi_ubl_cii_available():
return super()._post_invoice_edi(invoices)
invoice = invoices # no batch ensure that there is only one invoice
attachment = self._export_nlcius(invoice)
return {invoice: {'success': True, 'attachment': attachment}}
def _create_invoice_from_xml_tree(self, filename, tree, journal=None):
self.ensure_one()
if self.code == 'nlcius_1' and self._is_nlcius(filename, tree) and not self._is_account_edi_ubl_cii_available():
return self._decode_bis3(tree, self.env['account.move'])
return super()._create_invoice_from_xml_tree(filename, tree, journal=journal)
def _update_invoice_from_xml_tree(self, filename, tree, invoice):
self.ensure_one()
if self.code == 'nlcius_1' and self._is_nlcius(filename, tree) and not self._is_account_edi_ubl_cii_available():
return self._decode_bis3(tree, invoice)
return super()._update_invoice_from_xml_tree(filename, tree, invoice)
def _is_required_for_invoice(self, invoice):
self.ensure_one()
if self.code != 'nlcius_1' or self._is_account_edi_ubl_cii_available():
return super()._is_required_for_invoice(invoice)
return invoice.commercial_partner_id.country_code in COUNTRY_EAS
| 47.053333
| 7,058
|
2,564
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Task Logs',
'version': '1.0',
'category': 'Services/Timesheets',
'sequence': 23,
'summary': 'Track employee time on tasks',
'description': """
This module implements a timesheet system.
==========================================
Each employee can encode and track their time spent on the different projects.
Lots of reporting on time and employee tracking are provided.
It is completely integrated with the cost accounting module. It allows you to set
up a management by affair.
""",
'website': 'https://www.odoo.com/app/timesheet',
'depends': ['hr', 'analytic', 'project', 'uom'],
'data': [
'security/hr_timesheet_security.xml',
'security/ir.model.access.csv',
'security/ir.model.access.xml',
'data/digest_data.xml',
'views/hr_timesheet_views.xml',
'views/res_config_settings_views.xml',
'views/project_views.xml',
'views/project_portal_templates.xml',
'views/hr_timesheet_portal_templates.xml',
'report/hr_timesheet_report_view.xml',
'report/project_report_view.xml',
'report/report_timesheet_templates.xml',
'views/hr_views.xml',
'data/hr_timesheet_data.xml',
'wizard/project_task_create_timesheet_views.xml',
'views/project_sharing_views.xml',
],
'demo': [
'data/hr_timesheet_demo.xml',
],
'installable': True,
'application': False,
'auto_install': False,
'post_init_hook': 'create_internal_project',
'uninstall_hook': '_uninstall_hook',
'assets': {
'web.assets_backend': [
'hr_timesheet/static/src/scss/timesheets_task_form.scss',
'hr_timesheet/static/src/js/task_with_hours.js',
'hr_timesheet/static/src/js/timesheet_uom.js',
'hr_timesheet/static/src/js/timesheet_factor.js',
'hr_timesheet/static/src/js/timesheet_config_form_view.js',
'hr_timesheet/static/src/js/qr_code_action.js',
'hr_timesheet/static/src/js/timesheet_graph_view.js',
'hr_timesheet/static/src/js/timesheet_graph_model.js',
],
"web.assets_backend_legacy_lazy": [
'hr_timesheet/static/src/js/*_legacy.js',
],
'web.qunit_suite_tests': [
'hr_timesheet/static/tests/**/*',
],
'web.assets_qweb': [
'hr_timesheet/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 35.611111
| 2,564
|
26,202
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase, Form
from odoo.exceptions import AccessError, UserError
class TestCommonTimesheet(TransactionCase):
def setUp(self):
super(TestCommonTimesheet, self).setUp()
# Crappy hack to disable the rule from timesheet grid, if it exists
# The registry doesn't contain the field timesheet_manager_id.
# but there is an ir.rule about it, crashing during its evaluation
rule = self.env.ref('timesheet_grid.hr_timesheet_rule_approver_update', raise_if_not_found=False)
if rule:
rule.active = False
# customer partner
self.partner = self.env['res.partner'].create({
'name': 'Customer Task',
'email': 'customer@task.com',
'phone': '42',
})
self.analytic_account = self.env['account.analytic.account'].create({
'name': 'Analytic Account for Test Customer',
'partner_id': self.partner.id,
'code': 'TEST'
})
# project and tasks
self.project_customer = self.env['project.project'].create({
'name': 'Project X',
'allow_timesheets': True,
'partner_id': self.partner.id,
'analytic_account_id': self.analytic_account.id,
})
self.task1 = self.env['project.task'].create({
'name': 'Task One',
'priority': '0',
'kanban_state': 'normal',
'project_id': self.project_customer.id,
'partner_id': self.partner.id,
})
self.task2 = self.env['project.task'].create({
'name': 'Task Two',
'priority': '1',
'kanban_state': 'done',
'project_id': self.project_customer.id,
})
# users
self.user_employee = self.env['res.users'].create({
'name': 'User Employee',
'login': 'user_employee',
'email': 'useremployee@test.com',
'groups_id': [(6, 0, [self.ref('hr_timesheet.group_hr_timesheet_user')])],
})
self.user_employee2 = self.env['res.users'].create({
'name': 'User Employee 2',
'login': 'user_employee2',
'email': 'useremployee2@test.com',
'groups_id': [(6, 0, [self.ref('hr_timesheet.group_hr_timesheet_user')])],
})
self.user_manager = self.env['res.users'].create({
'name': 'User Officer',
'login': 'user_manager',
'email': 'usermanager@test.com',
'groups_id': [(6, 0, [self.ref('hr_timesheet.group_timesheet_manager')])],
})
# employees
self.empl_employee = self.env['hr.employee'].create({
'name': 'User Empl Employee',
'user_id': self.user_employee.id,
})
self.empl_employee2 = self.env['hr.employee'].create({
'name': 'User Empl Employee 2',
'user_id': self.user_employee2.id,
})
self.empl_manager = self.env['hr.employee'].create({
'name': 'User Empl Officer',
'user_id': self.user_manager.id,
})
class TestTimesheet(TestCommonTimesheet):
def setUp(self):
super(TestTimesheet, self).setUp()
# Crappy hack to disable the rule from timesheet grid, if it exists
# The registry doesn't contain the field timesheet_manager_id.
# but there is an ir.rule about it, crashing during its evaluation
rule = self.env.ref('timesheet_grid.timesheet_line_rule_user_update-unlink', raise_if_not_found=False)
if rule:
rule.active = False
def test_log_timesheet(self):
""" Test when log timesheet : check analytic account, user and employee are correctly set. """
Timesheet = self.env['account.analytic.line']
timesheet_uom = self.project_customer.analytic_account_id.company_id.project_time_mode_id
# employee 1 log some timesheet on task 1
timesheet1 = Timesheet.with_user(self.user_employee).create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'my first timesheet',
'unit_amount': 4,
})
self.assertEqual(timesheet1.account_id, self.project_customer.analytic_account_id, 'Analytic account should be the same as the project')
self.assertEqual(timesheet1.employee_id, self.empl_employee, 'Employee should be the one of the current user')
self.assertEqual(timesheet1.partner_id, self.task1.partner_id, 'Customer of task should be the same of the one set on new timesheet')
self.assertEqual(timesheet1.product_uom_id, timesheet_uom, "The UoM of the timesheet should be the one set on the company of the analytic account.")
# employee 1 cannot log timesheet for employee 2
with self.assertRaises(AccessError):
timesheet2 = Timesheet.with_user(self.user_employee).create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'a second timesheet but for employee 2',
'unit_amount': 3,
'employee_id': self.empl_employee2.id,
})
# manager log timesheet for employee 2
timesheet3 = Timesheet.with_user(self.user_manager).create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'a second timesheet but for employee 2',
'unit_amount': 7,
'employee_id': self.empl_employee2.id,
})
self.assertEqual(timesheet3.user_id, self.user_employee2, 'Timesheet user should be the one linked to the given employee')
self.assertEqual(timesheet3.product_uom_id, timesheet_uom, "The UoM of the timesheet 3 should be the one set on the company of the analytic account.")
# employee 1 log some timesheet on project (no task)
timesheet4 = Timesheet.with_user(self.user_employee).create({
'project_id': self.project_customer.id,
'name': 'my first timesheet',
'unit_amount': 4,
})
self.assertEqual(timesheet4.partner_id, self.project_customer.partner_id, 'Customer of new timesheet should be the same of the one set project (since no task on timesheet)')
def test_log_access_rights(self):
""" Test access rights : user can update its own timesheets only, and manager can change all """
# employee 1 log some timesheet on task 1
Timesheet = self.env['account.analytic.line']
timesheet1 = Timesheet.with_user(self.user_employee).create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'my first timesheet',
'unit_amount': 4,
})
# then employee 2 try to modify it
with self.assertRaises(AccessError):
timesheet1.with_user(self.user_employee2).write({
'name': 'i try to update this timesheet',
'unit_amount': 2,
})
# manager can modify all timesheet
timesheet1.with_user(self.user_manager).write({
'unit_amount': 8,
'employee_id': self.empl_employee2.id,
})
self.assertEqual(timesheet1.user_id, self.user_employee2, 'Changing timesheet employee should change the related user')
def test_create_unlink_project(self):
""" Check project creation, and if necessary the analytic account generated when project should track time. """
# create project wihtout tracking time, nor provide AA
non_tracked_project = self.env['project.project'].create({
'name': 'Project without timesheet',
'allow_timesheets': False,
'partner_id': self.partner.id,
})
self.assertFalse(non_tracked_project.analytic_account_id, "A non time-tracked project shouldn't generate an analytic account")
# create a project tracking time
tracked_project = self.env['project.project'].create({
'name': 'Project with timesheet',
'allow_timesheets': True,
'partner_id': self.partner.id,
})
self.assertTrue(tracked_project.analytic_account_id, "A time-tracked project should generate an analytic account")
self.assertTrue(tracked_project.analytic_account_id.active, "A time-tracked project should generate an active analytic account")
self.assertEqual(tracked_project.partner_id, tracked_project.analytic_account_id.partner_id, "The generated AA should have the same partner as the project")
self.assertEqual(tracked_project.name, tracked_project.analytic_account_id.name, "The generated AA should have the same name as the project")
self.assertEqual(tracked_project.analytic_account_id.project_count, 1, "The generated AA should be linked to the project")
# create a project without tracking time, but with analytic account
analytic_project = self.env['project.project'].create({
'name': 'Project without timesheet but with AA',
'allow_timesheets': True,
'partner_id': self.partner.id,
'analytic_account_id': tracked_project.analytic_account_id.id,
})
self.assertNotEqual(analytic_project.name, tracked_project.analytic_account_id.name, "The name of the associated AA can be different from the project")
self.assertEqual(tracked_project.analytic_account_id.project_count, 2, "The AA should be linked to 2 project")
# analytic linked to projects containing tasks can not be removed
task = self.env['project.task'].create({
'name': 'task in tracked project',
'project_id': tracked_project.id,
})
with self.assertRaises(UserError):
tracked_project.analytic_account_id.unlink()
# task can be removed, as there is no timesheet
task.unlink()
# since both projects linked to the same analytic account are empty (no task), it can be removed
tracked_project.analytic_account_id.unlink()
def test_transfert_project(self):
""" Transfert task with timesheet to another project. """
Timesheet = self.env['account.analytic.line']
# create nested subtasks
task_child = self.env['project.task'].create({
'name': 'Task Child',
'parent_id': self.task1.id,
})
task_grandchild = self.env['project.task'].create({
'name': 'Task Grandchild',
'parent_id': task_child.id,
})
# create a second project
self.project_customer2 = self.env['project.project'].create({
'name': 'Project NUMBER DEUX',
'allow_timesheets': True,
})
# employee 1 log some timesheet on task 1 and its subtasks
Timesheet.create([{
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'my first timesheet',
'unit_amount': 4,
'employee_id': self.empl_employee.id,
}, {
'project_id': self.project_customer.id,
'task_id': task_child.id,
'name': 'my second timesheet',
'unit_amount': 4,
'employee_id': self.empl_employee.id,
}, {
'project_id': self.project_customer.id,
'task_id': task_grandchild.id,
'name': 'my third timesheet',
'unit_amount': 4,
'employee_id': self.empl_employee.id,
}])
timesheet_count1 = Timesheet.search_count([('project_id', '=', self.project_customer.id)])
timesheet_count2 = Timesheet.search_count([('project_id', '=', self.project_customer2.id)])
self.assertEqual(timesheet_count1, 3, "3 timesheets should be linked to Project1")
self.assertEqual(timesheet_count2, 0, "No timesheets should be linked to Project2")
self.assertEqual(len(self.task1.timesheet_ids), 1, "The timesheet should be linked to task1")
self.assertEqual(len(task_child.timesheet_ids), 1, "The timesheet should be linked to task_child")
self.assertEqual(len(task_grandchild.timesheet_ids), 1, "The timesheet should be linked to task_grandchild")
# change project of task 1 from form to trigger onchange
with Form(self.task1) as task_form:
task_form.project_id = self.project_customer2
timesheet_count1 = Timesheet.search_count([('project_id', '=', self.project_customer.id)])
timesheet_count2 = Timesheet.search_count([('project_id', '=', self.project_customer2.id)])
self.assertEqual(timesheet_count1, 0, "There are still timesheets linked to Project1")
self.assertEqual(timesheet_count2, 3, "3 timesheets should be linked to Project2")
self.assertEqual(len(self.task1.timesheet_ids), 1, "The timesheet still should be linked to task1")
self.assertEqual(len(task_child.timesheet_ids), 1, "The timesheet still should be linked to task_child")
self.assertEqual(len(task_grandchild.timesheet_ids), 1, "The timesheet still should be linked to task_grandchild")
# it is forbidden to set a task with timesheet without project
with self.assertRaises(UserError):
self.task1.write({
'project_id': False
})
def test_recompute_amount_for_multiple_timesheets(self):
""" Check that amount is recomputed correctly when setting unit_amount for multiple timesheets at once. """
Timesheet = self.env['account.analytic.line']
self.empl_employee.timesheet_cost = 5.0
self.empl_employee2.timesheet_cost = 6.0
# create a timesheet for each employee
timesheet_1 = Timesheet.with_user(self.user_employee).create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': '/',
'unit_amount': 1,
})
timesheet_2 = Timesheet.with_user(self.user_employee2).create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': '/',
'unit_amount': 1,
})
timesheets = timesheet_1 + timesheet_2
with self.assertRaises(AccessError):
# should raise since employee 1 doesn't have the access rights to update employee's 2 timesheet
timesheets.with_user(self.empl_employee.user_id).write({
'unit_amount': 2,
})
timesheets.with_user(self.user_manager).write({
'unit_amount': 2,
})
# since timesheet costs are different for both employees, we should get different amounts
self.assertRecordValues(timesheets.with_user(self.user_manager), [{
'amount': -10.0,
}, {
'amount': -12.0,
}])
def test_recompute_partner_from_task_customer_change(self):
partner2 = self.env['res.partner'].create({
'name': 'Customer Task 2',
'email': 'customer2@task.com',
'phone': '43',
})
timesheet_entry = self.env['account.analytic.line'].create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'my only timesheet',
'unit_amount': 4,
})
self.assertEqual(timesheet_entry.partner_id, self.partner, "The timesheet entry's partner should be equal to the task's partner/customer")
self.task1.write({'partner_id': partner2})
self.assertEqual(timesheet_entry.partner_id, partner2, "The timesheet entry's partner should still be equal to the task's partner/customer, after the change")
def test_task_with_timesheet_project_change(self):
'''This test checks that no error is raised when moving a task that contains timesheet to another project.
This move implying writing on the account.analytic.line.
'''
project_manager = self.env['res.users'].create({
'name': 'user_project_manager',
'login': 'user_project_manager',
'groups_id': [(6, 0, [self.ref('project.group_project_manager')])],
})
project = self.env['project.project'].create({
'name': 'Project With Timesheets',
'privacy_visibility': 'employees',
'allow_timesheets': True,
'user_id': project_manager.id,
})
second_project = self.env['project.project'].create({
'name': 'Project w/ timesheets',
'privacy_visibility': 'employees',
'allow_timesheets': True,
'user_id': project_manager.id,
})
task_1 = self.env['project.task'].create({
'name': 'First task',
'user_ids': self.user_employee2,
'project_id': project.id
})
timesheet = self.env['account.analytic.line'].create({
'name': 'FirstTimeSheet',
'project_id': project.id,
'task_id': task_1.id,
'unit_amount': 2,
'employee_id': self.empl_employee2.id
})
task_1.with_user(project_manager).write({
'project_id': second_project.id
})
self.assertEqual(timesheet.project_id, second_project, 'The project_id of timesheet should be second_project')
def test_create_timesheet_employee_not_in_company(self):
''' ts.employee_id only if the user has an employee in the company or one employee for all companies.
'''
company_2 = self.env['res.company'].create({'name': 'Company 2'})
company_3 = self.env['res.company'].create({'name': 'Company 3'})
analytic_account = self.env['account.analytic.account'].create({
'name': 'Aa Aa',
'company_id': company_3.id,
})
project = self.env['project.project'].create({
'name': 'Aa Project',
'company_id': company_3.id,
'analytic_account_id': analytic_account.id,
})
task = self.env['project.task'].create({
'name': 'Aa Task',
'project_id': project.id,
})
Timesheet = self.env['account.analytic.line'].with_context(allowed_company_ids=[company_3.id, company_2.id, self.env.company.id])
timesheet = Timesheet.create({
'name': 'Timesheet',
'project_id': project.id,
'task_id': task.id,
'unit_amount': 2,
'user_id': self.user_manager.id,
'company_id': company_3.id,
})
self.assertEqual(timesheet.employee_id, self.user_manager.employee_id, 'As there is a unique employee for this user, it must be found')
self.env['hr.employee'].with_company(company_2).create({
'name': 'Employee 2',
'user_id': self.user_manager.id,
})
timesheet = Timesheet.create({
'name': 'Timesheet',
'project_id': project.id,
'task_id': task.id,
'unit_amount': 2,
'user_id': self.user_manager.id,
'company_id': company_3.id,
})
self.assertFalse(timesheet.employee_id, 'As there are several employees for this user, but none of them in this company, none must be found')
def test_ensure_product_uom_set_in_timesheet(self):
self.assertFalse(self.project_customer.timesheet_ids, 'No timesheet should be recorded in this project')
self.assertFalse(self.project_customer.total_timesheet_time, 'The total time recorded should be equal to 0 since no timesheet is recorded.')
timesheet1, timesheet2 = self.env['account.analytic.line'].create([
{'unit_amount': 1.0, 'project_id': self.project_customer.id},
{'unit_amount': 3.0, 'project_id': self.project_customer.id, 'product_uom_id': False},
])
self.assertEqual(
timesheet1.product_uom_id,
self.project_customer.analytic_account_id.company_id.timesheet_encode_uom_id,
'The default UoM set on the timesheet should be the one set on the company of AA.'
)
self.assertEqual(
timesheet2.product_uom_id,
self.project_customer.analytic_account_id.company_id.timesheet_encode_uom_id,
'Even if the product_uom_id field is empty in the vals, the product_uom_id should have a UoM by default,'
' otherwise the `total_timesheet_time` in project should not included the timesheet.'
)
self.assertEqual(self.project_customer.timesheet_ids, timesheet1 + timesheet2)
self.assertEqual(
self.project_customer.total_timesheet_time,
timesheet1.unit_amount + timesheet2.unit_amount,
'The total timesheet time of this project should be equal to 4.'
)
def test_create_timesheet_with_archived_employee(self):
''' the timesheet can be created or edited only with an active employee
'''
self.empl_employee2.active = False
batch_vals = {
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'archived employee timesheet',
'unit_amount': 3,
'employee_id': self.empl_employee2.id
}
self.assertRaises(UserError, self.env['account.analytic.line'].create, batch_vals)
batch_vals["employee_id"] = self.empl_employee.id
timesheet = self.env['account.analytic.line'].create(batch_vals)
with self.assertRaises(UserError):
timesheet.employee_id = self.empl_employee2
def test_remaining_hours_on_project(self):
''' Test the remaining hours on the project '''
self.task1.planned_hours = 4.0
self.assertEqual(self.project_customer.remaining_hours, 4.0, 'Remaining hours should be 4.0 before adding timesheet')
self.env['account.analytic.line'].create({
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'name': 'test',
'unit_amount': 2,
})
self.assertEqual(self.project_customer.remaining_hours, 2.0, 'Remaining hours should be 2.0 after adding timesheet')
task_child = self.env['project.task'].create({
'name': 'Task Child',
'parent_id': self.task1.id,
})
self.assertEqual(self.project_customer.remaining_hours, 2.0, 'Remaining hours should be 2.0 after adding a child task with no timesheets')
self.env['account.analytic.line'].create({
'project_id': self.project_customer.id,
'task_id': task_child.id,
'name': 'test',
'unit_amount': 2,
})
self.assertEqual(self.project_customer.remaining_hours, 0.0, 'Remaining hours should be 0.0 after adding timesheet to child task')
def test_check_timesheet_user(self):
""" Test Check whether the timesheet user is correct or not.
Part 1: Test Case:
----------
1) Create employee without user
2) Create timesheet
3) Check the user of the timesheet
Part 2: Test Case:
----------
3) Create a timesheet of the employee linked to the user
4) Check the user of the timesheet
"""
Timesheet = self.env['account.analytic.line']
emp_without_user = self.env['hr.employee'].create({
'name': 'Empl Employee',
})
without_user_timesheet = Timesheet.with_context(default_employee_id=emp_without_user.id).create({
'project_id': self.project_customer.id,
'unit_amount': 8.0,
})
self.assertFalse(without_user_timesheet.user_id, 'User is not set in timesheet.')
with_user_timesheet = Timesheet.with_context(default_employee_id=self.empl_employee.id).create({
'project_id': self.project_customer.id,
'unit_amount': 8.0,
})
self.assertEqual(with_user_timesheet.user_id, self.user_employee, 'User Employee is set in timesheet.')
def test_create_timesheet_with_companyless_analytic_account(self):
""" This test ensures that a timesheet can be created on an analytic account whose company_id is set to False"""
self.project_customer.analytic_account_id.company_id = False
timesheet = self.env['account.analytic.line'].with_user(self.user_employee).create(
{'unit_amount': 1.0, 'project_id': self.project_customer.id})
self.assertEqual(timesheet.product_uom_id, self.project_customer.company_id.project_time_mode_id,
"The product_uom_id of the timesheet should be equal to the project's company uom "
"if the project's analytic account has no company_id")
def test_percentage_of_planned_hours(self):
""" Test the percentage of planned hours on a task. """
self.task1.planned_hours = round(11/60, 2)
self.assertEqual(self.task1.effective_hours, 0, 'No timesheet should be created yet.')
self.assertEqual(self.task1.progress, 0, 'No timesheet should be created yet.')
self.env['account.analytic.line'].create([
{
'name': 'Timesheet',
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'unit_amount': 3/60,
'employee_id': self.empl_employee.id,
}, {
'name': 'Timesheet',
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'unit_amount': 4/60,
'employee_id': self.empl_employee.id,
}, {
'name': 'Timesheet',
'project_id': self.project_customer.id,
'task_id': self.task1.id,
'unit_amount': 4/60,
'employee_id': self.empl_employee.id,
},
])
self.assertEqual(self.task1.progress, 100, 'The percentage of planned hours should be 100%.')
| 46.293286
| 26,202
|
1,152
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ProjectTaskCreateTimesheet(models.TransientModel):
_name = 'project.task.create.timesheet'
_description = "Create Timesheet from task"
_sql_constraints = [('time_positive', 'CHECK(time_spent > 0)', 'The timesheet\'s time must be positive' )]
time_spent = fields.Float('Time', digits=(16, 2))
description = fields.Char('Description')
task_id = fields.Many2one(
'project.task', "Task", required=True,
default=lambda self: self.env.context.get('active_id', None),
help="Task for which we are creating a sales order",
)
def save_timesheet(self):
# Deprecated the method in hr_timesheet and overridden in timesheet_grid as config has moved to timesheet_grid.
# Move the whole wizard to timesheet_grid in master.
return self.env['account.analytic.line']
def action_delete_timesheet(self):
# Deprecated the method in hr_timesheet and overridden in timesheet_grid as timer mixin has moved to enterprise.
return True
| 41.142857
| 1,152
|
17,297
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from lxml import etree
import re
from odoo import api, Command, fields, models, _
from odoo.exceptions import UserError, AccessError
from odoo.osv import expression
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
@api.model
def default_get(self, field_list):
result = super(AccountAnalyticLine, self).default_get(field_list)
if 'encoding_uom_id' in field_list:
result['encoding_uom_id'] = self.env.company.timesheet_encode_uom_id.id
employee_id = self._context.get('default_employee_id')
if employee_id:
employee = self.env['hr.employee'].browse(employee_id)
if 'user_id' not in result or employee.user_id.id != result.get('user_id'):
result['user_id'] = employee.user_id.id
if not self.env.context.get('default_employee_id') and 'employee_id' in field_list and result.get('user_id'):
result['employee_id'] = self.env['hr.employee'].search([('user_id', '=', result['user_id']), ('company_id', '=', result.get('company_id', self.env.company.id))], limit=1).id
return result
def _domain_project_id(self):
domain = [('allow_timesheets', '=', True)]
if not self.user_has_groups('hr_timesheet.group_timesheet_manager'):
return expression.AND([domain,
['|', ('privacy_visibility', '!=', 'followers'), ('message_partner_ids', 'in', [self.env.user.partner_id.id])]
])
return domain
def _domain_employee_id(self):
if not self.user_has_groups('hr_timesheet.group_hr_timesheet_approver'):
return [('user_id', '=', self.env.user.id)]
return []
def _domain_task_id(self):
if not self.user_has_groups('hr_timesheet.group_hr_timesheet_approver'):
return ['|', ('privacy_visibility', '!=', 'followers'), ('message_partner_ids', 'in', [self.env.user.partner_id.id])]
return []
task_id = fields.Many2one(
'project.task', 'Task', compute='_compute_task_id', store=True, readonly=False, index=True,
domain="[('company_id', '=', company_id), ('project_id.allow_timesheets', '=', True), ('project_id', '=?', project_id)]")
project_id = fields.Many2one(
'project.project', 'Project', compute='_compute_project_id', store=True, readonly=False,
domain=_domain_project_id)
user_id = fields.Many2one(compute='_compute_user_id', store=True, readonly=False)
employee_id = fields.Many2one('hr.employee', "Employee", domain=_domain_employee_id, context={'active_test': False})
department_id = fields.Many2one('hr.department', "Department", compute='_compute_department_id', store=True, compute_sudo=True)
encoding_uom_id = fields.Many2one('uom.uom', compute='_compute_encoding_uom_id')
partner_id = fields.Many2one(compute='_compute_partner_id', store=True, readonly=False)
def name_get(self):
result = super().name_get()
timesheets_read = self.env[self._name].search_read([('project_id', '!=', False), ('id', 'in', self.ids)], ['id', 'project_id', 'task_id'])
if not timesheets_read:
return result
def _get_display_name(project_id, task_id):
""" Get the display name of the timesheet based on the project and task
:param project_id: tuple containing the id and the display name of the project
:param task_id: tuple containing the id and the display name of the task if a task exists in the timesheet
otherwise False.
:returns: the display name of the timesheet
"""
if task_id:
return '%s - %s' % (project_id[1], task_id[1])
return project_id[1]
timesheet_dict = {res['id']: _get_display_name(res['project_id'], res['task_id']) for res in timesheets_read}
return list({**dict(result), **timesheet_dict}.items())
def _compute_encoding_uom_id(self):
for analytic_line in self:
analytic_line.encoding_uom_id = analytic_line.company_id.timesheet_encode_uom_id
@api.depends('task_id.partner_id', 'project_id.partner_id')
def _compute_partner_id(self):
for timesheet in self:
if timesheet.project_id:
timesheet.partner_id = timesheet.task_id.partner_id or timesheet.project_id.partner_id
@api.depends('task_id', 'task_id.project_id')
def _compute_project_id(self):
for line in self:
if not line.task_id.project_id or line.project_id == line.task_id.project_id:
continue
line.project_id = line.task_id.project_id
@api.depends('project_id')
def _compute_task_id(self):
for line in self.filtered(lambda line: not line.project_id):
line.task_id = False
@api.onchange('project_id')
def _onchange_project_id(self):
# TODO KBA in master - check to do it "properly", currently:
# This onchange is used to reset the task_id when the project changes.
# Doing it in the compute will remove the task_id when the project of a task changes.
if self.project_id != self.task_id.project_id:
self.task_id = False
@api.depends('employee_id')
def _compute_user_id(self):
for line in self:
line.user_id = line.employee_id.user_id if line.employee_id else line._default_user()
@api.depends('employee_id')
def _compute_department_id(self):
for line in self:
line.department_id = line.employee_id.department_id
@api.model_create_multi
def create(self, vals_list):
default_user_id = self._default_user()
user_ids = list(map(lambda x: x.get('user_id', default_user_id), filter(lambda x: not x.get('employee_id') and x.get('project_id'), vals_list)))
for vals in vals_list:
# when the name is not provide by the 'Add a line', we set a default one
if vals.get('project_id') and not vals.get('name'):
vals['name'] = '/'
vals.update(self._timesheet_preprocess(vals))
# Although this make a second loop on the vals, we need to wait the preprocess as it could change the company_id in the vals
# TODO To be refactored in master
employees = self.env['hr.employee'].sudo().search([('user_id', 'in', user_ids)])
employee_for_user_company = defaultdict(dict)
for employee in employees:
employee_for_user_company[employee.user_id.id][employee.company_id.id] = employee.id
employee_ids = set()
for vals in vals_list:
# compute employee only for timesheet lines, makes no sense for other lines
if not vals.get('employee_id') and vals.get('project_id'):
employee_for_company = employee_for_user_company.get(vals.get('user_id', default_user_id), False)
if not employee_for_company:
continue
company_id = list(employee_for_company)[0] if len(employee_for_company) == 1 else vals.get('company_id', self.env.company.id)
vals['employee_id'] = employee_for_company.get(company_id, False)
elif vals.get('employee_id'):
employee_ids.add(vals['employee_id'])
if any(not emp.active for emp in self.env['hr.employee'].browse(list(employee_ids))):
raise UserError(_('Timesheets must be created with an active employee.'))
lines = super(AccountAnalyticLine, self).create(vals_list)
for line, values in zip(lines, vals_list):
if line.project_id: # applied only for timesheet
line._timesheet_postprocess(values)
return lines
def write(self, values):
# If it's a basic user then check if the timesheet is his own.
if not (self.user_has_groups('hr_timesheet.group_hr_timesheet_approver') or self.env.su) and any(self.env.user.id != analytic_line.user_id.id for analytic_line in self):
raise AccessError(_("You cannot access timesheets that are not yours."))
values = self._timesheet_preprocess(values)
if values.get('employee_id'):
employee = self.env['hr.employee'].browse(values['employee_id'])
if not employee.active:
raise UserError(_('You cannot set an archived employee to the existing timesheets.'))
if 'name' in values and not values.get('name'):
values['name'] = '/'
result = super(AccountAnalyticLine, self).write(values)
# applied only for timesheet
self.filtered(lambda t: t.project_id)._timesheet_postprocess(values)
return result
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
""" Set the correct label for `unit_amount`, depending on company UoM """
result = super(AccountAnalyticLine, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
result['arch'] = self._apply_timesheet_label(result['arch'], view_type=view_type)
return result
@api.model
def _apply_timesheet_label(self, view_arch, view_type='form'):
doc = etree.XML(view_arch)
encoding_uom = self.env.company.timesheet_encode_uom_id
# Here, we select only the unit_amount field having no string set to give priority to
# custom inheretied view stored in database. Even if normally, no xpath can be done on
# 'string' attribute.
for node in doc.xpath("//field[@name='unit_amount'][@widget='timesheet_uom'][not(@string)]"):
node.set('string', _('%s Spent') % (re.sub(r'[\(\)]', '', encoding_uom.name or '')))
return etree.tostring(doc, encoding='unicode')
@api.model
def _apply_time_label(self, view_arch, related_model):
doc = etree.XML(view_arch)
Model = self.env[related_model]
# Just fetch the name of the uom in `timesheet_encode_uom_id` of the current company
encoding_uom_name = self.env.company.timesheet_encode_uom_id.with_context(prefetch_fields=False).sudo().name
for node in doc.xpath("//field[@widget='timesheet_uom'][not(@string)] | //field[@widget='timesheet_uom_no_toggle'][not(@string)]"):
name_with_uom = re.sub(_('Hours') + "|Hours", encoding_uom_name or '', Model._fields[node.get('name')]._description_string(self.env), flags=re.IGNORECASE)
node.set('string', name_with_uom)
return etree.tostring(doc, encoding='unicode')
def _timesheet_get_portal_domain(self):
if self.env.user.has_group('hr_timesheet.group_hr_timesheet_user'):
# Then, he is internal user, and we take the domain for this current user
return self.env['ir.rule']._compute_domain(self._name)
return [
'|',
'&',
'|',
('task_id.project_id.message_partner_ids', 'child_of', [self.env.user.partner_id.commercial_partner_id.id]),
('task_id.message_partner_ids', 'child_of', [self.env.user.partner_id.commercial_partner_id.id]),
('task_id.project_id.privacy_visibility', '=', 'portal'),
'&',
('task_id', '=', False),
'&',
('project_id.message_partner_ids', 'child_of', [self.env.user.partner_id.commercial_partner_id.id]),
('project_id.privacy_visibility', '=', 'portal')
]
def _timesheet_preprocess(self, vals):
""" Deduce other field values from the one given.
Overrride this to compute on the fly some field that can not be computed fields.
:param values: dict values for `create`or `write`.
"""
# task implies analytic account and tags
if vals.get('task_id') and not vals.get('account_id'):
task = self.env['project.task'].browse(vals.get('task_id'))
task_analytic_account_id = task._get_task_analytic_account_id()
vals['account_id'] = task_analytic_account_id.id
vals['company_id'] = task_analytic_account_id.company_id.id or task.company_id.id
if vals.get('tag_ids'):
vals['tag_ids'] += [Command.link(tag_id.id) for tag_id in task.analytic_tag_ids]
else:
vals['tag_ids'] = [Command.set(task.analytic_tag_ids.ids)]
if not task_analytic_account_id.active:
raise UserError(_('You cannot add timesheets to a project or a task linked to an inactive analytic account.'))
# project implies analytic account
if vals.get('project_id') and not vals.get('account_id'):
project = self.env['project.project'].browse(vals.get('project_id'))
vals['account_id'] = project.analytic_account_id.id
vals['company_id'] = project.analytic_account_id.company_id.id or project.company_id.id
if not project.analytic_account_id.active:
raise UserError(_('You cannot add timesheets to a project linked to an inactive analytic account.'))
# employee implies user
if vals.get('employee_id') and not vals.get('user_id'):
employee = self.env['hr.employee'].browse(vals['employee_id'])
vals['user_id'] = employee.user_id.id
# force customer partner, from the task or the project
if (vals.get('project_id') or vals.get('task_id')) and not vals.get('partner_id'):
partner_id = False
if vals.get('task_id'):
partner_id = self.env['project.task'].browse(vals['task_id']).partner_id.id
else:
partner_id = self.env['project.project'].browse(vals['project_id']).partner_id.id
if partner_id:
vals['partner_id'] = partner_id
# set timesheet UoM from the AA company (AA implies uom)
if not vals.get('product_uom_id') and all(v in vals for v in ['account_id', 'project_id']): # project_id required to check this is timesheet flow
analytic_account = self.env['account.analytic.account'].sudo().browse(vals['account_id'])
uom_id = analytic_account.company_id.project_time_mode_id.id
if not uom_id:
company_id = vals.get('company_id', False)
if not company_id:
project = self.env['project.project'].browse(vals.get('project_id'))
company_id = project.analytic_account_id.company_id.id or project.company_id.id
uom_id = self.env['res.company'].browse(company_id).project_time_mode_id.id
vals['product_uom_id'] = uom_id
return vals
def _timesheet_postprocess(self, values):
""" Hook to update record one by one according to the values of a `write` or a `create`. """
sudo_self = self.sudo() # this creates only one env for all operation that required sudo() in `_timesheet_postprocess_values`override
values_to_write = self._timesheet_postprocess_values(values)
for timesheet in sudo_self:
if values_to_write[timesheet.id]:
timesheet.write(values_to_write[timesheet.id])
return values
def _timesheet_postprocess_values(self, values):
""" Get the addionnal values to write on record
:param dict values: values for the model's fields, as a dictionary::
{'field_name': field_value, ...}
:return: a dictionary mapping each record id to its corresponding
dictionary values to write (may be empty).
"""
result = {id_: {} for id_ in self.ids}
sudo_self = self.sudo() # this creates only one env for all operation that required sudo()
# (re)compute the amount (depending on unit_amount, employee_id for the cost, and account_id for currency)
if any(field_name in values for field_name in ['unit_amount', 'employee_id', 'account_id']):
for timesheet in sudo_self:
cost = timesheet._employee_timesheet_cost()
amount = -timesheet.unit_amount * cost
amount_converted = timesheet.employee_id.currency_id._convert(
amount, timesheet.account_id.currency_id or timesheet.currency_id, self.env.company, timesheet.date)
result[timesheet.id].update({
'amount': amount_converted,
})
return result
def _is_timesheet_encode_uom_day(self):
company_uom = self.env.company.timesheet_encode_uom_id
return company_uom == self.env.ref('uom.product_uom_day')
@api.model
def _convert_hours_to_days(self, time):
uom_hour = self.env.ref('uom.product_uom_hour')
uom_day = self.env.ref('uom.product_uom_day')
return round(uom_hour._compute_quantity(time, uom_day, raise_if_failure=False), 2)
def _get_timesheet_time_day(self):
return self._convert_hours_to_days(self.unit_amount)
def _employee_timesheet_cost(self):
self.ensure_one()
return self.employee_id.timesheet_cost or 0.0
| 55.085987
| 17,297
|
1,637
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
from odoo.http import request
class Http(models.AbstractModel):
_inherit = 'ir.http'
def session_info(self):
""" The widget 'timesheet_uom' needs to know which UoM conversion factor and which javascript
widget to apply, depending on the current company.
"""
result = super(Http, self).session_info()
if request.env.user.has_group('base.group_user'):
company_ids = request.env.user.company_ids
for company in company_ids:
result["user_companies"]["allowed_companies"][company.id].update({
"timesheet_uom_id": company.timesheet_encode_uom_id.id,
"timesheet_uom_factor": company.project_time_mode_id._compute_quantity(
1.0,
company.timesheet_encode_uom_id,
round=False
),
})
result["uom_ids"] = self.get_timesheet_uoms()
return result
@api.model
def get_timesheet_uoms(self):
company_ids = request.env.user.company_ids
uom_ids = company_ids.mapped('timesheet_encode_uom_id') | \
company_ids.mapped('project_time_mode_id')
return {
uom.id:
{
'id': uom.id,
'name': uom.name,
'rounding': uom.rounding,
'timesheet_widget': uom.timesheet_widget,
} for uom in uom_ids
}
| 37.204545
| 1,637
|
838
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class ProjectCollaborator(models.Model):
_inherit = 'project.collaborator'
@api.model
def _toggle_project_sharing_portal_rules(self, active):
super()._toggle_project_sharing_portal_rules(active)
# ir.model.access
access_timesheet_portal = self.env.ref('hr_timesheet.access_account_analytic_line_portal_user').sudo()
if access_timesheet_portal.active != active:
access_timesheet_portal.write({'active': active})
# ir.rule
timesheet_portal_ir_rule = self.env.ref('hr_timesheet.timesheet_line_rule_portal_user').sudo()
if timesheet_portal_ir_rule.active != active:
timesheet_portal_ir_rule.write({'active': active})
| 39.904762
| 838
|
579
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Uom(models.Model):
_inherit = 'uom.uom'
def _unprotected_uom_xml_ids(self):
# Override
# When timesheet App is installed, we also need to protect the hour UoM
# from deletion (and warn in case of modification)
return [
"product_uom_dozen",
]
timesheet_widget = fields.Char("Widget", help="Widget used in the webclient when this unit is the one used to encode timesheets.")
| 32.166667
| 579
|
452
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class IrUiMenu(models.Model):
_inherit = 'ir.ui.menu'
def _load_menus_blacklist(self):
res = super()._load_menus_blacklist()
if self.env.user.has_group('hr_timesheet.group_hr_timesheet_approver'):
res.append(self.env.ref('hr_timesheet.timesheet_menu_activity_user').id)
return res
| 32.285714
| 452
|
4,061
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class ResCompany(models.Model):
_inherit = 'res.company'
@api.model
def _default_project_time_mode_id(self):
uom = self.env.ref('uom.product_uom_hour', raise_if_not_found=False)
wtime = self.env.ref('uom.uom_categ_wtime')
if not uom:
uom = self.env['uom.uom'].search([('category_id', '=', wtime.id), ('uom_type', '=', 'reference')], limit=1)
if not uom:
uom = self.env['uom.uom'].search([('category_id', '=', wtime.id)], limit=1)
return uom
@api.model
def _default_timesheet_encode_uom_id(self):
uom = self.env.ref('uom.product_uom_hour', raise_if_not_found=False)
wtime = self.env.ref('uom.uom_categ_wtime')
if not uom:
uom = self.env['uom.uom'].search([('category_id', '=', wtime.id), ('uom_type', '=', 'reference')], limit=1)
if not uom:
uom = self.env['uom.uom'].search([('category_id', '=', wtime.id)], limit=1)
return uom
project_time_mode_id = fields.Many2one('uom.uom', string='Project Time Unit',
default=_default_project_time_mode_id,
help="This will set the unit of measure used in projects and tasks.\n"
"If you use the timesheet linked to projects, don't "
"forget to setup the right unit of measure in your employees.")
timesheet_encode_uom_id = fields.Many2one('uom.uom', string="Timesheet Encoding Unit",
default=_default_timesheet_encode_uom_id, domain=lambda self: [('category_id', '=', self.env.ref('uom.uom_categ_wtime').id)],
help="""This will set the unit of measure used to encode timesheet. This will simply provide tools
and widgets to help the encoding. All reporting will still be expressed in hours (default value).""")
internal_project_id = fields.Many2one(
'project.project', string="Internal Project",
help="Default project value for timesheet generated from time off type.")
@api.constrains('internal_project_id')
def _check_internal_project_id_company(self):
if self.filtered(lambda company: company.internal_project_id and company.internal_project_id.sudo().company_id != company):
raise ValidationError(_('The Internal Project of a company should be in that company.'))
@api.model_create_multi
def create(self, values):
company = super(ResCompany, self).create(values)
# use sudo as the user could have the right to create a company
# but not to create a project. On the other hand, when the company
# is created, it is not in the allowed_company_ids on the env
company.sudo()._create_internal_project_task()
return company
def _create_internal_project_task(self):
results = []
type_ids = [(4, self.env.ref('hr_timesheet.internal_project_default_stage').id)]
for company in self:
company = company.with_company(company)
results += [{
'name': _('Internal'),
'allow_timesheets': True,
'company_id': company.id,
'type_ids': type_ids,
'task_ids': [(0, 0, {
'name': name,
'company_id': company.id,
}) for name in [_('Training'), _('Meeting')]]
}]
project_ids = self.env['project.project'].create(results)
projects_by_company = {project.company_id.id: project for project in project_ids}
for company in self:
company.internal_project_id = projects_by_company.get(company.id, False)
return project_ids
def _is_timesheet_hour_uom(self):
return self.timesheet_encode_uom_id and self.timesheet_encode_uom_id == self.env.ref('uom.product_uom_hour')
def _timesheet_uom_text(self):
return self._is_timesheet_hour_uom() and _("hours") or _("days")
| 48.927711
| 4,061
|
425
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployee(models.Model):
_inherit = 'hr.employee'
timesheet_cost = fields.Monetary('Timesheet Cost', currency_field='currency_id',
groups="hr.group_hr_user", default=0.0)
currency_id = fields.Many2one('res.currency', related='company_id.currency_id', readonly=True)
| 35.416667
| 425
|
2,166
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
module_project_timesheet_synchro = fields.Boolean("Awesome Timesheet",
compute="_compute_timesheet_modules", store=True, readonly=False)
module_project_timesheet_holidays = fields.Boolean("Time Off",
compute="_compute_timesheet_modules", store=True, readonly=False)
reminder_user_allow = fields.Boolean(string="Employee Reminder", help="If checked, send an email to all users who have not recorded their timesheet")
reminder_manager_allow = fields.Boolean(string="Manager Reminder", help="If checked, send an email to all manager")
project_time_mode_id = fields.Many2one(
'uom.uom', related='company_id.project_time_mode_id', string='Project Time Unit', readonly=False,
help="This will set the unit of measure used in projects and tasks.\n"
"If you use the timesheet linked to projects, don't "
"forget to setup the right unit of measure in your employees.")
timesheet_encode_uom_id = fields.Many2one('uom.uom', string="Encoding Unit",
related='company_id.timesheet_encode_uom_id', readonly=False,
help="""This will set the unit of measure used to encode timesheet. This will simply provide tools
and widgets to help the encoding. All reporting will still be expressed in hours (default value).""")
is_encode_uom_days = fields.Boolean(compute='_compute_is_encode_uom_days')
@api.depends('timesheet_encode_uom_id')
def _compute_is_encode_uom_days(self):
product_uom_day = self.env.ref('uom.product_uom_day')
for settings in self:
settings.is_encode_uom_days = settings.timesheet_encode_uom_id == product_uom_day
@api.depends('module_hr_timesheet')
def _compute_timesheet_modules(self):
self.filtered(lambda config: not config.module_hr_timesheet).update({
'module_project_timesheet_synchro': False,
'module_project_timesheet_holidays': False,
})
| 57
| 2,166
|
20,672
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import models, fields, api, _, _lt
from odoo.exceptions import UserError, ValidationError, RedirectWarning
PROJECT_TASK_READABLE_FIELDS = {
'allow_subtasks',
'allow_timesheets',
'analytic_account_active',
'effective_hours',
'encode_uom_in_days',
'planned_hours',
'progress',
'overtime',
'remaining_hours',
'subtask_effective_hours',
'subtask_planned_hours',
'timesheet_ids',
'total_hours_spent',
}
class Project(models.Model):
_inherit = "project.project"
allow_timesheets = fields.Boolean(
"Timesheets", compute='_compute_allow_timesheets', store=True, readonly=False,
default=True, help="Enable timesheeting on the project.")
analytic_account_id = fields.Many2one(
# note: replaces ['|', ('company_id', '=', False), ('company_id', '=', company_id)]
domain="""[
'|', ('company_id', '=', False), ('company_id', '=', company_id),
('partner_id', '=?', partner_id),
]"""
)
timesheet_ids = fields.One2many('account.analytic.line', 'project_id', 'Associated Timesheets')
timesheet_count = fields.Boolean(compute="_compute_timesheet_count")
timesheet_encode_uom_id = fields.Many2one('uom.uom', related='company_id.timesheet_encode_uom_id')
total_timesheet_time = fields.Integer(
compute='_compute_total_timesheet_time', groups='hr_timesheet.group_hr_timesheet_user',
help="Total number of time (in the proper UoM) recorded in the project, rounded to the unit.")
encode_uom_in_days = fields.Boolean(compute='_compute_encode_uom_in_days')
is_internal_project = fields.Boolean(compute='_compute_is_internal_project', search='_search_is_internal_project')
remaining_hours = fields.Float(compute='_compute_remaining_hours', string='Remaining Invoiced Time', compute_sudo=True)
has_planned_hours_tasks = fields.Boolean(compute='_compute_remaining_hours', compute_sudo=True,
help="True if any of the project's task has a set planned hours")
def _compute_encode_uom_in_days(self):
self.encode_uom_in_days = self.env.company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day')
@api.depends('analytic_account_id')
def _compute_allow_timesheets(self):
without_account = self.filtered(lambda t: not t.analytic_account_id and t._origin)
without_account.update({'allow_timesheets': False})
@api.depends('company_id')
def _compute_is_internal_project(self):
for project in self:
project.is_internal_project = project == project.company_id.internal_project_id
@api.model
def _search_is_internal_project(self, operator, value):
if not isinstance(value, bool):
raise ValueError('Invalid value: %s' % (value))
if operator not in ['=', '!=']:
raise ValueError('Invalid operator: %s' % (operator))
query = """
SELECT C.internal_project_id
FROM res_company C
WHERE C.internal_project_id IS NOT NULL
"""
if (operator == '=' and value is True) or (operator == '!=' and value is False):
operator_new = 'inselect'
else:
operator_new = 'not inselect'
return [('id', operator_new, (query, ()))]
@api.depends('allow_timesheets', 'task_ids.planned_hours', 'timesheet_ids')
def _compute_remaining_hours(self):
timesheet_read_group = self.env['account.analytic.line'].read_group(
domain=[('project_id', 'in', self.filtered('allow_timesheets').ids), ('task_id', '!=', False),
'|', ('task_id.stage_id.fold', '=', False), ('task_id.stage_id', '=', False)],
fields=['effective_hours:sum(unit_amount)'], groupby='project_id')
task_read_group = self.env['project.task'].read_group(
domain=[('planned_hours', '!=', 0.0), ('project_id', 'in', self.filtered('allow_timesheets').ids),
('parent_id', '=', False), '|', ('stage_id.fold', '=', False), ('stage_id', '=', False)],
fields=['planned_hours:sum', ], groupby='project_id')
effective_hours_per_project_id = {res['project_id'][0]: res['effective_hours'] for res in timesheet_read_group}
planned_hours_per_project_id = {res['project_id'][0]: res['planned_hours'] for res in task_read_group}
for project in self:
planned_hours = planned_hours_per_project_id.get(project.id, 0.0)
effective_hours = effective_hours_per_project_id.get(project.id, 0.0)
project.remaining_hours = planned_hours - effective_hours if planned_hours else 0.0
project.has_planned_hours_tasks = project.id in planned_hours_per_project_id
@api.constrains('allow_timesheets', 'analytic_account_id')
def _check_allow_timesheet(self):
for project in self:
if project.allow_timesheets and not project.analytic_account_id:
raise ValidationError(_('You cannot use timesheets without an analytic account.'))
@api.depends('timesheet_ids')
def _compute_total_timesheet_time(self):
timesheets_read_group = self.env['account.analytic.line'].read_group(
[('project_id', 'in', self.ids)],
['project_id', 'unit_amount', 'product_uom_id'],
['project_id', 'product_uom_id'],
lazy=False)
timesheet_time_dict = defaultdict(list)
uom_ids = set(self.timesheet_encode_uom_id.ids)
for result in timesheets_read_group:
uom_id = result['product_uom_id'] and result['product_uom_id'][0]
if uom_id:
uom_ids.add(uom_id)
timesheet_time_dict[result['project_id'][0]].append((uom_id, result['unit_amount']))
uoms_dict = {uom.id: uom for uom in self.env['uom.uom'].browse(uom_ids)}
for project in self:
# Timesheets may be stored in a different unit of measure, so first
# we convert all of them to the reference unit
# if the timesheet has no product_uom_id then we take the one of the project
total_time = sum([
unit_amount * uoms_dict.get(product_uom_id, project.timesheet_encode_uom_id).factor_inv
for product_uom_id, unit_amount in timesheet_time_dict[project.id]
], 0.0)
# Now convert to the proper unit of measure set in the settings
total_time *= project.timesheet_encode_uom_id.factor
project.total_timesheet_time = int(round(total_time))
@api.depends('timesheet_ids')
def _compute_timesheet_count(self):
timesheet_project_map = {}
if self.env['account.analytic.line'].check_access_rights('read', raise_exception=False):
timesheet_read_group = self.env['account.analytic.line'].read_group(
[('project_id', 'in', self.ids)],
['project_id'],
['project_id']
)
timesheet_project_map = {project_info['project_id'][0]: project_info['project_id_count'] for project_info in timesheet_read_group}
for project in self:
project.timesheet_count = timesheet_project_map.get(project.id, 0)
@api.model_create_multi
def create(self, vals_list):
""" Create an analytic account if project allow timesheet and don't provide one
Note: create it before calling super() to avoid raising the ValidationError from _check_allow_timesheet
"""
defaults = self.default_get(['allow_timesheets', 'analytic_account_id'])
for values in vals_list:
allow_timesheets = values.get('allow_timesheets', defaults.get('allow_timesheets'))
analytic_account_id = values.get('analytic_account_id', defaults.get('analytic_account_id'))
if allow_timesheets and not analytic_account_id:
analytic_account = self._create_analytic_account_from_values(values)
values['analytic_account_id'] = analytic_account.id
return super(Project, self).create(vals_list)
def write(self, values):
# create the AA for project still allowing timesheet
if values.get('allow_timesheets') and not values.get('analytic_account_id'):
for project in self:
if not project.analytic_account_id:
project._create_analytic_account()
return super(Project, self).write(values)
@api.model
def _init_data_analytic_account(self):
self.search([('analytic_account_id', '=', False), ('allow_timesheets', '=', True)])._create_analytic_account()
@api.ondelete(at_uninstall=False)
def _unlink_except_contains_entries(self):
"""
If some projects to unlink have some timesheets entries, these
timesheets entries must be unlinked first.
In this case, a warning message is displayed through a RedirectWarning
and allows the user to see timesheets entries to unlink.
"""
projects_with_timesheets = self.filtered(lambda p: p.timesheet_ids)
if projects_with_timesheets:
if len(projects_with_timesheets) > 1:
warning_msg = _("These projects have some timesheet entries referencing them. Before removing these projects, you have to remove these timesheet entries.")
else:
warning_msg = _("This project has some timesheet entries referencing it. Before removing this project, you have to remove these timesheet entries.")
raise RedirectWarning(
warning_msg, self.env.ref('hr_timesheet.timesheet_action_project').id,
_('See timesheet entries'), {'active_ids': projects_with_timesheets.ids})
def action_show_timesheets_by_employee_invoice_type(self):
action = self.env["ir.actions.actions"]._for_xml_id("hr_timesheet.timesheet_action_all")
#Let's put the chart view first
new_views = []
for view in action['views']:
new_views.insert(0, view) if view[1] == 'graph' else new_views.append(view)
action.update({
'display_name': _("Timesheets"),
'domain': [('project_id', '=', self.id)],
'context': {
'default_project_id': self.id,
'search_default_groupby_employee': True,
'search_default_groupby_timesheet_invoice_type': True
},
'views': new_views
})
return action
def _convert_project_uom_to_timesheet_encode_uom(self, time):
uom_from = self.company_id.project_time_mode_id
uom_to = self.env.company.timesheet_encode_uom_id
return round(uom_from._compute_quantity(time, uom_to, raise_if_failure=False), 2)
# ----------------------------
# Project Updates
# ----------------------------
def _get_stat_buttons(self):
buttons = super(Project, self)._get_stat_buttons()
if self.user_has_groups('hr_timesheet.group_hr_timesheet_user'):
buttons.append({
'icon': 'clock-o',
'text': _lt('Recorded'),
'number': '%s %s' % (self.total_timesheet_time, self.env.company.timesheet_encode_uom_id.name),
'action_type': 'object',
'action': 'action_show_timesheets_by_employee_invoice_type',
'show': self.allow_timesheets,
'sequence': 4,
})
return buttons
class Task(models.Model):
_name = "project.task"
_inherit = "project.task"
analytic_account_active = fields.Boolean("Active Analytic Account", compute='_compute_analytic_account_active', compute_sudo=True)
allow_timesheets = fields.Boolean("Allow timesheets", related='project_id.allow_timesheets', help="Timesheets can be logged on this task.", readonly=True)
remaining_hours = fields.Float("Remaining Hours", compute='_compute_remaining_hours', store=True, readonly=True, help="Total remaining time, can be re-estimated periodically by the assignee of the task.")
effective_hours = fields.Float("Hours Spent", compute='_compute_effective_hours', compute_sudo=True, store=True, help="Time spent on this task, excluding its sub-tasks.")
total_hours_spent = fields.Float("Total Hours", compute='_compute_total_hours_spent', store=True, help="Time spent on this task, including its sub-tasks.")
progress = fields.Float("Progress", compute='_compute_progress_hours', store=True, group_operator="avg", help="Display progress of current task.")
overtime = fields.Float(compute='_compute_progress_hours', store=True)
subtask_effective_hours = fields.Float("Sub-tasks Hours Spent", compute='_compute_subtask_effective_hours', recursive=True, store=True, help="Time spent on the sub-tasks (and their own sub-tasks) of this task.")
timesheet_ids = fields.One2many('account.analytic.line', 'task_id', 'Timesheets')
encode_uom_in_days = fields.Boolean(compute='_compute_encode_uom_in_days', default=lambda self: self._uom_in_days())
@property
def SELF_READABLE_FIELDS(self):
return super().SELF_READABLE_FIELDS | PROJECT_TASK_READABLE_FIELDS
def _uom_in_days(self):
return self.env.company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day')
def _compute_encode_uom_in_days(self):
self.encode_uom_in_days = self._uom_in_days()
@api.depends('analytic_account_id.active', 'project_id.analytic_account_id.active')
def _compute_analytic_account_active(self):
""" Overridden in sale_timesheet """
for task in self:
task.analytic_account_active = task._get_task_analytic_account_id().active
@api.depends('timesheet_ids.unit_amount')
def _compute_effective_hours(self):
if not any(self._ids):
for task in self:
task.effective_hours = sum(task.timesheet_ids.mapped('unit_amount'))
return
timesheet_read_group = self.env['account.analytic.line'].read_group([('task_id', 'in', self.ids)], ['unit_amount', 'task_id'], ['task_id'])
timesheets_per_task = {res['task_id'][0]: res['unit_amount'] for res in timesheet_read_group}
for task in self:
task.effective_hours = timesheets_per_task.get(task.id, 0.0)
@api.depends('effective_hours', 'subtask_effective_hours', 'planned_hours')
def _compute_progress_hours(self):
for task in self:
if (task.planned_hours > 0.0):
task_total_hours = task.effective_hours + task.subtask_effective_hours
task.overtime = max(task_total_hours - task.planned_hours, 0)
if task_total_hours > task.planned_hours:
task.progress = 100
else:
task.progress = round(100.0 * task_total_hours / task.planned_hours, 2)
else:
task.progress = 0.0
task.overtime = 0
@api.depends('effective_hours', 'subtask_effective_hours', 'planned_hours')
def _compute_remaining_hours(self):
for task in self:
task.remaining_hours = task.planned_hours - task.effective_hours - task.subtask_effective_hours
@api.depends('effective_hours', 'subtask_effective_hours')
def _compute_total_hours_spent(self):
for task in self:
task.total_hours_spent = task.effective_hours + task.subtask_effective_hours
@api.depends('child_ids.effective_hours', 'child_ids.subtask_effective_hours')
def _compute_subtask_effective_hours(self):
for task in self.with_context(active_test=False):
task.subtask_effective_hours = sum(child_task.effective_hours + child_task.subtask_effective_hours for child_task in task.child_ids)
def action_view_subtask_timesheet(self):
self.ensure_one()
tasks = self.with_context(active_test=False)._get_all_subtasks()
return {
'type': 'ir.actions.act_window',
'name': _('Timesheets'),
'res_model': 'account.analytic.line',
'view_mode': 'list,form',
'context': {
'default_project_id': self.project_id.id
},
'domain': [('project_id', '!=', False), ('task_id', 'in', tasks.ids)],
}
def _get_timesheet(self):
# Is override in sale_timesheet
return self.timesheet_ids
def write(self, values):
# a timesheet must have an analytic account (and a project)
if 'project_id' in values and not values.get('project_id') and self._get_timesheet():
raise UserError(_('This task must be part of a project because there are some timesheets linked to it.'))
res = super(Task, self).write(values)
if 'project_id' in values:
project = self.env['project.project'].browse(values.get('project_id'))
if project.allow_timesheets:
# We write on all non yet invoiced timesheet the new project_id (if project allow timesheet)
self._get_timesheet().write({'project_id': values.get('project_id')})
return res
def name_get(self):
if self.env.context.get('hr_timesheet_display_remaining_hours'):
name_mapping = dict(super().name_get())
for task in self:
if task.allow_timesheets and task.planned_hours > 0 and task.encode_uom_in_days:
days_left = _("(%s days remaining)") % task._convert_hours_to_days(task.remaining_hours)
name_mapping[task.id] = name_mapping.get(task.id, '') + u"\u00A0" + days_left
elif task.allow_timesheets and task.planned_hours > 0:
hours, mins = (str(int(duration)).rjust(2, '0') for duration in divmod(abs(task.remaining_hours) * 60, 60))
hours_left = _(
"(%(sign)s%(hours)s:%(minutes)s remaining)",
sign='-' if task.remaining_hours < 0 else '',
hours=hours,
minutes=mins,
)
name_mapping[task.id] = name_mapping.get(task.id, '') + u"\u00A0" + hours_left
return list(name_mapping.items())
return super().name_get()
@api.model
def _fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
""" Set the correct label for `unit_amount`, depending on company UoM """
result = super(Task, self)._fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
# Use of sudo as the portal user doesn't have access to uom
result['arch'] = self.env['account.analytic.line'].sudo()._apply_timesheet_label(result['arch'])
if view_type in ['tree', 'pivot', 'graph', 'form'] and self.env.company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day'):
result['arch'] = self.env['account.analytic.line']._apply_time_label(result['arch'], related_model=self._name)
return result
@api.ondelete(at_uninstall=False)
def _unlink_except_contains_entries(self):
"""
If some tasks to unlink have some timesheets entries, these
timesheets entries must be unlinked first.
In this case, a warning message is displayed through a RedirectWarning
and allows the user to see timesheets entries to unlink.
"""
timesheet_data = self.env['account.analytic.line'].sudo().read_group(
[('task_id', 'in', self.ids)],
['task_id'],
['task_id'],
)
task_with_timesheets_ids = [res['task_id'][0] for res in timesheet_data]
if task_with_timesheets_ids:
if len(task_with_timesheets_ids) > 1:
warning_msg = _("These tasks have some timesheet entries referencing them. Before removing these tasks, you have to remove these timesheet entries.")
else:
warning_msg = _("This task has some timesheet entries referencing it. Before removing this task, you have to remove these timesheet entries.")
raise RedirectWarning(
warning_msg, self.env.ref('hr_timesheet.timesheet_action_task').id,
_('See timesheet entries'), {'active_ids': task_with_timesheets_ids})
@api.model
def _convert_hours_to_days(self, time):
uom_hour = self.env.ref('uom.product_uom_hour')
uom_day = self.env.ref('uom.product_uom_day')
return round(uom_hour._compute_quantity(time, uom_day, raise_if_failure=False), 2)
| 52.070529
| 20,672
|
1,606
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class ReportProjectTaskUser(models.Model):
_inherit = "report.project.task.user"
hours_planned = fields.Float('Planned Hours', readonly=True)
hours_effective = fields.Float('Effective Hours', readonly=True)
remaining_hours = fields.Float('Remaining Hours', readonly=True)
progress = fields.Float('Progress', group_operator='avg', readonly=True)
def _select(self):
return super(ReportProjectTaskUser, self)._select() + """,
(t.effective_hours * 100) / NULLIF(t.planned_hours, 0) as progress,
t.effective_hours as hours_effective,
t.planned_hours - t.effective_hours - t.subtask_effective_hours as remaining_hours,
NULLIF(t.planned_hours, 0) as hours_planned"""
def _group_by(self):
return super(ReportProjectTaskUser, self)._group_by() + """,
t.remaining_hours,
t.effective_hours,
t.planned_hours
"""
@api.model
def _fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
result = super(ReportProjectTaskUser, self)._fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
if view_type in ['pivot', 'graph'] and self.env.company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day'):
result['arch'] = self.env['account.analytic.line']._apply_time_label(result['arch'], related_model=self._name)
return result
| 47.235294
| 1,606
|
8,369
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import OrderedDict
from dateutil.relativedelta import relativedelta
from operator import itemgetter
from odoo import fields, http, _
from odoo.http import request
from odoo.tools import date_utils, groupby as groupbyelem
from odoo.osv.expression import AND, OR
from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager
class TimesheetCustomerPortal(CustomerPortal):
def _prepare_home_portal_values(self, counters):
values = super()._prepare_home_portal_values(counters)
if 'timesheet_count' in counters:
Timesheet = request.env['account.analytic.line']
domain = Timesheet._timesheet_get_portal_domain()
values['timesheet_count'] = Timesheet.sudo().search_count(domain)
return values
def _get_searchbar_inputs(self):
return {
'all': {'input': 'all', 'label': _('Search in All')},
'employee': {'input': 'employee', 'label': _('Search in Employee')},
'project': {'input': 'project', 'label': _('Search in Project')},
'task': {'input': 'task', 'label': _('Search in Task')},
'name': {'input': 'name', 'label': _('Search in Description')},
}
def _task_get_searchbar_sortings(self):
values = super()._task_get_searchbar_sortings()
values['progress'] = {'label': _('Progress'), 'order': 'progress asc', 'sequence': 9}
return values
def _get_searchbar_groupby(self):
return {
'none': {'input': 'none', 'label': _('None')},
'project': {'input': 'project', 'label': _('Project')},
'task': {'input': 'task', 'label': _('Task')},
'date': {'input': 'date', 'label': _('Date')},
'employee': {'input': 'employee', 'label': _('Employee')}
}
def _get_search_domain(self, search_in, search):
search_domain = []
if search_in in ('project', 'all'):
search_domain = OR([search_domain, [('project_id', 'ilike', search)]])
if search_in in ('name', 'all'):
search_domain = OR([search_domain, [('name', 'ilike', search)]])
if search_in in ('employee', 'all'):
search_domain = OR([search_domain, [('employee_id', 'ilike', search)]])
if search_in in ('task', 'all'):
search_domain = OR([search_domain, [('task_id', 'ilike', search)]])
return search_domain
def _get_groupby_mapping(self):
return {
'project': 'project_id',
'task': 'task_id',
'employee': 'employee_id',
'date': 'date'
}
def _get_searchbar_sortings(self):
return {
'date': {'label': _('Newest'), 'order': 'date desc'},
'employee': {'label': _('Employee'), 'order': 'employee_id'},
'project': {'label': _('Project'), 'order': 'project_id'},
'task': {'label': _('Task'), 'order': 'task_id'},
'name': {'label': _('Description'), 'order': 'name'},
}
@http.route(['/my/timesheets', '/my/timesheets/page/<int:page>'], type='http', auth="user", website=True)
def portal_my_timesheets(self, page=1, sortby=None, filterby=None, search=None, search_in='all', groupby='none', **kw):
Timesheet = request.env['account.analytic.line']
domain = Timesheet._timesheet_get_portal_domain()
Timesheet_sudo = Timesheet.sudo()
values = self._prepare_portal_layout_values()
_items_per_page = 100
searchbar_sortings = self._get_searchbar_sortings()
searchbar_inputs = self._get_searchbar_inputs()
searchbar_groupby = self._get_searchbar_groupby()
today = fields.Date.today()
quarter_start, quarter_end = date_utils.get_quarter(today)
last_week = today + relativedelta(weeks=-1)
last_month = today + relativedelta(months=-1)
last_year = today + relativedelta(years=-1)
searchbar_filters = {
'all': {'label': _('All'), 'domain': []},
'today': {'label': _('Today'), 'domain': [("date", "=", today)]},
'week': {'label': _('This week'), 'domain': [('date', '>=', date_utils.start_of(today, "week")), ('date', '<=', date_utils.end_of(today, 'week'))]},
'month': {'label': _('This month'), 'domain': [('date', '>=', date_utils.start_of(today, 'month')), ('date', '<=', date_utils.end_of(today, 'month'))]},
'year': {'label': _('This year'), 'domain': [('date', '>=', date_utils.start_of(today, 'year')), ('date', '<=', date_utils.end_of(today, 'year'))]},
'quarter': {'label': _('This Quarter'), 'domain': [('date', '>=', quarter_start), ('date', '<=', quarter_end)]},
'last_week': {'label': _('Last week'), 'domain': [('date', '>=', date_utils.start_of(last_week, "week")), ('date', '<=', date_utils.end_of(last_week, 'week'))]},
'last_month': {'label': _('Last month'), 'domain': [('date', '>=', date_utils.start_of(last_month, 'month')), ('date', '<=', date_utils.end_of(last_month, 'month'))]},
'last_year': {'label': _('Last year'), 'domain': [('date', '>=', date_utils.start_of(last_year, 'year')), ('date', '<=', date_utils.end_of(last_year, 'year'))]},
}
# default sort by value
if not sortby:
sortby = 'date'
order = searchbar_sortings[sortby]['order']
# default filter by value
if not filterby:
filterby = 'all'
domain = AND([domain, searchbar_filters[filterby]['domain']])
if search and search_in:
domain += self._get_search_domain(search_in, search)
timesheet_count = Timesheet_sudo.search_count(domain)
# pager
pager = portal_pager(
url="/my/timesheets",
url_args={'sortby': sortby, 'search_in': search_in, 'search': search, 'filterby': filterby, 'groupby': groupby},
total=timesheet_count,
page=page,
step=_items_per_page
)
def get_timesheets():
groupby_mapping = self._get_groupby_mapping()
field = groupby_mapping.get(groupby, None)
orderby = '%s, %s' % (field, order) if field else order
timesheets = Timesheet_sudo.search(domain, order=orderby, limit=_items_per_page, offset=pager['offset'])
if field:
if groupby == 'date':
raw_timesheets_group = Timesheet_sudo.read_group(
domain, ["unit_amount:sum", "ids:array_agg(id)"], ["date:day"]
)
grouped_timesheets = [(Timesheet_sudo.browse(group["ids"]), group["unit_amount"]) for group in raw_timesheets_group]
else:
time_data = Timesheet_sudo.read_group(domain, [field, 'unit_amount:sum'], [field])
mapped_time = dict([(m[field][0] if m[field] else False, m['unit_amount']) for m in time_data])
grouped_timesheets = [(Timesheet_sudo.concat(*g), mapped_time[k.id]) for k, g in groupbyelem(timesheets, itemgetter(field))]
return timesheets, grouped_timesheets
grouped_timesheets = [(
timesheets,
sum(Timesheet_sudo.search(domain).mapped('unit_amount'))
)] if timesheets else []
return timesheets, grouped_timesheets
timesheets, grouped_timesheets = get_timesheets()
values.update({
'timesheets': timesheets,
'grouped_timesheets': grouped_timesheets,
'page_name': 'timesheet',
'default_url': '/my/timesheets',
'pager': pager,
'searchbar_sortings': searchbar_sortings,
'search_in': search_in,
'search': search,
'sortby': sortby,
'groupby': groupby,
'searchbar_inputs': searchbar_inputs,
'searchbar_groupby': searchbar_groupby,
'searchbar_filters': OrderedDict(sorted(searchbar_filters.items())),
'filterby': filterby,
'is_uom_day': request.env['account.analytic.line']._is_timesheet_encode_uom_day(),
})
return request.render("hr_timesheet.portal_my_timesheets", values)
| 47.822857
| 8,369
|
2,354
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo.http import request
from odoo.osv import expression
from odoo.addons.project.controllers.portal import CustomerPortal
class ProjectCustomerPortal(CustomerPortal):
def _prepare_project_sharing_session_info(self, project):
session_info = super()._prepare_project_sharing_session_info(project)
company = project.company_id
timesheet_encode_uom = company.timesheet_encode_uom_id
project_time_mode_uom = company.project_time_mode_id
session_info['user_companies']['allowed_companies'][company.id].update(
timesheet_uom_id=timesheet_encode_uom.id,
timesheet_uom_factor=project_time_mode_uom._compute_quantity(
1.0,
timesheet_encode_uom,
round=False
),
)
session_info['uom_ids'] = {
uom.id:
{
'id': uom.id,
'name': uom.name,
'rounding': uom.rounding,
'timesheet_widget': uom.timesheet_widget,
} for uom in [timesheet_encode_uom, project_time_mode_uom]
}
return session_info
def _task_get_page_view_values(self, task, access_token, **kwargs):
values = super(ProjectCustomerPortal, self)._task_get_page_view_values(task, access_token, **kwargs)
domain = request.env['account.analytic.line']._timesheet_get_portal_domain()
task_domain = expression.AND([domain, [('task_id', '=', task.id)]])
subtask_domain = expression.AND([domain, [('task_id', 'in', task.child_ids.ids)]])
timesheets = request.env['account.analytic.line'].sudo().search(task_domain)
subtasks_timesheets = request.env['account.analytic.line'].sudo().search(subtask_domain)
timesheets_by_subtask = defaultdict(lambda: request.env['account.analytic.line'].sudo())
for timesheet in subtasks_timesheets:
timesheets_by_subtask[timesheet.task_id] |= timesheet
values['timesheets'] = timesheets
values['timesheets_by_subtask'] = timesheets_by_subtask
values['is_uom_day'] = request.env['account.analytic.line']._is_timesheet_encode_uom_day()
return values
| 46.156863
| 2,354
|
654
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
{
'name': 'Product Email Template',
'depends': ['account'],
'category': 'Accounting/Accounting',
'description': """
Add email templates to products to be sent on invoice confirmation
==================================================================
With this module, link your products to a template to send complete information and tools to your customer.
For instance when invoicing a training, the training agenda and materials will automatically be sent to your customers.'
""",
'data': [
'views/product_views.xml',
'views/mail_template_views.xml',
],
'license': 'LGPL-3',
}
| 34.421053
| 654
|
2,865
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestAccountMove(AccountTestInvoicingCommon):
def setUp(self):
super().setUp()
Template = self.env['mail.template']
self.template = Template.create({
'name': 'Product Template',
'subject': 'YOUR PRODUCT',
'model_id': self.env['ir.model']._get_id('product.template')
})
self.customer = self.env['res.partner'].create({
'name': 'James Bond',
'email': 'james.bond@yopmail.com'
})
self.product_a.email_template_id = self.template.id
def test_send_product_template_email_on_invoice_post(self):
id_max = self.env['mail.message'].search([], order='id desc', limit=1)
if id_max:
id_max = id_max[0].id
else:
id_max = 0
invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.customer.id,
'invoice_line_ids': [(0, 0, {
'name': 'Walter PPK',
'quantity': 1,
'price_unit': 123,
'product_id': self.product_a.id
})]
})
invoice.action_post()
message_sent = self.env['mail.message'].search([('id', '>', id_max), ('subject', '=', 'YOUR PRODUCT')])
self.assertEqual(len(message_sent), 1, 'Should send 1 message for product')
self.assertTrue(message_sent[0].email_from, 'Should have from email address')
def test_send_as_system_when_sudo(self):
"""
Test scenario of a product ordered through the portal.
"""
id_max = self.env['mail.message'].search([], order='id desc', limit=1)
if id_max:
id_max = id_max[0].id
else:
id_max = 0
invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.customer.id,
'invoice_line_ids': [(0, 0, {
'name': 'Walter PPK',
'quantity': 1,
'price_unit': 123,
'product_id': self.product_a.id
})]
})
pub_user = self.env['res.users'].create({
'login': 'test_public_user',
'name': 'test_public_user',
'email': False,
'groups_id': [(6, 0, [self.env.ref('base.group_public').id])]
})
invoice.with_user(pub_user).sudo().action_post()
message_sent = self.env['mail.message'].search([('id', '>', id_max), ('subject', '=', 'YOUR PRODUCT')])
self.assertEqual(len(message_sent), 1, 'Should send 1 message for product')
self.assertTrue(message_sent[0].email_from, 'Should have from email address')
| 40.928571
| 2,865
|
1,192
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, models, SUPERUSER_ID
class AccountMove(models.Model):
_inherit = 'account.move'
def invoice_validate_send_email(self):
if self.env.su:
# sending mail in sudo was meant for it being sent from superuser
self = self.with_user(SUPERUSER_ID)
for invoice in self.filtered(lambda x: x.move_type == 'out_invoice'):
# send template only on customer invoice
# subscribe the partner to the invoice
if invoice.partner_id not in invoice.message_partner_ids:
invoice.message_subscribe([invoice.partner_id.id])
for line in invoice.invoice_line_ids:
if line.product_id.email_template_id:
invoice.message_post_with_template(
line.product_id.email_template_id.id,
composition_mode="comment",
email_layout_xmlid="mail.mail_notification_light"
)
return True
def _post(self, soft=True):
# OVERRIDE
posted = super()._post(soft)
posted.invoice_validate_send_email()
return posted
| 38.451613
| 1,192
|
711
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class ProductTemplate(models.Model):
""" Product Template inheritance to add an optional email.template to a
product.template. When validating an invoice, an email will be send to the
customer based on this template. The customer will receive an email for each
product linked to an email template. """
_inherit = "product.template"
email_template_id = fields.Many2one('mail.template', string='Product Email Template',
help='When validating an invoice, an email will be sent to the customer '
'based on this template. The customer will receive an email for each '
'product linked to an email template.')
| 44.4375
| 711
|
436
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Project Purchase",
'version': '1.0',
'summary': "Monitor purchase in project",
'description': "",
'category': 'Services/Project',
'depends': ['purchase', 'project'],
'data': [
'views/project_views.xml',
],
'application': False,
'auto_install': True,
'license': 'LGPL-3',
}
| 25.647059
| 436
|
2,508
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _, _lt
class Project(models.Model):
_inherit = "project.project"
purchase_orders_count = fields.Integer('# Purchase Orders', compute='_compute_purchase_orders_count', groups='purchase.group_purchase_user')
@api.depends('analytic_account_id')
def _compute_purchase_orders_count(self):
purchase_orders_data = self.env['purchase.order.line'].read_group([
('account_analytic_id', '!=', False),
('account_analytic_id', 'in', self.analytic_account_id.ids)
], ['account_analytic_id', 'order_id:count_distinct'], ['account_analytic_id'])
mapped_data = dict([(data['account_analytic_id'][0], data['order_id']) for data in purchase_orders_data])
for project in self:
project.purchase_orders_count = mapped_data.get(project.analytic_account_id.id, 0)
# ----------------------------
# Actions
# ----------------------------
def action_open_project_purchase_orders(self):
purchase_orders = self.env['purchase.order'].search([
('order_line.account_analytic_id', '!=', False),
('order_line.account_analytic_id', 'in', self.analytic_account_id.ids)
])
action_window = {
'name': _('Purchase Orders'),
'type': 'ir.actions.act_window',
'res_model': 'purchase.order',
'views': [[False, 'tree'], [False, 'form']],
'domain': [('id', 'in', purchase_orders.ids)],
'context': {
'create': False,
}
}
if len(purchase_orders) == 1:
action_window['views'] = [[False, 'form']]
action_window['res_id'] = purchase_orders.id
return action_window
# ----------------------------
# Project Updates
# ----------------------------
def _get_stat_buttons(self):
buttons = super(Project, self)._get_stat_buttons()
if self.user_has_groups('purchase.group_purchase_user'):
buttons.append({
'icon': 'credit-card',
'text': _lt('Purchase Orders'),
'number': self.purchase_orders_count,
'action_type': 'object',
'action': 'action_open_project_purchase_orders',
'show': self.purchase_orders_count > 0,
'sequence': 13,
})
return buttons
| 40.451613
| 2,508
|
2,290
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2008 JAILLET Simon - CrysaLEAD - www.crysalead.fr
{
'name': 'France - Accounting',
'version': '2.1',
'category': 'Accounting/Localizations/Account Charts',
'description': """
This is the module to manage the accounting chart for France in Odoo.
========================================================================
This module applies to companies based in France mainland. It doesn't apply to
companies based in the DOM-TOMs (Guadeloupe, Martinique, Guyane, Réunion, Mayotte).
This localisation module creates the VAT taxes of type 'tax included' for purchases
(it is notably required when you use the module 'hr_expense'). Beware that these
'tax included' VAT taxes are not managed by the fiscal positions provided by this
module (because it is complex to manage both 'tax excluded' and 'tax included'
scenarios in fiscal positions).
This localisation module doesn't properly handle the scenario when a France-mainland
company sells services to a company based in the DOMs. We could manage it in the
fiscal positions, but it would require to differentiate between 'product' VAT taxes
and 'service' VAT taxes. We consider that it is too 'heavy' to have this by default
in l10n_fr; companies that sell services to DOM-based companies should update the
configuration of their taxes and fiscal positions manually.
**Credits:** Sistheo, Zeekom, CrysaLEAD, Akretion and Camptocamp.
""",
'depends': [
'account',
'base_iban',
'base_vat',
],
'data': [
'data/l10n_fr_chart_data.xml',
'data/account.account.template.csv',
'data/account.group.template.csv',
'data/account_chart_template_data.xml',
'views/l10n_fr_view.xml',
'data/account_tax_group_data.xml',
'data/tax_report_data.xml',
'data/account_tax_data.xml',
'data/res_country_data.xml',
'data/account_fiscal_position_template_data.xml',
'data/account_reconcile_model_template.xml',
'data/account_chart_template_configure_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'post_init_hook': '_l10n_fr_post_init_hook',
'license': 'LGPL-3',
}
| 40.875
| 2,289
|
259
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
update_taxes_from_templates(cr, 'l10n_fr.l10n_fr_pcg_chart_template')
| 43.166667
| 259
|
291
|
py
|
PYTHON
|
15.0
|
from openerp.modules.registry import RegistryManager
def migrate(cr, version):
registry = RegistryManager.get(cr.dbname)
from openerp.addons.account.models.chart_template import migrate_set_tags_and_taxes_updatable
migrate_set_tags_and_taxes_updatable(cr, registry, 'l10n_fr')
| 41.571429
| 291
|
253
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
class ResPartner(models.Model):
_inherit = 'res.partner'
siret = fields.Char(string='SIRET', size=14)
| 25.3
| 253
|
2,722
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api, _
class ResCompany(models.Model):
_inherit = 'res.company'
l10n_fr_closing_sequence_id = fields.Many2one('ir.sequence', 'Sequence to use to build sale closings', readonly=True)
siret = fields.Char(related='partner_id.siret', string='SIRET', size=14, readonly=False)
ape = fields.Char(string='APE')
@api.model
def _get_unalterable_country(self):
return ['FR', 'MF', 'MQ', 'NC', 'PF', 'RE', 'GF', 'GP', 'TF'] # These codes correspond to France and DOM-TOM.
def _is_accounting_unalterable(self):
if not self.vat and not self.country_id:
return False
return self.country_id and self.country_id.code in self._get_unalterable_country()
@api.model_create_multi
def create(self, vals_list):
companies = super().create(vals_list)
for company in companies:
#when creating a new french company, create the securisation sequence as well
if company._is_accounting_unalterable():
sequence_fields = ['l10n_fr_closing_sequence_id']
company._create_secure_sequence(sequence_fields)
return companies
def write(self, vals):
res = super(ResCompany, self).write(vals)
#if country changed to fr, create the securisation sequence
for company in self:
if company._is_accounting_unalterable():
sequence_fields = ['l10n_fr_closing_sequence_id']
company._create_secure_sequence(sequence_fields)
return res
def _create_secure_sequence(self, sequence_fields):
"""This function creates a no_gap sequence on each company in self that will ensure
a unique number is given to all posted account.move in such a way that we can always
find the previous move of a journal entry on a specific journal.
"""
for company in self:
vals_write = {}
for seq_field in sequence_fields:
if not company[seq_field]:
vals = {
'name': _('Securisation of %s - %s') % (seq_field, company.name),
'code': 'FRSECURE%s-%s' % (company.id, seq_field),
'implementation': 'no_gap',
'prefix': '',
'suffix': '',
'padding': 0,
'company_id': company.id}
seq = self.env['ir.sequence'].create(vals)
vals_write[seq_field] = seq.id
if vals_write:
company.write(vals_write)
| 43.903226
| 2,722
|
726
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
@api.model
def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):
journal_data = super(AccountChartTemplate, self)._prepare_all_journals(
acc_template_ref, company, journals_dict)
if company.account_fiscal_country_id.code != 'FR':
return journal_data
for journal in journal_data:
if journal['type'] in ('sale', 'purchase'):
journal.update({'refund_sequence': True})
return journal_data
| 36.3
| 726
|
457
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'pos_mrp',
'version': '1.0',
'category': 'Hidden',
'sequence': 6,
'summary': 'Link module between Point of Sale and Mrp',
'description': """
This is a link module between Point of Sale and Mrp.
""",
'depends': ['point_of_sale', 'mrp'],
'installable': True,
'auto_install': True,
'license': 'LGPL-3',
}
| 25.388889
| 457
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.