def exceptions(request, exception=None):
    groups = utils.stringify_groups(request.user)
    if not (Roles.ASCS in groups or Roles.DEALERS in groups):
        return HttpResponseBadRequest()
    if request.method == 'GET':
        template = 'portal/exception.html'
        data = None
        if exception in ['close', 'check']:
            if Roles.ASCS in groups:
                data = models.ServiceAdvisor.objects.active_under_asc(request.user)
            else:
                data = models.ServiceAdvisor.objects.active_under_dealer(request.user)
        return render(request, template, {'active_menu': exception,
                                           "data": data, 'groups': groups})
    elif request.method == 'POST':
        function_mapping = {
            'customer': get_customer_info,
            'recover': recover_coupon_info,
            'search': utils.search_details,
            'status': utils.services_search_details,
            'serviceadvisor': utils.service_advisor_search
        }
        try:
            post_data = request.POST.copy()
            post_data['current_user'] = request.user
            post_data['groups'] = groups
            if request.FILES:
                post_data['job_card']=request.FILES['jobCard']
            data = function_mapping[exception](post_data)
            return HttpResponse(content=json.dumps(data),  content_type='application/json')
        except Exception as ex:
            logger.error(ex)
            return HttpResponseBadRequest()
    else:
        return HttpResponseBadRequest()
def register(request, menu):
    groups = utils.stringify_groups(request.user)
    use_cdms = True
    if len(set([Roles.ASCS, Roles.DEALERS, Roles.SDMANAGERS]).intersection(set(groups))) == 0:
        return HttpResponseBadRequest()

    if request.method == 'GET':
        user_id = request.user
        reset_password =  models.UserProfile.objects.get(user=request.user).reset_password
        if not reset_password:
            return render(request, 'portal/change_password.html')
        if Roles.DEALERS in groups:
            use_cdms=models.Dealer.objects.get(user__user=user_id).use_cdms
        return render(request, TEMPLATE_MAPPING.get(menu, 'portal/404.html'), {'active_menu' : ACTIVE_MENU.get(menu)\
                                                                    , 'groups': groups,
                                                                    'user_id' : user_id,
                                                                    'use_cdms' : use_cdms})
    elif request.method == 'POST':
        save_user = {
            'asc': save_asc_registration,
            'sa': save_sa_registration,
            'customer': register_customer
        }
        try:
            response_object = save_user[menu](request, groups)
            return HttpResponse(response_object, content_type="application/json")
        except Exception as ex:
            logger.error('[registration failure {0}] : {1}'.format(menu, ex))
            return HttpResponseBadRequest()
    else:
        return HttpResponseBadRequest()
def get_servicedesk_tickets(request):
    groups = utils.stringify_groups(request.user)
    status = request.GET.get('status')
    priority = request.GET.get('priority')
    type = request.GET.get('type')
    search = request.GET.get('search')
    count = request.GET.get('count') or BY_DEFAULT_RECORDS_PER_PAGE
    page_details = {}
    feedback_obects = get_feedbacks(request.user, status, priority, type, search)
    paginator = Paginator(feedback_obects, count)
    page = request.GET.get('page', 1)
    feedbacks = paginator.page(page)
    page_details['total_objects'] = paginator.count
    page_details['from'] = feedbacks.start_index()
    page_details['to'] = feedbacks.end_index()
    training_material = models.Service.objects.filter(service_type__name=Services.SERVICE_DESK)
    if len(training_material)>0:
        training_material = training_material[0].training_material_url
    else:
        training_material = None

    return render(request, 'service-desk/tickets.html', {"feedbacks" : feedbacks,
                                          "status": utils.get_list_from_set(FEEDBACK_STATUS),
                                          "types": utils.get_list_from_set(FEEDBACK_TYPE),
                                          "priorities": utils.get_list_from_set(PRIORITY),
                                          "pagination_links": PAGINATION_LINKS,
                                          "page_details": page_details,
                                          "record_showing_counts": RECORDS_PER_PAGE,
                                          "training_material" : training_material,
                                          "groups":groups[0],
                                          "filter_params": {'status': status, 'priority': priority, 'type': type,
                                                            'count': str(count), 'search': search}}
                                        )
