Virtual Currencies Setup Guide
Overview
The Virtual Currencies system includes two automated edge functions that should run on a schedule:
Prerequisites
Your Supabase project needs the following extensions enabled:
pg_cron- For scheduling automated taskspg_net- For making HTTP requests from scheduled tasks
Setting Up Cron Jobs
Step 1: Enable Required Extensions
Run the following SQL in your Supabase SQL Editor:
-- Enable pg_cron extension CREATE EXTENSION IF NOT EXISTS pg_cron; -- Enable pg_net extension CREATE EXTENSION IF NOT EXISTS pg_net;
Step 2: Schedule Expiration Processing
This job runs daily at 2 AM UTC to process expired currencies:
SELECT cron.schedule(
'process-currency-expirations-daily',
'0 2 * * *', -- Daily at 2 AM UTC
$$
SELECT
net.http_post(
url:='https://api.billdog.io/v1/process-currency-expirations',
headers:='{"Content-Type": "application/json", "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhidW14Z2RoamtndW55ZHhmdG9tIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjA1NDQyMDAsImV4cCI6MjA3NjEyMDIwMH0.0NbtTT3B9vWjJPHZal4v46bRG3uXoDewppYL5MUnhjU"}'::jsonb,
body:=concat('{"triggered_at": "', now(), '"}')::jsonb
) as request_id;
$$
);Step 3: Schedule Expiration Notifications
This job runs daily at 10 AM UTC to notify customers about expiring currencies:
SELECT cron.schedule(
'notify-currency-expiration-daily',
'0 10 * * *', -- Daily at 10 AM UTC
$$
SELECT
net.http_post(
url:='https://api.billdog.io/v1/notify-currency-expiration',
headers:='{"Content-Type": "application/json", "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhidW14Z2RoamtndW55ZHhmdG9tIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjA1NDQyMDAsImV4cCI6MjA3NjEyMDIwMH0.0NbtTT3B9vWjJPHZal4v46bRG3uXoDewppYL5MUnhjU"}'::jsonb,
body:=concat('{"triggered_at": "', now(), '"}')::jsonb
) as request_id;
$$
);Managing Cron Jobs
View Scheduled Jobs
SELECT * FROM cron.job ORDER BY jobname;
Delete a Scheduled Job
SELECT cron.unschedule('process-currency-expirations-daily');
SELECT cron.unschedule('notify-currency-expiration-daily');View Job Run History
SELECT * FROM cron.job_run_details WHERE jobid = (SELECT jobid FROM cron.job WHERE jobname = 'process-currency-expirations-daily') ORDER BY start_time DESC LIMIT 10;
Configuring Expiration Settings
When creating or editing a Virtual Currency product, you can configure:
Expiration Days
- Field:
expiration_days - Purpose: Number of days until granted currency expires
- Example: Set to 30 for currency to expire 30 days after grant
- Default: null (no expiration)
Notification Window
- Field:
notify_before_expiration_days - Purpose: How many days before expiration to notify customers
- Example: Set to 7 to notify customers 7 days before expiration
- Default: null (no notification)
Example Configuration
For a premium subscription that grants 100 gems:
- Units on Purchase: 100
- Expiration Days: 30
- Notify Before Expiration: 7
This means: Customer receives 100 gems on purchase, gems expire 30 days after grant, customer is notified 7 days before expiration (on day 23), and on day 30 the system automatically deducts any remaining balance.
How It Works
Expiration Processing Flow
- Daily at 2 AM UTC:
process-currency-expirationsruns - Finds all grants with
expires_at <= now() - For each expired grant:
- Calculates amount to expire (min of grant amount and current balance)
- Deducts from customer's balance
- Creates a deduction transaction record
- Records the expiration in
virtual_currency_expirationstable
Notification Flow
- Daily at 10 AM UTC:
notify-currency-expirationruns - Finds grants expiring within notification window
- For each grant not yet notified:
- Checks if within
notify_before_expiration_dayswindow - Marks grant as notified in metadata
- Logs notification details
- Checks if within
notify-currency-expiration edge function.Monitoring & Debugging
Check Edge Function Logs
- Go to Supabase Dashboard → Functions
- Select the function (
process-currency-expirationsornotify-currency-expiration) - Click "Logs" tab to view execution history
Query Expiration History
-- View recent expirations SELECT e.*, c.email as customer_email, vc.code as currency_code, vc.name as currency_name FROM virtual_currency_expirations e JOIN customers c ON e.customer_id = c.id JOIN virtual_currencies vc ON e.virtual_currency_id = vc.id ORDER BY e.expired_at DESC LIMIT 20;
Check Upcoming Expirations
-- View grants expiring in next 7 days SELECT vct.id, vct.customer_id, vct.amount, vct.expires_at, vc.code, vc.name, EXTRACT(DAY FROM (vct.expires_at - now())) as days_until_expiration FROM virtual_currency_transactions vct JOIN virtual_currencies vc ON vct.virtual_currency_id = vc.id WHERE vct.transaction_type = 'grant' AND vct.expires_at IS NOT NULL AND vct.expires_at > now() AND vct.expires_at <= (now() + interval '7 days') ORDER BY vct.expires_at ASC;
Testing
Manual Trigger (Testing)
You can manually trigger the edge functions for testing:
# Test expiration processing curl -X POST \ https://api.billdog.io/v1/process-currency-expirations \ -H "Authorization: Bearer YOUR_ANON_KEY" \ -H "Content-Type: application/json" # Test expiration notifications curl -X POST \ https://api.billdog.io/v1/notify-currency-expiration \ -H "Authorization: Bearer YOUR_ANON_KEY" \ -H "Content-Type: application/json"
Create Test Expiring Grant
-- Insert a grant that expires in 1 hour (for testing) INSERT INTO virtual_currency_transactions ( customer_id, virtual_currency_id, transaction_type, amount, balance_before, balance_after, source, notes, expires_at ) SELECT (SELECT id FROM customers LIMIT 1), (SELECT id FROM virtual_currencies LIMIT 1), 'grant', 100, 0, 100, 'test', 'Test expiring grant', now() + interval '1 hour';
Best Practices
- Schedule During Low Traffic: Run cron jobs during low-traffic hours (2 AM UTC is typical)
- Monitor Logs: Regularly check edge function logs for errors
- Set Reasonable Windows: Don't set expiration too short (minimum 7 days recommended)
- Test Before Production: Always test with sample data first
- Notification Timing: Send notifications during customer's active hours (10 AM UTC is daytime for most timezones)
Troubleshooting
Cron Jobs Not Running
- Verify extensions are enabled:
SELECT * FROM pg_extension WHERE extname IN ('pg_cron', 'pg_net'); - Check cron job exists:
SELECT * FROM cron.job WHERE jobname LIKE '%currency%';
- Check job run history for errors:
SELECT * FROM cron.job_run_details WHERE status = 'failed' ORDER BY start_time DESC;
Expirations Not Processing
- Check edge function logs in Supabase Dashboard
- Verify
expires_atdates are in the past - Ensure customer has sufficient balance
- Check service role key is configured
Notifications Not Sending
- Verify
notify_before_expiration_daysis set on currency - Check grant hasn't already been notified (check
metadata.expiration_notified) - Review edge function logs for errors
- Confirm customer email exists in
customerstable
Security Notes
- Cron jobs use the Supabase anon key (read-only by default)
- Edge functions use service role key for administrative operations
- All operations respect RLS policies
- Transaction history is fully auditable
Next Steps
After setting up automated processing:
- ✅ Monitor the first few cron job executions
- ✅ Review expiration history data
- ✅ Integrate email/push notifications in
notify-currency-expiration - ✅ Set up alerts for failed cron jobs
- ✅ Document customer-facing expiration policies
Was this page helpful?
Or rate this page: