Example #1
0
def errorReport(eMsg, reporter, buildingName, roomNumber, errorTypes, comment):
        if (len(errorTypes) == 0):
                return

        # Create the message to send
        msg = "A printer error has been reported. <br /><br />"
        msg += "<strong>Building:</strong>      %s <br /><br />" % buildingName
        msg += "<strong>Room:</strong>          %s <br /><br />" % roomNumber

        if (reporter != ""):
                msg += "<strong>Reporter Netids:</strong>          %s <br /><br />" % reporter

        msg += "<strong>Errors</strong>:       %s <br /><br />" % eMsg

        msg += "<strong>Comments:</strong>          %s <br /> <br />" % comment

        subject = "Problem in " + buildingName + " " + roomNumber;

        email = []

        timePeriod = emails.getTimePeriod()

        # Send an email to each affected party
        for i in errorTypes:
                newEmail = getErrorEmail(i, timePeriod)

                if (not newEmail in email):
                        email.append(newEmail)

        for i in email:
                if (i != "undefined" and i != None):
                        emails.sendEmail(i, subject, msg)
                else:
                        print ("Undefined Email Address")
Example #2
0
File: bot.py Project: rreyv/rcb
def print_wiki_schedule(schedule,debug_mode,r):
  schedule_table = "This wiki lists all cricket fixtures scheduled to begin in the next 48 hours. \
      Matches involving test playing nations are pre-scheduled. To request a thread for any other match, \
      click on request thread and then hit send immediately without changing anything in the message. \
      You will get a confirmation shortly that a thread has been scheduled and will be created an hour before \
      the start time. \n\n"
  schedule_table += "Match | Time Left | Match Thread \n:--|:--|:--\n"
  current_date_time = datetime.datetime.utcnow()
  for match_date_time in upcoming_schedule.sorted_keys():
    for matchday in upcoming_schedule.get(match_date_time):
      time_left, time_left_dt = get_time_left(current_date_time,match_date_time)
      if (time_left_dt.total_seconds()//60 < - 480) and time_left == 'In Progress':
        continue
      elif (time_left_dt.total_seconds()//60 > 2880):
        continue
      else:
        name = '**' + str(matchday.match_name) + '**' if matchday.important else str(matchday.match_name)
        schedule_table = schedule_table + str(name) + "|" + time_left + "|" + user_action(matchday) + "\n"
        if (time_left_dt.total_seconds()//60 < 65) and matchday.important == True:
          add_to_requested_table(matchday,'rCricketBot',matchday.match_name)
  if debug_mode==True:
    print schedule_table
  else:
    try:
      wiki_page = r.get_wiki_page(subreddit,'bot_schedule')
      wiki_page.edit(schedule_table)
      logging.info('Successfully updated wiki.')
    except:
      logging.warning("Couldn't update wiki. Trying again in 50 seconds.")
      emails.sendEmail('Wiki Error!', 'Could not update wiki. Trying again in 50 seconds')
Example #3
0
def query_movie(config):
    new_tickets = {
        'taototo': [],
        'piaohenduo': [],
        'mgmovie': [],
        'chadan': [],
    }
    new_append_tickets = {
        'taototo': [],
        'piaohenduo': [],
        'mgmovie': [],
        'chadan': [],
    }
    new_append = 0
    if config['taototo']['enable']:
        code = 'taototo'
        new_tickets[code] = movie[code].query_all()
    if config['piaohenduo']['enable']:
        code = 'piaohenduo'
        new_tickets[code] = movie[code].query_all()
    if config['mgmovie']['enable']:
        code = 'mgmovie'
        new_tickets[code] = movie[code].query_all()
    if config['chadan']['enable']:
        code = 'chadan'
        new_tickets[code] = movie[code].query_all()
    # 查询完毕 处理结果
    logger.info('查询结果: %s', new_tickets)

    # 根据城市过滤
    include_city = config['global']['includeCity']
    for code in new_tickets:
        new_orders = []
        for ticket in new_tickets[code][:]:
            if include_city is not None and ticket.city not in include_city:
                new_tickets[code].remove(ticket)
            else:
                # 添加到新订单列表
                new_orders.append(ticket.order_no)
                # 判断是不是新增订单,是的话置为新增订单
                if ticket.order_no not in old_orders[code]:
                    ticket.is_new = True
                    new_append += 1
                    new_append_tickets[code].append(ticket.__dict__)
        # 新换旧
        old_orders[code] = new_orders

    if new_append > 0:
        logger.info('有新的订单: %s', new_append_tickets)
        toast.show_toast("新订单提示",
                         "来新订单啦",
                         icon_path="custom.ico",
                         duration=config['schedule']['interval'] - 1,
                         threaded=True)
        emails.sendEmail(
            '电影订单通知', '来新订单啦\n' +
            json.dumps(new_append_tickets, ensure_ascii=False, indent=4))
    else:
        logger.info('暂无新订单')
Example #4
0
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		rejectPath = UrlBuilder(self.request).buildUrl('/reject')
		
		user = users.get_current_user()
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("cow")
		members = group.memberships
		
		parser = CowParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
		
		result = transaction.getResult()
		
		# Update balance and send mails
		for member, balance in result.balanceChange.iteritems():
			balanceBefore = member.balance
			balanceNow = member.balance + balance
			
			# Balance
			member.balance += balance
			member.put()
			
			# Send mail, but not to the creator of this mail
			if member.user != creatorMember.user:
				message = createCowMail(creatorMember, transaction, result, member, balanceBefore, balanceNow, lang)
				sendEmail(message)
			
		# Create transactions
		for debt in result.debts:
			for singleDebt in debt.singleDebts:
				tr = Transaction(
					group = group,
					creatorMember = creatorMember, 
					fromMember = debt.fromMember,
					toMember = singleDebt.toMember,
					type = 'debt',
					amount = singleDebt.money, 
					reason = transaction.reason,
					isRejected = False
				)
				tr.put()
				
		location = '/group?group=%s&msg=%s' % (group.key(), _('Debts saved!', lang))
		redirectPage(self,location)
Example #5
0
def submitAccept(request, pk):
	name = request.REQUEST['name']
	email = request.REQUEST['email']
	if name and email:
		appointment = Appointment.objects.get(pk=pk)
		appointment.isActive = False
		appointment.save()
		sendEmail(appointment, name, email)
	return redirect("/")
Example #6
0
def email(req, cycle):
    req_strs = ''.join(['<p><b>%s</b> will swap from %s into %s.</p>' % (swap.netid, swap.have.name, swap.want.name) for swap in cycle])
    body = """
    	<p>Hey there, %s!</p>
    	<p>We've identified a potential swap for <b>%s</b> from <b>%s</b> into <b>%s</b>.</p>
    	<p>Here's how it'll go down:</p>
    	%s
    	<p>Cheers!</p>
    	<p>The Section Swap Team</p>
    	""" % (str(req.netid), str(req.have.course), str(req.have.name), str(req.want.name), req_strs)

    subject = 'Successful swap into ' + str(req.want)
    to = req.netid + '@princeton.edu'
    sendEmail(to, subject, body)
Example #7
0
def run():
    to = request.get_json()["to"]
    content = request.get_json()["content"]
    response = emails.sendEmail(to, content)
    print(response)
    data = json.dumps({"to": to, "content": content})
    return data
def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening.........")
        r.pause_threshold = 1
        audio = r.listen(source)
    try:
        print("Recognizing...")
        command = r.recognize_google(audio, language='en-in')
        print(f"User said: {command}\n")

    except Exception as e:
        print("sorry can you Say that again ......")
        return "None"
    return command

    while True:
        speak("ok speak your friend name")
        try:
            name = takeCommand().lower()
            print(name)
            if name in dict[name]:
                print("can you speak your message.")
                speak("can you speak your message.")
                content = takeCommand().lower()
                print("do yo want to send a message")
                speak("do yo want to send a message")
                confirm = takeCommand().lower()
                if 'yes' in confirm:
                    try:
                        to = dict[name]
                        sendEmail(to, content)
                        print("Email has been sent!")
                        speak("Email has been sent!")
                        break
                    except Exception as e:
                        print("message sending failed")
                        speak("message sending failed")
                        continue
                elif 'no' in confirm:
                    print("message sending process cancel..")
                    speak("message sending process cancel")
                    break
        except Exception as e:
            speak("can you say again your friend name")
Example #9
0
File: bot.py Project: rreyv/rcb
def create_thread(match_id, series_id, day, thread_title, i, r, requestor,Pkey,debug_mode):

  try:
    score_response = requests.get("https://dev132-cricket-live-scores-v1.p.mashape.com/matchdetail.php?matchid=" + str(match_id) + "&seriesid=" + str(series_id),
    headers={
      "X-Mashape-Key":  parser.get('r_cricket_bot','api_key'),
      "Accept": "application/json"
      }
    )
    # score_response = requests.get("kasjdlas")
    score_data = score_response.json()
  except:
    if i == 5:
      logging.info("Failed to get scores from the API. I've tried 5 times and failed and won't try again.")
      emails.sendEmail('Create Thread Error', "Failed to get scores from the API for " + thread_title + " [ID: ]" + str(Pkey) + ". I've tried 5 times and failed and won't try again. Please create a match thread manually.")
      remove_from_requested_table(match_id, series_id, day)
      # delete_from_requested(Pkey)
    else:
      increment_attempts(Pkey)
      logging.info("Failed to get scores from the API. This was attempt #" + str(i) + " for "+ thread_title + " [ID: ]" + str(Pkey) + ".") 
    return

  try:
    #create thread with threadtitle from the schedule 
    if debug_mode == True:
      logging_info('Thread Title: ' + thread_title) 
    else:
      submission = r.submit(subreddit, "Match Thread: " + thread_title,text=thread_title)
      logging.info('Created thread. Title: ' + thread_title + ".")
  except:
    if i == 5:
      print "Failed to create thread. I've tried 5 times and failed and won't try again."
      #email - "Failed to create thread. I've tried 5 times and failed and won't try again. Please create a match thread manually."
      logging.info("Failed to create reddit thread. Reddit error. I've tried 5 times and failed and won't try again.")
      emails.sendEmail('Create Thread Error (reddit)', "Failed to create thread for " + thread_title + " [ID: ]" + str(Pkey) + ". I've tried 5 times and failed and won't try again. Please create a match thread manually.")
      remove_from_requested_table(match_id, series_id, day)
    else:
      increment_attempts(Pkey)
      logging.info("Failed to create thread. Reddit down? I've tried " + str(i) + " times and failed and won't try again.")
    return
  
  remove_from_requested_table(match_id, series_id, day)
  add_to_created_table(match_id, series_id, day, thread_title, requestor, submission.url, submission.id)
Example #10
0
File: bot.py Project: rreyv/rcb
def print_sidebar_schedule(schedule,debug_mode,r):
  i = 0 
  schedule_table = ">Match|Time Left\n:--|:--\n"
  current_date_time = datetime.datetime.utcnow()
  for match_date_time in upcoming_schedule.sorted_keys():
    for matchday in upcoming_schedule.get(match_date_time):
      time_left, time_left_dt = get_time_left(current_date_time,match_date_time)
      if (not matchday.important) or time_left == 'In Progress':
        continue
      else:
        schedule_table = schedule_table + str(matchday.match_abr) + "|" + time_left + "\n"
        i+=1
        if i==5:
          break
    if i==5:
      break

  if debug_mode == True:
    logging.info(schedule_table)
    logging.info('Printing sidebar schedule.')
  else:
    end_of_table=">[More International Fixtures](http://www.espncricinfo.com/ci/engine/series/index.html?view=month)." #Signature to look for that marks the end of table
    beg_of_table=">**Upcoming International Fixtures:**" #Signature to look for that marks beginning of table
    
    schedule_table = beg_of_table + "\n\n" + schedule_table + "\n" + end_of_table

    try:
      settings = r.get_settings(subreddit)
      description_html = settings['description']
      html_parser = HTMLParser.HTMLParser()
      description = html_parser.unescape(description_html)
      if ((description.find(beg_of_table) == -1) or (description.find(end_of_table)==-1)):
        emails.sendEmail('Sidebar Error!', 'Could not find sidebar marker.')
        logging.error('Could not find the sidebar markers. Trying again in 50 seconds.')
        return
      description_begin = description.find(beg_of_table)
      description_end = description.find(end_of_table) + len(end_of_table)
      description = description[:description_begin] + schedule_table + description[description_end:]
      settings = r.get_subreddit(subreddit).update_settings(description=description)
      logging.info('Successfully updated sidebar.')
    except:
      logging.warning('Could not update sidebar. Trying again in 50 seconds.')
      emails.sendEmail('Sidebar Error!', 'Could not update sidebar. Trying again in 50 seconds.')
Example #11
0
def run():
    to = request.get_json()["to"]
    content = request.get_json()["content"]
    emails.sendEmail(to, content)
    return '', 204
Example #12
0
def reminders(request):
    json_data = {}
    json_data['status'] = "success"
    email_type = 'reminder'
    
    # Authenticate the request - has to be issued by a superuser
    if 'auth_name' in request.POST and 'auth_pass' in request.POST:
        username = request.POST['auth_name']
        password = request.POST['auth_pass']
        system_user = authenticate(username=username, password=password)
        output = ""
        if system_user is not None:
            if system_user.is_active and system_user.is_superuser:
                
                # Find all users who we need to remind & who have a validated email address
                users_to_remind = Subject.objects.filter(preference_email_reminders=1,email_validated=1,email_reminders__isnull=False,preference_email_reminders_freq__isnull=False)
                for user in users_to_remind:
                    
                    username = User.objects.get(id=user.user_id).username
                    output += "User to remind: %s, %s" % (user.user_id, username)
                    
                    # Check if it has been X days since the last session access
                    user_email = user.email_reminders
                    user_pref_freq = int(user.preference_email_reminders_freq)
                    user_last_access = user.date_last_session_access # stored as datetime.date
                    user_created = user.date_created # stored as datetime.date
                    
                    # Date of last access is either the last time the user accessed a session 
                    # OR the date they created their account (if they haven't created any 
                    # sessions yet)
                    date_last_access = None
                    if user_last_access:
                        date_last_access = user_last_access
                    elif user_created:
                        date_last_access = user_created
                    
                    if date_last_access:
                        # Compute the date when we need to send the first reminder: X days 
                        # (according to frequency preference) after the date of last access
                        date_first_reminder = date_last_access + datetime.timedelta(days=user_pref_freq)
                        
                        output += ", Date of first reminder: %s" % (date_first_reminder) 
                        
                        # Check if today's date is past the day when the first reminder 
                        # should be sent, and if it is, check if a reminder email was already sent
                        # today (to avoid duplication, e.g. if the script is re-run twice on same day)
                        delta = (today - date_first_reminder).days
                        if delta >= 0:
                            if delta % user_pref_freq == 0:
                                # Time for a reminder, but check if one was already sent today
                                existing_reminders = Subject_Emails.objects.filter(date_sent=today, subject=user, email_to=user_email, email_type=email_type)
                                if not existing_reminders:
                                    output += ", Time for a reminder (last access date: %s, reminder freq in days: %s)" % (date_last_access, user_pref_freq)
                                    
                                    # Set up message
                                    email_subject = "%s - %s Reminder" % (website_name, reminder_freq[user_pref_freq])
                                    email_sender = email_username
                                    email_receiver = user_email
                                    email_text = "Dear <b>%s</b>, \r\n\r\nIt's time for your next session on %s! When you are ready for some new language puzzles, <a href='%s'>click here</a>. Your participation in this project is important to us, and directly helps enable research into language pattern changes over time.\r\n\r\n- The SPOClab team!\r\n\r\nSPOClab: Signal Processing and Oral Communication lab\r\n550 University Avenue, 12-175\r\nToronto, Ontario M5G 2A2\r\n<a href='http://spoclab.ca'>http://spoclab.ca</a>\r\n\r\nYou are receiving this email due to your account preferences. To unsubscribe, please visit <a href='%s'>your Account Settings page</a>." % (username, website_name, website_hostname, website_hostname + '/account')
                                    email_html = """<h2 style="Margin-top: 0;color: #44a8c7;font-weight: 700;font-size: 24px;Margin-bottom: 16px;font-family: Lato,sans-serif;line-height: 32px;text-align: center">Dear %s, it's time for your next session on %s!</h2>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">When you are ready for some new language puzzles,\r\n <a style="text-decoration: none;color: #5c91ad;border-bottom: 1px dotted #5c91ad" data-emb-href-display="undefined" href='%s'>click here</a>.\r\n Your participation in this project is important to us, and directly helps enable research into language pattern changes over time.</p>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">&mdash; The SPOClab team</p>""" % (username, website_name, website_hostname)
                                    
                                    output += ", Message from %s (%s) to %s, body: %s" % (email_sender, email_subject, email_receiver, email_text)
                                    
                                    # Send the prepared email
                                    result_flag = emails.sendEmail(email_sender, email_name, [email_receiver], [], [], email_subject, email_text, emails.emailPre + email_html + emails.emailPost)
                                    
                                    # If the send was successful, record it in the database
                                    if result_flag:
                                        Subject_Emails.objects.create(date_sent=today, subject=user, email_from=email_sender, email_to=email_receiver, email_type=email_type)
            else:
                json_data['status'] = 'error'
                json_data['error'] = 'Unauthorized'
                return HttpResponse(json.dumps(json_data), status=401)
        else:
            json_data['status'] = 'error'
            json_data['error'] = 'Unauthorized'
            return HttpResponse(json.dumps(json_data), status=401)
        
        #json_data['debug'] = output
        return HttpResponse(json.dumps(json_data))
    else:
        json_data['status'] = 'error'
        json_data['error'] = 'Unauthorized'
        return HttpResponse(json.dumps(json_data), status=401)
Example #13
0
def monthlydraw(request):
    json_data = {}
    json_data['status'] = "success"
    email_type = 'prize_notification'
    notification_type = Notification.objects.get(notification_id='monthlyprize_winner')
    NUM_WINNERS = 5
    
    # Authenticate the request - has to be issued by a superuser
    if 'auth_name' in request.POST and 'auth_pass' in request.POST:
        username = request.POST['auth_name']
        password = request.POST['auth_pass']
        system_user = authenticate(username=username, password=password)
        output = ""
        if system_user is not None:
            if system_user.is_active and system_user.is_superuser:
            
                today = datetime.datetime.now().date()
		#today = datetime.datetime.strptime('2016-02-28', '%Y-%m-%d').date()
                month_start = datetime.date(today.year, today.month, 1)
                month_end = datetime.date(today.year, today.month, calendar.monthrange(today.year, today.month)[1])
                
                # Build a list of all available monetary prizes
                prizes_list = [p.prize_name for p in Prize.objects.filter(prize_value__gt=0).order_by('prize_name')]
                
                # Build a probability distribution over the users who have
                # at least one completed session over the past month, and have elected
                # to participate in the monthly prize draws, and have a valid email 
                # address. 
                # The probability of winning is equal to the number of completed sessions over the 
                # past month / total number of completed sessions over the past month.
                # NB: it doesn't matter when the session was started.
                subj_eligible = Subject.objects.filter(preference_prizes=1, email_prizes__isnull=False, email_validated=1, session__isnull=False, session__end_date__isnull=False, session__end_date__gte=month_start, session__end_date__lte=month_end).distinct().annotate(Count('session', distinct=True))
                total_sess = sum([x.session__count for x in subj_eligible])
                
                distribution_values = np.array([x.user_id for x in subj_eligible])
                distribution_prob = np.array([x.session__count * 1.0 / total_sess for x in subj_eligible])
                
                # Adjust the distribution probabilities by penalizing previous prize winners, 
                # where the penalty is proportional to the number of wins
                penalty_past_win = 0.5
                past_wins = [x.subject_notifications_set.filter(notification=notification_type).count() for x in subj_eligible]
                penalty_factors = [ float(math.pow(penalty_past_win, x)) for x in past_wins]
                penalized_prob = [distribution_prob[x] * penalty_factors[x] for x in range(len(subj_eligible))]
                adjustment_factor = sum(penalized_prob)
                distribution_prob = [ x / adjustment_factor for x in penalized_prob]
                
                # The number of winners is either the pre-specified number, or the number of eligible subjects
                # (if the latter is smaller).
                NUM_WINNERS = min(NUM_WINNERS, len(subj_eligible))
                
                # Select the winners randomly by sampling the distribution, without replacement.
                winners = []
                for run in range(NUM_WINNERS):
                    bins = np.add.accumulate(distribution_prob)
                    winner_ind = np.digitize(random_sample(1), bins)
                    winner_id = int(distribution_values[winner_ind])
                    winner_subject = Subject.objects.get(user_id=winner_id)
                    winner_user = User.objects.get(id=winner_id)
                    winners += [winner_id]
                    
                    # Update the distribution (remove the winner that was just selected).
                    distribution_values = np.delete(distribution_values, winner_ind)
                    distribution_prob = np.delete(distribution_prob, winner_ind)
                    normalization_factor = sum(distribution_prob)
                    distribution_prob = np.divide(distribution_prob, normalization_factor)
                    
                    # 1) Send an email to the winner
                    email_subject = "%s - Monthly Prize Winner" % (website_name)
                    email_sender = email_username
                    email_receiver = winner_user.email
                    email_text = "Dear <b>%s</b>, \r\n\r\nYou won a prize from the monthly draw on %s!\r\n\r\nTo claim your prize, please respond to this email with the following information:\r\n\r\n1. Your e-mail address where you would like to receive the prize\r\n2. Your choice of prize (choose ONE of the following):\r\n%s\r\n\r\nThank you for your participation this month. You're awesome!\r\n\r\n- The SPOClab team!\r\n\r\nSPOClab: Signal Processing and Oral Communication lab\r\n550 University Avenue, 12-175\r\nToronto, Ontario M5G 2A2\r\n<a href='http://spoclab.ca'>http://spoclab.ca</a>\r\n\r\nYou are receiving this email due to your account preferences. To unsubscribe, please visit <a href='%s'>your Account Settings page</a>." % (winner_user.username, website_name, "\r\n".join(prizes_list), website_hostname + '/account')
                    email_html = """<h2 style="Margin-top: 0;color: #44a8c7;font-weight: 700;font-size: 24px;Margin-bottom: 16px;font-family: Lato,sans-serif;line-height: 32px;text-align: center">Dear %s, you won a prize from the monthly draw on %s!</h2>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">To claim your prize, please respond to this email with the following information:\r\n<ol style="font-size: 15px;font-family: sans-serif;line-height: 24px;text-align: left; margin-bottom: 24px;color: #000000;">\r\n<li>Your e-mail address where you would like to receive the prize</li>\r\n<li>Your choice of prize (choose ONE of the following):<br />%s</li></ol></p>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">&mdash; The SPOClab team</p>""" % (winner_user.username, website_name, "<br />\r\n".join(prizes_list))
                    
                    result_flag = emails.sendEmail(email_sender, email_name, [email_receiver], [], [email_sender], email_subject, email_text, emails.emailPre + email_html + emails.emailPost)
                    
                    # If the send was successful, record it in the database
                    if result_flag:
                        Subject_Emails.objects.create(date_sent=today, subject=winner_subject, email_from=email_sender, email_to=email_receiver, email_type=email_type)
                    
                    # 2) Issue a notification to the winner (to be seen within the website). There is no expiry/end date for prizes.
                    Subject_Notifications.objects.create(subject=winner_subject, notification=notification_type, date_start=today, dismissed=0)
                    
                json_data['winners'] = " || ".join([str(w) for w in winners])
                
    return HttpResponse(json.dumps(json_data))
Example #14
0
def reminders(request):
    json_data = {}
    json_data['status'] = "success"
    email_type = 'reminder'

    # Authenticate the request - has to be issued by a superuser
    if 'auth_name' in request.POST and 'auth_pass' in request.POST:
        username = request.POST['auth_name']
        password = request.POST['auth_pass']
        system_user = authenticate(username=username, password=password)
        output = ""
        if system_user is not None:
            if system_user.is_active and system_user.is_superuser:

                # Find all users who we need to remind & who have a validated email address
                users_to_remind = Subject.objects.filter(
                    preference_email_reminders=1,
                    email_validated=1,
                    email_reminders__isnull=False,
                    preference_email_reminders_freq__isnull=False)
                for user in users_to_remind:

                    username = User.objects.get(id=user.user_id).username
                    output += "User to remind: %s, %s" % (user.user_id,
                                                          username)

                    # Check if it has been X days since the last session access
                    user_email = user.email_reminders
                    user_pref_freq = int(user.preference_email_reminders_freq)
                    user_last_access = user.date_last_session_access  # stored as datetime.date
                    user_created = user.date_created  # stored as datetime.date

                    # Date of last access is either the last time the user accessed a session
                    # OR the date they created their account (if they haven't created any
                    # sessions yet)
                    date_last_access = None
                    if user_last_access:
                        date_last_access = user_last_access
                    elif user_created:
                        date_last_access = user_created

                    if date_last_access:
                        # Compute the date when we need to send the first reminder: X days
                        # (according to frequency preference) after the date of last access
                        date_first_reminder = date_last_access + datetime.timedelta(
                            days=user_pref_freq)

                        output += ", Date of first reminder: %s" % (
                            date_first_reminder)

                        # Check if today's date is past the day when the first reminder
                        # should be sent, and if it is, check if a reminder email was already sent
                        # today (to avoid duplication, e.g. if the script is re-run twice on same day)
                        delta = (today - date_first_reminder).days
                        if delta >= 0:
                            if delta % user_pref_freq == 0:
                                # Time for a reminder, but check if one was already sent today
                                existing_reminders = Subject_Emails.objects.filter(
                                    date_sent=today,
                                    subject=user,
                                    email_to=user_email,
                                    email_type=email_type)
                                if not existing_reminders:
                                    output += ", Time for a reminder (last access date: %s, reminder freq in days: %s)" % (
                                        date_last_access, user_pref_freq)

                                    # Set up message
                                    email_subject = "%s - %s Reminder" % (
                                        website_name,
                                        reminder_freq[user_pref_freq])
                                    email_sender = email_username
                                    email_receiver = user_email
                                    email_text = "Dear <b>%s</b>, \r\n\r\nIt's time for your next session on %s! When you are ready for some new language puzzles, <a href='%s'>click here</a>. Your participation in this project is important to us, and directly helps enable research into language pattern changes over time.\r\n\r\n- The SPOClab team!\r\n\r\nSPOClab: Signal Processing and Oral Communication lab\r\n550 University Avenue, 12-175\r\nToronto, Ontario M5G 2A2\r\n<a href='http://spoclab.ca'>http://spoclab.ca</a>\r\n\r\nYou are receiving this email due to your account preferences. To unsubscribe, please visit <a href='%s'>your Account Settings page</a>." % (
                                        username, website_name,
                                        website_hostname,
                                        website_hostname + '/account')
                                    email_html = """<h2 style="Margin-top: 0;color: #44a8c7;font-weight: 700;font-size: 24px;Margin-bottom: 16px;font-family: Lato,sans-serif;line-height: 32px;text-align: center">Dear %s, it's time for your next session on %s!</h2>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">When you are ready for some new language puzzles,\r\n <a style="text-decoration: none;color: #5c91ad;border-bottom: 1px dotted #5c91ad" data-emb-href-display="undefined" href='%s'>click here</a>.\r\n Your participation in this project is important to us, and directly helps enable research into language pattern changes over time.</p>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">&mdash; The SPOClab team</p>""" % (
                                        username, website_name,
                                        website_hostname)

                                    output += ", Message from %s (%s) to %s, body: %s" % (
                                        email_sender, email_subject,
                                        email_receiver, email_text)

                                    # Send the prepared email
                                    result_flag = emails.sendEmail(
                                        email_sender, email_name,
                                        [email_receiver], [], [],
                                        email_subject, email_text,
                                        emails.emailPre + email_html +
                                        emails.emailPost)

                                    # If the send was successful, record it in the database
                                    if result_flag:
                                        Subject_Emails.objects.create(
                                            date_sent=today,
                                            subject=user,
                                            email_from=email_sender,
                                            email_to=email_receiver,
                                            email_type=email_type)
            else:
                json_data['status'] = 'error'
                json_data['error'] = 'Unauthorized'
                return HttpResponse(json.dumps(json_data), status=401)
        else:
            json_data['status'] = 'error'
            json_data['error'] = 'Unauthorized'
            return HttpResponse(json.dumps(json_data), status=401)

        #json_data['debug'] = output
        return HttpResponse(json.dumps(json_data))
    else:
        json_data['status'] = 'error'
        json_data['error'] = 'Unauthorized'
        return HttpResponse(json.dumps(json_data), status=401)
def callback_query(call):

    now = datetime.datetime.now()
    # print(now.date()+timedelta(days=15))
    # Quantity of products with names
    list_callbacks_sales = []
    all_names_products = showInfoProducts()
    query_quantity_products = cantProducts()
    try:
        for x in range(query_quantity_products):
            products_names_query = all_names_products.next()
            for items in products_names_query:
                # print(items)
                if items == 'name':
                    list_callbacks_sales.append(products_names_query[items])
    except:
        pass
    # Variables
    sales_buttons = InlineKeyboardMarkup()
    uid = call.from_user.id
    # print(str(uid))
    infoCustomer = showInfoCustomer(uid)
    isExist = customer_exist(uid)
    info_null = False
    data_incomplete = []
    band_action = False
    save = ''
    action = ''
    index = 0
    for items in list_callbacks_sales:
        # print(items)
        if call.data == items:
            infoCustomer = showInfoCustomer(uid)
            print(call.data)
            name_product_sale = ''
            details_sales = {}
            details_sales = QueryInfoShoppingProduct(items)
            product_n = details_sales['name_product']
            details_of_product_query = showDetailsProducts(product_n)
            buttons_options_to_declined_product = InlineKeyboardMarkup()
            buttons_options_to_declined_product.add(
                InlineKeyboardButton("Cancelar pedido", callback_data="cancel_order"),
                InlineKeyboardButton("Okay", callback_data="ok_order")
                )
            message = responses['shop']['info_shop']['info'] + "\n" + responses['shop']['info_shop']['name_customer'] + details_sales['name_customer'] + "\n" + responses['shop']['info_shop']['ship'] + details_sales['shipment_no'] + "\n" +responses['shop']['info_shop']['name_product'] + details_sales['name_product'] + "\n" +responses['shop']['info_shop']['Fecha_compra'] + details_sales['date_sale'] + "\n" +responses['shop']['info_shop']['date_delivered'] + details_sales['date_delivered'] + "\n" +responses['shop']['info_shop']['track_code'] + details_sales['track_code'] + "\n" +responses['shop']['info_shop']['total_paid'] + details_sales['total_paid']
            bot.send_photo(chat_id=call.message.json['chat']['id'], photo=details_of_product_query['image'], caption=message, reply_markup=buttons_options_to_declined_product)
    
    if call.data == 'my_sales_cenceled':
        print("asd")

    if call.data == 'cancel_order_confimation_yes':
        cont = 0
        for lines in call.message.text.splitlines():
            # print(lines)
            cont = cont + 1
            nameProductToCancelOrder = ''
            if cont == 3:
                nameProductToCancelOrder = lines.replace('Producto: ', "")
        object_ = 'status'
        details = QueryInfoShoppingProduct(nameProductToCancelOrder)
        # print(details)
        with open('extra_data/cancel_order.json', encoding='utf-8') as f:
                conditions = json.load(f)
        for i in conditions:
           if i == object_:
                    print(conditions[i])
                    conditions[i] = "Orden cancelada"
        data_product = conditions

        with open('extra_data/cancel_order.json', 'w') as f:
            json.dump(data_product, f)

        updateSale(uid)
    
    if call.data == 'cancel_order_confimation_no':
        bot.send_chat_action(call.message.json['chat']['id'], 'typing')
        bot.send_message(call.message.json['chat']['id'], "Acción cancelada.")
   
    
    if call.data == 'cancel_order':
        # print(call.message.caption)
        message_caption = call.message.caption
        today = datetime.datetime.now()
        cont = 0
        cancel_nameProduct = ''
        time_to_cancel = ''
        for lines in message_caption.splitlines():
            # print(lines)
            cont = cont + 1
            if cont == 4:
                cancel_nameProduct = lines.replace('Producto: ', "")
            if cont == 5:
                time_to_cancel = lines.replace('Fecha de la compra: ' , "")
        time_remaining = datetime.datetime.strptime(time_to_cancel,  "%Y-%m-%d %H:%M:%S")
        date_remaining = time_remaining.date()
        print(date_remaining)
        hour_remaining = time_remaining.time()

        details_of_sale = QueryInfoShoppingPerProduct(cancel_nameProduct)
        # for items_ in details_of_sale:
        #     # print(items_)
        #     pass

        # Same DATE
        if date_remaining == now.date():
            if hour_remaining < now.time():
                format = "%H:%M:%S"
                hours = time_remaining.hour + 4
                aux = str(hours) + ":"+str(time_remaining.minute )+":"+str(time_remaining.second) 
                timeDate = datetime.datetime.strptime(aux, format)
                print(timeDate.time())
                print(now.time())
                if timeDate.time() < now.time():
                    message = responses['shop']['line4']
                    bot.send_photo(chat_id=call.message.json['chat']['id'], photo='https://vistapointe.net/images/errors-9.jpg', caption=message)
                else:
                    buttons_options_to_declined_product = InlineKeyboardMarkup()
                    buttons_options_to_declined_product.add(
                        InlineKeyboardButton("Si", callback_data="cancel_order_confimation_yes"),
                        InlineKeyboardButton("No", callback_data="cancel_order_confimation_no"),
                    )
                    bot.send_chat_action(call.message.json['chat']['id'], 'typing')
                    bot.send_message(call.message.json['chat']['id'], "Confirmación🚨\n¿Estas seguro de querer cancelar la orden?\n" + cancel_nameProduct, reply_markup=buttons_options_to_declined_product)
   
        else:
            message = responses['shop']['line4']
            bot.send_photo(chat_id=call.message.json['chat']['id'], photo='https://vistapointe.net/images/errors-9.jpg', caption=message)

        if time_remaining < today:
            pass
    if call.data == 'ok_order':
        message = responses['shop']['success']
        bot.send_photo(chat_id=call.message.json['chat']['id'], photo='https://cdn.dribbble.com/users/1751799/screenshots/5512482/check02.gif', caption=message)

    # Sales info
    if call.data == 'my_sales':
        quantity = QueryInfoShoppingCount(uid)
        print(quantity)
        if quantity > 0:
            sales_information = QueryInfoShopping(uid)
            for amount in range(quantity):
                sales = sales_information.next()
                for items_ in sales:
                    if items_ == 'name_product':
                        # print(sales[items_])
                        name_product_query = sales[items_]
                        sales_buttons.add(InlineKeyboardButton(name_product_query, callback_data=name_product_query))
            bot.send_chat_action(call.message.json['chat']['id'], 'typing')
            bot.send_message(call.message.json['chat']['id'], "Sales🚨", reply_markup=sales_buttons)
        else:
            bot.send_chat_action(call.message.json['chat']['id'], 'typing')
            bot.send_message(call.message.json['chat']['id'], "No ha hecho ninguna compra hasta el momento, favor confirme su compra si no lo ha hecho.\nUtiliza /products para ver los productos disponibles.", reply_markup=sales_buttons)
        
    if call.data == 'x':
        jsonProduct = call.message.json['caption']
        if isExist != None:
            for items in infoCustomer:
                index = index + 1
                x = items
                if infoCustomer[x] == "null":
                    info_null = True
                    print(info_null)
                    data_incomplete.insert(index,x)
                    print(infoCustomer[x] + "errir")
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_customer']['es'])

        # print(info_null)
        if info_null == True:
            print("asd")
            info_for_user = "******" + "Los siguientes campos debe completarlos correctamente:"
            print(info_for_user)
            for item in data_incomplete:
                print(item)
                info_for_user = info_for_user + " " + item + ","
            print(info_for_user)
            bot.send_message(call.message.json['chat']['id'], info_for_user + "\nUtilice el comando /register para confirmar sus datos")
        else:
            cont = 0
            total_paid = ''
            for line in jsonProduct.splitlines():
                cont = cont + 1
                # print(cont)
                # print(line)
                if cont == 1:
                    jsonProduct = line
                elif cont == 3:
                    total_paid = line
                elif cont == 4:
                    break
            buttons = InlineKeyboardMarkup()
            list = {"Si", "No"}
            buttons.add(InlineKeyboardButton("Si", callback_data="Si_comprar"),
            InlineKeyboardButton("No", callback_data="No_comprar") )
            bot.send_message(call.message.json['chat']['id'],jsonProduct + "\n" + total_paid + "\n" + responses['shop']['line1'], reply_markup=buttons)
    if call.data == 'Si_comprar':
        cont = 0
        jsonProduct = call.message.json['text']
        total_paid = ''
        for line in jsonProduct.splitlines():
            cont = cont + 1
            if cont == 1:
                jsonProduct = line
            if cont == 2:
                total_paid = line.replace("Precio: ", "")
        print(jsonProduct)
        # details_product = showInfoProducts(jsonProduct)
        print(total_paid)
        infoCustomer = showInfoCustomer(uid)
        # print(infoCustomer)
        details = showDetailsProducts(jsonProduct)
        description_product = details['detail']
        category_product = details['category']
        no_shipment = random.randint(100000000,200000000)
        now = datetime.datetime.now()
        date_sale = str(now)
        date_delivered = str(now.date()+timedelta(days=15))
        track_code = generate_track_code()
        information_sale = {
        "idCustomer": infoCustomer['id'],
        'name_customer':infoCustomer['name'],
        'shipment_no':str(no_shipment),
        'name_product':jsonProduct,
        'description':description_product,
        'category_product': category_product,
        'date_sale':date_sale,
        'date_delivered': date_delivered,
        'track_code':track_code,
        'total_paid':total_paid,
        'status':"enviado",
        }

        with open('extra_data/information_sale.json', 'w') as f:
            json.dump(information_sale, f)
        print(information_sale)
        info_email = {}
        with open('extra_data/email.json', 'r') as file:
            info_email = json.load(file)
        # Create sale
        create_sale()
        message = responses['shop']['info_shop']['info'] + "\n" +responses['shop']['info_shop']['name_customer'] + infoCustomer['name'] + "\n" +responses['shop']['info_shop']['ship'] + str(no_shipment) + "\n" +responses['shop']['info_shop']['name_product'] + jsonProduct + "\n" +responses['shop']['info_shop']['Fecha_compra'] + date_sale + "\n" +responses['shop']['info_shop']['date_delivered'] + date_delivered + "\n" +responses['shop']['info_shop']['track_code'] + track_code + "\n" +responses['shop']['info_shop']['total_paid'] + total_paid + "\n" +responses['shop']['line2'] + "\n" +responses['information_myself']['state'] + infoCustomer['state'] + "\n" +responses['information_myself']['country'] + infoCustomer['country'] + "\n" +responses['information_myself']['address1'] + infoCustomer['address_1'] + "\n" +responses['information_myself']['address2'] + infoCustomer['address_2'] + "\n" +responses['information_myself']['email'] + infoCustomer['email'] + "\n" +responses['information_myself']['zip'] + infoCustomer['zip_code'] + "\nStatus de la entrega: Enviado\nPuedes utilizar el comando /Shopping para ver la informacion de todas tus compras."
        sendEmail(info_email['email'], info_email['password'], message.encode('utf-8'), infoCustomer['email'])
        bot.send_message(call.message.json['chat']['id'],
        message
        )

    if call.data == 'Mi informacion':
        infoCustomer = showInfoCustomer(uid)
        bot.send_message(call.message.json['chat']['id'],
        responses['information_myself']['name'] + infoCustomer['name'] + "\n" +
        responses['information_myself']['age'] + infoCustomer['age'] + "\n" +
        responses['information_myself']['state'] + infoCustomer['state'] + "\n" +
        responses['information_myself']['country'] + infoCustomer['country'] + "\n" +
        responses['information_myself']['address1'] + infoCustomer['address_1'] + "\n" +
        responses['information_myself']['address2'] + infoCustomer['address_2'] + "\n" +
        responses['information_myself']['email'] + infoCustomer['email'] + "\n" +
        responses['information_myself']['zip'] + infoCustomer['zip_code']
        )
    if call.data == 'save_country':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['country'], reply_markup=sendto)
    if call.data == 'save_state':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['state'], reply_markup=sendto)
    if call.data == 'save_email':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['email'], reply_markup=sendto)
    if call.data == 'save_age':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['age'], reply_markup=sendto)
    if call.data == 'save_zip_code':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['zip'], reply_markup=sendto)
    if call.data == 'save_address_1':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['address1'], reply_markup=sendto)
    if call.data == 'save_address_2':
        sendto = types.ForceReply(selective=True)
        bot.send_message(call.message.json['chat']['id'], responses['register_customer']['address2'], reply_markup=sendto)

    if call.data == 'Country':
        if infoCustomer['country'] == "null":
            band_action = True
            save = 'save_'+'country'
            action = "Ciudad/Región\nClick en Guardar\nInserta el campo. Example: Santiago de los caballeros"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['country'] + infoCustomer['country'])
    if call.data == 'Age':
        if infoCustomer['age'] == "null":
            band_action = True
            save = 'save_'+'age'
            action = "Edad\nClick en Guardar\nInserta el campo. Example: 21"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['age'] + infoCustomer['age'])
    if call.data == 'Name':
        if infoCustomer['name'] == "null":
            band_action = True
            save = 'save_'+'name'
            action = "Nombre y Apellido\nClick en Guardar\nInserta el campo. Example: Pedro"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['name'] + infoCustomer['name'])
    if call.data == 'Zip code':
        if infoCustomer['zip_code'] == "null":
            band_action = True
            save = 'save_'+'zip_code'
            action = "Zip code\nClick en Guardar\nInserta el campo. Example: 51000"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['zip'] + infoCustomer['zip_code'])
    if call.data == 'State':
        if infoCustomer['state'] == "null":
            band_action = True
            save = 'save_'+'state'
            action = "Estado \nClick en Guardar\nInserta el campo. Example: Cibao"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['state'] + infoCustomer['state'])
    if call.data == 'Address1':
        if infoCustomer['address_1'] == "null":
            band_action = True
            save = 'save_'+'address_1'
            action = "Primera Direccion\nClick en Guardar\nInserta el campo. Example: Mella 85"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['address1'] + infoCustomer['address_1'])
    if call.data == 'Address2':
        if infoCustomer['address_2'] == "null":
            band_action = True
            save = 'save_'+'address_2'
            action = "Segunda Direccion\nClick en Guardar\nInserta el campo. Example: Navarrete,villa bisono"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['address2'] + infoCustomer['address_2'])
    if call.data == 'Email':
        if infoCustomer['email'] == "null":
            band_action = True
            save = 'save_'+'email'
            action = "Email\nClick en Guardar\nInserta el campo. Example: [email protected]"
        else:
            bot.send_message(call.message.json['chat']['id'], responses['register_complete']['email'] + infoCustomer['email'])

    if band_action == True:
        send_action_to_user(call, action,save)

    for x in range(0,10):
        if call.data == str(x):
            showDetails(call, str(x))
