def get_requested_quotation_detail(request):
    """ This method returns a specific quotation details against the request in request details Page """
    try:
        store_user_track(
            request, "Customer Viewed Quotation" + request.GET.get("quote_uid")
        )  # for tracking user activity

        quote_id = request.GET.get("quote_uid")
        quotation = QuotationResponse.objects.get(quotation_uid=request.GET.get("quote_uid"))
        pro_images = PropertyImage.objects.filter(property_id=quotation.property_id)
        images = ""
        if pro_images:
            images = [image.image_name.url for image in pro_images]
        data = {
            "success": "true",
            "quote_uid": quotation.quotation_uid,
            "quote_date": quotation.quote_date.strftime("%d/%m/%Y"),
            "rate": quotation.rate,
            "amount": quotation.amount,
            "tax_amount": quotation.tax_amount,
            "images": images,
            "rack_rate": quotation.property_rack_rate,
            "total_amount": quotation.total_quote_amt,
            "action_text": quotation.action,
            "property_name": quotation.property_id.property_actual_name,
            "property_location": quotation.property_id.property_location,
            "facility_list": [q for q in quotation.property_id.property_facility.split(",") if q],
        }
        print data
    except Exception as e:
        print "Exception : ", e
        data = {"success": "false"}
    return HttpResponse(json.dumps(data), content_type="application/json")
def save_guest_information(request):
    print "save_guest_information"
    sid = transaction.savepoint()
    try:
        store_user_track(request, "Customer Adding new Guest")   # for tracking user activity
        if request.method == "POST":
            cam_id= request.session['user_id']
            cam_obj=Customer.objects.get(id=cam_id)
            guest_obj = Guest(
                guest_first_name = request.POST.get('guest_name'),
                guest_email = request.POST.get('guest_email'),
                guest_contactno = request.POST.get('phone_number'),
                customer_id = cam_obj,
                guest_status = 1,
                guest_creation_date = datetime.datetime.now()
            )
            guest_obj.save()
            guest_obj.guest_unique_id = 'CAMGST' +  str(cam_obj.id) + str(guest_obj.guest_id).zfill(6)
            guest_obj.save()
            transaction.savepoint_commit(sid)

            data = {'success': 'true', 'guest_id':guest_obj.guest_id , 'guest_name' : guest_obj.guest_first_name, 'email_id':guest_obj.guest_email, 'phone_no':guest_obj.guest_contactno }
        else:
            transaction.savepoint_rollback(sid)
            print 'Invalid Request'
            data = {'success': 'false' , ExceptionLabel.ERROR_MESSAGE :'Invalid Request'}
    except Exception, e:
        print 'error',e
        data = {'success': 'false', ExceptionLabel.ERROR_MESSAGE :'Server Error'}
def request_quote_details(request):
    if not request.user.is_authenticated():
        return redirect("/business/")
    print "Detail Page"
    store_user_track(request, "Customer Requesting Details")  # for tracking user activity
    data = get_request_info(request.GET.get("request_uid"))
    return render(request, "cam-user/quote-request/request-details.html", data)
def cam_password_change(request):
    store_user_track(request, "Customer Password Change")   # for tracking user activity
    #pdb.set_trace()
    try:
        if request.method == 'POST':
            data ={}
            #json_obj=json.loads(request.body)
            # if new password and confirm password are mis-matched..!
            if request.POST.get('new_password') != request.POST.get('new_password'):
                data = { 'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'New Password and Confirm Password Mis-matched!'} 
                return HttpResponse(json.dumps(data), content_type='application/json')
            
            user_obj = User.objects.get(id= request.session['user_id'])
            user = authenticate(username=user_obj.username, password= request.POST.get('current_password'))
            if user is not None:
                if user.is_active:
                    user.set_password(request.POST.get('new_password'))
                    user.save()
                    print 'succeess'
                    data= {'success' : 'true', ExceptionLabel.ERROR_MESSAGE:'Successfully Login'}
                else:
                    data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'User Is Not Active'}
            else:
                data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'Invalid Username or Password'}
        else:
            data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'Invalid Request'}
    except User.DoesNotExist:
        print 'usr'
        data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'User Not Exit'}
    except MySQLdb.OperationalError, e:
        print e
        data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'Internal Server Error '}
def cam_ledger_page(request):
    if not request.user.is_authenticated():
        return redirect('/business/')
    store_user_track(request,'Customer Ledger List')   # for tracking user activity
    cam_user_id = request.session['user_id']
    
    print 'Opening Ledger Page'
    data = {}
    return render(request,'cam-user/cam-ledger-list.html',data)
def edit_cam_profile_page(request):
    store_user_track(request,"Customer Edit Profile" )   # for tracking user activity
    if not request.user.is_authenticated():
        return redirect('/corporate/')
    try:
        cam = Customer.objects.get(id=request.session['user_id'])
        data = { 'cam' : cam }
    except Customer.DoesNotExist,e:
        print 'FAILED TO retrieve Customer information'
def submit_quote_request(request):
    a = ()
    try:
        store_user_track(request, "Customer Submitting New Request for quotation")  # for tracking user activity

        location_list = request.POST.getlist("location")
        location = "$".join(location_list)

        cust = Customer.objects.get(id=request.session["user_id"])

        quote_request = QuoteRequest(
            quote_category=request.POST.get("category"),
            quote_sub_category=request.POST.get("subcategory"),
            quote_start_date=datetime.datetime.strptime(request.POST.get("start"), "%d/%m/%Y"),
            quote_end_date=datetime.datetime.strptime(request.POST.get("end"), "%d/%m/%Y"),
            quote_city=request.POST.get("city"),
            quote_location=location,
            quote_property_type=request.POST.get("property_type"),
            property_rating=request.POST.get("property_rating"),
            quote_lowest_price=float(request.POST.get("minPrice")),
            quote_highest_price=float(request.POST.get("maxPrice")),
            quote_no_of_guest=request.POST.get("no_of_guest"),
            quote_no_of_room=request.POST.get("no_of_rooms"),
            quote_request_creation_date=datetime.datetime.now(),
            quote_remark=request.POST.get("remark"),
            customer_id=cust,
            quote_request_status=QuoteConstant.QUOTE_STATUS_OPEN,
            quote_customer_status=QuoteConstant.REQUEST_SUBMITTED,
        )
        a = quote_request
        quote_request.save()
        quote_request.quote_request_uid = "QR" + str(quote_request.quote_request_id).zfill(6)
        quote_request.save()
        try:
            # SMS to All Relationship Manager
            # send_new_request_sms_to_relationship_managers(quote_request.quote_request_uid,request.POST.get('start'), request.POST.get('end'), location_list[0] )
            # Message To DAR CUSTOMER CARE
            new_request_sms_to_admin("8928513850")  # test purpose
            # new_request_sms_to_admin('8087700499,7722071007,9175103645,9423567224')
        except Exception as err:
            print "Unable to send msg to Dial-A-Room Team"
        # This will search nearby properties and send email and sms to them
        nearby_properties(location, quote_request.quote_request_id)

        # This is added on 11 Dec 2015 for request statistics
        request_stat = UserRequestStatisticTrack(
            user_id=cust, request_path=request.path, request_date=datetime.datetime.today(), request_id=quote_request
        )
        request_stat.save()

        data = {"quote": quote_request}
        return HttpResponseRedirect("/corporate/quote/request-list/?success=1")
    except Exception as err:
        print "Exception : ", err
        data = {"quote": a, "status": 1, "error_message": "Could not submit the request"}
    return render(request, "cam-user/quote-request/request-new-quote.html", data)
