history sync created when adding products from csv

This commit is contained in:
Sam
2021-02-04 10:56:34 +00:00
parent 0107d86a27
commit 89b68dd516
4 changed files with 22 additions and 9 deletions

View File

@@ -1,5 +1,6 @@
import logging
import csv
import datetime
from django.shortcuts import render
from django.conf import settings
@@ -16,6 +17,7 @@ import requests
from products.models import Product
from products.serializers import ProductSerializer
from companies.models import Company
from history.models import HistorySync
from back_latienda.permissions import IsCreator
@@ -43,7 +45,7 @@ def my_products(request):
@api_view(['POST',])
@permission_classes([IsAdminUser,])
@permission_classes([IsAuthenticated,])
def load_coop_products(request):
"""Read CSV file being received
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()
csv_reader = csv.DictReader(decoded_file, delimiter=',')
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:
if '' in (row['nombre-producto'], row['descripcion'], row['precio'], row['categoria']):
@@ -81,7 +92,6 @@ def load_coop_products(request):
else:
new_image = None
# assemble instance data
product_data = {
'id': None if row['id'].strip()=='' else row['id'].strip(),
'company': Company.objects.filter(creator=request.user).first(),
@@ -97,6 +107,8 @@ def load_coop_products(request):
'tags': row['tags'].strip(),
'category': row['categoria'].strip(),
'identifiers': row['identificadores'].strip(),
'history': history,
'creator': request.user,
}
Product.objects.create(**product_data)
@@ -121,7 +133,6 @@ def product_search(request):
chunks = query_string.split(' ')
result_set = set()
# import ipdb; ipdb.set_trace()
for chunk in chunks:
# search in name
products = Product.objects.filter(name=chunk)