work on product csv loading

This commit is contained in:
Sam
2021-03-02 13:53:48 +00:00
parent 8bae68907e
commit 4a0a9c3788
3 changed files with 28 additions and 23 deletions

View File

@@ -421,6 +421,9 @@ class LoadCoopProductsTestCase(APITestCase):
# create company # create company
company = CompanyFactory(creator=self.user) company = CompanyFactory(creator=self.user)
# link with user
self.user.company = company
self.user.save()
# read csv file # read csv file
files = {'csv_file': open(self.csv_path,'rt')} files = {'csv_file': open(self.csv_path,'rt')}
@@ -431,8 +434,9 @@ class LoadCoopProductsTestCase(APITestCase):
# send in request # send in request
response = self.client.post(self.endpoint, files) response = self.client.post(self.endpoint, files)
import ipdb; ipdb.set_trace()
# check re sponse # check response
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
# check for object creation # check for object creation
self.assertEquals(5, self.model.objects.count()) self.assertEquals(5, self.model.objects.count())

View File

@@ -184,7 +184,6 @@ def product_loader(csv_reader, user, company=None):
# create historysync instance # create historysync instance
history = HistorySync.objects.create(company=company, sync_date=datetime.datetime.now()) history = HistorySync.objects.create(company=company, sync_date=datetime.datetime.now())
for row in csv_reader: for row in csv_reader:
# trim strings # trim strings
for key in row: for key in row:
@@ -246,6 +245,7 @@ def product_loader(csv_reader, user, company=None):
counter += 1 counter += 1
except Exception as e: except Exception as e:
logging.error(f"Could not parse {counter}: {str(e)}") logging.error(f"Could not parse {counter}: {str(e)}")
import ipdb; ipdb.set_trace()
history.quantity = counter history.quantity = counter
history.save() history.save()

View File

@@ -62,30 +62,31 @@ def my_products(request):
@api_view(['POST',]) @api_view(['POST',])
@permission_classes([IsAuthenticated,]) @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
Authenticated user must have a related company Authenticated user must have a related company
""" """
try: # check company linked to user
# check company linked to user if request.user.company is None:
if request.user.company is None: return Response({"errors":{"details": "Your user has no company to add products to"}}, status=status.HTTP_406_NOT_ACCEPTABLE)
return Response({"errors":{"details": "Your user has no company to add products to"}})
csv_file = request.FILES['csv_file'] try:
if csv_file.name.endswith('.csv') is not True: csv_file = request.FILES['csv_file']
logging.error(f"File {csv_file.name} is not a CSV file") if csv_file.name.endswith('.csv') is not True:
return Response({"errors":{"details": "File is not CSV type"}}) logging.error(f"File {csv_file.name} is not a CSV file")
return Response({"errors":{"details": "File is not CSV type"}})
logging.info(f"Reading contents of {csv_file.name}") logging.info(f"Reading contents of {csv_file.name}")
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=',')
count = product_loader(csv_reader, request.user)
if count is None: count = product_loader(csv_reader, request.user)
return Response({"errors": {"details": "Authenticated user is not related to any company"}}, status=status.HTTP_406_NOT_ACCEPTABLE) if count is None:
return Response(f"{count} products registered for {request.user.company.company_name}") return Response({"errors": {"details": "Authenticated user is not related to any company"}}, status=status.HTTP_406_NOT_ACCEPTABLE)
except Exception as e: return Response(f"{count} products registered for {request.user.company.company_name}")
return Response({"errors": {"details": str(type(e))}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Exception as e:
return Response({"errors": {"details": str(type(e))}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@api_view(['GET',]) # include allowed methods @api_view(['GET',]) # include allowed methods