def cam_new_booking_search(request):
    store_user_track(request, "Customer New Booking Search")   # for tracking user activity
    if not request.user.is_authenticated():
        return redirect('/corporate/?next='+request.path)
    try:
        corporate_user = Customer.objects.get(id=request.session['user_id'])
        prefered_properties = CustomerFavoriteProperty.objects.filter(customer_id=corporate_user)
        data = {'prefered_properties': [ get_property_info(pre_property.property_id,corporate_user) for pre_property in prefered_properties ] }
        print data
    except Exception as err:
        print 'Exception : ',err
        data = {'prefered_properties': []}
    return render(request,'cam-user/cam-booking-search.html',data)
def cam_my_profile(request):
    store_user_track(request, "Customer Profile Page")   # for tracking user activity
    if not request.user.is_authenticated():
        return redirect('/?next='+request.path)
    try:
        if request.session['user_id']:
            cam = Customer.objects.get(id=request.session['user_id'])
        else:
            cam = Customer.objects.get(cust_unique_id=request.GET.get('profile'))
        
        data = { 'cam' : cam , 'fav_properties' : get_favorite_list(cam) }
    except Customer.DoesNotExist,e:
        print 'FAILED TO retrieve Customer information'
def corporate_quote_booking_page(request):
    
    data = {}
    try:
        store_user_track(request, 'Customer moved to Booking By Accepting Quotation') # for tracking user activity
        
        qt = QuotationResponse.objects.get(quotation_uid=request.GET.get('qtuid'))
        guest_list = guests = Guest.objects.filter(customer_id= qt.request_id.customer_id)
        data = { 'quotation' : qt, 'quote_request':qt.request_id, 'guest_list': guest_list }
    except Exception as err:
        print 'exception : ',err
        data = { 'quotation': '', 'quote_request':'','error_message': 'Oops Something Wrong..!' }
    return render(request,'cam-user/quote-request/quote-booking.html',data)
def open_payment_page(request):
    try:
        store_user_track(request, "Customer Payment")   # for tracking user activity
        
        customer = Customer.objects.get(id=request.session['user_id'])
        bookings = Booking.objects.filter(customer_id=customer)
        invoices = Invoice.objects.filter(booking_id__in=bookings)
        #booking_list = [booking.booking_unique_id for booking in bookings]
        data = { 'invoices' : invoices, 'fullName' : customer.cust_first_name + ' ' +  customer.cust_last_name,
            'email' : customer.cust_email, 'phoneNumber' : customer.cust_contact_no }
    except Exception as err:
        print 'error : ',err
        data = { 'invoices' : [] }
    return render(request,'cam-user/cam-payment-page.html',data)
def get_specific_property_info(request):
    """ This is getting specific property information at the time of Booking search page """
    store_user_track(request, "Customer Views Property Information For Booking")   # for tracking user activity
    try:
        property_obj = Property.objects.get(property_id = request.GET.get('property_id'))
        
        pro_images = PropertyImage.objects.filter(property_id=property_obj)
        images = ''
        if pro_images:
            images = [image.image_name.url for image in pro_images]
        data = { 'success':'true', 'property_name': property_obj.property_actual_name, 'property_location' : property_obj.property_location,
         'images':images, 'facility_list' : [q for q in property_obj.property_facility.split(',') if q]}
    except Exception as e:
        print 'Exception '
        data = {}
    return HttpResponse(json.dumps(data), content_type='application/json')
def payment_details(request):
    try:
        store_user_track(request,'Customer Online Payment Result ')   # for tracking user activity
        response_code = request.GET.get('response_code')
        response_status = request.GET.get('response_status')
        if response_code!='null':
            payment_obj = PaymentTransaction.objects.get(payment_transaction_id=response_code)
            if response_status== 'true' and payment_obj.f_code == OK :
                data = {'success' : 1, 'error_message': payment_obj.error_description }
            else:
                data = {'success' : 2, 'error_message': payment_obj.error_description }
        else:
            data = {'success' : 2, 'error_message': 'Oops something went wrong...'}
    except Exception as err:
        print err
        data = {'success' : 2, 'error_message': 'Oops something went wrong...'}
    return render(request,'cam-user/cam-payment-success.html', data)