Example #16
0
def monthlydraw(request):
    json_data = {}
    json_data['status'] = "success"
    email_type = 'prize_notification'
    notification_type = Notification.objects.get(
        notification_id='monthlyprize_winner')
    NUM_WINNERS = 5

    # Authenticate the request - has to be issued by a superuser
    if 'auth_name' in request.POST and 'auth_pass' in request.POST:
        username = request.POST['auth_name']
        password = request.POST['auth_pass']
        system_user = authenticate(username=username, password=password)
        output = ""
        if system_user is not None:
            if system_user.is_active and system_user.is_superuser:

                today = datetime.datetime.now().date()
                #today = datetime.datetime.strptime('2016-02-28', '%Y-%m-%d').date()
                month_start = datetime.date(today.year, today.month, 1)
                month_end = datetime.date(
                    today.year, today.month,
                    calendar.monthrange(today.year, today.month)[1])

                # Build a list of all available monetary prizes
                prizes_list = [
                    p.prize_name for p in Prize.objects.filter(
                        prize_value__gt=0).order_by('prize_name')
                ]

                # Build a probability distribution over the users who have
                # at least one completed session over the past month, and have elected
                # to participate in the monthly prize draws, and have a valid email
                # address.
                # The probability of winning is equal to the number of completed sessions over the
                # past month / total number of completed sessions over the past month.
                # NB: it doesn't matter when the session was started.
                subj_eligible = Subject.objects.filter(
                    preference_prizes=1,
                    email_prizes__isnull=False,
                    email_validated=1,
                    session__isnull=False,
                    session__end_date__isnull=False,
                    session__end_date__gte=month_start,
                    session__end_date__lte=month_end).distinct().annotate(
                        Count('session', distinct=True))
                total_sess = sum([x.session__count for x in subj_eligible])

                distribution_values = np.array(
                    [x.user_id for x in subj_eligible])
                distribution_prob = np.array([
                    x.session__count * 1.0 / total_sess for x in subj_eligible
                ])

                # Adjust the distribution probabilities by penalizing previous prize winners,
                # where the penalty is proportional to the number of wins
                penalty_past_win = 0.5
                past_wins = [
                    x.subject_notifications_set.filter(
                        notification=notification_type).count()
                    for x in subj_eligible
                ]
                penalty_factors = [
                    float(math.pow(penalty_past_win, x)) for x in past_wins
                ]
                penalized_prob = [
                    distribution_prob[x] * penalty_factors[x]
                    for x in range(len(subj_eligible))
                ]
                adjustment_factor = sum(penalized_prob)
                distribution_prob = [
                    x / adjustment_factor for x in penalized_prob
                ]

                # The number of winners is either the pre-specified number, or the number of eligible subjects
                # (if the latter is smaller).
                NUM_WINNERS = min(NUM_WINNERS, len(subj_eligible))

                # Select the winners randomly by sampling the distribution, without replacement.
                winners = []
                for run in range(NUM_WINNERS):
                    bins = np.add.accumulate(distribution_prob)
                    winner_ind = np.digitize(random_sample(1), bins)
                    winner_id = int(distribution_values[winner_ind])
                    winner_subject = Subject.objects.get(user_id=winner_id)
                    winner_user = User.objects.get(id=winner_id)
                    winners += [winner_id]

                    # Update the distribution (remove the winner that was just selected).
                    distribution_values = np.delete(distribution_values,
                                                    winner_ind)
                    distribution_prob = np.delete(distribution_prob,
                                                  winner_ind)
                    normalization_factor = sum(distribution_prob)
                    distribution_prob = np.divide(distribution_prob,
                                                  normalization_factor)

                    # 1) Send an email to the winner
                    email_subject = "%s - Monthly Prize Winner" % (
                        website_name)
                    email_sender = email_username
                    email_receiver = winner_user.email
                    email_text = "Dear <b>%s</b>, \r\n\r\nYou won a prize from the monthly draw on %s!\r\n\r\nTo claim your prize, please respond to this email with the following information:\r\n\r\n1. Your e-mail address where you would like to receive the prize\r\n2. Your choice of prize (choose ONE of the following):\r\n%s\r\n\r\nThank you for your participation this month. You're awesome!\r\n\r\n- The SPOClab team!\r\n\r\nSPOClab: Signal Processing and Oral Communication lab\r\n550 University Avenue, 12-175\r\nToronto, Ontario M5G 2A2\r\n<a href='http://spoclab.ca'>http://spoclab.ca</a>\r\n\r\nYou are receiving this email due to your account preferences. To unsubscribe, please visit <a href='%s'>your Account Settings page</a>." % (
                        winner_user.username, website_name,
                        "\r\n".join(prizes_list),
                        website_hostname + '/account')
                    email_html = """<h2 style="Margin-top: 0;color: #44a8c7;font-weight: 700;font-size: 24px;Margin-bottom: 16px;font-family: Lato,sans-serif;line-height: 32px;text-align: center">Dear %s, you won a prize from the monthly draw on %s!</h2>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">To claim your prize, please respond to this email with the following information:\r\n<ol style="font-size: 15px;font-family: sans-serif;line-height: 24px;text-align: left; margin-bottom: 24px;color: #000000;">\r\n<li>Your e-mail address where you would like to receive the prize</li>\r\n<li>Your choice of prize (choose ONE of the following):<br />%s</li></ol></p>\r\n<p style="Margin-top: 0;color: #60666d;font-size: 15px;font-family: sans-serif;line-height: 24px;Margin-bottom: 24px;text-align: center">&mdash; The SPOClab team</p>""" % (
                        winner_user.username, website_name,
                        "<br />\r\n".join(prizes_list))

                    result_flag = emails.sendEmail(
                        email_sender, email_name, [email_receiver], [],
                        [email_sender], email_subject, email_text,
                        emails.emailPre + email_html + emails.emailPost)

                    # If the send was successful, record it in the database
                    if result_flag:
                        Subject_Emails.objects.create(date_sent=today,
                                                      subject=winner_subject,
                                                      email_from=email_sender,
                                                      email_to=email_receiver,
                                                      email_type=email_type)

                    # 2) Issue a notification to the winner (to be seen within the website). There is no expiry/end date for prizes.
                    Subject_Notifications.objects.create(
                        subject=winner_subject,
                        notification=notification_type,
                        date_start=today,
                        dismissed=0)

                json_data['winners'] = " || ".join([str(w) for w in winners])

    return HttpResponse(json.dumps(json_data))
