Skip to content

fix(plugin-multi-tenant): prefer assigned tenants for selector population #13213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@ import type { CollectionSlug, ServerProps, ViewTypes } from 'payload'
import { headers as getHeaders } from 'next/headers.js'
import { redirect } from 'next/navigation.js'

import type { MultiTenantPluginConfig } from '../../types.js'

import { getGlobalViewRedirect } from '../../utilities/getGlobalViewRedirect.js'

type Args = {
basePath?: string
collectionSlug: CollectionSlug
docID?: number | string
globalSlugs: string[]
tenantArrayFieldName: string
tenantArrayTenantFieldName: string
tenantFieldName: string
tenantsCollectionSlug: string
useAsTitle: string
userHasAccessToAllTenants: Required<MultiTenantPluginConfig<any>>['userHasAccessToAllTenants']
viewType: ViewTypes
} & ServerProps

Expand All @@ -27,9 +32,12 @@ export const GlobalViewRedirect = async (args: Args) => {
headers,
payload: args.payload,
tenantFieldName: args.tenantFieldName,
tenantsArrayFieldName: args.tenantArrayFieldName,
tenantsArrayTenantFieldName: args.tenantArrayTenantFieldName,
tenantsCollectionSlug: args.tenantsCollectionSlug,
useAsTitle: args.useAsTitle,
user: args.user,
userHasAccessToAllTenants: args.userHasAccessToAllTenants,
view: args.viewType,
})

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { Endpoint } from 'payload'

import { APIError } from 'payload'

import type { MultiTenantPluginConfig } from '../types.js'

import { getTenantOptions } from '../utilities/getTenantOptions.js'

export const getTenantOptionsEndpoint = <ConfigType>({
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle,
userHasAccessToAllTenants,
}: {
tenantsArrayFieldName: string
tenantsArrayTenantFieldName: string
tenantsCollectionSlug: string
useAsTitle: string
userHasAccessToAllTenants: Required<
MultiTenantPluginConfig<ConfigType>
>['userHasAccessToAllTenants']
}): Endpoint => ({
handler: async (req) => {
const { payload, user } = req

if (!user) {
throw new APIError('Unauthorized', 401)
}

const tenantOptions = await getTenantOptions({
payload,
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle,
user,
userHasAccessToAllTenants,
})

return new Response(JSON.stringify({ tenantOptions }))
},
method: 'get',
path: '/populate-tenant-options',
})
18 changes: 18 additions & 0 deletions packages/plugin-multi-tenant/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { PluginDefaultTranslationsObject } from './translations/types.js'
import type { MultiTenantPluginConfig } from './types.js'

import { defaults } from './defaults.js'
import { getTenantOptionsEndpoint } from './endpoints/getTenantOptionsEndpoint.js'
import { tenantField } from './fields/tenantField/index.js'
import { tenantsArrayField } from './fields/tenantsArrayField/index.js'
import { addTenantCleanup } from './hooks/afterTenantDelete.js'
Expand Down Expand Up @@ -248,6 +249,17 @@ export const multiTenantPlugin =
},
},
})

