def close_coupon(sms_dict, phone_number):
    '''
        A function that handles coupon close
    '''
    service_advisor = validate_service_advisor(phone_number, close_action=True)
    unique_service_coupon = sms_dict['usc']
    customer_id = sms_dict.get('sap_customer_id', None)
    message = None
    if settings.LOGAN_ACTIVE:
        LOGGER.post_event("close_coupon", {'sender':phone_number,
                                          'brand':settings.BRAND})
    if not service_advisor:
        return {'status': False, 'message': templates.get_template('UNAUTHORISED_SA')}
    
    sa_uinitiator_result, msg = is_sa_initiator(unique_service_coupon, service_advisor, phone_number)
    if not sa_uinitiator_result:
        return {'status': False, 'message': msg}
    
    try:
        product = get_product(sms_dict)
        if not product:
                    return {'status': False, 'message': templates.get_template('INVALID_CUSTOMER_ID')}
        coupon_object = models.CouponData.objects.filter(product=product.id,
                                                         unique_service_coupon=unique_service_coupon).select_related ('product')
                                                         
        if not coupon_object:
                    return {'status': False, 'message': templates.get_template('INVALID_UCN')}
        coupon_object = coupon_object[0]     
        if coupon_object.status == 2 or coupon_object.status == 6:
            message = templates.get_template('COUPON_ALREADY_CLOSED')
        elif coupon_object.status == 4:
            customer_phone_number = coupon_object.product.customer_phone_number
            coupon_object.status = 2
            coupon_object.service_advisor = service_advisor
            coupon_object.closed_date = datetime.now()
            coupon_object.save()
            message = templates.get_template('SEND_SA_CLOSE_COUPON').format(customer_id=customer_id, usc=unique_service_coupon)
        else:
            message = templates.get_template('SEND_SA_WRONG_CUSTOMER_UCN')
    except Exception as ex:
        LOG.error("[Exception_coupon_close] {0}".format(ex))
        message = templates.get_template('SEND_INVALID_MESSAGE')
    finally:
        LOG.info("Close coupon with message %s" % message)
        phone_number = utils.get_phone_number_format(phone_number)
        sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=message)
        send_job_to_queue(send_coupon, {"phone_number":phone_number, "message": message, "sms_client":settings.SMS_CLIENT})
    return {'status': True, 'message': message}
def validate_coupon(sms_dict, phone_number):
    '''
        A function that handles coupon check
    '''
    #vehicle_registration_no = sms_dict['veh_reg_no']
    service_type = sms_dict['service_type']
    dealer_message = None
    customer_message = None
    customer_phone_number = None
    customer_message_countdown = settings.DELAY_IN_CUSTOMER_UCN_MESSAGE
    vehicle_registration_no = sms_dict.get('veh_reg_no', None)
    service_advisor = validate_service_advisor(phone_number)
    
    if settings.LOGAN_ACTIVE:
        LOGGER.post_event("check_coupon", {'sender':phone_number,
                                          'brand':settings.BRAND})
    if not service_advisor:
        return {'status': False, 'message': templates.get_template('UNAUTHORISED_SA')}
     
#     if not is_valid_data(customer_registration=customer_registration, sa_phone=phone_number):
#         return {'status': False, 'message': templates.get_template('SEND_SA_WRONG_CUSTOMER_UCN'

    if service_type not in ['1','2','3']:
        return {'status': False, 'message': templates.get_template('INVALID_ST')}
    try:
        product_data_list = get_product(sms_dict)
        customer_support = models.Constant.objects.get(constant_name='customer_support_number_uganda').constant_value
        if not product_data_list:
                    # This new line is added 
                    message = templates.get_template('INVALID_VEH_REG_NO').format(
                                                    support_number=customer_support)
                    return {'status': False, 'message': message}
                   # return {'status': False, 'message': templates.get_template('INVALID_VEH_REG_NO')}
        LOG.info("Associated product %s" % product_data_list.product_id)
