refactor(#22): add PP with @jcreek

Breaking version of customer stripe sync
This commit is contained in:
OllyNicholass
2024-07-23 20:53:03 +01:00
parent 4d80534244
commit c47c933ce1
5 changed files with 108 additions and 41 deletions
+57 -7
View File
@@ -1,7 +1,11 @@
<script lang="ts"> <script lang="ts">
import { createEventDispatcher } from 'svelte'; import { createEventDispatcher } from 'svelte';
import { general } from '$lib/stores/generalStore.js'; import { general } from '$lib/stores/generalStore.js';
import stripe from 'stripe';
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
const dispatch = createEventDispatcher(); const dispatch = createEventDispatcher();
function emitSignedInEvent() { function emitSignedInEvent() {
@@ -13,16 +17,62 @@
// Access the supabase client from the layout data // Access the supabase client from the layout data
export let supabase: any; export let supabase: any;
export let session: any;
async function signInWithEmail() { async function signInWithEmail() {
// TODO use the data and error from the response try {
const { data, error } = await supabase.auth // Sign in with email and password
.signInWithPassword({ const { data, error } = await supabase.auth.signInWithPassword({
email: email, email: email,
password: password password: password,
});
if (error) {
console.error('Sign in error:', error.message);
return;
}
// Emit signed-in event
emitSignedInEvent();
// Check if the session data is available
if (data && data.session && data.session.user) {
const userId = data.session.user.id;
// Create Stripe customer
await createStripeCustomer(userId);
} else {
console.error('User session data is missing');
}
// Log data for debugging purposes
console.log(data);
} catch (err) {
console.error('Unexpected error:', err);
}
}
async function createStripeCustomer(userId: string) {
console.log('createStripeCustomer');
await stripeClient.customers
.create({
email
}) })
.then(() => { .then(async (customer) => {
emitSignedInEvent(); // Create a new customer in the database customers table with id data.user.id and stripe_customer_id customer.id
const { dataFromUpsert, error } = await supabase.from('customers').upsert([
{
id: userId,
stripe_customer_id: customer.id
}
]);
console.log(dataFromUpsert);
if (error) {
throw error;
}
}); });
} }
+1 -31
View File
@@ -1,21 +1,14 @@
<script lang="ts"> <script lang="ts">
import stripe from 'stripe';
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
let email = ''; let email = '';
let password = ''; let password = '';
// Access the supabase client from the layout data // Access the supabase client from the layout data
export let supabase: any; export let supabase: any;
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
async function signUpNewUser() { async function signUpNewUser() {
try { try {
await supabaseSignUp().then((data) => { await supabaseSignUp();
console.log(data);
createStripeCustomer(data);
});
// Handle success (optional) // Handle success (optional)
} catch (error: any) { } catch (error: any) {
@@ -42,29 +35,6 @@
return data; return data;
} }
async function createStripeCustomer(data: any) {
console.log('createStripeCustomer');
await stripeClient.customers
.create({
email
})
.then(async (customer) => {
// Create a new customer in the database customers table with id data.user.id and stripe_customer_id customer.id
const { dataFromUpsert, error } = await supabase.from('customers').upsert([
{
id: data.user.id,
stripe_customer_id: customer.id
}
]);
console.log(dataFromUpsert);
if (error) {
throw error;
}
});
}
</script> </script>
<form class="card-body"> <form class="card-body">
+9 -2
View File
@@ -155,8 +155,15 @@ const createOrRetrieveCustomer = async ({ email, uuid }: { email: string; uuid:
console.warn(`Supabase customer record was missing. A new record was created.`); console.warn(`Supabase customer record was missing. A new record was created.`);
// If Supabase has no record, create a new record and return Stripe customer ID // If Supabase has no record, create a new record and return Stripe customer ID
const upsertedStripeCustomer = await upsertCustomerToSupabase(uuid, stripeIdToInsert); try {
if (!upsertedStripeCustomer) throw new Error('Supabase customer record creation failed.'); const upsertedStripeCustomer = await upsertCustomerToSupabase(uuid, stripeIdToInsert);
if (!upsertedStripeCustomer) throw new Error('Supabase customer record creation failed.');
return upsertedStripeCustomer;
} catch (error) {
console.error(`Supabase customer record creation failed: ${error}`);
return null;
}
return upsertedStripeCustomer; return upsertedStripeCustomer;
} }
+1 -1
View File
@@ -147,7 +147,7 @@
<div <div
class="mt-3 z-[1] p-2 shadow menu menu-sm dropdown-content bg-base-100 text-base-content rounded-box min-w-[13rem] w-auto" class="mt-3 z-[1] p-2 shadow menu menu-sm dropdown-content bg-base-100 text-base-content rounded-box min-w-[13rem] w-auto"
> >
<SignIn {supabase} /> <SignIn {supabase} {session} />
</div> </div>
{/if} {/if}
</div> </div>
@@ -0,0 +1,40 @@
-- TESTS FOR RLS policy
create policy "Enable update for users based on id"
on "public"."customers"
as permissive
for update
to public
using ((( SELECT auth.uid() AS uid) = id))
with check ((( SELECT auth.uid() AS uid) = id));
create policy "Enable insert for users based on id"
on "public"."customers"
as permissive
for insert
to public
with check ((( SELECT auth.uid() AS uid) = id));
create policy "DEMO Enable insert for users based on id"
on "public"."customers"
as permissive
for insert
to public
with check (true);
create policy "DEMO Enable update for users based on id"
on "public"."customers"
as permissive
for update
to public
using (true)
with check (true);
GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role;
GRANT ALL ON ALL TABLES IN SCHEMA public TO anon, authenticated, service_role;
GRANT ALL ON ALL ROUTINES IN SCHEMA public TO anon, authenticated, service_role;
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO anon, authenticated, service_role;
ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO anon, authenticated, service_role;
ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON ROUTINES TO anon, authenticated, service_role;
ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO anon, authenticated, service_role;