76 lines
1.8 KiB
Ruby
76 lines
1.8 KiB
Ruby
class LifePex::Pex < Sequel::Model(LifePex::DB[:pexs].order(:category, :name))
|
|
one_to_many :user_pexs
|
|
many_to_one :user
|
|
one_to_many :recalls
|
|
|
|
# note: wont work on #update
|
|
def before_validation
|
|
self.category = self.category.to_s.downcase
|
|
self.hidden = false if self.hidden.nil?
|
|
end
|
|
|
|
# common interface for setup_user_pexs_*
|
|
def self.setup_user_pexs(user_id: nil, user_pexs: nil)
|
|
raise RuntimeError.new "user_id is required" if user_id.nil?
|
|
user_pexs = LifePex::UserPex.where(user_id: user_id) if user_pexs.nil?
|
|
pexs = LifePex::Pex
|
|
.where(user_id: user_id)
|
|
.order(:name).all()
|
|
.group_by { |pex| pex[:id] }
|
|
.map { |id, pex_group| [id, pex_group[0]] }
|
|
.to_h
|
|
pexs.each do |id, pex|
|
|
pex[:count_by_date] = {}
|
|
end
|
|
|
|
user_pexs.each do |user_pex|
|
|
pex_id = user_pex[:pex_id]
|
|
pex = pexs[pex_id]
|
|
pex[:count_by_date][user_pex[:created_at]] ||= 0
|
|
pex[:count_by_date][user_pex[:created_at]] += 1
|
|
end
|
|
|
|
pexs.each do |id, pex|
|
|
pex[:total_by_date] = pex[:count_by_date].map { |date, count| [date, count * pex[:amount]] }.to_h
|
|
end
|
|
|
|
pexs
|
|
end
|
|
|
|
PUBLIC_FIELDS = %w(id name category amount)
|
|
|
|
def to_s
|
|
fields = PUBLIC_FIELDS.map { |f| "#{f} #{self.send(f)}" }.join(' ')
|
|
"Pex(#{fields})"
|
|
end
|
|
|
|
# TODO what the hell is params, is it an io or someting ?
|
|
def to_json(*params)
|
|
(
|
|
PUBLIC_FIELDS.map { |f| [f, self.send(f)] }.to_h
|
|
.merge(pex_meta)
|
|
).to_json
|
|
end
|
|
|
|
include LifePex::Utils::Url
|
|
|
|
def pex_url(id, *more_path, **options)
|
|
base_url("/api/pex/v2/pexs", id, *more_path, **options)
|
|
end
|
|
|
|
def pex_meta
|
|
{
|
|
base: {
|
|
url: pex_url(id),
|
|
},
|
|
more: {
|
|
url: pex_url(id, "more"),
|
|
},
|
|
}
|
|
end
|
|
|
|
def bookmarked?
|
|
self.flag == "bookmarked"
|
|
end
|
|
end
|