forked from trytonus/trytond-sale-channel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
product.py
365 lines (311 loc) · 11.2 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
# -*- coding: utf-8 -*-
"""
product.py
Implementing Add listing wizard for downstream modules:
* In the __setup__ method of `product.listing.add.start` in downstream
module, add the type as a valid channel type. Since this is non trivial
a convenience method `add_source` is provided which will add the source
type in an idempotent fashion.
* Implement a StateView in the `product.listing.add` wizard with the name
`start_<source_name>`. This StateView can change the state to other state
views or transitions. Eventually it should end with the `end` state.
"""
from collections import defaultdict
from trytond.pool import PoolMeta, Pool
from trytond.wizard import Wizard, Button, StateTransition, StateView
from trytond.transaction import Transaction
from trytond.model import ModelView, fields, ModelSQL, Unique
from trytond.pyson import Eval, Bool
__metaclass__ = PoolMeta
__all__ = [
'ProductSaleChannelListing', 'Product', 'AddProductListing',
'AddProductListingStart', 'TemplateSaleChannelListing',
'Template'
]
class AddProductListingStart(ModelView):
"Add listing form start"
__name__ = 'product.listing.add.start'
product = fields.Many2One(
'product.product', 'Product', readonly=True
)
channel = fields.Many2One(
'sale.channel', 'Channel', required=True,
domain=[('source', 'in', [])]
)
channel_source = fields.Function(
fields.Char("Channel Source"),
getter="on_change_with_channel_source"
)
@fields.depends('channel')
def on_change_with_channel_source(self, name=None):
return self.channel and self.channel.source
@classmethod
def add_source(cls, source):
"""
A convenience method for downstream modules to add channel
source types once they have implemented the step in the wizard
below.
This method must be called from `__setup__` method of downstream
module.
"""
source_leaf = cls.channel.domain[0][2]
if source not in source_leaf:
source_leaf.append(source)
class AddProductListing(Wizard):
"Add product Channel Listing Wizard"
__name__ = 'product.listing.add'
start = StateView(
'product.listing.add.start',
'sale_channel.listing_add_start_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('Next', 'next', 'tryton-go-next', default=True),
]
)
next = StateTransition()
def default_start(self, fields):
return {
'product': Transaction().context['active_id']
}
def transition_next(self):
return 'start_%s' % self.start.channel.source
class Template:
"Product Template"
__name__ = 'product.template'
channel_listings = fields.One2Many(
'product.template.channel_listing', 'template', 'Channel Listings'
)
class TemplateSaleChannelListing(ModelSQL, ModelView):
"""
Template - Sale Channel
This model keeps a record of a template's association with Sale Channels.
"""
__name__ = 'product.template.channel_listing'
channel = fields.Many2One(
'sale.channel', 'Sale Channel',
domain=[('source', '!=', 'manual')],
select=True, required=True,
ondelete='RESTRICT'
)
template = fields.Many2One(
'product.template', 'Product Template', required=True,
select=True, ondelete='CASCADE'
)
template_identifier = fields.Char(
'Template Identifier', select=True, required=True
)
@classmethod
def __setup__(cls):
"""
Setup the class and define constraints
"""
super(TemplateSaleChannelListing, cls).__setup__()
table = cls.__table__()
cls._sql_constraints += [(
'channel_template_unique',
Unique(table, table.channel, table.template_identifier, table.template), # noqa
'Product Template is already mapped to this channel with same identifier' # noqa
)]
class Product:
"Product"
__name__ = "product.product"
channel_listings = fields.One2Many(
'product.product.channel_listing', 'product', 'Channel Listings',
)
@classmethod
def __setup__(cls):
super(Product, cls).__setup__()
cls._buttons.update({
'add_listing': {},
})
@classmethod
@ModelView.button_action('sale_channel.wizard_add_listing')
def add_listing(cls, products):
pass
@classmethod
def create_from(cls, channel, product_data):
"""
Create the product for the channel
"""
raise NotImplementedError(
"create_from is not implemented in product for %s channels"
% channel.source
)
class ProductSaleChannelListing(ModelSQL, ModelView):
'''Product - Sale Channel
This model keeps a record of a product's association with Sale Channels.
A product can be listed on multiple marketplaces
'''
__name__ = 'product.product.channel_listing'
# TODO: Only show channels where this ability is there. For example
# showing a manual channel is pretty much useless
channel = fields.Many2One(
'sale.channel', 'Sale Channel',
domain=[('source', '!=', 'manual')],
required=True, select=True,
ondelete='RESTRICT'
)
product = fields.Many2One(
'product.product', 'Product', select=True,
states={'required': Eval('state') == 'active'},
ondelete='CASCADE', depends=['state']
)
product_identifier = fields.Char(
"Product Identifier", select=True, required=True
)
state = fields.Selection([
('active', 'Active'),
('disabled', 'Disabled'),
], 'State', required=True, select=True)
channel_source = fields.Function(
fields.Char("Channel Source"),
getter="on_change_with_channel_source"
)
quantity = fields.Function(
fields.Float(
'Quantity',
digits=(16, Eval('unit_digits', 2)), depends=['unit_digits']
), 'get_availability_fields'
)
unit_digits = fields.Function(
fields.Integer('Unit Digits'), 'get_unit_digits'
)
availability_type_used = fields.Function(
fields.Selection([
('bucket', 'Bucket'),
('quantity', 'Quantity'),
('infinite', 'Infinite'),
], 'Type'), 'get_availability_fields'
)
availability_used = fields.Function(
fields.Selection([
('in_stock', 'In-Stock'),
('out_of_stock', 'Out Of Stock'),
], 'Availability', states={
'invisible': ~Bool(Eval('availability_type_used') == 'bucket')
}, depends=['availability_type_used']),
'get_availability_fields'
)
listing_url = fields.Function(
fields.Char('Listing URL'), 'get_listing_url'
)
def get_unit_digits(self, name):
if self.product:
self.product.default_uom.digits
return 2
def get_listing_url(self, name):
"""
Downstream modules should implement this function
and return a valid url
"""
return None
@classmethod
def get_availability_fields(cls, listings, names):
listing_ids = map(int, listings)
values = defaultdict(lambda: dict.fromkeys(listing_ids, None))
for name in names:
# Just call the default dict once so all fields have values
# even if product is absent
values[name]
for listing in listings:
if listing.product:
availability = listing.get_availability()
values['availability_type_used'][listing.id] = \
availability['type']
values['availability_used'][listing.id] = availability.get(
'value'
)
values['quantity'][listing.id] = availability.get('quantity')
return values
@fields.depends('channel')
def on_change_with_channel_source(self, name=None):
return self.channel and self.channel.source
@classmethod
def __setup__(cls):
'''
Setup the class and define constraints
'''
super(ProductSaleChannelListing, cls).__setup__()
table = cls.__table__()
cls._sql_constraints += [
(
'channel_product_identifier_uniq',
Unique(table, table.channel, table.product_identifier),
'This external product is already mapped with same channel.'
)
]
cls._buttons.update({
'export_inventory_button': {},
})
@staticmethod
def default_state():
return 'active'
@classmethod
def create_from(cls, channel, product_data):
"""
Create a listing for the product from channel and data
"""
raise NotImplementedError(
"create_from is not implemented in channel listing for %s channels"
% channel.source
)
@classmethod
@ModelView.button
def export_inventory_button(cls, listings):
return cls.export_bulk_inventory(listings)
def export_inventory(self):
"""
Export listing.product inventory to listing.channel
Since external channels are implemented by downstream modules, it is
the responsibility of those channels to implement exporting or call
super to delegate.
"""
raise NotImplementedError(
"Export inventory is not implemented for %s channels"
% self.channel.source
)
@classmethod
def export_bulk_inventory(cls, listings):
"""
Export listing.product inventory to listing.channel in bulk
Since external channels are implemented by downstream modules, it is
the responsibility of those channels to implement bulk exporting for
respective channels.
Default behaviour is to export inventory individually.
"""
for listing in listings:
listing.export_inventory()
def import_product_image(self):
"""
Import specific product image from external channel based on product
identifier.
Since external channels are implemented by downstream modules, it is
the responsibility of those channels to implement importing or call
super to delegate.
"""
raise NotImplementedError(
"Method import_product_image is not implemented for %s channel yet"
% self.source
)
def get_availability_context(self):
"""
Allow overriding the context used to compute availability of
products.
"""
return {
'locations': [self.channel.warehouse.id],
}
def get_availability(self):
"""
Return the availability of the product for this listing
"""
Product = Pool().get('product.product')
with Transaction().set_context(**self.get_availability_context()):
rv = {'type': 'bucket', 'value': None, 'quantity': None}
if self.product:
product = Product(self.product.id)
rv['quantity'] = product.quantity
if rv['quantity'] > 0:
rv['value'] = 'in_stock'
else:
rv['value'] = 'out_of_stock'
return rv