size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
2,364
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase class TestUI(HttpCase): def setUp(self): super().setUp() self.product = self.env["product.template"].create( { "name": "Test Product 1", "is_published": True, "website_sequence": 1, "type": "consu", } ) def test_01_ui_no_restriction(self): self.env["ir.filters"].create( { "name": "Test Assortment", "model_id": "product.product", "is_assortment": True, "domain": [("id", "!=", self.product.product_variant_id.id)], "partner_domain": "[('id', '=', %s)]" % self.env.ref("base.partner_admin").id, } ) self.start_tour("/shop", "test_assortment_with_no_restriction", login="admin") def test_02_ui_no_show(self): self.env["ir.filters"].create( { "name": "Test Assortment", "model_id": "product.product", "is_assortment": True, "domain": [("id", "!=", self.product.product_variant_id.id)], "partner_domain": "[('id', '=', %s)]" % self.env.ref("base.partner_admin").id, "website_availability": "no_show", } ) self.start_tour("/shop", "test_assortment_with_no_show", login="admin") def test_03_ui_no_purchase(self): self.env["ir.filters"].create( { "name": "Test Assortment", "model_id": "product.product", "is_assortment": True, "domain": [("id", "!=", self.product.product_variant_id.id)], "partner_domain": "[('id', '=', %s)]" % self.env.ref("base.partner_admin").id, "website_availability": "no_purchase", "message_unavailable": "Can't purchase", "assortment_information": """<span name='testing'> This product is not available for purchase </span> """, } ) self.start_tour("/shop", "test_assortment_with_no_purchase", login="admin")
38.129032
2,364
3,318
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class ProductTemplate(models.Model): _inherit = "product.template" @api.model def get_product_assortment_restriction_info(self, product_ids): partner = self.env.user.partner_id website = self.env["website"].get_current_website() assortments = ( self.env["ir.filters"] .sudo() .search( [ ("is_assortment", "=", True), ("website_availability", "in", ["no_purchase", "no_show"]), "|", ("website_ids", "=", website.id), ("website_ids", "=", False), ] ) ) assortment_dict = {} for assortment in assortments: if partner & assortment.with_context(active_test=False).all_partner_ids: allowed_product_ids = assortment.all_product_ids.ids for product in product_ids: if product not in allowed_product_ids: assortment_dict.setdefault(product, self.env["ir.filters"]) assortment_dict[product] |= assortment return assortment_dict def _get_combination_info( self, combination=False, product_id=False, add_qty=1, pricelist=False, parent_combination=False, only_template=False, ): res = super()._get_combination_info( combination=combination, product_id=product_id, add_qty=add_qty, pricelist=pricelist, parent_combination=parent_combination, only_template=only_template, ) product_res_id = res["product_id"] if self.env.context.get("website_id") and not only_template and product_res_id: not_allowed_product_dict = self.get_product_assortment_restriction_info( [product_res_id] ) if not_allowed_product_dict and product_res_id in not_allowed_product_dict: res["product_avoid_purchase"] = True res["product_assortment_type"] = "no_purchase" assortments = not_allowed_product_dict[product_res_id] for assortment in assortments: if assortment.website_availability == "no_show": res["product_assortment_type"] = "no_show" break if res["product_assortment_type"] != "no_show": assortment = assortments[0] res["message_unavailable"] = assortment.message_unavailable res["assortment_information"] = assortment.assortment_information else: res["product_avoid_purchase"] = False return res @api.model def _search_get_detail(self, website, order, options): res = super()._search_get_detail(website, order, options) domain = res["base_domain"] allowed_product_domain = options.get("allowed_product_domain") if allowed_product_domain: domain.append(allowed_product_domain) res["base_domain"] = domain return res
40.463415
3,318
2,275
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class IrFilters(models.Model): _inherit = "ir.filters" website_availability = fields.Selection( selection=[ ("no_restriction", "Don't apply restriction"), ("no_show", "Avoid to show non available products"), ("no_purchase", "Avoid selling not available products"), ], string="Availability on Website", default="no_restriction", required=True, help=""" Each point is used to:\n \t- Don't apply restriction: Show all products available for sale on website.\n \t- Avoid to show non available products: Show only products available for sale on website.\n \t- Avoid selling not available products: Show all products, but avoid purchase on website.\n """, ) message_unavailable = fields.Char( string="Message when unavailable", help="""Message showed when some product is not available and the option 'Avoid selling not available products' is selected. """, ) website_ids = fields.Many2many( comodel_name="website", ondelete="cascade", string="Websites" ) apply_on_public_user = fields.Boolean() assortment_information = fields.Html() all_product_ids = fields.Many2many( comodel_name="product.product", relation="assortment_all_products", compute="_compute_all_product_ids", ) @api.depends("domain", "blacklist_product_ids", "whitelist_product_ids") def _compute_all_product_ids(self): for record in self: record.all_product_ids = record.env["product.product"] if record.is_assortment: record.all_product_ids = record.env["product.product"].search( record._get_eval_domain() ) @api.depends("apply_on_public_user") def _compute_all_partner_ids(self): res = super()._compute_all_partner_ids() for ir_filter in self: if ir_filter.apply_on_public_user: ir_filter.all_partner_ids += self.env.ref("base.public_user").partner_id return res
38.559322
2,275
2,903
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from werkzeug.exceptions import NotFound from odoo.http import request, route from odoo.addons.website_sale.controllers.main import WebsiteSale class WebsiteSale(WebsiteSale): def _get_products_allowed(self): partner = request.env.user.partner_id website_id = request.website.id assortments = ( request.env["ir.filters"] .sudo() .search( [ ("is_assortment", "=", True), ("website_availability", "=", "no_show"), "|", ("website_ids", "=", False), ("website_ids", "=", website_id), ] ) ) assortment_restriction = False allowed_product_ids = set() for assortment in assortments: if ( # Set active_test to False to allow filtering by partners # that are not active, (for example Public User) partner & assortment.with_context(active_test=False).all_partner_ids ): assortment_restriction = True allowed_product_ids = allowed_product_ids.union( set(assortment.all_product_ids.ids) ) return allowed_product_ids, assortment_restriction @route() def product(self, product, category="", search="", **kwargs): """Overriding product method to avoid accessing to product sheet when the product assortments prevent to show them. """ allowed_product_ids, assortment_restriction = self._get_products_allowed() if assortment_restriction: if len(set(product.product_variant_ids.ids) & allowed_product_ids) == 0: raise NotFound() return super().product(product, category=category, search=search, **kwargs) def _get_search_options( self, category=None, attrib_values=None, pricelist=None, min_price=0.0, max_price=0.0, conversion_rate=1, **post ): """Overriding _get_search_options method to avoid show product templates that has all their variants not allowed to be shown.""" res = super()._get_search_options( category=category, attrib_values=attrib_values, pricelist=pricelist, min_price=min_price, max_price=max_price, conversion_rate=conversion_rate, **post ) allowed_product_ids, assortment_restriction = self._get_products_allowed() if assortment_restriction: res["allowed_product_domain"] = [ ("product_variant_ids", "in", list(allowed_product_ids)) ] return res
36.746835
2,903
1,556
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, http from odoo.http import request from odoo.addons.sale.controllers.variant import VariantController class WebsiteSaleVariantController(VariantController): @http.route( ["/sale/get_info_assortment_preview"], type="json", auth="public", methods=["POST"], website=True, ) def get_info_assortment_preview(self, product_template_ids, **kw): """Special route to use website logic in get_combination_info override. This route is called in JS by appending _website to the base route. """ res = [] templates = request.env["product.template"].sudo().browse(product_template_ids) not_allowed_product_dict = templates.get_product_assortment_restriction_info( templates.mapped("product_variant_ids.id") ) for template in templates: variant_ids = set(template.product_variant_ids.ids) if ( variant_ids and variant_ids & set(not_allowed_product_dict.keys()) == variant_ids ): res.append( { "id": template.id, "message_unavailable": not_allowed_product_dict[ variant_ids.pop() ][0].message_unavailable or _("Not available"), } ) return res
37.047619
1,556
1,053
py
PYTHON
15.0
# © 2016 Serpent Consulting Services Pvt. Ltd. (http://www.serpentcs.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Product Brand Filtering in Website", "category": "e-commerce", "author": "Serpent Consulting Services Pvt. Ltd., " "Tecnativa, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/e-commerce", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["product_brand", "website_sale"], "data": [ "security/ir.model.access.csv", "data/website_menu.xml", "views/product_brand.xml", "views/product_brand_views.xml", ], "demo": [ "demo/product_brand_demo.xml", "demo/product_product_demo.xml", ], "assets": { "web.assets_frontend": [ "/website_sale_product_brand/static/src/scss/website_sale_product_brand.scss" ], "web.assets_tests": [ "/website_sale_product_brand/static/src/js/tour.js", ], }, "installable": True, }
31.878788
1,052
315
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import odoo.tests @odoo.tests.tagged("post_install", "-at_install") class UICase(odoo.tests.HttpCase): def test_ui_website(self): """Test frontend tour.""" self.start_tour("/shop", "website_sale_product_brand", login="portal")
31.5
315
315
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class ProductBrand(models.Model): _name = "product.brand" _inherit = ["product.brand", "website.published.mixin"] is_published = fields.Boolean(default=True)
31.5
315
565
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class ProductTemplate(models.Model): _inherit = "product.template" @api.model def _search_get_detail(self, website, order, options): res = super()._search_get_detail(website, order, options) domain = res["base_domain"] brand_id = options.get("brand") if brand_id: domain.append([("product_brand_id", "=", brand_id)]) res["base_domain"] = domain return res
33.235294
565
3,046
py
PYTHON
15.0
# © 2016 Serpent Consulting Services Pvt. Ltd. (http://www.serpentcs.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import http from odoo.http import request from odoo.osv import expression from odoo.addons.website_sale.controllers.main import QueryURL, WebsiteSale class WebsiteSale(WebsiteSale): def _get_search_options( self, category=None, attrib_values=None, pricelist=None, min_price=0.0, max_price=0.0, conversion_rate=1, **post ): res = super()._get_search_options( category=category, attrib_values=attrib_values, pricelist=pricelist, min_price=min_price, max_price=max_price, conversion_rate=conversion_rate, **post ) res["brand"] = request.context.get("brand_id") return res def _get_search_domain( self, search, category, attrib_values, search_in_description=True ): domain = super()._get_search_domain( search, category, attrib_values, search_in_description=search_in_description ) if "brand_id" in request.context: domain = expression.AND( [domain, [("product_brand_id", "=", request.context["brand_id"])]] ) return domain @http.route( [ "/shop", "/shop/page/<int:page>", '/shop/category/<model("product.public.category"):category>', '/shop/category/<model("product.public.category"):category' ">/page/<int:page>", # Continue previous line "/shop/brands", ], type="http", auth="public", website=True, ) def shop( self, page=0, category=None, search="", min_price=0.0, max_price=0.0, ppg=False, brand=None, **post ): if brand: context = dict(request.context) context.setdefault("brand_id", int(brand)) request.context = context return super().shop( page=page, category=category, search=search, min_price=min_price, max_price=max_price, ppg=ppg, brand=brand, **post ) # Method to get the brands. @http.route(["/page/product_brands"], type="http", auth="public", website=True) def product_brands(self, **post): b_obj = request.env["product.brand"] domain = [("website_published", "=", True)] if post.get("search"): domain += [("name", "ilike", post.get("search"))] brand_rec = b_obj.sudo().search(domain) keep = QueryURL("/page/product_brands", brand_id=[]) values = {"brand_rec": brand_rec, "keep": keep} if post.get("search"): values.update({"search": post.get("search")}) return request.render("website_sale_product_brand.product_brands", values)
31.071429
3,045
527
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Barcodes GS1", "summary": "It provides read GS1 barcode on stock operations.", "version": "15.0.1.0.0", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "license": "AGPL-3", "category": "Extra Tools", "depends": ["stock_barcodes", "base_gs1_barcode"], "installable": True, }
40.538462
527
1,329
py
PYTHON
15.0
# Copyright 2108-2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from .test_stock_barcodes_gs1 import TestStockBarcodesGS1 @common.tagged("post_install", "-at_install") class TestStockBarcodesNewLotGS1(TestStockBarcodesGS1): def setUp(self): super().setUp() self.ScanReadLot = self.env["wiz.stock.barcodes.new.lot"] self.wiz_scan_lot = self.ScanReadLot.new() self.gs1_barcode_02_10 = "02174512345678911718112510AAA2701370150" def test_new_lot_gs1_package(self): self.action_barcode_scanned(self.wiz_scan_lot, self.gs1_barcode_01) self.assertEqual(self.wiz_scan_lot.product_id, self.product_wo_tracking_gs1) self.assertEqual(self.wiz_scan_lot.lot_name, "AB-123") def test_new_lot_gs1_product(self): self.product_tracking_gs1.barcode = "17451234567891" self.action_barcode_scanned(self.wiz_scan_lot, self.gs1_barcode_02_10) self.assertEqual(self.wiz_scan_lot.product_id, self.product_tracking_gs1) self.assertEqual(self.wiz_scan_lot.lot_name, "AAA2701370150") def test_new_lot_gs1_no_lot(self): self.action_barcode_scanned(self.wiz_scan_lot, self.gs1_barcode_02) self.assertFalse(self.wiz_scan_lot.product_id)
45.827586
1,329
7,133
py
PYTHON
15.0
# Copyright 2108-2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.addons.stock_barcodes.tests.test_stock_barcodes import TestStockBarcodes @common.tagged("post_install", "-at_install") class TestStockBarcodesGS1(TestStockBarcodes): # pylint: disable=W8121 def setUp(self): super().setUp() # Barcode for packaging and lot self.gs1_barcode_01_product = "0119501101530000" self.gs1_barcode_01_lot = "1714070410AB-123" self.gs1_separator = self.env.user.gs1_barcode_separator or "\x1D" self.gs1_barcode_unit_01 = self.gs1_separator + "371" self.gs1_barcode_unit_02 = self.gs1_separator + "372" self.gs1_barcode_01 = self.gs1_barcode_01_product + self.gs1_barcode_01_lot self.gs1_barcode_01_not_found = "011xxx11015300001714070410AB-123" self.gs1_barcode_01_not_lot = "01195011015300001714070410AB-124" # Barcode for product and quantities self.gs1_barcode_02 = "0207010001234567150410183724" self.gs1_barcode_02_not_found = "020xxx0001234567150410183724" # Barcode not processed self.gs1_barcode_01_not_processed = ( "01993167101234533101002620130" "5041710ABC123214145354" ) self.product_wo_tracking_gs1 = self.product_wo_tracking.with_context({}).copy( {"barcode": "07010001234567"} ) self.product_tracking_gs1 = self.product_tracking.with_context({}).copy() self.packaging_gs1 = self.ProductPackaging.create( { "product_id": self.product_wo_tracking_gs1.id, "name": "Box 10 Units", "qty": 10.0, "barcode": "19501101530000", } ) # Set location to avoid crash tests self.wiz_scan.location_id = self.location_1 def test_wizard_scan_gs1_package_multi(self): self.packaging_gs1.product_id = self.product_tracking_gs1 lot = self.StockProductionLot.create( { "name": "AB-123", "product_id": self.product_tracking_gs1.id, "company_id": self.company.id, } ) self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01_product) self.assertEqual(self.wiz_scan.product_id, self.product_tracking_gs1) self.assertEqual(self.wiz_scan.packaging_id, self.packaging_gs1) self.assertFalse(self.wiz_scan.lot_id) self.assertEqual(self.wiz_scan.packaging_qty, 1) self.assertEqual(self.wiz_scan.product_qty, 10) self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01_lot) self.assertEqual(self.wiz_scan.product_id, self.product_tracking_gs1) self.assertEqual(self.wiz_scan.packaging_id, self.packaging_gs1) self.assertEqual(self.wiz_scan.lot_id, lot) self.assertEqual(self.wiz_scan.packaging_qty, 1) self.assertEqual(self.wiz_scan.product_qty, 10) def test_wizard_scan_gs1_package(self): self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01) self.assertEqual(self.wiz_scan.packaging_id, self.packaging_gs1) # Scan no exist packaging self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01_not_found) self.assertEqual( self.wiz_scan.message, "011xxx11015300001714070410AB-123 " "(Barcode for product packaging not found)", ) # Scan packaging barcode with more than one package self.packaging_gs1.with_context({}).copy({"barcode": "19501101530000"}) self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01) self.assertEqual( self.wiz_scan.message, "01195011015300001714070410AB-123 " "(More than one package found)", ) def test_wizard_scan_gs1_package_units(self): self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01) self.assertEqual(self.wiz_scan.packaging_id, self.packaging_gs1) self.assertEqual(self.wiz_scan.product_qty, 10) self.action_barcode_scanned( self.wiz_scan, self.gs1_barcode_01 + self.gs1_barcode_unit_01 ) self.assertEqual(self.wiz_scan.packaging_id, self.packaging_gs1) self.assertEqual(self.wiz_scan.product_qty, 10) self.action_barcode_scanned( self.wiz_scan, self.gs1_barcode_01 + self.gs1_barcode_unit_02 ) self.assertEqual(self.wiz_scan.packaging_id, self.packaging_gs1) self.assertEqual(self.wiz_scan.product_qty, 20) def test_wizard_scan_gs1_product(self): self.wiz_scan.location_id = self.location_1 self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_02) self.assertEqual(self.wiz_scan.product_id, self.product_wo_tracking_gs1) self.assertEqual(self.wiz_scan.product_qty, 24) # Scan non exists product self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_02_not_found) self.assertEqual( self.wiz_scan.message, "020xxx0001234567150410183724 (Barcode for product packaging not found)", ) def test_wizard_scan_gs1_product_as_packaging(self): self.product_wo_tracking_gs1.barcode = "X07010001234567Xg" self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_02) self.assertEqual( self.wiz_scan.message, "0207010001234567150410183724 " "(Barcode for product packaging not found)", ) self.ProductPackaging.create( { "product_id": self.product_wo_tracking_gs1.id, "name": "Barcode as package", "qty": 2.0, "barcode": "07010001234567", } ) self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_02) self.assertEqual(self.wiz_scan.product_id, self.product_wo_tracking_gs1) self.assertEqual(self.wiz_scan.product_qty, 48) def test_wizard_scan_gs1_lot(self): self.packaging_gs1.product_id = self.product_tracking_gs1 lot = self.StockProductionLot.create( { "name": "AB-123", "product_id": self.product_tracking_gs1.id, "company_id": self.company.id, } ) self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01) self.assertEqual(self.wiz_scan.lot_id, lot) self.assertEqual( self.wiz_scan.message, "01195011015300001714070410AB-123 " "(Barcode read correctly)", ) self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01_not_lot) self.assertEqual(self.wiz_scan.lot_id.name, "AB-124") def test_wizard_scan_gs1_not_found(self): self.action_barcode_scanned(self.wiz_scan, self.gs1_barcode_01_not_processed) self.assertEqual( self.wiz_scan.message, "0199316710123453310100262013050417" "10ABC123214145354 (Barcode for product packaging " "not found)", )
45.724359
7,133
4,708
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, models class WizStockBarcodesRead(models.AbstractModel): _inherit = "wiz.stock.barcodes.read" def _prepare_lot_values(self, barcode_decoded): lot_barcode = barcode_decoded.get("10", False) return { "name": lot_barcode, "product_id": self.product_id.id, "company_id": self.env.company.id, } def _create_lot(self, barcode_decoded): return self.env["stock.production.lot"].create( self._prepare_lot_values(barcode_decoded) ) def process_lot(self, barcode_decoded): lot_barcode = barcode_decoded.get("10", False) lot = self.env["stock.production.lot"].search( [("name", "=", lot_barcode), ("product_id", "=", self.product_id.id)] ) if not lot and self.option_group_id.create_lot: lot = self._create_lot(barcode_decoded) self.lot_id = lot def _process_product_qty_gs1(self, product_qty): """Extend for custom processing of product qty.""" return product_qty def process_barcode_package(self, package_barcode, processed): packaging = self.env["product.packaging"].search( self._barcode_domain(package_barcode) ) if not packaging: self._set_messagge_info( "not_found", _("Barcode for product packaging not found") ) return False else: if len(packaging) > 1: self._set_messagge_info("more_match", _("More than one package found")) return False self.action_packaging_scaned_post(packaging) def process_barcode(self, barcode): """Only has been implemented AI (01, 02, 10, 37), so is possible that scanner reads a barcode ok but this one is not precessed. """ try: barcode_decoded = self.env["gs1_barcode"].decode(barcode) except Exception: return super().process_barcode(barcode) processed = False package_barcode = barcode_decoded.get("01", False) product_barcode = barcode_decoded.get("02", False) if not product_barcode: # Sometimes the product does not yet have a GTIN. In this case # try the AI 240 'Additional product identification assigned # by the manufacturer'. product_barcode = barcode_decoded.get("240", False) lot_barcode = barcode_decoded.get("10", False) product_qty = barcode_decoded.get("37", False) if product_barcode: product = self.env["product.product"].search( self._barcode_domain(product_barcode) ) if not product and not package_barcode: # If we did not found a product and we have not a package, maybe we # can try to use this product barcode as a packaging barcode package_barcode = product_barcode elif not product: self._set_messagge_info("not_found", _("Barcode for product not found")) return False else: processed = True self.action_product_scaned_post(product) if package_barcode: value_returned = self.process_barcode_package(package_barcode, processed) if value_returned is not None: return value_returned if lot_barcode and self.product_id.tracking != "none": self.process_lot(barcode_decoded) processed = True if product_qty and package_barcode: # If we have processed a package, we need to multiply it product_qty = self._process_product_qty_gs1(product_qty) self.product_qty = self.product_qty * product_qty elif product_qty: product_qty = self._process_product_qty_gs1(product_qty) self.product_qty = product_qty if not self.product_qty: # This could happen with double GS1-128 barcodes if self.packaging_id: self.packaging_qty = 0.0 if self.manual_entry else 1.0 self.product_qty = self.packaging_id.qty * self.packaging_qty else: self.product_qty = 0.0 if self.manual_entry else 1.0 if processed: if not self.check_option_required(): return False self.action_confirm() self._set_messagge_info("success", _("Barcode read correctly")) return True return super().process_barcode(barcode)
43.192661
4,708
1,607
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class WizStockBarcodesNewLot(models.TransientModel): _inherit = "wiz.stock.barcodes.new.lot" _description = "Wizard to create new lot from barcode scanner" def _decode_barcode(self, barcode): return self.env["gs1_barcode"].decode(barcode) def on_barcode_scanned(self, barcode): try: barcode_decoded = self._decode_barcode(barcode) except Exception: return super().on_barcode_scanned(barcode) package_barcode = barcode_decoded.get("01", False) product_barcode = barcode_decoded.get("02", False) if not product_barcode: # Sometimes the product does not yet have a GTIN. In this case # try the AI 240 'Additional product identification assigned # by the manufacturer'. product_barcode = barcode_decoded.get("240", False) lot_barcode = barcode_decoded.get("10", False) if not lot_barcode: return if package_barcode: packaging = self.env["product.packaging"].search( [("barcode", "=", package_barcode)] ) if packaging: self.product_id = packaging.product_id elif product_barcode: product = self.env["product.product"].search( [("barcode", "=", product_barcode)] ) if product: self.product_id = product self.lot_name = lot_barcode
40.175
1,607
525
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import tools def pre_init_hook(cr): if not tools.column_exists(cr, "stock_move_line", "barcode_scan_state"): cr.execute( """ ALTER TABLE stock_move_line ADD COLUMN barcode_scan_state varchar""" ) cr.execute( """ UPDATE stock_move_line sml SET barcode_scan_state = 'pending' """ )
29.166667
525
1,663
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Barcodes", "summary": "It provides read barcode on stock operations.", "version": "15.0.1.2.2", "author": "Tecnativa, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "license": "AGPL-3", "category": "Extra Tools", "depends": ["barcodes", "stock", "web_widget_numeric_step"], "data": [ "security/ir.model.access.csv", "data/stock_barcodes_action.xml", "data/stock_barcodes_option.xml", "views/stock_barcodes_action_view.xml", "views/stock_barcodes_option_view.xml", "views/stock_location_views.xml", "views/stock_picking_views.xml", "wizard/stock_production_lot_views.xml", "wizard/stock_barcodes_read_views.xml", "wizard/stock_barcodes_read_picking_views.xml", "wizard/stock_barcodes_read_todo_view.xml", # Keep order "views/stock_barcodes_menu.xml", ], "assets": { "web.assets_backend": [ "/stock_barcodes/static/src/js/barcodes_models_mixin.js", "/stock_barcodes/static/src/js/basic_controller.js", "/stock_barcodes/static/src/js/kanban_renderer.js", "/stock_barcodes/static/src/js/basic_fields.js", "/stock_barcodes/static/src/js/form_view.js", "/stock_barcodes/static/src/js/numeric_step.js", "/stock_barcodes/static/src/css/stock.scss", ], }, "installable": True, "pre_init_hook": "pre_init_hook", }
41.575
1,663
400
py
PYTHON
15.0
# Copyright 2023 ForgeFlow <http://www.forgeflow.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade def delete_fk_constraints(env): # delete obsolete model references openupgrade.remove_tables_fks(env.cr, ["wiz_stock_barcodes_read_inventory"]) @openupgrade.migrate() def migrate(env, version): delete_fk_constraints(env)
28.571429
400
1,041
py
PYTHON
15.0
# Copyright 2108-2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import tagged from .test_stock_barcodes_picking import TestStockBarcodesPicking @tagged("post_install", "-at_install") class TestStockBarcodesNewLot(TestStockBarcodesPicking): def setUp(self): super().setUp() self.ScanReadLot = self.env["wiz.stock.barcodes.new.lot"] self.wiz_scan_lot = self.ScanReadLot.new() def test_new_lot(self): self.action_barcode_scanned(self.wiz_scan_lot, "8433281006850") self.assertEqual(self.wiz_scan_lot.product_id, self.product_tracking) self.action_barcode_scanned(self.wiz_scan_lot, "8433281xy6850") self.assertEqual(self.wiz_scan_lot.lot_name, "8433281xy6850") self.wiz_scan_lot.with_context( active_model=self.wiz_scan._name, active_id=self.wiz_scan.id, ).confirm() self.assertEqual(self.wiz_scan_lot.lot_name, self.wiz_scan.lot_id.name)
43.375
1,041
19,330
py
PYTHON
15.0
# Copyright 2108-2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import tagged from .test_stock_barcodes import TestStockBarcodes @tagged("post_install", "-at_install") class TestStockBarcodesPicking(TestStockBarcodes): def setUp(self): super().setUp() self.ScanReadPicking = self.env["wiz.stock.barcodes.read.picking"] self.stock_picking_model = self.env.ref("stock.model_stock_picking") # Model Data self.barcode_option_group_out = self._create_barcode_option_group_outgoing() self.barcode_option_group_in = self._create_barcode_option_group_incoming() self.barcode_option_group_out.show_scan_log = True self.barcode_option_group_in.show_scan_log = True self.barcode_option_group_out.barcode_guided_mode = False self.barcode_option_group_in.barcode_guided_mode = False self.partner_agrolite = self.env.ref("base.res_partner_2") self.picking_type_in = self.env.ref("stock.picking_type_in") self.picking_type_in.barcode_option_group_id = self.barcode_option_group_in self.picking_type_out = self.env.ref("stock.picking_type_out") self.picking_type_out.reservation_method = "manual" self.picking_type_out.barcode_option_group_id = self.barcode_option_group_out self.supplier_location = self.env.ref("stock.stock_location_suppliers") self.customer_location = self.env.ref("stock.stock_location_customers") self.stock_location = self.env.ref("stock.stock_location_stock") self.categ_unit = self.env.ref("uom.product_uom_categ_unit") self.categ_kgm = self.env.ref("uom.product_uom_categ_kgm") self.picking_out_01 = ( self.env["stock.picking"] .with_context(planned_picking=True) .create( { "location_id": self.stock_location.id, "location_dest_id": self.customer_location.id, "partner_id": self.partner_agrolite.id, "picking_type_id": self.picking_type_out.id, "move_lines": [ ( 0, 0, { "name": self.product_tracking.name, "product_id": self.product_tracking.id, "product_uom_qty": 3, "product_uom": self.product_tracking.uom_id.id, "location_id": self.stock_location.id, "location_dest_id": self.customer_location.id, }, ) ], } ) ) self.picking_out_02 = self.picking_out_01.copy() self.picking_in_01 = ( self.env["stock.picking"] .with_context(planned_picking=True) .create( { "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, "partner_id": self.partner_agrolite.id, "picking_type_id": self.picking_type_in.id, "move_lines": [ ( 0, 0, { "name": self.product_wo_tracking.name, "product_id": self.product_wo_tracking.id, "product_uom_qty": 3, "product_uom": self.product_wo_tracking.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, }, ), ( 0, 0, { "name": self.product_wo_tracking.name, "product_id": self.product_wo_tracking.id, "product_uom_qty": 5, "product_uom": self.product_wo_tracking.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, }, ), ( 0, 0, { "name": self.product_tracking.name, "product_id": self.product_tracking.id, "product_uom_qty": 3, "product_uom": self.product_tracking.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, }, ), ( 0, 0, { "name": self.product_tracking.name, "product_id": self.product_tracking.id, "product_uom_qty": 5, "product_uom": self.product_tracking.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, }, ), ], } ) ) self.picking_in_01.action_confirm() action = self.picking_in_01.action_barcode_scan() self.wiz_scan_picking = self.ScanReadPicking.browse(action["res_id"]) # Create a wizard for outgoing picking self.picking_out_01.action_confirm() action = self.picking_out_01.action_barcode_scan() self.wiz_scan_picking_out = self.ScanReadPicking.browse(action["res_id"]) def test_wiz_picking_values(self): self.assertEqual( self.wiz_scan_picking.location_id, self.picking_in_01.location_id ) self.assertEqual(self.wiz_scan_picking.res_model_id, self.stock_picking_model) self.assertEqual(self.wiz_scan_picking.res_id, self.picking_in_01.id) self.assertIn( "Barcode reader - %s - " % (self.picking_in_01.name), self.wiz_scan_picking.display_name, ) def test_picking_wizard_scan_product(self): wiz_scan_picking = self.wiz_scan_picking.with_context(force_create_move=True) self.action_barcode_scanned(wiz_scan_picking, "8480000723208") sml = self.picking_in_01.move_line_ids.filtered( lambda x: x.product_id == self.product_wo_tracking ) self.assertEqual(sml.qty_done, 1.0) # Scan product with tracking lot enable self.action_barcode_scanned(wiz_scan_picking, "8433281006850") sml = self.picking_in_01.move_line_ids.filtered( lambda x: x.product_id == self.product_tracking ) self.assertEqual(sml.qty_done, 0.0) self.assertEqual( self.wiz_scan_picking.message, "8433281006850 (Scan Product, Packaging, Lot / Serial)", ) # Scan a lot. Increment quantities if scan product or other lot from # this product self.action_barcode_scanned(wiz_scan_picking, "8411822222568") sml = self.picking_in_01.move_line_ids.filtered( lambda x: x.product_id == self.product_tracking and x.lot_id ) self.assertEqual(sml.lot_id, self.lot_1) self.assertEqual(sml.qty_done, 1.0) self.action_barcode_scanned(wiz_scan_picking, "8433281006850") stock_move = sml.move_id self.assertEqual(sum(stock_move.move_line_ids.mapped("qty_done")), 2.0) self.action_barcode_scanned(wiz_scan_picking, "8411822222568") self.assertEqual(sum(stock_move.move_line_ids.mapped("qty_done")), 3.0) self.assertEqual( self.wiz_scan_picking.message, "8411822222568 (Scan Product, Packaging, Lot / Serial)", ) # Scan a package self.action_barcode_scanned(wiz_scan_picking, "5420008510489") # Package of 5 product units. Already three unit exists self.assertEqual(sum(stock_move.move_line_ids.mapped("qty_done")), 8.0) def test_picking_wizard_scan_product_manual_entry(self): wiz_scan_picking = self.wiz_scan_picking.with_context(force_create_move=True) wiz_scan_picking.manual_entry = True self.action_barcode_scanned(wiz_scan_picking, "8480000723208") sml = self.picking_in_01.move_line_ids.filtered( lambda x: x.product_id == self.product_wo_tracking ) self.assertEqual(wiz_scan_picking.product_qty, 0.0) wiz_scan_picking.product_qty = 12.0 wiz_scan_picking.action_confirm() self.assertEqual(sml.qty_done, 12.0) def test_barcode_from_operation(self): picking_out_3 = self.picking_out_01.copy() self.picking_out_01.action_assign() self.picking_out_02.action_assign() self.picking_type_out.default_location_dest_id = self.customer_location action = self.picking_type_out.action_barcode_scan() self.wiz_scan_picking = self.ScanReadPicking.browse(action["res_id"]) self.wiz_scan_picking.manual_entry = True self.wiz_scan_picking.product_id = self.product_tracking self.wiz_scan_picking.lot_id = self.lot_1 self.wiz_scan_picking.product_qty = 2 self.wiz_scan_picking.with_context(force_create_move=True).action_confirm() self.assertEqual(len(self.wiz_scan_picking.candidate_picking_ids), 2) # Lock first picking candidate = self.wiz_scan_picking.candidate_picking_ids.filtered( lambda c: c.picking_id == self.picking_out_01 ) candidate_wiz = candidate.with_context( wiz_barcode_id=self.wiz_scan_picking.id, picking_id=self.picking_out_01.id ) candidate_wiz.with_context(force_create_move=True).action_lock_picking() self.assertEqual(self.picking_out_01.move_lines.quantity_done, 2) self.wiz_scan_picking.product_qty = 2 self.wiz_scan_picking.with_context(force_create_move=True).action_confirm() self.assertEqual(self.picking_out_01.move_lines.quantity_done, 4) # Picking out 3 is in confirmed state, so until confirmed moves has # not been activated candidate pickings is 2 picking_out_3.action_confirm() candidate_wiz.action_unlock_picking() self.wiz_scan_picking.product_qty = 2 self.wiz_scan_picking.with_context(force_create_move=True).action_confirm() self.assertEqual(len(self.wiz_scan_picking.candidate_picking_ids), 2) candidate_wiz.action_unlock_picking() self.wiz_scan_picking.product_qty = 2 self.wiz_scan_picking.option_group_id.confirmed_moves = True self.wiz_scan_picking.with_context(force_create_move=True).action_confirm() self.assertEqual(len(self.wiz_scan_picking.candidate_picking_ids), 3) def test_picking_wizard_scan_product_auto_lot(self): # Prepare more data lot_2 = self.StockProductionLot.create( { "name": "8411822222578", "product_id": self.product_tracking.id, "company_id": self.company.id, } ) lot_3 = self.StockProductionLot.create( { "name": "8411822222588", "product_id": self.product_tracking.id, "company_id": self.company.id, } ) quant_lot_2 = self.StockQuant.create( { "product_id": self.product_tracking.id, "lot_id": lot_2.id, "location_id": self.stock_location.id, "quantity": 15.0, } ) quant_lot_3 = self.StockQuant.create( { "product_id": self.product_tracking.id, "lot_id": lot_3.id, "location_id": self.stock_location.id, "quantity": 10.0, } ) self.quant_lot_1.in_date = "2021-01-01" quant_lot_2.in_date = "2021-01-05" quant_lot_3.in_date = "2021-01-06" # Scan product with tracking lot enable self.action_barcode_scanned(self.wiz_scan_picking, "8433281006850") self.assertEqual( self.wiz_scan_picking.message, "8433281006850 (Scan Product, Packaging, Lot / Serial)", ) self.wiz_scan_picking.auto_lot = True # self.wiz_scan_picking.manual_entry = True # Removal strategy FIFO # No auto lot for incoming pickings self.action_barcode_scanned(self.wiz_scan_picking, "8433281006850") self.assertFalse(self.wiz_scan_picking.lot_id) # Continue test with a outgoing wizard self.wiz_scan_picking_out.option_group_id.auto_lot = True self.action_barcode_scanned(self.wiz_scan_picking_out, "8433281006850") self.assertEqual(self.wiz_scan_picking_out.lot_id, self.lot_1) # Removal strategy LIFO self.wiz_scan_picking_out.lot_id = False self.product_tracking.categ_id.removal_strategy_id = self.env.ref( "stock.removal_lifo" ) self.action_barcode_scanned(self.wiz_scan_picking_out, "8433281006850") self.assertEqual(self.wiz_scan_picking_out.lot_id, lot_3) def _create_barcode_option_group_incoming(self): return self.env["stock.barcodes.option.group"].create( { "name": "option group incoming for tests", "option_ids": [ ( 0, 0, { "step": 1, "name": "Location", "field_name": "location_id", "filled_default": True, "to_scan": False, "required": True, }, ), ( 0, 0, { "step": 2, "name": "Product", "field_name": "product_id", "to_scan": True, "required": True, "clean_after_done": True, }, ), ( 0, 0, { "step": 2, "name": "Packaging", "field_name": "packaging_id", "to_scan": True, "required": False, }, ), ( 0, 0, { "step": 2, "name": "Lot / Serial", "field_name": "lot_id", "to_scan": True, "required": True, }, ), ( 0, 0, { "step": 3, "name": "Location Dest", "field_name": "location_dest_id", "filled_default": True, "to_scan": False, "required": True, }, ), ( 0, 0, { "step": 4, "name": "Quantity", "field_name": "product_qty", "required": True, "clean_after_done": True, }, ), ], } ) def _create_barcode_option_group_outgoing(self): return self.env["stock.barcodes.option.group"].create( { "name": "option group outgoing for tests", "option_ids": [ ( 0, 0, { "step": 1, "name": "Location", "field_name": "location_id", "to_scan": True, "required": True, "filled_default": True, }, ), ( 0, 0, { "step": 2, "name": "Product", "field_name": "product_id", "to_scan": True, "required": True, }, ), ( 0, 0, { "step": 2, "name": "Packaging", "field_name": "packaging_id", "to_scan": True, "required": False, }, ), ( 0, 0, { "step": 2, "name": "Lot / Serial", "field_name": "lot_id", "to_scan": True, "required": True, }, ), ( 0, 0, { "step": 3, "name": "Location Dest", "field_name": "location_dest_id", "filled_default": True, "to_scan": False, "required": True, }, ), ( 0, 0, { "step": 4, "name": "Quantity", "field_name": "product_qty", "required": True, "clean_after_done": True, }, ), ], } )
42.765487
19,330
9,194
py
PYTHON
15.0
# Copyright 2108-2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestStockBarcodes(TransactionCase): def setUp(self): super().setUp() # Active group_stock_packaging and group_production_lot for user group_stock_packaging = self.env.ref("product.group_stock_packaging") group_production_lot = self.env.ref("stock.group_production_lot") self.env.user.groups_id = [ (4, group_stock_packaging.id), (4, group_production_lot.id), ] # models self.StockLocation = self.env["stock.location"] self.Product = self.env["product.product"] self.ProductPackaging = self.env["product.packaging"] self.WizScanReadPicking = self.env["wiz.stock.barcodes.read.picking"] self.StockProductionLot = self.env["stock.production.lot"] self.StockPicking = self.env["stock.picking"] self.StockQuant = self.env["stock.quant"] self.company = self.env.company # Option groups for test self.option_group = self._create_barcode_option_group() # warehouse and locations self.warehouse = self.env.ref("stock.warehouse0") self.stock_location = self.env.ref("stock.stock_location_stock") self.location_1 = self.StockLocation.create( { "name": "Test location 1", "usage": "internal", "location_id": self.stock_location.id, "barcode": "8411322222568", } ) self.location_2 = self.StockLocation.create( { "name": "Test location 2", "usage": "internal", "location_id": self.stock_location.id, "barcode": "8470001809032", } ) # products self.product_wo_tracking = self.Product.create( { "name": "Product test wo lot tracking", "type": "product", "tracking": "none", "barcode": "8480000723208", "packaging_ids": [ ( 0, 0, { "name": "Box 10 Units", "qty": 10.0, "barcode": "5099206074439", }, ) ], } ) self.product_tracking = self.Product.create( { "name": "Product test with lot tracking", "type": "product", "tracking": "lot", "barcode": "8433281006850", "packaging_ids": [ ( 0, 0, {"name": "Box 5 Units", "qty": 5.0, "barcode": "5420008510489"}, ) ], } ) self.lot_1 = self.StockProductionLot.create( { "name": "8411822222568", "product_id": self.product_tracking.id, "company_id": self.company.id, } ) self.quant_lot_1 = self.StockQuant.create( { "product_id": self.product_tracking.id, "lot_id": self.lot_1.id, "location_id": self.stock_location.id, "quantity": 100.0, } ) self.wiz_scan = self.WizScanReadPicking.create( {"option_group_id": self.option_group.id, "step": 1} ) def _create_barcode_option_group(self): return self.env["stock.barcodes.option.group"].create( { "name": "option group for tests", "show_scan_log": True, "create_lot": True, "option_ids": [ ( 0, 0, { "step": 1, "name": "Location", "field_name": "location_id", "to_scan": True, "required": True, }, ), ( 0, 0, { "step": 2, "name": "Product", "field_name": "product_id", "to_scan": True, "required": True, }, ), ( 0, 0, { "step": 2, "name": "Packaging", "field_name": "packaging_id", "to_scan": True, "required": False, }, ), ( 0, 0, { "step": 2, "name": "Lot / Serial", "field_name": "lot_id", "to_scan": True, "required": True, }, ), ], } ) def action_barcode_scanned(self, wizard, barcode): wizard._barcode_scanned = barcode wizard._on_barcode_scanned() def test_wizard_scan_location(self): self.action_barcode_scanned(self.wiz_scan, "8411322222568") self.assertEqual(self.wiz_scan.location_id, self.location_1) def test_wizard_scan_product(self): self.wiz_scan.location_id = self.location_1 self.wiz_scan.action_show_step() self.action_barcode_scanned(self.wiz_scan, "8480000723208") self.assertEqual(self.wiz_scan.product_id, self.product_wo_tracking) self.assertEqual(self.wiz_scan.product_qty, 1.0) def test_wizard_scan_product_manual_entry(self): # Test manual entry self.wiz_scan.manual_entry = True self.wiz_scan.location_id = self.location_1 self.wiz_scan.action_show_step() self.action_barcode_scanned(self.wiz_scan, "8480000723208") self.assertEqual(self.wiz_scan.product_qty, 0.0) self.wiz_scan.product_qty = 50.0 def test_wizard_scan_package(self): self.wiz_scan.location_id = self.location_1 self.wiz_scan.action_show_step() self.action_barcode_scanned(self.wiz_scan, "5420008510489") self.assertEqual(self.wiz_scan.product_id, self.product_tracking) self.assertEqual(self.wiz_scan.product_qty, 5.0) self.assertEqual( self.wiz_scan.packaging_id, self.product_tracking.packaging_ids ) # Manual entry self.wiz_scan.manual_entry = True self.action_barcode_scanned(self.wiz_scan, "5420008510489") self.assertEqual(self.wiz_scan.packaging_qty, 0.0) self.wiz_scan.packaging_qty = 3.0 self.wiz_scan.onchange_packaging_qty() self.assertEqual(self.wiz_scan.product_qty, 15.0) self.wiz_scan.manual_entry = False # Force more than one package with the same lot self.product_wo_tracking.packaging_ids.barcode = "5420008510489" self.action_barcode_scanned(self.wiz_scan, "5420008510489") self.assertEqual( self.wiz_scan.message, "5420008510489 (More than one package found)", ) def test_wizard_scan_lot(self): self.wiz_scan.location_id = self.location_1.id self.wiz_scan.action_show_step() self.action_barcode_scanned(self.wiz_scan, "8411822222568") # Lot found for one product, so product_id is filled self.assertTrue(self.wiz_scan.product_id) self.action_barcode_scanned(self.wiz_scan, "8433281006850") self.action_barcode_scanned(self.wiz_scan, "8411822222568") self.assertEqual(self.wiz_scan.lot_id, self.lot_1) # After scan other product, set wizard lot to False self.action_barcode_scanned(self.wiz_scan, "8480000723208") self.assertFalse(self.wiz_scan.lot_id) def test_wizard_scan_not_found(self): self.action_barcode_scanned(self.wiz_scan, "84118xxx22568") self.assertEqual( self.wiz_scan.message, "84118xxx22568 (Barcode not found with this screen values)", ) def test_wizard_remove_last_scan(self): self.assertTrue(self.wiz_scan.action_undo_last_scan()) def test_wiz_clean_lot(self): self.wiz_scan.location_id = self.location_1.id self.wiz_scan.action_show_step() self.action_barcode_scanned(self.wiz_scan, "8433281006850") self.action_barcode_scanned(self.wiz_scan, "8411822222568") self.wiz_scan.action_clean_lot() self.assertFalse(self.wiz_scan.lot_id)
37.991736
9,194
27,154
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import _, api, fields, models _logger = logging.getLogger(__name__) class WizStockBarcodesRead(models.AbstractModel): _name = "wiz.stock.barcodes.read" _inherit = "barcodes.barcode_events_mixin" _description = "Wizard to read barcode" # To prevent remove the record wizard until 2 days old _transient_max_hours = 48 _allowed_product_types = ["product", "consu"] barcode = fields.Char() res_model_id = fields.Many2one(comodel_name="ir.model", index=True) res_id = fields.Integer(index=True) product_id = fields.Many2one( comodel_name="product.product", domain=[("type", "in", _allowed_product_types)] ) product_uom_id = fields.Many2one(comodel_name="uom.uom") product_tracking = fields.Selection(related="product_id.tracking", readonly=True) lot_id = fields.Many2one(comodel_name="stock.production.lot") location_id = fields.Many2one(comodel_name="stock.location") location_dest_id = fields.Many2one( comodel_name="stock.location", string="Location dest." ) packaging_id = fields.Many2one(comodel_name="product.packaging") product_packaging_ids = fields.One2many(related="product_id.packaging_ids") package_id = fields.Many2one(comodel_name="stock.quant.package") result_package_id = fields.Many2one(comodel_name="stock.quant.package") owner_id = fields.Many2one(comodel_name="res.partner") packaging_qty = fields.Float(string="Package Qty", digits="Product Unit of Measure") product_qty = fields.Float(digits="Product Unit of Measure") manual_entry = fields.Boolean(string="Manual", help="Entry manual data") confirmed_moves = fields.Boolean( string="Confirmed moves", related="option_group_id.confirmed_moves" ) # Computed field for display all scanning logs from res_model and res_id # when change product_id scan_log_ids = fields.Many2many( comodel_name="stock.barcodes.read.log", compute="_compute_scan_log_ids" ) message_type = fields.Selection( [ ("info", "Barcode read with additional info"), ("not_found", "No barcode found"), ("more_match", "More than one matches found"), ("success", "Barcode read correctly"), ], readonly=True, ) message = fields.Char(readonly=True) message_step = fields.Char(readonly=True) guided_product_id = fields.Many2one(comodel_name="product.product") guided_location_id = fields.Many2one(comodel_name="stock.location") guided_location_dest_id = fields.Many2one(comodel_name="stock.location") guided_lot_id = fields.Many2one(comodel_name="stock.production.lot") action_ids = fields.Many2many( comodel_name="stock.barcodes.action", compute="_compute_action_ids" ) option_group_id = fields.Many2one(comodel_name="stock.barcodes.option.group") visible_force_done = fields.Boolean() step = fields.Integer() is_manual_qty = fields.Boolean(compute="_compute_is_manual_qty") is_manual_confirm = fields.Boolean(compute="_compute_is_manual_qty") show_scan_log = fields.Boolean(compute="_compute_is_manual_qty") # Technical field to allow use in attrs display_menu = fields.Boolean() qty_available = fields.Float(compute="_compute_qty_available") auto_lot = fields.Boolean( string="Get lots automatically", help="If checked the lot will be set automatically with the same " "removal startegy", compute="_compute_auto_lot", store=True, readonly=False, ) display_assign_serial = fields.Boolean(compute="_compute_display_assign_serial") @api.depends("res_id") def _compute_action_ids(self): actions = self.env["stock.barcodes.action"].search([]) self.action_ids = actions @api.depends("option_group_id") def _compute_is_manual_qty(self): for rec in self: rec.is_manual_qty = rec.option_group_id.is_manual_qty rec.is_manual_confirm = rec.option_group_id.is_manual_confirm rec.auto_lot = rec.option_group_id.auto_lot rec.show_scan_log = rec.option_group_id.show_scan_log @api.depends("option_group_id") def _compute_auto_lot(self): for rec in self: rec.auto_lot = rec.option_group_id.auto_lot @api.depends("location_id", "product_id", "lot_id") def _compute_qty_available(self): if not self.product_id or self.location_id.usage != "internal": self.qty_available = 0.0 return domain_quant = [ ("product_id", "=", self.product_id.id), ("location_id", "=", self.location_id.id), ] if self.lot_id: domain_quant.append(("lot_id", "=", self.lot_id.id)) # if self.package_id: # domain_quant.append(('package_id', '=', self.package_id.id)) groups = self.env["stock.quant"].read_group( domain_quant, ["quantity"], [], orderby="id" ) self.qty_available = groups[0]["quantity"] @api.depends("product_id") def _compute_display_assign_serial(self): for rec in self: rec.display_assign_serial = rec.product_id.tracking == "serial" @api.onchange("packaging_qty") def onchange_packaging_qty(self): if self.packaging_id: self.product_qty = self.packaging_qty * self.packaging_id.qty def _set_messagge_info(self, message_type, message): """ Set message type and message description. For manual entry mode barcode is not set so is not displayed """ self.message_type = message_type # TODO: Uncomment this line when the tests of all modules have been adapted # if self.barcode and self.message_type in ["more_match", "not_found"]: if self.barcode: self.message = _( "%(barcode)s (%(message)s)", barcode=self.barcode, message=message ) else: self.message = "%s" % message def process_barcode_location_id(self): location = self.env["stock.location"].search(self._barcode_domain(self.barcode)) if location: self.location_id = location return True return False def process_barcode_location_dest_id(self): location = self.env["stock.location"].search(self._barcode_domain(self.barcode)) if location: self.location_dest_id = location return True return False def process_barcode_product_id(self): domain = self._barcode_domain(self.barcode) product = self.env["product.product"].search(domain) if product: if len(product) > 1: self._set_messagge_info("more_match", _("More than one product found")) return False elif product.type not in self._allowed_product_types: self._set_messagge_info( "not_found", _("The product type is not allowed") ) return False self.action_product_scaned_post(product) # self.action_done() return True return False def process_barcode_lot_id(self): if self.env.user.has_group("stock.group_production_lot"): lot_domain = [("name", "=", self.barcode)] if self.product_id: lot_domain.append(("product_id", "=", self.product_id.id)) lot = self.env["stock.production.lot"].search(lot_domain) if len(lot) == 1: if self.option_group_id.fill_fields_from_lot: quant_domain = [ ("lot_id.name", "=", self.barcode), ("quantity", ">", 0.0), ] if self.location_id: quant_domain.append(("location_id", "=", self.location_id.id)) else: quant_domain.append(("location_id.usage", "=", "internal")) if self.owner_id: quant_domain.append(("owner_id", "=", self.owner_id.id)) quants = self.env["stock.quant"].search(quant_domain) if ( not self._name == "wiz.stock.barcodes.read.inventory" and not quants and not self.option_group_id.allow_negative_quant ): self._set_messagge_info( "more_match", _("No stock available for this lot with screen values"), ) return False if quants: self.set_info_from_quants(quants) else: self.product_id = lot.product_id self.action_lot_scaned_post(lot) return True else: self.product_id = lot.product_id self.action_lot_scaned_post(lot) return True elif lot: self._set_messagge_info( "more_match", _("More than one lot found\nScan product before") ) elif ( self.product_id and self.product_id.tracking != "none" and self.option_group_id.create_lot ): new_lot = self._create_new_lot(self.barcode) self.action_lot_scaned_post(new_lot) return True return False def process_barcode_package_id(self): if not self.env.user.has_group("stock.group_tracking_lot"): return False quant_domain = [ ("package_id.name", "=", self.barcode), ("quantity", ">", 0.0), ] if self.location_id and self._name != "wiz.stock.barcodes.read.inventory": quant_domain.append(("location_id", "=", self.location_id.id)) else: quant_domain.append(("location_id.usage", "=", "internal")) if self.owner_id: quant_domain.append(("owner_id", "=", self.owner_id.id)) quants = self.env["stock.quant"].search(quant_domain) if not quants: # self._set_messagge_info("more_match", _("Package not fount or empty")) return False self.set_info_from_quants(quants) return True def process_barcode_result_package_id(self): if not self.env.user.has_group("stock.group_tracking_lot"): return False domain = [("name", "=", self.barcode)] package = self.env["stock.quant.package"].search(domain) if package: self.result_package_id = package[:1] return True return False def set_info_from_quants(self, quants): """ Fill wizard fields from stock quants """ if len(quants) == 1: # All ok self.action_product_scaned_post(quants.product_id) self.package_id = quants.package_id if quants.lot_id: self.action_lot_scaned_post(quants.lot_id) if quants.owner_id: self.owner_id = quants.owner_id # Review conditions if not self.location_id and self.option_group_id.code != "IN": self.location_id = quants.location_id if not self.is_manual_qty and self.option_group_id.code not in [ "OUT", "INV", ]: self.product_qty = quants.quantity elif len(quants) > 1: # More than one record found with same barcode. # Could be half lot in two distinct locations. # Empty location field to force a location barcode scan products = quants.mapped("product_id") if len(products) == 1: self.action_product_scaned_post(products[0]) packages = quants.mapped("package_id") if len(packages) == 1: self.package_id = packages lots = quants.mapped("lot_id") if len(lots) == 1: self.action_lot_scaned_post(lots[0]) owners = quants.mapped("owner_id") if len(owners) == 1: self.owner_id = owners locations = quants.mapped("location_id") if len(locations) == 1: if not self.location_id and self.option_group_id.code != "IN": self.location_id = locations def process_barcode_packaging_id(self): domain = self._barcode_domain(self.barcode) if self.env.user.has_group("product.group_stock_packaging"): packaging = self.env["product.packaging"].search(domain) if packaging: if len(packaging) > 1: self._set_messagge_info( "more_match", _("More than one package found") ) return False self.action_packaging_scaned_post(packaging) return True return False def process_barcode(self, barcode): self._set_messagge_info("success", _("OK")) options = self.option_group_id.option_ids barcode_found = False options_to_scan = options.filtered("to_scan") options_required = options.filtered("required") options_to_scan = options_to_scan.filtered(lambda op: op.step == self.step) for option in options_to_scan: if ( self.option_group_id.ignore_filled_fields and option in options_required and getattr(self, option.field_name, False) ): continue option_func = getattr(self, "process_barcode_%s" % option.field_name, False) if option_func: res = option_func() if option.required: self.play_sounds(res) if res: barcode_found = True break elif self.message_type != "success": return False if not barcode_found: if self.option_group_id.ignore_filled_fields: self._set_messagge_info( "info", _("Barcode not found or field already filled") ) else: self._set_messagge_info( "not_found", _("Barcode not found with this screen values") ) return False if not self.check_option_required(): return False if self.is_manual_confirm or self.manual_entry: self._set_messagge_info("info", _("Review and confirm")) return False return self.action_confirm() def check_option_required(self): options = self.option_group_id.option_ids options_required = options.filtered("required") for option in options_required: if not getattr(self, option.field_name, False): if self.is_manual_qty and option.field_name in [ "product_qty", "packaging_qty", ]: self._set_focus_on_qty_input("product_qty") if option.field_name == "lot_id" and ( self.product_id.tracking == "none" or self.auto_lot ): continue self._set_messagge_info("info", option.name) self.action_show_step() return False return True def _scanned_location(self, barcode): location = self.env["stock.location"].search(self._barcode_domain(barcode)) if location: self.location_id = location self._set_messagge_info("info", _("Waiting product")) return True else: return False def _barcode_domain(self, barcode): return [("barcode", "=", barcode)] def _clean_barcode_scanned(self, barcode): return barcode.rstrip() def on_barcode_scanned(self, barcode): self.barcode = self._clean_barcode_scanned(barcode) self.process_barcode(barcode) def check_location_contidion(self): if not self.location_id: self._set_messagge_info("info", _("Waiting location")) # Remove product when no location has been scanned self.product_id = False return False return True def check_lot_contidion(self): if self.product_id.tracking != "none" and not self.lot_id: self._set_messagge_info("info", _("Waiting lot")) return False return True def check_done_conditions(self): result_ok = self.check_location_contidion() if not result_ok: return False if not self.product_id: self._set_messagge_info("info", _("Waiting product")) return False result_ok = self.check_lot_contidion() if not result_ok: return False if not self.product_qty: self._set_messagge_info("info", _("Waiting quantities")) return False if ( self.option_group_id.barcode_guided_mode == "guided" and not self._check_guided_values() ): return False if self.manual_entry: self._set_messagge_info("success", _("Manual entry OK")) return True def _check_guided_values(self): if ( self.product_id != self.guided_product_id and self.option_group_id.get_option_value("product_id", "forced") ): self._set_messagge_info("more_match", _("Wrong product")) self.product_qty = 0.0 return False if ( self.guided_product_id.tracking != "none" and self.lot_id != self.guided_lot_id and self.option_group_id.get_option_value("lot_id", "forced") ): self._set_messagge_info("more_match", _("Wrong lot")) return False if ( self.location_id != self.guided_location_id and self.option_group_id.get_option_value("location_id", "forced") ): self._set_messagge_info("more_match", _("Wrong location")) return False if ( self.location_dest_id != self.guided_location_dest_id and self.option_group_id.get_option_value("location_dest_id", "forced") ): self._set_messagge_info("more_match", _("Wrong location dest")) return False return True def action_done(self): if not self.manual_entry and not self.product_qty and not self.is_manual_qty: self.product_qty = 1.0 if not self.check_done_conditions(): return False if not self.env.context.get("_stock_barcodes_skip_read_log"): _logger.info("Add scanned log barcode:{}".format(self.barcode)) self._add_read_log() return True def action_cancel(self): return True def action_product_scaned_post(self, product): self.package_id = False if self.product_id != product and self.lot_id.product_id != product: self.lot_id = False self.product_id = product self.product_uom_id = self.product_id.uom_id self.packaging_id = self.product_id.packaging_ids[:1] self.product_qty = 0.0 if self.manual_entry or self.is_manual_qty else 1.0 def action_packaging_scaned_post(self, packaging): self.packaging_id = packaging if ( self.product_id != packaging.product_id and self.lot_id.product_id != packaging.product_id ): self.lot_id = False self.product_id = packaging.product_id self.packaging_qty = 0.0 if self.manual_entry or self.is_manual_qty else 1.0 self.product_qty = packaging.qty * self.packaging_qty def action_lot_scaned_post(self, lot): self.lot_id = lot self.product_qty = 0.0 if self.manual_entry or self.is_manual_qty else 1.0 def action_clean_lot(self): self.lot_id = False self.action_show_step() def action_clean_product(self): self.product_id = False self.action_show_step() def action_clean_package(self): self.package_id = False self.result_package_id = False self.action_show_step() def action_create_package(self): self.result_package_id = self.env["stock.quant.package"].create({}) def action_clean_values(self): options = self.option_group_id.option_ids options_to_clean = options.filtered("clean_after_done") for option in options_to_clean: if option.field_name: setattr(self, option.field_name, False) self.action_show_step() # self.product_id = False # self.lot_id = False # self.packaging_id = False # self.package_id = False # self.result_package_id = False self.product_qty = 0.0 self.packaging_qty = 0.0 def action_manual_entry(self): return True def _prepare_scan_log_values(self, log_detail=False): return { "name": self.barcode, "location_id": self.location_id.id, "product_id": self.product_id.id, "packaging_id": self.packaging_id.id, "lot_id": self.lot_id.id, "packaging_qty": self.packaging_qty, "product_qty": self.product_qty, "manual_entry": self.manual_entry, "res_model_id": self.res_model_id.id, "res_id": self.res_id, } def _add_read_log(self, log_detail=False): if self.product_qty and not self.env.context.get("force_create_move", False): vals = self._prepare_scan_log_values(log_detail) self.env["stock.barcodes.read.log"].create(vals) @api.depends("product_id", "lot_id") def _compute_scan_log_ids(self): if self.option_group_id.show_scan_log: logs = self.env["stock.barcodes.read.log"].search( [ ("res_model_id", "=", self.res_model_id.id), ("res_id", "=", self.res_id), # ("location_id", "=", self.location_id.id), # ("product_id", "=", self.product_id.id), ], limit=10, ) self.scan_log_ids = logs else: self.scan_log_ids = False # TODO: To remove when stock_move_location uses action_clean_values def reset_qty(self): self.product_qty = 0 self.packaging_qty = 0 def action_undo_last_scan(self): return True def open_actions(self): self.display_menu = True def action_back(self): self.display_menu = False def open_records(self): action = self.action_ids return action def get_option_value(self, field_name, attribute): option = self.option_group_id.option_ids.filtered( lambda op: op.field_name == field_name )[:1] return option[attribute] def action_force_done(self): res = self.with_context(force_create_move=True).action_confirm() self.visible_force_done = False return res @api.model def create(self, vals): wiz = super().create(vals) wiz.action_show_step() return wiz def action_manual_quantity(self): action = self.get_formview_action() form_view = self.env.ref( "stock_barcodes.view_stock_barcodes_read_form_manual_qty" ) action["views"] = [(form_view.id, "form")] action["res_id"] = self.ids[0] return action def action_reopen_wizard(self): return self.get_formview_action() @api.onchange("step") def action_show_step(self): options_required = self.option_group_id.option_ids.filtered("required") self.step = 0 for option in options_required: if not getattr(self, option.field_name, False): if option.field_name == "lot_id" and self.product_id.tracking == "none": continue self.step = option.step break if not self.step: self.step = options_required[:1].step options = self.option_group_id.option_ids.filtered( lambda op: op.step == self.step and op.to_scan ) self._set_messagge_info( "info", _("Scan {}").format(", ".join(options.mapped("name"))) ) @api.onchange("package_id") def onchange_package_id(self): if self.manual_entry: self.barcode = self.package_id.name self.process_barcode_package_id() def action_confirm(self): if not self.check_option_required(): return False record = self.browse(self.ids) record.write(self._convert_to_write(self._cache)) self = record res = self.action_done() if res: self.action_clean_values() self.refresh() self.play_sounds(res) return res def play_sounds(self, res): if res: self.env["bus.bus"]._sendone( "stock_barcodes-{}".format(self.ids[0]), "stock_barcodes_sound-{}".format(self.ids[0]), {"sound": "ok"}, ) else: self.env["bus.bus"]._sendone( "stock_barcodes-{}".format(self.ids[0]), "stock_barcodes_sound-{}".format(self.ids[0]), {"sound": "ko"}, ) def _set_focus_on_qty_input(self, field_name="product_qty"): if field_name == "product_qty" and self.packaging_id: field_name = "packaging_qty" self.env["bus.bus"]._sendone( "stock_barcodes-{}".format(self.ids[0]), "stock_barcodes_read-{}".format(self.ids[0]), {"action": "focus", "field_name": field_name}, ) @api.onchange("product_id") def onchange_product_id(self): self.product_uom_id = self.product_id.uom_id @api.onchange("manual_entry") def onchange_manual_entry(self): if self.manual_entry and self.option_group_id.manual_entry_field_focus: self._set_focus_on_qty_input(self.option_group_id.manual_entry_field_focus) def _prepare_lot_vals(self, barcode): return { "name": barcode, "product_id": self.product_id.id, "company_id": self.env.company.id, } def _create_new_lot(self, barcode): new_lot = self.env["stock.production.lot"].create( self._prepare_lot_vals(barcode) ) return new_lot def action_clean_message(self): self.message = False self.check_option_required()
38.958393
27,154
31,480
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.fields import first from odoo.tools.float_utils import float_compare _logger = logging.getLogger(__name__) class WizStockBarcodesReadPicking(models.TransientModel): _name = "wiz.stock.barcodes.read.picking" _inherit = "wiz.stock.barcodes.read" _description = "Wizard to read barcode on picking" @property @api.depends("picking_mode") def _field_candidate_ids(self): return "candidate_%s_ids" % self.picking_mode picking_id = fields.Many2one( comodel_name="stock.picking", string="Picking", readonly=True ) picking_state = fields.Selection(related="picking_id.state") picking_ids = fields.Many2many( comodel_name="stock.picking", string="Pickings", readonly=True ) candidate_picking_ids = fields.One2many( comodel_name="wiz.candidate.picking", inverse_name="wiz_barcode_id", string="Candidate pickings", readonly=True, ) # TODO: Remove this field picking_product_qty = fields.Float( string="Picking quantities", digits="Product Unit of Measure", readonly=True ) picking_type_code = fields.Selection( [("incoming", "Vendors"), ("outgoing", "Customers"), ("internal", "Internal")], "Type of Operation", ) # TODO: Check if move_line_ids is used move_line_ids = fields.Many2many(comodel_name="stock.move.line", readonly=True) todo_line_ids = fields.One2many( string="To Do Lines", comodel_name="wiz.stock.barcodes.read.todo", inverse_name="wiz_barcode_id", ) todo_line_display_ids = fields.Many2many( comodel_name="wiz.stock.barcodes.read.todo", compute="_compute_todo_line_display_ids", ) todo_line_id = fields.Many2one(comodel_name="wiz.stock.barcodes.read.todo") picking_mode = fields.Selection([("picking", "Picking mode")]) pending_move_ids = fields.Many2many( comodel_name="wiz.stock.barcodes.read.todo", compute="_compute_pending_move_ids", ) @api.depends("todo_line_id") def _compute_todo_line_display_ids(self): """Technical field to display only the first record in kanban view""" self.todo_line_display_ids = self.todo_line_id @api.depends("todo_line_ids") def _compute_pending_move_ids(self): if self.option_group_id.show_pending_moves: self.pending_move_ids = self.todo_line_ids.filtered( lambda t: t.state == "pending" ) else: self.pending_move_ids = False def name_get(self): return [ ( rec.id, "{} - {} - {}".format( _("Barcode reader"), rec.picking_id.name or rec.picking_type_code, self.env.user.name, ), ) for rec in self ] def _set_default_picking(self): picking_id = self.env.context.get("default_picking_id", False) if picking_id: self._set_candidate_pickings(self.env["stock.picking"].browse(picking_id)) @api.model def create(self, vals): # When user click any view button the wizard record is create and the # picking candidates have been lost, so we need set it. wiz = super().create(vals) if wiz.picking_id: wiz._set_candidate_pickings(wiz.picking_id) return wiz @api.onchange("picking_id") def onchange_picking_id(self): # Add to candidate pickings the default picking. We are in a wizard # view, so for create a candidate picking with the same default picking # we need create it in this onchange self._set_default_picking() self.determine_todo_action() self.fill_pending_moves() def get_sorted_move_lines(self, move_lines): if self.picking_id.picking_type_code in ["incoming", "internal"]: location_field = "location_dest_id" else: location_field = "location_id" if self.option_group_id.source_pending_moves == "move_line_ids": move_lines = move_lines.sorted( lambda sml: ( sml[location_field].posx, sml[location_field].posy, sml[location_field].posz, sml[location_field].name, ) ) else: # Stock moves move_lines = move_lines.sorted( lambda sm: ( (sm.move_line_ids[:1] or sm)[location_field].posx, (sm.move_line_ids[:1] or sm)[location_field].posy, (sm.move_line_ids[:1] or sm)[location_field].posz, (sm.move_line_ids[:1] or sm)[location_field].name, ) ) return move_lines def _get_stock_move_lines_todo(self): move_lines = self.picking_id.move_line_ids.filtered( lambda ml: (not ml.barcode_scan_state or ml.barcode_scan_state == "pending") and ml.qty_done < ml.product_qty ) return move_lines def fill_pending_moves(self): if ( self.option_group_id.barcode_guided_mode != "guided" and self.option_group_id.show_pending_moves and not self.todo_line_ids ): self.fill_todo_records() def get_moves_or_move_lines(self): if self.option_group_id.source_pending_moves == "move_line_ids": return self.picking_id.move_line_ids.filtered(lambda ln: ln.move_id) else: return self.picking_id.move_lines def fill_todo_records(self): move_lines = self.get_sorted_move_lines(self.get_moves_or_move_lines()) self.env["wiz.stock.barcodes.read.todo"].fill_records(self, [move_lines]) def determine_todo_action(self, forced_todo_line=False): self.visible_force_done = self.env.context.get("visible_force_done", False) if not self.option_group_id.barcode_guided_mode == "guided": return False if not self.todo_line_ids: self.fill_todo_records() # When scanning all information in one step (e.g. using GS-1), the # status and qty processed might have not been update, we ensure it # invalidating the cache. self.todo_line_ids.invalidate_cache() self.todo_line_id = ( forced_todo_line or self.todo_line_ids.filtered(lambda t: t._origin.state == "pending")[:1] ) self.todo_line_id._compute_qty_done() move_line = self.todo_line_id self.guided_location_id = move_line.location_id self.guided_location_dest_id = move_line.location_dest_id self.guided_product_id = move_line.product_id self.guided_lot_id = move_line.lot_id if self.option_group_id.get_option_value("location_id", "filled_default"): self.location_id = move_line.location_id elif self.picking_type_code != "incoming": self.location_id = False if self.option_group_id.get_option_value("location_dest_id", "filled_default"): self.location_dest_id = move_line.location_dest_id elif self.picking_type_code != "outgoing": self.location_dest_id = False if self.option_group_id.get_option_value("package_id", "filled_default"): self.package_id = move_line.package_id if self.option_group_id.get_option_value("result_package_id", "filled_default"): self.result_package_id = move_line.result_package_id if self.option_group_id.get_option_value("product_id", "filled_default"): self.product_id = move_line.product_id else: self.product_id = False if self.option_group_id.get_option_value("lot_id", "filled_default"): self.lot_id = move_line.lot_id else: self.lot_id = False if self.option_group_id.get_option_value("product_qty", "filled_default"): self.product_qty = move_line.product_uom_qty - move_line.qty_done else: if not self.visible_force_done: self.product_qty = 0.0 self.update_fields_after_determine_todo(move_line) def update_fields_after_determine_todo(self, move_line): self.picking_product_qty = move_line.qty_done def action_done(self): # Skip read log creation to be able to pass log_detail when available. res = super( WizStockBarcodesReadPicking, self.with_context(_stock_barcodes_skip_read_log=True), ).action_done() if res: move_dic = self._process_stock_move_line() if move_dic: self[self._field_candidate_ids].scan_count += 1 if self.option_group_id.barcode_guided_mode == "guided": self.action_clean_values() if self.env.context.get("force_create_move"): self.move_line_ids.barcode_scan_state = "done_forced" self.determine_todo_action() # Now we can add read log with details. _logger.info("Add scanned log barcode:{}".format(self.barcode)) self._add_read_log(log_detail=move_dic) return bool(move_dic) # Add read log normally. _logger.info("Add scanned log barcode:{}".format(self.barcode)) self._add_read_log() return res def action_manual_entry(self): result = super().action_manual_entry() if result: self.action_done() return result def _prepare_move_line_values(self, candidate_move, available_qty): """When we've got an out picking, the logical workflow is that the scanned location is the location we're getting the stock from""" picking = self.env.context.get("picking", self.picking_id) if not picking: raise ValidationError( _("You can not add extra moves if you have " "not set a picking") ) # If we move all package units the result package is the same if ( self.package_id and not self.result_package_id and sum(self.package_id.quant_ids.mapped("quantity")) <= self.product_qty ): self.result_package_id = self.package_id vals = { "picking_id": picking.id, "move_id": candidate_move.id, "qty_done": available_qty, "product_uom_id": candidate_move.product_uom.id or self.product_id.uom_id.id if not self.packaging_id else self.packaging_id.product_uom_id.id, "product_id": self.product_id.id, "location_id": self.location_id.id, "location_dest_id": self.location_dest_id.id, "lot_id": self.lot_id.id, "lot_name": self.lot_id.name, "barcode_scan_state": "done_forced", "package_id": self.package_id.id, "result_package_id": self.result_package_id.id, } if self.owner_id: vals["owner_id"] = self.owner_id.id return vals def _states_move_allowed(self): move_states = ["assigned", "partially_available"] if self.confirmed_moves: move_states.append("confirmed") return move_states def _prepare_stock_moves_domain(self): domain = [ ("product_id", "=", self.product_id.id), ("picking_id.picking_type_id.code", "=", self.picking_type_code), ("state", "in", self._states_move_allowed()), ] if self.picking_id: domain.append(("picking_id", "=", self.picking_id.id)) return domain def _set_candidate_pickings(self, candidate_pickings): vals = [(5, 0, 0)] vals.extend([(0, 0, {"picking_id": p.id}) for p in candidate_pickings]) self.candidate_picking_ids = vals def _search_candidate_picking(self, moves_todo=False): if not moves_todo: moves_todo = self.env["stock.move"].search( self._prepare_stock_moves_domain() ) if not self.picking_id: candidate_pickings = moves_todo.mapped("picking_id") candidate_pickings_count = len(candidate_pickings) if candidate_pickings_count > 1: self._set_candidate_pickings(candidate_pickings) return False if candidate_pickings_count == 1: self.picking_id = candidate_pickings self._set_candidate_pickings(candidate_pickings) _logger.info("No picking assigned") return True def _check_guided_restrictions(self): # Check restrictions in guided mode if self.option_group_id.barcode_guided_mode == "guided": if ( self.option_group_id.get_option_value("product_id", "forced") and self.product_id != self.todo_line_id.product_id ): self._set_messagge_info("more_match", _("Wrong product")) return False return True def _get_candidate_stock_move_lines(self, moves_todo, sml_vals): candidate_lines = moves_todo.mapped("move_line_ids").filtered( lambda l: ( # l.picking_id == self.picking_id and l.location_id == self.location_id and l.location_dest_id == self.location_dest_id and l.product_id == self.product_id ) ) if not candidate_lines: location_option = self.option_group_id.option_ids.filtered( lambda op: op.field_name == "location_id" ) if not location_option.forced: candidate_lines = moves_todo.mapped("move_line_ids").filtered( lambda l: ( l.location_dest_id == self.location_dest_id and l.product_id == self.product_id ) ) if candidate_lines and self.location_id: sml_vals.update({"location_id": self.location_id.id}) if not candidate_lines: location_dest_option = self.option_group_id.option_ids.filtered( lambda op: op.field_name == "location_dest_id" ) if not location_dest_option.forced: candidate_lines = moves_todo.mapped("move_line_ids").filtered( lambda l: ( l.location_id == self.location_id and l.product_id == self.product_id ) ) if candidate_lines and self.location_dest_id: sml_vals.update({"location_dest_id": self.location_dest_id.id}) return candidate_lines def _process_stock_move_line(self): # noqa: C901 """ Search assigned or confirmed stock moves from a picking operation type or a picking. If there is more than one picking with demand from scanned product the interface allow to select what picking to work. If only there is one picking the scan data is assigned to it. """ StockMove = self.env["stock.move"] domain = self._prepare_stock_moves_domain() if self.option_group_id.barcode_guided_mode == "guided": moves_todo = self.todo_line_id.stock_move_ids else: moves_todo = StockMove.search(domain) if not getattr( self, "_search_candidate_%s" % self.picking_mode, )(moves_todo): return False sml_vals = {} candidate_lines = self._get_candidate_stock_move_lines(moves_todo, sml_vals) lines = candidate_lines.filtered( lambda l: (l.lot_id == self.lot_id and l.barcode_scan_state == "pending") ) # Check if exists lines with lot created if product has tracking serial if self.product_id.tracking == "serial": serial_lines = self.picking_id.move_line_ids.filtered( lambda sml: ( sml.lot_id == self.lot_id or sml.lot_name == self.lot_id.name ) and sml.qty_done >= 1.0 ) if serial_lines: self._set_messagge_info("more_match", _("S/N Already in picking")) return False # For incoming pickings the lot is not filled so we try fill it with # the lot scanned if ( not lines and self.picking_type_code == "incoming" and self.product_id.tracking != "none" ): if ( self.option_group_id.create_lot and self.product_id.tracking == "serial" and candidate_lines.filtered(lambda ln: ln.lot_name == self.lot_id.name) ): self.lot_id = False self._set_messagge_info("more_match", _("S/N already created")) return False lines = candidate_lines.filtered( lambda l: (not l.lot_id and l.barcode_scan_state == "pending") ) if lines: sml_vals.update( {"lot_id": self.lot_id.id, "lot_name": self.lot_id.name} ) # The new lines scanned has been created without reserved quantity if not lines: lines = candidate_lines.filtered( lambda l: ( l.lot_id == self.lot_id and l.product_uom_qty == 0.0 and l.qty_done > 0.0 ) ) if lines: # Hook: extra filter to be extend by other modules lines = self.filter_sml(candidate_lines, lines, sml_vals) # Determine location depend on picking type code # lines = lines.filtered(lambda ln: ) available_qty = self.product_qty max_quantity = sum(sm.product_uom_qty - sm.quantity_done for sm in moves_todo) if ( not self.option_group_id.code == "REL" and not self.env.context.get("force_create_move", False) and not self.env.context.get("manual_picking", False) and float_compare( available_qty, max_quantity, precision_rounding=self.product_id.uom_id.rounding, ) > 0 ): self._set_messagge_info( "more_match", _("Quantities scanned are higher than necessary") ) self.visible_force_done = True self._set_focus_on_qty_input("product_qty") return False move_lines_dic = {} for line in lines: if line.product_uom_qty and len(lines) > 1: assigned_qty = min( max(line.product_uom_qty - line.qty_done, 0.0), available_qty ) else: assigned_qty = available_qty sml_vals.update( { "qty_done": line.qty_done + assigned_qty, "result_package_id": self.result_package_id.id, } ) # Add or remove result_package_id package_qty_available = sum( self.package_id.quant_ids.filtered( lambda q: q.lot_id == self.lot_id ).mapped("quantity") ) if sml_vals["qty_done"] >= package_qty_available: if not self.result_package_id: sml_vals.update({"result_package_id": self.package_id.id}) elif line.result_package_id == line.package_id: sml_vals.update({"result_package_id": False}) line.write(sml_vals) if line.qty_done >= line.product_uom_qty: line.barcode_scan_state = "done" elif self.env.context.get("done_forced"): line.barcode_scan_state = "done_forced" available_qty -= assigned_qty if assigned_qty: move_lines_dic[line.id] = assigned_qty if ( float_compare( available_qty, 0.0, precision_rounding=line.product_id.uom_id.rounding, ) < 1 ): break if ( float_compare( available_qty, 0, precision_rounding=self.product_id.uom_id.rounding ) > 0 ): # Create an extra stock move line if this product has an # initial demand. stock_move_lines = self.create_new_stock_move_line( moves_todo, available_qty ) for sml in stock_move_lines: if not sml.move_id: self.create_new_stock_move(sml) move_lines_dic[sml.id] = sml.qty_done # When create new stock move lines and we are in guided mode we need # link this new lines to the todo line details if self.option_group_id.barcode_guided_mode == "guided": self.todo_line_id.line_ids = [(4, sml.id) for sml in stock_move_lines] elif self.option_group_id.show_pending_moves: # TODO: Check performance with a lot records self.fill_todo_records() self.update_fields_after_process_stock(moves_todo) return move_lines_dic def create_new_stock_move_line(self, moves_todo, available_qty): """Create a new stock move line when a sml is not available for the wizard values. """ return self.env["stock.move.line"].create( self._prepare_move_line_values(moves_todo[:1], available_qty) ) def create_new_stock_move(self, sml): vals = { "name": _("New Move:") + sml.product_id.display_name, "product_uom": sml.product_uom_id.id, "product_uom_qty": sml.qty_done, "state": "assigned", "additional": True, "product_id": sml.product_id.id, "location_id": sml.location_id.id, "location_dest_id": sml.location_dest_id.id, "picking_id": sml.picking_id.id, } new_move = self.env["stock.move"].create(vals) sml.move_id = new_move def filter_sml(self, candidate_lines, lines, sml_vals): """Empty method that needs to be implemented in other modules.""" return lines def update_fields_after_process_stock(self, moves): self.picking_product_qty = sum(moves.mapped("quantity_done")) def _candidate_picking_selected(self): if len(self.candidate_picking_ids) == 1: return self.candidate_picking_ids.picking_id else: return self.env["stock.picking"].browse() def check_done_conditions(self): res = super().check_done_conditions() if ( self.picking_type_code != "incoming" and float_compare( self.product_qty, self.qty_available, precision_rounding=self.product_id.uom_id.rounding, ) > 0 and not self.env.context.get("force_create_move", False) and not self.option_group_id.allow_negative_quant ): self._set_messagge_info( "more_match", _("Quantities not available in location") ) if self.option_group_id.allow_negative_quant: self.visible_force_done = True # Set focus on product_qty input box self._set_focus_on_qty_input("product_qty") return False if self.picking_mode == "picking_batch": return res if not self.picking_id: if not self._search_candidate_picking(): self._set_messagge_info( "info", _("Click on picking pushpin to lock it") ) return False if self.picking_id and self.picking_id != self._candidate_picking_selected(): self._set_messagge_info("info", _("Click on picking pushpin to lock it")) return False return res def _prepare_scan_log_values(self, log_detail=False): # Store in read log line each line added with the quantities assigned vals = super()._prepare_scan_log_values(log_detail=log_detail) vals["picking_id"] = self.picking_id.id if log_detail: vals["log_line_ids"] = [ (0, 0, {"move_line_id": x[0], "product_qty": x[1]}) for x in log_detail.items() ] return vals def remove_scanning_log(self, scanning_log): for log in scanning_log: for log_scan_line in log.log_line_ids: sml = log_scan_line.move_line_id if sml.state not in ["draft", "assigned", "confirmed"]: raise ValidationError( _( "You cannot remove an entry linked to a operation " "in state new, assigned or confirmed" ) ) qty = sml.qty_done - log_scan_line.product_qty log_scan_line.move_line_id.qty_done = max(qty, 0.0) if sml.state == "draft" and sml.move_id.quantity_done == 0.0: # This move has been created by the last scan, remove it. sml.move_id.unlink() self.picking_product_qty = sum( log.log_line_ids.mapped("move_line_id.move_id.quantity_done") ) log.unlink() def action_undo_last_scan(self): res = super().action_undo_last_scan() log_scan = first( self.scan_log_ids.filtered(lambda x: x.create_uid == self.env.user) ) self.remove_scanning_log(log_scan) return res def get_lot_by_removal_strategy(self): quants = first( self.env["stock.quant"]._gather(self.product_id, self.location_id) ) # TODO: Perhaps update location_id from quant?? self.lot_id = quants.lot_id def action_product_scaned_post(self, product): res = super().action_product_scaned_post(product) if self.auto_lot and self.picking_type_code != "incoming": self.get_lot_by_removal_strategy() return res def action_assign_serial(self): move = self.env["stock.move"].search(self._prepare_stock_moves_domain()) if len(move) > 1: smls = move.move_line_ids.filtered( lambda ln: ln.barcode_scan_state == "pending" ) move = smls[:1].move_id if move: return move.action_assign_serial() raise ValidationError(_("No pending lines for this product")) def action_put_in_pack(self): self.picking_id.action_put_in_pack() class WizCandidatePicking(models.TransientModel): """ TODO: explain """ _name = "wiz.candidate.picking" _description = "Candidate pickings for barcode interface" # To prevent remove the record wizard until 2 days old _transient_max_hours = 48 wiz_barcode_id = fields.Many2one( comodel_name="wiz.stock.barcodes.read.picking", readonly=True ) picking_id = fields.Many2one( comodel_name="stock.picking", string="Picking", readonly=True ) wiz_picking_id = fields.Many2one( comodel_name="stock.picking", related="wiz_barcode_id.picking_id", string="Wizard Picking", readonly=True, ) name = fields.Char( related="picking_id.name", readonly=True, string="Candidate Picking" ) partner_id = fields.Many2one( comodel_name="res.partner", related="picking_id.partner_id", readonly=True, string="Partner", ) state = fields.Selection(related="picking_id.state", readonly=True) date = fields.Datetime( related="picking_id.date", readonly=True, string="Creation Date" ) product_qty_reserved = fields.Float( "Reserved", compute="_compute_picking_quantity", digits="Product Unit of Measure", readonly=True, ) product_uom_qty = fields.Float( "Demand", compute="_compute_picking_quantity", digits="Product Unit of Measure", readonly=True, ) product_qty_done = fields.Float( "Done", compute="_compute_picking_quantity", digits="Product Unit of Measure", readonly=True, ) # For reload kanban view scan_count = fields.Integer() is_pending = fields.Boolean(compute="_compute_is_pending") @api.depends("scan_count") def _compute_picking_quantity(self): for candidate in self: qty_reserved = 0 qty_demand = 0 qty_done = 0 candidate.product_qty_reserved = sum( candidate.picking_id.mapped("move_lines.reserved_availability") ) for move in candidate.picking_id.move_lines: qty_reserved += move.reserved_availability qty_demand += move.product_uom_qty qty_done += move.quantity_done candidate.update( { "product_qty_reserved": qty_reserved, "product_uom_qty": qty_demand, "product_qty_done": qty_done, } ) @api.depends("scan_count") def _compute_is_pending(self): for rec in self: rec.is_pending = bool(rec.wiz_barcode_id.pending_move_ids) def _get_wizard_barcode_read(self): return self.env["wiz.stock.barcodes.read.picking"].browse( self.env.context["wiz_barcode_id"] ) def action_lock_picking(self): wiz = self._get_wizard_barcode_read() picking_id = self.env.context["picking_id"] wiz.picking_id = picking_id wiz._set_candidate_pickings(wiz.picking_id) return wiz.action_confirm() def action_unlock_picking(self): wiz = self._get_wizard_barcode_read() wiz.update( { "picking_id": False, "candidate_picking_ids": False, "message_type": False, "message": False, } ) return wiz.action_cancel() def action_validate_picking(self): picking = self.env["stock.picking"].browse( self.env.context.get("picking_id", False) ) res = picking.button_validate() if isinstance(res, dict): # backorder wizard return res return self.env["ir.actions.actions"]._for_xml_id( "stock_barcodes.action_stock_barcodes_action" ) def action_open_picking(self): picking = self.env["stock.picking"].browse( self.env.context.get("picking_id", False) ) return picking.with_context(control_panel_hidden=False).get_formview_action() def action_put_in_pack(self): self.picking_id.action_put_in_pack()
39.898606
31,480
2,217
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class WizStockBarcodesNewLot(models.TransientModel): _inherit = "barcodes.barcode_events_mixin" _name = "wiz.stock.barcodes.new.lot" _description = "Wizard to create new lot from barcode scanner" product_id = fields.Many2one(comodel_name="product.product", required=True) lot_name = fields.Char(string="Lot name") def on_barcode_scanned(self, barcode): product = self.env["product.product"].search([("barcode", "=", barcode)])[:1] if product and not self.product_id: self.product_id = product return self.lot_name = barcode def _prepare_lot_values(self): return { "product_id": self.product_id.id, "name": self.lot_name, "company_id": self.env.company.id, } def get_scan_wizard(self): return self.env[self.env.context["active_model"]].browse( self.env.context["active_id"] ) def scan_wizard_action(self): if self.env.context.get("active_model") == "wiz.stock.barcodes.read.inventory": action = self.env["ir.actions.actions"]._for_xml_id( "stock_barcodes.action_stock_barcodes_read_inventory" ) else: action = self.env["ir.actions.actions"]._for_xml_id( "stock_barcodes.action_stock_barcodes_read_picking" ) wiz_id = self.get_scan_wizard() action["res_id"] = wiz_id.id return action def confirm(self): ProductionLot = self.env["stock.production.lot"] lot = ProductionLot.search( [("product_id", "=", self.product_id.id), ("name", "=", self.lot_name)] ) if not lot: lot = self.env["stock.production.lot"].create(self._prepare_lot_values()) # Assign lot created or found to wizard scanning barcode lot_id field wiz = self.get_scan_wizard() if wiz: wiz.lot_id = lot return self.scan_wizard_action() def cancel(self): return self.scan_wizard_action()
36.95
2,217
9,814
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from collections import OrderedDict from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval class WizStockBarcodesReadTodo(models.TransientModel): _name = "wiz.stock.barcodes.read.todo" _description = "Wizard to read barcode todo" # To prevent remove the record wizard until 2 days old _transient_max_hours = 48 name = fields.Char() wiz_barcode_id = fields.Many2one(comodel_name="wiz.stock.barcodes.read.picking") partner_id = fields.Many2one( comodel_name="res.partner", readonly=True, string="Partner", ) state = fields.Selection( [("pending", "Pending"), ("done", "Done"), ("done_forced", "Done forced")], string="Scan State", default="pending", compute="_compute_state", readonly=False, ) product_qty_reserved = fields.Float( "Reserved", digits="Product Unit of Measure", readonly=True, ) product_uom_qty = fields.Float( "Demand", digits="Product Unit of Measure", readonly=True, ) qty_done = fields.Float( "Done", digits="Product Unit of Measure", readonly=False, compute="_compute_qty_done", store=True, ) location_id = fields.Many2one(comodel_name="stock.location") location_name = fields.Char(related="location_id.name") location_dest_id = fields.Many2one(comodel_name="stock.location") location_dest_name = fields.Char( string="Destinatino Name", related="location_dest_id.name" ) product_id = fields.Many2one(comodel_name="product.product") lot_id = fields.Many2one(comodel_name="stock.production.lot") uom_id = fields.Many2one(comodel_name="uom.uom") package_id = fields.Many2one(comodel_name="stock.quant.package") result_package_id = fields.Many2one(comodel_name="stock.quant.package") package_product_qty = fields.Float() res_model_id = fields.Many2one(comodel_name="ir.model") res_ids = fields.Char() line_ids = fields.Many2many(comodel_name="stock.move.line") stock_move_ids = fields.Many2many(comodel_name="stock.move") position_index = fields.Integer() picking_code = fields.Char("Type of Operation") def _group_key(self, wiz, line): group_key_for_todo_records = wiz.option_group_id.group_key_for_todo_records if group_key_for_todo_records: return safe_eval(group_key_for_todo_records, globals_dict={"object": line}) if wiz.option_group_id.source_pending_moves == "move_line_ids": return (line.location_id, line.product_id, line.lot_id) else: return (line.location_id, line.product_id) def _get_all_products_quantities_in_package(self, package): res = {} for quant in package._get_contained_quants(): if quant.product_id not in res: res[quant.product_id] = 0 res[quant.product_id] += quant.quantity return res @api.model def fill_records(self, wiz_barcode, lines_list): """ :param lines_list: browse list :return: """ wiz_barcode.todo_line_ids = self.browse() todo_vals = OrderedDict() position = 0 for lines in lines_list: for line in lines: key = self._group_key(wiz_barcode, line) if key not in todo_vals: vals = { "product_id": line.product_id.id, "product_uom_qty": line.product_uom_qty, "name": "To do action", "position_index": position, "picking_code": line.picking_code, } if ( wiz_barcode.option_group_id.source_pending_moves == "move_line_ids" ): package_product_dic = ( self._get_all_products_quantities_in_package( line.package_id ) ) vals.update( { "location_id": line.location_id.id, "location_dest_id": line.location_dest_id.id, "lot_id": line.lot_id.id, "package_id": line.package_id.id, "result_package_id": line.result_package_id.id, "uom_id": line.product_uom_id.id, "qty_done": line.qty_done, "product_qty_reserved": line.product_qty, "line_ids": [(6, 0, line.ids)], "stock_move_ids": [(6, 0, line.move_id.ids)], "package_product_qty": package_product_dic and package_product_dic[line.product_id] or 0.0, } ) else: vals.update( { "location_id": ( line.move_line_ids[:1] or line ).location_id.id, "location_dest_id": ( line.move_line_ids[:1] or line ).location_dest_id.id, "uom_id": line.product_uom.id, "qty_done": line.quantity_done, "product_qty_reserved": line.move_line_ids and sum(line.move_line_ids.mapped("product_qty")) or line.product_uom_qty, "line_ids": [(6, 0, line.move_line_ids.ids)], "stock_move_ids": [(6, 0, line.ids)], } ) todo_vals[key] = vals position += 1 else: todo_vals[key]["product_uom_qty"] += line.product_uom_qty if ( wiz_barcode.option_group_id.source_pending_moves == "move_line_ids" ): todo_vals[key]["product_qty_reserved"] += line.product_qty todo_vals[key]["qty_done"] += line.qty_done todo_vals[key]["line_ids"][0][2].append(line.id) todo_vals[key]["stock_move_ids"][0][2].append(line.move_id.id) else: todo_vals[key]["product_qty_reserved"] += ( line.move_line_ids and sum(line.move_line_ids.mapped("product_qty")) or line.product_uom_qty ) todo_vals[key]["qty_done"] += line.quantity_done todo_vals[key]["line_ids"][0][2].extend(line.move_line_ids.ids) todo_vals[key]["stock_move_ids"][0][2].extend(line.ids) wiz_barcode.todo_line_ids = self.create(list(todo_vals.values())) def action_todo_next(self): self.state = "done_forced" self.line_ids.barcode_scan_state = "done_forced" self.wiz_barcode_id.determine_todo_action() def action_reset_lines(self): self.state = "pending" self.line_ids.barcode_scan_state = "pending" self.line_ids.qty_done = 0.0 self.wiz_barcode_id.action_clean_values() self.wiz_barcode_id.determine_todo_action() def action_back_line(self): if self.position_index > 0: record = self.wiz_barcode_id.todo_line_ids[self.position_index - 1] self.wiz_barcode_id.determine_todo_action(forced_todo_line=record) def action_next_line(self): if self.position_index < len(self.wiz_barcode_id.todo_line_ids) - 1: record = self.wiz_barcode_id.todo_line_ids[self.position_index + 1] self.wiz_barcode_id.determine_todo_action(forced_todo_line=record) @api.depends("line_ids.qty_done") def _compute_qty_done(self): for rec in self: rec.qty_done = sum(ln._origin.qty_done for ln in rec.line_ids) @api.depends( "line_ids", "line_ids.qty_done", "line_ids.product_uom_qty", "line_ids.barcode_scan_state", "qty_done", "product_uom_qty", ) def _compute_state(self): for rec in self: if rec.qty_done >= rec.product_uom_qty or ( rec.wiz_barcode_id.option_group_id.source_pending_moves == "move_line_ids" and rec.line_ids and not any(ln.barcode_scan_state == "pending" for ln in rec.line_ids) ): rec.state = "done" else: rec.state = "pending" @api.model def fields_to_fill_from_pending_line(self): return [ "location_id", "product_id", "lot_id", "package_id", "result_package_id", ] def fill_from_pending_line(self): self.wiz_barcode_id.determine_todo_action(forced_todo_line=self) for field in self.fields_to_fill_from_pending_line(): self.wiz_barcode_id[field] = self[field] self.wiz_barcode_id.product_uom_id = self.uom_id self.wiz_barcode_id._set_focus_on_qty_input()
41.940171
9,814
3,944
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockBarcodesOptionGroup(models.Model): _name = "stock.barcodes.option.group" _description = "Options group for barcode interface" name = fields.Char() code = fields.Char() option_ids = fields.One2many( comodel_name="stock.barcodes.option", inverse_name="option_group_id", copy=True ) barcode_guided_mode = fields.Selection( [("guided", "Guided")], string="Mode", help="When guided mode is selected, information will appear with the " "movement to be processed", ) manual_entry = fields.Boolean( string="Manual entry", help="Default value when open scan interface", ) manual_entry_field_focus = fields.Char( help="Set field to set focus when manual entry mode is enabled", default="location_id", ) confirmed_moves = fields.Boolean( string="Confirmed moves", help="It allows to work with movements without reservation " "(Without detailed operations)", ) show_pending_moves = fields.Boolean( string="Show pending moves", help="Shows a list of movements to process" ) source_pending_moves = fields.Selection( [("move_line_ids", "Detailed operations"), ("move_lines", "Operations")], default="move_line_ids", help="Origin of the data to generate the movements to process", ) show_scan_log = fields.Boolean( string="Show scan log", help="Displays a log of the scans processed" ) ignore_filled_fields = fields.Boolean( string="Ignore filled fields", ) auto_put_in_pack = fields.Boolean( string="Auto put in pack", help="Auto put in pack before picking validation" ) is_manual_qty = fields.Boolean( help="If it is checked, it always shows the product quantity field in edit mode" ) is_manual_confirm = fields.Boolean( help="If it is marked, the movement must always be confirmed from a button" ) allow_negative_quant = fields.Boolean( help="If it is checked, it will allow the creation of movements that " "generate negative stock" ) fill_fields_from_lot = fields.Boolean( help="If checked, the fields in the interface will be filled from " "the scanned lot" ) group_key_for_todo_records = fields.Char( help="You can establish a list of fields that will act as a grouping " "key to generate the movements to be process.\n" "The object variable is used to refer to the source record\n" "For example, object.location_id,object.product_id,object.lot_id" ) auto_lot = fields.Boolean( string="Get lots automatically", help="If checked the lot will be set automatically with the same " "removal startegy", ) create_lot = fields.Boolean( string="Create lots if not match", help="If checked the lot will created automatically with the scanned barcode " "if not exists ", ) def get_option_value(self, field_name, attribute): option = self.option_ids.filtered(lambda op: op.field_name == field_name)[:1] return option[attribute] class StockBarcodesOption(models.Model): _name = "stock.barcodes.option" _description = "Options for barcode interface" _order = "step, sequence, id" sequence = fields.Integer(default=100) name = fields.Char() option_group_id = fields.Many2one( comodel_name="stock.barcodes.option.group", ondelete="cascade" ) field_name = fields.Char() filled_default = fields.Boolean() forced = fields.Boolean() to_scan = fields.Boolean() required = fields.Boolean() clean_after_done = fields.Boolean() message = fields.Char() step = fields.Integer()
37.923077
3,944
809
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockMoveLine(models.Model): _inherit = "stock.move.line" barcode_scan_state = fields.Selection( [("pending", "Pending"), ("done", "Done"), ("done_forced", "Done forced")], string="Scan State", default="pending", compute="_compute_barcode_scan_state", readonly=False, store=True, ) @api.depends("qty_done", "product_uom_qty") def _compute_barcode_scan_state(self): for line in self: if line.qty_done >= line.product_uom_qty: line.barcode_scan_state = "done" else: line.barcode_scan_state = "pending"
33.708333
809
1,105
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models from odoo.tools.safe_eval import safe_eval class StockBarcodesAction(models.Model): _name = "stock.barcodes.action" _description = "Actions for barcode interface" _order = "sequence, id" name = fields.Char(translate=True) active = fields.Boolean(default=True) sequence = fields.Integer(default=100) action_window_id = fields.Many2one( comodel_name="ir.actions.act_window", string="Action window" ) context = fields.Char() key_shortcut = fields.Integer() key_char_shortcut = fields.Char() icon_class = fields.Char() def open_action(self): action = self.action_window_id.sudo().read()[0] action_context = safe_eval(action["context"]) ctx = self.env.context.copy() if action_context: ctx.update(action_context) if self.context: ctx.update(safe_eval(self.context)) action["context"] = ctx return action
34.53125
1,105
2,675
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockPickingType(models.Model): _inherit = "stock.picking.type" barcode_option_group_id = fields.Many2one( comodel_name="stock.barcodes.option.group" ) new_picking_barcode_option_group_id = fields.Many2one( comodel_name="stock.barcodes.option.group", help="This Barcode Option Group will be selected when clicking the 'New' button" " in an operation type. It will be used to create a non planned picking.", ) def action_barcode_scan(self): vals = { "res_model_id": self.env.ref("stock.model_stock_picking_type").id, "res_id": self.id, "picking_type_code": self.code, "option_group_id": self.barcode_option_group_id.id, "manual_entry": self.barcode_option_group_id.manual_entry, "picking_mode": "picking", } if self.code == "outgoing": location_dest_id = ( self.default_location_dest_id.id or self.env.ref("stock.stock_location_customers").id ) vals["location_dest_id"] = location_dest_id if self.code == "incoming": location_src_id = ( self.default_location_src_id.id or self.env.ref("stock.stock_location_suppliers").id ) vals["location_id"] = location_src_id if self.barcode_option_group_id.get_option_value( "location_id", "filled_default" ): vals["location_id"] = self.default_location_src_id.id if self.barcode_option_group_id.get_option_value( "location_dest_id", "filled_default" ): vals["location_dest_id"] = self.default_location_dest_id.id wiz = self.env["wiz.stock.barcodes.read.picking"].create(vals) wiz.determine_todo_action() wiz.fill_pending_moves() action = self.env["ir.actions.actions"]._for_xml_id( "stock_barcodes.action_stock_barcodes_read_picking" ) action["res_id"] = wiz.id return action def action_barcode_new_picking(self): picking = self.env["stock.picking"].create( { "picking_type_id": self.id, "location_id": self.default_location_src_id.id, "location_dest_id": self.default_location_dest_id.id, } ) option_group = self.new_picking_barcode_option_group_id return picking.action_barcode_scan(option_group=option_group)
40.530303
2,675
2,084
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockBarcodesReadLog(models.Model): _name = "stock.barcodes.read.log" _description = "Log barcode scanner" _order = "id DESC" name = fields.Char(string="Barcode Scanned") res_model_id = fields.Many2one(comodel_name="ir.model", index=True) res_id = fields.Integer(index=True) product_id = fields.Many2one(comodel_name="product.product", index=True) lot_id = fields.Many2one(comodel_name="stock.production.lot", string="Lot scanned") location_id = fields.Many2one(comodel_name="stock.location") packaging_id = fields.Many2one(comodel_name="product.packaging") packaging_qty = fields.Float(string="Package Qty", digits="Product Unit of Measure") product_qty = fields.Float(string="Quantity", digits="Product Unit of Measure") manual_entry = fields.Boolean(string="Manual entry") picking_id = fields.Many2one(comodel_name="stock.picking", string="Picking") log_line_ids = fields.One2many( comodel_name="stock.barcodes.read.log.line", inverse_name="read_log_id", string="Scanning log details", ) class StockBarcodesReadLogLine(models.Model): """ The goal of this model is store detail about scanning log, for example, when user read in pickings the product quantity can be distributed in more than one stock move line. This help to know what records have been affected by a scanning read. """ _name = "stock.barcodes.read.log.line" _description = "Stock barcodes read log lines" read_log_id = fields.Many2one( comodel_name="stock.barcodes.read.log", string="Scanning log", ondelete="cascade", readonly=True, ) move_line_id = fields.Many2one( comodel_name="stock.move.line", string="Stock move lines", readonly=True ) product_qty = fields.Float( string="Quantity scanned", digits="Product Unit of Measure", readonly=True )
40.862745
2,084
1,830
py
PYTHON
15.0
# Copyright 2019 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class StockPicking(models.Model): _inherit = "stock.picking" def action_barcode_scan(self, option_group=False): option_group = option_group or self.picking_type_id.barcode_option_group_id vals = { "picking_id": self.id, "res_model_id": self.env.ref("stock.model_stock_picking").id, "res_id": self.id, "picking_type_code": self.picking_type_code, "option_group_id": option_group.id, "manual_entry": option_group.manual_entry, "picking_mode": "picking", } if self.picking_type_id.code == "outgoing": vals["location_dest_id"] = self.location_dest_id.id if self.picking_type_id.code == "incoming": vals["location_id"] = self.location_id.id if option_group.get_option_value("location_id", "filled_default"): vals["location_id"] = self.location_id.id if option_group.get_option_value("location_dest_id", "filled_default"): vals["location_dest_id"] = self.location_dest_id.id wiz = self.env["wiz.stock.barcodes.read.picking"].create(vals) wiz.determine_todo_action() wiz.fill_pending_moves() action = self.env["ir.actions.actions"]._for_xml_id( "stock_barcodes.action_stock_barcodes_read_picking" ) action["res_id"] = wiz.id return action def button_validate(self): if ( self.picking_type_id.barcode_option_group_id.auto_put_in_pack and not self.move_line_ids.mapped("result_package_id") ): self.action_put_in_pack() return super().button_validate()
41.590909
1,830
870
py
PYTHON
15.0
# Copyright (C) 2014-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # Copyright (C) 2018 Komit (https://komit-consulting.com) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Generate Barcodes (Abstract)", "summary": "Generate Barcodes for Any Models", "version": "15.0.1.0.0", "category": "Tools", "author": "GRAP, La Louve, LasLabs, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "license": "AGPL-3", "depends": ["barcodes"], "data": [ "security/res_groups.xml", "views/view_barcode_rule.xml", "views/menu.xml", ], "demo": ["demo/res_users.xml"], "external_dependencies": {"python": ["python-barcode"]}, }
37.826087
870
612
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class BarcodeRuleUserFake(models.Model): _inherit = "barcode.rule" generate_model = fields.Selection( selection_add=[("res.users", "Users")], ondelete={"res.users": "cascade"} ) type = fields.Selection( selection_add=[("user", "User")], ondelete={"user": "cascade"} ) class BarcodeGeneratorUserFake(models.Model): _name = "res.users" _inherit = ["res.users", "barcode.generate.mixin"] barcode = fields.Char(copy=False)
27.818182
612
1,740
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo_test_helper import FakeModelLoader from odoo.tests import SavepointCase class TestBarcodesGeneratorAbstract(SavepointCase, FakeModelLoader): @classmethod def setUpClass(cls): super().setUpClass() cls.loader = FakeModelLoader(cls.env, cls.__module__) cls.loader.backup_registry() from .models import BarcodeGeneratorUserFake, BarcodeRuleUserFake cls.loader.update_registry( ( BarcodeGeneratorUserFake, BarcodeRuleUserFake, ) ) cls.barcode_rule_fake = cls.env["barcode.rule"].create( { "name": "User rule", "barcode_nomenclature_id": cls.env.ref( "barcodes.default_barcode_nomenclature" ).id, "type": "user", "sequence": 999, "encoding": "ean13", "pattern": "20.....{NNNDD}", "generate_type": "manual", "generate_model": "res.users", } ) cls.user_fake = cls.env["res.users"].create( { "name": "Test user", "login": "testing_01", "barcode_rule_id": cls.barcode_rule_fake.id, "barcode_base": 10, } ) cls.user_fake.generate_barcode() @classmethod def tearDownClass(cls): cls.loader.restore_registry() return super().tearDownClass() def test_generate_sequence(self): self.assertEqual( self.user_fake.barcode, "2000010000005", )
31.636364
1,740
3,179
py
PYTHON
15.0
# Copyright (C) 2014-TODAY GRAP (http://www.grap.coop) # Copyright (C) 2016-TODAY La Louve (http://www.lalouve.net) # Copyright 2017 LasLabs Inc. # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging import barcode # pylint: disable=W7936 from odoo import _, api, exceptions, fields, models _logger = logging.getLogger(__name__) class BarcodeGenerateMixin(models.AbstractModel): _name = "barcode.generate.mixin" _description = "Generate Barcode Mixin" # Column Section barcode_rule_id = fields.Many2one( string="Barcode Rule", comodel_name="barcode.rule" ) barcode_base = fields.Integer(copy=False) generate_type = fields.Selection( related="barcode_rule_id.generate_type", ) @api.model def create(self, vals): """It creates a new barcode if automation is active.""" barcode_rule = self.env["barcode.rule"].get_automatic_rule(self._name) if barcode_rule.exists(): vals.update({"barcode_rule_id": barcode_rule.id}) record = super().create(vals) if barcode_rule: record.generate_base() record.generate_barcode() return record # View Section def generate_base(self): for item in self: if item.generate_type != "sequence": raise exceptions.UserError( _( "Generate Base can be used only with barcode rule with" " 'Generate Type' set to 'Base managed by Sequence'" ) ) else: item.barcode_base = item.barcode_rule_id.sequence_id.next_by_id() def generate_barcode(self): for item in self: padding = item.barcode_rule_id.padding str_base = str(item.barcode_base).rjust(padding, "0") custom_code = self._get_custom_barcode(item) if custom_code: custom_code = custom_code.replace("." * padding, str_base) barcode_class = barcode.get_barcode_class(item.barcode_rule_id.encoding) item.barcode = barcode_class(custom_code) # Custom Section @api.model def _get_custom_barcode(self, item): """ If the pattern is '23.....{NNNDD}' this function will return '23.....00000' Note : Overload _get_replacement_char to have another char instead that replace 'N' and 'D' char. """ if not item.barcode_rule_id: return False # Define barcode custom_code = item.barcode_rule_id.pattern custom_code = custom_code.replace("{", "").replace("}", "") custom_code = custom_code.replace("D", self._get_replacement_char("D")) return custom_code.replace("N", self._get_replacement_char("N")) @api.model def _get_replacement_char(self, char): """ Can be overload by inheritance Define wich character will be used instead of the 'N' or the 'D' char, present in the pattern of the barcode_rule_id """ return "0"
34.934066
3,179
5,043
py
PYTHON
15.0
# Copyright (C) 2014-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # Copyright 2017 LasLabs Inc. # @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, exceptions, fields, models, tools _GENERATE_TYPE = [ ("no", "No generation"), ("manual", "Base set Manually"), ("sequence", "Base managed by Sequence"), ] class BarcodeRule(models.Model): _inherit = "barcode.rule" # Column Section generate_type = fields.Selection( selection=_GENERATE_TYPE, required=True, default="no", help="Allow to generate barcode, including a number" " (a base) in the final barcode.\n" " 'Base Set Manually' : User should set manually the value of the" " barcode base\n" " 'Base managed by Sequence': User will use a button to generate a" " new base. This base will be generated by a sequence", ) generate_model = fields.Selection( selection=[], help="If 'Generate Type' is set, mention the model related to this" " rule.", ) padding = fields.Integer(compute="_compute_padding", readonly=True, store=True) sequence_id = fields.Many2one(comodel_name="ir.sequence") generate_automate = fields.Boolean( string="Automatic Generation", help="Check this to automatically generate a barcode upon creation of " "a new record in the mixed model.", ) # Compute Section @api.depends("pattern") def _compute_padding(self): for rule in self: rule.padding = rule.pattern.count(".") # On Change Section @api.onchange("generate_type") def onchange_generate_type(self): for rule in self: if rule.generate_type == "no": rule.generate_model = False # Constrains Section @api.constrains("generate_model", "generate_automate") def _check_generate_model_automate(self): """It should not allow two automated barcode generators per model. It also clears the cache of automated rules if necessary. """ for record in self: if not record.generate_automate: continue # This query is duplicated, but necessary because the other # method is cached & we need a completely current result. domain = [ ("generate_model", "=", record.generate_model), ("generate_automate", "=", True), ] if len(self.search(domain)) > 1: raise exceptions.ValidationError( _( "Only one rule per model can be used for automatic " "barcode generation." ) ) # CRUD @api.model def create(self, vals): self._clear_cache(vals) return super().create(vals) def write(self, vals): self._clear_cache(vals) return super().write(vals) # View Section def generate_sequence(self): sequence_obj = self.env["ir.sequence"] for rule in self: if rule.generate_type != "sequence": raise exceptions.UserError( _( "Generate Sequence is possible only if 'Generate Type'" " is set to 'Base managed by Sequence'" ) ) sequence = sequence_obj.create(self._prepare_sequence(rule)) rule.sequence_id = sequence.id # Custom Section @api.model def _prepare_sequence(self, rule): return { "name": _("Sequence - %s") % rule.name, "padding": rule.padding, } @api.model def get_automatic_rule(self, model): """It provides a cached indicator for barcode automation. Args: model (str): Name of model to search for. Returns: BarcodeRule: Recordset of automated barcode rules for model. """ return self.browse(self.get_automatic_rule_ids(model)) @api.model @tools.ormcache("model") def get_automatic_rule_ids(self, model): """It provides a cached indicator for barcode automation. Note that this cache needs to be explicitly cleared when `generate_automate` is changed on an associated `barcode.rule`. Args: model (str): Name of model to search for. Returns: list of int: IDs of the automated barcode rules for model. """ record = self.search( [("generate_model", "=", model), ("generate_automate", "=", True)] ) return record.ids @api.model def _clear_cache(self, vals): """It clears the caches if certain vals are updated.""" fields = ("generate_model", "generate_automate") if any(k in vals for k in fields): self.invalidate_cache(fields)
33.177632
5,043
962
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-stock-logistics-barcode", description="Meta package for oca-stock-logistics-barcode Odoo addons", version=version, install_requires=[ 'odoo-addon-barcodes_generator_abstract>=15.0dev,<15.1dev', 'odoo-addon-barcodes_generator_product>=15.0dev,<15.1dev', 'odoo-addon-base_gs1_barcode>=15.0dev,<15.1dev', 'odoo-addon-product_supplierinfo_barcode>=15.0dev,<15.1dev', 'odoo-addon-stock_barcodes>=15.0dev,<15.1dev', 'odoo-addon-stock_barcodes_gs1>=15.0dev,<15.1dev', 'odoo-addon-stock_picking_product_barcode_report>=15.0dev,<15.1dev', 'odoo-addon-stock_picking_product_barcode_report_secondary_unit>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
38.48
962
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
1,068
py
PYTHON
15.0
# Copyright 2020 Carlos Roca <carlos.roca@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Picking Product Barcode Report", "summary": "It provides a wizard to select how many barcodes print.", "version": "15.0.2.0.0", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "license": "AGPL-3", "maintainers": ["CarlosRoca13"], "category": "Extra Tools", "depends": ["stock"], "external_dependencies": {"python": ["python-barcode"]}, "data": [ "security/ir.model.access.csv", "views/res_config_settings_view.xml", "data/paperformat_label.xml", "wizard/stock_barcode_selection_printing_view.xml", "report/report_label_barcode.xml", "report/report_label_barcode_quant_package_template.xml", "report/report_label_barcode_template.xml", "report/report_label_custom.xml", "views/ir_actions_report_view.xml", ], "installable": True, }
41.076923
1,068
408
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade renamed_fields = [ ( "res.company", "res_company", "barcode_default_format", "barcode_report_default_format", ) ] @openupgrade.migrate() def migrate(env, version): openupgrade.rename_fields(env, renamed_fields)
22.666667
408
4,004
py
PYTHON
15.0
# Copyright 2020 Carlos Roca <carlos.roca@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestStockPickingProductBarcodeReport(TransactionCase): def setUp(self): super().setUp() self.supplier_location = self.env.ref("stock.stock_location_suppliers") self.stock_location = self.env.ref("stock.stock_location_stock") self.product_barcode = self.env["product.product"].create( {"name": "Test Product 1", "type": "product", "barcode": "1001"} ) self.product_no_barcode = self.env["product.product"].create( {"name": "Test Product 2", "type": "product"} ) self.package = self.env["stock.quant.package"].create({"name": "Pack-Test"}) partner = self.env["res.partner"].create({"name": "Test Partner"}) self.picking = self.env["stock.picking"].create( { "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, "partner_id": partner.id, "picking_type_id": self.env.ref( "stock.picking_type_in" ).id, # Operation type Receipts "move_ids_without_package": [ ( 0, 0, { "name": "Test 01", "product_id": self.product_barcode.id, "product_uom_qty": 20, "product_uom": self.product_barcode.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, }, ), ( 0, 0, { "name": "Test 02", "product_id": self.product_no_barcode.id, "product_uom_qty": 10, "product_uom": self.product_barcode.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.stock_location.id, }, ), ], } ) self.picking.action_confirm() for move_line_id in self.picking.move_line_ids: move_line_id.result_package_id = self.package self.wizard = ( self.env["stock.picking.print"] .with_context( **{"active_ids": [self.picking.id], "active_model": "stock.picking"} ) .create({}) ) def test_wizard_creation(self): self.wizard.barcode_report = self.env.ref( "stock_picking_product_barcode_report.action_label_barcode_report" ) self.wizard._onchange_picking_ids() self.assertEqual(1, len(self.wizard.product_print_moves.ids)) line = self.wizard.product_print_moves[0] self.assertEqual(line.label_qty, 1) self.assertEqual(line.product_id.id, self.product_barcode.id) # This two sentences are added just for check that not throw an exception self.wizard.barcode_format = "gs1_128" self.wizard.print_labels() # Check that wizard add lines with packages and the label not # throw an exception when trying to print it self.wizard.barcode_report = self.env.ref( "stock_picking_product_barcode_report.action_label_barcode_report_quant_package" ) self.wizard._onchange_picking_ids() self.assertEqual(2, len(self.wizard.product_print_moves.ids)) line = self.wizard.product_print_moves[0] self.assertEqual(line.label_qty, 1) self.assertEqual(line.product_id.id, self.product_barcode.id) self.wizard.print_labels()
44.988764
4,004
5,303
py
PYTHON
15.0
# Copyright 2020 Carlos Roca <carlos.roca@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ProductPrintingQty(models.TransientModel): _name = "stock.picking.line.print" _rec_name = "product_id" _description = "Print Picking Line" product_id = fields.Many2one( "product.product", string="Product", required=True, domain="[('id', '=', product_id)]", ) quantity = fields.Float(digits="Product Unit of Measure", required=True) label_qty = fields.Integer("Quantity of Labels") uom_id = fields.Many2one( "uom.uom", string="Unit of Measure", related="move_line_id.product_uom_id", readonly=False, ) lot_id = fields.Many2one("stock.production.lot", string="Lot/Serial Number") result_package_id = fields.Many2one( comodel_name="stock.quant.package", string="Dest. package" ) wizard_id = fields.Many2one("stock.picking.print", string="Wizard") move_line_id = fields.Many2one("stock.move.line", "Move") class WizStockBarcodeSelectionPrinting(models.TransientModel): _name = "stock.picking.print" _description = "Wizard to select how many barcodes have to be printed" @api.model def default_get(self, fields): ctx = self.env.context.copy() res = super().default_get(fields) if ctx.get("active_ids") and ctx.get("active_model") == "stock.picking": picking_ids = self.env["stock.picking"].browse(ctx.get("active_ids")) res.update({"picking_ids": picking_ids.ids}) return res def _default_barcode_report(self): barcode_report = self.env.company.barcode_default_report if not barcode_report: barcode_report = self.env.ref( "stock_picking_product_barcode_report.action_label_barcode_report" ) return barcode_report picking_ids = fields.Many2many("stock.picking") product_print_moves = fields.One2many( "stock.picking.line.print", "wizard_id", "Moves" ) barcode_format = fields.Selection( selection=[("gs1_128", "Display GS1_128 format for barcodes")], default=lambda self: self.env.company.barcode_report_default_format, ) barcode_report = fields.Many2one( comodel_name="ir.actions.report", string="Report to print", domain=[("is_barcode_label", "=", True)], default=_default_barcode_report, required=True, ) is_custom_label = fields.Boolean(compute="_compute_is_custom_label") html_content = fields.Html() label_qty = fields.Integer(default=1) @api.onchange("picking_ids", "barcode_report") def _onchange_picking_ids(self): product_print_moves = [(5, 0)] line_fields = [f for f in self.env["stock.picking.line.print"]._fields.keys()] product_print_moves_data_tmpl = self.env[ "stock.picking.line.print" ].default_get(line_fields) for picking_id in self.picking_ids.ids: picking = self.env["stock.picking"].browse(picking_id) for move_line in self._get_move_lines(picking): product_print_moves_data = dict(product_print_moves_data_tmpl) product_print_moves_data.update( self._prepare_data_from_move_line(move_line) ) if product_print_moves_data: product_print_moves.append((0, 0, product_print_moves_data)) if self.picking_ids: self.product_print_moves = product_print_moves @api.model def _get_move_lines(self, picking): stock_move_line_to_print_id = self.env.context.get( "stock_move_line_to_print", False ) if stock_move_line_to_print_id: return self.env["stock.move.line"].browse(stock_move_line_to_print_id) if self.barcode_report == self.env.ref( "stock_picking_product_barcode_report.action_label_barcode_report_quant_package" ): return picking.move_line_ids.filtered("result_package_id") elif self.barcode_report == self.env.ref( "stock_picking_product_barcode_report.action_label_barcode_report" ): return picking.move_line_ids.filtered("product_id.barcode") return picking.move_line_ids @api.model def _prepare_data_from_move_line(self, move_line): return { "product_id": move_line.product_id.id, "quantity": move_line.qty_done, "label_qty": 1, "move_line_id": move_line.id, "uom_id": move_line.product_uom_id.id, "lot_id": move_line.lot_id.id, "result_package_id": move_line.result_package_id.id, } def print_labels(self): if self.is_custom_label: return self.barcode_report.report_action(self) print_move = self.product_print_moves.filtered(lambda p: p.label_qty > 0) if print_move: return self.barcode_report.report_action(self.product_print_moves) @api.onchange("barcode_report") def _compute_is_custom_label(self): for record in self: record.is_custom_label = record.barcode_report.is_custom_label
39.574627
5,303
335
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class IrActionsReport(models.Model): _inherit = "ir.actions.report" is_barcode_label = fields.Boolean(string="Barcode label") is_custom_label = fields.Boolean(string="Custom label")
33.5
335
581
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class Company(models.Model): _inherit = "res.company" barcode_report_default_format = fields.Selection( [("gs1_128", "Display GS1_128 format for barcodes")], string="Method to choose the barcode formating", ) barcode_default_report = fields.Many2one( comodel_name="ir.actions.report", string="Default template for barcode labels", domain=[("is_barcode_label", "=", True)], )
32.277778
581
657
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" barcode_report_default_format = fields.Selection( string="Method to choose the barcode formating", related="company_id.barcode_report_default_format", readonly=False, ) barcode_default_report = fields.Many2one( comodel_name="ir.actions.report", related="company_id.barcode_default_report", string="Default template for barcode labels", readonly=False, )
32.85
657
1,430
py
PYTHON
15.0
# Copyright 2020 Carlos Roca <carlos.roca@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import barcode # pylint: disable=missing-manifest-dependency from barcode.writer import SVGWriter # pylint: disable=missing-manifest-dependency from odoo import http from odoo.http import request from odoo.addons.web.controllers.main import ReportController class ReportController(ReportController): @http.route() def report_barcode( self, type, # pylint: disable=redefined-builtin value, width=600, height=100, humanreadable=0, quiet=1, ): if type == "gs1_128": Gs1_128 = barcode.get_barcode_class("gs1_128") gs1_182 = Gs1_128(str(value), writer=SVGWitoutTextWriter()) image = gs1_182.render() return request.make_response( image, headers=[("Content-Type", "image/svg+xml")] ) return super().report_barcode( type, value, width=width, height=height, humanreadable=humanreadable, quiet=quiet, ) class SVGWitoutTextWriter(SVGWriter): """This class extend the SVGWriter of python-barcode to delete the text on the barcode image generated by this addon.""" def _create_text(self, xpos, ypos): self.font_size = 0 self.text = None
31.086957
1,430
959
py
PYTHON
15.0
# Copyright (C) 2014-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # Copyright (C) 2018 Komit (https://komit-consulting.com) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Generate Barcodes for Products", "summary": "Generate Barcodes for Products (Templates and Variants)", "version": "15.0.1.0.0", "category": "Tools", "author": "GRAP, La Louve, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "license": "AGPL-3", "depends": ["barcodes_generator_abstract", "product"], "data": ["views/view_product_product.xml", "views/view_product_template.xml"], "maintainers": ["legalsylvain"], "demo": [ "demo/res_users.xml", "demo/barcode_rule.xml", "demo/product.xml", "demo/function.xml", ], }
39.958333
959
2,647
py
PYTHON
15.0
# Copyright (C) 2016-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class Tests(TransactionCase): """Tests 'Barcodes Generator for Products'""" def setUp(self): super().setUp() self.template_obj = self.env["product.template"] self.product_obj = self.env["product.product"] self.barcode_rule = self.env["barcode.rule"].create( { "name": "Product Rule Test", "barcode_nomenclature_id": self.env.ref( "barcodes.default_barcode_nomenclature" ).id, "type": "product", "sequence": 999, "encoding": "ean13", "pattern": "20.....{NNNDD}", "generate_type": "manual", "generate_model": "product.product", } ) # Test Section def test_01_manual_generation_template(self): self.template_mono = self.template_obj.create( { "name": "Template Mono Variant", "barcode_rule_id": self.barcode_rule.id, "barcode_base": 50, } ) self.template_mono.generate_barcode() self.assertEqual( self.template_mono.barcode, "2000050000003", "Incorrect Manual Barcode Generation for non varianted Template." " Pattern : %s - Base : %s" % ( self.template_mono.barcode_rule_id.pattern, self.template_mono.barcode_base, ), ) def test_02_manual_generation_product(self): self.template_multi = self.template_obj.create( {"name": "Template Multi Variant"} ) self.product_variant_1 = self.product_obj.create( { "name": "Variant 1", "product_tmpl_id": self.template_multi.id, "barcode_rule_id": self.barcode_rule.id, "barcode_base": 10001, } ) self.product_variant_1.generate_barcode() self.assertEqual( self.product_variant_1.barcode, "2010001000006", "Incorrect Manual Barcode Generation for varianted Product." " Pattern : %s - Base : %s" % ( self.product_variant_1.barcode_rule_id.pattern, self.product_variant_1.barcode_base, ), )
35.77027
2,647
1,866
py
PYTHON
15.0
# Copyright (C) 2014-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # @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 ProductTemplate(models.Model): _inherit = "product.template" # Related to display product product information if is_product_variant barcode_rule_id = fields.Many2one( related="product_variant_ids.barcode_rule_id", string="Barcode Rule", readonly=False, comodel_name="barcode.rule", ) barcode_base = fields.Integer( related="product_variant_ids.barcode_base", readonly=False, string="Barcode Base", ) generate_type = fields.Selection( string="Generate Type", readonly=True, related="product_variant_ids.barcode_rule_id.generate_type", ) # View Section def generate_base(self): self.product_variant_ids.generate_base() def generate_barcode(self): self.ensure_one() self.product_variant_ids.generate_barcode() @api.onchange("barcode_rule_id") def onchange_barcode_rule_id(self): self.generate_type = self.barcode_rule_id.generate_type # Overload Section @api.model def create(self, vals): template = super().create(vals) # this is needed to set given values to first variant after creation # these fields should be moved to product as lead to confusion # (Ref. product module feature in Odoo Core) related_vals = {} for field in ["barcode_rule_id", "barcode_base"]: if vals.get(field, False): related_vals[field] = vals[field] if related_vals: template.write(related_vals) return template
32.172414
1,866
400
py
PYTHON
15.0
# Copyright (C) 2014-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class ProductProduct(models.Model): _name = "product.product" _inherit = ["product.product", "barcode.generate.mixin"]
36.363636
400
432
py
PYTHON
15.0
# Copyright (C) 2014-Today GRAP (http://www.grap.coop) # Copyright (C) 2016-Today La Louve (http://www.lalouve.net) # @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 BarcodeRule(models.Model): _inherit = "barcode.rule" generate_model = fields.Selection(selection_add=[("product.product", "Products")])
36
432
781
py
PYTHON
15.0
# Copyright 2020 Lorenzo Battistini @ TAKOBI # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). { "name": "Barcode in supplier pricelist", "summary": "Add a barcode to supplier pricelist items", "version": "15.0.1.1.0", "development_status": "Beta", "category": "Hidden", "website": "https://github.com/OCA/stock-logistics-barcode", "author": "TAKOBI, Odoo Community Association (OCA)", "maintainers": ["eLBati"], "license": "LGPL-3", "application": False, "installable": True, "preloadable": True, "depends": [ # we need purchase to view seller_ids in product form "purchase", ], "data": [ "views/supplierinfo_views.xml", "views/product_views.xml", ], "demo": [], }
31.24
781
410
py
PYTHON
15.0
from odoo import fields, models class SupplierInfo(models.Model): _inherit = "product.supplierinfo" barcode = fields.Char( copy=False, help="Article number used by supplier for product identification.", ) _sql_constraints = [ ( "barcode_uniq", "unique(barcode)", "A barcode can only be assigned to one product !", ) ]
22.777778
410
670
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Picking Product Barcode Report Secondary Unit", "summary": "Set by default the maximum quantity of labels to print.", "version": "15.0.1.1.0", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "license": "AGPL-3", "maintainers": ["CarlosRoca13"], "category": "Extra Tools", "depends": ["stock_picking_product_barcode_report", "stock_secondary_unit"], "external_dependencies": {"python": ["python-barcode"]}, "installable": True, }
44.666667
670
3,743
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestStockPickingProductBarcodeReportSecondaryUnit(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") cls.stock_location = cls.env.ref("stock.stock_location_stock") primary_uom = cls.env.ref("uom.product_uom_kgm") cls.product_barcode = cls.env["product.product"].create( { "name": "Test Product 1", "type": "product", "barcode": "1001", "uom_id": primary_uom.id, "uom_po_id": primary_uom.id, "qty_available": 300, "secondary_uom_ids": [ ( 0, 0, { "code": "TB", "name": "Test Box", "uom_id": cls.env.ref("uom.product_uom_unit").id, "factor": 10, }, ), ( 0, 0, { "code": "TP", "name": "Test Package", "uom_id": cls.env.ref("uom.product_uom_unit").id, "factor": 20, }, ), ], } ) partner = cls.env["res.partner"].create({"name": "Test Partner"}) picking_receipt_type = cls.env.ref("stock.picking_type_in") cls.picking = cls.env["stock.picking"].create( { "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, "partner_id": partner.id, "picking_type_id": picking_receipt_type.id, "move_ids_without_package": [ ( 0, 0, { "name": "Test 01", "product_id": cls.product_barcode.id, "quantity_done": 50, "product_uom": cls.product_barcode.uom_id.id, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, }, ) ], } ) cls.picking.button_validate() def _create_print_wizard(self): self.wizard = ( self.env["stock.picking.print"] .with_context(active_ids=[self.picking.id], active_model="stock.picking") .create({}) ) def test_wizard_creation(self): self._create_print_wizard() self.wizard._onchange_picking_ids() self.assertEqual(1, len(self.wizard.product_print_moves.ids)) line = self.wizard.product_print_moves[0] self.assertEqual(line.label_qty, 5) self.assertEqual(line.product_id.id, self.product_barcode.id) def test_wizard_creation_with_secondary_uom_move(self): sml = self.picking.move_line_ids sml.secondary_uom_id = self.product_barcode.secondary_uom_ids[1] sml.secondary_uom_qty = 2 self._create_print_wizard() self.wizard._onchange_picking_ids() self.assertEqual(1, len(self.wizard.product_print_moves.ids)) line = self.wizard.product_print_moves[0] self.assertEqual(line.label_qty, 2)
39.819149
3,743
799
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from math import ceil from odoo import api, models class WizStockBarcodeSelectionPrinting(models.TransientModel): _inherit = "stock.picking.print" @api.model def _prepare_data_from_move_line(self, move_line): res = super()._prepare_data_from_move_line(move_line) if move_line.secondary_uom_id: factor = move_line.secondary_uom_id.factor elif move_line.product_id.secondary_uom_ids: factor = min( move_line.product_id.secondary_uom_ids, key=lambda u: u.factor ).factor else: factor = 1.0 res["label_qty"] = ceil(move_line.qty_done / (factor or 1.0)) return res
33.291667
799
601
py
PYTHON
15.0
# Copyright 2012-2014 Numérigraphe SARL. { "name": "GS1 Barcode API", "summary": "Decoding API for GS1-128 (aka UCC/EAN-128) and GS1-Datamatrix", "version": "15.0.1.0.0", "author": "Numérigraphe, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-barcode", "category": "Generic Modules/Inventory Control", "depends": ["base"], "data": [ "views/gs1_barcode.xml", "views/res_users.xml", "data/gs1_barcode.csv", "security/ir.model.access.csv", ], "installable": True, "license": "AGPL-3", }
33.277778
599
2,534
py
PYTHON
15.0
# © 2019 Wassim Ghannoum <wassim@mediaengagers.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo.exceptions import ValidationError from odoo.tests import common _logger = logging.getLogger(__name__) class TestGS1Barcode(common.TransactionCase): def test_decode(self): GS = "\x1D" PREFIX = "" # AI 01 (GTIN, fixed length) gtin = "03400933816759" # AI 17 (expiry date) - day 0 will be replaced with day 31 expiry = "140500" # AI 10 (lot number, variable length) lot = "B04059A" # AI 310 (Net Weight in Kg, 5 decimals) weight = "006385" barcode = PREFIX + "01" + gtin barcode += "17" + expiry barcode += "10" + lot + GS barcode += "3105" + weight expiry = "140501" barcode += "15" + expiry result = self.env["gs1_barcode"].decode(barcode) assert len(result) == 5, "The barcode should decode to 5 AIs" assert result.get("01") == gtin, "The GTIN should be %s" % gtin assert result.get("17") == "2014-05-31" assert result.get("10") == lot, "The lot should be %s" % lot assert result.get("310") == 0.06385, "The weight should be %s" % weight # AI 311 (expiry date) - day 0 will be replaced with day 31 expiry = "140515" # AI 11 (lot number, variable length) lot = "B04059A" weight = "006385" barcode = PREFIX + "01" + gtin barcode += "11" + expiry result = self.env["gs1_barcode"].decode(barcode) assert len(result) == 2, "The barcode should decode to 4 AIs" assert result.get("11") == "2014-05-15" gtin = "03400933816759" # AI 17 (expiry date) - day 0 will be replaced with day 31 expiry = "140522" # AI 10 (lot number, variable length) lot = "B04059A" # AI 310 (Net Weight in Kg, 5 decimals) weight = "006385" barcode = PREFIX + "01" + gtin + "17" barcode += expiry + "10" + lot + GS + "3105" + weight result = self.env["gs1_barcode"].decode(barcode) assert len(result) == 4, "The barcode should decode to 4 AIs" assert result.get("01") == gtin, "The GTIN should be %s" % gtin assert result.get("17") == "2014-05-22" assert result.get("10") == lot, "The lot should be %s" % lot try: self.env["gs1_barcode"].decode(barcode) except ValidationError as exc: _logger.error(exc)
40.854839
2,533
8,438
py
PYTHON
15.0
# Copyright 2012-2014 Numérigraphe SARL. # Make it easier to divide integers and get floating point results import re from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import _, api, exceptions, fields, models class GS1Barcode(models.Model): """GS1-128/GS1-Datamatrix barcode decoder API and configuration""" _name = "gs1_barcode" _description = __doc__ _order = "ai" ai = fields.Char( "Application Identifier", size=14, required=True, help="The standard Application Identifier (AI)", ) name = fields.Char("Description", required=True, translate=True) length_fixed = fields.Boolean( "Fixed-length Data", default=True, help=( "Indicates whether the length of the data " "for this Application Identifier is fixed or not." ), ) length_max = fields.Integer( "Maximum Data Length", default=30, required=True, help="Maximum length of the data for this Application Identifier.", ) length_min = fields.Integer( "Minimum Data Length", help="Minimum length of the data for this Application Identifier.", ) decimal = fields.Boolean( "Decimal Indicator", help=( "Indicates whether a digit is expected before the data for this " "Application Identifier to indicate the position of the decimal " "point." ), ) data_type = fields.Selection( [ ("string", "Any character string"), ("numeric", "Numeric value"), ("date", "Date"), ], default="string", required=True, ) _sql_constraints = [ ("ai_uniq", "unique (ai)", "The Application Identifier must be unique!") ] @api.model def decode(self, barcode_string): """ Decode a GS1-128/GS1-Datamatrix string to dictionary of values with Application Identifiers as keys. Please note that the string MUST contain a <GS> character (group separator) after each variable-length value. <GS> is usually expected to be sent as ASCII character 29 but that may be configured per user. If the same Application Identifier is present several times in the string, only the its last value is returned. @type barcode_string: string @param barcode_string: GS1-128/GS1-Datamatrix string to decode @return: A dictionary of values with Application Identifiers as keys """ def normalize_date(datestring): """ Convert dates like '151231' as Odoo formatted '2015-12-31'. Note that the day can be underspecified as '00'. As per https://www.gs1.ch/docs/default-source/gs1-system-document/\ genspecs/general-specifications_e_-section-3.pdf?sfvrsn=18, section 3.4.2, this denotes the end of the month. """ if datestring.endswith("00"): date = ( datetime.strptime(datestring[:4], "%y%m") + relativedelta(months=1) - relativedelta(days=1) ) else: date = datetime.strptime(datestring, "%y%m%d") return fields.Date.to_string(date) # Prefix and Group Separator # Search if the barcode contains the \x1D group separator already, # and then use it. Some scanners are able to pass this group separator, # and others are not able. If a user works with both devices, # this is becomes the most effective mechanism to ensure co-existence. if "\x1D" in barcode_string: separator = "\x1D" else: separator = self.env.user.gs1_barcode_separator or "\x1D" prefix = self.env.user.gs1_barcode_prefix or "" if not barcode_string.startswith(prefix): raise exceptions.ValidationError( _( "Could not decode barcode : wrong prefix - the code should " 'start with "%s"' ) % prefix ) # We are going to use lots of regular expressions to decode the string, # and they all boil down to the following templates: # * regular expression template to match the AI code %s, to the group # "ai". Must be formated with a string AI = r"(?P<ai>%s)" # * regular expression template to match a fixed-length value of # %d characters, to the group called "value". # Must be formated with an integer. # <GS> can optionally follow after a fixed length value. See p.19 # of http://www.gs1.org/docs/barcodes/GS1_DataMatrix_Guideline.pdf FIXED_LENGTH = r"(?P<value>.{%d}" + separator + r"?)" # * regular expression to match a variable length value ending with # a <GS> character, to the group called "value". # Must be formated with a pair of integers. VARIABLE_LENGTH = r"(?P<value>[^" + separator + r"]{%d,%d}" + separator + r"?)" # * regular expression to match the position of the decimal separator # after the AI code, to the group called "decimal". DECIMAL = r"(?P<decimal>\d)" # Make a dictionary of compiled regular expressions to decode the # string ai_regexps = {} value_regexps = {} types = {} for config in self.search([]): # Compile a regular expression to match the Application Identifier ai = config.ai ai_regexps[ai] = re.compile(AI % ai) # Compile a regular expression to match the data format if config.length_fixed: value_regexp = FIXED_LENGTH % config.length_max else: value_regexp = VARIABLE_LENGTH % (config.length_min, config.length_max) if config.decimal: value_regexp = DECIMAL + value_regexp value_regexps[ai] = re.compile(value_regexp) # remember the data type types[ai] = config.data_type # Now let's decode the string, one Application Identifier at a time results = {} # Start searching from the first character after the prefix position = len(prefix) while position < len(barcode_string): # Search for a known Application Identifier for (ai, regexp) in list(ai_regexps.items()): match = regexp.match(barcode_string, position) if not match: continue position += len(match.group("ai")) # We found the Application Identifier, now decode the value try: groups = ( value_regexps[ai].match(barcode_string, position).groupdict() ) except AttributeError as e: raise exceptions.ValidationError( _( "Could not decode barcode: incorrect value for " 'Application Identifer "%(ai)s" at position %(position)d' ) % ({"ai": ai, "position": position}) ) from e position += len(groups["value"]) results[ai] = groups["value"].replace(separator, "") if types[ai] == "numeric": results[ai] = int(results[ai]) if "decimal" in groups: # Account for the decimal position results[ai] /= 10 ** int(groups["decimal"]) position += len(groups["decimal"]) elif types[ai] == "date": results[ai] = normalize_date(results[ai]) # We know we won't match another AI for now, move on break else: # We couldn't find another valid AI in the rest of the code, # give up raise exceptions.ValidationError( _( "Could not decode barcode: unknown Application " "Identifier at position %d" ) % position ) return results
40.5625
8,437
874
py
PYTHON
15.0
# Copyright 2012-2014 Numérigraphe SARL. from odoo import fields, models class ResUsers(models.Model): _inherit = "res.users" gs1_barcode_prefix = fields.Char( "Prefix", help=( "The prefix that the barcode scanner will send when GS1-128 " "or GS1-Datamatrix codes are scanned. No prefix is expected " "if this fields is left empty" ), ) gs1_barcode_separator = fields.Char( "Group Separator", size=1, help=( "The characters that the barcode scanner will send when a " "<GS> (Group Separator) is encountered in a GS1-128 or " "GS1-Datamatrix code. <GS> is usually found when the data is of " "variable length. The ASCII character 29 will be expected by " "default if this field is left empty." ), )
33.576923
873
770
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Mail Autosubscribe", "summary": "Automatically subscribe partners to its company's business documents", "version": "15.0.1.0.3", "author": "Camptocamp SA, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Marketing", "depends": ["mail"], "external_dependencies": { "python": ["odoo_test_helper"], }, "website": "https://github.com/OCA/social", "data": [ "security/ir.model.access.csv", "views/mail_autosubscribe.xml", "views/mail_template.xml", "views/res_partner.xml", ], }
33.434783
769
5,721
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo_test_helper import FakeModelLoader from odoo.tests.common import Form, TransactionCase, tagged @tagged("post_install", "-at_install") class TestMailAutosubscribe(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Setup env cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # Load fake order model cls.loader = FakeModelLoader(cls.env, cls.__module__) cls.loader.backup_registry() from .models.fake_order import FakeOrder cls.loader.update_registry((FakeOrder,)) cls.fake_order_model = cls.env["ir.model"].search( [("model", "=", "fake.order")] ) # Email Template cls.mail_template = cls.env["mail.template"].create( { "model_id": cls.fake_order_model.id, "name": "Fake Order: Send by Mail", "subject": "Fake Order: {{object.partner_id.name}}", "partner_to": "{{object.partner_id.id}}", "body_html": "Hello, this is a fake order", } ) # Partners cls.commercial_partner = cls.env.ref("base.res_partner_4") cls.partner_1 = cls.env.ref("base.res_partner_address_13") cls.partner_2 = cls.env.ref("base.res_partner_address_14") cls.partner_3 = cls.env.ref("base.res_partner_address_24") # Autosubscribe rules cls.autosubscribe_fake_order = cls.env["mail.autosubscribe"].create( {"model_id": cls.fake_order_model.id} ) cls.partner_3.mail_autosubscribe_ids = [(4, cls.autosubscribe_fake_order.id)] # Empty fake.order cls.order = cls.env["fake.order"].create({"partner_id": cls.partner_2.id}) @classmethod def tearDownClass(cls): cls.loader.restore_registry() return super().tearDownClass() def test_message_subscribe(self): """Test autosubscribe on a basic workflow""" self.assertFalse(self.order.message_partner_ids, "No subscribers yet") self.order.message_subscribe([self.order.partner_id.id]) self.assertEqual( self.order.message_partner_ids, self.partner_2 | self.partner_3, "Partner 3 is automatically subscribed", ) def test_message_subscribe_disabled(self): """Test autosubscribe on a basic workflow (disabled)""" self.partner_3.mail_autosubscribe_ids = [(5, False)] self.assertFalse(self.order.message_partner_ids, "No subscribers yet") self.order.message_subscribe([self.order.partner_id.id]) self.assertEqual( self.order.message_partner_ids, self.partner_2, "Partner 2 is the only subscriber", ) def test_mail_template(self): """Test autosubscribe when partner is set in the mail.template partners_to""" self.mail_template.send_mail(self.order.id) message = self.order.message_ids[0] self.assertEqual(message.partner_ids, self.partner_2 | self.partner_3) def test_mail_template_disabled(self): """Test autosubscribe when the partner is not an autosubscribe follower""" self.partner_3.mail_autosubscribe_ids = [(5, False)] self.mail_template.send_mail(self.order.id) message = self.order.message_ids[0] self.assertEqual(message.partner_ids, self.partner_2) def test_mail_template_no_autosubscribe_followers(self): """Test autosubscribe doesn't apply if it's disabled on the template""" self.mail_template.use_autosubscribe_followers = False self.mail_template.send_mail(self.order.id) message = self.order.message_ids[0] self.assertEqual(message.partner_ids, self.partner_2) def test_mail_template_default_recipients(self): """Test autosubscribe when using default recipients""" self.mail_template.use_default_to = True self.mail_template.send_mail(self.order.id) message = self.order.message_ids[0] self.assertEqual(message.partner_ids, self.partner_2 | self.partner_3) def test_mail_message_composer(self): """Test autosubscribe when using the mail composer""" self.assertFalse(self.order.message_partner_ids, "No subscribers yet") composer = Form( self.env["mail.compose.message"].with_context( default_model="fake.order", default_res_id=self.order.id, default_use_template=True, default_template_id=self.mail_template.id, default_composition_mode="comment", ) ) composer.save().action_send_mail() message = self.order.message_ids[0] self.assertEqual(message.partner_ids, self.partner_2 | self.partner_3) def test_mail_message_composer_no_autosubscribe_followers(self): """Test autosubscribe when using the mail composer and it's disabled""" self.mail_template.use_autosubscribe_followers = False composer = Form( self.env["mail.compose.message"].with_context( default_model="fake.order", default_res_id=self.order.id, default_use_template=True, default_template_id=self.mail_template.id, default_composition_mode="comment", ) ) composer.save().action_send_mail() message = self.order.message_ids[0] self.assertEqual(message.partner_ids, self.partner_2)
43.333333
5,720
408
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class FakeOrder(models.Model): _name = "fake.order" _inherit = "mail.thread" _description = "Fake sale.order like model" partner_id = fields.Many2one("res.partner", required=True)
31.307692
407
1,492
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class BaseModel(models.AbstractModel): _inherit = "base" @api.model def _message_get_autosubscribe_followers_domain(self, partners): return [ ("id", "child_of", partners.commercial_partner_id.ids), ("mail_autosubscribe_ids.model", "=", self._name), ] @api.model def _message_get_autosubscribe_followers(self, partners): domain = self._message_get_autosubscribe_followers_domain(partners) return self.env["res.partner"].sudo().search(domain) def _message_get_default_recipients(self): # Overload to include auto follow document partners in the composer # Note: This only works if the template is configured with 'Default recipients' res = super()._message_get_default_recipients() if self.env.context.get("no_autosubscribe_followers"): return res for rec in self: partner_ids = res[rec.id]["partner_ids"] partners = self.env["res.partner"].sudo().browse(partner_ids) followers = rec._message_get_autosubscribe_followers(partners) follower_ids = [ follower.id for follower in followers if follower not in partners ] partner_ids += follower_ids return res
40.297297
1,491
1,390
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MailTemplate(models.Model): _inherit = "mail.template" use_autosubscribe_followers = fields.Boolean(default=True) def generate_recipients(self, results, res_ids): res = super().generate_recipients(results, res_ids) autosubscribe_followers = ( self.use_autosubscribe_followers and not self.env.context.get("no_autosubscribe_followers") # In this case, autosubscribers will be added by # :func:`_message_get_default_recipients` and not self.use_default_to and not self.env.context.get("tpl_force_default_to") ) if autosubscribe_followers: for res_id in res.keys(): partners = ( self.env["res.partner"].sudo().browse(res[res_id]["partner_ids"]) ) ResModel = self.env[self.model] followers = ResModel._message_get_autosubscribe_followers(partners) follower_ids = [ follower.id for follower in followers if follower not in partners ] res[res_id]["partner_ids"] += follower_ids return res
40.852941
1,389
1,192
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class MailThread(models.AbstractModel): _inherit = "mail.thread" def message_subscribe(self, partner_ids=None, subtype_ids=None): # Overload to automatically subscribe autosubscribe followers. autosubscribe_followers = not self.env.context.get("no_autosubscribe_followers") if partner_ids and autosubscribe_followers: partners = self.env["res.partner"].sudo().browse(partner_ids) followers = self._message_get_autosubscribe_followers(partners) follower_ids = [ follower.id for follower in followers if follower not in partners and follower not in self.message_partner_ids ] if isinstance(partner_ids, tuple): partner_ids += tuple(follower_ids) else: partner_ids += follower_ids return super().message_subscribe( partner_ids=partner_ids, subtype_ids=subtype_ids, )
41.068966
1,191
1,025
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class MailAutosubscribe(models.Model): _name = "mail.autosubscribe" _description = "Mail Autosubscribe" _sql_constraints = [ ( "model_id_unique", "UNIQUE(model_id)", "There's already a rule for this model", ) ] model_id = fields.Many2one( "ir.model", required=True, index=True, ondelete="cascade", ) model = fields.Char( related="model_id.model", string="Model Name", store=True, index=True, ) name = fields.Char( compute="_compute_name", store=True, readonly=False, ) @api.depends("model_id") def _compute_name(self): for rec in self: if not rec.name: rec.name = rec.model_id.name
24.380952
1,024
453
py
PYTHON
15.0
# Copyright 2021 Camptocamp (http://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" mail_autosubscribe_ids = fields.Many2many( "mail.autosubscribe", string="Autosubscribe Models", column1="partner_id", column2="model_id", )
28.25
452
599
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging try: from odoo.addons.mail_tracking.hooks import column_add_with_value except ImportError: column_add_with_value = False _logger = logging.getLogger(__name__) def pre_init_hook(cr): if column_add_with_value: _logger.info("Creating mailing_contact.email_score column with value 50.0") column_add_with_value( cr, "mailing_contact", "email_score", "double precision", 50.0 )
29.95
599
901
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # Copyright 2017 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Mail tracking for mass mailing", "summary": "Improve mass mailing email tracking", "version": "15.0.1.0.0", "category": "Social Network", "website": "https://github.com/OCA/social", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "auto_install": True, "depends": ["mass_mailing", "mail_tracking"], "data": [ "views/mail_tracking_email_view.xml", "views/mail_trace_view.xml", "views/mail_mass_mailing_view.xml", "views/mailing_contact_view.xml", ], "pre_init_hook": "pre_init_hook", }
34.653846
901
5,169
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # Copyright 2017 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from unittest import mock from odoo.tests.common import TransactionCase, tagged from odoo.tools import mute_logger mock_send_email = "odoo.addons.base.models.ir_mail_server.IrMailServer.send_email" @tagged("-at_install", "post_install") class TestMassMailing(TransactionCase): def setUp(self, *args, **kwargs): super().setUp(*args, **kwargs) self.list = self.env["mailing.list"].create({"name": "Test mail tracking"}) self.list.name = "{} #{}".format(self.list.name, self.list.id) self.contact_a = self.env["mailing.contact"].create( { "list_ids": [(6, 0, self.list.ids)], "name": "Test contact A", "email": "contact_a@example.com", } ) self.mailing = self.env["mailing.mailing"].create( { "subject": "Test subject", "email_from": "from@example.com", "mailing_model_id": self.env.ref( "mass_mailing.model_mailing_contact" ).id, "mailing_domain": "[('list_ids', 'in', %d)]" % self.list.id, "contact_list_ids": [(6, False, [self.list.id])], "body_html": "<p>Test email body</p>", "reply_to_mode": "new", } ) @mute_logger("odoo.addons.mail.models.mail_mail") def test_smtp_error(self): with mock.patch(mock_send_email) as mock_func: mock_func.side_effect = Warning("Mock test error") self.mailing.action_send_mail() for stat in self.mailing.mailing_trace_ids: if stat.mail_mail_id: stat.mail_mail_id.send() tracking = self.env["mail.tracking.email"].search( [("mail_id_int", "=", stat.mail_mail_id_int)] ) for track in tracking: self.assertEqual("error", track.state) self.assertEqual("Warning", track.error_type) self.assertEqual("Mock test error", track.error_description) self.assertEqual(stat.trace_status, "outgoing") self.assertEqual(stat.failure_type, "mail_smtp") self.assertTrue(self.contact_a.email_bounced) def test_tracking_email_link(self): self.mailing.action_send_mail() for stat in self.mailing.mailing_trace_ids: if stat.mail_mail_id: stat.mail_mail_id.send() tracking_email = self.env["mail.tracking.email"].search( [("mail_id_int", "=", stat.mail_mail_id_int)] ) self.assertTrue(tracking_email) self.assertEqual(tracking_email.mass_mailing_id.id, self.mailing.id) self.assertEqual(tracking_email.mail_stats_id.id, stat.id) self.assertEqual(stat.mail_tracking_id.id, tracking_email.id) # And now open the email metadata = { "ip": "127.0.0.1", "user_agent": "Odoo Test/1.0", "os_family": "linux", "ua_family": "odoo", } tracking_email.event_create("open", metadata) self.assertEqual(stat.trace_status, "open") def _tracking_email_bounce(self, event_type, state): self.mailing.action_send_mail() for stat in self.mailing.mailing_trace_ids: if stat.mail_mail_id: stat.mail_mail_id.send() tracking_email = self.env["mail.tracking.email"].search( [("mail_id_int", "=", stat.mail_mail_id_int)] ) # And now mark the email as bounce metadata = { "bounce_type": "499", "bounce_description": "Unable to connect to MX servers", } tracking_email.event_create(event_type, metadata) self.assertEqual(stat.trace_status, "bounce") def test_tracking_email_hard_bounce(self): self._tracking_email_bounce("hard_bounce", "bounced") def test_tracking_email_soft_bounce(self): self._tracking_email_bounce("soft_bounce", "soft-bounced") def test_tracking_email_reject(self): self._tracking_email_bounce("reject", "rejected") def test_tracking_email_spam(self): self._tracking_email_bounce("spam", "spam") def test_contact_tracking_emails(self): self._tracking_email_bounce("hard_bounce", "bounced") self.assertTrue(self.contact_a.email_bounced) self.assertTrue(self.contact_a.email_score < 50.0) self.contact_a.email = "other_contact_a@example.com" self.assertFalse(self.contact_a.email_bounced) self.assertTrue(self.contact_a.email_score == 50.0) self.contact_a.email = "contact_a@example.com" self.assertTrue(self.contact_a.email_bounced) self.assertTrue(self.contact_a.email_score < 50.0)
43.075
5,169
808
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailMassMailingContact(models.Model): _name = "mailing.contact" _inherit = ["mailing.contact", "mail.bounced.mixin"] email_score = fields.Float( string="Email score", readonly=True, store=False, compute="_compute_email_score" ) @api.depends("email") def _compute_email_score(self): with_email = self.filtered("email") for contact in with_email: contact.email_score = self.env[ "mail.tracking.email" ].email_score_from_email(contact.email) remaining = self - with_email remaining.email_score = 0.0
33.666667
808
907
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class MailTrace(models.Model): _inherit = "mailing.trace" mail_tracking_id = fields.Many2one( string="Mail tracking", comodel_name="mail.tracking.email", readonly=True ) tracking_event_ids = fields.One2many( string="Tracking events", comodel_name="mail.tracking.event", related="mail_tracking_id.tracking_event_ids", readonly=True, ) def write(self, values): """Ignore write from _postprocess_sent_message on selected ids""" to_ignore_ids = self.env.context.get("_ignore_write_trace_postprocess_ids") if to_ignore_ids: self = self.browse(set(self.ids) - set(to_ignore_ids)) return super().write(values)
34.884615
907
1,938
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailTrackingEvent(models.Model): _inherit = "mail.tracking.event" mass_mailing_id = fields.Many2one( string="Mass mailing", comodel_name="mailing.mailing", readonly=True, related="tracking_email_id.mass_mailing_id", store=True, ) @api.model def process_open(self, tracking_email, metadata): res = super().process_open(tracking_email, metadata) mail_mail_stats = self.sudo().env["mailing.trace"] domain = [("mail_mail_id_int", "=", tracking_email.mail_id_int)] mail_mail_stats.set_opened(domain=domain) return res def _tracking_set_bounce(self, tracking_email, metadata): mail_mail_stats = self.sudo().env["mailing.trace"] domain = [("mail_mail_id_int", "=", tracking_email.mail_id_int)] mail_mail_stats.set_bounced(domain=domain) @api.model def process_hard_bounce(self, tracking_email, metadata): res = super().process_hard_bounce(tracking_email, metadata) self._tracking_set_bounce(tracking_email, metadata) return res @api.model def process_soft_bounce(self, tracking_email, metadata): res = super().process_soft_bounce(tracking_email, metadata) self._tracking_set_bounce(tracking_email, metadata) return res @api.model def process_reject(self, tracking_email, metadata): res = super().process_reject(tracking_email, metadata) self._tracking_set_bounce(tracking_email, metadata) return res @api.model def process_spam(self, tracking_email, metadata): res = super().process_spam(tracking_email, metadata) self._tracking_set_bounce(tracking_email, metadata) return res
35.888889
1,938
2,316
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class MailTrackingEmail(models.Model): _inherit = "mail.tracking.email" mass_mailing_id = fields.Many2one( string="Mass mailing", comodel_name="mailing.mailing", readonly=True ) mail_stats_id = fields.Many2one( string="Mail statistics", comodel_name="mailing.trace", readonly=True ) mail_id_int = fields.Integer(string="Mail ID", readonly=True) @api.model def _statistics_link_prepare(self, tracking): """Inherit this method to link other object to mailing.trace""" return {"mail_tracking_id": tracking.id} @api.depends("mail_stats_id") def _compute_message_id(self): """For the mass mailings, the message id is stored in the mailing.trace record.""" res = super()._compute_message_id() for tracking in self.filtered("mail_stats_id"): tracking.message_id = tracking.mail_stats_id.message_id return res @api.model def create(self, vals): tracking = super().create(vals) # Link mail statistics with this tracking if tracking.mail_stats_id: tracking.mail_stats_id.write(self._statistics_link_prepare(tracking)) return tracking def _contacts_email_bounced_set(self, reason, event=None): recipients = [] if event and event.recipient_address: recipients.append(event.recipient_address) else: recipients = list(filter(None, self.mapped("recipient_address"))) for recipient in recipients: self.env["mailing.contact"].search( [("email", "=ilike", recipient)] ).email_bounced_set(self, reason, event=event) def smtp_error(self, mail_server, smtp_server, exception): res = super().smtp_error(mail_server, smtp_server, exception) self._contacts_email_bounced_set("error") return res def event_create(self, event_type, metadata): res = super().event_create(event_type, metadata) if event_type in {"hard_bounce", "spam", "reject"}: self._contacts_email_bounced_set(event_type) return res
38.6
2,316
2,620
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class MailMail(models.Model): _inherit = "mail.mail" @api.model def _tracking_email_prepare(self, partner, email): res = super()._tracking_email_prepare(partner, email) res["mail_id_int"] = self.id res["mass_mailing_id"] = self.mailing_id.id res["mail_stats_id"] = ( self.mailing_trace_ids[:1].id if self.mailing_trace_ids else False ) return res @api.model def _get_tracking_url(self): # Invalid this tracking image, we have other to do the same return False def _postprocess_sent_message( self, success_pids, failure_reason=False, failure_type=None ): """Set mailing traces in error according to mail tracking state If an exception is caught by ir.mail_server.send_email in mail_tracking module, the mail.tracking.email record will appear in error but the related mailing trace would still appear as sent because this method is called without any failure_type in mail.mail._send in the mail module (as Exception is not raised after being caught in mail_tracking module). Since this method not only sets the mailing.trace state in mass_mailing module but can also delete the mail.mail records in mail module, we need to ensure the mailing.trace is written accordingly to the tracking here, and avoid having the mass_mailing module set a 'sent' status if we had an exception, hence the usage of a context key to ignore possible writes. """ processed_ids = [] for mail in self: mail_tracking = mail.mailing_trace_ids.mail_tracking_id if mail.mailing_id and mail_tracking.state == "error": mail_failure_type = ( "mail_email_invalid" if mail_tracking.error_type == "no_recipient" else "mail_smtp" ) mail.mailing_trace_ids.write( { "failure_type": mail_failure_type, } ) processed_ids.extend(mail.mailing_trace_ids.ids) return super( MailMail, self.with_context(_ignore_write_trace_postprocess_ids=processed_ids), )._postprocess_sent_message( success_pids, failure_reason=failure_reason, failure_type=failure_type )
41.587302
2,620
786
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # Copyright 2018 Tecnativa - David Vidal # Copyright 2019 Tecnativa - Victor Martin # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Dynamic Mass Mailing Lists", "summary": "Mass mailing lists that get autopopulated", "version": "15.0.1.0.0", "category": "Marketing", "website": "https://github.com/OCA/social", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["mass_mailing_partner"], "data": [ "security/ir.model.access.csv", # This should go before "mailing_list_view.xml" "wizards/mailing_load_filter_views.xml", "views/mailing_list_view.xml", ], }
35.727273
786
7,053
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # Copyright 2020 Hibou Corp. - Jared Kipe # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from mock import patch from odoo.exceptions import ValidationError from odoo.tests import common, tagged @tagged("post_install", "-at_install") class DynamicListCase(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.tag = cls.env["res.partner.category"].create({"name": "testing tag"}) cls.partners = cls.env["res.partner"] for number in range(5): cls.partners |= cls.partners.create( { "name": "partner %d" % number, "category_id": [(4, cls.tag.id, False)], "email": "%d@example.com" % number, } ) cls.list = cls.env["mailing.list"].create( { "name": "test list", "dynamic": True, "sync_domain": repr([("category_id", "in", cls.tag.ids)]), } ) cls.mail = cls.env["mailing.mailing"].create( { "name": "test mass mailing", "subject": "test mass mailing", "contact_list_ids": [(4, cls.list.id, False)], } ) def test_list_sync(self): """List is synced correctly.""" Contact = self.env["mailing.contact"] # Partner 0 is not categorized self.partners[0].category_id = False # Partner 1 has no email self.partners[1].email = False # Set list as unsynced self.list.dynamic = False # Create contact for partner 0 in unsynced list contact0 = Contact.create( {"list_ids": [(4, self.list.id)], "partner_id": self.partners[0].id} ) self.list.flush() self.assertEqual(self.list.contact_count, 1) # Set list as add-synced self.list.dynamic = True self.list.action_sync() self.list.flush() self.assertEqual(self.list.contact_count, 4) self.assertTrue(contact0.exists()) # Set list as full-synced self.list.sync_method = "full" Contact.search( [ ("list_ids", "in", self.list.ids), ("partner_id", "=", self.partners[2].id), ] ).unlink() self.list.action_sync() self.list.flush() self.assertEqual(self.list.contact_count, 3) self.assertFalse(contact0.exists()) # Cannot add or edit contacts in fully synced lists with self.assertRaises(ValidationError): Contact.create( {"list_ids": [(4, self.list.id)], "partner_id": self.partners[0].id} ) contact1 = Contact.search([("list_ids", "in", self.list.ids)], limit=1) with self.assertRaises(ValidationError): contact1.name = "other" with self.assertRaises(ValidationError): contact1.email = "other@example.com" with self.assertRaises(ValidationError): contact1.partner_id = self.partners[0] # Unset dynamic list self.list.dynamic = False # Now the contact is created without exception Contact.create({"list_ids": [(4, self.list.id)], "email": "test@example.com"}) # Contacts can now be changed contact1.name = "other" def test_sync_when_sending_mail(self): """Check that list in synced when sending a mass mailing.""" self.list.action_sync() self.list.flush() self.assertEqual(self.list.contact_count, 5) # Create a new partner self.partners.create( { "name": "extra partner", "category_id": [(4, self.tag.id, False)], "email": "extra@example.com", } ) # Mock sending low level method, because an auto-commit happens there with patch("odoo.addons.mail.models.mail_mail.MailMail.send") as s: self.mail.action_send_mail() self.assertEqual(1, s.call_count) self.list.flush() self.assertEqual(6, self.list.contact_count) def test_load_filter(self): domain = "[('id', '=', 1)]" ir_filter = self.env["ir.filters"].create( {"name": "Test filter", "model_id": "res.partner", "domain": domain} ) wizard = ( self.env["mailing.load.filter"] .with_context(active_id=self.list.id) .create({"filter_id": ir_filter.id}) ) wizard.load_filter() self.assertEqual(self.list.sync_domain, domain) def test_change_partner(self): self.list.sync_method = "full" self.list.action_sync() # This shouldn't fail self.partners[:1].write({"email": "test_mass_mailing_list_dynamic@example.org"}) def test_is_synced(self): self.list.dynamic = False self.list._onchange_dynamic() # It shouldn't change when list is reversed to normal self.assertTrue(self.list.is_synced) self.list.dynamic = True self.list._onchange_dynamic() self.assertFalse(self.list.is_synced) self.list.action_sync() self.assertTrue(self.list.is_synced) def test_partners_merge(self): tag2 = self.tag.copy({"name": "Tag 2"}) self.list.sync_method = "full" list2 = self.list.copy( { "name": "test list 2", "sync_domain": repr([("category_id", "in", tag2.ids)]), } ) partner_1 = self.partners.create( { "name": "Demo 1", "email": "demo1@demo.com", "category_id": [(4, self.tag.id, False)], } ) partner_2 = self.partners.create( { "name": "Demo 2", "email": "demo2@demo.com", "category_id": [(4, self.tag.id, False), (4, tag2.id, False)], } ) self.list.action_sync() list2.action_sync() self.assertTrue(partner_1.id in self.list.contact_ids.mapped("partner_id").ids) self.assertTrue(partner_2.id in self.list.contact_ids.mapped("partner_id").ids) self.assertFalse(partner_1.id in list2.contact_ids.mapped("partner_id").ids) self.assertTrue(partner_2.id in list2.contact_ids.mapped("partner_id").ids) # Wizard partner merge (partner_1 + partner_2) in partner_i1 wizard = self.env["base.partner.merge.automatic.wizard"].create( { "state": "option", "dst_partner_id": partner_1.id, "partner_ids": [(4, partner_1.id), (4, partner_2.id)], } ) wizard.action_merge() self.assertTrue(partner_1.id in self.list.contact_ids.mapped("partner_id").ids) self.assertTrue(partner_1.id in list2.contact_ids.mapped("partner_id").ids)
38.741758
7,051
969
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # Copyright 2019 Tecnativa - Victor M.M. Torres # Copyright 2020 Hibou Corp. - Jared Kipe # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, models from odoo.exceptions import ValidationError class MassMailingContact(models.Model): _inherit = "mailing.contact" @api.constrains("partner_id", "list_ids", "name", "email") def _check_no_manual_edits_on_fully_synced_lists(self): if self.env.context.get("syncing"): return full_synced_lists = self.mapped("list_ids").filtered( lambda x: x.dynamic and x.sync_method == "full" ) if full_synced_lists: raise ValidationError( _( "Cannot edit manually contacts in a fully " "synchronized list. Change its sync method or execute " "a manual sync instead." ) )
35.888889
969
574
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # Copyright 2020 Hibou Corp. - Jared Kipe # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class MassMailing(models.Model): _inherit = "mailing.mailing" def _get_remaining_recipients(self): """When evaluating remaining recipients we must resync the list in advance to avoid missing recipients due to domain change or new partners fitting into the conditions""" self.contact_list_ids.action_sync() return super()._get_remaining_recipients()
35.875
574
2,948
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # Copyright 2020 Hibou Corp. - Jared Kipe # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval class MassMailingList(models.Model): _inherit = "mailing.list" dynamic = fields.Boolean( help="Set this list as dynamic, to make it autosynchronized with " "partners from a given criteria." ) sync_method = fields.Selection( selection=[ ("add", "Only add new records"), ("full", "Add and remove records as needed"), ], default="add", required=True, help="Choose the syncronization method for this list if you want to " "make it dynamic", ) sync_domain = fields.Char( string="Synchronization critera", default="[('is_blacklisted', '=', False), ('email', '!=', False)]", required=True, help="Filter partners to sync in this list", ) is_synced = fields.Boolean( help="Helper field to make the user aware of unsynced changes", default=True ) def action_sync(self): """Sync contacts in dynamic lists.""" Contact = self.env["mailing.contact"].with_context(syncing=True) Partner = self.env["res.partner"] # Skip non-dynamic lists dynamic = self.filtered("dynamic").with_context(syncing=True) for one in dynamic: sync_domain = [("email", "!=", False)] + safe_eval(one.sync_domain) desired_partners = Partner.search(sync_domain) # Detach or remove undesired contacts when synchronization is full if one.sync_method == "full": contact_to_detach = one.contact_ids.filtered( lambda r: r.partner_id not in desired_partners ) one.contact_ids -= contact_to_detach contact_to_detach.filtered(lambda r: not r.list_ids).unlink() # Add new contacts current_partners = one.contact_ids.mapped("partner_id") contact_to_list = self.env["mailing.contact"] vals_list = [] for partner in desired_partners - current_partners: contacts_in_partner = partner.mass_mailing_contact_ids if contacts_in_partner: contact_to_list |= contacts_in_partner[0] else: vals_list.append( {"list_ids": [(4, one.id)], "partner_id": partner.id} ) one.contact_ids |= contact_to_list Contact.create(vals_list) one.is_synced = True # Invalidate cached contact count self.invalidate_cache(["contact_count"], dynamic.ids) @api.onchange("dynamic", "sync_method", "sync_domain") def _onchange_dynamic(self): if self.dynamic: self.is_synced = False
40.383562
2,948
368
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class ResPartner(models.Model): _inherit = "res.partner" def write(self, vals): """Allow to write values in mass mailing contact.""" return super(ResPartner, self.with_context(syncing=True)).write(vals)
30.666667
368
779
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Pedro M. Baeza # Copyright 2020 Hibou Corp. - Jared Kipe # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class MailingLoadFilter(models.TransientModel): _name = "mailing.load.filter" _description = "Mass Mailing Load Filter" filter_id = fields.Many2one( comodel_name="ir.filters", string="Filter to load", required=True, domain="[('model_id', '=', 'res.partner'), '|', " "('user_id', '=', uid), ('user_id','=',False)]", ondelete="cascade", ) def load_filter(self): self.ensure_one() mass_list = self.env["mailing.list"].browse(self.env.context["active_id"]) mass_list.sync_domain = self.filter_id.domain
32.458333
779
571
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class BasePartnerMergeAutomaticWizard(models.TransientModel): _inherit = "base.partner.merge.automatic.wizard" def _merge(self, partner_ids, dst_partner=None, extra_checks=True): return super( BasePartnerMergeAutomaticWizard, self.with_context(syncing=True) )._merge( partner_ids=partner_ids, dst_partner=dst_partner, extra_checks=extra_checks, )
33.470588
569
619
py
PYTHON
15.0
# Copyright (C) 2015 Therp BV <http://therp.nl> # Copyright (C) 2017 Komit <http://www.komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Restrict follower selection", "version": "15.0.1.0.0", "author": "Therp BV,Creu Blanca,Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Social Network", "website": "https://github.com/OCA/social", "summary": "Define a domain from which followers can be selected", "depends": ["mail"], "data": ["data/ir_config_parameter.xml", "data/ir_actions.xml"], "installable": True, }
38.6875
619
2,964
py
PYTHON
15.0
# Copyright (C) 2015 Therp BV <http://therp.nl> # Copyright (C) 2017 Komit <http://www.komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo.tests.common import TransactionCase class TestMailRestrictFollowerSelection(TransactionCase): def setUp(self): super().setUp() self.category_employees = self.env["res.partner.category"].create( {"name": "Employees"} ) self.partner = self.env["res.partner"].create( { "name": "Partner", "category_id": self.category_employees, "email": "test@test.com", } ) def test_fields_view_get(self): result = self.env["mail.wizard.invite"].fields_view_get(view_type="form") for field in etree.fromstring(result["arch"]).xpath( '//field[@name="partner_ids"]' ): self.assertTrue(field.get("domain")) def send_action(self): compose = ( self.env["mail.compose.message"] .with_context( mail_post_autofollow=True, default_composition_mode="comment", default_model="res.partner", default_use_active_domain=True, test_restrict_follower=True, ) .create( { "subject": "From Composer Test", "body": "${object.description}", "res_id": self.partner.id, "partner_ids": [(4, id) for id in self.partner.ids], } ) ) self.assertEqual(compose.partner_ids, self.partner) compose._action_send_mail() def test_followers_meet(self): self.partner.write({"category_id": self.category_employees}) self.send_action() self.assertIn( self.partner, self.partner.message_follower_ids.mapped("partner_id") ) def test_followers_not_meet(self): self.partner.write({"category_id": False}) self.send_action() self.assertNotIn( self.partner, self.partner.message_follower_ids.mapped("partner_id") ) def test_message_add_suggested_recipient(self): res = self.partner.with_context( test_restrict_follower=True )._message_add_suggested_recipient({self.partner.id: []}, partner=self.partner) self.assertEqual(res[self.partner.id][0][0], self.partner.id) self.env["ir.config_parameter"].create( { "key": "mail_restrict_follower_selection.domain.res.partner", "value": "[('category_id.name', '!=', 'Employees')]", } ) new_res = self.partner.with_context( test_restrict_follower=True )._message_add_suggested_recipient({self.partner.id: []}) self.assertFalse(new_res[self.partner.id][0][0])
36.146341
2,964
1,582
py
PYTHON
15.0
# Copyright (C) 2018 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models from odoo.tools import config from odoo.tools.safe_eval import safe_eval class MailFollowers(models.Model): _inherit = "mail.followers" def _add_followers( self, res_model, res_ids, partner_ids, subtypes, check_existing=False, existing_policy="skip", ): test_condition = config["test_enable"] and not self.env.context.get( "test_restrict_follower" ) if test_condition or self.env.context.get("no_restrict_follower"): return super()._add_followers( res_model, res_ids, partner_ids, subtypes, check_existing=check_existing, existing_policy=existing_policy, ) domain = self.env[ "mail.wizard.invite" ]._mail_restrict_follower_selection_get_domain(res_model=res_model) partners = self.env["res.partner"].search( [("id", "in", partner_ids)] + safe_eval(domain) ) _res_ids = res_ids.copy() or [0] new, update = super()._add_followers( res_model, res_ids, partners.ids, subtypes, check_existing=check_existing, existing_policy=existing_policy, ) for res_id in _res_ids: if res_id not in new: new.setdefault(res_id, list()) return new, update
30.423077
1,582
1,432
py
PYTHON
15.0
# Copyright (C) 2015 Therp BV <http://therp.nl> # Copyright (C) 2017 Komit <http://www.komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo import api, models class MailWizardInvite(models.TransientModel): _inherit = "mail.wizard.invite" @api.model def _mail_restrict_follower_selection_get_domain(self, res_model=None): if not res_model: res_model = self.env.context.get("default_res_model") parameter_name = "mail_restrict_follower_selection.domain" return ( self.env["ir.config_parameter"] .sudo() .get_param( "{}.{}".format(parameter_name, res_model), self.env["ir.config_parameter"] .sudo() .get_param(parameter_name, default="[]"), ) ) @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): result = super(MailWizardInvite, self).fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu ) arch = etree.fromstring(result["arch"]) for field in arch.xpath('//field[@name="partner_ids"]'): field.attrib["domain"] = self._mail_restrict_follower_selection_get_domain() result["arch"] = etree.tostring(arch) return result
35.8
1,432
1,185
py
PYTHON
15.0
from odoo import models from odoo.tools import config from odoo.tools.safe_eval import safe_eval class MailThread(models.AbstractModel): _inherit = "mail.thread" def _message_add_suggested_recipient( self, result, partner=None, email=None, reason="" ): result = super()._message_add_suggested_recipient( result, partner=partner, email=email, reason=reason ) test_condition = config["test_enable"] and not self.env.context.get( "test_restrict_follower" ) if test_condition or self.env.context.get("no_restrict_follower"): return result domain = self.env[ "mail.wizard.invite" ]._mail_restrict_follower_selection_get_domain() eval_domain = safe_eval(domain) for key in result: for partner_id, email, reason in result[key]: if partner_id: partner = self.env["res.partner"].search( [("id", "=", partner_id)] + eval_domain ) if not partner: result[key].remove((partner_id, email, reason)) return result
37.03125
1,185
1,267
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza <pedro.baeza@tecnativa.com> # Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2015 Javier Iniesta <javieria@antiun.com> # Copyright 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com> # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import SUPERUSER_ID, api _logger = logging.getLogger(__name__) def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) # ACTION 1: Match existing contacts contact_model = env["mailing.contact"] partner_model = env["res.partner"] contacts = contact_model.search([("email", "!=", False)]) _logger.info("Trying to match %d contacts to partner by email", len(contacts)) for contact in contacts: partners = partner_model.search([("email", "=ilike", contact.email)], limit=1) if partners: contact.write({"partner_id": partners.id}) # ACTION 2: Match existing statistics stat_model = env["mailing.trace"] stats = stat_model.search([("model", "!=", False), ("res_id", "!=", False)]) _logger.info("Trying to link %d mass mailing statistics to partner", len(stats)) stats.partner_link()
42.233333
1,267
905
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza <pedro.baeza@tecnativa.com> # Copyright 2015-2016 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2015 Javier Iniesta <javieria@antiun.com> # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Link partners with mass-mailing", "version": "15.0.1.0.0", "author": "Tecnativa, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/social", "license": "AGPL-3", "category": "Marketing", "depends": ["mass_mailing"], "post_init_hook": "post_init_hook", "data": [ "security/ir.model.access.csv", "views/mailing_trace_view.xml", "views/mailing_contact_view.xml", "views/mailing_view.xml", "views/res_partner_view.xml", "wizard/partner_mail_list_wizard.xml", ], "installable": True, }
36.2
905
6,020
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza <pedro.baeza@tecnativa.com> # Copyright 2015 Antonio Espinosa <antonio.espinosa@tecnativa.com> # Copyright 2015 Javier Iniesta <javieria@antiun.com> # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from ..hooks import post_init_hook from . import base class MailMassMailingContactCase(base.BaseCase): def test_match_existing_contacts(self): contact = self.create_mailing_contact( {"email": "partner@test.com", "list_ids": [(6, 0, self.mailing_list.ids)]} ) post_init_hook(self.cr, self.registry) self.assertEqual(contact.partner_id.id, self.partner.id) self.check_mailing_contact_partner(contact) def test_create_mass_mailing_contact(self): title_doctor = self.env.ref("base.res_partner_title_doctor") country_cu = self.env.ref("base.cu") category_8 = self.env.ref("base.res_partner_category_8") category_11 = self.env.ref("base.res_partner_category_11") contact_vals = { "name": "Partner test 2", "email": "partner2@test.com", "title_id": title_doctor.id, "company_name": "TestCompany", "country_id": country_cu.id, "tag_ids": [(6, 0, (category_8 | category_11).ids)], "list_ids": [(6, 0, (self.mailing_list | self.mailing_list2).ids)], } contact = self.create_mailing_contact(contact_vals) self.check_mailing_contact_partner(contact) with self.assertRaises(ValidationError): self.create_mailing_contact( { "email": "partner2@test.com", "list_ids": [[6, 0, [self.mailing_list2.id]]], } ) def test_create_mass_mailing_contact_with_subscription(self): title_doctor = self.env.ref("base.res_partner_title_doctor") country_cu = self.env.ref("base.cu") category_8 = self.env.ref("base.res_partner_category_8") category_11 = self.env.ref("base.res_partner_category_11") contact_vals = { "name": "Partner test 2", "email": "partner2@test.com", "title_id": title_doctor.id, "company_name": "TestCompany", "country_id": country_cu.id, "tag_ids": [(6, 0, (category_8 | category_11).ids)], "subscription_list_ids": [ (0, 0, {"list_id": self.mailing_list.id}), (0, 0, {"list_id": self.mailing_list2.id}), ], } contact = self.create_mailing_contact(contact_vals) self.check_mailing_contact_partner(contact) with self.assertRaises(ValidationError): self.create_mailing_contact( { "email": "partner2@test.com", "subscription_list_ids": [ (0, 0, {"list_id": self.mailing_list2.id}) ], } ) def test_write_mass_mailing_contact(self): contact = self.create_mailing_contact( {"email": "partner@test.com", "list_ids": [(6, 0, self.mailing_list.ids)]} ) contact.write({"partner_id": False}) self.check_mailing_contact_partner(contact) contact2 = self.create_mailing_contact( { "email": "partner2@test.com", "name": "Partner test 2", "list_ids": [(6, 0, self.mailing_list.ids)], } ) contact2.write({"partner_id": False}) self.assertFalse(contact2.partner_id) def test_onchange_partner(self): contact = self.create_mailing_contact( {"email": "partner@test.com", "list_ids": [[6, 0, [self.mailing_list.id]]]} ) title_doctor = self.env.ref("base.res_partner_title_doctor") country_cu = self.env.ref("base.cu") category_8 = self.env.ref("base.res_partner_category_8") category_11 = self.env.ref("base.res_partner_category_11") partner_vals = { "name": "Partner test 2", "email": "partner2@test.com", "title": title_doctor.id, "company_id": self.main_company.id, "country_id": country_cu.id, "category_id": [(6, 0, (category_8 | category_11).ids)], } partner = self.create_partner(partner_vals) contact.partner_id = partner contact._onchange_partner_mass_mailing_partner() self.check_mailing_contact_partner(contact) def test_partners_merge(self): partner_1 = self.create_partner({"name": "Demo 1", "email": "demo1@demo.com"}) partner_2 = self.create_partner({"name": "Demo 2", "email": "demo2@demo.com"}) list_1 = self.create_mailing_list({"name": "List test Partners Merge 1"}) list_2 = self.create_mailing_list({"name": "List test Partners Merge 2"}) contact_1 = self.create_mailing_contact( { "email": partner_1.email, "name": partner_1.name, "partner_id": partner_1.id, "list_ids": [(6, 0, [list_1.id])], } ) contact_2 = self.create_mailing_contact( { "email": partner_2.email, "name": partner_2.name, "partner_id": partner_2.id, "list_ids": [(6, 0, [list_1.id, list_2.id])], } ) # Wizard partner merge (partner_1 + partner_2) in partner_i1 wizard = self.env["base.partner.merge.automatic.wizard"].create( {"state": "option"} ) wizard._merge((partner_1 + partner_2).ids, partner_1) contact = self.env["mailing.contact"].search( [("id", "in", (contact_1 + contact_2).ids)] ) self.assertEqual(len(contact), 1) self.assertEqual(contact.list_ids.ids, (list_1 + list_2).ids)
42.394366
6,020
829
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Ernesto tejeda # Copyright 2020 Tecnativa - Manuel Calero # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from . import base class MailMassMailingListContactRelCase(base.BaseCase): def test_create_mass_mailing_list(self): contact_test_1 = self.create_mailing_contact( {"name": "Contact test 1", "partner_id": self.partner.id} ) contact_test_2 = self.create_mailing_contact( {"name": "Contact test 2", "partner_id": self.partner.id} ) list_3 = self.create_mailing_list( {"name": "List test 3", "contact_ids": [(4, contact_test_1.id)]} ) with self.assertRaises(ValidationError): list_3.contact_ids = [(4, contact_test_2.id)]
37.681818
829