def service_desk(request):
    status = request.GET.get('status')
    priority = request.GET.get('priority')
    type = request.GET.get('type')
    search = request.GET.get('search')
    count = request.GET.get('count') or BY_DEFAULT_RECORDS_PER_PAGE
    page_details = {}
    feedback_obects = get_feedbacks(request.user, status, priority, type, search)
    paginator = Paginator(feedback_obects, count)
    page = request.GET.get('page', 1)
    feedbacks = paginator.page(page)
    page_details['total_objects'] = paginator.count
    page_details['from'] = feedbacks.start_index()
    page_details['to'] = feedbacks.end_index()
    groups = utils.stringify_groups(request.user)
    training_material = models.Service.objects.filter(service_type__name=Services.SERVICE_DESK)
    if len(training_material)>0:
        training_material = training_material[0].training_material_url
    else:
        training_material = None
    if request.method == 'GET':
        template = 'service-desk/feedback_details.html'
        data = None
        if request.user.groups.filter(name=Roles.DEALERS).exists():
            data = models.ServiceAdvisor.objects.active_under_dealer(request.user)
        else:
            data = models.ServiceAdvisor.objects.active_under_asc(request.user)
        dealer_asc_details = models.UserProfile.objects.get(user__username=request.user)
        return render(request, template, {"feedbacks" : feedbacks,
                                          'active_menu': 'support',
                                          "data": data, 'groups': groups,
                                          "status": utils.get_list_from_set(FEEDBACK_STATUS),
                                          "pagination_links": PAGINATION_LINKS,
                                          "page_details": page_details,
                                          "record_showing_counts": RECORDS_PER_PAGE,
                                          "types": utils.get_list_from_set(FEEDBACK_TYPE),
                                          "priorities": utils.get_list_from_set(PRIORITY),
                                          "training_material" : training_material,
                                          "dealer_asc" : dealer_asc_details,
                                          "filter_params": {'status': status, 'priority': priority, 'type': type,
                                                            'count': str(count), 'search': search}}
                                        )
    elif request.method == 'POST':
        try:
            data = save_help_desk_data(request)
            return HttpResponse(content=json.dumps(data),
                                content_type='application/json')
        except Exception as ex:
            LOG.error('Exception while saving data : {0}'.format(ex))
            return HttpResponseBadRequest()
    else:
        return HttpResponseBadRequest()
def service_desk(request):
    status = request.GET.get('status')
    priority = request.GET.get('priority')
    type = request.GET.get('type')
    search = request.GET.get('search')
    count = request.GET.get('count') or BY_DEFAULT_RECORDS_PER_PAGE
    page_details = {}
    feedback_obects = get_feedbacks(request.user, status, priority, type, search)
    paginator = Paginator(feedback_obects, count)
    page = request.GET.get('page', 1)
    feedbacks = paginator.page(page)
    page_details['total_objects'] = paginator.count
    page_details['from'] = feedbacks.start_index()
    page_details['to'] = feedbacks.end_index()
    groups = utils.stringify_groups(request.user)
    brand_departments = get_brand_departments()
    training_material = get_model('Service').objects.filter(service_type__name=Services.SERVICE_DESK)
    department_sub_categories= get_subcategories()
    if len(training_material)>0:
        training_material = training_material[0].training_material_url
    else:
        training_material = None
    if request.method == 'GET':
        template = 'portal/feedback_details.html'
        data = None
        if request.user.groups.filter(name=Roles.DEALERS).exists():
            data = get_model('ServiceAdvisor').objects.active_under_dealer(request.user)
        else:
            data = get_model('ServiceAdvisor').objects.active_under_asc(request.user)
        dealer_asc_details = get_model('UserProfile').objects.get(user__username=request.user)
        return render(request, template, {"feedbacks" : feedbacks,
                                          'active_menu': 'support',
                                          "data": data, 'groups': groups,
                                          "status": utils.get_list_from_set(FEEDBACK_STATUS),
                                          "pagination_links": PAGINATION_LINKS,
                                          "page_details": page_details,
                                          "departments": brand_departments,
                                          "department_sub_categories" : department_sub_categories,
                                          "record_showing_counts": RECORDS_PER_PAGE,
                                          "types": utils.get_list_from_set(FEEDBACK_TYPE),
                                          "priorities": utils.get_list_from_set(DEMO_PRIORITY),
                                          "training_material" : training_material,
                                          "dealer_asc" : dealer_asc_details,
                                          "filter_params": {'status': status, 'priority': priority, 'type': type,
                                                            'count': str(count), 'search': search}}
                                        )
    else:
        return HttpResponseBadRequest()
def users(request, users=None):
    groups = utils.stringify_groups(request.user)
    if not (Roles.ASCS in groups or Roles.DEALERS in groups):
        return HttpResponseBadRequest()
    if request.method == 'GET':
        template = 'portal/users.html'
        data=None
        data_mapping = {
            'sa': utils.get_sa_list_for_login_dealer,
            'asc': utils.get_asc_list_for_login_dealer
        }
        try:
            data = data_mapping[users](request.user)
        except:
            #It is acceptable if there is no data_mapping defined for a function
            pass
        return render(request, template, {'active_menu' : users, "data" : data, 'groups': groups})
    else:
        return HttpResponseBadRequest()
