예제 #1
0
 def list(self, request):
     role = user_role(request.user)
     search = request.QUERY_PARAMS.get('search', None)
     page = request.QUERY_PARAMS.get('page', '1')
     if role == constants.VENDOR:
         vendor_agent = VendorAgent.objects.get(user=self.request.user)
         products_of_vendor = Product.objects.filter(
             vendor=vendor_agent.vendor).order_by(
                 Lower('name')).prefetch_related('timeslots')
         if search is not None:
             products_of_vendor = products_of_vendor.filter(
                 Q(name__icontains=search))
         # PAGINATION  ----------------------------------------------------------------
         total_product_count = len(products_of_vendor)
         page = int(page)
         total_pages = int(
             total_product_count / constants.PAGINATION_PAGE_SIZE) + 1
         if page > total_pages or page <= 0:
             return response_invalid_pagenumber()
         else:
             result_products = paginate(products_of_vendor, page)
         # ----------------------------------------------------------------------------
         result = []
         for product in result_products:
             product_dict = product_list_dict(product)
             result.append(product_dict)
         response_content = {
             "data": result,
             "total_pages": total_pages,
             "total_product_count": total_product_count
         }
         return response_with_payload(response_content, None)
     else:
         return response_access_denied()
예제 #2
0
def profile(request):
    role = user_role(request.user)
    if role == constants.VENDOR:
        vendor_agent = VendorAgent.objects.get(user=request.user)
        name = vendor_agent.vendor.store_name
    elif role == constants.OPERATIONS or role == constants.OPERATIONS_MANAGER or role == constants.SALES or role == constants.HR or role == constants.ACCOUNTS or role == constants.CALLER:
        employee = Employee.objects.get(user=request.user)
        name = employee.user.first_name
    else:
        return response_access_denied()

    result = {'name': name, 'role': role}
    return response_with_payload(result, None)
    def list(self, request):
        role = user_role(request.user)
        if role == constants.VENDOR:
            vendor_agent = VendorAgent.objects.get(user=request.user)
            vendor_agents_of_vendor = VendorAgent.objects.filter(
                vendor=vendor_agent.vendor)
            vendoragents = []
            for agent in vendor_agents_of_vendor:
                vendor_agent_dict = vendor_agent_list_dict(agent)
                vendoragents.append(vendor_agent_dict)

            content = {"vendor_agents": vendor_agent_dict}
            return response_with_payload(content, None)
        else:
            return response_access_denied()
예제 #4
0
    def destroy(self, request, pk):
        role = user_role(request.user)
        product = get_object_or_404(Product, pk=pk)

        if role == constants.VENDOR:
            vendor_agent = get_object_or_404(VendorAgent, user=request.user)
            vendor = vendor_agent.vendor
            if product.vendor == vendor:
                product.delete()
                success_message = 'Product deleted Successfully.'
                return response_success_with_message(success_message)
            else:
                return response_access_denied()
        else:
            return response_access_denied()
예제 #5
0
    def list(self, request):
        role = user_role(request.user)
        is_verified = request.QUERY_PARAMS.get('is_verified', None)
        search = request.QUERY_PARAMS.get('search', None)
        page = request.QUERY_PARAMS.get('page', '1')

        if (role == constants.HR) or (role == constants.SALES) or (
                role == constants.OPERATIONS) or (role == constants.ACCOUNTS):
            all_vendors = Vendor.objects.all().order_by(Lower('store_name'))
            if search is not None:
                all_vendors = all_vendors.filter(
                    Q(store_name__icontains=search))

            if is_verified is not None:
                is_verified = json.loads(is_verified.lower())
                if is_verified is True:
                    all_vendors = all_vendors.filter(verified=True)
                else:
                    all_vendors = all_vendors.filter(verified=False)
            # PAGINATION  ----------------------------------------------------------------
            total_vendor_count = len(all_vendors)
            page = int(page)
            total_pages = int(
                total_vendor_count / constants.PAGINATION_PAGE_SIZE) + 1
            if page > total_pages or page <= 0:
                return response_invalid_pagenumber()
            else:
                result_vendors = paginate(all_vendors, page)
            # ----------------------------------------------------------------------------

            result = []
            for vendor in result_vendors:
                vendor_dict = vendor_list_dict(vendor)
                result.append(vendor_dict)

            response_content = {
                "data": result,
                "total_pages": total_pages,
                "total_vendor_count": total_vendor_count
            }
            return response_with_payload(response_content, None)
        elif role == constants.VENDOR:
            vendor_agent = get_object_or_404(VendorAgent, user=request.user)
            vendor_detail = vendor_detail_dict(vendor_agent.vendor)
            return response_with_payload(vendor_detail, None)
        else:
            return response_access_denied()
