feat: ruff'ed
This commit is contained in:
+22
-89
@@ -24,123 +24,71 @@ from shop.models import (
|
||||
# Register your models here.
|
||||
@admin.register(Product)
|
||||
class ProductAdmin(ModelAdmin):
|
||||
search_fields = ("name",)
|
||||
list_display = (
|
||||
"id",
|
||||
"name",
|
||||
"stock",
|
||||
)
|
||||
search_fields = ('name',)
|
||||
list_display = ('id', 'name', 'stock')
|
||||
|
||||
|
||||
@admin.register(ProductPrice)
|
||||
class ProductPriceAdmin(ModelAdmin):
|
||||
search_fields = ("product",)
|
||||
autocomplete_fields = ("product",)
|
||||
list_display = (
|
||||
"id",
|
||||
"product",
|
||||
"price",
|
||||
"date",
|
||||
"tax",
|
||||
)
|
||||
search_fields = ('product',)
|
||||
autocomplete_fields = ('product',)
|
||||
list_display = ('id', 'product', 'price', 'date', 'tax')
|
||||
|
||||
|
||||
@admin.register(Tax)
|
||||
class TaxAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"code",
|
||||
"value",
|
||||
)
|
||||
list_display = ('code', 'value')
|
||||
|
||||
|
||||
@admin.register(OrderLine)
|
||||
class OrderLineAdmin(ModelAdmin):
|
||||
autocomplete_fields = ("product",)
|
||||
list_display = (
|
||||
"id",
|
||||
"product",
|
||||
"price",
|
||||
"quantity",
|
||||
)
|
||||
autocomplete_fields = ('product',)
|
||||
list_display = ('id', 'product', 'price', 'quantity')
|
||||
|
||||
|
||||
@admin.register(Order)
|
||||
class OrderAdmin(ModelAdmin):
|
||||
list_display = ("id",)
|
||||
list_display = ('id',)
|
||||
|
||||
|
||||
@admin.register(Provider)
|
||||
class ProviderAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"vat_id",
|
||||
"name",
|
||||
)
|
||||
list_display = ('vat_id', 'name')
|
||||
|
||||
|
||||
@admin.register(Tag)
|
||||
class TagAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"name",
|
||||
)
|
||||
list_display = ('id', 'name')
|
||||
|
||||
|
||||
@admin.register(Brand)
|
||||
class BrandAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"name",
|
||||
)
|
||||
list_display = ('id', 'name')
|
||||
|
||||
|
||||
@admin.register(ProductBatch)
|
||||
class ProductBatchAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"product",
|
||||
"quantity",
|
||||
"provider",
|
||||
)
|
||||
list_display = ('id', 'product', 'quantity', 'provider')
|
||||
|
||||
|
||||
@admin.register(Cart)
|
||||
class ProductBatchAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"uuid",
|
||||
"user",
|
||||
"creation_date",
|
||||
)
|
||||
class CartAdmin(ModelAdmin):
|
||||
list_display = ('uuid', 'user', 'creation_date')
|
||||
|
||||
|
||||
@admin.register(CartItem)
|
||||
class ProductBatchAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"cart",
|
||||
"product",
|
||||
"quantity",
|
||||
)
|
||||
class CartItemAdmin(ModelAdmin):
|
||||
list_display = ('id', 'cart', 'product', 'quantity')
|
||||
|
||||
|
||||
@admin.register(ShippingMethod)
|
||||
class ShippingMethodAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"name",
|
||||
"description",
|
||||
)
|
||||
list_display = ('id', 'name', 'description')
|
||||
|
||||
|
||||
@admin.register(CustomerAddress)
|
||||
class CustomerAddressAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"user",
|
||||
"vat_id",
|
||||
"address",
|
||||
"address_state",
|
||||
"address_zip",
|
||||
)
|
||||
list_display = ('id', 'user', 'vat_id', 'address', 'address_state', 'address_zip')
|
||||
|
||||
def get_queryset(self, request):
|
||||
qs = super().get_queryset(request)
|
||||
@@ -149,29 +97,14 @@ class CustomerAddressAdmin(ModelAdmin):
|
||||
|
||||
@admin.register(ProductCategory)
|
||||
class ProductCategoryAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"name",
|
||||
"parent",
|
||||
"promoted",
|
||||
"hidden",
|
||||
"show_in_navbar",
|
||||
)
|
||||
list_display = ('id', 'name', 'parent', 'promoted', 'hidden', 'show_in_navbar')
|
||||
|
||||
|
||||
@admin.register(ShopSettings)
|
||||
class ShopSettingsAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"merchant_code",
|
||||
"currency_code",
|
||||
"terminal",
|
||||
)
|
||||
list_display = ('id', 'merchant_code', 'currency_code', 'terminal')
|
||||
|
||||
|
||||
@admin.register(ProductImage)
|
||||
class ProductImageAdmin(ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"original",
|
||||
)
|
||||
list_display = ('id', 'original')
|
||||
|
||||
+4
-2
@@ -1,6 +1,8 @@
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
class ShopConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "shop"
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'shop'
|
||||
verbose_name = _('Tienda')
|
||||
|
||||
+15
-30
@@ -6,44 +6,29 @@ from shop.models import Product, ProductPrice
|
||||
|
||||
|
||||
class ProductFilter(django_filters.FilterSet):
|
||||
name = django_filters.CharFilter(
|
||||
field_name="name", lookup_expr="icontains", label=_("Nombre")
|
||||
)
|
||||
tags = django_filters.BaseInFilter(field_name="tags", label=_("Etiquetas"))
|
||||
category = django_filters.BaseInFilter(
|
||||
field_name="categories", label=_("Categorías")
|
||||
)
|
||||
price_lt = django_filters.NumberFilter(method="filter_price_lt")
|
||||
price_gt = django_filters.NumberFilter(method="filter_price_gt")
|
||||
o = OrderingFilter(
|
||||
fields=(
|
||||
("name", "name"),
|
||||
("id", "id"),
|
||||
)
|
||||
)
|
||||
name = django_filters.CharFilter(field_name='name', lookup_expr='icontains', label=_('Nombre'))
|
||||
tags = django_filters.BaseInFilter(field_name='tags', label=_('Etiquetas'))
|
||||
category = django_filters.BaseInFilter(field_name='categories', label=_('Categorías'))
|
||||
price_lt = django_filters.NumberFilter(method='filter_price_lt')
|
||||
price_gt = django_filters.NumberFilter(method='filter_price_gt')
|
||||
o = OrderingFilter(fields=(('name', 'name'), ('id', 'id')))
|
||||
|
||||
def filter_price_lt(self, queryset, name, value):
|
||||
ids = queryset.values("id")
|
||||
product_ids = ProductPrice.objects.filter(
|
||||
product_id__in=ids, current=True, price_with_tax__lte=value
|
||||
).values("product_id")
|
||||
ids = queryset.values('id')
|
||||
product_ids = ProductPrice.objects.filter(product_id__in=ids, current=True, price_with_tax__lte=value).values(
|
||||
'product_id'
|
||||
)
|
||||
|
||||
return queryset.filter(pk__in=product_ids)
|
||||
|
||||
def filter_price_gt(self, queryset, name, value):
|
||||
ids = queryset.values("id")
|
||||
product_ids = ProductPrice.objects.filter(
|
||||
product_id__in=ids, current=True, price_with_tax__gte=value
|
||||
).values("product_id")
|
||||
ids = queryset.values('id')
|
||||
product_ids = ProductPrice.objects.filter(product_id__in=ids, current=True, price_with_tax__gte=value).values(
|
||||
'product_id'
|
||||
)
|
||||
|
||||
return queryset.filter(pk__in=product_ids)
|
||||
|
||||
class Meta:
|
||||
model = Product
|
||||
fields = (
|
||||
"name",
|
||||
"stock",
|
||||
"is_digital_asset",
|
||||
"tags",
|
||||
"category",
|
||||
)
|
||||
fields = ('name', 'stock', 'is_digital_asset', 'tags', 'category')
|
||||
|
||||
+488
-1119
File diff suppressed because it is too large
Load Diff
@@ -4,15 +4,12 @@ from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("shop", "0001_initial"),
|
||||
]
|
||||
dependencies = [('shop', '0001_initial')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="shopsettings",
|
||||
name="debug",
|
||||
field=models.BooleanField(default=True, verbose_name="Modo depuración"),
|
||||
),
|
||||
model_name='shopsettings',
|
||||
name='debug',
|
||||
field=models.BooleanField(default=True, verbose_name='Modo depuración'),
|
||||
)
|
||||
]
|
||||
|
||||
+205
-466
@@ -19,12 +19,8 @@ User = get_user_model()
|
||||
|
||||
|
||||
class TimestampedModel(models.Model):
|
||||
creation_date = models.DateTimeField(
|
||||
auto_now_add=True, verbose_name=_("fecha de creación")
|
||||
)
|
||||
last_modification_date = models.DateTimeField(
|
||||
auto_now=True, verbose_name=_("fecha de última modificación")
|
||||
)
|
||||
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('fecha de creación'))
|
||||
last_modification_date = models.DateTimeField(auto_now=True, verbose_name=_('fecha de última modificación'))
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
@@ -37,33 +33,20 @@ class Tag(models.Model):
|
||||
return self.name
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("etiqueta")
|
||||
verbose_name_plural = _("etiquetas")
|
||||
ordering = ("name",)
|
||||
verbose_name = _('etiqueta')
|
||||
verbose_name_plural = _('etiquetas')
|
||||
ordering = ('name',)
|
||||
|
||||
|
||||
class ProductCategory(models.Model):
|
||||
name = models.CharField(max_length=32)
|
||||
parent = models.ForeignKey(
|
||||
"shop.ProductCategory",
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
blank=True,
|
||||
verbose_name=_("categoría padre"),
|
||||
)
|
||||
promoted = models.BooleanField(default=False, verbose_name=_("promocionada"))
|
||||
hidden = models.BooleanField(default=False, verbose_name=_("oculta"))
|
||||
show_in_navbar = models.BooleanField(
|
||||
default=False, verbose_name=_("mostrar en cabecera")
|
||||
)
|
||||
slug = models.SlugField(
|
||||
max_length=48,
|
||||
blank=True,
|
||||
default="",
|
||||
verbose_name=_("slug"),
|
||||
unique=True,
|
||||
db_index=True,
|
||||
'shop.ProductCategory', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('categoría padre')
|
||||
)
|
||||
promoted = models.BooleanField(default=False, verbose_name=_('promocionada'))
|
||||
hidden = models.BooleanField(default=False, verbose_name=_('oculta'))
|
||||
show_in_navbar = models.BooleanField(default=False, verbose_name=_('mostrar en cabecera'))
|
||||
slug = models.SlugField(max_length=48, blank=True, default='', verbose_name=_('slug'), unique=True, db_index=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
@@ -73,58 +56,24 @@ class ProductCategory(models.Model):
|
||||
super().save()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("categoría")
|
||||
verbose_name_plural = _("categorías")
|
||||
ordering = ("name",)
|
||||
verbose_name = _('categoría')
|
||||
verbose_name_plural = _('categorías')
|
||||
ordering = ('name',)
|
||||
|
||||
|
||||
class Product(TimestampedModel):
|
||||
sku = models.CharField(
|
||||
max_length=64,
|
||||
blank=False,
|
||||
null=False,
|
||||
unique=True,
|
||||
verbose_name=_("código de referencia"),
|
||||
)
|
||||
name = models.CharField(
|
||||
max_length=96,
|
||||
blank=False,
|
||||
null=False,
|
||||
verbose_name=_("nombre"),
|
||||
)
|
||||
description = models.TextField(
|
||||
blank=True,
|
||||
default="",
|
||||
verbose_name=_("descripción"),
|
||||
)
|
||||
stock = models.DecimalField(
|
||||
max_digits=13,
|
||||
decimal_places=4,
|
||||
default=Decimal("0"),
|
||||
verbose_name=_("stock"),
|
||||
)
|
||||
is_digital_asset = models.BooleanField(
|
||||
default=False, verbose_name=_("es un activo digital")
|
||||
)
|
||||
url = models.URLField(blank=True, verbose_name=_("URL de descarga"))
|
||||
tags = models.ManyToManyField("shop.Tag", blank=True, verbose_name=_("etiquetas"))
|
||||
categories = models.ManyToManyField(
|
||||
"shop.ProductCategory", blank=True, verbose_name=_("categorías")
|
||||
)
|
||||
brand = models.ForeignKey(
|
||||
"shop.Brand",
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=models.SET_NULL,
|
||||
verbose_name=_("marca"),
|
||||
)
|
||||
slug = models.SlugField(
|
||||
default="", blank=True, null=True, max_length=128, verbose_name=_("Slug")
|
||||
)
|
||||
hidden = models.BooleanField(default=False, db_index=True, verbose_name=_("oculto"))
|
||||
is_shipping_method = models.BooleanField(
|
||||
default=False, verbose_name=_("es forma de envío")
|
||||
)
|
||||
sku = models.CharField(max_length=64, blank=False, null=False, unique=True, verbose_name=_('código de referencia'))
|
||||
name = models.CharField(max_length=96, blank=False, null=False, verbose_name=_('nombre'))
|
||||
description = models.TextField(blank=True, default='', verbose_name=_('descripción'))
|
||||
stock = models.DecimalField(max_digits=13, decimal_places=4, default=Decimal('0'), verbose_name=_('stock'))
|
||||
is_digital_asset = models.BooleanField(default=False, verbose_name=_('es un activo digital'))
|
||||
url = models.URLField(blank=True, verbose_name=_('URL de descarga'))
|
||||
tags = models.ManyToManyField('shop.Tag', blank=True, verbose_name=_('etiquetas'))
|
||||
categories = models.ManyToManyField('shop.ProductCategory', blank=True, verbose_name=_('categorías'))
|
||||
brand = models.ForeignKey('shop.Brand', blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('marca'))
|
||||
slug = models.SlugField(default='', blank=True, null=True, max_length=128, verbose_name=_('Slug'))
|
||||
hidden = models.BooleanField(default=False, db_index=True, verbose_name=_('oculto'))
|
||||
is_shipping_method = models.BooleanField(default=False, verbose_name=_('es forma de envío'))
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
@@ -139,38 +88,25 @@ class Product(TimestampedModel):
|
||||
return self.prices.filter(current=True).first()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("producto")
|
||||
verbose_name_plural = _("productos")
|
||||
ordering = ("id",)
|
||||
verbose_name = _('producto')
|
||||
verbose_name_plural = _('productos')
|
||||
ordering = ('id',)
|
||||
|
||||
|
||||
class ProductPrice(TimestampedModel):
|
||||
price = models.DecimalField(
|
||||
max_digits=11, decimal_places=2, verbose_name=_("precio")
|
||||
)
|
||||
date = models.DateTimeField(default=timezone.now, verbose_name=_("fecha"))
|
||||
price = models.DecimalField(max_digits=11, decimal_places=2, verbose_name=_('precio'))
|
||||
date = models.DateTimeField(default=timezone.now, verbose_name=_('fecha'))
|
||||
product = models.ForeignKey(
|
||||
"shop.Product",
|
||||
on_delete=models.CASCADE,
|
||||
verbose_name=_("producto"),
|
||||
related_name="prices",
|
||||
)
|
||||
tax = models.ForeignKey(
|
||||
"shop.Tax",
|
||||
on_delete=models.PROTECT,
|
||||
verbose_name=_("impuesto aplicable"),
|
||||
'shop.Product', on_delete=models.CASCADE, verbose_name=_('producto'), related_name='prices'
|
||||
)
|
||||
tax = models.ForeignKey('shop.Tax', on_delete=models.PROTECT, verbose_name=_('impuesto aplicable'))
|
||||
price_with_tax = models.DecimalField(
|
||||
max_digits=11,
|
||||
decimal_places=2,
|
||||
blank=True,
|
||||
null=True,
|
||||
verbose_name=_("precio con impuestos"),
|
||||
max_digits=11, decimal_places=2, blank=True, null=True, verbose_name=_('precio con impuestos')
|
||||
)
|
||||
current = models.BooleanField(default=False, verbose_name=_("es el precio actual"))
|
||||
current = models.BooleanField(default=False, verbose_name=_('es el precio actual'))
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.price} - {self.tax.code}"
|
||||
return f'{self.price} - {self.tax.code}'
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
tax_value = self.price * Decimal(self.tax.value / 100)
|
||||
@@ -178,63 +114,41 @@ class ProductPrice(TimestampedModel):
|
||||
super().save()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("precio de producto")
|
||||
verbose_name_plural = _("precio de producto")
|
||||
ordering = ("-date",)
|
||||
verbose_name = _('precio de producto')
|
||||
verbose_name_plural = _('precio de producto')
|
||||
ordering = ('-date',)
|
||||
|
||||
|
||||
class ProductImage(models.Model):
|
||||
product = models.ForeignKey(
|
||||
"shop.Product",
|
||||
'shop.Product',
|
||||
on_delete=models.CASCADE,
|
||||
blank=False,
|
||||
null=False,
|
||||
verbose_name=_("Producto"),
|
||||
related_name="images",
|
||||
)
|
||||
original = models.ImageField(
|
||||
upload_to="uploads", blank=False, null=False, verbose_name=_("Imagen original")
|
||||
verbose_name=_('Producto'),
|
||||
related_name='images',
|
||||
)
|
||||
original = models.ImageField(upload_to='uploads', blank=False, null=False, verbose_name=_('Imagen original'))
|
||||
|
||||
xl = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("XL")
|
||||
)
|
||||
xl_dark = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("XL (fondo oscuro)")
|
||||
)
|
||||
xl = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('XL'))
|
||||
xl_dark = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('XL (fondo oscuro)'))
|
||||
|
||||
l = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("L")
|
||||
)
|
||||
l_dark = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("L (fondo oscuro)")
|
||||
)
|
||||
l = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('L'))
|
||||
l_dark = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('L (fondo oscuro)'))
|
||||
|
||||
m = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("M")
|
||||
)
|
||||
m_dark = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("M (fondo oscuro)")
|
||||
)
|
||||
m = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('M'))
|
||||
m_dark = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('M (fondo oscuro)'))
|
||||
|
||||
s = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("S")
|
||||
)
|
||||
s_dark = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("S (fondo oscuro)")
|
||||
)
|
||||
s = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('S'))
|
||||
s_dark = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('S (fondo oscuro)'))
|
||||
|
||||
xs = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("XS")
|
||||
)
|
||||
xs_dark = models.ImageField(
|
||||
upload_to="uploads", blank=True, null=True, verbose_name=_("XS (fondo oscuro)")
|
||||
)
|
||||
xs = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('XS'))
|
||||
xs_dark = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name=_('XS (fondo oscuro)'))
|
||||
|
||||
def __str__(self):
|
||||
return self.original.url
|
||||
|
||||
def make_square(self, image, max_size=512, fill_color="#000000"):
|
||||
def make_square(self, image, max_size=512, fill_color='#000000'):
|
||||
width, height = image.size
|
||||
|
||||
if width > height:
|
||||
@@ -247,7 +161,7 @@ class ProductImage(models.Model):
|
||||
|
||||
resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
||||
|
||||
new_image = Image.new("RGB", (max_size, max_size), fill_color)
|
||||
new_image = Image.new('RGB', (max_size, max_size), fill_color)
|
||||
|
||||
position_x = int((max_size - new_width) / 2)
|
||||
position_y = int((max_size - new_height) / 2)
|
||||
@@ -256,503 +170,328 @@ class ProductImage(models.Model):
|
||||
|
||||
return new_image
|
||||
|
||||
def get_resized_image(self, image, size, fill_color="#000000"):
|
||||
def get_resized_image(self, image, size, fill_color='#000000'):
|
||||
image = Image.open(image)
|
||||
image = self.make_square(image, size, fill_color)
|
||||
buffer = BytesIO()
|
||||
image.save(fp=buffer, format="WEBP")
|
||||
image.save(fp=buffer, format='WEBP')
|
||||
|
||||
return ContentFile(buffer.getvalue(), name=f"{self.product.slug}_{size}.webp")
|
||||
return ContentFile(buffer.getvalue(), name=f'{self.product.slug}_{size}.webp')
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
self.xl = self.get_resized_image(self.original, 1024, fill_color="#FFFFFF")
|
||||
self.xl = self.get_resized_image(self.original, 1024, fill_color='#FFFFFF')
|
||||
self.xl_dark = self.get_resized_image(self.original, 1024)
|
||||
|
||||
self.l = self.get_resized_image(self.original, 512, fill_color="#FFFFFF")
|
||||
self.l = self.get_resized_image(self.original, 512, fill_color='#FFFFFF')
|
||||
self.l_dark = self.get_resized_image(self.original, 512)
|
||||
|
||||
self.m = self.get_resized_image(self.original, 256, fill_color="#FFFFFF")
|
||||
self.m = self.get_resized_image(self.original, 256, fill_color='#FFFFFF')
|
||||
self.m_dark = self.get_resized_image(self.original, 256)
|
||||
|
||||
self.s = self.get_resized_image(self.original, 128, fill_color="#FFFFFF")
|
||||
self.s = self.get_resized_image(self.original, 128, fill_color='#FFFFFF')
|
||||
self.s_dark = self.get_resized_image(self.original, 128)
|
||||
|
||||
self.xs = self.get_resized_image(self.original, 96, fill_color="#FFFFFF")
|
||||
self.xs = self.get_resized_image(self.original, 96, fill_color='#FFFFFF')
|
||||
self.xs_dark = self.get_resized_image(self.original, 96)
|
||||
|
||||
return super().save(*args, **kwargs)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('imágenes de producto')
|
||||
verbose_name_plural = _('imágenes de producto')
|
||||
|
||||
|
||||
class ProductBatch(TimestampedModel):
|
||||
code = models.CharField(
|
||||
max_length=32, unique=True, db_index=True, verbose_name=_("código")
|
||||
)
|
||||
product = models.ForeignKey(
|
||||
"shop.Product", on_delete=models.PROTECT, verbose_name=_("producto")
|
||||
)
|
||||
quantity = models.DecimalField(
|
||||
max_digits=13,
|
||||
decimal_places=4,
|
||||
default=Decimal("1"),
|
||||
verbose_name=_("cantidad"),
|
||||
)
|
||||
code = models.CharField(max_length=32, unique=True, db_index=True, verbose_name=_('código'))
|
||||
product = models.ForeignKey('shop.Product', on_delete=models.PROTECT, verbose_name=_('producto'))
|
||||
quantity = models.DecimalField(max_digits=13, decimal_places=4, default=Decimal('1'), verbose_name=_('cantidad'))
|
||||
expiration_date = models.DateField(
|
||||
blank=True, null=True, verbose_name=_("fecha de caducidad / consumo preferente")
|
||||
blank=True, null=True, verbose_name=_('fecha de caducidad / consumo preferente')
|
||||
)
|
||||
provider = models.ForeignKey(
|
||||
"shop.Provider",
|
||||
on_delete=models.SET_NULL,
|
||||
blank=True,
|
||||
null=True,
|
||||
verbose_name=_("proveedor"),
|
||||
'shop.Provider', on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('proveedor')
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.code} - {self.product.name} - {self.quantity}"
|
||||
return f'{self.code} - {self.product.name} - {self.quantity}'
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("remesa de producto")
|
||||
verbose_name_plural = _("remesas de productos")
|
||||
verbose_name = _('remesa de producto')
|
||||
verbose_name_plural = _('remesas de productos')
|
||||
|
||||
|
||||
class Tax(TimestampedModel):
|
||||
code = models.CharField(
|
||||
max_length=8, blank=False, unique=True, verbose_name=_("código de impuesto")
|
||||
)
|
||||
value = models.PositiveIntegerField(
|
||||
null=False, blank=False, verbose_name=_("valor entero (porcentaje)")
|
||||
)
|
||||
code = models.CharField(max_length=8, blank=False, unique=True, verbose_name=_('código de impuesto'))
|
||||
value = models.PositiveIntegerField(null=False, blank=False, verbose_name=_('valor entero (porcentaje)'))
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.code} - {self.value}%"
|
||||
return f'{self.code} - {self.value}%'
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("impuesto")
|
||||
verbose_name_plural = _("impuestos")
|
||||
ordering = ("id",)
|
||||
verbose_name = _('impuesto')
|
||||
verbose_name_plural = _('impuestos')
|
||||
ordering = ('id',)
|
||||
|
||||
|
||||
class Provider(TimestampedModel):
|
||||
vat_id = models.CharField(
|
||||
max_length=32,
|
||||
blank=False,
|
||||
unique=True,
|
||||
verbose_name=_("documento de identidad"),
|
||||
)
|
||||
name = models.CharField(max_length=64, blank=False, verbose_name=_("nombre"))
|
||||
vat_id = models.CharField(max_length=32, blank=False, unique=True, verbose_name=_('documento de identidad'))
|
||||
name = models.CharField(max_length=64, blank=False, verbose_name=_('nombre'))
|
||||
|
||||
email = models.EmailField(blank=False, verbose_name=_("e-mail de contacto"))
|
||||
phone = models.CharField(
|
||||
max_length=16,
|
||||
blank=True,
|
||||
null=True,
|
||||
default="",
|
||||
verbose_name=_("Teléfono de contacto"),
|
||||
)
|
||||
email = models.EmailField(blank=False, verbose_name=_('e-mail de contacto'))
|
||||
phone = models.CharField(max_length=16, blank=True, null=True, default='', verbose_name=_('Teléfono de contacto'))
|
||||
|
||||
address = models.CharField(max_length=255, blank=False, verbose_name=_("dirección"))
|
||||
city = models.CharField(max_length=64, blank=False, verbose_name=_("ciudad"))
|
||||
state = models.CharField(max_length=64, blank=False, verbose_name=_("región"))
|
||||
country = models.CharField(max_length=64, blank=False, verbose_name=_("país"))
|
||||
zip = models.CharField(max_length=32, blank=False, verbose_name=_("código postal"))
|
||||
address = models.CharField(max_length=255, blank=False, verbose_name=_('dirección'))
|
||||
city = models.CharField(max_length=64, blank=False, verbose_name=_('ciudad'))
|
||||
state = models.CharField(max_length=64, blank=False, verbose_name=_('región'))
|
||||
country = models.CharField(max_length=64, blank=False, verbose_name=_('país'))
|
||||
zip = models.CharField(max_length=32, blank=False, verbose_name=_('código postal'))
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.vat_id} - {self.name}"
|
||||
return f'{self.vat_id} - {self.name}'
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("proveedor")
|
||||
verbose_name_plural = _("proveedores")
|
||||
verbose_name = _('proveedor')
|
||||
verbose_name_plural = _('proveedores')
|
||||
|
||||
|
||||
class Brand(TimestampedModel):
|
||||
name = models.CharField(
|
||||
max_length=100, unique=True, blank=False, null=False, verbose_name=_("nombre")
|
||||
)
|
||||
name = models.CharField(max_length=100, unique=True, blank=False, null=False, verbose_name=_('nombre'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("marca")
|
||||
verbose_name_plural = _("marcas")
|
||||
verbose_name = _('marca')
|
||||
verbose_name_plural = _('marcas')
|
||||
|
||||
|
||||
class OrderLine(TimestampedModel):
|
||||
order = models.ForeignKey(
|
||||
"shop.Order",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="lines",
|
||||
verbose_name=_("pedido"),
|
||||
)
|
||||
order = models.ForeignKey('shop.Order', on_delete=models.CASCADE, related_name='lines', verbose_name=_('pedido'))
|
||||
product = models.ForeignKey(
|
||||
"shop.Product",
|
||||
on_delete=models.CASCADE,
|
||||
null=False,
|
||||
blank=False,
|
||||
verbose_name=_("producto"),
|
||||
'shop.Product', on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('producto')
|
||||
)
|
||||
quantity = models.DecimalField(
|
||||
max_digits=13,
|
||||
decimal_places=4,
|
||||
default=Decimal("1"),
|
||||
null=False,
|
||||
blank=False,
|
||||
verbose_name=_("cantidad"),
|
||||
max_digits=13, decimal_places=4, default=Decimal('1'), null=False, blank=False, verbose_name=_('cantidad')
|
||||
)
|
||||
|
||||
# Precio del producto en el momento en el que se crea el pedido
|
||||
price = models.DecimalField(
|
||||
max_digits=13, decimal_places=4, verbose_name=_("precio")
|
||||
)
|
||||
price = models.DecimalField(max_digits=13, decimal_places=4, verbose_name=_('precio'))
|
||||
|
||||
# base_total = quantity * price
|
||||
base_total = models.DecimalField(
|
||||
max_digits=13,
|
||||
decimal_places=4,
|
||||
default=Decimal("0"),
|
||||
default=Decimal('0'),
|
||||
null=False,
|
||||
blank=False,
|
||||
verbose_name=_("total sin impuestos"),
|
||||
verbose_name=_('total sin impuestos'),
|
||||
)
|
||||
|
||||
# Valor entero del impuesto en el momento en el que se crea el pedido
|
||||
tax_value = models.PositiveIntegerField(
|
||||
null=False, blank=False, verbose_name=_("valor de impuestos")
|
||||
)
|
||||
tax_value = models.PositiveIntegerField(null=False, blank=False, verbose_name=_('valor de impuestos'))
|
||||
|
||||
# taxes = price * quantity * (tax_value / 100)
|
||||
taxes = models.DecimalField(
|
||||
max_digits=13, decimal_places=4, verbose_name=_("impuestos")
|
||||
)
|
||||
taxes = models.DecimalField(max_digits=13, decimal_places=4, verbose_name=_('impuestos'))
|
||||
|
||||
# total = base_total + taxes
|
||||
total = models.DecimalField(
|
||||
max_digits=13, decimal_places=4, verbose_name=_("total")
|
||||
)
|
||||
total = models.DecimalField(max_digits=13, decimal_places=4, verbose_name=_('total'))
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.product.name} - {self.quantity} - {self.price}"
|
||||
return f'{self.product.name} - {self.quantity} - {self.price}'
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("línea de pedido")
|
||||
verbose_name_plural = _("líneas de pedido")
|
||||
verbose_name = _('línea de pedido')
|
||||
verbose_name_plural = _('líneas de pedido')
|
||||
|
||||
|
||||
def create_order_code(*args, **kwargs):
|
||||
return (
|
||||
timezone.now()
|
||||
.isoformat()
|
||||
.replace("-", "")
|
||||
.replace("T", "")
|
||||
.replace(":", "")
|
||||
.replace(".", "")[:-5]
|
||||
)
|
||||
return timezone.now().isoformat().replace('-', '').replace('T', '').replace(':', '').replace('.', '')[:-5]
|
||||
|
||||
|
||||
class Order(TimestampedModel):
|
||||
class Statuses(models.TextChoices):
|
||||
STATUS_PENDING = "PEN", _("pendiente de pago")
|
||||
STATUS_PAID = "PAI", _("pagado")
|
||||
STATUS_RETURNED = "RTN", _("devuelto")
|
||||
STATUS_ERROR = "ERR", _("Error")
|
||||
STATUS_PENDING = 'PEN', _('pendiente de pago')
|
||||
STATUS_PAID = 'PAI', _('pagado')
|
||||
STATUS_RETURNED = 'RTN', _('devuelto')
|
||||
STATUS_ERROR = 'ERR', _('Error')
|
||||
|
||||
class ShippingStatuses(models.TextChoices):
|
||||
STATUS_NOT_READY = "NOT", _("no preparado")
|
||||
STATUS_READY = "RDY", _("preparado")
|
||||
STATUS_TO_BE_SENT = "TBS", _("listo para ser enviado")
|
||||
STATUS_SENT = "SNT", _("enviado")
|
||||
STATUS_DELIVERED = "DLV", _("entregado")
|
||||
STATUS_FINISHED = "FIN", _("finalizado")
|
||||
STATUS_CANCELED = "CAN", _("cancelado")
|
||||
STATUS_REQUESTED_RETURN = "RQT", _("devolución solicitada")
|
||||
STATUS_RETURNED = "RTN", _("devuelto")
|
||||
STATUS_NOT_READY = 'NOT', _('no preparado')
|
||||
STATUS_READY = 'RDY', _('preparado')
|
||||
STATUS_TO_BE_SENT = 'TBS', _('listo para ser enviado')
|
||||
STATUS_SENT = 'SNT', _('enviado')
|
||||
STATUS_DELIVERED = 'DLV', _('entregado')
|
||||
STATUS_FINISHED = 'FIN', _('finalizado')
|
||||
STATUS_CANCELED = 'CAN', _('cancelado')
|
||||
STATUS_REQUESTED_RETURN = 'RQT', _('devolución solicitada')
|
||||
STATUS_RETURNED = 'RTN', _('devuelto')
|
||||
|
||||
uuid = models.UUIDField(default=uuid4, verbose_name=_("UUID"), db_index=True)
|
||||
uuid = models.UUIDField(default=uuid4, verbose_name=_('UUID'), db_index=True)
|
||||
code = models.CharField(default=create_order_code, max_length=20, unique=True)
|
||||
|
||||
status = models.CharField(
|
||||
max_length=3, default=Statuses.STATUS_PENDING, verbose_name=_("estado")
|
||||
)
|
||||
status = models.CharField(max_length=3, default=Statuses.STATUS_PENDING, verbose_name=_('estado'))
|
||||
|
||||
shipping_status = models.CharField(
|
||||
max_length=3,
|
||||
default=ShippingStatuses.STATUS_NOT_READY,
|
||||
verbose_name=_("estado de envío"),
|
||||
max_length=3, default=ShippingStatuses.STATUS_NOT_READY, verbose_name=_('estado de envío')
|
||||
)
|
||||
|
||||
base_total = models.DecimalField(
|
||||
default=Decimal("0"),
|
||||
max_digits=13,
|
||||
decimal_places=2,
|
||||
verbose_name=_("base imponible"),
|
||||
default=Decimal('0'), max_digits=13, decimal_places=2, verbose_name=_('base imponible')
|
||||
)
|
||||
|
||||
total = models.DecimalField(
|
||||
default=Decimal("0"), max_digits=13, decimal_places=2, verbose_name=_("total")
|
||||
)
|
||||
total = models.DecimalField(default=Decimal('0'), max_digits=13, decimal_places=2, verbose_name=_('total'))
|
||||
|
||||
user = models.ForeignKey(
|
||||
User, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_("cliente")
|
||||
)
|
||||
email = models.EmailField(blank=True, verbose_name=_("e-mail"))
|
||||
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_('cliente'))
|
||||
email = models.EmailField(blank=True, verbose_name=_('e-mail'))
|
||||
|
||||
# Datos de facturación
|
||||
billing_address = models.CharField(
|
||||
max_length=255, blank=False, verbose_name=_("dirección de facturación")
|
||||
)
|
||||
billing_city = models.CharField(
|
||||
max_length=64, blank=False, verbose_name=_("ciudad de facturación")
|
||||
)
|
||||
billing_state = models.CharField(
|
||||
max_length=64, blank=False, verbose_name=_("región de facturación")
|
||||
)
|
||||
billing_country = models.CharField(
|
||||
max_length=64, blank=False, verbose_name=_("país de facturación")
|
||||
)
|
||||
billing_zip = models.CharField(
|
||||
max_length=32, blank=False, verbose_name=_("código postal de facturación")
|
||||
)
|
||||
billing_address = models.CharField(max_length=255, blank=False, verbose_name=_('dirección de facturación'))
|
||||
billing_city = models.CharField(max_length=64, blank=False, verbose_name=_('ciudad de facturación'))
|
||||
billing_state = models.CharField(max_length=64, blank=False, verbose_name=_('región de facturación'))
|
||||
billing_country = models.CharField(max_length=64, blank=False, verbose_name=_('país de facturación'))
|
||||
billing_zip = models.CharField(max_length=32, blank=False, verbose_name=_('código postal de facturación'))
|
||||
|
||||
# Datos de envío
|
||||
shipping_address = models.CharField(
|
||||
max_length=255, blank=False, verbose_name=_("dirección")
|
||||
)
|
||||
shipping_city = models.CharField(
|
||||
max_length=64, blank=False, verbose_name=_("ciudad")
|
||||
)
|
||||
shipping_state = models.CharField(
|
||||
max_length=64, blank=False, verbose_name=_("región")
|
||||
)
|
||||
shipping_country = models.CharField(
|
||||
max_length=64, blank=False, verbose_name=_("país")
|
||||
)
|
||||
shipping_zip = models.CharField(
|
||||
max_length=32, blank=False, verbose_name=_("código postal")
|
||||
)
|
||||
contact_phone = models.CharField(
|
||||
max_length=32, blank=True, verbose_name=_("teléfono de contacto")
|
||||
)
|
||||
shipping_address = models.CharField(max_length=255, blank=False, verbose_name=_('dirección'))
|
||||
shipping_city = models.CharField(max_length=64, blank=False, verbose_name=_('ciudad'))
|
||||
shipping_state = models.CharField(max_length=64, blank=False, verbose_name=_('región'))
|
||||
shipping_country = models.CharField(max_length=64, blank=False, verbose_name=_('país'))
|
||||
shipping_zip = models.CharField(max_length=32, blank=False, verbose_name=_('código postal'))
|
||||
contact_phone = models.CharField(max_length=32, blank=True, verbose_name=_('teléfono de contacto'))
|
||||
|
||||
amount_paid = models.DecimalField(
|
||||
default=Decimal("0.00"),
|
||||
max_digits=11,
|
||||
decimal_places=2,
|
||||
verbose_name=_("cantidad pagada"),
|
||||
default=Decimal('0.00'), max_digits=11, decimal_places=2, verbose_name=_('cantidad pagada')
|
||||
)
|
||||
|
||||
shipping_method = models.ForeignKey(
|
||||
"shop.ShippingMethod",
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=models.SET_NULL,
|
||||
verbose_name=_("método de envío"),
|
||||
'shop.ShippingMethod', blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('método de envío')
|
||||
)
|
||||
|
||||
from_cart = models.ForeignKey(
|
||||
"shop.Cart",
|
||||
on_delete=models.SET_NULL,
|
||||
blank=True,
|
||||
null=True,
|
||||
verbose_name=_("carrito de origen de pedido"),
|
||||
'shop.Cart', on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('carrito de origen de pedido')
|
||||
)
|
||||
|
||||
def calculate_total_from_lines(self):
|
||||
self.base_total = self.lines.aggregate(base_total=models.Sum("base_total")).get(
|
||||
"base_total"
|
||||
)
|
||||
self.total = self.lines.aggregate(base_total=models.Sum("total")).get(
|
||||
"base_total"
|
||||
)
|
||||
self.base_total = self.lines.aggregate(base_total=models.Sum('base_total')).get('base_total')
|
||||
self.total = self.lines.aggregate(base_total=models.Sum('total')).get('base_total')
|
||||
|
||||
self.save()
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("pedido")
|
||||
verbose_name_plural = _("pedidos")
|
||||
ordering = ("creation_date",)
|
||||
verbose_name = _('pedido')
|
||||
verbose_name_plural = _('pedidos')
|
||||
ordering = ('creation_date',)
|
||||
|
||||
|
||||
class Cart(models.Model):
|
||||
uuid = models.UUIDField(default=uuid4, primary_key=True, verbose_name=_("uuid"))
|
||||
user = models.ForeignKey(
|
||||
User,
|
||||
on_delete=models.CASCADE,
|
||||
verbose_name=_("usuario"),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
creation_date = models.DateTimeField(
|
||||
auto_now_add=True, verbose_name=_("fecha de creación")
|
||||
)
|
||||
uuid = models.UUIDField(default=uuid4, primary_key=True, verbose_name=_('uuid'))
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('usuario'), blank=True, null=True)
|
||||
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('fecha de creación'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("carrito")
|
||||
verbose_name_plural = _("carritos")
|
||||
verbose_name = _('carrito')
|
||||
verbose_name_plural = _('carritos')
|
||||
|
||||
|
||||
class CartItem(models.Model):
|
||||
cart = models.ForeignKey(
|
||||
"shop.Cart",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="items",
|
||||
verbose_name=_("carrito"),
|
||||
)
|
||||
product = models.ForeignKey(
|
||||
"shop.Product", on_delete=models.CASCADE, verbose_name=_("producto")
|
||||
)
|
||||
quantity = models.PositiveIntegerField(default=1, verbose_name=_("cantidad"))
|
||||
cart = models.ForeignKey('shop.Cart', on_delete=models.CASCADE, related_name='items', verbose_name=_('carrito'))
|
||||
product = models.ForeignKey('shop.Product', on_delete=models.CASCADE, verbose_name=_('producto'))
|
||||
quantity = models.PositiveIntegerField(default=1, verbose_name=_('cantidad'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("línea de carrito")
|
||||
verbose_name_plural = _("líneas de carrito")
|
||||
verbose_name = _('línea de carrito')
|
||||
verbose_name_plural = _('líneas de carrito')
|
||||
|
||||
|
||||
class CustomerAddress(models.Model):
|
||||
class Types(models.TextChoices):
|
||||
BILLING = "BILL", _("facturación")
|
||||
SHIPPING = "SHIP", _("envío")
|
||||
BILLING = 'BILL', _('facturación')
|
||||
SHIPPING = 'SHIP', _('envío')
|
||||
|
||||
user = models.ForeignKey(
|
||||
User, on_delete=models.CASCADE, null=True, verbose_name=_("usuario")
|
||||
)
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, verbose_name=_('usuario'))
|
||||
vat_id = models.CharField(
|
||||
max_length=16,
|
||||
blank=True,
|
||||
null=True,
|
||||
default="",
|
||||
verbose_name=_("número de identificación fiscal"),
|
||||
)
|
||||
full_name = models.CharField(
|
||||
max_length=128, blank=False, null=False, verbose_name=_("dirección")
|
||||
)
|
||||
address = models.CharField(
|
||||
max_length=128, blank=False, null=False, verbose_name=_("dirección")
|
||||
)
|
||||
address_town = models.CharField(
|
||||
max_length=64, blank=False, null=False, verbose_name=_("localidad")
|
||||
)
|
||||
address_zip = models.CharField(
|
||||
max_length=16, blank=False, null=False, verbose_name=_("código postal")
|
||||
)
|
||||
address_state = models.CharField(
|
||||
max_length=64, blank=False, null=False, verbose_name=_("provincia")
|
||||
max_length=16, blank=True, null=True, default='', verbose_name=_('número de identificación fiscal')
|
||||
)
|
||||
full_name = models.CharField(max_length=128, blank=False, null=False, verbose_name=_('dirección'))
|
||||
address = models.CharField(max_length=128, blank=False, null=False, verbose_name=_('dirección'))
|
||||
address_town = models.CharField(max_length=64, blank=False, null=False, verbose_name=_('localidad'))
|
||||
address_zip = models.CharField(max_length=16, blank=False, null=False, verbose_name=_('código postal'))
|
||||
address_state = models.CharField(max_length=64, blank=False, null=False, verbose_name=_('provincia'))
|
||||
address_country = models.CharField(
|
||||
max_length=64,
|
||||
default=settings.SHOP_COUNTRY,
|
||||
blank=False,
|
||||
null=False,
|
||||
verbose_name=_("país"),
|
||||
)
|
||||
address_phone = models.CharField(
|
||||
max_length=16, blank=True, null=True, default="", verbose_name=_("teléfono")
|
||||
max_length=64, default=settings.SHOP_COUNTRY, blank=False, null=False, verbose_name=_('país')
|
||||
)
|
||||
address_phone = models.CharField(max_length=16, blank=True, null=True, default='', verbose_name=_('teléfono'))
|
||||
|
||||
address_type = models.CharField(
|
||||
max_length=4,
|
||||
choices=Types.choices,
|
||||
default=Types.SHIPPING,
|
||||
verbose_name=_("tipo de dirección"),
|
||||
max_length=4, choices=Types.choices, default=Types.SHIPPING, verbose_name=_('tipo de dirección')
|
||||
)
|
||||
email = models.EmailField(blank=False, null=False, verbose_name=_("e-mail"))
|
||||
default = models.BooleanField(default=True, verbose_name=_("por defecto"))
|
||||
hidden = models.BooleanField(default=False, db_index=True, verbose_name=_("oculto"))
|
||||
email = models.EmailField(blank=False, null=False, verbose_name=_('e-mail'))
|
||||
default = models.BooleanField(default=True, verbose_name=_('por defecto'))
|
||||
hidden = models.BooleanField(default=False, db_index=True, verbose_name=_('oculto'))
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.full_name} - {self.address}, {self.address_zip}, {self.address_state} - {self.address_country}"
|
||||
return f'{self.full_name} - {self.address}, {self.address_zip}, {self.address_state} - {self.address_country}'
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("dirección de cliente")
|
||||
verbose_name_plural = _("direcciones de cliente")
|
||||
verbose_name = _('dirección de cliente')
|
||||
verbose_name_plural = _('direcciones de cliente')
|
||||
|
||||
|
||||
class ShippingMethod(models.Model):
|
||||
name = models.CharField(max_length=64, verbose_name=_("nombre"))
|
||||
description = models.CharField(
|
||||
max_length=256, default="", blank=True, verbose_name=_("description")
|
||||
)
|
||||
url = models.URLField(default="", blank=True, verbose_name=_("url"))
|
||||
shipping_product = models.ForeignKey(
|
||||
"shop.Product", on_delete=models.CASCADE, verbose_name=_("producto de envío")
|
||||
)
|
||||
enabled = models.BooleanField(default=True, verbose_name=_("habilitado"))
|
||||
name = models.CharField(max_length=64, verbose_name=_('nombre'))
|
||||
description = models.CharField(max_length=256, default='', blank=True, verbose_name=_('description'))
|
||||
url = models.URLField(default='', blank=True, verbose_name=_('url'))
|
||||
shipping_product = models.ForeignKey('shop.Product', on_delete=models.CASCADE, verbose_name=_('producto de envío'))
|
||||
enabled = models.BooleanField(default=True, verbose_name=_('habilitado'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("método de envío")
|
||||
verbose_name_plural = _("métodos de envío")
|
||||
verbose_name = _('método de envío')
|
||||
verbose_name_plural = _('métodos de envío')
|
||||
|
||||
|
||||
class WishlistedProduct(TimestampedModel):
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("usuario"))
|
||||
product = models.ForeignKey(
|
||||
"shop.Product", on_delete=models.CASCADE, verbose_name=_("producto")
|
||||
)
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('usuario'))
|
||||
product = models.ForeignKey('shop.Product', on_delete=models.CASCADE, verbose_name=_('producto'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("productos deseados")
|
||||
verbose_name_plural = _("productos deseados")
|
||||
unique_together = (
|
||||
"user",
|
||||
"product",
|
||||
)
|
||||
verbose_name = _('productos deseados')
|
||||
verbose_name_plural = _('productos deseados')
|
||||
unique_together = ('user', 'product')
|
||||
|
||||
|
||||
class Payment(models.Model):
|
||||
class MethodChoices(models.TextChoices):
|
||||
REDSYS = "REDSYS"
|
||||
REDSYS = 'REDSYS'
|
||||
|
||||
hash = models.UUIDField(verbose_name=_("Hash"), default=uuid4, primary_key=True)
|
||||
amount = models.DecimalField(
|
||||
max_digits=8,
|
||||
decimal_places=2,
|
||||
default=Decimal("0"),
|
||||
verbose_name=_("Cantidad"),
|
||||
)
|
||||
hash = models.UUIDField(verbose_name=_('Hash'), default=uuid4, primary_key=True)
|
||||
amount = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal('0'), verbose_name=_('Cantidad'))
|
||||
order = models.ForeignKey(
|
||||
"shop.Order",
|
||||
on_delete=models.PROTECT,
|
||||
verbose_name=_("pedido"),
|
||||
related_name="payments",
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
User, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_("cliente")
|
||||
'shop.Order', on_delete=models.PROTECT, verbose_name=_('pedido'), related_name='payments'
|
||||
)
|
||||
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_('cliente'))
|
||||
|
||||
creation_date = models.DateTimeField(
|
||||
auto_now_add=True, verbose_name=_("Fecha de creación")
|
||||
)
|
||||
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('Fecha de creación'))
|
||||
|
||||
metadata = models.JSONField(default=dict, verbose_name=_("Metadata"))
|
||||
metadata = models.JSONField(default=dict, verbose_name=_('Metadata'))
|
||||
|
||||
method = models.CharField(
|
||||
max_length=6,
|
||||
choices=MethodChoices.choices,
|
||||
default=MethodChoices.REDSYS,
|
||||
verbose_name=_("método de pago"),
|
||||
max_length=6, choices=MethodChoices.choices, default=MethodChoices.REDSYS, verbose_name=_('método de pago')
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("Pago")
|
||||
verbose_name_plural = _("Pagos")
|
||||
verbose_name = _('Pago')
|
||||
verbose_name_plural = _('Pagos')
|
||||
|
||||
|
||||
class ShopSettings(SingletonModel):
|
||||
debug = models.BooleanField(default=True, verbose_name=_("Modo depuración"))
|
||||
debug = models.BooleanField(default=True, verbose_name=_('Modo depuración'))
|
||||
merchant_code = models.CharField(
|
||||
max_length=9,
|
||||
blank=False,
|
||||
null=False,
|
||||
verbose_name=_("Identificación de comercio"),
|
||||
max_length=9, blank=False, null=False, verbose_name=_('Identificación de comercio')
|
||||
)
|
||||
currency_code = models.CharField(
|
||||
max_length=4,
|
||||
default="978",
|
||||
choices=CURRENCY_CODES,
|
||||
verbose_name=_("Código de moneda"),
|
||||
max_length=4, default='978', choices=CURRENCY_CODES, verbose_name=_('Código de moneda')
|
||||
) # 978 == EURO
|
||||
terminal = models.CharField(max_length=8, verbose_name=_("Terminal"))
|
||||
shared_secret = models.CharField(max_length=100, verbose_name=_("Clave de Redsys"))
|
||||
tpv_domain = models.URLField(
|
||||
max_length=128, blank=True, null=True, verbose_name=_("dominio del tpv")
|
||||
)
|
||||
terminal = models.CharField(max_length=8, verbose_name=_('Terminal'))
|
||||
shared_secret = models.CharField(max_length=100, verbose_name=_('Clave de Redsys'))
|
||||
tpv_domain = models.URLField(max_length=128, blank=True, null=True, verbose_name=_('dominio del tpv'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("ajustes de la tienda")
|
||||
verbose_name_plural = _("ajustes de la tienda")
|
||||
verbose_name = _('ajustes de la tienda')
|
||||
verbose_name_plural = _('ajustes de la tienda')
|
||||
|
||||
+49
-93
@@ -13,13 +13,11 @@ from shop.utils import compute_signature, decode_b64_dict
|
||||
|
||||
|
||||
class RedsysClient:
|
||||
DEBUG_ENVIRONMENT_URL = "https://sis-t.redsys.es:25443/sis/realizarPago"
|
||||
PROD_ENVIRONMENT_URL = "https://sis.redsys.es/sis/realizarPago"
|
||||
DEBUG_ENVIRONMENT_URL = 'https://sis-t.redsys.es:25443/sis/realizarPago'
|
||||
PROD_ENVIRONMENT_URL = 'https://sis.redsys.es/sis/realizarPago'
|
||||
|
||||
REST_DEBUG_ENVIRONMENT_URL = (
|
||||
"https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST"
|
||||
)
|
||||
REST_PROD_ENVIRONMENT_URL = "https://sis.redsys.es/sis/rest/trataPeticionREST"
|
||||
REST_DEBUG_ENVIRONMENT_URL = 'https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST'
|
||||
REST_PROD_ENVIRONMENT_URL = 'https://sis.redsys.es/sis/rest/trataPeticionREST'
|
||||
|
||||
def __init__(self):
|
||||
self.settings = ShopSettings.load()
|
||||
@@ -46,19 +44,19 @@ class RedsysClient:
|
||||
return self.settings.currency_code
|
||||
|
||||
def get_merchant_url_ok_for_order(self, order: Order) -> str:
|
||||
path = reverse("web:order", kwargs={"uuid": order.uuid})
|
||||
return f"{self.settings.tpv_domain}{path}"
|
||||
path = reverse('web:order', kwargs={'uuid': order.uuid})
|
||||
return f'{self.settings.tpv_domain}{path}'
|
||||
|
||||
def to_integer(self, value: Decimal):
|
||||
return int(value * 100)
|
||||
|
||||
def get_merchant_url_ko_for_order(self, order: Order) -> str:
|
||||
path = reverse("web:order", kwargs={"uuid": order.uuid})
|
||||
return f"{self.settings.tpv_domain}{path}"
|
||||
path = reverse('web:order', kwargs={'uuid': order.uuid})
|
||||
return f'{self.settings.tpv_domain}{path}'
|
||||
|
||||
def get_webhook_url_for_order(self, order: Order) -> str:
|
||||
path = reverse("shop:webhook", kwargs={"uuid": order.uuid})
|
||||
return f"{self.settings.tpv_domain}{path}"
|
||||
path = reverse('shop:webhook', kwargs={'uuid': order.uuid})
|
||||
return f'{self.settings.tpv_domain}{path}'
|
||||
|
||||
def get_shared_secret(self) -> str:
|
||||
return self.settings.shared_secret
|
||||
@@ -68,131 +66,89 @@ class RedsysClient:
|
||||
return compute_signature(str(hash), payload, key).decode()
|
||||
|
||||
def _get_merchant_parameters_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
self, order: Order, order_type: int = TransactionTypes.AUTHORIZATION
|
||||
) -> dict:
|
||||
merchant_code = self.get_merchant_code()
|
||||
|
||||
return {
|
||||
"DS_MERCHANT_AMOUNT": str(self.to_integer(order.total)),
|
||||
"DS_MERCHANT_CURRENCY": self.get_currency_code(),
|
||||
"DS_MERCHANT_MERCHANTCODE": merchant_code,
|
||||
'DS_MERCHANT_AMOUNT': str(self.to_integer(order.total)),
|
||||
'DS_MERCHANT_CURRENCY': self.get_currency_code(),
|
||||
'DS_MERCHANT_MERCHANTCODE': merchant_code,
|
||||
# Webhook
|
||||
"DS_MERCHANT_MERCHANTURL": self.get_webhook_url_for_order(order),
|
||||
"DS_MERCHANT_ORDER": order.code,
|
||||
"DS_MERCHANT_TERMINAL": self.get_terminal(),
|
||||
"DS_MERCHANT_TRANSACTIONTYPE": order_type,
|
||||
'DS_MERCHANT_MERCHANTURL': self.get_webhook_url_for_order(order),
|
||||
'DS_MERCHANT_ORDER': order.code,
|
||||
'DS_MERCHANT_TERMINAL': self.get_terminal(),
|
||||
'DS_MERCHANT_TRANSACTIONTYPE': order_type,
|
||||
# Página informativa al usuario - Pago erróneo
|
||||
"DS_MERCHANT_URLKO": self.get_merchant_url_ko_for_order(order),
|
||||
'DS_MERCHANT_URLKO': self.get_merchant_url_ko_for_order(order),
|
||||
# Página informativa al usuario - Pago confirmado
|
||||
"DS_MERCHANT_URLOK": self.get_merchant_url_ok_for_order(order),
|
||||
'DS_MERCHANT_URLOK': self.get_merchant_url_ok_for_order(order),
|
||||
}
|
||||
|
||||
def _get_encoded_merchant_parameters_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
self, order: Order, order_type: int = TransactionTypes.AUTHORIZATION
|
||||
) -> str:
|
||||
body = self._get_merchant_parameters_for_order(order, order_type)
|
||||
return self._encode_body(body)
|
||||
|
||||
def get_body_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
) -> dict:
|
||||
merchant_parameters = self._get_encoded_merchant_parameters_for_order(
|
||||
order, order_type
|
||||
)
|
||||
def get_body_for_order(self, order: Order, order_type: int = TransactionTypes.AUTHORIZATION) -> dict:
|
||||
merchant_parameters = self._get_encoded_merchant_parameters_for_order(order, order_type)
|
||||
signature = self.get_signature(order.code, merchant_parameters)
|
||||
|
||||
return {
|
||||
"Ds_MerchantParameters": merchant_parameters,
|
||||
"Ds_SignatureVersion": "HMAC_SHA256_V1",
|
||||
"Ds_Signature": signature,
|
||||
'Ds_MerchantParameters': merchant_parameters,
|
||||
'Ds_SignatureVersion': 'HMAC_SHA256_V1',
|
||||
'Ds_Signature': signature,
|
||||
}
|
||||
|
||||
def _encode_body(self, value):
|
||||
stringified_body = json.dumps(value)
|
||||
return base64.b64encode(stringified_body.encode()).decode("utf-8")
|
||||
return base64.b64encode(stringified_body.encode()).decode('utf-8')
|
||||
|
||||
def _get_rest_merchant_parameters_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
pan: str,
|
||||
expiry_date: str,
|
||||
cvv2: str,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
self, order: Order, pan: str, expiry_date: str, cvv2: str, order_type: int = TransactionTypes.AUTHORIZATION
|
||||
) -> dict:
|
||||
merchant_code = self.get_merchant_code()
|
||||
|
||||
return {
|
||||
"DS_MERCHANT_AMOUNT": str(self.to_integer(order.total)),
|
||||
"DS_MERCHANT_CURRENCY": self.get_currency_code(),
|
||||
"DS_MERCHANT_CVV2": cvv2,
|
||||
"DS_MERCHANT_EXPIRYDATE": expiry_date,
|
||||
"DS_MERCHANT_MERCHANTCODE": merchant_code,
|
||||
"DS_MERCHANT_ORDER": order.uuid.hex,
|
||||
"DS_MERCHANT_PAN": pan,
|
||||
"DS_MERCHANT_TERMINAL": "1",
|
||||
"DS_MERCHANT_TRANSACTIONTYPE": order_type,
|
||||
'DS_MERCHANT_AMOUNT': str(self.to_integer(order.total)),
|
||||
'DS_MERCHANT_CURRENCY': self.get_currency_code(),
|
||||
'DS_MERCHANT_CVV2': cvv2,
|
||||
'DS_MERCHANT_EXPIRYDATE': expiry_date,
|
||||
'DS_MERCHANT_MERCHANTCODE': merchant_code,
|
||||
'DS_MERCHANT_ORDER': order.uuid.hex,
|
||||
'DS_MERCHANT_PAN': pan,
|
||||
'DS_MERCHANT_TERMINAL': '1',
|
||||
'DS_MERCHANT_TRANSACTIONTYPE': order_type,
|
||||
}
|
||||
|
||||
def _get_rest_encoded_merchant_parameters_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
pan: str,
|
||||
expiry_date: str,
|
||||
cvv2: str,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
self, order: Order, pan: str, expiry_date: str, cvv2: str, order_type: int = TransactionTypes.AUTHORIZATION
|
||||
) -> str:
|
||||
body = self._get_rest_merchant_parameters_for_order(
|
||||
order,
|
||||
pan=pan,
|
||||
expiry_date=expiry_date,
|
||||
cvv2=cvv2,
|
||||
order_type=order_type,
|
||||
order, pan=pan, expiry_date=expiry_date, cvv2=cvv2, order_type=order_type
|
||||
)
|
||||
return self._encode_body(body)
|
||||
|
||||
def _get_rest_body_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
pan: str,
|
||||
expiry_date: str,
|
||||
cvv2: str,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
self, order: Order, pan: str, expiry_date: str, cvv2: str, order_type: int = TransactionTypes.AUTHORIZATION
|
||||
) -> dict:
|
||||
merchant_parameters = self._get_rest_encoded_merchant_parameters_for_order(
|
||||
order=order,
|
||||
pan=pan,
|
||||
expiry_date=expiry_date,
|
||||
cvv2=cvv2,
|
||||
order_type=order_type,
|
||||
order=order, pan=pan, expiry_date=expiry_date, cvv2=cvv2, order_type=order_type
|
||||
)
|
||||
signature = self.get_signature(order.code, merchant_parameters)
|
||||
|
||||
return {
|
||||
"Ds_MerchantParameters": merchant_parameters,
|
||||
"Ds_SignatureVersion": "HMAC_SHA256_V1",
|
||||
"Ds_Signature": signature,
|
||||
'Ds_MerchantParameters': merchant_parameters,
|
||||
'Ds_SignatureVersion': 'HMAC_SHA256_V1',
|
||||
'Ds_Signature': signature,
|
||||
}
|
||||
|
||||
def make_request_for_order(
|
||||
self,
|
||||
order: Order,
|
||||
pan: str,
|
||||
expiry_date: str,
|
||||
cvv2: str,
|
||||
order_type: int = TransactionTypes.AUTHORIZATION,
|
||||
self, order: Order, pan: str, expiry_date: str, cvv2: str, order_type: int = TransactionTypes.AUTHORIZATION
|
||||
):
|
||||
body = self._get_rest_body_for_order(
|
||||
order=order,
|
||||
pan=pan,
|
||||
expiry_date=expiry_date,
|
||||
cvv2=cvv2,
|
||||
order_type=order_type,
|
||||
order=order, pan=pan, expiry_date=expiry_date, cvv2=cvv2, order_type=order_type
|
||||
)
|
||||
url = self.get_rest_target_url()
|
||||
response = requests.post(url, body)
|
||||
@@ -201,14 +157,14 @@ class RedsysClient:
|
||||
def pay_order_rest(self, order: Order, pan: str, expiry_date: str, cvv2: str):
|
||||
response = self.make_request_for_order(order, pan, expiry_date, cvv2)
|
||||
data = response.json()
|
||||
error_code: str = data.get("errorCode", "")
|
||||
error_code: str = data.get('errorCode', '')
|
||||
|
||||
if error_code:
|
||||
error_code.replace("SIS0", "0")
|
||||
error_code.replace('SIS0', '0')
|
||||
|
||||
raise RedsysPaymentException(error_code)
|
||||
|
||||
merchant_parameters = data.get("Ds_MerchantParameters")
|
||||
merchant_parameters = data.get('Ds_MerchantParameters')
|
||||
parameters = decode_b64_dict(merchant_parameters)
|
||||
|
||||
return parameters
|
||||
|
||||
+242
-246
@@ -20,253 +20,249 @@ class TransactionTypes:
|
||||
|
||||
|
||||
CURRENCY_CODES = {
|
||||
"8": "LEK ALL",
|
||||
"12": "ALGERIAN DINAR DZD",
|
||||
"24": "ANGOLA KWANZA AOK",
|
||||
"30": "PROBANDO DESA MON",
|
||||
"31": "AZERBAIJANIAN MANAT AZM",
|
||||
"32": "ARGENTINE AUSTRAL ARP",
|
||||
"36": "AUSTRALIAN DOLLAR AUD",
|
||||
"44": "BAHAMIAN DOLLAR BSD",
|
||||
"48": "BAHRAINI DINAR BHD",
|
||||
"50": "TAKA BDT",
|
||||
"51": "ARMENIAN DRAM AMD",
|
||||
"52": "BARBADOS DOLLAR BBD",
|
||||
"60": "BERMUDAN DOLLAR BMD",
|
||||
"64": "NGULTRUM BTN",
|
||||
"68": "BOLIVIAN PESO BOP",
|
||||
"70": "DINAR BAD",
|
||||
"72": "PULA BWP",
|
||||
"76": "CRUZEIRO BRC",
|
||||
"84": "BELIZE DOLLAR 084",
|
||||
"90": "SOLOMON ISLANDS DOLL SBD",
|
||||
"96": "BRUNEI DOLLAR BND",
|
||||
"100": "LEV BGL",
|
||||
"104": "KYAT BUK",
|
||||
"108": "BURUNDI FRANC BIF",
|
||||
"112": "BELARUSSIAN RUBLE BYB",
|
||||
"116": "RIEL KHR",
|
||||
"124": "CANADIAN DOLLAR CAD",
|
||||
"132": "CAPE VERDE ESCUDO CVE",
|
||||
"136": "CAYMAN ISLANDS DOLLA KYD",
|
||||
"144": "SRI LANKA RUPEE LKR",
|
||||
"152": "CHILEAN PESO CLP",
|
||||
"156": "YUAN RENMINBI CNY",
|
||||
"157": "CHINESE RENMIMBI CNH",
|
||||
"158": "CHINESE RENMINBI CNX",
|
||||
"170": "COLOMBIAN PESO COP",
|
||||
"174": "COMOROS FRANC KMF",
|
||||
"180": "ZAIRE ZRZ",
|
||||
"188": "COSTA RICA COLON CRC",
|
||||
"191": "CROATIAN KUNA HRK",
|
||||
"192": "CUBAN PESO CUP",
|
||||
"196": "CYPRUS POUND CYP",
|
||||
"200": "KORUNA CSK",
|
||||
"203": "CZECH KORUNA CZK",
|
||||
"208": "DANISH KRONE DKK",
|
||||
"214": "DOMINICAN PESO DOP",
|
||||
"218": "SUCRE ECS",
|
||||
"222": "EL SALVADOR COLON SVC",
|
||||
"226": "EKWELE GQE",
|
||||
"230": "ETHIOPIAN BIRR ETB",
|
||||
"232": "ERITREAN NAKTAN ERN",
|
||||
"233": "ESTONIAN KROON EEK",
|
||||
"238": "FALKLAND ISLANDS FKP",
|
||||
"242": "FIJI DOLLAR FJD",
|
||||
"262": "DJIBOUTI FRANC DJF",
|
||||
"268": "GEORGIAN LARI GEL",
|
||||
"270": "DALASI GMD",
|
||||
"278": "MARK DER DDR DDM",
|
||||
"288": "GHANA CEDI GHC",
|
||||
"292": "GIBRALTAR POUND GIP",
|
||||
"320": "QUETZAL GTQ",
|
||||
"324": "SYLI GNS",
|
||||
"328": "GUYANA DOLLAR GYD",
|
||||
"332": "GOURDE HTG",
|
||||
"340": "LEMPIRA HNL",
|
||||
"344": "HONG KONG DOLLAR HKD",
|
||||
"348": "FORINT HUF",
|
||||
"352": "ICELAND KRONA ISK",
|
||||
"356": "INDIAN RUPEE INR",
|
||||
"360": "RUPIAH IDR",
|
||||
"364": "IRANIAL RIAL IRR",
|
||||
"365": "IRANIAN AIRLINE RATE IRA",
|
||||
"368": "IRAQI DINAR IQD",
|
||||
"376": "ISRAEL SHEKEL ILS",
|
||||
"388": "JAMAICAN DOLLAR JMD",
|
||||
"392": "YEN JPY",
|
||||
"398": "TENGE KZT",
|
||||
"400": "JORDANIAN DINAR JOD",
|
||||
"404": "KENYAN SHILLING KES",
|
||||
"408": "NORTH KOREAN WON KPW",
|
||||
"410": "KOREAN WON KRW",
|
||||
"414": "KUWAITI DINAR KWD",
|
||||
"417": "KYRGYZSTAN SON KGS",
|
||||
"418": "KIP LAK",
|
||||
"422": "LEBANESE POUND LBP",
|
||||
"426": "LESOTHO LOTI LSM",
|
||||
"428": "LATVIAN LAT LVL",
|
||||
"430": "LIBERIAN DOLLAR LRD",
|
||||
"434": "LIBYAN DINAR LYD",
|
||||
"440": "LITHUANIAN LITAS LTL",
|
||||
"446": "PATACA MOP",
|
||||
"450": "MALAGASY FRANC MGF",
|
||||
"454": "MALAWI KWACHA MWK",
|
||||
"458": "MALASYAN RINGGIT MYR",
|
||||
"462": "MALDIVE RUPEE MVR",
|
||||
"466": "MALI MLF",
|
||||
"470": "MALTESE LIRA MTL",
|
||||
"478": "OUGUIYA MRO",
|
||||
"480": "MAURITIUS RUPEE MUR",
|
||||
"484": "MEXICAN PESO MXP",
|
||||
"496": "TUGRIK MNT",
|
||||
"498": "MOLDOVIAN LEU MDL",
|
||||
"504": "MORROCAN DIRHAM MAD",
|
||||
"508": "METICAL MZM",
|
||||
"512": "RIAL OMANI OMR",
|
||||
"516": "NAMIBIAN DOLLAR NAD",
|
||||
"524": "NEPALESE RUPEE NPR",
|
||||
"532": "NETHERLANDS ANTILLIA ANG",
|
||||
"533": "ARUBA AWG",
|
||||
"536": "YUGOSLAVIAN NEW DIAN NTZ",
|
||||
"548": "VANUATU VATU VUV",
|
||||
"554": "NEW ZEALAND DOLLAR NZD",
|
||||
"556": "NAIRA 566",
|
||||
"558": "CORDOBA NIC",
|
||||
"566": "NAIRA NGN",
|
||||
"578": "NORWEGIAN KRONE NOK",
|
||||
"582": "PACIFIC ISLAND PCI",
|
||||
"586": "PAKISTAN RUPEE PKR",
|
||||
"590": "BALBOA PAB",
|
||||
"598": "KINA PGK",
|
||||
"600": "GUARANI PYG",
|
||||
"604": "PERU INTI PEI",
|
||||
"608": "PHILIPPINE PESO PHP",
|
||||
"616": "ZLOTY PLZ",
|
||||
"624": "GUINEA",
|
||||
"626": "TIMOR ESCUDO TPE",
|
||||
"634": "QATARI RIAL QAR",
|
||||
"642": "LEU ROL",
|
||||
"643": "RUSSIAN ROUBLE RUB",
|
||||
"646": "RWANDA FRANC RWF",
|
||||
"654": "ST.HELENA POUND SHP",
|
||||
"678": "DOBRA STD",
|
||||
"682": "SAUDI RIYAL SAR",
|
||||
"690": "SEYCHELLES RUPEE SCR",
|
||||
"694": "LEONE SLL",
|
||||
"702": "SINGAPORE DOLLAR SGD",
|
||||
"703": "SLOVAK KORUNA SKK",
|
||||
"704": "DONG VND",
|
||||
"705": "SLOVENIAN TOLAR SIT",
|
||||
"706": "SOMALI SHILLING SOS",
|
||||
"710": "RAND ZAR",
|
||||
"716": "ZIMBABWE DOLLAR ZWD",
|
||||
"720": "YEMENI DINAR YDD",
|
||||
"728": "SOUTH SUDANESE POUND SSP",
|
||||
"736": "SUDANESE POUND SDP",
|
||||
"737": "SUDAN AIRLINES SDA",
|
||||
"740": "SURINAM GUILDER SRG",
|
||||
"748": "LILANGENI SZL",
|
||||
"752": "SWEDISH KRONA SEK",
|
||||
"756": "SWISS FRANC CHF",
|
||||
"760": "SYRIAN POUND SYP",
|
||||
"762": "TAJIK RUBLE TJR",
|
||||
"764": "BAHT THB",
|
||||
"776": "PA'ANGA TOP",
|
||||
"780": "TRINIDAD Y TOBAGO DO TTD",
|
||||
"784": "UAE DIRHAM AED",
|
||||
"788": "TUNISIAN DINAR TND",
|
||||
"792": "TURKISH LIRA TRL",
|
||||
"793": "PSEUDO TURKISH LIRA PTL",
|
||||
"795": "MANAT TMM",
|
||||
"800": "UGANDA SHILLING UGS",
|
||||
"804": "KARBOVANET UAK",
|
||||
"807": "MACEDONIAN DENAR MKD",
|
||||
"810": "RUSSIAN ROUBLE RUR",
|
||||
"818": "EGYPTIAN POUND EGP",
|
||||
"826": "POUND STERLING GBP",
|
||||
"834": "TANZANIAN SHILLING TZS",
|
||||
"840": "DOLAR U.S.A. USD",
|
||||
"858": "URUGUAYAN PESO UYP",
|
||||
"860": "UZBEKISTAN SUM UZS",
|
||||
"862": "BOLIVAR VEB",
|
||||
"882": "TALA WST",
|
||||
"886": "YEMINI RIAL YER",
|
||||
"890": "NEW YUGOSLAVIAN DOLL YUD",
|
||||
"891": "NEW DINAR YUG",
|
||||
"894": "KWACHA ZMK",
|
||||
"901": "NEW TAIWAN DOLLAR TWD",
|
||||
"934": "NEW MANAT TMT",
|
||||
"936": "GHANA CEDI GHS",
|
||||
"941": "DINAR SERBIO RSD",
|
||||
"943": "MOZAMBIQUE METICAL MZN",
|
||||
"944": "AZERBAIJANIAN MANAT AZN",
|
||||
"946": "NEW LEU RON",
|
||||
"949": "TURKISH LIRA TRY",
|
||||
"950": "CFA FRANC BEAC XAF",
|
||||
"951": "EAST CARIBBEAN DOLLA XCD",
|
||||
"952": "CFA FRANC BCEAO XOF",
|
||||
"953": "CFP FRANC XPF",
|
||||
"954": "E.C.U. EUROPEAN CUR XEU",
|
||||
"967": "KWACHA ZMW",
|
||||
"968": "SURINAME DOLLAR SRD",
|
||||
"969": "ARIARY MGA",
|
||||
"971": "AFGHANISTAN AFGHANI AFN",
|
||||
"972": "TAJIKISTAN SOMONI TJS",
|
||||
"973": "KWANZA ANGOLA AOA",
|
||||
"974": "BELARUSSIAN RUBLE BYR",
|
||||
"975": "NEW LEV BGN",
|
||||
"976": "FRANCO DEL CONGO CDF",
|
||||
"977": "BOSNIAN MARKA BAM",
|
||||
"978": "EURO EUR",
|
||||
"980": "HRYVNIA UAH",
|
||||
"981": "GEORGIAN LARI GEL",
|
||||
"985": "NEW POLISH ZLOTY PLN",
|
||||
"986": "BRAZILIAN REAL BRL",
|
||||
"991": "RAND FINANCIER ZAL",
|
||||
'8': 'LEK ALL',
|
||||
'12': 'ALGERIAN DINAR DZD',
|
||||
'24': 'ANGOLA KWANZA AOK',
|
||||
'30': 'PROBANDO DESA MON',
|
||||
'31': 'AZERBAIJANIAN MANAT AZM',
|
||||
'32': 'ARGENTINE AUSTRAL ARP',
|
||||
'36': 'AUSTRALIAN DOLLAR AUD',
|
||||
'44': 'BAHAMIAN DOLLAR BSD',
|
||||
'48': 'BAHRAINI DINAR BHD',
|
||||
'50': 'TAKA BDT',
|
||||
'51': 'ARMENIAN DRAM AMD',
|
||||
'52': 'BARBADOS DOLLAR BBD',
|
||||
'60': 'BERMUDAN DOLLAR BMD',
|
||||
'64': 'NGULTRUM BTN',
|
||||
'68': 'BOLIVIAN PESO BOP',
|
||||
'70': 'DINAR BAD',
|
||||
'72': 'PULA BWP',
|
||||
'76': 'CRUZEIRO BRC',
|
||||
'84': 'BELIZE DOLLAR 084',
|
||||
'90': 'SOLOMON ISLANDS DOLL SBD',
|
||||
'96': 'BRUNEI DOLLAR BND',
|
||||
'100': 'LEV BGL',
|
||||
'104': 'KYAT BUK',
|
||||
'108': 'BURUNDI FRANC BIF',
|
||||
'112': 'BELARUSSIAN RUBLE BYB',
|
||||
'116': 'RIEL KHR',
|
||||
'124': 'CANADIAN DOLLAR CAD',
|
||||
'132': 'CAPE VERDE ESCUDO CVE',
|
||||
'136': 'CAYMAN ISLANDS DOLLA KYD',
|
||||
'144': 'SRI LANKA RUPEE LKR',
|
||||
'152': 'CHILEAN PESO CLP',
|
||||
'156': 'YUAN RENMINBI CNY',
|
||||
'157': 'CHINESE RENMIMBI CNH',
|
||||
'158': 'CHINESE RENMINBI CNX',
|
||||
'170': 'COLOMBIAN PESO COP',
|
||||
'174': 'COMOROS FRANC KMF',
|
||||
'180': 'ZAIRE ZRZ',
|
||||
'188': 'COSTA RICA COLON CRC',
|
||||
'191': 'CROATIAN KUNA HRK',
|
||||
'192': 'CUBAN PESO CUP',
|
||||
'196': 'CYPRUS POUND CYP',
|
||||
'200': 'KORUNA CSK',
|
||||
'203': 'CZECH KORUNA CZK',
|
||||
'208': 'DANISH KRONE DKK',
|
||||
'214': 'DOMINICAN PESO DOP',
|
||||
'218': 'SUCRE ECS',
|
||||
'222': 'EL SALVADOR COLON SVC',
|
||||
'226': 'EKWELE GQE',
|
||||
'230': 'ETHIOPIAN BIRR ETB',
|
||||
'232': 'ERITREAN NAKTAN ERN',
|
||||
'233': 'ESTONIAN KROON EEK',
|
||||
'238': 'FALKLAND ISLANDS FKP',
|
||||
'242': 'FIJI DOLLAR FJD',
|
||||
'262': 'DJIBOUTI FRANC DJF',
|
||||
'268': 'GEORGIAN LARI GEL',
|
||||
'270': 'DALASI GMD',
|
||||
'278': 'MARK DER DDR DDM',
|
||||
'288': 'GHANA CEDI GHC',
|
||||
'292': 'GIBRALTAR POUND GIP',
|
||||
'320': 'QUETZAL GTQ',
|
||||
'324': 'SYLI GNS',
|
||||
'328': 'GUYANA DOLLAR GYD',
|
||||
'332': 'GOURDE HTG',
|
||||
'340': 'LEMPIRA HNL',
|
||||
'344': 'HONG KONG DOLLAR HKD',
|
||||
'348': 'FORINT HUF',
|
||||
'352': 'ICELAND KRONA ISK',
|
||||
'356': 'INDIAN RUPEE INR',
|
||||
'360': 'RUPIAH IDR',
|
||||
'364': 'IRANIAL RIAL IRR',
|
||||
'365': 'IRANIAN AIRLINE RATE IRA',
|
||||
'368': 'IRAQI DINAR IQD',
|
||||
'376': 'ISRAEL SHEKEL ILS',
|
||||
'388': 'JAMAICAN DOLLAR JMD',
|
||||
'392': 'YEN JPY',
|
||||
'398': 'TENGE KZT',
|
||||
'400': 'JORDANIAN DINAR JOD',
|
||||
'404': 'KENYAN SHILLING KES',
|
||||
'408': 'NORTH KOREAN WON KPW',
|
||||
'410': 'KOREAN WON KRW',
|
||||
'414': 'KUWAITI DINAR KWD',
|
||||
'417': 'KYRGYZSTAN SON KGS',
|
||||
'418': 'KIP LAK',
|
||||
'422': 'LEBANESE POUND LBP',
|
||||
'426': 'LESOTHO LOTI LSM',
|
||||
'428': 'LATVIAN LAT LVL',
|
||||
'430': 'LIBERIAN DOLLAR LRD',
|
||||
'434': 'LIBYAN DINAR LYD',
|
||||
'440': 'LITHUANIAN LITAS LTL',
|
||||
'446': 'PATACA MOP',
|
||||
'450': 'MALAGASY FRANC MGF',
|
||||
'454': 'MALAWI KWACHA MWK',
|
||||
'458': 'MALASYAN RINGGIT MYR',
|
||||
'462': 'MALDIVE RUPEE MVR',
|
||||
'466': 'MALI MLF',
|
||||
'470': 'MALTESE LIRA MTL',
|
||||
'478': 'OUGUIYA MRO',
|
||||
'480': 'MAURITIUS RUPEE MUR',
|
||||
'484': 'MEXICAN PESO MXP',
|
||||
'496': 'TUGRIK MNT',
|
||||
'498': 'MOLDOVIAN LEU MDL',
|
||||
'504': 'MORROCAN DIRHAM MAD',
|
||||
'508': 'METICAL MZM',
|
||||
'512': 'RIAL OMANI OMR',
|
||||
'516': 'NAMIBIAN DOLLAR NAD',
|
||||
'524': 'NEPALESE RUPEE NPR',
|
||||
'532': 'NETHERLANDS ANTILLIA ANG',
|
||||
'533': 'ARUBA AWG',
|
||||
'536': 'YUGOSLAVIAN NEW DIAN NTZ',
|
||||
'548': 'VANUATU VATU VUV',
|
||||
'554': 'NEW ZEALAND DOLLAR NZD',
|
||||
'556': 'NAIRA 566',
|
||||
'558': 'CORDOBA NIC',
|
||||
'566': 'NAIRA NGN',
|
||||
'578': 'NORWEGIAN KRONE NOK',
|
||||
'582': 'PACIFIC ISLAND PCI',
|
||||
'586': 'PAKISTAN RUPEE PKR',
|
||||
'590': 'BALBOA PAB',
|
||||
'598': 'KINA PGK',
|
||||
'600': 'GUARANI PYG',
|
||||
'604': 'PERU INTI PEI',
|
||||
'608': 'PHILIPPINE PESO PHP',
|
||||
'616': 'ZLOTY PLZ',
|
||||
'624': 'GUINEA',
|
||||
'626': 'TIMOR ESCUDO TPE',
|
||||
'634': 'QATARI RIAL QAR',
|
||||
'642': 'LEU ROL',
|
||||
'643': 'RUSSIAN ROUBLE RUB',
|
||||
'646': 'RWANDA FRANC RWF',
|
||||
'654': 'ST.HELENA POUND SHP',
|
||||
'678': 'DOBRA STD',
|
||||
'682': 'SAUDI RIYAL SAR',
|
||||
'690': 'SEYCHELLES RUPEE SCR',
|
||||
'694': 'LEONE SLL',
|
||||
'702': 'SINGAPORE DOLLAR SGD',
|
||||
'703': 'SLOVAK KORUNA SKK',
|
||||
'704': 'DONG VND',
|
||||
'705': 'SLOVENIAN TOLAR SIT',
|
||||
'706': 'SOMALI SHILLING SOS',
|
||||
'710': 'RAND ZAR',
|
||||
'716': 'ZIMBABWE DOLLAR ZWD',
|
||||
'720': 'YEMENI DINAR YDD',
|
||||
'728': 'SOUTH SUDANESE POUND SSP',
|
||||
'736': 'SUDANESE POUND SDP',
|
||||
'737': 'SUDAN AIRLINES SDA',
|
||||
'740': 'SURINAM GUILDER SRG',
|
||||
'748': 'LILANGENI SZL',
|
||||
'752': 'SWEDISH KRONA SEK',
|
||||
'756': 'SWISS FRANC CHF',
|
||||
'760': 'SYRIAN POUND SYP',
|
||||
'762': 'TAJIK RUBLE TJR',
|
||||
'764': 'BAHT THB',
|
||||
'776': "PA'ANGA TOP",
|
||||
'780': 'TRINIDAD Y TOBAGO DO TTD',
|
||||
'784': 'UAE DIRHAM AED',
|
||||
'788': 'TUNISIAN DINAR TND',
|
||||
'792': 'TURKISH LIRA TRL',
|
||||
'793': 'PSEUDO TURKISH LIRA PTL',
|
||||
'795': 'MANAT TMM',
|
||||
'800': 'UGANDA SHILLING UGS',
|
||||
'804': 'KARBOVANET UAK',
|
||||
'807': 'MACEDONIAN DENAR MKD',
|
||||
'810': 'RUSSIAN ROUBLE RUR',
|
||||
'818': 'EGYPTIAN POUND EGP',
|
||||
'826': 'POUND STERLING GBP',
|
||||
'834': 'TANZANIAN SHILLING TZS',
|
||||
'840': 'DOLAR U.S.A. USD',
|
||||
'858': 'URUGUAYAN PESO UYP',
|
||||
'860': 'UZBEKISTAN SUM UZS',
|
||||
'862': 'BOLIVAR VEB',
|
||||
'882': 'TALA WST',
|
||||
'886': 'YEMINI RIAL YER',
|
||||
'890': 'NEW YUGOSLAVIAN DOLL YUD',
|
||||
'891': 'NEW DINAR YUG',
|
||||
'894': 'KWACHA ZMK',
|
||||
'901': 'NEW TAIWAN DOLLAR TWD',
|
||||
'934': 'NEW MANAT TMT',
|
||||
'936': 'GHANA CEDI GHS',
|
||||
'941': 'DINAR SERBIO RSD',
|
||||
'943': 'MOZAMBIQUE METICAL MZN',
|
||||
'944': 'AZERBAIJANIAN MANAT AZN',
|
||||
'946': 'NEW LEU RON',
|
||||
'949': 'TURKISH LIRA TRY',
|
||||
'950': 'CFA FRANC BEAC XAF',
|
||||
'951': 'EAST CARIBBEAN DOLLA XCD',
|
||||
'952': 'CFA FRANC BCEAO XOF',
|
||||
'953': 'CFP FRANC XPF',
|
||||
'954': 'E.C.U. EUROPEAN CUR XEU',
|
||||
'967': 'KWACHA ZMW',
|
||||
'968': 'SURINAME DOLLAR SRD',
|
||||
'969': 'ARIARY MGA',
|
||||
'971': 'AFGHANISTAN AFGHANI AFN',
|
||||
'972': 'TAJIKISTAN SOMONI TJS',
|
||||
'973': 'KWANZA ANGOLA AOA',
|
||||
'974': 'BELARUSSIAN RUBLE BYR',
|
||||
'975': 'NEW LEV BGN',
|
||||
'976': 'FRANCO DEL CONGO CDF',
|
||||
'977': 'BOSNIAN MARKA BAM',
|
||||
'978': 'EURO EUR',
|
||||
'980': 'HRYVNIA UAH',
|
||||
'981': 'GEORGIAN LARI GEL',
|
||||
'985': 'NEW POLISH ZLOTY PLN',
|
||||
'986': 'BRAZILIAN REAL BRL',
|
||||
'991': 'RAND FINANCIER ZAL',
|
||||
}
|
||||
|
||||
ERROR_CODES = {
|
||||
"10000": _("Error no tipificado"),
|
||||
"0900": _("Transacción autorizada para devoluciones y confirmaciones"),
|
||||
"0400": _("Transacción autorizada para anulaciones"),
|
||||
"0101": _("Tarjeta caducada"),
|
||||
"0102": _("Tarjeta en excepción transitoria o bajo sospecha de fraude"),
|
||||
"0106": _("Intentos de PIN excedidos"),
|
||||
"0125": _("Tarjeta no efectiva"),
|
||||
"0129": _("Código de seguridad (CVV2/CVC2) incorrecto"),
|
||||
"172": _("Denegada, no repetir."),
|
||||
"173": _("Denegada, no repetir sin actualizar datos de tarjeta."),
|
||||
"174": _("Denegada, no repetir antes de 72 horas."),
|
||||
"0180": _("Tarjeta ajena al servicio"),
|
||||
"0184": _("Error en la autenticación del titular"),
|
||||
"0190": _("Denegación del emisor sin especificar motivo"),
|
||||
"0191": _("Fecha de caducidad errónea"),
|
||||
"0195": _("Requiere autenticación SCA"),
|
||||
"0202": _(
|
||||
"Tarjeta en excepción transitoria o bajo sospecha de fraude con retirada de tarjeta"
|
||||
),
|
||||
"0904": _("Comercio no registrado en FUC"),
|
||||
"0909": _("Error de sistema"),
|
||||
"0913": _("Pedido repetido"),
|
||||
"0944": _("Sesión Incorrecta"),
|
||||
"0950": _("Operación de devolución no permitida"),
|
||||
"9912": _("Emisor no disponible"),
|
||||
"0912": _("Emisor no disponible"),
|
||||
"9064": _("Número de posiciones de la tarjeta incorrecto"),
|
||||
"9078": _("Tipo de operación no permitida para esa tarjeta"),
|
||||
"9093": _("Tarjeta no existente"),
|
||||
"9094": _("Rechazo servidores internacionales"),
|
||||
"9104": _("Comercio con titular seguro y titular sin clave de compra segura"),
|
||||
"9218": _("El comercio no permite op. seguras por entrada /operaciones"),
|
||||
"9253": _("Tarjeta no cumple el check-digit"),
|
||||
"9256": _("El comercio no puede realizar preautorizaciones"),
|
||||
"9257": _("Esta tarjeta no permite operativa de preautorizaciones"),
|
||||
"9261": _(
|
||||
"Operación detenida por superar el control de restricciones en la entrada al SIS"
|
||||
),
|
||||
"9915": _("A petición del usuario se ha cancelado el pago"),
|
||||
"9997": _("Se está procesando otra transacción en SIS con la misma tarjeta"),
|
||||
"9998": _("Operación en proceso de solicitud de datos de tarjeta"),
|
||||
"9999": _("Operación que ha sido redirigida al emisor a autenticar"),
|
||||
'10000': _('Error no tipificado'),
|
||||
'0900': _('Transacción autorizada para devoluciones y confirmaciones'),
|
||||
'0400': _('Transacción autorizada para anulaciones'),
|
||||
'0101': _('Tarjeta caducada'),
|
||||
'0102': _('Tarjeta en excepción transitoria o bajo sospecha de fraude'),
|
||||
'0106': _('Intentos de PIN excedidos'),
|
||||
'0125': _('Tarjeta no efectiva'),
|
||||
'0129': _('Código de seguridad (CVV2/CVC2) incorrecto'),
|
||||
'172': _('Denegada, no repetir.'),
|
||||
'173': _('Denegada, no repetir sin actualizar datos de tarjeta.'),
|
||||
'174': _('Denegada, no repetir antes de 72 horas.'),
|
||||
'0180': _('Tarjeta ajena al servicio'),
|
||||
'0184': _('Error en la autenticación del titular'),
|
||||
'0190': _('Denegación del emisor sin especificar motivo'),
|
||||
'0191': _('Fecha de caducidad errónea'),
|
||||
'0195': _('Requiere autenticación SCA'),
|
||||
'0202': _('Tarjeta en excepción transitoria o bajo sospecha de fraude con retirada de tarjeta'),
|
||||
'0904': _('Comercio no registrado en FUC'),
|
||||
'0909': _('Error de sistema'),
|
||||
'0913': _('Pedido repetido'),
|
||||
'0944': _('Sesión Incorrecta'),
|
||||
'0950': _('Operación de devolución no permitida'),
|
||||
'9912': _('Emisor no disponible'),
|
||||
'0912': _('Emisor no disponible'),
|
||||
'9064': _('Número de posiciones de la tarjeta incorrecto'),
|
||||
'9078': _('Tipo de operación no permitida para esa tarjeta'),
|
||||
'9093': _('Tarjeta no existente'),
|
||||
'9094': _('Rechazo servidores internacionales'),
|
||||
'9104': _('Comercio con titular seguro y titular sin clave de compra segura'),
|
||||
'9218': _('El comercio no permite op. seguras por entrada /operaciones'),
|
||||
'9253': _('Tarjeta no cumple el check-digit'),
|
||||
'9256': _('El comercio no puede realizar preautorizaciones'),
|
||||
'9257': _('Esta tarjeta no permite operativa de preautorizaciones'),
|
||||
'9261': _('Operación detenida por superar el control de restricciones en la entrada al SIS'),
|
||||
'9915': _('A petición del usuario se ha cancelado el pago'),
|
||||
'9997': _('Se está procesando otra transacción en SIS con la misma tarjeta'),
|
||||
'9998': _('Operación en proceso de solicitud de datos de tarjeta'),
|
||||
'9999': _('Operación que ha sido redirigida al emisor a autenticar'),
|
||||
}
|
||||
|
||||
+4
-23
@@ -7,28 +7,9 @@ from shop.models import Product, ProductPrice, Tax
|
||||
|
||||
class CreateProductsMixin:
|
||||
def create_product(
|
||||
self,
|
||||
sku="000001",
|
||||
name="Producto 1",
|
||||
description="Descripción",
|
||||
price=Decimal("10.00"),
|
||||
is_shipping=False,
|
||||
self, sku='000001', name='Producto 1', description='Descripción', price=Decimal('10.00'), is_shipping=False
|
||||
) -> Product:
|
||||
tax, created = Tax.objects.get_or_create(
|
||||
code="IVA",
|
||||
value=21,
|
||||
)
|
||||
product = Product.objects.create(
|
||||
sku=sku,
|
||||
name=name,
|
||||
description=description,
|
||||
is_shipping_method=is_shipping,
|
||||
)
|
||||
ProductPrice.objects.create(
|
||||
price=price,
|
||||
product=product,
|
||||
date=now(),
|
||||
tax=tax,
|
||||
current=True,
|
||||
)
|
||||
tax, created = Tax.objects.get_or_create(code='IVA', value=21)
|
||||
product = Product.objects.create(sku=sku, name=name, description=description, is_shipping_method=is_shipping)
|
||||
ProductPrice.objects.create(price=price, product=product, date=now(), tax=tax, current=True)
|
||||
return product
|
||||
|
||||
@@ -13,11 +13,11 @@ class TestProductImages(TestCase, CreateProductsMixin):
|
||||
self.product = self.create_product()
|
||||
|
||||
def create_image_file(self, size=(768, 768)):
|
||||
image = Image.new("RGB", size, "#ACACAC")
|
||||
image = Image.new('RGB', size, '#ACACAC')
|
||||
|
||||
buffer = BytesIO()
|
||||
image.save(fp=buffer, format="WEBP")
|
||||
file = ContentFile(buffer.getvalue(), name=f"{self.product.slug}.webp")
|
||||
image.save(fp=buffer, format='WEBP')
|
||||
file = ContentFile(buffer.getvalue(), name=f'{self.product.slug}.webp')
|
||||
return file
|
||||
|
||||
def test_product_image_creation(self):
|
||||
|
||||
+84
-116
@@ -22,58 +22,51 @@ User = get_user_model()
|
||||
|
||||
def redsys_response_ok(*args, **kwargs):
|
||||
response = {
|
||||
"Ds_SignatureVersion": "HMAC_SHA256_V1",
|
||||
"Ds_MerchantParameters": "eyJEc19BbW91bnQiOiIxNDUiLCJEc19DdXJyZW5jeSI6Ijk3OCIsIkRzX09yZGVyIjoiMTQ0NjA2ODU4MSIsIkRzX01lcmNoYW50Q29kZSI6Ijk5OTAwODg4MSIsIkRzX1Rlcm1pbmFsIjoiMSIsIkRzX1Jlc3BvbnNlIjoiMDAwMCIsIkRzX0F1dGhvcmlzYXRpb25Db2RlIjoiNTAxNjAyIiwiRHNfVHJhbnNhY3Rpb25UeXBlIjoiMCIsIkRzX1NlY3VyZVBheW1lbnQiOiIwIiwiRHNfTGFuZ3VhZ2UiOiIxIiwiRHNfQ2FyZE51bWJlciI6IjQ1NDg4MSoqKioqKioqMDQiLCJEc19NZXJjaGFudERhdGEiOiIiLCJEc19DYXJkX0NvdW50cnkiOiI3MjQiLCJEc19DYXJkX0JyYW5kIjoiMSJ9",
|
||||
"Ds_Signature": "QVxoXwwp919v7XYjyBjhr1VXozESRosHPb3PDW-rcME=",
|
||||
'Ds_SignatureVersion': 'HMAC_SHA256_V1',
|
||||
'Ds_MerchantParameters': 'eyJEc19BbW91bnQiOiIxNDUiLCJEc19DdXJyZW5jeSI6Ijk3OCIsIkRzX09yZGVyIjoiMTQ0NjA2ODU4MSIsIkRzX01lcmNoYW50Q29kZSI6Ijk5OTAwODg4MSIsIkRzX1Rlcm1pbmFsIjoiMSIsIkRzX1Jlc3BvbnNlIjoiMDAwMCIsIkRzX0F1dGhvcmlzYXRpb25Db2RlIjoiNTAxNjAyIiwiRHNfVHJhbnNhY3Rpb25UeXBlIjoiMCIsIkRzX1NlY3VyZVBheW1lbnQiOiIwIiwiRHNfTGFuZ3VhZ2UiOiIxIiwiRHNfQ2FyZE51bWJlciI6IjQ1NDg4MSoqKioqKioqMDQiLCJEc19NZXJjaGFudERhdGEiOiIiLCJEc19DYXJkX0NvdW50cnkiOiI3MjQiLCJEc19DYXJkX0JyYW5kIjoiMSJ9',
|
||||
'Ds_Signature': 'QVxoXwwp919v7XYjyBjhr1VXozESRosHPb3PDW-rcME=',
|
||||
}
|
||||
|
||||
return Response(response, status_code=200)
|
||||
|
||||
|
||||
def redsys_response_error(*args, **kwargs):
|
||||
response = {"errorCode": "SIS00001"}
|
||||
response = {'errorCode': 'SIS00001'}
|
||||
return Response(response, status_code=200)
|
||||
|
||||
|
||||
class TestRedsysTPV(APITestCase, CreateProductsMixin):
|
||||
def setUp(self):
|
||||
self.tax = Tax.objects.create(
|
||||
code="IVA",
|
||||
value=21,
|
||||
)
|
||||
self.tax = Tax.objects.create(code='IVA', value=21)
|
||||
self.customer = get_user_model().objects.create_user(
|
||||
username="11111111H",
|
||||
first_name="Darth",
|
||||
last_name="Maul",
|
||||
email="darth@maul.com",
|
||||
password="dathomir",
|
||||
username='11111111H', first_name='Darth', last_name='Maul', email='darth@maul.com', password='dathomir'
|
||||
)
|
||||
|
||||
self.customer_shipping_address = CustomerAddress.objects.create(
|
||||
user=self.customer,
|
||||
address="Dathomir",
|
||||
address_town="Dathomir",
|
||||
address_zip="00001",
|
||||
address_state="Dathomir",
|
||||
address_phone="900000000",
|
||||
address='Dathomir',
|
||||
address_town='Dathomir',
|
||||
address_zip='00001',
|
||||
address_state='Dathomir',
|
||||
address_phone='900000000',
|
||||
address_type=CustomerAddress.Types.SHIPPING,
|
||||
)
|
||||
|
||||
self.customer_billing_address = CustomerAddress.objects.create(
|
||||
user=self.customer,
|
||||
address="Dathomir",
|
||||
address_town="Dathomir",
|
||||
address_zip="00001",
|
||||
address_state="Dathomir",
|
||||
address_phone="900000000",
|
||||
address='Dathomir',
|
||||
address_town='Dathomir',
|
||||
address_zip='00001',
|
||||
address_state='Dathomir',
|
||||
address_phone='900000000',
|
||||
address_type=CustomerAddress.Types.BILLING,
|
||||
)
|
||||
self.product = self.create_product()
|
||||
self.order = self.create_order()
|
||||
self.order.calculate_total_from_lines()
|
||||
self.settings = ShopSettings.load()
|
||||
self.settings.merchant_code = "999008881"
|
||||
self.settings.shared_secret = "sq7HjrUOBfKmC576ILgskD5srU870gJ7" # Debug secret
|
||||
self.settings.merchant_code = '999008881'
|
||||
self.settings.shared_secret = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7' # Debug secret
|
||||
self.settings.save()
|
||||
|
||||
def create_order(self):
|
||||
@@ -86,66 +79,53 @@ class TestRedsysTPV(APITestCase, CreateProductsMixin):
|
||||
billing_country=self.customer_billing_address.address_country,
|
||||
)
|
||||
|
||||
l1 = create_order_line_for_product(
|
||||
self.product,
|
||||
quantity=Decimal("1.0"),
|
||||
order=order,
|
||||
)
|
||||
create_order_line_for_product(self.product, quantity=Decimal('1.0'), order=order)
|
||||
return order
|
||||
|
||||
def test_redsys_client(self):
|
||||
amount_to_pay = Decimal("12.10")
|
||||
amount_to_pay = Decimal('12.10')
|
||||
|
||||
client = RedsysClient()
|
||||
merchant_parameters = client._get_merchant_parameters_for_order(
|
||||
self.order,
|
||||
)
|
||||
merchant_parameters = client._get_merchant_parameters_for_order(self.order)
|
||||
|
||||
assert merchant_parameters.get("DS_MERCHANT_ORDER") == self.order.code
|
||||
assert merchant_parameters.get("DS_MERCHANT_AMOUNT") == str(
|
||||
int(amount_to_pay * 100)
|
||||
)
|
||||
assert merchant_parameters.get("DS_MERCHANT_TERMINAL") == self.settings.terminal
|
||||
assert (
|
||||
merchant_parameters.get("DS_MERCHANT_MERCHANTCODE")
|
||||
== self.settings.merchant_code
|
||||
)
|
||||
assert merchant_parameters.get('DS_MERCHANT_ORDER') == self.order.code
|
||||
assert merchant_parameters.get('DS_MERCHANT_AMOUNT') == str(int(amount_to_pay * 100))
|
||||
assert merchant_parameters.get('DS_MERCHANT_TERMINAL') == self.settings.terminal
|
||||
assert merchant_parameters.get('DS_MERCHANT_MERCHANTCODE') == self.settings.merchant_code
|
||||
|
||||
client.get_body_for_order(self.order)
|
||||
|
||||
def test_redsys_webhook(self):
|
||||
redsys_response_data = {
|
||||
"Ds_MerchantCode": "999008881",
|
||||
"Ds_Terminal": "001",
|
||||
"Ds_Order": self.order.code,
|
||||
"Ds_Amount": str(self.order.total * 100),
|
||||
"Ds_Currency": "978",
|
||||
"Ds_Date": "01/01/2024",
|
||||
"Ds_Hour": "00:00",
|
||||
"Ds_SecurePayment": "1",
|
||||
"Ds_Card_Number": "454881******1156",
|
||||
"Ds_Card_Country": "724",
|
||||
"Ds_Response": "0000",
|
||||
"Ds_MerchantData": "",
|
||||
"Ds_TransactionType": "0",
|
||||
"Ds_ConsumerLanguage": "1",
|
||||
"Ds_AuthorisationCode": "182670",
|
||||
"Ds_Card_Brand": "1",
|
||||
"Ds_ProcessedPayMethod": "80",
|
||||
"Ds_ECI": "05",
|
||||
"Ds_Response_Description": "OPERACION AUTORIZADA",
|
||||
'Ds_MerchantCode': '999008881',
|
||||
'Ds_Terminal': '001',
|
||||
'Ds_Order': self.order.code,
|
||||
'Ds_Amount': str(self.order.total * 100),
|
||||
'Ds_Currency': '978',
|
||||
'Ds_Date': '01/01/2024',
|
||||
'Ds_Hour': '00:00',
|
||||
'Ds_SecurePayment': '1',
|
||||
'Ds_Card_Number': '454881******1156',
|
||||
'Ds_Card_Country': '724',
|
||||
'Ds_Response': '0000',
|
||||
'Ds_MerchantData': '',
|
||||
'Ds_TransactionType': '0',
|
||||
'Ds_ConsumerLanguage': '1',
|
||||
'Ds_AuthorisationCode': '182670',
|
||||
'Ds_Card_Brand': '1',
|
||||
'Ds_ProcessedPayMethod': '80',
|
||||
'Ds_ECI': '05',
|
||||
'Ds_Response_Description': 'OPERACION AUTORIZADA',
|
||||
}
|
||||
redsys_response_data_str = json.dumps(redsys_response_data)
|
||||
b64_merchant_params = base64.b64encode(
|
||||
redsys_response_data_str.encode()
|
||||
).decode()
|
||||
b64_merchant_params = base64.b64encode(redsys_response_data_str.encode()).decode()
|
||||
|
||||
response = self.client.post(
|
||||
reverse("shop:webhook", kwargs={"uuid": self.order.uuid}),
|
||||
reverse('shop:webhook', kwargs={'uuid': self.order.uuid}),
|
||||
data={
|
||||
"Ds_MerchantParameters": b64_merchant_params,
|
||||
"Ds_Signature": self.settings.shared_secret,
|
||||
"Ds_SignatureVersion": "HMAC_SHA256_V1",
|
||||
'Ds_MerchantParameters': b64_merchant_params,
|
||||
'Ds_Signature': self.settings.shared_secret,
|
||||
'Ds_SignatureVersion': 'HMAC_SHA256_V1',
|
||||
},
|
||||
)
|
||||
self.order.refresh_from_db()
|
||||
@@ -154,38 +134,36 @@ class TestRedsysTPV(APITestCase, CreateProductsMixin):
|
||||
|
||||
def test_redsys_webhook_payment_error(self):
|
||||
redsys_response_data = {
|
||||
"Ds_MerchantCode": "999008881",
|
||||
"Ds_Terminal": "001",
|
||||
"Ds_Order": self.order.code,
|
||||
"Ds_Amount": "1000",
|
||||
"Ds_Currency": "978",
|
||||
"Ds_Date": "01/01/2024",
|
||||
"Ds_Hour": "00:00",
|
||||
"Ds_SecurePayment": "1",
|
||||
"Ds_Card_Number": "454881******1156",
|
||||
"Ds_Card_Country": "724",
|
||||
"Ds_Response": "0184",
|
||||
"Ds_MerchantData": "",
|
||||
"Ds_TransactionType": "0",
|
||||
"Ds_ConsumerLanguage": "1",
|
||||
"Ds_AuthorisationCode": "182670",
|
||||
"Ds_Card_Brand": "1",
|
||||
"Ds_ProcessedPayMethod": "80",
|
||||
"Ds_ECI": "05",
|
||||
"Ds_Response_Description": "ERROR",
|
||||
'Ds_MerchantCode': '999008881',
|
||||
'Ds_Terminal': '001',
|
||||
'Ds_Order': self.order.code,
|
||||
'Ds_Amount': '1000',
|
||||
'Ds_Currency': '978',
|
||||
'Ds_Date': '01/01/2024',
|
||||
'Ds_Hour': '00:00',
|
||||
'Ds_SecurePayment': '1',
|
||||
'Ds_Card_Number': '454881******1156',
|
||||
'Ds_Card_Country': '724',
|
||||
'Ds_Response': '0184',
|
||||
'Ds_MerchantData': '',
|
||||
'Ds_TransactionType': '0',
|
||||
'Ds_ConsumerLanguage': '1',
|
||||
'Ds_AuthorisationCode': '182670',
|
||||
'Ds_Card_Brand': '1',
|
||||
'Ds_ProcessedPayMethod': '80',
|
||||
'Ds_ECI': '05',
|
||||
'Ds_Response_Description': 'ERROR',
|
||||
}
|
||||
|
||||
redsys_response_data_str = json.dumps(redsys_response_data)
|
||||
b64_merchant_params = base64.b64encode(
|
||||
redsys_response_data_str.encode()
|
||||
).decode()
|
||||
b64_merchant_params = base64.b64encode(redsys_response_data_str.encode()).decode()
|
||||
|
||||
response = self.client.post(
|
||||
reverse("shop:webhook", kwargs={"uuid": self.order.uuid}),
|
||||
reverse('shop:webhook', kwargs={'uuid': self.order.uuid}),
|
||||
data={
|
||||
"Ds_MerchantParameters": b64_merchant_params,
|
||||
"Ds_Signature": self.settings.shared_secret,
|
||||
"Ds_SignatureVersion": "HMAC_SHA256_V1",
|
||||
'Ds_MerchantParameters': b64_merchant_params,
|
||||
'Ds_Signature': self.settings.shared_secret,
|
||||
'Ds_SignatureVersion': 'HMAC_SHA256_V1',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -196,37 +174,27 @@ class TestRedsysTPV(APITestCase, CreateProductsMixin):
|
||||
|
||||
def test_expiry_date(self):
|
||||
now = timezone.now()
|
||||
previous_year = str(now.year - 1).rjust(2, "0")
|
||||
current_month = str(now.month).rjust(2, "0")
|
||||
previous_year = str(now.year - 1).rjust(2, '0')
|
||||
current_month = str(now.month).rjust(2, '0')
|
||||
current_year = str(now.year)[-2:]
|
||||
|
||||
assert not validate_expiry_date("042024")
|
||||
assert not validate_expiry_date(f"{previous_year}{current_month}")
|
||||
assert not validate_expiry_date('042024')
|
||||
assert not validate_expiry_date(f'{previous_year}{current_month}')
|
||||
|
||||
assert validate_expiry_date(f"{current_year}{current_month}")
|
||||
assert validate_expiry_date(f'{current_year}{current_month}')
|
||||
|
||||
@patch("requests.post", redsys_response_ok)
|
||||
@patch('requests.post', redsys_response_ok)
|
||||
def test_redsys_rest_client(self):
|
||||
client = RedsysClient()
|
||||
|
||||
params = client.pay_order_rest(
|
||||
self.order,
|
||||
pan="4548810000000003",
|
||||
expiry_date="122049",
|
||||
cvv2="285",
|
||||
)
|
||||
params = client.pay_order_rest(self.order, pan='4548810000000003', expiry_date='122049', cvv2='285')
|
||||
|
||||
assert params.get("Ds_Order") == "1446068581"
|
||||
assert params.get("Ds_MerchantCode") == self.settings.merchant_code
|
||||
assert params.get('Ds_Order') == '1446068581'
|
||||
assert params.get('Ds_MerchantCode') == self.settings.merchant_code
|
||||
|
||||
@patch("requests.post", redsys_response_error)
|
||||
@patch('requests.post', redsys_response_error)
|
||||
def test_redsys_rest_client_error(self):
|
||||
client = RedsysClient()
|
||||
|
||||
with pytest.raises(RedsysPaymentException):
|
||||
client.pay_order_rest(
|
||||
self.order,
|
||||
pan="4548810000000003",
|
||||
expiry_date="122049",
|
||||
cvv2="285",
|
||||
)
|
||||
client.pay_order_rest(self.order, pan='4548810000000003', expiry_date='122049', cvv2='285')
|
||||
|
||||
+2
-4
@@ -2,9 +2,7 @@ from django.urls import path
|
||||
|
||||
from shop.views import webhook
|
||||
|
||||
app_name = "shop"
|
||||
app_name = 'shop'
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("order/<str:uuid>/webhook/", webhook, name="webhook"),
|
||||
]
|
||||
urlpatterns = [path('order/<str:uuid>/webhook/', webhook, name='webhook')]
|
||||
|
||||
+33
-52
@@ -12,17 +12,7 @@ from django.utils import timezone
|
||||
from django.utils.text import gettext_lazy as _
|
||||
|
||||
from shop.exceptions import RedsysPaymentException, RedsysValidationException
|
||||
from shop.models import (
|
||||
Cart,
|
||||
CartItem,
|
||||
Order,
|
||||
OrderLine,
|
||||
Payment,
|
||||
Product,
|
||||
ProductBatch,
|
||||
ProductPrice,
|
||||
ShippingMethod,
|
||||
)
|
||||
from shop.models import Cart, CartItem, Order, OrderLine, Payment, Product, ProductBatch, ProductPrice, ShippingMethod
|
||||
from shop.settings import ERROR_CODES
|
||||
from shop.signals import clear_cart
|
||||
|
||||
@@ -32,7 +22,7 @@ User = get_user_model()
|
||||
def create_order_line_for_product(product: Product, quantity: Decimal, order: Order):
|
||||
price = product.prices.last()
|
||||
base_total = round(price.price * quantity, 2)
|
||||
tax_value = price.tax.value / Decimal("100")
|
||||
tax_value = price.tax.value / Decimal('100')
|
||||
taxes = round(base_total * tax_value, 2)
|
||||
|
||||
return OrderLine.objects.create(
|
||||
@@ -54,11 +44,11 @@ def create_order(
|
||||
billing_state: str,
|
||||
billing_country: str,
|
||||
billing_zip: str,
|
||||
shipping_address: str = "",
|
||||
shipping_city: str = "",
|
||||
shipping_state: str = "",
|
||||
shipping_country: str = "",
|
||||
shipping_zip: str = "",
|
||||
shipping_address: str = '',
|
||||
shipping_city: str = '',
|
||||
shipping_state: str = '',
|
||||
shipping_country: str = '',
|
||||
shipping_zip: str = '',
|
||||
) -> Order:
|
||||
order = Order.objects.create(
|
||||
user=customer,
|
||||
@@ -87,29 +77,29 @@ def delete_product_batch(batch: ProductBatch):
|
||||
def create_order_from_cart(
|
||||
cart: Cart,
|
||||
shipping_method: ShippingMethod,
|
||||
billing_address_full_name="",
|
||||
billing_address_address="",
|
||||
billing_address_town="",
|
||||
billing_address_state="",
|
||||
billing_address_country="",
|
||||
billing_address_zip="",
|
||||
shipping_address_full_name="",
|
||||
shipping_address_address="",
|
||||
shipping_address_town="",
|
||||
shipping_address_state="",
|
||||
shipping_address_country="",
|
||||
shipping_address_zip="",
|
||||
shipping_address_phone="",
|
||||
email="",
|
||||
billing_address_full_name='',
|
||||
billing_address_address='',
|
||||
billing_address_town='',
|
||||
billing_address_state='',
|
||||
billing_address_country='',
|
||||
billing_address_zip='',
|
||||
shipping_address_full_name='',
|
||||
shipping_address_address='',
|
||||
shipping_address_town='',
|
||||
shipping_address_state='',
|
||||
shipping_address_country='',
|
||||
shipping_address_zip='',
|
||||
shipping_address_phone='',
|
||||
email='',
|
||||
):
|
||||
order = Order.objects.create(
|
||||
billing_address=f"{billing_address_full_name} {billing_address_address}",
|
||||
billing_address=f'{billing_address_full_name} {billing_address_address}',
|
||||
billing_city=billing_address_town,
|
||||
billing_state=billing_address_state,
|
||||
billing_country=billing_address_country,
|
||||
billing_zip=billing_address_zip,
|
||||
contact_phone=shipping_address_phone,
|
||||
shipping_address=f"{shipping_address_address} {shipping_address_full_name}",
|
||||
shipping_address=f'{shipping_address_address} {shipping_address_full_name}',
|
||||
shipping_city=shipping_address_town,
|
||||
shipping_state=shipping_address_state,
|
||||
shipping_country=shipping_address_country,
|
||||
@@ -174,9 +164,7 @@ def compute_signature(salt, payload, key):
|
||||
"""
|
||||
b64_key = base64.b64decode(key)
|
||||
|
||||
des3 = pyDes.triple_des(
|
||||
b64_key, mode=pyDes.CBC, IV="\0" * 8, pad="\0", padmode=pyDes.PAD_NORMAL
|
||||
)
|
||||
des3 = pyDes.triple_des(b64_key, mode=pyDes.CBC, IV='\0' * 8, pad='\0', padmode=pyDes.PAD_NORMAL)
|
||||
pepper = des3.encrypt(str(salt))
|
||||
|
||||
payload_hash = hmac.new(pepper, payload.encode(), hashlib.sha256).digest()
|
||||
@@ -211,27 +199,25 @@ def validate_payment_for_order(request, order: Order) -> Decimal:
|
||||
"""
|
||||
data = request.POST
|
||||
|
||||
merchant_parameters = data.get("Ds_MerchantParameters")
|
||||
merchant_parameters = data.get('Ds_MerchantParameters')
|
||||
|
||||
if not merchant_parameters:
|
||||
raise RedsysValidationException(
|
||||
_("No se ha recibido ningún valor para Ds_MerchantParameters")
|
||||
)
|
||||
raise RedsysValidationException(_('No se ha recibido ningún valor para Ds_MerchantParameters'))
|
||||
|
||||
merchant_params = decode_b64_string(merchant_parameters)
|
||||
result = json.loads(merchant_params)
|
||||
|
||||
order_code = result.get("Ds_Order")
|
||||
order_code = result.get('Ds_Order')
|
||||
assert order_code == order.code
|
||||
|
||||
status_code = result.get("Ds_Response")
|
||||
status_code = result.get('Ds_Response')
|
||||
|
||||
if int(status_code) > 100:
|
||||
reason = ERROR_CODES.get(status_code, _("Error no tipificado"))
|
||||
reason = ERROR_CODES.get(status_code, _('Error no tipificado'))
|
||||
|
||||
raise RedsysPaymentException(_(f"No se ha realizado el pago. Motivo: {reason}"))
|
||||
raise RedsysPaymentException(_(f'No se ha realizado el pago. Motivo: {reason}'))
|
||||
|
||||
amount = Decimal(result.get("Ds_Amount")) / 100
|
||||
amount = Decimal(result.get('Ds_Amount')) / 100
|
||||
|
||||
return amount
|
||||
|
||||
@@ -268,9 +254,7 @@ def validate_expiry_date(expiry_date: str):
|
||||
def update_order_payment_status(order: Order):
|
||||
if order.amount_paid >= order.total:
|
||||
order.status = Order.Statuses.STATUS_PAID
|
||||
elif order.status == Order.Statuses.STATUS_PAID and order.amount_paid == Decimal(
|
||||
"0.00"
|
||||
):
|
||||
elif order.status == Order.Statuses.STATUS_PAID and order.amount_paid == Decimal('0.00'):
|
||||
order.status = Order.Statuses.STATUS_RETURNED
|
||||
else:
|
||||
order.status = Order.Statuses.STATUS_PENDING
|
||||
@@ -286,10 +270,7 @@ def delete_cart_items_from_order(order):
|
||||
def add_payment_to_order(order: Order, amount):
|
||||
with transaction.atomic():
|
||||
payment = Payment.objects.create(
|
||||
amount=amount,
|
||||
order=order,
|
||||
user=order.user,
|
||||
method=Payment.MethodChoices.REDSYS,
|
||||
amount=amount, order=order, user=order.user, method=Payment.MethodChoices.REDSYS
|
||||
)
|
||||
order.amount_paid += payment.amount
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ def webhook(request, uuid):
|
||||
add_payment_to_order(order, amount_paid)
|
||||
|
||||
return HttpResponse(status=200)
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
order.status = Order.Statuses.STATUS_ERROR
|
||||
order.save()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user