def change_password(request): 
    if request.method == 'GET':
        return render(request, 'portal/change_password.html')
    if request.method == 'POST':
        groups = utils.stringify_groups(request.user)
        if Roles.DEALERS in groups or Roles.ASCS in groups:
            user = User.objects.get(username=request.user)
            old_password = request.POST.get('oldPassword')
            new_password = request.POST.get('newPassword')
            check_pass = user.check_password(str(old_password))
            if check_pass:
                user.set_password(str(new_password))
                user.save()
                data = {'message': 'Password Changed successfully', 'status': True}
            else:
                data = {'message': 'Old password wrong', 'status': False}
            return HttpResponse(json.dumps(data), content_type='application/json')
        else:
            return HttpResponseBadRequest('Not Allowed')
def reports(request):
    groups = utils.stringify_groups(request.user)
    report_data=[]
    if not (Roles.ASCS in groups or Roles.DEALERS in groups):
        return HttpResponseBadRequest()
    status_options = {'4': 'In Progress', '2':'Closed'}
    report_options = {'reconciliation': 'Reconciliation', 'credit':'Credit Note'}
    min_date, max_date = utils.get_min_and_max_filter_date()
    template_rendered = 'portal/reconciliation_report.html'
    report_data =  {'status_options': status_options,
                    'report_options': report_options,
                    'min_date':min_date,
                    'max_date': max_date}
    if request.method == 'POST':
        report_data['params'] = request.POST.copy()
        if report_data['params']['type']== 'credit':
            report_data['params']['status']='2'
            template_rendered = 'portal/credit_note_report.html'
        report_data['records'] = create_reconciliation_report(report_data['params'], request.user)
    return render(request, template_rendered, report_data)
def register(request, menu):
    groups = utils.stringify_groups(request.user)
    if not (Roles.ASCS in groups or Roles.DEALERS in groups):
        return HttpResponseBadRequest()
    if request.method == 'GET':
        user_id = request.user
        return render(request, TEMPLATE_MAPPING.get(menu), {'active_menu' : ACTIVE_MENU.get(menu)\
                                                                    , 'groups': groups, 'user_id' : user_id})
    elif request.method == 'POST':
        save_user = {
            'asc': save_asc_registration,
            'sa': save_sa_registration,
            'customer': register_customer
        }
        try:
            response_object = save_user[menu](request, groups)
            return HttpResponse(response_object, content_type="application/json")
        except Exception as ex:
            logger.error('[registration failure {0}] : {1}'.format(menu, ex))
            return HttpResponseBadRequest()
    else:
        return HttpResponseBadRequest()
