Skip to content

Instantly share code, notes, and snippets.

@linqing
Created May 30, 2013 03:12
Show Gist options
  • Save linqing/5675520 to your computer and use it in GitHub Desktop.
Save linqing/5675520 to your computer and use it in GitHub Desktop.
class Bill < ActiveRecord::Base
set_table_name "ads"
has_many :bill_edit_histories
has_many :bill_display_dates, :dependent => :destroy, :foreign_key => 'bill_id'
has_many :bill_display_times, :dependent => :destroy
has_many :mem_integrals
belongs_to :bill_type
belongs_to :bill_brand
has_one :bill_last_display_date, :class_name=>'BillDisplayDate', :order => 'edates desc' # todo 这个地方好像有错
has_many :attachments, :as => :container, :dependent => :destroy
has_many :bill_areas, :dependent => :destroy
has_one :full_text, :as => :document, :dependent => :delete
scope :with_id, lambda { |id| { :conditions => ['ads.id = ?', id]}}
scope :with_text, lambda { |search_str|
{ :include => :full_text,
:conditions => ["#{FullText.table_name}.full_text like ?", "%#{search_str}%"]}
}
scope :of_type, lambda { |t|
{ :conditions => (t.blank? ? [] : ["bill_type_id = ?", t])}
}
scope :huge_bills, :conditions => ["bill_type_id = 1"]
scope :big_bills, :conditions => ["bill_type_id = 2"], :order => 'position desc'
scope :sex_of, lambda { |sex| { :conditions => ['sex = ? or sex = 2', sex]}}
scope :date_match_today, :include => :bill_display_dates,
:conditions => ["(UNIX_TIMESTAMP(#{BillDisplayDate.table_name}.bdates)<=UNIX_TIMESTAMP(now()) and UNIX_TIMESTAMP(#{BillDisplayDate.table_name}.edates)>=UNIX_TIMESTAMP(now()))"]
scope :time_match_now, :include => :bill_display_times,
:conditions => ["""unix_timestamp(now()) between UNIX_TIMESTAMP( CONCAT( date_format( now( ) , ? ) , #{BillDisplayTime.table_name}.btimes, ':00' ) ) and UNIX_TIMESTAMP( CONCAT( date_format( now( ) , ? ) , #{BillDisplayTime.table_name}.etimes, ':00' ))""", '%Y-%c-%d ', '%Y-%c-%d ']
scope :target_year_match, lambda { |user_birth_year| { :conditions => ["(target_begin_year is null or target_begin_year <= ? ) and (target_end_year is null or target_end_year >= ?)", user_birth_year, user_birth_year] } }
scope :is_place_holder, :conditions => ["isplaceholder = 1"]
scope :surplus_hits_match_or_is_place_holder, :conditions => ["surplus_hits > 0 or isplaceholder = 1"]
scope :day_limit_traffic_match_or_is_place_holder, :conditions => ["isplaceholder = 1 or day_limit_traffic > (
select count(*)
from #{MemIntegral.table_name} as lmi
where lmi.bill_id = ads.id
and add_date between unix_timestamp( date_format( now(), ?) )
and unix_timestamp( date_format( now( ), ?) )
)", '%Y-%c-%d 00:00:00', '%Y-%c-%d 23:59:59']
scope :user_day_limit_traffic_match_or_is_place_holder, lambda { |current_member_id| { :conditions => ["isplaceholder = 1 or one_user_traffic > (
select count(*)
from #{MemIntegral.table_name} as lmi
where bill_id = ads.id
and member_id = ?
and add_date between unix_timestamp( date_format( now(), ?))
and unix_timestamp( date_format( now( ), ?))
)", current_member_id, '%Y-%c-%d 00:00:00', '%Y-%c-%d 23:59:59']
} }
# 会员当日点击这个广告的次数, 没有达到广告的[单用户单日点击上限]的所有广告(说明用户还可以点击这个广告)
scope :user_day_limit_traffic_match, lambda { |current_member_id| { :conditions => [" (
select count(*)
from #{MemIntegral.table_name} as lmi
where bill_id = ads.id
and member_id = ?
and add_date between unix_timestamp( CONCAT( date_format( now(), ?) , ' 00:00:00'))
and unix_timestamp( CONCAT( date_format( now( ), ?), ' 23:59:59'))
) < one_user_traffic", current_member_id, '%Y-%c-%d', '%Y-%c-%d']
} }
# 会员当日点击这个广告的次数, 没有达到广告的[单用户总点击上限]的所有广告(说明用户还可以点击这个广告)
scope :user_day_total_click_limit_traffic_match, lambda { |current_member_id| { :conditions => [" (
select count(*)
from #{MemIntegral.table_name} as lmi
where bill_id = ads.id
and member_id = ?) < one_user_total_click_traffic", current_member_id, '%Y-%c-%d', '%Y-%c-%d']
} }
scope :target_region_match, lambda { |province, city, area | { :include => :bill_areas,
:conditions => ["? like concat(#{BillArea.table_name}.area, '%')","#{province}#{city}#{area}"]}
}
scope :abnormal_bills, :include => :bill_display_dates, :conditions => ["surplus_hits < day_limit_traffic * 10 or unix_timestamp(#{BillDisplayDate.table_name}.edates) < e_date"]
scope :has_edit_histories, :include => :bill_edit_histories,
:conditions => ["exists(select ad_edit_histories.bill_id from ad_edit_histories where ad_edit_histories.bill_id = ads.id)"]
scope :industry_and_position_match, lambda { |industry, position | {
:conditions => ["(target_positions is null) or (target_positions = '') or (target_positions like ?) or (target_positions like ?) or (target_positions like ?) ", "%#{industry},%", "%#{position},%", "%#{industry}#{position},%"]}
}
scope :personality_and_favorite_match, lambda { |personality, favorite | {
:conditions => ["(target_favoriates is null) or (target_favoriates = '') or (target_favoriates like ?) or (target_favoriates like ?) or (target_favoriates like ?) ", "%#{personality}|%", "%#{favorite}|%", "%#{personality}#{favorite},%"]}
}
scope :industry_match, lambda { |industry|
{ :conditions => ["target_industries is null or target_industries= '' or target_industries like ? ", "%#{industry}%"] }
}
scope :position_match, lambda { |position|
{ :conditions => ["target_positions is null or target_positions= '' or target_positions like ? ", "%#{position}%"] }
}
scope :personality_match, lambda { |personality|
{ :conditions => ["target_personalities is null or target_personalities= '' or target_personalities like ? ", "%#{personality}%"] }
}
scope :favoriate_match, lambda { |favoriate|
{ :conditions => ["target_favoriates is null or target_favoriates= '' or target_favoriates like ? ", "%#{favoriate}%"] }
}
validates_presence_of :bill_brand_id, :message => "品牌名称必须填写!"
validates_presence_of :bill_type_id, :message => "广告类型必须填写!"
validates_presence_of :playtimes, :message => "播放时长必须填写!"
validates_presence_of :playtimes, :message => '播放时间不能为空!'
validates_presence_of :total_score, :message => '总积分不能为空!'
validates_presence_of :one_click, :message => '单次点击积分不能为空!'
validates_presence_of :day_limit_traffic, :message => '单日上限点击量不能为空!'
validates_presence_of :one_user_traffic, :message => '单位点击量不能为空!'
validates_presence_of :b_date, :message => '开始时间不能为空!'
validates_presence_of :e_date, :message => '结束时间不能为空!'
validates_presence_of :body, :message => "广告详细描述不能为空!"
validates_presence_of :isplaceholder, :message => '是否占位不能为空!'
validates_presence_of :sex, :message => '性别不能为空!'
validates_presence_of :description, :message => '广告描述不能为空!'
before_save :old_before_save
after_save :old_after_save
def old_before_save
self.url ||= ""
self.time_user_amount ||= 1
self.clicked_points ||= 0
self.curr_points = self.total_score - self.clicked_points
self.description ||= "我是广告的 description"
self.pimg ||= "/cache/upfile/20100630/1277877355_5200.jpg"
self.return_points ||= 0
self.position ||= 0
self.limit_traffic ||= 0
self.area ||= ""
if one_click.blank? || one_click == 0
self.surplus_hits = 0
self.limit_traffic = 0
else
self.surplus_hits = self.curr_points/self.one_click #剩余点击量
self.limit_traffic = self.total_score/self.one_click #上限点击量
end
# 更新全文搜索对象
self.full_text ||= self.create_full_text
subject = self.billid
text = self.attributes.collect { |k, v| v.to_s}.join(' ')
text << " " << bill_brand.attributes.collect { |k, v| v.to_s}.join(' ') if bill_brand
self.full_text.update_attributes(:subject => subject, :full_text => text)
end
def old_after_save
bill_areas.destroy_all
areas = area.sub(/,$/, '').split(',')
if areas.blank?
bill_areas.create(:area => "")
else
areas.each do |a|
bill_areas.create(:area => a)
end
end
end
def picture_options
attachments.collect { |a| [a.filename, "/attachments/#{a.id}"]}
end
def self.next_bill_id
max_bill_id = Bill.maximum('billid')
date_str =Time.now.strftime("%Y%m%d")
if !max_bill_id.blank? && (max_bill_id[2, 8] == date_str)
seq = max_bill_id[11, 3].to_i + 1
else
seq = 1
end
"AD#{date_str}#{'%03d'% seq}"
end
def self.bill_brands
BillBrand.all.collect { |b| [b.name, b.id]}
end
def self.choose_type
BillType.all.collect{ |t| [t.tname, t.id] }
end
def update_total_score(new_score)
old_score = self.total_score
#curr_points = self.curr_points + new_score - old_score
curr_points = new_score - self.sum_of_clicked_integral
self.update_attributes(:total_score => new_score,
:curr_points => curr_points)
end
def surplus_hits_less_than_ten_days_max_hits?
surplus_hits < self.day_limit_traffic * 10
end
def has_margin_between_last_display_date_and_contract_end_date?
last_display_date = bill_display_dates.maximum(:edates)
return true if last_display_date.blank?
self.e_date > last_display_date.to_time.to_i
end
def abnormal?
surplus_hits_less_than_ten_days_max_hits? || has_margin_between_last_display_date_and_contract_end_date?
end
=begin
def self.abnormal_bills(position, billid)
Bill.find_by_sql("select b.*
from ads as b
left join (select id,max(edates) as me,bill_id
from ad_display_dates group by bill_id) as bldd
on b.id = bldd.bill_id
where (b.surplus_hits <= b.day_limit_traffic * 10
and unix_timestamp(bldd.me) <= b.e_date and b.billid like '%#{billid}%')
or bldd.me IS NULL order by #{position} desc")
end
=end
def is_play_time_effective
end
def is_integral_left
end
# 今日点击量
def click_of_today
self.mem_integrals.from_click.today.count
end
# 编辑广告页面点击修改对单项进行修改
def update_attribute_and_add_edit_history(field, old_value, new_value, author_id)
add_bill_edit_history("ads", field, old_value, new_value.to_i, author_id, "修改")
update_attribute(field, new_value)
end
# 编辑广告页面点击保存进行更新
def add_basic_bill_edit_histories(bill_hash, author_id, type)
if type == "add"
bill_hash.each do |field_name, new_value|
add_bill_edit_history("ads", field_name, "", new_value, author_id, "新增")
end
elsif type == "update"
bill_hash.each do |field_name, new_value|
add_bill_edit_history("ads", field_name, self[field_name], new_value, author_id, "更新")
end
elsif type == "delete"
Bill.column_names.each do |field_name|
add_bill_edit_history("ads", field_name, self[field_name], "", author_id, "删除")
end
# 记录播放日期的删除
bill_display_dates.each do |date|
date.add_display_date_edit_histories(nil, author_id, "delete")
end
# 记录播放时间段的删除
bill_display_times.each do |time|
time.add_display_time_edit_histories(nil, author_id, "delete")
end
# 记录图片附件的删除
#attachments.each do |a|
# time.add_display_time_edit_histories(nil, author_id, "delete")
#end
end
end
# 增加一条编辑记录
def add_bill_edit_history(table_name, field_name, old_value, new_value, author_id, type)
unless old_value == new_value || old_value.to_s == new_value
bill_edit_histories.create(:table_name => table_name,
:field_name => field_name,
:old_value => old_value.to_s,
:new_value => new_value.to_s,
:pdate => Time.now.to_i,
:author => author_id,
:operation_type => type)
end
end
def self.translate_field_name(field_name)
h = { "total_score" => "总积分",
"one_click" => "单次点击积分",
"day_limit_traffic" => "单日上限点击量",
"one_user_traffic" => "单用户单日点击上限",
"one_user_total_click_traffic" => "单用户总点击上限",
"bill_type_id" => "广告类型ID",
"bill_brand_id" => "广告品牌ID",
"billid" => "广告编号",
"url" => "官网url",
"pimg" => "图片地址",
"body" => "详细描述",
"p_date" => "录入时间",
"b_date" => "签约开始时间",
"e_date" => "签约结束时间",
"playtimes" => "播放时间",
"curr_points" => "剩余积分",
"limit_traffic" => "上限点击量",
"surplus_hits" => "剩余点击量",
"time_user_amount" => "时间段使用个数",
"area" => "受众区域",
"isplaceholder" => "是否占位",
"sex" => "受众性别",
"return_points" => "返还积分",
"description" => "广告描述",
"position" => "排序积分",
"use_default_display_layout" => "是否使用默认页面格式",
"target_begin_year" => "受众年龄起始值",
"target_end_year" => "受众年龄结束值",
"px" => "排序位置", # 弃用
"big_img" => "大幅广告图片",
"huge_img" => "超大幅广告图片",
"bdates" => "开始播放日期",
"edates" => "结束播放日期",
"btimes" => "开始播放时间",
"etimes" => "结束播放时间" }
h[field_name]
end
def self.industry_options
options = WebConfig.get_value("bill_target_industries").gsub(/:/, ":")
options.split("\r\n").map { |o| o.split(":") }.group_by{ |e| e[0] }
end
def self.position_options
options = WebConfig.get_value("bill_target_positions").gsub(/:/, ":")
options.split("\r\n").map { |o| o.split(":") }.group_by{ |e| e[0] }
end
def member_today_click_times(member)
mem_integrals.of_member(member).today.count
end
def member_click_times(member)
mem_integrals.of_member(member).count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment