pricing_plans 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 99983bea54e570eebe0d01fecb11245816a95ed60eb7cc87a61756009764817f
4
- data.tar.gz: 388d3c8b0791cf5388dda9d670a21fd53613105cefcf861c2769667f9f15fab1
3
+ metadata.gz: 5d4d6193dae586244d9a5eb2780ca9f1b2447636fac1b832cca17832adb19280
4
+ data.tar.gz: aacfdf85b8f20fca5d2c81d4118a053e47f2636304330c399804d978035b2275
5
5
  SHA512:
6
- metadata.gz: f99451ddc7aaba6ea9cf5bebf81395ee88383cb5a27cd2efb491ae78a711d99115f4cb5c1fade02aaa9d8cc6b09afcefe96abc8e3f00cf772d4e797b66a13424
7
- data.tar.gz: bd14a7080334f2e6aeb215739d33ac3d91f97803a706dfcd83c8053b185ba36fd7797804e4a41a10500946acb00667dfabb6536fa3e184bbac41923e3adef375
6
+ metadata.gz: b245d32bc4c997d3422aae208fbdd345d06cc6b4473fc2c1712cbabf5be48eb0962879de5dd3410e07191a629f6ea5df296f09525841d60aaa519f978619128a
7
+ data.tar.gz: 65ac67157b979b0d84590463082d71101cd5ff0d73afc528e54357eecb0e4db365f03a50e57ef5949db699f50d1a010ec72f3e211312dbeeae030bbc9c119e96
data/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## [0.3.2] - 2026-02-25
2
+
3
+ - **Fix stale grace warnings after plan upgrades**: Grace/blocked flags now auto-clear when usage drops below limit (self-healing state)
4
+ - **Fix grace triggering at exact limit**: `grace_then_block` now uses `>` (over limit) not `>=` (at limit)
5
+ - **Add lazy grace creation**: Grace starts on-demand when checking status, even if callbacks were bypassed
6
+ - **Add `ExceededStateUtils` module**: DRY extraction for shared exceeded/blocked logic
7
+
1
8
  ## [0.3.1] - 2026-02-16
2
9
 
3
10
  - **Add `has_plan_assignment?` helper**: Check if a plan owner has a manual assignment without full plan resolution
data/README.md CHANGED
@@ -180,10 +180,14 @@ Enforcing pricing plans is one of those boring plumbing problems that look easy
180
180
 
181
181
  - Safe under load: we use row locks and retries when setting grace/blocked/warning state, and we avoid firing the same event twice. See [grace_manager.rb](lib/pricing_plans/grace_manager.rb).
182
182
 
183
+ - Self-healing state: when usage drops below the limit (e.g., user deletes resources, upgrades plan, or reduces usage), stale exceeded/blocked flags are automatically cleared. Methods like `grace_active?` and `should_block?` will clear outdated enforcement state as a side effect. This prevents users from remaining incorrectly flagged after remediation.
184
+
183
185
  - Accurate counting: persistent limits count live current rows (using `COUNT(*)`, make sure to index your foreign keys to make it fast at scale); per‑period limits record usage for the current window only. You can filter what counts with `count_scope` (Symbol/Hash/Proc/Array), and plan settings override model defaults. See [limitable.rb](lib/pricing_plans/limitable.rb) and [limit_checker.rb](lib/pricing_plans/limit_checker.rb).
184
186
 
185
187
  - Clear rules: default is to block when you hit the cap; grace periods are opt‑in. In status/UI, 0 of 0 isn’t shown as blocked. See [plan.rb](lib/pricing_plans/plan.rb), [grace_manager.rb](lib/pricing_plans/grace_manager.rb), and [view_helpers.rb](lib/pricing_plans/view_helpers.rb).
186
188
 
189
+ - Semantic enforcement: for `grace_then_block`, grace periods start when usage goes *over* the limit (e.g., 6/5), not when it *reaches* the limit (5/5). This allows users to use their full allocation before grace begins. For `block_usage`, blocking occurs at or over the limit (e.g., at 5/5, the next creation is blocked).
190
+
187
191
  - Simple controllers: one‑liners to guard actions, predictable redirect order (per‑call → per‑controller → global → pricing_path), and an optional central handler. See [controller_guards.rb](lib/pricing_plans/controller_guards.rb).
188
192
 
189
193
  - Billing‑aware periods: supports billing cycle (when Pay is present), calendar month/week/day, custom time windows, and durations. See [period_calculator.rb](lib/pricing_plans/period_calculator.rb).
@@ -106,17 +106,24 @@ module PricingPlans
106
106
  return if limit_config[:to] == :unlimited
