fix: creacion repetida de categoria de productos.

This commit is contained in:
Mono Mono 2024-06-29 16:23:47 -05:00
parent 252720b324
commit ed5d3f447a
4 changed files with 49 additions and 10 deletions

View File

@ -0,0 +1,18 @@
# Generated by Django 5.0.6 on 2024-06-29 21:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('don_confiao', '0009_productcategory_product'),
]
operations = [
migrations.AlterField(
model_name='productcategory',
name='name',
field=models.CharField(max_length=100, unique=True),
),
]

View File

@ -21,7 +21,7 @@ class MeasuringUnits(models.TextChoices):
UNIT = 'UNIT', _('Unit')
class ProductCategory(models.Model):
name = models.CharField(max_length=100)
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name

View File

@ -3,6 +3,7 @@ from django.contrib.auth.models import AnonymousUser, User
from django.conf import settings
from .views import import_products, products
from .models import ProductCategory
import os
import json
@ -12,19 +13,37 @@ class TestProducts(TestCase):
self.client = Client()
def test_import_products(self):
self._import_csv()
all_products = self._get_products()
self.assertEqual(
len(all_products),
3
)
def test_import_products_with_categories(self):
self._import_csv()
all_products = self._get_products()
self.assertIn("Aceites", all_products[0]["categories"])
def test_don_repeat_categories_on_import(self):
self._import_csv()
categories_on_csv = ["Cafes", "Alimentos", "Aceites"]
categories = ProductCategory.objects.all()
self.assertCountEqual(
[c.name for c in categories],
categories_on_csv
)
def _get_products(self):
products_response = self.client.get("/don_confiao/productos")
return json.loads(products_response.content.decode('utf-8'))
def _import_csv(self, csv_file='example_products.csv'):
app_name = "don_confiao"
app_dir = os.path.join(settings.BASE_DIR, app_name)
example_csv = os.path.join(app_dir, 'example_products.csv')
products_in_example = 3
with open(example_csv, 'rb') as csv:
self.client.post(
"/don_confiao/importar_productos",
{"csv_file": csv}
)
products_response = self.client.get("/don_confiao/productos")
all_products = json.loads(products_response.content.decode('utf-8'))
self.assertEqual(
len(all_products),
products_in_example
)
self.assertIn("Aceites", all_products[0]["categories"])

View File

@ -65,9 +65,11 @@ def handle_import_products_file(csv_file):
product.measuring_unit = row['unidad']
product.save()
categories = [n.strip for n in row["categorias"].split("&")]
categories = [n.strip() for n in row["categorias"].split("&")]
for category in categories:
category_model, _ = ProductCategory.objects.get_or_create(
name=category
)
category_model.save()
product.categories.add(category_model)
product.save()