Example #1
0
def close_contests(request):

    if request.user.is_authenticated():
        clean = False
    else:
        clean = True

    inputs = request.POST if request.POST else None
    if clean:
        cred = check_creds(request.POST, Platform)
        if not cred['success']:
            return HttpResponse(json.encode(cred), mimetype="application/json")

    current_time = current_time_aware()
    yesterday = current_time - datetime.timedelta(days=1)

    contests = Contest.objects.filter(closed=False)

    contest_data = []
    for i in contests:

        if i.end_price_date() < current_time and i.end_price_date(
        ) >= yesterday:

            contest_meta_data = {'key': i.key}

            subs = Submission.objects.filter(
                contest=i).order_by('created_date')
            contest_meta_data['subs'] = subs.count()

            if subs:

                # build list of current flights
                res = run_flight_search(i.origin_code,
                                        i.destination_code,
                                        i.depart_date,
                                        i.return_date,
                                        'any',
                                        'any',
                                        'any',
                                        'any',
                                        cached=True)
                if res['success']:
                    #return HttpResponse(json.encode(res), mimetype="application/json")
                    i.end_price = res['min_fare']

            if not i.end_price:
                i.closed = True
                i.save()

            else:

                try:
                    # find earliest-closest entry
                    closest = None
                    for k in subs:
                        dif = abs(k.value - i.end_price)
                        if not closest:
                            closest = (k, dif)
                        else:
                            if dif < closest[1]:
                                closest = (k, dif)

                    # create promo for this user
                    new_promo = Promo(customer=closest[0].customer,
                                      created_date=current_time,
                                      value=i.value,
                                      code=gen_alphanum_key())
                    new_promo.save()

                    # send email
                    subject = "You won the fare prediction contest!"
                    title = "Dang, you are good."
                    body = "You may remember entering a fare prediction contest on %s. We told you we'd let you know if your guess was closest to the actual fare and here we are. Also as promised, here's a promo code which let's you buy a Flex Fare for just $1:\n\n%s\n\nThe Level Skies Team" % (
                        closest[0].created_date.strftime("%B %d"),
                        new_promo.code)
                    try:
                        send_template_email(closest[0].customer.email, subject,
                                            title, body)
                    except:
                        pass

                    # close contest
                    i.closed = True
                    i.save()

                except Exception as err:
                    contest_meta_data['error'] = err

            contest_data.append(contest_meta_data)

    results = {'success': True, 'contest_data': contest_data}

    return gen_search_display(request, {'results': results},
                              clean,
                              method='post')
Example #2
0
def make_submission(request):

    if request.user.is_authenticated():
        clean = False
    else:
        clean = True

    inputs = request.POST if request.POST else None
    if clean:
        cred = check_creds(request.POST, Platform)
        if not cred['success']:
            return HttpResponse(json.encode(cred), mimetype="application/json")

    form = ContestSubmissionForm(inputs)
    build = {'form': form}

    if (inputs) and form.is_valid():
        cd = form.cleaned_data

        try:

            find_platform = Platform.objects.get(key=cd['platform_key'])
            find_contest = Contest.objects.get(key=cd['contest_key'])

            # either find the existing customer associated with the platform and email addres or create it
            try:
                find_cust = Customer.objects.get(email=cd['email'],
                                                 platform=find_platform)
            except:
                inps = {}
                inps['key'] = gen_alphanum_key()
                inps['reg_date'] = current_time_aware().date()
                inps['platform'] = find_platform
                inps['email'] = cd['email']
                find_cust = Customer(**inps)
                find_cust.save()
                find_cust.create_highrise_account()

            find_cust.add_highrise_tag('contest')

            try:
                sub = Submission.objects.get(customer=find_cust,
                                             contest=find_contest)
            except:
                sub = Submission(contest=find_contest,
                                 customer=find_cust,
                                 created_date=current_time_aware(),
                                 value=cd['value'])
                sub.save()
            else:
                raise Exception(
                    "A submission has already been made to this contest with this email address."
                )

        except (Contest.DoesNotExist):
            build['error_message'] = 'The contest key entered is not valid.'
            build['results'] = {
                'success': False,
                'error': 'The contest key entered is not valid.'
            }

        except (Exception) as err:
            build['error_message'] = '%s' % err
            build['results'] = {
                'success': False,
                'error': 'Could not record your entry. %s' % err
            }

        else:

            # send email if subission successful
            subject = "We got your submission"
            title = "Now let's see how well you do..."

            if find_contest.decision_time == 1:
                time = "another week"
            elif find_contest.decision_time == 2:
                time = "another two weeks"
            elif find_contest.decision_time == 3:
                time = "another three weeks"
            elif find_contest.decision_time == 4:
                time = "another four weeks"
            else:
                time = "several days"

            body = "This contest is over soon but we won't know the final price of the flight for %s. When that happens we'll let you know if you won and earned a discount on your next Flex Fare. Don't worry, you don't have to wait long and you can enter the next contest as soon as it starts." % (
                time)
            try:
                send_template_email(sub.customer.email, subject, title, body)
            except:
                pass

            build['results'] = {'success': True}
    else:
        err_string = ""
        for error in form.errors.iteritems():
            err_string += "%s - %s " % (
                error[0],
                unicode(striptags(error[1]) if striptags else error[1]))

        build['results'] = {'success': False, 'error': err_string}

    return gen_search_display(request, build, clean, method='post')