107
107
 
108
108
  limit_amount = limit_config[:to].to_i
109
- return unless current_usage >= limit_amount
109
+ after_limit = limit_config[:after_limit]
110
110
 
111
- case limit_config[:after_limit]
111
+ case after_limit
112
112
  when :just_warn
113
+ return unless current_usage >= limit_amount
114
+
113
115
  # Just emit warning, don't track grace/block
114
116
  check_and_emit_warnings!(plan_owner, limit_key, current_usage, limit_amount)
115
117
  when :block_usage
118
+ return unless current_usage >= limit_amount
119
+
116
120
  # Do NOT mark as blocked here - this callback runs after SUCCESSFUL creation.
117
121
  # Block events are emitted from validation when creation is actually blocked.
118
122
  nil
119
123
  when :grace_then_block
124
+ # Grace semantics are for over-limit usage, not exact-at-limit.
125
+ return unless current_usage > limit_amount
126
+
120
127
  # Start grace period if not already in grace/blocked
121
128
  unless GraceManager.grace_active?(plan_owner, limit_key) || GraceManager.should_block?(plan_owner, limit_key)
122
129
  GraceManager.mark_exceeded!(plan_owner, limit_key, grace_period: limit_config[:grace])
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PricingPlans
4
+ # Shared utilities for checking and managing exceeded state.
5
+ #
6
+ # This module provides common logic for determining whether usage has exceeded
7
+ # limits and for clearing stale exceeded flags. It is included by both
8
+ # GraceManager (class methods) and StatusContext (instance methods) to ensure
9
+ # consistent behavior.
10
+ #
11
+ # NOTE: Methods that modify state (`clear_exceeded_flags!`) are intentionally
12
+ # included here. The design decision is that grace/block checks should be
13
+ # "self-healing" - if usage drops below the limit, stale exceeded flags are
14
+ # automatically cleared. This prevents situations where users remain incorrectly
15
+ # flagged as exceeded after deleting resources or after plan upgrades.
16
+ module ExceededStateUtils
17
+ # Determine if usage has exceeded the limit based on the after_limit policy.
18
+ #
19
+ # For :grace_then_block, exceeded means strictly OVER the limit (>).
20
+ # For :block_usage and :just_warn, exceeded means AT or over the limit (>=).
21
+ #
22
+ # This distinction exists because:
23
+ # - :block_usage blocks creation of the Nth item (at limit = blocked)
24
+ # - :grace_then_block allows the Nth item, only starting grace when OVER
25
+ #
26
+ # @param current_usage [Integer] Current usage count
27
+ # @param limit_amount [Integer, Symbol] The configured limit (may be :unlimited)
28
+ # @param after_limit [Symbol] The enforcement policy (:block_usage, :grace_then_block, :just_warn)
29
+ # @return [Boolean] true if usage is considered exceeded for this policy
30
+ def exceeded_now?(current_usage, limit_amount, after_limit:)
31
+ # 0-of-0 is a special case: not considered exceeded for UX purposes
32
+ return false if limit_amount.to_i.zero? && current_usage.to_i.zero?
33
+
34
+ if after_limit == :grace_then_block
35
+ current_usage > limit_amount.to_i
36
+ else
37
+ current_usage >= limit_amount.to_i
38
+ end
39
+ end
40
+
41
+ # Clear exceeded and blocked flags from an enforcement state record.
42
+ #
43
+ # This is called when usage drops below the limit to "heal" stale state.
44
+ # Uses update_columns for efficiency (skips validations/callbacks).
45
+ #
46
+ # @param state [EnforcementState] The state record to clear
47
+ # @return [EnforcementState, nil] The updated state, or nil if no updates needed
48
+ def clear_exceeded_flags!(state)
49
+ return unless state
50
+
51
+ updates = {}
52
+ updates[:exceeded_at] = nil if state.exceeded_at.present?
53
+ updates[:blocked_at] = nil if state.blocked_at.present?
54
+ return state if updates.empty?
55
+
56
+ updates[:updated_at] = Time.current
57
+ state.update_columns(updates)
58
+ state
59
+ end
60
+ end
61
+ end
@@ -3,6 +3,7 @@
3
3
  module PricingPlans
4
4
  class GraceManager
5
5
  class << self
6
+ include ExceededStateUtils
6
7
  def mark_exceeded!(plan_owner, limit_key, grace_period: nil)
7
8
  with_lock(plan_owner, limit_key) do |state|
8
9
  # Ensure state is for the current window for per-period limits
