contactorama/app/controllers/birthdays_controller.rb

92 lines
2.9 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
birthdays = get_birthdays_next_7d
logger.debug "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.next_weeks_birthday_notification(email, bdays).deliver
end
# logger.debug "..... birthdays: " + birthdays.count.to_s + "......"
# birthdays.each do |bday|
# logger.info "............< do_mailing: " + bday.firstname + " " + bday.lastname + " >.............."
# UserMailer.next_weeks_birthday_notification(birthdays).deliver
# end
end
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 get_birthdays_next_7d
get_birthdays_next_n_days(7)
end
def get_birthdays_next_2d
get_birthdays_next_n_days(2)
end
def get_birthdays_in_7d
get_birthdays_in_n_days(7)
end
def get_birthdays_in_2d
get_birthdays_in_n_days(2)
end
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
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