#         update_exceed_limit_coupon(actual_kms, product, service_advisor)
        valid_coupon = models.CouponData.objects.filter( (Q(status=1) | Q(status=4) | Q(status=5))  & Q(product=product_data_list.id)
                                                         & Q(service_type=service_type )) 
        try :
            closed_coupon_latest = models.CouponData.objects.filter( Q(status=2) & Q(product=product_data_list.id) ).latest('closed_date')
        except:
            closed_coupon_latest = []
            
        if not valid_coupon:
            return {'status': False, 'message': templates.get_template('COUPON_ALREADY_CLOSED')}
        LOG.info("List of available valid coupons %s" % valid_coupon)
        if len(valid_coupon) > 0:
            valid_coupon = valid_coupon[0]
            LOG.info("valid coupon %s" % valid_coupon)
            coupon_sa_obj = models.ServiceAdvisorCouponRelationship.objects.filter(unique_service_coupon=valid_coupon\
                                                                                ,service_advisor=service_advisor)
            LOG.info('Coupon_sa_obj exists: %s' % coupon_sa_obj)
            if not len(coupon_sa_obj):
                coupon_sa_obj = models.ServiceAdvisorCouponRelationship(unique_service_coupon=valid_coupon\
                                                                        ,service_advisor=service_advisor)
                coupon_sa_obj.save()
                LOG.info('Coupon obj created: %s' % coupon_sa_obj)

        in_progress_coupon = models.CouponData.objects.filter(product=product_data_list.id, status=4) \
                             .select_related ('product').order_by('service_type')
                             
        try:
            customer_phone_number = product_data_list.customer_phone_number
        except Exception as ax:
            LOG.error('Customer Phone Number is not stored in DB %s' % ax)
            
        rider = models.FleetRider.objects.filter(product=product_data_list, is_active=True)
        rider_message={'message':None}
        if rider:
            rider_phone_number = rider[0].phone_number
        else:
            rider = None
            
        if len(in_progress_coupon) > 0:
            update_inprogress_coupon(in_progress_coupon[0], service_advisor)
            LOG.info("Validate_coupon: Already in progress coupon")
            if (in_progress_coupon[0] == valid_coupon):
                dealer_message = templates.get_template('COUPON_ALREADY_INPROGRESS').format(
                                                    service_type=service_type,
                                                    customer_id=product_data_list.customer_id)
                
                
                customer_message = templates.get_template('SEND_CUSTOMER_VALID_COUPON').format(customer_name=product_data_list.customer_name,
                                                    coupon=in_progress_coupon[0].unique_service_coupon,
                                                    service_type=in_progress_coupon[0].service_type)
                rider_message  = customer_message
                
            else:
                #in_progress_coupon_name = in_progress_coupon[0].unique_service_coupon
                dealer_message = templates.get_template('PLEASE_CLOSE_INPROGRESS_COUPON').format(
                                                    coupon=in_progress_coupon[0].unique_service_coupon)
                
                #dealer_message = templates.get_template('PLEASE_CLOSE_INPROGRESS_COUPON')
        elif valid_coupon:
            
            if closed_coupon_latest:
                closed_coupon_date = closed_coupon_latest.closed_date
                today = datetime.now(pytz.utc)
                free_service_coupon_diffrence = (today-closed_coupon_date).days
                if free_service_coupon_diffrence < 15:
                    return {'status': False, 'message': templates.get_template('INVALID_SERVICE_DIFFERENCE')}
            
            LOG.info("Validate_coupon: valid coupon")
            update_coupon(valid_coupon, service_advisor, 4, datetime.now())
            dealer_message = templates.get_template('SEND_SA_VALID_COUPON').format(
                                            service_type=service_type,
                                            customer_id=product_data_list.customer_id, customer_phone=product_data_list.customer_phone_number)
            customer_message = templates.get_template('SEND_CUSTOMER_VALID_COUPON').format(
                                        customer_name=product_data_list.customer_name,coupon=valid_coupon.unique_service_coupon,
                                        service_type=valid_coupon.service_type)
            rider_message = customer_message
        else:
            LOG.info("Validate_coupon: No valid or in-progress coupon")
            requested_coupon_status = get_requested_coupon_status(product_data_list.id, service_type)
            dealer_message = templates.get_template('SEND_SA_OTHER_VALID_COUPON').format(
                                        req_service_type=service_type,
                                        req_status=requested_coupon_status,
                                        customer_id=product_data_list.customer_id)
            customer_message = dealer_message
            rider_message = dealer_message
            
        try:
            val =unicodedata.normalize('NFKD', rider_message).encode('ascii','ignore')
            if rider and val != None:
                sms_log(settings.BRAND, receiver=rider_phone_number, action=AUDIT_ACTION, message=rider_message)
                send_job_to_queue(send_coupon, {"phone_number":rider_phone_number, "message": rider_message,
                                                        "sms_client":settings.SMS_CLIENT})
        except Exception as ex:
            LOG.info('[Rider_message]:Exception : '.format(ex))
        sms_log(settings.BRAND, receiver=customer_phone_number, action=AUDIT_ACTION, message=customer_message)
        send_job_to_queue(send_coupon_detail_customer, {"phone_number":utils.get_phone_number_format(customer_phone_number), "message":customer_message, "sms_client":settings.SMS_CLIENT},
                          delay_seconds=customer_message_countdown)
        sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=dealer_message)
        send_job_to_queue(send_service_detail, {"phone_number": phone_number,
                                                "message": dealer_message,
                                                "sms_client": settings.SMS_CLIENT})

    except Exception as ex:
        LOG.info('[validate_coupon]:Exception : '.format(ex))
        dealer_message = templates.get_template('SEND_INVALID_MESSAGE')
    finally:
        LOG.info("validate message send to SA %s" % dealer_message)
        phone_number = utils.get_phone_number_format(phone_number)
        sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=dealer_message)
        send_job_to_queue(send_service_detail, {"phone_number": phone_number,
                                                "message": dealer_message,
                                                "sms_client": settings.SMS_CLIENT})
    return {'status': True, 'message': dealer_message}