def register_customer(request, group=None):
    post_data = request.POST
    data_source = []
    existing_customer = False
    product_obj = models.ProductData.objects.filter(product_id=post_data['customer-vin'])
    if not post_data['customer-id']:
        temp_customer_id = utils.generate_temp_id(TEMP_ID_PREFIX)
    else:
        temp_customer_id = post_data['customer-id']
        existing_customer = True
    data_source.append(utils.create_purchase_feed_data(post_data, product_obj[0], temp_customer_id))

    check_with_invoice_date = utils.subtract_dates(data_source[0]['product_purchase_date'], product_obj[0].invoice_date)    
    check_with_today_date = utils.subtract_dates(data_source[0]['product_purchase_date'], datetime.datetime.now())
    if not existing_customer and check_with_invoice_date.days < 0 or check_with_today_date.days > 0:
        message = "Product purchase date should be between {0} and {1}".\
                format((product_obj[0].invoice_date).strftime("%d-%m-%Y"),(datetime.datetime.now()).strftime("%d-%m-%Y"))
        logger.info('[Temporary_cust_registration]:: {0} Entered date is: {1}'.format(message, str(data_source[0]['product_purchase_date'])))
        return json.dumps({"message": message})

    try:
        with transaction.atomic():
            customer_obj = models.CustomerTempRegistration.objects.filter(temp_customer_id = temp_customer_id)
            if customer_obj:
                customer_obj = customer_obj[0]
                if customer_obj.new_number != data_source[0]['customer_phone_number']:
                    update_count = models.Constant.objects.get(constant_name='mobile_number_update_count').constant_value
                    if customer_obj.mobile_number_update_count >= int(update_count) and group[0] != Roles.SDMANAGERS:
                        customer_update = models.CustomerUpdateFailure(product_id = product_obj[0],
                                                                       customer_name = data_source[0]['customer_name'],
                                                                       customer_id = customer_obj.temp_customer_id,
                                                                       updated_by = "dealer-"+ str(request.user),
                                                                       old_number = customer_obj.new_number,
                                                                       new_number = data_source[0]['customer_phone_number'])
                        customer_update.save()
                        message = get_template('PHONE_NUMBER_UPDATE_COUNT_EXCEEDED')
                        return json.dumps({'message' : message})

                    if models.UserProfile.objects.filter(phone_number=data_source[0]['customer_phone_number']):
                        message = get_template('FAILED_UPDATE_PHONE_NUMBER').format(phone_number=data_source[0]['customer_phone_number'])
                        return json.dumps({'message': message})
                    old_number = customer_obj.new_number
                    customer_obj.new_number = data_source[0]['customer_phone_number']
                    customer_obj.product_data = product_obj[0]
                    customer_obj.sent_to_sap = False
                    customer_obj.dealer_asc_id = str(request.user)
                    customer_obj.mobile_number_update_count+=1
                    update_history = models.CustomerUpdateHistory(temp_customer=customer_obj,
                                                                  updated_field='Phone Number',
                                                                  old_value=old_number,
                                                                  new_value=customer_obj.new_number,
                                                                  email_flag=False)
                    update_history.save()
                    message = get_template('CUSTOMER_MOBILE_NUMBER_UPDATE').format(customer_name=customer_obj.new_customer_name, new_number=customer_obj.new_number)
                    for phone_number in [customer_obj.new_number, old_number]:
                        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_customer_phone_number_update_message, {"phone_number":phone_number, "message":message, "sms_client":settings.SMS_CLIENT})
                            
                    if models.UserProfile.objects.filter(user__groups__name=Roles.BRANDMANAGERS).exists():
                        groups = utils.stringify_groups(request.user)
                        if Roles.ASCS in groups:
                            dealer_asc_id = "asc : " + customer_obj.dealer_asc_id
                        elif Roles.DEALERS in groups:
                            dealer_asc_id = "dealer : " + customer_obj.dealer_asc_id
                        else :
                            dealer_asc_id = "manager : " + customer_obj.dealer_asc_id
                        
                        message = get_template('CUSTOMER_PHONE_NUMBER_UPDATE').format(customer_id=customer_obj.temp_customer_id, old_number=old_number, 
                                                                                  new_number=customer_obj.new_number, dealer_asc_id=dealer_asc_id)
                        managers = models.UserProfile.objects.filter(user__groups__name=Roles.BRANDMANAGERS)
                        for manager in managers:
                            phone_number = utils.get_phone_number_format(manager.phone_number)
                            sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=message)
                            send_job_to_queue(send_customer_phone_number_update_message, {"phone_number":phone_number, "message":message, "sms_client":settings.SMS_CLIENT})

            else:
                if models.UserProfile.objects.filter(phone_number=data_source[0]['customer_phone_number']):
                    message = get_template('FAILED_UPDATE_PHONE_NUMBER').format(phone_number=data_source[0]['customer_phone_number'])
                    return json.dumps({'message': message})
                customer_obj = models.CustomerTempRegistration(product_data=product_obj[0], 
                                                               new_customer_name = data_source[0]['customer_name'],
                                                               new_number = data_source[0]['customer_phone_number'],
                                                               product_purchase_date = data_source[0]['product_purchase_date'],
                                                               temp_customer_id = temp_customer_id,
                                                               dealer_asc_id = str(request.user))
            customer_obj.save()
            logger.info('[Temporary_cust_registration]:: Initiating purchase feed')
            feed_remark = FeedLogWithRemark(len(data_source),
                                                feed_type='Purchase Feed',
                                                action='Received', status=True)
            sap_obj = SAPFeed()
            feed_response = sap_obj.import_to_db(feed_type='purchase', data_source=data_source, feed_remark=feed_remark)
            if feed_response.failed_feeds > 0:
                logger.info('[Temporary_cust_registration]:: ' + json.dumps(feed_response.remarks))
                raise ValueError('purchase feed failed!')
            logger.info('[Temporary_cust_registration]:: purchase feed completed')
    except Exception as ex: 
        logger.info(ex)

        return HttpResponseBadRequest()
    if existing_customer:
        return json.dumps({'message': CUST_UPDATE_SUCCESS})
    return json.dumps({'message': CUST_REGISTER_SUCCESS + temp_customer_id})