Files
Brunobrno c0bd24ee5e Refactor commerce models and enhance payment logic
Refactored commerce models to remove language prefixes from status choices, improved order and payment validation, and enforced business rules for payment and shipping combinations. Updated order item and cart calculations to use VAT-inclusive prices, added unique constraints and indexes to reviews, and improved stock management logic. Added new Stripe client methods for session and refund management, and updated Zasilkovna and Deutsche Post models for consistency. Minor fixes and improvements across related tasks, URLs, and configuration models.
2026-01-20 23:45:21 +01:00

69 lines
2.5 KiB
Python

from django.db import models
from django.apps import apps
from django.utils import timezone
# Create your models here.
from .client import StripeClient
class StripeModel(models.Model):
class STATUS_CHOICES(models.TextChoices):
PENDING = "pending", "cz#Čeká se na platbu"
PAID = "paid", "cz#Zaplaceno"
FAILED = "failed", "cz#Neúspěšné"
CANCELLED = "cancelled", "cz#Zrušeno"
REFUNDING = "refunding", "cz#Platba se vrací"
REFUNDED = "refunded", "cz#Platba úspěšně vrácena"
status = models.CharField(max_length=20, choices=STATUS_CHOICES.choices, default=STATUS_CHOICES.PENDING)
stripe_session_id = models.CharField(max_length=255, blank=True, null=True)
stripe_payment_intent = models.CharField(max_length=255, blank=True, null=True)
stripe_session_url = models.URLField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
def __str__(self):
return f"Order {self.id} - {self.status}"
def save(self, *args, **kwargs):
# If new (no primary key yet)
if self.pk is None:
super().save(*args, **kwargs) # Save first to get pk
Order = apps.get_model('commerce', 'Order')
Payment = apps.get_model('commerce', 'Payment')
order = Order.objects.get(payment=Payment.objects.get(stripe=self))
session = StripeClient.create_checkout_session(order)
self.stripe_session_id = session.id
self.stripe_payment_intent = session.payment_intent
self.stripe_session_url = session.url
# Save again with Stripe data
super().save(update_fields=['stripe_session_id', 'stripe_payment_intent', 'stripe_session_url', 'updated_at'])
else:
self.updated_at = timezone.now()
super().save(*args, **kwargs)
def paid(self):
self.status = self.STATUS_CHOICES.PAID
self.save()
def refund(self):
StripeClient.refund_order(self.stripe_payment_intent)
self.status = self.STATUS_CHOICES.REFUNDING
self.save()
def refund_confirmed(self):
self.status = self.STATUS_CHOICES.REFUNDED
self.save()
def cancel(self):
StripeClient.cancel_checkout_session(self.stripe_session_id)
self.status = self.STATUS_CHOICES.CANCELLED
self.save()