Пример #1
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()
Пример #2
0
    def request_vendor_account(self, request, pk=None):
        try:
            store_name = request.data['store_name']
            phone_number = request.data['phone_number']
            email = request.data['email']
            full_address = request.data['full_address']
            pin_code = request.data['pin_code']
            landmark = request.data.get('landmark')
        except APIException:
            parameters = [
                'store_name', 'phone_number', 'email', 'full_address',
                'pin_code', 'landmark(optional)'
            ]
            return response_incomplete_parameters(parameters)

        # CHECK IF THE VENDOR HAS ALREADY REQUESTED FOR AN ACCOUNT
        existing_vendors = Vendor.objects.filter(phone_number=phone_number)
        existing_users = User.objects.filter(username=phone_number)
        if len(existing_vendors) > 0 or len(existing_users) > 0:
            error_message = 'Vendor with similar details already exists'
            return response_error_with_message(error_message)

        # CREATING NEW VENDOR
        new_vendor = Vendor.objects.create(store_name=store_name,
                                           email=email,
                                           phone_number=phone_number)
        new_address = create_address(full_address, pin_code, landmark)
        new_vendor.addresses.add(new_address)
        new_vendor.save()

        # SEND EMAIL TO SALES
        try:
            approval_link = 'http://app.yourguy.in/#/home/vendor/{}'.format(
                new_vendor.id)
            subject = 'YourGuy: New Vendor Account Request'
            body = constants.VENDOR_ACCOUNT_REQUESTED_MESSAGE_SALES.format(
                store_name, phone_number, email, full_address, pin_code,
                approval_link)
            send_email(constants.SALES_EMAIL, subject, body)
        except Exception as e:
            pass

        success_message = 'Thank you! We have received your request. Our sales team will contact you soon.'
        return response_success_with_message(success_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()
Пример #4
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()
Пример #5
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()
Пример #6
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)
Пример #7
0
def register(request):
    try:
        role = request.data['role']
        phone_number = request.data['phone_number']
        password = request.data['password']
        name = request.data['name']

        email = request.data.get('email')
        vendor_id = request.data.get('vendor_id')
    except APIException:
        params = [
            'role', 'phone_number', 'password', 'name', 'email(optional)',
            'vendor_id(optional)'
        ]
        return response_incomplete_parameters(params)

    # CHECK IF USER EXISTS  -----------------------------------
    if is_userexists(phone_number):
        error_message = 'User with same phone number already exists'
        return response_error_with_message(error_message)
    # -----------------------------------------------------------

    # VENDOR AGENT CREATION NEEDS VENDOR_ID ----------------------
    if role == constants.VENDOR:
        if vendor_id is None:
            params = ['vendor_id']
            return response_incomplete_parameters(params)
        try:
            vendor = Vendor.objects.get(id=vendor_id)
        except APIException:
            error_message = 'Vendor with given id doesnt exists'
            return response_error_with_message(error_message)
    # ---------------------------------------------------------------

    user = User.objects.create_user(username=phone_number,
                                    password=password,
                                    first_name=name)
    if email is not None:
        user.email = email
    user.save()

    token = None
    if role == constants.VENDOR:
        token = create_token(user, constants.VENDOR)
        vendor = get_object_or_404(Vendor, id=vendor_id)
        vendor_agent = VendorAgent.objects.create(user=user, vendor=vendor)
        assign_usergroup(user)
    elif role == constants.DELIVERY_GUY:
        token = create_token(user, constants.DELIVERY_GUY)
        delivery_guy = DeliveryGuy.objects.create(user=user)
        assign_usergroup(user)
    elif role == constants.OPERATIONS:
        token = create_token(user, constants.OPERATIONS)
        employee = Employee.objects.create(user=user)
        employee.department = constants.OPERATIONS
        assign_usergroup(user)
    elif role == constants.OPERATIONS_MANAGER:
        token = create_token(user, constants.OPERATIONS_MANAGER)
        employee = Employee.objects.create(user=user)
        employee.department = constants.OPERATIONS_MANAGER
        assign_usergroup(user)
    elif role == constants.SALES:
        token = create_token(user, constants.SALES)
        employee = Employee.objects.create(user=user)
        employee.department = constants.SALES
        assign_usergroup(user)
    elif role == constants.HR:
        token = create_token(user, constants.HR)
        employee = Employee.objects.create(user=user)
        employee.department = constants.HR
        assign_usergroup(user)
    elif role == constants.ACCOUNTS:
        token = create_token(user, constants.ACCOUNTS)
        employee = Employee.objects.create(user=user)
        employee.department = constants.ACCOUNTS
        assign_usergroup(user)
    elif role == constants.CALLER:
        token = create_token(user, constants.CALLER)
        employee = Employee.objects.create(user=user)
        employee.department = constants.CALLER
        assign_usergroup(user)
    else:
        token = None

    employee.save()

    if token is not None:
        content = {'auth_token': token.key}
    else:
        content = {'auth_token': None, 'user created for group: ': role}

    return response_with_payload(content, None)
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)
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)