Example #14
0
def show_dashboard(request):
#    return authenticate_system_user(request)
    store_user_track(request, "Admin Dashboard")
    try:
        print 'Dashboard'
        today = date.today()
        if today.month <=3:
            start_date = date(today.year-1, 04, 01)  # (yy,mm,dd)
            end_date = date(today.year, 03, 31)  # (yy,mm,dd)
        else:
            start_date = date(today.year, 04, 01)  # (yy,mm,dd)
            end_date = date(today.year+1, 03, 31)  # (yy,mm,dd)
            
        # This is for getting the list of Bookings against month
        #monthly_bookings = CAMBooking.objects.filter(cam_booking_estimated_checkin_date__range=(start_date, end_date)).extra(select={'month': "EXTRACT(month FROM cam_booking_estimated_checkin_date)"}).values('month').annotate(total=Count('cam_booking_id'))
        #monthly_bookings = CAMBooking.objects.filter(cam_booking_estimated_checkin_date__range=(start_date, end_date)).extra(select={'month': "EXTRACT(month FROM cam_booking_estimated_checkin_date)"}).values('month','cam_booking_estimated_no_of_day_stay').annotate(total=Count('cam_booking_id'))
        monthly_bookings = Booking.objects.filter(booking_estimated_checkin_date__range=(start_date, end_date)).extra(select={'month': "EXTRACT(month FROM booking_estimated_checkin_date)"}).values('month').annotate(total=Sum('booking_estimated_no_of_day_stay'))
        list = {}
        # Convert a month value and total value into single dictionary as 
        # Month is Key and Total as Value,so that it can sorted in ascending order 
        for book in monthly_bookings:   
            list[book['month']]=book['total']
        monthly_booking_count =[]
        
        try:
            for m in FY_MONTH_LIST:
                monthly_booking_count.append(list[m])
        except KeyError,e:
            print monthly_booking_count
            
        print monthly_booking_count
        
        month_amt, total_amt = get_month_and_total_amount()
        request.session['ADMIN_total_income'] = total_amt
        data = {
            'cam_count': get_cam_count(),
            'guest_count':get_guest_count(),
            'available_rooms': get_no_of_available_rooms(),
            'month_amount': month_amt,
            'total_amount': total_amt,
            'booked_rooms':get_no_of_booked_rooms(),
            'graph_data_list' : monthly_booking_count,
            'start_date': start_date.strftime('%b %Y'),
            'end_date':end_date.strftime('%b %Y')
        }
        print data
def cam_booking_detail_display(request):
    if not request.user.is_authenticated():
        return redirect('/corporate/?next='+request.path)
    store_user_track(request,"Customer Booking Details Page")   # for tracking user activity
    try:
        if request.GET.get('booking_id'):
            v_booking_id = request.GET.get('booking_id')
            cam_booking_obj = Booking.objects.get(booking_unique_id=v_booking_id)
            if cam_booking_obj.booking_status == BOOKING_OPEN:
                return render(request,'cam-user/cam-booking-details.html', get_booking_details(v_booking_id))
            else:
                return render(request,'cam-user/booking-completed-cancelled-booked.html', get_booking_details(v_booking_id))
        else:
            print 'Hello'
            data = {'success': 'false'}
    except Exception, e:
        print 'Exception : ', e
        data = { 'success': 'false','error_message': 'Internal Server Error' }
Example #16
0
def admin_login(request):
    print 'request accepted'
    try:
        if request.method == 'POST':
            user = authenticate(username=request.POST.get('username'), password= request.POST.get('password'))
            if user is not None:
                if user.is_active:
                    login(request,user)
                    request.session['login_user']=user.username
                    request.session['login_status']=True
                    request.session['user_id']= user.id
                    if user.is_superuser :
                        store_user_track(request,'Admin Login')   # for tracking user activity
                        return redirect('/business/dashboard/')
                    else:
                        customer = Customer.objects.get(id=user.id)
                        if customer.user_type == CORPORATE:
                            if customer.cust_image:
                                request.session['user_profile_image'] = SERVER_MEDIA_URL + customer.cust_image.url
                            else:
                                request.session['user_profile_image'] = SERVER_MEDIA_URL + USER_PLACEHOLDER
                        request.session['user_full_name'] = customer.cust_first_name + ' '+ customer.cust_last_name
                        store_user_track(request,'Customer Login')   # for tracking user activity
                        if request.POST.get('next'):
                            return HttpResponseRedirect(request.POST.get('next'))
                        else:
                            return HttpResponseRedirect('/corporate/')
                        #return render(request,'/cam/',context_instance=RequestContext(request))
                else:
                    print 'User Not Active'
                    data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'User Is Not Active'}
            else:
                print 'User Not Available'
                data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'Invalid Username or Password'}
        else:
            print 'Invalid Request'
            data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'Invalid Request'}
    except User.DoesNotExist:
        print 'usr'
        data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'User Not Exist'}
    except MySQLdb.OperationalError, e:
        print e
        data= {'success' : 'false', ExceptionLabel.ERROR_MESSAGE:'Internal Server Error '}
def update_guest_information(request):
    
    try:
        store_user_track(request, "Customer Updating Guest Details")   # for tracking user activity
        if request.method == "POST":
            var_guest_id = request.POST.get('edit_guest_id')
            guest_obj = Guest.objects.get(guest_id = var_guest_id)
            guest_obj.guest_first_name = request.POST.get('edit_guest_name')
            guest_obj.guest_email = request.POST.get('edit_guest_email')
            guest_obj.guest_contactno = request.POST.get('edit_phone_number')
            guest_obj.guest_status = request.POST.get('edit_guest_active_status')
            guest_obj.save()
            data = {'success': 'true'}
        else:
            print 'Invalid Request'
            data = {'sucess': 'false' , ExceptionLabel.ERROR_MESSAGE :'Invalid Request'}
    except Exception, e:
        print 'error',e
        data = {'sucess': 'false', ExceptionLabel.ERROR_MESSAGE :'Server Error'}
def request_list_page(request):
    print 'Quote Request List Page'
    data="";
    try:
        request.session['vendor_name']
    except:
        sign_out_vendor(request)
        return redirect('/vendor/')

    if not request.user.is_authenticated():
        return redirect('/vendor/')
    try:
        # store user activities
        store_user_track(request,'Vendor Opening Request List Page' )
        
        vendor = Customer.objects.get(id=request.session['apt_vendor_id'])
        data = { 'vendor' : vendor }
    except Customer.DoesNotExist,e:
        print 'FAILED TO retrieve Customer information'
def cam_new_booking_page(request):
    """
    This web service open a new page for adding booking by Customer.
    Check In Date, CheckOut Date and City
    """
    store_user_track(request, "Customer New Booking Page")   # for tracking user activity
    try:
        print '--|  New booking Page  |--'
        var_property_id = request.GET.get('apartment_room_id')
        var_check_in = request.GET.get('check_in')
        var_check_out = request.GET.get('check_out')