예제 #6
0
def remove_address(request):
    try:
        address_id = request.data['address_id']
    except APIException:
        parameters = ['description', 'address_id']
        return response_incomplete_parameters(parameters)

    role = user_role(request.user)
    if role == constants.VENDOR:
        address = get_object_or_404(Address, pk=address_id)

        vendor_agent = get_object_or_404(VendorAgent, user=request.user)
        vendor = vendor_agent.vendor
        vendor.addresses.remove(address)
        success_message = 'Address removed successfully'
        return response_success_with_message(success_message)
    else:
        return response_access_denied()
예제 #7
0
def all_tickets(request):
    role = user_role(request.user)
    page = request.QUERY_PARAMS.get('page', 1)
    page = int(page)
    if role == constants.VENDOR:
        vendor_agent = get_object_or_404(VendorAgent, user=request.user)
        vendor = vendor_agent.vendor
        url = '{}api/v2/tickets?updated_since=2015-01-19T02:00:00Z&email={}&per_page={}&page={}'.format(
            constants.FRESHDESK_BASEURL, vendor.email,
            constants.FRESHDESK_PAGE_COUNT, page)
    elif role == constants.OPERATIONS:
        url = '{}api/v2/tickets?updated_since=2015-01-19T02:00:00Z&per_page={}&page={}'.format(
            constants.FRESHDESK_BASEURL, constants.FRESHDESK_PAGE_COUNT, page)
    else:
        return response_access_denied()

    try:
        if role == constants.VENDOR:
            vendor_agent = get_object_or_404(VendorAgent, user=request.user)
            vendor = vendor_agent.vendor
            count_url = '{}helpdesk/tickets/summary.json?view_name=all&email={}'.format(
                constants.FRESHDESK_BASEURL, vendor.email)
        elif role == constants.OPERATIONS:
            count_url = '{}helpdesk/tickets/summary.json?view_name=all'.format(
                constants.FRESHDESK_BASEURL)
        else:
            return response_access_denied()

        count_request = requests.get(count_url, headers=auth_headers())
        count_response = count_request.json()
        count = count_response['view_count']
        total_pages = int(count / constants.FRESHDESK_PAGE_COUNT) + 1

        r = requests.get(url, headers=auth_headers())
        content = r.json()
        response_content = {
            "data": content,
            "total_pages": total_pages,
            "total_tickets": count
        }
        return response_with_payload(response_content, None)
    except Exception as e:
        error_message = 'Something went wrong'
        return response_error_with_message(error_message)
    def create(self, request):
        role = user_role(request.user)
        if (role == constants.VENDOR) or (role == constants.SALES):
            try:
                vendor_id = request.data['vendor_id']
                phone_number = request.data['phone_number']
                name = request.data.get('name')
                password = request.data['password']
            except APIException:
                params = ['vendor_id', 'phone_number', 'name', 'password']
                return response_incomplete_parameters(params)

            try:
                vendor = Vendor.objects.get(id=vendor_id)
            except APIException:
                error_message = 'Vendor with id doesnt exists'
                return response_error_with_message(error_message)

            if is_userexists(phone_number) is True:
                user = User.objects.get(username=phone_number)
                if is_vendoragentexists(user) is True:
                    error_message = 'Vendor Agent with same details exists'
                    return response_error_with_message(error_message)
                else:
                    vendor_agent = VendorAgent.objects.create(user=user)
            else:
                user = User.objects.create(username=phone_number,
                                           password=password,
                                           first_name=name)
                new_vendor_agent = VendorAgent.objects.create(user=user,
                                                              vendor=vendor)

            # GROUP SETTING
            try:
                group = Group.objects.get(name=constants.VENDOR)
                group.user_set.add(user)
            except Exception as e:
                log_exception(e, 'Group settings failed for vendor agent')

            token = create_token(user, constants.VENDOR)
            return response_with_payload(token.key, None)
        else:
            return response_access_denied()