Example #3
0
def sweep_expired(request):
    """
    @summary:   run this daily to find prices on searches that expired within 24 hours
                this will help with analysis and model building
                cycle through recently expired options
    """

    if request.user.is_authenticated():
        clean = False
    else:
        clean = True

    if (request.POST):
        if clean:
            cred = check_creds(request.POST, Platform)
            if not cred['success']:
                return HttpResponse(json.encode(cred),
                                    content_type="application/json")

    # ensure this query is not run more than once/24hrs
    current_time = current_time_aware()
    run_dates = ExpiredSearchPriceCheck.objects

    if not run_dates.exists() or (current_time - run_dates.latest(
            'run_date').run_date) >= datetime.timedelta(hours=23):
        latest_price_check = ExpiredSearchPriceCheck(run_date=current_time)
        latest_price_check.save()

        # pull searches expiring in last 24 hours
        yesterday = current_time - datetime.timedelta(days=1)
        recent_expired = Searches.objects.filter(
            exp_date__range=[yesterday, current_time])

        # check expired demos
        exp_demo_query = Demo.objects.filter(
            search__exp_date__range=[yesterday, current_time])
        demo_keys = [str(i.search.key) for i in exp_demo_query]

        # run flight search query on each recently expired option
        expired_searches = []
        expired_demos = []
        for i in recent_expired:

            flights = pull_fares_range(i.origin_code,
                                       i.destination_code,
                                       (i.depart_date1, i.depart_date2),
                                       (i.return_date1, i.return_date2),
                                       i.depart_times,
                                       i.return_times,
                                       i.convenience,
                                       i.airlines,
                                       cached=True)
            expired_searches.append({
                'search': i.key,
                'success': flights['success']
            })

            # check if search relates to an expired demo contract, if so, check if customer would have saved money
            if i.key in demo_keys and flights['success']:
                savings_string = ""
                for j in flights['fares']:
                    savings = math.floor(float(j['fare']) - i.locked_fare)
                    # don't alert customer of savings unless greater than X dollars
                    if savings >= 10:
                        """
                        dep_flights = " | ".join(["%s %s" % (k['airline_short_name'], k['flight_number']) for k in j['flight']['departing']['detail']])
                        ret_flights = " | ".join(["%s %s" % (k['airline_short_name'], k['flight_number']) for k in j['flight']['returning']['detail']])
                        dep_datetime = parse(j['flight']['departing']['take_off_time']).strftime("%B %d, %Y at %I:%M%p")
                        ret_datetime = parse(j['flight']['returning']['take_off_time']).strftime("%B %d, %Y at %I:%M%p")
                   
                        savings_string += "$%s departing %s on %s \nand returning %s on %s\n\n" % (savings, dep_datetime, dep_flights, ret_datetime, ret_flights)
                        """
                        dep_datetime = parse(
                            j['flight']['departing']
                            ['take_off_time']).strftime("%B %d, %Y")
                        ret_datetime = parse(
                            j['flight']['returning']
                            ['take_off_time']).strftime("%B %d, %Y")

                        savings_string += "$%s departing %s and returning %s\n\n" % (
                            savings, dep_datetime, ret_datetime)
                # send customer email describing potential savings if savings were possible
                if savings_string:
                    try:
                        title = "Here's what you could have saved by buying a Flex Fare"
                        body = "Thanks for checking out Level Skies and for taking a closer look at the Flex Fare. You previously signed up for a trial run of the Flex Fare and now we're hear to show you what could have happened had you actually made the purchase. Prices on the flights you were looking at went up, as they tend to do! Here are the potential savings that would have been available to you:\n\n"
                        body += savings_string + "\n\nWe hope you check in with us again soon becasue we'd love to save you some real cash!\n\nThe Level Skies Team"
                        email_address = exp_demo_query.get(
                            search__key=i.key).customer.email
                        send_template_email(email_address, 'Flex Fare Trial',
                                            title, body)
                    except:
                        pass

                expired_demos.append({
                    'search':
                    i.key,
                    'savings':
                    True if savings_string else False
                })

        #  check fares on open contracts
        contracts_query = Contract.objects.filter(
            search__exp_date__gt=current_time, ex_date=None)

        open_contracts = []
        for i in contracts_query:

            flights = pull_fares_range(
                i.search.origin_code,
                i.search.destination_code,
                (i.search.depart_date1, i.search.depart_date2),
                (i.search.return_date1, i.search.return_date2),
                i.search.depart_times,
                i.search.return_times,
                i.search.convenience,
                i.search.airlines,
                cached=True)
            open_contracts.append({
                'search': i.search.key,
                'success': flights['success']
            })

        duration = current_time_aware() - current_time

        results = {
            'success': True,
            'time_run': str(current_time),
            'expired_demos': expired_demos,
            'expired_searches': expired_searches,
            'open_contracts': open_contracts,
            'duration': str(duration),
            'count': recent_expired.count()
        }

        # send email to sysadmin summarizing expired searches
        #if MODE == 'live':
        try:
            searches_email_string = ""
            for i in expired_searches:
                searches_email_string += "%s : %s\n" % (i['search'],
                                                        i['success'])

            contracts_email_string = ""
            for i in open_contracts:
                contracts_email_string += "%s : %s\n" % (i['search'],
                                                         i['success'])

            demos_email_string = ""
            for i in expired_demos:
                demos_email_string += "%s : %s\n" % (i['search'], i['savings'])

            email_body = 'Completed flight search for %s expired searches with duration of %s.\n\nSearch Key : Success status\n%s\n\n' % (
                results['count'], results['duration'], searches_email_string)
            email_body += 'Completed %s open contracts.\n\nSearch Key : Success status\n%s\n\n' % (
                len(open_contracts), contracts_email_string)
            email_body += 'Completed %s expired demos.\n\nSearch Key : Savings\n%s' % (
                len(expired_demos), demos_email_string)
            send_mail('Expired searches price check',
                      email_body,
                      '*****@*****.**', ['*****@*****.**'],
                      fail_silently=False)
        except:
            pass

    else:
        results = {
            'success': False,
            'error': 'Expired search price check ran within last 24 hours.'
        }

    return gen_search_display(request, {'results': results}, clean)
