mirror of
https://github.com/jcreek/SvelteKitSaasBoilerplate.git
synced 2026-07-15 20:13:50 +00:00
Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eb979add7d | |||
| 5744ad4db8 | |||
| cd65181e3e | |||
| 532ac0cbe5 | |||
| e47fa54ea8 | |||
| a33779ce53 | |||
| 570b11ef2a | |||
| 7825d29081 | |||
| f3e6c236d5 | |||
| 4c44f772e5 | |||
| 7d994d1c09 | |||
| 03157a6d2f | |||
| 7e458b7297 | |||
| b61983368c | |||
| 43bd4e8026 | |||
| ec684f9074 | |||
| 0b2b0fc7f3 | |||
| 8eb309e393 | |||
| 29f418cc91 | |||
| f34954f45a | |||
| 616009ea05 | |||
| 59258a4750 | |||
| f46b6359ab | |||
| 79e2dcb744 | |||
| 15913ad413 | |||
| 8f7075db28 | |||
| 8221224255 | |||
| 36a8620e70 | |||
| e666aa95d0 | |||
| 95a0c1dee5 | |||
| 73cb21d9de | |||
| e51aeb7c63 | |||
| 2f7ec9860a | |||
| 5d83c79b97 | |||
| db3425ec96 | |||
| fcbd69373c | |||
| c9682be7c8 | |||
| c674eb7c8d | |||
| 108b534a9c | |||
| b2d4d005e1 | |||
| d3a134891c | |||
| 5b137cf715 | |||
| fce4c0e0a5 | |||
| a4764c547e | |||
| 05891ad510 | |||
| d4f7f5041d | |||
| b159c33487 | |||
| 780d810597 | |||
| 47305ba570 | |||
| a3873f93fb | |||
| 6e1d38ef58 | |||
| 0a906fa94d | |||
| 32a3feef64 | |||
| e1df81f104 | |||
| ec456a9b22 | |||
| 02a75e1393 | |||
| 9089aa270b | |||
| 7e05b3f361 | |||
| 49a9b079ea | |||
| 2b2e3e6063 | |||
| 6cf1ffe4f4 | |||
| 7e0c06bab3 | |||
| b365d77c16 | |||
| 723f7eddf7 | |||
| 31a81f6312 | |||
| 65fdc1834a | |||
| cd1d4b7d71 | |||
| 35105d31f1 | |||
| f376a942b3 | |||
| 94de247d56 | |||
| d95c8ec6cc | |||
| 0423bfa701 | |||
| 5c0cce9e47 | |||
| ff71f7a0db | |||
| a29df65cbb | |||
| ceba7622a9 | |||
| 3d296c8f2c | |||
| 0990edab2e | |||
| bd560c41e1 | |||
| c76c6f4484 | |||
| a964f19fc4 | |||
| 06fc2c2cd2 | |||
| b521314cc6 | |||
| 3fa3ace4ee | |||
| 67fcf8ea38 | |||
| 37a8062c75 | |||
| c32d62d420 | |||
| 1f0ff5bc5c | |||
| 103ee16cec | |||
| 337bc648ca | |||
| 14992c3798 | |||
| 48aaee744f | |||
| 2fe426b3f4 | |||
| a10d22d1f8 | |||
| 8634e56bd1 | |||
| d30d6181cf | |||
| 540352657c | |||
| f10e0537bd | |||
| 113268614b | |||
| e15565bb56 | |||
| fd4befcd12 | |||
| ed4b5f3725 | |||
| 83c8e44f33 | |||
| 66698445f2 | |||
| 1303c97f72 | |||
| 822b8c7235 |
+4
-1
@@ -1,3 +1,6 @@
|
|||||||
PUBLIC_SUPABASE_URL=""
|
PUBLIC_SUPABASE_URL=""
|
||||||
PUBLIC_SUPABASE_ANON_KEY=""
|
PUBLIC_SUPABASE_ANON_KEY=""
|
||||||
PUBLIC_STRIPE_SECRET_KEY=""
|
SUPABASE_SERVICE_ROLE_KEY=""
|
||||||
|
STRIPE_SECRET_KEY=""
|
||||||
|
STRIPE_ENDPOINT_SECRET=""
|
||||||
|
VITE_PRODUCT_ID_EXAMPLEPRODUCT=""
|
||||||
@@ -8,5 +8,4 @@ node_modules
|
|||||||
!.env.example
|
!.env.example
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
vite.config.ts.timestamp-*
|
vite.config.ts.timestamp-*
|
||||||
/static/output.css
|
|
||||||
.netlify
|
.netlify
|
||||||
|
|||||||
@@ -17,6 +17,13 @@ npm run dev -- --open
|
|||||||
|
|
||||||
An example `.env` file is provided in the repository. You will need to copy `.env.example` to `.env` and fill in the values with your own credentials.
|
An example `.env` file is provided in the repository. You will need to copy `.env.example` to `.env` and fill in the values with your own credentials.
|
||||||
|
|
||||||
|
If you want a fully local development environment (other than stripe) then you can follow the instructions in the [database setup](/docs/database-setup.md) document and make use of the local supabase instance and a local email service.
|
||||||
|
|
||||||
|
- [Local DB Url](http://localhost:54323/)
|
||||||
|
- [Local Email Monitoring Url](http://localhost:54324/)
|
||||||
|
|
||||||
|
For stripe, you can forward the events to your local server using `stripe listen --forward-to localhost:5173/api/webhook/stripe --skip-verify` in a separate terminal window.
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
To create a production version:
|
To create a production version:
|
||||||
@@ -41,4 +48,14 @@ In its current configuration, the application can be easily linked to Netlify vi
|
|||||||
|
|
||||||
## To Do
|
## To Do
|
||||||
|
|
||||||
|
- [Update types automatically](https://supabase.com/docs/guides/api/rest/generating-types#update-types-automatically-with-github-actions)
|
||||||
|
|
||||||
Please see the Issues tab for `enhancement` tagged issues.
|
Please see the Issues tab for `enhancement` tagged issues.
|
||||||
|
|
||||||
|
## [Database setup](/docs/database-setup.md)
|
||||||
|
|
||||||
|
## [Stripe webhook event listening](/docs/stripe-setup.md)
|
||||||
|
|
||||||
|
## Testing the example credits management system
|
||||||
|
|
||||||
|
There is an example system in this project for being able to manage credits that are sold to users. To test this system you can visit the `http://localhost:5173/test/test-credits` route. This will allow you to add credits to a user and then spend them by clicking the buttons on the page, and will show the user's credit balance updating in real time.
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Database Setup
|
||||||
|
|
||||||
|
Databases are stored in Supabase. The auth table for signing up and logging in users is created automatically when you set up Supabase Auth.
|
||||||
|
|
||||||
|
## Initial Setup
|
||||||
|
|
||||||
|
To add the tables for recording their active subscriptions and bought products, as well as products and prices, you can use the SQL scripts from the `supabase/migrations` folder in the Supabase SQL Editor.
|
||||||
|
|
||||||
|
## Common commands for local development
|
||||||
|
|
||||||
|
- `npx supabase start` - Start the local Supabase instance
|
||||||
|
- `npx supabase stop` - Stop the local Supabase instance
|
||||||
|
- `npx supabase db reset` - Reset the local database
|
||||||
|
- `npx supabase gen types typescript --local > src/lib/types/supabase.d.ts` - Generate types for the local database
|
||||||
|
|
||||||
|
## Generating Types
|
||||||
|
|
||||||
|
To get the types for the tables, you can follow these instructions taken from [here](https://supabase.com/docs/guides/api/rest/generating-types#generating-types-using-supabase-cli):
|
||||||
|
|
||||||
|
`npm i supabase@">=1.8.1" --save-dev`
|
||||||
|
|
||||||
|
`npx supabase login`
|
||||||
|
|
||||||
|
`npx supabase init`
|
||||||
|
|
||||||
|
Replace `$PROJECT_REF` with your project reference and replace `types/supabase.d.ts` with whatever file you want your types in:
|
||||||
|
`npx supabase gen types typescript --project-id "$PROJECT_REF" --schema public > src/lib/types/supabase.d.ts`
|
||||||
|
|
||||||
|
If you are using a local Supabase instance, you can use the following command to generate the types:
|
||||||
|
`npx supabase gen types typescript --local > src/lib/types/supabase.d.ts`
|
||||||
|
|
||||||
|
## Local DB Development
|
||||||
|
|
||||||
|
Ensure you have [Docker](https://docs.docker.com/get-docker/) installed and running.
|
||||||
|
|
||||||
|
You can start and stop the local DB environment with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx supabase start
|
||||||
|
|
||||||
|
npx supabase stop
|
||||||
|
```
|
||||||
|
|
||||||
|
This will start the local DB and email monitoring services. You can access the web interfaces for the local DB at [http://localhost:54323/](http://localhost:54323/) and the email monitoring at [http://localhost:54324/](http://localhost:54324/).It will also give you the API URL, anon key and service_role key to put in your `.env` file for local development.
|
||||||
|
|
||||||
|
## Migrations
|
||||||
|
|
||||||
|
There are two options to create a migration file:
|
||||||
|
|
||||||
|
1. [Writing the SQL manually](https://supabase.com/docs/guides/cli/local-development#database-migrations)
|
||||||
|
|
||||||
|
- Create new blank migration file
|
||||||
|
|
||||||
|
`npx supabase migration new <migration_name>`
|
||||||
|
|
||||||
|
- Add the SQL you want to deploy as part of the migration e.g.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
create table
|
||||||
|
employees (
|
||||||
|
id bigint primary key generated always as identity,
|
||||||
|
name text,
|
||||||
|
email text,
|
||||||
|
created_at timestamptz default now()
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
- Reset the DB and apply the latest migrations
|
||||||
|
|
||||||
|
`npx supabase db reset`
|
||||||
|
|
||||||
|
2. [Generate SQL based on differences to the schema](https://supabase.com/docs/guides/cli/local-development#diffing-changes)
|
||||||
|
|
||||||
|
- With the local DB running, enter the studio and make your changes to the schema
|
||||||
|
|
||||||
|
- Generate the migration file containing the SQL with the differences in the schema
|
||||||
|
|
||||||
|
`npx supabase db diff -f <migration_name>`
|
||||||
|
|
||||||
|
## Applying migrations
|
||||||
|
|
||||||
|
Reset database in cloud
|
||||||
|
|
||||||
|
> Prerequisite login using `npx supabase login`
|
||||||
|
|
||||||
|
`npx supabase db reset --linked`
|
||||||
|
|
||||||
|
## Enabling sending emails with Brevo
|
||||||
|
|
||||||
|
1. Go to the Project Settings in Supabase, then Authentication, then SMTP Settings. You should end up at `https://supabase.com/dashboard/project/[your-project-here]/settings/auth`
|
||||||
|
2. Enable custom SMTP and fill in the required fields with your Brevo credentials.
|
||||||
|
|
||||||
|
- You need to have an email address that you can send stuff from
|
||||||
|
- You need to have a Brevo account
|
||||||
|
- sender email as noreply@yourdomain.com
|
||||||
|
|
||||||
|
3. `https://app.brevo.com/senders/list` to add senders
|
||||||
|
4. Add a sender for noreply@yourdomain.com
|
||||||
|
5. Verify your email domain via DKIM or DMARC
|
||||||
|
6. In Brevo go to `https://app.brevo.com/settings/keys/smtp` to see your SMTP credentials.
|
||||||
|
7. Fill in the SMTP credentials in Supabase.
|
||||||
|
8. Go to `https://supabase.com/dashboard/project/[your-project-here]/auth/url-configuration`
|
||||||
|
9. Add these redirect URLs:
|
||||||
|
|
||||||
|
- `http://localhost:3000`
|
||||||
|
- `http://localhost:3000/**`
|
||||||
|
- `https://www.your-domain.com`
|
||||||
|
- `https://your-domain.com`
|
||||||
|
- `http://localhost:5173`
|
||||||
|
- `http://localhost:5173/**`
|
||||||
|
- Add your netlify.app domain here with **-- at the start, e.g. `http://**--your-netlify-app.netlify.app`
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Stripe webhook event listening
|
||||||
|
|
||||||
|
> First ensure you've installed the [Stripe CLI](https://docs.stripe.com/stripe-cli)
|
||||||
|
|
||||||
|
Log in using the stripe CLI:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
stripe login
|
||||||
|
```
|
||||||
|
|
||||||
|
Obtain your Webhook signing secret:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
stripe listen
|
||||||
|
```
|
||||||
|
|
||||||
|
Add the secret key to to your .env(.local):
|
||||||
|
|
||||||
|
`STRIPE_ENDPOINT_SECRET`
|
||||||
|
|
||||||
|
## Testing the webhook locally
|
||||||
|
|
||||||
|
You can use the [Stripe CLI to forward events to your local server](https://docs.stripe.com/webhooks):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
stripe listen --forward-to localhost:5173/api/webhook/stripe
|
||||||
|
```
|
||||||
|
|
||||||
|
To disable HTTPS certificate verification, use the --skip-verify optional flag.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
stripe listen --forward-to localhost:5173/api/webhook/stripe --skip-verify
|
||||||
|
```
|
||||||
|
|
||||||
|
## Purchaseable products
|
||||||
|
|
||||||
|
As well as subscriptions you can also create purchaseable products in Stripe. These can be used for one-off payments or for products that are not subscription based. To add these to the application you can follow the example product's pattern.
|
||||||
|
|
||||||
|
There is a config value `VITE_PRODUCT_ID_EXAMPLEPRODUCT` that is used to identify the product in the Stripe checkout session. This is the product code from Stripe. The actual 'product' that users are getting access to is at the `src/routes/tools/exampleproduct` path.
|
||||||
Generated
-9835
File diff suppressed because it is too large
Load Diff
+17
-9
@@ -3,14 +3,14 @@
|
|||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "npx tailwindcss -i ./static/input.css -o ./static/output.css && vite dev",
|
"dev": "vite dev",
|
||||||
"build": "npx tailwindcss -i ./static/input.css -o ./static/output.css && vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
"lint": "prettier --check . && eslint .",
|
"lint": "prettier --check . && eslint .",
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"tailwind": "npx tailwindcss -i ./static/input.css -o ./static/output.css"
|
"generate": "supabase gen types typescript --local > src/lib/types/supabase.d.ts && prettier --write src/lib/types/supabase.d.ts"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sveltejs/adapter-auto": "^3.0.0",
|
"@sveltejs/adapter-auto": "^3.0.0",
|
||||||
@@ -19,6 +19,8 @@
|
|||||||
"@sveltejs/adapter-static": "^3.0.0",
|
"@sveltejs/adapter-static": "^3.0.0",
|
||||||
"@sveltejs/kit": "^2.0.6",
|
"@sveltejs/kit": "^2.0.6",
|
||||||
"@sveltejs/vite-plugin-svelte": "^3.0.0",
|
"@sveltejs/vite-plugin-svelte": "^3.0.0",
|
||||||
|
"@tailwindcss/forms": "^0.5.7",
|
||||||
|
"@tailwindcss/typography": "^0.5.13",
|
||||||
"@types/cookie": "^0.6.0",
|
"@types/cookie": "^0.6.0",
|
||||||
"@types/eslint": "^8.56.0",
|
"@types/eslint": "^8.56.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
||||||
@@ -30,22 +32,28 @@
|
|||||||
"eslint": "^8.56.0",
|
"eslint": "^8.56.0",
|
||||||
"eslint-config-prettier": "^9.1.0",
|
"eslint-config-prettier": "^9.1.0",
|
||||||
"eslint-plugin-svelte": "^2.35.1",
|
"eslint-plugin-svelte": "^2.35.1",
|
||||||
"postcss": "^8.4.38",
|
"postcss": "^8.4.39",
|
||||||
|
"postcss-load-config": "^5.1.0",
|
||||||
"prettier": "^3.1.1",
|
"prettier": "^3.1.1",
|
||||||
"prettier-plugin-svelte": "^3.1.2",
|
"prettier-plugin-svelte": "^3.1.2",
|
||||||
|
"supabase": "^1.178.2",
|
||||||
"svelte": "^4.2.8",
|
"svelte": "^4.2.8",
|
||||||
"svelte-check": "^3.6.2",
|
"svelte-check": "^3.6.2",
|
||||||
"tailwindcss": "^3.4.3",
|
"tailwindcss": "^3.4.3",
|
||||||
"tslib": "^2.6.2",
|
"tslib": "^2.6.2",
|
||||||
"typescript": "^5.3.3"
|
"typescript": "^5.3.3",
|
||||||
|
"vite": "^5.4.6",
|
||||||
|
"vite-plugin-tailwind-purgecss": "^0.3.3"
|
||||||
},
|
},
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@supabase/ssr": "^0.1.0",
|
"@supabase/ssr": "^0.4.0",
|
||||||
"@supabase/supabase-js": "^2.42.0",
|
"@supabase/supabase-js": "^2.44.2",
|
||||||
"stripe": "^15.4.0"
|
"stripe": "^15.4.0",
|
||||||
|
"ts-debounce": "^4.0.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.13.0"
|
"node": ">=18.13.0"
|
||||||
}
|
},
|
||||||
|
"packageManager": "pnpm@9.9.0+sha512.60c18acd138bff695d339be6ad13f7e936eea6745660d4cc4a776d5247c540d0edee1a563695c183a66eb917ef88f2b4feb1fc25f32a7adcadc7aaf3438e99c1"
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+6905
File diff suppressed because it is too large
Load Diff
Vendored
+10
-5
@@ -1,22 +1,27 @@
|
|||||||
// See https://kit.svelte.dev/docs/types#app
|
// See https://kit.svelte.dev/docs/types#app
|
||||||
// for information about these interfaces
|
// for information about these interfaces
|
||||||
// and what to do when importing types
|
// and what to do when importing types
|
||||||
import { SupabaseClient, Session, User } from '@supabase/supabase-js'
|
import { SupabaseClient, Session, User } from '@supabase/supabase-js';
|
||||||
|
import type { Database } from '$lib/types/supabase';
|
||||||
declare global {
|
declare global {
|
||||||
const __DATE__: string;
|
const __DATE__: string;
|
||||||
const __RELOAD_SW__: boolean;
|
const __RELOAD_SW__: boolean;
|
||||||
|
|
||||||
|
// Enable images with query params
|
||||||
|
declare module '*&img';
|
||||||
|
|
||||||
namespace App {
|
namespace App {
|
||||||
// interface Error {}
|
// interface Error {}
|
||||||
interface Locals {
|
interface Locals {
|
||||||
supabase: SupabaseClient
|
supabase: SupabaseClient<Database>;
|
||||||
safeGetSession(): Promise<{ session: Session | null; user: User | null }>
|
safeGetSession(): Promise<{ session: Session | null; user: User | null }>;
|
||||||
userid: string;
|
userid: string;
|
||||||
buildDate: string;
|
buildDate: string;
|
||||||
periodicUpdates: boolean;
|
periodicUpdates: boolean;
|
||||||
}
|
}
|
||||||
interface PageData {
|
interface PageData {
|
||||||
session: Session | null
|
session: Session | null;
|
||||||
}
|
}
|
||||||
// interface PageState {}
|
// interface PageState {}
|
||||||
// interface Platform {}
|
// interface Platform {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@
|
|||||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
%sveltekit.head%
|
%sveltekit.head%
|
||||||
<link rel="stylesheet" href="%sveltekit.assets%/output.css" />
|
|
||||||
</head>
|
</head>
|
||||||
<body data-sveltekit-preload-data="hover">
|
<body data-sveltekit-preload-data="hover">
|
||||||
<div style="display: contents">%sveltekit.body%</div>
|
<div style="display: contents">%sveltekit.body%</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
@tailwind base;
|
@tailwind base;
|
||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
@tailwind variants;
|
||||||
+30
-22
@@ -1,49 +1,57 @@
|
|||||||
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
|
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
|
||||||
import { createServerClient } from '@supabase/ssr';
|
import { createServerClient } from '@supabase/ssr';
|
||||||
import type { Handle } from '@sveltejs/kit';
|
import type { Handle } from '@sveltejs/kit';
|
||||||
|
import type { Database } from '$lib/types/supabase';
|
||||||
|
|
||||||
export const handle: Handle = async ({ event, resolve }) => {
|
export const handle: Handle = async ({ event, resolve }) => {
|
||||||
event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
|
event.locals.supabase = createServerClient<Database>(
|
||||||
cookies: {
|
PUBLIC_SUPABASE_URL,
|
||||||
get: (key) => event.cookies.get(key),
|
PUBLIC_SUPABASE_ANON_KEY,
|
||||||
/**
|
{
|
||||||
* Note: You have to add the `path` variable to the
|
cookies: {
|
||||||
* set and remove method due to sveltekit's cookie API
|
getAll: () => event.cookies.getAll(),
|
||||||
* requiring this to be set, setting the path to an empty string
|
/**
|
||||||
* will replicate previous/standard behaviour (https://kit.svelte.dev/docs/types#public-types-cookies)
|
* SvelteKit's cookies API requires `path` to be explicitly set in
|
||||||
*/
|
* the cookie options. Setting `path` to `/` replicates previous/
|
||||||
set: (key, value, options) => {
|
* standard behavior.
|
||||||
event.cookies.set(key, value, { ...options, path: '/' });
|
*/
|
||||||
},
|
setAll: (cookiesToSet) => {
|
||||||
remove: (key, options) => {
|
cookiesToSet.forEach(({ name, value, options }) => {
|
||||||
event.cookies.delete(key, { ...options, path: '/' });
|
event.cookies.set(name, value, { ...options, path: '/' });
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unlike `supabase.auth.getSession`, which is unsafe on the server because it
|
* Unlike `supabase.auth.getSession()`, which returns the session _without_
|
||||||
* doesn't validate the JWT, this function validates the JWT by first calling
|
* validating the JWT, this function also calls `getUser()` to validate the
|
||||||
* `getUser` and aborts early if the JWT signature is invalid.
|
* JWT before returning the session.
|
||||||
*/
|
*/
|
||||||
event.locals.safeGetSession = async () => {
|
event.locals.safeGetSession = async () => {
|
||||||
|
const {
|
||||||
|
data: { session }
|
||||||
|
} = await event.locals.supabase.auth.getSession();
|
||||||
|
if (!session) {
|
||||||
|
return { session: null, user: null };
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: { user },
|
data: { user },
|
||||||
error
|
error
|
||||||
} = await event.locals.supabase.auth.getUser();
|
} = await event.locals.supabase.auth.getUser();
|
||||||
if (error) {
|
if (error) {
|
||||||
|
// JWT validation has failed
|
||||||
return { session: null, user: null };
|
return { session: null, user: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
|
||||||
data: { session }
|
|
||||||
} = await event.locals.supabase.auth.getSession();
|
|
||||||
return { session, user };
|
return { session, user };
|
||||||
};
|
};
|
||||||
|
|
||||||
return resolve(event, {
|
return resolve(event, {
|
||||||
filterSerializedResponseHeaders(name) {
|
filterSerializedResponseHeaders(name) {
|
||||||
return name === 'content-range';
|
return name === 'content-range' || name === 'x-supabase-api-version';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { isBrowser } from '@supabase/ssr';
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
export let cookiesAccepted;
|
export let cookiesAccepted;
|
||||||
let showBanner = !cookiesAccepted;
|
let showBanner = false;
|
||||||
$: showBanner = !cookiesAccepted;
|
|
||||||
|
onMount(() => {
|
||||||
|
if (!cookiesAccepted) {
|
||||||
|
const storedValue = localStorage.getItem('cookiesAccepted');
|
||||||
|
showBanner = storedValue !== 'true';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const acceptCookies = () => {
|
const acceptCookies = () => {
|
||||||
if (isBrowser()) {
|
localStorage.setItem('cookiesAccepted', 'true');
|
||||||
localStorage.setItem('cookiesAccepted', 'true');
|
showBanner = false;
|
||||||
showBanner = false;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if showBanner}
|
{#if showBanner}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
export let supabase: any;
|
||||||
|
|
||||||
|
let error = '',
|
||||||
|
message = '',
|
||||||
|
loading = false,
|
||||||
|
email = '';
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
error = '';
|
||||||
|
message = '';
|
||||||
|
loading = true;
|
||||||
|
|
||||||
|
const { error: err } = await supabase.auth.signInWithOtp({ email });
|
||||||
|
|
||||||
|
if (err) error = err.message;
|
||||||
|
else message = 'Check your email for the magic link.';
|
||||||
|
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="p-4">
|
||||||
|
<div class="component">
|
||||||
|
<div class="container">
|
||||||
|
<form on:submit|preventDefault={submit}>
|
||||||
|
<label class="input input-bordered flex items-center gap-2">
|
||||||
|
Email
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="email"
|
||||||
|
class="grow"
|
||||||
|
placeholder="Your email address"
|
||||||
|
bind:value={email}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button class="btn btn-active btn-primary w-full" on:click disabled={loading}
|
||||||
|
>Send magic link</button
|
||||||
|
>
|
||||||
|
|
||||||
|
{#if message}
|
||||||
|
<div class="text-success">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if error}
|
||||||
|
<div class="text-error">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.component {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
<div tabindex="0" role="button" class="">Parent</div>
|
<div tabindex="0" role="button" class="">Parent</div>
|
||||||
{:else}
|
{:else}
|
||||||
<details>
|
<details>
|
||||||
<summary>Parent</summary>
|
<summary class="flex items-center"><span class="mr-1">▼</span>Parent </summary>
|
||||||
</details>
|
</details>
|
||||||
{/if}
|
{/if}
|
||||||
<ul
|
<ul
|
||||||
@@ -20,4 +20,4 @@
|
|||||||
<li><a href="/">Submenu 2</a></li>
|
<li><a href="/">Submenu 2</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="/">Item 3</a></li>
|
<li><a href="/tools/exampleproduct">Example Product</a></li>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
|
||||||
let email = '';
|
let email = '';
|
||||||
let password = '';
|
let password = '';
|
||||||
|
|
||||||
@@ -12,7 +13,7 @@
|
|||||||
password: password,
|
password: password,
|
||||||
options: {
|
options: {
|
||||||
// Redirect URL after successful sign-up
|
// Redirect URL after successful sign-up
|
||||||
redirectTo: '/welcome'
|
redirectTo: '/account'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { formatCurrency } from '$lib/utils/currency';
|
import { formatCurrency } from '$lib/utils/currency';
|
||||||
export let imgAlt = '';
|
export let imgAlt = '';
|
||||||
export let imgSrc = '';
|
export let imgSrc = '';
|
||||||
// export let itemCategoryDescription = '';
|
export let itemCategoryDescription = '';
|
||||||
export let itemName = '';
|
export let itemName = '';
|
||||||
export let price = 0;
|
export let price = 0;
|
||||||
export let quantity = 0;
|
export let quantity = 0;
|
||||||
@@ -20,11 +20,11 @@
|
|||||||
<h5 class="font-semibold text-xl leading-8 text-black max-[550px]:text-center">
|
<h5 class="font-semibold text-xl leading-8 text-black max-[550px]:text-center">
|
||||||
{itemName}
|
{itemName}
|
||||||
</h5>
|
</h5>
|
||||||
<!-- <p
|
<p
|
||||||
class="font-normal text-lg leading-8 text-gray-500 my-2 min-[550px]:my-3 max-[550px]:text-center"
|
class="font-normal text-lg leading-8 text-gray-500 my-2 min-[550px]:my-3 max-[550px]:text-center"
|
||||||
>
|
>
|
||||||
{itemCategoryDescription}
|
{itemCategoryDescription}
|
||||||
</p> -->
|
</p>
|
||||||
|
|
||||||
<div class="flex items-center">
|
<div class="flex items-center">
|
||||||
<h6
|
<h6
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
export let product;
|
export let product;
|
||||||
|
|
||||||
|
const defaultPrice = product.prices[0];
|
||||||
|
const isSubscription = defaultPrice.type === 'recurring';
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<a href="/products/{product.id}" class="max-w-[384px] mx-auto">
|
<a href="/products/{product.id}" class="max-w-[384px] mx-auto">
|
||||||
@@ -13,7 +16,7 @@
|
|||||||
<div class="mt-5 flex items-center justify-between">
|
<div class="mt-5 flex items-center justify-between">
|
||||||
<div class="">
|
<div class="">
|
||||||
<h6 class="font-medium text-xl leading-8 text-black mb-2">{product.name}</h6>
|
<h6 class="font-medium text-xl leading-8 text-black mb-2">{product.name}</h6>
|
||||||
<h6 class="font-semibold text-xl leading-8 text-indigo-600">£{product.actualPrice}</h6>
|
<h6 class="font-semibold text-xl leading-8 text-indigo-600">£{product.actualPrice} {isSubscription ? `/ ${defaultPrice.interval}` : ''}</h6>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
class="p-2 min-[400px]:p-4 rounded-full bg-white border border-gray-300 flex items-center justify-center group shadow-sm shadow-transparent transition-all duration-500 hover:shadow-gray-200 hover:border-gray-400 hover:bg-gray-50"
|
class="p-2 min-[400px]:p-4 rounded-full bg-white border border-gray-300 flex items-center justify-center group shadow-sm shadow-transparent transition-all duration-500 hover:shadow-gray-200 hover:border-gray-400 hover:bg-gray-50"
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import Stripe from 'stripe';
|
||||||
|
|
||||||
|
export type ProductInfo = {
|
||||||
|
product: Stripe.Product;
|
||||||
|
price: Stripe.Price;
|
||||||
|
isSubscription: boolean;
|
||||||
|
};
|
||||||
Vendored
+459
@@ -0,0 +1,459 @@
|
|||||||
|
export type Json =
|
||||||
|
| string
|
||||||
|
| number
|
||||||
|
| boolean
|
||||||
|
| null
|
||||||
|
| { [key: string]: Json | undefined }
|
||||||
|
| Json[]
|
||||||
|
|
||||||
|
export type Database = {
|
||||||
|
graphql_public: {
|
||||||
|
Tables: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
Views: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
Functions: {
|
||||||
|
graphql: {
|
||||||
|
Args: {
|
||||||
|
operationName?: string
|
||||||
|
query?: string
|
||||||
|
variables?: Json
|
||||||
|
extensions?: Json
|
||||||
|
}
|
||||||
|
Returns: Json
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Enums: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
CompositeTypes: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public: {
|
||||||
|
Tables: {
|
||||||
|
credit_transactions: {
|
||||||
|
Row: {
|
||||||
|
created_at: string
|
||||||
|
credits_change: number
|
||||||
|
description: string | null
|
||||||
|
id: string
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
created_at?: string
|
||||||
|
credits_change: number
|
||||||
|
description?: string | null
|
||||||
|
id?: string
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
created_at?: string
|
||||||
|
credits_change?: number
|
||||||
|
description?: string | null
|
||||||
|
id?: string
|
||||||
|
user_id?: string
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "credit_transactions_user_id_fkey"
|
||||||
|
columns: ["user_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "users"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
customers: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
stripe_customer_id: string | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
id: string
|
||||||
|
stripe_customer_id?: string | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
id?: string
|
||||||
|
stripe_customer_id?: string | null
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "customers_id_fkey"
|
||||||
|
columns: ["id"]
|
||||||
|
isOneToOne: true
|
||||||
|
referencedRelation: "users"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
prices: {
|
||||||
|
Row: {
|
||||||
|
active: boolean | null
|
||||||
|
currency: string | null
|
||||||
|
description: string | null
|
||||||
|
id: string
|
||||||
|
interval: Database["public"]["Enums"]["pricing_plan_interval"] | null
|
||||||
|
interval_count: number | null
|
||||||
|
metadata: Json | null
|
||||||
|
product_id: string
|
||||||
|
trial_period_days: number | null
|
||||||
|
type: Database["public"]["Enums"]["pricing_type"] | null
|
||||||
|
unit_amount: number | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
active?: boolean | null
|
||||||
|
currency?: string | null
|
||||||
|
description?: string | null
|
||||||
|
id: string
|
||||||
|
interval?: Database["public"]["Enums"]["pricing_plan_interval"] | null
|
||||||
|
interval_count?: number | null
|
||||||
|
metadata?: Json | null
|
||||||
|
product_id: string
|
||||||
|
trial_period_days?: number | null
|
||||||
|
type?: Database["public"]["Enums"]["pricing_type"] | null
|
||||||
|
unit_amount?: number | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
active?: boolean | null
|
||||||
|
currency?: string | null
|
||||||
|
description?: string | null
|
||||||
|
id?: string
|
||||||
|
interval?: Database["public"]["Enums"]["pricing_plan_interval"] | null
|
||||||
|
interval_count?: number | null
|
||||||
|
metadata?: Json | null
|
||||||
|
product_id?: string
|
||||||
|
trial_period_days?: number | null
|
||||||
|
type?: Database["public"]["Enums"]["pricing_type"] | null
|
||||||
|
unit_amount?: number | null
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "prices_product_id_fkey"
|
||||||
|
columns: ["product_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "products"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
products: {
|
||||||
|
Row: {
|
||||||
|
active: boolean | null
|
||||||
|
created_at: string
|
||||||
|
description: string | null
|
||||||
|
features: string[] | null
|
||||||
|
id: string
|
||||||
|
images: string[] | null
|
||||||
|
metadata: Json | null
|
||||||
|
name: string | null
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
active?: boolean | null
|
||||||
|
created_at?: string
|
||||||
|
description?: string | null
|
||||||
|
features?: string[] | null
|
||||||
|
id: string
|
||||||
|
images?: string[] | null
|
||||||
|
metadata?: Json | null
|
||||||
|
name?: string | null
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
active?: boolean | null
|
||||||
|
created_at?: string
|
||||||
|
description?: string | null
|
||||||
|
features?: string[] | null
|
||||||
|
id?: string
|
||||||
|
images?: string[] | null
|
||||||
|
metadata?: Json | null
|
||||||
|
name?: string | null
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
Relationships: []
|
||||||
|
}
|
||||||
|
purchases: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
price_id: string
|
||||||
|
product_id: string
|
||||||
|
purchased_at: string
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
id?: string
|
||||||
|
price_id: string
|
||||||
|
product_id: string
|
||||||
|
purchased_at?: string
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
id?: string
|
||||||
|
price_id?: string
|
||||||
|
product_id?: string
|
||||||
|
purchased_at?: string
|
||||||
|
user_id?: string
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "purchases_price_id_fkey"
|
||||||
|
columns: ["price_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "prices"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "purchases_product_id_fkey"
|
||||||
|
columns: ["product_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "products"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "purchases_user_id_fkey"
|
||||||
|
columns: ["user_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "users"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
subscriptions: {
|
||||||
|
Row: {
|
||||||
|
cancel_at: string | null
|
||||||
|
cancel_at_period_end: boolean | null
|
||||||
|
canceled_at: string | null
|
||||||
|
created: string
|
||||||
|
current_period_end: string
|
||||||
|
current_period_start: string
|
||||||
|
ended_at: string | null
|
||||||
|
id: string
|
||||||
|
metadata: Json | null
|
||||||
|
price_id: string | null
|
||||||
|
product_id: string
|
||||||
|
quantity: number | null
|
||||||
|
status: Database["public"]["Enums"]["subscription_status"] | null
|
||||||
|
trial_end: string | null
|
||||||
|
trial_start: string | null
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
cancel_at?: string | null
|
||||||
|
cancel_at_period_end?: boolean | null
|
||||||
|
canceled_at?: string | null
|
||||||
|
created?: string
|
||||||
|
current_period_end?: string
|
||||||
|
current_period_start?: string
|
||||||
|
ended_at?: string | null
|
||||||
|
id: string
|
||||||
|
metadata?: Json | null
|
||||||
|
price_id?: string | null
|
||||||
|
product_id: string
|
||||||
|
quantity?: number | null
|
||||||
|
status?: Database["public"]["Enums"]["subscription_status"] | null
|
||||||
|
trial_end?: string | null
|
||||||
|
trial_start?: string | null
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
cancel_at?: string | null
|
||||||
|
cancel_at_period_end?: boolean | null
|
||||||
|
canceled_at?: string | null
|
||||||
|
created?: string
|
||||||
|
current_period_end?: string
|
||||||
|
current_period_start?: string
|
||||||
|
ended_at?: string | null
|
||||||
|
id?: string
|
||||||
|
metadata?: Json | null
|
||||||
|
price_id?: string | null
|
||||||
|
product_id?: string
|
||||||
|
quantity?: number | null
|
||||||
|
status?: Database["public"]["Enums"]["subscription_status"] | null
|
||||||
|
trial_end?: string | null
|
||||||
|
trial_start?: string | null
|
||||||
|
user_id?: string
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "subscriptions_price_id_fkey"
|
||||||
|
columns: ["price_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "prices"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "subscriptions_product_id_fkey"
|
||||||
|
columns: ["product_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "products"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: "subscriptions_user_id_fkey"
|
||||||
|
columns: ["user_id"]
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: "users"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
user_credits: {
|
||||||
|
Row: {
|
||||||
|
credits_remaining: number
|
||||||
|
last_updated: string
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
credits_remaining?: number
|
||||||
|
last_updated?: string
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
credits_remaining?: number
|
||||||
|
last_updated?: string
|
||||||
|
user_id?: string
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "user_credits_user_id_fkey"
|
||||||
|
columns: ["user_id"]
|
||||||
|
isOneToOne: true
|
||||||
|
referencedRelation: "users"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
users: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
name: string | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
id: string
|
||||||
|
name?: string | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
id?: string
|
||||||
|
name?: string | null
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: "users_id_fkey"
|
||||||
|
columns: ["id"]
|
||||||
|
isOneToOne: true
|
||||||
|
referencedRelation: "users"
|
||||||
|
referencedColumns: ["id"]
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Views: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
Functions: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
Enums: {
|
||||||
|
pricing_plan_interval: "day" | "week" | "month" | "year"
|
||||||
|
pricing_type: "one_time" | "recurring"
|
||||||
|
subscription_status:
|
||||||
|
| "trialing"
|
||||||
|
| "active"
|
||||||
|
| "canceled"
|
||||||
|
| "incomplete"
|
||||||
|
| "incomplete_expired"
|
||||||
|
| "past_due"
|
||||||
|
| "unpaid"
|
||||||
|
| "paused"
|
||||||
|
}
|
||||||
|
CompositeTypes: {
|
||||||
|
[_ in never]: never
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PublicSchema = Database[Extract<keyof Database, "public">]
|
||||||
|
|
||||||
|
export type Tables<
|
||||||
|
PublicTableNameOrOptions extends
|
||||||
|
| keyof (PublicSchema["Tables"] & PublicSchema["Views"])
|
||||||
|
| { schema: keyof Database },
|
||||||
|
TableName extends PublicTableNameOrOptions extends { schema: keyof Database }
|
||||||
|
? keyof (Database[PublicTableNameOrOptions["schema"]]["Tables"] &
|
||||||
|
Database[PublicTableNameOrOptions["schema"]]["Views"])
|
||||||
|
: never = never,
|
||||||
|
> = PublicTableNameOrOptions extends { schema: keyof Database }
|
||||||
|
? (Database[PublicTableNameOrOptions["schema"]]["Tables"] &
|
||||||
|
Database[PublicTableNameOrOptions["schema"]]["Views"])[TableName] extends {
|
||||||
|
Row: infer R
|
||||||
|
}
|
||||||
|
? R
|
||||||
|
: never
|
||||||
|
: PublicTableNameOrOptions extends keyof (PublicSchema["Tables"] &
|
||||||
|
PublicSchema["Views"])
|
||||||
|
? (PublicSchema["Tables"] &
|
||||||
|
PublicSchema["Views"])[PublicTableNameOrOptions] extends {
|
||||||
|
Row: infer R
|
||||||
|
}
|
||||||
|
? R
|
||||||
|
: never
|
||||||
|
: never
|
||||||
|
|
||||||
|
export type TablesInsert<
|
||||||
|
PublicTableNameOrOptions extends
|
||||||
|
| keyof PublicSchema["Tables"]
|
||||||
|
| { schema: keyof Database },
|
||||||
|
TableName extends PublicTableNameOrOptions extends { schema: keyof Database }
|
||||||
|
? keyof Database[PublicTableNameOrOptions["schema"]]["Tables"]
|
||||||
|
: never = never,
|
||||||
|
> = PublicTableNameOrOptions extends { schema: keyof Database }
|
||||||
|
? Database[PublicTableNameOrOptions["schema"]]["Tables"][TableName] extends {
|
||||||
|
Insert: infer I
|
||||||
|
}
|
||||||
|
? I
|
||||||
|
: never
|
||||||
|
: PublicTableNameOrOptions extends keyof PublicSchema["Tables"]
|
||||||
|
? PublicSchema["Tables"][PublicTableNameOrOptions] extends {
|
||||||
|
Insert: infer I
|
||||||
|
}
|
||||||
|
? I
|
||||||
|
: never
|
||||||
|
: never
|
||||||
|
|
||||||
|
export type TablesUpdate<
|
||||||
|
PublicTableNameOrOptions extends
|
||||||
|
| keyof PublicSchema["Tables"]
|
||||||
|
| { schema: keyof Database },
|
||||||
|
TableName extends PublicTableNameOrOptions extends { schema: keyof Database }
|
||||||
|
? keyof Database[PublicTableNameOrOptions["schema"]]["Tables"]
|
||||||
|
: never = never,
|
||||||
|
> = PublicTableNameOrOptions extends { schema: keyof Database }
|
||||||
|
? Database[PublicTableNameOrOptions["schema"]]["Tables"][TableName] extends {
|
||||||
|
Update: infer U
|
||||||
|
}
|
||||||
|
? U
|
||||||
|
: never
|
||||||
|
: PublicTableNameOrOptions extends keyof PublicSchema["Tables"]
|
||||||
|
? PublicSchema["Tables"][PublicTableNameOrOptions] extends {
|
||||||
|
Update: infer U
|
||||||
|
}
|
||||||
|
? U
|
||||||
|
: never
|
||||||
|
: never
|
||||||
|
|
||||||
|
export type Enums<
|
||||||
|
PublicEnumNameOrOptions extends
|
||||||
|
| keyof PublicSchema["Enums"]
|
||||||
|
| { schema: keyof Database },
|
||||||
|
EnumName extends PublicEnumNameOrOptions extends { schema: keyof Database }
|
||||||
|
? keyof Database[PublicEnumNameOrOptions["schema"]]["Enums"]
|
||||||
|
: never = never,
|
||||||
|
> = PublicEnumNameOrOptions extends { schema: keyof Database }
|
||||||
|
? Database[PublicEnumNameOrOptions["schema"]]["Enums"][EnumName]
|
||||||
|
: PublicEnumNameOrOptions extends keyof PublicSchema["Enums"]
|
||||||
|
? PublicSchema["Enums"][PublicEnumNameOrOptions]
|
||||||
|
: never
|
||||||
|
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import Stripe from 'stripe'
|
||||||
|
import { STRIPE_SECRET_KEY } from '$env/static/private'
|
||||||
|
|
||||||
|
export const stripe = new Stripe(STRIPE_SECRET_KEY)
|
||||||
@@ -0,0 +1,499 @@
|
|||||||
|
import { createClient } from '@supabase/supabase-js';
|
||||||
|
import stripe from 'stripe';
|
||||||
|
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';
|
||||||
|
|
||||||
|
const toDateTime = (secs: number) => {
|
||||||
|
const t = new Date(+0); // Unix epoch start.
|
||||||
|
t.setSeconds(secs);
|
||||||
|
return t;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Product = Tables<'products'>;
|
||||||
|
type Price = Tables<'prices'>;
|
||||||
|
|
||||||
|
// Change to control trial period length
|
||||||
|
const TRIAL_PERIOD_DAYS = 0;
|
||||||
|
|
||||||
|
// Note: supabaseAdmin uses the SERVICE_ROLE_KEY which you must only use in a secure server-side context
|
||||||
|
// as it has admin privileges and overwrites RLS policies!
|
||||||
|
const supabaseAdmin = createClient<Database>(
|
||||||
|
PUBLIC_SUPABASE_URL || '',
|
||||||
|
SUPABASE_SERVICE_ROLE_KEY || ''
|
||||||
|
);
|
||||||
|
|
||||||
|
const upsertProductRecord = async (product: stripe.Product) => {
|
||||||
|
const productData: Product = {
|
||||||
|
id: product.id,
|
||||||
|
active: product.active,
|
||||||
|
name: product.name,
|
||||||
|
description: product.description ?? null,
|
||||||
|
features: product.marketing_features.map(({ name }) => name || '').filter((name) => !!name),
|
||||||
|
images: product.images ?? null,
|
||||||
|
metadata: product.metadata,
|
||||||
|
created_at: new Date(product.created * 1000).toISOString(),
|
||||||
|
updated_at: new Date(product.updated * 1000).toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
|
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}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const upsertPriceRecord = async (price: stripe.Price, retryCount = 0, maxRetries = 3) => {
|
||||||
|
const priceData: Price = {
|
||||||
|
id: price.id,
|
||||||
|
product_id: typeof price.product === 'string' ? price.product : '',
|
||||||
|
active: price.active,
|
||||||
|
currency: price.currency,
|
||||||
|
description: price.nickname ?? null,
|
||||||
|
metadata: price.metadata,
|
||||||
|
type: price.type,
|
||||||
|
unit_amount: price.unit_amount ?? null,
|
||||||
|
interval: price.recurring?.interval ?? null,
|
||||||
|
interval_count: price.recurring?.interval_count ?? null,
|
||||||
|
trial_period_days: price.recurring?.trial_period_days ?? TRIAL_PERIOD_DAYS
|
||||||
|
};
|
||||||
|
|
||||||
|
const { error: upsertError } = await supabaseAdmin.from('prices').upsert([priceData]);
|
||||||
|
|
||||||
|
if (upsertError?.message.includes('foreign key constraint')) {
|
||||||
|
if (retryCount < maxRetries) {
|
||||||
|
console.log(`Retry attempt ${retryCount + 1} for price ID: ${price.id}`);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
await upsertPriceRecord(price, retryCount + 1, maxRetries);
|
||||||
|
} else {
|
||||||
|
throw new Error(
|
||||||
|
`Price insert/update failed after ${maxRetries} retries: ${upsertError.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (upsertError) {
|
||||||
|
throw new Error(`Price insert/update failed: ${upsertError.message}`);
|
||||||
|
} else {
|
||||||
|
console.log(`Price inserted/updated: ${price.id}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteProductRecord = async (product: stripe.Product) => {
|
||||||
|
const { error: deletionError } = await supabaseAdmin
|
||||||
|
.from('products')
|
||||||
|
.delete()
|
||||||
|
.eq('id', product.id);
|
||||||
|
if (deletionError) throw new Error(`Product deletion failed: ${deletionError.message}`);
|
||||||
|
console.log(`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}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const upsertCustomerToSupabase = async (uuid: string, customerId: string) => {
|
||||||
|
const { error: upsertError } = await supabaseAdmin
|
||||||
|
.from('customers')
|
||||||
|
.upsert([{ id: uuid, stripe_customer_id: customerId }]);
|
||||||
|
|
||||||
|
if (upsertError)
|
||||||
|
throw new Error(`Supabase customer record creation failed: ${upsertError.message}`);
|
||||||
|
|
||||||
|
return customerId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createCustomerInStripe = async (uuid: string, email: string) => {
|
||||||
|
const customerData = { metadata: { supabaseUUID: uuid }, email: email };
|
||||||
|
const newCustomer = await stripeClient.customers.create(customerData);
|
||||||
|
if (!newCustomer) throw new Error('Stripe customer creation failed.');
|
||||||
|
|
||||||
|
return newCustomer.id;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStripeCustomerId = async (email: string, uuid: string) => {
|
||||||
|
const { data: existingSupabaseCustomer, error: queryError } = await supabaseAdmin
|
||||||
|
.from('customers')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', uuid)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (queryError) {
|
||||||
|
throw new Error(`Supabase customer lookup failed: ${queryError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let stripeCustomerId: string | undefined;
|
||||||
|
if (existingSupabaseCustomer?.stripe_customer_id) {
|
||||||
|
const existingStripeCustomer = await stripeClient.customers.retrieve(
|
||||||
|
existingSupabaseCustomer.stripe_customer_id
|
||||||
|
);
|
||||||
|
stripeCustomerId = existingStripeCustomer.id;
|
||||||
|
} else {
|
||||||
|
const stripeCustomers = await stripeClient.customers.list({ email: email });
|
||||||
|
stripeCustomerId = stripeCustomers.data.length > 0 ? stripeCustomers.data[0].id : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return stripeCustomerId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createOrRetrieveCustomer = async ({ email, uuid }: { email: string; uuid: string }) => {
|
||||||
|
// Check if the customer already exists in Supabase
|
||||||
|
const { data: existingSupabaseCustomer, error: queryError } = await supabaseAdmin
|
||||||
|
.from('customers')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', uuid)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (queryError) {
|
||||||
|
throw new Error(`Supabase customer lookup failed: ${queryError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieve the Stripe customer ID using the Supabase customer ID, with email fallback
|
||||||
|
let stripeCustomerId: string | undefined;
|
||||||
|
if (existingSupabaseCustomer?.stripe_customer_id) {
|
||||||
|
const existingStripeCustomer = await stripeClient.customers.retrieve(
|
||||||
|
existingSupabaseCustomer.stripe_customer_id
|
||||||
|
);
|
||||||
|
stripeCustomerId = existingStripeCustomer.id;
|
||||||
|
} else {
|
||||||
|
// If Stripe ID is missing from Supabase, try to retrieve Stripe customer ID by email
|
||||||
|
const stripeCustomers = await stripeClient.customers.list({ email: email });
|
||||||
|
stripeCustomerId = stripeCustomers.data.length > 0 ? stripeCustomers.data[0].id : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If still no stripeCustomerId, create a new customer in Stripe
|
||||||
|
const stripeIdToInsert = stripeCustomerId
|
||||||
|
? stripeCustomerId
|
||||||
|
: await createCustomerInStripe(uuid, email);
|
||||||
|
if (!stripeIdToInsert) throw new Error('Stripe customer creation failed.');
|
||||||
|
|
||||||
|
if (existingSupabaseCustomer && stripeCustomerId) {
|
||||||
|
// If Supabase has a record but doesn't match Stripe, update Supabase record
|
||||||
|
if (existingSupabaseCustomer.stripe_customer_id !== stripeCustomerId) {
|
||||||
|
const { error: updateError } = await supabaseAdmin
|
||||||
|
.from('customers')
|
||||||
|
.update({ stripe_customer_id: stripeCustomerId })
|
||||||
|
.eq('id', uuid);
|
||||||
|
|
||||||
|
if (updateError)
|
||||||
|
throw new Error(`Supabase customer record update failed: ${updateError.message}`);
|
||||||
|
console.warn(`Supabase customer record mismatched Stripe ID. Supabase record updated.`);
|
||||||
|
}
|
||||||
|
// If Supabase has a record and matches Stripe, return Stripe customer ID
|
||||||
|
return stripeCustomerId;
|
||||||
|
} else {
|
||||||
|
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
|
||||||
|
const upsertedStripeCustomer = await upsertCustomerToSupabase(uuid, stripeIdToInsert);
|
||||||
|
if (!upsertedStripeCustomer) throw new Error('Supabase customer record creation failed.');
|
||||||
|
|
||||||
|
return upsertedStripeCustomer;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copies the billing details from the payment method to the customer object.
|
||||||
|
*/
|
||||||
|
const copyBillingDetailsToCustomer = async (uuid: string, payment_method: stripe.PaymentMethod) => {
|
||||||
|
//Todo: check this assertion
|
||||||
|
const customer = payment_method.customer as string;
|
||||||
|
const { name, phone, address } = payment_method.billing_details;
|
||||||
|
if (!name || !phone || !address) return;
|
||||||
|
|
||||||
|
await stripeClient.customers.update(customer, { name, phone, address });
|
||||||
|
const { error: updateError } = await supabaseAdmin
|
||||||
|
.from('users')
|
||||||
|
.update({
|
||||||
|
billing_address: { ...address },
|
||||||
|
payment_method: { ...payment_method[payment_method.type] }
|
||||||
|
})
|
||||||
|
.eq('id', uuid);
|
||||||
|
if (updateError) throw new Error(`Customer update failed: ${updateError.message}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const manageSubscriptionStatusChange = async (
|
||||||
|
subscriptionId: string,
|
||||||
|
customerId: string,
|
||||||
|
createAction = false
|
||||||
|
) => {
|
||||||
|
// Get customer's UUID from mapping table.
|
||||||
|
const { data: customerData, error: noCustomerError } = await supabaseAdmin
|
||||||
|
.from('customers')
|
||||||
|
.select('id')
|
||||||
|
.eq('stripe_customer_id', customerId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (noCustomerError) throw new Error(`Customer lookup failed: ${noCustomerError.message}`);
|
||||||
|
|
||||||
|
const { id: uuid } = customerData!;
|
||||||
|
|
||||||
|
const subscription = await stripeClient.subscriptions.retrieve(subscriptionId, {
|
||||||
|
expand: ['default_payment_method']
|
||||||
|
});
|
||||||
|
// Upsert the latest status of the subscription object.
|
||||||
|
const subscriptionData: TablesInsert<'subscriptions'> = {
|
||||||
|
id: subscription.id,
|
||||||
|
user_id: uuid,
|
||||||
|
metadata: subscription.metadata,
|
||||||
|
status: subscription.status,
|
||||||
|
product_id: subscription.items.data[0].price.product as string,
|
||||||
|
price_id: subscription.items.data[0].price.id,
|
||||||
|
quantity: 1, //subscription.quantity,
|
||||||
|
cancel_at_period_end: subscription.cancel_at_period_end,
|
||||||
|
cancel_at: subscription.cancel_at ? toDateTime(subscription.cancel_at).toISOString() : null,
|
||||||
|
canceled_at: subscription.canceled_at
|
||||||
|
? toDateTime(subscription.canceled_at).toISOString()
|
||||||
|
: null,
|
||||||
|
current_period_start: toDateTime(subscription.current_period_start).toISOString(),
|
||||||
|
current_period_end: toDateTime(subscription.current_period_end).toISOString(),
|
||||||
|
created: toDateTime(subscription.created).toISOString(),
|
||||||
|
ended_at: subscription.ended_at ? toDateTime(subscription.ended_at).toISOString() : null,
|
||||||
|
trial_start: subscription.trial_start
|
||||||
|
? toDateTime(subscription.trial_start).toISOString()
|
||||||
|
: null,
|
||||||
|
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}]`);
|
||||||
|
|
||||||
|
// // 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.
|
||||||
|
// if (createAction && subscription.default_payment_method && uuid) {
|
||||||
|
// await copyBillingDetailsToCustomer(
|
||||||
|
// uuid,
|
||||||
|
// subscription.default_payment_method as stripe.PaymentMethod
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
};
|
||||||
|
|
||||||
|
const recordProductPurchase = async (userId: string, productId: string, priceId: string) => {
|
||||||
|
console.log(
|
||||||
|
`Recording product purchase for user [${userId}] and product [${productId}] with price [${priceId}]`
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await supabaseAdmin
|
||||||
|
.from('purchases')
|
||||||
|
.insert([{ user_id: userId, product_id: productId, price_id: priceId }]);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Failed to record product purchase: ${error.message}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`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);
|
||||||
|
|
||||||
|
if (purchaseError) throw new Error(purchaseError.message);
|
||||||
|
|
||||||
|
if (purchases && purchases.length > 0) {
|
||||||
|
// User has purchased the product
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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']);
|
||||||
|
|
||||||
|
if (subError) throw new Error(subError.message);
|
||||||
|
|
||||||
|
if (subscriptions && subscriptions.length > 0) {
|
||||||
|
// User has an active subscription
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateInput = (userId: string, credits: number, description: string) => {
|
||||||
|
if (!userId) throw new Error('User ID is required');
|
||||||
|
if (credits <= 0) throw new Error('Credits must be greater than zero');
|
||||||
|
if (!description) throw new Error('Description is required');
|
||||||
|
};
|
||||||
|
|
||||||
|
const logCreditTransaction = async (userId: string, creditsChange: number, description: string) => {
|
||||||
|
const { error } = await supabaseAdmin.from('credit_transactions').insert({
|
||||||
|
user_id: userId,
|
||||||
|
credits_change: creditsChange,
|
||||||
|
description,
|
||||||
|
created_at: new Date().toISOString()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Error logging credit transaction: ${error.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateUserCredits = async (userId: string, creditsChange: number, description: string) => {
|
||||||
|
validateInput(userId, Math.abs(creditsChange), description);
|
||||||
|
|
||||||
|
const { data: creditData, error: fetchError } = await supabaseAdmin
|
||||||
|
.from('user_credits')
|
||||||
|
.select('credits_remaining, last_updated')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (fetchError) {
|
||||||
|
throw new Error(`Error fetching credits: ${fetchError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const newCreditTotal = (creditData?.credits_remaining || 0) + creditsChange;
|
||||||
|
|
||||||
|
if (newCreditTotal < 0) {
|
||||||
|
throw new Error('Insufficient credits');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { error: upsertError } = await supabaseAdmin
|
||||||
|
.from('user_credits')
|
||||||
|
.upsert(
|
||||||
|
{
|
||||||
|
user_id: userId,
|
||||||
|
credits_remaining: newCreditTotal,
|
||||||
|
last_updated: new Date().toISOString()
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onConflict: 'user_id'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.eq('last_updated', creditData?.last_updated); // Optimistic concurrency control
|
||||||
|
|
||||||
|
if (upsertError) {
|
||||||
|
throw new Error(`Error updating credits: ${upsertError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await logCreditTransaction(userId, creditsChange, description);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`${creditsChange > 0 ? 'Added' : 'Deducted'} ${Math.abs(creditsChange)} credits to user [${userId}]`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const addCredits = async (userId: string, creditsToAdd: number, description: string) => {
|
||||||
|
try {
|
||||||
|
await updateUserCredits(userId, creditsToAdd, description);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deductCredits = async (userId: string, creditsToDeduct: number, description: string) => {
|
||||||
|
try {
|
||||||
|
await updateUserCredits(userId, -creditsToDeduct, description);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getUserCredits = async (userId: string) => {
|
||||||
|
if (!userId) throw new Error('User ID is required');
|
||||||
|
|
||||||
|
// Fetch the user's credits from the user_credits table
|
||||||
|
const { data: creditData, error } = await supabaseAdmin
|
||||||
|
.from('user_credits')
|
||||||
|
.select('credits_remaining')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error && error.code !== 'PGRST116') {
|
||||||
|
// Code 'PGRST116' represents no rows found
|
||||||
|
throw new Error(`Error fetching credits: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!creditData) {
|
||||||
|
// If no row exists in the user_credits table, insert a new row for the user
|
||||||
|
const { error: insertError } = await supabaseAdmin.from('user_credits').insert({
|
||||||
|
user_id: userId,
|
||||||
|
credits_remaining: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
if (insertError) {
|
||||||
|
throw new Error(`Error creating user credits: ${insertError.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return creditData.credits_remaining;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ProductWithPrices = Product & {
|
||||||
|
prices: Price[];
|
||||||
|
actualPrice?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getActiveProductsWithPrices = async (limit = 10, offset = 0) => {
|
||||||
|
const {
|
||||||
|
data: products,
|
||||||
|
error,
|
||||||
|
count
|
||||||
|
} = await supabaseAdmin
|
||||||
|
.from('products')
|
||||||
|
.select('*, prices(*)', { count: 'exact' })
|
||||||
|
.eq('active', true)
|
||||||
|
.order('name', { ascending: true })
|
||||||
|
.range(offset, offset + limit - 1);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Error fetching products: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const product of products as ProductWithPrices[]) {
|
||||||
|
if (product.prices && product.prices.length > 0) {
|
||||||
|
// Assuming the default price is the first one
|
||||||
|
const defaultPrice = product.prices[0];
|
||||||
|
product.actualPrice = defaultPrice.unit_amount! / 100;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { products: products as ProductWithPrices[], count };
|
||||||
|
};
|
||||||
|
|
||||||
|
const getProductById = async (productId: string) => {
|
||||||
|
const { data: product, error } = await supabaseAdmin
|
||||||
|
.from('products')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', productId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Error fetching product: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return product as Product;
|
||||||
|
};
|
||||||
|
|
||||||
|
export {
|
||||||
|
upsertProductRecord,
|
||||||
|
upsertPriceRecord,
|
||||||
|
deleteProductRecord,
|
||||||
|
deletePriceRecord,
|
||||||
|
createOrRetrieveCustomer,
|
||||||
|
manageSubscriptionStatusChange,
|
||||||
|
recordProductPurchase,
|
||||||
|
hasProductAccess,
|
||||||
|
addCredits,
|
||||||
|
deductCredits,
|
||||||
|
getUserCredits,
|
||||||
|
getActiveProductsWithPrices,
|
||||||
|
getProductById,
|
||||||
|
upsertCustomerToSupabase,
|
||||||
|
getStripeCustomerId
|
||||||
|
};
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import type { LayoutServerLoad } from './$types';
|
import type { LayoutServerLoad } from './$types';
|
||||||
|
|
||||||
export const load: LayoutServerLoad = async ({ locals: { safeGetSession } }) => {
|
export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
|
||||||
const { session, user } = await safeGetSession();
|
const { session, user } = await safeGetSession();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
session,
|
session,
|
||||||
user
|
user,
|
||||||
|
cookies: cookies.getAll()
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
+110
-87
@@ -1,14 +1,14 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import 'tailwindcss/tailwind.css';
|
import '../app.postcss';
|
||||||
import { onDestroy, onMount } from 'svelte';
|
import { onDestroy, onMount } from 'svelte';
|
||||||
import { isBrowser } from '@supabase/ssr';
|
import { isBrowser } from '@supabase/ssr';
|
||||||
import { basket, type Basket, type Item } from '$lib/stores/basket.js';
|
import { basket, type Basket, type Item } from '$lib/stores/basket.js';
|
||||||
import { general } from '$lib/stores/generalStore.js';
|
import { general } from '$lib/stores/generalStore.js';
|
||||||
import { invalidate } from '$app/navigation';
|
import { invalidate } from '$app/navigation';
|
||||||
import SignIn from '$lib/components/SignIn.svelte';
|
|
||||||
import SignOut from '$lib/components/SignOut.svelte';
|
import SignOut from '$lib/components/SignOut.svelte';
|
||||||
import CookieConsent from '$lib/components/CookieConsent.svelte';
|
import CookieConsent from '$lib/components/CookieConsent.svelte';
|
||||||
import NavLinks from '$lib/components/NavLinks.svelte';
|
import NavLinks from '$lib/components/NavLinks.svelte';
|
||||||
|
import MagicLink from '$lib/components/MagicLink.svelte';
|
||||||
|
|
||||||
export let data;
|
export let data;
|
||||||
let { supabase, session } = data;
|
let { supabase, session } = data;
|
||||||
@@ -32,8 +32,8 @@
|
|||||||
let cookiesAccepted = false;
|
let cookiesAccepted = false;
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const { data } = supabase.auth.onAuthStateChange((event, _session) => {
|
const { data } = supabase.auth.onAuthStateChange((event, newSession) => {
|
||||||
if (_session?.expires_at !== session?.expires_at) {
|
if (newSession?.expires_at !== session?.expires_at) {
|
||||||
// tells SvelteKit that the root +layout.ts load function should be executed whenever the session updates to keep the page store in sync.
|
// tells SvelteKit that the root +layout.ts load function should be executed whenever the session updates to keep the page store in sync.
|
||||||
invalidate('supabase:auth');
|
invalidate('supabase:auth');
|
||||||
}
|
}
|
||||||
@@ -47,6 +47,12 @@
|
|||||||
|
|
||||||
return () => data.subscription.unsubscribe();
|
return () => data.subscription.unsubscribe();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let isMobileMenuOpen = false;
|
||||||
|
|
||||||
|
function toggleMobileMenu() {
|
||||||
|
isMobileMenuOpen = !isMobileMenuOpen;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
@@ -63,95 +69,108 @@
|
|||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<header>
|
<header>
|
||||||
<nav class="navbar bg-primary text-primary-content">
|
<nav class="bg-primary text-primary-content p-4">
|
||||||
<div class="navbar-start">
|
<div class="container mx-auto flex justify-between items-center">
|
||||||
<div class="dropdown">
|
<a href="/" class="text-white font-bold text-xl">SvelteKit SaaS Boilerplate</a>
|
||||||
<div tabindex="0" role="button" class="btn btn-ghost lg:hidden">
|
|
||||||
<svg
|
<!-- Hamburger Menu Button (Mobile) -->
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
<button on:click={toggleMobileMenu} class="block md:hidden text-white focus:outline-none">
|
||||||
class="h-5 w-5"
|
<svg
|
||||||
fill="none"
|
class="w-6 h-6"
|
||||||
viewBox="0 0 24 24"
|
fill="none"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
><path
|
viewBox="0 0 24 24"
|
||||||
stroke-linecap="round"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
stroke-linejoin="round"
|
|
||||||
stroke-width="2"
|
|
||||||
d="M4 6h16M4 12h8m-8 6h16"
|
|
||||||
/></svg
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<ul
|
|
||||||
class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 text-base-content rounded-box w-52"
|
|
||||||
>
|
>
|
||||||
<NavLinks isMobile={true} />
|
<path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M4 6h16M4 12h8m-8 6h16"
|
||||||
|
></path>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Navbar Links (hidden on mobile, visible on larger screens) -->
|
||||||
|
<div class="hidden md:flex space-x-4">
|
||||||
|
<ul class="flex flex-col md:flex-row md:space-x-4">
|
||||||
|
<NavLinks isMobile={false} />
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<a href="/" class="btn btn-ghost text-xl">SvelteKit SaaS Boilerplate</a>
|
|
||||||
</div>
|
|
||||||
<div class="navbar-center hidden lg:flex">
|
|
||||||
<ul class="menu menu-horizontal px-1">
|
|
||||||
<NavLinks isMobile={false} />
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
<div class="navbar-end">
|
|
||||||
<a href="/checkout" class="btn btn-ghost btn-circle">
|
|
||||||
<div class="indicator">
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
class="h-5 w-5"
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
stroke="currentColor"
|
|
||||||
><path
|
|
||||||
stroke-linecap="round"
|
|
||||||
stroke-linejoin="round"
|
|
||||||
stroke-width="2"
|
|
||||||
d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
|
|
||||||
/></svg
|
|
||||||
>
|
|
||||||
<span class="badge badge-sm indicator-item">{localBasket.items.length}</span>
|
|
||||||
</div>
|
|
||||||
</a>
|
|
||||||
<div class="dropdown dropdown-end">
|
|
||||||
<div tabindex="0" role="button" class="btn btn-ghost btn-circle avatar">
|
|
||||||
<div class="w-10 rounded-full">
|
|
||||||
{#if session?.user}
|
|
||||||
<div class="user-circle text-primary-content border-primary-content">
|
|
||||||
{session?.user.email[0].toUpperCase()}
|
|
||||||
</div>
|
|
||||||
{:else}
|
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
|
|
||||||
<path
|
|
||||||
fill-rule="evenodd"
|
|
||||||
d="M18.685 19.097A9.723 9.723 0 0 0 21.75 12c0-5.385-4.365-9.75-9.75-9.75S2.25 6.615 2.25 12a9.723 9.723 0 0 0 3.065 7.097A9.716 9.716 0 0 0 12 21.75a9.716 9.716 0 0 0 6.685-2.653Zm-12.54-1.285A7.486 7.486 0 0 1 12 15a7.486 7.486 0 0 1 5.855 2.812A8.224 8.224 0 0 1 12 20.25a8.224 8.224 0 0 1-5.855-2.438ZM15.75 9a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"
|
|
||||||
clip-rule="evenodd"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if session?.user}
|
<!-- Right Side: Basket & User Account -->
|
||||||
<ul
|
<div class="flex items-center space-x-4">
|
||||||
tabindex="-1"
|
<!-- Basket/Checkout Icon -->
|
||||||
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"
|
<a href="/checkout" class="btn btn-ghost btn-circle">
|
||||||
>
|
<div class="indicator">
|
||||||
<li>
|
<svg
|
||||||
<a href="/profile"> Profile </a>
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
</li>
|
class="h-5 w-5"
|
||||||
<li><a href="/settings">Settings</a></li>
|
fill="none"
|
||||||
<li><SignOut {supabase} /></li>
|
viewBox="0 0 24 24"
|
||||||
</ul>
|
stroke="currentColor"
|
||||||
{:else}
|
>
|
||||||
<div
|
<path
|
||||||
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"
|
stroke-linecap="round"
|
||||||
>
|
stroke-linejoin="round"
|
||||||
<SignIn {supabase} />
|
stroke-width="2"
|
||||||
|
d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
<span class="badge badge-sm indicator-item">{localBasket.items.length}</span>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
</a>
|
||||||
|
|
||||||
|
<!-- User Account Dropdown -->
|
||||||
|
<details class="dropdown dropdown-end">
|
||||||
|
<summary tabindex="0" role="button" class="btn btn-ghost btn-circle avatar">
|
||||||
|
<div class="w-10 rounded-full">
|
||||||
|
{#if session?.user}
|
||||||
|
<div class="user-circle text-primary-content border-primary-content">
|
||||||
|
{session?.user.email[0].toUpperCase()}
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path
|
||||||
|
fill-rule="evenodd"
|
||||||
|
d="M18.685 19.097A9.723 9.723 0 0 0 21.75 12c0-5.385-4.365-9.75-9.75-9.75S2.25 6.615 2.25 12a9.723 9.723 0 0 0 3.065 7.097A9.716 9.716 0 0 0 12 21.75a9.716 9.716 0 0 0 6.685-2.653Zm-12.54-1.285A7.486 7.486 0 0 1 12 15a7.486 7.486 0 0 1 5.855 2.812A8.224 8.224 0 0 1 12 20.25a8.224 8.224 0 0 1-5.855-2.438ZM15.75 9a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"
|
||||||
|
clip-rule="evenodd"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</summary>
|
||||||
|
|
||||||
|
{#if session?.user}
|
||||||
|
<ul
|
||||||
|
tabindex="-1"
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<li><a href="/account">Account</a></li>
|
||||||
|
<li><a href="/settings">Settings</a></li>
|
||||||
|
<li><SignOut {supabase} /></li>
|
||||||
|
</ul>
|
||||||
|
{:else}
|
||||||
|
<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"
|
||||||
|
>
|
||||||
|
<MagicLink {supabase} />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</details>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Mobile Menu -->
|
||||||
|
<div
|
||||||
|
class="bg-base-100 text-base-content shadow rounded-box p-4 transition duration-300 ease-in-out md:hidden"
|
||||||
|
class:block={isMobileMenuOpen}
|
||||||
|
class:hidden={!isMobileMenuOpen}
|
||||||
|
>
|
||||||
|
<ul class="flex flex-col space-y-4">
|
||||||
|
<NavLinks isMobile={true} />
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -265,7 +284,7 @@
|
|||||||
<span>{localGeneral.toastMessage == '' ? 'Added to basket' : localGeneral.toastMessage}</span>
|
<span>{localGeneral.toastMessage == '' ? 'Added to basket' : localGeneral.toastMessage}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped lang="postcss">
|
||||||
.user-circle {
|
.user-circle {
|
||||||
width: 40px;
|
width: 40px;
|
||||||
height: 40px;
|
height: 40px;
|
||||||
@@ -277,4 +296,8 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
font-size: 20px; /* Adjust font size as needed */
|
font-size: 20px; /* Adjust font size as needed */
|
||||||
}
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
min-height: calc(100dvh - 68px - 68px);
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
+16
-15
@@ -1,25 +1,26 @@
|
|||||||
|
import { createBrowserClient, createServerClient, isBrowser } from '@supabase/ssr';
|
||||||
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';
|
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';
|
||||||
import type { LayoutLoad } from './$types';
|
import type { LayoutLoad } from './$types';
|
||||||
import { createBrowserClient, isBrowser, parse } from '@supabase/ssr';
|
|
||||||
|
|
||||||
export const load: LayoutLoad = async ({ fetch, data, depends }) => {
|
export const load: LayoutLoad = async ({ fetch, data, depends }) => {
|
||||||
depends('supabase:auth');
|
depends('supabase:auth');
|
||||||
|
|
||||||
const supabase = createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
|
const supabase = isBrowser()
|
||||||
global: {
|
? createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
|
||||||
fetch
|
global: {
|
||||||
},
|
fetch
|
||||||
cookies: {
|
|
||||||
get(key) {
|
|
||||||
if (!isBrowser()) {
|
|
||||||
return JSON.stringify(data.session);
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
const cookie = parse(document.cookie);
|
: createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
|
||||||
return cookie[key];
|
global: {
|
||||||
}
|
fetch
|
||||||
}
|
},
|
||||||
});
|
cookies: {
|
||||||
|
getAll() {
|
||||||
|
return data.cookies;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* It's fine to use `getSession` here, because on the client, `getSession` is
|
* It's fine to use `getSession` here, because on the client, `getSession` is
|
||||||
|
|||||||
+17
-11
@@ -1,23 +1,29 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onDestroy } from 'svelte';
|
import MagicLink from '$lib/components/MagicLink.svelte';
|
||||||
import { type User } from '@supabase/auth-js';
|
|
||||||
import SignUp from '$lib/components/SignUp.svelte';
|
|
||||||
|
|
||||||
export let data;
|
export let data;
|
||||||
let { supabase, session } = data;
|
let { supabase, session } = data;
|
||||||
$: ({ supabase, session } = data);
|
$: ({ supabase, session } = data);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="hero bg-base-100 my-36">
|
{#if session !== null}
|
||||||
<div class="hero-content flex-col lg:flex-row-reverse">
|
<div class="hero bg-base-100 my-36">
|
||||||
<div class="text-center lg:text-left">
|
Welcome back {session.user.email}
|
||||||
<h1 class="text-5xl font-bold">Sign up for this amazing SaaS right now - don't miss out!</h1>
|
</div>
|
||||||
</div>
|
{:else}
|
||||||
<div id="sign-up" class="card shrink-0 w-full max-w-sm shadow-2xl">
|
<div class="hero bg-base-100 my-36">
|
||||||
<SignUp {supabase} />
|
<div class="hero-content flex-col lg:flex-row-reverse">
|
||||||
|
<div class="text-center lg:text-left">
|
||||||
|
<h1 class="text-5xl font-bold">
|
||||||
|
Sign up for this amazing SaaS right now - don't miss out!
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
<div id="sign-up" class="card shrink-0 w-full max-w-sm shadow-2xl">
|
||||||
|
<MagicLink {supabase} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
{/if}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
class="md:container md:mx-auto justify-self-center flex justify-center items-center h-full flex-col mb-10"
|
class="md:container md:mx-auto justify-self-center flex justify-center items-center h-full flex-col mb-10"
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ locals: { supabase, safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
redirect(303, '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: user } = await supabase
|
||||||
|
.from('users')
|
||||||
|
.select(`name`)
|
||||||
|
.eq('id', session.user.id)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
return { session, user };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions: Actions = {
|
||||||
|
update: async ({ request, locals: { supabase, safeGetSession } }) => {
|
||||||
|
const formData = await request.formData();
|
||||||
|
const name = formData.get('name') as string;
|
||||||
|
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return fail(401, { name });
|
||||||
|
}
|
||||||
|
const { error } = await supabase.from('users').update({
|
||||||
|
name: name,
|
||||||
|
}).eq('id', session?.user.id);
|
||||||
|
|
||||||
|
console.error(error);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return fail(500, {
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
signout: async ({ locals: { supabase, safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
if (session) {
|
||||||
|
await supabase.auth.signOut();
|
||||||
|
redirect(303, '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { enhance } from '$app/forms';
|
||||||
|
import type { SubmitFunction } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
export let form;
|
||||||
|
|
||||||
|
let { session, supabase, user } = data;
|
||||||
|
$: ({ session, supabase, user } = data);
|
||||||
|
|
||||||
|
let profileForm: HTMLFormElement;
|
||||||
|
let loading = false;
|
||||||
|
let name: string = user?.name ?? '';
|
||||||
|
|
||||||
|
const handleSubmit: SubmitFunction = () => {
|
||||||
|
loading = true;
|
||||||
|
return async () => {
|
||||||
|
loading = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSignOut: SubmitFunction = () => {
|
||||||
|
loading = true;
|
||||||
|
return async ({ update }) => {
|
||||||
|
loading = false;
|
||||||
|
update();
|
||||||
|
};
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-widget">
|
||||||
|
<form
|
||||||
|
class="form-widget"
|
||||||
|
method="post"
|
||||||
|
action="?/update"
|
||||||
|
use:enhance={handleSubmit}
|
||||||
|
bind:this={profileForm}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<label for="name">Name</label>
|
||||||
|
<input id="name" name="name" type="text" value={form?.name ?? name} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<input
|
||||||
|
type="submit"
|
||||||
|
class="button block primary"
|
||||||
|
value={loading ? 'Loading...' : 'Update'}
|
||||||
|
disabled={loading}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form method="post" action="?/signout" use:enhance={handleSignOut}>
|
||||||
|
<div>
|
||||||
|
<button class="button block" disabled={loading}>Sign Out</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
@@ -1,11 +1,20 @@
|
|||||||
import { type RequestHandler, redirect } from '@sveltejs/kit';
|
import { type RequestHandler, redirect } from '@sveltejs/kit';
|
||||||
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
|
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||||
import stripe from 'stripe';
|
import { getStripeCustomerId } from '$lib/utils/supabase/admin';
|
||||||
|
import type Stripe from 'stripe';
|
||||||
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
|
|
||||||
|
|
||||||
// Create a checkout session
|
// Create a checkout session
|
||||||
export const POST: RequestHandler = async ({ request, cookies }) => {
|
export const POST: RequestHandler = async ({ request, cookies, locals: { safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
// If no session is found, the user isn't authenticated, so block the action
|
||||||
|
return new Response('Unauthorized', { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = session.user.id;
|
||||||
|
const userEmail = session.user.email;
|
||||||
|
|
||||||
const formData = new URLSearchParams(await request.text());
|
const formData = new URLSearchParams(await request.text());
|
||||||
const items: { priceId: string; quantity: number }[] = [];
|
const items: { priceId: string; quantity: number }[] = [];
|
||||||
|
|
||||||
@@ -19,14 +28,37 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
|||||||
quantity: item.quantity
|
quantity: item.quantity
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const session = await stripeClient.checkout.sessions.create({
|
let stripeCustomerId = null;
|
||||||
|
|
||||||
|
// Get the existing Stripe customer ID from Supabase, if it exists
|
||||||
|
try {
|
||||||
|
stripeCustomerId = await getStripeCustomerId(userEmail!, userId);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching Stripe customer ID:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stripeCheckoutSessionObject = {
|
||||||
line_items: lineItems,
|
line_items: lineItems,
|
||||||
mode: 'payment',
|
mode: 'payment',
|
||||||
success_url: `${request.headers.get('origin')}/checkout/success`,
|
success_url: `${request.headers.get('origin')}/checkout/success`,
|
||||||
cancel_url: `${request.headers.get('origin')}/checkout/cancelled`
|
cancel_url: `${request.headers.get('origin')}/checkout/cancelled`,
|
||||||
});
|
metadata: {
|
||||||
|
userId: userId
|
||||||
|
}
|
||||||
|
} as Stripe.Checkout.SessionCreateParams;
|
||||||
|
|
||||||
|
if (stripeCustomerId) {
|
||||||
|
// If the user has a Stripe customer ID, attach it to the checkout session
|
||||||
|
stripeCheckoutSessionObject.customer = stripeCustomerId;
|
||||||
|
} else {
|
||||||
|
// If the user doesn't have a Stripe customer ID, create a new customer
|
||||||
|
stripeCheckoutSessionObject.customer_creation = 'always';
|
||||||
|
stripeCheckoutSessionObject.customer_email = userEmail;
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkoutSession = await stripeClient.checkout.sessions.create(stripeCheckoutSessionObject);
|
||||||
|
|
||||||
// Store the checkout session.id for access from the frontend
|
// Store the checkout session.id for access from the frontend
|
||||||
cookies.set('checkout_session_id', session.id, { path: '/' });
|
cookies.set('checkout_session_id', checkoutSession.id, { path: '/' });
|
||||||
return redirect(303, session.url as string);
|
return redirect(303, checkoutSession.url as string);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { upsertCustomerToSupabase } from '$lib/utils/supabase/admin';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ url, locals: { safeGetSession } }) => {
|
||||||
|
const stripeCustomerId = url.searchParams.get('stripeCustomerId');
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
|
||||||
|
if (!session || !stripeCustomerId) {
|
||||||
|
return json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await upsertCustomerToSupabase(session?.user.id, stripeCustomerId);
|
||||||
|
|
||||||
|
return json({ message: 'Customer created' });
|
||||||
|
};
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
import { json } from '@sveltejs/kit';
|
import { json } from '@sveltejs/kit';
|
||||||
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
|
|
||||||
import stripe from 'stripe';
|
|
||||||
import type { RequestHandler } from './$types';
|
import type { RequestHandler } from './$types';
|
||||||
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
|
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ cookies }) => {
|
export const GET: RequestHandler = async ({ cookies }) => {
|
||||||
const sessionId = cookies.get('checkout_session_id');
|
const sessionId = cookies.get('checkout_session_id');
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { type RequestHandler, redirect } from '@sveltejs/kit';
|
||||||
|
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||||
|
import { getStripeCustomerId } from '$lib/utils/supabase/admin';
|
||||||
|
import type Stripe from 'stripe';
|
||||||
|
|
||||||
|
// Create a subscription checkout session
|
||||||
|
export const POST: RequestHandler = async ({ request, cookies, locals: { safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
// If no session is found, the user isn't authenticated, so block the action
|
||||||
|
return new Response('Unauthorized', { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = session.user.id;
|
||||||
|
const userEmail = session.user.email;
|
||||||
|
|
||||||
|
// Get the price ID from the request form data
|
||||||
|
const formData = await request.formData();
|
||||||
|
const priceId = formData.get('priceId');
|
||||||
|
|
||||||
|
if (!priceId) {
|
||||||
|
return new Response('Price ID is required', { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let stripeCustomerId = null;
|
||||||
|
|
||||||
|
// Get the existing Stripe customer ID from Supabase, if it exists
|
||||||
|
try {
|
||||||
|
stripeCustomerId = await getStripeCustomerId(userEmail!, userId);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching Stripe customer ID:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stripeCheckoutSessionObject = {
|
||||||
|
line_items: [
|
||||||
|
{
|
||||||
|
price: priceId,
|
||||||
|
quantity: 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
mode: 'subscription',
|
||||||
|
success_url: `${request.headers.get('origin')}/checkout/success`,
|
||||||
|
cancel_url: `${request.headers.get('origin')}/checkout/cancelled`,
|
||||||
|
metadata: {
|
||||||
|
userId: userId
|
||||||
|
}
|
||||||
|
} as Stripe.Checkout.SessionCreateParams;
|
||||||
|
|
||||||
|
if (stripeCustomerId) {
|
||||||
|
// If the user has a Stripe customer ID, attach it to the checkout session
|
||||||
|
stripeCheckoutSessionObject.customer = stripeCustomerId;
|
||||||
|
} else {
|
||||||
|
// If the user doesn't have a Stripe customer ID, create a new customer with their email
|
||||||
|
stripeCheckoutSessionObject.customer_email = userEmail;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a subscription checkout session with Stripe
|
||||||
|
const checkoutSession = await stripeClient.checkout.sessions.create(stripeCheckoutSessionObject);
|
||||||
|
|
||||||
|
// Store the checkout session.id for access from the frontend
|
||||||
|
cookies.set('checkout_session_id', checkoutSession.id, { path: '/' });
|
||||||
|
return redirect(303, checkoutSession.url as string);
|
||||||
|
};
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
|
import stripe from 'stripe';
|
||||||
|
import { STRIPE_ENDPOINT_SECRET } from '$env/static/private';
|
||||||
|
import {
|
||||||
|
deletePriceRecord,
|
||||||
|
deleteProductRecord,
|
||||||
|
manageSubscriptionStatusChange,
|
||||||
|
upsertPriceRecord,
|
||||||
|
upsertProductRecord,
|
||||||
|
recordProductPurchase
|
||||||
|
} from '$lib/utils/supabase/admin';
|
||||||
|
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||||
|
|
||||||
|
export const POST: RequestHandler = async ({ request }) => {
|
||||||
|
const body = await request.text();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let event = JSON.parse(body) as stripe.Event;
|
||||||
|
|
||||||
|
// Get the signature sent by Stripe
|
||||||
|
const signature = request.headers.get('stripe-signature');
|
||||||
|
|
||||||
|
// Only verify the event if you have an endpoint secret defined.
|
||||||
|
// Otherwise use the basic event deserialized with JSON.parse
|
||||||
|
if (STRIPE_ENDPOINT_SECRET && signature) {
|
||||||
|
try {
|
||||||
|
event = stripeClient.webhooks.constructEvent(body, signature, STRIPE_ENDPOINT_SECRET);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`⚠️ Webhook signature verification failed.`, err.message);
|
||||||
|
return {
|
||||||
|
status: 400,
|
||||||
|
body: {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (event.type) {
|
||||||
|
case 'product.created':
|
||||||
|
case 'product.updated':
|
||||||
|
await upsertProductRecord(event.data.object as stripe.Product);
|
||||||
|
break;
|
||||||
|
case 'product.deleted':
|
||||||
|
await deleteProductRecord(event.data.object as stripe.Product);
|
||||||
|
break;
|
||||||
|
case 'price.created':
|
||||||
|
case 'price.updated':
|
||||||
|
await upsertPriceRecord(event.data.object as stripe.Price);
|
||||||
|
break;
|
||||||
|
case 'price.deleted':
|
||||||
|
await deletePriceRecord(event.data.object as stripe.Price);
|
||||||
|
break;
|
||||||
|
case 'customer.subscription.created':
|
||||||
|
case 'customer.subscription.updated':
|
||||||
|
case 'customer.subscription.deleted':
|
||||||
|
case 'customer.subscription.paused':
|
||||||
|
case 'customer.subscription.resumed': {
|
||||||
|
const subscription = event.data.object as stripe.Subscription;
|
||||||
|
await manageSubscriptionStatusChange(
|
||||||
|
subscription.id,
|
||||||
|
subscription.customer as string,
|
||||||
|
event.type === 'customer.subscription.created'
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'checkout.session.completed': {
|
||||||
|
const checkoutSession = event.data.object as stripe.Checkout.Session;
|
||||||
|
|
||||||
|
if (checkoutSession.mode === 'subscription') {
|
||||||
|
const subscriptionId = checkoutSession.subscription;
|
||||||
|
await manageSubscriptionStatusChange(
|
||||||
|
subscriptionId as string,
|
||||||
|
checkoutSession.customer as string,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
} else if (checkoutSession.mode === 'payment') {
|
||||||
|
// Fetch session with expanded line_items
|
||||||
|
const sessionWithLineItems = await stripeClient.checkout.sessions.retrieve(
|
||||||
|
checkoutSession.id,
|
||||||
|
{
|
||||||
|
expand: ['line_items']
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const lineItems = sessionWithLineItems.line_items?.data;
|
||||||
|
const userId = checkoutSession.metadata!.userId;
|
||||||
|
|
||||||
|
if (!lineItems) {
|
||||||
|
throw new Error('No line items found in session');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
throw new Error('No user ID found in session metadata');
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const item of lineItems ?? []) {
|
||||||
|
const productId = item.price?.product as string;
|
||||||
|
const priceId = item.price?.id as string;
|
||||||
|
|
||||||
|
if (productId && priceId) {
|
||||||
|
await recordProductPurchase(userId, productId, priceId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
console.log(`Unhandled event type ${event.type}`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : 'An unknown error has occurred';
|
||||||
|
return new Response(`Webhook Error: ${message}`, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return json({ received: true });
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { redirect, type RequestHandler } from '@sveltejs/kit'
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async (event) => {
|
||||||
|
const { url, locals: { supabase } } = event;
|
||||||
|
const code = url.searchParams.get('code')
|
||||||
|
|
||||||
|
if (code) {
|
||||||
|
await supabase.auth.exchangeCodeForSession(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Create stripe customer and sync with supabase user
|
||||||
|
|
||||||
|
throw redirect(303, '/account')
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<p>Login error</p>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
/** @type {import('./$types').PageLoad} */
|
||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const load = async ({ params, locals: { safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
if (!session) {
|
||||||
|
throw redirect(303, '/login'); // Redirect unauthenticated users to login
|
||||||
|
}
|
||||||
|
|
||||||
|
return params;
|
||||||
|
};
|
||||||
@@ -3,6 +3,10 @@
|
|||||||
import { basket, type Basket, type Item } from '$lib/stores/basket.js';
|
import { basket, type Basket, type Item } from '$lib/stores/basket.js';
|
||||||
import BasketItem from '$lib/components/checkout/BasketItem.svelte';
|
import BasketItem from '$lib/components/checkout/BasketItem.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
let { supabase, session, url } = data;
|
||||||
|
$: ({ supabase, session, url } = data);
|
||||||
|
|
||||||
let localBasket: Basket;
|
let localBasket: Basket;
|
||||||
const unsubscribe = basket.subscribe((value) => {
|
const unsubscribe = basket.subscribe((value) => {
|
||||||
localBasket = value;
|
localBasket = value;
|
||||||
@@ -101,28 +105,32 @@
|
|||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
</a>
|
</a>
|
||||||
<button
|
{#if session?.user !== undefined}
|
||||||
type="submit"
|
<button
|
||||||
class="btn btn-primary"
|
type="submit"
|
||||||
disabled={localBasket.items && localBasket.items.length === 0}
|
class="btn btn-primary"
|
||||||
>Continue to Payment
|
disabled={localBasket.items && localBasket.items.length === 0}
|
||||||
<svg
|
>Continue to Payment
|
||||||
class="ml-2"
|
<svg
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
class="ml-2"
|
||||||
width="23"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
height="22"
|
width="23"
|
||||||
viewBox="0 0 23 22"
|
height="22"
|
||||||
fill="none"
|
viewBox="0 0 23 22"
|
||||||
>
|
fill="none"
|
||||||
<path
|
>
|
||||||
d="M8.75324 5.49609L14.2535 10.9963L8.75 16.4998"
|
<path
|
||||||
stroke="white"
|
d="M8.75324 5.49609L14.2535 10.9963L8.75 16.4998"
|
||||||
stroke-width="1.6"
|
stroke="white"
|
||||||
stroke-linecap="round"
|
stroke-width="1.6"
|
||||||
stroke-linejoin="round"
|
stroke-linecap="round"
|
||||||
/>
|
stroke-linejoin="round"
|
||||||
</svg>
|
/>
|
||||||
</button>
|
</svg>
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<p>You must sign in to checkout</p>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import Stripe from 'stripe';
|
||||||
|
import { getProductById } from '$lib/utils/supabase/admin';
|
||||||
|
|
||||||
|
export const load = async ({ fetch }) => {
|
||||||
|
const response = await fetch('/api/checkout/status');
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error('Failed to fetch checkout status');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const responseJson = await response.json();
|
||||||
|
const checkoutSession: Stripe.Checkout.Session = responseJson.checkoutSession;
|
||||||
|
const lineItems: Stripe.LineItem[] = responseJson.lineItems.data;
|
||||||
|
const paymentStatus: Stripe.Checkout.Session.PaymentStatus = responseJson.paymentStatus;
|
||||||
|
|
||||||
|
if (paymentStatus == 'unpaid') {
|
||||||
|
throw redirect(303, '/checkout/cancelled');
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const lineItem of lineItems as LineItemForCheckout[]) {
|
||||||
|
const product = await getProductById(lineItem.price?.product.toString() ?? '');
|
||||||
|
lineItem.imgSrc = product.images ? product.images[0] : '';
|
||||||
|
lineItem.productDescription = product.description ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the stripe customer id in the customers table
|
||||||
|
const stripeCustomerId = checkoutSession.customer as string;
|
||||||
|
const createCustomerResponse = await fetch(
|
||||||
|
'/api/checkout/create-customer?stripeCustomerId=' + stripeCustomerId
|
||||||
|
);
|
||||||
|
if (!createCustomerResponse.ok) {
|
||||||
|
console.error('Failed to create customer');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
checkoutSession,
|
||||||
|
lineItems
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
type LineItemForCheckout = Stripe.LineItem & {
|
||||||
|
imgSrc: string;
|
||||||
|
productDescription: string;
|
||||||
|
};
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
localBasket = value;
|
localBasket = value;
|
||||||
});
|
});
|
||||||
|
|
||||||
let { checkoutSession, lineItems, paymentStatus } = data;
|
let { checkoutSession, lineItems } = data;
|
||||||
|
|
||||||
onDestroy(unsubscribe);
|
onDestroy(unsubscribe);
|
||||||
|
|
||||||
@@ -64,13 +64,15 @@
|
|||||||
>
|
>
|
||||||
</div> -->
|
</div> -->
|
||||||
<div class="w-full px-3 min-[400px]:px-6">
|
<div class="w-full px-3 min-[400px]:px-6">
|
||||||
{#if lineItems.length == 0}
|
{#if lineItems !== undefined && lineItems.length == 0}
|
||||||
<p class="font-semibold text-lg leading-7 text-black text-center">
|
<p class="font-semibold text-lg leading-7 text-black text-center">
|
||||||
No items in the basket
|
No items in the basket
|
||||||
</p>
|
</p>
|
||||||
{:else}
|
{:else if lineItems !== undefined}
|
||||||
{#each lineItems as item (item.id)}
|
{#each lineItems as item (item.id)}
|
||||||
<OrderConfirmationItem
|
<OrderConfirmationItem
|
||||||
|
imgSrc={item.imgSrc}
|
||||||
|
itemCategoryDescription={item.productDescription}
|
||||||
itemName={item.description}
|
itemName={item.description}
|
||||||
price={item.price.unit_amount / 100}
|
price={item.price.unit_amount / 100}
|
||||||
quantity={item.quantity}
|
quantity={item.quantity}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
import type { PageLoad } from './$types';
|
|
||||||
import { redirect } from '@sveltejs/kit';
|
|
||||||
import Stripe from 'stripe';
|
|
||||||
|
|
||||||
export const load: PageLoad = async ({fetch}) => {
|
|
||||||
const response = await fetch('/api/checkout/status');
|
|
||||||
if (!response.ok) {
|
|
||||||
console.error('Failed to fetch checkout status');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const responseJson = await response.json();
|
|
||||||
const checkoutSession: Stripe.Checkout.Session = responseJson.checkoutSession;
|
|
||||||
const lineItems: Stripe.LineItem[] = responseJson.lineItems.data;
|
|
||||||
const paymentStatus: Stripe.Checkout.Session.PaymentStatus = responseJson.paymentStatus;
|
|
||||||
|
|
||||||
if (paymentStatus == 'unpaid') {
|
|
||||||
throw redirect(303, '/checkout/cancelled');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
checkoutSession,
|
|
||||||
lineItems,
|
|
||||||
paymentStatus
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import MagicLink from '$lib/components/MagicLink.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
let { supabase, session, url } = data;
|
||||||
|
$: ({ supabase, session, url } = data);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<MagicLink {supabase} />
|
||||||
@@ -1,18 +1,108 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import ProductsListItem from '$lib/components/products/ProductsListItem.svelte';
|
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
let products = [] as any;
|
import { debounce } from 'ts-debounce';
|
||||||
|
import ProductsListItem from '$lib/components/products/ProductsListItem.svelte';
|
||||||
|
|
||||||
|
let products = [] as any[];
|
||||||
let enablePagination = false;
|
let enablePagination = false;
|
||||||
|
let totalPages = 1;
|
||||||
|
let currentPage = 1;
|
||||||
|
const limit = 20;
|
||||||
|
let isLoading = false;
|
||||||
|
let errorMessage = '';
|
||||||
|
|
||||||
onMount(async () => {
|
// Debounced fetchProducts function to prevent rapid requests
|
||||||
const response = await fetch('/products');
|
const fetchProducts = debounce(async (page: number) => {
|
||||||
const responseJson = await response.json();
|
isLoading = true;
|
||||||
products = responseJson.data;
|
errorMessage = '';
|
||||||
if (responseJson.has_more) {
|
|
||||||
enablePagination = true;
|
// Ensure page number is within valid range
|
||||||
|
if (page < 1) {
|
||||||
|
page = 1;
|
||||||
|
} else if (page > totalPages) {
|
||||||
|
page = totalPages;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/products?limit=${limit}&offset=${offset}`);
|
||||||
|
const responseJson = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
products = responseJson.products;
|
||||||
|
const count = responseJson.count;
|
||||||
|
|
||||||
|
totalPages = Math.ceil(count / limit);
|
||||||
|
enablePagination = totalPages > 1;
|
||||||
|
currentPage = page;
|
||||||
|
} else {
|
||||||
|
throw new Error(responseJson.error || 'Failed to load products.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
errorMessage = error.message || 'Failed to load products.';
|
||||||
|
} finally {
|
||||||
|
isLoading = false;
|
||||||
|
}
|
||||||
|
}, 300); // 300ms debounce delay
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
fetchProducts(currentPage);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Generate pagination buttons with ellipsis for large numbers of pages
|
||||||
|
function getPageNumbers() {
|
||||||
|
const maxButtons = 5;
|
||||||
|
const pageNumbers = [];
|
||||||
|
|
||||||
|
if (totalPages <= maxButtons) {
|
||||||
|
// Show all pages as there aren't many
|
||||||
|
for (let i = 1; i <= totalPages; i++) {
|
||||||
|
pageNumbers.push(i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let startPage = Math.max(currentPage - 2, 1);
|
||||||
|
let endPage = Math.min(currentPage + 2, totalPages);
|
||||||
|
|
||||||
|
if (currentPage <= 3) {
|
||||||
|
startPage = 1;
|
||||||
|
endPage = maxButtons;
|
||||||
|
} else if (currentPage >= totalPages - 2) {
|
||||||
|
startPage = totalPages - (maxButtons - 1);
|
||||||
|
endPage = totalPages;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add first page and ellipsis if needed
|
||||||
|
if (startPage > 1) {
|
||||||
|
pageNumbers.push(1);
|
||||||
|
if (startPage > 2) {
|
||||||
|
pageNumbers.push('...');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add page numbers
|
||||||
|
for (let i = startPage; i <= endPage; i++) {
|
||||||
|
pageNumbers.push(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add ellipsis and last page if needed
|
||||||
|
if (endPage < totalPages) {
|
||||||
|
if (endPage < totalPages - 1) {
|
||||||
|
pageNumbers.push('...');
|
||||||
|
}
|
||||||
|
pageNumbers.push(totalPages);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pageNumbers;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePageClick(pageNumber: number | string) {
|
||||||
|
if (typeof pageNumber === 'number' && pageNumber !== currentPage) {
|
||||||
|
fetchProducts(pageNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<section class="py-24">
|
<section class="py-24">
|
||||||
@@ -22,20 +112,67 @@
|
|||||||
>
|
>
|
||||||
Available Products
|
Available Products
|
||||||
</h2>
|
</h2>
|
||||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
|
||||||
{#each products as product (product.id)}
|
{#if isLoading}
|
||||||
<ProductsListItem {product} />
|
<p class="loading">Loading products...</p>
|
||||||
{/each}
|
{:else if errorMessage}
|
||||||
</div>
|
<p class="error">{errorMessage}</p>
|
||||||
{#if enablePagination}
|
{:else}
|
||||||
<div class="flex justify-center mt-12">
|
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||||
<div class="join">
|
{#each products as product (product.id)}
|
||||||
<button class="join-item btn">1</button>
|
<ProductsListItem {product} />
|
||||||
<button class="join-item btn btn-active">2</button>
|
{/each}
|
||||||
<button class="join-item btn">3</button>
|
|
||||||
<button class="join-item btn">4</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{#if enablePagination}
|
||||||
|
<div class="flex justify-center mt-12">
|
||||||
|
<div class="join">
|
||||||
|
<!-- Previous Button -->
|
||||||
|
<button
|
||||||
|
class="join-item btn"
|
||||||
|
on:click={() => fetchProducts(currentPage - 1)}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
>
|
||||||
|
Previous
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Page Number Buttons -->
|
||||||
|
{#each getPageNumbers() as pageNumber}
|
||||||
|
{#if pageNumber === '...'}
|
||||||
|
<span class="join-item btn">...</span>
|
||||||
|
{:else}
|
||||||
|
<button
|
||||||
|
class="join-item btn {currentPage === pageNumber ? 'btn-active' : ''}"
|
||||||
|
on:click={() => handlePageClick(pageNumber)}
|
||||||
|
>
|
||||||
|
{pageNumber}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
|
||||||
|
<!-- Next Button -->
|
||||||
|
<button
|
||||||
|
class="join-item btn"
|
||||||
|
on:click={() => fetchProducts(currentPage + 1)}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
>
|
||||||
|
Next
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.loading {
|
||||||
|
text-align: center;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
.error {
|
||||||
|
color: red;
|
||||||
|
text-align: center;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -1,23 +1,19 @@
|
|||||||
import { json } from '@sveltejs/kit';
|
import { json } from '@sveltejs/kit';
|
||||||
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
|
import { getActiveProductsWithPrices } from '$lib/utils/supabase/admin';
|
||||||
import stripe from 'stripe';
|
|
||||||
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
|
|
||||||
|
|
||||||
export const GET = async () => {
|
|
||||||
const products = await stripeClient.products.list({
|
|
||||||
limit: 100
|
|
||||||
});
|
|
||||||
|
|
||||||
|
export const GET = async ({ url }) => {
|
||||||
try {
|
try {
|
||||||
// Get the price for each product
|
const limitParam = url.searchParams.get('limit');
|
||||||
for (const product of products.data) {
|
const offsetParam = url.searchParams.get('offset');
|
||||||
const price = await stripeClient.prices.retrieve(product.default_price as string);
|
|
||||||
if (price) {
|
const limit = limitParam ? parseInt(limitParam, 10) : 10;
|
||||||
product.actualPrice = price.unit_amount / 100;
|
const offset = offsetParam ? parseInt(offsetParam, 10) : 0;
|
||||||
}
|
|
||||||
}
|
const { products, count } = await getActiveProductsWithPrices(limit, offset);
|
||||||
|
|
||||||
|
return json({ products, count });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
return json({ error: error.message }, { status: 500 });
|
||||||
}
|
}
|
||||||
return json(products);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import { hasProductAccess } from '$lib/utils/supabase/admin';
|
||||||
|
import type { ProductInfo } from '$lib/types/Products/ProductInfo';
|
||||||
|
|
||||||
|
export const load = async ({ params, locals: { safeGetSession }, fetch }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
if (!session) {
|
||||||
|
throw redirect(303, '/login'); // Redirect unauthenticated users to login
|
||||||
|
}
|
||||||
|
|
||||||
|
const productResponse = await fetch(`/products/${params.productId}`);
|
||||||
|
const { product, isSubscription, price }: ProductInfo = await productResponse.json();
|
||||||
|
|
||||||
|
// Create the item object
|
||||||
|
const item = {
|
||||||
|
id: product.id,
|
||||||
|
name: product.name,
|
||||||
|
categoryDescription: product.description,
|
||||||
|
imgAlt: product.description,
|
||||||
|
imgSrc: product.images[0],
|
||||||
|
priceId: product.default_price,
|
||||||
|
quantity: 1,
|
||||||
|
isSubscription: isSubscription,
|
||||||
|
price: (price.unit_amount ? price.unit_amount / 100 : NaN),
|
||||||
|
interval: price.recurring ? price.recurring.interval : null,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Check if the user has access to the 'EXAMPLE PRODUCT' product
|
||||||
|
const hasPurchasedProduct = await hasProductAccess(session.user.id, params.productId);
|
||||||
|
|
||||||
|
return { params, hasPurchasedProduct, item };
|
||||||
|
};
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onDestroy, onMount } from 'svelte';
|
import { onDestroy } from 'svelte';
|
||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
import { basket, type Basket, type Item } from '$lib/stores/basket.js';
|
import { basket, type Basket, type Item } from '$lib/stores/basket.js';
|
||||||
import { general } from '$lib/stores/generalStore.js';
|
import { general } from '$lib/stores/generalStore.js';
|
||||||
|
|
||||||
/** @type {import('./$types').PageData} */
|
/** @type {import('./$types').PageData} */
|
||||||
export let data;
|
export let data;
|
||||||
|
|
||||||
|
let { supabase, session, hasPurchasedProduct, item } = data;
|
||||||
|
$: ({ supabase, session, hasPurchasedProduct, item } = data);
|
||||||
|
|
||||||
let localBasket: Basket;
|
let localBasket: Basket;
|
||||||
const unsubscribeToBasket = basket.subscribe((value) => {
|
const unsubscribeToBasket = basket.subscribe((value) => {
|
||||||
localBasket = value;
|
localBasket = value;
|
||||||
@@ -16,6 +20,9 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
function addToBasket() {
|
function addToBasket() {
|
||||||
|
if (!session) {
|
||||||
|
redirect(303, '/');
|
||||||
|
}
|
||||||
basket.update((value) => {
|
basket.update((value) => {
|
||||||
const existingItemIndex = value.items.findIndex((basketItem) => basketItem.id === item.id);
|
const existingItemIndex = value.items.findIndex((basketItem) => basketItem.id === item.id);
|
||||||
|
|
||||||
@@ -43,32 +50,6 @@
|
|||||||
});
|
});
|
||||||
}, 5000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
|
|
||||||
let item = {};
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
fetch(`/products/${data.productId}`)
|
|
||||||
.then((response) => response.json())
|
|
||||||
.then((product) => {
|
|
||||||
item = {
|
|
||||||
id: product.id,
|
|
||||||
name: product.name,
|
|
||||||
categoryDescription: product.description,
|
|
||||||
imgAlt: product.description,
|
|
||||||
imgSrc: product.images[0],
|
|
||||||
price: 0,
|
|
||||||
priceId: product.default_price,
|
|
||||||
quantity: 1
|
|
||||||
};
|
|
||||||
|
|
||||||
// Fetch the price of the product
|
|
||||||
fetch(`/products/prices/${product.default_price}`)
|
|
||||||
.then((response) => response.json())
|
|
||||||
.then((price) => {
|
|
||||||
item.price = price.unit_amount / 100;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<section class="relative">
|
<section class="relative">
|
||||||
@@ -83,9 +64,6 @@
|
|||||||
class="data w-full lg:pr-8 pr-0 xl:justify-start justify-center flex items-center max-lg:pb-10 xl:my-2 lg:my-5 my-0"
|
class="data w-full lg:pr-8 pr-0 xl:justify-start justify-center flex items-center max-lg:pb-10 xl:my-2 lg:my-5 my-0"
|
||||||
>
|
>
|
||||||
<div class="data w-full max-w-xl">
|
<div class="data w-full max-w-xl">
|
||||||
<!-- <p class="text-lg font-medium leading-8 text-indigo-600 mb-4">
|
|
||||||
Clothing / Menswear
|
|
||||||
</p> -->
|
|
||||||
<h2 class="font-manrope font-bold text-3xl leading-10 text-gray-900 mb-2 capitalize">
|
<h2 class="font-manrope font-bold text-3xl leading-10 text-gray-900 mb-2 capitalize">
|
||||||
{item.name}
|
{item.name}
|
||||||
</h2>
|
</h2>
|
||||||
@@ -94,6 +72,7 @@
|
|||||||
class="font-manrope font-semibold text-2xl leading-9 text-gray-900 pr-5 sm:border-r border-gray-200 mr-5"
|
class="font-manrope font-semibold text-2xl leading-9 text-gray-900 pr-5 sm:border-r border-gray-200 mr-5"
|
||||||
>
|
>
|
||||||
£{item.price}
|
£{item.price}
|
||||||
|
{item.isSubscription ? `/ ${item.interval}` : ''}
|
||||||
</h6>
|
</h6>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<div class="flex items-center gap-1">
|
<div class="flex items-center gap-1">
|
||||||
@@ -275,72 +254,83 @@
|
|||||||
<span class="font-normal text-base text-gray-900">all size is available</span>
|
<span class="font-normal text-base text-gray-900">all size is available</span>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<!-- <p class="text-gray-900 text-lg leading-8 font-medium mb-4">Size</p>
|
|
||||||
<div class="w-full pb-8 border-b border-gray-100 flex-wrap">
|
|
||||||
<div class="grid grid-cols-3 min-[400px]:grid-cols-5 gap-3 max-w-md">
|
|
||||||
<button
|
|
||||||
class="bg-white text-center py-1.5 px-6 w-full font-semibold text-lg leading-8 text-gray-900 border border-gray-200 flex items-center rounded-full justify-center transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-100 hover:border-gray-300 visited:border-gray-300 visited:bg-gray-50"
|
|
||||||
>S</button
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class="bg-white text-center py-1.5 px-6 w-full font-semibold text-lg leading-8 text-gray-900 border border-gray-200 flex items-center rounded-full justify-center transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-100 hover:border-gray-300 visited:border-gray-300 visited:bg-gray-50"
|
|
||||||
>M</button
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class="bg-white text-center py-1.5 px-6 w-full font-semibold text-lg leading-8 text-gray-900 border border-gray-200 flex items-center rounded-full justify-center transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-100 hover:border-gray-300 visited:border-gray-300 visited:bg-gray-50"
|
|
||||||
>L</button
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class="bg-white text-center py-1.5 px-6 w-full font-semibold text-lg leading-8 text-gray-900 border border-gray-200 flex items-center rounded-full justify-center transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-100 hover:border-gray-300 visited:border-gray-300 visited:bg-gray-50"
|
|
||||||
>XL</button
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class="bg-white text-center py-1.5 px-6 w-full font-semibold text-lg leading-8 text-gray-900 border border-gray-200 flex items-center rounded-full justify-center transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-100 hover:border-gray-300 visited:border-gray-300 visited:bg-gray-50"
|
|
||||||
>XXL</button
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div> -->
|
|
||||||
|
|
||||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 py-8">
|
{#if !item.isSubscription && !hasPurchasedProduct}
|
||||||
<div class="flex sm:items-center sm:justify-center w-full">
|
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 py-8">
|
||||||
<button
|
<div class="flex sm:items-center sm:justify-center w-full">
|
||||||
class="group py-4 px-6 border border-gray-400 rounded-l-full bg-white transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-300"
|
<button
|
||||||
>
|
class="group py-4 px-6 border border-gray-400 rounded-l-full bg-white transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-300"
|
||||||
<svg
|
|
||||||
class="stroke-gray-900 group-hover:stroke-black"
|
|
||||||
width="22"
|
|
||||||
height="22"
|
|
||||||
viewBox="0 0 22 22"
|
|
||||||
fill="none"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
>
|
||||||
<path d="M16.5 11H5.5" stroke="" stroke-width="1.6" stroke-linecap="round" />
|
<svg
|
||||||
<path
|
class="stroke-gray-900 group-hover:stroke-black"
|
||||||
d="M16.5 11H5.5"
|
width="22"
|
||||||
stroke=""
|
height="22"
|
||||||
stroke-opacity="0.2"
|
viewBox="0 0 22 22"
|
||||||
stroke-width="1.6"
|
fill="none"
|
||||||
stroke-linecap="round"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
/>
|
>
|
||||||
<path
|
<path d="M16.5 11H5.5" stroke="" stroke-width="1.6" stroke-linecap="round" />
|
||||||
d="M16.5 11H5.5"
|
<path
|
||||||
stroke=""
|
d="M16.5 11H5.5"
|
||||||
stroke-opacity="0.2"
|
stroke=""
|
||||||
stroke-width="1.6"
|
stroke-opacity="0.2"
|
||||||
stroke-linecap="round"
|
stroke-width="1.6"
|
||||||
/>
|
stroke-linecap="round"
|
||||||
</svg>
|
/>
|
||||||
</button>
|
<path
|
||||||
<input
|
d="M16.5 11H5.5"
|
||||||
type="text"
|
stroke=""
|
||||||
class="font-semibold text-gray-900 cursor-pointer text-lg py-[13px] px-6 w-full sm:max-w-[118px] outline-0 border-y border-gray-400 bg-transparent placeholder:text-gray-900 text-center hover:bg-gray-50"
|
stroke-opacity="0.2"
|
||||||
placeholder="1"
|
stroke-width="1.6"
|
||||||
/>
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
class="font-semibold text-gray-900 cursor-pointer text-lg py-[13px] px-6 w-full sm:max-w-[118px] outline-0 border-y border-gray-400 bg-transparent placeholder:text-gray-900 text-center hover:bg-gray-50"
|
||||||
|
placeholder="1"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
class="group py-4 px-6 border border-gray-400 rounded-r-full bg-white transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-300"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
class="stroke-gray-900 group-hover:stroke-black"
|
||||||
|
width="22"
|
||||||
|
height="22"
|
||||||
|
viewBox="0 0 22 22"
|
||||||
|
fill="none"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M11 5.5V16.5M16.5 11H5.5"
|
||||||
|
stroke="#9CA3AF"
|
||||||
|
stroke-width="1.6"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M11 5.5V16.5M16.5 11H5.5"
|
||||||
|
stroke="black"
|
||||||
|
stroke-opacity="0.2"
|
||||||
|
stroke-width="1.6"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M11 5.5V16.5M16.5 11H5.5"
|
||||||
|
stroke="black"
|
||||||
|
stroke-opacity="0.2"
|
||||||
|
stroke-width="1.6"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
class="group py-4 px-6 border border-gray-400 rounded-r-full bg-white transition-all duration-300 hover:bg-gray-50 hover:shadow-sm hover:shadow-gray-300"
|
class="group py-4 px-5 rounded-full bg-indigo-50 text-indigo-600 font-semibold text-lg w-full flex items-center justify-center gap-2 transition-all duration-500 hover:bg-indigo-100"
|
||||||
|
on:click={addToBasket}
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
class="stroke-gray-900 group-hover:stroke-black"
|
class="stroke-indigo-600"
|
||||||
width="22"
|
width="22"
|
||||||
height="22"
|
height="22"
|
||||||
viewBox="0 0 22 22"
|
viewBox="0 0 22 22"
|
||||||
@@ -348,77 +338,40 @@
|
|||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
d="M11 5.5V16.5M16.5 11H5.5"
|
d="M10.7394 17.875C10.7394 18.6344 10.1062 19.25 9.32511 19.25C8.54402 19.25 7.91083 18.6344 7.91083 17.875M16.3965 17.875C16.3965 18.6344 15.7633 19.25 14.9823 19.25C14.2012 19.25 13.568 18.6344 13.568 17.875M4.1394 5.5L5.46568 12.5908C5.73339 14.0221 5.86724 14.7377 6.37649 15.1605C6.88573 15.5833 7.61377 15.5833 9.06984 15.5833H15.2379C16.6941 15.5833 17.4222 15.5833 17.9314 15.1605C18.4407 14.7376 18.5745 14.0219 18.8421 12.5906L19.3564 9.84059C19.7324 7.82973 19.9203 6.8243 19.3705 6.16215C18.8207 5.5 17.7979 5.5 15.7522 5.5H4.1394ZM4.1394 5.5L3.66797 2.75"
|
||||||
stroke="#9CA3AF"
|
stroke=""
|
||||||
stroke-width="1.6"
|
|
||||||
stroke-linecap="round"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M11 5.5V16.5M16.5 11H5.5"
|
|
||||||
stroke="black"
|
|
||||||
stroke-opacity="0.2"
|
|
||||||
stroke-width="1.6"
|
|
||||||
stroke-linecap="round"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M11 5.5V16.5M16.5 11H5.5"
|
|
||||||
stroke="black"
|
|
||||||
stroke-opacity="0.2"
|
|
||||||
stroke-width="1.6"
|
stroke-width="1.6"
|
||||||
stroke-linecap="round"
|
stroke-linecap="round"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
|
Add to basket
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<button
|
{:else}
|
||||||
class="group py-4 px-5 rounded-full bg-indigo-50 text-indigo-600 font-semibold text-lg w-full flex items-center justify-center gap-2 transition-all duration-500 hover:bg-indigo-100"
|
{#if hasPurchasedProduct}
|
||||||
on:click={addToBasket}
|
<div class="flex items-center gap-3">
|
||||||
>
|
<button
|
||||||
<svg
|
class="group text-center w-full py-4 px-5 rounded-full bg-gray-100 text-gray-600 font-semibold text-lg w-full flex items-center justify-center gap-2 transition-all duration-500"
|
||||||
class="stroke-indigo-600"
|
disabled
|
||||||
width="22"
|
>
|
||||||
height="22"
|
You already own this
|
||||||
viewBox="0 0 22 22"
|
</button>
|
||||||
fill="none"
|
</div>
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
{/if}
|
||||||
>
|
{#if item.isSubscription}
|
||||||
<path
|
<div class="flex items-center gap-3">
|
||||||
d="M10.7394 17.875C10.7394 18.6344 10.1062 19.25 9.32511 19.25C8.54402 19.25 7.91083 18.6344 7.91083 17.875M16.3965 17.875C16.3965 18.6344 15.7633 19.25 14.9823 19.25C14.2012 19.25 13.568 18.6344 13.568 17.875M4.1394 5.5L5.46568 12.5908C5.73339 14.0221 5.86724 14.7377 6.37649 15.1605C6.88573 15.5833 7.61377 15.5833 9.06984 15.5833H15.2379C16.6941 15.5833 17.4222 15.5833 17.9314 15.1605C18.4407 14.7376 18.5745 14.0219 18.8421 12.5906L19.3564 9.84059C19.7324 7.82973 19.9203 6.8243 19.3705 6.16215C18.8207 5.5 17.7979 5.5 15.7522 5.5H4.1394ZM4.1394 5.5L3.66797 2.75"
|
<form method="POST" action="/api/subscribe">
|
||||||
stroke=""
|
<input type="hidden" name="priceId" value={item.priceId} />
|
||||||
stroke-width="1.6"
|
<button
|
||||||
stroke-linecap="round"
|
type="submit"
|
||||||
/>
|
class="text-center w-full px-5 py-4 rounded-[100px] bg-indigo-600 flex items-center justify-center font-semibold text-lg text-white shadow-sm transition-all duration-500 hover:bg-indigo-700 hover:shadow-indigo-400"
|
||||||
</svg>
|
>
|
||||||
Add to basket</button
|
Subscribe
|
||||||
>
|
</button>
|
||||||
</div>
|
</form>
|
||||||
<div class="flex items-center gap-3">
|
</div>
|
||||||
<button
|
{/if}
|
||||||
class="group transition-all duration-500 p-4 rounded-full bg-indigo-50 hover:bg-indigo-100 hover:shadow-sm hover:shadow-indigo-300"
|
{/if}
|
||||||
>
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
width="26"
|
|
||||||
height="26"
|
|
||||||
viewBox="0 0 26 26"
|
|
||||||
fill="none"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
d="M4.47084 14.3196L13.0281 22.7501L21.9599 13.9506M13.0034 5.07888C15.4786 2.64037 19.5008 2.64037 21.976 5.07888C24.4511 7.5254 24.4511 11.4799 21.9841 13.9265M12.9956 5.07888C10.5204 2.64037 6.49824 2.64037 4.02307 5.07888C1.54789 7.51738 1.54789 11.4799 4.02307 13.9184M4.02307 13.9184L4.04407 13.939M4.02307 13.9184L4.46274 14.3115"
|
|
||||||
stroke="#4F46E5"
|
|
||||||
stroke-width="1.6"
|
|
||||||
stroke-miterlimit="10"
|
|
||||||
stroke-linecap="round"
|
|
||||||
stroke-linejoin="round"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
class="text-center w-full px-5 py-4 rounded-[100px] bg-indigo-600 flex items-center justify-center font-semibold text-lg text-white shadow-sm transition-all duration-500 hover:bg-indigo-700 hover:shadow-indigo-400"
|
|
||||||
>
|
|
||||||
Buy Now
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
/** @type {import('./$types').PageLoad} */
|
|
||||||
export function load({ params }) {
|
|
||||||
return params;
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,21 @@
|
|||||||
import { json } from '@sveltejs/kit';
|
import { json } from '@sveltejs/kit';
|
||||||
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
|
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||||
import stripe from 'stripe';
|
import Stripe from 'stripe';
|
||||||
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
|
import { type ProductInfo } from '$lib/types/Products/ProductInfo';
|
||||||
|
|
||||||
export const GET = async ({ params }) => {
|
export const GET = async ({ params }) => {
|
||||||
const { productId } = params;
|
const { productId } = params;
|
||||||
const product = await stripeClient.products.retrieve(productId);
|
const product = await stripeClient.products.retrieve(productId);
|
||||||
return json(product);
|
|
||||||
|
const price = await stripeClient.prices.retrieve(product.default_price as string);
|
||||||
|
|
||||||
|
const isSubscription = price.type === ('recurring' as Stripe.Price.Type);
|
||||||
|
|
||||||
|
const productInfo: ProductInfo = {
|
||||||
|
product,
|
||||||
|
price,
|
||||||
|
isSubscription
|
||||||
|
}
|
||||||
|
|
||||||
|
return json(productInfo);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { json } from '@sveltejs/kit';
|
import { json } from '@sveltejs/kit';
|
||||||
import { PUBLIC_STRIPE_SECRET_KEY } from '$env/static/public';
|
import { stripe as stripeClient } from '$lib/utils/stripe';
|
||||||
import stripe from 'stripe';
|
|
||||||
const stripeClient = new stripe(PUBLIC_STRIPE_SECRET_KEY);
|
|
||||||
|
|
||||||
export const GET = async ({ params }) => {
|
export const GET = async ({ params }) => {
|
||||||
const { priceId } = params;
|
const { priceId } = params;
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { onDestroy } from 'svelte';
|
|
||||||
import { type User } from '@supabase/auth-js';
|
|
||||||
|
|
||||||
export let data;
|
|
||||||
let { supabase, session } = data;
|
|
||||||
$: ({ supabase, session } = data);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="h-screen">
|
|
||||||
{#if session?.user}
|
|
||||||
{session?.user?.email}
|
|
||||||
{:else}
|
|
||||||
<p>Please log in to view this page</p>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ locals: { supabase, safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
redirect(303, '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: user } = await supabase
|
||||||
|
.from('users')
|
||||||
|
.select(`name, id`)
|
||||||
|
.eq('id', session.user.id)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
return { session, user };
|
||||||
|
};
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
|
||||||
|
let { session, supabase, user } = data;
|
||||||
|
$: ({ session, supabase, user } = data);
|
||||||
|
|
||||||
|
const credits = writable<number>(0);
|
||||||
|
let errorMessage: string = '';
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
try {
|
||||||
|
const pageUserId = user?.id;
|
||||||
|
if (pageUserId) {
|
||||||
|
const response = await fetch('/test/test-credits', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ action: 'getUserCredits', userId: pageUserId })
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('Failed to fetch credits');
|
||||||
|
const { credits: fetchedCredits } = await response.json();
|
||||||
|
credits.set(fetchedCredits);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
errorMessage = error.message;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const addCredits = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/test/test-credits', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
action: 'addCredits',
|
||||||
|
userId: user?.id,
|
||||||
|
credits: 10,
|
||||||
|
description: 'Test add credits'
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('Failed to add credits');
|
||||||
|
const { credits: updatedCredits } = await response.json();
|
||||||
|
credits.set(updatedCredits);
|
||||||
|
} catch (error) {
|
||||||
|
errorMessage = error.message;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deductCredits = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/test/test-credits', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
action: 'deductCredits',
|
||||||
|
userId: user?.id,
|
||||||
|
credits: 5,
|
||||||
|
description: 'Test deduct credits'
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('Failed to deduct credits');
|
||||||
|
const { credits: updatedCredits } = await response.json();
|
||||||
|
credits.set(updatedCredits);
|
||||||
|
} catch (error) {
|
||||||
|
errorMessage = error.message;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<h1>Credits Management for User: {user?.id}</h1>
|
||||||
|
<p>Credits Remaining: {$credits}</p>
|
||||||
|
{#if errorMessage}
|
||||||
|
<p style="color: red;">{errorMessage}</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<button on:click={addCredits}>Add 10 Credits</button>
|
||||||
|
<button on:click={deductCredits}>Deduct 5 Credits</button>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
main {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
margin: 0.5rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import { addCredits, deductCredits, getUserCredits } from '$lib/utils/supabase/admin';
|
||||||
|
|
||||||
|
export const POST = async ({ request }) => {
|
||||||
|
const { action, userId, credits, description } = await request.json();
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return json({ success: false, error: 'User ID is required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (action === 'addCredits') {
|
||||||
|
await addCredits(userId, credits, description);
|
||||||
|
const updatedCredits = await getUserCredits(userId);
|
||||||
|
return json({ success: true, credits: updatedCredits });
|
||||||
|
} else if (action === 'deductCredits') {
|
||||||
|
await deductCredits(userId, credits, description);
|
||||||
|
const updatedCredits = await getUserCredits(userId);
|
||||||
|
return json({ success: true, credits: updatedCredits });
|
||||||
|
} else if (action === 'getUserCredits') {
|
||||||
|
const fetchedCredits = await getUserCredits(userId);
|
||||||
|
return json({ success: true, credits: fetchedCredits });
|
||||||
|
} else {
|
||||||
|
return json({ success: false, error: 'Invalid action' }, { status: 400 });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return json({ success: false, error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
/** @type {import('./$types').PageLoad} */
|
||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import { hasProductAccess } from '$lib/utils/supabase/admin';
|
||||||
|
import { VITE_PRODUCT_ID_EXAMPLEPRODUCT } from '$env/static/private'; // Import the example product ID from env
|
||||||
|
|
||||||
|
export const load = async ({ params, locals: { safeGetSession } }) => {
|
||||||
|
const { session } = await safeGetSession();
|
||||||
|
if (!session) {
|
||||||
|
throw redirect(303, '/login'); // Redirect unauthenticated users to login
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the user has access to the 'EXAMPLE PRODUCT' product
|
||||||
|
const accessGranted = await hasProductAccess(session.user.id, VITE_PRODUCT_ID_EXAMPLEPRODUCT);
|
||||||
|
if (!accessGranted) {
|
||||||
|
throw redirect(303, '/unauthorised');
|
||||||
|
}
|
||||||
|
|
||||||
|
return params;
|
||||||
|
};
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<h1>Example Product</h1>
|
||||||
|
<p>This is an example of a tool you could be selling.</p>
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<h1>Unauthorised Access</h1>
|
||||||
|
<p>Sorry, you don't have permission to access this tool.</p>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Supabase
|
||||||
|
.branches
|
||||||
|
.temp
|
||||||
|
.env
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
# A string used to distinguish different Supabase projects on the same host. Defaults to the
|
||||||
|
# working directory name when running `supabase init`.
|
||||||
|
project_id = "SvelteKitSaasBoilerplate"
|
||||||
|
|
||||||
|
[api]
|
||||||
|
enabled = true
|
||||||
|
# Port to use for the API URL.
|
||||||
|
port = 54321
|
||||||
|
# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
|
||||||
|
# endpoints. `public` is always included.
|
||||||
|
schemas = ["public", "graphql_public"]
|
||||||
|
# Extra schemas to add to the search_path of every request. `public` is always included.
|
||||||
|
extra_search_path = ["public", "extensions"]
|
||||||
|
# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
|
||||||
|
# for accidental or malicious requests.
|
||||||
|
max_rows = 1000
|
||||||
|
|
||||||
|
[db]
|
||||||
|
# Port to use for the local database URL.
|
||||||
|
port = 54322
|
||||||
|
# Port used by db diff command to initialize the shadow database.
|
||||||
|
shadow_port = 54320
|
||||||
|
# The database major version to use. This has to be the same as your remote database's. Run `SHOW
|
||||||
|
# server_version;` on the remote database to check.
|
||||||
|
major_version = 15
|
||||||
|
|
||||||
|
[db.pooler]
|
||||||
|
enabled = false
|
||||||
|
# Port to use for the local connection pooler.
|
||||||
|
port = 54329
|
||||||
|
# Specifies when a server connection can be reused by other clients.
|
||||||
|
# Configure one of the supported pooler modes: `transaction`, `session`.
|
||||||
|
pool_mode = "transaction"
|
||||||
|
# How many server connections to allow per user/database pair.
|
||||||
|
default_pool_size = 20
|
||||||
|
# Maximum number of client connections allowed.
|
||||||
|
max_client_conn = 100
|
||||||
|
|
||||||
|
[realtime]
|
||||||
|
enabled = true
|
||||||
|
# Bind realtime via either IPv4 or IPv6. (default: IPv4)
|
||||||
|
# ip_version = "IPv6"
|
||||||
|
# The maximum length in bytes of HTTP request headers. (default: 4096)
|
||||||
|
# max_header_length = 4096
|
||||||
|
|
||||||
|
[studio]
|
||||||
|
enabled = true
|
||||||
|
# Port to use for Supabase Studio.
|
||||||
|
port = 54323
|
||||||
|
# External URL of the API server that frontend connects to.
|
||||||
|
api_url = "http://127.0.0.1"
|
||||||
|
|
||||||
|
# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
|
||||||
|
# are monitored, and you can view the emails that would have been sent from the web interface.
|
||||||
|
[inbucket]
|
||||||
|
enabled = true
|
||||||
|
# Port to use for the email testing server web interface.
|
||||||
|
port = 54324
|
||||||
|
# Uncomment to expose additional ports for testing user applications that send emails.
|
||||||
|
# smtp_port = 54325
|
||||||
|
# pop3_port = 54326
|
||||||
|
|
||||||
|
[storage]
|
||||||
|
enabled = true
|
||||||
|
# The maximum file size allowed (e.g. "5MB", "500KB").
|
||||||
|
file_size_limit = "50MiB"
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
enabled = true
|
||||||
|
# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
|
||||||
|
# in emails.
|
||||||
|
site_url = "http://localhost:5173"
|
||||||
|
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
|
||||||
|
additional_redirect_urls = ["http://localhost:5173/auth/confirm", "http://localhost:5173/auth/callback"]
|
||||||
|
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
|
||||||
|
jwt_expiry = 3600
|
||||||
|
# If disabled, the refresh token will never expire.
|
||||||
|
enable_refresh_token_rotation = true
|
||||||
|
# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
|
||||||
|
# Requires enable_refresh_token_rotation = true.
|
||||||
|
refresh_token_reuse_interval = 10
|
||||||
|
# Allow/disallow new user signups to your project.
|
||||||
|
enable_signup = true
|
||||||
|
# Allow/disallow anonymous sign-ins to your project.
|
||||||
|
enable_anonymous_sign_ins = false
|
||||||
|
# Allow/disallow testing manual linking of accounts
|
||||||
|
enable_manual_linking = false
|
||||||
|
|
||||||
|
[auth.email]
|
||||||
|
# Allow/disallow new user signups via email to your project.
|
||||||
|
enable_signup = true
|
||||||
|
# If enabled, a user will be required to confirm any email change on both the old, and new email
|
||||||
|
# addresses. If disabled, only the new email is required to confirm.
|
||||||
|
double_confirm_changes = true
|
||||||
|
# If enabled, users need to confirm their email address before signing in.
|
||||||
|
enable_confirmations = false
|
||||||
|
# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
|
||||||
|
max_frequency = "1s"
|
||||||
|
|
||||||
|
# Use a production-ready SMTP server
|
||||||
|
# [auth.email.smtp]
|
||||||
|
# host = "smtp.sendgrid.net"
|
||||||
|
# port = 587
|
||||||
|
# user = "apikey"
|
||||||
|
# pass = "env(SENDGRID_API_KEY)"
|
||||||
|
# admin_email = "admin@email.com"
|
||||||
|
# sender_name = "Admin"
|
||||||
|
|
||||||
|
# Uncomment to customize email template
|
||||||
|
[auth.email.template.magic_link]
|
||||||
|
subject = "Sign in to your account"
|
||||||
|
content_path = "./supabase/templates/magic_link.html"
|
||||||
|
|
||||||
|
[auth.sms]
|
||||||
|
# Allow/disallow new user signups via SMS to your project.
|
||||||
|
enable_signup = true
|
||||||
|
# If enabled, users need to confirm their phone number before signing in.
|
||||||
|
enable_confirmations = false
|
||||||
|
# Template for sending OTP to users
|
||||||
|
template = "Your code is {{ .Code }} ."
|
||||||
|
# Controls the minimum amount of time that must pass before sending another sms otp.
|
||||||
|
max_frequency = "5s"
|
||||||
|
|
||||||
|
# Use pre-defined map of phone number to OTP for testing.
|
||||||
|
# [auth.sms.test_otp]
|
||||||
|
# 4152127777 = "123456"
|
||||||
|
|
||||||
|
# Configure logged in session timeouts.
|
||||||
|
# [auth.sessions]
|
||||||
|
# Force log out after the specified duration.
|
||||||
|
# timebox = "24h"
|
||||||
|
# Force log out if the user has been inactive longer than the specified duration.
|
||||||
|
# inactivity_timeout = "8h"
|
||||||
|
|
||||||
|
# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used.
|
||||||
|
# [auth.hook.custom_access_token]
|
||||||
|
# enabled = true
|
||||||
|
# uri = "pg-functions://<database>/<schema>/<hook_name>"
|
||||||
|
|
||||||
|
# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`.
|
||||||
|
[auth.sms.twilio]
|
||||||
|
enabled = false
|
||||||
|
account_sid = ""
|
||||||
|
message_service_sid = ""
|
||||||
|
# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead:
|
||||||
|
auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)"
|
||||||
|
|
||||||
|
# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
|
||||||
|
# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`,
|
||||||
|
# `twitter`, `slack`, `spotify`, `workos`, `zoom`.
|
||||||
|
[auth.external.apple]
|
||||||
|
enabled = false
|
||||||
|
client_id = ""
|
||||||
|
# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
|
||||||
|
secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
|
||||||
|
# Overrides the default auth redirectUrl.
|
||||||
|
redirect_uri = ""
|
||||||
|
# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
|
||||||
|
# or any other third-party OIDC providers.
|
||||||
|
url = ""
|
||||||
|
# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
|
||||||
|
skip_nonce_check = false
|
||||||
|
|
||||||
|
[edge_runtime]
|
||||||
|
enabled = true
|
||||||
|
# Configure one of the supported request policies: `oneshot`, `per_worker`.
|
||||||
|
# Use `oneshot` for hot reload, or `per_worker` for load testing.
|
||||||
|
policy = "oneshot"
|
||||||
|
inspector_port = 8083
|
||||||
|
|
||||||
|
[analytics]
|
||||||
|
enabled = false
|
||||||
|
port = 54327
|
||||||
|
vector_port = 54328
|
||||||
|
# Configure one of the supported backends: `postgres`, `bigquery`.
|
||||||
|
backend = "postgres"
|
||||||
|
|
||||||
|
# Experimental features may be deprecated any time
|
||||||
|
[experimental]
|
||||||
|
# Configures Postgres storage engine to use OrioleDB (S3)
|
||||||
|
orioledb_version = ""
|
||||||
|
# Configures S3 bucket URL, eg. <bucket_name>.s3-<region>.amazonaws.com
|
||||||
|
s3_host = "env(S3_HOST)"
|
||||||
|
# Configures S3 bucket region, eg. us-east-1
|
||||||
|
s3_region = "env(S3_REGION)"
|
||||||
|
# Configures AWS_ACCESS_KEY_ID for S3 bucket
|
||||||
|
s3_access_key = "env(S3_ACCESS_KEY)"
|
||||||
|
# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
|
||||||
|
s3_secret_key = "env(S3_SECRET_KEY)"
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
/**
|
||||||
|
* USERS
|
||||||
|
* Note: This table contains user data. Users should only be able to view and update their own data.
|
||||||
|
*/
|
||||||
|
create table users (
|
||||||
|
-- UUID from auth.users
|
||||||
|
id uuid references auth.users not null primary key,
|
||||||
|
name text
|
||||||
|
);
|
||||||
|
alter table users enable row level security;
|
||||||
|
create policy "Can view own user data." on users for select using (auth.uid() = id);
|
||||||
|
create policy "Can update own user data." on users for update using (auth.uid() = id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This trigger automatically creates a user entry when a new user signs up via Supabase Auth.
|
||||||
|
*/
|
||||||
|
create function public.handle_new_user()
|
||||||
|
returns trigger as $$
|
||||||
|
begin
|
||||||
|
insert into public.users (id, name)
|
||||||
|
values (new.id, new.raw_user_meta_data->>'name');
|
||||||
|
return new;
|
||||||
|
end;
|
||||||
|
$$ language plpgsql security definer;
|
||||||
|
create trigger on_auth_user_created
|
||||||
|
after insert on auth.users
|
||||||
|
for each row execute procedure public.handle_new_user();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CUSTOMERS
|
||||||
|
* Note: this is a private table that contains a mapping of user IDs to Stripe customer IDs.
|
||||||
|
*/
|
||||||
|
create table customers (
|
||||||
|
-- UUID from auth.users
|
||||||
|
id uuid references auth.users not null primary key,
|
||||||
|
-- The user's customer ID in Stripe. User must not be able to update this.
|
||||||
|
stripe_customer_id text
|
||||||
|
);
|
||||||
|
alter table customers enable row level security;
|
||||||
|
-- No policies as this is a private table that the user must not have access to.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PRODUCTS
|
||||||
|
* Note: products are created and managed in Stripe and synced to our DB via Stripe webhooks.
|
||||||
|
*/
|
||||||
|
create table products (
|
||||||
|
-- Product ID from Stripe, e.g. prod_1234.
|
||||||
|
id text primary key,
|
||||||
|
-- Whether the product is currently available for purchase.
|
||||||
|
active boolean,
|
||||||
|
-- The product's name, meant to be displayable to the customer. Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions.
|
||||||
|
name text,
|
||||||
|
-- The product's description, meant to be displayable to the customer. Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes.
|
||||||
|
description text,
|
||||||
|
-- URLs of the product images in Stripe, meant to be displayable to the customer.
|
||||||
|
images text[],
|
||||||
|
-- A list of up to 15 features for this product. These are displayed in pricing tables.
|
||||||
|
features text[],
|
||||||
|
-- Set of key-value pairs, used to store additional information about the object in a structured format.
|
||||||
|
metadata jsonb,
|
||||||
|
"created_at" timestamp with time zone not null default now(),
|
||||||
|
"updated_at" timestamp with time zone not null default now()
|
||||||
|
);
|
||||||
|
alter table products enable row level security;
|
||||||
|
create policy "Allow public read-only access." on products for select using (true);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PRICES
|
||||||
|
* Note: prices are created and managed in Stripe and synced to our DB via Stripe webhooks.
|
||||||
|
*/
|
||||||
|
create type pricing_type as enum ('one_time', 'recurring');
|
||||||
|
create type pricing_plan_interval as enum ('day', 'week', 'month', 'year');
|
||||||
|
create table prices (
|
||||||
|
-- Price ID from Stripe, e.g. price_1234.
|
||||||
|
id text primary key,
|
||||||
|
-- The ID of the product that this price belongs to.
|
||||||
|
product_id text not null references products,
|
||||||
|
-- Whether the price can be used for new purchases.
|
||||||
|
active boolean,
|
||||||
|
-- A brief description of the price.
|
||||||
|
description text,
|
||||||
|
-- The unit amount as a positive integer in the smallest currency unit (e.g., 100 cents for US$1.00 or 100 for ¥100, a zero-decimal currency).
|
||||||
|
unit_amount bigint,
|
||||||
|
-- Three-letter ISO currency code, in lowercase.
|
||||||
|
currency text check (char_length(currency) = 3),
|
||||||
|
-- One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase.
|
||||||
|
type pricing_type,
|
||||||
|
-- The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`.
|
||||||
|
interval pricing_plan_interval,
|
||||||
|
-- The number of intervals (specified in the `interval` attribute) between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months.
|
||||||
|
interval_count integer,
|
||||||
|
-- Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan).
|
||||||
|
trial_period_days integer,
|
||||||
|
-- Set of key-value pairs, used to store additional information about the object in a structured format.
|
||||||
|
metadata jsonb
|
||||||
|
);
|
||||||
|
alter table prices enable row level security;
|
||||||
|
create policy "Allow public read-only access." on prices for select using (true);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SUBSCRIPTIONS
|
||||||
|
* Note: subscriptions are created and managed in Stripe and synced to our DB via Stripe webhooks.
|
||||||
|
*/
|
||||||
|
create type subscription_status as enum ('trialing', 'active', 'canceled', 'incomplete', 'incomplete_expired', 'past_due', 'unpaid', 'paused');
|
||||||
|
create table subscriptions (
|
||||||
|
-- Subscription ID from Stripe, e.g. sub_1234.
|
||||||
|
id text primary key,
|
||||||
|
user_id uuid references auth.users not null,
|
||||||
|
-- The status of the subscription object, one of subscription_status type above.
|
||||||
|
status subscription_status,
|
||||||
|
-- Set of key-value pairs, used to store additional information about the object in a structured format.
|
||||||
|
metadata jsonb,
|
||||||
|
-- ID of the product this subscription is for.
|
||||||
|
product_id text references products(id) not null,
|
||||||
|
-- ID of the price that created this subscription.
|
||||||
|
price_id text references prices,
|
||||||
|
-- Quantity multiplied by the unit amount of the price creates the amount of the subscription. Can be used to charge multiple seats.
|
||||||
|
quantity integer,
|
||||||
|
-- If true the subscription has been canceled by the user and will be deleted at the end of the billing period.
|
||||||
|
cancel_at_period_end boolean,
|
||||||
|
-- Time at which the subscription was created.
|
||||||
|
created timestamp with time zone default timezone('utc'::text, now()) not null,
|
||||||
|
-- Start of the current period that the subscription has been invoiced for.
|
||||||
|
current_period_start timestamp with time zone default timezone('utc'::text, now()) not null,
|
||||||
|
-- End of the current period that the subscription has been invoiced for. At the end of this period, a new invoice will be created.
|
||||||
|
current_period_end timestamp with time zone default timezone('utc'::text, now()) not null,
|
||||||
|
-- If the subscription has ended, the timestamp of the date the subscription ended.
|
||||||
|
ended_at timestamp with time zone default timezone('utc'::text, now()),
|
||||||
|
-- A date in the future at which the subscription will automatically get canceled.
|
||||||
|
cancel_at timestamp with time zone default timezone('utc'::text, now()),
|
||||||
|
-- If the subscription has been canceled, the date of that cancellation. If the subscription was canceled with `cancel_at_period_end`, `canceled_at` will still reflect the date of the initial cancellation request, not the end of the subscription period when the subscription is automatically moved to a canceled state.
|
||||||
|
canceled_at timestamp with time zone default timezone('utc'::text, now()),
|
||||||
|
-- If the subscription has a trial, the beginning of that trial.
|
||||||
|
trial_start timestamp with time zone default timezone('utc'::text, now()),
|
||||||
|
-- If the subscription has a trial, the end of that trial.
|
||||||
|
trial_end timestamp with time zone default timezone('utc'::text, now())
|
||||||
|
);
|
||||||
|
alter table subscriptions enable row level security;
|
||||||
|
create policy "Can only view own subs data." on subscriptions for select using (auth.uid() = user_id);
|
||||||
|
|
||||||
|
-- Purchases table to record product purchases.
|
||||||
|
create table purchases (
|
||||||
|
id uuid default uuid_generate_v4() primary key,
|
||||||
|
user_id uuid references auth.users not null,
|
||||||
|
product_id text references products(id) not null,
|
||||||
|
price_id text references prices(id) not null,
|
||||||
|
purchased_at timestamp with time zone not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Enabling row-level security for purchases.
|
||||||
|
alter table purchases enable row level security;
|
||||||
|
|
||||||
|
-- Creating a policy to ensure that users can only view their own purchase data.
|
||||||
|
create policy "Can view own purchase data." on purchases for select using (auth.uid() = user_id);
|
||||||
|
create policy "Can insert own purchase data." on purchases for insert with check (auth.uid() = user_id);
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
create table user_credits (
|
||||||
|
user_id uuid references auth.users not null primary key,
|
||||||
|
credits_remaining integer not null default 0,
|
||||||
|
last_updated timestamp with time zone not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table user_credits enable row level security;
|
||||||
|
|
||||||
|
create policy "Can view own credits." on user_credits
|
||||||
|
for select using (auth.uid() = user_id);
|
||||||
|
|
||||||
|
-- Uncomment and modify the update policy if allowing users to modify their own credits
|
||||||
|
-- create policy "Can update own credits." on user_credits
|
||||||
|
-- for update using (auth.uid() = user_id);
|
||||||
|
|
||||||
|
create table credit_transactions (
|
||||||
|
id uuid default uuid_generate_v4() primary key,
|
||||||
|
user_id uuid references auth.users not null,
|
||||||
|
credits_change integer not null,
|
||||||
|
description text,
|
||||||
|
created_at timestamp with time zone not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table credit_transactions enable row level security;
|
||||||
|
|
||||||
|
create policy "Can view own transactions." on credit_transactions
|
||||||
|
for select using (auth.uid() = user_id);
|
||||||
|
|
||||||
|
-- Adding indexing to improve query performance
|
||||||
|
create index on user_credits (user_id);
|
||||||
|
create index on credit_transactions (user_id);
|
||||||
|
|
||||||
|
-- Adding a check constraint to enforce data integrity
|
||||||
|
alter table credit_transactions
|
||||||
|
add constraint check_credits_change_nonzero check (credits_change <> 0);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<h1>Sign in to your account</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Click this link to log in:
|
||||||
|
<a href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email"> Log In </a>
|
||||||
|
</p>
|
||||||
+1
-1
@@ -12,7 +12,7 @@
|
|||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
"module": "es2015"
|
"module": "es2015"
|
||||||
},
|
},
|
||||||
"include": ["src/**/*", "node_modules/**/*.d.ts"]
|
"include": ["src/**/*", "node_modules/**/*.d.ts", ".svelte-kit/ambient.d.ts"]
|
||||||
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
||||||
//
|
//
|
||||||
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
import { sveltekit } from '@sveltejs/kit/vite';
|
import { sveltekit } from '@sveltejs/kit/vite';
|
||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
|
import { purgeCss } from 'vite-plugin-tailwind-purgecss';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [sveltekit()]
|
plugins: [sveltekit(), purgeCss()]
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user