history sync created when adding products from csv
This commit is contained in:
@@ -2,6 +2,7 @@ import csv
|
|||||||
import logging
|
import logging
|
||||||
import json
|
import json
|
||||||
import io
|
import io
|
||||||
|
import datetime
|
||||||
|
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
@@ -122,7 +123,6 @@ def load_coop_managers(request):
|
|||||||
'shop': bool(row['es-tienda'].strip()),
|
'shop': bool(row['es-tienda'].strip()),
|
||||||
'shop_link': row['url'].strip(),
|
'shop_link': row['url'].strip(),
|
||||||
}
|
}
|
||||||
# import ipdb; ipdb.set_trace()
|
|
||||||
coop = Company.objects.create(**coop_data)
|
coop = Company.objects.create(**coop_data)
|
||||||
logging.info(f"Created Coop: {coop_data}")
|
logging.info(f"Created Coop: {coop_data}")
|
||||||
coop_counter += 1
|
coop_counter += 1
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class Product(models.Model):
|
|||||||
created = models.DateTimeField('date of creation', auto_now_add=True)
|
created = models.DateTimeField('date of creation', auto_now_add=True)
|
||||||
updated = models.DateTimeField('date last update', auto_now=True)
|
updated = models.DateTimeField('date last update', auto_now=True)
|
||||||
creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='product')
|
creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='product')
|
||||||
# history = models.FoiregnKey('history.History', on_delete=models.DO_NOTHING, null=True)
|
history = models.ForeignKey('history.HistorySync', on_delete=models.DO_NOTHING, null=True, related_name='product')
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"{self.name} / {self.sku}"
|
return f"{self.name} / {self.sku}"
|
||||||
|
|||||||
@@ -283,15 +283,18 @@ class LoadCoopProductsTestCase(APITestCase):
|
|||||||
# test CSV file path
|
# test CSV file path
|
||||||
self.csv_path = 'datasets/test_products.csv'
|
self.csv_path = 'datasets/test_products.csv'
|
||||||
|
|
||||||
def test_admin_can_load_csv(self):
|
def test_auth_user_with_company_can_load_csv(self):
|
||||||
# delete existing instances
|
# delete existing instances
|
||||||
self.model.objects.all().delete()
|
self.model.objects.all().delete()
|
||||||
|
|
||||||
|
# create company
|
||||||
|
company = CompanyFactory(creator=self.user)
|
||||||
|
|
||||||
# read csv file
|
# read csv file
|
||||||
files = {'csv_file': open(self.csv_path,'rt')}
|
files = {'csv_file': open(self.csv_path,'rt')}
|
||||||
|
|
||||||
# Authenticate
|
# Authenticate
|
||||||
token = get_tokens_for_user(self.admin_user)
|
token = get_tokens_for_user(self.user)
|
||||||
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}")
|
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}")
|
||||||
|
|
||||||
# send in request
|
# send in request
|
||||||
@@ -302,7 +305,7 @@ class LoadCoopProductsTestCase(APITestCase):
|
|||||||
# check for object creation
|
# check for object creation
|
||||||
self.assertEquals(5, self.model.objects.count())
|
self.assertEquals(5, self.model.objects.count())
|
||||||
|
|
||||||
def test_auth_user_cannot_load_csv(self):
|
def test_auth_user_with_no_company_cannot_load_csv(self):
|
||||||
# delete existing instances
|
# delete existing instances
|
||||||
self.model.objects.all().delete()
|
self.model.objects.all().delete()
|
||||||
|
|
||||||
@@ -364,7 +367,6 @@ class ProductSearchTest(TestCase):
|
|||||||
url = f"{self.endpoint}?query_string={query_string}"
|
url = f"{self.endpoint}?query_string={query_string}"
|
||||||
# send in request
|
# send in request
|
||||||
response = self.client.get(url)
|
response = self.client.get(url)
|
||||||
import ipdb; ipdb.set_trace()
|
|
||||||
|
|
||||||
# check re sponse
|
# check re sponse
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import logging
|
import logging
|
||||||
import csv
|
import csv
|
||||||
|
import datetime
|
||||||
|
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@@ -16,6 +17,7 @@ import requests
|
|||||||
from products.models import Product
|
from products.models import Product
|
||||||
from products.serializers import ProductSerializer
|
from products.serializers import ProductSerializer
|
||||||
from companies.models import Company
|
from companies.models import Company
|
||||||
|
from history.models import HistorySync
|
||||||
|
|
||||||
from back_latienda.permissions import IsCreator
|
from back_latienda.permissions import IsCreator
|
||||||
|
|
||||||
@@ -43,7 +45,7 @@ def my_products(request):
|
|||||||
|
|
||||||
|
|
||||||
@api_view(['POST',])
|
@api_view(['POST',])
|
||||||
@permission_classes([IsAdminUser,])
|
@permission_classes([IsAuthenticated,])
|
||||||
def load_coop_products(request):
|
def load_coop_products(request):
|
||||||
"""Read CSV file being received
|
"""Read CSV file being received
|
||||||
Parse it to create products for related Company
|
Parse it to create products for related Company
|
||||||
@@ -58,6 +60,15 @@ def load_coop_products(request):
|
|||||||
decoded_file = csv_file.read().decode('utf-8').splitlines()
|
decoded_file = csv_file.read().decode('utf-8').splitlines()
|
||||||
csv_reader = csv.DictReader(decoded_file, delimiter=',')
|
csv_reader = csv.DictReader(decoded_file, delimiter=',')
|
||||||
counter = 0
|
counter = 0
|
||||||
|
# get company linked to user
|
||||||
|
company_qs = Company.objects.filter(creator=request.user)
|
||||||
|
|
||||||
|
if company_qs:
|
||||||
|
company = company_qs.first()
|
||||||
|
else:
|
||||||
|
return Response({"errors":{"details": "Your user has no company to add products to"}})
|
||||||
|
# create historysync instance
|
||||||
|
history = HistorySync.objects.create(company=company, sync_date=datetime.datetime.now(), quantity=len(decoded_file))
|
||||||
|
|
||||||
for row in csv_reader:
|
for row in csv_reader:
|
||||||
if '' in (row['nombre-producto'], row['descripcion'], row['precio'], row['categoria']):
|
if '' in (row['nombre-producto'], row['descripcion'], row['precio'], row['categoria']):
|
||||||
@@ -81,7 +92,6 @@ def load_coop_products(request):
|
|||||||
else:
|
else:
|
||||||
new_image = None
|
new_image = None
|
||||||
# assemble instance data
|
# assemble instance data
|
||||||
|
|
||||||
product_data = {
|
product_data = {
|
||||||
'id': None if row['id'].strip()=='' else row['id'].strip(),
|
'id': None if row['id'].strip()=='' else row['id'].strip(),
|
||||||
'company': Company.objects.filter(creator=request.user).first(),
|
'company': Company.objects.filter(creator=request.user).first(),
|
||||||
@@ -97,6 +107,8 @@ def load_coop_products(request):
|
|||||||
'tags': row['tags'].strip(),
|
'tags': row['tags'].strip(),
|
||||||
'category': row['categoria'].strip(),
|
'category': row['categoria'].strip(),
|
||||||
'identifiers': row['identificadores'].strip(),
|
'identifiers': row['identificadores'].strip(),
|
||||||
|
'history': history,
|
||||||
|
'creator': request.user,
|
||||||
}
|
}
|
||||||
|
|
||||||
Product.objects.create(**product_data)
|
Product.objects.create(**product_data)
|
||||||
@@ -121,7 +133,6 @@ def product_search(request):
|
|||||||
chunks = query_string.split(' ')
|
chunks = query_string.split(' ')
|
||||||
|
|
||||||
result_set = set()
|
result_set = set()
|
||||||
# import ipdb; ipdb.set_trace()
|
|
||||||
for chunk in chunks:
|
for chunk in chunks:
|
||||||
# search in name
|
# search in name
|
||||||
products = Product.objects.filter(name=chunk)
|
products = Product.objects.filter(name=chunk)
|
||||||
|
|||||||
Reference in New Issue
Block a user