Example #4
0
def close_contests(request):


	if request.user.is_authenticated():
	    clean = False
	else:
	    clean = True

	inputs = request.POST if request.POST else None
	if clean:
	    cred = check_creds(request.POST, Platform)
	    if not cred['success']:
	        return HttpResponse(json.encode(cred), mimetype="application/json")


	current_time = current_time_aware()
	yesterday = current_time - datetime.timedelta(days=1)
	
	contests = Contest.objects.filter(closed=False)

	contest_data = []
	for i in contests:

		if i.end_price_date() < current_time and i.end_price_date() >= yesterday:

			contest_meta_data = {'key': i.key}

			subs = Submission.objects.filter(contest=i).order_by('created_date')
			contest_meta_data['subs'] = subs.count()
			
			if subs:

				# build list of current flights
				res = run_flight_search(i.origin_code, i.destination_code, i.depart_date, i.return_date, 'any', 'any', 'any', 'any', cached=True)	
				if res['success']:
					#return HttpResponse(json.encode(res), mimetype="application/json")
					i.end_price = res['min_fare']

			if not i.end_price:
				i.closed = True
				i.save()
			
			else:
				
				try:
					# find earliest-closest entry
					closest = None
					for k in subs:
						dif = abs(k.value-i.end_price)
						if not closest:
							closest = (k, dif)
						else:
							if dif < closest[1]:
								closest = (k, dif)

					# create promo for this user
					new_promo = Promo(customer=closest[0].customer, 
									created_date=current_time,
									value=i.value,
									code=gen_alphanum_key())
					new_promo.save()

					# send email
					subject = "You won the fare prediction contest!"
					title = "Dang, you are good."
					body = "You may remember entering a fare prediction contest on %s. We told you we'd let you know if your guess was closest to the actual fare and here we are. Also as promised, here's a promo code which let's you buy a Flex Fare for just $1:\n\n%s\n\nThe Level Skies Team" % (closest[0].created_date.strftime("%B %d"), new_promo.code)
					try:
						send_template_email(closest[0].customer.email, subject, title, body)
					except:
						pass

					# close contest
					i.closed = True
					i.save()

				except Exception as err:
					contest_meta_data['error'] = err
			
			contest_data.append(contest_meta_data)

	results = {'success': True, 'contest_data': contest_data}

	return gen_search_display(request, {'results': results}, clean, method='post')