##        if request.GET.get('check_in'):
##            check_in_date=datetime.datetime.strptime(var_check_in, '%d/%m/%Y')
##            check_out_date=datetime.datetime.strptime(var_check_out, '%d/%m/%Y')
##            d = check_out_date - check_in_date
##        else:
        check_in_date = datetime.date.today()
        check_out_date = datetime.date.today()
        d = check_out_date - check_in_date
        # getting list of Customer users

        print request.session['user_id']
        cam_user= Customer.objects.get(id=request.session['user_id'])

        guests = Guest.objects.filter(customer_id=cam_user)
        property_obj = Property.objects.get(property_id=var_property_id)

        pro_images = PropertyImage.objects.filter(property_id=property_obj)
        images = ''
        if pro_images:
            images = [image.image_name.url for image in pro_images]
            images = '$'.join(images)
        
        data = { 'success':'true','property': property_obj, 'no_of_days': str(d.days), 'image_list': images,
         'check_in':check_in_date.strftime('%d/%m/%Y'), 'check_out':check_out_date.strftime('%d/%m/%Y'),
         'guest_list':guests, 'facility_list' : [f for f in property_obj.property_facility.split(',') if f ] }
        print data
        #data = { 'success':'true', 'guest_list':guests }
    except Exception, e:
        print 'Exception ',e
        data = { 'success': 'false' }
def print_cam_ledger_transactions(request):
    print 'transactions'
    cam_user_id = request.session['user_id']
    balance_amount = 0.0
    data = {}
    var_transaction_list = []
    desc = ''
    store_user_track(request,'Customer Printing Ledger Report')   # for tracking user activity
    try:
        customer_obj=Customer.objects.get(id=cam_user_id)
        corporate_name = customer_obj.cust_company_id.company_name
        company_address = customer_obj.cust_company_id.get_company_address()
        company_state_pin = customer_obj.cust_company_id.get_company_state_pincode()
        i=0
        transactions = CorporateTransaction.objects.filter(corporate_id=customer_obj)
        for transaction in transactions :
            i = i+1
            if transaction.transaction_type == 1:
                balance_amount = balance_amount + transaction.transaction_amount
                amt = transaction.transaction_amount
                desc = 'Invoice : ' + str(transaction.invoice_id)
            else:
                balance_amount = balance_amount - transaction.transaction_amount
                amt = -transaction.transaction_amount
                desc = 'Deposit'
            var_transaction_list.append({ 'sr_no':i,  'date' : transaction.transaction_date.strftime('%d/%m/%Y'), 'desc': desc, 'amount' : '{:,.2f}'.format(amt), 'balance' : '{:,.2f}'.format(balance_amount) })
        data = { 'transaction_list' : var_transaction_list, 'corporate_name': corporate_name, 'company_address':company_address,'company_state_pin':company_state_pin, 'final_balance' : '{:,.2f}'.format(balance_amount) }
        
    except Exception as err:
        print 'Error',err
        data = { 'data' : 'None' }
        
    return render_to_pdf(
            'cam-user/cam-ledger-print.html',
            {
                'pagesize':'A4',
                'data' : data
            }
        )
def cam_booking_confirm_page(request):
    """
    This request method will redirect to booking details page,
    where user can view/add guest Detail and confirms the booking details.
    Also This is used for to confirm the booking details which is registered from
    Mobile app.
    """
    store_user_track(request,"Customer Booking Confirm Page")   # for tracking user activity

    if not request.user.is_authenticated():
        return redirect('/corporate/')
    try:
        if request.GET.get('booking_id'):
            booking_id = request.GET.get('booking_id')
            return render(request,'cam-user/cam-new-booking.html', get_booking_details(booking_id) )
            #return render(request,'cam-user/cam-booking-confirmed-page.html', get_booking_details(booking_id) )
        else:
            print 'Hello'
            data = { 'success': 'false'}
    except Exception, e:
        print 'Exception : ', e
        data = { 'success': 'false'}
def update_cam_profile_info(request):
    """
    This is for updating the cam Information
    """
    store_user_track(request, "Customer Updating Profile")   # for tracking user activity
    try:
        if request.method == "POST":
            print 'Request Accepted '
            cam_obj = Customer.objects.get(id= request.POST.get('cam_user_id'))

##            cam_obj.username = request.POST.get('user_name')
##            cam_obj.password = request.POST.get('passwd')
            cam_obj.cust_first_name = request.POST.get('first_name')
            cam_obj.cust_last_name = request.POST.get('last_name')
            cam_obj.cust_company_id = Company.objects.get(company_id=request.POST.get('company_name'))
            cam_obj.cust_email       = request.POST.get('cam_email')
            cam_obj.cust_contact_no  = request.POST.get('contact_number')
            cam_obj.cust_address_line   = request.POST.get('address_line')
            cam_obj.cust_city   = request.POST.get('city')
            #cam_obj.cam_state   = request.POST.get('state')
            #cam_obj.cam_country   = request.POST.get('country')
            cam_obj.cust_pincode   = request.POST.get('pincode')
            cam_obj.cust_gender   = request.POST.get('gender')
            cam_obj.cust_age   = request.POST.get('cam_age')
            cam_obj.email_alert_on   = request.POST.get('email_alert')
            cam_obj.sms_alert_on   = request.POST.get('sms_alert')

            cam_obj.save()
##            cam_obj.set_password(request.POST.get('passwd'))
##            cam_obj.save()
            data = {'success': 'true','cam':cam_obj, 'mode':'show' }
        else:
            print 'Invalid Request'
            data = {'sucess': 'false' , ExceptionLabel.ERROR_MESSAGE :'Invalid Request'}
        return redirect('../cam-my-profile/?profile='+cam_obj.cust_unique_id)
    except Exception, e:
        print 'error',e
        data = {'sucess': 'false', ExceptionLabel.ERROR_MESSAGE :'Server Error'}
def get_cam_ledger_transactions(request):
    print 'transactions'
    cam_user_id = request.session['user_id']
    balance_amount = 0.0
    data ={}
    var_transaction_list =[]
    desc = ''
    try:
        store_user_track(request,'Customer check for ledger ')   # for tracking user activity
        print 'GET REQUEST : ',  request.GET
        i=0
        if request.GET.get('startDate'):
            startDate = datetime.datetime.strptime(request.GET.get('startDate'), '%d/%m/%Y')
            endDate = datetime.datetime.strptime(request.GET.get('endDate'), '%d/%m/%Y')
            transactions = CorporateTransaction.objects.filter(corporate_id=Customer.objects.get(id=cam_user_id), transaction_date__range=[startDate, endDate] )
            
        else:
            print 'I am in Else'
            transactions = CorporateTransaction.objects.filter(corporate_id=Customer.objects.get(id=cam_user_id))
            
        for transaction in transactions :
            i = i+1
            if transaction.transaction_type == 1:
                balance_amount = balance_amount + transaction.transaction_amount
                amt = transaction.transaction_amount
                desc = 'Invoice :' + str(transaction.invoice_id)
            else:
                balance_amount = balance_amount - transaction.transaction_amount
                amt = -transaction.transaction_amount
                desc = 'Deposit'
            var_transaction_list.append({ 'sr_no':i,  'date' : transaction.transaction_date.strftime('%d/%m/%Y'), 'desc': desc, 'amount' : '{:,.2f}'.format(amt), 'balance' : '{:,.2f}'.format(balance_amount) })
        data = { 'data' : var_transaction_list }
    except Exception as err:
        print 'Error',err
        data = { 'data' : 'None' }
    return HttpResponse(json.dumps(data), content_type='application/json')
