85 lines
1.9 KiB
TypeScript
85 lines
1.9 KiB
TypeScript
import { type LoaderFunctionArgs, createContext } from 'react-router'
|
|
|
|
import { userContext } from '@repo/auth/context'
|
|
import { request as req } from '@repo/util/request'
|
|
|
|
import type { Address } from '@/routes/_.$orgid.enrollments.buy/review'
|
|
|
|
export type Subscription = {
|
|
billing_day: number
|
|
payment_method: 'PIX' | 'BANK_SLIP' | 'MANUAL'
|
|
}
|
|
|
|
export type Workspace = {
|
|
id: string
|
|
name: string
|
|
cnpj: string
|
|
}
|
|
|
|
export type WorkspaceContextProps = {
|
|
activeWorkspace: Workspace
|
|
workspaces: Workspace[]
|
|
subscription: Subscription | null
|
|
address: Address | null
|
|
}
|
|
|
|
export const workspaceContext = createContext<WorkspaceContextProps>()
|
|
|
|
export const workspaceMiddleware = async (
|
|
{ params, request, context }: LoaderFunctionArgs,
|
|
next: () => Promise<Response>
|
|
): Promise<Response> => {
|
|
const org_id = params.orgid
|
|
const user = context.get(userContext)!
|
|
|
|
const r = await req({
|
|
url: `/users/${user.sub}/orgs?limit=25`,
|
|
request,
|
|
context
|
|
})
|
|
|
|
if (!r.ok) {
|
|
throw new Response(await r.text(), { status: r.status })
|
|
}
|
|
|
|
const { items } = (await r.json()) as { items: { sk: string }[] }
|
|
const workspaces = items.map(({ sk, ...props }) => {
|
|
const [, id] = sk?.split('#')
|
|
return { ...props, id }
|
|
}) as Workspace[]
|
|
|
|
const activeWorkspace = workspaces.find(
|
|
({ id }) => id === org_id
|
|
) as Workspace
|
|
|
|
const [subscription, address] = await Promise.all([
|
|
req({
|
|
url: `/orgs/${activeWorkspace.id}/subscription`,
|
|
request,
|
|
context
|
|
})
|
|
.then((r) => r.json())
|
|
.then(emptyObjectToNull),
|
|
|
|
req({
|
|
url: `/orgs/${activeWorkspace.id}/address`,
|
|
request,
|
|
context
|
|
})
|
|
.then((r) => r.json())
|
|
.then(emptyObjectToNull)
|
|
])
|
|
|
|
context.set(workspaceContext, {
|
|
activeWorkspace,
|
|
workspaces,
|
|
subscription,
|
|
address
|
|
})
|
|
|
|
return await next()
|
|
}
|
|
|
|
const emptyObjectToNull = (data: any) =>
|
|
data && Object.keys(data).length === 0 ? null : data
|