コード例 #1
0
class RepairService():
    def setservices(self):
        from customer.factories import CustomerServicesFactory
        self.customer_service_factory = CustomerServicesFactory()
        self.dealer_service_factory = CustomerServicesFactory()
        self.cuserservice = self.customer_service_factory.get_instance("user")
        self.userservice = self.dealer_service_factory.get_instance("user")
        self.appointment_service = self.dealer_service_factory.get_instance(
            "appointment")
        self.vehicle_service = self.dealer_service_factory.get_instance(
            "vehicle")
        self.repair_service = self
        self.dealership_service = self.dealer_service_factory.get_instance(
            "dealership")

    def get_service_for(self, appointment_id, s_r_type="s"):
        services = AppointmentService.objects.filter(
            appointment_id=appointment_id, service__type=s_r_type)
        return services

    def get_appointment_services(self, appointment_id):
        services = AppointmentService.objects.filter(
            appointment_id=appointment_id)
        servicename = ""
        data = []
        if len(services) == 1:
            services = services.get()
            repair = ServiceRepair.objects.get(id=services.service_id)
            servicename = repair.name
            data.append({
                'name': servicename,
                'id': repair.id,
                'type': repair.type,
                "appt_service_id": services.id
            })
        else:
            for ser in services:
                repair = ServiceRepair.objects.get(id=ser.service_id)
                data.append({
                    'name': repair.name,
                    'id': repair.id,
                    'type': repair.type,
                    "appt_service_id": ser.id
                })
                servicename += repair.name + ", "
            servicename = servicename[:-2]
        service = {'combined_name': servicename, 'details': data}
        return service

    def remove_service(self, id):
        try:
            appt_service = AppointmentService.objects.get(id=id).delete()
            return True
        except Exception, e:
            return False
コード例 #2
0
def save_advisor(request, dealer_code):
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    resp = True
    user = None
    dealer_service = dealer_factory.get_instance(
        "dealership")  #DealerShipService()
    dealership = dealer_service.get_dealer_by(
        request.session.get("dealer_code"))
    rtype = request.GET.get("type", "appointment")
    if rtype == "appointment":
        #         if request.GET.get("advisor_id"):
        try:
            appointment_id = request.GET.get("appointment_id")

            service = AppointmentService()
            appointment = service.get_appointment(appointment_id)
            advisor_id = request.GET.get("advisor_id", appointment.advisor_id)
            save_advisor = service.save_advisor(appointment, advisor_id)
            cservice = customer_factory.get_instance("user")  #CUserService()
            if save_advisor:
                resp = True
            print appointment.customer.id
            print dealership.id
            print advisor_id
            save = cservice.save_my_advisor(appointment.customer.id,
                                            dealership.id, advisor_id)
            if save == False:
                resp = False
        except Exception, e:
            print e
コード例 #3
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def createuser(request, dealer_code=None):
    customer_factory = CustomerServicesFactory()
    userservice = customer_factory.get_instance("user")  #CUserService()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            profile_id = form.cleaned_data["profile"]
            profile = userservice.get_user_profile(profile_id)
            user = userservice.create_customer(username)
            referrer = request.POST.get("referrer")
            if user:
                user.set_password(form.cleaned_data['new'])
                user.save()
                messages.success(
                    request,
                    "Account has been successfully created. Your information will be stored for future service appointment needs. Please click 'DONE' to review your appointment, make changes or cancel the appointment."
                )
                if profile:
                    profile.user = user
                    profile.save()
                    if referrer:
                        return HttpResponseRedirect(referrer)
                    else:
                        return HttpResponseRedirect(
                            reverse('customer:index') + "?dealer_code=" +
                            dealer_code)
        else:
            print form.errors
            print "form not valid"
コード例 #4
0
def get_all_advisor(request, dealer_code):
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    service_layer = customer_factory.get_instance("user")  #CUserService()
    media_url = settings.MEDIA_URL
    dealer_service = dealer_factory.get_instance(
        "dealership")  #DealerShipService()
    dealership = dealer_service.get_dealer_by(
        request.session.get("dealer_code"))
    selected_advisor_id = None
    appointment = None
    rtype = request.GET.get("type", "appointment")
    profile_id = request.GET.get("profile_id")
    """when saving for appointment"""
    if rtype == "appointment":
        appointment_id = request.GET.get("appointment_id")
        service = dealer_factory.get_instance(
            "appointment")  #AppointmentService()
        appointment = service.get_appointment(appointment_id)
        if appointment and appointment.advisor:
            selected_advisor_id = appointment.advisor.id
        if selected_advisor_id == None and appointment:
            try:
                customer_advisor = CustomerAdvisor.objects.get(
                    customer_id=appointment.customer.id)
                selected_advisor_id = customer_advisor.advisor.id
            except Exception, e:
                print e
                customer_advisor = None
コード例 #5
0
def get_cart(request,dealer_code,profile,appointment):
    try:
        if appointment:
                
                customer_factory = CustomerServicesFactory()
                dealer_factory = DealerShipServicesFactory()
                dealer_service = dealer_factory.get_instance("dealership")
                dealer = dealer_service.get_dealer_by(dealer_code)
                userservice = customer_factory.get_instance("user")
                appointmentservice = dealer_factory.get_instance("appointment")
                repairservice = dealer_factory.get_instance("repair")
                services = repairservice.get_service_for(appointment.id,'s')
                repairs = repairservice.get_service_for(appointment.id,'r')
                print services
                print repairs
               
                context = {
                                        "mainurl":settings.MEDIA_ROOT,
                                          "appointment":appointment,
                                          "dealer_code":dealer_code,
                                          "services":services,"repairs":repairs,
                                          "cart_count":len(repairs)+len(services)
            
                }
   
                return render(request, "customer/cart/main.html",context)
        else:
#             return ""
            return render(request, "customer/cart/main.html",{})
    except Exception,e:
        print e
            
