discourse/plugins/discourse-ai/app/models/llm_credit_daily_usage.rb
Keegan George 150c51aedc
DEV: Move AI credits daily usage to it's own table (#36369)
## 🔍 Overview
This update moves the AI credit daily usage data from being a `jsonb`
value in the `LlmCreditAllocation` table to it's own dedicated table
with each day as it's own record. There is still some of the old code
for now as we migrate existing sites over, which we will eventually
follow-up and remove the deprecated code.
2025-12-02 11:54:58 -08:00

46 lines
1.3 KiB
Ruby
Vendored

# frozen_string_literal: true
class LlmCreditDailyUsage < ActiveRecord::Base
self.table_name = "llm_credit_daily_usages"
belongs_to :llm_model
validates :llm_model_id, presence: true
validates :usage_date, presence: true
validates :credits_used,
presence: true,
numericality: {
only_integer: true,
greater_than_or_equal_to: 0,
}
def self.find_or_create_for_today(llm_model)
find_or_create_by!(llm_model: llm_model, usage_date: Date.current)
end
def self.increment_usage!(llm_model, credits)
usage = find_or_create_for_today(llm_model)
usage.with_lock { usage.increment!(:credits_used, credits) }
end
def self.usage_for_date(llm_model, date)
find_by(llm_model: llm_model, usage_date: date)&.credits_used || 0
end
end
# == Schema Information
#
# Table name: llm_credit_daily_usages
#
# id :bigint not null, primary key
# credits_used :bigint default(0), not null
# usage_date :date not null
# created_at :datetime not null
# updated_at :datetime not null
# llm_model_id :bigint not null
#
# Indexes
#
# index_llm_credit_daily_usages_on_llm_model_id (llm_model_id)
# index_llm_credit_daily_usages_on_llm_model_id_and_usage_date (llm_model_id,usage_date) UNIQUE
#