-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsale.py
427 lines (353 loc) · 13 KB
/
sale.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
# -*- coding: utf-8 -*-
from trytond.model import fields, ModelView
from trytond.pool import PoolMeta, Pool
from trytond.pyson import Eval, Bool, Get
from trytond.wizard import Wizard
__all__ = [
'SaleLine', 'Sale', 'AddSalePaymentView', 'Payment', 'AddSalePayment'
]
__metaclass__ = PoolMeta
class SaleLine:
"SaleLine"
__name__ = 'sale.line'
gift_card_delivery_mode = fields.Function(
fields.Selection([
('virtual', 'Virtual'),
('physical', 'Physical'),
('combined', 'Combined'),
], 'Gift Card Delivery Mode', states={
'invisible': ~Bool(Eval('is_gift_card')),
}, depends=['is_gift_card']), 'get_gift_card_delivery_mode'
)
is_gift_card = fields.Function(
fields.Boolean('Gift Card'),
'get_is_gift_card'
)
gift_cards = fields.One2Many(
'gift_card.gift_card', "sale_line", "Gift Cards", readonly=True
)
message = fields.Text(
"Message", states={'invisible': ~Bool(Eval('is_gift_card'))}
)
recipient_email = fields.Char(
"Recipient Email", states={
'invisible': ~(
Bool(Eval('is_gift_card')) &
(Eval('gift_card_delivery_mode').in_(['virtual', 'combined']))
),
'required': (
Bool(Eval('is_gift_card')) &
(Eval('gift_card_delivery_mode').in_(['virtual', 'combined']))
),
}, depends=['gift_card_delivery_mode', 'is_gift_card']
)
recipient_name = fields.Char(
"Recipient Name", states={
'invisible': ~Bool(Eval('is_gift_card')),
}, depends=['is_gift_card']
)
allow_open_amount = fields.Function(
fields.Boolean("Allow Open Amount?", states={
'invisible': ~Bool(Eval('is_gift_card'))
}, depends=['is_gift_card']), 'get_allow_open_amount'
)
gc_price = fields.Many2One(
'product.product.gift_card.price', "Gift Card Price", states={
'required': (
~Bool(Eval('allow_open_amount')) & Bool(Eval('is_gift_card'))
),
'invisible': ~(
~Bool(Eval('allow_open_amount')) & Bool(Eval('is_gift_card'))
)
}, depends=['allow_open_amount', 'is_gift_card', 'product'], domain=[
('product', '=', Eval('product'))
]
)
@classmethod
def view_attributes(cls):
return super(SaleLine, cls).view_attributes() + [
('//page[@id="gift_cards"]', 'states', {
'invisible': ~Bool(Eval('is_gift_card'))
}), ('//separator[@id="recipient_details"]', 'states', {
'invisible': ~Bool(Eval('is_gift_card'))
}), (
'//field[@name="message"]', 'spell',
Get(Eval('_parent_sale', {}), 'party_lang')
)]
@fields.depends('product')
def on_change_with_allow_open_amount(self, name=None):
SaleLine = Pool().get('sale.line')
return SaleLine.get_allow_open_amount(
[self], name='allow_open_amount'
)[self.id]
@classmethod
def get_allow_open_amount(cls, lines, name):
return {
line.id: (
line.product.allow_open_amount if line.product else None
)
for line in lines
}
@fields.depends('gc_price', 'unit_price')
def on_change_gc_price(self):
if self.gc_price:
self.unit_price = self.gc_price.price
@classmethod
def __setup__(cls):
super(SaleLine, cls).__setup__()
cls.unit_price.states['readonly'] = (
~Bool(Eval('allow_open_amount')) & Bool(Eval('is_gift_card'))
)
cls._error_messages.update({
'amounts_out_of_range':
'Gift card amount must be within %s %s and %s %s'
})
@classmethod
def get_gift_card_delivery_mode(cls, lines, name):
res = {}
for line in lines:
if not (line.product and line.is_gift_card):
mode = None
else:
mode = line.product.gift_card_delivery_mode
res[line.id] = mode
return res
@fields.depends('product', 'is_gift_card')
def on_change_with_gift_card_delivery_mode(self, name=None):
"""
Returns delivery mode of the gift card product
"""
SaleLine = Pool().get('sale.line')
return SaleLine.get_gift_card_delivery_mode(
[self], name='gift_card_delivery_mode'
)[self.id]
@classmethod
def copy(cls, lines, default=None):
if default is None:
default = {}
default['gift_cards'] = None
return super(SaleLine, cls).copy(lines, default=default)
@fields.depends('product')
def on_change_with_is_gift_card(self, name=None):
"""
Returns boolean value to tell if product is gift card or not
"""
SaleLine = Pool().get('sale.line')
return SaleLine.get_is_gift_card(
[self], name='is_gift_card'
)[self.id]
@classmethod
def get_is_gift_card(cls, lines, name):
return {
line.id: (
line.product.is_gift_card if line.product else None
)
for line in lines
}
def get_invoice_line(self):
"""
Pick up liability account from gift card configuration for invoices
"""
GiftCardConfiguration = Pool().get('gift_card.configuration')
lines = super(SaleLine, self).get_invoice_line()
if lines and self.is_gift_card:
liability_account = GiftCardConfiguration(1).liability_account
if not liability_account:
self.raise_user_error(
"Liability Account is missing from Gift Card "
"Configuration"
)
for invoice_line in lines:
invoice_line.account = liability_account
return lines
@fields.depends('is_gift_card', 'product')
def on_change_is_gift_card(self):
ModelData = Pool().get('ir.model.data')
if self.is_gift_card:
self.product = None
self.description = "Gift Card"
self.unit = ModelData.get_id('product', 'uom_unit')
else:
self.description = None
self.unit = None
def create_gift_cards(self):
'''
Create the actual gift card for this line
'''
GiftCard = Pool().get('gift_card.gift_card')
if not self.is_gift_card:
# Not a gift card line
return None
product = self.product
if product.allow_open_amount and not (
product.gc_min <= self.unit_price <= product.gc_max
):
self.raise_user_error(
"amounts_out_of_range", (
self.sale.currency.code, product.gc_min,
self.sale.currency.code, product.gc_max
)
)
# XXX: Do not consider cancelled ones in the gift cards.
# card could have been cancelled for reasons like wrong message ?
quantity_created = len(self.gift_cards)
if self.sale.gift_card_method == 'order':
quantity = self.quantity - quantity_created
else:
# On invoice paid
quantity_paid = 0
for invoice_line in self.invoice_lines:
if invoice_line.invoice.state == 'paid':
invoice_line.quantity
quantity_paid += invoice_line.quantity
# Remove already created gift cards
quantity = quantity_paid - quantity_created
if not quantity > 0:
# No more gift cards to create
return
gift_cards = GiftCard.create([{
'amount': self.unit_price,
'sale_line': self.id,
'message': self.message,
'recipient_email': self.recipient_email,
'recipient_name': self.recipient_name,
'currency': self.sale.currency.id,
'origin': '%s,%d' % (self.sale.__name__, self.sale.id),
} for each in range(0, int(quantity))])
GiftCard.activate(gift_cards)
return gift_cards
class Sale:
"Sale"
__name__ = 'sale.sale'
# Gift card creation method
gift_card_method = fields.Selection([
('order', 'On Order Processed'),
('invoice', 'On Invoice Paid'),
], 'Gift Card Creation Method', required=True)
@classmethod
def __setup__(cls):
super(Sale, cls).__setup__()
cls.gift_card_method.states = cls.shipment_method.states
@staticmethod
def default_gift_card_method():
SaleConfig = Pool().get('sale.configuration')
config = SaleConfig(1)
return config.gift_card_method
def create_gift_cards(self):
'''
Create the gift cards if not already created
'''
for line in filter(lambda l: l.is_gift_card, self.lines):
line.create_gift_cards()
@classmethod
def get_payment_method_priority(cls):
"""Priority order for payment methods. Downstream modules can override
this method to change the method priority.
"""
return ('gift_card',) + \
super(Sale, cls).get_payment_method_priority()
@classmethod
@ModelView.button
def process(cls, sales):
"""
Create gift card on processing sale
"""
super(Sale, cls).process(sales)
for sale in sales:
if sale.state not in ('confirmed', 'processing', 'done'):
continue # pragma: no cover
sale.create_gift_cards()
class Payment:
'Payment'
__name__ = 'sale.payment'
gift_card = fields.Many2One(
"gift_card.gift_card", "Gift Card", states={
'required': Eval('method') == 'gift_card',
'invisible': ~(Eval('method') == 'gift_card'),
}, domain=[('state', '=', 'active')], depends=['method']
)
def _create_payment_transaction(self, amount, description):
"""Creates an active record for gateway transaction.
"""
payment_transaction = super(Payment, self)._create_payment_transaction(
amount, description,
)
payment_transaction.gift_card = self.gift_card
return payment_transaction
@classmethod
def validate(cls, payments):
"""
Validate payments
"""
super(Payment, cls).validate(payments)
for payment in payments:
payment.check_gift_card_amount()
def check_gift_card_amount(self):
"""
Payment should not be created if gift card has insufficient amount
"""
if self.gift_card and self.gift_card.amount_available < self.amount:
self.raise_user_error(
'insufficient_amount', (
self.gift_card.number, self.sale.currency.code, self.amount,
)
)
@classmethod
def __setup__(cls):
super(Payment, cls).__setup__()
cls._error_messages.update({
'insufficient_amount':
'Gift card %s has no sufficient amount to pay %s %s'
})
def get_payment_description(self, name):
"""
Return a short description of the sale payment
This can be used in documents to show payment details
"""
if self.method == 'gift_card':
return (
"Paid by Gift Certificate " + "(" + ("x" * 5) +
self.gift_card.number[-3:] + ")"
)
return super(Payment, self).get_payment_description(name)
class AddSalePaymentView:
"""
View for adding Sale Payments
"""
__name__ = 'sale.payment.add_view'
gift_card = fields.Many2One(
"gift_card.gift_card", "Gift Card", states={
'required': Eval('method') == 'gift_card',
'invisible': ~(Eval('method') == 'gift_card'),
}, domain=[('state', '=', 'active')], depends=['method']
)
@classmethod
def __setup__(cls):
super(AddSalePaymentView, cls).__setup__()
for field in [
'owner', 'number', 'expiry_year', 'expiry_month',
'csc', 'swipe_data', 'payment_profile'
]:
getattr(cls, field).states['invisible'] = (
getattr(cls, field).states['invisible'] |
(Eval('method') == 'gift_card')
)
class AddSalePayment(Wizard):
"""
Wizard to add a Sale Payment
"""
__name__ = 'sale.payment.add'
def create_sale_payment(self, profile=None):
"""
Helper function to create new payment
"""
sale_payment = super(AddSalePayment, self).create_sale_payment(
profile=profile
)
# XXX: While a value will exist for the field gift_card when
# it's the Tryton client calling the wizard, it is not going
# to be there as an attribute when called from API (from another
# module/model for example).
sale_payment.gift_card = (self.payment_info.method == 'gift_card') \
and self.payment_info.gift_card or None
return sale_payment