Debian Codegraph @

addons/barcodes_gs1_nomenclature/models/barcode_nomenclature.py

raw
1 import re
2 import datetime
3 import calendar
4
5 from odoo import api, fields, models, _
6 from odoo.exceptions import ValidationError
7 from odoo.fields import Domain
8 from odoo.tools.barcode import get_barcode_check_digit
9
10 FNC1_CHAR = '\x1D'
11
12
13 class BarcodeNomenclature(models.Model):
14 _inherit = 'barcode.nomenclature'
15
16 is_gs1_nomenclature = fields.Boolean(
17 string="Is GS1 Nomenclature",
18 help="This Nomenclature use the GS1 specification, only GS1-128 encoding rules is accepted is this kind of nomenclature.")
19 gs1_separator_fnc1 = fields.Char(
20 string="FNC1 Separator", trim=False, default=r'(Alt029|#|\x1D)',
21 help="Alternative regex delimiter for the FNC1. The separator must not match the begin/end of any related rules pattern.")
22
23 @api.constrains('gs1_separator_fnc1')
24 def _check_pattern(self):
25 for nom in self:
26 if nom.is_gs1_nomenclature and nom.gs1_separator_fnc1:
27 try:
28 re.compile("(?:%s)?" % nom.gs1_separator_fnc1)
29 except re.error as error:
30 raise ValidationError(_("The FNC1 Separator Alternative is not a valid Regex: %(error)s", error))
31
32 @api.model
33 def gs1_date_to_date(self, gs1_date):
34 """ Converts a GS1 date into a datetime.date.
35
36 :param gs1_date: A year formated as yymmdd
37 :type gs1_date: str
38 :return: converted date
39 :rtype: datetime.date
40 """
41 # See 7.12 Determination of century in dates:
42 # https://www.gs1.org/sites/default/files/docs/barcodes/GS1_General_Specifications.pdf
43 now = datetime.date.today()
44 current_century = now.year // 100
45 substract_year = int(gs1_date[0:2]) - (now.year % 100)
46 century = (51 <= substract_year <= 99 and current_century - 1) or\
47 (-99 <= substract_year <= -50 and current_century + 1) or\
48 current_century
49 year = century * 100 + int(gs1_date[0:2])
50
51 if gs1_date[-2:] == '00': # Day is not mandatory, when not set -> last day of the month
52 date = datetime.datetime.strptime(str(year) + gs1_date[2:4], '%Y%m')
53 date = date.replace(day=calendar.monthrange(year, int(gs1_date[2:4]))[1])
54 else:
55 try:
56 date = datetime.datetime.strptime(str(year) + gs1_date[2:], '%Y%m%d')
57 except ValueError as e:
58 raise ValidationError(_(
59 "A GS1 barcode nomenclature pattern was matched. However, the barcode failed to be converted to a valid date: '%(error_message)s'",
60 error_message=e
61 ))
62 return date.date()
63
64 def parse_gs1_rule_pattern(self, match, rule):
65 result = {
66 'rule': rule,
67 'type': rule.type,
68 'ai': match.group(1),
69 'string_value': match.group(2),
70 }
71 if rule.gs1_content_type == 'measure':
72 try:
73 decimal_position = 0 # Decimal position begins at the end, 0 means no decimal.
74 if rule.gs1_decimal_usage:
75 decimal_position = int(match.group(1)[-1])
76 if decimal_position > 0:
77 result['value'] = float(match.group(2)[:-decimal_position] + "." + match.group(2)[-decimal_position:])
78 else:
79 result['value'] = int(match.group(2))
80 except Exception:
81 raise ValidationError(_(
82 "There is something wrong with the barcode rule \"%s\" pattern.\n"
83 "If this rule uses decimal, check it can't get sometime else than a digit as last char for the Application Identifier.\n"
84 "Check also the possible matched values can only be digits, otherwise the value can't be casted as a measure.",
85 rule.name))
86 elif rule.gs1_content_type == 'identifier':
87 # Check digit and remove it of the value
88 if match.group(2)[-1] != str(get_barcode_check_digit("0" * (18 - len(match.group(2))) + match.group(2))):
89 return None
90 result['value'] = match.group(2)
91 elif rule.gs1_content_type == 'date':
92 if len(match.group(2)) != 6:
93 return None
94 result['value'] = self.gs1_date_to_date(match.group(2))
95 else: # when gs1_content_type == 'alpha':
96 result['value'] = match.group(2)
97 return result
98
99 def gs1_decompose_extended(self, barcode):
100 """Try to decompose the gs1 extended barcode into several unit of information using gs1 rules.
101
102 Return a ordered list of dict
103 """
104 self.ensure_one()
105 separator_group = FNC1_CHAR + "?"
106 if self.gs1_separator_fnc1:
107 separator_group = "(?:%s)?" % self.gs1_separator_fnc1
108 # zxing-library patch, removing GS1 identifiers
109 for identifier in [']C1', ']e0', ']d2', ']Q3', ']J1', FNC1_CHAR]:
110 if barcode.startswith(identifier):
111 barcode = barcode.replace(identifier, '', 1)
112 break
113 results = []
114 gs1_rules = self.rule_ids.filtered(lambda r: r.encoding == 'gs1-128')
115
116 def find_next_rule(remaining_barcode):
117 for rule in gs1_rules:
118 match = re.search("^" + rule.pattern + separator_group, remaining_barcode)
119 # If match and contains 2 groups at minimun, the first one need to be the AI and the second the value
120 # We can't use regex nammed group because in JS, it is not the same regex syntax (and not compatible in all browser)
121 if match and len(match.groups()) >= 2:
122 res = self.parse_gs1_rule_pattern(match, rule)
123 if res:
124 return res, remaining_barcode[match.end():]
125 return None
126
127 while len(barcode) > 0:
128 res_bar = find_next_rule(barcode)
129 # Cannot continue -> Fail to decompose gs1 and return
130 if not res_bar or res_bar[1] == barcode:
131 return None
132 barcode = res_bar[1]
133 results.append(res_bar[0])
134
135 return results
136
137 def parse_nomenclature_barcode(self, barcode):
138 if self.is_gs1_nomenclature:
139 return self.gs1_decompose_extended(barcode)
140 return super().parse_nomenclature_barcode(barcode)
141
142 @api.model
143 def _preprocess_gs1_search_args(self, domain, barcode_types, field='barcode'):
144 """Helper method to preprocess 'domain' in _search method to add support to
145 search with GS1 barcode result.
146 Cut off the padding if using GS1 and searching on barcode. If the barcode
147 is only digits to keep the original barcode part only.
148 """
149 domain = Domain(domain)
150 nomenclature = self.env.company.nomenclature_id
151 if not self.env.context.get('skip_preprocess_gs1'):
152 def map_gs1_barcode(condition):
153 if condition.field_expr != field or not nomenclature.is_gs1_nomenclature:
154 return condition
155 # Check operator
156 # handle `in` first and check the rest
157 operator = condition.operator
158 value = condition.value
159 if not value:
160 return condition
161
162 if operator in ('in', 'not in') and len(value) > 1:
163 sub_domain = Domain.OR(
164 map_gs1_barcode(Domain(field, '=', v))
165 for v in value
166 )
167 if operator == 'not in':
168 sub_domain = ~sub_domain
169 return sub_domain
170 if operator in ('in', 'not in'):
171 operator = '=' if operator == 'in' else '!='
172 value = next(iter(value))
173 elif operator not in ('ilike', 'not ilike', '=', '!='):
174 return condition
175
176 # Parse the value
177 if not value:
178 return condition
179 try:
180 parsed_data = nomenclature.parse_barcode(value) or []
181 except (ValidationError, ValueError):
182 parsed_data = []
183
184 replacing_operator = 'ilike' if operator in ['ilike', '='] else 'not ilike'
185 for data in parsed_data:
186 data_type = data['type']
187 value = data['value']
188 if data_type in barcode_types:
189 if data_type == 'lot':
190 return Domain(field, operator, value)
191 match = re.match('0*([0-9]+)$', str(value))
192 if match:
193 unpadded_barcode = match.groups()[0]
194 return Domain(field, replacing_operator, unpadded_barcode)
195 break
196
197 # The barcode isn't a valid GS1 barcode, checks if it can be unpadded.
198 if not parsed_data:
199 match = re.match('0+([0-9]+)$', value)
200 if match:
201 return Domain(field, replacing_operator, match.groups()[0])
202 return condition
203
204 domain = domain.map_conditions(map_gs1_barcode)
205 return domain