Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor event names and move static methods outside of classes
NyanKiyoshie2dfc63476c4
diff --git a/docs/architecture/events.rst b/docs/architecture/events.rstindex 42dda74013..01e6fc0370 100644--- a/docs/architecture/events.rst+++ b/docs/architecture/events.rst@@ -108,3 +108,7 @@ If now you want to send a 'sent email' event you would do the following:event.save()Notice how we are providing the email type.++.. note::++ The methods are using a ``model_action_event`` naming pattern.diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 515421b3dc..0fb370b6ac 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -928,7 +928,7 @@ def place_checkout_to_order(request, checkout) -> Order:# Create the order placed and email confirmation sent eventsOrderEvent.objects.bulk_create([- OrderEvent.placed_event(order, request.user),+ OrderEvent.order_created_event(order, request.user),OrderEvent.email_sent_event(order=order, email_type=OrderEventsEmails.ORDER,source=request.user)])diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 249cae67df..aef04a97be 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -271,25 +271,18 @@ class BasePaymentForm(forms.Form):None, pgettext_lazy('Payment form error', 'Payment gateway error: %s') % message)- def _try_payment_action(self, user, action, payment, *args):+ def try_payment_action(self, user, action, *args):try:- action(payment, *args)+ action(self.payment, *args)except (PaymentError, ValueError) as e:message = str(e)self.payment_error(message)OrderEvent.payment_failed_event(order=self.payment.order, source=user,- message=message, payment=payment).save()+ message=message, payment=self.payment).save()return Falsereturn True- def try_payment_action_with_amount(self, user, action):- amount = self.cleaned_data['amount']- return self._try_payment_action(user, action, self.payment, amount)-- def try_payment_action_without_amount(self, user, action):- return self._try_payment_action(user, action, self.payment)-class CapturePaymentForm(BasePaymentForm):@@ -302,7 +295,8 @@ class CapturePaymentForm(BasePaymentForm):raise forms.ValidationError(self.clean_error)def capture(self, user):- return self.try_payment_action_with_amount(user, gateway_capture)+ return self.try_payment_action(+ user, gateway_capture, self.cleaned_data['amount'])class RefundPaymentForm(BasePaymentForm):@@ -322,7 +316,8 @@ class RefundPaymentForm(BasePaymentForm):'Manual payments can not be refunded'))def refund(self, user):- return self.try_payment_action_with_amount(user, gateway_refund)+ return self.try_payment_action(+ user, gateway_refund, self.cleaned_data['amount'])class VoidPaymentForm(BasePaymentForm):@@ -343,7 +338,7 @@ class VoidPaymentForm(BasePaymentForm):raise forms.ValidationError(self.clean_error)def void(self, user):- return self.try_payment_action_without_amount(user, gateway_void)+ return self.try_payment_action(user, gateway_void)class OrderMarkAsPaidForm(forms.Form):@@ -585,7 +580,7 @@ class AddVariantToOrderForm(forms.Form):quantity = self.cleaned_data.get('quantity')line = add_variant_to_order(self.order, variant, quantity, self.discounts, self.taxes)- OrderEvent.draft_added_products_event(+ OrderEvent.draft_order_added_products_event(order=self.order, source=user,order_lines=[(line.quantity, line)]).save()recalculate_order(self.order)diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 997fe8eb01..55fd32435d 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -65,7 +65,7 @@ def order_create(request):status=OrderStatus.DRAFT, display_gross_prices=display_gross_prices)# Create the draft creation event- OrderEvent.draft_created_event(order=order, source=request.user).save()+ OrderEvent.draft_order_created_event(order=order, source=request.user).save()# Send success message and redirect to the draft detailsmessages.success(request, msg)@@ -85,7 +85,7 @@ def create_order_from_draft(request, order_pk):'Order created from draft order')events = [- OrderEvent.placed_event(+ OrderEvent.order_created_event(order=order, source=request.user, from_draft=True)]messages.success(request, msg)@@ -144,7 +144,7 @@ def order_add_note(request, order_pk):form = OrderNoteForm(request.POST or None)status = 200if form.is_valid():- OrderEvent.note_added_event(+ OrderEvent.order_note_added_event(order=order, source=request.user,message=form.cleaned_data['message']).save()msg = pgettext_lazy(@@ -348,7 +348,7 @@ def order_address(request, order_pk, address_type):if update_prices:update_order_prices(order, request.discounts)if not order.is_draft():- OrderEvent.updated_address_event(+ OrderEvent.order_updated_address_event(order=order, source=request.user, address=address).save()messages.success(request, success_msg)return redirect('dashboard:order-details', order_pk=order_pk)diff --git a/saleor/events/models/OrderEvent.py b/saleor/events/models/OrderEvent.pyindex 2b89ddcb4c..d66a78c42b 100644--- a/saleor/events/models/OrderEvent.py+++ b/saleor/events/models/OrderEvent.py@@ -17,13 +17,30 @@ from ..types import OrderEvents, OrderEventsEmailsUserType = AbstractBaseUser+def _lines_per_quantity_to_str_line_list(quantities_per_order_line):+ return [{+ 'quantity': quantity,+ 'item': str(line)+ } for quantity, line in quantities_per_order_line]+++def _get_payment_data(+ amount: Optional[Decimal], payment: Payment) -> Dict:+ return {+ 'parameters': {+ 'amount': amount,+ 'payment_id': payment.token,+ 'payment_gateway': payment.gateway}}++class OrderEvent(models.Model):"""Model used to store events that happened during the order lifecycle.- Args:- parameters: Values needed to display the event on the storefront- type: Type of an order+ Args:+ parameters: Values needed to display the event on the storefront+ type: Type of an order"""+date = models.DateTimeField(default=now, editable=False)type = models.CharField(max_length=255,@@ -43,13 +60,6 @@ class OrderEvent(models.Model):def __repr__(self):return 'OrderEvent(type=%r, user=%r)' % (self.type, self.user)- @staticmethod- def _lines_per_quantity_to_str_line_list(quantities_per_order_line):- return [{- 'quantity': quantity,- 'item': str(line)- } for quantity, line in quantities_per_order_line]-@classmethoddef email_sent_event(cls, *,@@ -74,13 +84,13 @@ class OrderEvent(models.Model):raise NotImplementedError@classmethod- def draft_created_event(+ def draft_order_created_event(cls, *, order: Order, source: UserType) -> models.Model:return cls(order=order, type=OrderEvents.DRAFT_CREATED.value, user=source)@classmethod- def draft_added_products_event(+ def draft_order_added_products_event(cls, *,order: Order, source: UserType,order_lines: List[Tuple[int, ProductVariant]]) -> models.Model:@@ -89,11 +99,10 @@ class OrderEvent(models.Model):order=order, type=OrderEvents.DRAFT_ADDED_PRODUCTS.value,user=source,parameters={- 'lines': cls._lines_per_quantity_to_str_line_list(order_lines)- })+ 'lines': _lines_per_quantity_to_str_line_list(order_lines)})@classmethod- def draft_removed_products_event(+ def draft_order_removed_products_event(cls, *,order: Order, source: UserType,order_lines: List[Tuple[int, ProductVariant]]@@ -103,11 +112,10 @@ class OrderEvent(models.Model):order=order, type=OrderEvents.DRAFT_REMOVED_PRODUCTS.value,user=source,parameters={- 'lines': cls._lines_per_quantity_to_str_line_list(- order_lines)})+ 'lines': _lines_per_quantity_to_str_line_list(order_lines)})@classmethod- def placed_event(+ def order_created_event(cls, order: Order, source: UserType,from_draft=False) -> models.Model:event_type = (@@ -121,7 +129,7 @@ class OrderEvent(models.Model):order=order, type=event_type.value, user=source)@classmethod- def draft_oversold_items_event(+ def draft_order_oversold_items_event(cls, *,order: Order, source: UserType,oversold_items: List[str]) -> models.Model:@@ -132,7 +140,7 @@ class OrderEvent(models.Model):'oversold_items': oversold_items})@classmethod- def cancelled_event(+ def order_canceled_event(cls, *,order: Order, source: UserType) -> models.Model:return cls(@@ -140,7 +148,7 @@ class OrderEvent(models.Model):user=source)@classmethod- def manually_marked_as_paid_event(+ def order_manually_marked_as_paid_event(cls, *,order: Order, source: UserType) -> models.Model:return cls(@@ -148,18 +156,9 @@ class OrderEvent(models.Model):user=source)@classmethod- def fully_paid_event_event(cls, *, order: Order) -> models.Model:+ def order_fully_paid_event(cls, *, order: Order) -> models.Model:return cls(order=order, type=OrderEvents.ORDER_FULLY_PAID.value)- @staticmethod- def _get_payment_data(- amount: Optional[Decimal], payment: Payment) -> Dict:- return {- 'parameters': {- 'amount': amount,- 'payment_id': payment.token,- 'payment_gateway': payment.gateway}}-@classmethoddef payment_captured_event(cls, *,@@ -167,7 +166,7 @@ class OrderEvent(models.Model):amount: Decimal, payment: Payment) -> models.Model:return cls(order=order, type=OrderEvents.PAYMENT_CAPTURED.value,- user=source, **cls._get_payment_data(amount, payment))+ user=source, **_get_payment_data(amount, payment))@classmethoddef payment_refunded_event(@@ -176,7 +175,7 @@ class OrderEvent(models.Model):amount: Decimal, payment: Payment) -> models.Model:return cls(order=order, type=OrderEvents.PAYMENT_REFUNDED.value,- user=source, **cls._get_payment_data(amount, payment))+ user=source, **_get_payment_data(amount, payment))@classmethoddef payment_voided_event(@@ -184,7 +183,7 @@ class OrderEvent(models.Model):order: Order, source: UserType, payment: Payment) -> models.Model:return cls(order=order, type=OrderEvents.PAYMENT_VOIDED.value,- user=source, **cls._get_payment_data(None, payment))+ user=source, **_get_payment_data(None, payment))@classmethoddef payment_failed_event(@@ -234,7 +233,7 @@ class OrderEvent(models.Model):order=order, type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS.value,user=source,parameters={- 'lines': cls._lines_per_quantity_to_str_line_list(+ 'lines': _lines_per_quantity_to_str_line_list(zip(quantities, order_lines))})@classmethod@@ -251,7 +250,7 @@ class OrderEvent(models.Model):'fulfillment': fulfillment.composed_id})@classmethod- def note_added_event(+ def order_note_added_event(cls, *,order: Order, source: UserType, message: str) -> models.Model:return cls(@@ -261,7 +260,7 @@ class OrderEvent(models.Model):'message': message})@classmethod- def updated_address_event(+ def order_updated_address_event(cls, *,order: Order, source: UserType, address: Address) -> models.Model:return cls(diff --git a/saleor/graphql/order/bulk_mutations/orders.py b/saleor/graphql/order/bulk_mutations/orders.pyindex 98ec4cfa54..cf9a5b29cf 100644--- a/saleor/graphql/order/bulk_mutations/orders.py+++ b/saleor/graphql/order/bulk_mutations/orders.py@@ -40,5 +40,5 @@ class OrderBulkCancel(BaseBulkMutation):events.append(OrderEvent.fulfillment_restocked_items_event(order=order, source=user, fulfillment=order))- events.append(OrderEvent.cancelled_event(order=order, source=user))+ events.append(OrderEvent.order_canceled_event(order=order, source=user))OrderEvent.objects.bulk_create(events)diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex e646a6ae7b..f8eecab261 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -124,7 +124,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):track_inventory=False)# Add event- events.append(OrderEvent.draft_added_products_event(+ events.append(OrderEvent.draft_order_added_products_event(order=instance, source=info.context.user, order_lines=lines))@classmethod@@ -134,7 +134,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):# Create draft created event if the instance is from scratchif not created:- events.append(OrderEvent.draft_created_event(+ events.append(OrderEvent.draft_order_created_event(order=instance, source=info.context.user))instance.save(update_fields=['billing_address', 'shipping_address'])@@ -231,11 +231,11 @@ class DraftOrderComplete(BaseMutation):oversold_items.append(str(line))events = [- OrderEvent.placed_event(+ OrderEvent.order_created_event(order=order, source=info.context.user, from_draft=True)]if oversold_items:- events.append(OrderEvent.draft_oversold_items_event(+ events.append(OrderEvent.draft_order_oversold_items_event(order=order,source=info.context.user,oversold_items=oversold_items))@@ -289,7 +289,7 @@ class DraftOrderLinesCreate(BaseMutation):for quantity, variant in lines_to_add]# Create the event- OrderEvent.draft_added_products_event(+ OrderEvent.draft_order_added_products_event(order=order, source=info.context.user, order_lines=lines_to_add)recalculate_order(order)@@ -321,7 +321,7 @@ class DraftOrderLineDelete(BaseMutation):line.id = db_id# Create the removal event- OrderEvent.draft_removed_products_event(+ OrderEvent.draft_order_removed_products_event(order=order, source=info.context.user,order_lines=[(line.quantity, line)]).save()diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 9663a9e79f..353fd835b8 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -194,7 +194,7 @@ class OrderAddNote(BaseMutation):def perform_mutation(cls, _root, info, **data):order = cls.get_node_or_error(info, data.get('id'), only_type=Order)- event = event_models.OrderEvent.note_added_event(+ event = event_models.OrderEvent.order_note_added_event(order=order, source=info.context.user,message=data.get('input')['message'])event.save()diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 2d5a496a56..bff5b909a3 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -173,7 +173,7 @@ def cancel_order(user, order, restock):"""events = [- OrderEvent.cancelled_event(order=order, source=user)]+ OrderEvent.order_canceled_event(order=order, source=user)]if restock:events.append(OrderEvent.fulfillment_restocked_items_event(order=order, source=user,@@ -300,11 +300,11 @@ def change_order_line_quantity(user, line, old_quantity, new_quantity):# Create the removal eventif quantity_diff > 0:- OrderEvent.draft_removed_products_event(+ OrderEvent.draft_order_removed_products_event(order=line.order, source=user,order_lines=[(quantity_diff, line)]).save()elif quantity_diff < 0:- OrderEvent.draft_added_products_event(+ OrderEvent.draft_order_added_products_event(order=line.order, source=user,order_lines=[(quantity_diff * -1, line)]).save()diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 7b70ff7e01..ff36331338 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -76,7 +76,7 @@ def create_payment_information(def handle_fully_paid_order(order):- events = [OrderEvent.fully_paid_event_event(order=order)]+ events = [OrderEvent.order_fully_paid_event(order=order)]if order.get_user_current_email():events.append(OrderEvent.email_sent_event(@@ -177,7 +177,7 @@ def mark_order_as_paid(order: Order, request_user: User):payment.charge_status = ChargeStatus.FULLY_CHARGEDpayment.captured_amount = order.total.gross.amountpayment.save(update_fields=['captured_amount', 'charge_status'])- OrderEvent.manually_marked_as_paid_event(+ OrderEvent.order_manually_marked_as_paid_event(order=order, source=request_user).save()