From ed5d3f447ac6c4d5f554f46b2dd823e9cf865529 Mon Sep 17 00:00:00 2001
From: Mono Mono <monomono@disroot.org>
Date: Sat, 29 Jun 2024 16:23:47 -0500
Subject: [PATCH] fix: creacion repetida de categoria de productos.

---
 .../0010_alter_productcategory_name.py        | 18 ++++++++++
 tienda_ilusion/don_confiao/models.py          |  2 +-
 tienda_ilusion/don_confiao/test_products.py   | 35 ++++++++++++++-----
 tienda_ilusion/don_confiao/views.py           |  4 ++-
 4 files changed, 49 insertions(+), 10 deletions(-)
 create mode 100644 tienda_ilusion/don_confiao/migrations/0010_alter_productcategory_name.py

diff --git a/tienda_ilusion/don_confiao/migrations/0010_alter_productcategory_name.py b/tienda_ilusion/don_confiao/migrations/0010_alter_productcategory_name.py
new file mode 100644
index 0000000..c400651
--- /dev/null
+++ b/tienda_ilusion/don_confiao/migrations/0010_alter_productcategory_name.py
@@ -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),
+        ),
+    ]
diff --git a/tienda_ilusion/don_confiao/models.py b/tienda_ilusion/don_confiao/models.py
index cdd9bc7..dc51642 100644
--- a/tienda_ilusion/don_confiao/models.py
+++ b/tienda_ilusion/don_confiao/models.py
@@ -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
diff --git a/tienda_ilusion/don_confiao/test_products.py b/tienda_ilusion/don_confiao/test_products.py
index 6743a5e..89dc1e4 100644
--- a/tienda_ilusion/don_confiao/test_products.py
+++ b/tienda_ilusion/don_confiao/test_products.py
@@ -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"])
diff --git a/tienda_ilusion/don_confiao/views.py b/tienda_ilusion/don_confiao/views.py
index bca21a5..a542a51 100644
--- a/tienda_ilusion/don_confiao/views.py
+++ b/tienda_ilusion/don_confiao/views.py
@@ -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()