def validate_coupon(sms_dict, phone_number):
    actual_kms = int(sms_dict['kms'])
    service_type = sms_dict['service_type']
    dealer_message = None
    customer_message = None
    customer_phone_number = None
    customer_message_countdown = settings.DELAY_IN_CUSTOMER_UCN_MESSAGE
    sap_customer_id = sms_dict.get('sap_customer_id', None)
    service_advisor = validate_service_advisor(phone_number)
    if settings.LOGAN_ACTIVE:
        LOGGER.post_event("check_coupon", {'sender':phone_number,
                                          'brand':settings.BRAND})
    if not service_advisor:
        return {'status': False, 'message': templates.get_template('UNAUTHORISED_SA')}
    if not is_valid_data(customer_id=sap_customer_id, sa_phone=phone_number):
        return {'status': False, 'message': templates.get_template('SEND_SA_WRONG_CUSTOMER_UCN')}
    try:
        product = get_product(sap_customer_id)
        LOG.info("Associated product %s" % product)
        update_exceed_limit_coupon(actual_kms, product, service_advisor)
        valid_coupon = models.CouponData.objects.filter(Q(status=1) | Q(status=4) | Q(status=5), product=product,
                        valid_kms__gte=actual_kms, service_type=service_type) \
                       .select_related('vin', 'customer_phone_number__phone_number').order_by('service_type')
        LOG.info("List of available valid coupons %s" % valid_coupon)
        if len(valid_coupon) > 0:
            update_higher_range_coupon(valid_coupon[0].valid_kms, product)
            valid_coupon = valid_coupon[0]
            LOG.info("valid coupon %s" % valid_coupon)
            coupon_sa_obj = models.ServiceAdvisorCouponRelationship.objects.filter(unique_service_coupon=valid_coupon\
                                                                                   ,service_advisor=service_advisor)
            LOG.info('Coupon_sa_obj exists: %s' % coupon_sa_obj)
            if not len(coupon_sa_obj):
                coupon_sa_obj = models.ServiceAdvisorCouponRelationship(unique_service_coupon=valid_coupon\
                                                                        ,service_advisor=service_advisor)
                coupon_sa_obj.save()
                LOG.info('Coupon obj created: %s' % coupon_sa_obj)

        in_progress_coupon = models.CouponData.objects.filter(product=product, valid_kms__gte=actual_kms, status=4) \
                             .select_related ('product').order_by('service_type')
        try:
            customer_phone_number = product.customer_phone_number
        except Exception as ax:
            LOG.error('Customer Phone Number is not stored in DB %s' % ax)
        if len(in_progress_coupon) > 0:
            update_inprogress_coupon(in_progress_coupon[0], actual_kms, service_advisor)
            LOG.info("Validate_coupon: Already in progress coupon")
            dealer_message = templates.get_template('COUPON_ALREADY_INPROGRESS').format(
                                                service_type=in_progress_coupon[0].service_type,
                                                customer_id=sap_customer_id)
            customer_message = templates.get_template('SEND_CUSTOMER_VALID_COUPON').format(
                                                coupon=in_progress_coupon[0].unique_service_coupon,
                                                service_type=in_progress_coupon[0].service_type)
        elif valid_coupon:
            LOG.info("Validate_coupon: valid coupon")
            update_coupon(valid_coupon, actual_kms, service_advisor, 4, datetime.now())
            dealer_message = templates.get_template('SEND_SA_VALID_COUPON').format(
                                            service_type=valid_coupon.service_type,
                                            customer_id=sap_customer_id, customer_phone=product.customer_phone_number)

            customer_message = templates.get_template('SEND_CUSTOMER_VALID_COUPON').format(
                                        coupon=valid_coupon.unique_service_coupon,
                                        service_type=valid_coupon.service_type)
        else:
            LOG.info("Validate_coupon: No valid or in-progress coupon")
            requested_coupon_status = get_requested_coupon_status(product, service_type)
            dealer_message = templates.get_template('SEND_SA_OTHER_VALID_COUPON').format(
                                        req_service_type=service_type,
                                        req_status=requested_coupon_status,
                                        customer_id=sap_customer_id)
            customer_message=dealer_message
        sms_log(settings.BRAND, receiver=customer_phone_number, action=AUDIT_ACTION, message=customer_message)
        send_job_to_queue(send_coupon_detail_customer, {"phone_number":utils.get_phone_number_format(customer_phone_number), "message":customer_message, "sms_client":settings.SMS_CLIENT},
                          delay_seconds=customer_message_countdown)

    except Exception as ex:
        LOG.info('[validate_coupon]:Exception : '.format(ex))
        dealer_message = templates.get_template('SEND_INVALID_MESSAGE')
    finally:
        LOG.info("validate message send to SA %s" % dealer_message)
        phone_number = utils.get_phone_number_format(phone_number)
        sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=dealer_message)
        send_job_to_queue(send_service_detail, {"phone_number": phone_number,
                                                "message": dealer_message,
                                                "sms_client": settings.SMS_CLIENT})
    return {'status': True, 'message': dealer_message}