def cam_guest_list(request):
    store_user_track(request,"Customer Guest List")   # for tracking user activity
    if not request.user.is_authenticated():
        return redirect('/coporate/')
    return render(request,'cam-user/cam-guest-list.html')
def new_booking_from_dashboard(request):
    if not request.user.is_authenticated():
        return redirect('/corporate/')
    sid = transaction.savepoint()
    print request.POST
    
    try:
        print 'Request Accepted '
        store_user_track(request, "Customer Doing Booking From Dashboard")   # for tracking user activity
        if request.method == "POST":
            v_cam_id        = request.session['user_id']
            var_property_id = request.POST.get('property_id')
            occupancy_type  = int(request.POST.get('occupancy_type'))
            check_in    = datetime.datetime.strptime(request.POST.get('check_in'), '%d/%m/%Y')
            check_out   = datetime.datetime.strptime(request.POST.get('check_out'), '%d/%m/%Y')
            
            guest_list = request.POST.get('guest_ids')
            guest_list = guest_list.split(',')
            # Getting Property Object
            property_obj = Property.objects.get(property_id=var_property_id)
            
            # Default Property Rate if it is not decided for CAM.
            default_rate = PropertyRate.objects.get(property_id=property_obj)
            occupancy_rate =0
        
            # Customer Object
            cam_obj= Customer.objects.get(id=v_cam_id)
            # This is for fetching property rates and applying rates according to occupancy type
            property_rates = CAMPropertyRate.objects.filter(property_id=property_obj, cust_id=cam_obj)
            if property_rates:
                for rate in property_rates:
                    if int(rate.occupancy_type) == int(occupancy_type):
                        occupancy_rate = rate.agreed_rate
            else:
                if occupancy_type == 0:
                    occupancy_rate = default_rate.single_occupancy_display_rate
                else:
                    occupancy_rate = default_rate.double_occupancy_display_rate
            
            days = check_out - check_in
            if days.days == 0:
                day = 1
            else:
                day = days.days
                
            booking_obj = Booking(
                customer_id     = cam_obj,
                guest_id        = None,
                property_id     = property_obj,
                booking_estimated_checkin_date  = check_in,
                booking_actual_checkin_date     = check_in,
                booking_estimated_checkout_date = check_out,
                booking_actual_checkout_date    = check_out,
                booking_estimated_checkout_time = datetime.datetime.now().time(),
                booking_estimated_checkin_time  = datetime.datetime.now().time(),
                booking_estimated_no_of_day_stay = days.days,
                booking_actual_no_of_day_stay   = day,
                booking_status  = BOOKING_OPEN, #BOOKING_BOOKED
                booking_rate    = occupancy_rate
            )
            booking_obj.save()
            booking_obj.booking_unique_id = 'BK' +  datetime.date.today().strftime('%d%m%y') + str(booking_obj.booking_id).zfill(6)
            booking_obj.save()
            
            # Generating Invoice
            
            amount = occupancy_rate * day
            service_tax_amount = ( amount * SERVICE_TAX )/100
            luxury_tax_amount  = ( amount * LUXURY_TAX )/100
        
            tax_amount = service_tax_amount + luxury_tax_amount
            gross_amount = amount + tax_amount
            invoice = Invoice(
                booking_id = booking_obj,
                room_charges = amount,
                invoice_total_amount = amount,
                tax_amount  = tax_amount,
                invoice_gross_amount = gross_amount,
                invoice_status = 0,
            )
            invoice.save()
            invoice.invoice_unique_id = 'INVBK' + str(booking_obj.booking_id) + str(invoice.invoice_id).zfill(6)
            invoice.save()
            
            corporate_transaction = CorporateTransaction(
                invoice_id      = invoice.invoice_unique_id,
                corporate_id    = cam_obj,
                transaction_amount= invoice.invoice_gross_amount,
                transaction_type = 1
            )
            corporate_transaction.save()
            
            # guest bookings
            for guest in guest_list:
                guest_in_booking = BookingGuest(
                    guest_id    = Guest.objects.get(guest_id=guest),
                    booking_id  = booking_obj
                )
                guest_in_booking.save()
                
            # Update booking with guest
            booking_obj.guest_id = guest_in_booking.guest_id
            booking_obj.save()
            
            # This is for Booking Statistics added on 11 Dec 2015
            booking_stat = UserBookingStatisticTrack(
                user_id = cam_obj,
                booking_path = request.path,
                booking_date = datetime.date.today(),
                booking_id = booking_obj
            )
            booking_stat.save()
            transaction.savepoint_commit(sid)
            try:
                # Sending SMS to vendot regarding booking submission
                send_booking_submission_sms_to_vendor(property_obj.property_owner_id.cust_contact_no, property_obj.property_owner_id.cust_first_name,
                    booking_obj.booking_unique_id, property_obj.property_actual_name,  booking_obj.booking_id)
                # Sending Booking Submission SMS to Corporate User
                send_booking_submission_sms_to_customer(cam_obj.cust_contact_no, cam_obj.cust_first_name, booking_obj.booking_unique_id)
                # Sending Booking Submission Email to Corporate User
                send_booking_submission_mail_with_template(booking_obj.booking_id)
            except Exception as err:
                print 'SMS/ Email not sent to vendor/ customer / '
            data = {'success':'true', 'error_message':'Successfullly Booked'}
            return HttpResponse(json.dumps(data), content_type='application/json')
            #return redirect('/corporate/cam-booking-details/?booking_id='+ str(booking_obj.booking_unique_id))
        else:
            print 'Hello'
            transaction.savepoint_rollback(sid)
            data = {'success':'false', 'error_message':'Invalid Request'}
    except Exception, e:
        print 'cam_additional_functionality.py | new_booking_from_dashboard | EXCEPTION ', e
        transaction.savepoint_rollback(sid)