예제 #9
0
    def retrieve(self, request, pk=None):
        vendor = get_object_or_404(Vendor, id=pk)
        role = user_role(request.user)
        can_respond = False

        if role == constants.VENDOR:
            vendor_agent = get_object_or_404(VendorAgent, user=request.user)
            if vendor.id == vendor_agent.vendor.id:
                can_respond = True
            else:
                can_respond = False
        else:
            can_respond = True

        if can_respond:
            vendor_detail = vendor_detail_dict(vendor)
            return response_with_payload(vendor_detail, None)
        else:
            return response_access_denied()
예제 #10
0
def servicible_pincodes(request):
    role = user_role(request.user)
    if role == constants.VENDOR or \
                    role == constants.OPERATIONS or \
                    role == constants.OPERATIONS_MANAGER or \
                    role == constants.HR or \
                    role == constants.SALES or \
                    role == constants.SALES_MANAGER:
        all_pincodes = ServiceablePincode.objects.all()
        result = []
        for pincode in all_pincodes:
            pincode_dict = {
                'pincode': pincode.pincode,
                'city': pincode.city.city_name
            }
            result.append(pincode_dict)
        return response_with_payload(result, None)
    else:
        return response_access_denied()
예제 #11
0
def add_address(request):
    try:
        full_address = request.data['full_address']
        pin_code = request.data['pin_code']
        landmark = request.data.get('landmark')
    except APIException:
        parameters = ['full_address', 'pin_code', 'landmark']
        return response_incomplete_parameters(parameters)

    role = user_role(request.user)
    if role == constants.VENDOR:
        vendor_agent = get_object_or_404(VendorAgent, user=request.user)
        vendor = vendor_agent.vendor

        new_address = create_address(full_address, pin_code, landmark)
        vendor.addresses.add(new_address)
        success_message = 'Address added successfully'
        return response_success_with_message(success_message)
    else:
        return response_access_denied()
예제 #12
0
def get_open_ticket_count(request):
    try:
        role = user_role(request.user)
        if role == constants.VENDOR:
            vendor_agent = get_object_or_404(VendorAgent, user=request.user)
            vendor = vendor_agent.vendor
            count_url = '{}helpdesk/tickets/summary.json?view_name=open&email={}'.format(
                constants.FRESHDESK_BASEURL, vendor.email)
        elif role == constants.OPERATIONS:
            count_url = '{}helpdesk/tickets/summary.json?view_name=open'.format(
                constants.FRESHDESK_BASEURL)
        else:
            return response_access_denied()

        count_request = requests.get(count_url, headers=auth_headers())
        count_response = count_request.json()
        count = count_response['view_count']
        return response_with_payload(count, None)
    except Exception as e:
        error_message = 'Something went wrong'
        return response_error_with_message(error_message)
예제 #13
0
    def create(self, request):
        role = user_role(request.user)
        if role == constants.VENDOR:
            vendor_agent = get_object_or_404(VendorAgent,
                                             user=self.request.user)
            vendor = vendor_agent.vendor
            try:
                name = request.data['name']
                description = request.data['description']
                cost_string = request.data['cost']
                cost = float(cost_string)
            except Exception as e:
                params = ['name' 'description', 'cost', 'vendor']
                return response_incomplete_parameters(params)

            new_product = Product.objects.create(vendor=vendor,
                                                 name=name,
                                                 description=description,
                                                 cost=cost)

            product_dict = product_list_dict(new_product)
            return response_with_payload(product_dict, None)
        else:
            return response_access_denied()
