77 lines
2.6 KiB
Ruby
77 lines
2.6 KiB
Ruby
# -*- coding: utf-8 -*-
|
|
class BirthdaysController < ApplicationController
|
|
before_filter :authenticate_user!, :except => [:do_mailing]
|
|
|
|
def index
|
|
@birthdays = get_birthdays_in_2d # get_birthdays_next_7d
|
|
@nav_active = "birthdays"
|
|
end
|
|
|
|
# curl --verbose --header "Content-type: application/html" --request POST --data "" http://contactorama.dev/birthdays/do_mailing
|
|
# wget --post-data '' http://contact-o-rama.de/birthdays/do_mailing
|
|
# crontab:
|
|
# 30 3 * * * wget --post-data '' http://contact-o-rama.de/birthdays/do_mailing
|
|
def do_mailing
|
|
do_mailing_days_in_advance(2)
|
|
do_mailing_days_in_advance(7)
|
|
|
|
logger.debug "........... Mailings done (or had none to do)"
|
|
respond_to do |format|
|
|
logger.debug ".... rendering...."
|
|
format.html { render :layout => false }
|
|
logger.debug ".... rendered ...."
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def do_mailing_days_in_advance(num_days)
|
|
birthdays = get_birthdays_in_n_days(num_days)
|
|
logger.debug "[" + num_days.to_s + "]: birthdays.nil? = " + birthdays.nil?.to_s + "......"
|
|
unless birthdays.nil?
|
|
birthdays_by_email = group_birthdays_by_email(birthdays)
|
|
birthdays_by_email.each do |email, bdays|
|
|
UserMailer.upcoming_birthdays_notification(email, bdays, num_days).deliver
|
|
end
|
|
end
|
|
end
|
|
|
|
# returns all birthdays happening during the next num_days.
|
|
def get_birthdays_next_n_days(num_days)
|
|
n = Date.today
|
|
e = Date.today + num_days.days
|
|
|
|
# two cases here: now + x days is still the same month. or it's not.
|
|
if n.month == e.month
|
|
birthdays = Contact.where("birth_month = ? AND birth_day <= ? AND birth_day >= ?",
|
|
e.month, e.day, n.day)
|
|
else
|
|
birthdays = Contact.where("(birth_month = ? AND birth_day <= ?) OR (birth_month = ? AND birth_day >= ?)",
|
|
e.month, e.day, n.month, n.day)
|
|
end
|
|
birthdays
|
|
end
|
|
|
|
# returns all birthdays happening exactly num_days from now.
|
|
def get_birthdays_in_n_days(num_days)
|
|
target_date = Date.today + num_days.days
|
|
birthdays = Contact.where("birth_month = ? AND birth_day = ?", target_date.month, target_date.day)
|
|
end
|
|
|
|
# in: Array [contact,contact,contact,...]
|
|
# out: Hash[email] = [contact,contact,contact,....]
|
|
def group_birthdays_by_email(birthday_contacts)
|
|
ret = Hash.new
|
|
birthday_contacts.each do |contact|
|
|
email = User.find(contact.user_id).email
|
|
if ret[email].nil? then # haven't seen this email, yet
|
|
a = Array.new
|
|
a << contact
|
|
ret[email] = a
|
|
else # add contact w/ birthday for this email
|
|
ret[email] << contact
|
|
end
|
|
end
|
|
ret
|
|
end
|
|
end
|