def save_payment_gateway_response(request):
    print "save_payment_details"
    try:
        print request.POST
        link=''
        if request.method == 'POST':
            store_user_track(request,"Customer Online Payment Gateway Response")   # for tracking user activity
            print 'Online Payment Status', request.POST.get('mmp_txn')
            payment_obj = PaymentTransaction(
                mmp_txn                            =    request.POST.get('mmp_txn'),
                ipg_txn_id                         =    request.POST.get('ipg_txn_id'),
                transaction_type                   =    request.POST.get('transaction_type'),
                property_booking_id                =    request.POST.get('udf4'),
                discriminator                      =    request.POST.get('discriminator'),
                srcharge                           =    request.POST.get('surcharge'),
                customer_name                      =    request.POST.get('udf1'),
                mer_txn                            =    request.POST.get('mer_txn'),
                card_number                        =    request.POST.get('CardNumber'),
                ath_code                           =    request.POST.get('auth_code'),
                prod                               =    request.POST.get('prod'),
                bank_name                          =    request.POST.get('bank_name'),
                date                               =    request.POST.get('date'),
                merchant_id                        =    request.POST.get('merchant_id'),
                amount                             =    request.POST.get('amt'),
                error_description                  =    request.POST.get('desc'),
                bank_txn                           =    request.POST.get('bank_txn'),
                f_code                             =    request.POST.get('f_code'),
                clientcode                         =    request.POST.get('clientcode'),
                mobile_no                          =    request.POST.get('udf3'),
                email_id                           =    request.POST.get('udf2'),
                udf5                               =    request.POST.get('udf5'),
                billing_address                    =    request.POST.get('udf4'),
                udf6                               =    request.POST.get('udf6'),
                booking_transaction_create_by      =    request.POST.get('udf1'),
                booking_transaction_update_by      =    request.POST.get('udf1')
            )
            payment_obj.save()

            data = {
                'success': 'true',
                'cust_email':payment_obj.email_id,
                'error_message': payment_obj.error_description,
                'merchant_id':payment_obj.merchant_id,
                'mer_txn':payment_obj.mer_txn,
                'amt':payment_obj.amount,
                'date':payment_obj.date,
            }

            if payment_obj.f_code == OK :
                invoices = payment_obj.udf6.split(',') # Getting invoice list for confirming the paid status and paid date
                for inv_no in invoices:
                    invoice = Invoice.objects.get(invoice_unique_id=inv_no)
                    invoice.invoice_status = PAID
                    invoice.booking_id.payment_status = PAID
                    invoice.invoice_paid_date = datetime.datetime.now()
                    invoice.save()

                data.update({ 'invoice_list' : invoices })
                
                return redirect('/corporate/payment-detail/?response_code='+str( payment_obj.payment_transaction_id)+'&response_status=true')
            else:
                return redirect('/corporate/payment-detail/?response_code='+str( payment_obj.payment_transaction_id)+'&response_status=false')
    except Exception as e:
        print e
    return redirect('/corporate/payment-detail/?response_code=null&response_status=false')
def request_quote_details(request):
    #pdb.set_trace()
    try:
         request.session['vendor_name']
    except:
         sign_out_vendor(request)
         return redirect('/vendor/')
    data = {}
    try:
        # store user activities
        store_user_track(request,'Vendor Views Request Details '+request.GET.get('request_uid') )
        # Request Objects
        quote_req = QuoteRequest.objects.get(quote_request_uid=request.GET.get('request_uid'))
        locations = quote_req.quote_location.split('$')
        
        quote_requote = REQUOTE # By Default Requote
        days = quote_req.quote_end_date - quote_req.quote_start_date
        
        owner = Customer.objects.get(id=request.session['apt_vendor_id'])
        
        if days.days == 0:
            no_of_days = 1
        else:
            no_of_days = days.days
        
        my_status = 0
        
        # GET APARTMENT LIST OF OWENR
        apartment_list = Property.objects.filter(property_owner_id=owner)
        property_list = []
        try:
            requestProperty = RequestedProperty.objects.filter(quote_request_id=quote_req, property_owner_id=owner, property_id__in= apartment_list, quoted_status=False )
            if requestProperty: 
                for req_prop in requestProperty:
                    if req_prop.property_id.property_type == 0:
                        prop_type='Service Apartment'
                    if req_prop.property_id.property_type == 1:
                        prop_type='Hotel'
                    if req_prop.property_id.property_status ==1:
                        status='NOT AVAILABLE'
                    if req_prop.property_id.property_status ==0:
                        status='AVAILABLE'
                    
                    quote_requote = QUOTE #if not req_prop.quoted_status else REQUOTE
                    
                    rate = get_property_rate(req_prop.property_id)
                    amount = rate * no_of_days * quote_req.quote_no_of_guest
                    tax_amount = amount * (SERVICE_TAX + LUXURY_TAX) / 100
                    total = amount + tax_amount
                
                    property_list.append({ 'property_id': req_prop.property_id.property_id,
                    'property_location':req_prop.property_id.property_location,
                    'property_name': req_prop.property_id.property_actual_name, 'tax' : '{:.2f}'.format(tax_amount),
                    'property_rack_rate' : req_prop.property_id.rack_rate, 'quote_status' : req_prop.quoted_status, 
                    'property_rate' : '{:.2f}'.format(rate), 'amount' : '{:.2f}'.format(amount), 
                    'total_amt': '{:.2f}'.format(total),'property_type' : prop_type, 'status' :status })
            else:
                property_list = get_quoted_property(quote_req,owner)
        except Exception as err:
            print 'vendor_request.py | request_quote_details | Exception ', err
            mystatus = 0

        data = { 'quote' : quote_req,   'error_message': 'success',
           'no_of_days':no_of_days,     'success': 'true', 'quote_requote': quote_requote,
           'my_status' : my_status,     'property_list': property_list,
           'location_list': locations,  'city_list': pcf.get_all_city_name(),
           #'quoted_property_list':get_quoted_property(quote_req,owner) 
        }
    except Exception as err:
        print 'vendor_request.py | request_quote_details | Exception ', err
        data = {}
    return render(request,'property-vendor/quote-request/request-details.html',data)
