133 lines
4.4 KiB
Python
133 lines
4.4 KiB
Python
import csv
|
|
import logging
|
|
import json
|
|
import io
|
|
|
|
from django.shortcuts import render
|
|
from django.http import HttpResponse
|
|
from django.contrib.auth import get_user_model
|
|
|
|
from rest_framework import status
|
|
from rest_framework import viewsets
|
|
from rest_framework.response import Response
|
|
from rest_framework.permissions import IsAdminUser
|
|
from rest_framework.generics import UpdateAPIView
|
|
from rest_framework.decorators import api_view, permission_classes
|
|
|
|
from companies.models import Company
|
|
|
|
from . import models
|
|
from . import serializers
|
|
|
|
from back_latienda.permissions import CustomUserPermissions, YourOwnUserPermissions
|
|
|
|
|
|
User = get_user_model()
|
|
|
|
# Create your views here.
|
|
|
|
logging.basicConfig(
|
|
filename='logs/csv-load.log',
|
|
filemode='w',
|
|
format='%(levelname)s:%(message)s',
|
|
level=logging.INFO,
|
|
)
|
|
|
|
|
|
class CustomUserViewSet(viewsets.ModelViewSet):
|
|
|
|
model = models.CustomUser
|
|
# serializer_class = serializers.CustomUserSerializer
|
|
serializer_class = serializers.CustomUserReadSerializer
|
|
write_serializer_class =serializers.CustomUserWriteSerializer
|
|
model_name = 'custom_user'
|
|
queryset = models.CustomUser.objects.all()
|
|
permission_classes = [CustomUserPermissions,]
|
|
|
|
def create(self, request):
|
|
"""
|
|
Create Instance
|
|
"""
|
|
try:
|
|
serializer = self.write_serializer_class(
|
|
data=request.data,
|
|
)
|
|
if serializer.is_valid():
|
|
# save model instance data
|
|
password = serializer.validated_data.pop('password')
|
|
instance = self.model(**serializer.validated_data)
|
|
instance.set_password(password)
|
|
instance.save()
|
|
|
|
return Response(self.serializer_class(
|
|
instance, many=False, context={'request': request}).data,
|
|
status=status.HTTP_201_CREATED)
|
|
else:
|
|
return Response(
|
|
serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)
|
|
except Exception as e:
|
|
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
|
|
|
|
|
class ChangeUserPasswordView(UpdateAPIView):
|
|
|
|
model = models.CustomUser
|
|
queryset = model.objects.all()
|
|
permission_classes = (YourOwnUserPermissions,)
|
|
serializer_class = serializers.ChangePasswordSerializer
|
|
|
|
|
|
class UpdateUserView(UpdateAPIView):
|
|
|
|
model = models.CustomUser
|
|
queryset = model.objects.all()
|
|
permission_classes = (YourOwnUserPermissions,)
|
|
serializer_class = serializers.UpdateUserSerializer
|
|
|
|
|
|
@api_view(['POST',])
|
|
@permission_classes([IsAdminUser,])
|
|
def load_coop_managers(request):
|
|
"""Read CSV file being received
|
|
Parse it to create users and related companies
|
|
"""
|
|
try:
|
|
csv_file = request.FILES['csv_file']
|
|
if csv_file.name.endswith('.csv') is not True:
|
|
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}")
|
|
decoded_file = csv_file.read().decode('utf-8').splitlines()
|
|
csv_reader = csv.DictReader(decoded_file, delimiter=',')
|
|
coop_counter = 0
|
|
user_counter = 0
|
|
for row in csv_reader:
|
|
if '' in (row['cif'], row['nombre-coop'], row['email']):
|
|
logging.error(f"Required data missing: {row}")
|
|
continue
|
|
try:
|
|
coop_data = {
|
|
'cif': row['cif'].strip(),
|
|
'company_name': row['nombre-coop'].strip(),
|
|
'short_name': row['nombre-corto'].strip(),
|
|
'shop': bool(row['es-tienda'].strip()),
|
|
'shop_link': row['url'].strip(),
|
|
}
|
|
# import ipdb; ipdb.set_trace()
|
|
coop = Company.objects.create(**coop_data)
|
|
logging.info(f"Created Coop: {coop_data}")
|
|
coop_counter += 1
|
|
|
|
coop_user = User.objects.create_user(email=row['email'], company=coop, role='COOP_MANAGER')
|
|
logging.info(f"Created User: {coop_user}")
|
|
# TODO: send confirmation email
|
|
user_counter += 1
|
|
except Exception as e:
|
|
logging.error(f"Could not parse {row}")
|
|
|
|
return Response()
|
|
except Exception as e:
|
|
return Response({"errors": {"details": str(type(e))}})
|
|
|