コード例 #6
0
ファイル: views.py プロジェクト: asimriaz85/bmw-grenlight
def index(request, dealer_code, profile):
    """    
            this method is the index view for the chat session. Its just a test page currently 
            for advisors
    """
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    dealer_service = dealer_factory.get_instance(
        "dealership")  #DealerShipService()
    dealership = dealer_service.get_dealer_by(dealer_code)
    userservice = customer_factory.get_instance("user")  #CUserService()

    #     userservice = UserService()
    advisor = userservice.get_advisor_for_chat(dealership, profile)
    img = UploadForm()
    template_name = 'livechat/advisorchat.html'
    chat_username = getUserName(request)
    chat_nick = getChatNick(request)

    return render(
        request, template_name, {
            "CENTRIFUGE_URL": settings.CENTRIFUGE_URL,
            "CENTRIFUGE_SECRET": settings.CENTRIFUGE_SECRET,
            "advisor": advisor,
            "chat_username": chat_username,
            "chat_nick": chat_nick,
            'form': img
        })
コード例 #7
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def passreset(request, dealer_code=None):
    '''Reseting Password email'''
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    if request.method == 'POST':
        form = ResetForm(request.POST)
        if form.is_valid():
            try:
                user_service = customer_factory.get_instance("user")
                profile = user_service.get_user_profile_by_email(
                    form.cleaned_data['email'])
                if profile == None:
                    raise Exception("Email not found")

                token = user_service.create_token(profile.user)
                try:
                    user_service.send_pass_reset_link_profile(
                        profile, token, form.cleaned_data['email'],
                        dealer_code)
                    messages.success(request, 'Email has been sent')

                except Exception, e:
                    print e
                    form.add_error("email", "email sending failed")

            except Exception, e:
                form.add_error("email", "email doesnot exist")
コード例 #8
0
class AppointmentService():

    STATUS_SCHEDULED_ID = 1
    CANCEL_STATUS_ID = 11
    COMPLETED_STATUS_ID = 8
    NO_SHOW_STATUS = 12

    def setservices(self):
        from customer.factories import CustomerServicesFactory
        from dealership.factories import DealerShipServicesFactory
        self.customer_service_factory = CustomerServicesFactory()
        self.dealer_service_factory = DealerShipServicesFactory()
        self.cuserservice = self.customer_service_factory.get_instance("user")
        self.userservice = self.dealer_service_factory.get_instance("user")
        self.vehicle_service = self.dealer_service_factory.get_instance(
            "vehicle")
        self.repair_service = self.dealer_service_factory.get_instance(
            "repair")
        self.dealership_service = self.dealer_service_factory.get_instance(
            "dealership")
        self.capacity_service = self.dealer_service_factory.get_instance(
            "capacity")
        self.email_service = self.dealer_service_factory.get_instance("email")
        self.appointment_service = self

    def update_noshow(self):
        try:
            time_threshold = timezone.now() - timedelta(hours=24)

            Appointment.objects.filter(
                appointment_status_id=self.STATUS_SCHEDULED_ID,
                start_time__lt=time_threshold).update(
                    appointment_status_id=self.NO_SHOW_STATUS)
        except Exception, e:
            print "error"
コード例 #9
0
ファイル: overview.py プロジェクト: asimriaz85/bmw-grenlight
def appointment_update_insurance(request):
    customer_factory = CustomerServicesFactory()
    service = customer_factory.get_instance("user")
    account_service =  customer_factory.get_instance("account")
    if request.method == 'POST':
        userprofile =service.get_user_profile(request.POST.get('user'))
        insurance_profile = service.get_user_driver_insurance(userprofile)
        driver_initial  =account_service.get_initial_driver_form(request.POST.get('customer_id'), insurance_profile,userprofile)
        driver_form = CustomerInsuranceForm(request.POST,instance = insurance_profile, initial=driver_initial)
        if driver_form.is_valid():
            resp = driver_form.save()
            #result = account_service.save_driver_form(insurance_profile,driver_form)
            return JsonResponse({"status":"success", "message":"Insurance Information Updated Successfully"})
   
        else:
            return JsonResponse({"status":"error", "message":"Insurance Data is not Valid"})
    return JsonResponse({"status":"error"})            
コード例 #10
0
ファイル: overview.py プロジェクト: asimriaz85/bmw-grenlight
def appointment_update_creditcard(request):
    customer_factory = CustomerServicesFactory()
    service = customer_factory.get_instance("user")
    account_service =  customer_factory.get_instance("account")
    if request.method == 'POST':         
        userprofile =service.get_user_profile(request.POST.get('user'))
        cc_profile = service.get_cc_profile(userprofile)
        cc_form = CreditDebitForm(request.POST,instance = cc_profile)
        if cc_form.is_valid():
            resp = account_service.save_cc_form(cc_profile,cc_form)
            if resp == True:
                return JsonResponse({"status":"success", "message":"Credit Card Information Updated Successfully"})
            else:
                return JsonResponse({"status":"error", "message":"Credit Card Information Failed to Update"})
        else:
            return JsonResponse({"status":"error", "message":"Credit Card Data is not Valid"})
            #return JsonResponse({"status":"error", "errors":cc_form.errors})
    return JsonResponse({"status":"error"})
コード例 #11
0
def index(request, appointment_id):
    customer_factory = CustomerServicesFactory()

    service = customer_factory.get_instance("user")

    templates = "customer/statusalert/index.html"
    try:
        appt_details = Appointment.objects.get(id=appointment_id)
    except Appointment.DoesNotExist:
        raise Http404
    flages = Flags.objects.filter(type=3,
                                  customer_facing=True,
                                  dealer_id=appt_details.dealer.id)
    recmndations = AppointmentRecommendation.objects.filter(
        appointment_id=appointment_id)

    total = 0
    for obj in recmndations:
        total += obj.price

    appt_services = AppointmentService.objects.filter(
        appointment_id=appointment_id)
    if appt_details:
        userprofile = appt_details.customer