Example #5
0
def make_submission(request):
	
	if request.user.is_authenticated():
	    clean = False
	else:
	    clean = True

	inputs = request.POST if request.POST else None
	if clean:
	    cred = check_creds(request.POST, Platform)
	    if not cred['success']:
	        return HttpResponse(json.encode(cred), mimetype="application/json")


	form = ContestSubmissionForm(inputs)
	build = {'form': form}

	if (inputs) and form.is_valid():
		cd = form.cleaned_data
		
		try:

			find_platform = Platform.objects.get(key=cd['platform_key'])
			find_contest = Contest.objects.get(key=cd['contest_key'])

			# either find the existing customer associated with the platform and email addres or create it
			try:
			    find_cust = Customer.objects.get(email=cd['email'], platform=find_platform)
			except:
			    inps = {}
			    inps['key'] = gen_alphanum_key()
			    inps['reg_date'] = current_time_aware().date()
			    inps['platform'] = find_platform
			    inps['email'] = cd['email']
			    find_cust = Customer(**inps)
			    find_cust.save()
			    find_cust.create_highrise_account()

			find_cust.add_highrise_tag('contest')

			try:
				sub = Submission.objects.get(customer=find_cust, contest=find_contest)
			except:
				sub = Submission(contest=find_contest, customer=find_cust, created_date=current_time_aware(), value=cd['value'])
				sub.save()
			else:
				raise Exception("A submission has already been made to this contest with this email address.")

		except (Contest.DoesNotExist):
		    build['error_message'] = 'The contest key entered is not valid.'
		    build['results'] = {'success': False, 'error': 'The contest key entered is not valid.'}

		except (Exception) as err:
		    build['error_message'] = '%s' % err
		    build['results'] = {'success': False, 'error': 'Could not record your entry. %s' % err}

		else:

			# send email if subission successful
			subject = "We got your submission"
			title = "Now let's see how well you do..."
			
			if find_contest.decision_time == 1:
				time = "another week"
			elif find_contest.decision_time == 2:
				time = "another two weeks"
			elif find_contest.decision_time == 3:
				time = "another three weeks"
			elif find_contest.decision_time == 4:
				time = "another four weeks"
			else:
				time = "several days"
			
			body = "This contest is over soon but we won't know the final price of the flight for %s. When that happens we'll let you know if you won and earned a discount on your next Flex Fare. Don't worry, you don't have to wait long and you can enter the next contest as soon as it starts." % (time)
			try:
				send_template_email(sub.customer.email, subject, title, body)
			except:
				pass

			build['results'] = {'success': True}
	else:
		err_string = ""
		for error in form.errors.iteritems():
			err_string += "%s - %s " % (error[0], unicode(striptags(error[1]) if striptags else error[1]))

		build['results'] = {'success': False, 'error': err_string}
		
	return gen_search_display(request, build, clean, method='post')
