-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproduct.py
856 lines (748 loc) · 29.8 KB
/
product.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import copy
import logging
from decimal import Decimal
from importlib import import_module
import stdnum
import stdnum.exceptions
from sql import Column, Literal, Null
from sql.operators import Equal
from trytond import backend
from trytond.i18n import gettext
from trytond.model import (
DeactivableMixin, Exclude, Model, ModelSQL, ModelView, UnionMixin, fields,
sequence_ordered)
from trytond.modules.company.model import (
CompanyMultiValueMixin, CompanyValueMixin)
from trytond.pool import Pool
from trytond.pyson import Eval, Get, If
from trytond.tools import lstrip_wildcard
from trytond.tools.multivalue import migrate_property
from trytond.transaction import Transaction
from .exceptions import InvalidIdentifierCode
from .ir import price_decimal
__all__ = ['price_digits', 'round_price', 'TemplateFunction']
logger = logging.getLogger(__name__)
TYPES = [
('goods', 'Goods'),
('assets', 'Assets'),
('service', 'Service'),
]
COST_PRICE_METHODS = [
('fixed', 'Fixed'),
('average', 'Average'),
]
price_digits = (16, price_decimal)
def round_price(value, rounding=None):
"Round price using the price digits"
if isinstance(value, int):
return Decimal(value)
return value.quantize(
Decimal(1) / 10 ** price_digits[1], rounding=rounding)
class Template(
DeactivableMixin, ModelSQL, ModelView, CompanyMultiValueMixin):
"Product Template"
__name__ = "product.template"
_order_name = 'rec_name'
name = fields.Char(
"Name", size=None, required=True, translate=True, select=True)
code_readonly = fields.Function(
fields.Boolean("Code Readonly"), 'get_code_readonly')
code = fields.Char(
"Code", select=True,
states={
'readonly': Eval('code_readonly', False),
})
type = fields.Selection(TYPES, "Type", required=True)
consumable = fields.Boolean('Consumable',
states={
'invisible': Eval('type', 'goods') != 'goods',
},
help="Check to allow stock moves to be assigned "
"regardless of stock level.")
list_price = fields.MultiValue(fields.Numeric(
"List Price", digits=price_digits,
states={
'readonly': ~Eval('context', {}).get('company'),
},
help="The standard price the product is sold at."))
list_prices = fields.One2Many(
'product.list_price', 'template', "List Prices")
cost_price = fields.Function(fields.Numeric(
"Cost Price", digits=price_digits,
help="The amount it costs to purchase or make the product, "
"or carry out the service."),
'get_cost_price')
cost_price_method = fields.MultiValue(fields.Selection(
COST_PRICE_METHODS, "Cost Price Method", required=True,
help="The method used to calculate the cost price."))
cost_price_methods = fields.One2Many(
'product.cost_price_method', 'template', "Cost Price Methods")
default_uom = fields.Many2One('product.uom', "Default UOM", required=True,
help="The standard unit of measure for the product.\n"
"Used internally when calculating the stock levels of goods "
"and assets.")
default_uom_category = fields.Function(
fields.Many2One('product.uom.category', 'Default UOM Category'),
'on_change_with_default_uom_category',
searcher='search_default_uom_category')
default_uom_digits = fields.Function(fields.Integer("Default Unit Digits"),
'on_change_with_default_uom_digits')
categories = fields.Many2Many(
'product.template-product.category', 'template', 'category',
"Categories",
help="The categories that the product is in.\n"
"Used to group similar products together.")
categories_all = fields.Many2Many(
'product.template-product.category.all',
'template', 'category', "Categories", readonly=True)
products = fields.One2Many(
'product.product', 'template', "Variants",
domain=[
If(~Eval('active'), ('active', '=', False), ()),
],
help="The different variants the product comes in.")
@classmethod
def __register__(cls, module_name):
super(Template, cls).__register__(module_name)
table = cls.__table_handler__(module_name)
# Migration from 3.8: rename category into categories
if table.column_exist('category'):
logger.warning(
'The column "category" on table "%s" must be dropped manually',
cls._table)
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(0, ('rec_name', 'ASC'))
types_cost_method = cls._cost_price_method_domain_per_type()
cls.cost_price_method.domain = [
Get(types_cost_method, Eval('type'), []),
]
@classmethod
def _cost_price_method_domain_per_type(cls):
return {'service': [('cost_price_method', '=', 'fixed')]}
@classmethod
def multivalue_model(cls, field):
pool = Pool()
if field == 'list_price':
return pool.get('product.list_price')
elif field == 'cost_price_method':
return pool.get('product.cost_price_method')
return super(Template, cls).multivalue_model(field)
@classmethod
def order_rec_name(cls, tables):
table, _ = tables[None]
return [table.code, table.name]
def get_rec_name(self, name):
if self.code:
return '[' + self.code + '] ' + self.name
else:
return self.name
@classmethod
def search_rec_name(cls, name, clause):
if clause[1].startswith('!') or clause[1].startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
code_value = clause[2]
if clause[1].endswith('like'):
code_value = lstrip_wildcard(clause[2])
return [bool_op,
('name',) + tuple(clause[1:]),
('code', clause[1], code_value) + tuple(clause[3:]),
('products.code', clause[1], code_value) + tuple(clause[3:]),
('products.identifiers.code', clause[1], code_value)
+ tuple(clause[3:]),
]
@staticmethod
def default_type():
return 'goods'
@staticmethod
def default_consumable():
return False
def get_cost_price(self, name):
if len(self.products) == 1:
product, = self.products
return product.cost_price
@classmethod
def default_cost_price_method(cls, **pattern):
pool = Pool()
Configuration = pool.get('product.configuration')
return Configuration(1).get_multivalue(
'default_cost_price_method', **pattern)
@classmethod
def default_products(cls):
transaction = Transaction()
if (transaction.user == 0
or not transaction.context.get('default_products', True)):
return []
return [{}]
@classmethod
def default_code_readonly(cls):
pool = Pool()
Configuration = pool.get('product.configuration')
config = Configuration(1)
return bool(config.template_sequence)
def get_code_readonly(self, name):
return self.default_code_readonly()
@fields.depends('type', 'cost_price_method')
def on_change_type(self):
if self.type == 'service':
self.cost_price_method = 'fixed'
@fields.depends('default_uom')
def on_change_with_default_uom_category(self, name=None):
if self.default_uom:
return self.default_uom.category.id
@classmethod
def search_default_uom_category(cls, name, clause):
return [('default_uom.category' + clause[0].lstrip(name),)
+ tuple(clause[1:])]
@fields.depends('default_uom')
def on_change_with_default_uom_digits(self, name=None):
if self.default_uom:
return self.default_uom.digits
@classmethod
def _new_code(cls):
pool = Pool()
Configuration = pool.get('product.configuration')
config = Configuration(1)
sequence = config.template_sequence
if sequence:
return sequence.get()
@classmethod
def create(cls, vlist):
pool = Pool()
Product = pool.get('product.product')
vlist = [v.copy() for v in vlist]
for values in vlist:
values.setdefault('products', None)
if not values.get('code'):
values['code'] = cls._new_code()
templates = super(Template, cls).create(vlist)
products = sum((t.products for t in templates), ())
Product.sync_code(products)
return templates
@classmethod
def write(cls, *args):
pool = Pool()
Product = pool.get('product.product')
super().write(*args)
templates = sum(args[0:None:2], [])
products = sum((t.products for t in templates), ())
Product.sync_code(products)
@classmethod
def copy(cls, templates, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('code', None)
return super().copy(templates, default=default)
@classmethod
def search_global(cls, text):
for record, rec_name, icon in super(Template, cls).search_global(text):
icon = icon or 'tryton-product'
yield record, rec_name, icon
class TemplateFunction(fields.Function):
def __init__(self, field):
super(TemplateFunction, self).__init__(
field, 'get_template', searcher='search_template')
# Disable on_change as it is managed by on_change_template
self.on_change = set()
self.on_change_with = set()
def __copy__(self):
return TemplateFunction(copy.copy(self._field))
def __deepcopy__(self, memo):
return TemplateFunction(copy.deepcopy(self._field, memo))
@staticmethod
def order(name):
@classmethod
def order(cls, tables):
pool = Pool()
Template = pool.get('product.template')
product, _ = tables[None]
if 'template' not in tables:
template = Template.__table__()
tables['template'] = {
None: (template, product.template == template.id),
}
return getattr(Template, name).convert_order(
name, tables['template'], Template)
return order
def definition(self, model, language):
pool = Pool()
Template = pool.get('product.template')
definition = super().definition(model, language)
definition['searchable'] = self._field.definition(
Template, language)['searchable']
return definition
class Product(
DeactivableMixin, ModelSQL, ModelView, CompanyMultiValueMixin):
"Product Variant"
__name__ = "product.product"
_order_name = 'rec_name'
template = fields.Many2One(
'product.template', "Product Template",
required=True, ondelete='CASCADE', select=True,
search_context={'default_products': False},
domain=[
If(Eval('active'), ('active', '=', True), ()),
],
help="The product that defines the common properties "
"inherited by the variant.")
code_readonly = fields.Function(fields.Boolean('Code Readonly'),
'get_code_readonly')
prefix_code = fields.Function(fields.Char(
"Prefix Code",
states={
'invisible': ~Eval('prefix_code'),
}),
'on_change_with_prefix_code')
suffix_code = fields.Char(
"Suffix Code",
states={
'readonly': Eval('code_readonly', False),
},
help="The unique identifier for the product (aka SKU).")
code = fields.Char("Code", readonly=True, select=True,
help="A unique identifier for the variant.")
identifiers = fields.One2Many(
'product.identifier', 'product', "Identifiers",
help="Other identifiers associated with the variant.")
cost_price = fields.MultiValue(fields.Numeric(
"Cost Price", digits=price_digits,
states={
'readonly': ~Eval('context', {}).get('company'),
},
help="The amount it costs to purchase or make the variant, "
"or carry out the service."))
cost_prices = fields.One2Many(
'product.cost_price', 'product', "Cost Prices")
description = fields.Text("Description", translate=True)
list_price_uom = fields.Function(fields.Numeric('List Price',
digits=price_digits), 'get_price_uom')
cost_price_uom = fields.Function(fields.Numeric('Cost Price',
digits=price_digits), 'get_price_uom')
@classmethod
def __setup__(cls):
pool = Pool()
Template = pool.get('product.template')
if not hasattr(cls, '_no_template_field'):
cls._no_template_field = set()
cls._no_template_field.update(['products'])
super(Product, cls).__setup__()
cls.__access__.add('template')
cls._order.insert(0, ('rec_name', 'ASC'))
t = cls.__table__()
cls._sql_constraints = [
('code_exclude', Exclude(t, (t.code, Equal),
where=(t.active == Literal(True))
& (t.code != '')),
'product.msg_product_code_unique'),
]
for attr in dir(Template):
tfield = getattr(Template, attr)
if not isinstance(tfield, fields.Field):
continue
if attr in cls._no_template_field:
continue
field = getattr(cls, attr, None)
if not field or isinstance(field, TemplateFunction):
tfield = copy.deepcopy(tfield)
if hasattr(tfield, 'field'):
tfield.field = None
invisible_state = ~Eval('template')
if 'invisible' in tfield.states:
tfield.states['invisible'] |= invisible_state
else:
tfield.states['invisible'] = invisible_state
setattr(cls, attr, TemplateFunction(tfield))
order_method = getattr(cls, 'order_%s' % attr, None)
if (not order_method
and not isinstance(tfield, (
fields.Function,
fields.One2Many,
fields.Many2Many))):
order_method = TemplateFunction.order(attr)
setattr(cls, 'order_%s' % attr, order_method)
if isinstance(tfield, fields.One2Many):
getattr(cls, attr).setter = '_set_template_function'
@classmethod
def __register__(cls, module):
table = cls.__table__()
table_h = cls.__table_handler__(module)
fill_suffix_code = (
table_h.column_exist('code')
and not table_h.column_exist('suffix_code'))
super().__register__(module)
cursor = Transaction().connection.cursor()
# Migration from 5.4: split code into prefix/suffix
if fill_suffix_code:
cursor.execute(*table.update(
[table.suffix_code],
[table.code]))
@classmethod
def _set_template_function(cls, products, name, value):
# Prevent NotImplementedError for One2Many
pass
@fields.depends('template', '_parent_template.id')
def on_change_template(self):
for name, field in self._fields.items():
if isinstance(field, TemplateFunction):
if self.template:
value = getattr(self.template, name, None)
else:
value = None
setattr(self, name, value)
def get_template(self, name):
value = getattr(self.template, name)
if isinstance(value, Model):
field = getattr(self.__class__, name)
if field._type == 'reference':
return str(value)
return value.id
elif (isinstance(value, (list, tuple))
and value and isinstance(value[0], Model)):
return [r.id for r in value]
else:
return value
@fields.depends('template', '_parent_template.code')
def on_change_with_prefix_code(self, name=None):
if self.template:
return self.template.code
@classmethod
def multivalue_model(cls, field):
pool = Pool()
if field == 'cost_price':
return pool.get('product.cost_price')
return super(Product, cls).multivalue_model(field)
def set_multivalue(self, name, value, save=True, **pattern):
context = Transaction().context
if name in {'cost_price', 'list_price'} and not value:
if not pattern.get('company', context.get('company')):
return []
return super().set_multivalue(name, value, save=save, **pattern)
@classmethod
def default_cost_price(cls, **pattern):
context = Transaction().context
if pattern.get('company', context.get('company')):
return Decimal(0)
@classmethod
def search_template(cls, name, clause):
return [('template.' + clause[0],) + tuple(clause[1:])]
@classmethod
def order_rec_name(cls, tables):
pool = Pool()
Template = pool.get('product.template')
product, _ = tables[None]
if 'template' not in tables:
template = Template.__table__()
tables['template'] = {
None: (template, product.template == template.id),
}
else:
template = tables['template']
return [product.code] + Template.name.convert_order('name',
tables['template'], Template)
def get_rec_name(self, name):
if self.code:
return '[' + self.code + '] ' + self.name
else:
return self.name
@classmethod
def search_rec_name(cls, name, clause):
if clause[1].startswith('!') or clause[1].startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
code_value = clause[2]
if clause[1].endswith('like'):
code_value = lstrip_wildcard(clause[2])
return [bool_op,
('code', clause[1], code_value) + tuple(clause[3:]),
('identifiers.code', clause[1], code_value) + tuple(clause[3:]),
('template.name',) + tuple(clause[1:]),
('template.code', clause[1], code_value) + tuple(clause[3:]),
]
@staticmethod
def get_price_uom(products, name):
Uom = Pool().get('product.uom')
res = {}
field = name[:-4]
if Transaction().context.get('uom'):
to_uom = Uom(Transaction().context['uom'])
else:
to_uom = None
for product in products:
price = getattr(product, field)
if to_uom and product.default_uom.category == to_uom.category:
res[product.id] = Uom.compute_price(
product.default_uom, price, to_uom)
else:
res[product.id] = price
return res
@classmethod
def search_global(cls, text):
for id_, rec_name, icon in super(Product, cls).search_global(text):
icon = icon or 'tryton-product'
yield id_, rec_name, icon
@classmethod
def default_code_readonly(cls):
pool = Pool()
Configuration = pool.get('product.configuration')
config = Configuration(1)
return bool(config.product_sequence)
def get_code_readonly(self, name):
return self.default_code_readonly()
@classmethod
def _new_suffix_code(cls):
pool = Pool()
Configuration = pool.get('product.configuration')
config = Configuration(1)
sequence = config.product_sequence
if sequence:
return sequence.get()
@classmethod
def create(cls, vlist):
vlist = [x.copy() for x in vlist]
for values in vlist:
if not values.get('suffix_code'):
values['suffix_code'] = cls._new_suffix_code()
products = super().create(vlist)
cls.sync_code(products)
return products
@classmethod
def write(cls, *args):
super().write(*args)
products = sum(args[0:None:2], [])
cls.sync_code(products)
@classmethod
def copy(cls, products, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('suffix_code', None)
default.setdefault('code', None)
return super().copy(products, default=default)
@property
def list_price_used(self):
transaction = Transaction()
with transaction.reset_context(), \
transaction.set_context(self._context):
return self.template.get_multivalue('list_price')
@classmethod
def sync_code(cls, products):
for product in products:
code = ''.join(filter(None, [
product.prefix_code, product.suffix_code]))
if not code:
code = None
if code != product.code:
product.code = code
cls.save(products)
class ProductListPrice(ModelSQL, CompanyValueMixin):
"Product List Price"
__name__ = 'product.list_price'
template = fields.Many2One(
'product.template', "Template", ondelete='CASCADE', select=True,
context={
'company': Eval('company', -1),
},
depends={'company'})
list_price = fields.Numeric("List Price", digits=price_digits)
@classmethod
def __setup__(cls):
super().__setup__()
cls.company.required = True
@classmethod
def __register__(cls, module_name):
exist = backend.TableHandler.table_exist(cls._table)
super(ProductListPrice, cls).__register__(module_name)
if not exist:
cls._migrate_property([], [], [])
@classmethod
def _migrate_property(cls, field_names, value_names, fields):
field_names.append('list_price')
value_names.append('list_price')
fields.append('company')
migrate_property(
'product.template', field_names, cls, value_names,
parent='template', fields=fields)
class ProductCostPriceMethod(ModelSQL, CompanyValueMixin):
"Product Cost Price Method"
__name__ = 'product.cost_price_method'
template = fields.Many2One(
'product.template', "Template", ondelete='CASCADE', select=True,
context={
'company': Eval('company', -1),
},
depends={'company'})
cost_price_method = fields.Selection(
'get_cost_price_methods', "Cost Price Method")
@classmethod
def __register__(cls, module_name):
pool = Pool()
ProductCostPrice = pool.get('product.cost_price')
sql_table = cls.__table__()
cost_price = ProductCostPrice.__table__()
cursor = Transaction().connection.cursor()
exist = backend.TableHandler.table_exist(cls._table)
cost_price_exist = backend.TableHandler.table_exist(
ProductCostPrice._table)
super(ProductCostPriceMethod, cls).__register__(module_name)
# Migrate from 4.4: move cost_price_method from ProductCostPrice
if not exist and not cost_price_exist:
cls._migrate_property([], [], [])
elif not exist and cost_price_exist:
cost_price_table = backend.TableHandler(
ProductCostPrice, module_name)
if cost_price_table.column_exist('template'):
columns = ['create_uid', 'create_date',
'write_uid', 'write_date',
'template', 'cost_price_method']
cursor.execute(*sql_table.insert(
columns=[Column(sql_table, c) for c in columns],
values=cost_price.select(
*[Column(cost_price, c) for c in columns])))
@classmethod
def _migrate_property(cls, field_names, value_names, fields):
field_names.append('cost_price_method')
value_names.append('cost_price_method')
fields.append('company')
migrate_property(
'product.template', field_names, cls, value_names,
parent='template', fields=fields)
@classmethod
def get_cost_price_methods(cls):
pool = Pool()
Template = pool.get('product.template')
field_name = 'cost_price_method'
methods = Template.fields_get([field_name])[field_name]['selection']
methods.append((None, ''))
return methods
class ProductCostPrice(ModelSQL, CompanyValueMixin):
"Product Cost Price"
__name__ = 'product.cost_price'
product = fields.Many2One(
'product.product', "Product", ondelete='CASCADE', select=True,
context={
'company': Eval('company', -1),
},
depends={'company'})
cost_price = fields.Numeric(
"Cost Price", required=True, digits=price_digits)
@classmethod
def __setup__(cls):
super().__setup__()
cls.company.required = True
@classmethod
def __register__(cls, module_name):
pool = Pool()
Product = pool.get('product.product')
sql_table = cls.__table__()
product = Product.__table__()
cursor = Transaction().connection.cursor()
exist = backend.TableHandler.table_exist(cls._table)
super(ProductCostPrice, cls).__register__(module_name)
table = cls.__table_handler__(module_name)
if not exist:
# Create template column for property migration
table.add_column('template', 'INTEGER')
cls._migrate_property([], [], [])
# Migration from 4.4: replace template by product
if table.column_exist('template'):
columns = ['create_uid', 'create_date',
'write_uid', 'write_date', 'cost_price']
cursor.execute(*sql_table.insert(
columns=[Column(sql_table, c) for c in columns]
+ [sql_table.product],
values=sql_table.join(product,
condition=sql_table.template == product.template
).select(
*[Column(sql_table, c) for c in columns]
+ [product.id],
where=(sql_table.template != Null)
& (sql_table.product == Null))))
cursor.execute(*sql_table.delete(
where=(sql_table.template != Null)
& (sql_table.product == Null)))
table.drop_column('template')
@classmethod
def _migrate_property(cls, field_names, value_names, fields):
field_names.append('cost_price')
value_names.append('cost_price')
fields.append('company')
migrate_property(
'product.template', field_names, cls, value_names,
parent='template', fields=fields)
class TemplateCategory(ModelSQL):
'Template - Category'
__name__ = 'product.template-product.category'
template = fields.Many2One('product.template', 'Template',
ondelete='CASCADE', required=True, select=True)
category = fields.Many2One('product.category', 'Category',
ondelete='CASCADE', required=True, select=True)
class TemplateCategoryAll(UnionMixin, ModelSQL):
"Template - Category All"
__name__ = 'product.template-product.category.all'
template = fields.Many2One('product.template', "Template")
category = fields.Many2One('product.category', "Category")
@classmethod
def union_models(cls):
return ['product.template-product.category']
class ProductIdentifier(sequence_ordered(), ModelSQL, ModelView):
"Product Identifier"
__name__ = 'product.identifier'
_rec_name = 'code'
product = fields.Many2One('product.product', "Product", ondelete='CASCADE',
required=True, select=True,
help="The product identified by the code.")
type = fields.Selection([
(None, ''),
('ean', "International Article Number"),
('isan', "International Standard Audiovisual Number"),
('isbn', "International Standard Book Number"),
('isil', "International Standard Identifier for Libraries"),
('isin', "International Securities Identification Number"),
('ismn', "International Standard Music Number"),
], "Type")
type_string = type.translated('type')
code = fields.Char("Code", required=True)
@classmethod
def __setup__(cls):
super().__setup__()
cls.__access__.add('product')
@fields.depends('type', 'code')
def on_change_with_code(self):
if self.type and self.type != 'other':
try:
module = import_module('stdnum.%s' % self.type)
return module.compact(self.code)
except ImportError:
pass
except stdnum.exceptions.ValidationError:
pass
return self.code
def pre_validate(self):
super().pre_validate()
self.check_code()
@fields.depends('type', 'product', 'code')
def check_code(self):
if self.type:
try:
module = import_module('stdnum.%s' % self.type)
except ModuleNotFoundError:
return
if not module.is_valid(self.code):
if self.product and self.product.id > 0:
product = self.product.rec_name
else:
product = ''
raise InvalidIdentifierCode(
gettext('product.msg_invalid_code',
type=self.type_string,
code=self.code,
product=product))