Example #17
0
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		rejectPath = UrlBuilder(self.request).buildUrl('/reject')
		
		user = users.get_current_user()
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("command")
		members = group.memberships
		
		parser = OrderParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
			
		payersBalanceBefore = transaction.payer.balance
		
		for debt in transaction.debts:
		    debtor = debt.member
		    payer = transaction.payer
		    debtorLang = getLanguage(self, debtor.user)
			
		    if debtor.user.email().lower() == payer.user.email().lower():
		        continue
			
		    debtorsBalanceBefore = debtor.balance
		    
		    # Adjust balance
		    debtor.balance -= debt.money
		    debtor.put()
		    
		    payer.balance += debt.money
		    
		    debtorsBalanceNow = debtor.balance
		    
		    # Create transaction
		    tr = Transaction(
		        group = group,
		        creatorMember = creatorMember, 
		        fromMember = debtor,
		        toMember = payer,
		        type = 'debt',
		        amount = debt.money, 
		        reason = debt.reason,
		        isRejected = False
		        )
		    tr.put()
			
		    # If the one that created this transaction is the one that owes,
		    # don't sent a mail to him/her
		    if creatorMember.user == debtor.user:
		    	continue
		    
		    # Build the reject url
		    rejectUrl = UrlBuilder(self.request).buildUrl('/reject')
		    rejectUrl += "?key=%s&h=%s" % (str(tr.key()), tr.hash)
		    
		    # Try send email to the debtor
		    if creatorMember.user == transaction.payer.user:
		    	message = createActionMail(payer, debtor, debt.money, debt.reason, debtorsBalanceBefore, debtorsBalanceNow, rejectUrl, youOwedSomeone(debtorLang), debtorLang) 
		    else:
		    	message = createThirdPartyActionMail(creatorMember, payer, debtor, debt.money, debt.reason, debtorsBalanceBefore, debtorsBalanceNow, rejectUrl, creatorSaysYouOwedSomeone(debtorLang), debtorLang)
		    
		    sendEmail(message)
				
		transaction.payer.put()
		
		payersBalanceNow = transaction.payer.balance
		
		# Now try send email to the payer with a summary
		if not creatorMember.user == transaction.payer.user:
			payerLang = getLanguage(self, transaction.payer.user)
			message = createBulkMail(transaction, creatorMember, payersBalanceBefore, payersBalanceNow, payerLang)
			sendEmail(message)
				
		location = '/group?group=%s&msg=%s' % (group.key(), _('Debts saved!', lang))
		redirectPage(self,location)