#     userprofile =service.get_userprofile(request.user)
    service_total = 0
    for obj in appt_services:
        service_total += obj.price
    approved_recmm = AppointmentRecommendation.objects.filter(
        appointment_id=appointment_id, status="Accept")
    for obj in approved_recmm:
        service_total += obj.price
    dealer = appt_details.dealer
    dealer_code = None
    if dealer:
        dealer_code = dealer.dealer_code

    context = {
        'flages': flages,
        'appt': appt_details,
        'recommandations': recmndations,
        'total': total,
        'appt_services': appt_services,
        'approved_rec': approved_recmm,
        's_total': service_total,
        'dealer_code': dealer_code
    }
    service.set_centrifuge_context(request,
                                   dealer_code,
                                   userprofile,
                                   context,
                                   chatposition="top")
    return render(request, templates, context)
コード例 #12
0
def ocr_snap(request):
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    if request.POST.get("imgBase64") != None:
        cameraservice = customer_factory.get_instance(
            "camera")  #CameraService()
        img = cameraservice.get_image_from_base64(
            request.POST.get("imgBase64"))
        print img
        qr_text = cameraservice.get_zbar_from(img)
        #         qr_text = "baAe"
        return JsonResponse({"resp": qr_text})
コード例 #13
0
ファイル: account.py プロジェクト: asimriaz85/bmw-grenlight
def delete(request):
    try:
        customer_factory = CustomerServicesFactory()
        user = request.user
        service = customer_factory.get_instance("account")  #AccountService()
        resp = service.delete_account(user.userprofile)
        if resp:
            messages.success(request, "Account Deleted Successfully")
        else:
            messages.success(request, "Unable to Delete Account")
    except:
        messages.error(request, "Unable to  Deleted account. Try later")
    return HttpResponseRedirect(reverse("customer:accountsettings"))
コード例 #14
0
def save_customer_number(request):
    if request.GET.get("phone_number"):
        customer_factory = CustomerServicesFactory()
        user_service = customer_factory.get_instance("user")
        profile = user_service.get_userprofile(request.user)
        phone_number = request.GET.get("phone_number")
        carrier_choices = request.GET.get("carrier")
        user_service.save_active_phone(profile,
                                       phone_number,
                                       carrier_choice=carrier_choices)
        return JsonResponse({"success": True}, safe=False)
    else:
        return JsonResponse({"success": False}, safe=False)
コード例 #15
0
def notificationssettings(request,dealer_code,profile):
    """
           This is the notification screen. This is used to save settings
    """
    customer_factory = CustomerServicesFactory()
    dealer_factory= DealerShipServicesFactory()
    user_service = customer_factory.get_instance("user")
    profile = user_service.get_userprofile(request.user)
    notificationservice = dealer_factory.get_instance("notification")
    remindersettings = notificationservice.get_user_remindersettings(profile,True)
    phone_numbers = user_service.get_profile_numbers(profile)
    emails = user_service.get_profile_emails(profile)
    carrier_choices =    (
                         ("Verizon"),
                         ("AT & T"),
                         
    )
    tab = "notification"
    if request.method == "POST":
        special_offer_notify = False
        if request.POST.get("special_offer_notify"):
            special_offer_notify = True
        ids =  request.POST.getlist("settings_id")
        for id in ids:
            
            textset = False
            phoneset=False
            emailset = False
            if request.POST.get("setting_email_"+id):
                emailset = True
            if request.POST.get("setting_text_"+id):
                textset=True
            if request.POST.get("setting_phone_"+id):
                phoneset=True
            notificationservice.save_reminder_settings(id,emailset,textset,phoneset)
#         user_service.save_active_phone(profile,request.POST.get("active_phone_number"))
        user_service.save_active_email(profile,request.POST.get("active_email"))
        user_service.save_special_offer_notify(profile,special_offer_notify)
        messages.success(request, "Reminder settings saved successfully")
        return HttpResponseRedirect(reverse("customer:notifications"))
        
    else:
        context = {"dealer_code":dealer_code,"tab":tab,"page_title":"Customer Profile",
                                                              "remindersettings":remindersettings,
                                                                "phonenumbers":phone_numbers,
                                                                "emails":emails,"profile":profile,"carrier_choices":carrier_choices}
        user_service.set_centrifuge_context(request, dealer_code,profile,context,chatposition="top")
        return render(request, "customer/notifications.html",context
                    )
コード例 #16
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def sync_gcalendar(request):
    gcalservice = GoogleService()
    if request.GET.get("appointment_id"):
        if request.GET.get("refferrer"):
            request.session["refferrer"] = request.GET.get("refferrer")

        customer_factory = CustomerServicesFactory()
        dealer_factory = DealerShipServicesFactory()
        dealer_service = dealer_factory.get_instance("dealership")
        #         dealer = dealer_service.get_dealer_by(dealer_code)
        uservice = customer_factory.get_instance("user")  #CUserService()
        appt_service = dealer_factory.get_instance(
            "appointment")  #AppointmentService()
        appointment = appt_service.get_appointment(
            request.GET.get("appointment_id"))  #,dealer)

        #         REDIRECT_URI = 'http://127.0.0.1:8000/customer/oauth2callback/'#?appointment_id='+request.GET.get("appointment_id")
        request.session["oauth_appointment"] = request.GET.get(
            "appointment_id")
        #REDIRECT_URI = "https://%s%s" % (
        #   get_current_site(request).domain, reverse("customer:return"))
        REDIRECT_URI = settings.SITE_MAIN_URL + reverse("customer:return")
        CLIENT_SECRETS = os.path.join(os.path.dirname(__file__),
                                      gcalservice.CLIENT_SECRET_FILE)

        FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
                                       scope=gcalservice.SCOPES,
                                       redirect_uri=REDIRECT_URI)
        storage = Storage(CredentialsModel, 'id', appointment, 'credential')
        credential = storage.get()
        if credential is None or credential.invalid is True:
            FLOW.params['state'] = xsrfutil.generate_token(
                settings.SECRET_KEY, appointment)
            authorize_url = FLOW.step1_get_authorize_url()
            f = FlowModel(id=appointment, flow=FLOW)
            f.save()

            return HttpResponseRedirect(authorize_url)
        else:
            resp = gcalservice.create_event(appointment, credential)
            messages.success(
                request, "Your appointment has been added to Google Calendars")
            if request.session.get("refferrer"):
                refferrer = request.session["refferrer"]
                del request.session["refferrer"]
                return HttpResponseRedirect(refferrer)
            else:

                return JsonResponse({"success": resp}, safe=False)
