/
product.py
641 lines (550 loc) · 19.1 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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Budy
# Copyright (c) 2008-2016 Hive Solutions Lda.
#
# This file is part of Hive Budy.
#
# Hive Budy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Budy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Budy. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2016 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import json
import commons
import appier
from . import base
class Product(base.BudyBase):
GENDER_S = {
"Male" : "Male",
"Female" : "Female",
"Both" : "Both"
}
short_description = appier.field(
index = True,
default = True
)
search_description = appier.field(
index = True
)
product_id = appier.field(
index = True
)
gender = appier.field(
index = True,
meta = "enum",
enum = GENDER_S
)
quantity_hand = appier.field(
type = commons.Decimal,
index = True
)
quantity_reserved = appier.field(
type = commons.Decimal,
index = True
)
price = appier.field(
type = commons.Decimal,
index = True
)
currency = appier.field(
index = True
)
order = appier.field(
type = int,
index = True
)
tag = appier.field()
tag_description = appier.field()
price_provider = appier.field(
index = True
)
price_url = appier.field(
index = True,
meta = "url"
)
farfetch_url = appier.field(
index = True,
meta = "url"
)
farfetch_male_url = appier.field(
index = True,
meta = "url"
)
farfetch_female_url = appier.field(
index = True,
meta = "url"
)
characteristics = appier.field(
type = list
)
colors = appier.field(
type = appier.references(
"Color",
name = "id"
)
)
categories = appier.field(
type = appier.references(
"Category",
name = "id"
)
)
collections = appier.field(
type = appier.references(
"Collection",
name = "id"
)
)
variants = appier.field(
type = appier.references(
"Product",
name = "id"
)
)
images = appier.field(
type = appier.references(
"Media",
name = "id"
)
)
brand = appier.field(
type = appier.reference(
"Brand",
name = "id"
)
)
season = appier.field(
type = appier.reference(
"Season",
name = "id"
)
)
measurements = appier.field(
type = appier.references(
"Measurement",
name = "id"
)
)
compositions = appier.field(
type = appier.references(
"Composition",
name = "id"
)
)
live_movel = appier.field(
type = appier.references(
"LiveModel",
name = "id"
)
)
@classmethod
def validate(cls):
return super(Product, cls).validate() + [
appier.not_null("short_description"),
appier.not_empty("short_description"),
appier.not_null("gender"),
appier.not_empty("gender"),
appier.not_null("price"),
appier.gte("price", 0.0)
]
@classmethod
def list_names(cls):
return ["id", "product_id", "short_description", "enabled", "gender", "tag"]
@classmethod
def order_name(self):
return ["id", -1]
@classmethod
def index_names(cls):
return super(Product, cls).index_names() + ["product_id"]
@classmethod
def from_omni(
cls,
merchandise,
gender = "Both",
currency = "EUR",
force = False
):
from . import color
from . import category
from . import collection
object_id = merchandise["object_id"]
company_product_code = merchandise["company_product_code"]
metadata = merchandise["metadata"] or dict()
_color = metadata.get("material")
_category = metadata.get("category")
_collection = metadata.get("collection")
order = metadata.get("order")
if _color: _color = color.Color.ensure_s(_color)
if _category: _category = category.Category.ensure_s(_category)
if _collection: _collection = collection.Collection.ensure_s(_collection)
_product = cls.get(product_id = company_product_code, raise_e = False)
if not _product: _product = cls()
_product.product_id = company_product_code
_product.short_description = merchandise["name"] or company_product_code
_product.description = merchandise["description"]
_product.gender = gender
_product.currency = currency
_product.order = order
_product.characteristics = metadata.get("characteristics", [])
_product.colors = [_color]
_product.categories = [_category]
_product.collections = [_collection]
_product.meta = dict(object_id = object_id)
if "stock_on_hand" in merchandise or force:
_product.quantity_hand = merchandise.get("stock_on_hand", 0.0)
if "retail_price" in merchandise or force:
_product.price = merchandise.get("retail_price", 0.0)
return _product
@classmethod
@appier.operation(
name = "Import Omni",
parameters = (
("Product", "product", "longtext"),
),
factory = True
)
def import_omni_s(cls, product, safe = True):
product = json.loads(product)
product = cls.from_omni(product)
product.save()
@classmethod
@appier.operation(
name = "Import CSV",
parameters = (
("CSV File", "file", "file"),
("Empty source", "empty", bool, True)
)
)
def import_csv_s(cls, file, empty):
def callback(line):
from . import color
from . import brand
from . import season
from . import category
from . import collection
from . import composition
from . import measurement
description,\
short_description,\
product_id,\
gender,\
price,\
order,\
tag,\
tag_description,\
farfetch_url,\
farfetch_male_url,\
farfetch_female_url,\
colors,\
categories,\
collections, \
variants,\
_brand,\
_season,\
measurements,\
compositions, \
price_provider, \
price_url = line
product_id = product_id or None
price = float(price) if price else None
order = int(order) if order else None
tag = tag or None
tag_description = tag_description or None
farfetch_url = farfetch_url or None
farfetch_male_url = farfetch_male_url or None
farfetch_female_url = farfetch_female_url or None
price_provider = price_provider or None
price_url = price_url or None
colors = colors.split(";") if colors else []
colors = color.Color.find(name = {"$in" : colors})
categories = categories.split(";") if categories else []
categories = category.Category.find(name = {"$in" : categories})
collections = collections.split(";") if collections else []
collections = collection.Collection.find(name = {"$in" : collections})
variants = variants.split(";") if variants else []
variants = Product.find(product_id = {"$in" : variants})
_brand = brand.Brand.find(name = _brand) if _brand else None
_season = season.Season.find(name = _season) if _season else None
measurements = measurements.split(";") if measurements else []
measurements = measurement.Measurement.find(name = {"$in" : measurements})
compositions = compositions.split(";") if compositions else []
compositions = composition.Composition.find(name = {"$in" : compositions})
product = cls(
description = description,
short_description = short_description,
product_id = product_id,
gender = gender,
price = price,
order = order,
tag = tag,
tag_description = tag_description,
farfetch_url = farfetch_url,
farfetch_male_url = farfetch_male_url,
farfetch_female_url = farfetch_female_url,
colors = colors,
categories = categories,
collections = collections,
variants = variants,
brand = _brand,
season = _season,
measurements = measurements,
compositions = compositions,
price_provider = price_provider,
price_url = price_url
)
product.save()
if empty: cls.delete_c()
cls._csv_import(file, callback)
@classmethod
@appier.link(name = "Export Simple")
def simple_csv_url(cls, absolute = False):
return appier.get_app().url_for(
"product_api.simple_csv",
absolute = absolute
)
def pre_save(self):
base.BudyBase.pre_save(self)
self._update_search_description()
if not self.measurements: return
self.quantity_hand = sum(measurement.quantity_hand for measurement in self.measurements)
self.price = max(measurement.price for measurement in self.measurements)
@appier.operation(name = "Update Search Description")
def update_search_description_s(self):
self._update_search_description()
self.save()
def related(self, limit = 6):
cls = self.__class__
kwargs = dict()
if self.collections: kwargs["collections"] = {"$in" : [self.collections[0].id]}
elif self.categories: kwargs["categories"] = {"$in" : [self.categories[0].id]}
elif self.colors: kwargs["colors"] = {"$in" : [self.colors[0].id]}
kwargs["id"] = {"$nin" : [self.id]}
kwargs["sort"] = [("id", 1)]
count = cls.count(**kwargs)
skip = self._get_offset(count, limit, kwargs = kwargs)
delta = skip + limit - count
if delta > 0: skip = count - skip - delta
if skip < 0: skip = 0
products = cls.find(
eager = ("images",),
skip = skip,
limit = limit,
map = True,
**kwargs
)
return products
def get_measurement(self, value, name = None):
for measurement in self.measurements:
if not measurement.value == value: continue
if not measurement.name == name: continue
return measurement
return None
def get_price(
self,
currency = None,
country = None,
attributes = None
):
if not self.price_provider: return self.price
method = getattr(self, "get_price_%s" % self.price_provider)
return method(
currency = currency,
country = country,
attributes = attributes
)
def get_price_ripe(
self,
currency = None,
country = None,
attributes = None
):
if not self.price_url: return self.price
attributes_m = json.loads(attributes)
p = []
parts = attributes_m.get("parts", {})
embossing = attributes_m.get("embossing", None)
letters = attributes_m.get("letters", None)
for key, value in appier.legacy.iteritems(parts):
material = value["material"]
color = value["color"]
triplet = "%s:%s:%s" % (key, material, color)
p.append(triplet)
params = dict(
product_id = self.product_id,
p = p
)
if currency: params["currency"] = currency
if country: params["country"] = country
if embossing: params["embossing"] = embossing
if letters: params["letters"] = letters
result = appier.get(
self.price_url,
params = params
)
total = result["total"]
return total["price_final"]
def get_currency(self, currency = None):
if not self.price_provider: return self.currency or currency
method = getattr(self, "get_currency_%s" % self.price_provider)
return method(currency = currency)
def get_currency_ripe(self, currency = None):
return self.currency or currency
def get_size(self, currency = None, country = None, attributes = None):
if not self.price_provider: return None, None
method = getattr(self, "get_size_%s" % self.price_provider)
return method(
country = country,
attributes = attributes
)
def get_size_ripe(
self,
currency = None,
country = None,
attributes = None
):
attributes_m = json.loads(attributes)
size = attributes_m["size"]
scale = attributes_m["scale"]
gender = attributes_m["gender"]
if gender == "male": converter = lambda native: ((native - 17) / 2) + 36
else: converter = lambda native: ((native - 17) / 2) + 34
return converter(size), scale
@appier.operation(
name = "Add Collection",
parameters = (
(
"Collection",
"collection",
appier.reference("Collection", name = "id")
),
)
)
def add_collection_s(self, collection):
if not collection: return
if collection in self.collections: return
self.collections.append(collection)
self.save()
@appier.operation(
name = "Remove Collection",
parameters = (
(
"Collection",
"collection",
appier.reference("Collection", name = "id")
),
)
)
def remove_collection_s(self, collection):
if not collection: return
if not collection in self.collections: return
self.collections.remove(collection)
self.save()
@appier.operation(
name = "Add Image",
parameters = (
(
"Image",
"image",
appier.reference("Media", name = "id")
),
)
)
def add_image_s(self, image):
if not image: return
if image in self.images: return
self.images.append(image)
self.save()
@appier.operation(
name = "Remove Image",
parameters = (
(
"Image",
"image",
appier.reference("Media", name = "id")
),
)
)
def remove_image_s(self, image):
if not image: return
if not image in self.images: return
self.images.remove(image)
self.save()
@appier.operation(name = "Fix")
def fix_s(self):
if not self.exists(): return
self.save()
@property
def quantity(self):
return self.quantity_hand
def _get_offset(self, count, limit, kwargs):
return self._get_offset_offset(count, limit, kwargs)
def _get_offset_simple(self, count, limit, kwargs):
return self.id % count
def _get_offset_offset(self, count, limit, kwargs):
cls = self.__class__
kwargs = dict(kwargs)
kwargs["id"] = {"$lt" : self.id}
offset = cls.count(**kwargs)
return offset
def _update_search_description(self):
tokens = []
self._add_tokens("short_description", tokens, pluralize = True)
self._add_tokens("product_id", tokens, pluralize = False)
self._add_tokens("brand.name", tokens, pluralize = True)
self._add_tokens("season.name", tokens, pluralize = True)
self._add_tokens("characteristics", tokens, pluralize = False)
self._add_tokens("colors.name", tokens, pluralize = True)
self._add_tokens("categories.name", tokens, pluralize = True)
self._add_tokens("collections.name", tokens, pluralize = True)
self._add_tokens("compositions.name", tokens, pluralize = True)
tokens_s = "|".join(tokens)
tokens_s = tokens_s.lower()
tokens_s = self._simplify(tokens_s)
self.search_description = tokens_s
def _add_tokens(self, attribute, tokens, pluralize = False):
attributes = attribute.split(".")
attribute = attributes[0]
attributes = attributes[1:] if len(attributes) > 1 else []
if not hasattr(self, attribute): return
value = getattr(self, attribute)
if not value: return
type_s = str(type(value))
values = value if type_s in ("<type 'list'>", "<type 'tuple'>", "<class 'appier.typesf._References'>") else [value]
for value in values:
for _attribute in attributes: value = getattr(value, _attribute)
tokens.append(value)
if pluralize: tokens.append(value)
def _simplify(self, value):
value = value.replace(u"á", "a")
value = value.replace(u"é", "e")
value = value.replace(u"í", "i")
value = value.replace(u"ó", "o")
value = value.replace(u"ú", "u")
value = value.replace(u"ã", "a")
value = value.replace(u"õ", "o")
value = value.replace(u"â", "a")
value = value.replace(u"ô", "o")
value = value.replace(u"ç", "c")
return value
def _pluralize(self, value):
return value + "s"