Example #18
0
    def post(self):
        if not userIsLoggedIn(self):
            return
        
        key = self.request.get('key')
        hash = self.request.get('h')
        reason = self.request.get('reason').strip()
        user = users.get_current_user()
        lang = getLanguage(self, user)
        
        # Check that all is ok
        tr = isValidTransaction(key, hash, user)
        if not tr:
            self.redirect('/')
            return
        
        # Check that the transaction is not rejected
        if tr.isRejected:
            self.redirect('/')
            return
        
        # Reject it and everything else...
        tr.isRejected = True
        
        compensateTr = tr.getCompensateFor(user)
        
        # See who is me, and who is someone
        if compensateTr.creatorMember == compensateTr.fromMember:
            me = compensateTr.fromMember
            someone = compensateTr.toMember
        else:
            me = compensateTr.toMember
            someone = compensateTr.fromMember
            
        someoneLang = getLanguage(self, someone.user)
            
        balanceBefore = someone.balance

        # ========================================================= #
        # See what's the type of the transaction and adjust balance
        # ========================================================= #
        
        if tr.type == 'debt':
            # If it's a debt, fromMember always wins
            tr.fromMember.balance += tr.amount
            tr.toMember.balance -= tr.amount
            
            if compensateTr.creatorMember.user == tr.fromMember.user:
                # I owe someone
                mailBody = someoneOwedYou(someoneLang, reject = True)
            else:
                # Someone owes me
                mailBody = youOwedSomeone(someoneLang, reject = True)
        elif tr.type == 'payment':
            # If it's a payment, fromMember always looses
            tr.fromMember.balance -= tr.amount
            tr.toMember.balance += tr.amount
            
            if compensateTr.creatorMember.user == tr.fromMember.user:
                # I paid someone
                mailBody = someonePayedYou(someoneLang, reject = True)
            else:
                # Someone paid me
                mailBody = youPayedSomeone(someoneLang, reject = True)
        else:
            # Can't happen, only with hackery
            return
        
        tr.fromMember.put()
        tr.toMember.put()
        tr.put()
        compensateTr.put()
        
        balanceNow = someone.balance

        # ========================== #
        # Try send notification mail #
        # ========================== #        
        
        # Try send mail
        message = createRejectionMail(me, someone, tr, reason, balanceBefore, balanceNow, mailBody, someoneLang)
        sendEmail(message)
        
        location = '/group?group=%s&msg=%s' % (tr.group.key(), _('You rejected the transaction', lang))
        redirectPage(self,location)