예제 #14
0
def dashboard_stats(request):
    try:
        start_date_string = request.QUERY_PARAMS.get('start_date', None)
        end_date_string = request.QUERY_PARAMS.get('end_date', None)

        start_date = parse_datetime(start_date_string)
        start_date = ist_datetime(start_date)

        end_date = parse_datetime(end_date_string)
        end_date = ist_datetime(end_date)
    except Exception as e:
        params = ['start_date', 'end_date']
        return response_incomplete_parameters(params)

    # CREATE DATE RULE -----------------------------------------------------------
    rule_daily = rrule(DAILY, dtstart=start_date, until=end_date)
    alldates = list(rule_daily)

    # VENDOR FILTERING -----------------------------------------------------------
    vendor = None
    role = user_role(request.user)
    if role == constants.VENDOR:
        vendor_agent = get_object_or_404(VendorAgent, user=request.user)
        vendor = vendor_agent.vendor
    else:
        vendor_id = request.QUERY_PARAMS.get('vendor_id', None)
        if vendor_id is not None:
            vendor = get_object_or_404(Vendor, pk=vendor_id)
        else:
            pass

    if vendor is not None:
        delivery_status_queryset = OrderDeliveryStatus.objects.filter(
            order__vendor=vendor)
    else:
        delivery_status_queryset = OrderDeliveryStatus.objects.all()

    # DATE FILTERING ---------------------------------------------------------------
    delivery_status_queryset = delivery_status_queryset.filter(
        date__gte=start_date, date__lte=end_date)
    total_orders = delivery_status_queryset.filter(
        Q(order_status=constants.ORDER_STATUS_QUEUED)
        | Q(order_status=constants.ORDER_STATUS_INTRANSIT)
        | Q(order_status=constants.ORDER_STATUS_OUTFORDELIVERY)
        | Q(order_status=constants.ORDER_STATUS_DELIVERED)
        | Q(order_status=constants.ORDER_STATUS_DELIVERY_ATTEMPTED)).count()

    # ORDER STATUS FILTERING -------------------------------------------------------
    total_orders_executed = delivery_status_queryset.filter(
        Q(order_status=constants.ORDER_STATUS_DELIVERED)
        | Q(order_status=constants.ORDER_STATUS_DELIVERY_ATTEMPTED)).count()

    # TOTAL COD TO BE COLLECTED -----------------------------
    executable_deliveries = delivery_status_queryset.filter(
        Q(order_status=constants.ORDER_STATUS_QUEUED)
        | Q(order_status=constants.ORDER_STATUS_INTRANSIT)
        | Q(order_status=constants.ORDER_STATUS_OUTFORDELIVERY)
        | Q(order_status=constants.ORDER_STATUS_DELIVERED))
    total_cod_dict = executable_deliveries.aggregate(
        total_cod=Sum('order__cod_amount'))
    total_cod = total_cod_dict['total_cod']

    # TOTAL COD COLLECTED ------------------------------------
    executed_deliveries = delivery_status_queryset.filter(
        Q(order_status=constants.ORDER_STATUS_DELIVERED))
    total_cod_dict = executed_deliveries.aggregate(
        total_cod=Sum('cod_collected_amount'))
    cod_collected = total_cod_dict['total_cod']

    # FOR ORDER COUNT FOR INDIVIDUAL DATES -----------------------------------------
    fullday_timedelta = timedelta(hours=23, minutes=59)
    orders_graph = []
    for date in alldates:
        day_start = date
        day_end = day_start + fullday_timedelta
        delivery_status_per_date = delivery_status_queryset.filter(
            date__gte=day_start, date__lte=day_end)

        total_orders_per_day = delivery_status_per_date.count()
        orders_delivered_count = delivery_status_per_date.filter(
            Q(order_status=constants.ORDER_STATUS_DELIVERED)).count()
        orders_delivered_attempted_count = delivery_status_per_date.filter(
            Q(order_status=constants.ORDER_STATUS_DELIVERY_ATTEMPTED)).count()
        orders_pickup_attempted_count = delivery_status_per_date.filter(
            Q(order_status=constants.ORDER_STATUS_PICKUP_ATTEMPTED)).count()
        orders_cancelled_count = delivery_status_per_date.filter(
            Q(order_status=constants.ORDER_STATUS_CANCELLED)).count()
        orders_undelivered_count = delivery_status_per_date.filter(
            Q(order_status=constants.ORDER_STATUS_PLACED)
            | Q(order_status=constants.ORDER_STATUS_QUEUED)).count()
        orders_intransit_count = delivery_status_per_date.filter(
            Q(order_status=constants.ORDER_STATUS_OUTFORDELIVERY)
            | Q(order_status=constants.ORDER_STATUS_INTRANSIT)).count()

        ist_timedelta = timedelta(hours=5, minutes=30)
        display_date = date + ist_timedelta

        result = {
            'total_orders_count': total_orders_per_day,
            'delivered_count': orders_delivered_count,
            'delivery_attempted_count': orders_delivered_attempted_count,
            'pickup_attempted_count': orders_pickup_attempted_count,
            'cancelled_count': orders_cancelled_count,
            'queued_count': orders_undelivered_count,
            'intransit_count': orders_intransit_count,
            'date': display_date.date()
        }
        orders_graph.append(result)

    content = {
        'total_orders': total_orders,
        'total_orders_executed': total_orders_executed,
        'total_cod': total_cod,
        'cod_collected': cod_collected,
        'orders': orders_graph
    }
    return response_with_payload(content, None)