コード例 #17
0
ファイル: overview.py プロジェクト: asimriaz85/bmw-grenlight
def appointment_detail_ajax_view(request):
    template = 'overview/detail.html'
    context = {}
    customer_factory = CustomerServicesFactory()
    if request.method == 'POST': 
        dealer_factory = DealerShipServicesFactory()
        aptservice = dealer_factory.get_instance("appointment")
        vehicleservice = dealer_factory.get_instance("vehicle")
        service = customer_factory.get_instance("user")
        account_service =  customer_factory.get_instance("account")
        userprofile =service.get_user_profile(request.POST.get('customer_id'))
        context = aptservice.get_appointment_by_id(request.POST.get('appointment_id'));
        print context['appointment'].checkin_time,"$$$$$$$$$$"
        #get credit card form        
        cc_profile = service.get_cc_profile(userprofile)
        cc_initial = account_service.get_initial_cc_form(request.POST.get('customer_id'),cc_profile,userprofile)
        cc_form = CreditDebitForm(instance=cc_profile,initial=cc_initial)        
        context['cc_form'] = cc_form 
        #get vechicle information form
        vehicle_instance = vehicleservice.get_customer_vehicle(request.POST.get('vehicle_id'))
        vehicle_form = CustomerVehichleForm(instance=vehicle_instance) 
        context['vehicle_form'] = vehicle_form
        #insurence form
        insurance_profile = service.get_user_driver_insurance(userprofile)
        driver_initial  =account_service.get_initial_driver_form(request.POST.get('customer_id'), insurance_profile,userprofile)
        ins_form = CustomerInsuranceForm(instance=insurance_profile,initial=driver_initial)
        context['ins_form'] = ins_form   
        
        if request.POST.get('checkin'): 
            context['checkin'] = 'true'
        else:
            context['checkin'] = 'false'   
        
        
            
    return render(request, template, context)
コード例 #18
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def registeruer(request, dealer_code=None):
    customer_factory = CustomerServicesFactory()
    cuser = customer_factory.get_instance("user")
    if request.GET.get("profile_id"):
        profile = cuser.get_user_profile(request.GET.get("profile_id"))
        if profile:
            initial_user_form = {"profile": profile.id}
            usercreateform = CreateUserForm(initial=initial_user_form)
            return render(
                request, "customer/registeruser.html", {
                    "usercreationform": usercreateform,
                    "profile": profile,
                    "done_disable": True,
                    "request": request
                })
        else:
            raise Http404("Profile not found")
コード例 #19
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def passcreate(request, dealer_code=None):
    '''Setting new password'''
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    form = UserPasswordResetForm()
    template = 'customer/404.html'
    question = ''
    token = request.GET.get('token')
    if token is not None:
        user_service = customer_factory.get_instance("user")
        user = user_service.get_user_from_token(token)
        if user is not None:
            template = 'customer/password_create.html'
            #             question =  user_service.get_user_question(user)
            if request.method == 'POST':
                form = UserPasswordResetForm(request.POST)
                if form.is_valid():
                    #                     if user_service.verify_user_answer(user, form.cleaned_data['answer']) == True:
                    user_service.save_user_password(user,
                                                    form.cleaned_data['new'])
                    messages.success(
                        request,
                        'Password has been updated. Please provide the new credentials'
                    )
                    return HttpResponseRedirect(
                        reverse('customer:index') + "?dealer_code=" +
                        dealer_code)


#                     else:
#                         form.add_error("answer","You have not provided the correct answer")
                else:
                    print form.errors

        else:
            print "user not found"

    context = {
        'form': form,
        'question': None,
        'token': token,
        "dealer_code": dealer_code
    }
    return render(request, template, context)
コード例 #20
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def index(request, dealer_code=None):
    '''Main Page View'''
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    if request.user.is_authenticated() and request.user.groups.filter(
            name__in=[confg.GROUP_NAME]):
        return HttpResponseRedirect(reverse('customer:main'))
    form = LoginForm()
    userservice = customer_factory.get_instance("user")  #CUserService()

    context = {
        'form': form,
        "dealer_code": dealer_code,
        "tab": "",
        "request": request
    }

    template_name = 'customer/login_form.html'
    userservice.set_centrifuge_context(request, dealer_code, None, context)
    return render(request, template_name, context)
コード例 #21
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def userreset(request, dealer_code=None):
    """
    UserReset
    * Request to retrieve username
    """
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    if request.method == 'POST':
        form = ResetForm(request.POST)
        if form.is_valid():
            try:
                cuser_service = customer_factory.get_instance("user")
                duser_service = dealer_factory.get_instance("user")
                profile = cuser_service.get_user_profile_by_email(
                    form.cleaned_data['email'])
                if profile == None:
                    raise Exception("Email not found")
                if dealer_group_check(profile.user) == False:
                    form.add_error("email", conf.RESET_EMAIL_GROUP_ERROR)
                else:
                    #                     user_service = UserService()
                    try:
                        duser_service.send_username_link_new(
                            profile.user, form.cleaned_data['email'])
                        messages.success(request,
                                         conf.RESET_EMAIL_SENT_MESSAGE)
                    except:
                        form.add_error("email", conf.RESET_EMAIL_SENT_ERROR)
            except:
                form.add_error("email", conf.RESET_EMAIL_EXIST_ERROR)
    else:
        form = ResetForm()
    template = login_template + 'username_reset.html'
    return render(
        request, template, {
            'form': form,
            "name": request.session["dealer_name"],
            "code": request.session["dealer_code"]
        })