collection.endpoints = [
...(collection.endpoints || []),
getTenantOptionsEndpoint<ConfigType>({
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle: tenantCollection.admin?.useAsTitle || 'id',
userHasAccessToAllTenants,
}),
]
} else if (pluginConfig.collections?.[collection.slug]) {
const isGlobal = Boolean(pluginConfig.collections[collection.slug]?.isGlobal)

Expand Down Expand Up @@ -327,8 +339,11 @@ export const multiTenantPlugin =
*/
incomingConfig.admin.components.providers.push({
clientProps: {
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug: tenantCollection.slug,
useAsTitle: tenantCollection.admin?.useAsTitle || 'id',
userHasAccessToAllTenants,
},
path: '@payloadcms/plugin-multi-tenant/rsc#TenantSelectionProvider',
})
Expand All @@ -343,8 +358,11 @@ export const multiTenantPlugin =
basePath,
globalSlugs: globalCollectionSlugs,
tenantFieldName,
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle: tenantCollection.admin?.useAsTitle || 'id',
userHasAccessToAllTenants,
},
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,14 @@ const Context = createContext<ContextType>({

export const TenantSelectionProviderClient = ({
children,
initialTenantOptions,
initialValue,
tenantCookie,
tenantOptions: tenantOptionsFromProps,
tenantsCollectionSlug,
useAsTitle,
}: {
children: React.ReactNode
initialTenantOptions: OptionObject[]
initialValue?: number | string
tenantCookie?: string
tenantOptions: OptionObject[]
tenantsCollectionSlug: string
useAsTitle: string
}) => {
const [selectedTenantID, setSelectedTenantID] = React.useState<number | string | undefined>(
initialValue,
Expand All @@ -89,7 +85,7 @@ export const TenantSelectionProviderClient = ({
const prevUserID = React.useRef(userID)
const userChanged = userID !== prevUserID.current
const [tenantOptions, setTenantOptions] = React.useState<OptionObject[]>(
() => tenantOptionsFromProps,
() => initialTenantOptions,
)
const selectedTenantLabel = React.useMemo(
() => tenantOptions.find((option) => option.value === selectedTenantID)?.label,
Expand Down Expand Up @@ -142,7 +138,7 @@ export const TenantSelectionProviderClient = ({
const syncTenants = React.useCallback(async () => {
try {
const req = await fetch(
`${config.serverURL}${config.routes.api}/${tenantsCollectionSlug}?select[${useAsTitle}]=true&limit=0&depth=0`,
`${config.serverURL}${config.routes.api}/${tenantsCollectionSlug}/populate-tenant-options`,
{
credentials: 'include',
method: 'GET',
Expand All @@ -151,23 +147,18 @@ export const TenantSelectionProviderClient = ({

const result = await req.json()

if (result.docs && userID) {
setTenantOptions(
result.docs.map((doc: Record<string, number | string>) => ({
label: doc[useAsTitle],
value: doc.id,
})),
)

if (result.totalDocs === 1) {
setSelectedTenantID(result.docs[0].id)
setCookie(String(result.docs[0].id))
if (result.tenantOptions && userID) {
setTenantOptions(result.tenantOptions)

if (result.tenantOptions.length === 1) {
setSelectedTenantID(result.tenantOptions[0].value)
setCookie(String(result.tenantOptions[0].value))
}
}
} catch (e) {
toast.error(`Error fetching tenants`)
}
}, [config.serverURL, config.routes.api, tenantsCollectionSlug, useAsTitle, setCookie, userID])
}, [config.serverURL, config.routes.api, tenantsCollectionSlug, setCookie, userID])

const updateTenants = React.useCallback<ContextType['updateTenants']>(
({ id, label }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,45 +1,47 @@
import type { OptionObject, Payload, TypedUser } from 'payload'
import type { Payload, TypedUser } from 'payload'

import { cookies as getCookies } from 'next/headers.js'

import { findTenantOptions } from '../../queries/findTenantOptions.js'
import type { MultiTenantPluginConfig } from '../../types.js'

import { getTenantOptions } from '../../utilities/getTenantOptions.js'
import { TenantSelectionProviderClient } from './index.client.js'

type Args = {
type Args<ConfigType> = {
children: React.ReactNode
payload: Payload
tenantsArrayFieldName: string
tenantsArrayTenantFieldName: string
tenantsCollectionSlug: string
useAsTitle: string
user: TypedUser
userHasAccessToAllTenants: Required<
MultiTenantPluginConfig<ConfigType>
>['userHasAccessToAllTenants']
}

export const TenantSelectionProvider = async ({
children,
payload,
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle,
user,
}: Args) => {
let tenantOptions: OptionObject[] = []

try {
const { docs } = await findTenantOptions({
limit: 0,
payload,
tenantsCollectionSlug,
useAsTitle,
user,
})
tenantOptions = docs.map((doc) => ({
label: String(doc[useAsTitle]),
value: doc.id,
}))
} catch (_) {
// user likely does not have access
}
userHasAccessToAllTenants,
}: Args<any>) => {
const tenantOptions = await getTenantOptions({
payload,
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle,
user,
userHasAccessToAllTenants,
})

const cookies = await getCookies()
let tenantCookie = cookies.get('payload-tenant')?.value
const tenantCookie = cookies.get('payload-tenant')?.value
let initialValue = undefined

/**
Expand All @@ -56,17 +58,14 @@ export const TenantSelectionProvider = async ({
* If the there was no cookie or the cookie was an invalid tenantID set intialValue
*/
if (!initialValue) {
tenantCookie = undefined
initialValue = tenantOptions.length > 1 ? undefined : tenantOptions[0]?.value
}

return (
<TenantSelectionProviderClient
initialTenantOptions={tenantOptions}
initialValue={initialValue}
tenantCookie={tenantCookie}
tenantOptions={tenantOptions}
tenantsCollectionSlug={tenantsCollectionSlug}
useAsTitle={useAsTitle}
>
{children}
</TenantSelectionProviderClient>
Expand Down
30 changes: 0 additions & 30 deletions packages/plugin-multi-tenant/src/queries/findTenantOptions.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { Payload, TypedUser, ViewTypes } from 'payload'

import { unauthorized } from 'next/navigation.js'
import { formatAdminURL } from 'payload/shared'

import { findTenantOptions } from '../queries/findTenantOptions.js'
import type { MultiTenantPluginConfig } from '../types.js'

import { getCollectionIDType } from './getCollectionIDType.js'
import { getTenantFromCookie } from './getTenantFromCookie.js'
import { getTenantOptions } from './getTenantOptions.js'

type Args = {
basePath?: string
Expand All @@ -13,9 +16,12 @@ type Args = {
payload: Payload
slug: string
tenantFieldName: string
tenantsArrayFieldName: string
tenantsArrayTenantFieldName: string
tenantsCollectionSlug: string
useAsTitle: string
user?: TypedUser
userHasAccessToAllTenants: Required<MultiTenantPluginConfig<any>>['userHasAccessToAllTenants']
view: ViewTypes
}
export async function getGlobalViewRedirect({
Expand All @@ -25,9 +31,12 @@ export async function getGlobalViewRedirect({
headers,
payload,
tenantFieldName,
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle,
user,
userHasAccessToAllTenants,
view,
}: Args): Promise<string | void> {
const idType = getCollectionIDType({
Expand All @@ -37,16 +46,22 @@ export async function getGlobalViewRedirect({
let tenant = getTenantFromCookie(headers, idType)
let redirectRoute: `/${string}` | void = undefined

if (!user) {
return unauthorized()
}

if (!tenant) {
const tenantsQuery = await findTenantOptions({
limit: 1,
const tenantOptions = await getTenantOptions({
payload,
tenantsArrayFieldName,
tenantsArrayTenantFieldName,
tenantsCollectionSlug,
useAsTitle,
user,
userHasAccessToAllTenants,
})

tenant = tenantsQuery.docs[0]?.id || null
tenant = tenantOptions[0]?.value || null
}

try {
Expand Down
Loading
Loading