예제 #15
0
def excel_download(request):
    try:
        start_date_string = request.QUERY_PARAMS.get('start_date', None)
        end_date_string = request.QUERY_PARAMS.get('end_date', None)

        start_date = parse_datetime(start_date_string)
        start_date = ist_day_start(start_date)

        end_date = parse_datetime(end_date_string)
        end_date = ist_day_end(end_date)
    except Exception as e:
        params = ['start_date', 'end_date']
        return response_incomplete_parameters(params)

    # VENDOR FILTERING -----------------------------------------------------------
    vendor = None
    role = user_role(request.user)
    if role == constants.VENDOR:
        vendor_agent = get_object_or_404(VendorAgent, user=request.user)
        vendor = vendor_agent.vendor
    else:
        vendor_id = request.QUERY_PARAMS.get('vendor_id', None)
        if vendor_id is not None:
            vendor = get_object_or_404(Vendor, pk=vendor_id)
        else:
            pass

    if vendor is not None:
        delivery_status_queryset = OrderDeliveryStatus.objects.filter(
            order__vendor=vendor).select_related('delivery_guy__user')
    else:
        delivery_status_queryset = OrderDeliveryStatus.objects.all(
        ).select_related('delivery_guy__user')

    # DATE FILTERING ---------------------------------------------------------------
    delivery_status_queryset = delivery_status_queryset.filter(
        date__gte=start_date, date__lte=end_date).select_related('order')
    # ------------------------------------------------------------------------------

    if len(delivery_status_queryset) > 5000:
        error_message = 'Too many records. Max of 5000 deliveries can be downloaded at a time.'
        return response_error_with_message(error_message)

    # CONSTRUCTING RESPONSE ---------------------------------------------------------------
    ist_timedelta = timedelta(hours=5, minutes=30)
    excel_order_details = []
    for delivery_status in delivery_status_queryset:
        try:
            date = delivery_status.date + ist_timedelta
            order = delivery_status.order
            excel_order = {
                'date': date.strftime('%d-%m-%Y'),
                'order_id': delivery_status.id,
                'customer_name': order.consumer.full_name,
                'customer_phone_number': order.consumer.phone_number,
                'cod_amount': order.cod_amount,
                'cod_collected': delivery_status.cod_collected_amount,
                'cod_reason': delivery_status.cod_remarks,
                'status': delivery_status.order_status,
                'vendor_notes': order.notes,
                'vendor_order_id': order.vendor_order_id
            }
            if role == constants.OPERATIONS:
                excel_order['vendor_name'] = order.vendor.store_name
                if delivery_status.delivery_guy is not None:
                    excel_order[
                        'delivery_guy'] = delivery_status.delivery_guy.user.first_name
                else:
                    excel_order['delivery_guy'] = None

            excel_order_details.append(excel_order)
        except Exception as e:
            pass
    return response_with_payload(excel_order_details, None)