コード例 #22
0
def edit_customer(request):
    if request.POST:
        customer_factory = CustomerServicesFactory()
        uservice = customer_factory.get_instance("user")
        phone_number = request.POST.get("phone_number_1")
        email = request.POST.get("email_1")
        id = request.POST.get("id")
        profile = uservice.get_user_profile_by_phone(phone_number)
        if profile == None or profile.id == id:
            profile = uservice.get_user_profile_by_email(email)
        if profile == None or profile.id == id:
            profile = UserProfile.objects.get(id=id)
        customer_form = CustomerGuestAccountForm(request.POST,
                                                 instance=profile)
        if customer_form.is_valid():
            customer_form.save()
            return JsonResponse({"success": True, 'message': 'accepted'})
        else:
            return JsonResponse({
                "success":
                False,
                'message': [(k, v[0]) for k, v in customer_form.errors.items()]
            })
コード例 #23
0
class VehicleService():
    def setservices(self):
        from customer.factories import CustomerServicesFactory
        from dealership.factories import DealerShipServicesFactory
        self.customer_service_factory = CustomerServicesFactory()
        self.dealer_service_factory = DealerShipServicesFactory()
        self.cuserservice = self.customer_service_factory.get_instance("user")
        self.userservice = self.dealer_service_factory.get_instance("user")
        self.appointment_service = self.dealer_service_factory.get_instance(
            "appointment")
        self.vehicle_service = self
        self.repair_service = self.dealer_service_factory.get_instance(
            "repair")
        self.dealership_service = self.dealer_service_factory.get_instance(
            "dealership")

    def save_vehicle_for(self, profile, vehicle):
        try:
            vehicle.user = profile
            vehicle.save()
        except Exception, e:
            print e
            return False
コード例 #24
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def passreset(request, dealer_code=None):
    """
    PassCreate
    * Request for creating new password
    """
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    if request.method == 'POST':
        form = ResetForm(request.POST)
        if form.is_valid():
            try:
                #                 user = User.objects.get(email = form.cleaned_data['email'])
                cuser_service = customer_factory.get_instance("user")
                duser_service = dealer_factory.get_instance("user")
                profile = cuser_service.get_user_profile_by_email(
                    form.cleaned_data['email'])

                if profile == None:
                    raise Exception("Email not found")
                if dealer_group_check(profile.user) == False:
                    print "Not in dealer group"
                    form.add_error("email", conf.RESET_EMAIL_GROUP_ERROR)
                else:
                    #                     user_service = UserService()
                    try:
                        duser_service.send_pass_reset_link_new(
                            profile.user, request,
                            reverse("dealership:passcreate"),
                            form.cleaned_data['email'], dealer_code)
                        messages.success(request,
                                         conf.RESET_EMAIL_SENT_MESSAGE)
                    except Exception, e:
                        print e
                        form.add_error("email", conf.RESET_EMAIL_SENT_ERROR)
            except Exception, e:
                print e
                form.add_error("email", conf.RESET_EMAIL_EXIST_ERROR)
コード例 #25
0
ファイル: login.py プロジェクト: asimriaz85/bmw-grenlight
def new_customer_vehicle(request, dealer_code=None):
    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    if request.user.is_authenticated() and request.user.groups.filter(
            name__in=[confg.GROUP_NAME]):
        return HttpResponseRedirect(reverse('customer:main'))
    dealer_service = dealer_factory.get_instance(
        "dealership")  #DealerShipService()
    dealership = dealer_service.get_dealer_by(
        request.session.get("dealer_code"))
    service = dealer_factory.get_instance("vehicle")  #VehicleService()
    userservice = customer_factory.get_instance("user")  #CUserService()
    #     vehichles = service.get_vehichles()
    vehichles = service.get_vehichles_dealer(dealership)
    appservice = dealer_factory.get_instance(
        "appointment")  #appointmentservices.AppointmentService()
    vehicles = list(vehichles)
    media_url = settings.MEDIA_URL
    customer_vehicle = None
    if request.method == 'POST':
        if request.POST.get("make") != None and request.POST.get(
                "year") != None:
            if request.POST.get("vehicle_id") != None and request.POST.get(
                    "vehicle_id") != "":
                customer_vehicle = service.save_customer_vehicle(
                    None, request.POST.get("vehicle_id"),
                    request.POST.get("vin_vehicle"),
                    request.POST.get("desc_vehicle", ""))

            app = appservice.save_empty_appointment(dealership.id)
            vehicle_desc = request.POST.get("desc_vehicle", "test")
            if app:
                url ="?dealer_code="+dealer_code+"&"+confg.SESSION_MAKE_KEY\
                                                +"="+request.POST.get("make")\
                                                +"&"+confg.SESSION_YEAR_KEY+"="+request.POST.get("year")\
                                                +"&appointment_id="+str(app.id)

                if customer_vehicle and customer_vehicle.vehicle:
                    appservice.save_customer_vehicle(app, customer_vehicle.id)
                    if request.POST.get(
                            "vin_data") != None and request.POST.get(
                                "vin_data") != "":
                        service.save_vehicle_vin_data(
                            customer_vehicle, request.POST.get("vin_data"))
                    return HttpResponseRedirect(
                        reverse('customer:service_selection_appointment') +
                        url)
                else:
                    if request.POST.get("vin_vehicle") != None:
                        url += "&" + confg.SESSION_VIN_NUM_KEY + "=" + request.POST.get(
                            "vin_vehicle")
                    return HttpResponseRedirect(
                        reverse('customer:vehicle_selection_appointment') +
                        url)
            else:
                messages.error(request,
                               'Unable to save appointment. Please try later')

    context = {
        'acitve': True,
        "dealer_code": dealer_code,
        "tab": "new",
        "media_url": media_url,
        "vehichles": mainjson.dumps(vehicles),
        "bmw_make_settings": settings.BMW_MAKE_CODE
    }
    userservice.set_centrifuge_context(request, dealer_code, None, context)
    template_name = 'customer/new_user_vehicle.html'
    return render(request, template_name, context)
