Class: PgLedger::Account
- Defined in:
- lib/pg_ledger/models.rb
Constant Summary collapse
- INTERVALS =
%w[hour day week month].freeze
- FIXED_STEP =
Fixed-step buckets ("30 minutes", "6 hours") chart via date_bin; calendar units above stay on date_trunc (a month has no fixed step).
/\A\d+\s+(minute|minutes|hour|hours)\z/
Class Method Summary collapse
Instance Method Summary collapse
- #balance(at: nil) ⇒ Object
-
#balance_series(from:, to: Time.current, interval: "day") ⇒ Object
Balance at the end of each bucket in [from, to] — chart-ready [[Time, Integer]].
-
#rollup_next_day ⇒ Object
First un-rolled day, as a bare Date — bound into SQL and interpreted in Postgres' timezone, matching how rollup! truncates days.
-
#turnover(from:, to: Time.current, interval: nil) ⇒ Object
Debit/credit volume, total or per bucket.
Class Method Details
.resolve!(ref, currency: nil, ledger_id: Ledger::DEFAULT_ID) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/pg_ledger/models.rb', line 21 def self.resolve!(ref, currency: nil, ledger_id: Ledger::DEFAULT_ID) case ref when Account then ref when String scope = where(code: ref, ledger_id: ledger_id) scope = scope.where(currency: currency.to_s.upcase) if currency found = scope.limit(2).to_a raise UnknownAccount, "no account with code #{ref.inspect}#{" (#{currency})" if currency} in ledger #{ledger_id}" if found.empty? raise Error, "code #{ref.inspect} is ambiguous, pass the record or a currency:" if found.size > 1 found.first else raise ArgumentError, "account must be a PgLedger::Account or code String, got #{ref.class}" end end |
Instance Method Details
#balance(at: nil) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/pg_ledger/models.rb', line 69 def balance(at: nil) return balances.sum(:amount) unless at # Watermark resolved separately and bound as a literal — a subquery here # blinds the planner and turns the tail read into a seq scan. All day # boundaries are computed by Postgres in its own timezone (rollup! cuts # days the same way); Ruby's zone never enters the comparison. sql = <<~SQL SELECT COALESCE((SELECT SUM(debits - credits) FROM pg_ledger_account_days WHERE account_id = :id AND day < LEAST(:wm_next::date, :at::timestamptz::date)), 0) + COALESCE((SELECT SUM(amount) FROM pg_ledger_lines WHERE debit_account_id = :id AND posted_at >= LEAST(:wm_next::date, :at::timestamptz::date)::timestamptz AND posted_at <= :at), 0) - COALESCE((SELECT SUM(amount) FROM pg_ledger_lines WHERE credit_account_id = :id AND posted_at >= LEAST(:wm_next::date, :at::timestamptz::date)::timestamptz AND posted_at <= :at), 0) SQL row = self.class.connection.select_rows( self.class.sanitize_sql_array([sql, { id: id, at: at, wm_next: rollup_next_day }]) ).first signed = Integer(row.first) normal_balance == "debit" ? signed : -signed end |
#balance_series(from:, to: Time.current, interval: "day") ⇒ Object
Balance at the end of each bucket in [from, to] — chart-ready [[Time, Integer]]. day/week/month read the daily rollups plus an un-rolled tail from lines; hour reads lines directly (rollups are daily). Exact for sharded accounts.
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/pg_ledger/models.rb', line 109 def balance_series(from:, to: Time.current, interval: "day") interval = interval.to_s fixed = interval.match?(FIXED_STEP) unless fixed || INTERVALS.include?(interval) raise ArgumentError, "interval must be one of #{INTERVALS.join(", ")} or a fixed step like \"30 minutes\", got #{interval.inspect}" end # Bucket function: date_bin for fixed steps, date_trunc for calendar # units. Both strings are chosen here, never from user input. bucket = fixed ? "date_bin(:unit::interval, %s, 'epoch'::timestamptz)" : "date_trunc(:unit, %s)" step = fixed ? ":unit::interval" : "('1 ' || :unit)::interval" sign = normal_balance == "debit" ? "1" : "-1" source = if fixed || interval == "hour" <<~SQL day_rows AS ( SELECT l.posted_at AS ts, #{sign} * l.amount AS delta FROM pg_ledger_lines l WHERE l.debit_account_id = :id UNION ALL SELECT l.posted_at, #{sign} * -l.amount FROM pg_ledger_lines l WHERE l.credit_account_id = :id ) SQL else <<~SQL day_rows AS ( SELECT day::timestamptz AS ts, #{sign} * (debits - credits) AS delta FROM pg_ledger_account_days WHERE account_id = :id UNION ALL SELECT date_trunc('day', l.posted_at), SUM(#{sign} * l.amount) FROM pg_ledger_lines l WHERE l.debit_account_id = :id AND l.posted_at >= :wm_next::date GROUP BY 1 UNION ALL SELECT date_trunc('day', l.posted_at), SUM(#{sign} * -l.amount) FROM pg_ledger_lines l WHERE l.credit_account_id = :id AND l.posted_at >= :wm_next::date GROUP BY 1 ) SQL end sql = <<~SQL WITH #{source}, buckets AS ( SELECT generate_series( #{format(bucket, ":from::timestamptz")}, #{format(bucket, ":to::timestamptz")}, #{step} ) AS bucket ), opening AS ( SELECT COALESCE(SUM(delta), 0) AS amount FROM day_rows WHERE ts < #{format(bucket, ":from::timestamptz")} ), deltas AS ( SELECT #{format(bucket, "ts")} AS bucket, SUM(delta) AS delta FROM day_rows WHERE ts >= #{format(bucket, ":from::timestamptz")} AND ts <= :to GROUP BY 1 ) SELECT b.bucket, (SELECT amount FROM opening) + COALESCE(SUM(d.delta) OVER (ORDER BY b.bucket ROWS UNBOUNDED PRECEDING), 0) FROM buckets b LEFT JOIN deltas d USING (bucket) ORDER BY b.bucket SQL rows = self.class.connection.select_rows(self.class.sanitize_sql_array( [sql, { unit: interval, from: from, to: to, id: id, wm_next: rollup_next_day }] )) rows.map { |bucket, amount| [bucket.to_time, Integer(amount)] } end |
#rollup_next_day ⇒ Object
First un-rolled day, as a bare Date — bound into SQL and interpreted in Postgres' timezone, matching how rollup! truncates days.
101 102 103 104 |
# File 'lib/pg_ledger/models.rb', line 101 def rollup_next_day day = AccountDay.where(account_id: id).maximum(:day) day ? day + 1 : Date.new(1970, 1, 1) end |
#turnover(from:, to: Time.current, interval: nil) ⇒ Object
Debit/credit volume, total or per bucket. day/week/month buckets read the daily rollups + un-rolled tail; hour and totals read lines directly.
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
# File 'lib/pg_ledger/models.rb', line 187 def turnover(from:, to: Time.current, interval: nil) if interval.nil? return { debits: debit_lines.where(posted_at: from..to).sum(:amount), credits: credit_lines.where(posted_at: from..to).sum(:amount) } end if interval.to_s == "hour" sql = <<~SQL SELECT bucket, SUM(d), SUM(c) FROM ( SELECT date_trunc('hour', posted_at) AS bucket, SUM(amount) AS d, 0 AS c FROM pg_ledger_lines WHERE debit_account_id = :id AND posted_at BETWEEN :from AND :to GROUP BY 1 UNION ALL SELECT date_trunc('hour', posted_at), 0, SUM(amount) FROM pg_ledger_lines WHERE credit_account_id = :id AND posted_at BETWEEN :from AND :to GROUP BY 1 ) t GROUP BY 1 ORDER BY 1 SQL return self.class.connection.select_rows(self.class.sanitize_sql_array( [sql, { id: id, from: from, to: to }] )).map { |b, d, c| { period: b.to_time, debits: d.to_i, credits: c.to_i } } end interval = interval.to_s unless INTERVALS.include?(interval) raise ArgumentError, "interval must be one of #{INTERVALS.join(", ")}, got #{interval.inspect}" end sql = <<~SQL WITH day_rows AS ( SELECT day::timestamptz AS ts, debits, credits FROM pg_ledger_account_days WHERE account_id = :id UNION ALL SELECT date_trunc('day', l.posted_at), SUM(l.amount), 0 FROM pg_ledger_lines l WHERE l.debit_account_id = :id AND l.posted_at >= :wm_next::date GROUP BY 1 UNION ALL SELECT date_trunc('day', l.posted_at), 0, SUM(l.amount) FROM pg_ledger_lines l WHERE l.credit_account_id = :id AND l.posted_at >= :wm_next::date GROUP BY 1 ) SELECT date_trunc(:unit, ts) AS bucket, SUM(debits), SUM(credits) FROM day_rows WHERE ts >= date_trunc(:unit, :from::timestamptz) AND ts <= :to GROUP BY 1 ORDER BY 1 SQL rows = self.class.connection.select_rows(self.class.sanitize_sql_array( [sql, { unit: interval, from: from, to: to, id: id, wm_next: rollup_next_day }] )) rows.map { |b, d, c| { period: b.to_time, debits: Integer(d), credits: Integer(c) } } end |