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
|
---|---|---|---|---|---|---|
5,004 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website.tools import MockRequest
from odoo.addons.sale.tests.test_sale_product_attribute_value_config import TestSaleProductAttributeValueCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestWebsiteSaleStockProductWarehouse(TestSaleProductAttributeValueCommon):
@classmethod
def setUpClass(self):
super().setUpClass()
# Run the tests in another company, so the tests do not rely on the
# database state (eg the default company's warehouse)
self.company = self.env['res.company'].create({'name': 'Company C'})
self.env.user.company_id = self.company
self.website = self.env['website'].create({'name': 'Website Company C'})
self.website.company_id = self.company
# Set two warehouses (one was created on company creation)
self.warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.company.id)])
self.warehouse_2 = self.env['stock.warehouse'].create({
'name': 'Warehouse 2',
'code': 'WH2'
})
# Create two stockable products
self.product_A = self.env['product.product'].create({
'name': 'Product A',
'allow_out_of_stock_order': False,
'type': 'product',
'default_code': 'E-COM1',
})
self.product_B = self.env['product.product'].create({
'name': 'Product B',
'allow_out_of_stock_order': False,
'type': 'product',
'default_code': 'E-COM2',
})
# Add 10 Product A in WH1 and 15 Product 1 in WH2
quants = self.env['stock.quant'].with_context(inventory_mode=True).create([{
'product_id': self.product_A.id,
'inventory_quantity': qty,
'location_id': wh.lot_stock_id.id,
} for wh, qty in [(self.warehouse_1, 10.0), (self.warehouse_2, 15.0)]])
# Add 10 Product 2 in WH2
quants |= self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_B.id,
'inventory_quantity': 10.0,
'location_id': self.warehouse_2.lot_stock_id.id,
})
quants.action_apply_inventory()
def test_01_get_combination_info(self):
""" Checked that correct product quantity is shown in website according
to the warehouse which is set in current website.
- Set Warehouse 1, Warehouse 2 or none in website and:
- Check available quantity of Product A and Product B in website
When the user doesn't set any warehouse, the module should still select
a default one.
"""
for wh, qty_a, qty_b in [(self.warehouse_1, 10, 0), (self.warehouse_2, 15, 10), (False, 10, 0)]:
# set warehouse_id
self.website.warehouse_id = wh
product = self.product_A.with_context(website_id=self.website.id)
combination_info = product.product_tmpl_id.with_context(website_sale_stock_get_quantity=True)._get_combination_info()
# Check available quantity of product is according to warehouse
self.assertEqual(combination_info['free_qty'], qty_a, "%s units of Product A should be available in warehouse %s" % (qty_a, wh))
product = self.product_B.with_context(website_id=self.website.id)
combination_info = product.product_tmpl_id.with_context(website_sale_stock_get_quantity=True)._get_combination_info()
# Check available quantity of product is according to warehouse
self.assertEqual(combination_info['free_qty'], qty_b, "%s units of Product B should be available in warehouse %s" % (qty_b, wh))
def test_02_update_cart_with_multi_warehouses(self):
""" When the user updates his cart and increases a product quantity, if
this quantity is not available in the SO's warehouse, a warning should
be returned and the quantity updated to its maximum. """
so = self.env['sale.order'].create({
'partner_id': self.env.user.partner_id.id,
'order_line': [(0, 0, {
'name': self.product_A.name,
'product_id': self.product_A.id,
'product_uom_qty': 5,
'product_uom': self.product_A.uom_id.id,
'price_unit': self.product_A.list_price,
})]
})
with MockRequest(self.env, website=self.website, sale_order_id=so.id):
website_so = self.website.sale_get_order()
self.assertEqual(website_so.order_line.product_id.virtual_available, 10, "This quantity should be based on SO's warehouse")
values = so._cart_update(product_id=self.product_A.id, line_id=so.order_line.id, set_qty=20)
self.assertTrue(values.get('warning', False))
self.assertEqual(values.get('quantity'), 10)
| 47.207547 | 5,004 |
2,753 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, fields
from odoo.tools.translate import _
class SaleOrder(models.Model):
_inherit = 'sale.order'
warning_stock = fields.Char('Warning')
def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
values = super(SaleOrder, self)._cart_update(product_id, line_id, add_qty, set_qty, **kwargs)
values = self._cart_lines_stock_update(values, **kwargs)
return values
def _cart_lines_stock_update(self, values, **kwargs):
line_id = values.get('line_id')
for line in self.order_line:
if line.product_id.type == 'product' and not line.product_id.allow_out_of_stock_order:
cart_qty = sum(self.order_line.filtered(lambda p: p.product_id.id == line.product_id.id).mapped('product_uom_qty'))
if (line_id == line.id) and cart_qty > line.product_id.with_context(warehouse=self.warehouse_id.id).free_qty:
qty = line.product_id.with_context(warehouse=self.warehouse_id.id).free_qty - cart_qty
new_val = super(SaleOrder, self)._cart_update(line.product_id.id, line.id, qty, 0, **kwargs)
values.update(new_val)
# Make sure line still exists, it may have been deleted in super()_cartupdate because qty can be <= 0
if line.exists() and new_val['quantity']:
line.warning_stock = _('You ask for %s products but only %s is available') % (cart_qty, new_val['quantity'])
values['warning'] = line.warning_stock
else:
self.warning_stock = _("Some products became unavailable and your cart has been updated. We're sorry for the inconvenience.")
values['warning'] = self.warning_stock
return values
def _website_product_id_change(self, order_id, product_id, qty=0, **kwargs):
res = super(SaleOrder, self)._website_product_id_change(order_id, product_id, qty=qty, **kwargs)
product = self.env['product.product'].browse(product_id)
res['customer_lead'] = product.sale_delay
return res
def _get_stock_warning(self, clear=True):
self.ensure_one()
warn = self.warning_stock
if clear:
self.warning_stock = ''
return warn
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
warning_stock = fields.Char('Warning')
def _get_stock_warning(self, clear=True):
self.ensure_one()
warn = self.warning_stock
if clear:
self.warning_stock = ''
return warn
| 45.131148 | 2,753 |
2,463 |
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.translate import html_translate
class ProductTemplate(models.Model):
_inherit = 'product.template'
allow_out_of_stock_order = fields.Boolean(string='Continue selling when out-of-stock', default=True)
available_threshold = fields.Float(string='Show Threshold', default=5.0)
show_availability = fields.Boolean(string='Show availability Qty', default=False)
out_of_stock_message = fields.Html(string="Out-of-Stock Message", translate=html_translate)
def _get_combination_info(self, combination=False, product_id=False, add_qty=1, pricelist=False, parent_combination=False, only_template=False):
combination_info = super(ProductTemplate, self)._get_combination_info(
combination=combination, product_id=product_id, add_qty=add_qty, pricelist=pricelist,
parent_combination=parent_combination, only_template=only_template)
if not self.env.context.get('website_sale_stock_get_quantity'):
return combination_info
if combination_info['product_id']:
product = self.env['product.product'].sudo().browse(combination_info['product_id'])
website = self.env['website'].get_current_website()
free_qty = product.with_context(warehouse=website._get_warehouse_available()).free_qty
combination_info.update({
'free_qty': free_qty,
'product_type': product.type,
'product_template': self.id,
'available_threshold': self.available_threshold,
'cart_qty': product.cart_qty,
'uom_name': product.uom_id.name,
'allow_out_of_stock_order': self.allow_out_of_stock_order,
'show_availability': self.show_availability,
'out_of_stock_message': self.out_of_stock_message,
})
else:
product_template = self.sudo()
combination_info.update({
'free_qty': 0,
'product_type': product_template.type,
'allow_out_of_stock_order': product_template.allow_out_of_stock_order,
'available_threshold': product_template.available_threshold,
'product_template': product_template.id,
'cart_qty': 0,
})
return combination_info
| 49.26 | 2,463 |
677 |
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.addons.website.models import ir_http
class ProductProduct(models.Model):
_inherit = 'product.product'
cart_qty = fields.Integer(compute='_compute_cart_qty')
def _compute_cart_qty(self):
website = ir_http.get_request_website()
if not website:
self.cart_qty = 0
return
cart = website.sale_get_order()
for product in self:
product.cart_qty = sum(cart.order_line.filtered(lambda p: p.product_id.id == product.id).mapped('product_uom_qty')) if cart else 0
| 33.85 | 677 |
467 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, fields
from odoo.tools.translate import _
class StockPicking(models.Model):
_inherit = 'stock.picking'
website_id = fields.Many2one('website', related='sale_id.website_id', string='Website',
help='Website this picking belongs to.',
store=True, readonly=True)
| 33.357143 | 467 |
1,893 |
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 ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
allow_out_of_stock_order = fields.Boolean(string='Continue selling when out-of-stock', default=True)
available_threshold = fields.Float(string='Show Threshold', default=5.0)
show_availability = fields.Boolean(string='Show availability Qty', default=False)
website_warehouse_id = fields.Many2one('stock.warehouse', related='website_id.warehouse_id', domain="[('company_id', '=', website_company_id)]", readonly=False)
def set_values(self):
super(ResConfigSettings, self).set_values()
IrDefault = self.env['ir.default'].sudo()
IrDefault.set('product.template', 'allow_out_of_stock_order', self.allow_out_of_stock_order)
IrDefault.set('product.template', 'available_threshold', self.available_threshold)
IrDefault.set('product.template', 'show_availability', self.show_availability)
@api.model
def get_values(self):
res = super(ResConfigSettings, self).get_values()
IrDefault = self.env['ir.default'].sudo()
allow_out_of_stock_order = IrDefault.get('product.template', 'allow_out_of_stock_order')
res.update(
allow_out_of_stock_order=allow_out_of_stock_order if allow_out_of_stock_order is not None else True,
available_threshold=IrDefault.get('product.template', 'available_threshold') or 5.0,
show_availability=IrDefault.get('product.template', 'show_availability') or False
)
return res
@api.onchange('website_company_id')
def _onchange_website_company_id(self):
if self.website_warehouse_id.company_id != self.website_company_id:
return {'value': {'website_warehouse_id': False}}
| 46.170732 | 1,893 |
1,299 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import api, fields, models
class Website(models.Model):
_inherit = 'website'
warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse')
def _prepare_sale_order_values(self, partner, pricelist):
self.ensure_one()
values = super(Website, self)._prepare_sale_order_values(partner, pricelist)
if values['company_id']:
warehouse_id = self._get_warehouse_available()
if warehouse_id:
values['warehouse_id'] = warehouse_id
return values
def _get_warehouse_available(self):
return (
self.warehouse_id and self.warehouse_id.id or
self.env['ir.default'].get('sale.order', 'warehouse_id', company_id=self.company_id.id) or
self.env['ir.default'].get('sale.order', 'warehouse_id') or
self.env['stock.warehouse'].sudo().search([('company_id', '=', self.company_id.id)], limit=1).id
)
def sale_get_order(self, force_create=False, code=None, update_pricelist=False, force_pricelist=False):
so = super().sale_get_order(force_create=force_create, code=code, update_pricelist=update_pricelist, force_pricelist=force_pricelist)
return so.with_context(warehouse=so.warehouse_id.id) if so else so
| 44.793103 | 1,299 |
1,427 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.website_sale.controllers import main as website_sale_controller
from odoo import http, _
from odoo.http import request
from odoo.exceptions import ValidationError
class PaymentPortal(website_sale_controller.PaymentPortal):
@http.route()
def shop_payment_transaction(self, *args, **kwargs):
""" Payment transaction override to double check cart quantities before
placing the order
"""
order = request.website.sale_get_order()
values = []
for line in order.order_line:
if line.product_id.type == 'product' and not line.product_id.allow_out_of_stock_order:
cart_qty = sum(order.order_line.filtered(lambda p: p.product_id.id == line.product_id.id).mapped('product_uom_qty'))
avl_qty = line.product_id.with_context(warehouse=order.warehouse_id.id).free_qty
if cart_qty > avl_qty:
values.append(_(
'You ask for %(quantity)s products but only %(available_qty)s is available',
quantity=cart_qty,
available_qty=avl_qty if avl_qty > 0 else 0
))
if values:
raise ValidationError('. '.join(values) + '.')
return super().shop_payment_transaction(*args, **kwargs)
| 44.59375 | 1,427 |
669 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.addons.website_sale.controllers.variant import WebsiteSaleVariantController
class WebsiteSaleStockVariantController(WebsiteSaleVariantController):
@http.route()
def get_combination_info_website(self, product_template_id, product_id, combination, add_qty, **kw):
kw['context'] = kw.get('context', {})
kw['context'].update(website_sale_stock_get_quantity=True)
return super(WebsiteSaleStockVariantController, self).get_combination_info_website(product_template_id, product_id, combination, add_qty, **kw)
| 51.461538 | 669 |
1,094 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>)
{
'name': 'Singapore - Accounting',
'author': 'Tech Receptives',
'version': '2.1',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Singapore accounting chart and localization.
=======================================================
This module add, for accounting:
- The Chart of Accounts of Singapore
- Field UEN (Unique Entity Number) on company and partner
- Field PermitNo and PermitNoDate on invoice
""",
'depends': ['base', 'account'],
'data': [
'data/l10n_sg_chart_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_report_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_data.xml',
'views/account_invoice_view.xml',
'views/res_company_view.xml',
'views/res_partner_view.xml',
],
'post_init_hook': '_preserve_tag_on_taxes',
'license': 'LGPL-3',
}
| 32.176471 | 1,094 |
250 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.account.models.chart_template import update_taxes_from_templates
def migrate(cr, version):
update_taxes_from_templates(cr, 'l10n_sg.sg_chart_template')
| 41.666667 | 250 |
290 |
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_sg')
| 48.333333 | 290 |
262 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class AccountMove(models.Model):
_inherit = 'account.move'
l10n_sg_permit_number = fields.Char(string="Permit No.")
l10n_sg_permit_number_date = fields.Date(string="Date of permit number")
| 23.818182 | 262 |
305 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class ResCompany(models.Model):
_name = 'res.company'
_description = 'Companies'
_inherit = 'res.company'
l10n_sg_unique_entity_number = fields.Char(string='UEN', related="partner_id.l10n_sg_unique_entity_number", readonly=False)
| 30.5 | 305 |
207 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class ResPartner(models.Model):
_name = 'res.partner'
_inherit = 'res.partner'
l10n_sg_unique_entity_number = fields.Char(string='UEN')
| 23 | 207 |
3,712 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'LATAM Localization Base',
'version': '1.0',
'category': 'Accounting/Localizations',
'sequence': 14,
'author': 'Odoo, ADHOC SA',
'summary': 'LATAM Identification Types',
'description': """
Add a new model named "Identification Type" that extend the vat field functionality in the partner and let the user to identify (an eventually invoice) to contacts not only with their fiscal tax ID (VAT) but with other types of identifications like national document, passport, foreign ID, etc. With this module installed you will see now in the partner form view two fields:
* Identification Type
* Identification Number
This behavior is a common requirement for some latam countries like Argentina and Chile. If your localization has this requirements then you need to depend on this module and define in your localization module the identifications types that are used in your country. Generally these types of identifications are defined by the government authorities that regulate the fiscal operations. For example:
* AFIP in Argentina defines DNI, CUIT (vat for legal entities), CUIL (vat for natural person), and another 80 valid identification types.
Each identification holds this information:
* name: short name of the identification
* description: could be the same short name or a long name
* country_id: the country where this identification belongs
* is_vat: identify this record as the corresponding VAT for the specific country.
* sequence: let us to sort the identification types depending on the ones that are most used.
* active: we can activate/inactivate identifications to make it easier to our customers
In order to make this module compatible for multi-company environments where we have companies that does not need/support this requirement, we have added generic identification types and generic rules to manage the contact information and make it transparent for the user when only use the VAT as we formerly know.
Generic Identifications:
* VAT: The Fiscal Tax Identification or VAT number, by default will be selected as identification type so the user will only need to add the related vat number.
* Passport
* Foreign ID (Foreign National Document)
Rules when creating a new partner: We will only see the identification types that are meaningful, taking into account these rules:
* If the partner have not country address set: Will show the generic identification types plus the ones defined in the partner's related company country (If the partner has not specific company then will show the identification types related to the current user company)
* If the partner has country address : will show the generic identification types plus the ones defined for the country of the partner.
When creating a new company, will set to the related partner always the related country is_vat identification type.
All the defined identification types can be reviewed and activate/deactivate in "Contacts / Configuration / Identification Type" menu.
This module is compatible with base_vat module in order to be able to validate VAT numbers for each country that have or not have the possibility to manage multiple identification types.
""",
'depends': [
'contacts',
'base_vat',
],
'data': [
'data/l10n_latam.identification.type.csv',
'views/res_partner_view.xml',
'views/l10n_latam_identification_type_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'auto_install': False,
'application': False,
'post_init_hook': '_set_default_identification_type',
'license': 'LGPL-3',
}
| 58.920635 | 3,712 |
812 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
from odoo.osv import expression
class L10nLatamIdentificationType(models.Model):
_name = 'l10n_latam.identification.type'
_description = "Identification Types"
_order = 'sequence'
sequence = fields.Integer(default=10)
name = fields.Char(translate=True, required=True,)
description = fields.Char()
active = fields.Boolean(default=True)
is_vat = fields.Boolean()
country_id = fields.Many2one('res.country')
def name_get(self):
multi_localization = len(self.search([]).mapped('country_id')) > 1
return [(rec.id, '%s%s' % (
rec.name, multi_localization and rec.country_id and ' (%s)' % rec.country_id.code or '')) for rec in self]
| 36.909091 | 812 |
720 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
class ResCompany(models.Model):
_inherit = 'res.company'
@api.model
def create(self, vals):
""" If exists, use specific vat identification.type for the country of the company """
country_id = vals.get('country_id')
if country_id:
country_vat_type = self.env['l10n_latam.identification.type'].search(
[('is_vat', '=', True), ('country_id', '=', country_id)], limit=1)
if country_vat_type:
self = self.with_context(default_l10n_latam_identification_type_id=country_vat_type.id)
return super().create(vals)
| 40 | 720 |
1,558 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
class ResPartner(models.Model):
_inherit = 'res.partner'
l10n_latam_identification_type_id = fields.Many2one('l10n_latam.identification.type',
string="Identification Type", index=True, auto_join=True,
default=lambda self: self.env.ref('l10n_latam_base.it_vat', raise_if_not_found=False),
help="The type of identification")
vat = fields.Char(string='Identification Number', help="Identification Number for selected type")
@api.model
def _commercial_fields(self):
return super()._commercial_fields() + ['l10n_latam_identification_type_id']
@api.constrains('vat', 'l10n_latam_identification_type_id')
def check_vat(self):
with_vat = self.filtered(lambda x: x.l10n_latam_identification_type_id.is_vat)
return super(ResPartner, with_vat).check_vat()
@api.onchange('country_id')
def _onchange_country(self):
country = self.country_id or self.company_id.account_fiscal_country_id or self.env.company.account_fiscal_country_id
identification_type = self.l10n_latam_identification_type_id
if not identification_type or (identification_type.country_id != country):
self.l10n_latam_identification_type_id = self.env['l10n_latam.identification.type'].search(
[('country_id', '=', country.id), ('is_vat', '=', True)], limit=1) or self.env.ref(
'l10n_latam_base.it_vat', raise_if_not_found=False)
| 50.258065 | 1,558 |
843 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Uruguay - Accounting',
'version': '0.1',
'author': 'Uruguay l10n Team, Guillem Barba',
'category': 'Accounting/Localizations/Account Charts',
'description': """
General Chart of Accounts.
==========================
Provide Templates for Chart of Accounts, Taxes for Uruguay.
""",
'depends': ['account'],
'data': [
'data/l10n_uy_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_uy_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_report_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_data.xml',
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 28.1 | 843 |
3,713 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Restaurant',
'version': '1.0',
'category': 'Sales/Point of Sale',
'sequence': 6,
'summary': 'Restaurant extensions for the Point of Sale ',
'description': """
This module adds several features to the Point of Sale that are specific to restaurant management:
- Bill Printing: Allows you to print a receipt before the order is paid
- Bill Splitting: Allows you to split an order into different orders
- Kitchen Order Printing: allows you to print orders updates to kitchen or bar printers
""",
'depends': ['point_of_sale'],
'website': 'https://www.odoo.com/app/point-of-sale-restaurant',
'data': [
'security/ir.model.access.csv',
'views/pos_order_views.xml',
'views/pos_restaurant_views.xml',
'views/pos_config_views.xml',
],
'demo': [
'data/pos_restaurant_demo.xml',
],
'installable': True,
'auto_install': False,
'assets': {
'point_of_sale.assets': [
'pos_restaurant/static/lib/js/jquery.ui.touch-punch.js',
'pos_restaurant/static/src/js/multiprint.js',
'pos_restaurant/static/src/js/floors.js',
'pos_restaurant/static/src/js/notes.js',
'pos_restaurant/static/src/js/payment.js',
'pos_restaurant/static/src/js/Resizeable.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/ControlButtons/OrderlineNoteButton.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/ControlButtons/TableGuestsButton.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/ControlButtons/PrintBillButton.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/ControlButtons/SubmitOrderButton.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/ControlButtons/SplitBillButton.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/ControlButtons/TransferOrderButton.js',
'pos_restaurant/static/src/js/Screens/ProductScreen/Orderline.js',
'pos_restaurant/static/src/js/Screens/BillScreen.js',
'pos_restaurant/static/src/js/Screens/SplitBillScreen/SplitBillScreen.js',
'pos_restaurant/static/src/js/Screens/SplitBillScreen/SplitOrderline.js',
'pos_restaurant/static/src/js/Screens/FloorScreen/FloorScreen.js',
'pos_restaurant/static/src/js/Screens/FloorScreen/EditBar.js',
'pos_restaurant/static/src/js/Screens/FloorScreen/TableWidget.js',
'pos_restaurant/static/src/js/Screens/FloorScreen/EditableTable.js',
'pos_restaurant/static/src/js/Screens/TicketScreen.js',
'pos_restaurant/static/src/js/ChromeWidgets/BackToFloorButton.js',
'pos_restaurant/static/src/js/ChromeWidgets/TicketButton.js',
'pos_restaurant/static/src/js/Chrome.js',
'pos_restaurant/static/src/js/Screens/ReceiptScreen/ReceiptScreen.js',
'pos_restaurant/static/src/js/Screens/PaymentScreen.js',
'pos_restaurant/static/src/js/Screens/TipScreen.js',
('after', 'point_of_sale/static/src/css/pos.css', 'pos_restaurant/static/src/css/restaurant.css'),
],
'web.assets_backend': [
'point_of_sale/static/src/scss/pos_dashboard.scss',
],
'web.assets_tests': [
'pos_restaurant/static/tests/tours/**/*',
],
'point_of_sale.qunit_suite_tests': [
'pos_restaurant/static/tests/unit/**/*',
],
'web.assets_qweb': [
'pos_restaurant/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 48.220779 | 3,713 |
9,055 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
@odoo.tests.tagged('post_install', '-at_install')
class TestFrontend(odoo.tests.HttpCase):
def setUp(self):
super().setUp()
self.env = self.env(user=self.env.ref('base.user_admin'))
account_obj = self.env['account.account']
account_receivable = account_obj.create({'code': 'X1012',
'name': 'Account Receivable - Test',
'user_type_id': self.env.ref(
'account.data_account_type_receivable').id,
'reconcile': True})
printer = self.env['restaurant.printer'].create({
'name': 'Kitchen Printer',
'proxy_ip': 'localhost',
})
drinks_category = self.env['pos.category'].create({'name': 'Drinks'})
main_company = self.env.ref('base.main_company')
second_cash_journal = self.env['account.journal'].create({
'name': 'Cash 2',
'code': 'CSH2',
'type': 'cash',
'company_id': main_company.id
})
self.env['pos.payment.method'].create({
'name': 'Cash 2',
'split_transactions': False,
'receivable_account_id': account_receivable.id,
'journal_id': second_cash_journal.id,
})
pos_config = self.env['pos.config'].create({
'name': 'Bar',
'barcode_nomenclature_id': self.env.ref('barcodes.default_barcode_nomenclature').id,
'module_pos_restaurant': True,
'is_table_management': True,
'iface_splitbill': True,
'iface_printbill': True,
'iface_orderline_notes': True,
'printer_ids': [(4, printer.id)],
'iface_start_categ_id': drinks_category.id,
'start_category': True,
'pricelist_id': self.env.ref('product.list0').id,
})
main_floor = self.env['restaurant.floor'].create({
'name': 'Main Floor',
'pos_config_id': pos_config.id,
})
table_05 = self.env['restaurant.table'].create({
'name': 'T5',
'floor_id': main_floor.id,
'seats': 4,
'position_h': 100,
'position_v': 100,
})
table_04 = self.env['restaurant.table'].create({
'name': 'T4',
'floor_id': main_floor.id,
'seats': 4,
'shape': 'square',
'position_h': 150,
'position_v': 100,
})
table_02 = self.env['restaurant.table'].create({
'name': 'T2',
'floor_id': main_floor.id,
'seats': 4,
'position_h': 250,
'position_v': 100,
})
second_floor = self.env['restaurant.floor'].create({
'name': 'Second Floor',
'pos_config_id': pos_config.id,
})
table_01 = self.env['restaurant.table'].create({
'name': 'T1',
'floor_id': second_floor.id,
'seats': 4,
'shape': 'square',
'position_h': 100,
'position_v': 150,
})
table_03 = self.env['restaurant.table'].create({
'name': 'T3',
'floor_id': second_floor.id,
'seats': 4,
'position_h': 100,
'position_v': 250,
})
self.env['ir.property']._set_default(
'property_account_receivable_id',
'res.partner',
account_receivable,
main_company,
)
test_sale_journal = self.env['account.journal'].create({
'name': 'Sales Journal - Test',
'code': 'TSJ',
'type': 'sale',
'company_id': main_company.id
})
cash_journal = self.env['account.journal'].create({
'name': 'Cash Test',
'code': 'TCJ',
'type': 'cash',
'company_id': main_company.id
})
pos_config.write({
'journal_id': test_sale_journal.id,
'invoice_journal_id': test_sale_journal.id,
'payment_method_ids': [(0, 0, {
'name': 'Cash restaurant',
'split_transactions': True,
'receivable_account_id': account_receivable.id,
'journal_id': cash_journal.id,
})],
})
coke = self.env['product.product'].create({
'available_in_pos': True,
'list_price': 2.20,
'name': 'Coca-Cola',
'weight': 0.01,
'pos_categ_id': drinks_category.id,
'categ_id': self.env.ref('point_of_sale.product_category_pos').id,
'taxes_id': [(6, 0, [])],
})
water = self.env['product.product'].create({
'available_in_pos': True,
'list_price': 2.20,
'name': 'Water',
'weight': 0.01,
'pos_categ_id': drinks_category.id,
'categ_id': self.env.ref('point_of_sale.product_category_pos').id,
'taxes_id': [(6, 0, [])],
})
minute_maid = self.env['product.product'].create({
'available_in_pos': True,
'list_price': 2.20,
'name': 'Minute Maid',
'weight': 0.01,
'pos_categ_id': drinks_category.id,
'categ_id': self.env.ref('point_of_sale.product_category_pos').id,
'taxes_id': [(6, 0, [])],
})
pricelist = self.env['product.pricelist'].create({'name': 'Restaurant Pricelist'})
pos_config.write({'pricelist_id': pricelist.id})
self.pos_config = pos_config
def test_01_pos_restaurant(self):
self.pos_config.with_user(self.env.ref('base.user_admin')).open_session_cb(check_coa=False)
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'pos_restaurant_sync', login="admin")
self.assertEqual(1, self.env['pos.order'].search_count([('amount_total', '=', 4.4), ('state', '=', 'draft')]))
self.assertEqual(1, self.env['pos.order'].search_count([('amount_total', '=', 4.4), ('state', '=', 'paid')]))
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'pos_restaurant_sync_second_login', login="admin")
self.assertEqual(0, self.env['pos.order'].search_count([('amount_total', '=', 4.4), ('state', '=', 'draft')]))
self.assertEqual(1, self.env['pos.order'].search_count([('amount_total', '=', 2.2), ('state', '=', 'draft')]))
self.assertEqual(2, self.env['pos.order'].search_count([('amount_total', '=', 4.4), ('state', '=', 'paid')]))
def test_02_others(self):
self.pos_config.with_user(self.env.ref('base.user_admin')).open_session_cb(check_coa=False)
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'SplitBillScreenTour', login="admin")
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'ControlButtonsTour', login="admin")
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'FloorScreenTour', login="admin")
def test_04_ticket_screen(self):
self.pos_config.with_user(self.env.ref('base.user_admin')).open_session_cb(check_coa=False)
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'PosResTicketScreenTour', login="admin")
def test_05_tip_screen(self):
self.pos_config.write({'set_tip_after_payment': True, 'iface_tipproduct': True, 'tip_product_id': self.env.ref('point_of_sale.product_product_tip')})
self.pos_config.with_user(self.env.ref('base.user_admin')).open_session_cb(check_coa=False)
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'PosResTipScreenTour', login="admin")
order1 = self.env['pos.order'].search([('pos_reference', 'ilike', '%-0001')])
order2 = self.env['pos.order'].search([('pos_reference', 'ilike', '%-0002')])
order3 = self.env['pos.order'].search([('pos_reference', 'ilike', '%-0003')])
order4 = self.env['pos.order'].search([('pos_reference', 'ilike', '%-0004')])
self.assertTrue(order1.is_tipped and order1.tip_amount == 0.40)
self.assertTrue(order2.is_tipped and order2.tip_amount == 1.00)
self.assertTrue(order3.is_tipped and order3.tip_amount == 1.50)
self.assertTrue(order4.is_tipped and order4.tip_amount == 1.00)
def test_06_split_bill_screen(self):
self.pos_config.with_user(self.env.ref('base.user_admin')).open_session_cb(check_coa=False)
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'SplitBillScreenTour2', login="admin")
def test_07_refund_stay_current_table(self):
self.pos_config.with_user(self.env.ref('base.user_admin')).open_session_cb(check_coa=False)
self.start_tour("/pos/ui?config_id=%d" % self.pos_config.id, 'RefundStayCurrentTableTour', login="admin")
| 41.921296 | 9,055 |
5,477 |
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 RestaurantFloor(models.Model):
_name = 'restaurant.floor'
_description = 'Restaurant Floor'
name = fields.Char('Floor Name', required=True, help='An internal identification of the restaurant floor')
pos_config_id = fields.Many2one('pos.config', string='Point of Sale')
background_image = fields.Binary('Background Image', help='A background image used to display a floor layout in the point of sale interface')
background_color = fields.Char('Background Color', help='The background color of the floor layout, (must be specified in a html-compatible format)', default='rgb(210, 210, 210)')
table_ids = fields.One2many('restaurant.table', 'floor_id', string='Tables', help='The list of tables in this floor')
sequence = fields.Integer('Sequence', help='Used to sort Floors', default=1)
active = fields.Boolean(default=True)
@api.ondelete(at_uninstall=False)
def _unlink_except_active_pos_session(self):
confs = self.mapped('pos_config_id').filtered(lambda c: c.is_table_management == True)
opened_session = self.env['pos.session'].search([('config_id', 'in', confs.ids), ('state', '!=', 'closed')])
if opened_session:
error_msg = _("You cannot remove a floor that is used in a PoS session, close the session(s) first: \n")
for floor in self:
for session in opened_session:
if floor in session.config_id.floor_ids:
error_msg += _("Floor: %s - PoS Config: %s \n") % (floor.name, session.config_id.name)
if confs:
raise UserError(error_msg)
def write(self, vals):
for floor in self:
if floor.pos_config_id.has_active_session and (vals.get('pos_config_id') or vals.get('active')) :
raise UserError(
'Please close and validate the following open PoS Session before modifying this floor.\n'
'Open session: %s' % (' '.join(floor.pos_config_id.mapped('name')),))
if vals.get('pos_config_id') and floor.pos_config_id.id and vals.get('pos_config_id') != floor.pos_config_id.id:
raise UserError('The %s is already used in another Pos Config.' % floor.name)
return super(RestaurantFloor, self).write(vals)
class RestaurantTable(models.Model):
_name = 'restaurant.table'
_description = 'Restaurant Table'
name = fields.Char('Table Name', required=True, help='An internal identification of a table')
floor_id = fields.Many2one('restaurant.floor', string='Floor')
shape = fields.Selection([('square', 'Square'), ('round', 'Round')], string='Shape', required=True, default='square')
position_h = fields.Float('Horizontal Position', default=10,
help="The table's horizontal position from the left side to the table's center, in pixels")
position_v = fields.Float('Vertical Position', default=10,
help="The table's vertical position from the top to the table's center, in pixels")
width = fields.Float('Width', default=50, help="The table's width in pixels")
height = fields.Float('Height', default=50, help="The table's height in pixels")
seats = fields.Integer('Seats', default=1, help="The default number of customer served at this table.")
color = fields.Char('Color', help="The table's color, expressed as a valid 'background' CSS property value")
active = fields.Boolean('Active', default=True, help='If false, the table is deactivated and will not be available in the point of sale')
@api.model
def create_from_ui(self, table):
""" create or modify a table from the point of sale UI.
table contains the table's fields. If it contains an
id, it will modify the existing table. It then
returns the id of the table.
"""
if table.get('floor_id'):
table['floor_id'] = table['floor_id'][0]
table_id = table.pop('id', False)
if table_id:
self.browse(table_id).write(table)
else:
table_id = self.create(table).id
return table_id
@api.ondelete(at_uninstall=False)
def _unlink_except_active_pos_session(self):
confs = self.mapped('floor_id').mapped('pos_config_id').filtered(lambda c: c.is_table_management == True)
opened_session = self.env['pos.session'].search([('config_id', 'in', confs.ids), ('state', '!=', 'closed')])
if opened_session:
error_msg = _("You cannot remove a table that is used in a PoS session, close the session(s) first.")
if confs:
raise UserError(error_msg)
class RestaurantPrinter(models.Model):
_name = 'restaurant.printer'
_description = 'Restaurant Printer'
name = fields.Char('Printer Name', required=True, default='Printer', help='An internal identification of the printer')
printer_type = fields.Selection(string='Printer Type', default='iot',
selection=[('iot', ' Use a printer connected to the IoT Box')])
proxy_ip = fields.Char('Proxy IP Address', help="The IP Address or hostname of the Printer's hardware proxy")
product_categories_ids = fields.Many2many('pos.category', 'printer_category_rel', 'printer_id', 'category_id', string='Printed Product Categories')
| 55.323232 | 5,477 |
4,612 |
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 PosConfig(models.Model):
_inherit = 'pos.config'
iface_splitbill = fields.Boolean(string='Bill Splitting', help='Enables Bill Splitting in the Point of Sale.')
iface_printbill = fields.Boolean(string='Bill Printing', help='Allows to print the Bill before payment.')
iface_orderline_notes = fields.Boolean(string='Internal Notes', help='Allow custom internal notes on Orderlines.')
floor_ids = fields.One2many('restaurant.floor', 'pos_config_id', string='Restaurant Floors', help='The restaurant floors served by this point of sale.')
printer_ids = fields.Many2many('restaurant.printer', 'pos_config_printer_rel', 'config_id', 'printer_id', string='Order Printers')
is_table_management = fields.Boolean('Floors & Tables')
is_order_printer = fields.Boolean('Order Printer')
set_tip_after_payment = fields.Boolean('Set Tip After Payment', help="Adjust the amount authorized by payment terminals to add a tip after the customers left or at the end of the day.")
module_pos_restaurant = fields.Boolean(default=True)
@api.onchange('module_pos_restaurant')
def _onchange_module_pos_restaurant(self):
if not self.module_pos_restaurant:
self.update({'iface_printbill': False,
'iface_splitbill': False,
'is_order_printer': False,
'is_table_management': False,
'iface_orderline_notes': False})
@api.onchange('iface_tipproduct')
def _onchange_iface_tipproduct(self):
if not self.iface_tipproduct:
self.set_tip_after_payment = False
def _force_http(self):
enforce_https = self.env['ir.config_parameter'].sudo().get_param('point_of_sale.enforce_https')
if not enforce_https and self.printer_ids.filtered(lambda pt: pt.printer_type == 'epson_epos'):
return True
return super(PosConfig, self)._force_http()
def get_tables_order_count(self):
""" """
self.ensure_one()
tables = self.env['restaurant.table'].search([('floor_id.pos_config_id', 'in', self.ids)])
domain = [('state', '=', 'draft'), ('table_id', 'in', tables.ids)]
order_stats = self.env['pos.order'].read_group(domain, ['table_id'], 'table_id')
orders_map = dict((s['table_id'][0], s['table_id_count']) for s in order_stats)
result = []
for table in tables:
result.append({'id': table.id, 'orders': orders_map.get(table.id, 0)})
return result
def _get_forbidden_change_fields(self):
forbidden_keys = super(PosConfig, self)._get_forbidden_change_fields()
forbidden_keys.append('is_table_management')
forbidden_keys.append('floor_ids')
return forbidden_keys
def write(self, vals):
if ('is_table_management' in vals and vals['is_table_management'] == False):
vals['floor_ids'] = [(5, 0, 0)]
if ('is_order_printer' in vals and vals['is_order_printer'] == False):
vals['printer_ids'] = [(5, 0, 0)]
return super(PosConfig, self).write(vals)
@api.model
def add_cash_payment_method(self):
companies = self.env['res.company'].search([])
for company in companies.filtered('chart_template_id'):
pos_configs = self.search([('company_id', '=', company.id), ('module_pos_restaurant', '=', True)])
journal_counter = 2
for pos_config in pos_configs:
if pos_config.payment_method_ids.filtered('is_cash_count'):
continue
cash_journal = self.env['account.journal'].search([('company_id', '=', company.id), ('type', '=', 'cash'), ('pos_payment_method_ids', '=', False)], limit=1)
if not cash_journal:
cash_journal = self.env['account.journal'].create({
'name': 'Cash %s' % journal_counter,
'code': 'RCSH%s' % journal_counter,
'type': 'cash',
'company_id': company.id
})
journal_counter += 1
payment_methods = pos_config.payment_method_ids
payment_methods |= self.env['pos.payment.method'].create({
'name': _('Cash Bar'),
'journal_id': cash_journal.id,
'company_id': company.id,
})
pos_config.write({'payment_method_ids': [(6, 0, payment_methods.ids)]})
| 50.681319 | 4,612 |
457 |
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 PosConfig(models.Model):
_inherit = 'pos.payment'
def _update_payment_line_for_tip(self, tip_amount):
"""Inherit this method to perform reauthorization or capture on electronic payment."""
self.ensure_one()
self.write({
"amount": self.amount + tip_amount,
})
| 30.466667 | 457 |
11,179 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tools import groupby
from re import search
from functools import partial
import pytz
from odoo import api, fields, models
class PosOrderLine(models.Model):
_inherit = 'pos.order.line'
note = fields.Char('Internal Note added by the waiter.')
mp_skip = fields.Boolean('Skip line when sending ticket to kitchen printers.')
mp_dirty = fields.Boolean()
class PosOrder(models.Model):
_inherit = 'pos.order'
table_id = fields.Many2one('restaurant.table', string='Table', help='The table where this order was served', index=True)
customer_count = fields.Integer(string='Guests', help='The amount of customers that have been served by this order.')
multiprint_resume = fields.Char()
def _get_pack_lot_lines(self, order_lines):
"""Add pack_lot_lines to the order_lines.
The function doesn't return anything but adds the results directly to the order_lines.
:param order_lines: order_lines for which the pack_lot_lines are to be requested.
:type order_lines: pos.order.line.
"""
pack_lots = self.env['pos.pack.operation.lot'].search_read(
domain = [('pos_order_line_id', 'in', [order_line['id'] for order_line in order_lines])],
fields = [
'id',
'lot_name',
'pos_order_line_id'
])
for pack_lot in pack_lots:
pack_lot['order_line'] = pack_lot['pos_order_line_id'][0]
pack_lot['server_id'] = pack_lot['id']
del pack_lot['pos_order_line_id']
del pack_lot['id']
for order_line_id, pack_lot_ids in groupby(pack_lots, key=lambda x:x['order_line']):
next(order_line for order_line in order_lines if order_line['id'] == order_line_id)['pack_lot_ids'] = list(pack_lot_ids)
def _get_fields_for_order_line(self):
fields = super(PosOrder, self)._get_fields_for_order_line()
fields.extend([
'id',
'discount',
'tax_ids',
'product_id',
'price_unit',
'order_id',
'qty',
'note',
'mp_skip',
'mp_dirty',
'full_product_name',
'customer_note',
])
return fields
def _prepare_order_line(self, order_line):
"""Method that will allow the cleaning of values to send the correct information.
:param order_line: order_line that will be cleaned.
:type order_line: pos.order.line.
:returns: dict -- dict representing the order line's values.
"""
order_line = super(PosOrder, self)._prepare_order_line(order_line)
order_line["product_id"] = order_line["product_id"][0]
order_line["server_id"] = order_line["id"]
del order_line["id"]
if not "pack_lot_ids" in order_line:
order_line["pack_lot_ids"] = []
else:
order_line["pack_lot_ids"] = [[0, 0, lot] for lot in order_line["pack_lot_ids"]]
order_line["tax_ids"] = [(6, False, [tax for tax in order_line["tax_ids"]])]
return order_line
def _get_order_lines(self, orders):
"""Add pos_order_lines to the orders.
The function doesn't return anything but adds the results directly to the orders.
:param orders: orders for which the order_lines are to be requested.
:type orders: pos.order.
"""
order_lines = self.env['pos.order.line'].search_read(
domain = [('order_id', 'in', [to['id'] for to in orders])],
fields = self._get_fields_for_order_line())
if order_lines != []:
self._get_pack_lot_lines(order_lines)
extended_order_lines = []
for order_line in order_lines:
extended_order_lines.append([0, 0, self._prepare_order_line(order_line)])
for order_id, order_lines in groupby(extended_order_lines, key=lambda x:x[2]['order_id']):
next(order for order in orders if order['id'] == order_id[0])['lines'] = list(order_lines)
def _get_fields_for_payment_lines(self):
return [
'id',
'amount',
'pos_order_id',
'payment_method_id',
'card_type',
'cardholder_name',
'transaction_id',
'payment_status'
]
def _get_payments_lines_list(self, orders):
payment_lines = self.env['pos.payment'].search_read(
domain = [('pos_order_id', 'in', [po['id'] for po in orders])],
fields = self._get_fields_for_payment_lines())
extended_payment_lines = []
for payment_line in payment_lines:
payment_line['server_id'] = payment_line['id']
payment_line['payment_method_id'] = payment_line['payment_method_id'][0]
del payment_line['id']
extended_payment_lines.append([0, 0, payment_line])
return extended_payment_lines
def _get_payment_lines(self, orders):
"""Add account_bank_statement_lines to the orders.
The function doesn't return anything but adds the results directly to the orders.
:param orders: orders for which the payment_lines are to be requested.
:type orders: pos.order.
"""
extended_payment_lines = self._get_payments_lines_list(orders)
for order_id, payment_lines in groupby(extended_payment_lines, key=lambda x:x[2]['pos_order_id']):
next(order for order in orders if order['id'] == order_id[0])['statement_ids'] = list(payment_lines)
def _get_fields_for_draft_order(self):
fields = super(PosOrder, self)._get_fields_for_draft_order()
fields.extend([
'id',
'pricelist_id',
'partner_id',
'sequence_number',
'session_id',
'pos_reference',
'create_uid',
'create_date',
'customer_count',
'fiscal_position_id',
'table_id',
'to_invoice',
'multiprint_resume',
])
return fields
@api.model
def _get_domain_for_draft_orders(self, table_id):
""" Get the domain to search for draft orders on a table.
:param table_id: Id of a table.
:type table_id: int.
"returns: list -- list of tuples that represents a domain.
"""
return [("state", "=", "draft"), ("table_id", "=", table_id)]
@api.model
def get_table_draft_orders(self, table_id):
"""Generate an object of all draft orders for the given table.
Generate and return an JSON object with all draft orders for the given table, to send to the
front end application.
:param table_id: Id of the selected table.
:type table_id: int.
:returns: list -- list of dict representing the table orders
"""
self = self.with_context(prefetch_fields=False)
table_orders = self.search_read(
domain=self._get_domain_for_draft_orders(table_id),
fields=self._get_fields_for_draft_order())
self._get_order_lines(table_orders)
self._get_payment_lines(table_orders)
for order in table_orders:
order['pos_session_id'] = order['session_id'][0]
order['uid'] = search(r"\d{5,}-\d{3,}-\d{4,}", order['pos_reference']).group(0)
order['name'] = order['pos_reference']
order['creation_date'] = order['create_date']
order['server_id'] = order['id']
if order['fiscal_position_id']:
order['fiscal_position_id'] = order['fiscal_position_id'][0]
if order['pricelist_id']:
order['pricelist_id'] = order['pricelist_id'][0]
if order['partner_id']:
order['partner_id'] = order['partner_id'][0]
if order['table_id']:
order['table_id'] = order['table_id'][0]
if 'employee_id' in order:
order['employee_id'] = order['employee_id'][0] if order['employee_id'] else False
if not 'lines' in order:
order['lines'] = []
if not 'statement_ids' in order:
order['statement_ids'] = []
del order['id']
del order['session_id']
del order['pos_reference']
del order['create_date']
return table_orders
def set_tip(self, tip_line_vals):
"""Set tip to `self` based on values in `tip_line_vals`."""
self.ensure_one()
PosOrderLine = self.env['pos.order.line']
process_line = partial(PosOrderLine._order_line_fields, session_id=self.session_id.id)
# 1. add/modify tip orderline
processed_tip_line_vals = process_line([0, 0, tip_line_vals])[2]
processed_tip_line_vals.update({ "order_id": self.id })
tip_line = self.lines.filtered(lambda line: line.product_id == self.session_id.config_id.tip_product_id)
if not tip_line:
tip_line = PosOrderLine.create(processed_tip_line_vals)
else:
tip_line.write(processed_tip_line_vals)
# 2. modify payment
payment_line = self.payment_ids.filtered(lambda line: not line.is_change)[0]
# TODO it would be better to throw error if there are multiple payment lines
# then ask the user to select which payment to update, no?
payment_line._update_payment_line_for_tip(tip_line.price_subtotal_incl)
# 3. flag order as tipped and update order fields
self.write({
"is_tipped": True,
"tip_amount": tip_line.price_subtotal_incl,
"amount_total": self.amount_total + tip_line.price_subtotal_incl,
"amount_paid": self.amount_paid + tip_line.price_subtotal_incl,
})
def set_no_tip(self):
"""Override this method to introduce action when setting no tip."""
self.ensure_one()
self.write({
"is_tipped": True,
"tip_amount": 0,
})
@api.model
def _order_fields(self, ui_order):
order_fields = super(PosOrder, self)._order_fields(ui_order)
order_fields['table_id'] = ui_order.get('table_id', False)
order_fields['customer_count'] = ui_order.get('customer_count', 0)
order_fields['multiprint_resume'] = ui_order.get('multiprint_resume', False)
return order_fields
def _export_for_ui(self, order):
result = super(PosOrder, self)._export_for_ui(order)
result['table_id'] = order.table_id.id
return result
@api.model
def get_all_table_draft_orders(self, pos_config_id):
tables = self.env['restaurant.table'].search([('floor_id.pos_config_id', '=', pos_config_id)])
order_obj = self.env['pos.order']
return [order for table in tables for order in order_obj.get_table_draft_orders(table.id) if order]
| 39.925 | 11,179 |
2,139 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'France - VAT Anti-Fraud Certification for Point of Sale (CGI 286 I-3 bis)',
'icon': '/l10n_fr/static/description/icon.png',
'version': '1.0',
'category': 'Accounting/Localizations/Point of Sale',
'description': """
This add-on brings the technical requirements of the French regulation CGI art. 286, I. 3° bis that stipulates certain criteria concerning the inalterability, security, storage and archiving of data related to sales to private individuals (B2C).
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Install it if you use the Point of Sale app to sell to individuals.
The module adds following features:
Inalterability: deactivation of all the ways to cancel or modify key data of POS orders, invoices and journal entries
Security: chaining algorithm to verify the inalterability
Storage: automatic sales closings with computation of both period and cumulative totals (daily, monthly, annually)
Access to download the mandatory Certificate of Conformity delivered by Odoo SA (only for Odoo Enterprise users)
""",
'depends': ['l10n_fr', 'point_of_sale'],
'installable': True,
'auto_install': True,
'application': False,
'data': [
'views/account_views.xml',
'views/pos_views.xml',
'views/account_sale_closure.xml',
'views/pos_inalterability_menuitem.xml',
'report/pos_hash_integrity.xml',
'data/account_sale_closure_cron.xml',
'security/ir.model.access.csv',
'security/account_closing_intercompany.xml',
],
'post_init_hook': '_setup_inalterability',
'assets': {
'point_of_sale.assets': [
'l10n_fr_pos_cert/static/src/js/**/*',
],
'web.assets_qweb': [
'l10n_fr_pos_cert/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 43.632653 | 2,138 |
7,260 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from hashlib import sha256
from json import dumps
from odoo import models, api, fields
from odoo.fields import Datetime
from odoo.tools.translate import _, _lt
from odoo.exceptions import UserError
class pos_config(models.Model):
_inherit = 'pos.config'
def open_ui(self):
for config in self:
if not config.company_id.country_id:
raise UserError(_("You have to set a country in your company setting."))
if config.company_id._is_accounting_unalterable():
if config.current_session_id:
config.current_session_id._check_session_timing()
return super(pos_config, self).open_ui()
class pos_session(models.Model):
_inherit = 'pos.session'
def _check_session_timing(self):
self.ensure_one()
return True
def open_frontend_cb(self):
sessions_to_check = self.filtered(lambda s: s.config_id.company_id._is_accounting_unalterable())
sessions_to_check.filtered(lambda s: s.state == 'opening_control').start_at = fields.Datetime.now()
for session in sessions_to_check:
session._check_session_timing()
return super(pos_session, self).open_frontend_cb()
ORDER_FIELDS = ['date_order', 'user_id', 'lines', 'payment_ids', 'pricelist_id', 'partner_id', 'session_id', 'pos_reference', 'sale_journal', 'fiscal_position_id']
LINE_FIELDS = ['notice', 'product_id', 'qty', 'price_unit', 'discount', 'tax_ids', 'tax_ids_after_fiscal_position']
ERR_MSG = _lt('According to the French law, you cannot modify a %s. Forbidden fields: %s.')
class pos_order(models.Model):
_inherit = 'pos.order'
l10n_fr_hash = fields.Char(string="Inalteralbility Hash", readonly=True, copy=False)
l10n_fr_secure_sequence_number = fields.Integer(string="Inalteralbility No Gap Sequence #", readonly=True, copy=False)
l10n_fr_string_to_hash = fields.Char(compute='_compute_string_to_hash', readonly=True, store=False)
def _get_new_hash(self, secure_seq_number):
""" Returns the hash to write on pos orders when they get posted"""
self.ensure_one()
#get the only one exact previous order in the securisation sequence
prev_order = self.search([('state', 'in', ['paid', 'done', 'invoiced']),
('company_id', '=', self.company_id.id),
('l10n_fr_secure_sequence_number', '!=', 0),
('l10n_fr_secure_sequence_number', '=', int(secure_seq_number) - 1)])
if prev_order and len(prev_order) != 1:
raise UserError(
_('An error occurred when computing the inalterability. Impossible to get the unique previous posted point of sale order.'))
#build and return the hash
return self._compute_hash(prev_order.l10n_fr_hash if prev_order else u'')
def _compute_hash(self, previous_hash):
""" Computes the hash of the browse_record given as self, based on the hash
of the previous record in the company's securisation sequence given as parameter"""
self.ensure_one()
hash_string = sha256((previous_hash + self.l10n_fr_string_to_hash).encode('utf-8'))
return hash_string.hexdigest()
def _compute_string_to_hash(self):
def _getattrstring(obj, field_str):
field_value = obj[field_str]
if obj._fields[field_str].type == 'many2one':
field_value = field_value.id
if obj._fields[field_str].type in ['many2many', 'one2many']:
field_value = field_value.sorted().ids
return str(field_value)
for order in self:
values = {}
for field in ORDER_FIELDS:
values[field] = _getattrstring(order, field)
for line in order.lines:
for field in LINE_FIELDS:
k = 'line_%d_%s' % (line.id, field)
values[k] = _getattrstring(line, field)
#make the json serialization canonical
# (https://tools.ietf.org/html/draft-staykov-hu-json-canonical-form-00)
order.l10n_fr_string_to_hash = dumps(values, sort_keys=True,
ensure_ascii=True, indent=None,
separators=(',',':'))
def write(self, vals):
has_been_posted = False
for order in self:
if order.company_id._is_accounting_unalterable():
# write the hash and the secure_sequence_number when posting or invoicing an pos.order
if vals.get('state') in ['paid', 'done', 'invoiced']:
has_been_posted = True
# restrict the operation in case we are trying to write a forbidden field
if (order.state in ['paid', 'done', 'invoiced'] and set(vals).intersection(ORDER_FIELDS)):
raise UserError(_('According to the French law, you cannot modify a point of sale order. Forbidden fields: %s.') % ', '.join(ORDER_FIELDS))
# restrict the operation in case we are trying to overwrite existing hash
if (order.l10n_fr_hash and 'l10n_fr_hash' in vals) or (order.l10n_fr_secure_sequence_number and 'l10n_fr_secure_sequence_number' in vals):
raise UserError(_('You cannot overwrite the values ensuring the inalterability of the point of sale.'))
res = super(pos_order, self).write(vals)
# write the hash and the secure_sequence_number when posting or invoicing a pos order
if has_been_posted:
for order in self.filtered(lambda o: o.company_id._is_accounting_unalterable() and
not (o.l10n_fr_secure_sequence_number or o.l10n_fr_hash)):
new_number = order.company_id.l10n_fr_pos_cert_sequence_id.next_by_id()
vals_hashing = {'l10n_fr_secure_sequence_number': new_number,
'l10n_fr_hash': order._get_new_hash(new_number)}
res |= super(pos_order, order).write(vals_hashing)
return res
@api.ondelete(at_uninstall=True)
def _unlink_except_pos_so(self):
for order in self:
if order.company_id._is_accounting_unalterable():
raise UserError(_("According to French law, you cannot delete a point of sale order."))
def _export_for_ui(self, order):
res = super()._export_for_ui(order)
res['l10n_fr_hash'] = order.l10n_fr_hash
return res
class PosOrderLine(models.Model):
_inherit = "pos.order.line"
def write(self, vals):
# restrict the operation in case we are trying to write a forbidden field
if set(vals).intersection(LINE_FIELDS):
if any(l.company_id._is_accounting_unalterable() and l.order_id.state in ['done', 'invoiced'] for l in self):
raise UserError(_('According to the French law, you cannot modify a point of sale order line. Forbidden fields: %s.') % ', '.join(LINE_FIELDS))
return super(PosOrderLine, self).write(vals)
| 50.769231 | 7,260 |
9,391 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo import models, api, fields
from odoo.fields import Datetime as FieldDateTime
from odoo.tools.translate import _
from odoo.exceptions import UserError
from odoo.osv.expression import AND
class AccountClosing(models.Model):
"""
This object holds an interval total and a grand total of the accounts of type receivable for a company,
as well as the last account_move that has been counted in a previous object
It takes its earliest brother to infer from when the computation needs to be done
in order to compute its own data.
"""
_name = 'account.sale.closing'
_order = 'date_closing_stop desc, sequence_number desc'
_description = "Sale Closing"
name = fields.Char(help="Frequency and unique sequence number", required=True)
company_id = fields.Many2one('res.company', string='Company', readonly=True, required=True)
date_closing_stop = fields.Datetime(string="Closing Date", help='Date to which the values are computed', readonly=True, required=True)
date_closing_start = fields.Datetime(string="Starting Date", help='Date from which the total interval is computed', readonly=True, required=True)
frequency = fields.Selection(string='Closing Type', selection=[('daily', 'Daily'), ('monthly', 'Monthly'), ('annually', 'Annual')], readonly=True, required=True)
total_interval = fields.Monetary(string="Period Total", help='Total in receivable accounts during the interval, excluding overlapping periods', readonly=True, required=True)
cumulative_total = fields.Monetary(string="Cumulative Grand Total", help='Total in receivable accounts since the beginnig of times', readonly=True, required=True)
sequence_number = fields.Integer('Sequence #', readonly=True, required=True)
last_order_id = fields.Many2one('pos.order', string='Last Pos Order', help='Last Pos order included in the grand total', readonly=True)
last_order_hash = fields.Char(string='Last Order entry\'s inalteralbility hash', readonly=True)
currency_id = fields.Many2one('res.currency', string='Currency', help="The company's currency", readonly=True, related='company_id.currency_id', store=True)
def _query_for_aml(self, company, first_move_sequence_number, date_start):
params = {'company_id': company.id}
query = '''WITH aggregate AS (SELECT m.id AS move_id,
aml.balance AS balance,
aml.id as line_id
FROM account_move_line aml
JOIN account_journal j ON aml.journal_id = j.id
JOIN account_account acc ON acc.id = aml.account_id
JOIN account_account_type t ON (t.id = acc.user_type_id AND t.type = 'receivable')
JOIN account_move m ON m.id = aml.move_id
WHERE j.type = 'sale'
AND aml.company_id = %(company_id)s
AND m.state = 'posted' '''
if first_move_sequence_number is not False and first_move_sequence_number is not None:
params['first_move_sequence_number'] = first_move_sequence_number
query += '''AND m.secure_sequence_number > %(first_move_sequence_number)s'''
elif date_start:
#the first time we compute the closing, we consider only from the installation of the module
params['date_start'] = date_start
query += '''AND m.date >= %(date_start)s'''
query += " ORDER BY m.secure_sequence_number DESC) "
query += '''SELECT array_agg(move_id) AS move_ids,
array_agg(line_id) AS line_ids,
sum(balance) AS balance
FROM aggregate'''
self.env.cr.execute(query, params)
return self.env.cr.dictfetchall()[0]
def _compute_amounts(self, frequency, company):
"""
Method used to compute all the business data of the new object.
It will search for previous closings of the same frequency to infer the move from which
account move lines should be fetched.
@param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually)
frequencies are literal (daily means 24 hours and so on)
@param {recordset} company: the company for which the closing is done
@return {dict} containing {field: value} for each business field of the object
"""
interval_dates = self._interval_dates(frequency, company)
previous_closing = self.search([
('frequency', '=', frequency),
('company_id', '=', company.id)], limit=1, order='sequence_number desc')
first_order = self.env['pos.order']
date_start = interval_dates['interval_from']
cumulative_total = 0
if previous_closing:
first_order = previous_closing.last_order_id
date_start = previous_closing.create_date
cumulative_total += previous_closing.cumulative_total
domain = [('company_id', '=', company.id), ('state', 'in', ('paid', 'done', 'invoiced'))]
if first_order.l10n_fr_secure_sequence_number is not False and first_order.l10n_fr_secure_sequence_number is not None:
domain = AND([domain, [('l10n_fr_secure_sequence_number', '>', first_order.l10n_fr_secure_sequence_number)]])
elif date_start:
#the first time we compute the closing, we consider only from the installation of the module
domain = AND([domain, [('date_order', '>=', date_start)]])
orders = self.env['pos.order'].search(domain, order='date_order desc')
total_interval = sum(orders.mapped('amount_total'))
cumulative_total += total_interval
# We keep the reference to avoid gaps (like daily object during the weekend)
last_order = first_order
if orders:
last_order = orders[0]
return {'total_interval': total_interval,
'cumulative_total': cumulative_total,
'last_order_id': last_order.id,
'last_order_hash': last_order.l10n_fr_secure_sequence_number,
'date_closing_stop': interval_dates['date_stop'],
'date_closing_start': date_start,
'name': interval_dates['name_interval'] + ' - ' + interval_dates['date_stop'][:10]}
def _interval_dates(self, frequency, company):
"""
Method used to compute the theoretical date from which account move lines should be fetched
@param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually)
frequencies are literal (daily means 24 hours and so on)
@param {recordset} company: the company for which the closing is done
@return {dict} the theoretical date from which account move lines are fetched.
date_stop date to which the move lines are fetched, always now()
the dates are in their Odoo Database string representation
"""
date_stop = datetime.utcnow()
interval_from = None
name_interval = ''
if frequency == 'daily':
interval_from = date_stop - timedelta(days=1)
name_interval = _('Daily Closing')
elif frequency == 'monthly':
month_target = date_stop.month > 1 and date_stop.month - 1 or 12
year_target = month_target < 12 and date_stop.year or date_stop.year - 1
interval_from = date_stop.replace(year=year_target, month=month_target)
name_interval = _('Monthly Closing')
elif frequency == 'annually':
year_target = date_stop.year - 1
interval_from = date_stop.replace(year=year_target)
name_interval = _('Annual Closing')
return {'interval_from': FieldDateTime.to_string(interval_from),
'date_stop': FieldDateTime.to_string(date_stop),
'name_interval': name_interval}
def write(self, vals):
raise UserError(_('Sale Closings are not meant to be written or deleted under any circumstances.'))
@api.ondelete(at_uninstall=True)
def _unlink_never(self):
raise UserError(_('Sale Closings are not meant to be written or deleted under any circumstances.'))
@api.model
def _automated_closing(self, frequency='daily'):
"""To be executed by the CRON to create an object of the given frequency for each company that needs it
@param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually)
frequencies are literal (daily means 24 hours and so on)
@return {recordset} all the objects created for the given frequency
"""
res_company = self.env['res.company'].search([])
account_closings = self.env['account.sale.closing']
for company in res_company.filtered(lambda c: c._is_accounting_unalterable()):
new_sequence_number = company.l10n_fr_closing_sequence_id.next_by_id()
values = self._compute_amounts(frequency, company)
values['frequency'] = frequency
values['company_id'] = company.id
values['sequence_number'] = new_sequence_number
account_closings |= account_closings.create(values)
return account_closings
| 55.89881 | 9,391 |
4,716 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, fields, _
from odoo.exceptions import UserError
from datetime import datetime
from odoo.fields import Datetime, Date
from odoo.tools.misc import format_date
import pytz
def ctx_tz(record, field):
res_lang = None
ctx = record._context
tz_name = pytz.timezone(ctx.get('tz') or record.env.user.tz)
timestamp = Datetime.from_string(record[field])
if ctx.get('lang'):
res_lang = record.env['res.lang']._lang_get(ctx['lang'])
if res_lang:
timestamp = pytz.utc.localize(timestamp, is_dst=False)
return datetime.strftime(timestamp.astimezone(tz_name), res_lang.date_format + ' ' + res_lang.time_format)
return Datetime.context_timestamp(record, timestamp)
class ResCompany(models.Model):
_inherit = 'res.company'
l10n_fr_pos_cert_sequence_id = fields.Many2one('ir.sequence')
@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_pos_cert_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_pos_cert_sequence_id']
company._create_secure_sequence(sequence_fields)
return res
def _action_check_pos_hash_integrity(self):
return self.env.ref('l10n_fr_pos_cert.action_report_pos_hash_integrity').report_action(self.id)
def _check_pos_hash_integrity(self):
"""Checks that all posted or invoiced pos orders have still the same data as when they were posted
and raises an error with the result.
"""
def build_order_info(order):
entry_reference = _('(Receipt ref.: %s)')
order_reference_string = order.pos_reference and entry_reference % order.pos_reference or ''
return [ctx_tz(order, 'date_order'), order.l10n_fr_hash, order.name, order_reference_string, ctx_tz(order, 'write_date')]
msg_alert = ''
report_dict = {}
if self._is_accounting_unalterable():
orders = self.env['pos.order'].search([('state', 'in', ['paid', 'done', 'invoiced']), ('company_id', '=', self.id),
('l10n_fr_secure_sequence_number', '!=', 0)], order="l10n_fr_secure_sequence_number ASC")
if not orders:
msg_alert = (_('There isn\'t any order flagged for data inalterability yet for the company %s. This mechanism only runs for point of sale orders generated after the installation of the module France - Certification CGI 286 I-3 bis. - POS', self.env.company.name))
raise UserError(msg_alert)
previous_hash = u''
corrupted_orders = []
for order in orders:
if order.l10n_fr_hash != order._compute_hash(previous_hash=previous_hash):
corrupted_orders.append(order.name)
msg_alert = (_('Corrupted data on point of sale order with id %s.', order.id))
previous_hash = order.l10n_fr_hash
orders_sorted_date = orders.sorted(lambda o: o.date_order)
start_order_info = build_order_info(orders_sorted_date[0])
end_order_info = build_order_info(orders_sorted_date[-1])
report_dict.update({
'first_order_name': start_order_info[2],
'first_order_hash': start_order_info[1],
'first_order_date': start_order_info[0],
'last_order_name': end_order_info[2],
'last_order_hash': end_order_info[1],
'last_order_date': end_order_info[0],
})
corrupted_orders = ', '.join([o for o in corrupted_orders])
return {
'result': report_dict or 'None',
'msg_alert': msg_alert or 'None',
'printing_date': format_date(self.env, Date.to_string( Date.today())),
'corrupted_orders': corrupted_orders or 'None'
}
else:
raise UserError(_('Accounting is not unalterable for the company %s. This mechanism is designed for companies where accounting is unalterable.') % self.env.company.name)
| 48.122449 | 4,716 |
646 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import _, models
from odoo.exceptions import UserError
class AccountFiscalPosition(models.Model):
_inherit = "account.fiscal.position"
def write(self, vals):
if "tax_ids" in vals:
if self.env["pos.order"].sudo().search_count([("fiscal_position_id", "in", self.ids)]):
raise UserError(
_(
"You cannot modify a fiscal position used in a POS order. "
"You should archive it and create a new one."
)
)
return super(AccountFiscalPosition, self).write(vals)
| 34 | 646 |
1,344 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api
from odoo.tools.translate import _
from odoo.exceptions import UserError
class AccountBankStatement(models.Model):
_inherit = 'account.bank.statement'
@api.ondelete(at_uninstall=True)
def _unlink_except_created_by_pos(self):
for statement in self:
if not statement.company_id._is_accounting_unalterable() or not statement.journal_id.pos_payment_method_ids:
continue
if statement.state != 'open':
raise UserError(_('You cannot modify anything on a bank statement (name: %s) that was created by point of sale operations.') % statement.name)
class AccountBankStatementLine(models.Model):
_inherit = 'account.bank.statement.line'
@api.ondelete(at_uninstall=True)
def _unlink_except_created_by_pos(self):
for st_line in self:
statement = st_line.statement_id
if not statement.company_id._is_accounting_unalterable() or not statement.journal_id.pos_payment_method_ids:
continue
if statement.state != 'open':
raise UserError(_('You cannot modify anything on a bank statement (name: %s) that was created by point of sale operations.') % statement.name)
| 43.354839 | 1,344 |
699 |
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 ReportPosHashIntegrity(models.AbstractModel):
_name = 'report.l10n_fr_pos_cert.report_pos_hash_integrity'
_description = 'Get french pos hash integrity result as PDF.'
@api.model
def _get_report_values(self, docids, data=None):
data = data or {}
data.update(self.env.company._check_pos_hash_integrity() or {})
return {
'doc_ids' : docids,
'doc_model' : self.env['res.company'],
'data' : data,
'docs' : self.env['res.company'].browse(self.env.company.id),
}
| 34.95 | 699 |
1,031 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright: (C) 2012 - Mentis d.o.o., Dravograd
{
"name": "Slovenian - Accounting",
"version": "1.1",
"author": "Mentis d.o.o.",
"website": "http://www.mentis.si",
'category': 'Accounting/Localizations/Account Charts',
"description": "Kontni načrt za gospodarske družbe",
"depends": [
"account",
"base_iban",
],
"data": [
"data/l10n_si_chart_data.xml",
"data/account.account.template.csv",
"data/account.chart.template.csv",
"data/account.tax.group.csv",
"data/account_tax_report_data.xml",
"data/account_tax_data.xml",
"data/account.fiscal.position.template.csv",
"data/account.fiscal.position.account.template.csv",
"data/account.fiscal.position.tax.template.csv",
"data/account_chart_template_data.xml",
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 31.181818 | 1,029 |
819 |
py
|
PYTHON
|
15.0
|
#-*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Work Entries - Contract',
'category': 'Human Resources/Employees',
'sequence': 39,
'summary': 'Manage work entries',
'description': "",
'installable': True,
'depends': [
'hr_work_entry',
'hr_contract',
],
'data': [
'security/hr_work_entry_security.xml',
'security/ir.model.access.csv',
'data/hr_work_entry_data.xml',
'views/hr_work_entry_views.xml',
'wizard/hr_work_entry_regeneration_wizard_views.xml',
],
'demo': [
'data/hr_work_entry_demo.xml',
],
'assets': {
'web.assets_backend': [
'hr_work_entry_contract/static/src/**/*',
],
},
'license': 'LGPL-3',
}
| 26.419355 | 819 |
2,779 |
py
|
PYTHON
|
15.0
|
from odoo.addons.hr_work_entry_contract.models.hr_work_intervals import WorkIntervals
from odoo.tests.common import TransactionCase
class TestIntervals(TransactionCase):
def ints(self, pairs):
recs = self.env['base']
return [(a, b, recs) for a, b in pairs]
def test_union(self):
def check(a, b):
a, b = self.ints(a), self.ints(b)
self.assertEqual(list(WorkIntervals(a)), b)
check([(1, 2), (3, 4)], [(1, 2), (3, 4)])
check([(1, 2), (2, 4)], [(1, 2), (2, 4)])
check([(1, 3), (2, 4)], [(1, 4)])
check([(1, 4), (2, 3)], [(1, 4)])
check([(1, 4), (1, 4)], [(1, 4)])
check([(3, 4), (1, 2)], [(1, 2), (3, 4)])
check([(2, 4), (1, 2)], [(1, 2), (2, 4)])
check([(2, 4), (1, 3)], [(1, 4)])
check([(2, 3), (1, 4)], [(1, 4)])
def test_intersection(self):
def check(a, b, c):
a, b, c = self.ints(a), self.ints(b), self.ints(c)
self.assertEqual(list(WorkIntervals(a) & WorkIntervals(b)), c)
check([(10, 20)], [(5, 8)], [])
check([(10, 20)], [(5, 10)], [])
check([(10, 20)], [(5, 15)], [(10, 15)])
check([(10, 20)], [(5, 20)], [(10, 20)])
check([(10, 20)], [(5, 25)], [(10, 20)])
check([(10, 20)], [(10, 15)], [(10, 15)])
check([(10, 20)], [(10, 20)], [(10, 20)])
check([(10, 20)], [(10, 25)], [(10, 20)])
check([(10, 20)], [(15, 18)], [(15, 18)])
check([(10, 20)], [(15, 20)], [(15, 20)])
check([(10, 20)], [(15, 25)], [(15, 20)])
check([(10, 20)], [(20, 25)], [])
check(
[(0, 5), (10, 15), (20, 25), (30, 35)],
[(6, 7), (9, 12), (13, 17), (22, 23), (24, 40)],
[(10, 12), (13, 15), (22, 23), (24, 25), (30, 35)],
)
def test_difference(self):
def check(a, b, c):
a, b, c = self.ints(a), self.ints(b), self.ints(c)
self.assertEqual(list(WorkIntervals(a) - WorkIntervals(b)), c)
check([(10, 20)], [(5, 8)], [(10, 20)])
check([(10, 20)], [(5, 10)], [(10, 20)])
check([(10, 20)], [(5, 15)], [(15, 20)])
check([(10, 20)], [(5, 20)], [])
check([(10, 20)], [(5, 25)], [])
check([(10, 20)], [(10, 15)], [(15, 20)])
check([(10, 20)], [(10, 20)], [])
check([(10, 20)], [(10, 25)], [])
check([(10, 20)], [(15, 18)], [(10, 15), (18, 20)])
check([(10, 20)], [(15, 20)], [(10, 15)])
check([(10, 20)], [(15, 25)], [(10, 15)])
check([(10, 20)], [(20, 25)], [(10, 20)])
check(
[(0, 5), (10, 15), (20, 25), (30, 35)],
[(6, 7), (9, 12), (13, 17), (22, 23), (24, 40)],
[(0, 5), (12, 13), (20, 22), (23, 24)],
)
| 39.7 | 2,779 |
10,179 |
py
|
PYTHON
|
15.0
|
# # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from dateutil.relativedelta import relativedelta
from psycopg2 import IntegrityError
import pytz
from odoo.tests.common import tagged
from odoo.tools import mute_logger
from odoo.addons.hr_work_entry_contract.tests.common import TestWorkEntryBase
@tagged('work_entry')
class TestWorkEntry(TestWorkEntryBase):
def setUp(self):
super(TestWorkEntry, self).setUp()
self.tz = pytz.timezone(self.richard_emp.tz)
self.start = datetime(2015, 11, 1, 1, 0, 0)
self.end = datetime(2015, 11, 30, 23, 59, 59)
self.resource_calendar_id = self.env['resource.calendar'].create({'name': 'My Calendar'})
contract = self.env['hr.contract'].create({
'date_start': self.start.date() - relativedelta(days=5),
'name': 'dodo',
'resource_calendar_id': self.resource_calendar_id.id,
'wage': 1000,
'employee_id': self.richard_emp.id,
'state': 'open',
'date_generated_from': self.end.date() + relativedelta(days=5),
})
self.richard_emp.resource_calendar_id = self.resource_calendar_id
self.richard_emp.contract_id = contract
def test_no_duplicate(self):
self.richard_emp.generate_work_entries(self.start, self.end)
pou1 = self.env['hr.work.entry'].search_count([])
self.richard_emp.generate_work_entries(self.start, self.end)
pou2 = self.env['hr.work.entry'].search_count([])
self.assertEqual(pou1, pou2, "Work entries should not be duplicated")
def test_work_entry(self):
self.richard_emp.generate_work_entries(self.start, self.end)
attendance_nb = len(self.resource_calendar_id._attendance_intervals_batch(self.start.replace(tzinfo=pytz.utc), self.end.replace(tzinfo=pytz.utc))[False])
work_entry_nb = self.env['hr.work.entry'].search_count([
('employee_id', '=', self.richard_emp.id),
('date_start', '>=', self.start),
('date_stop', '<=', self.end)])
self.assertEqual(attendance_nb, work_entry_nb, "One work_entry should be generated for each calendar attendance")
def test_approve_multiple_day_work_entry(self):
start = datetime(2015, 11, 1, 9, 0, 0)
end = datetime(2015, 11, 3, 18, 0, 0)
work_entry = self.env['hr.work.entry'].create({
'name': '1',
'employee_id': self.richard_emp.id,
'contract_id': self.richard_emp.contract_id.id,
'date_start': start,
'date_stop': end,
'work_entry_type_id': self.work_entry_type.id,
})
work_entry.action_validate()
work_entries = self.env['hr.work.entry'].search([('employee_id', '=', self.richard_emp.id)])
self.assertTrue(all((b.state == 'validated' for b in work_entries)), "Work entries should be approved")
def test_validate_conflict_work_entry(self):
start = datetime(2015, 11, 1, 9, 0, 0)
end = datetime(2015, 11, 1, 13, 0, 0)
work_entry1 = self.env['hr.work.entry'].create({
'name': '1',
'employee_id': self.richard_emp.id,
'work_entry_type_id': self.env.ref('hr_work_entry.work_entry_type_attendance').id,
'contract_id': self.richard_emp.contract_id.id,
'date_start': start,
'date_stop': end + relativedelta(hours=5),
})
self.env['hr.work.entry'].create({
'name': '2',
'employee_id': self.richard_emp.id,
'work_entry_type_id': self.env.ref('hr_work_entry.work_entry_type_attendance').id,
'contract_id': self.richard_emp.contract_id.id,
'date_start': start + relativedelta(hours=3),
'date_stop': end,
})
self.assertFalse(work_entry1.action_validate(), "It should not validate work_entries conflicting with others")
self.assertEqual(work_entry1.state, 'conflict')
self.assertNotEqual(work_entry1.state, 'validated')
def test_validate_undefined_work_entry(self):
work_entry1 = self.env['hr.work.entry'].create({
'name': '1',
'employee_id': self.richard_emp.id,
'contract_id': self.richard_emp.contract_id.id,
'date_start': self.start,
'date_stop': self.end,
})
self.assertFalse(work_entry1.action_validate(), "It should not validate work_entries without a type")
self.assertEqual(work_entry1.state, 'conflict', "It should change to conflict state")
work_entry1.work_entry_type_id = self.work_entry_type
self.assertTrue(work_entry1.action_validate(), "It should validate work_entries")
def test_outside_calendar(self):
""" Test leave work entries outside schedule are conflicting """
# Outside but not a leave
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 3, 0), datetime(2018, 10, 10, 4, 0))
# Outside and a leave
work_entry_2 = self.create_work_entry(datetime(2018, 10, 10, 1, 0), datetime(2018, 10, 10, 2, 0), work_entry_type=self.work_entry_type_leave)
# Overlapping and a leave
work_entry_3 = self.create_work_entry(datetime(2018, 10, 10, 7, 0), datetime(2018, 10, 10, 10, 0), work_entry_type=self.work_entry_type_leave)
# Overlapping and not a leave
work_entry_4 = self.create_work_entry(datetime(2018, 10, 10, 11, 0), datetime(2018, 10, 10, 13, 0))
(work_entry_1 | work_entry_2 | work_entry_3 | work_entry_4)._mark_leaves_outside_schedule()
self.assertEqual(work_entry_2.state, 'conflict', "It should conflict")
self.assertNotEqual(work_entry_1.state, 'conflict', "It should not conflict")
self.assertNotEqual(work_entry_3.state, 'conflict', "It should not conflict")
self.assertNotEqual(work_entry_4.state, 'conflict', "It should not conflict")
def test_write_conflict(self):
""" Test updating work entries dates recomputes conflicts """
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 9, 0), datetime(2018, 10, 10, 12, 0))
work_entry_2 = self.create_work_entry(datetime(2018, 10, 10, 12, 0), datetime(2018, 10, 10, 18, 0))
self.assertNotEqual(work_entry_1.state, 'conflict', "It should not conflict")
self.assertNotEqual(work_entry_2.state, 'conflict', "It should not conflict")
work_entry_1.date_stop = datetime(2018, 10, 10, 14, 0)
self.assertEqual(work_entry_1.state, 'conflict', "It should conflict")
self.assertEqual(work_entry_2.state, 'conflict', "It should conflict")
work_entry_1.date_stop = datetime(2018, 10, 10, 12, 0) # cancel conflict
self.assertNotEqual(work_entry_1.state, 'conflict', "It should no longer conflict")
self.assertNotEqual(work_entry_2.state, 'conflict', "It should no longer conflict")
def test_write_move(self):
""" Test completely moving a work entry recomputes conflicts """
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 9, 0), datetime(2018, 10, 10, 12, 0))
work_entry_2 = self.create_work_entry(datetime(2018, 10, 18, 9, 0), datetime(2018, 10, 18, 12, 0))
work_entry_3 = self.create_work_entry(datetime(2018, 10, 18, 10, 0), datetime(2018, 10, 18, 12, 0))
work_entry_2.write({
'date_start': datetime(2018, 10, 10, 9, 0),
'date_stop': datetime(2018, 10, 10, 10, 0),
})
self.assertEqual(work_entry_1.state, 'conflict')
self.assertEqual(work_entry_2.state, 'conflict')
self.assertNotEqual(work_entry_3.state, 'conflict')
def test_create_conflict(self):
""" Test creating a work entry recomputes conflicts """
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 9, 0), datetime(2018, 10, 10, 12, 0))
self.assertNotEqual(work_entry_1.state, 'conflict', "It should not conflict")
work_entry_2 = self.create_work_entry(datetime(2018, 10, 10, 10, 0), datetime(2018, 10, 10, 18, 0))
self.assertEqual(work_entry_1.state, 'conflict', "It should conflict")
self.assertEqual(work_entry_2.state, 'conflict', "It should conflict")
def test_unarchive_conflict(self):
""" Test archive/unarchive a work entry recomputes conflicts """
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 9, 0), datetime(2018, 10, 10, 12, 0))
work_entry_2 = self.create_work_entry(datetime(2018, 10, 10, 10, 0), datetime(2018, 10, 10, 18, 0))
work_entry_2.active = False
self.assertNotEqual(work_entry_1.state, 'conflict', "It should not conflict")
self.assertEqual(work_entry_2.state, 'cancelled', "It should be cancelled")
work_entry_2.active = True
self.assertEqual(work_entry_1.state, 'conflict', "It should conflict")
self.assertEqual(work_entry_2.state, 'conflict', "It should conflict")
def test_validated_no_conflict(self):
""" Test validating a work entry removes the conflict """
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 9, 0), datetime(2018, 10, 10, 12, 0))
work_entry_1.state = 'validated'
work_entry_2 = self.create_work_entry(datetime(2018, 10, 10, 10, 0), datetime(2018, 10, 10, 18, 0))
self.assertEqual(work_entry_1.state, 'conflict', "It should not conflict")
self.assertEqual(work_entry_2.state, 'conflict', "It should conflict")
def test_no_overlap_sql_constraint(self):
""" Test _work_entries_no_validated_conflict sql constrains """
work_entry_1 = self.create_work_entry(datetime(2018, 10, 10, 9, 0), datetime(2018, 10, 10, 12, 0))
work_entry_1.state = 'validated'
work_entry_2 = self.create_work_entry(datetime(2018, 10, 10, 8, 0), datetime(2018, 10, 10, 10, 0))
self.assertEqual(work_entry_1.state, 'conflict')
with mute_logger('odoo.sql_db'):
with self.assertRaises(IntegrityError):
with self.cr.savepoint():
(work_entry_1 + work_entry_2).write({'state': 'validated'})
| 55.928571 | 10,179 |
2,286 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo.fields import Date
from odoo.tests.common import TransactionCase
class TestWorkEntryBase(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestWorkEntryBase, cls).setUpClass()
cls.env.user.tz = 'Europe/Brussels'
cls.env.ref('resource.resource_calendar_std').tz = 'Europe/Brussels'
cls.dep_rd = cls.env['hr.department'].create({
'name': 'Research & Development - Test',
})
# I create a new employee "Richard"
cls.richard_emp = cls.env['hr.employee'].create({
'name': 'Richard',
'gender': 'male',
'birthday': '1984-05-01',
'country_id': cls.env.ref('base.be').id,
'department_id': cls.dep_rd.id,
})
# I create a contract for "Richard"
cls.env['hr.contract'].create({
'date_end': Date.today() + relativedelta(years=2),
'date_start': Date.to_date('2018-01-01'),
'name': 'Contract for Richard',
'wage': 5000.0,
'employee_id': cls.richard_emp.id,
})
cls.work_entry_type = cls.env['hr.work.entry.type'].create({
'name': 'Extra attendance',
'is_leave': False,
'code': 'WORKTEST200',
})
cls.work_entry_type_unpaid = cls.env['hr.work.entry.type'].create({
'name': 'Unpaid Leave',
'is_leave': True,
'code': 'LEAVETEST300',
})
cls.work_entry_type_leave = cls.env['hr.work.entry.type'].create({
'name': 'Leave',
'is_leave': True,
'code': 'LEAVETEST100'
})
def create_work_entry(self, start, stop, work_entry_type=None):
work_entry_type = work_entry_type or self.work_entry_type
return self.env['hr.work.entry'].create({
'contract_id': self.richard_emp.contract_ids[0].id,
'name': "Work entry %s-%s" % (start, stop),
'date_start': start,
'date_stop': stop,
'employee_id': self.richard_emp.id,
'work_entry_type_id': work_entry_type.id,
})
| 34.119403 | 2,286 |
1,566 |
py
|
PYTHON
|
15.0
|
# # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from .common import TestWorkEntryBase
from datetime import datetime
from odoo.tests import tagged
@tagged('-at_install', 'post_install')
class TestGlobalTimeOff(TestWorkEntryBase):
def test_gto_other_calendar(self):
# Tests that a global time off in another calendar does not affect work entry generation
# for other calendars
other_calendar = self.env['resource.calendar'].create({
'name': 'other calendar',
})
start = datetime(2018, 1, 1, 0, 0, 0)
end = datetime(2018, 1, 1, 23, 59, 59)
leave = self.env['resource.calendar.leaves'].create({
'date_from': start,
'date_to': end,
'calendar_id': other_calendar.id,
'work_entry_type_id': self.work_entry_type_leave.id,
})
contract = self.richard_emp.contract_ids
contract.state = 'open'
contract.date_generated_from = start
contract.date_generated_to = start
work_entries = contract._generate_work_entries(start, end)
self.assertEqual(work_entries.work_entry_type_id, contract._get_default_work_entry_type())
work_entries.unlink()
contract.date_generated_from = start
contract.date_generated_to = start
leave.calendar_id = contract.resource_calendar_id
work_entries = contract._generate_work_entries(start, end)
self.assertEqual(work_entries.work_entry_type_id, leave.work_entry_type_id)
| 41.210526 | 1,566 |
6,162 |
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 HrWorkEntryRegenerationWizard(models.TransientModel):
_name = 'hr.work.entry.regeneration.wizard'
_description = 'Regenerate Employee Work Entries'
earliest_available_date = fields.Date('Earliest date', compute='_compute_earliest_available_date')
earliest_available_date_message = fields.Char(readonly=True, store=False, default='')
latest_available_date = fields.Date('Latest date', compute='_compute_latest_available_date')
latest_available_date_message = fields.Char(readonly=True, store=False, default='')
date_from = fields.Date('From', required=True, default=lambda self: self.env.context.get('date_start'))
date_to = fields.Date('To', required=True, default=lambda self: self.env.context.get('date_end'))
employee_id = fields.Many2one('hr.employee', 'Employee', required=True)
validated_work_entry_ids = fields.Many2many('hr.work.entry', string='Work Entries Within Interval',
compute='_compute_validated_work_entry_ids')
search_criteria_completed = fields.Boolean(compute='_compute_search_criteria_completed')
valid = fields.Boolean(compute='_compute_valid')
@api.depends('employee_id')
def _compute_earliest_available_date(self):
for wizard in self:
dates = wizard.mapped('employee_id.contract_ids.date_generated_from')
wizard.earliest_available_date = min(dates) if dates else None
@api.depends('employee_id')
def _compute_latest_available_date(self):
for wizard in self:
dates = wizard.mapped('employee_id.contract_ids.date_generated_to')
wizard.latest_available_date = max(dates) if dates else None
@api.depends('date_from', 'date_to', 'employee_id')
def _compute_validated_work_entry_ids(self):
for wizard in self:
validated_work_entry_ids = self.env['hr.work.entry']
if wizard.search_criteria_completed:
search_domain = [('employee_id', '=', self.employee_id.id),
('date_start', '>=', self.date_from),
('date_stop', '<=', self.date_to),
('state', '=', 'validated')]
validated_work_entry_ids = self.env['hr.work.entry'].search(search_domain, order="date_start")
wizard.validated_work_entry_ids = validated_work_entry_ids
@api.depends('validated_work_entry_ids')
def _compute_valid(self):
for wizard in self:
wizard.valid = wizard.search_criteria_completed and len(wizard.validated_work_entry_ids) == 0
@api.depends('date_from', 'date_to', 'employee_id')
def _compute_search_criteria_completed(self):
for wizard in self:
wizard.search_criteria_completed = wizard.date_from and wizard.date_to and wizard.employee_id and wizard.earliest_available_date and wizard.latest_available_date
@api.onchange('date_from', 'date_to', 'employee_id')
def _check_dates(self):
for wizard in self:
wizard.earliest_available_date_message = ''
wizard.latest_available_date_message = ''
if wizard.search_criteria_completed:
if wizard.date_from > wizard.date_to:
date_from = wizard.date_from
wizard.date_from = wizard.date_to
wizard.date_to = date_from
if wizard.earliest_available_date and wizard.date_from < wizard.earliest_available_date:
wizard.date_from = wizard.earliest_available_date
wizard.earliest_available_date_message = 'The earliest available date is {date}' \
.format(date=self._date_to_string(wizard.earliest_available_date))
if wizard.latest_available_date and wizard.date_to > wizard.latest_available_date:
wizard.date_to = wizard.latest_available_date
wizard.latest_available_date_message = 'The latest available date is {date}' \
.format(date=self._date_to_string(wizard.latest_available_date))
@api.model
def _date_to_string(self, date):
if not date:
return ''
user_date_format = self.env['res.lang']._lang_get(self.env.user.lang).date_format
return date.strftime(user_date_format)
def regenerate_work_entries(self):
self.ensure_one()
if not self.env.context.get('work_entry_skip_validation'):
if not self.valid:
raise ValidationError(_("In order to regenerate the work entries, you need to provide the wizard with an employee_id, a date_from and a date_to. In addition to that, the time interval defined by date_from and date_to must not contain any validated work entries."))
if self.date_from < self.earliest_available_date or self.date_to > self.latest_available_date:
raise ValidationError(_("The from date must be >= '%(earliest_available_date)s' and the to date must be <= '%(latest_available_date)s', which correspond to the generated work entries time interval.", earliest_available_date=self._date_to_string(self.earliest_available_date), latest_available_date=self._date_to_string(self.latest_available_date)))
date_from = max(self.date_from, self.earliest_available_date) if self.earliest_available_date else self.date_from
date_to = min(self.date_to, self.latest_available_date) if self.latest_available_date else self.date_to
work_entries = self.env['hr.work.entry'].search([
('employee_id', '=', self.employee_id.id),
('date_stop', '>=', date_from),
('date_start', '<=', date_to),
('state', '!=', 'validated')])
work_entries.write({'active': False})
self.employee_id.generate_work_entries(date_from, date_to, True)
action = self.env["ir.actions.actions"]._for_xml_id('hr_work_entry.hr_work_entry_action')
return action
| 59.25 | 6,162 |
3,625 |
py
|
PYTHON
|
15.0
|
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from itertools import chain
def _boundaries(intervals, opening, closing):
""" Iterate on the boundaries of intervals. """
for start, stop, recs in intervals:
if start < stop:
yield (start, opening, recs)
yield (stop, closing, recs)
class WorkIntervals(object):
"""
This class is a modified copy of the ``Intervals`` class in the resource module.
A generic solution to handle intervals should probably be developped the day a similar
class is needed elsewhere.
This implementation differs from the resource implementation in its management
of two continuous intervals. Here, continuous intervals are not merged together
while they are merged in resource.
e.g.:
In resource: (1, 4, rec1) and (4, 10, rec2) are merged into (1, 10, rec1 | rec2)
Here: they remain two different intervals.
To implement this behaviour, the main implementation change is the way boundaries are sorted.
"""
def __init__(self, intervals=()):
self._items = []
if intervals:
# normalize the representation of intervals
append = self._items.append
starts = []
recses = []
for value, flag, recs in sorted(_boundaries(sorted(intervals), 'start', 'stop'), key=lambda i: i[0]):
if flag == 'start':
starts.append(value)
recses.append(recs)
else:
start = starts.pop()
if not starts:
append((start, value, recses[0].union(*recses)))
recses.clear()
def __bool__(self):
return bool(self._items)
def __len__(self):
return len(self._items)
def __iter__(self):
return iter(self._items)
def __reversed__(self):
return reversed(self._items)
def __or__(self, other):
""" Return the union of two sets of intervals. """
return WorkIntervals(chain(self._items, other._items))
def __and__(self, other):
""" Return the intersection of two sets of intervals. """
return self._merge(other, False)
def __sub__(self, other):
""" Return the difference of two sets of intervals. """
return self._merge(other, True)
def _merge(self, other, difference):
""" Return the difference or intersection of two sets of intervals. """
result = WorkIntervals()
append = result._items.append
# using 'self' and 'other' below forces normalization
bounds1 = _boundaries(sorted(self), 'start', 'stop')
bounds2 = _boundaries(sorted(other), 'switch', 'switch')
start = None # set by start/stop
recs1 = None # set by start
enabled = difference # changed by switch
for value, flag, recs in sorted(chain(bounds1, bounds2), key=lambda i: i[0]):
if flag == 'start':
start = value
recs1 = recs
elif flag == 'stop':
if enabled and start < value:
append((start, value, recs1))
start = None
else:
if not enabled and start is not None:
start = value
if enabled and start is not None and start < value:
append((start, value, recs1))
enabled = not enabled
return result
| 37.371134 | 3,625 |
733 |
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'
_description = 'Employee'
def generate_work_entries(self, date_start, date_stop, force=False):
date_start = fields.Date.to_date(date_start)
date_stop = fields.Date.to_date(date_stop)
if self:
current_contracts = self._get_contracts(date_start, date_stop, states=['open', 'close'])
else:
current_contracts = self._get_all_contracts(date_start, date_stop, states=['open', 'close'])
return bool(current_contracts._generate_work_entries(date_start, date_stop, force))
| 36.65 | 733 |
15,551 |
py
|
PYTHON
|
15.0
|
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from datetime import datetime, date
from odoo import fields, models, _
from odoo.addons.resource.models.resource import datetime_to_string, string_to_datetime, Intervals
from odoo.osv import expression
from odoo.exceptions import UserError
import pytz
class HrContract(models.Model):
_inherit = 'hr.contract'
_description = 'Employee Contract'
date_generated_from = fields.Datetime(string='Generated From', readonly=True, required=True,
default=lambda self: datetime.now().replace(hour=0, minute=0, second=0), copy=False)
date_generated_to = fields.Datetime(string='Generated To', readonly=True, required=True,
default=lambda self: datetime.now().replace(hour=0, minute=0, second=0), copy=False)
def _get_default_work_entry_type(self):
return self.env.ref('hr_work_entry.work_entry_type_attendance', raise_if_not_found=False)
def _get_leave_work_entry_type_dates(self, leave, date_from, date_to, employee):
return self._get_leave_work_entry_type(leave)
def _get_leave_work_entry_type(self, leave):
return leave.work_entry_type_id
# Is used to add more values, for example leave_id (in hr_work_entry_holidays)
def _get_more_vals_leave_interval(self, interval, leaves):
return []
def _get_bypassing_work_entry_type_codes(self):
return []
def _get_interval_leave_work_entry_type(self, interval, leaves, bypassing_codes):
# returns the work entry time related to the leave that
# includes the whole interval.
# Overriden in hr_work_entry_contract_holiday to select the
# global time off first (eg: Public Holiday > Home Working)
self.ensure_one()
for leave in leaves:
if interval[0] >= leave[0] and interval[1] <= leave[1] and leave[2]:
interval_start = interval[0].astimezone(pytz.utc).replace(tzinfo=None)
interval_stop = interval[1].astimezone(pytz.utc).replace(tzinfo=None)
return self._get_leave_work_entry_type_dates(leave[2], interval_start, interval_stop, self.employee_id)
return self.env.ref('hr_work_entry_contract.work_entry_type_leave')
def _get_leave_domain(self, start_dt, end_dt):
self.ensure_one()
return [
('time_type', '=', 'leave'),
('calendar_id', 'in', [False, self.resource_calendar_id.id]),
('resource_id', 'in', [False, self.employee_id.resource_id.id]),
('date_from', '<=', end_dt),
('date_to', '>=', start_dt),
('company_id', 'in', [False, self.company_id.id]),
]
def _get_contract_work_entries_values(self, date_start, date_stop):
contract_vals = []
bypassing_work_entry_type_codes = self._get_bypassing_work_entry_type_codes()
for contract in self:
employee = contract.employee_id
calendar = contract.resource_calendar_id
resource = employee.resource_id
tz = pytz.timezone(calendar.tz)
start_dt = pytz.utc.localize(date_start) if not date_start.tzinfo else date_start
end_dt = pytz.utc.localize(date_stop) if not date_stop.tzinfo else date_stop
attendances = calendar._attendance_intervals_batch(
start_dt, end_dt, resources=resource, tz=tz
)[resource.id]
# Other calendars: In case the employee has declared time off in another calendar
# Example: Take a time off, then a credit time.
# YTI TODO: This mimics the behavior of _leave_intervals_batch, while waiting to be cleaned
# in master.
resources_list = [self.env['resource.resource'], resource]
resource_ids = [False, resource.id]
leave_domain = contract._get_leave_domain(start_dt, end_dt)
result = defaultdict(lambda: [])
tz_dates = {}
for leave in self.env['resource.calendar.leaves'].sudo().search(leave_domain):
for resource in resources_list:
if leave.resource_id.id not in [False, resource.id]:
continue
tz = tz if tz else pytz.timezone((resource or contract).tz)
if (tz, start_dt) in tz_dates:
start = tz_dates[(tz, start_dt)]
else:
start = start_dt.astimezone(tz)
tz_dates[(tz, start_dt)] = start
if (tz, end_dt) in tz_dates:
end = tz_dates[(tz, end_dt)]
else:
end = end_dt.astimezone(tz)
tz_dates[(tz, end_dt)] = end
dt0 = string_to_datetime(leave.date_from).astimezone(tz)
dt1 = string_to_datetime(leave.date_to).astimezone(tz)
result[resource.id].append((max(start, dt0), min(end, dt1), leave))
mapped_leaves = {r.id: Intervals(result[r.id]) for r in resources_list}
leaves = mapped_leaves[resource.id]
real_attendances = attendances - leaves
real_leaves = attendances - real_attendances
# A leave period can be linked to several resource.calendar.leave
split_leaves = []
for leave_interval in leaves:
if leave_interval[2] and len(leave_interval[2]) > 1:
split_leaves += [(leave_interval[0], leave_interval[1], l) for l in leave_interval[2]]
else:
split_leaves += [(leave_interval[0], leave_interval[1], leave_interval[2])]
leaves = split_leaves
# Attendances
default_work_entry_type = contract._get_default_work_entry_type()
for interval in real_attendances:
work_entry_type_id = interval[2].mapped('work_entry_type_id')[:1] or default_work_entry_type
# All benefits generated here are using datetimes converted from the employee's timezone
contract_vals += [{
'name': "%s: %s" % (work_entry_type_id.name, employee.name),
'date_start': interval[0].astimezone(pytz.utc).replace(tzinfo=None),
'date_stop': interval[1].astimezone(pytz.utc).replace(tzinfo=None),
'work_entry_type_id': work_entry_type_id.id,
'employee_id': employee.id,
'contract_id': contract.id,
'company_id': contract.company_id.id,
'state': 'draft',
}]
for interval in real_leaves:
# Could happen when a leave is configured on the interface on a day for which the
# employee is not supposed to work, i.e. no attendance_ids on the calendar.
# In that case, do try to generate an empty work entry, as this would raise a
# sql constraint error
if interval[0] == interval[1]: # if start == stop
continue
leave_entry_type = contract._get_interval_leave_work_entry_type(interval, leaves, bypassing_work_entry_type_codes)
interval_leaves = [leave for leave in leaves if leave[2].work_entry_type_id.id == leave_entry_type.id]
interval_start = interval[0].astimezone(pytz.utc).replace(tzinfo=None)
interval_stop = interval[1].astimezone(pytz.utc).replace(tzinfo=None)
contract_vals += [dict([
('name', "%s%s" % (leave_entry_type.name + ": " if leave_entry_type else "", employee.name)),
('date_start', interval_start),
('date_stop', interval_stop),
('work_entry_type_id', leave_entry_type.id),
('employee_id', employee.id),
('company_id', contract.company_id.id),
('state', 'draft'),
('contract_id', contract.id),
] + contract._get_more_vals_leave_interval(interval, interval_leaves))]
return contract_vals
def _get_work_entries_values(self, date_start, date_stop):
"""
Generate a work_entries list between date_start and date_stop for one contract.
:return: list of dictionnary.
"""
contract_vals = self._get_contract_work_entries_values(date_start, date_stop)
for contract in self:
# If we generate work_entries which exceeds date_start or date_stop, we change boundaries on contract
if contract_vals:
#Handle empty work entries for certain contracts, could happen on an attendance based contract
#NOTE: this does not handle date_stop or date_start not being present in vals
dates_stop = [x['date_stop'] for x in contract_vals if x['contract_id'] == contract.id]
if dates_stop:
date_stop_max = max(dates_stop)
if date_stop_max > contract.date_generated_to:
contract.date_generated_to = date_stop_max
dates_start = [x['date_start'] for x in contract_vals if x['contract_id'] == contract.id]
if dates_start:
date_start_min = min(dates_start)
if date_start_min < contract.date_generated_from:
contract.date_generated_from = date_start_min
return contract_vals
def _generate_work_entries(self, date_start, date_stop, force=False):
canceled_contracts = self.filtered(lambda c: c.state == 'cancel')
if canceled_contracts:
raise UserError(
_("Sorry, generating work entries from cancelled contracts is not allowed.") + '\n%s' % (
', '.join(canceled_contracts.mapped('name'))))
vals_list = []
date_start = fields.Datetime.to_datetime(date_start)
date_stop = datetime.combine(fields.Datetime.to_datetime(date_stop), datetime.max.time())
intervals_to_generate = defaultdict(lambda: self.env['hr.contract'])
for contract in self:
contract_start = fields.Datetime.to_datetime(contract.date_start)
contract_stop = datetime.combine(fields.Datetime.to_datetime(contract.date_end or datetime.max.date()),
datetime.max.time())
date_start_work_entries = max(date_start, contract_start)
date_stop_work_entries = min(date_stop, contract_stop)
if force:
intervals_to_generate[(date_start_work_entries, date_stop_work_entries)] |= contract
continue
# In case the date_generated_from == date_generated_to, move it to the date_start to
# avoid trying to generate several months/years of history for old contracts for which
# we've never generated the work entries.
if contract.date_generated_from == contract.date_generated_to:
contract.write({
'date_generated_from': date_start,
'date_generated_to': date_start,
})
# For each contract, we found each interval we must generate
last_generated_from = min(contract.date_generated_from, contract_stop)
if last_generated_from > date_start_work_entries:
contract.date_generated_from = date_start_work_entries
intervals_to_generate[(date_start_work_entries, last_generated_from)] |= contract
last_generated_to = max(contract.date_generated_to, contract_start)
if last_generated_to < date_stop_work_entries:
contract.date_generated_to = date_stop_work_entries
intervals_to_generate[(last_generated_to, date_stop_work_entries)] |= contract
for interval, contracts in intervals_to_generate.items():
date_from, date_to = interval
vals_list.extend(contracts._get_work_entries_values(date_from, date_to))
if not vals_list:
return self.env['hr.work.entry']
return self.env['hr.work.entry'].create(vals_list)
def _remove_work_entries(self):
''' Remove all work_entries that are outside contract period (function used after writing new start or/and end date) '''
all_we_to_unlink = self.env['hr.work.entry']
for contract in self:
date_start = fields.Datetime.to_datetime(contract.date_start)
if contract.date_generated_from < date_start:
we_to_remove = self.env['hr.work.entry'].search([('date_stop', '<=', date_start), ('contract_id', '=', contract.id)])
if we_to_remove:
contract.date_generated_from = date_start
all_we_to_unlink |= we_to_remove
if not contract.date_end:
continue
date_end = datetime.combine(contract.date_end, datetime.max.time())
if contract.date_generated_to > date_end:
we_to_remove = self.env['hr.work.entry'].search([('date_start', '>=', date_end), ('contract_id', '=', contract.id)])
if we_to_remove:
contract.date_generated_to = date_end
all_we_to_unlink |= we_to_remove
all_we_to_unlink.unlink()
def _cancel_work_entries(self):
if not self:
return
domain = [('state', '!=', 'validated')]
for contract in self:
date_start = fields.Datetime.to_datetime(contract.date_start)
contract_domain = [
('contract_id', '=', contract.id),
('date_start', '>=', date_start),
]
if contract.date_end:
date_end = datetime.combine(contract.date_end, datetime.max.time())
contract_domain += [('date_stop', '<=', date_end)]
domain = expression.AND([domain, contract_domain])
work_entries = self.env['hr.work.entry'].search(domain)
if work_entries:
work_entries.unlink()
def write(self, vals):
result = super(HrContract, self).write(vals)
if vals.get('date_end') or vals.get('date_start'):
self.sudo()._remove_work_entries()
if vals.get('state') in ['draft', 'cancel']:
self._cancel_work_entries()
dependendant_fields = self._get_fields_that_recompute_we()
if any(key in dependendant_fields for key in vals.keys()):
for contract in self:
date_from = max(contract.date_start, contract.date_generated_from.date())
date_to = min(contract.date_end or date.max, contract.date_generated_to.date())
if date_from != date_to:
contract._recompute_work_entries(date_from, date_to)
return result
def _recompute_work_entries(self, date_from, date_to):
self.ensure_one()
wizard = self.env['hr.work.entry.regeneration.wizard'].create({
'employee_id': self.employee_id.id,
'date_from': date_from,
'date_to': date_to,
})
wizard.with_context(work_entry_skip_validation=True).regenerate_work_entries()
def _get_fields_that_recompute_we(self):
# Returns the fields that should recompute the work entries
return ['resource_calendar_id']
| 52.360269 | 15,551 |
6,865 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import pytz
from collections import defaultdict
from itertools import chain
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.addons.hr_work_entry_contract.models.hr_work_intervals import WorkIntervals
class HrWorkEntry(models.Model):
_inherit = 'hr.work.entry'
contract_id = fields.Many2one('hr.contract', string="Contract", required=True)
employee_id = fields.Many2one(domain=[('contract_ids.state', 'in', ('open', 'pending'))])
def _init_column(self, column_name):
if column_name != 'contract_id':
super()._init_column(column_name)
else:
self.env.cr.execute("""
UPDATE hr_work_entry AS _hwe
SET contract_id = result.contract_id
FROM (
SELECT
hc.id AS contract_id,
array_agg(hwe.id) AS entry_ids
FROM
hr_work_entry AS hwe
LEFT JOIN
hr_contract AS hc
ON
hwe.employee_id=hc.employee_id AND
hc.state in ('open', 'close') AND
hwe.date_start >= hc.date_start AND
hwe.date_stop < COALESCE(hc.date_end + integer '1', '9999-12-31 23:59:59')
WHERE
hwe.contract_id IS NULL
GROUP BY
hwe.employee_id, hc.id
) AS result
WHERE _hwe.id = ANY(result.entry_ids)
""")
def _get_duration_is_valid(self):
return self.work_entry_type_id and self.work_entry_type_id.is_leave
@api.onchange('employee_id', 'date_start', 'date_stop')
def _onchange_contract_id(self):
vals = {
'employee_id': self.employee_id.id,
'date_start': self.date_start,
'date_stop': self.date_stop,
}
try:
res = self._set_current_contract(vals)
except ValidationError:
return
if res.get('contract_id'):
self.contract_id = res.get('contract_id')
@api.depends('date_start', 'duration')
def _compute_date_stop(self):
for work_entry in self:
if work_entry._get_duration_is_valid():
calendar = work_entry.contract_id.resource_calendar_id
if not calendar:
continue
work_entry.date_stop = calendar.plan_hours(work_entry.duration, work_entry.date_start, compute_leaves=True)
continue
super(HrWorkEntry, work_entry)._compute_date_stop()
def _get_duration(self, date_start, date_stop):
if not date_start or not date_stop:
return 0
if self._get_duration_is_valid():
calendar = self.contract_id.resource_calendar_id
if not calendar:
return 0
employee = self.contract_id.employee_id
contract_data = employee._get_work_days_data_batch(
date_start, date_stop, compute_leaves=False, calendar=calendar
)[employee.id]
return contract_data.get('hours', 0)
return super()._get_duration(date_start, date_stop)
@api.model
def _set_current_contract(self, vals):
if not vals.get('contract_id') and vals.get('date_start') and vals.get('date_stop') and vals.get('employee_id'):
contract_start = fields.Datetime.to_datetime(vals.get('date_start')).date()
contract_end = fields.Datetime.to_datetime(vals.get('date_stop')).date()
employee = self.env['hr.employee'].browse(vals.get('employee_id'))
contracts = employee._get_contracts(contract_start, contract_end, states=['open', 'pending', 'close'])
if not contracts:
raise ValidationError(_("%s does not have a contract from %s to %s.") % (employee.name, contract_start, contract_end))
elif len(contracts) > 1:
raise ValidationError(_("%s has multiple contracts from %s to %s. A work entry cannot overlap multiple contracts.")
% (employee.name, contract_start, contract_end))
return dict(vals, contract_id=contracts[0].id)
return vals
@api.model_create_multi
def create(self, vals_list):
vals_list = [self._set_current_contract(vals) for vals in vals_list]
work_entries = super().create(vals_list)
return work_entries
def _check_if_error(self):
res = super()._check_if_error()
outside_calendar = self._mark_leaves_outside_schedule()
return res or outside_calendar
def _get_leaves_entries_outside_schedule(self):
return self.filtered(lambda w: w.work_entry_type_id.is_leave and w.state not in ('validated', 'cancelled'))
def _mark_leaves_outside_schedule(self):
"""
Check leave work entries in `self` which are completely outside
the contract's theoretical calendar schedule. Mark them as conflicting.
:return: leave work entries completely outside the contract's calendar
"""
work_entries = self._get_leaves_entries_outside_schedule()
entries_by_calendar = defaultdict(lambda: self.env['hr.work.entry'])
for work_entry in work_entries:
calendar = work_entry.contract_id.resource_calendar_id
entries_by_calendar[calendar] |= work_entry
outside_entries = self.env['hr.work.entry']
for calendar, entries in entries_by_calendar.items():
datetime_start = min(entries.mapped('date_start'))
datetime_stop = max(entries.mapped('date_stop'))
calendar_intervals = calendar._attendance_intervals_batch(pytz.utc.localize(datetime_start), pytz.utc.localize(datetime_stop))[False]
entries_intervals = entries._to_intervals()
overlapping_entries = self._from_intervals(entries_intervals & calendar_intervals)
outside_entries |= entries - overlapping_entries
outside_entries.write({'state': 'conflict'})
return bool(outside_entries)
def _to_intervals(self):
return WorkIntervals((w.date_start.replace(tzinfo=pytz.utc), w.date_stop.replace(tzinfo=pytz.utc), w) for w in self)
@api.model
def _from_intervals(self, intervals):
return self.browse(chain.from_iterable(recs.ids for start, end, recs in intervals))
class HrWorkEntryType(models.Model):
_inherit = 'hr.work.entry.type'
_description = 'HR Work Entry Type'
is_leave = fields.Boolean(
default=False, string="Time Off", help="Allow the work entry type to be linked with time off types.")
| 44.00641 | 6,865 |
889 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'pos_sale_product_configurator',
'version': '1.0',
'category': 'Hidden',
'summary': 'Link module between point_of_sale and sale_product_configurator',
'description': """
This module adds features depending on both modules.
""",
'depends': ['point_of_sale', 'sale_product_configurator'],
'installable': True,
'auto_install': True,
'data': [
'views/pos_config_views.xml',
],
'assets': {
'point_of_sale.assets': [
'pos_sale_product_configurator/static/src/js/models.js',
'pos_sale_product_configurator/static/src/css/popups/product_info_popup.css',
],
'web.assets_qweb': [
'pos_sale_product_configurator/static/src/xml/**/*'
]
},
'license': 'LGPL-3',
}
| 30.655172 | 889 |
276 |
py
|
PYTHON
|
15.0
|
from odoo import models, fields
class PosConfig(models.Model):
_inherit = 'pos.config'
iface_open_product_info = fields.Boolean(string="Open Product Info", help="Display the 'Product Info' page when a product with optional products are added in the customer cart")
| 39.428571 | 276 |
925 |
py
|
PYTHON
|
15.0
|
from odoo import models
class ProductProduct(models.Model):
_inherit = 'product.product'
def get_product_info_pos(self, price, quantity, pos_config_id):
res = super().get_product_info_pos(price, quantity, pos_config_id)
# Optional products
res['optional_products'] = [
{'name': p.name, 'price': min(p.product_variant_ids.mapped('lst_price'))}
for p in self.optional_product_ids.filtered_domain(self._optional_product_pos_domain())
]
return res
def has_optional_product_in_pos(self):
self.ensure_one()
return bool(self.optional_product_ids.filtered_domain(self._optional_product_pos_domain()))
def _optional_product_pos_domain(self):
return [
'&', '&', ['sale_ok', '=', True], ['available_in_pos', '=', True],
'|', ['company_id', '=', self.env.company], ['company_id', '=', False]
]
| 35.576923 | 925 |
595 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'POS Restaurant Adyen',
'version': '1.0',
'category': 'Point of Sale',
'sequence': 6,
'summary': 'Adds American style tipping to Adyen',
'description': '',
'depends': ['pos_adyen', 'pos_restaurant', 'payment_adyen'],
'data': [
'views/pos_payment_method_views.xml',
],
'auto_install': True,
'assets': {
'point_of_sale.assets': [
'pos_restaurant_adyen/static/**/*',
],
},
'license': 'LGPL-3',
}
| 27.045455 | 595 |
602 |
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 PosPaymentMethod(models.Model):
_inherit = 'pos.payment.method'
adyen_merchant_account = fields.Char(help='The POS merchant account code used in Adyen')
def _get_adyen_endpoints(self):
return {
**super(PosPaymentMethod, self).get_adyen_endpoints(),
'adjust': 'https://pal-%s.adyen.com/pal/servlet/Payment/v52/adjustAuthorisation',
'capture': 'https://pal-%s.adyen.com/pal/servlet/Payment/v52/capture',
}
| 35.411765 | 602 |
988 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import requests
from odoo import models
TIMEOUT = 10
class PosPayment(models.Model):
_inherit = 'pos.payment'
def _update_payment_line_for_tip(self, tip_amount):
"""Capture the payment when a tip is set."""
res = super(PosPayment, self)._update_payment_line_for_tip(tip_amount)
if self.payment_method_id.use_payment_terminal == 'adyen':
self._adyen_capture()
return res
def _adyen_capture(self):
data = {
'originalReference': self.transaction_id,
'modificationAmount': {
'value': int(self.amount * 10**self.currency_id.decimal_places),
'currency': self.currency_id.name,
},
'merchantAccount': self.payment_method_id.adyen_merchant_account,
}
return self.payment_method_id.proxy_adyen_request(data, 'capture')
| 30.875 | 988 |
569 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class PosOrder(models.Model):
_inherit = 'pos.order'
def action_pos_order_paid(self):
res = super(PosOrder, self).action_pos_order_paid()
if not self.config_id.set_tip_after_payment:
payment_lines = self.payment_ids.filtered(lambda line: line.payment_method_id.use_payment_terminal == 'adyen')
for payment_line in payment_lines:
payment_line._adyen_capture()
return res
| 35.5625 | 569 |
710 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import http
from odoo.http import request
from odoo.addons.payment_adyen.controllers.main import AdyenController
_logger = logging.getLogger(__name__)
class PosRestaurantAdyenController(AdyenController):
@http.route()
def adyen_notification(self, **post):
if post.get('eventCode') in ['CAPTURE', 'AUTHORISATION_ADJUSTMENT'] and post.get('success') != 'true':
_logger.warning('%s for transaction_id %s failed', post.get('eventCode'), post.get('originalReference'))
return super(PosRestaurantAdyenController, self).adyen_notification(**post)
| 37.368421 | 710 |
603 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Multi Language Chart of Accounts',
'version': '1.1',
'category': 'Accounting/Localizations',
'description': """
* Multi language support for Chart of Accounts, Taxes, Tax Codes, Journals,
Accounting Templates, Analytic Chart of Accounts and Analytic Journals.
* Setup wizard changes
- Copy translations for COA, Tax, Tax Code and Fiscal Position from
templates to target objects.
""",
'depends': ['account'],
'license': 'LGPL-3',
}
| 35.470588 | 603 |
8,423 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
def _load(self, sale_tax_rate, purchase_tax_rate, company):
res = super(AccountChartTemplate, self)._load(sale_tax_rate, purchase_tax_rate, company)
# Copy chart of account translations when loading chart of account
for chart_template in self.filtered('spoken_languages'):
external_id = self.env['ir.model.data'].search([
('model', '=', 'account.chart.template'),
('res_id', '=', chart_template.id),
], order='id', limit=1)
module = external_id and self.env.ref('base.module_' + external_id.module)
if module and module.state == 'installed':
langs = chart_template._get_langs()
if langs:
chart_template._process_single_company_coa_translations(company.id, langs)
return res
def process_translations(self, langs, in_field, in_ids, out_ids):
"""
This method copies translations values of templates into new Accounts/Taxes/Journals for languages selected
:param langs: List of languages to load for new records
:param in_field: Name of the translatable field of source templates
:param in_ids: Recordset of ids of source object
:param out_ids: Recordset of ids of destination object
:return: True
"""
xlat_obj = self.env['ir.translation']
#find the source from Account Template
for lang in langs:
#find the value from Translation
value = xlat_obj._get_ids(in_ids._name + ',' + in_field, 'model', lang, in_ids.ids)
counter = 0
for element in in_ids.with_context(lang=None):
if value[element.id]:
#copy Translation from Source to Destination object
xlat_obj._set_ids(
out_ids._name + ',' + in_field,
'model',
lang,
out_ids[counter].ids,
value[element.id],
element[in_field]
)
else:
_logger.info('Language: %s. Translation from template: there is no translation available for %s!' % (lang, element[in_field]))
counter += 1
return True
def process_coa_translations(self):
company_obj = self.env['res.company']
for chart_template_id in self:
langs = chart_template_id._get_langs()
if langs:
company_ids = company_obj.search([('chart_template_id', '=', chart_template_id.id)])
for company in company_ids:
chart_template_id._process_single_company_coa_translations(company.id, langs)
return True
def _process_single_company_coa_translations(self, company_id, langs):
# write account.account translations in the real COA
self._process_accounts_translations(company_id, langs, 'name')
# write account.group translations
self._process_account_group_translations(company_id, langs, 'name')
# copy account.tax name translations
self._process_taxes_translations(company_id, langs, 'name')
# copy account.tax description translations
self._process_taxes_translations(company_id, langs, 'description')
# copy account.fiscal.position translations
self._process_fiscal_pos_translations(company_id, langs, 'name')
def _get_langs(self):
if not self.spoken_languages:
return []
installed_langs = dict(self.env['res.lang'].get_installed())
langs = []
for lang in self.spoken_languages.split(';'):
if lang not in installed_langs:
# the language is not installed, so we don't need to load its translations
continue
else:
langs.append(lang)
return langs
def _process_accounts_translations(self, company_id, langs, field):
in_ids, out_ids = self._get_template_from_model(company_id, 'account.account')
return self.process_translations(langs, field, in_ids, out_ids)
def _process_account_group_translations(self, company_id, langs, field):
in_ids, out_ids = self._get_template_from_model(company_id, 'account.group')
return self.process_translations(langs, field, in_ids, out_ids)
def _process_taxes_translations(self, company_id, langs, field):
in_ids, out_ids = self._get_template_from_model(company_id, 'account.tax')
return self.process_translations(langs, field, in_ids, out_ids)
def _process_fiscal_pos_translations(self, company_id, langs, field):
in_ids, out_ids = self._get_template_from_model(company_id, 'account.fiscal.position')
return self.process_translations(langs, field, in_ids, out_ids)
def _get_template_from_model(self, company_id, model):
""" Find the records and their matching template """
# generated records have an external id with the format <company id>_<template xml id>
grouped_out_data = defaultdict(lambda: self.env['ir.model.data'])
for imd in self.env['ir.model.data'].search([
('model', '=', model),
('name', '=like', str(company_id) + '_%')
]):
grouped_out_data[imd.module] += imd
in_records = self.env[model + '.template']
out_records = self.env[model]
for module, out_data in grouped_out_data.items():
# templates and records may have been created in a different order
# reorder them based on external id names
expected_in_xml_id_names = {xml_id.name.partition(str(company_id) + '_')[-1]: xml_id for xml_id in out_data}
in_xml_ids = self.env['ir.model.data'].search([
('model', '=', model + '.template'),
('module', '=', module),
('name', 'in', list(expected_in_xml_id_names))
])
in_xml_ids = {xml_id.name: xml_id for xml_id in in_xml_ids}
for name, xml_id in expected_in_xml_id_names.items():
# ignore nonconforming customized data
if name not in in_xml_ids:
continue
in_records += self.env[model + '.template'].browse(in_xml_ids[name].res_id)
out_records += self.env[model].browse(xml_id.res_id)
return (in_records, out_records)
class BaseLanguageInstall(models.TransientModel):
""" Install Language"""
_inherit = "base.language.install"
def lang_install(self):
self.ensure_one()
already_installed = self.lang in [code for code, _ in self.env['res.lang'].get_installed()]
res = super(BaseLanguageInstall, self).lang_install()
if already_installed:
# update of translations instead of new installation
# skip to avoid duplicating the translations
return res
# CoA in multilang mode
for coa in self.env['account.chart.template'].search([('spoken_languages', '!=', False)]):
if self.lang in coa.spoken_languages.split(';'):
# companies on which it is installed
for company in self.env['res.company'].search([('chart_template_id', '=', coa.id)]):
# write account.account translations in the real COA
coa._process_accounts_translations(company.id, [self.lang], 'name')
# write account.group translations
coa._process_account_group_translations(company.id, [self.lang], 'name')
# copy account.tax name translations
coa._process_taxes_translations(company.id, [self.lang], 'name')
# copy account.tax description translations
coa._process_taxes_translations(company.id, [self.lang], 'description')
# copy account.fiscal.position translations
coa._process_fiscal_pos_translations(company.id, [self.lang], 'name')
return res
| 47.857955 | 8,423 |
2,477 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
#in this file, we mostly add the tag translate=True on existing fields that we now want to be translated
class AccountAccountTag(models.Model):
_inherit = 'account.account.tag'
name = fields.Char(translate=True)
class AccountAccountTemplate(models.Model):
_inherit = 'account.account.template'
name = fields.Char(translate=True)
class AccountAccount(models.Model):
_inherit = 'account.account'
name = fields.Char(translate=True)
class AccountGroupTemplate(models.Model):
_inherit = 'account.group.template'
name = fields.Char(translate=True)
class AccountGroup(models.Model):
_inherit = 'account.group'
name = fields.Char(translate=True)
class AccountTax(models.Model):
_inherit = 'account.tax'
name = fields.Char(translate=True)
description = fields.Char(translate=True)
class AccountTaxTemplate(models.Model):
_inherit = 'account.tax.template'
name = fields.Char(translate=True)
description = fields.Char(translate=True)
class AccountChartTemplate(models.Model):
_inherit = 'account.chart.template'
_order = 'name'
name = fields.Char(translate=True)
spoken_languages = fields.Char(string='Spoken Languages', help="State here the languages for which the translations of templates could be loaded at the time of installation of this localization module and copied in the final object when generating them from templates. You must provide the language codes separated by ';'")
class AccountFiscalPosition(models.Model):
_inherit = 'account.fiscal.position'
name = fields.Char(translate=True)
note = fields.Html(translate=True)
class AccountFiscalPositionTemplate(models.Model):
_inherit = 'account.fiscal.position.template'
name = fields.Char(translate=True)
note = fields.Text(translate=True)
class AccountJournal(models.Model):
_inherit = 'account.journal'
name = fields.Char(translate=True)
class AccountAnalyticAccount(models.Model):
_inherit = 'account.analytic.account'
name = fields.Char(translate=True)
class AccountTaxReportLine(models.Model):
_inherit = 'account.tax.report.line'
name = fields.Char(translate=True)
tag_name = fields.Char(translate=True)
class ResCountryState(models.Model):
_inherit = 'res.country.state'
name = fields.Char(translate=True)
| 26.634409 | 2,477 |
407 |
py
|
PYTHON
|
15.0
|
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'G.C.C. - Arabic/English Invoice',
'version': '1.0.0',
'author': 'Odoo',
'category': 'Accounting/Localizations',
'description': """
Arabic/English for GCC
""",
'license': 'LGPL-3',
'depends': ['account'],
'data': [
'views/report_invoice.xml',
],
}
| 25.4375 | 407 |
929 |
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 AccountMove(models.Model):
_inherit = 'account.move'
narration = fields.Html(translate=True)
def _get_name_invoice_report(self):
self.ensure_one()
if self.company_id.country_id in self.env.ref('base.gulf_cooperation_council').country_ids:
return 'l10n_gcc_invoice.arabic_english_invoice'
return super()._get_name_invoice_report()
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
l10n_gcc_invoice_tax_amount = fields.Float(string='Tax Amount', compute='_compute_tax_amount', digits='Product Price')
@api.depends('price_subtotal', 'price_total')
def _compute_tax_amount(self):
for record in self:
record.l10n_gcc_invoice_tax_amount = record.price_total - record.price_subtotal
| 34.407407 | 929 |
1,354 |
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 NewModel(models.Model):
_name = 'export.integer'
_description = 'Export: Integer'
value = fields.Integer(default=4)
def name_get(self):
return [(record.id, "%s:%s" % (self._name, record.value)) for record in self]
class GroupOperator(models.Model):
_name = 'export.group_operator'
_description = 'Export Group Operator'
int_sum = fields.Integer(group_operator='sum')
int_max = fields.Integer(group_operator='max')
float_min = fields.Float(group_operator='min')
float_avg = fields.Float(group_operator='avg')
float_monetary = fields.Monetary(currency_field='currency_id', group_operator='sum')
currency_id = fields.Many2one('res.currency')
date_max = fields.Date(group_operator='max')
bool_and = fields.Boolean(group_operator='bool_and')
bool_or = fields.Boolean(group_operator='bool_or')
many2one = fields.Many2one('export.integer')
one2many = fields.One2many('export.group_operator.one2many', 'parent_id')
class GroupOperatorO2M(models.Model):
_name = 'export.group_operator.one2many'
_description = 'Export Group Operator One2Many'
parent_id = fields.Many2one('export.group_operator')
value = fields.Integer()
| 37.611111 | 1,354 |
396 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'test xlsx export',
'version': '0.1',
'category': 'Hidden/Tests',
'description': """A module to test xlsx export.""",
'depends': ['web', 'test_mail'],
'data': ['ir.model.access.csv'],
'installable': True,
'auto_install': False,
'license': 'LGPL-3',
}
| 30.461538 | 396 |
15,449 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from datetime import date
from unittest.mock import patch
from odoo import http
from odoo.tests import common, tagged
from odoo.tools.misc import get_lang
from odoo.addons.web.controllers.main import ExportXlsxWriter
from odoo.addons.mail.tests.common import mail_new_test_user
class XlsxCreatorCase(common.HttpCase):
model_name = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.model = None
def setUp(self):
super().setUp()
self.model = self.env[self.model_name]
mail_new_test_user(self.env, login='fof', password='123456789', groups='base.group_user,base.group_allow_export')
self.session = self.authenticate('fof', '123456789')
self.worksheet = {} # mock worksheet
self.default_params = {
'domain': [],
'fields': [{'name': field.name, 'label': field.string} for field in self.model._fields.values()],
'groupby': [],
'ids': False,
'import_compat': False,
'model': self.model._name,
}
def _mock_write(self, row, column, value, style=None):
if isinstance(value, float):
decimal_places = style.num_format[::-1].find('.')
style_format = "{:." + str(decimal_places) + "f}"
self.worksheet[row, column] = style_format.format(value)
else:
self.worksheet[row, column] = str(value)
def make(self, values, context=None):
return self.model.with_context(**(context or {})).create(values)
def export(self, values, fields=[], params={}, context=None):
self.worksheet = {}
self.make(values, context=context)
if fields and 'fields' not in params:
params['fields'] = [{
'name': self.model._fields[f].name,
'label': self.model._fields[f].string,
'type': self.model._fields[f].type,
} for f in fields]
with patch.object(ExportXlsxWriter, 'write', self._mock_write):
self.url_open('/web/export/xlsx', data={
'data': json.dumps(dict(self.default_params, **params)),
'token': 'dummy',
'csrf_token': http.WebRequest.csrf_token(self),
})
return self.worksheet
def assertExportEqual(self, value, expected):
for row in range(len(expected)):
for column in range(len(expected[row])):
cell_value = value.pop((row, column), '')
expected_value = expected[row][column]
self.assertEqual(cell_value, expected_value, "Cell %s, %s have a wrong value" % (row, column))
self.assertFalse(value, "There are unexpected cells in the export")
@tagged('-at_install', 'post_install')
class TestGroupedExport(XlsxCreatorCase):
model_name = 'export.group_operator'
# pylint: disable=bad-whitespace
def test_int_sum_max(self):
values = [
{'int_sum': 10, 'int_max': 20},
{'int_sum': 10, 'int_max': 50},
{'int_sum': 20,'int_max': 30},
]
export = self.export(values, fields=['int_sum', 'int_max'], params={'groupby': ['int_sum', 'int_max']})
self.assertExportEqual(export, [
['Int Sum' ,'Int Max'],
['10 (2)' ,'50'],
[' 20 (1)' ,'20'],
['10' ,'20'],
[' 50 (1)' ,'50'],
['10' ,'50'],
['20 (1)' ,'30'],
[' 30 (1)' ,'30'],
['20' ,'30'],
])
export = self.export([], fields=['int_max', 'int_sum'], params={'groupby': ['int_sum', 'int_max']})
self.assertExportEqual(export, [
['Int Max' ,'Int Sum'],
['10 (2)' ,'20'],
[' 20 (1)' ,'10'],
['20' ,'10'],
[' 50 (1)' ,'10'],
['50' ,'10'],
['20 (1)' ,'20'],
[' 30 (1)' ,'20'],
['30' ,'20'],
])
def test_float_min(self):
values = [
{'int_sum': 10, 'float_min': 111.0},
{'int_sum': 10, 'float_min': 222.0},
{'int_sum': 20, 'float_min': 333.0},
]
export = self.export(values, fields=['int_sum', 'float_min'], params={'groupby': ['int_sum', 'float_min']})
self.assertExportEqual(export, [
['Int Sum' ,'Float Min'],
['10 (2)' ,'111.00'],
[' 111.0 (1)','111.00'],
['10' ,'111.00'],
[' 222.0 (1)','222.00'],
['10' ,'222.00'],
['20 (1)' ,'333.00'],
[' 333.0 (1)','333.00'],
['20' ,'333.00'],
])
def test_float_avg(self):
values = [
{'int_sum': 10, 'float_avg': 100.0},
{'int_sum': 10, 'float_avg': 200.0},
{'int_sum': 20, 'float_avg': 300.0},
]
export = self.export(values, fields=['int_sum', 'float_avg'], params={'groupby': ['int_sum', 'float_avg']})
self.assertExportEqual(export, [
['Int Sum' ,'Float Avg'],
['10 (2)' ,'150.00'],
[' 100.0 (1)','100.00'],
['10' ,'100.00'],
[' 200.0 (1)','200.00'],
['10' ,'200.00'],
['20 (1)' ,'300.00'],
[' 300.0 (1)','300.00'],
['20' ,'300.00'],
])
def test_float_avg_nested(self):
""" With more than one nested level (avg aggregation) """
values = [
{'int_sum': 10, 'int_max': 30, 'float_avg': 100.0},
{'int_sum': 10, 'int_max': 30, 'float_avg': 200.0},
{'int_sum': 10, 'int_max': 20, 'float_avg': 600.0},
]
export = self.export(values, fields=['int_sum', 'float_avg'], params={'groupby': ['int_sum', 'int_max', 'float_avg']})
self.assertExportEqual(export, [
['Int Sum' ,'Float Avg'],
['10 (3)' ,'300.00'],
[' 20 (1)' ,'600.00'],
[' 600.0 (1)','600.00'],
['10' ,'600.00'],
[' 30 (2)' ,'150.00'],
[' 100.0 (1)','100.00'],
['10' ,'100.00'],
[' 200.0 (1)','200.00'],
['10' ,'200.00'],
])
def test_float_avg_nested_no_value(self):
""" With more than one nested level (avg aggregation is done on 0, not False) """
values = [
{'int_sum': 10, 'int_max': 20, 'float_avg': False},
{'int_sum': 10, 'int_max': 30, 'float_avg': False},
{'int_sum': 10, 'int_max': 30, 'float_avg': False},
]
export = self.export(values, fields=['int_sum', 'float_avg'], params={'groupby': ['int_sum', 'int_max', 'float_avg']})
self.assertExportEqual(export, [
['Int Sum' ,'Float Avg'],
['10 (3)' ,'0.00'],
[' 20 (1)' ,'0.00'],
[' Undefined (1)','0.00'],
['10' ,'0.00'],
[' 30 (2)' ,'0.00'],
[' Undefined (2)','0.00'],
['10' ,'0.00'],
['10' ,'0.00'],
])
def test_date_max(self):
values = [
{'int_sum': 10, 'date_max': date(2019, 1, 1)},
{'int_sum': 10, 'date_max': date(2000, 1, 1)},
{'int_sum': 20, 'date_max': date(1980, 1, 1)},
]
export = self.export(values, fields=['int_sum', 'date_max'], params={'groupby': ['int_sum', 'date_max:month']})
self.assertExportEqual(export, [
['Int Sum' ,'Date Max'],
['10 (2)' ,'2019-01-01'],
[' January 2000 (1)' ,'2000-01-01'],
['10' ,'2000-01-01'],
[' January 2019 (1)' ,'2019-01-01'],
['10' ,'2019-01-01'],
['20 (1)' ,'1980-01-01'],
[' January 1980 (1)' ,'1980-01-01'],
['20' ,'1980-01-01'],
])
def test_bool_and(self):
values = [
{'int_sum': 10, 'bool_and': True},
{'int_sum': 10, 'bool_and': True},
{'int_sum': 20, 'bool_and': True},
{'int_sum': 20, 'bool_and': False},
]
export = self.export(values, fields=['int_sum', 'bool_and'], params={'groupby': ['int_sum', 'bool_and']})
self.assertExportEqual(export, [
['Int Sum' ,'Bool And'],
['10 (2)' ,'True'],
[' True (2)' ,'True'],
['10' ,'True'],
['10' ,'True'],
['20 (2)' ,'False'],
[' False (1)' ,'False'],
['20' ,'False'],
[' True (1)' ,'True'],
['20' ,'True'],
])
def test_bool_or(self):
values = [
{'int_sum': 10, 'bool_or': True},
{'int_sum': 10, 'bool_or': False},
{'int_sum': 20, 'bool_or': False},
{'int_sum': 20, 'bool_or': False},
]
export = self.export(values, fields=['int_sum', 'bool_or'], params={'groupby': ['int_sum', 'bool_or']})
self.assertExportEqual(export, [
['Int Sum' ,'Bool Or'],
['10 (2)' ,'True'],
[' False (1)' ,'False'],
['10' ,'False'],
[' True (1)' ,'True'],
['10' ,'True'],
['20 (2)' ,'False'],
[' False (2)' ,'False'],
['20' ,'False'],
['20' ,'False'],
])
def test_many2one(self):
values = [
{'int_sum': 10, 'many2one': self.env['export.integer'].create({}).id},
{'int_sum': 10},
]
export = self.export(values, fields=['int_sum', 'many2one'], params={'groupby': ['int_sum', 'many2one']})
self.assertExportEqual(export, [
['Int Sum' ,'Many2One'],
['10 (2)' ,''],
[' export.integer:4 (1)' ,''],
['10' ,'export.integer:4'],
[' Undefined (1)' ,''],
['10' ,''],
])
def test_nested_records(self):
"""
aggregated values currently not supported for nested record export, but it should not crash
e.g. export 'many2one/const'
"""
values = [{'int_sum': 10,
'date_max': date(2019, 1, 1),
'many2one': self.env['export.integer'].create({}).id,
}, {
'int_sum': 10,
'date_max': date(2000, 1, 1),
'many2one': self.env['export.integer'].create({}).id,
},]
export = self.export(values,
params={
'groupby': ['int_sum', 'date_max:month'],
'fields': [
{'name': 'int_sum', 'label': 'Int Sum'},
{'name': 'date_max', 'label': 'Date Max'},
{'name': 'many2one/value', 'label': 'Many2One/Value'},
]
})
self.assertExportEqual(export, [
['Int Sum' ,'Date Max' ,'Many2One/Value'],
['10 (2)' ,'2019-01-01' ,''],
[' January 2000 (1)' ,'2000-01-01' ,''],
['10' ,'2000-01-01' ,'4'],
[' January 2019 (1)' ,'2019-01-01' ,''],
['10' ,'2019-01-01' ,'4'],
])
def test_one2many(self):
values = [{
'int_sum': 10,
'one2many': [
(0, 0, {'value': 8}),
(0, 0, {'value': 9}),
],
}]
export = self.export(values,
params={
'groupby': ['int_sum',],
'fields': [
{'name': 'int_sum', 'label': 'Int Sum'},
{'name': 'one2many/value', 'label': 'One2many/Value'},
]
})
self.assertExportEqual(export, [
['Int Sum' ,'One2many/Value'],
['10 (1)' ,''],
['10' ,'8'],
['' ,'9'],
])
def test_unset_date_values(self):
values = [
{'int_sum': 10, 'date_max': date(2019, 1, 1)},
{'int_sum': 10, 'date_max': False},
]
# Group and aggregate by date, but date fields are not set for all records
export = self.export(values, fields=['int_sum', 'date_max'], params={'groupby': ['int_sum', 'date_max:month']})
self.assertExportEqual(export, [
['Int Sum' ,'Date Max'],
['10 (2)' ,'2019-01-01'],
[' January 2019 (1)' ,'2019-01-01'],
['10' ,'2019-01-01'],
[' Undefined (1)' ,''],
['10' ,''],
])
def test_float_representation(self):
currency = self.env['res.currency'].create({
'name': "bottlecap",
'symbol': "b",
'rounding': 0.001,
'decimal_places': 3,
})
values = [
{'int_sum': 1, 'currency_id': currency.id, 'float_monetary': 60739.2000000004},
{'int_sum': 2, 'currency_id': currency.id, 'float_monetary': 2.0},
{'int_sum': 3, 'currency_id': currency.id, 'float_monetary': 999.9995999},
]
export = self.export(values, fields=['int_sum', 'float_monetary'], params={'groupby': ['int_sum', 'float_monetary']})
self.assertExportEqual(export, [
['Int Sum', 'Float Monetary'],
['1 (1)', '60739.200'],
[' 60739.2 (1)', '60739.200'],
['1', '60739.20'],
['2 (1)', '2.000'],
[' 2.0 (1)', '2.000'],
['2', '2.00'],
['3 (1)', '1000.000'],
[' 1000.0 (1)', '1000.000'],
['3', '1000.00'],
])
def test_decimal_separator(self):
""" The decimal separator of the language used shouldn't impact the float representation in the exported xlsx """
get_lang(self.env).decimal_point = ','
get_lang(self.env).thousands_sep = '.'
values = [
{'int_sum': 1, 'float_min': 86420.864},
]
export = self.export(values, fields=['int_sum', 'float_min'], params={'groupby': ['int_sum', 'float_min']})
self.assertExportEqual(export, [
['Int Sum' ,'Float Min'],
['1 (1)' ,'86420.86'],
[' 86420.864 (1)','86420.86'],
['1' ,'86420.86'],
])
| 39.111392 | 15,449 |
583 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Wire Transfer Payment Acquirer',
'version': '2.0',
'category': 'Accounting/Payment Acquirers',
'summary': 'Payment Acquirer: Wire Transfer Implementation',
'description': """Wire Transfer Payment Acquirer""",
'depends': ['payment'],
'data': [
'views/payment_views.xml',
'views/payment_transfer_templates.xml',
'data/payment_acquirer_data.xml',
],
'auto_install': True,
'uninstall_hook': 'uninstall_hook',
'license': 'LGPL-3',
}
| 32.388889 | 583 |
3,204 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import _, api, models
from odoo.exceptions import ValidationError
from odoo.addons.payment_transfer.controllers.main import TransferController
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
def _get_specific_rendering_values(self, processing_values):
""" Override of payment to return Transfer-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 != 'transfer':
return res
return {
'api_url': TransferController._accept_url,
'reference': self.reference,
}
@api.model
def _get_tx_from_feedback_data(self, provider, data):
""" Override of payment to find the transaction based on transfer data.
:param str provider: The provider of the acquirer that handled the transaction
:param dict data: The transfer feedback data
:return: The transaction if found
:rtype: recordset of `payment.transaction`
:raise: ValidationError if the data match no transaction
"""
tx = super()._get_tx_from_feedback_data(provider, data)
if provider != 'transfer':
return tx
reference = data.get('reference')
tx = self.search([('reference', '=', reference), ('provider', '=', 'transfer')])
if not tx:
raise ValidationError(
"Wire Transfer: " + _("No transaction found matching reference %s.", reference)
)
return tx
def _process_feedback_data(self, data):
""" Override of payment to process the transaction based on transfer data.
Note: self.ensure_one()
:param dict data: The transfer feedback data
:return: None
"""
super()._process_feedback_data(data)
if self.provider != 'transfer':
return
_logger.info(
"validated transfer payment for tx with reference %s: set as pending", self.reference
)
self._set_pending()
def _log_received_message(self):
""" Override of payment to remove transfer acquirer from the recordset.
:return: None
"""
other_provider_txs = self.filtered(lambda t: t.provider != 'transfer')
super(PaymentTransaction, other_provider_txs)._log_received_message()
def _get_sent_message(self):
""" Override of payment to return a different message.
:return: The 'transaction sent' message
:rtype: str
"""
message = super()._get_sent_message()
if self.provider == 'transfer':
message = _(
"The customer has selected %(acq_name)s to make the payment.",
acq_name=self.acquirer_id.name
)
return message
| 34.451613 | 3,204 |
2,496 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
class PaymentAcquirer(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(
selection_add=[('transfer', "Wire Transfer")], default='transfer',
ondelete={'transfer': 'set default'})
qr_code = fields.Boolean(
string="Enable QR Codes", help="Enable the use of QR-codes when paying by wire transfer.")
@api.depends('provider')
def _compute_view_configuration_fields(self):
""" Override of payment to hide the credentials page.
:return: None
"""
super()._compute_view_configuration_fields()
self.filtered(lambda acq: acq.provider == 'transfer').write({
'show_credentials_page': False,
'show_payment_icon_ids': False,
'show_pre_msg': False,
'show_done_msg': False,
'show_cancel_msg': False,
})
@api.model_create_multi
def create(self, values_list):
""" Make sure to have a pending_msg set. """
# This is done here and not in a default to have access to all required values.
acquirers = super().create(values_list)
acquirers._transfer_ensure_pending_msg_is_set()
return acquirers
def write(self, values):
""" Make sure to have a pending_msg set. """
# This is done here and not in a default to have access to all required values.
res = super().write(values)
self._transfer_ensure_pending_msg_is_set()
return res
def _transfer_ensure_pending_msg_is_set(self):
for acquirer in self.filtered(lambda a: a.provider == 'transfer' and not a.pending_msg):
company_id = acquirer.company_id.id
# filter only bank accounts marked as visible
accounts = self.env['account.journal'].search([
('type', '=', 'bank'), ('company_id', '=', company_id)
]).bank_account_id
acquirer.pending_msg = f'<div>' \
f'<h3>{_("Please use the following transfer details")}</h3>' \
f'<h4>{_("Bank Account") if len(accounts) == 1 else _("Bank Accounts")}</h4>' \
f'<ul>{"".join(f"<li>{account.display_name}</li>" for account in accounts)}</ul>' \
f'<h4>{_("Communication")}</h4>' \
f'<p>{_("Please use the order name as communication reference.")}</p>' \
f'</div>'
| 43.034483 | 2,496 |
660 |
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.http import request
_logger = logging.getLogger(__name__)
class TransferController(http.Controller):
_accept_url = '/payment/transfer/feedback'
@http.route(_accept_url, type='http', auth='public', methods=['POST'], csrf=False)
def transfer_form_feedback(self, **post):
_logger.info("beginning _handle_feedback_data with post data %s", pprint.pformat(post))
request.env['payment.transaction'].sudo()._handle_feedback_data('transfer', post)
return request.redirect('/payment/status')
| 34.736842 | 660 |
533 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Mass mailing on course members',
'category': 'Hidden',
'version': '1.0',
'description':
"""
Mass mail course members
========================
Bridge module adding UX requirements to ease mass mailing of course members.
""",
'depends': ['website_slides', 'mass_mailing'],
'data': [
'views/slide_channel_views.xml'
],
'auto_install': True,
'license': 'LGPL-3',
}
| 25.380952 | 533 |
741 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
class Course(models.Model):
_inherit = "slide.channel"
def action_mass_mailing_attendees(self):
domain = repr([('slide_channel_ids', 'in', self.ids)])
mass_mailing_action = dict(
name=_('Mass Mail Course Members'),
type='ir.actions.act_window',
res_model='mailing.mailing',
view_mode='form',
target='current',
context=dict(
default_mailing_model_id=self.env.ref('base.model_res_partner').id,
default_mailing_domain=domain,
),
)
return mass_mailing_action
| 32.217391 | 741 |
1,221 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Coupons & Promotions for eCommerce",
'summary': """Use coupon & promotion programs in your eCommerce store""",
'description': """
Create coupon and promotion codes to share in order to boost your sales (free products, discounts, etc.). Shoppers can use them in the eCommerce checkout.
Coupon & promotion programs can be edited in the Catalog menu of the Website app.
""",
'category': 'Website/Website',
'version': '1.0',
'depends': ['website_sale', 'website_links', 'sale_coupon'],
'data': [
'security/ir.model.access.csv',
'views/coupon_share_views.xml',
'views/website_sale_templates.xml',
'views/res_config_settings_views.xml',
'views/sale_coupon_coupon_views.xml',
'views/sale_coupon_program_views.xml',
],
'auto_install': ['website_sale', 'sale_coupon'],
'assets': {
'web.assets_frontend': [
'website_sale_coupon/static/src/js/coupon_toaster_widget.js',
],
'web.assets_tests': [
'website_sale_coupon/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 38.15625 | 1,221 |
6,778 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo import fields
from odoo.tests import HttpCase, tagged, TransactionCase
from odoo.addons.sale.tests.test_sale_product_attribute_value_config import TestSaleProductAttributeValueCommon
@tagged('post_install', '-at_install')
class TestUi(TestSaleProductAttributeValueCommon, HttpCase):
@classmethod
def setUpClass(cls):
super(TestUi, cls).setUpClass()
# set currency to not rely on demo data and avoid possible race condition
cls.currency_ratio = 1.0
pricelist = cls.env.ref('product.list0')
new_currency = cls._setup_currency(cls.currency_ratio)
pricelist.currency_id = new_currency
pricelist.flush()
def test_01_admin_shop_sale_coupon_tour(self):
# pre enable "Show # found" option to avoid race condition...
public_category = self.env['product.public.category'].create({'name': 'Public Category'})
large_cabinet = self.env['product.product'].create({
'name': 'Small Cabinet',
'list_price': 320.0,
'type': 'consu',
'is_published': True,
'sale_ok': True,
'public_categ_ids': [(4, public_category.id)],
'taxes_id': False,
})
free_large_cabinet = self.env['product.product'].create({
'name': 'Free Product - Small Cabinet',
'type': 'service',
'taxes_id': False,
'supplier_taxes_id': False,
'sale_ok': False,
'purchase_ok': False,
'invoice_policy': 'order',
'default_code': 'FREELARGECABINET',
'categ_id': self.env.ref('product.product_category_all').id,
'taxes_id': False,
})
ten_percent = self.env['product.product'].create({
'name': '10.0% discount on total amount',
'type': 'service',
'taxes_id': False,
'supplier_taxes_id': False,
'sale_ok': False,
'purchase_ok': False,
'invoice_policy': 'order',
'default_code': '10PERCENTDISC',
'categ_id': self.env.ref('product.product_category_all').id,
'taxes_id': False,
})
self.env['coupon.program'].search([]).write({'active': False})
self.env['coupon.program'].create({
'name': "Buy 3 Small Cabinets, get one for free",
'promo_code_usage': 'no_code_needed',
'discount_apply_on': 'on_order',
'reward_type': 'product',
'program_type': 'promotion_program',
'reward_product_id': large_cabinet.id,
'rule_min_quantity': 3,
'rule_products_domain': "[['name', 'ilike', 'Small Cabinet']]",
'discount_line_product_id': free_large_cabinet.id
})
self.env['coupon.program'].create({
'name': "Code for 10% on orders",
'promo_code_usage': 'code_needed',
'promo_code': 'testcode',
'discount_apply_on': 'on_order',
'discount_type': 'percentage',
'discount_percentage': 10.0,
'program_type': 'promotion_program',
'discount_line_product_id': ten_percent.id
})
self.env.ref("website_sale.search_count_box").write({"active": True})
self.start_tour("/", 'shop_sale_coupon', login="admin")
@tagged('post_install', '-at_install')
class TestWebsiteSaleCoupon(TransactionCase):
def setUp(self):
super(TestWebsiteSaleCoupon, self).setUp()
program = self.env['coupon.program'].create({
'name': '10% TEST Discount',
'promo_code_usage': 'code_needed',
'discount_apply_on': 'on_order',
'discount_type': 'percentage',
'discount_percentage': 10.0,
'program_type': 'coupon_program',
})
self.env['coupon.generate.wizard'].with_context(active_id=program.id).create({}).generate_coupon()
self.coupon = program.coupon_ids[0]
self.steve = self.env['res.partner'].create({
'name': 'Steve Bucknor',
'email': '[email protected]',
})
self.empty_order = self.env['sale.order'].create({
'partner_id': self.steve.id
})
def test_01_gc_coupon(self):
# 1. Simulate a frontend order (website, product)
order = self.empty_order
order.website_id = self.env['website'].browse(1)
self.env['sale.order.line'].create({
'product_id': self.env['product.product'].create({
'name': 'Product A',
'list_price': 100,
'sale_ok': True,
}).id,
'name': 'Product A',
'product_uom_qty': 2.0,
'order_id': order.id,
})
# 2. Apply the coupon
self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({
'coupon_code': self.coupon.code
}).process_coupon()
order.recompute_coupon_lines()
self.assertEqual(len(order.applied_coupon_ids), 1, "The coupon should've been applied on the order")
self.assertEqual(self.coupon, order.applied_coupon_ids)
self.assertEqual(self.coupon.state, 'used')
# 3. Test recent order -> Should not be removed
order._gc_abandoned_coupons()
self.assertEqual(len(order.applied_coupon_ids), 1, "The coupon shouldn't have been removed from the order no more than 4 days")
self.assertEqual(self.coupon.state, 'used', "Should not have been changed")
# 4. Test order not older than ICP validity -> Should not be removed
ICP = self.env['ir.config_parameter']
icp_validity = ICP.create({'key': 'website_sale_coupon.abandonned_coupon_validity', 'value': 5})
order.flush()
query = """UPDATE %s SET write_date = %%s WHERE id = %%s""" % (order._table,)
self.env.cr.execute(query, (fields.Datetime.to_string(fields.datetime.now() - timedelta(days=4, hours=2)), order.id))
order._gc_abandoned_coupons()
self.assertEqual(len(order.applied_coupon_ids), 1, "The coupon shouldn't have been removed from the order the order is 4 days old but icp validity is 5 days")
self.assertEqual(self.coupon.state, 'used', "Should not have been changed (2)")
# 5. Test order with no ICP and older then 4 default days -> Should be removed
icp_validity.unlink()
order._gc_abandoned_coupons()
self.assertEqual(len(order.applied_coupon_ids), 0, "The coupon should've been removed from the order as more than 4 days")
self.assertEqual(self.coupon.state, 'new', "Should have been reset.")
| 41.329268 | 6,778 |
6,774 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale_coupon.tests.test_program_numbers import TestSaleCouponProgramNumbers
from odoo.addons.website.tools import MockRequest
from odoo.exceptions import UserError
from odoo.tests import tagged
@tagged('-at_install', 'post_install')
class TestSaleCouponMultiwebsite(TestSaleCouponProgramNumbers):
def setUp(self):
super(TestSaleCouponMultiwebsite, self).setUp()
self.website = self.env['website'].browse(1)
self.website2 = self.env['website'].create({'name': 'website 2'})
def test_01_multiwebsite_checks(self):
""" Ensure the multi website compliance of programs and coupons, both in
backend and frontend.
"""
order = self.empty_order
self.env['sale.order.line'].create({
'product_id': self.largeCabinet.id,
'name': 'Large Cabinet',
'product_uom_qty': 2.0,
'order_id': order.id,
})
def _remove_reward():
order.order_line.filtered('is_reward_line').unlink()
self.assertEqual(len(order.order_line.ids), 1, "Program should have been removed")
def _apply_code(code, backend=True):
if backend:
self.env['sale.coupon.apply.code'].with_context(active_id=order.id).create({
'coupon_code': code
}).process_coupon()
else:
self.env['sale.coupon.apply.code'].sudo().apply_coupon(order, code)
# ==========================================
# ========== Programs (with code) ==========
# ==========================================
# 1. Backend - Generic
_apply_code(self.p1.promo_code)
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a generic promo program")
_remove_reward()
# 2. Frontend - Generic
with MockRequest(self.env, website=self.website):
_apply_code(self.p1.promo_code, False)
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a generic promo program (2)")
_remove_reward()
# make program specific
self.p1.website_id = self.website.id
# 3. Backend - Specific
with self.assertRaises(UserError):
_apply_code(self.p1.promo_code) # the order has no website_id so not possible to use a website specific code
# 4. Frontend - Specific - Correct website
order.website_id = self.website.id
with MockRequest(self.env, website=self.website):
_apply_code(self.p1.promo_code, False)
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a specific promo program for the correct website")
_remove_reward()
# 5. Frontend - Specific - Wrong website
self.p1.website_id = self.website2.id
with MockRequest(self.env, website=self.website):
_apply_code(self.p1.promo_code, False)
self.assertEqual(len(order.order_line.ids), 1, "Should not get the reward as wrong website")
# ==============================
# =========== Coupons ==========
# ==============================
order.website_id = False
self.env['coupon.generate.wizard'].with_context(active_id=self.discount_coupon_program.id).create({
'nbr_coupons': 4,
}).generate_coupon()
coupons = self.discount_coupon_program.coupon_ids
# 1. Backend - Generic
_apply_code(coupons[0].code)
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a generic coupon program")
_remove_reward()
# 2. Frontend - Generic
with MockRequest(self.env, website=self.website):
_apply_code(coupons[1].code, False)
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a generic coupon program (2)")
_remove_reward()
# make program specific
self.discount_coupon_program.website_id = self.website.id
# 3. Backend - Specific
with self.assertRaises(UserError):
_apply_code(coupons[2].code) # the order has no website_id so not possible to use a website specific code
# 4. Frontend - Specific - Correct website
order.website_id = self.website.id
with MockRequest(self.env, website=self.website):
_apply_code(coupons[2].code, False)
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a specific coupon program for the correct website")
_remove_reward()
# 5. Frontend - Specific - Wrong website
self.discount_coupon_program.website_id = self.website2.id
with MockRequest(self.env, website=self.website):
_apply_code(coupons[3].code, False)
self.assertEqual(len(order.order_line.ids), 1, "Should not get the reward as wrong website")
# ========================================
# ========== Programs (no code) ==========
# ========================================
order.website_id = False
self.p1.website_id = False
self.p1.promo_code = False
self.p1.promo_code_usage = 'no_code_needed'
# 1. Backend - Generic
order.recompute_coupon_lines()
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a generic promo program")
# 2. Frontend - Generic
with MockRequest(self.env, website=self.website):
order.recompute_coupon_lines()
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a generic promo program (2)")
# make program specific
self.p1.website_id = self.website.id
# 3. Backend - Specific
order.recompute_coupon_lines()
self.assertEqual(len(order.order_line.ids), 1, "The order has no website_id so not possible to use a website specific code")
# 4. Frontend - Specific - Correct website
order.website_id = self.website.id
with MockRequest(self.env, website=self.website):
order.recompute_coupon_lines()
self.assertEqual(len(order.order_line.ids), 2, "Should get the discount line as it is a specific promo program for the correct website")
# 5. Frontend - Specific - Wrong website
self.p1.website_id = self.website2.id
with MockRequest(self.env, website=self.website):
order.recompute_coupon_lines()
self.assertEqual(len(order.order_line.ids), 1, "Should not get the reward as wrong website")
| 45.463087 | 6,774 |
3,319 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale_coupon.tests.test_program_numbers import TestSaleCouponProgramNumbers
from odoo.addons.website.tools import MockRequest
from odoo.addons.website_sale_coupon.controllers.main import WebsiteSale
from odoo.tests import tagged
@tagged('-at_install', 'post_install')
class TestSaleCouponApplyPending(TestSaleCouponProgramNumbers):
def setUp(self):
super().setUp()
self.WebsiteSaleController = WebsiteSale()
self.website = self.env['website'].browse(1)
self.global_program = self.p1
self.coupon_program = self.env['coupon.program'].create({
'name': 'One Free Product',
'program_type': 'coupon_program',
'rule_min_quantity': 2.0,
'reward_type': 'product',
'reward_product_id': self.largeCabinet.id,
'active': True,
})
self.coupon = self.env['coupon.coupon'].create({
'program_id': self.coupon_program.id,
})
def test_01_activate_coupon_with_existing_program(self):
order = self.empty_order
with MockRequest(self.env, website=self.website, sale_order_id=order.id, website_sale_current_pl=1) as request:
self.WebsiteSaleController.cart_update_json(self.largeCabinet.id, set_qty=3)
self.WebsiteSaleController.pricelist(self.global_program.promo_code)
self.assertEqual(order.amount_total, 864, "The order total should equal 864: 3*320 - 10% discount ")
self.WebsiteSaleController.activate_coupon(self.coupon.code)
promo_code = request.session.get('pending_coupon_code')
self.assertFalse(promo_code, "The promo code should be removed from the pending coupon dict")
self.assertEqual(order.amount_total, 576, "The order total should equal 576: 3*320 - 320 (free product) - 10%")
def test_02_pending_coupon_with_existing_program(self):
order = self.empty_order
with MockRequest(self.env, website=self.website, sale_order_id=order.id, website_sale_current_pl=1) as request:
self.WebsiteSaleController.cart_update_json(self.largeCabinet.id, set_qty=1)
self.WebsiteSaleController.pricelist(self.global_program.promo_code)
self.assertEqual(order.amount_total, 288, "The order total should equal 288: 320 - 10%")
self.WebsiteSaleController.activate_coupon(self.coupon.code)
promo_code = request.session.get('pending_coupon_code')
self.assertEqual(order.amount_total, 288, "The order total should still equal 288 as the coupon for free product can't be applied since it requires 2 min qty")
self.assertEqual(promo_code, self.coupon.code, "The promo code should be set in the pending coupon dict as it couldn't be applied, we save it for later reuse")
self.WebsiteSaleController.cart_update_json(self.largeCabinet.id, add_qty=2)
promo_code = request.session.get('pending_coupon_code')
self.assertFalse(promo_code, "The promo code should be removed from the pending coupon dict as it should have been applied")
self.assertEqual(order.amount_total, 576, "The order total should equal 576: 3*320 - 320 (free product) - 10%")
| 54.409836 | 3,319 |
4,132 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from werkzeug.urls import url_encode
from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError
class SaleCouponShare(models.TransientModel):
_name = 'coupon.share'
_description = 'Create links that apply a coupon and redirect to a specific page'
def _get_default_website_id(self):
# program_website_id = self.program_website_id
program_website_id = self.env['coupon.program'].browse(self.env.context.get('default_program_id')).website_id
if program_website_id:
return program_website_id
else:
Website = self.env['website']
websites = Website.search([])
return len(websites) == 1 and websites or Website
website_id = fields.Many2one('website', required=True, default=_get_default_website_id)
coupon_id = fields.Many2one('coupon.coupon', domain="[('program_id', '=', program_id)]")
program_id = fields.Many2one('coupon.program', required=True, domain=[
'|', ('program_type', '=', 'coupon_program'),
('promo_code_usage', '=', 'code_needed'),
])
program_website_id = fields.Many2one('website', string='Program Website', related='program_id.website_id')
promo_code = fields.Char(compute='_compute_promo_code')
share_link = fields.Char(compute='_compute_share_link')
redirect = fields.Char(required=True, default='/shop')
@api.constrains('coupon_id', 'program_id')
def _check_program(self):
if self.filtered(lambda record: not record.coupon_id and record.program_id.program_type == 'coupon_program'):
raise ValidationError(_("A coupon is needed for coupon programs."))
@api.constrains('website_id', 'program_id')
def _check_website(self):
if self.filtered(lambda record: record.program_website_id and record.program_website_id != record.website_id):
raise ValidationError(_("The shared website should correspond to the website of the program."))
@api.depends('coupon_id.code', 'program_id.promo_code')
def _compute_promo_code(self):
for record in self:
record.promo_code = record.coupon_id.code or record.program_id.promo_code
@api.depends('website_id', 'redirect')
@api.depends_context('use_short_link')
def _compute_share_link(self):
for record in self:
target_url = '{base}/coupon/{code}?{query}'.format(
base=record.website_id.get_base_url(),
code=record.promo_code,
query=url_encode({'r': record.redirect}),
)
if record.env.context.get('use_short_link'):
tracker = self.env['link.tracker'].search([('url', '=', target_url)], limit=1)
if not tracker:
tracker = self.env['link.tracker'].create({'url': target_url})
record.share_link = tracker.short_url
else:
record.share_link = target_url
def action_generate_short_link(self):
return {
'name': _('Share Coupon'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'coupon.share',
'target': 'new',
'res_id': self.id,
'context': {
'use_short_link': True,
}
}
@api.model
def create_share_action(self, coupon=None, program=None):
if bool(program) == bool(coupon):
raise UserError(_("Provide either a coupon or a program."))
return {
'name': _('Share Coupon'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'coupon.share',
'target': 'new',
'flags': {'form': {'action_buttons': True}},
'context': {
'form_view_initial_mode': 'edit',
'default_program_id': program and program.id or coupon.program_id.id,
'default_coupon_id': coupon and coupon.id or None,
}
}
| 41.737374 | 4,132 |
5,646 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from datetime import timedelta
from odoo import api, fields, models
from odoo.exceptions import UserError
from odoo.http import request
class SaleOrder(models.Model):
_inherit = "sale.order"
def _try_pending_coupon(self):
if not request:
return
pending_coupon_code = request.session.get('pending_coupon_code')
if pending_coupon_code:
try:
self.env['sale.coupon.apply.code'].with_context(active_id=self.id).create({
'coupon_code': pending_coupon_code
}).process_coupon()
request.session.pop('pending_coupon_code')
except UserError as e:
return e
return True
def recompute_coupon_lines(self):
for order in self:
order._try_pending_coupon()
return super().recompute_coupon_lines()
def _compute_website_order_line(self):
""" This method will merge multiple discount lines generated by a same program
into a single one (temporary line with `new()`).
This case will only occur when the program is a discount applied on multiple
products with different taxes.
In this case, each taxes will have their own discount line. This is required
to have correct amount of taxes according to the discount.
But we wan't these lines to be `visually` merged into a single one in the
e-commerce since the end user should only see one discount line.
This is only possible since we don't show taxes in cart.
eg:
line 1: 10% discount on product with tax `A` - $15
line 2: 10% discount on product with tax `B` - $11.5
line 3: 10% discount on product with tax `C` - $10
would be `hidden` and `replaced` by
line 1: 10% discount - $36.5
Note: The line will be created without tax(es) and the amount will be computed
depending if B2B or B2C is enabled.
"""
super()._compute_website_order_line()
for order in self:
# TODO: potential performance bottleneck downstream
programs = order._get_applied_programs_with_rewards_on_current_order()
for program in programs:
program_lines = order.order_line.filtered(lambda line:
line.product_id == program.discount_line_product_id)
if len(program_lines) > 1:
if self.env.user.has_group('sale.group_show_price_subtotal'):
price_unit = sum(program_lines.mapped('price_subtotal'))
else:
price_unit = sum(program_lines.mapped('price_total'))
# TODO: batch then flush
order.website_order_line += self.env['sale.order.line'].new({
'product_id': program_lines[0].product_id.id,
'price_unit': price_unit,
'name': program_lines[0].name,
'product_uom_qty': 1,
'product_uom': program_lines[0].product_uom.id,
'order_id': order.id,
'is_reward_line': True,
})
order.website_order_line -= program_lines
def _compute_cart_info(self):
super(SaleOrder, self)._compute_cart_info()
for order in self:
reward_lines = order.website_order_line.filtered(lambda line: line.is_reward_line)
order.cart_quantity -= int(sum(reward_lines.mapped('product_uom_qty')))
def get_promo_code_error(self, delete=True):
error = request.session.get('error_promo_code')
if error and delete:
request.session.pop('error_promo_code')
return error
def _get_coupon_program_domain(self):
return [('website_id', 'in', [False, self.website_id.id])]
def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
res = super(SaleOrder, self)._cart_update(product_id=product_id, line_id=line_id, add_qty=add_qty, set_qty=set_qty, **kwargs)
self.recompute_coupon_lines()
return res
def _get_free_shipping_lines(self):
self.ensure_one()
free_shipping_prgs_ids = self._get_applied_programs_with_rewards_on_current_order().filtered(lambda p: p.reward_type == 'free_shipping')
if not free_shipping_prgs_ids:
return self.env['sale.order.line']
free_shipping_product_ids = free_shipping_prgs_ids.mapped('discount_line_product_id')
return self.order_line.filtered(lambda l: l.product_id in free_shipping_product_ids)
@api.autovacuum
def _gc_abandoned_coupons(self, *args, **kwargs):
"""Remove/free coupon from abandonned ecommerce order."""
ICP = self.env['ir.config_parameter']
validity = ICP.get_param('website_sale_coupon.abandonned_coupon_validity', 4)
validity = fields.Datetime.to_string(fields.datetime.now() - timedelta(days=int(validity)))
coupon_to_reset = self.env['coupon.coupon'].search([
('state', '=', 'used'),
('sales_order_id.state', '=', 'draft'),
('sales_order_id.write_date', '<', validity),
('sales_order_id.website_id', '!=', False),
])
for coupon in coupon_to_reset:
coupon.sales_order_id.applied_coupon_ids -= coupon
coupon_to_reset.write({'state': 'new'})
coupon_to_reset.mapped('sales_order_id').recompute_coupon_lines()
| 47.445378 | 5,646 |
740 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class SaleCoupon(models.Model):
_inherit = 'coupon.coupon'
def _check_coupon_code(self, order_date, partner_id, **kwargs):
order = kwargs.get('order', False)
if order and self.program_id.website_id and self.program_id.website_id != order.website_id:
return {'error': 'This coupon is not valid on this website.'}
return super()._check_coupon_code(order_date, partner_id, **kwargs)
def action_coupon_share(self):
""" Open a window to copy the coupon link """
self.ensure_one()
return self.env['coupon.share'].create_share_action(coupon=self)
| 38.947368 | 740 |
248 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import models
from odoo.http import request
class Website(models.Model):
_inherit = 'website'
def sale_reset(self):
request.session.pop('pending_coupon_code')
return super().sale_reset()
| 22.545455 | 248 |
2,003 |
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 ValidationError
class CouponProgram(models.Model):
_name = 'coupon.program'
_inherit = ['coupon.program', 'website.multi.mixin']
@api.constrains('promo_code', 'website_id')
def _check_promo_code_constraint(self):
""" Only case where multiple same code could coexists is if they all belong to their own website.
If the program is website generic, we should ensure there is no generic and no specific (even for other website) already
If the program is website specific, we should ensure there is no existing code for this website or False
"""
for program in self.filtered(lambda p: p.promo_code):
domain = [('id', '!=', program.id), ('promo_code', '=', program.promo_code)]
if program.website_id:
domain += program.website_id.website_domain()
if self.search(domain):
raise ValidationError(_('The program code must be unique by website!'))
def _filter_programs_on_website(self, order):
return self.filtered(lambda program: not program.website_id or program.website_id.id == order.website_id.id)
@api.model
def _filter_programs_from_common_rules(self, order, next_order=False):
programs = self._filter_programs_on_website(order)
return super(CouponProgram, programs)._filter_programs_from_common_rules(order, next_order)
def _check_promo_code(self, order, coupon_code):
if self.website_id and self.website_id != order.website_id:
return {'error': 'This promo code is not valid on this website.'}
return super()._check_promo_code(order, coupon_code)
def action_program_share(self):
""" Open a window to copy the program link """
self.ensure_one()
return self.env['coupon.share'].create_share_action(program=self)
| 48.853659 | 2,003 |
2,463 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import http, _
from odoo.addons.website_sale.controllers import main
from odoo.exceptions import UserError
from odoo.http import request
from werkzeug.urls import url_encode, url_parse
class WebsiteSale(main.WebsiteSale):
@http.route(['/shop/pricelist'])
def pricelist(self, promo, **post):
order = request.website.sale_get_order()
coupon_status = request.env['sale.coupon.apply.code'].sudo().apply_coupon(order, promo)
if coupon_status.get('not_found'):
return super(WebsiteSale, self).pricelist(promo, **post)
elif coupon_status.get('error'):
request.session['error_promo_code'] = coupon_status['error']
return request.redirect(post.get('r', '/shop/cart'))
@http.route()
def shop_payment(self, **post):
order = request.website.sale_get_order()
order.recompute_coupon_lines()
return super(WebsiteSale, self).shop_payment(**post)
@http.route(['/shop/cart'], type='http', auth="public", website=True)
def cart(self, **post):
order = request.website.sale_get_order()
order.recompute_coupon_lines()
return super(WebsiteSale, self).cart(**post)
@http.route(['/coupon/<string:code>'], type='http', auth='public', website=True, sitemap=False)
def activate_coupon(self, code, r='/shop', **kw):
url_parts = url_parse(r)
url_query = url_parts.decode_query()
url_query.pop('coupon_error', False) # trust only Odoo error message
request.session['pending_coupon_code'] = code
order = request.website.sale_get_order()
if order:
result = order._try_pending_coupon()
order.recompute_coupon_lines()
if isinstance(result, UserError):
url_query['coupon_error'] = result
else:
url_query['notify_coupon'] = code
else:
url_query['coupon_error'] = _("The coupon will be automatically applied when you add something in your cart.")
redirect = url_parts.replace(query=url_encode(url_query))
return request.redirect(redirect.to_url())
# Override
# Add in the rendering the free_shipping_line
def _get_shop_payment_values(self, order, **kwargs):
values = super(WebsiteSale, self)._get_shop_payment_values(order, **kwargs)
values['free_shipping_lines'] = order._get_free_shipping_lines()
return values
| 41.745763 | 2,463 |
754 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com).
{
"name": "Panama - Accounting",
"description": """
Panamenian accounting chart and tax localization.
Plan contable panameño e impuestos de acuerdo a disposiciones vigentes
Con la Colaboración de
- AHMNET CORP http://www.ahmnet.com
""",
"author": "Cubic ERP",
'category': 'Accounting/Localizations/Account Charts',
"depends": ["account"],
"data": [
"data/l10n_pa_chart_data.xml",
"data/account_tax_group_data.xml",
"data/account_tax_data.xml",
"data/account_chart_template_data.xml",
],
'license': 'LGPL-3',
}
| 27.851852 | 752 |
633 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Lead Enrichment',
'summary': 'Enrich Leads/Opportunities using email address domain',
'version': '1.1',
'category': 'Sales/CRM',
'version': '1.1',
'depends': [
'iap_crm',
'iap_mail',
],
'data': [
'data/ir_cron.xml',
'data/ir_action.xml',
'data/mail_templates.xml',
'views/crm_lead_views.xml',
'views/res_config_settings_view.xml',
],
'post_init_hook': '_synchronize_cron',
'auto_install': True,
'license': 'LGPL-3',
}
| 26.375 | 633 |
2,145 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.crm.tests.common import TestCrmCommon
from odoo.addons.iap.tests.common import MockIAPEnrich
from odoo.tests.common import users
class TestLeadEnrich(TestCrmCommon, MockIAPEnrich):
@classmethod
def setUpClass(cls):
super(TestLeadEnrich, cls).setUpClass()
cls.registry.enter_test_mode(cls.cr)
cls.leads = cls.env['crm.lead']
for x in range(0, 4):
cls.leads += cls.env['crm.lead'].create({
'name': 'Test %s' % x,
'email_from': 'test_mail_%[email protected]' % x
})
@classmethod
def tearDownClass(cls):
cls.registry.leave_test_mode()
super().tearDownClass()
@users('user_sales_manager')
def test_enrich_internals(self):
leads = self.env['crm.lead'].browse(self.leads.ids)
leads[0].write({'partner_name': 'Already set', 'email_from': 'test@test1'})
leads.flush()
with self.mockIAPEnrichGateway(email_data={'test1': {'country_code': 'AU', 'state_code': 'NSW'}}):
leads.iap_enrich()
leads.flush()
self.assertEqual(leads[0].partner_name, 'Already set')
self.assertEqual(leads[0].country_id, self.env.ref('base.au'))
self.assertEqual(leads[0].state_id, self.env.ref('base.state_au_2'))
for lead in leads[1:]:
self.assertEqual(lead.partner_name, 'Simulator INC')
for lead in leads:
self.assertEqual(lead.street, 'Simulator Street')
# @users('sales_manager')
# def test_enrich_error_credit(self):
# leads = self.env['crm.lead'].browse(self.leads.ids)
# with self.mockIAPEnrichGateway(sim_error='credit'):
# leads.iap_enrich()
@users('user_sales_manager')
def test_enrich_error_jsonrpc_exception(self):
leads = self.env['crm.lead'].browse(self.leads.ids)
with self.mockIAPEnrichGateway(sim_error='jsonrpc_exception'):
leads.iap_enrich()
for lead in leads:
self.assertEqual(lead.street, False)
| 36.982759 | 2,145 |
847 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
@api.model
def get_values(self):
values = super(ResConfigSettings, self).get_values()
cron = self.sudo().with_context(active_test=False).env.ref('crm_iap_enrich.ir_cron_lead_enrichment', raise_if_not_found=False)
values['lead_enrich_auto'] = 'auto' if cron and cron.active else 'manual'
return values
def set_values(self):
super(ResConfigSettings, self).set_values()
cron = self.sudo().with_context(active_test=False).env.ref('crm_iap_enrich.ir_cron_lead_enrichment', raise_if_not_found=False)
if cron:
cron.active = self.lead_enrich_auto == 'auto'
| 40.333333 | 847 |
7,554 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import logging
from psycopg2 import OperationalError
from odoo import _, api, fields, models, tools
from odoo.addons.iap.tools import iap_tools
_logger = logging.getLogger(__name__)
class Lead(models.Model):
_inherit = 'crm.lead'
iap_enrich_done = fields.Boolean(string='Enrichment done', help='Whether IAP service for lead enrichment based on email has been performed on this lead.')
show_enrich_button = fields.Boolean(string='Allow manual enrich', compute="_compute_show_enrich_button")
@api.depends('email_from', 'probability', 'iap_enrich_done', 'reveal_id')
def _compute_show_enrich_button(self):
config = self.env['ir.config_parameter'].sudo().get_param('crm.iap.lead.enrich.setting', 'manual')
if not config or config != 'manual':
self.show_enrich_button = False
return
for lead in self:
if not lead.active or not lead.email_from or lead.email_state == 'incorrect' or lead.iap_enrich_done or lead.reveal_id or lead.probability == 100:
lead.show_enrich_button = False
else:
lead.show_enrich_button = True
@api.model
def _iap_enrich_leads_cron(self):
timeDelta = fields.datetime.now() - datetime.timedelta(hours=1)
# Get all leads not lost nor won (lost: active = False)
leads = self.search([
('iap_enrich_done', '=', False),
('reveal_id', '=', False),
('probability', '<', 100),
('create_date', '>', timeDelta)
])
leads.iap_enrich(from_cron=True)
def iap_enrich(self, from_cron=False):
# Split self in a list of sub-recordsets or 50 records to prevent timeouts
batches = [self[index:index + 50] for index in range(0, len(self), 50)]
for leads in batches:
lead_emails = {}
with self._cr.savepoint():
try:
self._cr.execute(
"SELECT 1 FROM {} WHERE id in %(lead_ids)s FOR UPDATE NOWAIT".format(self._table),
{'lead_ids': tuple(leads.ids)}, log_exceptions=False)
for lead in leads:
# If lead is lost, active == False, but is anyway removed from the search in the cron.
if lead.probability == 100 or lead.iap_enrich_done:
continue
normalized_email = tools.email_normalize(lead.email_from)
if not normalized_email:
lead.message_post_with_view(
'crm_iap_enrich.mail_message_lead_enrich_no_email',
subtype_id=self.env.ref('mail.mt_note').id)
continue
email_domain = normalized_email.split('@')[1]
# Discard domains of generic email providers as it won't return relevant information
if email_domain in iap_tools._MAIL_DOMAIN_BLACKLIST:
lead.write({'iap_enrich_done': True})
lead.message_post_with_view(
'crm_iap_enrich.mail_message_lead_enrich_notfound',
subtype_id=self.env.ref('mail.mt_note').id)
else:
lead_emails[lead.id] = email_domain
if lead_emails:
try:
iap_response = self.env['iap.enrich.api']._request_enrich(lead_emails)
except iap_tools.InsufficientCreditError:
_logger.info('Sent batch %s enrich requests: failed because of credit', len(lead_emails))
if not from_cron:
data = {
'url': self.env['iap.account'].get_credits_url('reveal'),
}
leads[0].message_post_with_view(
'crm_iap_enrich.mail_message_lead_enrich_no_credit',
values=data,
subtype_id=self.env.ref('mail.mt_note').id)
# Since there are no credits left, there is no point to process the other batches
break
except Exception as e:
_logger.info('Sent batch %s enrich requests: failed with exception %s', len(lead_emails), e)
else:
_logger.info('Sent batch %s enrich requests: success', len(lead_emails))
self._iap_enrich_from_response(iap_response)
except OperationalError:
_logger.error('A batch of leads could not be enriched :%s', repr(leads))
continue
# Commit processed batch to avoid complete rollbacks and therefore losing credits.
if not self.env.registry.in_test_mode():
self.env.cr.commit()
@api.model
def _iap_enrich_from_response(self, iap_response):
""" Handle from the service and enrich the lead accordingly
:param iap_response: dict{lead_id: company data or False}
"""
for lead in self.search([('id', 'in', list(iap_response.keys()))]): # handle unlinked data by performing a search
iap_data = iap_response.get(str(lead.id))
if not iap_data:
lead.write({'iap_enrich_done': True})
lead.message_post_with_view('crm_iap_enrich.mail_message_lead_enrich_notfound', subtype_id=self.env.ref('mail.mt_note').id)
continue
values = {'iap_enrich_done': True}
lead_fields = ['partner_name', 'reveal_id', 'street', 'city', 'zip']
iap_fields = ['name', 'clearbit_id', 'location', 'city', 'postal_code']
for lead_field, iap_field in zip(lead_fields, iap_fields):
if not lead[lead_field] and iap_data.get(iap_field):
values[lead_field] = iap_data[iap_field]
if not lead.phone and iap_data.get('phone_numbers'):
values['phone'] = iap_data['phone_numbers'][0]
if not lead.mobile and iap_data.get('phone_numbers') and len(iap_data['phone_numbers']) > 1:
values['mobile'] = iap_data['phone_numbers'][1]
if not lead.country_id and iap_data.get('country_code'):
country = self.env['res.country'].search([('code', '=', iap_data['country_code'].upper())])
values['country_id'] = country.id
else:
country = lead.country_id
if not lead.state_id and country and iap_data.get('state_code'):
state = self.env['res.country.state'].search([
('code', '=', iap_data['state_code']),
('country_id', '=', country.id)
])
values['state_id'] = state.id
lead.write(values)
template_values = iap_data
template_values['flavor_text'] = _("Lead enriched based on email address")
lead.message_post_with_view(
'iap_mail.enrich_company',
values=template_values,
subtype_id=self.env.ref('mail.mt_note').id
)
| 51.387755 | 7,554 |
806 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Authorize.Net Payment Acquirer',
'version': '2.0',
'category': 'Accounting/Payment Acquirers',
'sequence': 350,
'summary': 'Payment Acquirer: Authorize.net Implementation',
'description': """Authorize.Net Payment Acquirer""",
'depends': ['payment'],
'data': [
'views/payment_views.xml',
'views/payment_authorize_templates.xml',
'data/payment_acquirer_data.xml',
],
'application': True,
'uninstall_hook': 'uninstall_hook',
'assets': {
'web.assets_frontend': [
'payment_authorize/static/src/scss/payment_authorize.scss',
'payment_authorize/static/src/js/payment_form.js',
],
},
'license': 'LGPL-3',
}
| 32.24 | 806 |
673 |
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 AuthorizeCommon(PaymentCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.authorize = cls._prepare_acquirer('authorize', update_values={
'authorize_login': 'dummy',
'authorize_transaction_key': 'dummy',
'authorize_signature_key': '00000000',
'authorize_currency_id': cls.currency_usd.id,
})
cls.acquirer = cls.authorize
cls.currency = cls.currency_usd
| 33.65 | 673 |
2,351 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.addons.payment import utils as payment_utils
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.tools import mute_logger
from .common import AuthorizeCommon
@tagged('post_install', '-at_install')
class AuthorizeTest(AuthorizeCommon):
def test_compatible_acquirers(self):
# Note: in the test common, 'USD' is specified as authorize_currency_id
unsupported_currency = self._prepare_currency('CHF')
acquirers = self.env['payment.acquirer']._get_compatible_acquirers(
partner_id=self.partner.id,
currency_id=unsupported_currency.id,
company_id=self.company.id)
self.assertNotIn(self.authorize, acquirers)
acquirers = self.env['payment.acquirer']._get_compatible_acquirers(
partner_id=self.partner.id,
currency_id=self.currency_usd.id,
company_id=self.company.id)
self.assertIn(self.authorize, acquirers)
def test_processing_values(self):
"""Test custom 'access_token' processing_values for authorize acquirer."""
tx = self.create_transaction(flow='direct')
with mute_logger('odoo.addons.payment.models.payment_transaction'), \
patch(
'odoo.addons.payment.utils.generate_access_token',
new=self._generate_test_access_token
):
processing_values = tx._get_processing_values()
with patch(
'odoo.addons.payment.utils.generate_access_token', new=self._generate_test_access_token
):
self.assertTrue(payment_utils.check_access_token(
processing_values['access_token'], self.reference, self.partner.id,
))
def test_validation(self):
self.assertEqual(self.authorize.authorize_currency_id, self.currency_usd)
self.assertEqual(self.authorize._get_validation_amount(), 0.01)
self.assertEqual(self.authorize._get_validation_currency(), self.currency_usd)
def test_token_activation(self):
"""Activation of disabled authorize tokens is forbidden"""
token = self.create_token(active=False)
with self.assertRaises(UserError):
token._handle_reactivation_request()
| 41.982143 | 2,351 |
10,939 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
from odoo import _, api, models
from odoo.exceptions import UserError, ValidationError
from .authorize_request import AuthorizeAPI
from odoo.addons.payment import utils as payment_utils
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
def _get_specific_processing_values(self, processing_values):
""" Override of payment to return an access token as acquirer-specific processing values.
Note: self.ensure_one() from `_get_processing_values`
:param dict processing_values: The generic processing values of the transaction
:return: The dict of acquirer-specific processing values
:rtype: dict
"""
res = super()._get_specific_processing_values(processing_values)
if self.provider != 'authorize':
return res
return {
'access_token': payment_utils.generate_access_token(
processing_values['reference'], processing_values['partner_id']
)
}
def _authorize_create_transaction_request(self, opaque_data):
""" Create an Authorize.Net payment transaction request.
Note: self.ensure_one()
:param dict opaque_data: The payment details obfuscated by Authorize.Net
:return:
"""
self.ensure_one()
authorize_API = AuthorizeAPI(self.acquirer_id)
if self.acquirer_id.capture_manually or self.operation == 'validation':
return authorize_API.authorize(self, opaque_data=opaque_data)
else:
return authorize_API.auth_and_capture(self, opaque_data=opaque_data)
def _send_payment_request(self):
""" Override of payment to send a payment request to Authorize.
Note: self.ensure_one()
:return: None
:raise: UserError if the transaction is not linked to a token
"""
super()._send_payment_request()
if self.provider != 'authorize':
return
if not self.token_id.authorize_profile:
raise UserError("Authorize.Net: " + _("The transaction is not linked to a token."))
authorize_API = AuthorizeAPI(self.acquirer_id)
if self.acquirer_id.capture_manually:
res_content = authorize_API.authorize(self, token=self.token_id)
_logger.info("authorize request response:\n%s", pprint.pformat(res_content))
else:
res_content = authorize_API.auth_and_capture(self, token=self.token_id)
_logger.info("auth_and_capture request response:\n%s", pprint.pformat(res_content))
# As the API has no redirection flow, we always know the reference of the transaction.
# Still, we prefer to simulate the matching of the transaction by crafting dummy feedback
# data in order to go through the centralized `_handle_feedback_data` method.
feedback_data = {'reference': self.reference, 'response': res_content}
self._handle_feedback_data('authorize', feedback_data)
def _send_refund_request(self, amount_to_refund=None, create_refund_transaction=True):
""" Override of payment to send a refund request to Authorize.
Note: self.ensure_one()
:param float amount_to_refund: The amount to refund
:param bool create_refund_transaction: Whether a refund transaction should be created or not
:return: The refund transaction if any
:rtype: recordset of `payment.transaction`
"""
if self.provider != 'authorize':
return super()._send_refund_request(
amount_to_refund=amount_to_refund,
create_refund_transaction=create_refund_transaction,
)
refund_tx = super()._send_refund_request(
amount_to_refund=amount_to_refund, create_refund_transaction=False
)
authorize_API = AuthorizeAPI(self.acquirer_id)
rounded_amount = round(self.amount, self.currency_id.decimal_places)
res_content = authorize_API.refund(self.acquirer_reference, rounded_amount)
_logger.info("refund request response:\n%s", pprint.pformat(res_content))
# As the API has no redirection flow, we always know the reference of the transaction.
# Still, we prefer to simulate the matching of the transaction by crafting dummy feedback
# data in order to go through the centralized `_handle_feedback_data` method.
feedback_data = {'reference': self.reference, 'response': res_content}
self._handle_feedback_data('authorize', feedback_data)
return refund_tx
def _send_capture_request(self):
""" Override of payment to send a capture request to Authorize.
Note: self.ensure_one()
:return: None
"""
super()._send_capture_request()
if self.provider != 'authorize':
return
authorize_API = AuthorizeAPI(self.acquirer_id)
rounded_amount = round(self.amount, self.currency_id.decimal_places)
res_content = authorize_API.capture(self.acquirer_reference, rounded_amount)
_logger.info("capture request response:\n%s", pprint.pformat(res_content))
# As the API has no redirection flow, we always know the reference of the transaction.
# Still, we prefer to simulate the matching of the transaction by crafting dummy feedback
# data in order to go through the centralized `_handle_feedback_data` method.
feedback_data = {'reference': self.reference, 'response': res_content}
self._handle_feedback_data('authorize', feedback_data)
def _send_void_request(self):
""" Override of payment to send a void request to Authorize.
Note: self.ensure_one()
:return: None
"""
super()._send_void_request()
if self.provider != 'authorize':
return
authorize_API = AuthorizeAPI(self.acquirer_id)
res_content = authorize_API.void(self.acquirer_reference)
_logger.info("void request response:\n%s", pprint.pformat(res_content))
# As the API has no redirection flow, we always know the reference of the transaction.
# Still, we prefer to simulate the matching of the transaction by crafting dummy feedback
# data in order to go through the centralized `_handle_feedback_data` method.
feedback_data = {'reference': self.reference, 'response': res_content}
self._handle_feedback_data('authorize', feedback_data)
@api.model
def _get_tx_from_feedback_data(self, provider, data):
""" Find the transaction based on the feedback data.
:param str provider: The provider of the acquirer that handled the transaction
:param dict data: The feedback data sent by the acquirer
:return: The transaction if found
:rtype: recordset of `payment.transaction`
"""
tx = super()._get_tx_from_feedback_data(provider, data)
if provider != 'authorize':
return tx
reference = data.get('reference')
tx = self.search([('reference', '=', reference), ('provider', '=', 'authorize')])
if not tx:
raise ValidationError(
"Authorize.Net: " + _("No transaction found matching reference %s.", reference)
)
return tx
def _process_feedback_data(self, data):
""" Override of payment to process the transaction based on Authorize 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 != 'authorize':
return
response_content = data.get('response')
self.acquirer_reference = response_content.get('x_trans_id')
status_code = response_content.get('x_response_code', '3')
if status_code == '1': # Approved
status_type = response_content.get('x_type').lower()
if status_type in ('auth_capture', 'prior_auth_capture'):
self._set_done()
if self.tokenize and not self.token_id:
self._authorize_tokenize()
elif status_type == 'auth_only':
self._set_authorized()
if self.tokenize and not self.token_id:
self._authorize_tokenize()
if self.operation == 'validation':
# Void the transaction. In last step because it calls _handle_feedback_data()
self._send_refund_request(create_refund_transaction=False)
elif status_type == 'void':
if self.operation == 'validation': # Validation txs are authorized and then voided
self._set_done() # If the refund went through, the validation tx is confirmed
else:
self._set_canceled()
elif status_code == '2': # Declined
self._set_canceled()
elif status_code == '4': # Held for Review
self._set_pending()
else: # Error / Unknown code
error_code = response_content.get('x_response_reason_text')
_logger.info(
"received data with invalid status code %s and error code %s",
status_code, error_code
)
self._set_error(
"Authorize.Net: " + _(
"Received data with status code \"%(status)s\" and error code \"%(error)s\"",
status=status_code, error=error_code
)
)
def _authorize_tokenize(self):
""" Create a token for the current transaction.
Note: self.ensure_one()
:return: None
"""
self.ensure_one()
authorize_API = AuthorizeAPI(self.acquirer_id)
cust_profile = authorize_API.create_customer_profile(
self.partner_id, self.acquirer_reference
)
_logger.info("create_customer_profile request response:\n%s", pprint.pformat(cust_profile))
if cust_profile:
token = self.env['payment.token'].create({
'acquirer_id': self.acquirer_id.id,
'name': cust_profile.get('name'),
'partner_id': self.partner_id.id,
'acquirer_ref': cust_profile.get('payment_profile_id'),
'authorize_profile': cust_profile.get('profile_id'),
'authorize_payment_method_type': self.acquirer_id.authorize_payment_method_type,
'verified': True,
})
self.write({
'token_id': token.id,
'tokenize': False,
})
_logger.info(
"created token with id %s for partner with id %s", token.id, self.partner_id.id
)
| 42.564202 | 10,939 |
1,741 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
from odoo import _, fields, models
from odoo.exceptions import UserError
from .authorize_request import AuthorizeAPI
_logger = logging.getLogger(__name__)
class PaymentToken(models.Model):
_inherit = 'payment.token'
authorize_profile = fields.Char(
string="Authorize.Net Profile ID",
help="The unique reference for the partner/token combination in the Authorize.net backend.")
authorize_payment_method_type = fields.Selection(
string="Authorize.Net Payment Type",
help="The type of payment method this token is linked to.",
selection=[("credit_card", "Credit Card"), ("bank_account", "Bank Account (USA Only)")],
)
def _handle_deactivation_request(self):
""" Override of payment to request Authorize.Net to delete the token.
Note: self.ensure_one()
:return: None
"""
super()._handle_deactivation_request()
if self.provider != 'authorize':
return
authorize_API = AuthorizeAPI(self.acquirer_id)
res_content = authorize_API.delete_customer_profile(self.authorize_profile)
_logger.info("delete_customer_profile request response:\n%s", pprint.pformat(res_content))
def _handle_reactivation_request(self):
""" Override of payment to raise an error informing that Auth.net tokens cannot be restored.
Note: self.ensure_one()
:return: None
"""
super()._handle_reactivation_request()
if self.provider != 'authorize':
return
raise UserError(_("Saved payment methods cannot be restored once they have been deleted."))
| 33.480769 | 1,741 |
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['authorize'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]}
return res
| 30.857143 | 432 |
15,032 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import pprint
from uuid import uuid4
from odoo.addons.payment import utils as payment_utils
import requests
_logger = logging.getLogger(__name__)
class AuthorizeAPI:
""" Authorize.net Gateway API integration.
This class allows contacting the Authorize.net API with simple operation
requests. It implements a *very limited* subset of the complete API
(http://developer.authorize.net/api/reference); namely:
- Customer Profile/Payment Profile creation
- Transaction authorization/capture/voiding
"""
AUTH_ERROR_STATUS = '3'
def __init__(self, acquirer):
"""Initiate the environment with the acquirer data.
:param recordset acquirer: payment.acquirer account that will be contacted
"""
if acquirer.state == 'enabled':
self.url = 'https://api.authorize.net/xml/v1/request.api'
else:
self.url = 'https://apitest.authorize.net/xml/v1/request.api'
self.state = acquirer.state
self.name = acquirer.authorize_login
self.transaction_key = acquirer.authorize_transaction_key
self.payment_method_type = acquirer.authorize_payment_method_type
def _make_request(self, operation, data=None):
request = {
operation: {
'merchantAuthentication': {
'name': self.name,
'transactionKey': self.transaction_key,
},
**(data or {})
}
}
_logger.info("sending request to %s:\n%s", self.url, pprint.pformat(request))
response = requests.post(self.url, json.dumps(request), timeout=60)
response.raise_for_status()
response = json.loads(response.content)
_logger.info("response received:\n%s", pprint.pformat(response))
messages = response.get('messages')
if messages and messages.get('resultCode') == 'Error':
err_msg = messages.get('message')[0].get('text', '')
tx_errors = response.get('transactionResponse', {}).get('errors')
if tx_errors:
if err_msg:
err_msg += '\n'
err_msg += '\n'.join([e.get('errorText', '') for e in tx_errors])
return {
'err_code': messages.get('message')[0].get('code'),
'err_msg': err_msg,
}
return response
def _format_response(self, response, operation):
if response and response.get('err_code'):
return {
'x_response_code': self.AUTH_ERROR_STATUS,
'x_response_reason_text': response.get('err_msg')
}
else:
return {
'x_response_code': response.get('transactionResponse', {}).get('responseCode'),
'x_trans_id': response.get('transactionResponse', {}).get('transId'),
'x_type': operation,
}
# Customer profiles
def create_customer_profile(self, partner, transaction_id):
""" Create an Auth.net payment/customer profile from an existing transaction.
Creates a customer profile for the partner/credit card combination and links
a corresponding payment profile to it. Note that a single partner in the Odoo
database can have multiple customer profiles in Authorize.net (i.e. a customer
profile is created for every res.partner/payment.token couple).
Note that this function makes 2 calls to the authorize api, since we need to
obtain a partial card number to generate a meaningful payment.token name.
:param record partner: the res.partner record of the customer
:param str transaction_id: id of the authorized transaction in the
Authorize.net backend
:return: a dict containing the profile_id and payment_profile_id of the
newly created customer profile and payment profile as well as the
last digits of the card number
:rtype: dict
"""
response = self._make_request('createCustomerProfileFromTransactionRequest', {
'transId': transaction_id,
'customer': {
'merchantCustomerId': ('ODOO-%s-%s' % (partner.id, uuid4().hex[:8]))[:20],
'email': partner.email or ''
}
})
if not response.get('customerProfileId'):
_logger.warning(
'Unable to create customer payment profile, data missing from transaction. Transaction_id: %s - Partner_id: %s',
transaction_id, partner,
)
return False
res = {
'profile_id': response.get('customerProfileId'),
'payment_profile_id': response.get('customerPaymentProfileIdList')[0]
}
response = self._make_request('getCustomerPaymentProfileRequest', {
'customerProfileId': res['profile_id'],
'customerPaymentProfileId': res['payment_profile_id'],
})
payment = response.get('paymentProfile', {}).get('payment', {})
if self.payment_method_type == 'credit_card':
res['name'] = payment.get('creditCard', {}).get('cardNumber')
else:
res['name'] = payment.get('bankAccount', {}).get('accountNumber')
return res
def delete_customer_profile(self, profile_id):
"""Delete a customer profile
:param str profile_id: the id of the customer profile in the Authorize.net backend
:return: a dict containing the response code
:rtype: dict
"""
response = self._make_request("deleteCustomerProfileRequest", {'customerProfileId': profile_id})
return self._format_response(response, 'deleteCustomerProfile')
#=== Transaction management ===#
def _prepare_authorization_transaction_request(self, transaction_type, tx_data, tx):
# The billTo parameter is required for new ACH transactions (transactions without a payment.token),
# but is not allowed for transactions with a payment.token.
bill_to = {}
if 'profile' not in tx_data:
if tx.partner_id.is_company:
split_name = '', tx.partner_name
else:
split_name = payment_utils.split_partner_name(tx.partner_name)
# max lengths are defined by the Authorize API
bill_to = {
'billTo': {
'firstName': split_name[0][:50],
'lastName': split_name[1][:50], # lastName is always required
'company': tx.partner_name[:50] if tx.partner_id.is_company else '',
'address': tx.partner_address,
'city': tx.partner_city,
'state': tx.partner_state_id.name or '',
'zip': tx.partner_zip,
'country': tx.partner_country_id.name or '',
}
}
# These keys have to be in the order defined in
# https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd
return {
'transactionRequest': {
'transactionType': transaction_type,
'amount': str(tx.amount),
**tx_data,
'order': {
'invoiceNumber': tx.reference[:20],
'description': tx.reference[:255],
},
'customer': {
'email': tx.partner_email or '',
},
**bill_to,
'customerIP': payment_utils.get_customer_ip_address(),
}
}
def authorize(self, tx, token=None, opaque_data=None):
""" Authorize (without capture) a payment for the given amount.
:param recordset tx: The transaction of the payment, as a `payment.transaction` record
:param recordset token: The token of the payment method to charge, as a `payment.token`
record
:param dict opaque_data: The payment details obfuscated by Authorize.Net
:return: a dict containing the response code, transaction id and transaction type
:rtype: dict
"""
tx_data = self._prepare_tx_data(token=token, opaque_data=opaque_data)
response = self._make_request(
'createTransactionRequest',
self._prepare_authorization_transaction_request('authOnlyTransaction', tx_data, tx)
)
return self._format_response(response, 'auth_only')
def auth_and_capture(self, tx, token=None, opaque_data=None):
"""Authorize and capture a payment for the given amount.
Authorize and immediately capture a payment for the given payment.token
record for the specified amount with reference as communication.
:param recordset tx: The transaction of the payment, as a `payment.transaction` record
:param record token: the payment.token record that must be charged
:param str opaque_data: the transaction opaque_data obtained from Authorize.net
:return: a dict containing the response code, transaction id and transaction type
:rtype: dict
"""
tx_data = self._prepare_tx_data(token=token, opaque_data=opaque_data)
response = self._make_request(
'createTransactionRequest',
self._prepare_authorization_transaction_request('authCaptureTransaction', tx_data, tx)
)
result = self._format_response(response, 'auth_capture')
errors = response.get('transactionResponse', {}).get('errors')
if errors:
result['x_response_reason_text'] = '\n'.join([e.get('errorText') for e in errors])
return result
def _prepare_tx_data(self, token=None, opaque_data=False):
"""
:param token: The token of the payment method to charge, as a `payment.token` record
:param dict opaque_data: The payment details obfuscated by Authorize.Net
"""
assert (token or opaque_data) and not (token and opaque_data), "Exactly one of token or opaque_data must be specified"
if token:
token.ensure_one()
return {
'profile': {
'customerProfileId': token.authorize_profile,
'paymentProfile': {
'paymentProfileId': token.acquirer_ref,
}
},
}
else:
return {
'payment': {
'opaqueData': opaque_data,
}
}
def _get_transaction_details(self, transaction_id):
""" Return detailed information about a specific transaction. Useful to issue refunds.
:param str transaction_id: transaction id
:return: a dict containing the transaction details
:rtype: dict
"""
return self._make_request('getTransactionDetailsRequest', {'transId': transaction_id})
def capture(self, transaction_id, amount):
"""Capture a previously authorized payment for the given amount.
Capture a previsouly authorized payment. Note that the amount is required
even though we do not support partial capture.
:param str transaction_id: id of the authorized transaction in the
Authorize.net backend
:param str amount: transaction amount (up to 15 digits with decimal point)
:return: a dict containing the response code, transaction id and transaction type
:rtype: dict
"""
response = self._make_request('createTransactionRequest', {
'transactionRequest': {
'transactionType': 'priorAuthCaptureTransaction',
'amount': str(amount),
'refTransId': transaction_id,
}
})
return self._format_response(response, 'prior_auth_capture')
def void(self, transaction_id):
"""Void a previously authorized payment.
:param str transaction_id: the id of the authorized transaction in the
Authorize.net backend
:return: a dict containing the response code, transaction id and transaction type
:rtype: dict
"""
response = self._make_request('createTransactionRequest', {
'transactionRequest': {
'transactionType': 'voidTransaction',
'refTransId': transaction_id
}
})
return self._format_response(response, 'void')
def refund(self, transaction_id, amount):
"""Refund a previously authorized payment. If the transaction is not settled
yet, it will be voided.
:param str transaction_id: the id of the authorized transaction in the
Authorize.net backend
:param float amount: transaction amount to refund
:return: a dict containing the response code, transaction id and transaction type
:rtype: dict
"""
tx_details = self._get_transaction_details(transaction_id)
if tx_details and tx_details.get('err_code'):
return {
'x_response_code': self.AUTH_ERROR_STATUS,
'x_response_reason_text': tx_details.get('err_msg')
}
# Void transaction not yet settled instead of issuing a refund
# (spoiler alert: a refund on a non settled transaction will throw an error)
if tx_details.get('transaction', {}).get('transactionStatus') in ['authorizedPendingCapture', 'capturedPendingSettlement']:
return self.void(transaction_id)
card = tx_details.get('transaction', {}).get('payment', {}).get('creditCard', {}).get('cardNumber')
response = self._make_request('createTransactionRequest', {
'transactionRequest': {
'transactionType': 'refundTransaction',
'amount': str(amount),
'payment': {
'creditCard': {
'cardNumber': card,
'expirationDate': 'XXXX',
}
},
'refTransId': transaction_id,
}
})
return self._format_response(response, 'refund')
# Acquirer configuration: fetch authorize_client_key & currencies
def merchant_details(self):
""" Retrieves the merchant details and generate a new public client key if none exists.
:return: Dictionary containing the merchant details
:rtype: dict"""
return self._make_request('getMerchantDetailsRequest')
# Test
def test_authenticate(self):
""" Test Authorize.net communication with a simple credentials check.
:return: The authentication results
:rtype: dict
"""
return self._make_request('authenticateTestRequest')
| 41.524862 | 15,032 |
6,014 |
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import pprint
from odoo import _, api, fields, models
from odoo.fields import Command
from odoo.exceptions import UserError, ValidationError
from .authorize_request import AuthorizeAPI
_logger = logging.getLogger(__name__)
class PaymentAcquirer(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(
selection_add=[('authorize', 'Authorize.Net')], ondelete={'authorize': 'set default'})
authorize_login = fields.Char(
string="API Login ID", help="The ID solely used to identify the account with Authorize.Net",
required_if_provider='authorize')
authorize_transaction_key = fields.Char(
string="API Transaction Key", required_if_provider='authorize', groups='base.group_system')
authorize_signature_key = fields.Char(
string="API Signature Key", required_if_provider='authorize', groups='base.group_system')
authorize_client_key = fields.Char(
string="API Client Key",
help="The public client key. To generate directly from Odoo or from Authorize.Net backend.")
# Authorize.Net supports only one currency: "One gateway account is required for each currency"
# See https://community.developer.authorize.net/t5/The-Authorize-Net-Developer-Blog/Authorize-Net-UK-Europe-Update/ba-p/35957
authorize_currency_id = fields.Many2one(
string="Authorize Currency", comodel_name='res.currency', groups='base.group_system')
authorize_payment_method_type = fields.Selection(
string="Allow Payments From",
help="Determines with what payment method the customer can pay.",
selection=[('credit_card', "Credit Card"), ('bank_account', "Bank Account (USA Only)")],
default='credit_card',
required_if_provider='authorize',
)
@api.constrains('authorize_payment_method_type')
def _check_payment_method_type(self):
for acquirer in self.filtered(lambda acq: acq.provider == "authorize"):
if self.env['payment.token'].search([('acquirer_id', '=', acquirer.id)], limit=1):
raise ValidationError(_(
"There are active tokens linked to this acquirer. To change the payment method "
"type, please disable the acquirer and duplicate it. Then, change the payment "
"method type on the duplicated acquirer."
))
@api.onchange('authorize_payment_method_type')
def _onchange_authorize_payment_method_type(self):
if self.authorize_payment_method_type == 'bank_account':
self.display_as = _("Bank (powered by Authorize)")
self.payment_icon_ids = [Command.clear()]
else:
self.display_as = _("Credit Card (powered by Authorize)")
self.payment_icon_ids = [Command.set([self.env.ref(icon_xml_id).id for icon_xml_id in (
'payment.payment_icon_cc_maestro',
'payment.payment_icon_cc_mastercard',
'payment.payment_icon_cc_discover',
'payment.payment_icon_cc_diners_club_intl',
'payment.payment_icon_cc_jcb',
'payment.payment_icon_cc_visa',
)])]
def action_update_merchant_details(self):
""" Fetch the merchant details to update the client key and the account currency. """
self.ensure_one()
if self.state == 'disabled':
raise UserError(_("This action cannot be performed while the acquirer is disabled."))
authorize_API = AuthorizeAPI(self)
# Validate the API Login ID and Transaction Key
res_content = authorize_API.test_authenticate()
_logger.info("test_authenticate request response:\n%s", pprint.pformat(res_content))
if res_content.get('err_msg'):
raise UserError(_("Failed to authenticate.\n%s", res_content['err_msg']))
# Update the merchant details
res_content = authorize_API.merchant_details()
_logger.info("merchant_details request response:\n%s", pprint.pformat(res_content))
if res_content.get('err_msg'):
raise UserError(_("Could not fetch merchant details:\n%s", res_content['err_msg']))
currency = self.env['res.currency'].search([('name', 'in', res_content.get('currencies'))])
self.authorize_currency_id = currency
self.authorize_client_key = res_content.get('publicClientKey')
@api.model
def _get_compatible_acquirers(self, *args, currency_id=None, **kwargs):
""" Override of payment to unlist Authorize 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:
acquirers = acquirers.filtered(
lambda a: a.provider != 'authorize' or currency == a.authorize_currency_id
)
return acquirers
def _get_validation_amount(self):
""" Override of payment to return the amount for Authorize.Net validation operations.
:return: The validation amount
:rtype: float
"""
res = super()._get_validation_amount()
if self.provider != 'authorize':
return res
return 0.01
def _get_validation_currency(self):
""" Override of payment to return the currency for Authorize.Net validation operations.
:return: The validation currency
:rtype: recordset of `res.currency`
"""
res = super()._get_validation_currency()
if self.provider != 'authorize':
return res
return self.authorize_currency_id
def _get_default_payment_method_id(self):
self.ensure_one()
if self.provider != 'authorize':
return super()._get_default_payment_method_id()
return self.env.ref('payment_authorize.payment_method_authorize').id
| 44.880597 | 6,014 |
3,039 |
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
from odoo.addons.payment import utils as payment_utils
_logger = logging.getLogger(__name__)
class AuthorizeController(http.Controller):
@http.route('/payment/authorize/get_acquirer_info', type='json', auth='public')
def authorize_get_acquirer_info(self, acquirer_id):
""" Return public information on the acquirer.
:param int acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id
:return: Information on the acquirer, namely: the state, payment method type, login ID, and
public client key
:rtype: dict
"""
acquirer_sudo = request.env['payment.acquirer'].sudo().browse(acquirer_id).exists()
return {
'state': acquirer_sudo.state,
'payment_method_type': acquirer_sudo.authorize_payment_method_type,
# The public API key solely used to identify the seller account with Authorize.Net
'login_id': acquirer_sudo.authorize_login,
# The public client key solely used to identify requests from the Accept.js suite
'client_key': acquirer_sudo.authorize_client_key,
}
@http.route('/payment/authorize/payment', type='json', auth='public')
def authorize_payment(self, reference, partner_id, access_token, opaque_data):
""" Make a payment request and handle the response.
:param str reference: The reference of the transaction
:param int partner_id: The partner making the transaction, as a `res.partner` id
:param str access_token: The access token used to verify the provided values
:param dict opaque_data: The payment details obfuscated by Authorize.Net
:return: None
"""
# Check that the transaction details have not been altered
if not payment_utils.check_access_token(access_token, reference, partner_id):
raise ValidationError("Authorize.Net: " + _("Received tampered payment request data."))
# Make the payment request to Authorize.Net
tx_sudo = request.env['payment.transaction'].sudo().search([('reference', '=', reference)])
response_content = tx_sudo._authorize_create_transaction_request(opaque_data)
# Handle the payment request response
_logger.info("make payment response:\n%s", pprint.pformat(response_content))
# As the API has no redirection flow, we always know the reference of the transaction.
# Still, we prefer to simulate the matching of the transaction by crafting dummy feedback
# data in order to go through the centralized `_handle_feedback_data` method.
feedback_data = {'reference': tx_sudo.reference, 'response': response_content}
request.env['payment.transaction'].sudo()._handle_feedback_data(
'authorize', feedback_data
)
| 49.016129 | 3,039 |
1,632 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Product Comparison',
'summary': 'Allow shoppers to compare products based on their attributes',
'description': """
This module adds a comparison tool to your eCommerce shop, so that your shoppers can easily compare products based on their attributes. It will considerably accelerate their purchasing decision.
To configure product attributes, activate *Attributes & Variants* in the Website settings. This will add a dedicated section in the product form. In the configuration, this module adds a category field to product attributes in order to structure the shopper's comparison table.
Finally, the module comes with an option to display an attribute summary table in product web pages (available in Customize menu).
""",
'author': 'Odoo SA',
'category': 'Website/Website',
'version': '1.0',
'depends': ['website_sale'],
'data': [
'security/ir.model.access.csv',
'views/website_sale_comparison_template.xml',
'views/website_sale_comparison_view.xml',
],
'demo': [
'data/website_sale_comparison_data.xml',
'data/website_sale_comparison_demo.xml',
],
'installable': True,
'assets': {
'web.assets_frontend': [
'website_sale_comparison/static/src/scss/website_sale_comparison.scss',
'website_sale_comparison/static/src/js/website_sale_comparison.js',
],
'web.assets_tests': [
'website_sale_comparison/static/tests/**/*',
],
},
'license': 'LGPL-3',
}
| 44.108108 | 1,632 |
10,122 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import OrderedDict
from lxml import etree
from odoo import tools
import odoo.tests
@odoo.tests.tagged('-at_install', 'post_install')
class TestWebsiteSaleComparison(odoo.tests.TransactionCase):
def test_01_website_sale_comparison_remove(self):
""" This tour makes sure the product page still works after the module
`website_sale_comparison` has been removed.
Technically it tests the removal of copied views by the base method
`_remove_copied_views`. The problematic view that has to be removed is
`product_add_to_compare` because it has a reference to `add_to_compare`.
"""
# YTI TODO: Adapt this tour without demo data
# I still didn't figure why, but this test freezes on runbot
# without the demo data
if tools.config["without_demo"]:
return
Website0 = self.env['website'].with_context(website_id=None)
Website1 = self.env['website'].with_context(website_id=1)
# Create a generic inherited view, with a key not starting with
# `website_sale_comparison` otherwise the unlink will work just based on
# the key, but we want to test also for `MODULE_UNINSTALL_FLAG`.
product_add_to_compare = Website0.viewref('website_sale_comparison.product_add_to_compare')
test_view_key = 'my_test.my_key'
self.env['ir.ui.view'].with_context(website_id=None).create({
'name': 'test inherited view',
'key': test_view_key,
'inherit_id': product_add_to_compare.id,
'arch': '<div/>',
})
# Retrieve the generic view
product = Website0.viewref('website_sale.product')
# Trigger COW to create specific views of the whole tree
product.with_context(website_id=1).write({'name': 'Trigger COW'})
# Verify initial state: the specific views exist
self.assertEqual(Website1.viewref('website_sale.product').website_id.id, 1)
self.assertEqual(Website1.viewref('website_sale_comparison.product_add_to_compare').website_id.id, 1)
self.assertEqual(Website1.viewref(test_view_key).website_id.id, 1)
# Remove the module (use `module_uninstall` because it is enough to test
# what we want here, no need/can't use `button_immediate_uninstall`
# because it would commit the test transaction)
website_sale_comparison = self.env['ir.module.module'].search([('name', '=', 'website_sale_comparison')])
website_sale_comparison.module_uninstall()
# Check that the generic view is correctly removed
self.assertFalse(Website0.viewref('website_sale_comparison.product_add_to_compare', raise_if_not_found=False))
# Check that the specific view is correctly removed
self.assertFalse(Website1.viewref('website_sale_comparison.product_add_to_compare', raise_if_not_found=False))
# Check that the generic inherited view is correctly removed
self.assertFalse(Website0.viewref(test_view_key, raise_if_not_found=False))
# Check that the specific inherited view is correctly removed
self.assertFalse(Website1.viewref(test_view_key, raise_if_not_found=False))
@odoo.tests.tagged('post_install', '-at_install')
class TestUi(odoo.tests.HttpCase):
def setUp(self):
super(TestUi, self).setUp()
self.template_margaux = self.env['product.template'].create({
'name': "Château Margaux",
'website_published': True,
'list_price': 0,
})
self.attribute_varieties = self.env['product.attribute'].create({
'name': 'Grape Varieties',
'sequence': 2,
})
self.attribute_vintage = self.env['product.attribute'].create({
'name': 'Vintage',
'sequence': 1,
})
self.values_varieties = self.env['product.attribute.value'].create({
'name': n,
'attribute_id': self.attribute_varieties.id,
'sequence': i,
} for i, n in enumerate(['Cabernet Sauvignon', 'Merlot', 'Cabernet Franc', 'Petit Verdot']))
self.values_vintage = self.env['product.attribute.value'].create({
'name': n,
'attribute_id': self.attribute_vintage.id,
'sequence': i,
} for i, n in enumerate(['2018', '2017', '2016', '2015']))
self.attribute_line_varieties = self.env['product.template.attribute.line'].create([{
'product_tmpl_id': self.template_margaux.id,
'attribute_id': self.attribute_varieties.id,
'value_ids': [(6, 0, v.ids)],
} for v in self.values_varieties])
self.attribute_line_vintage = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.template_margaux.id,
'attribute_id': self.attribute_vintage.id,
'value_ids': [(6, 0, self.values_vintage.ids)],
})
self.variants_margaux = self.template_margaux._get_possible_variants_sorted()
for variant, price in zip(self.variants_margaux, [487.32, 394.05, 532.44, 1047.84]):
variant.product_template_attribute_value_ids.filtered(lambda ptav: ptav.attribute_id == self.attribute_vintage).price_extra = price
def test_01_admin_tour_product_comparison(self):
# YTI FIXME: Adapt to work without demo data
if tools.config["without_demo"]:
return
self.start_tour("/", 'product_comparison', login='admin')
def test_02_attribute_multiple_lines(self):
# Case product page with "Product attributes table" disabled (website_sale standard case)
self.env['website'].viewref('website_sale_comparison.product_attributes_body').active = False
res = self.url_open('/shop/%d' % self.template_margaux.id)
self.assertEqual(res.status_code, 200)
root = etree.fromstring(res.content, etree.HTMLParser())
tr_varieties_simple_att = root.xpath('//div[@id="product_attributes_simple"]//tr')[0]
text = etree.tostring(tr_varieties_simple_att, encoding='unicode', method='text')
self.assertEqual(text.replace(' ', '').replace('\n', ''), "GrapeVarieties:CabernetSauvignon,Merlot,CabernetFranc,PetitVerdot")
# Case product page with "Product attributes table" enabled
self.env['website'].viewref('website_sale_comparison.product_attributes_body').active = True
res = self.url_open('/shop/%d' % self.template_margaux.id)
self.assertEqual(res.status_code, 200)
root = etree.fromstring(res.content, etree.HTMLParser())
tr_vintage = root.xpath('//div[@id="product_specifications"]//tr')[0]
text_vintage = etree.tostring(tr_vintage, encoding='unicode', method='text')
self.assertEqual(text_vintage.replace(' ', '').replace('\n', ''), "Vintage2018or2017or2016or2015")
tr_varieties = root.xpath('//div[@id="product_specifications"]//tr')[1]
text_varieties = etree.tostring(tr_varieties, encoding='unicode', method='text')
self.assertEqual(text_varieties.replace(' ', '').replace('\n', ''), "GrapeVarietiesCabernetSauvignon,Merlot,CabernetFranc,PetitVerdot")
# Case compare page
res = self.url_open('/shop/compare?products=%s' % ','.join(str(id) for id in self.variants_margaux.ids))
self.assertEqual(res.status_code, 200)
root = etree.fromstring(res.content, etree.HTMLParser())
table = root.xpath('//table[@id="o_comparelist_table"]')[0]
products = table.xpath('//a[@class="o_product_comparison_table"]')
self.assertEqual(len(products), 4)
for product, name in zip(products, ['ChâteauMargaux(2018)', 'ChâteauMargaux(2017)', 'ChâteauMargaux(2016)', 'ChâteauMargaux(2015)']):
text = etree.tostring(product, encoding='unicode', method='text')
self.assertEqual(text.replace(' ', '').replace('\n', ''), name)
tr_vintage = table.xpath('tbody/tr')[0]
text_vintage = etree.tostring(tr_vintage, encoding='unicode', method='text')
self.assertEqual(text_vintage.replace(' ', '').replace('\n', ''), "Vintage2018201720162015")
tr_varieties = table.xpath('tbody/tr')[1]
text_varieties = etree.tostring(tr_varieties, encoding='unicode', method='text')
self.assertEqual(text_varieties.replace(' ', '').replace('\n', ''), "GrapeVarieties" + 4 * "CabernetSauvignon,Merlot,CabernetFranc,PetitVerdot")
def test_03_category_order(self):
"""Test that categories are shown in the correct order when the
attributes are in a different order."""
category_vintage = self.env['product.attribute.category'].create({
'name': 'Vintage',
'sequence': 2,
})
category_varieties = self.env['product.attribute.category'].create({
'name': 'Varieties',
'sequence': 1,
})
self.attribute_vintage.category_id = category_vintage
self.attribute_varieties.category_id = category_varieties
prep_categories = self.template_margaux.valid_product_template_attribute_line_ids._prepare_categories_for_display()
self.assertEqual(prep_categories, OrderedDict([
(category_varieties, self.attribute_line_varieties),
(category_vintage, self.attribute_line_vintage),
]))
prep_categories = self.variants_margaux[0]._prepare_categories_for_display()
self.assertEqual(prep_categories, OrderedDict([
(category_varieties, OrderedDict([
(self.attribute_varieties, OrderedDict([
(self.template_margaux.product_variant_id, self.attribute_line_varieties.product_template_value_ids)
]))
])),
(category_vintage, OrderedDict([
(self.attribute_vintage, OrderedDict([
(self.template_margaux.product_variant_id, self.attribute_line_vintage.product_template_value_ids[0])
]))
])),
]))
| 51.617347 | 10,117 |
3,320 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from collections import OrderedDict
from odoo import fields, models
class ProductAttributeCategory(models.Model):
_name = "product.attribute.category"
_description = "Product Attribute Category"
_order = 'sequence, id'
name = fields.Char("Category Name", required=True, translate=True)
sequence = fields.Integer("Sequence", default=10, index=True)
attribute_ids = fields.One2many('product.attribute', 'category_id', string="Related Attributes", domain="[('category_id', '=', False)]")
class ProductAttribute(models.Model):
_inherit = 'product.attribute'
_order = 'category_id, sequence, id'
category_id = fields.Many2one('product.attribute.category', string="Category", index=True,
help="Set a category to regroup similar attributes under "
"the same section in the Comparison page of eCommerce")
class ProductTemplateAttributeLine(models.Model):
_inherit = 'product.template.attribute.line'
def _prepare_categories_for_display(self):
"""On the product page group together the attribute lines that concern
attributes that are in the same category.
The returned categories are ordered following their default order.
:return: OrderedDict [{
product.attribute.category: [product.template.attribute.line]
}]
"""
attributes = self.attribute_id
categories = OrderedDict([(cat, self.env['product.template.attribute.line']) for cat in attributes.category_id.sorted()])
if any(not pa.category_id for pa in attributes):
# category_id is not required and the mapped does not return empty
categories[self.env['product.attribute.category']] = self.env['product.template.attribute.line']
for ptal in self:
categories[ptal.attribute_id.category_id] |= ptal
return categories
class ProductProduct(models.Model):
_inherit = 'product.product'
def _prepare_categories_for_display(self):
"""On the comparison page group on the same line the values of each
product that concern the same attributes, and then group those
attributes per category.
The returned categories are ordered following their default order.
:return: OrderedDict [{
product.attribute.category: OrderedDict [{
product.attribute: OrderedDict [{
product: [product.template.attribute.value]
}]
}]
}]
"""
attributes = self.product_tmpl_id.valid_product_template_attribute_line_ids._without_no_variant_attributes().attribute_id.sorted()
categories = OrderedDict([(cat, OrderedDict()) for cat in attributes.category_id.sorted()])
if any(not pa.category_id for pa in attributes):
# category_id is not required and the mapped does not return empty
categories[self.env['product.attribute.category']] = OrderedDict()
for pa in attributes:
categories[pa.category_id][pa] = OrderedDict([(
product,
product.product_template_attribute_value_ids.filtered(lambda ptav: ptav.attribute_id == pa)
) for product in self])
return categories
| 41.5 | 3,320 |
1,797 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
from odoo.addons.website_sale.controllers.main import WebsiteSale
import json
class WebsiteSaleProductComparison(WebsiteSale):
@http.route('/shop/compare', type='http', auth="public", website=True, sitemap=False)
def product_compare(self, **post):
values = {}
product_ids = [int(i) for i in post.get('products', '').split(',') if i.isdigit()]
if not product_ids:
return request.redirect("/shop")
# use search to check read access on each record/ids
products = request.env['product.product'].search([('id', 'in', product_ids)])
values['products'] = products.with_context(display_default_code=False)
return request.render("website_sale_comparison.product_compare", values)
@http.route(['/shop/get_product_data'], type='json', auth="public", website=True)
def get_product_data(self, product_ids, cookies=None):
ret = {}
pricelist_context, pricelist = self._get_pricelist_context()
prods = request.env['product.product'].with_context(pricelist_context, display_default_code=False).search([('id', 'in', product_ids)])
if cookies is not None:
ret['cookies'] = json.dumps(request.env['product.product'].search([('id', 'in', list(set(product_ids + cookies)))]).ids)
prods.mapped('name')
for prod in prods:
ret[prod.id] = {
'render': request.env['ir.ui.view']._render_template(
"website_sale_comparison.product_product",
{'product': prod, 'website': request.website}
),
'product': dict(id=prod.id, name=prod.name, display_name=prod.display_name),
}
return ret
| 46.076923 | 1,797 |
794 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Extended Addresses',
'summary': 'Add extra fields on addresses',
'sequence': '19',
'category': 'Hidden',
'complexity': 'easy',
'description': """
Extended Addresses Management
=============================
This module holds all extra fields one may need to manage accurately addresses.
For example, in legal reports, some countries need to split the street into several fields,
with the street name, the house number, and room number.
""",
'data': [
'views/base_address_extended.xml',
'data/base_address_extended_data.xml',
],
'depends': ['base'],
'post_init_hook': '_update_street_format',
'license': 'LGPL-3',
}
| 31.76 | 794 |
10,043 |
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.tests.common import TransactionCase
class TestStreetFields(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestStreetFields, cls).setUpClass()
cls.Partner = cls.env['res.partner']
cls.env.ref('base.be').write({'street_format': '%(street_name)s, %(street_number)s/%(street_number2)s'})
cls.env.ref('base.us').write({'street_format': '%(street_number)s/%(street_number2)s %(street_name)s'})
cls.env.ref('base.ch').write({'street_format': 'header %(street_name)s, %(street_number)s - %(street_number2)s trailer'})
cls.env.ref('base.mx').write({'street_format': '%(street_name)s %(street_number)s/%(street_number2)s'})
def assertStreetVals(self, record, street_data):
for key, val in street_data.items():
if key not in ['street', 'street_name', 'street_number', 'street_number2', 'name', 'city', 'country_id']:
continue
if isinstance(record[key], models.BaseModel):
self.assertEqual(record[key].id, val, 'Wrongly formatted street field %s: expected %s, received %s' % (key, val, record[key]))
else:
self.assertEqual(record[key], val, 'Wrongly formatted street field %s: expected %s, received %s' % (key, val, record[key]))
def test_company_create(self):
""" Will test the compute and inverse methods of street fields when creating partner records. """
us_id = self.env.ref('base.us').id
mx_id = self.env.ref('base.mx').id
ch_id = self.env.ref('base.ch').id
input_values = [
{'country_id': us_id, 'street': '40/2b Chaussee de Namur'},
{'country_id': us_id, 'street': '40 Chaussee de Namur'},
{'country_id': us_id, 'street': 'Chaussee de Namur'},
{'country_id': mx_id, 'street': 'Av. Miguel Hidalgo y Costilla 601'},
{'country_id': mx_id, 'street': 'Av. Miguel Hidalgo y Costilla 601/40'},
{'country_id': ch_id, 'street': 'header Chaussee de Namur, 40 - 2b trailer'},
{'country_id': ch_id, 'street': 'header Chaussee de Namur, 40 trailer'},
{'country_id': ch_id, 'street': 'header Chaussee de Namur trailer'},
]
expected = [
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': '2b'},
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': False},
{'street_name': 'de Namur', 'street_number': 'Chaussee', 'street_number2': False},
{'street_name': 'Av. Miguel Hidalgo y Costilla', 'street_number': '601', 'street_number2': False},
{'street_name': 'Av. Miguel Hidalgo y Costilla', 'street_number': '601', 'street_number2': '40'},
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': '2b'},
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': False},
{'street_name': 'Chaussee de Namur', 'street_number': False, 'street_number2': False}
]
# test street -> street values (compute)
for idx, (company_values, expected_vals) in enumerate(zip(input_values, expected)):
company_values['name'] = 'Test-%2d' % idx
company = self.env['res.company'].create(company_values)
self.assertStreetVals(company, expected_vals)
self.assertStreetVals(company.partner_id, expected_vals)
# test street_values -> street (inverse)
for idx, (company_values, expected_vals) in enumerate(zip(input_values, expected)):
company_values['name'] = 'TestNew-%2d' % idx
expected_street = company_values.pop('street')
company_values.update(expected_vals)
company = self.env['res.company'].create(company_values)
self.assertEqual(company.street, expected_street)
self.assertStreetVals(company, company_values)
self.assertEqual(company.partner_id.street, expected_street)
self.assertStreetVals(company.partner_id, company_values)
def test_company_write(self):
""" Will test the compute and inverse methods of street fields when updating partner records. """
be_id = self.env.ref('base.be').id
company = self.env['res.company'].create({
'name': 'Test',
'country_id': be_id,
'street': 'Chaussee de Namur, 40/2b'
})
self.assertStreetVals(company, {'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': '2b'})
input_values = [
{'street': 'Chaussee de Namur, 43'},
{'street': 'Chaussee de Namur'},
{'street_name': 'Chee de Namur', 'street_number': '40'},
{'street_number2': '4'},
{'country_id': self.env.ref('base.us').id},
]
expected = [
{'street_name': 'Chaussee de Namur', 'street_number': '43', 'street_number2': False},
{'street_name': 'Chaussee de Namur', 'street_number': False, 'street_number2': False},
{'street_name': 'Chee de Namur', 'street_number': '40', 'street_number2': False, 'street': 'Chee de Namur, 40'},
{'street_name': 'Chee de Namur', 'street_number': '40', 'street_number2': '4', 'street': 'Chee de Namur, 40/4'},
{'street_name': 'Chee de Namur', 'street_number': '40', 'street_number2': '4', 'street': '40/4 Chee de Namur'},
]
# test both compute and inverse (could probably be pimp)
for write_values, expected_vals in zip(input_values, expected):
company.write(write_values)
self.assertStreetVals(company, expected_vals)
self.assertStreetVals(company.partner_id, expected_vals)
def test_partner_create(self):
""" Will test the compute and inverse methods of street fields when creating partner records. """
us_id = self.env.ref('base.us').id
mx_id = self.env.ref('base.mx').id
ch_id = self.env.ref('base.ch').id
input_values = [
{'country_id': us_id, 'street': '40/2b Chaussee de Namur'},
{'country_id': us_id, 'street': '40 Chaussee de Namur'},
{'country_id': us_id, 'street': 'Chaussee de Namur'},
{'country_id': mx_id, 'street': 'Av. Miguel Hidalgo y Costilla 601'},
{'country_id': mx_id, 'street': 'Av. Miguel Hidalgo y Costilla 601/40'},
{'country_id': ch_id, 'street': 'header Chaussee de Namur, 40 - 2b trailer'},
{'country_id': ch_id, 'street': 'header Chaussee de Namur, 40 trailer'},
{'country_id': ch_id, 'street': 'header Chaussee de Namur trailer'},
]
expected = [
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': '2b'},
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': False},
{'street_name': 'de Namur', 'street_number': 'Chaussee', 'street_number2': False},
{'street_name': 'Av. Miguel Hidalgo y Costilla', 'street_number': '601', 'street_number2': False},
{'street_name': 'Av. Miguel Hidalgo y Costilla', 'street_number': '601', 'street_number2': '40'},
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': '2b'},
{'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': False},
{'street_name': 'Chaussee de Namur', 'street_number': False, 'street_number2': False}
]
# test street -> street values (compute)
for partner_values, expected_vals in zip(input_values, expected):
partner_values['name'] = 'Test'
partner = self.env['res.partner'].create(partner_values)
self.assertStreetVals(partner, expected_vals)
# test street_values -> street (inverse)
for partner_values, expected_vals in zip(input_values, expected):
partner_values['name'] = 'Test'
expected_street = partner_values.pop('street')
partner_values.update(expected_vals)
partner = self.env['res.partner'].create(partner_values)
self.assertEqual(partner.street, expected_street)
self.assertStreetVals(partner, partner_values)
def test_partner_write(self):
""" Will test the compute and inverse methods of street fields when updating partner records. """
be_id = self.env.ref('base.be').id
partner = self.env['res.partner'].create({
'name': 'Test',
'country_id': be_id,
'street': 'Chaussee de Namur, 40/2b'
})
self.assertStreetVals(partner, {'street_name': 'Chaussee de Namur', 'street_number': '40', 'street_number2': '2b'})
input_values = [
{'street': 'Chaussee de Namur, 43'},
{'street': 'Chaussee de Namur'},
{'street_name': 'Chee de Namur', 'street_number': '40'},
{'street_number2': '4'},
{'country_id': self.env.ref('base.us').id},
]
expected = [
{'street_name': 'Chaussee de Namur', 'street_number': '43', 'street_number2': False},
{'street_name': 'Chaussee de Namur', 'street_number': False, 'street_number2': False},
{'street_name': 'Chee de Namur', 'street_number': '40', 'street_number2': False, 'street': 'Chee de Namur, 40'},
{'street_name': 'Chee de Namur', 'street_number': '40', 'street_number2': '4', 'street': 'Chee de Namur, 40/4'},
{'street_name': 'Chee de Namur', 'street_number': '40', 'street_number2': '4', 'street': '40/4 Chee de Namur'},
]
# test both compute and inverse (could probably be pimp)
for write_values, expected_vals in zip(input_values, expected):
partner.write(write_values)
self.assertStreetVals(partner, expected_vals)
| 58.389535 | 10,043 |
1,036 |
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 ResCountry(models.Model):
_inherit = 'res.country'
street_format = fields.Text(
help="Format to use for streets belonging to this country.\n\n"
"You can use the python-style string pattern with all the fields of the street "
"(for example, use '%(street_name)s, %(street_number)s' if you want to display "
"the street name, followed by a comma and the house number)"
"\n%(street_name)s: the name of the street"
"\n%(street_number)s: the house number"
"\n%(street_number2)s: the door number",
default='%(street_number)s/%(street_number2)s %(street_name)s', required=True)
@api.onchange("street_format")
def onchange_street_format(self):
# Prevent unexpected truncation with whitespaces in front of the street format
self.street_format = self.street_format.strip()
| 45.043478 | 1,036 |
1,248 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Company(models.Model):
_inherit = 'res.company'
street_name = fields.Char('Street Name', compute='_compute_address',
inverse='_inverse_street_name')
street_number = fields.Char('House Number', compute='_compute_address',
inverse='_inverse_street_number')
street_number2 = fields.Char('Door Number', compute='_compute_address',
inverse='_inverse_street_number2')
def _get_company_address_field_names(self):
fields_matching = super(Company, self)._get_company_address_field_names()
return list(set(fields_matching + ['street_name', 'street_number', 'street_number2']))
def _inverse_street_name(self):
for company in self:
company.partner_id.street_name = company.street_name
def _inverse_street_number(self):
for company in self:
company.partner_id.street_number = company.street_number
def _inverse_street_number2(self):
for company in self:
company.partner_id.street_number2 = company.street_number2
| 40.258065 | 1,248 |
6,389 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class Partner(models.Model):
_inherit = ['res.partner']
street_name = fields.Char(
'Street Name', compute='_compute_street_data', inverse='_inverse_street_data', store=True)
street_number = fields.Char(
'House', compute='_compute_street_data', inverse='_inverse_street_data', store=True)
street_number2 = fields.Char(
'Door', compute='_compute_street_data', inverse='_inverse_street_data', store=True)
def _inverse_street_data(self):
"""Updates the street field.
Writes the `street` field on the partners when one of the sub-fields in STREET_FIELDS
has been touched"""
street_fields = self._get_street_fields()
for partner in self:
street_format = (partner.country_id.street_format or
'%(street_number)s/%(street_number2)s %(street_name)s')
previous_field = None
previous_pos = 0
street_value = ""
separator = ""
# iter on fields in street_format, detected as '%(<field_name>)s'
for re_match in re.finditer(r'%\(\w+\)s', street_format):
# [2:-2] is used to remove the extra chars '%(' and ')s'
field_name = re_match.group()[2:-2]
field_pos = re_match.start()
if field_name not in street_fields:
raise UserError(_("Unrecognized field %s in street format.", field_name))
if not previous_field:
# first iteration: add heading chars in street_format
if partner[field_name]:
street_value += street_format[0:field_pos] + partner[field_name]
else:
# get the substring between 2 fields, to be used as separator
separator = street_format[previous_pos:field_pos]
if street_value and partner[field_name]:
street_value += separator
if partner[field_name]:
street_value += partner[field_name]
previous_field = field_name
previous_pos = re_match.end()
# add trailing chars in street_format
street_value += street_format[previous_pos:]
partner.street = street_value
@api.depends('street')
def _compute_street_data(self):
"""Splits street value into sub-fields.
Recomputes the fields of STREET_FIELDS when `street` of a partner is updated"""
street_fields = self._get_street_fields()
for partner in self:
if not partner.street:
for field in street_fields:
partner[field] = None
continue
street_format = (partner.country_id.street_format or
'%(street_number)s/%(street_number2)s %(street_name)s')
street_raw = partner.street
vals = self._split_street_with_params(street_raw, street_format)
# assign the values to the fields
for k, v in vals.items():
partner[k] = v
for k in set(street_fields) - set(vals):
partner[k] = None
def _split_street_with_params(self, street_raw, street_format):
street_fields = self._get_street_fields()
vals = {}
previous_pos = 0
field_name = None
# iter on fields in street_format, detected as '%(<field_name>)s'
for re_match in re.finditer(r'%\(\w+\)s', street_format):
field_pos = re_match.start()
if not field_name:
#first iteration: remove the heading chars
street_raw = street_raw[field_pos:]
# get the substring between 2 fields, to be used as separator
separator = street_format[previous_pos:field_pos]
field_value = None
if separator and field_name:
#maxsplit set to 1 to unpack only the first element and let the rest untouched
tmp = street_raw.split(separator, 1)
if previous_greedy in vals:
# attach part before space to preceding greedy field
append_previous, sep, tmp[0] = tmp[0].rpartition(' ')
street_raw = separator.join(tmp)
vals[previous_greedy] += sep + append_previous
if len(tmp) == 2:
field_value, street_raw = tmp
vals[field_name] = field_value
if field_value or not field_name:
previous_greedy = None
if field_name == 'street_name' and separator == ' ':
previous_greedy = field_name
# select next field to find (first pass OR field found)
# [2:-2] is used to remove the extra chars '%(' and ')s'
field_name = re_match.group()[2:-2]
else:
# value not found: keep looking for the same field
pass
if field_name not in street_fields:
raise UserError(_("Unrecognized field %s in street format.", field_name))
previous_pos = re_match.end()
# last field value is what remains in street_raw minus trailing chars in street_format
trailing_chars = street_format[previous_pos:]
if trailing_chars and street_raw.endswith(trailing_chars):
vals[field_name] = street_raw[:-len(trailing_chars)]
else:
vals[field_name] = street_raw
return vals
def write(self, vals):
res = super(Partner, self).write(vals)
if 'country_id' in vals and 'street' not in vals:
self._inverse_street_data()
return res
def _formatting_address_fields(self):
"""Returns the list of address fields usable to format addresses."""
return super(Partner, self)._formatting_address_fields() + self._get_street_fields()
def _get_street_fields(self):
"""Returns the fields that can be used in a street format.
Overwrite this function if you want to add your own fields."""
return ['street_name', 'street_number', 'street_number2']
| 45.964029 | 6,389 |
1,950 |
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Module programed and financed by:
# Vauxoo, C.A. (<http://vauxoo.com>).
# Our Community team mantain this module:
# https://launchpad.net/~openerp-venezuela
{
'name' : 'Venezuela - Accounting',
'author': ['Odoo S.A.', 'Vauxoo'],
'category': 'Accounting/Localizations/Account Charts',
'description':
"""
Chart of Account for Venezuela.
===============================
Venezuela doesn't have any chart of account by law, but the default
proposed in Odoo should comply with some Accepted best practices in Venezuela,
this plan comply with this practices.
This module has been tested as base for more of 1000 companies, because
it is based in a mixtures of most common software in the Venezuelan
market what will allow for sure to accountants feel them first steps with
Odoo more comfortable.
This module doesn't pretend be the total localization for Venezuela,
but it will help you to start really quickly with Odoo in this country.
This module give you.
---------------------
- Basic taxes for Venezuela.
- Have basic data to run tests with community localization.
- Start a company from 0 if your needs are basic from an accounting PoV.
We recomend use of account_anglo_saxon if you want valued your
stocks as Venezuela does with out invoices.
If you install this module, and select Custom chart a basic chart will be proposed,
but you will need set manually account defaults for taxes.
""",
'depends': ['account',
],
'data': [
'data/l10n_ve_chart_data.xml',
'data/account.account.template.csv',
'data/l10n_ve_chart_post_data.xml',
'data/account_tax_group_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_data.xml'
],
'demo': [
'demo/demo_company.xml',
],
'license': 'LGPL-3',
}
| 34.210526 | 1,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.