コード例 #26
0
def mainview(request, dealer_code, profile):
    """
            This is the main screen after login. It is used to display the vehicles and also
            the add form form for vehicle
    """

    customer_factory = CustomerServicesFactory()
    dealer_factory = DealerShipServicesFactory()
    dealer_service = dealer_factory.get_instance(
        "dealership")  #DealerShipService()
    dealership = dealer_service.get_dealer_by(
        request.session.get("dealer_code"))
    name = request.user.first_name + " " + request.user.last_name
    service = dealer_factory.get_instance("vehicle")  #VehicleService()
    template_name = 'customer/customer_vehicle.html'
    userservice = customer_factory.get_instance("user")  #CUserService()
    #     vehichles = service.get_vehichles()
    vehichles = service.get_vehichles_dealer(dealership)
    profile = userservice.get_userprofile(request.user)
    customer_vehicles = service.get_customer_vehicles(profile.id, dealership)

    vehicles = list(vehichles)
    media_url = settings.MEDIA_URL
    tab = ""
    myadvisor = None
    if profile:
        myadvisor = userservice.get_my_advisor(profile.id, dealership.id)
    if request.method == 'POST':
        vehicle_form = CustomerVehichleForm(request.POST)
        if vehicle_form.is_valid():
            try:
                vehicle_form.save()
                if request.POST.get("vin_data") != None and request.POST.get(
                        "vin_data") != "":
                    service.save_vehicle_vin_data(vehicle_form.instance,
                                                  request.POST.get("vin_data"))
                messages.success(request, "Vehicle added successfully")
                return HttpResponseRedirect(reverse("customer:main"))
            except:
                vehicle_form.add_error(None, "Some error occured while saving")
    else:

        vehicle_form = CustomerVehichleForm(initial={'user': profile.id})

    context = {
        "page_title": "Customer Profile",
        "vehicle_form": vehicle_form,
        "media_url": media_url,
        'name': name,
        "vehicles": mainjson.dumps(vehicles),
        "customer_vehicles": customer_vehicles,
        "tab": tab,
        'acitve': True,
        "dealer_code": dealer_code,
        "profile": profile,
        "myadvisor": myadvisor,
        "request": request
        #                                           "userprofile":userservice.get_userprofile(request.user)
    }
    userservice.set_centrifuge_context(request,
                                       dealer_code,
                                       profile,
                                       context,
                                       chatposition="top")
    return render(request, template_name, context)
