Skip to content

Instantly share code, notes, and snippets.

@trongdth
Created November 21, 2019 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trongdth/f6eb7f4e6f9cac5020e414232c2498a5 to your computer and use it in GitHub Desktop.
Save trongdth/f6eb7f4e6f9cac5020e414232c2498a5 to your computer and use it in GitHub Desktop.
from django.utils import translation
from customer import utility
from rest_framework.decorators import api_view
from api.models import (Customer)
from rest_framework.parsers import JSONParser
from rest_framework import status
from django.http import JsonResponse
from .serializers import (
CustomerSerializer,
)
from api.enum import (Status)
from django.utils.translation import ugettext as _
from django.db import connection
@api_view(['POST'])
def save(request):
response_data = {}
request_object = JSONParser().parse(request)
translation.activate(request.META.get('HTTP_X_LOCAL'))
if not request_object.__contains__('name') or not request_object['name']:
response_data['message'] = 'Please enter name'
return JsonResponse(response_data, status=status.HTTP_400_BAD_REQUEST)
if request_object.__contains__('id') and request_object['id']:
customer = utility.get_object_by_id(Customer, request_object['id'])
if not customer:
response_data['message'] = _('Customer Not Available')
return JsonResponse(response_data, status=status.HTTP_400_BAD_REQUEST)
if request_object.__contains__('email') and request_object['email']:
exist_customer_email = utility.get_customer_by_email_client(request_object['email'], request.user.client_id)
if exist_customer_email and exist_customer_email.id != customer.id:
response_data['message'] = _('Customer email already exists')
return JsonResponse(response_data, status=status.HTTP_400_BAD_REQUEST)
if request_object.__contains__('ip_address') and request_object['ip_address']:
exist_customer_ip_address = utility.get_customer_by_ip_address_client(
request_object['ip_address'],
request.user.client_id)
if exist_customer_ip_address and exist_customer_ip_address.id != customer.id:
response_data['message'] = _('Customer ip address already exists')
return JsonResponse(response_data, status=status.HTTP_400_BAD_REQUEST)
else:
if request_object.__contains__('email') and request_object['email']:
exist_customer_email = utility.get_customer_by_email_client(request_object['email'], request.user.client_id)
if exist_customer_email:
response_data['message'] = _('Customer email already exists')
return JsonResponse(response_data, status=status.HTTP_400_BAD_REQUEST)
if request_object.__contains__('ip_address') and request_object['ip_address']:
exist_customer_ip_address = utility.get_customer_by_ip_address_client(
request_object['ip_address'],
request.user.client_id)
if exist_customer_ip_address:
response_data['message'] = _('Customer ip address already exists')
return JsonResponse(response_data, status=status.HTTP_400_BAD_REQUEST)
customer = Customer()
if request_object.__contains__('name') and request_object['name']:
customer.name = request_object['name']
if request_object.__contains__('email') and request_object['email']:
customer.email = request_object['email']
if request_object.__contains__('phone_number'):
customer.phone_number = request_object['phone_number']
if request_object.__contains__('notes') and request_object['notes']:
customer.notes = request_object["notes"]
if request_object.__contains__('ip_address') and request_object['ip_address']:
customer.ip_address = request_object["ip_address"]
customer.client_id = request.user.client_id
customer.status = Status.ACTIVE.name
customer.created_by = request.user.id
customer.save()
if request_object.__contains__('id') and request_object['id']:
response_data['message'] = _('Successful updated')
else:
response_data['message'] = _('Successful created')
response_data['id'] = customer.id
sql = ""
sql += "SELECT count(*) from sale WHERE customer_id = '" + str(customer.id) + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' GROUP BY customer_id"
cursor1 = connection.cursor()
cursor1.execute(sql)
total_visit = cursor1.fetchone()
cursor1.close()
query = ""
query += "SELECT created_at from sale WHERE customer_id = '" + str(customer.id) + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' ORDER BY created_at DESC LIMIT 1"
cursor2 = connection.cursor()
cursor2.execute(query)
last_visit = cursor2.fetchone()
cursor2.close()
if total_visit:
response_data['total_visit'] = total_visit[0]
if last_visit:
response_data['last_visit'] = last_visit[0]
return JsonResponse(response_data, status=status.HTTP_201_CREATED)
@api_view(['GET'])
def get_list(request):
queryset = Customer.objects.filter(status=Status.ACTIVE.name, client_id=request.user.client_id).values()
result = []
customer_list = []
for visit in queryset:
sql = ""
sql += "SELECT count(*) from sale WHERE customer_id = '" + str(visit['id']) + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' GROUP BY customer_id"
cursor1 = connection.cursor()
cursor1.execute(sql)
total_visit = cursor1.fetchone()
cursor1.close()
query = ""
query += "SELECT created_at from sale WHERE customer_id = '" + visit['id'] + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' ORDER BY created_at DESC LIMIT 1"
cursor2 = connection.cursor()
cursor2.execute(query)
last_visit = cursor2.fetchone()
cursor2.close()
serializer = CustomerSerializer(visit)
data = serializer.data
response_object = {}
response_object = data
if total_visit:
response_object['total_visit'] = total_visit[0]
if last_visit:
response_object['last_visit'] = last_visit[0]
result.append(response_object)
for customer in result:
data = CustomerSerializer(customer)
customer_list.append(data.data)
return JsonResponse({"list": customer_list})
@api_view(['GET'])
def get_list_back_office(request, *args, **kwargs):
page = kwargs['page_no']
sort_by = request.GET.get("sort_by")
order_by = request.GET.get("order_by")
if int(page) > 0:
offset = ((int(page) - 1) * int(kwargs['row_per_page']))
if not offset:
offset = 0
result = []
query = "SELECT d.id, d.name, d.email, d.phone_number, d.notes, d.status, d.created_by," \
" d.client_id FROM customer d " \
"WHERE d.status = '" + Status.ACTIVE.name + "' AND d.client_id = '"+str(request.user.client_id) + \
"'"
if request.GET.get('search'):
query += " AND (d.name like '%" + request.GET.get('search') + "%' " \
" OR d.email like '%" + request.GET.get('search') + "%' " \
" OR d.phone_number like '%" + request.GET.get('search') + "%' )"
if sort_by and order_by:
query += " order by d." + sort_by + " " + order_by
else:
query += " order by d.created_at DESC "
if page:
query += " limit " + str(offset) + ", " + str(kwargs['row_per_page'])
customers = utility.sql_select(query)
customer_list = []
for visit in customers:
sql = ""
sql += "SELECT count(*) from sale WHERE customer_id = '" + str(visit['id']) + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' GROUP BY customer_id"
cursor1 = connection.cursor()
cursor1.execute(sql)
total_visit = cursor1.fetchone()
cursor1.close()
query = ""
query += "SELECT created_at from sale WHERE customer_id = '" + visit['id'] + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' ORDER BY created_at DESC LIMIT 1"
cursor2 = connection.cursor()
cursor2.execute(query)
last_visit = cursor2.fetchone()
cursor2.close()
first_visit_query = ""
first_visit_query += "SELECT created_at from sale WHERE customer_id = '" + visit['id'] + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' ORDER BY created_at ASC LIMIT 1"
cursor3 = connection.cursor()
cursor3.execute(first_visit_query)
first_visit = cursor3.fetchone()
cursor3.close()
total_spend_query = ""
total_spend_query += "SELECT SUM(net_amount) as total_spend from sale WHERE customer_id = '" + visit['id'] +\
"' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' GROUP BY customer_id"
cursor4 = connection.cursor()
cursor4.execute(total_spend_query)
total_spend = cursor4.fetchone()
cursor4.close()
serializer = CustomerSerializer(visit)
data = serializer.data
response_object = {}
response_object = data
if total_visit:
response_object['total_visit'] = total_visit[0]
if last_visit:
response_object['last_visit'] = last_visit[0]
if first_visit:
response_object['first_visit'] = first_visit[0]
if total_spend:
response_object['total_spent'] = total_spend[0]
customer_list.append(response_object)
context = {}
if page and int(page) == 1:
sql = "SELECT count(*) FROM customer d " \
"WHERE d.status = '" + Status.ACTIVE.name + "' AND d.client_id = '" + str(request.user.client_id) + \
"'"
if request.GET.get('search'):
sql += " AND (d.name like '%" + request.GET.get('search') + "%' " \
" OR d.email like '%" + request.GET.get('search') + "%' " \
" OR d.phone_number like '%" + request.GET.get('search') + "%' )"
cursor1 = connection.cursor()
cursor1.execute(sql)
count = cursor1.fetchone()
cursor1.close()
context['count'] = count[0]
context['list'] = customer_list
return JsonResponse(context, status=status.HTTP_200_OK)
@api_view(['GET'])
def get_details_by_id(request, *args, **kwargs):
response_data = {}
translation.activate(request.META.get('HTTP_X_LOCAL'))
customer = utility.get_object_by_id(Customer, kwargs['pk'])
if not customer:
response_data['message'] = _('Customer Not Available')
return JsonResponse(response_data, status=status.HTTP_404_NOT_FOUND)
serializer = CustomerSerializer(customer)
data = serializer.data
sql = ""
sql += "SELECT count(*) from sale WHERE customer_id = '" + str(data['id']) + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' GROUP BY customer_id"
cursor1 = connection.cursor()
cursor1.execute(sql)
total_visit = cursor1.fetchone()
cursor1.close()
query = ""
query += "SELECT created_at from sale WHERE customer_id = '" + data['id'] + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' ORDER BY created_at DESC LIMIT 1"
cursor2 = connection.cursor()
cursor2.execute(query)
last_visit = cursor2.fetchone()
cursor2.close()
query = ""
query += "SELECT created_at from sale WHERE customer_id = '" + data['id'] + "' AND client_id = '" + \
str(request.user.client_id) + "' AND status = 'ACTIVE' ORDER BY created_at ASC LIMIT 1"
cursor3 = connection.cursor()
cursor3.execute(query)
first_visit = cursor3.fetchone()
cursor3.close()
response_data = data
if total_visit:
response_data['total_visit'] = total_visit[0]
if last_visit:
response_data['last_visit'] = last_visit[0]
if first_visit:
response_data['first_visit'] = first_visit[0]
customer = CustomerSerializer(response_data)
return JsonResponse(customer.data, safe=False, status=status.HTTP_200_OK)
@api_view(['DELETE'])
def delete(request, *args, **kwargs):
response_data = {}
translation.activate(request.META.get('HTTP_X_LOCAL'))
customer = utility.get_object_by_id(Customer, kwargs['pk'])
if not customer or (customer and customer.status == 'DELETED'):
response_data['message'] = _('Customer Not Available')
return JsonResponse(response_data, status=status.HTTP_404_NOT_FOUND)
customer.status = Status.DELETED.name
customer.save()
response_data['message'] = _('Deleted Successful')
return JsonResponse(response_data, status=status.HTTP_200_OK)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment