The minimalistic document archiving platform.
feat(organizations): add organization subscription management (#166)
Corentin Thomasset8622751c224e
diff --git a/apps/papra-client/src/modules/organizations/pages/organizations-settings.page.tsx b/apps/papra-client/src/modules/organizations/pages/organizations-settings.page.tsxindex 3cbf3b20..bdead98c 100644--- a/apps/papra-client/src/modules/organizations/pages/organizations-settings.page.tsx+++ b/apps/papra-client/src/modules/organizations/pages/organizations-settings.page.tsx@@ -1,13 +1,15 @@import type { Organization } from '../organizations.types';import { useConfirmModal } from '@/modules/shared/confirm';import { createForm } from '@/modules/shared/form/form';+import { getCustomerPortalUrl } from '@/modules/subscriptions/subscriptions.services';import { Button } from '@/modules/ui/components/button';import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/modules/ui/components/card';import { createToast } from '@/modules/ui/components/sonner';import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';+import { safely } from '@corentinth/chisels';import { useParams } from '@solidjs/router';import { createQuery } from '@tanstack/solid-query';-import { type Component, Show, Suspense } from 'solid-js';+import { type Component, createSignal, Show, Suspense } from 'solid-js';import * as v from 'valibot';import { useDeleteOrganization, useUpdateOrganization } from '../organizations.composables';import { organizationNameSchema } from '../organizations.schemas';@@ -57,6 +59,43 @@ const DeleteOrganizationCard: Component<{ organization: Organization }> = (props);};+export const SubscriptionCard: Component<{ organization: Organization }> = (props) => {+ const [getIsLoading, setIsLoading] = createSignal(false);++ const goToCustomerPortal = async () => {+ setIsLoading(true);++ const [result, error] = await safely(getCustomerPortalUrl({ organizationId: props.organization.id }));++ if (error) {+ createToast({ type: 'error', message: 'Failed to get customer portal URL' });+ setIsLoading(false);++ return;+ }++ window.open(result.customerPortalUrl, '_blank');++ setTimeout(() => {+ setIsLoading(false);+ }, 1000);+ };++ return (+ <Card class="flex flex-col sm:flex-row justify-between gap-4 sm:items-center p-6 ">+ <div>+ <div class="font-semibold">Subscription</div>+ <div class="text-sm text-muted-foreground">+ Manage your billing, invoices and payment methods.+ </div>+ </div>+ <Button onClick={goToCustomerPortal} isLoading={getIsLoading()} class="flex-shrink-0">+ Manage subscription+ </Button>+ </Card>+ );+};+const UpdateOrganizationNameCard: Component<{ organization: Organization }> = (props) => {const { updateOrganization } = useUpdateOrganization();@@ -139,6 +178,7 @@ export const OrganizationsSettingsPage: Component = () => {<div class="mt-6 flex flex-col gap-6"><UpdateOrganizationNameCard organization={getOrganization()} />+ <SubscriptionCard organization={getOrganization()} /><DeleteOrganizationCard organization={getOrganization()} /></div></>diff --git a/apps/papra-client/src/modules/subscriptions/subscriptions.services.ts b/apps/papra-client/src/modules/subscriptions/subscriptions.services.tsnew file mode 100644index 00000000..50ced66a--- /dev/null+++ b/apps/papra-client/src/modules/subscriptions/subscriptions.services.ts@@ -0,0 +1,32 @@+import type { OrganizationSubscription } from './subscriptions.types';+import { apiClient } from '../shared/http/api-client';++export async function getCheckoutUrl({ organizationId, planId }: { organizationId: string; planId: string }) {+ const { checkoutUrl } = await apiClient<{ checkoutUrl: string }>({+ method: 'POST',+ path: `/api/organizations/${organizationId}/checkout-session`,+ body: {+ planId,+ },+ });++ return { checkoutUrl };+}++export async function getCustomerPortalUrl({ organizationId }: { organizationId: string }) {+ const { customerPortalUrl } = await apiClient<{ customerPortalUrl: string }>({+ method: 'GET',+ path: `/api/organizations/${organizationId}/customer-portal`,+ });++ return { customerPortalUrl };+}++export async function getOrganizationSubscription({ organizationId }: { organizationId: string }) {+ const { subscription } = await apiClient<{ subscription: OrganizationSubscription }>({+ method: 'GET',+ path: `/api/organizations/${organizationId}/subscription`,+ });++ return { subscription };+}diff --git a/apps/papra-client/src/modules/subscriptions/subscriptions.types.ts b/apps/papra-client/src/modules/subscriptions/subscriptions.types.tsnew file mode 100644index 00000000..f3632e0a--- /dev/null+++ b/apps/papra-client/src/modules/subscriptions/subscriptions.types.ts@@ -0,0 +1,8 @@+export type OrganizationSubscription = {+ status: string;+ currentPeriodEnd: number;+ currentPeriodStart: number;+ cancelAtPeriodEnd: boolean;+ planId: string;+ seatsCount: number;+};diff --git a/apps/papra-server/migrations/0009_subscriptions.sql b/apps/papra-server/migrations/0009_subscriptions.sqlnew file mode 100644index 00000000..cf5b9347--- /dev/null+++ b/apps/papra-server/migrations/0009_subscriptions.sql@@ -0,0 +1,2 @@+ALTER TABLE `organization_subscriptions` ADD `seats_count` integer NOT NULL;--> statement-breakpoint+CREATE INDEX `documents_organization_id_size_index` ON `documents` (`organization_id`,`original_size`);\ No newline at end of filediff --git a/apps/papra-server/migrations/0010_subscriptions-2.sql b/apps/papra-server/migrations/0010_subscriptions-2.sqlnew file mode 100644index 00000000..37b894ae--- /dev/null+++ b/apps/papra-server/migrations/0010_subscriptions-2.sql@@ -0,0 +1,4 @@+ALTER TABLE `organization_subscriptions` RENAME COLUMN "stripe_customer_id" TO "customer_id";--> statement-breakpoint+ALTER TABLE `organization_subscriptions` DROP COLUMN `stripe_subscription_id`;--> statement-breakpoint+DROP INDEX `users_customer_id_unique`;--> statement-breakpoint+ALTER TABLE `users` DROP COLUMN `customer_id`;\ No newline at end of filediff --git a/apps/papra-server/migrations/0011_orgs-customer-id.sql b/apps/papra-server/migrations/0011_orgs-customer-id.sqlnew file mode 100644index 00000000..c2cab5f9--- /dev/null+++ b/apps/papra-server/migrations/0011_orgs-customer-id.sql@@ -0,0 +1 @@+ALTER TABLE `organizations` ADD `customer_id` text;\ No newline at end of filediff --git a/apps/papra-server/migrations/meta/0009_snapshot.json b/apps/papra-server/migrations/meta/0009_snapshot.jsonnew file mode 100644index 00000000..4fc91b52--- /dev/null+++ b/apps/papra-server/migrations/meta/0009_snapshot.json@@ -0,0 +1,1230 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "1768e474-bea5-49ef-b2c9-6a4b05e1a949",+ "prevId": "6c1b50c4-dfbb-4068-9c6a-468d6cf45040",+ "tables": {+ "documents": {+ "name": "documents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_deleted": {+ "name": "is_deleted",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_by": {+ "name": "deleted_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_size": {+ "name": "original_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "original_storage_key": {+ "name": "original_storage_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_sha256_hash": {+ "name": "original_sha256_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ }+ },+ "indexes": {+ "documents_organization_id_is_deleted_created_at_index": {+ "name": "documents_organization_id_is_deleted_created_at_index",+ "columns": [+ "organization_id",+ "is_deleted",+ "created_at"+ ],+ "isUnique": false+ },+ "documents_organization_id_is_deleted_index": {+ "name": "documents_organization_id_is_deleted_index",+ "columns": [+ "organization_id",+ "is_deleted"+ ],+ "isUnique": false+ },+ "documents_organization_id_original_sha256_hash_unique": {+ "name": "documents_organization_id_original_sha256_hash_unique",+ "columns": [+ "organization_id",+ "original_sha256_hash"+ ],+ "isUnique": true+ },+ "documents_original_sha256_hash_index": {+ "name": "documents_original_sha256_hash_index",+ "columns": [+ "original_sha256_hash"+ ],+ "isUnique": false+ },+ "documents_organization_id_size_index": {+ "name": "documents_organization_id_size_index",+ "columns": [+ "organization_id",+ "original_size"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "documents_organization_id_organizations_id_fk": {+ "name": "documents_organization_id_organizations_id_fk",+ "tableFrom": "documents",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_created_by_users_id_fk": {+ "name": "documents_created_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "documents_deleted_by_users_id_fk": {+ "name": "documents_deleted_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "deleted_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_invitations": {+ "name": "organization_invitations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_invitations_organization_id_organizations_id_fk": {+ "name": "organization_invitations_organization_id_organizations_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_invitations_inviter_id_users_id_fk": {+ "name": "organization_invitations_inviter_id_users_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "users",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_members": {+ "name": "organization_members",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_members_user_organization_unique": {+ "name": "organization_members_user_organization_unique",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "organization_members_organization_id_organizations_id_fk": {+ "name": "organization_members_organization_id_organizations_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_members_user_id_users_id_fk": {+ "name": "organization_members_user_id_users_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organizations": {+ "name": "organizations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_roles": {+ "name": "user_roles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_roles_role_index": {+ "name": "user_roles_role_index",+ "columns": [+ "role"+ ],+ "isUnique": false+ },+ "user_roles_user_id_role_unique_index": {+ "name": "user_roles_user_id_role_unique_index",+ "columns": [+ "user_id",+ "role"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "user_roles_user_id_users_id_fk": {+ "name": "user_roles_user_id_users_id_fk",+ "tableFrom": "user_roles",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "documents_tags": {+ "name": "documents_tags",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "documents_tags_document_id_documents_id_fk": {+ "name": "documents_tags_document_id_documents_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "documents",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_tags_tag_id_tags_id_fk": {+ "name": "documents_tags_tag_id_tags_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {+ "documents_tags_pkey": {+ "columns": [+ "document_id",+ "tag_id"+ ],+ "name": "documents_tags_pkey"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tags": {+ "name": "tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "tags_organization_id_name_unique": {+ "name": "tags_organization_id_name_unique",+ "columns": [+ "organization_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "tags_organization_id_organizations_id_fk": {+ "name": "tags_organization_id_organizations_id_fk",+ "tableFrom": "tags",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "customer_id": {+ "name": "customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_organization_count": {+ "name": "max_organization_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ },+ "users_customer_id_unique": {+ "name": "users_customer_id_unique",+ "columns": [+ "customer_id"+ ],+ "isUnique": true+ },+ "users_email_index": {+ "name": "users_email_index",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_accounts": {+ "name": "auth_accounts",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "auth_accounts_user_id_users_id_fk": {+ "name": "auth_accounts_user_id_users_id_fk",+ "tableFrom": "auth_accounts",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_sessions": {+ "name": "auth_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_sessions_token_index": {+ "name": "auth_sessions_token_index",+ "columns": [+ "token"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auth_sessions_user_id_users_id_fk": {+ "name": "auth_sessions_user_id_users_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "auth_sessions_active_organization_id_organizations_id_fk": {+ "name": "auth_sessions_active_organization_id_organizations_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "organizations",+ "columnsFrom": [+ "active_organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_verifications": {+ "name": "auth_verifications",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_verifications_identifier_index": {+ "name": "auth_verifications_identifier_index",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "intake_emails": {+ "name": "intake_emails",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_address": {+ "name": "email_address",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "allowed_origins": {+ "name": "allowed_origins",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "is_enabled": {+ "name": "is_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "intake_emails_email_address_unique": {+ "name": "intake_emails_email_address_unique",+ "columns": [+ "email_address"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "intake_emails_organization_id_organizations_id_fk": {+ "name": "intake_emails_organization_id_organizations_id_fk",+ "tableFrom": "intake_emails",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_subscriptions": {+ "name": "organization_subscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "stripe_subscription_id": {+ "name": "stripe_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "stripe_customer_id": {+ "name": "stripe_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seats_count": {+ "name": "seats_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_start": {+ "name": "current_period_start",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cancel_at_period_end": {+ "name": "cancel_at_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_subscriptions_organization_id_organizations_id_fk": {+ "name": "organization_subscriptions_organization_id_organizations_id_fk",+ "tableFrom": "organization_subscriptions",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/apps/papra-server/migrations/meta/0010_snapshot.json b/apps/papra-server/migrations/meta/0010_snapshot.jsonnew file mode 100644index 00000000..a85ee914--- /dev/null+++ b/apps/papra-server/migrations/meta/0010_snapshot.json@@ -0,0 +1,1211 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "7c18e991-3ae7-400a-9845-40a2e98a555c",+ "prevId": "1768e474-bea5-49ef-b2c9-6a4b05e1a949",+ "tables": {+ "documents": {+ "name": "documents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_deleted": {+ "name": "is_deleted",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_by": {+ "name": "deleted_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_size": {+ "name": "original_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "original_storage_key": {+ "name": "original_storage_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_sha256_hash": {+ "name": "original_sha256_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ }+ },+ "indexes": {+ "documents_organization_id_is_deleted_created_at_index": {+ "name": "documents_organization_id_is_deleted_created_at_index",+ "columns": [+ "organization_id",+ "is_deleted",+ "created_at"+ ],+ "isUnique": false+ },+ "documents_organization_id_is_deleted_index": {+ "name": "documents_organization_id_is_deleted_index",+ "columns": [+ "organization_id",+ "is_deleted"+ ],+ "isUnique": false+ },+ "documents_organization_id_original_sha256_hash_unique": {+ "name": "documents_organization_id_original_sha256_hash_unique",+ "columns": [+ "organization_id",+ "original_sha256_hash"+ ],+ "isUnique": true+ },+ "documents_original_sha256_hash_index": {+ "name": "documents_original_sha256_hash_index",+ "columns": [+ "original_sha256_hash"+ ],+ "isUnique": false+ },+ "documents_organization_id_size_index": {+ "name": "documents_organization_id_size_index",+ "columns": [+ "organization_id",+ "original_size"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "documents_organization_id_organizations_id_fk": {+ "name": "documents_organization_id_organizations_id_fk",+ "tableFrom": "documents",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_created_by_users_id_fk": {+ "name": "documents_created_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "documents_deleted_by_users_id_fk": {+ "name": "documents_deleted_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "deleted_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_invitations": {+ "name": "organization_invitations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_invitations_organization_id_organizations_id_fk": {+ "name": "organization_invitations_organization_id_organizations_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_invitations_inviter_id_users_id_fk": {+ "name": "organization_invitations_inviter_id_users_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "users",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_members": {+ "name": "organization_members",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_members_user_organization_unique": {+ "name": "organization_members_user_organization_unique",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "organization_members_organization_id_organizations_id_fk": {+ "name": "organization_members_organization_id_organizations_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_members_user_id_users_id_fk": {+ "name": "organization_members_user_id_users_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organizations": {+ "name": "organizations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_roles": {+ "name": "user_roles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_roles_role_index": {+ "name": "user_roles_role_index",+ "columns": [+ "role"+ ],+ "isUnique": false+ },+ "user_roles_user_id_role_unique_index": {+ "name": "user_roles_user_id_role_unique_index",+ "columns": [+ "user_id",+ "role"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "user_roles_user_id_users_id_fk": {+ "name": "user_roles_user_id_users_id_fk",+ "tableFrom": "user_roles",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "documents_tags": {+ "name": "documents_tags",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "documents_tags_document_id_documents_id_fk": {+ "name": "documents_tags_document_id_documents_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "documents",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_tags_tag_id_tags_id_fk": {+ "name": "documents_tags_tag_id_tags_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {+ "documents_tags_pkey": {+ "columns": [+ "document_id",+ "tag_id"+ ],+ "name": "documents_tags_pkey"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tags": {+ "name": "tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "tags_organization_id_name_unique": {+ "name": "tags_organization_id_name_unique",+ "columns": [+ "organization_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "tags_organization_id_organizations_id_fk": {+ "name": "tags_organization_id_organizations_id_fk",+ "tableFrom": "tags",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_organization_count": {+ "name": "max_organization_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ },+ "users_email_index": {+ "name": "users_email_index",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_accounts": {+ "name": "auth_accounts",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "auth_accounts_user_id_users_id_fk": {+ "name": "auth_accounts_user_id_users_id_fk",+ "tableFrom": "auth_accounts",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_sessions": {+ "name": "auth_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_sessions_token_index": {+ "name": "auth_sessions_token_index",+ "columns": [+ "token"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auth_sessions_user_id_users_id_fk": {+ "name": "auth_sessions_user_id_users_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "auth_sessions_active_organization_id_organizations_id_fk": {+ "name": "auth_sessions_active_organization_id_organizations_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "organizations",+ "columnsFrom": [+ "active_organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_verifications": {+ "name": "auth_verifications",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_verifications_identifier_index": {+ "name": "auth_verifications_identifier_index",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "intake_emails": {+ "name": "intake_emails",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_address": {+ "name": "email_address",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "allowed_origins": {+ "name": "allowed_origins",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "is_enabled": {+ "name": "is_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "intake_emails_email_address_unique": {+ "name": "intake_emails_email_address_unique",+ "columns": [+ "email_address"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "intake_emails_organization_id_organizations_id_fk": {+ "name": "intake_emails_organization_id_organizations_id_fk",+ "tableFrom": "intake_emails",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_subscriptions": {+ "name": "organization_subscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "customer_id": {+ "name": "customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seats_count": {+ "name": "seats_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_start": {+ "name": "current_period_start",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cancel_at_period_end": {+ "name": "cancel_at_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_subscriptions_organization_id_organizations_id_fk": {+ "name": "organization_subscriptions_organization_id_organizations_id_fk",+ "tableFrom": "organization_subscriptions",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {+ "\"organization_subscriptions\".\"stripe_customer_id\"": "\"organization_subscriptions\".\"customer_id\""+ }+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/apps/papra-server/migrations/meta/0011_snapshot.json b/apps/papra-server/migrations/meta/0011_snapshot.jsonnew file mode 100644index 00000000..900905dd--- /dev/null+++ b/apps/papra-server/migrations/meta/0011_snapshot.json@@ -0,0 +1,1216 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "9212b959-8c57-4df5-aeda-09c6e39a9062",+ "prevId": "7c18e991-3ae7-400a-9845-40a2e98a555c",+ "tables": {+ "documents": {+ "name": "documents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_deleted": {+ "name": "is_deleted",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_by": {+ "name": "deleted_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_size": {+ "name": "original_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "original_storage_key": {+ "name": "original_storage_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_sha256_hash": {+ "name": "original_sha256_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ }+ },+ "indexes": {+ "documents_organization_id_is_deleted_created_at_index": {+ "name": "documents_organization_id_is_deleted_created_at_index",+ "columns": [+ "organization_id",+ "is_deleted",+ "created_at"+ ],+ "isUnique": false+ },+ "documents_organization_id_is_deleted_index": {+ "name": "documents_organization_id_is_deleted_index",+ "columns": [+ "organization_id",+ "is_deleted"+ ],+ "isUnique": false+ },+ "documents_organization_id_original_sha256_hash_unique": {+ "name": "documents_organization_id_original_sha256_hash_unique",+ "columns": [+ "organization_id",+ "original_sha256_hash"+ ],+ "isUnique": true+ },+ "documents_original_sha256_hash_index": {+ "name": "documents_original_sha256_hash_index",+ "columns": [+ "original_sha256_hash"+ ],+ "isUnique": false+ },+ "documents_organization_id_size_index": {+ "name": "documents_organization_id_size_index",+ "columns": [+ "organization_id",+ "original_size"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "documents_organization_id_organizations_id_fk": {+ "name": "documents_organization_id_organizations_id_fk",+ "tableFrom": "documents",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_created_by_users_id_fk": {+ "name": "documents_created_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "documents_deleted_by_users_id_fk": {+ "name": "documents_deleted_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "deleted_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_invitations": {+ "name": "organization_invitations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_invitations_organization_id_organizations_id_fk": {+ "name": "organization_invitations_organization_id_organizations_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_invitations_inviter_id_users_id_fk": {+ "name": "organization_invitations_inviter_id_users_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "users",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_members": {+ "name": "organization_members",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_members_user_organization_unique": {+ "name": "organization_members_user_organization_unique",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "organization_members_organization_id_organizations_id_fk": {+ "name": "organization_members_organization_id_organizations_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_members_user_id_users_id_fk": {+ "name": "organization_members_user_id_users_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organizations": {+ "name": "organizations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "customer_id": {+ "name": "customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_roles": {+ "name": "user_roles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_roles_role_index": {+ "name": "user_roles_role_index",+ "columns": [+ "role"+ ],+ "isUnique": false+ },+ "user_roles_user_id_role_unique_index": {+ "name": "user_roles_user_id_role_unique_index",+ "columns": [+ "user_id",+ "role"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "user_roles_user_id_users_id_fk": {+ "name": "user_roles_user_id_users_id_fk",+ "tableFrom": "user_roles",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "documents_tags": {+ "name": "documents_tags",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "documents_tags_document_id_documents_id_fk": {+ "name": "documents_tags_document_id_documents_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "documents",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_tags_tag_id_tags_id_fk": {+ "name": "documents_tags_tag_id_tags_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {+ "documents_tags_pkey": {+ "columns": [+ "document_id",+ "tag_id"+ ],+ "name": "documents_tags_pkey"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tags": {+ "name": "tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "tags_organization_id_name_unique": {+ "name": "tags_organization_id_name_unique",+ "columns": [+ "organization_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "tags_organization_id_organizations_id_fk": {+ "name": "tags_organization_id_organizations_id_fk",+ "tableFrom": "tags",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_organization_count": {+ "name": "max_organization_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ },+ "users_email_index": {+ "name": "users_email_index",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_accounts": {+ "name": "auth_accounts",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "auth_accounts_user_id_users_id_fk": {+ "name": "auth_accounts_user_id_users_id_fk",+ "tableFrom": "auth_accounts",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_sessions": {+ "name": "auth_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_sessions_token_index": {+ "name": "auth_sessions_token_index",+ "columns": [+ "token"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auth_sessions_user_id_users_id_fk": {+ "name": "auth_sessions_user_id_users_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "auth_sessions_active_organization_id_organizations_id_fk": {+ "name": "auth_sessions_active_organization_id_organizations_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "organizations",+ "columnsFrom": [+ "active_organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_verifications": {+ "name": "auth_verifications",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_verifications_identifier_index": {+ "name": "auth_verifications_identifier_index",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "intake_emails": {+ "name": "intake_emails",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_address": {+ "name": "email_address",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "allowed_origins": {+ "name": "allowed_origins",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "is_enabled": {+ "name": "is_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "intake_emails_email_address_unique": {+ "name": "intake_emails_email_address_unique",+ "columns": [+ "email_address"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "intake_emails_organization_id_organizations_id_fk": {+ "name": "intake_emails_organization_id_organizations_id_fk",+ "tableFrom": "intake_emails",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_subscriptions": {+ "name": "organization_subscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "customer_id": {+ "name": "customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seats_count": {+ "name": "seats_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_start": {+ "name": "current_period_start",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cancel_at_period_end": {+ "name": "cancel_at_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_subscriptions_organization_id_organizations_id_fk": {+ "name": "organization_subscriptions_organization_id_organizations_id_fk",+ "tableFrom": "organization_subscriptions",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.jsonindex 91fc2a59..a1a90cd2 100644--- a/apps/papra-server/migrations/meta/_journal.json+++ b/apps/papra-server/migrations/meta/_journal.json@@ -64,6 +64,27 @@"when": 1742246019130,"tag": "0008_max-user-organization-count","breakpoints": true+ },+ {+ "idx": 9,+ "version": "6",+ "when": 1742335878357,+ "tag": "0009_subscriptions",+ "breakpoints": true+ },+ {+ "idx": 10,+ "version": "6",+ "when": 1742336671903,+ "tag": "0010_subscriptions-2",+ "breakpoints": true+ },+ {+ "idx": 11,+ "version": "6",+ "when": 1742339890093,+ "tag": "0011_orgs-customer-id",+ "breakpoints": true}]}diff --git a/apps/papra-server/package.json b/apps/papra-server/package.jsonindex 61f47ac8..8cdf276f 100644--- a/apps/papra-server/package.json+++ b/apps/papra-server/package.json@@ -25,7 +25,8 @@"clean:storage": "rm -rf local-documents","clean:all": "pnpm clean:db && pnpm clean:storage","dev:reset": "pnpm clean:all && pnpm migrate:push",- "script:send-intake-email": "tsx --env-file-if-exists=.env src/scripts/send-intake-email.script.ts | crowlog-pretty"+ "script:send-intake-email": "tsx --env-file-if-exists=.env src/scripts/send-intake-email.script.ts | crowlog-pretty",+ "stripe:webhook": "stripe listen --forward-to localhost:1221/api/stripe/webhook"},"dependencies": {"@aws-sdk/client-s3": "^3.722.0",diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.tsindex 8625ffc8..eb8e6b95 100644--- a/apps/papra-server/src/modules/app/server.routes.ts+++ b/apps/papra-server/src/modules/app/server.routes.ts@@ -3,6 +3,7 @@ import { registerConfigPublicRoutes } from '../config/config.routes';import { registerDocumentsPrivateRoutes } from '../documents/documents.routes';import { registerIntakeEmailsPrivateRoutes, registerIntakeEmailsPublicRoutes } from '../intake-emails/intake-emails.routes';import { registerOrganizationsPrivateRoutes } from '../organizations/organizations.routes';+import { registerSubscriptionsPrivateRoutes, registerSubscriptionsPublicRoutes } from '../subscriptions/subscriptions.routes';import { registerTagsRoutes } from '../tags/tags.routes';import { registerUsersPrivateRoutes } from '../users/users.routes';import { createUnauthorizedError } from './auth/auth.errors';@@ -21,6 +22,7 @@ function registerPublicRoutes(context: RouteDefinitionContext) {registerConfigPublicRoutes(context);registerHealthCheckRoutes(context);registerIntakeEmailsPublicRoutes(context);+ registerSubscriptionsPublicRoutes(context);}function registerPrivateRoutes(context: RouteDefinitionContext) {@@ -39,4 +41,5 @@ function registerPrivateRoutes(context: RouteDefinitionContext) {registerDocumentsPrivateRoutes(context);registerTagsRoutes(context);registerIntakeEmailsPrivateRoutes(context);+ registerSubscriptionsPrivateRoutes(context);}diff --git a/apps/papra-server/src/modules/app/server.ts b/apps/papra-server/src/modules/app/server.tsindex 735f078f..7478e091 100644--- a/apps/papra-server/src/modules/app/server.ts+++ b/apps/papra-server/src/modules/app/server.ts@@ -4,6 +4,7 @@ import { secureHeaders } from 'hono/secure-headers';import { parseConfig } from '../config/config';import { createEmailsServices } from '../emails/emails.services';import { createLoggerMiddleware } from '../shared/logger/logger.middleware';+import { createSubscriptionsServices } from '../subscriptions/subscriptions.services';import { createAuthEmailsServices } from './auth/auth.emails.services';import { getAuth } from './auth/auth.services';import { setupDatabase } from './database/database';@@ -18,12 +19,14 @@ function createGlobalDependencies(partialDeps: Partial<GlobalDependencies>): Gloconst db = partialDeps.db ?? setupDatabase(config.database).db;const emailsServices = createEmailsServices({ config });const auth = partialDeps.auth ?? getAuth({ db, config, authEmailsServices: createAuthEmailsServices({ emailsServices }) }).auth;+ const subscriptionsServices = createSubscriptionsServices({ config });return {config,db,auth,emailsServices,+ subscriptionsServices,};}diff --git a/apps/papra-server/src/modules/app/server.types.ts b/apps/papra-server/src/modules/app/server.types.tsindex 6867f574..3d59b620 100644--- a/apps/papra-server/src/modules/app/server.types.ts+++ b/apps/papra-server/src/modules/app/server.types.ts@@ -1,6 +1,7 @@import type { Context as BaseContext, Hono } from 'hono';import type { Config } from '../config/config.types';import type { EmailsServices } from '../emails/emails.services';+import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';import type { Auth } from './auth/auth.services';import type { Database } from './database/database.types';@@ -20,6 +21,7 @@ export type GlobalDependencies = {db: Database;auth: Auth;emailsServices: EmailsServices;+ subscriptionsServices: SubscriptionsServices;};export type RouteDefinitionContext = { app: ServerInstance } & GlobalDependencies;diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.tsindex 1a1377f3..9dd62024 100644--- a/apps/papra-server/src/modules/config/config.ts+++ b/apps/papra-server/src/modules/config/config.ts@@ -12,6 +12,7 @@ import { intakeEmailsConfig } from '../intake-emails/intake-emails.config';import { organizationsConfig } from '../organizations/organizations.config';import { organizationPlansConfig } from '../plans/plans.config';import { createLogger } from '../shared/logger/logger';+import { subscriptionsConfig } from '../subscriptions/subscriptions.config';import { tasksConfig } from '../tasks/tasks.config';export const configDefinition = {@@ -84,6 +85,7 @@ export const configDefinition = {emails: emailsConfig,organizations: organizationsConfig,organizationPlans: organizationPlansConfig,+ subscriptions: subscriptionsConfig,} as const satisfies ConfigDefinition;const logger = createLogger({ namespace: 'config' });diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.tsindex e3b0a56b..412d4d21 100644--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts@@ -215,11 +215,11 @@ describe('intake-emails usecases', () => {id: 'os-1',organizationId: 'org-1',status: 'active',+ seatsCount: 1,currentPeriodStart: new Date('2025-03-18T00:00:00.000Z'),currentPeriodEnd: new Date('2025-04-18T00:00:00.000Z'),- stripeCustomerId: 'sc_123',+ customerId: 'sc_123',planId: PLUS_PLAN_ID,- stripeSubscriptionId: 'sub_123',}],});@@ -236,7 +236,8 @@ describe('intake-emails usecases', () => {},},}),- } as PlansRepository;+ } as unknown as PlansRepository;+const subscriptionsRepository = createSubscriptionsRepository({ db });// no throw as the intake email count is less than the allowed limitdiff --git a/apps/papra-server/src/modules/organizations/organizations.errors.ts b/apps/papra-server/src/modules/organizations/organizations.errors.tsindex da29ae0f..15435a65 100644--- a/apps/papra-server/src/modules/organizations/organizations.errors.ts+++ b/apps/papra-server/src/modules/organizations/organizations.errors.ts@@ -23,3 +23,9 @@ export const createOrganizationDocumentStorageLimitReachedError = createErrorFaccode: 'organization.document_storage_limit_reached',statusCode: 403,});++export const createUserNotOrganizationOwnerError = createErrorFactory({+ message: 'You are not the owner of this organization.',+ code: 'user.not_organization_owner',+ statusCode: 403,+});diff --git a/apps/papra-server/src/modules/organizations/organizations.repository.ts b/apps/papra-server/src/modules/organizations/organizations.repository.tsindex 69082bf1..4ebca1b4 100644--- a/apps/papra-server/src/modules/organizations/organizations.repository.ts+++ b/apps/papra-server/src/modules/organizations/organizations.repository.ts@@ -2,6 +2,8 @@ import type { Database } from '../app/database/database.types';import type { DbInsertableOrganization } from './organizations.types';import { injectArguments } from '@corentinth/chisels';import { and, count, eq, getTableColumns } from 'drizzle-orm';+import { omitUndefined } from '../shared/utils';+import { usersTable } from '../users/users.table';import { ORGANIZATION_ROLES } from './organizations.constants';import { organizationMembersTable, organizationsTable } from './organizations.table';@@ -18,6 +20,8 @@ export function createOrganizationsRepository({ db }: { db: Database }) {deleteOrganization,getOrganizationById,getUserOwnedOrganizationCount,+ getOrganizationOwner,+ getOrganizationMembersCount,},{ db },);@@ -61,12 +65,10 @@ async function isUserInOrganization({ userId, organizationId, db }: { userId: st};}-async function updateOrganization({ organizationId, organization: organizationToUpdate, db }: { organizationId: string; organization: { name: string }; db: Database }) {+async function updateOrganization({ organizationId, organization: organizationToUpdate, db }: { organizationId: string; organization: { name?: string; customerId?: string }; db: Database }) {const [organization] = await db.update(organizationsTable)- .set({- name: organizationToUpdate.name,- })+ .set(omitUndefined(organizationToUpdate)).where(eq(organizationsTable.id, organizationId)).returning();@@ -105,3 +107,35 @@ async function getUserOwnedOrganizationCount({ userId, db }: { userId: string; dorganizationCount,};}++async function getOrganizationOwner({ organizationId, db }: { organizationId: string; db: Database }) {+ const [{ organizationOwner }] = await db+ .select({+ organizationOwner: getTableColumns(usersTable),+ })+ .from(usersTable)+ .leftJoin(organizationMembersTable, eq(usersTable.id, organizationMembersTable.userId))+ .where(+ and(+ eq(organizationMembersTable.organizationId, organizationId),+ eq(organizationMembersTable.role, ORGANIZATION_ROLES.OWNER),+ ),+ );++ return { organizationOwner };+}++async function getOrganizationMembersCount({ organizationId, db }: { organizationId: string; db: Database }) {+ const [{ membersCount }] = await db+ .select({+ membersCount: count(organizationMembersTable.id),+ })+ .from(organizationMembersTable)+ .where(+ eq(organizationMembersTable.organizationId, organizationId),+ );++ return {+ membersCount,+ };+}diff --git a/apps/papra-server/src/modules/organizations/organizations.table.ts b/apps/papra-server/src/modules/organizations/organizations.table.tsindex ba2666ae..5cfb0d28 100644--- a/apps/papra-server/src/modules/organizations/organizations.table.ts+++ b/apps/papra-server/src/modules/organizations/organizations.table.ts@@ -7,6 +7,7 @@ export const organizationsTable = sqliteTable('organizations', {...createTimestampColumns(),name: text('name').notNull(),+ customerId: text('customer_id'),});export const organizationMembersTable = sqliteTable('organization_members', {diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.test.tsindex 4c157702..42e0aa0a 100644--- a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts@@ -1,4 +1,5 @@import type { PlansRepository } from '../plans/plans.repository';+import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';import { overrideConfig } from '../config/config.test-utils';@@ -7,10 +8,10 @@ import { PLUS_PLAN_ID } from '../plans/plans.constants';import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';import { createUsersRepository } from '../users/users.repository';import { ORGANIZATION_ROLES } from './organizations.constants';-import { createOrganizationDocumentStorageLimitReachedError, createUserMaxOrganizationCountReachedError, createUserNotInOrganizationError } from './organizations.errors';+import { createOrganizationDocumentStorageLimitReachedError, createOrganizationNotFoundError, createUserMaxOrganizationCountReachedError, createUserNotInOrganizationError, createUserNotOrganizationOwnerError } from './organizations.errors';import { createOrganizationsRepository } from './organizations.repository';import { organizationMembersTable, organizationsTable } from './organizations.table';-import { checkIfOrganizationCanCreateNewDocument, checkIfUserCanCreateNewOrganization, ensureUserIsInOrganization } from './organizations.usecases';+import { checkIfOrganizationCanCreateNewDocument, checkIfUserCanCreateNewOrganization, ensureUserIsInOrganization, ensureUserIsOwnerOfOrganization, getOrCreateOrganizationCustomerId } from './organizations.usecases';describe('organizations usecases', () => {describe('ensureUserIsInOrganization', () => {@@ -163,8 +164,8 @@ describe('organizations usecases', () => {id: 'org_sub_1',organizationId: 'organization-1',planId: PLUS_PLAN_ID,- stripeSubscriptionId: 'sub_123',- stripeCustomerId: 'cus_123',+ seatsCount: 1,+ customerId: 'cus_123',status: 'active',currentPeriodStart: new Date('2025-03-18T00:00:00.000Z'),currentPeriodEnd: new Date('2025-04-18T00:00:00.000Z'),@@ -194,7 +195,7 @@ describe('organizations usecases', () => {},},}),- } as PlansRepository;+ } as unknown as PlansRepository;const subscriptionsRepository = createSubscriptionsRepository({ db });const documentsRepository = createDocumentsRepository({ db });@@ -222,4 +223,132 @@ describe('organizations usecases', () => {);});});++ describe('getOrCreateOrganizationCustomerId', () => {+ describe(`in order to handle organization subscriptions, we need a stripe customer id per organization+ as stripe require an email per customer, we use the organization owner's email`, () => {+ test('an organization that does not have a customer id, will have one created and saved', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],+ organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],+ });++ const organizationsRepository = createOrganizationsRepository({ db });+ const createCustomerArgs: unknown[] = [];++ const subscriptionsServices = {+ createCustomer: async (args: unknown) => {+ createCustomerArgs.push(args);+ return { customerId: 'cus_123' };+ },+ } as unknown as SubscriptionsServices;++ const { customerId } = await getOrCreateOrganizationCustomerId({+ organizationId: 'organization-1',+ subscriptionsServices,+ organizationsRepository,+ });++ expect(createCustomerArgs).toEqual([{ email: '[email protected]', ownerId: 'user-1', organizationId: 'organization-1' }]);+ expect(customerId).toEqual('cus_123');++ const { organization } = await organizationsRepository.getOrganizationById({ organizationId: 'organization-1' });++ expect(organization?.customerId).toEqual('cus_123');+ });++ test('an organization that already has a customer id, will not have a new customer created', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1', customerId: 'cus_123' }],+ organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],+ });++ const organizationsRepository = createOrganizationsRepository({ db });+ const subscriptionsServices = {+ createCustomer: async () => expect.fail('createCustomer should not be called'),+ } as unknown as SubscriptionsServices;++ const { customerId } = await getOrCreateOrganizationCustomerId({+ organizationId: 'organization-1',+ subscriptionsServices,+ organizationsRepository,+ });++ expect(customerId).toEqual('cus_123');++ // ensure the customer id is still the same in the database+ const { organization } = await organizationsRepository.getOrganizationById({ organizationId: 'organization-1' });++ expect(organization?.customerId).toEqual('cus_123');+ });++ test('if the organization does not exist, an error is thrown', async () => {+ const { db } = await createInMemoryDatabase();+ const organizationsRepository = createOrganizationsRepository({ db });+ const subscriptionsServices = {+ createCustomer: async () => expect.fail('createCustomer should not be called'),+ } as unknown as SubscriptionsServices;++ await expect(+ getOrCreateOrganizationCustomerId({+ organizationId: 'organization-1',+ subscriptionsServices,+ organizationsRepository,+ }),+ ).rejects.toThrow(+ createOrganizationNotFoundError(),+ );+ });+ });+ });++ describe('ensureUserIsOwnerOfOrganization', () => {+ test('throws an error if the user is not the owner of the organization', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: 'user-1', email: '[email protected]' },+ { id: 'user-2', email: '[email protected]' },+ { id: 'user-3', email: '[email protected]' },+ ],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],+ organizationMembers: [+ { organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER },+ { organizationId: 'organization-1', userId: 'user-2', role: ORGANIZATION_ROLES.MEMBER },+ ],+ });++ const organizationsRepository = createOrganizationsRepository({ db });++ // no throw as user-1 is the owner of the organization+ await ensureUserIsOwnerOfOrganization({+ userId: 'user-1',+ organizationId: 'organization-1',+ organizationsRepository,+ });++ // throw as user-2 is not the owner of the organization+ await expect(+ ensureUserIsOwnerOfOrganization({+ userId: 'user-2',+ organizationId: 'organization-1',+ organizationsRepository,+ }),+ ).rejects.toThrow(+ createUserNotOrganizationOwnerError(),+ );++ // throw as user-3 is not in the organization+ await expect(+ ensureUserIsOwnerOfOrganization({+ userId: 'user-3',+ organizationId: 'organization-1',+ organizationsRepository,+ }),+ ).rejects.toThrow(+ createUserNotOrganizationOwnerError(),+ );+ });+ });});diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.tsindex 9530aafc..24e13bb6 100644--- a/apps/papra-server/src/modules/organizations/organizations.usecases.ts+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.ts@@ -2,11 +2,12 @@ import type { Config } from '../config/config.types';import type { DocumentsRepository } from '../documents/documents.repository';import type { PlansRepository } from '../plans/plans.repository';import type { SubscriptionsRepository } from '../subscriptions/subscriptions.repository';+import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';import type { UsersRepository } from '../users/users.repository';import type { OrganizationsRepository } from './organizations.repository';import { getOrganizationPlan } from '../plans/plans.usecases';import { ORGANIZATION_ROLES } from './organizations.constants';-import { createOrganizationDocumentStorageLimitReachedError, createUserMaxOrganizationCountReachedError, createUserNotInOrganizationError } from './organizations.errors';+import { createOrganizationDocumentStorageLimitReachedError, createOrganizationNotFoundError, createUserMaxOrganizationCountReachedError, createUserNotInOrganizationError, createUserNotOrganizationOwnerError } from './organizations.errors';export async function createOrganization({ name, userId, organizationsRepository }: { name: string; userId: string; organizationsRepository: OrganizationsRepository }) {const { organization } = await organizationsRepository.saveOrganization({ organization: { name } });@@ -78,3 +79,54 @@ export async function checkIfOrganizationCanCreateNewDocument({throw createOrganizationDocumentStorageLimitReachedError();}}++export async function getOrCreateOrganizationCustomerId({+ organizationId,+ subscriptionsServices,+ organizationsRepository,+}: {+ organizationId: string;+ subscriptionsServices: SubscriptionsServices;+ organizationsRepository: OrganizationsRepository;+}) {+ const { organization } = await organizationsRepository.getOrganizationById({ organizationId });++ if (!organization) {+ throw createOrganizationNotFoundError();+ }++ if (organization.customerId) {+ return { customerId: organization.customerId };+ }++ const { organizationOwner } = await organizationsRepository.getOrganizationOwner({ organizationId });++ const { customerId } = await subscriptionsServices.createCustomer({+ ownerId: organizationOwner.id,+ email: organizationOwner.email,+ organizationId,+ });++ await organizationsRepository.updateOrganization({+ organizationId,+ organization: { customerId },+ });++ return { customerId };+}++export async function ensureUserIsOwnerOfOrganization({+ userId,+ organizationId,+ organizationsRepository,+}: {+ userId: string;+ organizationId: string;+ organizationsRepository: OrganizationsRepository;+}) {+ const { organizationOwner } = await organizationsRepository.getOrganizationOwner({ organizationId });++ if (organizationOwner.id !== userId) {+ throw createUserNotOrganizationOwnerError();+ }+}diff --git a/apps/papra-server/src/modules/plans/plans.config.ts b/apps/papra-server/src/modules/plans/plans.config.tsindex fff63e19..5615cfd4 100644--- a/apps/papra-server/src/modules/plans/plans.config.ts+++ b/apps/papra-server/src/modules/plans/plans.config.ts@@ -16,7 +16,13 @@ export const organizationPlansConfig = {plusPlanPriceId: {doc: 'The price id of the plus plan',schema: z.string(),- default: 'price_123456',+ default: 'change-me',env: 'PLANS_PLUS_PLAN_PRICE_ID',},+ familyPlanPriceId: {+ doc: 'The price id of the family plan',+ schema: z.string(),+ default: 'change-me',+ env: 'PLANS_FAMILY_PLAN_PRICE_ID',+ },} as const satisfies ConfigDefinition;diff --git a/apps/papra-server/src/modules/plans/plans.constants.ts b/apps/papra-server/src/modules/plans/plans.constants.tsindex d58130cc..2050239c 100644--- a/apps/papra-server/src/modules/plans/plans.constants.ts+++ b/apps/papra-server/src/modules/plans/plans.constants.ts@@ -1,2 +1,3 @@export const FREE_PLAN_ID = 'free';export const PLUS_PLAN_ID = 'plus';+export const FAMILY_PLAN_ID = 'family';diff --git a/apps/papra-server/src/modules/plans/plans.repository.ts b/apps/papra-server/src/modules/plans/plans.repository.tsindex 08616b1b..c1c708a6 100644--- a/apps/papra-server/src/modules/plans/plans.repository.ts+++ b/apps/papra-server/src/modules/plans/plans.repository.ts@@ -1,7 +1,7 @@import type { Config } from '../config/config.types';import type { OrganizationPlanRecord } from './plans.types';import { injectArguments } from '@corentinth/chisels';-import { FREE_PLAN_ID, PLUS_PLAN_ID } from './plans.constants';+import { FAMILY_PLAN_ID, FREE_PLAN_ID, PLUS_PLAN_ID } from './plans.constants';import { createPlanNotFoundError } from './plans.errors';export type PlansRepository = ReturnType<typeof createPlansRepository>;@@ -12,6 +12,7 @@ export function createPlansRepository({ config }: { config: Config }) {return injectArguments({getOrganizationPlanById,+ getOrganizationPlanByPriceId,},{organizationPlans,@@ -26,22 +27,37 @@ export function getOrganizationPlansRecords({ config }: { config: Config }) {[FREE_PLAN_ID]: {id: FREE_PLAN_ID,name: 'Free',+ isPerSeat: true,limits: {maxDocumentStorageBytes: isFreePlanUnlimited ? Number.POSITIVE_INFINITY : 1024 * 1024 * 500, // 500 MBmaxIntakeEmailsCount: isFreePlanUnlimited ? Number.POSITIVE_INFINITY : 1,maxOrganizationsMembersCount: isFreePlanUnlimited ? Number.POSITIVE_INFINITY : 10,},+},[PLUS_PLAN_ID]: {id: PLUS_PLAN_ID,name: 'Plus',priceId: config.organizationPlans.plusPlanPriceId,+ isPerSeat: true,limits: {maxDocumentStorageBytes: 1024 * 1024 * 1024 * 5, // 5 GBmaxIntakeEmailsCount: 10,maxOrganizationsMembersCount: 100,},},+ [FAMILY_PLAN_ID]: {+ id: FAMILY_PLAN_ID,+ name: 'Family',+ priceId: config.organizationPlans.familyPlanPriceId,+ isPerSeat: false,+ defaultSeatsCount: 6,+ limits: {+ maxDocumentStorageBytes: 1024 * 1024 * 1024 * 5, // 5 GB+ maxIntakeEmailsCount: 10,+ maxOrganizationsMembersCount: 6,+ },+ },};return { organizationPlans };@@ -56,3 +72,13 @@ async function getOrganizationPlanById({ planId, organizationPlans }: { planId:return { organizationPlan };}++async function getOrganizationPlanByPriceId({ priceId, organizationPlans }: { priceId: string; organizationPlans: Record<string, OrganizationPlanRecord> }) {+ const organizationPlan = Object.values(organizationPlans).find(plan => plan.priceId === priceId);++ if (!organizationPlan) {+ throw createPlanNotFoundError();+ }++ return { organizationPlan };+}diff --git a/apps/papra-server/src/modules/plans/plans.types.ts b/apps/papra-server/src/modules/plans/plans.types.tsindex 00bcfdff..bf44708e 100644--- a/apps/papra-server/src/modules/plans/plans.types.ts+++ b/apps/papra-server/src/modules/plans/plans.types.ts@@ -2,10 +2,11 @@ export type OrganizationPlanRecord = {id: string;name: string;priceId?: string;+ defaultSeatsCount?: number;+ isPerSeat: boolean;limits: {maxDocumentStorageBytes: number;maxIntakeEmailsCount: number;maxOrganizationsMembersCount: number;-};};diff --git a/apps/papra-server/src/modules/plans/plans.usecases.test.ts b/apps/papra-server/src/modules/plans/plans.usecases.test.tsindex 6419aca2..1ebf6561 100644--- a/apps/papra-server/src/modules/plans/plans.usecases.test.ts+++ b/apps/papra-server/src/modules/plans/plans.usecases.test.ts@@ -18,8 +18,8 @@ describe('plans usecases', () => {id: 'org_sub_1',organizationId: 'organization-1',planId: PLUS_PLAN_ID,- stripeSubscriptionId: 'sub_123',- stripeCustomerId: 'cus_123',+ customerId: 'cus_123',+ seatsCount: 1,status: 'active',currentPeriodStart: new Date('2025-03-18T00:00:00.000Z'),currentPeriodEnd: new Date('2025-04-18T00:00:00.000Z'),diff --git a/apps/papra-server/src/modules/subscriptions/stripe.services.ts b/apps/papra-server/src/modules/subscriptions/stripe.services.tsdeleted file mode 100644index d46a7df2..00000000--- a/apps/papra-server/src/modules/subscriptions/stripe.services.ts+++ /dev/null@@ -1,7 +0,0 @@-import Stripe from 'stripe';--export function createStripeClient({ stripeApiSecretKey }: { stripeApiSecretKey: string }) {- const stripeClient = new Stripe(stripeApiSecretKey);-- return { stripeClient };-}diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.config.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.config.tsnew file mode 100644index 00000000..4e39a26d--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.config.ts@@ -0,0 +1,17 @@+import type { ConfigDefinition } from 'figue';+import { z } from 'zod';++export const subscriptionsConfig = {+ stripeApiSecretKey: {+ doc: 'The API secret key for the Stripe',+ schema: z.string(),+ default: 'change-me',+ env: 'STRIPE_API_SECRET_KEY',+ },+ stripeWebhookSecret: {+ doc: 'The secret for the Stripe webhook',+ schema: z.string(),+ default: 'change-me',+ env: 'STRIPE_WEBHOOK_SECRET',+ },+} as const satisfies ConfigDefinition;diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.errors.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.errors.tsnew file mode 100644index 00000000..d35a7c8b--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.errors.ts@@ -0,0 +1,19 @@+import { createErrorFactory } from '../shared/errors/errors';++export const createOrganizationAlreadyHasSubscriptionError = createErrorFactory({+ message: 'Organization already has an active subscription',+ code: 'subscriptions.organization_already_has_subscription',+ statusCode: 400,+});++export const createUserHasNoSubscriptionError = createErrorFactory({+ message: 'User does not have an active subscription',+ code: 'subscriptions.user_has_no_subscription',+ statusCode: 400,+});++export const createInvalidWebhookPayloadError = createErrorFactory({+ message: 'Invalid webhook payload',+ code: 'subscriptions.invalid_webhook_payload',+ statusCode: 400,+});diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.models.test.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.models.test.tsnew file mode 100644index 00000000..6eafa792--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.models.test.ts@@ -0,0 +1,13 @@+import { describe, expect, test } from 'vitest';+import { coerceStripeTimestampToDate } from './subscriptions.models';++describe('subscriptions models', () => {+ describe('coerceStripeTimestampToDate', () => {+ test('stripe api dates are represented as unix timestamps (in seconds) and should be converted to JavaScript dates', () => {+ const date = coerceStripeTimestampToDate(1716150383);++ expect(date).to.deep.equal(new Date(1716150383 * 1000));+ expect(date).to.deep.equal(new Date('2024-05-19T20:26:23.000Z'));+ });+ });+});diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.models.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.models.tsnew file mode 100644index 00000000..a1283603--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.models.ts@@ -0,0 +1,3 @@+export function coerceStripeTimestampToDate(timestamp: number) {+ return new Date(timestamp * 1000);+}diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.repository.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.repository.tsindex 2ca1056a..96176bf7 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.repository.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.repository.ts@@ -1,6 +1,8 @@import type { Database } from '../app/database/database.types';+import type { DbInsertableSubscription } from './subscriptions.types';import { injectArguments } from '@corentinth/chisels';import { eq } from 'drizzle-orm';+import { omitUndefined } from '../shared/utils';import { organizationSubscriptionsTable } from './subscriptions.tables';export type SubscriptionsRepository = ReturnType<typeof createSubscriptionsRepository>;@@ -9,6 +11,8 @@ export function createSubscriptionsRepository({ db }: { db: Database }) {return injectArguments({getOrganizationSubscription,+ createSubscription,+ updateSubscription,},{db,@@ -26,3 +30,21 @@ async function getOrganizationSubscription({ organizationId, db }: { organizatioreturn { subscription };}++async function createSubscription({ db, ...subscription }: { db: Database } & DbInsertableSubscription) {+ const [createdSubscription] = await db.insert(organizationSubscriptionsTable).values(subscription).returning();++ return { createdSubscription };+}++async function updateSubscription({ subscriptionId, db, ...subscription }: { subscriptionId: string; db: Database } & Omit<Partial<DbInsertableSubscription>, 'id'>) {+ const [updatedSubscription] = await db+ .update(organizationSubscriptionsTable)+ .set(omitUndefined(subscription))+ .where(+ eq(organizationSubscriptionsTable.id, subscriptionId),+ )+ .returning();++ return { updatedSubscription };+}diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.tsnew file mode 100644index 00000000..328009b2--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts@@ -0,0 +1,190 @@+import type { RouteDefinitionContext } from '../app/server.types';+import { get, pick } from 'lodash-es';+import { z } from 'zod';+import { getUser } from '../app/auth/auth.models';+import { organizationIdRegex } from '../organizations/organizations.constants';+import { createOrganizationNotFoundError } from '../organizations/organizations.errors';+import { createOrganizationsRepository } from '../organizations/organizations.repository';+import { ensureUserIsInOrganization, ensureUserIsOwnerOfOrganization, getOrCreateOrganizationCustomerId } from '../organizations/organizations.usecases';+import { FREE_PLAN_ID, PLUS_PLAN_ID } from '../plans/plans.constants';+import { createPlansRepository } from '../plans/plans.repository';+import { getOrganizationPlan } from '../plans/plans.usecases';+import { createError } from '../shared/errors/errors';+import { getHeader } from '../shared/headers/headers.models';+import { createLogger } from '../shared/logger/logger';+import { validateJsonBody, validateParams } from '../shared/validation/validation';+import { createInvalidWebhookPayloadError, createOrganizationAlreadyHasSubscriptionError } from './subscriptions.errors';+import { createSubscriptionsRepository } from './subscriptions.repository';+import { handleStripeWebhookEvent } from './subscriptions.usecases';++const logger = createLogger({ namespace: 'subscriptions.routes' });++export function registerSubscriptionsPrivateRoutes(context: RouteDefinitionContext) {+ setupCreateCheckoutSessionRoute(context);+ setupGetCustomerPortalRoute(context);+ getOrganizationSubscriptionRoute(context);+}++export function registerSubscriptionsPublicRoutes(context: RouteDefinitionContext) {+ setupStripeWebhookRoute(context);+}++function setupStripeWebhookRoute({ app, config, db, subscriptionsServices }: RouteDefinitionContext) {+ app.post('/api/stripe/webhook', async (context) => {+ const signature = getHeader({ context, name: 'stripe-signature' });++ if (!signature) {+ throw createInvalidWebhookPayloadError();+ }++ const payload = await context.req.text();+ const plansRepository = createPlansRepository({ config });+ const subscriptionsRepository = createSubscriptionsRepository({ db });++ const { event } = await subscriptionsServices.parseWebhookEvent({ payload, signature });++ logger.info(+ {+ event: pick(event, ['id', 'type']),+ customerId: get(event, 'data.object.customer'),+ },+ 'Stripe webhook received',+ );++ await handleStripeWebhookEvent({+ event,+ plansRepository,+ subscriptionsRepository,+ });++ return context.body(null, 204);+ });+}++async function setupCreateCheckoutSessionRoute({ app, config, db, subscriptionsServices }: RouteDefinitionContext) {+ app.post(+ '/api/organizations/:organizationId/checkout-session',+ validateJsonBody(z.object({+ planId: z.enum([PLUS_PLAN_ID]),+ })),+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ async (context) => {+ const { userId } = getUser({ context });++ const organizationsRepository = createOrganizationsRepository({ db });+ const plansRepository = createPlansRepository ({ config });+ const subscriptionsRepository = createSubscriptionsRepository({ db });++ const { planId } = context.req.valid('json');+ const { organizationId } = context.req.valid('param');++ await ensureUserIsOwnerOfOrganization({+ userId,+ organizationId,+ organizationsRepository,+ });++ const { organization } = await organizationsRepository.getOrganizationById({ organizationId });++ if (!organization) {+ throw createOrganizationNotFoundError();+ }++ const { organizationPlan: organizationCurrentPlan } = await getOrganizationPlan({ organizationId, subscriptionsRepository, plansRepository });++ if (organizationCurrentPlan.id !== FREE_PLAN_ID) {+ throw createOrganizationAlreadyHasSubscriptionError();+ }++ const { organizationPlan: organizationPlanToSubscribeTo } = await plansRepository.getOrganizationPlanById({ planId });++ if (!organizationPlanToSubscribeTo.priceId) {+ // Very unlikely to happen, as only the free plan does not have a price ID, and we check for the plans in the route validation+ // but for type safety, we assert that the price ID is set+ throw createError({+ message: 'Organization plan price ID is not set',+ code: 'plans.organization_plan_price_id_not_set',+ statusCode: 500,+ isInternal: true,+ });+ }++ const { customerId } = await getOrCreateOrganizationCustomerId({ organizationId, subscriptionsServices, organizationsRepository });+ const { membersCount } = organizationPlanToSubscribeTo.isPerSeat ? await organizationsRepository.getOrganizationMembersCount({ organizationId }) : ({ membersCount: 1 });++ const { checkoutUrl } = await subscriptionsServices.createCheckoutUrl({+ customerId,+ priceId: organizationPlanToSubscribeTo.priceId,+ seatsCount: membersCount,+ });++ return context.json({ checkoutUrl });+ },+ );+}++function setupGetCustomerPortalRoute({ app, db, subscriptionsServices }: RouteDefinitionContext) {+ app.get(+ '/api/organizations/:organizationId/customer-portal',+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId } = context.req.valid('param');++ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsOwnerOfOrganization({+ userId,+ organizationId,+ organizationsRepository,+ });++ const { customerId } = await getOrCreateOrganizationCustomerId({ organizationId, subscriptionsServices, organizationsRepository });++ const { customerPortalUrl } = await subscriptionsServices.getCustomerPortalUrl({ customerId });++ return context.json({ customerPortalUrl });+ },+ );+}++function getOrganizationSubscriptionRoute({ app, db }: RouteDefinitionContext) {+ app.get(+ '/api/organizations/:organizationId/subscription',+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId } = context.req.valid('param');++ const organizationsRepository = createOrganizationsRepository({ db });+ const subscriptionsRepository = createSubscriptionsRepository({ db });++ await ensureUserIsInOrganization({+ userId,+ organizationId,+ organizationsRepository,+ });++ const { subscription } = await subscriptionsRepository.getOrganizationSubscription({+ organizationId,+ });++ return context.json({+ subscription: pick(subscription, [+ 'status',+ 'currentPeriodEnd',+ 'currentPeriodStart',+ 'cancelAtPeriodEnd',+ 'planId',+ 'seatsCount',+ ]),+ });+ },+ );+}diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.services.tsnew file mode 100644index 00000000..874ae59c--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts@@ -0,0 +1,101 @@+import type { Config } from '../config/config.types';+import { buildUrl, injectArguments } from '@corentinth/chisels';+import Stripe from 'stripe';++export type SubscriptionsServices = ReturnType<typeof createSubscriptionsServices>;++export function createSubscriptionsServices({ config }: { config: Config }) {+ const stripeClient = new Stripe(config.subscriptions.stripeApiSecretKey);++ return injectArguments(+ {+ createCustomer,+ createCheckoutUrl,+ parseWebhookEvent,+ getCustomerPortalUrl,+ getCheckoutSession,+ },+ { stripeClient, config },+ );+}++async function createCustomer({ stripeClient, email, ownerId, organizationId }: { stripeClient: Stripe; email: string; ownerId: string; organizationId: string }) {+ const customer = await stripeClient.customers.create({+ email,+ metadata: {+ ownerId,+ organizationId,+ },+ });++ const customerId = customer.id;++ return { customerId };+}++export async function createCheckoutUrl({+ stripeClient,+ customerId,+ priceId,+ seatsCount,+ config,+}: {+ stripeClient: Stripe;+ customerId: string;+ priceId: string;+ seatsCount: number;+ config: Config;+}) {+ const { baseUrl } = config.client;++ const successUrl = buildUrl({ baseUrl, path: '/checkout-success?sessionId={CHECKOUT_SESSION_ID}' });+ const cancelUrl = buildUrl({ baseUrl, path: '/checkout-cancel' });++ const session = await stripeClient.checkout.sessions.create({+ customer: customerId,+ payment_method_types: ['card'],+ line_items: [+ {+ price: priceId,+ quantity: seatsCount,+ },+ ],+ mode: 'subscription',+ allow_promotion_codes: true,+ success_url: successUrl,+ cancel_url: cancelUrl,+ });++ return { checkoutUrl: session.url };+}++async function parseWebhookEvent({ stripeClient, payload, signature, config }: { stripeClient: Stripe; payload: any; signature: string; config: Config }) {+ const event = await stripeClient.webhooks.constructEventAsync(payload, signature, config.subscriptions.stripeWebhookSecret);++ return { event };+}++async function getCustomerPortalUrl({+ stripeClient,+ customerId,+ config,+ returnUrl = config.client.baseUrl,+}: {+ stripeClient: Stripe;+ customerId: string;+ returnUrl?: string;+ config: Config;+}) {+ const session = await stripeClient.billingPortal.sessions.create({+ customer: customerId,+ return_url: returnUrl,+ });++ return { customerPortalUrl: session.url };+}++async function getCheckoutSession({ stripeClient, sessionId }: { stripeClient: Stripe; sessionId: string }) {+ const checkoutSession = await stripeClient.checkout.sessions.retrieve(sessionId);++ return { checkoutSession };+}diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.tables.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.tables.tsindex a9bcf78b..c8680ec9 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.tables.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.tables.ts@@ -1,20 +1,19 @@import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';import { organizationsTable } from '../organizations/organizations.table';-import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';+import { createTimestampColumns } from '../shared/db/columns.helpers';export const organizationSubscriptionsTable = sqliteTable('organization_subscriptions', {- ...createPrimaryKeyField({ prefix: 'org_sub' }),- ...createTimestampColumns(),-- organizationId: text('organization_id')- .notNull()- .references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),-+ // stripe subscription id, no auto-generated id+ id: text('id').primaryKey(),+ customerId: text('customer_id').notNull(),+ organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),planId: text('plan_id').notNull(),- stripeSubscriptionId: text('stripe_subscription_id').notNull(),- stripeCustomerId: text('stripe_customer_id').notNull(),status: text('status').notNull(),+ seatsCount: integer('seats_count', { mode: 'number' }).notNull(),currentPeriodEnd: integer('current_period_end', { mode: 'timestamp_ms' }).notNull(),currentPeriodStart: integer('current_period_start', { mode: 'timestamp_ms' }).notNull(),cancelAtPeriodEnd: integer('cancel_at_period_end', { mode: 'boolean' }).notNull().default(false),++ ...createTimestampColumns(),+});diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.types.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.types.tsnew file mode 100644index 00000000..86288f7c--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.types.ts@@ -0,0 +1,6 @@+import type { Expand } from '@corentinth/chisels';+import type { organizationSubscriptionsTable } from './subscriptions.tables';++export type Subscription = Expand<typeof organizationSubscriptionsTable.$inferSelect>;++export type DbInsertableSubscription = Expand<typeof organizationSubscriptionsTable.$inferInsert>;diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.tsnew file mode 100644index 00000000..c6d9803d--- /dev/null+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.usecases.ts@@ -0,0 +1,71 @@+import type Stripe from 'stripe';+import type { PlansRepository } from '../plans/plans.repository';+import type { SubscriptionsRepository } from './subscriptions.repository';+import { get } from 'lodash-es';+import { createOrganizationNotFoundError } from '../organizations/organizations.errors';+import { coerceStripeTimestampToDate } from './subscriptions.models';++export async function handleStripeWebhookEvent({+ event,+ plansRepository,+ subscriptionsRepository,+}: {+ event: Stripe.Event;+ subscriptionsRepository: SubscriptionsRepository;+ plansRepository: PlansRepository;+}) {+ if (event.type === 'customer.subscription.created') {+ const subscriptionItem = get(event, 'data.object.items.data[0]');+ const customerId = get(event, 'data.object.customer') as string;+ const organizationId = get(event, 'data.object.metadata.organizationId') as string | undefined;+ const currentPeriodEnd = coerceStripeTimestampToDate(get(event, 'data.object.current_period_end'));+ const currentPeriodStart = coerceStripeTimestampToDate(get(event, 'data.object.current_period_start'));+ const cancelAtPeriodEnd = get(event, 'data.object.cancel_at_period_end');+ const status = get(event, 'data.object.status');++ if (!organizationId) {+ throw createOrganizationNotFoundError();+ }++ const { organizationPlan } = await plansRepository.getOrganizationPlanByPriceId({ priceId: subscriptionItem.price.id });++ await subscriptionsRepository.createSubscription({+ id: subscriptionItem.id,+ organizationId,+ planId: organizationPlan.id,+ seatsCount: organizationPlan.limits.maxOrganizationsMembersCount,+ customerId,+ status,+ currentPeriodEnd,+ currentPeriodStart,+ cancelAtPeriodEnd,+ });++ return;+ }++ if (event.type === 'customer.subscription.updated') {+ const subscriptionItem = get(event, 'data.object.items.data[0]');+ const organizationId = get(event, 'data.object.metadata.organizationId') as string | undefined;+ const currentPeriodEnd = coerceStripeTimestampToDate(get(event, 'data.object.current_period_end'));+ const currentPeriodStart = coerceStripeTimestampToDate(get(event, 'data.object.current_period_start'));+ const cancelAtPeriodEnd = get(event, 'data.object.cancel_at_period_end');+ const status = get(event, 'data.object.status');++ if (!organizationId) {+ throw createOrganizationNotFoundError();+ }++ const { organizationPlan } = await plansRepository.getOrganizationPlanByPriceId({ priceId: subscriptionItem.price.id });++ await subscriptionsRepository.updateSubscription({+ subscriptionId: subscriptionItem.id,+ seatsCount: organizationPlan.limits.maxOrganizationsMembersCount,+ status,+ currentPeriodEnd,+ currentPeriodStart,+ cancelAtPeriodEnd,+ planId: organizationPlan.id,+ });+ }+}diff --git a/apps/papra-server/src/modules/users/users.table.ts b/apps/papra-server/src/modules/users/users.table.tsindex e396eae2..143a0c2c 100644--- a/apps/papra-server/src/modules/users/users.table.ts+++ b/apps/papra-server/src/modules/users/users.table.ts@@ -9,7 +9,6 @@ export const usersTable = sqliteTable(email: text('email').notNull().unique(),emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),- stripeCustomerId: text('customer_id').unique(),name: text('name'),image: text('image'),maxOrganizationCount: integer('max_organization_count', { mode: 'number' }),