コード例 #27
0
class CapacityService():
    def setservices(self):
        from customer.factories import CustomerServicesFactory
        self.customer_service_factory = CustomerServicesFactory()
        from dealership.factories import DealerShipServicesFactory
        self.customer_service_factory = CustomerServicesFactory()
        self.dealer_service_factory = DealerShipServicesFactory()
        self.cuserservice = self.customer_service_factory.get_instance("user")
        self.userservice = self.dealer_service_factory.get_instance("user")
        self.appointment_service = self.dealer_service_factory.get_instance(
            "appointment")
        self.vehicle_service = self
        self.repair_service = self.dealer_service_factory.get_instance(
            "repair")
        self.dealership_service = self.dealer_service_factory.get_instance(
            "dealership")

    def get_available_slabs_for(self, slab_day, dealer, advisor=None):

        self.setservices()
        timings = self.dealership_service.get_dealer_shop_time(
            slab_day, dealer.id)
        now = timezone.now()
        available_slabs = []
        if timings:
            slab = timings["open_time"]
            while slab < timings["close_time"]:
                slab_time_obj = slab_day.strftime(
                    '%Y-%m-%d ') + slab.time().strftime('%H:%M')
                slab_time_obj = timezone.make_aware(
                    datetime.datetime.strptime(slab_time_obj,
                                               '%Y-%m-%d %H:%M'))
                if slab_time_obj > now:
                    slab_detail = {
                        "value":
                        slab_day.strftime('%Y-%m-%d ') +
                        slab.time().strftime('%H:%M'),
                        "name":
                        slab_day.strftime('%a %b %d, ') +
                        slab.time().strftime('%I:%M %p')
                    }
                    if self.check_slab_availibity(slab, dealer, None):
                        if advisor:
                            if self.check_slab_for_advisor(
                                    dealer, slab, advisor, None):
                                available_slabs.append(slab_detail)
                        else:
                            available_slabs.append(slab_detail)
                slab = slab + datetime.timedelta(minutes=timings["slot"])
        return available_slabs

    def get_capacity_for_slab(self, slab_time, dealer):
        total_techs = self.get_available_techs_count_for_slab_db(
            slab_time, dealer)

        return total_techs

    def get_capacity_for_date(self, slab_time, dealer):
        total_techs = self.get_available_techs_for_date(slab_time, dealer)

        shop_timings = self.dealership_service.get_dealer_shop_time(
            slab_time, dealer.id)

        capacity_per = 100
        hours = 9

        if shop_timings:
            capacity_per = shop_timings["capacity"]
            difference = shop_timings["close_time"] - shop_timings[
                "open_time"]  # difference is of type timedelta

            hours = difference.seconds / 60 / 60  # convert seconds into hour

        total_capacity = (hours * len(total_techs) * 3) * capacity_per / 100

        return total_capacity

    def check_slab_availibity(self, slab_time, dealer, appointment=None):
        """slab_time should be timezone aware time"""

        self.setservices()
        capacity_per = 100
        shop_timings = self.dealership_service.get_dealer_shop_time(
            slab_time, dealer.id)
        if shop_timings:
            capacity_per = shop_timings["capacity"]

        if appointment and appointment.advisor:
            if self.check_slab_for_advisor(dealer, slab_time,
                                           appointment.advisor) == False:
                return False

        total_capacity_slab = self.get_capacity_for_slab(slab_time, dealer)
        total_capacity = self.get_capacity_for_date(
            slab_time, dealer)  #new method to get capacity for date

        #       total_capacity =  round(total_capacity * (capacity_per/100.0))#getting percentage of capacity
        total_appointments_count = 0
        total_appointments_count_slab = 0
        total_appointments_slab = self.appointment_service.get_active_appointment_by_time(
            slab_time, dealer, None, appointment)
        total_appointments = self.appointment_service.get_active_appointment_by_date(
            slab_time, dealer, None, appointment)

        if total_appointments:
            total_appointments_count = len(total_appointments)
        if total_appointments_slab:
            total_appointments_count_slab = len(total_appointments_slab)
        if total_capacity > total_appointments_count:
            print total_capacity_slab
            print total_appointments_count_slab
            if total_capacity_slab > total_appointments_count_slab:
                return True

        return False

    def check_slab_for_advisor(self,
                               dealer,
                               slab_time,
                               advisor,
                               appointment=None):
        self.setservices()
        if self.check_user_availabe_for_slab(slab_time, advisor):
            if self.appointment_service.get_active_appointment_by_time(
                    slab_time, dealer, advisor, appointment):
                return False
            return True
        else:
            return False

    def save_tech_count_for_date_range(self, slab_start_date, slab_end_date,
                                       dealer):
        """
                slab_start_date : date object
                slab_end_date: date object
                dealer : dealer object
        """
        self.setservices()

        for n in range(int((slab_end_date - slab_start_date).days)):
            dt = slab_start_date + timedelta(n)
            self.save_tech_count_for_date(dt, dealer)

    def save_tech_count_for_date(self, slab_date, dealer):
        timings = self.dealership_service.get_dealer_shop_time(
            slab_date, dealer.id)
        if timings:
            slab = timings["open_time"]

            while slab < timings["close_time"]:
                #                 tmp_slab_up = slab + datetime.timedelta(minutes = timings["slot"])
                #                 if timings["on"]:
                self.save_tech_count_for_slab(slab, dealer)
                slab = slab + datetime.timedelta(minutes=timings["slot"])

    def save_tech_count_for_slab(self, slab_time, dealer):
        #         print slab_time
        count = self.get_available_techs_count_for_slab(slab_time, dealer)
        try:
            capacitycount = CapacityCounts.objects.get(time_slab=slab_time,
                                                       dealer=dealer)
        except Exception, e:
            capacitycount = CapacityCounts()
            capacitycount.time_slab = slab_time
            capacitycount.dealer = dealer
        capacitycount.total_tech = count
        capacitycount.save()
コード例 #28
0
ファイル: account.py プロジェクト: asimriaz85/bmw-grenlight
def accountview(request):
    """
            This is the account view where oyu can sae the account information
    """
    customer_factory = CustomerServicesFactory()
    user = request.user
    dealer_code = request.session["dealer_code"]
    account_service = customer_factory.get_instance("account")
    service = customer_factory.get_instance("user")
    template_name = 'customer/customer_account.html'
    name = request.user.first_name + " " + request.user.last_name
    userprofile = service.get_userprofile(request.user)
    insurance_profile = service.get_user_driver_insurance(userprofile)
    cc_profile = service.get_cc_profile(userprofile)
    account_initial = account_service.get_initial_user_form(user, userprofile)
    driver_initial = account_service.get_initial_driver_form(
        user, insurance_profile, userprofile)
    cc_initial = account_service.get_initial_cc_form(user, cc_profile,
                                                     userprofile)
    customer_form = CustomerAccountForm(instance=userprofile,
                                        initial=account_initial)
    driver_form = CustomerInsuranceForm(instance=insurance_profile,
                                        initial=driver_initial)
    cc_form = CreditDebitForm(instance=cc_profile, initial=cc_initial)
    pass_form = ChangePasswordForm()
    tab = "account"

    if request.method == 'POST':
        resp = False
        password_changed = False

        if request.POST.get("type") == "account":

            customer_form = CustomerAccountForm(request.POST,
                                                instance=userprofile)
            resp = account_service.save_account_form(user, userprofile,
                                                     customer_form,
                                                     account_initial)
            msg = "Account Information saved  successfully"  #

        elif request.POST.get("type") == "driver":
            driver_form = CustomerInsuranceForm(request.POST,
                                                instance=insurance_profile)
            resp = account_service.save_driver_form(insurance_profile,
                                                    driver_form)
            msg = "Driver Liscense and Insurance Information saved  successfully"

        elif request.POST.get("type") == "cc":
            cc_form = CreditDebitForm(request.POST, instance=cc_profile)
            resp = account_service.save_cc_form(cc_profile, cc_form)
            msg = "Debit/Credit form save successfully"

        elif request.POST.get("type") == "change_password":
            pass_form = ChangePasswordForm(request.POST)
            resp = account_service.save_password_form(pass_form, user)
            msg = "Password Changed successfully"
            password_changed = True
        if password_changed:
            messages.success(request, msg)
            return HttpResponseRedirect(
                reverse("customer:index") + "?dealer_code=" + dealer_code)
        elif resp:
            messages.success(request, msg)
            return HttpResponseRedirect(reverse("customer:accountsettings"))

    else:
        customer_form = CustomerAccountForm(instance=userprofile,
                                            initial=account_initial)
        driver_form = CustomerInsuranceForm(instance=insurance_profile,
                                            initial=driver_initial)
        cc_form = CreditDebitForm(instance=cc_profile, initial=cc_initial)
        pass_form = ChangePasswordForm()

    context = {
        "page_title": "Customer Profile",
        "tab": tab,
        "customer_form": customer_form,
        "driver_form": driver_form,
        "cc_form": cc_form,
        "pass_form": pass_form,
        "dealer_code": dealer_code,
        'acitve': True,
    }
    service.set_centrifuge_context(request,
                                   dealer_code,
                                   userprofile,
                                   context,
                                   chatposition="top")
    return render(request, template_name, context)
