Skip to content

Commit 27b7899

Browse files
committed
Merge PR #216: fix/issue-150
2 parents 90bc26e + 7e4b2d2 commit 27b7899

4 files changed

Lines changed: 497 additions & 1 deletion

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
-- Create subscription_price_history table
2+
CREATE TABLE IF NOT EXISTS subscription_price_history (
3+
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
4+
subscription_id UUID NOT NULL REFERENCES subscriptions(id) ON DELETE CASCADE,
5+
old_price DECIMAL(10, 2) NOT NULL,
6+
new_price DECIMAL(10, 2) NOT NULL,
7+
changed_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL,
8+
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE
9+
);
10+
11+
-- Enable RLS
12+
ALTER TABLE subscription_price_history ENABLE ROW LEVEL SECURITY;
13+
14+
-- RLS Policies
15+
CREATE POLICY "Users can view their own price history"
16+
ON subscription_price_history FOR SELECT
17+
USING (auth.uid() = user_id);
18+
19+
-- Function to handle price changes
20+
CREATE OR REPLACE FUNCTION handle_subscription_price_change()
21+
RETURNS TRIGGER AS $$
22+
BEGIN
23+
IF (OLD.price IS DISTINCT FROM NEW.price) THEN
24+
INSERT INTO subscription_price_history (subscription_id, old_price, new_price, user_id)
25+
VALUES (NEW.id, OLD.price, NEW.price, NEW.user_id);
26+
END IF;
27+
RETURN NEW;
28+
END;
29+
$$ LANGUAGE plpgsql SECURITY DEFINER;
30+
31+
-- Trigger for price changes
32+
DROP TRIGGER IF EXISTS on_subscription_price_change ON subscriptions;
33+
CREATE TRIGGER on_subscription_price_change
34+
AFTER UPDATE ON subscriptions
35+
FOR EACH ROW
36+
EXECUTE FUNCTION handle_subscription_price_change();

0 commit comments

Comments
 (0)