add medreport schema

This commit is contained in:
Danel Kungla
2025-07-09 13:31:37 +03:00
parent 9371ff7710
commit d9198a8a12
73 changed files with 420 additions and 270 deletions

View File

@@ -1,7 +1,7 @@
import { Database } from '@kit/supabase/database';
export type UpsertSubscriptionParams =
Database['public']['Functions']['upsert_subscription']['Args'] & {
Database['medreport']['Functions']['upsert_subscription']['Args'] & {
line_items: Array<LineItem>;
};
@@ -19,4 +19,4 @@ interface LineItem {
}
export type UpsertOrderParams =
Database['public']['Functions']['upsert_order']['Args'];
Database['medreport']['Functions']['upsert_order']['Args'];

View File

@@ -32,8 +32,7 @@
"lucide-react": "^0.510.0",
"next": "15.3.2",
"react": "19.1.0",
"react-hook-form": "^7.56.3",
"react-i18next": "^15.5.1"
"react-hook-form": "^7.56.3"
},
"typesVersions": {
"*": {

View File

@@ -14,8 +14,8 @@ import { Trans } from '@kit/ui/trans';
import { CurrentPlanBadge } from './current-plan-badge';
import { LineItemDetails } from './line-item-details';
type Order = Tables<'orders'>;
type LineItem = Tables<'order_items'>;
type Order = Tables<{ schema: 'medreport' }, 'orders'>;
type LineItem = Tables<{ schema: 'medreport' }, 'order_items'>;
interface Props {
order: Order & {

View File

@@ -18,8 +18,8 @@ import { CurrentPlanAlert } from './current-plan-alert';
import { CurrentPlanBadge } from './current-plan-badge';
import { LineItemDetails } from './line-item-details';
type Subscription = Tables<'subscriptions'>;
type LineItem = Tables<'subscription_items'>;
type Subscription = Tables<{ schema: 'medreport' }, 'subscriptions'>;
type LineItem = Tables<{ schema: 'medreport' }, 'subscription_items'>;
interface Props {
subscription: Subscription & {

View File

@@ -86,6 +86,7 @@ class BillingEventHandlerService {
logger.info(ctx, 'Processing subscription deleted event...');
const { error } = await client
.schema('medreport')
.from('subscriptions')
.delete()
.match({ id: subscriptionId });
@@ -109,7 +110,7 @@ class BillingEventHandlerService {
logger.info(ctx, 'Successfully deleted subscription');
},
onSubscriptionUpdated: async (subscription) => {
const client = this.clientProvider();
const client = this.clientProvider().schema('medreport');
const logger = await getLogger();
const ctx = {
@@ -147,7 +148,7 @@ class BillingEventHandlerService {
onCheckoutSessionCompleted: async (payload) => {
// Handle the checkout session completed event
// here we add the subscription to the database
const client = this.clientProvider();
const client = this.clientProvider().schema('medreport');
const logger = await getLogger();
// Check if the payload contains an order_id
@@ -212,7 +213,7 @@ class BillingEventHandlerService {
}
},
onPaymentSucceeded: async (sessionId: string) => {
const client = this.clientProvider();
const client = this.clientProvider().schema('medreport');
const logger = await getLogger();
const ctx = {
@@ -244,7 +245,7 @@ class BillingEventHandlerService {
logger.info(ctx, 'Successfully updated payment status');
},
onPaymentFailed: async (sessionId: string) => {
const client = this.clientProvider();
const client = this.clientProvider().schema('medreport');
const logger = await getLogger();
const ctx = {

View File

@@ -21,6 +21,7 @@ export async function getBillingGatewayProvider(
async function getBillingProvider(client: SupabaseClient<Database>) {
const { data, error } = await client
.schema('medreport')
.from('config')
.select('billing_provider')
.single();

View File

@@ -4,7 +4,7 @@ import { Tables } from '@kit/supabase/database';
import { createBillingGatewayService } from '../billing-gateway/billing-gateway.service';
type Subscription = Tables<'subscriptions'>;
type Subscription = Tables<{ schema: 'medreport' }, 'subscriptions'>;
export function createBillingWebhooksService() {
return new BillingWebhooksService();

View File

@@ -17,14 +17,14 @@ import { createLemonSqueezySubscriptionPayloadBuilderService } from './lemon-squ
import { createHmac } from './verify-hmac';
type UpsertSubscriptionParams =
Database['public']['Functions']['upsert_subscription']['Args'] & {
Database['medreport']['Functions']['upsert_subscription']['Args'] & {
line_items: Array<LineItem>;
};
type UpsertOrderParams =
Database['public']['Functions']['upsert_order']['Args'];
Database['medreport']['Functions']['upsert_order']['Args'];
type BillingProvider = Enums<'billing_provider'>;
type BillingProvider = Enums<{ schema: 'medreport' }, 'billing_provider'>;
interface LineItem {
id: string;

View File

@@ -9,7 +9,7 @@ import { createStripeClient } from './stripe-sdk';
import { createStripeSubscriptionPayloadBuilderService } from './stripe-subscription-payload-builder.service';
type UpsertSubscriptionParams =
Database['public']['Functions']['upsert_subscription']['Args'] & {
Database['medreport']['Functions']['upsert_subscription']['Args'] & {
line_items: Array<LineItem>;
};
@@ -27,9 +27,9 @@ interface LineItem {
}
type UpsertOrderParams =
Database['public']['Functions']['upsert_order']['Args'];
Database['medreport']['Functions']['upsert_order']['Args'];
type BillingProvider = Enums<'billing_provider'>;
type BillingProvider = Enums<{ schema: 'medreport' }, 'billing_provider'>;
export class StripeWebhookHandlerService
implements BillingWebhookHandlerService

View File

@@ -1,6 +1,6 @@
import { Database } from '@kit/supabase/database';
export type Tables = Database['public']['Tables'];
export type Tables = Database['medreport']['Tables'];
export type TableChangeType = 'INSERT' | 'UPDATE' | 'DELETE';

View File

@@ -44,7 +44,6 @@
"react": "19.1.0",
"react-dom": "19.1.0",
"react-hook-form": "^7.56.3",
"react-i18next": "^15.5.1",
"sonner": "^2.0.3"
},
"prettier": "@kit/prettier-config",

View File

@@ -19,7 +19,8 @@ import { Trans } from '@kit/ui/trans';
import { useUpdateAccountData } from '../../hooks/use-update-account';
import { AccountDetailsSchema } from '../../schema/account-details.schema';
type UpdateUserDataParams = Database['public']['Tables']['accounts']['Update'];
type UpdateUserDataParams =
Database['medreport']['Tables']['accounts']['Update'];
export function UpdateAccountDetailsForm({
displayName,

View File

@@ -72,6 +72,7 @@ function UploadProfileAvatarForm(props: {
uploadUserProfilePhoto(client, file, props.userId)
.then((pictureUrl) => {
return client
.schema('medreport')
.from('accounts')
.update({
picture_url: pictureUrl,
@@ -90,6 +91,7 @@ function UploadProfileAvatarForm(props: {
removeExistingStorageFile()
.then(() => {
return client
.schema('medreport')
.from('accounts')
.update({
picture_url: null,

View File

@@ -17,7 +17,9 @@ interface UserWorkspace {
id: string | null;
name: string | null;
picture_url: string | null;
subscription_status: Tables<'subscriptions'>['status'] | null;
subscription_status:
| Tables<{ schema: 'medreport' }, 'subscriptions'>['status']
| null;
};
user: User;

View File

@@ -21,6 +21,7 @@ export function usePersonalAccountData(
}
const response = await client
.schema('medreport')
.from('accounts')
.select()
.eq('primary_owner_user_id', userId)

View File

@@ -3,7 +3,7 @@ import { useMutation } from '@tanstack/react-query';
import { Database } from '@kit/supabase/database';
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
type UpdateData = Database['public']['Tables']['accounts']['Update'];
type UpdateData = Database['medreport']['Tables']['accounts']['Update'];
export function useUpdateAccountData(accountId: string) {
const client = useSupabase();
@@ -11,9 +11,13 @@ export function useUpdateAccountData(accountId: string) {
const mutationKey = ['account:data', accountId];
const mutationFn = async (data: UpdateData) => {
const response = await client.from('accounts').update(data).match({
id: accountId,
});
const response = await client
.schema('medreport')
.from('accounts')
.update(data)
.match({
id: accountId,
});
if (response.error) {
throw response.error;

View File

@@ -17,6 +17,7 @@ class AccountsApi {
*/
async getAccount(id: string) {
const { data, error } = await this.client
.schema('medreport')
.from('accounts')
.select('*')
.eq('id', id)
@@ -35,6 +36,7 @@ class AccountsApi {
*/
async getAccountWorkspace() {
const { data, error } = await this.client
.schema('medreport')
.from('user_account_workspace')
.select(`*`)
.single();
@@ -63,6 +65,7 @@ class AccountsApi {
const { user } = data;
const { data: accounts, error } = await this.client
.schema('medreport')
.from('accounts_memberships')
.select(
`
@@ -91,6 +94,7 @@ class AccountsApi {
async loadTempUserAccounts() {
const { data: accounts, error } = await this.client
.schema('medreport')
.from('user_accounts')
.select(`name, slug`);
@@ -131,6 +135,7 @@ class AccountsApi {
*/
async getOrder(accountId: string) {
const response = await this.client
.schema('medreport')
.from('orders')
.select('*, items: order_items !inner (*)')
.eq('account_id', accountId)
@@ -151,6 +156,7 @@ class AccountsApi {
*/
async getCustomerId(accountId: string) {
const response = await this.client
.schema('medreport')
.from('billing_customers')
.select('customer_id')
.eq('account_id', accountId)

View File

@@ -3,6 +3,11 @@ import { BadgeX, Ban, ShieldPlus, VenetianMask } from 'lucide-react';
import { Tables } from '@kit/supabase/database';
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import {
AccountInvitationsTable,
AccountMembersTable,
InviteMembersDialogContainer,
} from '@kit/team-accounts/components';
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
import { AppBreadcrumbs } from '@kit/ui/app-breadcrumbs';
import { Badge } from '@kit/ui/badge';
@@ -28,14 +33,8 @@ import { AdminMembersTable } from './admin-members-table';
import { AdminMembershipsTable } from './admin-memberships-table';
import { AdminReactivateUserDialog } from './admin-reactivate-user-dialog';
import {
AccountInvitationsTable,
AccountMembersTable,
InviteMembersDialogContainer,
} from '@kit/team-accounts/components';
type Account = Tables<'accounts'>;
type Membership = Tables<'accounts_memberships'>;
type Account = Tables<{ schema: 'medreport' }, 'accounts'>;
type Membership = Tables<{ schema: 'medreport' }, 'accounts_memberships'>;
export function AdminAccountPage(props: {
account: Account & { memberships: Membership[] };
@@ -231,6 +230,7 @@ async function SubscriptionsTable(props: { accountId: string }) {
const client = getSupabaseServerClient();
const { data: subscription, error } = await client
.schema('medreport')
.from('subscriptions')
.select('*, subscription_items !inner (*)')
.eq('account_id', props.accountId)
@@ -372,6 +372,7 @@ async function getMemberships(userId: string) {
const client = getSupabaseServerClient();
const memberships = await client
.schema('medreport')
.from('accounts_memberships')
.select<
string,
@@ -394,7 +395,7 @@ async function getMemberships(userId: string) {
async function getMembers(accountSlug: string) {
const client = getSupabaseServerClient();
const members = await client.rpc('get_account_members', {
const members = await client.schema('medreport').rpc('get_account_members', {
account_slug: accountSlug,
});

View File

@@ -38,7 +38,7 @@ import { AdminDeleteUserDialog } from './admin-delete-user-dialog';
import { AdminImpersonateUserDialog } from './admin-impersonate-user-dialog';
import { AdminResetPasswordDialog } from './admin-reset-password-dialog';
type Account = Database['public']['Tables']['accounts']['Row'];
type Account = Database['medreport']['Tables']['accounts']['Row'];
const FiltersSchema = z.object({
type: z.enum(['all', 'team', 'personal']),

View File

@@ -9,7 +9,7 @@ import { DataTable } from '@kit/ui/enhanced-data-table';
import { ProfileAvatar } from '@kit/ui/profile-avatar';
type Memberships =
Database['public']['Functions']['get_account_members']['Returns'][number];
Database['medreport']['Functions']['get_account_members']['Returns'][number];
export function AdminMembersTable(props: { members: Memberships[] }) {
return <DataTable data={props.members} columns={getColumns()} />;

View File

@@ -7,7 +7,7 @@ import { ColumnDef } from '@tanstack/react-table';
import { Tables } from '@kit/supabase/database';
import { DataTable } from '@kit/ui/enhanced-data-table';
type Membership = Tables<'accounts_memberships'> & {
type Membership = Tables<{ schema: 'medreport' }, 'accounts_memberships'> & {
account: {
id: string;
name: string;

View File

@@ -15,13 +15,13 @@ import {
ImpersonateUserSchema,
ReactivateUserSchema,
} from './schema/admin-actions.schema';
import { CreateCompanySchema } from './schema/create-company.schema';
import { CreateUserSchema } from './schema/create-user.schema';
import { ResetPasswordSchema } from './schema/reset-password.schema';
import { createAdminAccountsService } from './services/admin-accounts.service';
import { createAdminAuthUserService } from './services/admin-auth-user.service';
import { adminAction } from './utils/admin-action';
import { CreateCompanySchema } from './schema/create-company.schema';
import { createCreateCompanyAccountService } from './services/admin-create-company-account.service';
import { adminAction } from './utils/admin-action';
/**
* @name banUserAction
@@ -183,12 +183,16 @@ export const createUserAction = adminAction(
);
const { error: accountError } = await adminClient
.schema('medreport')
.from('accounts')
.update({ personal_code: personalCode })
.eq('id', data.user.id);
if (accountError) {
logger.error({ accountError }, 'Error inserting personal code to accounts');
logger.error(
{ accountError },
'Error inserting personal code to accounts',
);
throw new Error(`Error saving personal code: ${accountError.message}`);
}

View File

@@ -13,6 +13,7 @@ class AdminAccountsService {
async deleteAccount(accountId: string) {
const { error } = await this.adminClient
.schema('medreport')
.from('accounts')
.delete()
.eq('id', accountId);

View File

@@ -30,6 +30,7 @@ export class AdminDashboardService {
};
const subscriptionsPromise = this.client
.schema('medreport')
.from('subscriptions')
.select('*', selectParams)
.eq('status', 'active')
@@ -47,6 +48,7 @@ export class AdminDashboardService {
});
const trialsPromise = this.client
.schema('medreport')
.from('subscriptions')
.select('*', selectParams)
.eq('status', 'trialing')
@@ -64,6 +66,7 @@ export class AdminDashboardService {
});
const accountsPromise = this.client
.schema('medreport')
.from('accounts')
.select('*', selectParams)
.eq('is_personal_account', true)
@@ -81,6 +84,7 @@ export class AdminDashboardService {
});
const teamAccountsPromise = this.client
.schema('medreport')
.from('accounts')
.select('*', selectParams)
.eq('is_personal_account', false)

View File

@@ -35,7 +35,6 @@
"lucide-react": "^0.510.0",
"next": "15.3.2",
"react-hook-form": "^7.56.3",
"react-i18next": "^15.5.1",
"sonner": "^2.0.3"
},
"prettier": "@kit/prettier-config",

View File

@@ -55,12 +55,11 @@ export function SignInMethodsContainer(props: {
}
try {
const { data: hasConsentPersonalData } = await client.rpc(
'has_consent_personal_data',
{
const { data: hasConsentPersonalData } = await client
.schema('medreport')
.rpc('has_consent_personal_data', {
account_id: userId,
},
);
});
if (hasConsentPersonalData) {
router.replace(props.paths.returnPath);

View File

@@ -86,7 +86,7 @@ class AuthApi {
if (!user) {
throw new Error('User not authenticated');
}
console.log('test', user, data);
const response = await this.client
.schema('medreport')
.from('account_params')

View File

@@ -1,29 +1,28 @@
import { HttpTypes } from "@medusajs/types"
import { NextRequest, NextResponse } from "next/server"
import { HttpTypes } from "@medusajs/types";
import { NextRequest, NextResponse } from "next/server";
const BACKEND_URL = process.env.MEDUSA_BACKEND_URL
const PUBLISHABLE_API_KEY = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY
const DEFAULT_REGION = process.env.NEXT_PUBLIC_DEFAULT_REGION || "us"
const BACKEND_URL = process.env.MEDUSA_BACKEND_URL;
const PUBLISHABLE_API_KEY = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY;
const DEFAULT_REGION = process.env.NEXT_PUBLIC_DEFAULT_REGION || "us";
const regionMapCache = {
regionMap: new Map<string, HttpTypes.StoreRegion>(),
regionMapUpdated: Date.now(),
}
};
async function getRegionMap(cacheId: string) {
const { regionMap, regionMapUpdated } = regionMapCache
const { regionMap, regionMapUpdated } = regionMapCache;
if (!BACKEND_URL) {
throw new Error(
"Middleware.ts: Error fetching regions. Did you set up regions in your Medusa Admin and define a MEDUSA_BACKEND_URL environment variable? Note that the variable is no longer named NEXT_PUBLIC_MEDUSA_BACKEND_URL."
)
);
}
if (
!regionMap.keys().next().value ||
regionMapUpdated < Date.now() - 3600 * 1000
) {
console.log("PUBLISHABLE_API_KEY", PUBLISHABLE_API_KEY)
// Fetch regions from Medusa. We can't use the JS client here because middleware is running on Edge and the client needs a Node environment.
const { regions } = await fetch(`${BACKEND_URL}/store/regions`, {
headers: {
@@ -35,32 +34,32 @@ async function getRegionMap(cacheId: string) {
},
cache: "force-cache",
}).then(async (response) => {
const json = await response.json()
const json = await response.json();
if (!response.ok) {
throw new Error(json.message)
throw new Error(json.message);
}
return json
})
return json;
});
if (!regions?.length) {
throw new Error(
"No regions found. Please set up regions in your Medusa Admin."
)
);
}
// Create a map of country codes to regions.
regions.forEach((region: HttpTypes.StoreRegion) => {
region.countries?.forEach((c) => {
regionMapCache.regionMap.set(c.iso_2 ?? "", region)
})
})
regionMapCache.regionMap.set(c.iso_2 ?? "", region);
});
});
regionMapCache.regionMapUpdated = Date.now()
regionMapCache.regionMapUpdated = Date.now();
}
return regionMapCache.regionMap
return regionMapCache.regionMap;
}
/**
@@ -73,30 +72,32 @@ async function getCountryCode(
regionMap: Map<string, HttpTypes.StoreRegion | number>
) {
try {
let countryCode
let countryCode;
const vercelCountryCode = request.headers
.get("x-vercel-ip-country")
?.toLowerCase()
?.toLowerCase();
const urlCountryCode = request.nextUrl.pathname.split("/")[1]?.toLowerCase()
const urlCountryCode = request.nextUrl.pathname
.split("/")[1]
?.toLowerCase();
if (urlCountryCode && regionMap.has(urlCountryCode)) {
countryCode = urlCountryCode
countryCode = urlCountryCode;
} else if (vercelCountryCode && regionMap.has(vercelCountryCode)) {
countryCode = vercelCountryCode
countryCode = vercelCountryCode;
} else if (regionMap.has(DEFAULT_REGION)) {
countryCode = DEFAULT_REGION
countryCode = DEFAULT_REGION;
} else if (regionMap.keys().next().value) {
countryCode = regionMap.keys().next().value
countryCode = regionMap.keys().next().value;
}
return countryCode
return countryCode;
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error(
"Middleware.ts: Error getting the country code. Did you set up regions in your Medusa Admin and define a MEDUSA_BACKEND_URL environment variable? Note that the variable is no longer named NEXT_PUBLIC_MEDUSA_BACKEND_URL."
)
);
}
}
}
@@ -105,56 +106,56 @@ async function getCountryCode(
* Middleware to handle region selection and onboarding status.
*/
export async function middleware(request: NextRequest) {
let redirectUrl = request.nextUrl.href
let redirectUrl = request.nextUrl.href;
let response = NextResponse.redirect(redirectUrl, 307)
let response = NextResponse.redirect(redirectUrl, 307);
let cacheIdCookie = request.cookies.get("_medusa_cache_id")
let cacheIdCookie = request.cookies.get("_medusa_cache_id");
let cacheId = cacheIdCookie?.value || crypto.randomUUID()
let cacheId = cacheIdCookie?.value || crypto.randomUUID();
const regionMap = await getRegionMap(cacheId)
const regionMap = await getRegionMap(cacheId);
const countryCode = regionMap && (await getCountryCode(request, regionMap))
const countryCode = regionMap && (await getCountryCode(request, regionMap));
const urlHasCountryCode =
countryCode && request.nextUrl.pathname.split("/")[1].includes(countryCode)
countryCode && request.nextUrl.pathname.split("/")[1].includes(countryCode);
// if one of the country codes is in the url and the cache id is set, return next
if (urlHasCountryCode && cacheIdCookie) {
return NextResponse.next()
return NextResponse.next();
}
// if one of the country codes is in the url and the cache id is not set, set the cache id and redirect
if (urlHasCountryCode && !cacheIdCookie) {
response.cookies.set("_medusa_cache_id", cacheId, {
maxAge: 60 * 60 * 24,
})
});
return response
return response;
}
// check if the url is a static asset
if (request.nextUrl.pathname.includes(".")) {
return NextResponse.next()
return NextResponse.next();
}
const redirectPath =
request.nextUrl.pathname === "/" ? "" : request.nextUrl.pathname
request.nextUrl.pathname === "/" ? "" : request.nextUrl.pathname;
const queryString = request.nextUrl.search ? request.nextUrl.search : ""
const queryString = request.nextUrl.search ? request.nextUrl.search : "";
// If no country code is set, we redirect to the relevant region.
if (!urlHasCountryCode && countryCode) {
redirectUrl = `${request.nextUrl.origin}/${countryCode}${redirectPath}${queryString}`
response = NextResponse.redirect(`${redirectUrl}`, 307)
redirectUrl = `${request.nextUrl.origin}/${countryCode}${redirectPath}${queryString}`;
response = NextResponse.redirect(`${redirectUrl}`, 307);
}
return response
return response;
}
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|favicon.ico|images|assets|png|svg|jpg|jpeg|gif|webp).*)",
],
}
};

View File

@@ -24,8 +24,7 @@
"@types/react": "19.1.4",
"lucide-react": "^0.510.0",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-i18next": "^15.5.1"
"react-dom": "19.1.0"
},
"prettier": "@kit/prettier-config",
"typesVersions": {

View File

@@ -14,7 +14,7 @@ import { cn } from '@kit/ui/utils';
import { useDismissNotification, useFetchNotifications } from '../hooks';
type Notification = Database['public']['Tables']['notifications']['Row'];
type Notification = Database['medreport']['Tables']['notifications']['Row'];
type PartialNotification = Pick<
Notification,
@@ -121,7 +121,10 @@ export function NotificationsPopover(params: {
return (
<Popover modal open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button className={'relative px-4 py-2 h-10 border-1 mr-0'} variant="ghost">
<Button
className={'relative mr-0 h-10 border-1 px-4 py-2'}
variant="ghost"
>
<Bell className={'size-4'} />
<span

View File

@@ -8,6 +8,7 @@ export function useDismissNotification() {
return useCallback(
async (notification: number) => {
const { error } = await client
.schema('medreport')
.from('notifications')
.update({ dismissed: true })
.eq('id', notification);

View File

@@ -49,6 +49,7 @@ function useFetchInitialNotifications(props: { accountIds: string[] }) {
queryKey: ['notifications', ...props.accountIds],
queryFn: async () => {
const { data } = await client
.schema('medreport')
.from('notifications')
.select(
`id,

View File

@@ -22,7 +22,7 @@ import { Database } from '@kit/supabase/database';
import { createNotificationsService } from './notifications.service';
type Notification = Database['public']['Tables']['notifications'];
type Notification = Database['medreport']['Tables']['notifications'];
/**
* @name createNotificationsApi

View File

@@ -4,7 +4,7 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { Database } from '@kit/supabase/database';
type Notification = Database['public']['Tables']['notifications'];
type Notification = Database['medreport']['Tables']['notifications'];
export function createNotificationsService(client: SupabaseClient<Database>) {
return new NotificationsService(client);
@@ -14,7 +14,10 @@ class NotificationsService {
constructor(private readonly client: SupabaseClient<Database>) {}
async createNotification(params: Notification['Insert']) {
const { error } = await this.client.from('notifications').insert(params);
const { error } = await this.client
.schema('medreport')
.from('notifications')
.insert(params);
if (error) {
throw error;

View File

@@ -45,7 +45,6 @@
"react": "19.1.0",
"react-dom": "19.1.0",
"react-hook-form": "^7.56.3",
"react-i18next": "^15.5.1",
"sonner": "^2.0.3"
},
"prettier": "@kit/prettier-config",

View File

@@ -27,7 +27,7 @@ import { RenewInvitationDialog } from './renew-invitation-dialog';
import { UpdateInvitationDialog } from './update-invitation-dialog';
type Invitations =
Database['public']['Functions']['get_account_invitations']['Returns'];
Database['medreport']['Functions']['get_account_invitations']['Returns'];
type AccountInvitationsTableProps = {
invitations: Invitations;

View File

@@ -27,7 +27,7 @@ import { TransferOwnershipDialog } from './transfer-ownership-dialog';
import { UpdateMemberRoleDialog } from './update-member-role-dialog';
type Members =
Database['public']['Functions']['get_account_members']['Returns'];
Database['medreport']['Functions']['get_account_members']['Returns'];
interface Permissions {
canUpdateRole: (roleHierarchy: number) => boolean;
@@ -87,7 +87,7 @@ export function AccountMembersTable({
return (
displayName.includes(searchString) ||
member.role.toLowerCase().includes(searchString) ||
member.role.toLowerCase().includes(searchString) ||
(member.personal_code || '').includes(searchString)
);
})

View File

@@ -21,7 +21,7 @@ export function RolesDataProvider(props: {
}
function useFetchRoles(props: { maxRoleHierarchy: number }) {
const supabase = useSupabase();
const supabase = useSupabase().schema('medreport');
return useQuery({
queryKey: ['roles', props.maxRoleHierarchy],

View File

@@ -53,6 +53,7 @@ export function UpdateTeamAccountImage(props: {
uploadUserProfilePhoto(client, file, props.account.id).then(
(pictureUrl) => {
return client
.schema('medreport')
.from('accounts')
.update({
picture_url: pictureUrl,
@@ -68,6 +69,7 @@ export function UpdateTeamAccountImage(props: {
const promise = () =>
removeExistingStorageFile().then(() => {
return client
.schema('medreport')
.from('accounts')
.update({
picture_url: null,

View File

@@ -7,8 +7,8 @@ import { User } from '@supabase/supabase-js';
import { Database } from '@kit/supabase/database';
interface AccountWorkspace {
accounts: Database['public']['Views']['user_accounts']['Row'][];
account: Database['public']['Functions']['team_account_workspace']['Returns'][0];
accounts: Database['medreport']['Views']['user_accounts']['Row'][];
account: Database['medreport']['Functions']['team_account_workspace']['Returns'][0];
user: User;
}

View File

@@ -25,7 +25,6 @@ export const TeamNameSchema = z
.max(50)
.refine(
(name) => {
console.log(name);
return !SPECIAL_CHARACTERS_REGEX.test(name);
},
{

View File

@@ -22,6 +22,7 @@ export const updateTeamAccountName = enhanceAction(
logger.info(ctx, `Updating team name...`);
const { error, data } = await client
.schema('medreport')
.from('accounts')
.update({
name,

View File

@@ -41,6 +41,7 @@ export const createInvitationsAction = enhanceAction(
);
const { data: company, error: companyError } = await client
.schema('medreport')
.from('accounts')
.select('id')
.eq('slug', accountSlug);

View File

@@ -79,9 +79,11 @@ export const transferOwnershipAction = enhanceAction(
logger.info(ctx, 'Processing team ownership transfer request...');
// assert that the user is the owner of the account
const { data: isOwner, error } = await client.rpc('is_account_owner', {
account_id: data.accountId,
});
const { data: isOwner, error } = await client
.schema('medreport')
.rpc('is_account_owner', {
account_id: data.accountId,
});
if (error || !isOwner) {
logger.error(ctx, 'User is not the owner of this account');

View File

@@ -17,6 +17,7 @@ export class TeamAccountsApi {
*/
async getTeamAccount(slug: string) {
const { data, error } = await this.client
.schema('medreport')
.from('accounts')
.select('*')
.eq('slug', slug)
@@ -36,6 +37,7 @@ export class TeamAccountsApi {
*/
async getTeamAccountById(accountId: string) {
const { data, error } = await this.client
.schema('medreport')
.from('accounts')
.select('*')
.eq('id', accountId)
@@ -55,6 +57,7 @@ export class TeamAccountsApi {
*/
async getSubscription(accountId: string) {
const { data, error } = await this.client
.schema('medreport')
.from('subscriptions')
.select('*, items: subscription_items !inner (*)')
.eq('account_id', accountId)
@@ -73,6 +76,7 @@ export class TeamAccountsApi {
*/
async getOrder(accountId: string) {
const response = await this.client
.schema('medreport')
.from('orders')
.select('*, items: order_items !inner (*)')
.eq('account_id', accountId)
@@ -91,13 +95,17 @@ export class TeamAccountsApi {
* @param slug
*/
async getAccountWorkspace(slug: string, userId: string) {
const accountPromise = this.client.rpc('team_account_workspace', {
account_slug: slug,
});
const accountPromise = this.client
.schema('medreport')
.rpc('team_account_workspace', {
account_slug: slug,
});
const accountsPromise = this.client
.schema('medreport')
.from('accounts_memberships')
.select(`
.select(
`
account_id,
user_accounts (
id,
@@ -106,7 +114,8 @@ export class TeamAccountsApi {
slug,
picture_url
)
`)
`,
)
.eq('user_id', userId)
.eq('account_role', 'owner');
@@ -114,7 +123,7 @@ export class TeamAccountsApi {
accountPromise,
accountsPromise,
]);
if (accountResult.error) {
return {
error: accountResult.error,
@@ -154,7 +163,7 @@ export class TeamAccountsApi {
async hasPermission(params: {
accountId: string;
userId: string;
permission: Database['public']['Enums']['app_permissions'];
permission: Database['medreport']['Enums']['app_permissions'];
}) {
const { data, error } = await this.client.rpc('has_permission', {
account_id: params.accountId,
@@ -176,6 +185,7 @@ export class TeamAccountsApi {
*/
async getMembersCount(accountId: string) {
const { count, error } = await this.client
.schema('medreport')
.from('accounts_memberships')
.select('*', {
head: true,
@@ -197,6 +207,7 @@ export class TeamAccountsApi {
*/
async getCustomerId(accountId: string) {
const { data, error } = await this.client
.schema('medreport')
.from('billing_customers')
.select('customer_id')
.eq('account_id', accountId)
@@ -217,6 +228,7 @@ export class TeamAccountsApi {
*/
async getInvitation(adminClient: SupabaseClient<Database>, token: string) {
const { data: invitation, error } = await adminClient
.schema('medreport')
.from('invitations')
.select<
string,

View File

@@ -43,6 +43,7 @@ class AccountInvitationsService {
logger.info(ctx, 'Removing invitation...');
const { data, error } = await this.client
.schema('medreport')
.from('invitations')
.delete()
.match({
@@ -76,6 +77,7 @@ class AccountInvitationsService {
logger.info(ctx, 'Updating invitation...');
const { data, error } = await this.client
.schema('medreport')
.from('invitations')
.update({
role: params.role,
@@ -105,12 +107,11 @@ class AccountInvitationsService {
invitation: z.infer<typeof InviteMembersSchema>['invitations'][number],
accountSlug: string,
) {
const { data: members, error } = await this.client.rpc(
'get_account_members',
{
const { data: members, error } = await this.client
.schema('medreport')
.rpc('get_account_members', {
account_slug: accountSlug,
},
);
});
if (error) {
throw error;
@@ -169,6 +170,7 @@ class AccountInvitationsService {
}
const accountResponse = await this.client
.schema('medreport')
.from('accounts')
.select('name')
.eq('slug', accountSlug)
@@ -183,10 +185,12 @@ class AccountInvitationsService {
throw new Error('Account not found');
}
const response = await this.client.rpc('add_invitations_to_account', {
invitations,
account_slug: accountSlug,
});
const response = await this.client
.schema('medreport')
.rpc('add_invitations_to_account', {
invitations,
account_slug: accountSlug,
});
if (response.error) {
logger.error(
@@ -232,10 +236,12 @@ class AccountInvitationsService {
logger.info(ctx, 'Accepting invitation to team');
const { error, data } = await adminClient.rpc('accept_invitation', {
token: params.inviteToken,
user_id: params.userId,
});
const { error, data } = await adminClient
.schema('medreport')
.rpc('accept_invitation', {
token: params.inviteToken,
user_id: params.userId,
});
if (error) {
logger.error(
@@ -272,6 +278,7 @@ class AccountInvitationsService {
const sevenDaysFromNow = formatISO(addDays(new Date(), 7));
const { data, error } = await this.client
.schema('medreport')
.from('invitations')
.update({
expires_at: sevenDaysFromNow,

View File

@@ -37,6 +37,7 @@ class AccountMembersService {
logger.info(ctx, `Removing member from account...`);
const { data, error } = await this.client
.schema('medreport')
.from('accounts_memberships')
.delete()
.match({
@@ -88,7 +89,7 @@ class AccountMembersService {
logger.info(ctx, `Validating permissions to update member role...`);
const { data: canActionAccountMember, error: accountError } =
await this.client.rpc('can_action_account_member', {
await this.client.schema('medreport').rpc('can_action_account_member', {
target_user_id: params.userId,
target_team_account_id: params.accountId,
});
@@ -112,6 +113,7 @@ class AccountMembersService {
// for updating accounts_memberships. Instead, we use the can_action_account_member
// RPC to validate permissions to update the role
const { data, error } = await adminClient
.schema('medreport')
.from('accounts_memberships')
.update({
account_role: params.role,
@@ -157,13 +159,12 @@ class AccountMembersService {
logger.info(ctx, `Transferring ownership of account...`);
const { data, error } = await adminClient.rpc(
'transfer_team_account_ownership',
{
const { data, error } = await adminClient
.schema('medreport')
.rpc('transfer_team_account_ownership', {
target_account_id: params.accountId,
new_owner_id: params.userId,
},
);
});
if (error) {
logger.error(

View File

@@ -36,6 +36,7 @@ class AccountPerSeatBillingService {
);
const { data, error } = await this.client
.schema('medreport')
.from('subscriptions')
.select(
`

View File

@@ -22,9 +22,11 @@ class CreateTeamAccountService {
logger.info(ctx, `Creating new team account...`);
const { error, data } = await this.client.rpc('create_team_account', {
account_name: params.name,
});
const { error, data } = await this.client
.schema('medreport')
.rpc('create_team_account', {
account_name: params.name,
});
if (error) {
logger.error(

View File

@@ -40,6 +40,7 @@ class DeleteTeamAccountService {
// we can use the admin client to delete the account.
const { error } = await adminClient
.schema('medreport')
.from('accounts')
.delete()
.eq('id', params.accountId);

View File

@@ -45,6 +45,7 @@ class LeaveTeamAccountService {
const { accountId, userId } = Schema.parse(params);
const { error } = await this.adminClient
.schema('medreport')
.from('accounts_memberships')
.delete()
.match({

View File

@@ -5,7 +5,7 @@ import { z } from 'zod';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
type Invitation = Database['public']['Tables']['invitations']['Row'];
type Invitation = Database['medreport']['Tables']['invitations']['Row'];
const invitePath = '/join';
@@ -72,6 +72,7 @@ class AccountInvitationsWebhookService {
);
const inviter = await this.adminClient
.schema('medreport')
.from('accounts')
.select('email, name')
.eq('id', invitation.invited_by)
@@ -90,6 +91,7 @@ class AccountInvitationsWebhookService {
}
const team = await this.adminClient
.schema('medreport')
.from('accounts')
.select('name')
.eq('id', invitation.account_id)

View File

@@ -3,7 +3,7 @@ import { z } from 'zod';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
type Account = Database['public']['Tables']['accounts']['Row'];
type Account = Database['medreport']['Tables']['accounts']['Row'];
export function createAccountWebhooksService() {
return new AccountWebhooksService();

View File

@@ -24,7 +24,7 @@
"next": "15.3.2",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-i18next": "^15.5.1"
"react-i18next": "^15.5.3"
},
"dependencies": {
"i18next": "25.1.3",

View File

@@ -74,7 +74,7 @@ class OtpService {
logger.info(ctx, 'Creating one-time token');
try {
const result = await this.client.rpc('create_nonce', {
const result = await this.client.schema('medreport').rpc('create_nonce', {
p_user_id: userId,
p_purpose: purpose,
p_expires_in_seconds: expiresInSeconds,
@@ -135,7 +135,7 @@ class OtpService {
logger.info(ctx, 'Verifying one-time token');
try {
const result = await this.client.rpc('verify_nonce', {
const result = await this.client.schema('medreport').rpc('verify_nonce', {
p_token: token,
p_user_id: params.userId,
p_purpose: purpose,
@@ -184,10 +184,12 @@ class OtpService {
logger.info(ctx, 'Revoking one-time token');
try {
const { data, error } = await this.client.rpc('revoke_nonce', {
p_id: id,
p_reason: reason,
});
const { data, error } = await this.client
.schema('medreport')
.rpc('revoke_nonce', {
p_id: id,
p_reason: reason,
});
if (error) {
logger.error(
@@ -225,9 +227,11 @@ class OtpService {
logger.info(ctx, 'Getting one-time token status');
try {
const result = await this.client.rpc('get_nonce_status', {
p_id: id,
});
const result = await this.client
.schema('medreport')
.rpc('get_nonce_status', {
p_id: id,
});
if (result.error) {
logger.error(

View File

@@ -55,7 +55,6 @@
"prettier": "^3.5.3",
"react-day-picker": "^8.10.1",
"react-hook-form": "^7.56.3",
"react-i18next": "^15.5.1",
"sonner": "^2.0.3",
"tailwindcss": "4.1.7",
"tailwindcss-animate": "^1.0.7",