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
|
|---|---|---|---|---|---|---|
3,434
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import datetime
from odoo import fields
from odoo.tests import tagged
from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon
@tagged("post_install", "-at_install")
class TestUi(TestPointOfSaleHttpCommon):
@classmethod
def setUpClass(cls, **kwargs):
super().setUpClass(**kwargs)
cls.env.user.groups_id += cls.env.ref("event.group_event_user")
cls.main_pos_config.iface_event_sale = True
# Configure product
cls.product_event = cls.env.ref("event_sale.product_product_event")
cls.product_event.active = True
cls.product_event.available_in_pos = True
# Create event
cls.event = cls.env["event.event"].create(
{
"name": "Les Misérables",
"event_type_id": cls.env.ref("event.event_type_0").id,
"use_sessions": True,
"stage_id": cls.env.ref("event.event_stage_booked").id,
"seats_limited": True,
"seats_max": 5,
}
)
cls.ticket_kids = cls.env["event.event.ticket"].create(
{
"name": "Kids",
"product_id": cls.product_event.id,
"event_id": cls.event.id,
"price": 0.0,
}
)
cls.ticket_regular = cls.env["event.event.ticket"].create(
{
"name": "Standard",
"product_id": cls.product_event.id,
"event_id": cls.event.id,
"price": 15.0,
}
)
# Create sessions
# Both at the same time and the whole day to avoid issues
# with current time (during tests)
date_begin = datetime.combine(fields.Date.today(), datetime.min.time())
date_end = datetime.combine(fields.Date.today(), datetime.max.time())
cls.sessions = cls.env["event.session"].create(
[
{
"event_id": cls.event.id,
"date_begin": date_begin,
"date_end": date_end,
},
{
"event_id": cls.event.id,
"date_begin": date_begin,
"date_end": date_end,
},
]
)
def test_pos_event_sale_basic_tour(self):
self.main_pos_config.open_session_cb(check_coa=False)
self.start_tour(
f"/pos/ui?config_id={self.main_pos_config.id}",
"EventSaleSessionTour",
login="accountman",
)
# Check POS Order (last created order)
pos_order = self.env["pos.order"].search([], order="id desc", limit=1)
# Check registrations
self.assertEqual(pos_order.event_registrations_count, 5)
self.assertEqual(pos_order.event_registration_ids.session_id, self.sessions)
for reg in pos_order.event_registration_ids:
self.assertEqual(reg.state, "open")
# Total sold amount for the event and sessions
self.assertEqual(self.event.pos_price_subtotal, 45.0)
self.assertEqual(self.sessions[0].pos_price_subtotal, 15.0)
self.assertEqual(self.sessions[1].pos_price_subtotal, 30.0)
| 39
| 3,432
|
3,558
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class EventSession(models.Model):
_inherit = "event.session"
pos_order_line_ids = fields.One2many(
comodel_name="pos.order.line",
inverse_name="event_session_id",
groups="point_of_sale.group_pos_user",
string="All the PoS Order Lines pointing to this event",
readonly=True,
)
pos_price_subtotal = fields.Monetary(
string="POS Sales (Tax Excluded)",
compute="_compute_pos_price_subtotal",
groups="point_of_sale.group_pos_user",
)
@api.depends(
"currency_id",
"pos_order_line_ids.price_subtotal",
"pos_order_line_ids.currency_id",
"pos_order_line_ids.company_id",
"pos_order_line_ids.order_id.date_order",
)
def _compute_pos_price_subtotal(self):
"""Compute POS Sales Amount
This method is similar to :meth:`~_compute_sale_price_subtotal`
only here we consider sales coming from pos.order.line(s).
"""
date_now = fields.Datetime.now()
sale_price_by_session = {}
if self.ids:
session_subtotals = self.env["pos.order.line"].read_group(
[
("event_session_id", "in", self.ids),
("order_id.state", "!=", "cancel"),
("price_subtotal", "!=", 0),
],
["event_session_id", "currency_id", "price_subtotal:sum"],
["event_session_id", "currency_id"],
lazy=False,
)
currency_ids = [
session_subtotal["currency_id"][0]
for session_subtotal in session_subtotals
]
company_by_session = {
session._origin.id or session.id: session.company_id for session in self
}
currency_by_event = {
session._origin.id or session.id: session.currency_id
for session in self
}
currency_by_id = {
currency.id: currency
for currency in self.env["res.currency"].browse(currency_ids)
}
for session_subtotal in session_subtotals:
price_subtotal = session_subtotal["price_subtotal"]
event_session_id = session_subtotal["event_session_id"][0]
currency_id = session_subtotal["currency_id"][0]
sale_price = currency_by_event[event_session_id]._convert(
price_subtotal,
currency_by_id[currency_id],
company_by_session[event_session_id],
date_now,
)
if event_session_id in sale_price_by_session:
sale_price_by_session[event_session_id] += sale_price
else:
sale_price_by_session[event_session_id] = sale_price
for rec in self:
rec.pos_price_subtotal = sale_price_by_session.get(
rec._origin.id or rec.id, 0
)
def action_view_pos_orders(self):
action = self.env["ir.actions.actions"]._for_xml_id(
"point_of_sale.action_pos_pos_form"
)
action["domain"] = [
("state", "!=", "cancel"),
("lines.event_session_id", "in", self.ids),
]
return action
| 38.247312
| 3,557
|
1,419
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PosOrderLine(models.Model):
_inherit = "pos.order.line"
event_session_id = fields.Many2one(
comodel_name="event.session",
string="Event Session",
readonly=True,
)
def _prepare_event_registration_vals(self):
res = super()._prepare_event_registration_vals()
res["session_id"] = self.event_session_id.id
return res
def _prepare_refund_data(self, refund_order, PosOrderLineLot):
# OVERRIDE to add the event the event.session info to refunds
res = super()._prepare_refund_data(refund_order, PosOrderLineLot)
if self.event_session_id:
res["event_session_id"] = self.event_session_id.id
return res
def _find_event_registrations_to_negate(self):
# OVERRIDE to match also by event_session_id
return (
super()
._find_event_registrations_to_negate()
.filtered(lambda r: r.session_id == self.event_session_id)
)
def _export_for_ui(self, orderline):
# OVERRIDE to add event_session_id
res = super()._export_for_ui(orderline)
res["event_session_id"] = orderline.event_session_id.id
return res
| 34.585366
| 1,418
|
727
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PosOrderReport(models.Model):
_inherit = "report.pos.order"
event_session_id = fields.Many2one(
comodel_name="event.session",
string="Event Session",
readonly=True,
)
def _select(self):
res = super()._select()
return f"""
{res},
l.event_session_id AS event_session_id
"""
def _group_by(self):
res = super()._group_by()
return f"""
{res},
l.event_session_id
"""
| 25.034483
| 726
|
1,466
|
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-pos",
description="Meta package for oca-pos Odoo addons",
version=version,
install_requires=[
'odoo-addon-pos_cash_move_reason>=15.0dev,<15.1dev',
'odoo-addon-pos_default_partner>=15.0dev,<15.1dev',
'odoo-addon-pos_event_sale>=15.0dev,<15.1dev',
'odoo-addon-pos_event_sale_registration_qr_code>=15.0dev,<15.1dev',
'odoo-addon-pos_event_sale_session>=15.0dev,<15.1dev',
'odoo-addon-pos_hide_cost_price_and_margin>=15.0dev,<15.1dev',
'odoo-addon-pos_lot_barcode>=15.0dev,<15.1dev',
'odoo-addon-pos_lot_selection>=15.0dev,<15.1dev',
'odoo-addon-pos_payment_change>=15.0dev,<15.1dev',
'odoo-addon-pos_product_display_default_code>=15.0dev,<15.1dev',
'odoo-addon-pos_receipt_hide_price>=15.0dev,<15.1dev',
'odoo-addon-pos_report_session_summary>=15.0dev,<15.1dev',
'odoo-addon-pos_sale_pos_event_sale>=15.0dev,<15.1dev',
'odoo-addon-pos_sale_pos_event_sale_session>=15.0dev,<15.1dev',
'odoo-addon-pos_supplierinfo_barcode>=15.0dev,<15.1dev',
'odoo-addon-pos_supplierinfo_search>=15.0dev,<15.1dev',
'odoo-addon-pos_user_restriction>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 43.117647
| 1,466
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
770
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Point of Sale Registration QR Code",
"summary": "Print registration QR codes on Point of Sale receipts",
"author": "Moka Tourisme, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"category": "Marketing",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"maintainers": ["ivantodorovich"],
"depends": ["pos_event_sale", "event_registration_qr_code"],
"assets": {
"web.assets_qweb": [
"pos_event_sale_registration_qr_code/static/src/xml/**/*.xml",
],
},
"auto_install": True,
}
| 36.619048
| 769
|
686
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa S.L. - David Vidal
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "POS Lot Selection",
"version": "15.0.1.0.1",
"category": "Point of Sale",
"author": "Tecnativa, Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"license": "AGPL-3",
"depends": [
"point_of_sale",
],
"assets": {
"web.assets_qweb": ["pos_lot_selection/static/src/xml/**/*.xml"],
"point_of_sale.assets": [
"pos_lot_selection/static/src/js/**/*.js",
],
},
"application": False,
"installable": True,
}
| 29.826087
| 686
|
797
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import api, models
from odoo.tools import float_compare
class ProductionLot(models.Model):
_inherit = "stock.production.lot"
@api.model
def get_available_lots_for_pos(self, product_id, company_id):
lots = self.sudo().search(
[
"&",
["product_id", "=", product_id],
"|",
["company_id", "=", company_id],
["company_id", "=", False],
]
)
lots = lots.filtered(
lambda l: float_compare(
l.product_qty, 0, precision_digits=l.product_uom_id.rounding
)
> 0
)
return lots.mapped("name")
| 26.566667
| 797
|
783
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Lorenzo Battistini @ TAKOBI
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Point of sale - Supplier barcodes",
"summary": "Search products by supplier barcode",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "Point Of Sale",
"website": "https://github.com/OCA/pos",
"author": "TAKOBI, Odoo Community Association (OCA)",
"maintainers": ["eLBati"],
"license": "LGPL-3",
"application": False,
"installable": True,
"auto_install": True,
"depends": [
"product_supplierinfo_barcode",
"point_of_sale",
],
"assets": {
"point_of_sale.assets": [
"/pos_supplierinfo_barcode/static/src/js/db.js",
],
},
"demo": [],
}
| 30.115385
| 783
|
525
|
py
|
PYTHON
|
15.0
|
import json
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
# technical field used in POS frontend
supplier_barcode_json = fields.Char(
"Supplier barcode list", readonly=True, compute="_compute_supplier_barcode_json"
)
def _compute_supplier_barcode_json(self):
for t in self:
supplier_barcode_json = [x for x in t.mapped("seller_ids.barcode") if x]
t.supplier_barcode_json = json.dumps(supplier_barcode_json)
| 30.882353
| 525
|
531
|
py
|
PYTHON
|
15.0
|
# copyright 2020 Akretion David BEAL
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Point Of Sale Default Partner",
"summary": "Add a default customer in pos order",
"license": "AGPL-3",
"version": "15.0.1.0.0",
"author": "Akretion," "Odoo Community Association (OCA)",
"maintainer": "Akretion",
"category": "Point of sale",
"depends": ["point_of_sale"],
"data": ["views/pos_config.xml"],
"website": "https://github.com/OCA/pos",
"installable": True,
}
| 33.1875
| 531
|
4,824
|
py
|
PYTHON
|
15.0
|
from odoo import fields
from odoo.tests.common import TransactionCase
class TestPosDefaultPartner(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.config = cls.env["pos.config"].create({"name": "DEMO Config"})
# Create a new cash payment method
cls.cash_pm1 = cls.env["pos.payment.method"].create(
{
"name": "Cash",
"journal_id": cls.env["account.journal"]
.search([("code", "=", "CSH1")])
.id,
"company_id": cls.env.company.id,
}
)
cls.config.payment_method_ids = cls.cash_pm1
cls.PosOrder = cls.env["pos.order"]
cls.AccountPayment = cls.env["account.payment"]
# Get Object
cls.pos_product = cls.env["product.product"].create(
{"name": "Test POS Product"}
)
cls.pricelist = cls.env["product.pricelist"].create(
{
"name": "Test pricelist",
"currency_id": cls.env.user.company_id.currency_id.id,
"item_ids": [
(
0,
0,
{
"applied_on": "3_global",
"compute_price": "formula",
"base": "list_price",
},
)
],
}
)
cls.partner_01 = cls.env["res.partner"].create({"name": "Test partner 1"})
cls.partner_02 = cls.env["res.partner"].create({"name": "Test partner 2"})
def _create_order(self, partner_id=False):
self.config.open_session_cb()
session = self.config.current_session_id
account_receivable_id = (
self.env.user.partner_id.property_account_receivable_id.id
)
payment_methods = session.payment_method_ids
# Create order
order_data = {
"id": "0006-001-0010",
"to_invoice": True,
"data": {
"pricelist_id": self.pricelist.id,
"user_id": 1,
"name": "Order 0006-001-0010",
"partner_id": partner_id,
"amount_paid": 0.9,
"pos_session_id": session.id,
"lines": [
[
0,
0,
{
"product_id": self.pos_product.id,
"price_unit": 0.9,
"qty": 1,
"price_subtotal": 0.9,
"price_subtotal_incl": 0.9,
},
]
],
"statement_ids": [
[
0,
0,
{
"journal_id": session.statement_ids[0].journal_id.id,
"amount": 0.9,
"name": fields.Datetime.now(),
"account_id": account_receivable_id,
"statement_id": session.statement_ids[0].id,
"payment_method_id": payment_methods.filtered(
lambda pm: pm.is_cash_count
and not pm.split_transactions
)[0].id,
},
]
],
"creation_date": "2018-09-27 15:51:03",
"amount_tax": 0,
"fiscal_position_id": False,
"uid": "00001-001-0001",
"amount_return": 0,
"sequence_number": 1,
"amount_total": 0.9,
},
}
result = self.PosOrder.create_from_ui([order_data])
order = self.PosOrder.browse(result[0]["id"])
return order
def test_no_default_partner(self):
order = self._create_order()
self.assertTrue(order)
self.assertFalse(order.partner_id)
def test_no_default_partner_assigned_partner(self):
order = self._create_order(self.partner_01.id)
self.assertTrue(order)
self.assertEqual(order.partner_id, self.partner_01)
def test_default_partner(self):
self.config.default_partner_id = self.partner_02
order = self._create_order()
self.assertTrue(order)
self.assertEqual(order.partner_id, self.partner_02)
def test_default_partner_assigned_partner(self):
self.config.default_partner_id = self.partner_02
order = self._create_order(self.partner_01.id)
self.assertTrue(order)
self.assertEqual(order.partner_id, self.partner_01)
| 36.824427
| 4,824
|
308
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
default_partner_id = fields.Many2one(
comodel_name="res.partner",
string="Default Customer",
)
| 22
| 308
|
524
|
py
|
PYTHON
|
15.0
|
# copyright 2020 Akretion David BEAL
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class PosOrder(models.Model):
_inherit = "pos.order"
@api.model
def _complete_values_from_session(self, session, values):
result = super()._complete_values_from_session(session, values)
if session.config_id.default_partner_id and not result.get("partner_id"):
result["partner_id"] = session.config_id.default_partner_id.id
return result
| 34.933333
| 524
|
848
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2013 - Today: GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Point Of Sale - Change Payments",
"version": "15.0.1.0.0",
"summary": "Allow cashier to change order payments, as long as"
" the session is not closed.",
"category": "Point Of Sale",
"author": "GRAP, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"license": "AGPL-3",
"depends": ["point_of_sale"],
"maintainers": ["legalsylvain"],
"development_status": "Beta",
"data": [
"security/ir.model.access.csv",
"wizards/view_pos_payment_change_wizard.xml",
"views/view_pos_config.xml",
"views/view_pos_order.xml",
],
"installable": True,
}
| 36.869565
| 848
|
6,597
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 - Today: GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class TestModule(TransactionCase):
"""Tests for 'Point of Sale - Change Payment' Module"""
def setUp(self):
super().setUp()
self.PosSession = self.env["pos.session"]
self.PosOrder = self.env["pos.order"]
self.PosPaymentMethod = self.env["pos.payment.method"]
self.PosPayment = self.env["pos.payment"]
self.PosMakePayment = self.env["pos.make.payment"]
self.PosPaymentChangeWizard = self.env["pos.payment.change.wizard"]
self.PosPaymentChangeWizardNewLine = self.env[
"pos.payment.change.wizard.new.line"
]
self.product = self.env.ref("product.product_product_3")
self.pos_config = self.env.ref("point_of_sale.pos_config_main").copy()
def _initialize_journals_open_session(self):
account_id = self.env.company.account_default_pos_receivable_account_id
self.bank_payment_method = self.PosPaymentMethod.create(
{
"name": "Bank",
"receivable_account_id": account_id.id,
}
)
self.cash_payment_method = self.PosPaymentMethod.create(
{
"name": "Cash",
"is_cash_count": True,
"receivable_account_id": account_id.id,
"journal_id": self.env["account.journal"]
.search(
[("type", "=", "cash"), ("company_id", "=", self.env.company.id)],
limit=1,
)
.id,
}
)
# create new session and open it
self.pos_config.payment_method_ids = [
self.bank_payment_method.id,
self.cash_payment_method.id,
]
self.pos_config.open_session_cb()
self.session = self.pos_config.current_session_id
def _sale(self, payment_method_1, price_1, payment_method_2=False, price_2=0.0):
price = price_1 + price_2
line_vals = {
"name": "OL/0001",
"product_id": self.product.id,
"qty": 1.0,
"price_unit": price,
"price_subtotal": price,
"price_subtotal_incl": price,
}
order = self.PosOrder.create(
{
"session_id": self.session.id,
"amount_tax": 0,
"amount_total": price,
"amount_paid": price,
"amount_return": 0,
"lines": [[0, False, line_vals]],
}
)
order.add_payment(
{
"pos_order_id": order.id,
"amount": price_1,
"payment_date": fields.Date.today(),
"payment_method_id": payment_method_1.id,
}
)
if payment_method_2:
order.add_payment(
{
"pos_order_id": order.id,
"amount": price_2,
"payment_date": fields.Date.today(),
"payment_method_id": payment_method_2.id,
}
)
order.action_pos_order_paid()
return order
def _change_payment(
self, order, payment_method_1, amount_1, payment_method_2=False, amount_2=0.0
):
# Switch to check journal
wizard = self.PosPaymentChangeWizard.with_context(active_id=order.id).create({})
self.PosPaymentChangeWizardNewLine.with_context(active_id=order.id).create(
{
"wizard_id": wizard.id,
"new_payment_method_id": payment_method_1.id,
"amount": amount_1,
}
)
if payment_method_2:
self.PosPaymentChangeWizardNewLine.with_context(active_id=order.id).create(
{
"wizard_id": wizard.id,
"new_payment_method_id": payment_method_2.id,
"amount": amount_2,
}
)
wizard.button_change_payment()
# Test Section
def test_01_payment_change_policy_update(self):
self.pos_config.payment_change_policy = "update"
self._initialize_journals_open_session()
# Make a sale with 35 in cash journal and 65 in check
order = self._sale(self.cash_payment_method, 35, self.bank_payment_method, 65)
order_qty = len(self.PosOrder.search([]))
with self.assertRaises(UserError):
# Should not work if total is not correct
self._change_payment(
order, self.cash_payment_method, 10, self.cash_payment_method, 10
)
self._change_payment(
order, self.cash_payment_method, 10, self.bank_payment_method, 90
)
self.bank_payment = self.session.order_ids.mapped("payment_ids").filtered(
lambda x: x.payment_method_id == self.bank_payment_method
)
self.cash_payment = self.session.order_ids.mapped("payment_ids").filtered(
lambda x: x.payment_method_id == self.cash_payment_method
)
# check Session
self.assertEqual(
self.cash_payment.amount,
10,
"Bad recompute of the balance for the statement cash",
)
self.assertEqual(
self.bank_payment.amount,
90,
"Bad recompute of the balance for the statement check",
)
# Check Order quantity
self.assertEqual(
order_qty,
len(self.PosOrder.search([])),
"In 'Update' mode, changing payment should not create" " other PoS Orders",
)
def test_02_payment_change_policy_refund(self):
self.pos_config.payment_change_policy = "refund"
self._initialize_journals_open_session()
# Make a sale with 35 in cash journal and 65 in check
order = self._sale(self.cash_payment_method, 35, self.bank_payment_method, 65)
order_qty = len(self.PosOrder.search([]))
self._change_payment(
order, self.cash_payment_method, 50, self.bank_payment_method, 50
)
# Check Order quantity
self.assertEqual(
order_qty + 2,
len(self.PosOrder.search([])),
"In 'Refund' mode, changing payment should generate" " two new PoS Orders",
)
| 36.04918
| 6,597
|
1,977
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 - Today: GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class PosConfig(models.Model):
_inherit = "pos.config"
_PAYMENT_CHANGE_POLICY_SELECTION = [
("refund", "Refund and Resale"),
("update", "Update Payments"),
]
payment_change_policy = fields.Selection(
selection=_PAYMENT_CHANGE_POLICY_SELECTION,
default="refund",
required=True,
help="Payment Change Policy when users want"
" to change the payment lines of a given PoS Order.\n"
"* 'Refund and Resale': Odoo will refund the current"
" Pos Order to cancel it, and create a new PoS Order"
" with the correct payment lines.\n"
"* 'Update Payments': Odoo will change payment lines.\n\n"
"Note : In some countries the 'Update Payments' Option"
" is not allowed by law, because orders history shouldn't"
" not be altered.",
)
@api.constrains("payment_change_policy")
def _check_payment_change_policy(self):
# Check if certification module is installed
# and if yes, if 'update payments' option is allowed
module_states = (
self.env["ir.module.module"]
.sudo()
.search([("name", "=", "l10n_fr_certification")])
.mapped("state")
)
if "installed" not in module_states:
return
for config in self.filtered(lambda x: x.payment_change_policy == "update"):
if config.company_id._is_accounting_unalterable():
raise ValidationError(
_(
"Unable to use the 'Update Payments' options"
" for companies that have unalterable accounting."
)
)
| 38.764706
| 1,977
|
3,793
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2015 - Today: GRAP (http://www.grap.coop)
# @author: Julien WESTE
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from datetime import datetime
from odoo import _, fields, models
from odoo.exceptions import Warning as UserError
from odoo.tools import float_is_zero
class PosOrder(models.Model):
_inherit = "pos.order"
def change_payment(self, payment_lines):
"""
Change payment of a given order.
payment_lines should be a list of data that are
the argument of the Odoo Core function add_payment()
Return a list of order ids, depending on the
payment_change_policy of the related pos_config.
"""
self.ensure_one()
orders = self
# Removing zero lines
precision = self.pricelist_id.currency_id.decimal_places
payment_lines = [
x
for x in payment_lines
if not float_is_zero(x["amount"], precision_digits=precision)
]
self._check_payment_change_allowed()
comment = _(
"The payments of the Order %(order)s (Ref: %(ref)s have"
" been changed by %(user_name)s on %(today)s",
order=self.name,
ref=self.pos_reference,
user_name=self.env.user.name,
today=datetime.today(),
)
if self.config_id.payment_change_policy == "update":
self.payment_ids.with_context().unlink()
# Create new payment
for line in payment_lines:
self.add_payment(line)
elif self.config_id.payment_change_policy == "refund":
# Refund order and mark it as paid
# with same payment method as the original one
refund_result = self.refund()
refund_order = self.browse(refund_result["res_id"])
for payment in self.payment_ids:
refund_order.add_payment(
{
"pos_order_id": refund_order.id,
"payment_method_id": payment.payment_method_id.id,
"amount": -payment.amount,
"payment_date": fields.Date.context_today(self),
}
)
refund_order.action_pos_order_paid()
# Resale order and mark it as paid
# with the new payment
resale_order = self.copy(default={"pos_reference": self.pos_reference})
for line in payment_lines:
line.update({"pos_order_id": resale_order.id})
resale_order.add_payment(line)
resale_order.action_pos_order_paid()
orders += refund_order + resale_order
comment += _(
" (Refund Order: %(refund_order)s ; Resale Order: %(resale_order)s)",
refund_order=refund_order.name,
resale_order=resale_order.name,
)
for order in orders:
order.note = "%s\n%s" % (order.note or "", comment)
return orders
def _check_payment_change_allowed(self):
"""Return True if the user can change the payment of a POS, depending
of the state of the current session."""
closed_orders = self.filtered(lambda x: x.session_id.state == "closed")
if len(closed_orders):
raise UserError(
_(
"You can not change payments of the POS '%(name)s' because"
" the associated session '%(session)s' has been closed!",
name=", ".join(closed_orders.mapped("name")),
session=", ".join(closed_orders.mapped("session_id.name")),
)
)
| 37.554455
| 3,793
|
1,111
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2015 - Today: GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PosPaymentChangeWizardOldLine(models.TransientModel):
_name = "pos.payment.change.wizard.old.line"
_description = "PoS Payment Change Wizard Old Line"
wizard_id = fields.Many2one(
comodel_name="pos.payment.change.wizard",
required=True,
)
old_payment_method_id = fields.Many2one(
comodel_name="pos.payment.method",
string="Payment Method",
required=True,
readonly=True,
)
company_currency_id = fields.Many2one(
comodel_name="res.currency",
store=True,
related="old_payment_method_id.company_id.currency_id",
string="Company Currency",
readonly=True,
help="Utility field to express amount currency",
)
amount = fields.Monetary(
required=True,
readonly=True,
default=0.0,
currency_field="company_currency_id",
)
| 29.236842
| 1,111
|
3,619
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2015-Today GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class PosPaymentChangeWizard(models.TransientModel):
_name = "pos.payment.change.wizard"
_description = "PoS Payment Change Wizard"
# Column Section
order_id = fields.Many2one(comodel_name="pos.order", string="Order", readonly=True)
old_line_ids = fields.One2many(
comodel_name="pos.payment.change.wizard.old.line",
inverse_name="wizard_id",
string="Old Payment Lines",
readonly=True,
)
new_line_ids = fields.One2many(
comodel_name="pos.payment.change.wizard.new.line",
inverse_name="wizard_id",
string="New Payment Lines",
)
amount_total = fields.Float(string="Total", readonly=True)
# View Section
@api.model
def default_get(self, fields):
PosOrder = self.env["pos.order"]
res = super().default_get(fields)
order = PosOrder.browse(self._context.get("active_id"))
old_lines_vals = []
for payment in order.payment_ids:
old_lines_vals.append(
(
0,
0,
{
"old_payment_method_id": payment.payment_method_id.id,
"amount": payment.amount,
},
)
)
res.update(
{
"order_id": order.id,
"amount_total": order.amount_total,
"old_line_ids": old_lines_vals,
}
)
return res
# View section
def button_change_payment(self):
self.ensure_one()
order = self.order_id
# Check if the total is correct
total = sum(self.mapped("new_line_ids.amount"))
if total != self.amount_total:
raise UserError(
_(
"Differences between the two values for the POS"
" Order '%(name)s':\n\n"
" * Total of all the new payments %(total)s;\n"
" * Total of the POS Order %(amount_total)s;\n\n"
"Please change the payments.",
name=order.name,
total=total,
amount_total=order.amount_total,
)
)
# Change payment
new_payments = [
{
"pos_order_id": order.id,
"payment_method_id": line.new_payment_method_id.id,
"amount": line.amount,
"payment_date": fields.Date.context_today(self),
}
for line in self.new_line_ids
]
orders = order.change_payment(new_payments)
# Note. Because of the poor design of the closing session process
# in Odoo, we call _check_pos_session_balance() that sets
# balance_end_real with balance_end for "non cash" journals
if order.session_id.state == "closing_control":
order.session_id._check_pos_session_balance()
if len(orders) == 1:
# if policy is 'update', only close the pop up
action = {"type": "ir.actions.act_window_close"}
else:
# otherwise (refund policy), displays the 3 orders
action = self.env.ref("point_of_sale.action_pos_pos_form").read()[0]
action["domain"] = [("id", "in", orders.ids)]
return action
| 34.141509
| 3,619
|
1,767
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2015 - Today: GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class PosPaymentChangeWizardLine(models.TransientModel):
_name = "pos.payment.change.wizard.new.line"
_description = "PoS Payment Change Wizard New Line"
wizard_id = fields.Many2one(
comodel_name="pos.payment.change.wizard",
required=True,
)
new_payment_method_id = fields.Many2one(
comodel_name="pos.payment.method",
string="Payment Method",
required=True,
domain=lambda s: s._domain_new_payment_method_id(),
)
company_currency_id = fields.Many2one(
comodel_name="res.currency",
store=True,
related="new_payment_method_id.company_id.currency_id",
string="Company Currency",
readonly=True,
help="Utility field to express amount currency",
)
amount = fields.Monetary(
required=True,
default=0.0,
currency_field="company_currency_id",
)
@api.model
def _domain_new_payment_method_id(self):
PosOrder = self.env["pos.order"]
order = PosOrder.browse(self.env.context.get("active_id"))
return [("id", "in", order.mapped("session_id.payment_method_ids").ids)]
# View Section
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if "new_line_ids" not in self._context:
return res
balance = self._context.get("amount_total", 0.0)
for line in self.wizard_id.old_line_ids:
balance -= line.get("amount")
res.update({"amount": balance})
return res
| 32.127273
| 1,767
|
572
|
py
|
PYTHON
|
15.0
|
# copyright Odoo SA
# copyright OCA
# Licence : LGPL-3
{
"name": "POS report Session Summary",
"version": "15.0.1.0.0",
"category": "Point Of Sale",
"summary": "Adds a Session Summary PDF report on the POS session",
"author": "Akretion, Odoo SA, Odoo Community Association (OCA)",
"license": "LGPL-3",
"depends": ["point_of_sale"],
"data": ["views/session_summary_report.xml", "views/report_session_summary.xml"],
"installable": True,
"application": False,
"website": "https://github.com/OCA/pos",
"auto_install": False,
}
| 31.777778
| 572
|
1,886
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import SUPERUSER_ID, api
from odoo.tools.sql import column_exists, create_column
_logger = logging.getLogger(__name__)
def pre_init_hook(cr):
"""Store currency_id in database for each existing pos_order_line"""
if not column_exists(cr, "pos_order_line", "currency_id"):
_logger.info("Pre-computing pos.order.line.currency_id..")
create_column(cr, "pos_order_line", "currency_id", "int4")
cr.execute(
"""
WITH pos_order_line_currency AS (
SELECT
pol.id AS id,
COALESCE(aj.currency_id, rc.currency_id) AS currency_id
FROM pos_order_line AS pol
JOIN pos_order AS po ON pol.order_id = po.id
JOIN pos_session AS ps ON po.session_id = ps.id
JOIN pos_config AS pc ON ps.config_id = pc.id
JOIN res_company AS rc ON pc.company_id = rc.id
LEFT JOIN account_journal AS aj ON pc.journal_id = aj.id
)
UPDATE pos_order_line
SET currency_id = pos_order_line_currency.currency_id
FROM pos_order_line_currency
WHERE pos_order_line.id = pos_order_line_currency.id
"""
)
def post_init_hook(cr, __):
"""Set the Event Registration product available for POS"""
env = api.Environment(cr, SUPERUSER_ID, {})
product = env.ref("event_sale.product_product_event", raise_if_not_found=False)
if product:
_logger.info("Setting default Event Product as available in Point of Sale..")
product.available_in_pos = True
| 41.888889
| 1,885
|
1,518
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Point of Sale Events",
"summary": "Sell events from Point of Sale",
"author": "Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"category": "Marketing",
"version": "15.0.3.1.0",
"license": "AGPL-3",
"maintainers": ["ivantodorovich"],
"depends": ["event_sale", "point_of_sale"],
"data": [
"security/security.xml",
"reports/report_pos_order.xml",
"views/event_registration.xml",
"views/event_event.xml",
"views/pos_order.xml",
"views/pos_config.xml",
],
"assets": {
"point_of_sale.assets": [
"web/static/lib/fullcalendar/core/main.css",
"web/static/lib/fullcalendar/daygrid/main.css",
"web/static/lib/fullcalendar/core/main.js",
"web/static/lib/fullcalendar/daygrid/main.js",
"web/static/lib/fullcalendar/interaction/main.js",
"pos_event_sale/static/src/js/**/*.js",
"pos_event_sale/static/src/scss/**/*.scss",
],
"web.assets_qweb": [
"pos_event_sale/static/src/xml/**/*.xml",
],
"web.assets_tests": [
"pos_event_sale/static/tests/tours/**/*",
],
},
"pre_init_hook": "pre_init_hook",
"post_init_hook": "post_init_hook",
}
| 36.119048
| 1,517
|
3,375
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com).
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import tagged
from .common import TestPoSEventCommon
@tagged("post_install", "-at_install")
class TestPoSEvent(TestPoSEventCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.order = cls._create_from_ui(
dict(
event_lines=[
dict(ticket=cls.ticket_kids, quantity=2),
dict(ticket=cls.ticket_regular, quantity=1),
]
)
)
def test_action_open_registrations(self):
action = self.order.action_open_event_registrations()
self.assertEqual(action["type"], "ir.actions.act_window")
def test_event_pos_price_subtotal(self):
self.assertEqual(self.event.pos_price_subtotal, self.order.amount_total)
def test_event_action_view_pos_orders(self):
action = self.event.action_view_pos_orders()
self.assertEqual(self.env["pos.order"].search(action["domain"]), self.order)
def test_order_refund(self):
refund = self.env["pos.order"].browse(self.order.refund()["res_id"])
self.env["pos.make.payment"].with_context(
active_ids=refund.ids,
active_id=refund.id,
active_model=refund._name,
).create(
{
"payment_method_id": self.config.payment_method_ids[0].id,
"amount": refund.amount_total,
}
).check()
self.assertTrue(
all(reg.state == "cancel" for reg in self.order.event_registration_ids)
)
def test_order_cancel(self):
done_registrations = self.order.event_registration_ids[-2:]
open_registrations = self.order.event_registration_ids - done_registrations
done_registrations.action_set_done()
self.order.action_pos_order_cancel()
self.assertTrue(
all(reg.state == "cancel" for reg in open_registrations),
"Open registrations should be cancelled with the order",
)
self.assertTrue(
all(reg.state == "done" for reg in done_registrations),
"Done registrations should remain done",
)
def test_order_with_negated_registrations(self):
order = self._create_from_ui(
dict(
event_lines=[
dict(ticket=self.ticket_kids, quantity=2),
dict(ticket=self.ticket_kids, quantity=-2),
dict(ticket=self.ticket_regular, quantity=1),
]
)
)
kids_registrations = order.event_registration_ids.filtered(
lambda r: r.event_ticket_id == self.ticket_kids
)
self.assertEqual(len(kids_registrations), 2)
self.assertTrue(
all(reg.state == "cancel" for reg in kids_registrations),
"Kids registrations should be cancelled (negated)",
)
regular_registrations = order.event_registration_ids.filtered(
lambda r: r.event_ticket_id == self.ticket_regular
)
self.assertEqual(len(regular_registrations), 1)
self.assertTrue(
all(reg.state == "open" for reg in regular_registrations),
"Regular registrations should be confirmed",
)
| 37.921348
| 3,375
|
1,083
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import tagged
from .common import TestPoSEventHttpCommon
@tagged("post_install", "-at_install")
class TestPoSEventHttp(TestPoSEventHttpCommon):
def test_pos_event_sale_basic_tour(self):
self.start_tour(
f"/pos/ui?config_id={self.main_pos_config.id}",
"EventSaleTour",
login="accountman",
)
order = self.env["pos.order"].search([], order="id desc", limit=1)
self.assertTrue(
all(reg.state == "open" for reg in order.event_registration_ids),
"Registrations should be confirmed",
)
def test_pos_event_sale_availability_tour(self):
self.event.seats_max = 5
self.ticket_kids.seats_max = 3
self.start_tour(
f"/pos/ui?config_id={self.main_pos_config.id}",
"EventSaleAvailabilityTour",
login="accountman",
)
| 34.903226
| 1,082
|
8,682
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com).
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from random import randint
from odoo import fields
from odoo.addons.point_of_sale.tests.common import TestPoSCommon
from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon
class PosEventMixin:
@classmethod
def setUpData(cls):
# Configure product
cls.product_event = cls.env.ref("event_sale.product_product_event")
cls.product_event.active = True
cls.product_event.available_in_pos = True
# Create event
cls.event = cls.env["event.event"].create(
{
"name": "Les Misérables",
"event_type_id": cls.env.ref("event.event_type_0").id,
"date_begin": fields.Datetime.start_of(fields.Datetime.now(), "day"),
"date_end": fields.Datetime.end_of(fields.Datetime.now(), "day"),
"stage_id": cls.env.ref("event.event_stage_booked").id,
"seats_limited": True,
"seats_max": 10,
}
)
cls.ticket_kids = cls.env["event.event.ticket"].create(
{
"name": "Kids",
"product_id": cls.product_event.id,
"event_id": cls.event.id,
"price": 0.0,
"seats_limited": True,
"seats_max": 5,
}
)
cls.ticket_regular = cls.env["event.event.ticket"].create(
{
"name": "Standard",
"product_id": cls.product_event.id,
"event_id": cls.event.id,
"price": 15.0,
}
)
class TestPoSEventCommon(TestPoSCommon, PosEventMixin):
@classmethod
def setUpClass(cls, **kwargs):
super().setUpClass(**kwargs)
cls.setUpData()
cls.env.user.groups_id += cls.env.ref("event.group_event_user")
cls.basic_config.iface_event_sale = True
cls.config = cls.basic_config
# Open session
cls.config.open_session_cb(check_coa=False)
cls.pos_session = cls.config.current_session_id
cls.currency = cls.pos_session.currency_id
cls.pricelist = cls.pos_session.config_id.pricelist_id
cls.pos_session.set_cashbox_pos(0.0, None)
# Used to generate unique order ids
cls._nextId = 0
@classmethod
def _create_order_line_data(cls, product=None, quantity=1.0, discount=0.0, fp=None):
cls._nextId += 1
price_unit = cls.pricelist.get_product_price(product, quantity, False)
tax_ids = fp.map_tax(product.taxes_id) if fp else product.taxes_id
price_unit_after_discount = price_unit * (1 - discount / 100.0)
tax_values = (
tax_ids.compute_all(price_unit_after_discount, cls.currency, quantity)
if tax_ids
else {
"total_excluded": price_unit * quantity,
"total_included": price_unit * quantity,
}
)
return {
"discount": discount,
"id": cls._nextId,
"pack_lot_ids": [],
"price_unit": price_unit,
"product_id": product.id,
"price_subtotal": tax_values["total_excluded"],
"price_subtotal_incl": tax_values["total_included"],
"qty": quantity,
"tax_ids": [(6, 0, tax_ids.ids)],
}
@classmethod
def _create_event_order_line_data(
cls, ticket=None, quantity=1.0, discount=0.0, fp=None
):
cls._nextId += 1
product = ticket.product_id
product_lst_price = product.lst_price
product_price = cls.pricelist.get_product_price(product, quantity, False)
price_unit = product_price / product_lst_price * ticket.price
tax_ids = (
fp.map_tax(ticket.product_id.taxes_id) if fp else ticket.product_id.taxes_id
)
price_unit_after_discount = price_unit * (1 - discount / 100.0)
tax_values = (
tax_ids.compute_all(price_unit_after_discount, cls.currency, quantity)
if tax_ids
else {
"total_excluded": price_unit * quantity,
"total_included": price_unit * quantity,
}
)
return {
"discount": discount,
"id": cls._nextId,
"pack_lot_ids": [],
"price_unit": price_unit,
"product_id": ticket.product_id.id,
"price_subtotal": tax_values["total_excluded"],
"price_subtotal_incl": tax_values["total_included"],
"qty": quantity,
"tax_ids": [(6, 0, tax_ids.ids)],
"event_ticket_id": ticket.id,
}
@classmethod
def _create_random_uid(cls):
return "%05d-%03d-%04d" % (randint(1, 99999), randint(1, 999), randint(1, 9999))
@classmethod
def _create_order_data(
cls,
lines=None,
event_lines=None,
partner=False,
is_invoiced=False,
payments=None,
uid=None,
):
"""Create a dictionary mocking data created by the frontend"""
default_fiscal_position = cls.config.default_fiscal_position_id
fiscal_position = (
partner.property_account_position_id if partner else default_fiscal_position
)
uid = uid or cls._create_random_uid()
# Lines
order_lines = []
if lines:
order_lines.extend(
[
cls._create_order_line_data(**line, fp=fiscal_position)
for line in lines
]
)
if event_lines:
order_lines.extend(
[
cls._create_event_order_line_data(**line, fp=fiscal_position)
for line in event_lines
]
)
# Payments
total_amount_incl = sum(line["price_subtotal_incl"] for line in order_lines)
if payments is None:
default_cash_pm = cls.config.payment_method_ids.filtered(
lambda pm: pm.is_cash_count
)[:1]
if not default_cash_pm:
raise Exception(
"There should be a cash payment method set in the pos.config."
)
payments = [
dict(
amount=total_amount_incl,
name=fields.Datetime.now(),
payment_method_id=default_cash_pm.id,
)
]
else:
payments = [
dict(amount=amount, name=fields.Datetime.now(), payment_method_id=pm.id)
for pm, amount in payments
]
# Order data
total_amount_base = sum(line["price_subtotal"] for line in order_lines)
return {
"data": {
"amount_paid": sum(payment["amount"] for payment in payments),
"amount_return": 0,
"amount_tax": total_amount_incl - total_amount_base,
"amount_total": total_amount_incl,
"creation_date": fields.Datetime.to_string(fields.Datetime.now()),
"fiscal_position_id": fiscal_position.id,
"pricelist_id": cls.config.pricelist_id.id,
"lines": [(0, 0, line) for line in order_lines],
"name": "Order %s" % uid,
"partner_id": partner and partner.id,
"pos_session_id": cls.pos_session.id,
"sequence_number": 2,
"statement_ids": [(0, 0, payment) for payment in payments],
"uid": uid,
"user_id": cls.env.user.id,
"to_invoice": is_invoiced,
},
"id": uid,
"to_invoice": is_invoiced,
}
@classmethod
def _create_from_ui(cls, order_list, draft=False):
if not isinstance(order_list, (list, tuple)):
order_list = [order_list]
order_data_list = [cls._create_order_data(**order) for order in order_list]
res = cls.env["pos.order"].create_from_ui(order_data_list, draft=draft)
order_ids = [order["id"] for order in res]
return cls.env["pos.order"].browse(order_ids)
class TestPoSEventHttpCommon(TestPointOfSaleHttpCommon, PosEventMixin):
@classmethod
def setUpClass(cls, **kwargs):
super().setUpClass(**kwargs)
cls.setUpData()
cls.env.user.groups_id += cls.env.ref("event.group_event_user")
cls.main_pos_config.iface_event_sale = True
cls.main_pos_config.open_session_cb(check_coa=False)
| 38.074561
| 8,681
|
2,823
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.tools import float_is_zero
class EventRegistration(models.Model):
_inherit = "event.registration"
pos_order_line_id = fields.Many2one(
comodel_name="pos.order.line",
string="POS Order Line",
ondelete="cascade",
readonly=True,
copy=False,
)
pos_order_id = fields.Many2one(
comodel_name="pos.order",
string="POS Order",
related="pos_order_line_id.order_id",
store=True,
ondelete="cascade",
copy=False,
)
pos_config_id = fields.Many2one(
comodel_name="pos.config",
string="Point of Sale",
related="pos_order_id.config_id",
)
@api.depends("pos_order_line_id.currency_id", "pos_order_line_id.price_subtotal")
def _compute_payment_status(self):
# Override to compute it for registrations created from PoS orders.
# The original method only considers Sales Orders.
res = super()._compute_payment_status()
for rec in self:
if not rec.pos_order_line_id:
continue
if float_is_zero(
rec.pos_order_line_id.price_subtotal,
precision_digits=rec.pos_order_line_id.currency_id.rounding,
):
rec.payment_status = "free"
elif rec.is_paid:
rec.payment_status = "paid"
else:
rec.payment_status = "to_pay"
return res
def _check_auto_confirmation(self):
# OVERRIDE to disable auto confirmation for registrations created from
# PoS orders. We confirm them explicitly when the orders are paid.
if any(rec.pos_order_line_id for rec in self):
return False
return super()._check_auto_confirmation()
@api.model_create_multi
def create(self, vals_list):
# Override to post the origin-link message.
# There's a similar implementation for Sales Orders in module `event_sale`.
records = super().create(vals_list)
for rec in records.filtered("pos_order_id"):
rec.message_post_with_view(
"mail.message_origin_link",
values={"self": rec, "origin": rec.pos_order_id.session_id},
subtype_id=self.env.ref("mail.mt_note").id,
)
return records
def action_view_pos_order(self):
action = self.env["ir.actions.actions"]._for_xml_id(
"point_of_sale.action_pos_pos_form"
)
action["views"] = [(False, "form")]
action["res_id"] = self.pos_order_id.id
return action
| 36.179487
| 2,822
|
1,995
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
iface_event_sale = fields.Boolean(
"Events",
help="Sell events on this point of sale.",
default=True,
)
iface_available_event_stage_ids = fields.Many2many(
"event.stage",
string="Available Event Stages",
help="Limit the available events for this Point of Sale.\n"
"Leave empty to load all stages.",
default=lambda self: self._default_available_event_stage_ids(),
)
iface_available_event_type_ids = fields.Many2many(
"event.type",
string="Available Event Types",
help="Limit the available events for this Point of Sale.\n"
"Leave empty to load all types.",
)
iface_available_event_tag_ids = fields.Many2many(
"event.tag",
string="Available Event Tags",
help="Limit the available events for this Point of Sale.\n"
"Leave empty to load all tags.",
)
iface_event_seats_available_warning = fields.Integer(
"Event Seats Available Warning",
help="Display a warning when available seats is below this quantity.",
default=10,
)
iface_event_load_days_before = fields.Integer(
string="Load past events (days)",
help="Number of days before today, to load past events.\n"
"Set to -1 to load all past events.",
default=0,
)
iface_event_load_days_after = fields.Integer(
string="Load future events (days)",
help="Number of days in the future to load events.\n"
"Set to -1 to load all future events.",
default=-1,
)
@api.model
def _default_available_event_stage_ids(self):
return self.env["event.stage"].search([("pipe_end", "=", False)])
| 36.254545
| 1,994
|
5,237
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class PosOrderLine(models.Model):
_inherit = "pos.order.line"
event_ticket_id = fields.Many2one(
comodel_name="event.event.ticket",
string="Event Ticket",
readonly=True,
)
event_id = fields.Many2one(
comodel_name="event.event",
string="Event",
related="event_ticket_id.event_id",
store=True,
readonly=True,
)
event_registration_ids = fields.One2many(
comodel_name="event.registration",
inverse_name="pos_order_line_id",
string="Event Registrations",
readonly=True,
)
# Make currency_id stored in order to compute
# :meth:`event_event._compute_sale_price_subtotal`
currency_id = fields.Many2one(store=True)
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
records._create_event_registrations()
return records
def _prepare_event_registration_vals(self):
self.ensure_one()
vals = {
"pos_order_line_id": self.id,
"event_ticket_id": self.event_ticket_id.id,
"event_id": self.event_id.id,
"partner_id": self.order_id.partner_id.id,
"name": self.order_id.partner_id.name,
"email": self.order_id.partner_id.email,
"state": "draft",
}
return vals
def _prepare_refund_data(self, refund_order, PosOrderLineLot):
# OVERRIDE to add the event the event.ticket info to refunds
res = super()._prepare_refund_data(refund_order, PosOrderLineLot)
if self.event_ticket_id:
res["event_ticket_id"] = self.event_ticket_id.id
return res
def _create_event_registrations(self):
"""Create the missing event.registrations for this order line"""
registrations = self.env["event.registration"]
for line in self:
if not line.event_ticket_id: # pragma: no cover
continue
qty_existing = len(
line.event_registration_ids.filtered(lambda r: r.state != "cancel")
)
qty_to_create = max(0, int(line.qty) - qty_existing)
if not qty_to_create: # pragma: no cover
continue
vals = line._prepare_event_registration_vals()
vals_list = [vals.copy() for __ in range(0, qty_to_create)]
registrations += self.env["event.registration"].create(vals_list)
return registrations
def _cancel_refunded_event_registrations(self):
"""Cancel refunded event registrations"""
for line in self:
if not line.event_ticket_id or not line.refunded_orderline_id:
continue
to_cancel_qty = max(0, -int(line.qty))
open_registrations = (
line.refunded_orderline_id.event_registration_ids.filtered(
lambda reg: reg.state == "open"
)
)
to_cancel_registrations = open_registrations[-to_cancel_qty:]
to_cancel_registrations.action_cancel()
for registration in to_cancel_registrations:
registration.message_post(
body=_("Refunded on %s", line.order_id.session_id.name)
)
def _find_event_registrations_to_negate(self):
"""Find the registrations that could be negated by this order line"""
self.ensure_one()
return self.order_id.event_registration_ids.filtered(
lambda r: (
r.event_ticket_id
and r.event_ticket_id == self.event_ticket_id
and r.state == "draft"
)
)
def _cancel_negated_event_registrations(self):
"""Cancel negated event registrations
This happens when the order contains a negative event line
that is not a refund of another order's line.
For example:
* Line 1: 10 tickets for event A
* Line 2: -5 tickets for event A
In this case, we need to cancel 5 registrations of the first
order line, as they are negated by the second line.
These registrations are never confirmed. They go from `draft`
to `cancel` directly.
"""
to_process = self.filtered(
lambda line: (
line.event_ticket_id
and int(line.qty) < 0
and not line.refunded_orderline_id
)
)
for line in to_process:
qty_to_cancel = max(0, -int(line.qty))
registrations = line._find_event_registrations_to_negate()
registrations = registrations[-qty_to_cancel:]
registrations.action_cancel()
def _export_for_ui(self, orderline):
# OVERRIDE to add event_ticket_id
res = super()._export_for_ui(orderline)
res["event_ticket_id"] = orderline.event_ticket_id.id
res["event_registration_ids"] = orderline.event_registration_ids.ids
return res
| 37.4
| 5,236
|
3,666
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class Event(models.Model):
_inherit = "event.event"
pos_order_line_ids = fields.One2many(
comodel_name="pos.order.line",
inverse_name="event_id",
groups="point_of_sale.group_pos_user",
string="All the PoS Order Lines pointing to this event",
readonly=True,
)
pos_price_subtotal = fields.Monetary(
string="POS Sales (Tax Excluded)",
compute="_compute_pos_price_subtotal",
groups="point_of_sale.group_pos_user",
)
@api.depends(
"currency_id",
"pos_order_line_ids.price_subtotal",
"pos_order_line_ids.currency_id",
"pos_order_line_ids.company_id",
"pos_order_line_ids.order_id.date_order",
)
def _compute_pos_price_subtotal(self):
"""Compute POS Sales Amount
This method is similar to upstream's :meth:`~_compute_sale_price_subtotal`
only here we consider sales coming from pos.order.line(s).
In theory we could merge them both together to compute a total Sales amount,
coming from both sale.order and pos.order. However, in order to provide two
separate smart buttons with proper information, one for each model, it's better
to split them.
"""
date_now = fields.Datetime.now()
sale_price_by_event = {}
if self.ids:
event_subtotals = self.env["pos.order.line"].read_group(
[
("event_id", "in", self.ids),
("order_id.state", "!=", "cancel"),
("price_subtotal", "!=", 0),
],
["event_id", "currency_id", "price_subtotal:sum"],
["event_id", "currency_id"],
lazy=False,
)
currency_ids = [
event_subtotal["currency_id"][0] for event_subtotal in event_subtotals
]
company_by_event = {
event._origin.id or event.id: event.company_id for event in self
}
currency_by_event = {
event._origin.id or event.id: event.currency_id for event in self
}
currency_by_id = {
currency.id: currency
for currency in self.env["res.currency"].browse(currency_ids)
}
for event_subtotal in event_subtotals:
price_subtotal = event_subtotal["price_subtotal"]
event_id = event_subtotal["event_id"][0]
currency_id = event_subtotal["currency_id"][0]
sale_price = currency_by_event[event_id]._convert(
price_subtotal,
currency_by_id[currency_id],
company_by_event[event_id],
date_now,
)
if event_id in sale_price_by_event:
sale_price_by_event[event_id] += sale_price
else:
sale_price_by_event[event_id] = sale_price
for rec in self:
rec.pos_price_subtotal = sale_price_by_event.get(
rec._origin.id or rec.id, 0
)
def action_view_pos_orders(self):
action = self.env["ir.actions.actions"]._for_xml_id(
"point_of_sale.action_pos_pos_form"
)
action["domain"] = [
("state", "!=", "cancel"),
("lines.event_id", "in", self.ids),
]
return action
| 38.177083
| 3,665
|
1,975
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PosOrder(models.Model):
_inherit = "pos.order"
event_registrations_count = fields.Integer(
string="Event Registration Count",
compute="_compute_event_registrations_count",
)
event_registration_ids = fields.One2many(
"event.registration",
"pos_order_id",
string="Event Registrations",
readonly=True,
)
def _compute_event_registrations_count(self):
count = self.env["event.registration"].read_group(
[("pos_order_id", "in", self.ids)],
fields=["pos_order_id"],
groupby=["pos_order_id"],
)
count_map = {x["pos_order_id"][0]: x["pos_order_id_count"] for x in count}
for rec in self:
rec.event_registrations_count = count_map.get(rec.id, 0)
def action_open_event_registrations(self):
action = self.env["ir.actions.actions"]._for_xml_id(
"event.event_registration_action_tree"
)
action["domain"] = [("pos_order_id", "in", self.ids)]
return action
def action_pos_order_paid(self):
res = super().action_pos_order_paid()
self.lines._cancel_negated_event_registrations()
self.lines._cancel_refunded_event_registrations()
to_confirm = self.event_registration_ids.filtered(lambda r: r.state == "draft")
to_confirm.action_confirm()
to_confirm._action_set_paid()
return res
def action_pos_order_cancel(self):
res = super().action_pos_order_cancel()
to_cancel = self.event_registration_ids.filtered(lambda r: r.state != "done")
to_cancel.action_cancel()
return res
def unlink(self):
self.event_registration_ids.unlink()
return super().unlink()
| 35.25
| 1,974
|
590
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class EventTypeTicket(models.Model):
_inherit = "event.type.ticket"
available_in_pos = fields.Boolean(
related="product_id.available_in_pos",
help="This is configured on the related Product.\n\n"
"Please note that for the ticket to be available in the Point of Sale, "
"the ticket's product has to be available there, too.",
)
| 36.8125
| 589
|
1,133
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Camptocamp (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PosOrderReport(models.Model):
_inherit = "report.pos.order"
event_ticket_id = fields.Many2one(
comodel_name="event.event.ticket",
string="Event Ticket",
readonly=True,
)
event_id = fields.Many2one(
comodel_name="event.event",
string="Event",
readonly=True,
)
def _select(self):
res = super()._select()
return f"""
{res},
l.event_ticket_id AS event_ticket_id,
event_event_ticket.event_id AS event_id
"""
def _from(self):
res = super()._from()
return f"""
{res}
LEFT JOIN event_event_ticket ON (l.event_ticket_id = event_event_ticket.id)
"""
def _group_by(self):
res = super()._group_by()
return f"""
{res},
l.event_ticket_id,
event_event_ticket.event_id
"""
| 26.325581
| 1,132
|
740
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "POS Lot Barcode",
"summary": "Scan barcode to enter lot/serial numbers",
"version": "15.0.1.0.0",
"development_status": "Alpha",
"category": "Sales/Point of Sale",
"website": "https://github.com/OCA/pos",
"author": "Camptocamp, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"point_of_sale",
],
"assets": {
"point_of_sale.assets": [
"pos_lot_barcode/static/src/js/**/*.js",
],
"web.assets_qweb": [
"pos_lot_barcode/static/src/xml/**/*.xml",
],
},
}
| 29.6
| 740
|
734
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Lorenzo Battistini @ TAKOBI
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Point of sale - Search products by supplier",
"summary": "Search products by supplier data",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "Point Of Sale",
"website": "https://github.com/OCA/pos",
"author": "TAKOBI, Odoo Community Association (OCA)",
"maintainers": ["eLBati"],
"license": "LGPL-3",
"application": False,
"installable": True,
"auto_install": False,
"depends": [
"point_of_sale",
],
"assets": {
"point_of_sale.assets": [
"/pos_supplierinfo_search/static/src/js/db.js",
],
},
}
| 30.583333
| 734
|
789
|
py
|
PYTHON
|
15.0
|
import json
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
supplier_data_json = fields.Char(
"Supplier data dict",
help="Technical field: Used in POS frontend to search products by supplierinfo",
compute="_compute_supplier_data_json",
)
def _compute_supplier_data_json(self):
for rec in self:
rec.supplier_data_json = json.dumps(
[
{
"supplier_name": s.name.display_name,
"supplier_product_code": s.product_code or "",
"supplier_product_name": s.product_name or "",
}
for s in rec.seller_ids
]
)
| 30.346154
| 789
|
588
|
py
|
PYTHON
|
15.0
|
{
"name": "PoS Product Display Default Code",
"summary": "pos: display product default code before product name",
"version": "15.0.1.0.0",
"category": "Point of Sale",
"website": "https://github.com/OCA/pos",
"author": "Odoo Community Association (OCA), Akretion",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"point_of_sale",
],
"assets": {
"point_of_sale.assets": [
"/pos_product_display_default_code/static/src/js/models.js",
]
},
"demo": [],
"qweb": [],
}
| 28
| 588
|
676
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2022 - Today: camptocamp (https://www.camptocamp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "PoS Hide Cost and Margin",
"summary": "Hide Cost and Margin on PoS",
"version": "15.0.1.0.1",
"category": "Point Of Sale",
"author": "CampToCamp, Odoo Community Association (OCA)",
"maintainers": [],
"website": "https://github.com/OCA/pos",
"license": "AGPL-3",
"depends": [
"point_of_sale",
],
"data": [],
"assets": {
"web.assets_qweb": [
"pos_hide_cost_price_and_margin/static/src/xml/pos_margin.xml",
],
},
"installable": True,
}
| 29.391304
| 676
|
750
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Akretion - Florian Mounier
{
"name": "POS Receipt Hide Price",
"summary": "Add button to remove price from receipt.",
"author": "Akretion, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"category": "Point of Sale",
"version": "15.0.1.0.0",
"license": "LGPL-3",
"depends": ["point_of_sale"],
"assets": {
"point_of_sale.assets": [
"pos_receipt_hide_price/static/src/js/ReceiptScreen.js",
"pos_receipt_hide_price/static/src/js/ReprintReceiptScreen.js",
"pos_receipt_hide_price/static/src/js/OrderReceipt.js",
],
"web.assets_qweb": [
"pos_receipt_hide_price/static/src/xml/**/*",
],
},
}
| 35.714286
| 750
|
773
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Lorenzo Battistini @ TAKOBI
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Point of Sale - Restrict users",
"summary": "Restrict some users to see and use only certain points of sale",
"version": "15.0.1.0.0",
"development_status": "Beta",
"category": "Point of Sale",
"website": "https://github.com/OCA/pos",
"author": "TAKOBI, Odoo Community Association (OCA)",
"maintainers": ["eLBati"],
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": [
"point_of_sale",
],
"data": [
"security/pos_security.xml",
"security/ir.model.access.csv",
"views/pos_config_views.xml",
"views/point_of_sale_views.xml",
],
}
| 32.208333
| 773
|
3,258
|
py
|
PYTHON
|
15.0
|
from odoo.tests.common import TransactionCase
class TestUserRestriction(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(
context=dict(
cls.env.context,
tracking_disable=True,
no_reset_password=True,
)
)
cls.pos_user = cls.env["res.users"].create(
{
"login": "pos_user",
"name": "pos_user",
"groups_id": [(6, 0, [cls.env.ref("point_of_sale.group_pos_user").id])],
}
)
cls.pos_user_assigned_pos = cls.env["res.users"].create(
{
"login": "pos_user_assigned_pos",
"name": "pos_user_assigned_pos",
"groups_id": [
(
6,
0,
[
cls.env.ref(
"pos_user_restriction.group_assigned_points_of_sale_user"
).id
],
)
],
}
)
cls.pos_config_main = cls.env.ref("point_of_sale.pos_config_main")
cls.pos_config_model = cls.env["pos.config"]
def test_access_pos(self):
# assigned_user_ids is not set: both users can read
pos_configs = self.pos_config_model.with_user(self.pos_user.id).search(
[
(
"id",
"=",
self.pos_config_main.id,
) # for tests to pass if pos_restaurant is installed
]
)
self.assertTrue(pos_configs)
pos_configs = self.pos_config_model.with_user(
self.pos_user_assigned_pos.id
).search([("id", "=", self.pos_config_main.id)])
self.assertTrue(pos_configs)
self.pos_config_main.assigned_user_ids = [
(6, 0, [self.pos_user_assigned_pos.id])
]
# assigned_user_ids is set with pos_user_assigned_pos: both users can read
pos_configs = self.pos_config_model.with_user(self.pos_user.id).search(
[("id", "=", self.pos_config_main.id)]
)
self.assertTrue(pos_configs)
pos_configs = self.pos_config_model.with_user(
self.pos_user_assigned_pos.id
).search([("id", "=", self.pos_config_main.id)])
self.assertTrue(pos_configs)
self.pos_config_main.assigned_user_ids = [(6, 0, [self.pos_user.id])]
# assigned_user_ids is set with pos_user: only pos_user can read
pos_configs = self.pos_config_model.with_user(self.pos_user.id).search(
[("id", "=", self.pos_config_main.id)]
)
self.assertTrue(pos_configs)
pos_configs = self.pos_config_model.with_user(
self.pos_user_assigned_pos.id
).search([("id", "=", self.pos_config_main.id)])
self.assertFalse(pos_configs)
self.assigned_group = self.env.ref(
"pos_user_restriction.group_assigned_points_of_sale_user"
)
self.assertEqual(self.assigned_group, self.pos_config_main.group_pos_user_id)
self.assertFalse(pos_configs)
| 37.448276
| 3,258
|
645
|
py
|
PYTHON
|
15.0
|
from odoo import models
class PosSession(models.Model):
_inherit = "pos.session"
def set_cashbox_pos(self, cashbox_value, notes):
if self.env.user.has_group(
"pos_user_restriction.group_assigned_points_of_sale_user"
):
self = self.with_context(bypass_pos_user=True)
return super().set_cashbox_pos(cashbox_value, notes)
def get_closing_control_data(self):
if self.env.user.has_group(
"pos_user_restriction.group_assigned_points_of_sale_user"
):
self = self.with_context(bypass_pos_user=True)
return super().get_closing_control_data()
| 33.947368
| 645
|
979
|
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
assigned_user_ids = fields.Many2many(
"res.users",
string="Assigned users",
help="Restrict some users to only access their assigned points of sale."
"In order to apply the restriction, the user needs the "
"'User: Assigned POS Only' group",
)
group_pos_user_id = fields.Many2one(
"res.groups",
compute="_compute_group_pos_user_id",
string="Point of Sale User Group",
help="This field is there to pass"
"the id of the pos user group to the point of sale client.",
store=True,
)
@api.depends("assigned_user_ids")
def _compute_group_pos_user_id(self):
for config in self:
config.group_pos_user_id = self.env.ref(
"pos_user_restriction.group_assigned_points_of_sale_user",
"point_of_sale.group_pos_user",
)
| 33.758621
| 979
|
668
|
py
|
PYTHON
|
15.0
|
from odoo import api, models
from odoo.tools import ormcache
class ResUsers(models.Model):
_inherit = "res.users"
@api.model
def has_group(self, group_ext_id):
if group_ext_id == "point_of_sale.group_pos_user" and self.env.context.get(
"bypass_pos_user"
):
return True
else:
res = super().has_group(group_ext_id)
return res
# HACK: To clear cache called from res.users write method
@api.model
@ormcache("self._uid", "group_ext_id")
def _has_group(self, group_ext_id):
return super()._has_group(group_ext_id)
has_group.clear_cache = _has_group.clear_cache
| 27.833333
| 668
|
748
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "POS cash in-out reason",
"summary": """""",
"author": "ACSONE SA/NV," "GRAP," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/pos",
"category": "Point Of sale",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["point_of_sale"],
"data": [
"security/ir_rule.xml",
"security/res_groups.xml",
"security/ir.model.access.csv",
"views/view_pos_move_reason.xml",
"views/view_pos_session.xml",
"wizard/wizard_pos_move_reason.xml",
],
"demo": ["demo/account_account.xml", "demo/pos_move_reason.xml"],
}
| 35.619048
| 748
|
3,759
|
py
|
PYTHON
|
15.0
|
# © 2015 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import UserError
from odoo.tests.common import Form, TransactionCase
class TestPosCashMoveReason(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.PosSession = cls.env["pos.session"]
cls.WizardReason = cls.env["wizard.pos.move.reason"]
cls.AccountMoveLine = cls.env["account.move.line"]
cls.config = cls.env.ref("point_of_sale.pos_config_main").copy()
cls.cash_journal = cls.env["account.journal"].search(
[
("type", "=", "cash"),
("company_id", "=", cls.env.ref("base.main_company").id),
]
)[0]
cls.deposit_reason = cls.env.ref("pos_cash_move_reason.bank_out_reason")
def test_onchange_expense_reason(self):
move_reason_form = Form(self.deposit_reason)
move_reason_form.is_expense_reason = True
move_reason_form.save()
self.assertTrue(self.deposit_reason.expense_account_id)
def test_take_money(self):
# Open New Session
self.config.open_session_cb()
session = self.PosSession.search(
[("state", "=", "opening_control"), ("config_id", "=", self.config.id)]
)
# Get Cash Statement
statement = session.statement_ids.filtered(
lambda x: x.journal_id == self.cash_journal
)
# Take money to put in Bank
wizard = self.WizardReason.with_context(
active_id=session.id, default_move_type="expense"
).create(
{
"move_reason_id": self.deposit_reason.id,
"journal_id": self.cash_journal.id,
"statement_id": statement.id,
"amount": 500,
"name": "Test Bank Deposit",
}
)
wizard.onchange_reason()
wizard.apply()
session.action_pos_session_closing_control()
# I get all move lines of this statement
move_line = self.env["account.move.line"].search(
[
("account_id", "=", self.deposit_reason.expense_account_id.id),
("debit", "=", 500.0),
("id", "in", statement.move_line_ids.ids),
]
)
# I check the created move line from the cash in
self.assertEqual(len(move_line), 1)
def test_take_invalid_amount(self):
# Open New Session
self.config.open_session_cb()
#
session = self.PosSession.search(
[("state", "=", "opening_control"), ("config_id", "=", self.config.id)]
)
# Get Cash Statement
statement = session.statement_ids.filtered(
lambda x: x.journal_id == self.cash_journal
)
# Enter Invalid money
with self.assertRaises(UserError):
self.WizardReason.with_context(
active_id=session.id, default_move_type="expense"
).create(
{
"move_reason_id": self.deposit_reason.id,
"journal_id": self.cash_journal.id,
"statement_id": statement.id,
"amount": -100,
"name": "Test Deposit",
}
)
def test_button_put_money(self):
self.config.open_session_cb()
session = self.PosSession.search(
[("state", "=", "opened"), ("config_id", "=", self.config.id)]
)
wiz = session.button_move_income()
self.assertEqual(wiz["context"]["default_move_type"], "income")
| 36.134615
| 3,758
|
3,601
|
py
|
PYTHON
|
15.0
|
# © 2015 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class WizardPosMoveReason(models.TransientModel):
_name = "wizard.pos.move.reason"
_description = "PoS Move Reasons Wizard"
def _default_move_type(self):
return self.env.context.get("default_move_type", "expense")
def _default_session_id(self):
return self.env.context.get("active_id", False)
_MOVE_TYPE_SELECTION = [
("income", "Put Money In"),
("expense", "Take Money Out"),
]
move_type = fields.Selection(
selection=_MOVE_TYPE_SELECTION, default=_default_move_type
)
move_reason_id = fields.Many2one(
comodel_name="pos.move.reason", string="Move Reason", required=True
)
journal_id = fields.Many2one(
comodel_name="account.journal",
string="Journal",
domain="[('id', 'in', journal_ids)]",
required=True,
)
session_id = fields.Many2one(
comodel_name="pos.session",
string="Current Session",
default=_default_session_id,
required=True,
readonly=True,
)
statement_id = fields.Many2one(
comodel_name="account.bank.statement",
string="Bank Statement",
compute="_compute_statement_id",
)
journal_ids = fields.Many2many(
comodel_name="account.journal", related="move_reason_id.journal_ids"
)
name = fields.Char(string="Reason", required=True)
amount = fields.Float(required=True)
@api.onchange("move_type")
def onchange_move_type(self):
if self.move_type == "income":
return {"domain": {"move_reason_id": [("is_income_reason", "=", True)]}}
else:
return {"domain": {"move_reason_id": [("is_expense_reason", "=", True)]}}
@api.onchange("move_reason_id")
def onchange_reason(self):
if len(self.journal_ids) == 1:
self.journal_id = fields.first(self.journal_ids).id
self.name = self.move_reason_id.name
@api.constrains("amount")
def _check_amount(self):
if any(w.amount <= 0 for w in self):
raise UserError(_("Invalid Amount"))
@api.depends("journal_id", "session_id")
def _compute_statement_id(self):
for wizard in self:
statement = self.env["account.bank.statement"].browse()
if wizard.session_id and wizard.journal_id:
statements = wizard.session_id.statement_ids.filtered(
lambda x, w=wizard: x.journal_id == w.journal_id
)
statement = fields.first(statements)
wizard.statement_id = statement
def apply(self):
self.ensure_one()
AccountBankStatementLine = self.env["account.bank.statement.line"]
AccountBankStatementLine.create(self._prepare_statement_line())
def _prepare_statement_line(self):
self.ensure_one()
if self.move_type == "income":
amount = self.amount
account_id = self.move_reason_id.income_account_id.id
else:
amount = -self.amount
account_id = self.move_reason_id.expense_account_id.id
return {
"date": fields.Date.context_today(self),
"statement_id": self.statement_id.id,
"journal_id": self.journal_id.id,
"amount": amount,
"payment_ref": f"{self.session_id.name} - {self.name}",
"counterpart_account_id": account_id,
}
| 33.027523
| 3,600
|
1,598
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: GTRAP (<http://www.grap.coop/>)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PosSession(models.Model):
_inherit = "pos.session"
display_move_reason_income = fields.Boolean(compute="_compute_display_move_reason")
display_move_reason_expense = fields.Boolean(compute="_compute_display_move_reason")
def _compute_display_move_reason(self):
MoveReason = self.env["pos.move.reason"]
all_reasons = MoveReason.search(
[("company_id", "in", self.mapped("config_id.company_id").ids)]
)
for session in self:
# Get all reasons
reasons = all_reasons.filtered_domain(
[("company_id", "=", session.config_id.company_id.id)]
)
session.display_move_reason_income = len(
reasons.filtered(lambda x: x.is_income_reason)
)
session.display_move_reason_expense = len(
reasons.filtered(lambda x: x.is_expense_reason)
)
def button_move_income(self):
return self._button_move_reason("income")
def button_move_expense(self):
return self._button_move_reason("expense")
def _button_move_reason(self, move_type):
action = (
self.env.ref("pos_cash_move_reason.action_wizard_pos_move_reason")
.sudo()
.read()[0]
)
action["context"] = {"default_move_type": move_type}
return action
| 35.511111
| 1,598
|
1,698
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: GTRAP (<http://www.grap.coop/>)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class PosMoveReason(models.Model):
_name = "pos.move.reason"
_description = "PoS - Move In / Out Reason"
@api.model
def _default_journal_ids(self):
AccountJournal = self.env["account.journal"]
journals = AccountJournal.search([("type", "=", "cash")])
return journals.ids
@api.model
def _default_company_id(self):
return self.env.user.company_id
name = fields.Char(required=True)
active = fields.Boolean(default=True)
journal_ids = fields.Many2many(
comodel_name="account.journal",
string="Accounting Journals",
default=_default_journal_ids,
)
is_income_reason = fields.Boolean(default=True)
is_expense_reason = fields.Boolean(default=True)
income_account_id = fields.Many2one(
string="Income Account", comodel_name="account.account"
)
expense_account_id = fields.Many2one(
string="Expense Account", comodel_name="account.account"
)
company_id = fields.Many2one(
string="Company",
comodel_name="res.company",
default=_default_company_id,
required=True,
)
@api.onchange("is_income_reason")
def _onchange_is_income_reason(self):
if not self.is_income_reason:
self.income_account_id = False
@api.onchange("is_expense_reason")
def _onchange_is_expense_reason(self):
if not self.is_expense_reason:
self.expense_account_id = False
| 28.779661
| 1,698
|
777
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "POS Sale and POS Event Sale Session",
"summary": "Glue module between pos_sale and pos_event_sale_session",
"version": "15.0.1.0.0",
"author": "Moka Tourisme, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/pos",
"license": "AGPL-3",
"category": "Marketing",
"depends": ["pos_sale_pos_event_sale", "pos_event_sale_session"],
"assets": {
"point_of_sale.assets": [
"pos_sale_pos_event_sale_session/static/src/js/**/*.js",
],
},
"auto_install": True,
}
| 36.952381
| 776
|
685
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
def read_converted(self):
# OVERRIDE to read also the event fields
res = super().read_converted()
product_lines = self.filtered(lambda rec: rec.product_type)
product_items = [item for item in res if item.get("product_id")]
for line, item in zip(product_lines, product_items):
item.update(line._read_format(["event_session_id"])[0])
return res
| 38
| 684
|
834
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "POS Sale and POS Event Sale",
"summary": "Glue module between pos_sale and pos_event_sale",
"version": "15.0.1.0.0",
"author": "Moka Tourisme, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/pos",
"license": "AGPL-3",
"category": "Marketing",
"depends": ["pos_sale", "pos_event_sale"],
"assets": {
"point_of_sale.assets": [
"pos_sale_pos_event_sale/static/src/js/**/*.js",
],
"web.assets_tests": [
"pos_sale_pos_event_sale/static/tests/tours/**/*",
],
},
"auto_install": True,
}
| 34.708333
| 833
|
5,443
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import datetime
from odoo import fields
from odoo.tests import RecordCapturer, tagged
from odoo.addons.point_of_sale.tests.test_frontend import TestPointOfSaleHttpCommon
@tagged("post_install", "-at_install")
class TestUi(TestPointOfSaleHttpCommon):
@classmethod
def setUpClass(cls, **kwargs):
super().setUpClass(**kwargs)
cls.env.user.groups_id += cls.env.ref("event.group_event_user")
cls.main_pos_config.iface_event_sale = True
# Configure product
cls.product_event = cls.env.ref("event_sale.product_product_event")
cls.product_event.active = True
cls.product_event.available_in_pos = True
# Create event
cls.event = cls.env["event.event"].create(
{
"name": "Les Misérables",
"event_type_id": cls.env.ref("event.event_type_0").id,
"date_begin": datetime.combine(
fields.Date.today(), datetime.min.time()
),
"date_end": datetime.combine(fields.Date.today(), datetime.max.time()),
"stage_id": cls.env.ref("event.event_stage_booked").id,
"seats_limited": True,
"seats_max": 10,
}
)
cls.ticket_kids = cls.env["event.event.ticket"].create(
{
"name": "Kids",
"product_id": cls.product_event.id,
"event_id": cls.event.id,
"price": 5.0,
"seats_limited": True,
"seats_max": 5,
}
)
cls.ticket_regular = cls.env["event.event.ticket"].create(
{
"name": "Standard",
"product_id": cls.product_event.id,
"event_id": cls.event.id,
"price": 15.0,
}
)
# Create a sale.order
cls.partner = cls.env.ref("base.res_partner_1")
cls.order = cls.env["sale.order"].create(
{
"name": "TEST01",
"partner_id": cls.partner.id,
"order_line": [
fields.Command.create(
{
"name": cls.ticket_regular.display_name,
"product_id": cls.ticket_regular.product_id.id,
"event_id": cls.event.id,
"event_ticket_id": cls.ticket_regular.id,
"price_unit": cls.ticket_regular.price,
"product_uom_qty": 2,
}
),
fields.Command.create(
{
"name": cls.ticket_kids.display_name,
"product_id": cls.ticket_kids.product_id.id,
"event_id": cls.event.id,
"event_ticket_id": cls.ticket_kids.id,
"price_unit": cls.ticket_kids.price,
"product_uom_qty": 1,
}
),
],
}
)
def _test_pos_sale_import_tour(self):
self.main_pos_config.open_session_cb(check_coa=False)
with RecordCapturer(self.env["pos.order"], []) as rc:
self.start_tour(
f"/pos/ui?config_id={self.main_pos_config.id}",
"PosEventSaleImportTour",
login="accountman",
)
pos_orders = rc.records
origin_sale_orders = pos_orders.lines.sale_order_origin_id
self.assertEqual(len(pos_orders), 2, "2 orders created")
self.assertEqual(origin_sale_orders, self.order, "linked to so")
registrations = pos_orders.event_registration_ids
self.assertEqual(len(registrations), 3, "3 registrations")
for registration in registrations:
self.assertEqual(registration.event_id, self.event)
# Check that the registration is linked to both pos and sale orders
self.assertTrue(registration.sale_order_line_id)
self.assertTrue(registration.pos_order_line_id)
# Check that both pos and sale lines are linked
self.assertEqual(
registration.pos_order_line_id.sale_order_line_id,
registration.sale_order_line_id,
)
# Check that the event is the one in the SO
self.assertEqual(
registration.event_id,
registration.sale_order_line_id.event_id,
)
# Check that the event ticket is the one in the SO
self.assertEqual(
registration.event_ticket_id,
registration.sale_order_line_id.event_ticket_id,
)
# Check that the registration is confirmed
self.assertEqual(registration.state, "open")
def test_pos_sale_import_draft_tour(self):
"""Test flow with a draft sale order (Quotation)"""
self._test_pos_sale_import_tour()
def test_pos_sale_import_confirmed_tour(self):
"""Test flow with a confirmed sale order"""
self.order.action_confirm()
self._test_pos_sale_import_tour()
| 41.534351
| 5,441
|
696
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
def read_converted(self):
# OVERRIDE to read also the event fields
res = super().read_converted()
product_lines = self.filtered(lambda rec: rec.product_type)
product_items = [item for item in res if item.get("product_id")]
for line, item in zip(product_lines, product_items):
item.update(line._read_format(["event_id", "event_ticket_id"])[0])
return res
| 38.611111
| 695
|
2,455
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Iván Todorovich <ivan.todorovich@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from collections import defaultdict
from odoo import models
class PosOrderLine(models.Model):
_inherit = "pos.order.line"
def _prepare_event_registration_vals(self):
# OVERRIDE to also link the created registrations to the sale_order_line.
res = super()._prepare_event_registration_vals()
if self.sale_order_line_id:
res["sale_order_line_id"] = self.sale_order_line_id.id
return res
def _create_event_registrations(self):
# OVERRIDE to attempt to link existing registrations from sale_order_lines
# before creating new ones.
sale_event_lines = self.filtered(
lambda l: (l.sale_order_line_id and l.product_id.detailed_type == "event")
)
if sale_event_lines:
# Get event.registrations created from Sales and group by sale_order_line
# Only those that aren't cancelled and already linked to pos lines.
sale_lines = sale_event_lines.sale_order_line_id
registrations = self.env["event.registration"].search(
[
("sale_order_line_id", "in", sale_lines.ids),
("pos_order_line_id", "=", False),
("state", "!=", "cancel"),
]
)
registrations_by_sale_line = defaultdict(
lambda: self.env["event.registration"]
)
for registration in registrations:
sale_line = registration.sale_order_line_id
registrations_by_sale_line[sale_line] += registration
# Attempt to link N (qty) registrations from sale lines to the pos lines
# It's possible there aren't enough registrations, but that's ok.
for pos_line in sale_event_lines:
sale_line = pos_line.sale_order_line_id
sale_registrations = registrations_by_sale_line[sale_line].filtered(
lambda reg: not reg.pos_order_line_id
)
qty = int(min(len(sale_registrations), pos_line.qty))
if qty:
sale_registrations[:qty].pos_order_line_id = pos_line
# Create the missing registrations
return super()._create_event_registrations()
| 45.444444
| 2,454
|
552
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{
"name": "Account Invoice Payment Block",
"version": "15.0.1.0.0",
"summary": "Module to block payment of invoices",
"author": "Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Accounting & Finance",
"depends": ["account"],
"data": [
"views/account_move.xml",
],
"application": False,
"installable": True,
}
| 30.666667
| 552
|
843
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo.exceptions import UserError
from odoo.tests import TransactionCase
class TestAccountInvoice(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# create an invoice with its payment unblocked
cls.account_move = cls.env["account.move"].create({"payment_blocked": False})
def test_payment_blocked(self):
# Blocked boolean set to true rises a ValidationError
self.assertFalse(self.account_move.payment_blocked)
self.account_move.payment_blocked = True
with self.assertRaises(UserError):
self.account_move.action_register_payment()
self.account_move.payment_blocked = False
self.account_move.action_register_payment()
| 38.318182
| 843
|
720
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import _, fields, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
payment_blocked = fields.Boolean(
help="if true, the payment of the invoice is blocked.",
)
def action_register_payment(self):
error_msg = ""
for move in self:
if move.payment_blocked:
error_msg += (
_("The payment on invoice {} is blocked.").format(move.name) + "\n"
)
if error_msg:
raise UserError(error_msg)
return super().action_register_payment()
| 30
| 720
|
619
|
py
|
PYTHON
|
15.0
|
# Copyright 2011-2016 Agile Business Group
# Copyright 2017 Alex Comba - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Force Invoice Number",
"version": "15.0.1.0.0",
"category": "Accounting & Finance",
"summary": "Allows to force invoice numbering on specific invoices",
"author": "Agile Business Group, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"depends": ["account"],
"data": ["security/security.xml", "views/account_move_view.xml"],
"installable": True,
}
| 41.266667
| 619
|
2,032
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Davide Corio - davidecorio.com
# Copyright 2017 Alex Comba - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged("post_install", "-at_install")
class TestAccountForceNumber(AccountTestInvoicingCommon):
def create_invoice(self, move_name=None):
partner_id = self.env.ref("base.res_partner_12").id
invoice_vals = {
"move_type": "out_invoice",
"partner_id": partner_id,
"invoice_line_ids": [
(
0,
0,
{
"name": "Test product",
"quantity": 1,
"price_unit": 450,
"tax_ids": [(6, 0, [])],
},
)
],
}
invoice = (
self.env["account.move"]
.with_context(default_move_type="out_invoice")
.create(invoice_vals)
)
if move_name:
invoice.write({"move_name": "0001"})
return invoice
def test_force_number(self):
# in order to test the correct assignment of the internal_number
# I create a customer invoice.
# I set the force number
invoice = self.create_invoice(move_name="0001")
# I validate the invoice
invoice.action_post()
# I check that the invoice number is the one we expect
self.assertEqual(invoice.name, invoice.move_name, msg="Wrong number")
# I check move_name is not modified when validating the invoice.
self.assertEqual(invoice.name, "0001")
# Delete invoice while move_name is True
with self.assertRaises(UserError):
invoice.unlink()
# Delete invoice while move_name is False
invoice_2 = self.create_invoice()
invoice_2.unlink()
| 35.649123
| 2,032
|
1,184
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (https://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import _, fields, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
move_name = fields.Char(
string="Force Number",
readonly=False,
default=False,
copy=False,
help="""Force invoice number. Use this field if
you don't want to use the default numbering.""",
)
def unlink(self):
for move in self:
if move.move_name:
raise UserError(
_(
"""You cannot delete an invoice after it has been validated"""
'''(and received a number). You can set it back to "Draft"'''
"""state and modify its content, then re-confirm it."""
)
)
return super(AccountMove, self).unlink()
def action_post(self):
for move in self:
if move.move_name:
move.write({"name": move.move_name})
return super(AccountMove, self).action_post()
| 32.888889
| 1,184
|
569
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Display invoices date due when using payment terms",
"version": "15.0.1.1.0",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Accounting",
"depends": ["account"],
"data": ["views/account_move.xml"],
}
| 37.866667
| 568
|
649
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 - Camptocamp SA - Author Vincent Renaville
# Copyright 2016 - Tecnativa - Angel Moya <odoo@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Tax required in invoice",
"version": "15.0.1.0.1",
"author": "Camptocamp,Tecnativa,Punt Sistemes, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"category": "Localization / Accounting",
"license": "AGPL-3",
"summary": """This module adds functional a check on invoice to force user
to set tax on invoice line.""",
"depends": ["account"],
"installable": True,
}
| 43.266667
| 649
|
3,224
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 - Tecnativa - Angel Moya <odoo@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import exceptions
from odoo.tests import tagged
from odoo.addons.account.tests.common import TestAccountReconciliationCommon
@tagged("post_install", "-at_install")
class TestAccountInvoiceTaxRequired(TestAccountReconciliationCommon):
def setUp(self):
super(TestAccountInvoiceTaxRequired, self).setUp()
self.account_invoice = self.env["account.move"]
self.account_journal = self.env["account.journal"]
self.journal = self.account_journal.create(
{"code": "test", "name": "test", "type": "sale"}
)
self.partner = self.env.ref("base.res_partner_3")
account_user_type = self.env.ref("account.data_account_type_receivable")
self.account_account = self.env["account.account"]
self.account_rec1_id = self.account_account.create(
dict(
code="cust_acc",
name="customer account",
user_type_id=account_user_type.id,
reconcile=True,
)
)
self.product_product = self.env["product.product"]
self.product = self.product_product.create(
{
"name": "Test",
"categ_id": self.env.ref("product.product_category_all").id,
"standard_price": 50,
"list_price": 100,
"type": "service",
"uom_id": self.env.ref("uom.product_uom_unit").id,
"uom_po_id": self.env.ref("uom.product_uom_unit").id,
"description": "Test",
}
)
invoice_line_data = [
(
0,
0,
{
"product_id": self.product.id,
"quantity": 10.0,
"account_id": self.account_account.search(
[
(
"user_type_id",
"=",
self.env.ref("account.data_account_type_revenue").id,
)
],
limit=1,
).id,
"name": "product test 5",
"price_unit": 100.00,
},
)
]
self.invoice = self.account_invoice.create(
dict(
name="Test Customer Invoice",
journal_id=self.journal.id,
partner_id=self.partner.id,
invoice_line_ids=invoice_line_data,
move_type="out_invoice",
)
)
def test_exception(self):
"""Validate invoice without tax must raise exception"""
with self.assertRaises(exceptions.UserError):
self.invoice.with_context(test_tax_required=True).action_post()
def test_without_exception(self):
"""Validate invoice without tax must raise exception"""
self.invoice.invoice_line_ids[0].tax_ids = [(4, self.tax_cash_basis.id)]
self.invoice.with_context(test_tax_required=True).action_post()
| 37.057471
| 3,224
|
2,017
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 - Camptocamp SA - Author Vincent Renaville
# Copyright 2016 - Tecnativa - Angel Moya <odoo@tecnativa.com>
# Copyright 2019 - Tecnativa - Pedro M. Baeza
# Copyright 2019 - Punt Sistemes - Juan Vicente Pascual
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID, _, models
from odoo.exceptions import UserError
from odoo.tools import config
class AccountMove(models.Model):
_inherit = "account.move"
def _test_invoice_line_tax(self):
errors = []
error_template = _("Invoice has a line with product %s with no taxes")
for invoice_line in self.mapped("invoice_line_ids").filtered(
lambda x: x.display_type is False
):
if not invoice_line.tax_ids:
error_string = error_template % (invoice_line.name)
errors.append(error_string)
if errors:
raise UserError(
_(
"%(message)s\n%(errors)s",
message="No Taxes Defined!",
errors=("\n".join(x for x in errors)),
)
)
def action_post(self):
# Always test if it is required by context
force_test = self.env.context.get("test_tax_required")
skip_test = any(
(
# It usually fails when installing other addons with demo data
self.with_user(SUPERUSER_ID)
.env["ir.module.module"]
.search(
[
("state", "in", ["to install", "to upgrade"]),
("demo", "=", True),
]
),
# Avoid breaking unaware addons' tests by default
config["test_enable"],
)
)
for move in self:
if move.move_type != "entry" and (force_test or not skip_test):
move._test_invoice_line_tax()
return super(AccountMove, self).action_post()
| 37.351852
| 2,017
|
765
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL (http://tiny.be).
# Copyright 2010-2011 Elico Corp.
# Copyright 2016 Acsone (https://www.acsone.eu/)
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# Copyright 2019 Okia SPRL
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Account Invoice Merge",
"version": "15.0.1.0.0",
"category": "Finance",
"summary": "Merge invoices in draft",
"author": "Elico Corp,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"depends": ["account"],
"data": [
"security/ir.model.access.csv",
"wizard/invoice_merge_view.xml",
],
"installable": True,
}
| 33.26087
| 765
|
7,034
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class TestAccountInvoiceMerge(TransactionCase):
"""
Tests for Account Invoice Merge.
"""
def setUp(self):
super(TestAccountInvoiceMerge, self).setUp()
self.company_model = self.env["res.company"]
self.par_model = self.env["res.partner"]
self.context = self.env["res.users"].context_get()
self.acc_model = self.env["account.account"]
self.inv_model = self.env["account.move"]
self.journal_model = self.env["account.journal"]
self.inv_line_model = self.env["account.move.line"]
self.wiz = self.env["invoice.merge"]
self.partner1 = self._create_partner()
self.partner2 = self._create_partner()
self.invoice_account = self.acc_model.search(
[
(
"user_type_id",
"=",
self.env.ref("account.data_account_type_revenue").id,
)
],
limit=1,
)
line_values = self._get_inv_line_values(self.invoice_account)
self.invoice1 = self._create_invoice(self.partner1, "A", line_values)
self.invoice2 = self._create_invoice(self.partner1, "B", line_values)
self.invoice3 = self._create_invoice(self.partner2, "C", line_values)
def _create_partner(self):
partner = self.par_model.create(
{
"name": "Test Partner",
"company_type": "company",
}
)
return partner
def _get_inv_line_values(self, account_id):
line_values = [
(
0,
0,
{
"name": "test invoice line",
"account_id": account_id.id,
"quantity": 1.0,
"price_unit": 3.0,
"product_id": self.env.ref("product.product_product_8").id,
},
)
]
return line_values
def _create_invoice(
self,
partner,
name,
line_values,
move_type="out_invoice",
journal_type="sale",
journal=False,
):
journal = journal or self.journal_model.search(
[("type", "=", journal_type)], limit=1
)
invoice = self.inv_model.with_company(journal.company_id).create(
{
"move_type": move_type,
"partner_id": partner.id,
"name": name,
"invoice_line_ids": line_values,
"journal_id": journal.id,
}
)
return invoice
def _get_wizard(self, active_ids, create=False):
wiz_id = self.wiz.with_context(
active_ids=active_ids,
active_model="account.move",
)
if create:
wiz_id = wiz_id.create({})
return wiz_id
def test_account_invoice_merge_1(self):
self.assertEqual(len(self.invoice1.invoice_line_ids), 1)
self.assertEqual(len(self.invoice2.invoice_line_ids), 1)
start_inv = self.inv_model.search(
[("state", "=", "draft"), ("partner_id", "=", self.partner1.id)]
)
self.assertEqual(len(start_inv), 2)
wiz_id = self._get_wizard([self.invoice1.id, self.invoice2.id], create=True)
wiz_id.fields_view_get()
action = wiz_id.merge_invoices()
self.assertLessEqual(
{
"type": "ir.actions.act_window",
"binding_view_types": "list,form",
"xml_id": "account.action_move_out_invoice_type",
}.items(),
action.items(),
"There was an error and the two invoices were not merged.",
)
end_inv = self.inv_model.search(
[("state", "=", "draft"), ("partner_id", "=", self.partner1.id)]
)
self.assertEqual(len(end_inv), 1)
self.assertEqual(len(end_inv[0].invoice_line_ids), 1)
self.assertEqual(end_inv[0].invoice_line_ids[0].quantity, 2.0)
def test_account_invoice_merge_2(self):
with self.assertRaises(UserError):
self._get_wizard(
[self.invoice1.id, self.invoice3.id], create=True
).fields_view_get()
def test_dirty_check(self):
"""Check"""
# Check with only one invoice
with self.assertRaises(UserError):
self._get_wizard([self.invoice1.id]).fields_view_get()
# Check with two different invoice type
# Create the invoice 4 with a different account
new_account = self.acc_model.create(
{
"code": "TEST",
"name": "Test Account",
"reconcile": True,
"user_type_id": self.env.ref("account.data_account_type_receivable").id,
}
)
line_values = self._get_inv_line_values(new_account)
invoice4 = self._create_invoice(
self.partner1,
"D",
line_values,
move_type="in_invoice",
journal_type="purchase",
)
with self.assertRaises(UserError):
self._get_wizard([self.invoice1.id, invoice4.id]).fields_view_get()
# Check with a canceled invoice
# Create and cancel the invoice 5
line_values = self._get_inv_line_values(self.invoice_account)
invoice5 = self._create_invoice(self.partner1, "E", line_values)
invoice5.button_cancel()
with self.assertRaises(UserError):
self._get_wizard([self.invoice1.id, invoice5.id]).fields_view_get()
# Check with another company
# Create the invoice 6 in new company
new_company = self.company_model.create({"name": "Hello World"})
new_account = self.acc_model.create(
{
"name": "New Account",
"code": "AAABBB",
"user_type_id": self.env.ref("account.data_account_type_receivable").id,
"reconcile": True,
"company_id": new_company.id,
}
)
line_values = self._get_inv_line_values(new_account)
new_journal = self.journal_model.create(
{
"name": "Test Journal",
"company_id": new_company.id,
"type": "sale",
"code": "AAABBB",
}
)
invoice6 = self._create_invoice(
self.partner1, "E", line_values, journal=new_journal
)
with self.assertRaises(UserError):
self._get_wizard([self.invoice1.id, invoice6.id]).fields_view_get()
# Check with two different partners
with self.assertRaises(UserError):
self._get_wizard([self.invoice1.id, self.invoice3.id]).fields_view_get()
| 35.346734
| 7,034
|
3,440
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL (http://tiny.be).
# Copyright 2010-2011 Elico Corp.
# Copyright 2016 Acsone (https://www.acsone.eu/)
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# Copyright 2019 Okia SPRL
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
from odoo.exceptions import UserError
from odoo.tools.translate import _
class InvoiceMerge(models.TransientModel):
_name = "invoice.merge"
_description = "Merge Partner Invoice"
keep_references = fields.Boolean(
"Keep references from original invoices", default=True
)
date_invoice = fields.Date("Invoice Date")
@api.model
def _get_not_mergeable_invoices_message(self, invoices):
"""Overridable function to custom error message"""
key_fields = invoices._get_invoice_key_cols()
error_msg = {}
if len(invoices) != len(invoices._get_draft_invoices()):
error_msg["state"] = _("Merge-able State (ex : %s)") % (
invoices and invoices[0].state or _("Draft")
)
for field in key_fields:
if len(set(invoices.mapped(field))) > 1:
error_msg[field] = invoices._fields[field].string
return error_msg
@api.model
def _dirty_check(self):
if self.env.context.get("active_model", "") == "account.move":
ids = self.env.context["active_ids"]
if len(ids) < 2:
raise UserError(
_("Please select multiple invoices to merge in the list " "view.")
)
invs = self.env["account.move"].browse(ids)
error_msg = self._get_not_mergeable_invoices_message(invs)
if error_msg:
all_msg = _("All invoices must have the same: \n")
all_msg += "\n".join([value for value in error_msg.values()])
raise UserError(all_msg)
return {}
@api.model
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
"""Changes the view dynamically
@param self: The object pointer.
@return: New arch of view.
"""
res = super(InvoiceMerge, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=False
)
self._dirty_check()
return res
def merge_invoices(self):
"""To merge similar type of account invoices.
@param self: The object pointer.
@return: account invoice action
"""
ids = self.env.context.get("active_ids", [])
invoices = self.env["account.move"].browse(
self.env.context.get("active_ids", [])
)
allinvoices = invoices.do_merge(
keep_references=self.keep_references, date_invoice=self.date_invoice
)
xid = {
"out_invoice": "action_move_out_invoice_type",
"out_refund": "action_move_out_refund_type",
"in_invoice": "action_move_in_invoice_type",
"in_refund": "action_move_in_refund_type",
}[invoices[0].move_type]
action = self.env["ir.actions.act_window"]._for_xml_id("account.{}".format(xid))
action.update(
{
"domain": [("id", "in", ids + list(allinvoices.keys()))],
}
)
return action
| 37.391304
| 3,440
|
9,573
|
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 Tiny SPRL (http://tiny.be).
# Copyright 2010-2011 Elico Corp.
# Copyright 2016 Acsone (https://www.acsone.eu/)
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# Copyright 2019 Okia SPRL
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, models
from odoo.tools import float_is_zero
class AccountMove(models.Model):
_inherit = "account.move"
@api.model
def _get_invoice_key_cols(self):
return [
"partner_id",
"user_id",
"move_type",
"currency_id",
"journal_id",
"company_id",
"partner_bank_id",
]
@api.model
def _get_invoice_line_key_cols(self):
fields = [
"name",
"discount",
"tax_ids",
"price_unit",
"product_id",
"account_id",
"analytic_account_id",
"product_uom_id",
]
for field in [
"sale_line_ids", # odoo/sale
"purchase_price", # OCA/account_invoice_margin
]:
if field in self.env["account.move.line"]._fields:
fields.append(field)
return fields
@api.model
def _get_first_invoice_fields(self, invoice):
return {
"invoice_origin": "%s" % (invoice.invoice_origin or "",),
"partner_id": invoice.partner_id.id,
"journal_id": invoice.journal_id.id,
"user_id": invoice.user_id.id,
"currency_id": invoice.currency_id.id,
"company_id": invoice.company_id.id,
"move_type": invoice.move_type,
"state": "draft",
"payment_reference": "%s" % (invoice.payment_reference or "",),
"name": "%s" % (invoice.name or "",),
"fiscal_position_id": invoice.fiscal_position_id.id,
"invoice_payment_term_id": invoice.invoice_payment_term_id.id,
"invoice_line_ids": {},
"partner_bank_id": invoice.partner_bank_id.id,
}
def _get_draft_invoices(self):
"""Overridable function to return draft invoices to merge"""
return self.filtered(lambda x: x.state == "draft")
# flake8: noqa: C901
def do_merge(
self, keep_references=True, date_invoice=False, remove_empty_invoice_lines=True
):
"""
To merge similar type of account invoices.
Invoices will only be merged if:
* Account invoices are in draft
* Account invoices belong to the same partner
* Account invoices are have same company, partner, address, currency,
journal, currency, salesman, account, type
Lines will only be merged if:
* Invoice lines are exactly the same except for the quantity and unit
@param self: The object pointer.
@param keep_references: If True, keep reference of original invoices
@return: new account invoice id
"""
def make_key(br, fields):
list_key = []
for field in fields:
field_val = getattr(br, field)
if field in ("product_id", "account_id"):
if not field_val:
field_val = False
if (
isinstance(field_val, models.Model)
and field != "tax_ids"
and field != "sale_line_ids"
):
field_val = field_val.id
elif (
isinstance(field_val, list)
or field == "tax_ids"
or field == "sale_line_ids"
):
field_val = ((6, 0, tuple(v.id for v in field_val)),)
list_key.append((field, field_val))
list_key.sort()
return tuple(list_key)
# compute what the new invoices should contain
new_invoices = {}
seen_origins = {}
seen_client_refs = {}
for account_invoice in self._get_draft_invoices():
invoice_key = make_key(account_invoice, self._get_invoice_key_cols())
new_invoice = new_invoices.setdefault(invoice_key, ({}, []))
origins = seen_origins.setdefault(invoice_key, set())
client_refs = seen_client_refs.setdefault(invoice_key, set())
new_invoice[1].append(account_invoice.id)
invoice_infos = new_invoice[0]
if not invoice_infos:
invoice_infos.update(self._get_first_invoice_fields(account_invoice))
origins.add(account_invoice.invoice_origin)
client_refs.add(account_invoice.payment_reference)
if not keep_references:
invoice_infos.pop("name")
else:
if account_invoice.name and keep_references:
invoice_infos["name"] = (
(invoice_infos["name"] or "") + " " + account_invoice.name
)
if (
account_invoice.invoice_origin
and account_invoice.invoice_origin not in origins
):
invoice_infos["invoice_origin"] = (
(invoice_infos["invoice_origin"] or "")
+ " "
+ account_invoice.invoice_origin
)
origins.add(account_invoice.invoice_origin)
if (
account_invoice.payment_reference
and account_invoice.payment_reference not in client_refs
):
invoice_infos["payment_reference"] = (
(invoice_infos["payment_reference"] or "")
+ " "
+ account_invoice.payment_reference
)
client_refs.add(account_invoice.payment_reference)
for invoice_line in account_invoice.invoice_line_ids:
line_key = make_key(invoice_line, self._get_invoice_line_key_cols())
o_line = invoice_infos["invoice_line_ids"].setdefault(line_key, {})
if o_line:
# merge the line with an existing line
o_line["quantity"] += invoice_line.quantity
else:
# append a new "standalone" line
o_line["quantity"] = invoice_line.quantity
allinvoices = []
allnewinvoices = []
invoices_info = {}
old_invoices = self.env["account.move"]
qty_prec = self.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
for invoice_key, (invoice_data, old_ids) in new_invoices.items():
# skip merges with only one invoice
if len(old_ids) < 2:
allinvoices += old_ids or []
continue
# cleanup invoice line data
for key, value in invoice_data["invoice_line_ids"].items():
value.update(dict(key))
if remove_empty_invoice_lines:
invoice_data["invoice_line_ids"] = [
(0, 0, value)
for value in invoice_data["invoice_line_ids"].values()
if not float_is_zero(value["quantity"], precision_digits=qty_prec)
]
else:
invoice_data["invoice_line_ids"] = [
(0, 0, value) for value in invoice_data["invoice_line_ids"].values()
]
if date_invoice:
invoice_data["invoice_date"] = date_invoice
# create the new invoice
newinvoice = self.with_context(is_merge=True).create(invoice_data)
invoices_info.update({newinvoice.id: old_ids})
allinvoices.append(newinvoice.id)
allnewinvoices.append(newinvoice)
# cancel old invoices
old_invoices = self.env["account.move"].browse(old_ids)
old_invoices.with_context(is_merge=True).button_cancel()
# Make link between original sale order
# None if sale is not installed
for new_invoice_id in invoices_info:
if "sale.order" in self.env.registry:
sale_todos = old_invoices.mapped(
"invoice_line_ids.sale_line_ids.order_id"
)
for org_so in sale_todos:
for so_line in org_so.order_line:
invoice_line = self.env["account.move.line"].search(
[
("id", "in", so_line.invoice_lines.ids),
("move_id", "=", new_invoice_id),
]
)
if invoice_line:
so_line.write({"invoice_lines": [(6, 0, invoice_line.ids)]})
# recreate link (if any) between original analytic account line
# (invoice time sheet for example) and this new invoice
anal_line_obj = self.env["account.analytic.line"]
if "timesheet_invoice_id" in anal_line_obj._fields:
for new_invoice_id in invoices_info:
anal_todos = anal_line_obj.search(
[("timesheet_invoice_id", "in", invoices_info[new_invoice_id])]
)
anal_todos.write({"timesheet_invoice_id": new_invoice_id})
return invoices_info
| 40.222689
| 9,573
|
582
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
{
"name": "Account Invoice View Payment",
"summary": "Access to the payment from an invoice",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"website": "https://github.com/OCA/account-invoicing",
"author": "ForgeFlow, " "Odoo Community Association (OCA)",
"category": "Accounting",
"depends": ["account"],
"data": ["views/account_payment_view.xml", "views/account_move_view.xml"],
"installable": True,
}
| 36.375
| 582
|
5,440
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import fields
from odoo.tests.common import TransactionCase
class TestAccountInvoiceViewPayment(TransactionCase):
"""
Tests for Account Invoice View Payment.
"""
def setUp(self):
super(TestAccountInvoiceViewPayment, self).setUp()
self.par_model = self.env["res.partner"]
self.acc_model = self.env["account.account"]
self.inv_model = self.env["account.move"]
self.inv_line_model = self.env["account.move.line"]
self.pay_model = self.env["account.payment"]
self.reg_pay_model = self.env["account.payment.register"]
self.cash = self.env["account.journal"].create(
{"name": "Cash Test", "type": "cash", "code": "CT"}
)
self.payment_method_manual_in = self.env.ref(
"account.account_payment_method_manual_in"
)
self.partner1 = self._create_partner()
self.invoice_account = self.acc_model.search(
[
(
"user_type_id",
"=",
self.env.ref("account.data_account_type_revenue").id,
)
],
limit=1,
)
self.invoice1 = self._create_invoice(self.partner1, "out_invoice")
self.invoice2 = self._create_invoice(self.partner1, "in_invoice")
self.invoice3 = self._create_invoice(self.partner1, "in_invoice")
self.invoice2.invoice_date = self.invoice3.invoice_date = fields.Date.today()
def _create_partner(self):
partner = self.par_model.create(
{"name": "Test Partner", "company_type": "company"}
)
return partner
def _create_invoice(self, partner, invoice_type):
inv_line = [
(
0,
0,
{
"product_id": self.env.ref("product.product_product_8").id,
"name": "Test Invoice Line",
"account_id": self.invoice_account.id,
"quantity": 1.0,
"price_unit": 3.0,
},
)
]
invoice = self.inv_model.create(
{
"partner_id": partner.id,
"move_type": invoice_type,
"invoice_line_ids": inv_line,
}
)
return invoice
def test_account_move_view_payment_out_invoice(self):
self.invoice1.action_post()
wiz = self.pay_model.with_context(
active_id=[self.invoice1.id], active_model="account.move"
).create(
{
"journal_id": self.cash.id,
"payment_method_id": self.payment_method_manual_in.id,
"amount": self.invoice1.amount_residual,
"payment_type": "inbound",
}
)
res = wiz.post_and_open_payment()
expect = {"type": "ir.actions.act_window", "res_model": "account.payment"}
self.assertDictEqual(
expect,
{k: v for k, v in res.items() if k in expect},
"There was an error and the view couldn't be opened.",
)
view_payment = self.invoice1.action_view_payments()
expect1 = {"type": "ir.actions.act_window", "res_model": "account.payment"}
self.assertDictEqual(
expect1,
{k: v for k, v in view_payment.items() if k in expect1},
"There was an error and the invoice couldn't be paid.",
)
def test_account_move_view_payment_in_invoice(self):
self.invoice2.action_post()
wiz = self.pay_model.with_context(
active_id=[self.invoice2.id], active_model="account.move"
).create(
{
"journal_id": self.cash.id,
"payment_method_id": self.payment_method_manual_in.id,
"amount": self.invoice2.amount_residual,
"payment_type": "inbound",
}
)
res = wiz.post_and_open_payment()
expect = {"type": "ir.actions.act_window", "res_model": "account.payment"}
self.assertDictEqual(
expect,
{k: v for k, v in res.items() if k in expect},
"There was an error and the view couldn't be opened.",
)
view_payment = self.invoice2.action_view_payments()
expect1 = {"type": "ir.actions.act_window", "res_model": "account.payment"}
self.assertDictEqual(
expect1,
{k: v for k, v in view_payment.items() if k in expect1},
"There was an error and the view couldn't be opened.",
)
def test_view_account_payment_register_form(self):
self.invoice2.action_post()
self.invoice3.action_post()
wiz = self.reg_pay_model.with_context(
active_ids=[self.invoice2.id, self.invoice3.id], active_model="account.move"
).create(
{
"journal_id": self.cash.id,
}
)
res = wiz.create_payment_and_open()
expect = {"type": "ir.actions.act_window", "res_model": "account.payment"}
self.assertDictEqual(
expect,
{k: v for k, v in res.items() if k in expect},
"There was an error and the two invoices were not merged.",
)
| 34.871795
| 5,440
|
1,257
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import models
class AccountMove(models.Model):
_inherit = "account.move"
def action_view_payments(self):
"""
This function returns an action that display existing payments of given
account moves.
When only one found, show the payment immediately.
"""
if self.move_type in ("in_invoice", "in_refund"):
action = self.env.ref("account.action_account_payments_payable")
else:
action = self.env.ref("account.action_account_payments")
result = action.read()[0]
reconciles = self._get_reconciled_info_JSON_values()
payment = []
for rec in reconciles:
payment.append(rec["account_payment_id"])
# choose the view_mode accordingly
if len(reconciles) != 1:
result["domain"] = "[('id', 'in', " + str(payment) + ")]"
else:
res = self.env.ref("account.view_account_payment_form", False)
result["views"] = [(res and res.id or False, "form")]
result["res_id"] = payment and payment[0] or False
return result
| 36.970588
| 1,257
|
1,501
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import _, models
class AccountPayment(models.Model):
_inherit = "account.payment"
def post_and_open_payment(self):
self.action_post()
res = {
"name": _("Payments"),
"views": [(False, "form")],
"res_id": self.id,
"res_model": "account.payment",
"view_id": False,
"context": False,
"type": "ir.actions.act_window",
}
return res
class AccountPaymentRegister(models.TransientModel):
_inherit = "account.payment.register"
def create_payment_and_open(self):
account_move_model = self.env["account.move"]
payment_model = self.env["account.payment"]
payments = payment_model
for _payment_vals in account_move_model.search(
[("id", "in", self.env.context.get("active_ids", False))]
):
vals = self._create_payment_vals_from_wizard()
payments += payment_model.create(vals)
payments.action_post()
res = {
"domain": [("id", "in", payments.ids), ("state", "=", "posted")],
"name": _("Payments"),
"view_mode": "tree,form",
"res_model": "account.payment",
"view_id": False,
"context": False,
"type": "ir.actions.act_window",
}
return res
| 31.93617
| 1,501
|
472
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Account Portal Invoice Search",
"version": "15.0.1.0.0",
"category": "Accounting",
"website": "https://github.com/OCA/account-invoicing",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"development_status": "Beta",
"application": False,
"installable": True,
"depends": ["account"],
}
| 33.714286
| 472
|
1,063
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
from odoo.osv import expression
class AccountMove(models.Model):
_inherit = "account.move"
@api.model
def _get_portal_search_domain(self, portal_invoice_filter):
return (
"|",
("name", "ilike", portal_invoice_filter),
("payment_reference", "ilike", portal_invoice_filter),
)
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
"""Display only standalone contact matching ``args`` or having
attached contact matching ``args``"""
portal_invoice_filter = self.env.context.get("portal_invoice_filter")
if portal_invoice_filter:
portal_search_domain = self._get_portal_search_domain(portal_invoice_filter)
args = expression.AND([args, portal_search_domain])
return super().search(
args, offset=offset, limit=limit, order=order, count=count
)
| 36.655172
| 1,063
|
1,908
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _
from odoo.http import request, route
from odoo.addons.account.controllers.portal import PortalAccount
from odoo.addons.portal.controllers.portal import pager as portal_pager
class PortalAccount(PortalAccount):
@route()
def portal_my_invoices(
self, page=1, date_begin=None, date_end=None, sortby=None, **kw
):
"""Inject search term in the context so it can be used in the search method
in account.move to filter invoices from the portal"""
if "search" in kw:
context = dict(request.env.context)
context.update({"portal_invoice_filter": kw.get("search", "")})
request.env.context = context
response = super().portal_my_invoices(
page=page, date_begin=date_begin, date_end=date_end, sortby=sortby, **kw
)
response.qcontext.setdefault("searchbar_inputs", {})
label_search = _("Search in Invoices & Bills")
pager = portal_pager(
url="/my/invoices",
url_args={
"date_begin": date_begin,
"date_end": date_end,
"sortby": sortby,
"search": kw.get("search"),
"search_in": "portal_invoice_filter",
},
total=self._items_per_page * response.qcontext["pager"]["page_count"],
page=page,
step=self._items_per_page,
)
response.qcontext["searchbar_inputs"].update(
{
"portal_order_filter": {
"input": "portal_invoice_filter",
"label": label_search,
},
}
)
response.qcontext["pager"] = pager
response.qcontext["search_in"] = "portal_invoice_filter"
return response
| 38.16
| 1,908
|
724
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Account Invoice Check Picking Date",
"summary": "Check if date of pickings match with accounting date",
"version": "15.0.1.1.0",
"development_status": "Production/Stable",
"category": "Accounting",
"website": "https://github.com/OCA/account-invoicing",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["stock_account"],
"maintainers": ["carlosdauden"],
"data": [
"security/ir.model.access.csv",
"wizards/invoice_stock_picking_date_wiz.xml",
],
}
| 36.2
| 724
|
2,569
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.tools import config
class AccountMove(models.Model):
_inherit = "account.move"
def _get_min_max_stock_move_dates(self):
self.ensure_one()
moves = self._stock_account_get_last_step_stock_moves()
min_date = moves[:1].date
max_date = min_date
for move in moves:
if move.date < min_date:
min_date = move.date
if move.date > max_date:
max_date = move.date
return min_date, max_date
def _match_invoice_and_stock_move_dates(self, min_date, max_date):
self.ensure_one()
if not max_date:
return True
return self.date.month == max_date.month
def action_post(self):
if config["test_enable"] or self.env.context.get(
"skip_account_invoice_check_picking_date", False
):
return super().action_post()
invoice_types = (
(
self.env["ir.config_parameter"]
.sudo()
.get_param(
"account_invoice_check_picking_date.invoice_types", "in_invoice"
)
)
.replace(" ", "")
.split(",")
)
for invoice in self:
if invoice.date and invoice.move_type in invoice_types:
min_date, max_date = invoice._get_min_max_stock_move_dates()
if invoice._match_invoice_and_stock_move_dates(min_date, max_date):
continue
DateField = self.env["ir.qweb.field.date"]
exception_msg = _(
"Accounting date: %(accounting_date)s\n"
"First stock move: %(min_date)s Last stock move: %(max_date)s\n\n"
"If dates are right and you have manager permissions you can use "
"special action to post this invoice."
) % {
"accounting_date": DateField.value_to_html(invoice.date, {}),
"min_date": DateField.value_to_html(min_date, {}),
"max_date": DateField.value_to_html(max_date, {}),
}
exception_wizard = self.env["invoice.picking.date.check.wiz"].create(
{"exception_msg": exception_msg, "invoice_id": invoice.id}
)
return exception_wizard.action_show()
return super().action_post()
| 39.523077
| 2,569
|
936
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, fields, models
class InvoicePickingDateCheckWiz(models.TransientModel):
_name = "invoice.picking.date.check.wiz"
_description = "Invoice and picking date check wizard"
invoice_id = fields.Many2one(comodel_name="account.move")
exception_msg = fields.Text(readonly=True)
def action_show(self):
self.ensure_one()
return {
"type": "ir.actions.act_window",
"name": _("Accounting date does not match with stock move dates"),
"res_model": self._name,
"res_id": self.id,
"view_mode": "form",
"target": "new",
}
def button_continue(self):
self.ensure_one()
return self.invoice_id.with_context(
skip_account_invoice_check_picking_date=True
).action_post()
| 32.275862
| 936
|
656
|
py
|
PYTHON
|
15.0
|
import logging
from odoo import tools
_logger = logging.getLogger(__name__)
def pre_init_hook(cr):
"""
Initializing column custom_rate on table account_move
for the improvement in performance to avoid long
duration in databases with thousand of moves
"""
_logger.info("Initializing column custom_rate on table account_move")
tools.create_column(
cr=cr,
tablename="account_move",
columnname="custom_rate",
columntype="numeric",
comment="Custom Rate",
)
cr.execute(
"""
UPDATE
account_move
SET
custom_rate = 1.0
"""
)
| 22.62069
| 656
|
675
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Komit <http://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Account Invoice - Change Currency",
"version": "15.0.2.0.0",
"category": "Accounting & Finance",
"summary": "Allows to change currency of Invoice by wizard",
"author": "Vauxoo, Komit Consulting, Odoo Community Association (OCA)",
"maintainers": ["luisg123v", "rolandojduartem"],
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"depends": ["account"],
"data": [
"views/account_move_views.xml",
],
"pre_init_hook": "pre_init_hook",
"installable": True,
}
| 37.5
| 675
|
12,032
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Komit <http://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import odoo.tests.common as common
from odoo import fields
from odoo.tools import float_compare
class TestAccountInvoiceChangeCurrency(common.TransactionCase):
def setUp(self):
super().setUp()
self.precision = self.env["decimal.precision"].precision_get("Payment Terms")
res_users_account_manager = self.env.ref("account.group_account_manager")
self.manager = (
self.env["res.users"]
.with_context(no_reset_password=True)
.create(
dict(
name="Adviser",
company_id=self.env.ref("base.main_company").id,
login="fm",
email="accountmanager@yourcompany.com",
groups_id=[(6, 0, [res_users_account_manager.id])],
)
)
)
# Needed to create invoice
self.account_type = self.env["account.account.type"].create(
{
"name": "acc type test 2",
"type": "other",
"include_initial_balance": True,
"internal_group": "asset",
}
)
self.account_account_line = self.env["account.account"].create(
{
"name": "acc inv line test",
"code": "X2021",
"user_type_id": self.account_type.id,
"reconcile": True,
}
)
self.product_1 = self.env["product.product"].create({"name": "Product 1"})
self.product_2 = self.env["product.product"].create({"name": "Product 2"})
self.analytic_account = self.env["account.analytic.account"].create(
{"name": "test account"}
)
self.tax_account = self.env["account.account"].search(
[
(
"user_type_id",
"=",
self.env.ref("account.data_account_type_current_assets").id,
)
],
limit=1,
)
def create_simple_invoice(self, date=False, context=None, inv_type=None):
if not context:
context = {}
context["default_move_type"] = True
invoice_lines = [
(
0,
0,
{
"product_id": self.product_1.id,
"quantity": 5.0,
"price_unit": 142.0,
"name": "Product that cost 142",
"account_id": self.account_account_line.id,
},
),
(
0,
0,
{
"product_id": self.product_2.id,
"quantity": 4.0,
"price_unit": 213.0,
"name": "Product that cost 213",
"account_id": self.account_account_line.id,
},
),
]
invoice = (
self.env["account.move"]
.with_user(self.manager)
.with_context(**context)
.create(
{
"partner_id": 1,
"move_type": inv_type or "in_invoice",
"invoice_date": date,
"currency_id": self.env.ref("base.EUR").id,
"invoice_line_ids": invoice_lines,
"state": "draft",
}
)
)
return invoice
def test_change_invoice_currency(self):
inv = self.create_simple_invoice(fields.Date.today())
before_curr = inv.currency_id
before_amount = inv.amount_total
after_curr = self.env.ref("base.USD")
inv.write({"currency_id": after_curr.id})
inv.action_account_change_currency()
expected_value = before_curr._convert(
before_amount, after_curr, inv.company_id, fields.Date.today()
)
self.assertEqual(
float_compare(inv.amount_total, expected_value, 0),
0,
"Total amount of invoice does not match to the expected value",
)
def test_change_validated_invoice_currency(self):
inv = self.create_simple_invoice(fields.Date.today())
before_amount = inv.amount_total
inv.action_post()
# Make sure that we can not change the currency after validated:
inv.write({"currency_id": self.env.ref("base.USD").id})
inv.action_account_change_currency()
self.assertEqual(
inv.amount_total,
before_amount,
"Total amount of invoice does not match to the expected value",
)
def test_create_invoice_update_currency(self):
inv = self.create_simple_invoice()
before_amount = inv.amount_total
inv.action_account_change_currency()
self.assertEqual(
inv.amount_total,
before_amount,
"Amount must remain the same, because no currency changes",
)
def test_custom_rate_update_currency(self):
inv = self.create_simple_invoice(fields.Date.today())
before_amount = inv.amount_total
after_curr = self.env.ref("base.USD")
custom_rate = 1.13208
inv.write({"currency_id": after_curr.id, "custom_rate": custom_rate})
inv.write({"custom_rate": custom_rate})
inv.action_account_change_currency()
expected_value = before_amount * custom_rate
# TODO: Check float comparation, 12013.64 vs 12013.632959999999
self.assertEqual(
float_compare(inv.amount_total, expected_value, self.precision),
1,
"Total amount of invoice does not match to the expected value",
)
def test_custom_rate_zero_update_currency(self):
inv = self.create_simple_invoice()
before_amount = inv.amount_total
before_curr = inv.currency_id
custom_rate = 0.0
usd = self.env.ref("base.USD")
eur = self.env.ref("base.EUR")
inv.write({"currency_id": usd.id, "custom_rate": custom_rate})
inv.write({"custom_rate": custom_rate})
inv.action_account_change_currency()
expected_value = before_curr._convert(
before_amount, usd, inv.company_id, fields.Date.today()
)
# Comparison 2004.64 vs 2004.67
self.assertEqual(
float_compare(inv.amount_total, expected_value, 0),
0,
"Total amount of invoice does not match to the expected value",
)
# Change currency and set custom rate 0
inv.write({"currency_id": eur.id, "custom_rate": custom_rate})
inv.write({"custom_rate": custom_rate})
inv.action_account_change_currency()
self.assertEqual(
inv.amount_total,
before_amount,
"Total amount of invoice does not match to the expected value",
)
# Change Again custom rate with old_rate but now without new currency
inv.write({"custom_rate": custom_rate})
inv.action_account_change_currency()
expected_value = before_curr._convert(
before_amount, eur, inv.company_id, fields.Date.today()
)
self.assertEqual(
inv.amount_total,
expected_value,
"Total amount of invoice does not match to the expected value",
)
# Custom rate with 0 but now without new currency
inv.write({"custom_rate": custom_rate})
inv.action_account_change_currency()
expected_value = before_curr._convert(
before_amount, eur, inv.company_id, fields.Date.today()
)
self.assertEqual(
inv.amount_total,
before_amount,
"Total amount of invoice does not match to the expected value",
)
# keep old_rate but now we update the currency.rate
# (Original currency rate can not be changed anymore)
before_amount = inv.amount_total
old_rate = custom_rate
new_rate = 1.6299
usd_updated_rate = self.env["res.currency.rate"].create(
{
"name": fields.Date.today(),
"rate": new_rate,
"currency_id": usd.id,
"company_id": inv.company_id.id,
}
)
rate = usd_updated_rate.rate
inv.write({"custom_rate": rate})
inv.action_account_change_currency()
expected_value = before_amount
# TODO: Check float comparation, 1562.0 vs 1562.0
self.assertEqual(
inv.amount_total,
expected_value,
"Total amount of invoice does not match to the expected value",
)
# change custom rate then we trigger the conversion 2 times
# The currency.rate modification above will be ignored and keep the
# custom rate
old_rate = inv.custom_rate
inv.write({"currency_id": usd.id, "custom_rate": rate})
inv.action_account_change_currency()
before_amount = inv.amount_total
rate = usd_updated_rate.rate
inv.action_account_change_currency()
expected_value = before_amount * rate / old_rate
self.assertEqual(
float_compare(inv.amount_total, expected_value, self.precision),
0,
"Total amount of invoice does not match to the expected value",
)
before_amount = inv.amount_total
rate = old_rate + 1
inv.write({"custom_rate": rate})
inv.action_account_change_currency()
expected_value = before_amount * rate / old_rate
# TODO: Check float comparation, 4107.93 vs 4107.946074605804
self.assertEqual(
float_compare(inv.amount_total, expected_value, 1),
0,
"Total amount of invoice does not match to the expected value",
)
inv.action_account_change_currency()
# TODO: Check float comparation, 4107.93 vs 4107.946074605804
self.assertEqual(
float_compare(inv.amount_total, expected_value, 1),
0,
"Total amount of invoice does not match to the expected value",
)
# Test if there are no currency
inv.write({"currency_id": False})
self.assertEqual(
inv.custom_rate,
1.0,
"Custom rate of invoice does not match to the expected value",
)
def test_not_currency_change(self):
inv = self.create_simple_invoice(inv_type="out_invoice")
before_amount = inv.amount_total
inv.action_account_change_currency()
self.assertEqual(
inv.amount_total,
before_amount,
"Amount must remain the same, because None change was made",
)
def test_old_invoices(self):
# This simulate an old invoice (no stored original values)
inv = self.create_simple_invoice(fields.Date.today())
inv.write({"original_currency_id": False})
inv.invoice_line_ids.write({"original_price_unit": False})
self.assertFalse(
inv.original_currency_id,
"There is an original currency in the invoice",
)
self.assertEqual(
inv.invoice_line_ids.mapped("original_price_unit"),
[0.0, 0.0],
"There are original price units in the invoice",
)
# Now, trigger the action to store the original values to change currencies
inv.action_account_change_currency()
self.assertEqual(
inv.original_currency_id,
inv.currency_id,
"Original currency of invoice is not match to the expected value",
)
self.assertEqual(
inv.invoice_line_ids.mapped("original_price_unit"),
inv.invoice_line_ids.mapped("price_unit"),
"Original price units of invoice do not match to the expected value",
)
| 38.812903
| 12,032
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.