Example #6
0
def sweep_expired(request):
    """
    @summary:   run this daily to find prices on searches that expired within 24 hours
                this will help with analysis and model building
                cycle through recently expired options
    """
    
    if request.user.is_authenticated():
        clean = False
    else:
        clean = True

    if (request.POST):
        if clean:
            cred = check_creds(request.POST, Platform)
            if not cred['success']:
                return HttpResponse(json.encode(cred), content_type="application/json")

    
    # ensure this query is not run more than once/24hrs
    current_time = current_time_aware()
    run_dates = ExpiredSearchPriceCheck.objects

    if not run_dates.exists() or (current_time - run_dates.latest('run_date').run_date) >= datetime.timedelta(hours=23):
        latest_price_check = ExpiredSearchPriceCheck(run_date=current_time)
        latest_price_check.save()

        # pull searches expiring in last 24 hours
        yesterday = current_time - datetime.timedelta(days=1)
        recent_expired = Searches.objects.filter(exp_date__range=[yesterday, current_time])
        
        # check expired demos
        exp_demo_query = Demo.objects.filter(search__exp_date__range=[yesterday, current_time])
        demo_keys = [str(i.search.key) for i in exp_demo_query]

        # run flight search query on each recently expired option     
        expired_searches = []
        expired_demos = []
        for i in recent_expired:

            flights = pull_fares_range(i.origin_code, i.destination_code, (i.depart_date1, i.depart_date2), (i.return_date1, i.return_date2), i.depart_times, i.return_times, i.convenience, i.airlines, cached=True)
            expired_searches.append({'search': i.key, 'success': flights['success']})
              
            # check if search relates to an expired demo contract, if so, check if customer would have saved money
            if i.key in demo_keys and flights['success']:
                savings_string = ""
                for j in flights['fares']:
                    savings = math.floor(float(j['fare']) - i.locked_fare)
                    # don't alert customer of savings unless greater than X dollars
                    if savings >= 10:
                        """
                        dep_flights = " | ".join(["%s %s" % (k['airline_short_name'], k['flight_number']) for k in j['flight']['departing']['detail']])
                        ret_flights = " | ".join(["%s %s" % (k['airline_short_name'], k['flight_number']) for k in j['flight']['returning']['detail']])
                        dep_datetime = parse(j['flight']['departing']['take_off_time']).strftime("%B %d, %Y at %I:%M%p")
                        ret_datetime = parse(j['flight']['returning']['take_off_time']).strftime("%B %d, %Y at %I:%M%p")
                   
                        savings_string += "$%s departing %s on %s \nand returning %s on %s\n\n" % (savings, dep_datetime, dep_flights, ret_datetime, ret_flights)
                        """
                        dep_datetime = parse(j['flight']['departing']['take_off_time']).strftime("%B %d, %Y")
                        ret_datetime = parse(j['flight']['returning']['take_off_time']).strftime("%B %d, %Y")
                   
                        savings_string += "$%s departing %s and returning %s\n\n" % (savings, dep_datetime, ret_datetime)
                # send customer email describing potential savings if savings were possible
                if savings_string:
                    try:
                        title = "Here's what you could have saved by buying a Flex Fare"
                        body = "Thanks for checking out Level Skies and for taking a closer look at the Flex Fare. You previously signed up for a trial run of the Flex Fare and now we're hear to show you what could have happened had you actually made the purchase. Prices on the flights you were looking at went up, as they tend to do! Here are the potential savings that would have been available to you:\n\n"
                        body += savings_string + "\n\nWe hope you check in with us again soon becasue we'd love to save you some real cash!\n\nThe Level Skies Team"
                        email_address = exp_demo_query.get(search__key=i.key).customer.email
                        send_template_email(email_address, 'Flex Fare Trial', title, body)
                    except:
                        pass

                expired_demos.append({'search': i.key, 'savings': True if savings_string else False})

        #  check fares on open contracts
        contracts_query = Contract.objects.filter(search__exp_date__gt=current_time, ex_date=None)
        
        open_contracts = []
        for i in contracts_query:

            flights = pull_fares_range(i.search.origin_code, i.search.destination_code, (i.search.depart_date1, i.search.depart_date2), (i.search.return_date1, i.search.return_date2), i.search.depart_times, i.search.return_times, i.search.convenience, i.search.airlines, cached=True)
            open_contracts.append({'search': i.search.key, 'success': flights['success']})
       

        duration = current_time_aware() - current_time
        
        results = {'success': True,  'time_run': str(current_time), 'expired_demos': expired_demos, 'expired_searches': expired_searches, 'open_contracts': open_contracts, 'duration': str(duration), 'count': recent_expired.count()}

        # send email to sysadmin summarizing expired searches
        #if MODE == 'live':    
        try:
            searches_email_string = ""
            for i in expired_searches:
                searches_email_string += "%s : %s\n" % (i['search'], i['success'])

            contracts_email_string = ""
            for i in open_contracts:
                contracts_email_string += "%s : %s\n" % (i['search'], i['success'])

            demos_email_string = ""
            for i in expired_demos:
                demos_email_string += "%s : %s\n" % (i['search'], i['savings'])

            email_body = 'Completed flight search for %s expired searches with duration of %s.\n\nSearch Key : Success status\n%s\n\n' % (results['count'], results['duration'], searches_email_string)
            email_body += 'Completed %s open contracts.\n\nSearch Key : Success status\n%s\n\n' % (len(open_contracts), contracts_email_string)
            email_body += 'Completed %s expired demos.\n\nSearch Key : Savings\n%s' % (len(expired_demos), demos_email_string)
            send_mail('Expired searches price check',
                email_body,
                '*****@*****.**',
                ['*****@*****.**'],
                fail_silently=False)
        except:
            pass

    else:
        results = {'success': False, 'error': 'Expired search price check ran within last 24 hours.'}
        
    return gen_search_display(request, {'results': results}, clean)