-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
orders.py
602 lines (496 loc) · 19.6 KB
/
orders.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
import graphene
from django.core.exceptions import ValidationError
from ....account.models import User
from ....core.permissions import OrderPermissions
from ....core.taxes import zero_taxed_money
from ....order import events, models
from ....order.actions import (
cancel_order,
clean_mark_order_as_paid,
mark_order_as_paid,
order_captured,
order_refunded,
order_shipping_updated,
order_voided,
)
from ....order.error_codes import InvoiceErrorCode, OrderErrorCode
from ....order.utils import get_valid_shipping_methods_for_order
from ....payment import CustomPaymentChoices, PaymentError, gateway
from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import Decimal
from ...core.types.common import OrderError
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
from ...meta.deprecated.types import MetaInput, MetaPath
from ...order.enums import InvoiceStatus
from ...order.mutations.draft_orders import DraftOrderUpdate
from ...order.types import Invoice, Order, OrderEvent
from ...shipping.types import ShippingMethod
def clean_order_update_shipping(order, method):
if not order.shipping_address:
raise ValidationError(
{
"order": ValidationError(
"Cannot choose a shipping method for an order without "
"the shipping address.",
code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS,
)
}
)
valid_methods = get_valid_shipping_methods_for_order(order)
if valid_methods is None or method.pk not in valid_methods.values_list(
"id", flat=True
):
raise ValidationError(
{
"shipping_method": ValidationError(
"Shipping method cannot be used with this order.",
code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE,
)
}
)
def clean_order_cancel(order):
if order and not order.can_cancel():
raise ValidationError(
{
"order": ValidationError(
"This order can't be canceled.",
code=OrderErrorCode.CANNOT_CANCEL_ORDER,
)
}
)
def clean_payment(payment):
if not payment:
raise ValidationError(
{
"payment": ValidationError(
"There's no payment associated with the order.",
code=OrderErrorCode.PAYMENT_MISSING,
)
}
)
def clean_order_capture(payment):
clean_payment(payment)
if not payment.is_active:
raise ValidationError(
{
"payment": ValidationError(
"Only pre-authorized payments can be captured",
code=OrderErrorCode.CAPTURE_INACTIVE_PAYMENT,
)
}
)
def clean_void_payment(payment):
"""Check for payment errors."""
clean_payment(payment)
if not payment.is_active:
raise ValidationError(
{
"payment": ValidationError(
"Only pre-authorized payments can be voided",
code=OrderErrorCode.VOID_INACTIVE_PAYMENT,
)
}
)
def clean_refund_payment(payment):
clean_payment(payment)
if payment.gateway == CustomPaymentChoices.MANUAL:
raise ValidationError(
{
"payment": ValidationError(
"Manual payments can not be refunded.",
code=OrderErrorCode.CANNOT_REFUND,
)
}
)
def try_payment_action(order, user, payment, func, *args, **kwargs):
try:
func(*args, **kwargs)
except (PaymentError, ValueError) as e:
message = str(e)
events.payment_failed_event(
order=order, user=user, message=message, payment=payment
)
raise ValidationError(
{"payment": ValidationError(message, code=OrderErrorCode.PAYMENT_ERROR)}
)
return True
class OrderUpdateInput(graphene.InputObjectType):
billing_address = AddressInput(description="Billing address of the customer.")
user_email = graphene.String(description="Email address of the customer.")
shipping_address = AddressInput(description="Shipping address of the customer.")
class OrderUpdate(DraftOrderUpdate):
class Arguments:
id = graphene.ID(required=True, description="ID of an order to update.")
input = OrderUpdateInput(
required=True, description="Fields required to update an order."
)
class Meta:
description = "Updates an order."
model = models.Order
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def clean_input(cls, info, instance, data):
draft_order_cleaned_input = super().clean_input(info, instance, data)
# We must to filter out field added by DraftOrderUpdate
editable_fields = ["billing_address", "shipping_address", "user_email"]
cleaned_input = {}
for key in draft_order_cleaned_input:
if key in editable_fields:
cleaned_input[key] = draft_order_cleaned_input[key]
return cleaned_input
@classmethod
def save(cls, info, instance, cleaned_input):
super().save(info, instance, cleaned_input)
if instance.user_email:
user = User.objects.filter(email=instance.user_email).first()
instance.user = user
instance.save()
class OrderUpdateShippingInput(graphene.InputObjectType):
shipping_method = graphene.ID(
description="ID of the selected shipping method.", name="shippingMethod"
)
class OrderUpdateShipping(BaseMutation):
order = graphene.Field(Order, description="Order with updated shipping method.")
class Arguments:
id = graphene.ID(
required=True,
name="order",
description="ID of the order to update a shipping method.",
)
input = OrderUpdateShippingInput(
description="Fields required to change shipping method of the order."
)
class Meta:
description = "Updates a shipping method of the order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
data = data.get("input")
if not data["shipping_method"]:
if not order.is_draft() and order.is_shipping_required():
raise ValidationError(
{
"shipping_method": ValidationError(
"Shipping method is required for this order.",
code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
)
}
)
order.shipping_method = None
order.shipping_price = zero_taxed_money()
order.shipping_method_name = None
order.save(
update_fields=[
"currency",
"shipping_method",
"shipping_price_net_amount",
"shipping_price_gross_amount",
"shipping_method_name",
]
)
return OrderUpdateShipping(order=order)
method = cls.get_node_or_error(
info,
data["shipping_method"],
field="shipping_method",
only_type=ShippingMethod,
)
clean_order_update_shipping(order, method)
order.shipping_method = method
order.shipping_price = info.context.extensions.calculate_order_shipping(order)
order.shipping_method_name = method.name
order.save(
update_fields=[
"currency",
"shipping_method",
"shipping_method_name",
"shipping_price_net_amount",
"shipping_price_gross_amount",
]
)
# Post-process the results
order_shipping_updated(order)
return OrderUpdateShipping(order=order)
class OrderAddNoteInput(graphene.InputObjectType):
message = graphene.String(
description="Note message.", name="message", required=True
)
class OrderAddNote(BaseMutation):
order = graphene.Field(Order, description="Order with the note added.")
event = graphene.Field(OrderEvent, description="Order note created.")
class Arguments:
id = graphene.ID(
required=True,
description="ID of the order to add a note for.",
name="order",
)
input = OrderAddNoteInput(
required=True, description="Fields required to create a note for the order."
)
class Meta:
description = "Adds note to the order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def clean_input(cls, _info, _instance, data):
message = data["input"]["message"].strip()
if not message:
raise ValidationError(
{
"message": ValidationError(
"Message can't be empty.", code=OrderErrorCode.REQUIRED,
)
}
)
data["input"]["message"] = message
return data
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
cleaned_input = cls.clean_input(info, order, data)
event = events.order_note_added_event(
order=order,
user=info.context.user,
message=cleaned_input["input"]["message"],
)
return OrderAddNote(order=order, event=event)
class OrderCancel(BaseMutation):
order = graphene.Field(Order, description="Canceled order.")
class Arguments:
id = graphene.ID(required=True, description="ID of the order to cancel.")
restock = graphene.Boolean(
required=True, description="Determine if lines will be restocked or not."
)
class Meta:
description = "Cancel an order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def perform_mutation(cls, _root, info, restock, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
clean_order_cancel(order)
cancel_order(order=order, user=info.context.user, restock=restock)
return OrderCancel(order=order)
class OrderMarkAsPaid(BaseMutation):
order = graphene.Field(Order, description="Order marked as paid.")
class Arguments:
id = graphene.ID(required=True, description="ID of the order to mark paid.")
class Meta:
description = "Mark order as manually paid."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def clean_billing_address(cls, instance):
if not instance.billing_address:
raise ValidationError(
"Order billing address is required to mark order as paid.",
code=OrderErrorCode.BILLING_ADDRESS_NOT_SET,
)
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
cls.clean_billing_address(order)
try_payment_action(
order, info.context.user, None, clean_mark_order_as_paid, order
)
mark_order_as_paid(order, info.context.user)
return OrderMarkAsPaid(order=order)
class OrderCapture(BaseMutation):
order = graphene.Field(Order, description="Captured order.")
class Arguments:
id = graphene.ID(required=True, description="ID of the order to capture.")
amount = Decimal(required=True, description="Amount of money to capture.")
class Meta:
description = "Capture an order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def perform_mutation(cls, _root, info, amount, **data):
if amount <= 0:
raise ValidationError(
{
"amount": ValidationError(
"Amount should be a positive number.",
code=OrderErrorCode.ZERO_QUANTITY,
)
}
)
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
payment = order.get_last_payment()
clean_order_capture(payment)
try_payment_action(
order, info.context.user, payment, gateway.capture, payment, amount
)
order_captured(order, info.context.user, amount, payment)
return OrderCapture(order=order)
class OrderVoid(BaseMutation):
order = graphene.Field(Order, description="A voided order.")
class Arguments:
id = graphene.ID(required=True, description="ID of the order to void.")
class Meta:
description = "Void an order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
payment = order.get_last_payment()
clean_void_payment(payment)
try_payment_action(order, info.context.user, payment, gateway.void, payment)
order_voided(order, info.context.user, payment)
return OrderVoid(order=order)
class OrderRefund(BaseMutation):
order = graphene.Field(Order, description="A refunded order.")
class Arguments:
id = graphene.ID(required=True, description="ID of the order to refund.")
amount = Decimal(required=True, description="Amount of money to refund.")
class Meta:
description = "Refund an order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@classmethod
def perform_mutation(cls, _root, info, amount, **data):
if amount <= 0:
raise ValidationError(
{
"amount": ValidationError(
"Amount should be a positive number.",
code=OrderErrorCode.ZERO_QUANTITY,
)
}
)
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
payment = order.get_last_payment()
clean_refund_payment(payment)
try_payment_action(
order, info.context.user, payment, gateway.refund, payment, amount
)
order_refunded(order, info.context.user, amount, payment)
return OrderRefund(order=order)
class OrderUpdateMeta(UpdateMetaBaseMutation):
class Meta:
description = "Updates meta for order."
model = models.Order
public = True
class Arguments:
token = graphene.UUID(
description="Token of an object to update.", required=True
)
input = MetaInput(
description="Fields required to update new or stored metadata item.",
required=True,
)
@classmethod
def get_instance(cls, info, **data):
token = data["token"]
return models.Order.objects.get(token=token)
class OrderUpdatePrivateMeta(UpdateMetaBaseMutation):
class Meta:
description = "Updates private meta for order."
model = models.Order
permissions = (OrderPermissions.MANAGE_ORDERS,)
public = False
class OrderClearMeta(ClearMetaBaseMutation):
class Meta:
description = "Clears stored metadata value."
model = models.Order
permissions = (OrderPermissions.MANAGE_ORDERS,)
public = True
class Arguments:
token = graphene.UUID(description="Token of an object to clear.", required=True)
input = MetaPath(
description="Fields required to update new or stored metadata item.",
required=True,
)
@classmethod
def get_instance(cls, info, **data):
token = data["token"]
return models.Order.objects.get(token=token)
class OrderClearPrivateMeta(ClearMetaBaseMutation):
class Meta:
description = "Clears stored private metadata value."
model = models.Order
permissions = (OrderPermissions.MANAGE_ORDERS,)
public = False
class RequestInvoice(BaseMutation):
class Meta:
description = "Request an invoice for the order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
class Arguments:
order_id = graphene.ID(
required=True, description="ID of the order related to invoice."
)
number = graphene.String(
required=False, description="Invoice number (optional)."
)
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(
info, data["order_id"], only_type=Order, field="orderId"
)
invoice = models.Invoice.objects.create(
order=order, status=InvoiceStatus.PENDING, number=data.get("number")
)
info.context.extensions.invoice_request(
order=order, invoice=invoice, number=data.get("number")
)
return RequestInvoice()
class DeleteInvoice(ModelDeleteMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of an invoice to delete.")
class Meta:
description = "Deletes an invoice."
model = models.Invoice
permissions = (OrderPermissions.MANAGE_ORDERS,)
@classmethod
def perform_mutation(cls, _root, info, **data):
info.context.extensions.invoice_delete(
cls.get_node_or_error(info, data["id"], only_type=Invoice)
)
return super().perform_mutation(_root, info, **data)
class UpdateInvoice(ModelMutation):
invoice = graphene.Field(Invoice, description="An updated invoice.")
class Arguments:
id = graphene.ID(required=True, description="ID of an invoice to update.")
number = graphene.String(description="Invoice number")
url = graphene.String(description="URL of an invoice to download.")
class Meta:
description = "Updates an invoice."
model = models.Invoice
permissions = (OrderPermissions.MANAGE_ORDERS,)
@classmethod
def clean_input(cls, info, instance, data):
if not (instance.number or data.get("number")) or not (
instance.url or data.get("url")
):
raise ValidationError(
{
"invoice": ValidationError(
"URL and number need to be set after update operation.",
code=InvoiceErrorCode.URL_OR_NUMBER_NOT_SET,
)
}
)
return data
@classmethod
def perform_mutation(cls, _root, info, **data):
instance = cls.get_instance(info, **data)
cleaned_input = cls.clean_input(info, instance, data)
instance.update_invoice(
number=cleaned_input.get("number"), url=cleaned_input.get("url")
)
instance.status = InvoiceStatus.READY
instance.save()
return UpdateInvoice(invoice=instance)