mirror of
https://github.com/jcreek/SvelteKitSaasBoilerplate.git
synced 2026-07-13 19:13:48 +00:00
Merge remote-tracking branch 'origin/master' into 35-replace-navbar-with-a-better-one
This commit is contained in:
+193
-36
@@ -4,6 +4,8 @@ import type { Database, Tables, TablesInsert } from '$lib/types/supabase';
|
||||
import { PUBLIC_SUPABASE_URL } from '$env/static/public';
|
||||
import { SUPABASE_SERVICE_ROLE_KEY } from '$env/static/private';
|
||||
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||
import logger from '$lib/utils/logger/logger';
|
||||
import { sendEmail } from '../brevo/email';
|
||||
|
||||
const toDateTime = (secs: number) => {
|
||||
const t = new Date(+0); // Unix epoch start.
|
||||
@@ -39,7 +41,7 @@ const upsertProductRecord = async (product: stripe.Product) => {
|
||||
|
||||
const { error: upsertError } = await supabaseAdmin.from('products').upsert([productData]);
|
||||
if (upsertError) throw new Error(`Product insert/update failed: ${upsertError.message}`);
|
||||
console.log(`Product inserted/updated: ${product.id}`);
|
||||
logger.info(`Product inserted/updated: ${product.id}`);
|
||||
};
|
||||
|
||||
const upsertPriceRecord = async (price: stripe.Price, retryCount = 0, maxRetries = 3) => {
|
||||
@@ -61,7 +63,7 @@ const upsertPriceRecord = async (price: stripe.Price, retryCount = 0, maxRetries
|
||||
|
||||
if (upsertError?.message.includes('foreign key constraint')) {
|
||||
if (retryCount < maxRetries) {
|
||||
console.log(`Retry attempt ${retryCount + 1} for price ID: ${price.id}`);
|
||||
logger.info(`Retry attempt ${retryCount + 1} for price ID: ${price.id}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
await upsertPriceRecord(price, retryCount + 1, maxRetries);
|
||||
} else {
|
||||
@@ -72,7 +74,7 @@ const upsertPriceRecord = async (price: stripe.Price, retryCount = 0, maxRetries
|
||||
} else if (upsertError) {
|
||||
throw new Error(`Price insert/update failed: ${upsertError.message}`);
|
||||
} else {
|
||||
console.log(`Price inserted/updated: ${price.id}`);
|
||||
logger.info(`Price inserted/updated: ${price.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -82,13 +84,13 @@ const deleteProductRecord = async (product: stripe.Product) => {
|
||||
.delete()
|
||||
.eq('id', product.id);
|
||||
if (deletionError) throw new Error(`Product deletion failed: ${deletionError.message}`);
|
||||
console.log(`Product deleted: ${product.id}`);
|
||||
logger.info(`Product deleted: ${product.id}`);
|
||||
};
|
||||
|
||||
const deletePriceRecord = async (price: stripe.Price) => {
|
||||
const { error: deletionError } = await supabaseAdmin.from('prices').delete().eq('id', price.id);
|
||||
if (deletionError) throw new Error(`Price deletion failed: ${deletionError.message}`);
|
||||
console.log(`Price deleted: ${price.id}`);
|
||||
logger.info(`Price deleted: ${price.id}`);
|
||||
};
|
||||
|
||||
const upsertCustomerToSupabase = async (uuid: string, customerId: string) => {
|
||||
@@ -254,11 +256,18 @@ const manageSubscriptionStatusChange = async (
|
||||
trial_end: subscription.trial_end ? toDateTime(subscription.trial_end).toISOString() : null
|
||||
};
|
||||
|
||||
const { error: upsertError } = await supabaseAdmin
|
||||
.from('subscriptions')
|
||||
.upsert([subscriptionData]);
|
||||
if (upsertError) throw new Error(`Subscription insert/update failed: ${upsertError.message}`);
|
||||
console.log(`Inserted/updated subscription [${subscription.id}] for user [${uuid}]`);
|
||||
try {
|
||||
const { error: upsertError } = await supabaseAdmin
|
||||
.from('subscriptions')
|
||||
.upsert([subscriptionData]);
|
||||
if (upsertError) {
|
||||
throw new Error(`Subscription insert/update failed: ${upsertError.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
}
|
||||
|
||||
logger.info(`Inserted/updated subscription [${subscription.id}] for user [${uuid}]`);
|
||||
|
||||
// // For a new subscription copy the billing details to the customer object.
|
||||
// // NOTE: This is a costly operation and should happen at the very end.
|
||||
@@ -271,7 +280,7 @@ const manageSubscriptionStatusChange = async (
|
||||
};
|
||||
|
||||
const recordProductPurchase = async (userId: string, productId: string, priceId: string) => {
|
||||
console.log(
|
||||
logger.info(
|
||||
`Recording product purchase for user [${userId}] and product [${productId}] with price [${priceId}]`
|
||||
);
|
||||
|
||||
@@ -284,40 +293,48 @@ const recordProductPurchase = async (userId: string, productId: string, priceId:
|
||||
throw new Error(`Failed to record product purchase: ${error.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
logger.error(error);
|
||||
}
|
||||
|
||||
console.log(`Product purchased recorded for user [${userId}] and product [${productId}]`);
|
||||
logger.info(`Product purchased recorded for user [${userId}] and product [${productId}]`);
|
||||
};
|
||||
|
||||
const hasProductAccess = async (userId: string, productId: string) => {
|
||||
// Check if user has purchased the product
|
||||
const { data: purchases, error: purchaseError } = await supabaseAdmin
|
||||
.from('purchases')
|
||||
.select('*')
|
||||
.eq('user_id', userId)
|
||||
.eq('product_id', productId);
|
||||
try {
|
||||
const { data: purchases, error: purchaseError } = await supabaseAdmin
|
||||
.from('purchases')
|
||||
.select('*')
|
||||
.eq('user_id', userId)
|
||||
.eq('product_id', productId);
|
||||
|
||||
if (purchaseError) throw new Error(purchaseError.message);
|
||||
if (purchaseError) throw new Error(purchaseError.message);
|
||||
|
||||
if (purchases && purchases.length > 0) {
|
||||
// User has purchased the product
|
||||
return true;
|
||||
if (purchases && purchases.length > 0) {
|
||||
// User has purchased the product
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
}
|
||||
|
||||
// Check if user has an active subscription for the product
|
||||
const { data: subscriptions, error: subError } = await supabaseAdmin
|
||||
.from('subscriptions')
|
||||
.select('*')
|
||||
.eq('user_id', userId)
|
||||
.eq('product_id', productId)
|
||||
.in('status', ['active', 'trialing']);
|
||||
try {
|
||||
const { data: subscriptions, error: subError } = await supabaseAdmin
|
||||
.from('subscriptions')
|
||||
.select('*')
|
||||
.eq('user_id', userId)
|
||||
.eq('product_id', productId)
|
||||
.in('status', ['active', 'trialing']);
|
||||
|
||||
if (subError) throw new Error(subError.message);
|
||||
if (subError) throw new Error(subError.message);
|
||||
|
||||
if (subscriptions && subscriptions.length > 0) {
|
||||
// User has an active subscription
|
||||
return true;
|
||||
if (subscriptions && subscriptions.length > 0) {
|
||||
// User has an active subscription
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -381,7 +398,7 @@ const updateUserCredits = async (userId: string, creditsChange: number, descript
|
||||
|
||||
await logCreditTransaction(userId, creditsChange, description);
|
||||
|
||||
console.log(
|
||||
logger.info(
|
||||
`${creditsChange > 0 ? 'Added' : 'Deducted'} ${Math.abs(creditsChange)} credits to user [${userId}]`
|
||||
);
|
||||
};
|
||||
@@ -390,7 +407,7 @@ const addCredits = async (userId: string, creditsToAdd: number, description: str
|
||||
try {
|
||||
await updateUserCredits(userId, creditsToAdd, description);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
logger.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -398,7 +415,7 @@ const deductCredits = async (userId: string, creditsToDeduct: number, descriptio
|
||||
try {
|
||||
await updateUserCredits(userId, -creditsToDeduct, description);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
logger.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -480,6 +497,142 @@ const getProductById = async (productId: string) => {
|
||||
return product as Product;
|
||||
};
|
||||
|
||||
const requestAccountDeletion = async (userId: string, userEmail: string, baseUrl: string) => {
|
||||
const token = crypto.randomUUID();
|
||||
|
||||
const { error: insertError } = await supabaseAdmin.from('account_deletion_requests').upsert({
|
||||
user_id: userId,
|
||||
token,
|
||||
requested_at: new Date().toISOString()
|
||||
});
|
||||
|
||||
if (insertError) throw new Error(`Account deletion request failed: ${insertError.message}`);
|
||||
|
||||
const deletionLink = `${baseUrl}/api/delete-account?token=${token}`;
|
||||
|
||||
// Send deletion email using Brevo
|
||||
try {
|
||||
await sendEmail(
|
||||
'Confirm Account Deletion',
|
||||
`<p>Click <a href="${deletionLink}">here</a> to confirm your account deletion.</p>`,
|
||||
userEmail
|
||||
);
|
||||
console.log('Deletion email sent successfully.');
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send deletion email:', emailError);
|
||||
throw new Error('Failed to send confirmation email.');
|
||||
}
|
||||
};
|
||||
|
||||
const deleteAccount = async (token: string) => {
|
||||
// Verify the token
|
||||
const { data: deletionRequest, error } = await supabaseAdmin
|
||||
.from('account_deletion_requests')
|
||||
.select('user_id')
|
||||
.eq('token', token)
|
||||
.single();
|
||||
|
||||
if (error || !deletionRequest) {
|
||||
return new Response('Invalid or expired token', { status: 400 });
|
||||
}
|
||||
|
||||
// N.B. The SQL here will either cascade delete or nullify the foreign key constraints depending on the table, to enable anonymisation
|
||||
const { error: deletionError } = await supabaseAdmin.auth.admin.deleteUser(
|
||||
deletionRequest.user_id
|
||||
);
|
||||
if (deletionError) {
|
||||
throw new Error(`Failed to delete user: ${deletionError.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
const getUserSubscriptions = async (userId: string) => {
|
||||
try {
|
||||
// Step 1: Retrieve subscription data
|
||||
const { data: subscriptions, error } = await supabaseAdmin
|
||||
.from('subscriptions')
|
||||
.select('*')
|
||||
.eq('user_id', userId);
|
||||
|
||||
if (error) {
|
||||
logger.error('Error retrieving subscriptions:', error.message);
|
||||
throw new Error('Failed to fetch subscriptions');
|
||||
}
|
||||
|
||||
// Step 2: Map through each subscription and fetch product and price details
|
||||
const subscriptionDetails = await Promise.all(
|
||||
subscriptions.map(async (sub) => {
|
||||
// Fetch product and price details from Stripe
|
||||
const product = await stripeClient.products.retrieve(sub.product_id);
|
||||
const price = await stripeClient.prices.retrieve(sub.price_id);
|
||||
|
||||
const expiryDate = new Date(sub.current_period_end);
|
||||
|
||||
// Format output data
|
||||
return {
|
||||
productName: product.name,
|
||||
amount: (price.unit_amount / 100).toFixed(2),
|
||||
currency: price.currency.toUpperCase(),
|
||||
interval: price.recurring?.interval || 'one-time',
|
||||
expiryDate: expiryDate.toLocaleDateString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric'
|
||||
}),
|
||||
status: sub.status
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return subscriptionDetails;
|
||||
} catch (error) {
|
||||
logger.error('An error occurred while retrieving subscription details:', error);
|
||||
throw new Error('Could not retrieve subscription details');
|
||||
}
|
||||
};
|
||||
|
||||
const getUserTransactions = async (userId: string) => {
|
||||
try {
|
||||
// Step 1: Retrieve the customer ID associated with the user
|
||||
const { data, error } = await supabaseAdmin
|
||||
.from('customers')
|
||||
.select('stripe_customer_id')
|
||||
.eq('id', userId)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Error retrieving user data:', error.message);
|
||||
throw new Error('Failed to fetch user data');
|
||||
}
|
||||
|
||||
const customerId = data?.stripe_customer_id;
|
||||
if (!customerId) {
|
||||
throw new Error('No Stripe customer ID found for this user');
|
||||
}
|
||||
|
||||
// Step 2: Fetch charge transactions from Stripe
|
||||
const charges = await stripeClient.charges.list({ customer: customerId });
|
||||
|
||||
// Step 3: Format transaction data
|
||||
const transactions = charges.data.map((charge) => ({
|
||||
amount: (charge.amount / 100).toFixed(2),
|
||||
currency: charge.currency.toUpperCase(),
|
||||
description: charge.description ?? 'No description provided',
|
||||
status: charge.status,
|
||||
created: new Date(charge.created * 1000).toLocaleDateString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric'
|
||||
}),
|
||||
receipt_url: charge.receipt_url
|
||||
}));
|
||||
|
||||
return transactions;
|
||||
} catch (error) {
|
||||
console.error('An error occurred while retrieving transactions:', error);
|
||||
throw new Error('Could not retrieve transactions');
|
||||
}
|
||||
};
|
||||
|
||||
export {
|
||||
upsertProductRecord,
|
||||
upsertPriceRecord,
|
||||
@@ -495,5 +648,9 @@ export {
|
||||
getActiveProductsWithPrices,
|
||||
getProductById,
|
||||
upsertCustomerToSupabase,
|
||||
getStripeCustomerId
|
||||
getStripeCustomerId,
|
||||
getUserSubscriptions,
|
||||
getUserTransactions,
|
||||
requestAccountDeletion,
|
||||
deleteAccount
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user