@@ -36,6 +37,14 @@ module PricingPlans
36
37
  def grace_active?(plan_owner, limit_key)
37
38
  state = fresh_state_or_nil(plan_owner, limit_key)
38
39
  return false unless state&.exceeded?
40
+
41
+ plan = PlanResolver.effective_plan_for(plan_owner)
42
+ limit_config = plan&.limit_for(limit_key)
43
+ unless currently_exceeded?(plan_owner, limit_key, limit_config)
44
+ clear_exceeded_flags!(state)
45
+ return false
46
+ end
47
+
39
48
  !state.grace_expired?
40
49
  end
41
50
 
@@ -51,11 +60,16 @@ module PricingPlans
51
60
  limit_amount = limit_config[:to]
52
61
  return false if limit_amount == :unlimited
53
62
  current_usage = LimitChecker.current_usage_for(plan_owner, limit_key, limit_config)
54
- exceeded = current_usage >= limit_amount.to_i
55
- # Treat 0-of-0 as not blocked for UX/severity/status purposes
56
- exceeded = false if limit_amount.to_i.zero? && current_usage.to_i.zero?
63
+ exceeded = exceeded_now?(current_usage, limit_amount, after_limit: after_limit)
57
64
 
58
- return exceeded if after_limit == :block_usage
65
+ unless exceeded
66
+ if (state = fresh_state_or_nil(plan_owner, limit_key))
67
+ clear_exceeded_flags!(state)
68
+ end
69
+ return false
70
+ end
71
+
72
+ return true if after_limit == :block_usage
59
73
 
60
74
  # For :grace_then_block, check if grace period expired
61
75
  state = fresh_state_or_nil(plan_owner, limit_key)
@@ -119,7 +133,7 @@ module PricingPlans
119
133
  end
120
134
 
121
135
  def grace_ends_at(plan_owner, limit_key)
122
- state = find_state(plan_owner, limit_key)
136
+ state = fresh_state_or_nil(plan_owner, limit_key)
123
137
  state&.grace_ends_at
124
138
  end
125
139
 
@@ -158,6 +172,17 @@ module PricingPlans
158
172
  EnforcementState.find_by(plan_owner: plan_owner, limit_key: limit_key.to_s)
159
173
  end
160
174
 
175
+ def currently_exceeded?(plan_owner, limit_key, limit_config = nil)
176
+ limit_config ||= PlanResolver.effective_plan_for(plan_owner)&.limit_for(limit_key)
177
+ return false unless limit_config
178
+
179
+ limit_amount = limit_config[:to]
180
+ return false if limit_amount == :unlimited
181
+
182
+ current_usage = LimitChecker.current_usage_for(plan_owner, limit_key, limit_config)
183
+ exceeded_now?(current_usage, limit_amount, after_limit: limit_config[:after_limit])
184
+ end
185
+
161
186
  # Returns nil if state is stale for the current period window for per-period limits
162
187
  def fresh_state_or_nil(plan_owner, limit_key)
163
188
  state = find_state(plan_owner, limit_key)
@@ -7,6 +7,8 @@ module PricingPlans
7
7
  #
8
8
  # Thread-safe by design: each call to status() gets its own context instance.
9
9
  class StatusContext
10
+ include ExceededStateUtils
11
+
10
12
  attr_reader :plan_owner
11
13
 
12
14
  def initialize(plan_owner)
@@ -67,7 +69,26 @@ module PricingPlans
67
69
  return @grace_active_cache[key] if @grace_active_cache.key?(key)
68
70
 
69
71
  state = fresh_enforcement_state(limit_key)
70
- return @grace_active_cache[key] = false unless state&.exceeded?
72
+
73
+ # If no state exists but we're over limit for grace_then_block, lazily create grace
74
+ unless state&.exceeded?
75
+ if should_lazily_start_grace?(limit_key)
76
+ limit_config = limit_config_for(limit_key)
77
+ GraceManager.mark_exceeded!(@plan_owner, limit_key, grace_period: limit_config[:grace])
78
+ # Clear caches to get fresh state
79
+ @fresh_enforcement_state_cache&.delete(key)
80
+ @enforcement_state_cache&.delete(key)
81
+ state = fresh_enforcement_state(limit_key)
82
+ else
83
+ return @grace_active_cache[key] = false
84
+ end
85
+ end
86
+
87
+ unless currently_exceeded?(limit_key)
88
+ clear_exceeded_flags!(state)
89
+ return @grace_active_cache[key] = false
90
+ end
91
+
71
92
  @grace_active_cache[key] = !state.grace_expired?
72
93
  end
73
94
 
