-
Couldn't load subscription status.
- Fork 11
feat: Handle inactive users #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| import { supabaseAdmin } from "@changes-page/supabase/admin"; | ||
| import { IErrorResponse } from "@changes-page/supabase/types/api"; | ||
| import type { NextApiRequest, NextApiResponse } from "next"; | ||
| import { v4 } from "uuid"; | ||
|
|
||
| interface CleanupResponse { | ||
| status: string; | ||
| deletedPages: number; | ||
| jobId: string; | ||
| } | ||
|
|
||
| const cleanupInactivePagesJob = async ( | ||
| req: NextApiRequest, | ||
| res: NextApiResponse<CleanupResponse | IErrorResponse> | ||
| ) => { | ||
| if (req.method !== "POST") { | ||
| return res | ||
| .status(405) | ||
| .json({ error: { statusCode: 405, message: "Method not allowed" } }); | ||
| } | ||
|
|
||
| const authHeader = req.headers["authorization"]; | ||
| if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) { | ||
| return res.status(401).json({ | ||
| error: { | ||
| statusCode: 401, | ||
| message: "Unauthorized", | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| try { | ||
| const jobId = v4(); | ||
|
|
||
| console.log(`[${jobId}] Starting cleanup inactive pages job`); | ||
|
|
||
| const { data: inactivePages, error: fetchError } = await supabaseAdmin.rpc( | ||
| "get_pages_with_inactive_subscriptions" | ||
| ); | ||
|
|
||
| if (fetchError) { | ||
| console.error(`[${jobId}] Error fetching inactive pages:`, fetchError); | ||
| throw fetchError; | ||
| } | ||
|
|
||
| const allInactivePages = inactivePages || []; | ||
|
|
||
| console.log( | ||
| `[${jobId}] Found ${allInactivePages.length} pages from inactive users to delete` | ||
| ); | ||
|
|
||
| if (allInactivePages.length === 0) { | ||
| console.log(`[${jobId}] No pages to delete`); | ||
| return res.status(200).json({ | ||
| status: "ok", | ||
| deletedPages: 0, | ||
| jobId, | ||
| }); | ||
| } | ||
|
|
||
| const pageIdsToDelete = allInactivePages.map((page) => page.page_id); | ||
|
|
||
| console.log(`[${jobId}] Deleting ${pageIdsToDelete.length} pages`); | ||
| const { error: pagesDeleteError } = await supabaseAdmin | ||
| .from("pages") | ||
| .delete() | ||
| .in("id", pageIdsToDelete); | ||
|
|
||
| if (pagesDeleteError) { | ||
| console.error(`[${jobId}] Error deleting pages:`, pagesDeleteError); | ||
| throw pagesDeleteError; | ||
| } | ||
arjunkomath marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| console.log( | ||
| `[${jobId}] Successfully deleted ${pageIdsToDelete.length} pages and related data` | ||
| ); | ||
|
|
||
| // Log deleted pages for audit purposes | ||
| allInactivePages.forEach((page) => { | ||
| console.log( | ||
| `[${jobId}] Deleted page: ${page.page_title} (ID: ${page.page_id}) from user: ${page.user_id}` | ||
| ); | ||
| }); | ||
|
|
||
| console.log(`[${jobId}] Cleanup job finished successfully`); | ||
|
|
||
| return res.status(200).json({ | ||
| status: "ok", | ||
| deletedPages: pageIdsToDelete.length, | ||
| jobId, | ||
| }); | ||
| } catch (err) { | ||
| console.error("cleanupInactivePagesJob error:", err); | ||
| res.status(500).json({ | ||
| error: { | ||
| statusCode: 500, | ||
| message: err.message || "Internal server error", | ||
| }, | ||
| }); | ||
| } | ||
| }; | ||
|
|
||
| export default cleanupInactivePagesJob; | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -3,6 +3,10 @@ | |||||||||||||||||||
| { | ||||||||||||||||||||
| "path": "/api/billing/jobs/report-usage", | ||||||||||||||||||||
| "schedule": "0 0 * * *" | ||||||||||||||||||||
| }, | ||||||||||||||||||||
| { | ||||||||||||||||||||
| "path": "/api/billing/jobs/cleanup-inactive-pages", | ||||||||||||||||||||
| "schedule": "0 1 * * *" | ||||||||||||||||||||
| } | ||||||||||||||||||||
|
Comment on lines
+7
to
10
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Verification agent 🧩 Analysis chainSpecify HTTP method to prevent side-effectful cleanup from defaulting to GET Vercel cron invocations default to a GET request, which is semantically wrong for a mutation-type endpoint and can introduce caching or proxy side-effects. Declare the intended verb explicitly. "path": "/api/billing/jobs/cleanup-inactive-pages",
+ "method": "POST",
"schedule": "0 1 * * *"Ensure the handler in 🏁 Script executed: #!/bin/bash
set -e
# Locate the cleanup-inactive-pages API handler file
handler_file=$(fd cleanup-inactive-pages.ts)
echo "Handler file found at: $handler_file"
# Inspect HTTP method checks in the handler
echo -e "\nChecking for HTTP method conditions (req.method) in the handler:"
grep -n -C2 "req.method" "$handler_file" || echo "No HTTP method checks found"
# Show the handler export signature for context
echo -e "\nHandler export signature:"
grep -n "export default" "$handler_file" | head -n 1Length of output: 864 Specify HTTP method for the cleanup-inactive-pages cron job Your handler in • File: apps/web/vercel.json {
"path": "/api/billing/jobs/cleanup-inactive-pages",
+ "method": "POST",
"schedule": "0 1 * * *"
}This ensures Vercel’s cron will invoke the endpoint with POST, matching your mutation-style handler. 📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||
| ] | ||||||||||||||||||||
| } | ||||||||||||||||||||
| } | ||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| -- Drop the existing foreign key constraint | ||
| ALTER TABLE page_audit_logs | ||
| DROP CONSTRAINT page_audit_logs_page_id_fkey; | ||
|
|
||
| -- Recreate the constraint with CASCADE DELETE | ||
| ALTER TABLE page_audit_logs | ||
| ADD CONSTRAINT page_audit_logs_page_id_fkey | ||
| FOREIGN KEY (page_id) | ||
| REFERENCES pages(id) | ||
| ON DELETE CASCADE; | ||
|
|
||
| -- Function to get pages with inactive subscriptions | ||
| CREATE OR REPLACE FUNCTION get_pages_with_inactive_subscriptions() | ||
| RETURNS TABLE ( | ||
| page_id uuid, | ||
| page_title text, | ||
| page_created_at timestamptz, | ||
| url text, | ||
| user_id uuid | ||
| ) AS $$ | ||
| BEGIN | ||
| RETURN QUERY | ||
| SELECT | ||
| p.id AS page_id, | ||
| p.title AS page_title, | ||
| p.created_at AS page_created_at, | ||
| p.url_slug AS url, | ||
| u.id AS user_id | ||
| FROM | ||
| pages p | ||
| JOIN | ||
| users u ON p.user_id = u.id | ||
| JOIN | ||
| auth.users au ON u.id = au.id | ||
| WHERE | ||
| ( | ||
| -- Users with canceled subscription | ||
| (u.stripe_subscription->>'status')::text = 'canceled' | ||
| -- OR users without any subscription | ||
| OR u.stripe_subscription IS NULL | ||
| ) | ||
| -- not gifted pro | ||
| AND u.pro_gifted = false | ||
| -- User hasn't been active in the last 180 days | ||
| AND (au.last_sign_in_at IS NULL OR au.last_sign_in_at < NOW() - INTERVAL '180 days') | ||
| ORDER BY | ||
arjunkomath marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| p.created_at ASC; | ||
| END; | ||
| $$ LANGUAGE plpgsql SECURITY DEFINER; | ||
Uh oh!
There was an error while loading. Please reload this page.