예제 #16
0
def login(request):
    try:
        username = request.data['username']
        password = request.data['password']
    except APIException:
        params = ['username', 'password']
        return response_incomplete_parameters(params)

    try:
        user = authenticate(username=username, password=password)
        role = user_role(user)
    except Exception as e:
        error_message = 'No such user found or No such token found for the role'
        return response_error_with_message(error_message)

    if role == constants.DELIVERY_GUY:
        dg = get_object_or_404(DeliveryGuy, user=user)
        if dg.is_active is True:
            try:
                auth_login(request, user)
                user_details = dg_details_dict(dg)
                token = Token.objects.get(user=user)
                if token is not None:
                    auth_token = token.key
                    user_details['auth_token'] = auth_token
                user_details['role'] = role
                content = user_details
                return response_with_payload(content, None)
            except Exception as e:
                error_message = 'Something went wrong'
                return response_error_with_message(error_message)
        else:
            error_message = 'This DG is deactive'
            return response_error_with_message(error_message)
    elif role == constants.VENDOR:
        vendor_agent = get_object_or_404(VendorAgent, user=user)
        try:
            auth_login(request, user)
            vendor_details = vendor_details_dict(vendor_agent)
            token = Token.objects.get(user=user)
            if token is not None:
                auth_token = token.key
                vendor_details['auth_token'] = auth_token
            vendor_details['role'] = role
            content = vendor_details
            return response_with_payload(content, None)
        except Exception as e:
            error_message = 'Something went wrong'
            return response_error_with_message(error_message)
    else:
        emp = get_object_or_404(Employee, user=user)
        try:
            auth_login(request, user)
            emp_details = emp_details_dict(emp)
            token = Token.objects.get(user=user)
            if token is not None:
                auth_token = token.key
                emp_details['auth_token'] = auth_token
            emp_details['role'] = emp.department
            content = emp_details
            return response_with_payload(content, None)
        except Exception as e:
            error_message = 'Something went wrong'
            return response_error_with_message(error_message)
예제 #17
0
    def approve(self, request, pk):
        role = user_role(request.user)
        vendor = get_object_or_404(Vendor, pk=pk)
        notes = request.data.get('notes')
        is_retail = request.data.get('is_retail')
        industry_ids = request.data.get('industry_ids')
        approved_by = request.user
        # pricing = request.data.get('pricing')
        # pan = request.data.get('pan')
        if role == constants.SALES:
            try:
                username = vendor.phone_number
                password = vendor.store_name.replace(" ", "")
                password = password.lower()

                if is_userexists(username):
                    user = get_object_or_404(User, username=username)
                    user.set_password(password)
                    user.save()
                else:
                    user = User.objects.create_user(username=username,
                                                    password=password)

                token = create_token(user, constants.VENDOR)
                vendor_agent = VendorAgent.objects.create(user=user,
                                                          vendor=vendor)

                vendor.verified = True

                if notes is not None:
                    vendor.notes = notes

                if is_retail is not None:
                    vendor.is_retail = is_retail

                if approved_by is not None:
                    vendor.approved_by = approved_by

                try:
                    if industry_ids is not None:
                        for industry_id in industry_ids:
                            industry = get_object_or_404(Industry,
                                                         pk=industry_id)
                            vendor.industries.add(industry)
                except Exception as e:
                    pass

                vendor.save()
            except Exception as e:
                error_message = 'An error occurred creating the account. Please try again'
                return response_error_with_message(error_message)

            subject = 'YourGuy: Account created for {}'.format(
                vendor.store_name)
            customer_message = constants.VENDOR_ACCOUNT_APPROVED_MESSAGE.format(
                vendor.phone_number, password)
            customer_emails = [vendor.email]
            send_email(customer_emails, subject, customer_message)
            send_sms(vendor.phone_number, customer_message)

            sales_message = constants.VENDOR_ACCOUNT_APPROVED_MESSAGE_SALES.format(
                vendor.store_name)
            send_email(constants.SALES_EMAIL, subject, sales_message)

            success_message = 'Your account credentials has been sent via email and SMS.'
            return response_success_with_message(success_message)
        else:
            return response_access_denied()