-
Notifications
You must be signed in to change notification settings - Fork 26
/
product.py
215 lines (177 loc) · 6.57 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
# -*- coding: utf-8 -*-
'''
product
:copyright: (c) 2014 by Openlabs Technologies & Consulting (P) Ltd.
:license: GPLv3, see LICENSE for more details
'''
from decimal import Decimal
from trytond.pool import Pool, PoolMeta
from jinja2.filters import do_striptags
from werkzeug.exceptions import NotFound
from nereid import jsonify, flash, request, url_for, route, redirect, \
render_template, abort
from nereid.contrib.locale import make_lazy_gettext
from forms import GiftCardForm
_ = make_lazy_gettext('gift_card')
__all__ = ['Product']
__metaclass__ = PoolMeta
class Product:
"Product extension for Nereid"
__name__ = "product.product"
def serialize(self, purpose=None):
"""
Downstream implementation which adds a key called inventory_status
to the dictionary if purpose is 'variant_selection'.
:param purpose: String which decides structure of dictionary
"""
res = super(Product, self).serialize(purpose=purpose)
if purpose == 'variant_selection':
res.update({
'inventory_status': self.inventory_status(),
})
return res
def get_default_image(self, name):
"Returns default product image"
ModelData = Pool().get('ir.model.data')
# Fallback condition if there is no default_image_set defined
images = self.get_images()
if images:
return images[0].id
else:
return ModelData.get_id("nereid_webshop", "mystery_box")
def ga_product_data(self, **kwargs):
'''
Return a dictionary of the product information as expected by Google
Analytics
Other possible values for kwargs include
:param list: The name of the list in which this impression is to be
recorded
:param position: Integer position of the item on the view
'''
rv = {
'id': self.code or unicode(self.id),
'name': self.name,
'category': self.category and self.category.name or None,
}
rv.update(kwargs)
return rv
def json_ld(self, **kwargs):
'''
Returns a JSON serializable dictionary of the product with the Product
schema markup.
See: http://schema.org/Product
Any key value pairs passed to kwargs overwrites default information.
'''
sale_price = self.sale_price(1)
return {
"@context": "http://schema.org",
"@type": "Product",
"name": self.name,
"sku": self.code,
"description": do_striptags(self.description),
"offers": {
"@type": "Offer",
"availability": "http://schema.org/InStock",
"price": str(sale_price),
"priceCurrency": request.nereid_currency.code,
},
"image": self.default_image.transform_command().thumbnail(
500, 500, 'a').url(_external=True),
"url": self.get_absolute_url(_external=True),
}
@classmethod
@route('/product/<uri>')
@route('/product/<path:path>/<uri>')
def render(cls, uri, path=None):
"""
Render gift card template if product is of type gift card
"""
render_obj = super(Product, cls).render(uri, path)
if not isinstance(render_obj, NotFound) \
and render_obj.context['product'].is_gift_card:
# Render gift card
return redirect(
url_for('product.product.render_gift_card', uri=uri)
)
return render_obj
@classmethod
@route('/gift-card/<uri>', methods=['GET', 'POST'])
def render_gift_card(cls, uri):
"""
Add gift card as a new line in cart
Request:
'GET': Renders gift card page
'POST': Buy Gift Card
Response:
'OK' if X-HTTPRequest
Redirect to shopping cart if normal request
"""
SaleLine = Pool().get('sale.line')
Cart = Pool().get('nereid.cart')
try:
product, = cls.search([
('displayed_on_eshop', '=', True),
('uri', '=', uri),
('template.active', '=', True),
('is_gift_card', '=', True)
], limit=1)
except ValueError:
abort(404)
form = GiftCardForm(product)
if form.validate_on_submit():
cart = Cart.open_cart(create_order=True)
# Code to add gift card as a line to cart
values = {
'product': product.id,
'sale': cart.sale.id,
'type': 'line',
'sequence': 10,
'quantity': 1,
'unit': None,
'description': None,
'recipient_email': form.recipient_email.data,
'recipient_name': form.recipient_name.data,
'message': form.message.data,
}
values.update(SaleLine(**values).on_change_product())
# Here 0 means the default option to enter open amount is
# selected
if form.selected_amount.data != 0:
values.update({'gc_price': form.selected_amount.data})
values.update(SaleLine(**values).on_change_gc_price())
else:
values.update({'unit_price': Decimal(form.open_amount.data)})
order_line = SaleLine(**values)
order_line.save()
message = 'Gift Card has been added to your cart'
if request.is_xhr: # pragma: no cover
return jsonify(message=message)
flash(_(message), 'info')
return redirect(url_for('nereid.cart.view_cart'))
return render_template(
'catalog/gift-card.html', product=product, form=form
)
def get_absolute_url(self, **kwargs):
"""
Return gift card URL if product is a gift card
"""
if self.is_gift_card:
return url_for(
'product.product.render_gift_card', uri=self.uri, **kwargs
)
return super(Product, self).get_absolute_url(**kwargs)
def get_menu_item(self, max_depth):
"""
Return dictionary with serialized node for menu item
{
title: <display name>,
link: <url>,
record: <instance of record> # if type_ is record
}
"""
return {
'record': self,
'title': self.name,
'image': self.default_image,
'link': self.get_absolute_url(),
}