def send_quotation(request):
    print 'send_quotation'
    property_ids = request.POST.getlist('property_ids')
    rate      = request.POST.getlist('rate')
    amount    = request.POST.getlist('amt')
    tax       = request.POST.getlist('tax')
    total_amt = request.POST.getlist('total_amt')

    # newly added on 14 Dec 2015
    rack_rate = request.POST.getlist('rack_rate')

    try:
        # store user activities
        store_user_track(request,'Vendor Sending Quotation against '+request.POST.get('request_id'))
        quote_req = QuoteRequest.objects.get(quote_request_id=request.POST.get('request_id'))
        
        if request.POST.get('quote_requote') == QUOTE:
        # If Already Quoted 
        #for prop in property_details:
            index=0
            for prop_id in property_ids:
                property= Property.objects.get(property_id=prop_id)
                property.rack_rate = rack_rate[index]
                property.save()
                    
                quotation = QuotationResponse(
                    request_id              = quote_req,
                    property_id             = Property.objects.get(property_id=prop_id),
                    rate                    = rate[index],
                    amount                  = amount[index],
                    tax_amount              = tax[index],
                    total_quote_amt         = total_amt[index],
                    property_rack_rate      = property.rack_rate,   # rack rate
                    quote_date              = datetime.datetime.today() ,
                    created_date            = datetime.datetime.today(),
                    created_by              = 'Admin',
                    is_new                  = True,
                    quotation_status        = 'QUOTED',
                    viewed_by_customer      = False
                )
                index += 1
                quotation.save()
                quotation.quotation_uid='QT'+str(quotation.quotation_id).zfill(6)
                quotation.save()
                try:
                    requestedProperty = RequestedProperty.objects.get(property_id=quotation.property_id,quote_request_id=quotation.request_id,property_owner_id =quotation.property_id.property_owner_id)
                    requestedProperty.quoted_status = True
                    requestedProperty.save()
                except Exception as err:
                    print 'Error '
                # Send SMS and EMAIL
                send_mail_and_sms_for_quotation(quote_req,quotation)
            print 'Quotation Successfully Saved'
        else:
            # Else Update the previous quote
            index = 0
            quotations = request.POST.getlist('quotations')
            for quote_id in quotations:
                try:
                    quotation = QuotationResponse.objects.get(quotation_id=quote_id)
                    quotation.request_id = quote_req
                    quotation.property_id = Property.objects.get(property_id=property_ids[index])
                    quotation.rate          = rate[index]
                    quotation.amount        = amount[index]
                    quotation.tax_amount    = tax[index]
                    quotation.total_quote_amt       = total_amt[index]
                    quotation.property_rack_rate    = rack_rate[index]
                    quotation.quote_date    = datetime.datetime.today()
                    quotation.created_by    = request.session['vendor_name']
                    quotation.save()
                    index+=1
                    # Send SMS and EMAIL
                    send_mail_and_sms_for_quotation(quote_req,quotation)
                except Exception as err:
                    print 'vendor_request.py | send_quotation | Update Quote | Exception ', err
            print 'Update Successfully '
    except Exception, e:
        print 'Exception : ',e
        data = { 'sucess': 'false' }
def cam_dashboard(request):
    store_user_track(request,'Customer Dashboard')   # for tracking user activity
    print 'CAM Dashboard'
    print 'REQUEST : ', dir(request)
    #pdb.set_trace()
    try:
        cam_id = int(request.session['user_id'])
        cam_object = Customer.objects.get(user_ptr_id=cam_id)
        total_days = cam_object.customerbooking.aggregate(total=Sum('booking_actual_no_of_day_stay'))
        cam_total_days = total_days['total']

        # Number of guest count
        no_of_guests = Guest.objects.filter(customer_id= cam_object).count()
        print 'Number Of Guest : ', no_of_guests

        this_month_days = 0
        this_month_amount = 0
        sum =0
        amount_fy   = 0
        days_fy     = 0
        this_month  = datetime.datetime.today().month
        this_year   = datetime.datetime.today().year

        if this_month <= 3:
            str_start_date  = '01-04-' + str((datetime.datetime.today().year - 1))
            str_end_date    = '31-03-' + str((datetime.datetime.today().year))
        else:
            str_start_date  = '01-04-' + str((datetime.datetime.today().year))
            str_end_date    = '31-03-' + str((datetime.datetime.today().year+1))

        start_date  = datetime.datetime.strptime(str_start_date, '%d-%m-%Y')
        end_date    = datetime.datetime.strptime(str_end_date, '%d-%m-%Y')
        
        s_date = date(start_date.year, start_date.month, start_date.day)
        e_date = date(end_date.year, end_date.month, end_date.day)        
        
        no_of_bookings = 0
        cbs = cam_object.customerbooking.all() 
        for cb in cbs:
            no_of_bookings = no_of_bookings +1
            try:
                invoice = Invoice.objects.get(booking_id=cb)
                sum = sum + invoice.invoice_gross_amount
                if cb.booking_estimated_checkin_date.month == this_month:
                    this_month_days = this_month_days + cb.booking_actual_no_of_day_stay
                    this_month_amount = this_month_amount + invoice.invoice_gross_amount
                
                temp_date = date(cb.booking_estimated_checkin_date.year, cb.booking_estimated_checkin_date.month, cb.booking_estimated_checkin_date.day)
                
                if s_date < temp_date < e_date:
                    days_fy     = days_fy + cb.booking_actual_no_of_day_stay
                    amount_fy   = amount_fy + invoice.invoice_gross_amount
            except Exception, e:
                print 'Exception ',e
                
        # this is for getting the no.of day for this month and amounts
        monthly_bookings = Booking.objects.filter(booking_estimated_checkin_date__range=(start_date, end_date)).extra(select={'month': "EXTRACT(month FROM booking_estimated_checkin_date)"}).values('month').annotate(total=Count('booking_id'))

        # guest List 
        guests = Guest.objects.filter(customer_id=cam_object)

        #orderList=OrderInfo.objects.filter(Q(**filter_args) &  (Q(ProductID = ProductInfo.objects.filter(Q(**product_filter_args) & Q(VendorID = VendorInfo.objects.filter(**vendor_filter_args)))) & Q(ShipmentAddressID = ShipmentAddressInfo.objects.filter(**ship_filter_args )))).order_by('-OrderDate')
        invoice_amount = Invoice.objects.filter(Q(booking_id = Booking.objects.filter(customer_id=cam_object))).aggregate(total_amount=Sum('invoice_gross_amount'))

        if invoice_amount['total_amount'] == None:
            tot_amount = 0
        else:
            tot_amount = invoice_amount['total_amount']

        request.session['total_amount'] = invoice_amount['total_amount']
        data = {'success':'true','total_days' : cam_total_days, 'total_amount': tot_amount, 'month_days': this_month_days, 'month_amount': this_month_amount,
            'days_fy': days_fy, 'amount_fy': amount_fy, 'no_of_guests':no_of_guests, 'no_of_bookings': no_of_bookings, 'state_list' : pcf.get_all_state_name(),
            'image_carousal' : get_corporate_prefered_property_images(cam_object), 'guest_list' :guests  }
        print data