コード例 #29
0
def create_appointment(request):
    print request.POST, "######################"
    try:
        advisor_user = request.user

        customer_factory = CustomerServicesFactory()
        dealer_factory = DealerShipServicesFactory()
        dealer_service = dealer_factory.get_instance("dealership")
        uservice = customer_factory.get_instance("user")  #CUserService()
        capacity_service = dealer_factory.get_instance("capacity")
        appt_service = dealer_factory.get_instance("appointment")
        if request.method == "POST":
            now = timezone.now()
            try:
                shophrs = ShopHours.objects.get(
                    day=now.strftime('%A'),
                    shop_id=request.session['dealer_id'])
            except Exception, e:
                return JsonResponse({
                    'success': False,
                    'message': 'Dealership is closed'
                })
            open_time = timezone.make_aware(
                datetime.datetime.combine(datetime.date.today(),
                                          shophrs.time_from))
            closing_time = timezone.make_aware(
                datetime.datetime.combine(datetime.date.today(),
                                          shophrs.time_to))
            dealer = dealer_service.get_dealer_by_id(
                request.session['dealer_id'])
            if now > closing_time:
                return JsonResponse({
                    'success': False,
                    'message': 'Dealership is closed'
                })
            else:
                profile_id = request.POST.get('customer_id')
                if profile_id:
                    user = UserProfile.objects.get(id=profile_id)
                    slab_date = timezone.make_aware(datetime.datetime.today())
                    slabs = capacity_service.get_available_slabs_for(
                        slab_date, dealer, None)

                    if len(slabs) > 0:
                        slab = slabs[0]
                        vehicle = Vehicle.objects.get(
                            id=request.POST['vehicle_id'])
                        cv = None
                        try:
                            cv = CustomerVehicle.objects.filter(
                                user=user,
                                vehicle=vehicle,
                                vin_number=request.POST['vin']).first()
                        except CustomerVehicle.DoesNotExist:
                            cv = None
                        if cv == None:
                            cv = CustomerVehicle(
                                user=user,
                                vehicle=vehicle,
                                vin_number=request.POST['vin'])
                            cv.save()
                        slab_time = datetime.datetime.strptime(
                            slab["value"], '%Y-%m-%d %H:%M')
                        slab_time = timezone.make_aware(slab_time)
                        appt_save = appt_service.save_appoitment_with(
                            slab_time,
                            advisor_user.id,
                            1,
                            user.id,
                            None,
                            None,
                            dealer_id=dealer.id)
                        appt_save.vehicle = cv
                        appt_save.save()
                        if appt_save == False:
                            return JsonResponse({
                                "success":
                                False,
                                'message':
                                'Error Occured While Booking Appointment'
                            })
                    else:
                        return JsonResponse({
                            "success": False,
                            'message': 'No Slot Available'
                        })

                    return JsonResponse({
                        "success": True,
                        'message': 'accepted'
                    })
                else:
                    phone_number = request.POST.get("phone_number_1")
                    email = request.POST.get("email_1")
                    profile = uservice.get_user_profile_by_phone(phone_number)
                    if profile == None:
                        profile = uservice.get_user_profile_by_email(email)
                    if profile == None:
                        profile = UserProfile()
                    customer_form = GuestccountForm(request.POST,
                                                    instance=profile)
                    if customer_form.is_valid():
                        slab_date = timezone.make_aware(
                            datetime.datetime.today())
                        slabs = capacity_service.get_available_slabs_for(
                            slab_date, dealer, None)
                        if len(slabs) > 0:
                            slab = slabs[0]
                            profile = customer_form.save()
                            vehicle = Vehicle.objects.get(
                                id=request.POST['vehicle_id'])
                            cv = None
                            try:
                                cv = CustomerVehicle.objects.filter(
                                    user=profile,
                                    vehicle=vehicle,
                                    vin_number=request.POST['vin']).first()
                            except CustomerVehicle.DoesNotExist:
                                cv = None
                            if cv == None:
                                cv = CustomerVehicle(
                                    user=profile,
                                    vehicle=vehicle,
                                    vin_number=request.POST['vin'])
                                cv.save()

                            slab_time = datetime.datetime.strptime(
                                slab["value"], '%Y-%m-%d %H:%M')
                            slab_time = timezone.make_aware(slab_time)
                            appt_save = appt_service.save_appoitment_with(
                                slab_time,
                                advisor_user.id,
                                1,
                                profile.id,
                                None,
                                None,
                                dealer_id=dealer.id)
                            appt_save.vehicle = cv
                            appt_save.save()
                            if appt_save == False:
                                return JsonResponse({
                                    "success":
                                    False,
                                    'message':
                                    'Error Occured While Booking Appointment'
                                })
                        else:
                            return JsonResponse({
                                "success": False,
                                'message': 'No Slot Available'
                            })
                    else:
                        return JsonResponse({
                            "success":
                            False,
                            'message':
                            [(k, v[0])
                             for k, v in customer_form.errors.items()]
                        })
                    return JsonResponse({
                        "success": True,
                        'message': 'accepted'
                    })
    except Exception, e:
        print e
        print "Exception"
        return JsonResponse({
            "success":
            False,
            'message':
            'Error Occured while Booking Appointment'
        })