@@ -77,7 +98,10 @@ module PricingPlans
77
98
  return @grace_ends_at_cache[key] if @grace_ends_at_cache.key?(key)
78
99
 
79
100
  state = fresh_enforcement_state(limit_key)
80
- @grace_ends_at_cache[key] = state&.grace_ends_at
101
+ return @grace_ends_at_cache[key] = nil unless state&.exceeded?
102
+ return @grace_ends_at_cache[key] = nil unless grace_active?(limit_key)
103
+
104
+ @grace_ends_at_cache[key] = state.grace_ends_at
81
105
  end
82
106
 
83
107
  # Cached should block check - implemented directly to avoid GraceManager's plan resolution
@@ -95,13 +119,16 @@ module PricingPlans
95
119
  return @should_block_cache[key] = false if limit_amount == :unlimited
96
120
 
97
121
  current_usage = current_usage_for(limit_key)
98
- exceeded = current_usage >= limit_amount.to_i
99
- exceeded = false if limit_amount.to_i.zero? && current_usage.to_i.zero?
122
+ exceeded = exceeded_now?(current_usage, limit_amount, after_limit: after_limit)
100
123
 
101
124
  return @should_block_cache[key] = exceeded if after_limit == :block_usage
102
125
 
103
126
  # For :grace_then_block, check if grace period expired
104
- return @should_block_cache[key] = false unless exceeded
127
+ unless exceeded
128
+ state = fresh_enforcement_state(limit_key)
129
+ clear_exceeded_flags!(state) if state
130
+ return @should_block_cache[key] = false
131
+ end
105
132
 
106
133
  state = fresh_enforcement_state(limit_key)
107
134
  return @should_block_cache[key] = false unless state&.exceeded?
@@ -339,5 +366,32 @@ module PricingPlans
339
366
  highest_warn = warn_thresholds.max.to_f * 100.0
340
367
  (percent >= highest_warn && highest_warn.positive?) ? :warning : :ok
341
368
  end
369
+
370
+ def currently_exceeded?(limit_key)
371
+ limit_config = limit_config_for(limit_key)
372
+ return false unless limit_config
373
+
374
+ limit_amount = limit_config[:to]
375
+ return false if limit_amount == :unlimited
376
+
377
+ current_usage = current_usage_for(limit_key)
378
+ exceeded_now?(current_usage, limit_amount, after_limit: limit_config[:after_limit])
379
+ end
380
+
381
+ # Check if we should lazily start grace for this limit.
382
+ # This handles edge cases where usage increased without triggering callbacks
383
+ # (e.g., status changes, bulk imports, manual DB updates).
384
+ def should_lazily_start_grace?(limit_key)
385
+ limit_config = limit_config_for(limit_key)
386
+ return false unless limit_config
387
+ return false unless limit_config[:after_limit] == :grace_then_block
388
+
389
+ limit_amount = limit_config[:to]
390
+ return false if limit_amount == :unlimited
391
+
392
+ current_usage = current_usage_for(limit_key)
393
+ current_usage > limit_amount.to_i
394
+ end
395
+
342
396
  end
343
397
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PricingPlans
4
- VERSION = "0.3.1"
4
+ VERSION = "0.3.2"
5
5
  end
data/lib/pricing_plans.rb CHANGED
@@ -27,6 +27,7 @@ module PricingPlans
27
27
  autoload :PaySupport, "pricing_plans/pay_support"
28
28
  autoload :LimitChecker, "pricing_plans/limit_checker"
29
29
  autoload :LimitableRegistry, "pricing_plans/limit_checker"
30
+ autoload :ExceededStateUtils, "pricing_plans/exceeded_state_utils"
30
31
  autoload :GraceManager, "pricing_plans/grace_manager"
31
32
  autoload :Callbacks, "pricing_plans/callbacks"
32
33
  autoload :PeriodCalculator, "pricing_plans/period_calculator"
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pricing_plans
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.1
4
+ version: 0.3.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - rameerez
8
8
  bindir: exe
9
9
  cert_chain: []
10
- date: 2026-02-16 00:00:00.000000000 Z
10
+ date: 2026-02-25 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: activerecord
@@ -93,6 +93,7 @@ files:
93
93
  - lib/pricing_plans/controller_rescues.rb
94
94
  - lib/pricing_plans/dsl.rb
95
95
  - lib/pricing_plans/engine.rb
96
+ - lib/pricing_plans/exceeded_state_utils.rb
96
97
  - lib/pricing_plans/grace_manager.rb
97
98
  - lib/pricing_plans/integer_refinements.rb
98
99
  - lib/pricing_plans/job_guards.rb