def cam_save_booking_details(request):
    if not request.user.is_authenticated():
        return redirect('/corporate/')
    sid = transaction.savepoint()
    #pdb.set_trace()
    try:
        print 'Request Accepted '
        store_user_track(request, "Customer Saving Booking details")   # for tracking user activity
        if request.method == "POST":
            v_cam_id        = request.session['user_id']
            guest_name      = request.POST.get('guest_name')
            guest_phone     = request.POST.get('phone_number')
            v_guest_email   = request.POST.get('email_id')
            var_property_id = request.POST.get('property_id')
            occupancy_type  = int(request.POST.get('occupancy_type'))
            check_in    = datetime.datetime.strptime(request.POST.get('check_in'), '%d/%m/%Y')
            check_out   = datetime.datetime.strptime(request.POST.get('check_out'), '%d/%m/%Y')
            promocode   = request.POST.get('promocode')
            #amount      = request.POST.get('amount')
            #taxes       = request.POST.get('taxes')
            gross_amount= request.POST.get('gross_amount')
            
            guest_obj = Guest.objects.get(guest_id=guest_name)
            guest_obj.guest_contactno     = guest_phone
            guest_obj.guest_email         = v_guest_email
            guest_obj.save()
            
            # Getting Property Object
            property_obj = Property.objects.get(property_id=var_property_id)
            
            # Default Property Rate if it is not decided for CAM.
            default_rate = PropertyRate.objects.get(property_id=property_obj)
            occupancy_rate =0
        
            # Customer Object
            cam_obj= Customer.objects.get(id=v_cam_id)
            # This is for fetching property rates and applying rates according to occupancy type
            property_rates = CAMPropertyRate.objects.filter(property_id=property_obj, cust_id=cam_obj)
            if property_rates:
                for rate in property_rates:
                    if int(rate.occupancy_type) == int(occupancy_type):
                        occupancy_rate = rate.agreed_rate
            else:
                if occupancy_type == 0:
                    occupancy_rate = default_rate.single_occupancy_display_rate
                else:
                    occupancy_rate = default_rate.double_occupancy_display_rate
            
            days = check_out - check_in
            if days.days == 0:
                day = 1
            else:
                day = days.days
                
            booking_obj = Booking(
                customer_id      = cam_obj,
                guest_id    = guest_obj,
                property_id   = property_obj,
                booking_estimated_checkin_date = check_in,
                booking_actual_checkin_date = check_in,
                booking_estimated_checkout_date = check_out,
                booking_actual_checkout_date = check_out,
                booking_estimated_checkout_time = datetime.datetime.now().time(),
                booking_estimated_checkin_time = datetime.datetime.now().time(),
                booking_estimated_no_of_day_stay = days.days,
                booking_actual_no_of_day_stay = day,
                booking_status  = BOOKING_OPEN, #BOOKING_BOOKED
                booking_rate    = occupancy_rate
            )
            booking_obj.save()
            booking_obj.booking_unique_id = 'BK' +  datetime.date.today().strftime('%d%m%y') + 'G' + str(guest_obj.guest_id) + str(booking_obj.booking_id).zfill(6)
            booking_obj.save()
            
            # Generating Invoice
            
            amount = occupancy_rate * day
            service_tax_amount = ( amount * SERVICE_TAX )/100
            luxury_tax_amount  = ( amount * LUXURY_TAX )/100
        
            tax_amount = service_tax_amount + luxury_tax_amount
            gross_amount = amount + tax_amount
            invoice = Invoice(
                booking_id = booking_obj,
                room_charges = amount,
                invoice_total_amount = amount,
                tax_amount  = tax_amount,
                invoice_gross_amount = gross_amount,
                invoice_status = 0,
            )
            invoice.save()
            invoice.invoice_unique_id = 'INVBK' + str(booking_obj.booking_id) + str(invoice.invoice_id).zfill(6)
            invoice.save()
            
            corporate_transaction = CorporateTransaction(
                invoice_id      = invoice.invoice_unique_id,
                corporate_id    = cam_obj,
                transaction_amount= invoice.invoice_gross_amount,
                transaction_type = 1
            )
            corporate_transaction.save()
            
            # This is for Booking Statistics added on 11 Dec 2015
            booking_stat = UserBookingStatisticTrack(
                user_id = cam_obj,
                booking_path = request.path,
                booking_date = datetime.date.today(),
                booking_id = booking_obj
            )
            booking_stat.save()
            transaction.savepoint_commit(sid)
            try:
                # Sending SMS to vendot regarding booking submission
                send_booking_submission_sms_to_vendor(property_obj.property_owner_id.cust_contact_no, property_obj.property_owner_id.cust_first_name,
                    booking_obj.booking_unique_id, property_obj.property_actual_name,  booking_obj.booking_id)
                # Sending Booking Submission SMS to Corporate User
                send_booking_submission_sms_to_customer(cam_obj.cust_contact_no, cam_obj.cust_first_name, booking_obj.booking_unique_id)
                # Sending Booking Submission Email to Corporate User
                send_booking_submission_mail_with_template(booking_obj.booking_id)
            except Exception as err:
                print 'SMS/ Email not sent to vendor/ customer / '
            return redirect('/corporate/cam-booking-details/?booking_id='+ str(booking_obj.booking_unique_id))
        else:
            print 'Hello'
            transaction.savepoint_rollback(sid)
            data = {'success':'false', 'error_message':'Invalid Request'}
    except Exception, e:
        print 'Error ', e
        transaction.savepoint_rollback(sid)
        data = {'success':'false', 'error_message':'Server Error- Please Try Again'}